Debian Codegraph @

kv.go

raw
1 // Copyright 2021-2023 The NATS Authors
2 // Licensed under the Apache License, Version 2.0 (the "License");
3 // you may not use this file except in compliance with the License.
4 // You may obtain a copy of the License at
5 //
6 // http://www.apache.org/licenses/LICENSE-2.0
7 //
8 // Unless required by applicable law or agreed to in writing, software
9 // distributed under the License is distributed on an "AS IS" BASIS,
10 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11 // See the License for the specific language governing permissions and
12 // limitations under the License.
13
14 package nats
15
16 import (
17 "context"
18 "errors"
19 "fmt"
20 "reflect"
21 "regexp"
22 "slices"
23 "strconv"
24 "strings"
25 "sync"
26 "time"
27
28 "github.com/nats-io/nats.go/internal/parser"
29 )
30
31 // KeyValueManager is used to manage KeyValue stores.
32 type KeyValueManager interface {
33 // KeyValue will lookup and bind to an existing KeyValue store.
34 KeyValue(bucket string) (KeyValue, error)
35 // CreateKeyValue will create a KeyValue store with the following configuration.
36 CreateKeyValue(cfg *KeyValueConfig) (KeyValue, error)
37 // DeleteKeyValue will delete this KeyValue store (JetStream stream).
38 DeleteKeyValue(bucket string) error
39 // KeyValueStoreNames is used to retrieve a list of key value store names
40 KeyValueStoreNames() <-chan string
41 // KeyValueStores is used to retrieve a list of key value store statuses
42 KeyValueStores() <-chan KeyValueStatus
43 }
44
45 // KeyValue contains methods to operate on a KeyValue store.
46 type KeyValue interface {
47 // Get returns the latest value for the key.
48 Get(key string) (entry KeyValueEntry, err error)
49 // GetRevision returns a specific revision value for the key.
50 GetRevision(key string, revision uint64) (entry KeyValueEntry, err error)
51 // Put will place the new value for the key into the store.
52 Put(key string, value []byte) (revision uint64, err error)
53 // PutString will place the string for the key into the store.
54 PutString(key string, value string) (revision uint64, err error)
55 // Create will add the key/value pair iff it does not exist.
56 Create(key string, value []byte) (revision uint64, err error)
57 // Update will update the value iff the latest revision matches.
58 // If the provided revision does not match the key's current revision,
59 // ErrKeyRevisionMismatch is returned.
60 // Update also resets the TTL associated with the key (if any).
61 Update(key string, value []byte, last uint64) (revision uint64, err error)
62 // Delete will place a delete marker and leave all revisions. The
63 // LastRevision option can be specified to only perform the delete if the
64 // latest revision matches the provided one; if it does not,
65 // ErrKeyRevisionMismatch is returned.
66 Delete(key string, opts ...DeleteOpt) error
67 // Purge will place a delete marker and remove all previous revisions. The
68 // LastRevision option can be specified to only perform the purge if the
69 // latest revision matches the provided one; if it does not,
70 // ErrKeyRevisionMismatch is returned.
71 Purge(key string, opts ...DeleteOpt) error
72 // Watch for any updates to keys that match the keys argument which could include wildcards.
73 // Watch will send a nil entry when it has received all initial values.
74 Watch(keys string, opts ...WatchOpt) (KeyWatcher, error)
75 // WatchAll will invoke the callback for all updates.
76 WatchAll(opts ...WatchOpt) (KeyWatcher, error)
77 // WatchFiltered will watch for any updates to keys that match the keys
78 // argument. It can be configured with the same options as Watch.
79 WatchFiltered(keys []string, opts ...WatchOpt) (KeyWatcher, error)
80 // Keys will return all keys, filtering out any duplicates.
81 // For large datasets, this can be memory-heavy as all keys are loaded
82 // into memory. Use ListKeys for a streaming alternative.
83 Keys(opts ...WatchOpt) ([]string, error)
84 // ListKeys will return all keys in a channel.
85 // Note: On buckets with a large number of keys and frequent writes,
86 // duplicate keys may be reported during listing.
87 ListKeys(opts ...WatchOpt) (KeyLister, error)
88 // History will return all historical values for the key.
89 History(key string, opts ...WatchOpt) ([]KeyValueEntry, error)
90 // Bucket returns the current bucket name.
91 Bucket() string
92 // PurgeDeletes will remove all current delete markers.
93 PurgeDeletes(opts ...PurgeOpt) error
94 // Status retrieves the status and configuration of a bucket
95 Status() (KeyValueStatus, error)
96 }
97
98 // KeyValueStatus is run-time status about a Key-Value bucket
99 type KeyValueStatus interface {
100 // Bucket the name of the bucket
101 Bucket() string
102
103 // Values is how many messages are in the bucket, including historical values
104 Values() uint64
105
106 // History returns the configured history kept per key
107 History() int64
108
109 // TTL is how long the bucket keeps values for
110 TTL() time.Duration
111
112 // BackingStore indicates what technology is used for storage of the bucket
113 BackingStore() string
114
115 // Bytes returns the size in bytes of the bucket
116 Bytes() uint64
117
118 // IsCompressed indicates if the data is compressed on disk
119 IsCompressed() bool
120
121 // Config returns the original configuration used to create the bucket
122 Config() KeyValueConfig
123 }
124
125 // KeyWatcher is what is returned when doing a watch.
126 type KeyWatcher interface {
127 // Context returns watcher context optionally provided by nats.Context option.
128 Context() context.Context
129 // Updates returns a channel to read any updates to entries.
130 Updates() <-chan KeyValueEntry
131 // Stop will stop this watcher.
132 Stop() error
133 // Error returns a channel that will receive any error that occurs during
134 // watching. In particular, this will receive an error if the watcher times
135 // out while expecting more initial keys. The channel is closed when the
136 // watch operation completes or when Stop() is called.
137 Error() <-chan error
138 }
139
140 // KeyLister is used to retrieve a list of key value store keys
141 type KeyLister interface {
142 Keys() <-chan string
143 Stop() error
144 // Error returns a channel that will receive any error that occurs during
145 // key listing. In particular, this will receive an error if the underlying
146 // watcher times out while expecting more keys. The channel is closed when
147 // the listing operation completes or when Stop() is called.
148 Error() <-chan error
149 }
150
151 type WatchOpt interface {
152 configureWatcher(opts *watchOpts) error
153 }
154
155 // For nats.Context() support.
156 func (ctx ContextOpt) configureWatcher(opts *watchOpts) error {
157 opts.ctx = ctx
158 return nil
159 }
160
161 type watchOpts struct {
162 ctx context.Context
163 // Do not send delete markers to the update channel.
164 ignoreDeletes bool
165 // Include all history per subject, not just last one.
166 includeHistory bool
167 // Include only updates for keys.
168 updatesOnly bool
169 // retrieve only the meta data of the entry
170 metaOnly bool
171 }
172
173 type watchOptFn func(opts *watchOpts) error
174
175 func (opt watchOptFn) configureWatcher(opts *watchOpts) error {
176 return opt(opts)
177 }
178
179 // IncludeHistory instructs the key watcher to include historical values as well.
180 func IncludeHistory() WatchOpt {
181 return watchOptFn(func(opts *watchOpts) error {
182 if opts.updatesOnly {
183 return errors.New("nats: include history can not be used with updates only")
184 }
185 opts.includeHistory = true
186 return nil
187 })
188 }
189
190 // UpdatesOnly instructs the key watcher to only include updates on values (without latest values when started).
191 func UpdatesOnly() WatchOpt {
192 return watchOptFn(func(opts *watchOpts) error {
193 if opts.includeHistory {
194 return errors.New("nats: updates only can not be used with include history")
195 }
196 opts.updatesOnly = true
197 return nil
198 })
199 }
200
201 // IgnoreDeletes will have the key watcher not pass any deleted keys.
202 func IgnoreDeletes() WatchOpt {
203 return watchOptFn(func(opts *watchOpts) error {
204 opts.ignoreDeletes = true
205 return nil
206 })
207 }
208
209 // MetaOnly instructs the key watcher to retrieve only the entry meta data, not the entry value
210 func MetaOnly() WatchOpt {
211 return watchOptFn(func(opts *watchOpts) error {
212 opts.metaOnly = true
213 return nil
214 })
215 }
216
217 type PurgeOpt interface {
218 configurePurge(opts *purgeOpts) error
219 }
220
221 type purgeOpts struct {
222 dmthr time.Duration // Delete markers threshold
223 ctx context.Context
224 }
225
226 // DeleteMarkersOlderThan indicates that delete or purge markers older than that
227 // will be deleted as part of PurgeDeletes() operation, otherwise, only the data
228 // will be removed but markers that are recent will be kept.
229 // Note that if no option is specified, the default is 30 minutes. You can set
230 // this option to a negative value to instruct to always remove the markers,
231 // regardless of their age.
232 type DeleteMarkersOlderThan time.Duration
233
234 func (ttl DeleteMarkersOlderThan) configurePurge(opts *purgeOpts) error {
235 opts.dmthr = time.Duration(ttl)
236 return nil
237 }
238
239 // For nats.Context() support.
240 func (ctx ContextOpt) configurePurge(opts *purgeOpts) error {
241 opts.ctx = ctx
242 return nil
243 }
244
245 type DeleteOpt interface {
246 configureDelete(opts *deleteOpts) error
247 }
248
249 type deleteOpts struct {
250 // Remove all previous revisions.
251 purge bool
252
253 // Delete only if the latest revision matches.
254 revision uint64
255 }
256
257 type deleteOptFn func(opts *deleteOpts) error
258
259 func (opt deleteOptFn) configureDelete(opts *deleteOpts) error {
260 return opt(opts)
261 }
262
263 // LastRevision deletes if the latest revision matches.
264 func LastRevision(revision uint64) DeleteOpt {
265 return deleteOptFn(func(opts *deleteOpts) error {
266 opts.revision = revision
267 return nil
268 })
269 }
270
271 // purge removes all previous revisions.
272 func purge() DeleteOpt {
273 return deleteOptFn(func(opts *deleteOpts) error {
274 opts.purge = true
275 return nil
276 })
277 }
278
279 // KeyValueConfig is for configuring a KeyValue store.
280 type KeyValueConfig struct {
281 Bucket string `json:"bucket"`
282 Description string `json:"description,omitempty"`
283 MaxValueSize int32 `json:"max_value_size,omitempty"`
284 History uint8 `json:"history,omitempty"`
285 TTL time.Duration `json:"ttl,omitempty"`
286 MaxBytes int64 `json:"max_bytes,omitempty"`
287 Storage StorageType `json:"storage,omitempty"`
288 Replicas int `json:"num_replicas,omitempty"`
289 Placement *Placement `json:"placement,omitempty"`
290 RePublish *RePublish `json:"republish,omitempty"`
291 Mirror *StreamSource `json:"mirror,omitempty"`
292 Sources []*StreamSource `json:"sources,omitempty"`
293
294 // Enable underlying stream compression.
295 // NOTE: Compression is supported for nats-server 2.10.0+
296 Compression bool `json:"compression,omitempty"`
297 }
298
299 // Used to watch all keys.
300 const (
301 KeyValueMaxHistory = 64
302 AllKeys = ">"
303 kvLatestRevision = 0
304 kvop = "KV-Operation"
305 kvdel = "DEL"
306 kvpurge = "PURGE"
307 )
308
309 type KeyValueOp uint8
310
311 const (
312 KeyValuePut KeyValueOp = iota
313 KeyValueDelete
314 KeyValuePurge
315 )
316
317 func (op KeyValueOp) String() string {
318 switch op {
319 case KeyValuePut:
320 return "KeyValuePutOp"
321 case KeyValueDelete:
322 return "KeyValueDeleteOp"
323 case KeyValuePurge:
324 return "KeyValuePurgeOp"
325 default:
326 return "Unknown Operation"
327 }
328 }
329
330 // KeyValueEntry is a retrieved entry for Get or List or Watch.
331 type KeyValueEntry interface {
332 // Bucket is the bucket the data was loaded from.
333 Bucket() string
334 // Key is the key that was retrieved.
335 Key() string
336 // Value is the retrieved value.
337 Value() []byte
338 // Revision is a unique sequence for this value.
339 Revision() uint64
340 // Created is the time the data was put in the bucket.
341 Created() time.Time
342 // Delta is distance from the latest value.
343 Delta() uint64
344 // Operation returns Put or Delete or Purge.
345 Operation() KeyValueOp
346 }
347
348 // Errors
349 var (
350 ErrKeyValueConfigRequired = errors.New("nats: config required")
351 ErrInvalidBucketName = errors.New("nats: invalid bucket name")
352 ErrInvalidKey = errors.New("nats: invalid key")
353 ErrBucketNotFound = errors.New("nats: bucket not found")
354 ErrBadBucket = errors.New("nats: bucket not valid key-value store")
355 ErrKeyNotFound = errors.New("nats: key not found")
356 ErrKeyDeleted = errors.New("nats: key was deleted")
357 ErrHistoryToLarge = errors.New("nats: history limited to a max of 64")
358 ErrNoKeysFound = errors.New("nats: no keys found")
359 ErrKeyWatcherTimeout = errors.New("nats: key watcher timed out waiting for initial keys")
360 )
361
362 var (
363 // ErrKeyExists is returned when attempting to create a key that already
364 // exists.
365 //
366 // Note: ErrKeyExists matches errors by code 10071, which CAS conflicts
367 // from Update/Delete/Purge also carry on non-replicated streams;
368 // replicated (R>1) streams report code 10164 instead and will not match.
369 // Do not use ErrKeyExists to detect revision conflicts - use
370 // ErrKeyRevisionMismatch.
371 ErrKeyExists JetStreamError = &jsError{apiErr: &APIError{ErrorCode: JSErrCodeStreamWrongLastSequence, Code: 400}, message: "key exists"}
372
373 // ErrKeyRevisionMismatch is returned by Update, and by Delete/Purge when
374 // the LastRevision option is used, if the provided revision does not
375 // match the key's current revision (an optimistic-concurrency conflict).
376 // Replicated (R>1) streams report this as error code 10164 instead of
377 // 10071; both map to this error.
378 ErrKeyRevisionMismatch JetStreamError = &jsError{message: "key revision mismatch"}
379 )
380
381 const (
382 kvBucketNamePre = "KV_"
383 kvBucketNameTmpl = "KV_%s"
384 kvSubjectsTmpl = "$KV.%s.>"
385 kvSubjectsPreTmpl = "$KV.%s."
386 kvSubjectsPreDomainTmpl = "%s.$KV.%s."
387 )
388
389 // Regex for valid keys and buckets.
390 var (
391 validBucketRe = regexp.MustCompile(`^[a-zA-Z0-9_-]+$`)
392 validKeyRe = regexp.MustCompile(`^[-/_=\.a-zA-Z0-9]+$`)
393 validSearchKeyRe = regexp.MustCompile(`^[-/_=\.a-zA-Z0-9*]*[>]?$`)
394 )
395
396 // KeyValue will lookup and bind to an existing KeyValue store.
397 func (js *js) KeyValue(bucket string) (KeyValue, error) {
398 if !js.nc.serverMinVersion(2, 6, 2) {
399 return nil, errors.New("nats: key-value requires at least server version 2.6.2")
400 }
401 if !bucketValid(bucket) {
402 return nil, ErrInvalidBucketName
403 }
404 stream := fmt.Sprintf(kvBucketNameTmpl, bucket)
405 si, err := js.StreamInfo(stream)
406 if err != nil {
407 if errors.Is(err, ErrStreamNotFound) {
408 err = ErrBucketNotFound
409 }
410 return nil, err
411 }
412 // Do some quick sanity checks that this is a correctly formed stream for KV.
413 // Max msgs per subject should be > 0.
414 if si.Config.MaxMsgsPerSubject < 1 {
415 return nil, ErrBadBucket
416 }
417
418 return mapStreamToKVS(js, si), nil
419 }
420
421 // CreateKeyValue will create a KeyValue store with the following configuration.
422 func (js *js) CreateKeyValue(cfg *KeyValueConfig) (KeyValue, error) {
423 if !js.nc.serverMinVersion(2, 6, 2) {
424 return nil, errors.New("nats: key-value requires at least server version 2.6.2")
425 }
426 if cfg == nil {
427 return nil, ErrKeyValueConfigRequired
428 }
429 if !bucketValid(cfg.Bucket) {
430 return nil, ErrInvalidBucketName
431 }
432 if _, err := js.AccountInfo(); err != nil {
433 return nil, err
434 }
435
436 // Default to 1 for history. Max is 64 for now.
437 history := int64(1)
438 if cfg.History > 0 {
439 if cfg.History > KeyValueMaxHistory {
440 return nil, ErrHistoryToLarge
441 }
442 history = int64(cfg.History)
443 }
444
445 replicas := cfg.Replicas
446 if replicas == 0 {
447 replicas = 1
448 }
449
450 // We will set explicitly some values so that we can do comparison
451 // if we get an "already in use" error and need to check if it is same.
452 maxBytes := cfg.MaxBytes
453 if maxBytes == 0 {
454 maxBytes = -1
455 }
456 maxMsgSize := cfg.MaxValueSize
457 if maxMsgSize == 0 {
458 maxMsgSize = -1
459 }
460 // When stream's MaxAge is not set, server uses 2 minutes as the default
461 // for the duplicate window. If MaxAge is set, and lower than 2 minutes,
462 // then the duplicate window will be set to that. If MaxAge is greater,
463 // we will cap the duplicate window to 2 minutes (to be consistent with
464 // previous behavior).
465 duplicateWindow := 2 * time.Minute
466 if cfg.TTL > 0 && cfg.TTL < duplicateWindow {
467 duplicateWindow = cfg.TTL
468 }
469 var compression StoreCompression
470 if cfg.Compression {
471 compression = S2Compression
472 }
473 scfg := &StreamConfig{
474 Name: fmt.Sprintf(kvBucketNameTmpl, cfg.Bucket),
475 Description: cfg.Description,
476 MaxMsgsPerSubject: history,
477 MaxBytes: maxBytes,
478 MaxAge: cfg.TTL,
479 MaxMsgSize: maxMsgSize,
480 Storage: cfg.Storage,
481 Replicas: replicas,
482 Placement: cfg.Placement,
483 AllowRollup: true,
484 DenyDelete: true,
485 Duplicates: duplicateWindow,
486 MaxMsgs: -1,
487 MaxConsumers: -1,
488 AllowDirect: true,
489 RePublish: cfg.RePublish,
490 Compression: compression,
491 }
492 if cfg.Mirror != nil {
493 // Copy in case we need to make changes so we do not change caller's version.
494 m := cfg.Mirror.copy()
495 if !strings.HasPrefix(m.Name, kvBucketNamePre) {
496 m.Name = fmt.Sprintf(kvBucketNameTmpl, m.Name)
497 }
498 scfg.Mirror = m
499 scfg.MirrorDirect = true
500 } else if len(cfg.Sources) > 0 {
501 for _, ss := range cfg.Sources {
502 var sourceBucketName string
503 if strings.HasPrefix(ss.Name, kvBucketNamePre) {
504 sourceBucketName = ss.Name[len(kvBucketNamePre):]
505 } else {
506 sourceBucketName = ss.Name
507 ss.Name = fmt.Sprintf(kvBucketNameTmpl, ss.Name)
508 }
509
510 if ss.External == nil || sourceBucketName != cfg.Bucket {
511 ss.SubjectTransforms = []SubjectTransformConfig{{Source: fmt.Sprintf(kvSubjectsTmpl, sourceBucketName), Destination: fmt.Sprintf(kvSubjectsTmpl, cfg.Bucket)}}
512 }
513 scfg.Sources = append(scfg.Sources, ss)
514 }
515 scfg.Subjects = []string{fmt.Sprintf(kvSubjectsTmpl, cfg.Bucket)}
516 } else {
517 scfg.Subjects = []string{fmt.Sprintf(kvSubjectsTmpl, cfg.Bucket)}
518 }
519
520 // If we are at server version 2.7.2 or above use DiscardNew. We can not use DiscardNew for 2.7.1 or below.
521 if js.nc.serverMinVersion(2, 7, 2) {
522 scfg.Discard = DiscardNew
523 }
524
525 si, err := js.AddStream(scfg)
526 if err != nil {
527 // If we have a failure to add, it could be because we have
528 // a config change if the KV was created against a pre 2.7.2
529 // and we are now moving to a v2.7.2+. If that is the case
530 // and the only difference is the discard policy, then update
531 // the stream.
532 // The same logic applies for KVs created pre 2.9.x and
533 // the AllowDirect setting.
534 if errors.Is(err, ErrStreamNameAlreadyInUse) {
535 if si, _ = js.StreamInfo(scfg.Name); si != nil {
536 // To compare, make the server's stream info discard
537 // policy same than ours.
538 si.Config.Discard = scfg.Discard
539 // Also need to set allow direct for v2.9.x+
540 si.Config.AllowDirect = scfg.AllowDirect
541 if reflect.DeepEqual(&si.Config, scfg) {
542 si, err = js.UpdateStream(scfg)
543 }
544 }
545 }
546 if err != nil {
547 return nil, err
548 }
549 }
550 return mapStreamToKVS(js, si), nil
551 }
552
553 // DeleteKeyValue will delete this KeyValue store (JetStream stream).
554 func (js *js) DeleteKeyValue(bucket string) error {
555 if !bucketValid(bucket) {
556 return ErrInvalidBucketName
557 }
558 stream := fmt.Sprintf(kvBucketNameTmpl, bucket)
559 return js.DeleteStream(stream)
560 }
561
562 type kvs struct {
563 name string
564 stream string
565 pre string
566 putPre string
567 js *js
568 // If true, it means that APIPrefix/Domain was set in the context
569 // and we need to add something to some of our high level protocols
570 // (such as Put, etc..)
571 useJSPfx bool
572 // To know if we can use the stream direct get API
573 useDirect bool
574 }
575
576 // Underlying entry.
577 type kve struct {
578 bucket string
579 key string
580 value []byte
581 revision uint64
582 delta uint64
583 created time.Time
584 op KeyValueOp
585 }
586
587 func (e *kve) Bucket() string { return e.bucket }
588 func (e *kve) Key() string { return e.key }
589 func (e *kve) Value() []byte { return e.value }
590 func (e *kve) Revision() uint64 { return e.revision }
591 func (e *kve) Created() time.Time { return e.created }
592 func (e *kve) Delta() uint64 { return e.delta }
593 func (e *kve) Operation() KeyValueOp { return e.op }
594
595 func bucketValid(bucket string) bool {
596 if len(bucket) == 0 {
597 return false
598 }
599 return validBucketRe.MatchString(bucket)
600 }
601
602 func keyValid(key string) bool {
603 if len(key) == 0 || key[0] == '.' || key[len(key)-1] == '.' || strings.Contains(key, "..") {
604 return false
605 }
606 return validKeyRe.MatchString(key)
607 }
608
609 func searchKeyValid(key string) bool {
610 if len(key) == 0 || key[0] == '.' || key[len(key)-1] == '.' || strings.Contains(key, "..") {
611 return false
612 }
613 return validSearchKeyRe.MatchString(key)
614 }
615
616 // Get returns the latest value for the key.
617 func (kv *kvs) Get(key string) (KeyValueEntry, error) {
618 e, err := kv.get(key, kvLatestRevision)
619 if err != nil {
620 if errors.Is(err, ErrKeyDeleted) {
621 return nil, ErrKeyNotFound
622 }
623 return nil, err
624 }
625
626 return e, nil
627 }
628
629 // GetRevision returns a specific revision value for the key.
630 func (kv *kvs) GetRevision(key string, revision uint64) (KeyValueEntry, error) {
631 e, err := kv.get(key, revision)
632 if err != nil {
633 if errors.Is(err, ErrKeyDeleted) {
634 return nil, ErrKeyNotFound
635 }
636 return nil, err
637 }
638
639 return e, nil
640 }
641
642 func (kv *kvs) get(key string, revision uint64) (KeyValueEntry, error) {
643 if !keyValid(key) {
644 return nil, ErrInvalidKey
645 }
646
647 var b strings.Builder
648 b.WriteString(kv.pre)
649 b.WriteString(key)
650
651 var m *RawStreamMsg
652 var err error
653 var _opts [1]JSOpt
654 opts := _opts[:0]
655 if kv.useDirect {
656 opts = append(opts, DirectGet())
657 }
658
659 if revision == kvLatestRevision {
660 m, err = kv.js.GetLastMsg(kv.stream, b.String(), opts...)
661 } else {
662 m, err = kv.js.GetMsg(kv.stream, revision, opts...)
663 // If a sequence was provided, just make sure that the retrieved
664 // message subject matches the request.
665 if err == nil && m.Subject != b.String() {
666 return nil, ErrKeyNotFound
667 }
668 }
669 if err != nil {
670 if errors.Is(err, ErrMsgNotFound) {
671 err = ErrKeyNotFound
672 }
673 return nil, err
674 }
675
676 entry := &kve{
677 bucket: kv.name,
678 key: key,
679 value: m.Data,
680 revision: m.Sequence,
681 created: m.Time,
682 }
683
684 // Double check here that this is not a DEL Operation marker.
685 if len(m.Header) > 0 {
686 switch m.Header.Get(kvop) {
687 case kvdel:
688 entry.op = KeyValueDelete
689 return entry, ErrKeyDeleted
690 case kvpurge:
691 entry.op = KeyValuePurge
692 return entry, ErrKeyDeleted
693 }
694 }
695
696 return entry, nil
697 }
698
699 // Put will place the new value for the key into the store.
700 func (kv *kvs) Put(key string, value []byte) (revision uint64, err error) {
701 if !keyValid(key) {
702 return 0, ErrInvalidKey
703 }
704
705 var b strings.Builder
706 if kv.useJSPfx {
707 b.WriteString(kv.js.opts.pre)
708 }
709 if kv.putPre != _EMPTY_ {
710 b.WriteString(kv.putPre)
711 } else {
712 b.WriteString(kv.pre)
713 }
714 b.WriteString(key)
715
716 pa, err := kv.js.Publish(b.String(), value)
717 if err != nil {
718 return 0, err
719 }
720 return pa.Sequence, err
721 }
722
723 // PutString will place the string for the key into the store.
724 func (kv *kvs) PutString(key string, value string) (revision uint64, err error) {
725 return kv.Put(key, []byte(value))
726 }
727
728 // Create will add the key/value pair if it does not exist.
729 func (kv *kvs) Create(key string, value []byte) (revision uint64, err error) {
730 v, err := kv.update(key, value, 0)
731 if err == nil {
732 return v, nil
733 }
734
735 // TODO(dlc) - Since we have tombstones for DEL ops for watchers, this could be from that
736 // so we need to double check.
737 if e, err := kv.get(key, kvLatestRevision); errors.Is(err, ErrKeyDeleted) {
738 return kv.update(key, value, e.Revision())
739 }
740
741 // A wrong-last-sequence response means the key already exists.
742 if isWrongLastSeqErr(err) {
743 // 10071 matches ErrKeyExists via its code and keeps its original
744 // message; 10164 (replicated streams) must wrap ErrKeyExists explicitly.
745 if errors.Is(err, ErrKeyExists) {
746 jserr := ErrKeyExists.(*jsError)
747 return 0, fmt.Errorf("%w: %s", err, jserr.message)
748 }
749 return 0, fmt.Errorf("%w: %w", err, ErrKeyExists)
750 }
751
752 return 0, err
753 }
754
755 // isWrongLastSeqErr reports whether err is a "wrong last sequence" API error.
756 // Replicated (R>1) streams report CAS conflicts as 10164 instead of 10071.
757 func isWrongLastSeqErr(err error) bool {
758 var apiErr *APIError
759 if !errors.As(err, &apiErr) {
760 return false
761 }
762 return apiErr.ErrorCode == JSErrCodeStreamWrongLastSequence ||
763 apiErr.ErrorCode == JSErrCodeStreamWrongLastSequenceConstant
764 }
765
766 // mapRevisionMismatch wraps a wrong-last-sequence error with
767 // ErrKeyRevisionMismatch so callers can detect CAS conflicts regardless of
768 // whether the stream reported code 10071 or 10164.
769 func mapRevisionMismatch(err error) error {
770 if err != nil && isWrongLastSeqErr(err) {
771 return fmt.Errorf("%w: %w", err, ErrKeyRevisionMismatch)
772 }
773 return err
774 }
775
776 // Update will update the value if the latest revision matches.
777 // If the provided revision does not match the key's current revision,
778 // ErrKeyRevisionMismatch is returned.
779 func (kv *kvs) Update(key string, value []byte, revision uint64) (uint64, error) {
780 rev, err := kv.update(key, value, revision)
781 return rev, mapRevisionMismatch(err)
782 }
783
784 func (kv *kvs) update(key string, value []byte, revision uint64) (uint64, error) {
785 if !keyValid(key) {
786 return 0, ErrInvalidKey
787 }
788
789 var b strings.Builder
790 if kv.useJSPfx {
791 b.WriteString(kv.js.opts.pre)
792 }
793 b.WriteString(kv.pre)
794 b.WriteString(key)
795
796 m := Msg{Subject: b.String(), Header: Header{}, Data: value}
797 m.Header.Set(ExpectedLastSubjSeqHdr, strconv.FormatUint(revision, 10))
798
799 pa, err := kv.js.PublishMsg(&m)
800 if err != nil {
801 return 0, err
802 }
803 return pa.Sequence, err
804 }
805
806 // Delete will place a delete marker and leave all revisions.
807 // The LastRevision option can be specified to only perform the delete if the
808 // latest revision matches the provided one; if it does not,
809 // ErrKeyRevisionMismatch is returned.
810 func (kv *kvs) Delete(key string, opts ...DeleteOpt) error {
811 if !keyValid(key) {
812 return ErrInvalidKey
813 }
814
815 var b strings.Builder
816 if kv.useJSPfx {
817 b.WriteString(kv.js.opts.pre)
818 }
819 if kv.putPre != _EMPTY_ {
820 b.WriteString(kv.putPre)
821 } else {
822 b.WriteString(kv.pre)
823 }
824 b.WriteString(key)
825
826 // DEL op marker. For watch functionality.
827 m := NewMsg(b.String())
828
829 var o deleteOpts
830 for _, opt := range opts {
831 if opt != nil {
832 if err := opt.configureDelete(&o); err != nil {
833 return err
834 }
835 }
836 }
837
838 if o.purge {
839 m.Header.Set(kvop, kvpurge)
840 m.Header.Set(MsgRollup, MsgRollupSubject)
841 } else {
842 m.Header.Set(kvop, kvdel)
843 }
844
845 if o.revision != 0 {
846 m.Header.Set(ExpectedLastSubjSeqHdr, strconv.FormatUint(o.revision, 10))
847 }
848
849 _, err := kv.js.PublishMsg(m)
850 return mapRevisionMismatch(err)
851 }
852
853 // Purge will remove the key and all revisions.
854 // The LastRevision option can be specified to only perform the purge if the
855 // latest revision matches the provided one; if it does not,
856 // ErrKeyRevisionMismatch is returned.
857 func (kv *kvs) Purge(key string, opts ...DeleteOpt) error {
858 return kv.Delete(key, append(opts, purge())...)
859 }
860
861 const kvDefaultPurgeDeletesMarkerThreshold = 30 * time.Minute
862
863 // PurgeDeletes will remove all current delete markers.
864 // This is a maintenance option if there is a larger buildup of delete markers.
865 // See DeleteMarkersOlderThan() option for more information.
866 func (kv *kvs) PurgeDeletes(opts ...PurgeOpt) error {
867 var o purgeOpts
868 for _, opt := range opts {
869 if opt != nil {
870 if err := opt.configurePurge(&o); err != nil {
871 return err
872 }
873 }
874 }
875 // Transfer possible context purge option to the watcher. This is the
876 // only option that matters for the PurgeDeletes() feature.
877 var wopts []WatchOpt
878 if o.ctx != nil {
879 wopts = append(wopts, Context(o.ctx))
880 }
881 watcher, err := kv.WatchAll(wopts...)
882 if err != nil {
883 return err
884 }
885 defer watcher.Stop()
886
887 var limit time.Time
888 olderThan := o.dmthr
889 // Negative value is used to instruct to always remove markers, regardless
890 // of age. If set to 0 (or not set), use our default value.
891 if olderThan == 0 {
892 olderThan = kvDefaultPurgeDeletesMarkerThreshold
893 }
894 if olderThan > 0 {
895 limit = time.Now().Add(-olderThan)
896 }
897
898 var deleteMarkers []KeyValueEntry
899 for entry := range watcher.Updates() {
900 if entry == nil {
901 break
902 }
903 if op := entry.Operation(); op == KeyValueDelete || op == KeyValuePurge {
904 deleteMarkers = append(deleteMarkers, entry)
905 }
906 }
907 // Stop watcher here so as we purge we do not have the system continually updating numPending.
908 watcher.Stop()
909
910 var (
911 pr StreamPurgeRequest
912 b strings.Builder
913 )
914 // Do actual purges here.
915 purgeOpts := []JSOpt{}
916 if o.ctx != nil {
917 purgeOpts = append(purgeOpts, Context(o.ctx))
918 }
919 for _, entry := range deleteMarkers {
920 b.WriteString(kv.pre)
921 b.WriteString(entry.Key())
922 pr.Subject = b.String()
923 pr.Keep = 0
924 if olderThan > 0 && entry.Created().After(limit) {
925 pr.Keep = 1
926 }
927 if err := kv.js.purgeStream(kv.stream, &pr, purgeOpts...); err != nil {
928 return err
929 }
930 b.Reset()
931 }
932 return nil
933 }
934
935 // Keys will return all keys, filtering out any duplicates.
936 func (kv *kvs) Keys(opts ...WatchOpt) ([]string, error) {
937 opts = append(opts, IgnoreDeletes(), MetaOnly())
938 watcher, err := kv.WatchAll(opts...)
939 if err != nil {
940 return nil, err
941 }
942 defer watcher.Stop()
943
944 var keys []string
945 for entry := range watcher.Updates() {
946 if entry == nil {
947 break
948 }
949 keys = append(keys, entry.Key())
950 }
951 if len(keys) == 0 {
952 return nil, ErrNoKeysFound
953 }
954 slices.Sort(keys)
955 return slices.Compact(keys), nil
956 }
957
958 type keyLister struct {
959 watcher KeyWatcher
960 keys chan string
961 }
962
963 // ListKeys will return all keys.
964 // Note: On buckets with a large number of keys and frequent writes,
965 // duplicate keys may be reported during listing.
966 func (kv *kvs) ListKeys(opts ...WatchOpt) (KeyLister, error) {
967 opts = append(opts, IgnoreDeletes(), MetaOnly())
968 watcher, err := kv.WatchAll(opts...)
969 if err != nil {
970 return nil, err
971 }
972 kl := &keyLister{watcher: watcher, keys: make(chan string, 256)}
973
974 go func() {
975 defer close(kl.keys)
976 defer watcher.Stop()
977 for entry := range watcher.Updates() {
978 if entry == nil {
979 return
980 }
981 kl.keys <- entry.Key()
982 }
983 }()
984 return kl, nil
985 }
986
987 func (kl *keyLister) Keys() <-chan string {
988 return kl.keys
989 }
990
991 func (kl *keyLister) Stop() error {
992 return kl.watcher.Stop()
993 }
994
995 func (kl *keyLister) Error() <-chan error {
996 return kl.watcher.Error()
997 }
998
999 // History will return all values for the key.
1000 func (kv *kvs) History(key string, opts ...WatchOpt) ([]KeyValueEntry, error) {
1001 opts = append(opts, IncludeHistory())
1002 watcher, err := kv.Watch(key, opts...)
1003 if err != nil {
1004 return nil, err
1005 }
1006 defer watcher.Stop()
1007
1008 var entries []KeyValueEntry
1009 for entry := range watcher.Updates() {
1010 if entry == nil {
1011 break
1012 }
1013 entries = append(entries, entry)
1014 }
1015 if len(entries) == 0 {
1016 return nil, ErrKeyNotFound
1017 }
1018 return entries, nil
1019 }
1020
1021 // Implementation for Watch
1022 type watcher struct {
1023 mu sync.Mutex
1024 updates chan KeyValueEntry
1025 sub *Subscription
1026 initDone bool
1027 initPending uint64
1028 received uint64
1029 ctx context.Context
1030 initDoneTimer *time.Timer
1031 errCh chan error
1032 }
1033
1034 // Context returns the context for the watcher if set.
1035 func (w *watcher) Context() context.Context {
1036 if w == nil {
1037 return nil
1038 }
1039 return w.ctx
1040 }
1041
1042 // Updates returns the interior channel.
1043 func (w *watcher) Updates() <-chan KeyValueEntry {
1044 if w == nil {
1045 return nil
1046 }
1047 return w.updates
1048 }
1049
1050 // Stop will unsubscribe from the watcher.
1051 func (w *watcher) Stop() error {
1052 if w == nil {
1053 return nil
1054 }
1055 return w.sub.Unsubscribe()
1056 }
1057
1058 // Error returns a channel that will receive any error that occurs during watching.
1059 func (w *watcher) Error() <-chan error {
1060 if w == nil {
1061 closedCh := make(chan error)
1062 close(closedCh)
1063 return closedCh
1064 }
1065 return w.errCh
1066 }
1067
1068 // WatchAll watches all keys.
1069 func (kv *kvs) WatchAll(opts ...WatchOpt) (KeyWatcher, error) {
1070 return kv.Watch(AllKeys, opts...)
1071 }
1072
1073 func (kv *kvs) WatchFiltered(keys []string, opts ...WatchOpt) (KeyWatcher, error) {
1074 for _, key := range keys {
1075 if !searchKeyValid(key) {
1076 return nil, fmt.Errorf("%w: %s", ErrInvalidKey, "key cannot be empty and must be a valid NATS subject")
1077 }
1078 }
1079 var o watchOpts
1080 for _, opt := range opts {
1081 if opt != nil {
1082 if err := opt.configureWatcher(&o); err != nil {
1083 return nil, err
1084 }
1085 }
1086 }
1087
1088 // Could be a pattern so don't check for validity as we normally do.
1089 for i, key := range keys {
1090 var b strings.Builder
1091 b.WriteString(kv.pre)
1092 b.WriteString(key)
1093 keys[i] = b.String()
1094 }
1095
1096 // if no keys are provided, watch all keys
1097 if len(keys) == 0 {
1098 var b strings.Builder
1099 b.WriteString(kv.pre)
1100 b.WriteString(AllKeys)
1101 keys = []string{b.String()}
1102 }
1103
1104 // We will block below on placing items on the chan. That is by design.
1105 w := &watcher{
1106 updates: make(chan KeyValueEntry, 256),
1107 ctx: o.ctx,
1108 errCh: make(chan error, 1),
1109 }
1110
1111 update := func(m *Msg) {
1112 tokens, err := parser.GetMetadataFields(m.Reply)
1113 if err != nil {
1114 return
1115 }
1116 if len(m.Subject) <= len(kv.pre) {
1117 return
1118 }
1119 subj := m.Subject[len(kv.pre):]
1120
1121 var op KeyValueOp
1122 if len(m.Header) > 0 {
1123 switch m.Header.Get(kvop) {
1124 case kvdel:
1125 op = KeyValueDelete
1126 case kvpurge:
1127 op = KeyValuePurge
1128 }
1129 }
1130 delta := parser.ParseNum(tokens[parser.AckNumPendingTokenPos])
1131 w.mu.Lock()
1132 defer w.mu.Unlock()
1133 if !o.ignoreDeletes || (op != KeyValueDelete && op != KeyValuePurge) {
1134 entry := &kve{
1135 bucket: kv.name,
1136 key: subj,
1137 value: m.Data,
1138 revision: parser.ParseNum(tokens[parser.AckStreamSeqTokenPos]),
1139 created: time.Unix(0, int64(parser.ParseNum(tokens[parser.AckTimestampSeqTokenPos]))),
1140 delta: delta,
1141 op: op,
1142 }
1143 w.updates <- entry
1144 }
1145 // Check if done and initial values.
1146 // Skip if UpdatesOnly() is set, since there will never be updates initially.
1147 if !w.initDone {
1148 w.received++
1149 // Use the stable initPending value set at consumer creation.
1150 // We're done if we've received all expected messages OR there are no more pending
1151 if w.received >= w.initPending || delta == 0 {
1152 // Avoid possible race setting up timer.
1153 if w.initDoneTimer != nil {
1154 w.initDoneTimer.Stop()
1155 }
1156 w.initDone = true
1157 w.updates <- nil
1158 } else if w.initDoneTimer != nil {
1159 w.initDoneTimer.Reset(kv.js.opts.wait)
1160 }
1161 }
1162 }
1163
1164 // Used ordered consumer to deliver results.
1165 subOpts := []SubOpt{BindStream(kv.stream), OrderedConsumer()}
1166 if !o.includeHistory {
1167 subOpts = append(subOpts, DeliverLastPerSubject())
1168 }
1169 if o.updatesOnly {
1170 subOpts = append(subOpts, DeliverNew())
1171 }
1172 if o.metaOnly {
1173 subOpts = append(subOpts, HeadersOnly())
1174 }
1175 if o.ctx != nil {
1176 subOpts = append(subOpts, Context(o.ctx))
1177 }
1178 // Create the sub and rest of initialization under the lock.
1179 // We want to prevent the race between this code and the
1180 // update() callback.
1181 w.mu.Lock()
1182 defer w.mu.Unlock()
1183 var sub *Subscription
1184 var err error
1185 if len(keys) == 1 {
1186 sub, err = kv.js.Subscribe(keys[0], update, subOpts...)
1187 } else {
1188 subOpts = append(subOpts, ConsumerFilterSubjects(keys...))
1189 sub, err = kv.js.Subscribe("", update, subOpts...)
1190 }
1191 if err != nil {
1192 return nil, err
1193 }
1194 sub.mu.Lock()
1195 // If there were no pending messages at the time of the creation
1196 // of the consumer, send the marker.
1197 // Skip if UpdatesOnly() is set, since there will never be updates initially.
1198 if !o.updatesOnly {
1199 if sub.jsi != nil {
1200 if sub.jsi.pending == 0 {
1201 w.initDone = true
1202 w.updates <- nil
1203 } else {
1204 w.initPending = sub.jsi.pending
1205 // Set a timer to send the marker if we do not get any messages.
1206 w.initDoneTimer = time.AfterFunc(kv.js.opts.wait, func() {
1207 w.mu.Lock()
1208 defer w.mu.Unlock()
1209 if !w.initDone {
1210 w.initDone = true
1211 select {
1212 case w.errCh <- ErrKeyWatcherTimeout:
1213 default:
1214 }
1215 w.updates <- nil
1216 }
1217 })
1218 }
1219 }
1220 } else {
1221 // if UpdatesOnly was used, mark initialization as complete
1222 w.initDone = true
1223 }
1224 // Set us up to close when the waitForMessages func returns.
1225 sub.pDone = func(_ string) {
1226 w.mu.Lock()
1227 defer w.mu.Unlock()
1228 if w.initDoneTimer != nil {
1229 w.initDoneTimer.Stop()
1230 }
1231 close(w.updates)
1232 close(w.errCh)
1233 }
1234
1235 sub.mu.Unlock()
1236
1237 w.sub = sub
1238 return w, nil
1239 }
1240
1241 // Watch will fire the callback when a key that matches the keys pattern is updated.
1242 // keys needs to be a valid NATS subject.
1243 func (kv *kvs) Watch(keys string, opts ...WatchOpt) (KeyWatcher, error) {
1244 return kv.WatchFiltered([]string{keys}, opts...)
1245 }
1246
1247 // Bucket returns the current bucket name (JetStream stream).
1248 func (kv *kvs) Bucket() string {
1249 return kv.name
1250 }
1251
1252 // KeyValueBucketStatus represents status of a Bucket, implements KeyValueStatus
1253 type KeyValueBucketStatus struct {
1254 nfo *StreamInfo
1255 bucket string
1256 }
1257
1258 // Bucket the name of the bucket
1259 func (s *KeyValueBucketStatus) Bucket() string { return s.bucket }
1260
1261 // Values is how many messages are in the bucket, including historical values
1262 func (s *KeyValueBucketStatus) Values() uint64 { return s.nfo.State.Msgs }
1263
1264 // History returns the configured history kept per key
1265 func (s *KeyValueBucketStatus) History() int64 { return s.nfo.Config.MaxMsgsPerSubject }
1266
1267 // TTL is how long the bucket keeps values for
1268 func (s *KeyValueBucketStatus) TTL() time.Duration { return s.nfo.Config.MaxAge }
1269
1270 // BackingStore indicates what technology is used for storage of the bucket
1271 func (s *KeyValueBucketStatus) BackingStore() string { return "JetStream" }
1272
1273 // StreamInfo is the stream info retrieved to create the status
1274 func (s *KeyValueBucketStatus) StreamInfo() *StreamInfo { return s.nfo }
1275
1276 // Bytes is the size of the stream
1277 func (s *KeyValueBucketStatus) Bytes() uint64 { return s.nfo.State.Bytes }
1278
1279 // IsCompressed indicates if the data is compressed on disk
1280 func (s *KeyValueBucketStatus) IsCompressed() bool { return s.nfo.Config.Compression != NoCompression }
1281
1282 func (s *KeyValueBucketStatus) Config() KeyValueConfig {
1283 return KeyValueConfig{
1284 Bucket: s.bucket,
1285 Description: s.nfo.Config.Description,
1286 MaxValueSize: s.nfo.Config.MaxMsgSize,
1287 History: uint8(s.nfo.Config.MaxMsgsPerSubject),
1288 TTL: s.nfo.Config.MaxAge,
1289 MaxBytes: s.nfo.Config.MaxBytes,
1290 Storage: s.nfo.Config.Storage,
1291 Replicas: s.nfo.Config.Replicas,
1292 Placement: s.nfo.Config.Placement,
1293 RePublish: s.nfo.Config.RePublish,
1294 Mirror: s.nfo.Config.Mirror,
1295 Sources: s.nfo.Config.Sources,
1296 Compression: s.nfo.Config.Compression != NoCompression,
1297 }
1298 }
1299
1300 // Status retrieves the status and configuration of a bucket
1301 func (kv *kvs) Status() (KeyValueStatus, error) {
1302 nfo, err := kv.js.StreamInfo(kv.stream)
1303 if err != nil {
1304 return nil, err
1305 }
1306
1307 return &KeyValueBucketStatus{nfo: nfo, bucket: kv.name}, nil
1308 }
1309
1310 // KeyValueStoreNames is used to retrieve a list of key value store names
1311 func (js *js) KeyValueStoreNames() <-chan string {
1312 ch := make(chan string)
1313 l := &streamNamesLister{js: js}
1314 l.js.opts.streamListSubject = fmt.Sprintf(kvSubjectsTmpl, "*")
1315 go func() {
1316 defer close(ch)
1317 for l.Next() {
1318 for _, name := range l.Page() {
1319 if !strings.HasPrefix(name, kvBucketNamePre) {
1320 continue
1321 }
1322 ch <- strings.TrimPrefix(name, kvBucketNamePre)
1323 }
1324 }
1325 }()
1326
1327 return ch
1328 }
1329
1330 // KeyValueStores is used to retrieve a list of key value store statuses
1331 func (js *js) KeyValueStores() <-chan KeyValueStatus {
1332 ch := make(chan KeyValueStatus)
1333 l := &streamLister{js: js}
1334 l.js.opts.streamListSubject = fmt.Sprintf(kvSubjectsTmpl, "*")
1335 go func() {
1336 defer close(ch)
1337 for l.Next() {
1338 for _, info := range l.Page() {
1339 if !strings.HasPrefix(info.Config.Name, kvBucketNamePre) {
1340 continue
1341 }
1342 ch <- &KeyValueBucketStatus{nfo: info, bucket: strings.TrimPrefix(info.Config.Name, kvBucketNamePre)}
1343 }
1344 }
1345 }()
1346 return ch
1347 }
1348
1349 func mapStreamToKVS(js *js, info *StreamInfo) *kvs {
1350 bucket := strings.TrimPrefix(info.Config.Name, kvBucketNamePre)
1351
1352 kv := &kvs{
1353 name: bucket,
1354 stream: info.Config.Name,
1355 pre: fmt.Sprintf(kvSubjectsPreTmpl, bucket),
1356 js: js,
1357 // Determine if we need to use the JS prefix in front of Put and Delete operations
1358 useJSPfx: js.opts.pre != defaultAPIPrefix,
1359 useDirect: info.Config.AllowDirect,
1360 }
1361
1362 // If we are mirroring, we will have mirror direct on, so just use the mirror name
1363 // and override use
1364 if m := info.Config.Mirror; m != nil {
1365 bucket := strings.TrimPrefix(m.Name, kvBucketNamePre)
1366 if m.External != nil && m.External.APIPrefix != _EMPTY_ {
1367 kv.useJSPfx = false
1368 kv.pre = fmt.Sprintf(kvSubjectsPreTmpl, bucket)
1369 kv.putPre = fmt.Sprintf(kvSubjectsPreDomainTmpl, m.External.APIPrefix, bucket)
1370 } else {
1371 kv.putPre = fmt.Sprintf(kvSubjectsPreTmpl, bucket)
1372 }
1373 }
1374
1375 return kv
1376 }