Debian Codegraph @

jetstream/kv.go

raw
1 // Copyright 2023-2024 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 jetstream
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"
29 "github.com/nats-io/nats.go/internal/parser"
30 )
31
32 type (
33 // KeyValueManager is used to manage KeyValue stores. It provides methods to
34 // create, delete, and retrieve KeyValue stores.
35 KeyValueManager interface {
36 // KeyValue will lookup and bind to an existing KeyValue store.
37 //
38 // If the KeyValue store with given name does not exist,
39 // ErrBucketNotFound will be returned.
40 KeyValue(ctx context.Context, bucket string) (KeyValue, error)
41
42 // CreateKeyValue will create a KeyValue store with the given
43 // configuration.
44 //
45 // If a KeyValue store with the same name already exists and the
46 // configuration is different, ErrBucketExists will be returned.
47 CreateKeyValue(ctx context.Context, cfg KeyValueConfig) (KeyValue, error)
48
49 // UpdateKeyValue will update an existing KeyValue store with the given
50 // configuration.
51 //
52 // If a KeyValue store with the given name does not exist, ErrBucketNotFound
53 // will be returned.
54 UpdateKeyValue(ctx context.Context, cfg KeyValueConfig) (KeyValue, error)
55
56 // CreateOrUpdateKeyValue will create a KeyValue store if it does not
57 // exist or update an existing KeyValue store with the given
58 // configuration (if possible).
59 CreateOrUpdateKeyValue(ctx context.Context, cfg KeyValueConfig) (KeyValue, error)
60
61 // DeleteKeyValue will delete this KeyValue store.
62 //
63 // If the KeyValue store with given name does not exist,
64 // ErrBucketNotFound will be returned.
65 DeleteKeyValue(ctx context.Context, bucket string) error
66
67 // KeyValueStoreNames is used to retrieve a list of key value store
68 // names. It returns a KeyValueNamesLister exposing a channel to read
69 // the names from. The lister will always close the channel when done
70 // (either all names have been read or an error occurred) and therefore
71 // can be used in range loops.
72 KeyValueStoreNames(ctx context.Context) KeyValueNamesLister
73
74 // KeyValueStores is used to retrieve a list of key value store
75 // statuses. It returns a KeyValueLister exposing a channel to read the
76 // statuses from. The lister will always close the channel when done
77 // (either all statuses have been read or an error occurred) and
78 // therefore can be used in range loops.
79 KeyValueStores(ctx context.Context) KeyValueLister
80 }
81
82 // KeyValue contains methods to operate on a KeyValue store.
83 // Using the KeyValue interface, it is possible to:
84 //
85 // - Get, Put, Create, Update, Delete and Purge a key
86 // - Watch for updates to keys
87 // - List all keys
88 // - Retrieve historical values for a key
89 // - Retrieve status and configuration of a key value bucket
90 // - Purge all delete markers
91 // - Close the KeyValue store
92 KeyValue interface {
93 // Get returns the latest value for the key. If the key does not exist,
94 // ErrKeyNotFound will be returned.
95 Get(ctx context.Context, key string) (KeyValueEntry, error)
96
97 // GetRevision returns a specific revision value for the key. If the key
98 // does not exist or the provided revision does not exists,
99 // ErrKeyNotFound will be returned.
100 GetRevision(ctx context.Context, key string, revision uint64) (KeyValueEntry, error)
101
102 // Put will place the new value for the key into the store. If the key
103 // does not exist, it will be created. If the key exists, the value will
104 // be updated.
105 //
106 // A key has to consist of alphanumeric characters, dashes, underscores,
107 // equal signs, and dots.
108 Put(ctx context.Context, key string, value []byte) (uint64, error)
109
110 // PutString will place the string for the key into the store. If the
111 // key does not exist, it will be created. If the key exists, the value
112 // will be updated.
113 //
114 // A key has to consist of alphanumeric characters, dashes, underscores,
115 // equal signs, and dots.
116 PutString(ctx context.Context, key string, value string) (uint64, error)
117
118 // Create will add the key/value pair if it does not exist. If the key
119 // already exists, ErrKeyExists will be returned.
120 //
121 // A key has to consist of alphanumeric characters, dashes, underscores,
122 // equal signs, and dots.
123 Create(ctx context.Context, key string, value []byte, opts ...KVCreateOpt) (uint64, error)
124
125 // Update will update the value if the latest revision matches.
126 // If the provided revision does not match the key's current revision,
127 // ErrKeyRevisionMismatch is returned.
128 // Update also resets the TTL associated with the key (if any).
129 Update(ctx context.Context, key string, value []byte, revision uint64) (uint64, error)
130
131 // Delete will place a delete marker and leave all revisions. A history
132 // of a deleted key can still be retrieved by using the History method
133 // or a watch on the key. [Delete] is a non-destructive operation and
134 // will not remove any previous revisions from the underlying stream.
135 //
136 // [LastRevision] option can be specified to only perform delete if the
137 // latest revision matches the provided one; if it does not,
138 // ErrKeyRevisionMismatch is returned.
139 Delete(ctx context.Context, key string, opts ...KVDeleteOpt) error
140
141 // Purge will place a delete marker and remove all previous revisions.
142 // Only the latest revision will be preserved (with a delete marker).
143 // Unlike [Delete], Purge is a destructive operation and will remove all
144 // previous revisions from the underlying streams.
145 //
146 // [LastRevision] option can be specified to only perform purge if the
147 // latest revision matches the provided one; if it does not,
148 // ErrKeyRevisionMismatch is returned.
149 Purge(ctx context.Context, key string, opts ...KVDeleteOpt) error
150
151 // Watch for any updates to keys that match the keys argument which
152 // could include wildcards. By default, the watcher will send the latest
153 // value for each key and all future updates. Watch will send a nil
154 // entry when it has received all initial values. There are a few ways
155 // to configure the watcher:
156 //
157 // - IncludeHistory will have the key watcher send all historical values
158 // for each key (up to KeyValueMaxHistory).
159 // - IgnoreDeletes will have the key watcher not pass any keys with
160 // delete markers.
161 // - UpdatesOnly will have the key watcher only pass updates on values
162 // (without latest values when started).
163 // - MetaOnly will have the key watcher retrieve only the entry meta
164 // data, not the entry value.
165 // - ResumeFromRevision instructs the key watcher to resume from a
166 // specific revision number.
167 Watch(ctx context.Context, keys string, opts ...WatchOpt) (KeyWatcher, error)
168
169 // WatchAll will watch for any updates to all keys. It can be configured
170 // with the same options as Watch.
171 WatchAll(ctx context.Context, opts ...WatchOpt) (KeyWatcher, error)
172
173 // WatchFiltered will watch for any updates to keys that match the keys
174 // argument. It can be configured with the same options as Watch.
175 WatchFiltered(ctx context.Context, keys []string, opts ...WatchOpt) (KeyWatcher, error)
176
177 // Keys will return all keys, filtering out any duplicates.
178 // For large datasets, this can be memory-heavy as all keys are loaded
179 // into memory. Use ListKeys for a streaming alternative.
180 Keys(ctx context.Context, opts ...WatchOpt) ([]string, error)
181
182 // ListKeys will return KeyLister, allowing to retrieve all keys from
183 // the key value store in a streaming fashion (on a channel).
184 // Note: On buckets with a large number of keys and frequent writes,
185 // duplicate keys may be reported during listing.
186 ListKeys(ctx context.Context, opts ...WatchOpt) (KeyLister, error)
187
188 // ListKeysFiltered returns a KeyLister for filtered keys in the bucket.
189 // Note: On buckets with a large number of keys and frequent writes,
190 // duplicate keys may be reported during listing.
191 ListKeysFiltered(ctx context.Context, filters ...string) (KeyLister, error)
192
193 // History will return all historical values for the key (up to
194 // KeyValueMaxHistory).
195 History(ctx context.Context, key string, opts ...WatchOpt) ([]KeyValueEntry, error)
196
197 // Bucket returns the KV store name.
198 Bucket() string
199
200 // PurgeDeletes will remove all current delete markers. It can be
201 // configured using DeleteMarkersOlderThan option to only remove delete
202 // markers older than a certain duration.
203 //
204 // [PurgeDeletes] is a destructive operation and will remove all entries
205 // with delete markers from the underlying stream.
206 PurgeDeletes(ctx context.Context, opts ...KVPurgeOpt) error
207
208 // Status retrieves the status and configuration of a bucket.
209 Status(ctx context.Context) (KeyValueStatus, error)
210 }
211
212 // KeyValueConfig is the configuration for a KeyValue store.
213 KeyValueConfig struct {
214 // Bucket is the name of the KeyValue store. Bucket name has to be
215 // unique and can only contain alphanumeric characters, dashes, and
216 // underscores.
217 Bucket string `json:"bucket"`
218
219 // Description is an optional description for the KeyValue store.
220 Description string `json:"description,omitempty"`
221
222 // MaxValueSize is the maximum size of a value in bytes. If not
223 // specified, the default is -1 (unlimited).
224 MaxValueSize int32 `json:"max_value_size,omitempty"`
225
226 // History is the number of historical values to keep per key. If not
227 // specified, the default is 1. Max is 64.
228 History uint8 `json:"history,omitempty"`
229
230 // TTL is the expiry time for keys. By default, keys do not expire.
231 TTL time.Duration `json:"ttl,omitempty"`
232
233 // MaxBytes is the maximum size in bytes of the KeyValue store. If not
234 // specified, the default is -1 (unlimited).
235 MaxBytes int64 `json:"max_bytes,omitempty"`
236
237 // Storage is the type of storage to use for the KeyValue store. If not
238 // specified, the default is FileStorage.
239 Storage StorageType `json:"storage,omitempty"`
240
241 // Replicas is the number of replicas to keep for the KeyValue store in
242 // clustered jetstream. Defaults to 1, maximum is 5.
243 Replicas int `json:"num_replicas,omitempty"`
244
245 // Placement is used to declare where the stream should be placed via
246 // tags and/or an explicit cluster name.
247 Placement *Placement `json:"placement,omitempty"`
248
249 // RePublish allows immediate republishing a message to the configured
250 // subject after it's stored.
251 RePublish *RePublish `json:"republish,omitempty"`
252
253 // Mirror defines the configuration for mirroring another KeyValue
254 // store.
255 Mirror *StreamSource `json:"mirror,omitempty"`
256
257 // Sources defines the configuration for sources of a KeyValue store.
258 // If no subject transforms are defined, it is assumed that a source is
259 // also a KV store and subject transforms will be set to correctly map
260 // keys from the source KV to the current one. If subject transforms are
261 // defined, they will be used as is. This allows using non-kv streams as
262 // sources.
263 Sources []*StreamSource `json:"sources,omitempty"`
264
265 // Compression sets the underlying stream compression.
266 // NOTE: Compression is supported for nats-server 2.10.0+
267 Compression bool `json:"compression,omitempty"`
268
269 // LimitMarkerTTL is how long the bucket keeps markers when keys are
270 // removed by the TTL setting.
271 // It is required for per-key TTL to work and for watcher to notify
272 // about TTL expirations (both per key and per bucket)
273 LimitMarkerTTL time.Duration `json:"limit_marker_ttl,omitempty"`
274
275 // Metadata is a set of application-defined key-value pairs that can be
276 // used to store arbitrary metadata about the bucket.
277 Metadata map[string]string `json:"metadata,omitempty"`
278 }
279
280 // KeyLister is used to retrieve a list of key value store keys. It returns
281 // a channel to read the keys from. The lister will always close the channel
282 // when done (either all keys have been read or an error occurred) and
283 // therefore can be used in range loops. Stop can be used to stop the lister
284 // when not all keys have been read.
285 KeyLister interface {
286 Keys() <-chan string
287 Stop() error
288 }
289
290 // KeyValueLister is used to retrieve a list of key value stores. It returns
291 // a channel to read the KV store statuses from. The lister will always
292 // close the channel when done (either all stores have been retrieved or an
293 // error occurred) and therefore can be used in range loops. Stop can be
294 // used to stop the lister when not all KeyValue stores have been read.
295 KeyValueLister interface {
296 Status() <-chan KeyValueStatus
297 Error() error
298 }
299
300 // KeyValueNamesLister is used to retrieve a list of key value store names.
301 // It returns a channel to read the KV bucket names from. The lister will
302 // always close the channel when done (either all stores have been retrieved
303 // or an error occurred) and therefore can be used in range loops. Stop can
304 // be used to stop the lister when not all bucket names have been read.
305 KeyValueNamesLister interface {
306 Name() <-chan string
307 Error() error
308 }
309
310 // KeyValueStatus is run-time status about a Key-Value bucket.
311 KeyValueStatus interface {
312 // Bucket returns the name of the KeyValue store.
313 Bucket() string
314
315 // Values is how many messages are in the bucket, including historical values.
316 Values() uint64
317
318 // History returns the configured history kept per key.
319 History() int64
320
321 // TTL returns the duration for which keys are kept in the bucket.
322 TTL() time.Duration
323
324 // BackingStore indicates what technology is used for storage of the bucket.
325 // Currently only JetStream is supported.
326 BackingStore() string
327
328 // Bytes returns the size of the bucket in bytes.
329 Bytes() uint64
330
331 // IsCompressed indicates if the data is compressed on disk.
332 IsCompressed() bool
333
334 // LimitMarkerTTL is how long the bucket keeps markers when keys are
335 // removed by the TTL setting, 0 meaning markers are not supported.
336 LimitMarkerTTL() time.Duration
337
338 // Metadata returns the metadata associated with the bucket.
339 Metadata() map[string]string
340
341 // Config returns the configuration for the bucket.
342 Config() KeyValueConfig
343 }
344
345 // KeyWatcher is what is returned when doing a watch. It can be used to
346 // retrieve updates to keys. If not using UpdatesOnly option, it will also
347 // send the latest value for each key. After all initial values have been
348 // sent, a nil entry will be sent. Stop can be used to stop the watcher and
349 // close the underlying channel. Watcher will not close the channel until
350 // Stop is called or connection is closed.
351 KeyWatcher interface {
352 Updates() <-chan KeyValueEntry
353 Stop() error
354 }
355
356 // KeyValueEntry is a retrieved entry for Get, List or Watch.
357 KeyValueEntry interface {
358 // Bucket is the bucket the data was loaded from.
359 Bucket() string
360
361 // Key is the name of the key that was retrieved.
362 Key() string
363
364 // Value is the retrieved value.
365 Value() []byte
366
367 // Revision is a unique sequence for this value.
368 Revision() uint64
369
370 // Created is the time the data was put in the bucket.
371 Created() time.Time
372
373 // Delta is distance from the latest value (how far the current sequence
374 // is from the latest).
375 Delta() uint64
376
377 // Operation returns Put or Delete or Purge, depending on the manner in
378 // which the current revision was created.
379 Operation() KeyValueOp
380 }
381 )
382
383 type (
384 WatchOpt interface {
385 configureWatcher(opts *watchOpts) error
386 }
387
388 watchOpts struct {
389 // Do not send delete markers to the update channel.
390 ignoreDeletes bool
391 // Include all history per subject, not just last one.
392 includeHistory bool
393 // Include only updates for keys.
394 updatesOnly bool
395 // retrieve only the meta data of the entry
396 metaOnly bool
397 // resumeFromRevision is the revision to resume from.
398 resumeFromRevision uint64
399 }
400
401 // KVDeleteOpt is used to configure delete and purge operations.
402 KVDeleteOpt interface {
403 configureDelete(opts *deleteOpts) error
404 }
405
406 deleteOpts struct {
407 // Remove all previous revisions.
408 purge bool
409
410 // Delete only if the latest revision matches.
411 revision uint64
412
413 // purge ttl
414 ttl time.Duration
415 }
416
417 // KVCreateOpt is used to configure Create.
418 KVCreateOpt interface {
419 configureCreate(opts *createOpts) error
420 }
421
422 createOpts struct {
423 ttl time.Duration // TTL for the key
424 }
425
426 // KVPurgeOpt is used to configure PurgeDeletes.
427 KVPurgeOpt interface {
428 configurePurge(opts *purgeOpts) error
429 }
430
431 purgeOpts struct {
432 dmthr time.Duration // Delete markers threshold
433 }
434 )
435
436 // kvs is the implementation of KeyValue
437 type kvs struct {
438 name string
439 streamName string
440 pre string
441 putPre string
442 pushJS nats.JetStreamContext
443 js *jetStream
444 stream Stream
445 // If true, it means that APIPrefix/Domain was set in the context
446 // and we need to add something to some of our high level protocols
447 // (such as Put, etc..)
448 useJSPfx bool
449 // To know if we can use the stream direct get API
450 useDirect bool
451 }
452
453 // KeyValueOp represents the type of KV operation (Put, Delete, Purge). It is a
454 // part of KeyValueEntry.
455 type KeyValueOp uint8
456
457 // Available KeyValueOp values.
458 const (
459 // KeyValuePut is a set on a revision which creates or updates a value for a
460 // key.
461 KeyValuePut KeyValueOp = iota
462
463 // KeyValueDelete is a set on a revision which adds a delete marker for a
464 // key.
465 KeyValueDelete
466
467 // KeyValuePurge is a set on a revision which removes all previous revisions
468 // for a key.
469 KeyValuePurge
470 )
471
472 func (op KeyValueOp) String() string {
473 switch op {
474 case KeyValuePut:
475 return "KeyValuePutOp"
476 case KeyValueDelete:
477 return "KeyValueDeleteOp"
478 case KeyValuePurge:
479 return "KeyValuePurgeOp"
480 default:
481 return "Unknown Operation"
482 }
483 }
484
485 const (
486 kvBucketNamePre = "KV_"
487 kvBucketNameTmpl = "KV_%s"
488 kvSubjectsTmpl = "$KV.%s.>"
489 kvSubjectsPreTmpl = "$KV.%s."
490 kvSubjectsPreDomainTmpl = "%s.$KV.%s."
491 )
492
493 const (
494 KeyValueMaxHistory = 64
495 AllKeys = ">"
496 kvLatestRevision = 0
497 kvop = "KV-Operation"
498 kvdel = "DEL"
499 kvpurge = "PURGE"
500 )
501
502 // Regex for valid keys and buckets.
503 var (
504 validBucketRe = regexp.MustCompile(`^[a-zA-Z0-9_-]+$`)
505 validKeyRe = regexp.MustCompile(`^[-/_=\.a-zA-Z0-9]+$`)
506 validSearchKeyRe = regexp.MustCompile(`^[-/_=\.a-zA-Z0-9*]*[>]?$`)
507 )
508
509 func (js *jetStream) KeyValue(ctx context.Context, bucket string) (KeyValue, error) {
510 if !bucketValid(bucket) {
511 return nil, ErrInvalidBucketName
512 }
513 streamName := fmt.Sprintf(kvBucketNameTmpl, bucket)
514 stream, err := js.Stream(ctx, streamName)
515 if err != nil {
516 if errors.Is(err, ErrStreamNotFound) {
517 err = ErrBucketNotFound
518 }
519 return nil, err
520 }
521 // Do some quick sanity checks that this is a correctly formed stream for KV.
522 // Max msgs per subject should be > 0.
523 if stream.CachedInfo().Config.MaxMsgsPerSubject < 1 {
524 return nil, ErrBadBucket
525 }
526 pushJS, err := js.legacyJetStream()
527 if err != nil {
528 return nil, err
529 }
530
531 return mapStreamToKVS(js, pushJS, stream), nil
532 }
533
534 func (js *jetStream) CreateKeyValue(ctx context.Context, cfg KeyValueConfig) (KeyValue, error) {
535 scfg, err := js.prepareKeyValueConfig(ctx, cfg)
536 if err != nil {
537 return nil, err
538 }
539
540 stream, err := js.CreateStream(ctx, scfg)
541 if err != nil {
542 if errors.Is(err, ErrStreamNameAlreadyInUse) {
543 // errors are joined so that backwards compatibility is retained
544 // and previous checks for ErrStreamNameAlreadyInUse will still work.
545 err = errors.Join(fmt.Errorf("%w: %s", ErrBucketExists, cfg.Bucket), err)
546
547 // If we have a failure to add, it could be because we have
548 // a config change if the KV was created against before a bug fix
549 // that changed the value of discard policy.
550 // We will check if the stream exists and if the only difference
551 // is the discard policy, we will update the stream.
552 // The same logic applies for KVs created pre 2.9.x and
553 // the AllowDirect setting.
554 if stream, _ = js.Stream(ctx, scfg.Name); stream != nil {
555 cfg := stream.CachedInfo().Config
556 cfg.Discard = scfg.Discard
557 cfg.AllowDirect = scfg.AllowDirect
558 if reflect.DeepEqual(cfg, scfg) {
559 stream, err = js.UpdateStream(ctx, scfg)
560 }
561 }
562 }
563 if err != nil {
564 return nil, err
565 }
566 }
567 pushJS, err := js.legacyJetStream()
568 if err != nil {
569 return nil, err
570 }
571
572 return mapStreamToKVS(js, pushJS, stream), nil
573 }
574
575 func (js *jetStream) UpdateKeyValue(ctx context.Context, cfg KeyValueConfig) (KeyValue, error) {
576 scfg, err := js.prepareKeyValueConfig(ctx, cfg)
577 if err != nil {
578 return nil, err
579 }
580
581 stream, err := js.UpdateStream(ctx, scfg)
582 if err != nil {
583 if errors.Is(err, ErrStreamNotFound) {
584 err = fmt.Errorf("%w: %s", ErrBucketNotFound, cfg.Bucket)
585 }
586 return nil, err
587 }
588 pushJS, err := js.legacyJetStream()
589 if err != nil {
590 return nil, err
591 }
592
593 return mapStreamToKVS(js, pushJS, stream), nil
594 }
595
596 func (js *jetStream) CreateOrUpdateKeyValue(ctx context.Context, cfg KeyValueConfig) (KeyValue, error) {
597 scfg, err := js.prepareKeyValueConfig(ctx, cfg)
598 if err != nil {
599 return nil, err
600 }
601
602 stream, err := js.CreateOrUpdateStream(ctx, scfg)
603 if err != nil {
604 return nil, err
605 }
606 pushJS, err := js.legacyJetStream()
607 if err != nil {
608 return nil, err
609 }
610
611 return mapStreamToKVS(js, pushJS, stream), nil
612 }
613
614 func (js *jetStream) prepareKeyValueConfig(ctx context.Context, cfg KeyValueConfig) (StreamConfig, error) {
615 if !bucketValid(cfg.Bucket) {
616 return StreamConfig{}, ErrInvalidBucketName
617 }
618 if _, err := js.AccountInfo(ctx); err != nil {
619 return StreamConfig{}, err
620 }
621
622 // Default to 1 for history. Max is 64 for now.
623 history := int64(1)
624 if cfg.History > 0 {
625 if cfg.History > KeyValueMaxHistory {
626 return StreamConfig{}, ErrHistoryTooLarge
627 }
628 history = int64(cfg.History)
629 }
630
631 replicas := cfg.Replicas
632 if replicas == 0 {
633 replicas = 1
634 }
635
636 // We will set explicitly some values so that we can do comparison
637 // if we get an "already in use" error and need to check if it is same.
638 maxBytes := cfg.MaxBytes
639 if maxBytes == 0 {
640 maxBytes = -1
641 }
642 maxMsgSize := cfg.MaxValueSize
643 if maxMsgSize == 0 {
644 maxMsgSize = -1
645 }
646 // When stream's MaxAge is not set, server uses 2 minutes as the default
647 // for the duplicate window. If MaxAge is set, and lower than 2 minutes,
648 // then the duplicate window will be set to that. If MaxAge is greater,
649 // we will cap the duplicate window to 2 minutes (to be consistent with
650 // previous behavior).
651 duplicateWindow := 2 * time.Minute
652 if cfg.TTL > 0 && cfg.TTL < duplicateWindow {
653 duplicateWindow = cfg.TTL
654 }
655 var compression StoreCompression
656 if cfg.Compression {
657 compression = S2Compression
658 }
659 var allowMsgTTL bool
660 var subjectDeleteMarkerTTL time.Duration
661 if cfg.LimitMarkerTTL != 0 {
662 info, err := js.AccountInfo(ctx)
663 if err != nil {
664 return StreamConfig{}, err
665 }
666 if info.API.Level < 1 {
667 return StreamConfig{}, ErrLimitMarkerTTLNotSupported
668 }
669 allowMsgTTL = true
670 subjectDeleteMarkerTTL = cfg.LimitMarkerTTL
671 }
672 scfg := StreamConfig{
673 Name: fmt.Sprintf(kvBucketNameTmpl, cfg.Bucket),
674 Description: cfg.Description,
675 MaxMsgsPerSubject: history,
676 MaxBytes: maxBytes,
677 MaxAge: cfg.TTL,
678 MaxMsgSize: maxMsgSize,
679 Storage: cfg.Storage,
680 Replicas: replicas,
681 Placement: cfg.Placement,
682 AllowRollup: true,
683 DenyDelete: true,
684 Duplicates: duplicateWindow,
685 MaxMsgs: -1,
686 MaxConsumers: -1,
687 AllowDirect: true,
688 RePublish: cfg.RePublish,
689 Compression: compression,
690 Discard: DiscardNew,
691 AllowMsgTTL: allowMsgTTL,
692 SubjectDeleteMarkerTTL: subjectDeleteMarkerTTL,
693 Metadata: cfg.Metadata,
694 }
695 if cfg.Mirror != nil {
696 // Copy in case we need to make changes so we do not change caller's version.
697 m := cfg.Mirror.copy()
698 if !strings.HasPrefix(m.Name, kvBucketNamePre) {
699 m.Name = fmt.Sprintf(kvBucketNameTmpl, m.Name)
700 }
701 scfg.Mirror = m
702 scfg.MirrorDirect = true
703 } else if len(cfg.Sources) > 0 {
704 for _, ss := range cfg.Sources {
705 // if subject transforms are already set, then use as is.
706 // this allows for full control of the source, e.g. using non-KV streams.
707 // Note that in this case, the Name is not modified and full stream name must be provided.
708 if len(ss.SubjectTransforms) > 0 {
709 scfg.Sources = append(scfg.Sources, ss)
710 continue
711 }
712 var sourceBucketName string
713 if strings.HasPrefix(ss.Name, kvBucketNamePre) {
714 sourceBucketName = ss.Name[len(kvBucketNamePre):]
715 } else {
716 sourceBucketName = ss.Name
717 ss.Name = fmt.Sprintf(kvBucketNameTmpl, ss.Name)
718 }
719
720 if ss.External == nil || sourceBucketName != cfg.Bucket {
721 ss.SubjectTransforms = []SubjectTransformConfig{{Source: fmt.Sprintf(kvSubjectsTmpl, sourceBucketName), Destination: fmt.Sprintf(kvSubjectsTmpl, cfg.Bucket)}}
722 }
723 scfg.Sources = append(scfg.Sources, ss)
724 }
725 scfg.Subjects = []string{fmt.Sprintf(kvSubjectsTmpl, cfg.Bucket)}
726 } else {
727 scfg.Subjects = []string{fmt.Sprintf(kvSubjectsTmpl, cfg.Bucket)}
728 }
729
730 return scfg, nil
731 }
732
733 // DeleteKeyValue will delete this KeyValue store (JetStream stream).
734 func (js *jetStream) DeleteKeyValue(ctx context.Context, bucket string) error {
735 if !bucketValid(bucket) {
736 return ErrInvalidBucketName
737 }
738 stream := fmt.Sprintf(kvBucketNameTmpl, bucket)
739 if err := js.DeleteStream(ctx, stream); err != nil {
740 if errors.Is(err, ErrStreamNotFound) {
741 err = errors.Join(fmt.Errorf("%w: %s", ErrBucketNotFound, bucket), err)
742 }
743 return err
744 }
745 return nil
746 }
747
748 // KeyValueStoreNames is used to retrieve a list of key value store names
749 func (js *jetStream) KeyValueStoreNames(ctx context.Context) KeyValueNamesLister {
750 res := &kvLister{
751 kvNames: make(chan string),
752 }
753 l := &streamLister{js: js}
754 streamsReq := streamsRequest{
755 Subject: fmt.Sprintf(kvSubjectsTmpl, "*"),
756 }
757 go func() {
758 defer close(res.kvNames)
759 for {
760 page, err := l.streamNames(ctx, streamsReq)
761 if err != nil && !errors.Is(err, ErrEndOfData) {
762 res.err = err
763 return
764 }
765 for _, name := range page {
766 if !strings.HasPrefix(name, kvBucketNamePre) {
767 continue
768 }
769 res.kvNames <- strings.TrimPrefix(name, kvBucketNamePre)
770 }
771 if errors.Is(err, ErrEndOfData) {
772 return
773 }
774 }
775 }()
776 return res
777 }
778
779 // KeyValueStores is used to retrieve a list of key value store statuses
780 func (js *jetStream) KeyValueStores(ctx context.Context) KeyValueLister {
781 res := &kvLister{
782 kvs: make(chan KeyValueStatus),
783 }
784 l := &streamLister{js: js}
785 streamsReq := streamsRequest{
786 Subject: fmt.Sprintf(kvSubjectsTmpl, "*"),
787 }
788 go func() {
789 defer close(res.kvs)
790 for {
791 page, err := l.streamInfos(ctx, streamsReq)
792 if err != nil && !errors.Is(err, ErrEndOfData) {
793 res.err = err
794 return
795 }
796 for _, info := range page {
797 if !strings.HasPrefix(info.Config.Name, kvBucketNamePre) {
798 continue
799 }
800 res.kvs <- &KeyValueBucketStatus{info: info, bucket: strings.TrimPrefix(info.Config.Name, kvBucketNamePre)}
801 }
802 if errors.Is(err, ErrEndOfData) {
803 return
804 }
805 }
806 }()
807 return res
808 }
809
810 // KeyValueBucketStatus represents status of a Bucket, implements KeyValueStatus
811 type KeyValueBucketStatus struct {
812 info *StreamInfo
813 bucket string
814 }
815
816 // Bucket the name of the bucket
817 func (s *KeyValueBucketStatus) Bucket() string { return s.bucket }
818
819 // Values is how many messages are in the bucket, including historical values
820 func (s *KeyValueBucketStatus) Values() uint64 { return s.info.State.Msgs }
821
822 // History returns the configured history kept per key
823 func (s *KeyValueBucketStatus) History() int64 { return s.info.Config.MaxMsgsPerSubject }
824
825 // TTL is how long the bucket keeps values for
826 func (s *KeyValueBucketStatus) TTL() time.Duration { return s.info.Config.MaxAge }
827
828 // BackingStore indicates what technology is used for storage of the bucket
829 func (s *KeyValueBucketStatus) BackingStore() string { return "JetStream" }
830
831 // StreamInfo is the stream info retrieved to create the status
832 func (s *KeyValueBucketStatus) StreamInfo() *StreamInfo { return s.info }
833
834 // Bytes is the size of the stream
835 func (s *KeyValueBucketStatus) Bytes() uint64 { return s.info.State.Bytes }
836
837 // IsCompressed indicates if the data is compressed on disk
838 func (s *KeyValueBucketStatus) IsCompressed() bool { return s.info.Config.Compression != NoCompression }
839
840 // LimitMarkerTTL is how long the bucket keeps markers when keys are
841 // removed by the TTL setting, 0 meaning markers are not supported.
842 func (s *KeyValueBucketStatus) LimitMarkerTTL() time.Duration {
843 return s.info.Config.SubjectDeleteMarkerTTL
844 }
845
846 // Config returns the configuration for the bucket.
847 func (s *KeyValueBucketStatus) Config() KeyValueConfig {
848 return KeyValueConfig{
849 Bucket: s.bucket,
850 Description: s.info.Config.Description,
851 MaxValueSize: s.info.Config.MaxMsgSize,
852 History: uint8(s.info.Config.MaxMsgsPerSubject),
853 TTL: s.info.Config.MaxAge,
854 MaxBytes: s.info.Config.MaxBytes,
855 Storage: s.info.Config.Storage,
856 Replicas: s.info.Config.Replicas,
857 Placement: s.info.Config.Placement,
858 RePublish: s.info.Config.RePublish,
859 Mirror: s.info.Config.Mirror,
860 Sources: s.info.Config.Sources,
861 Compression: s.info.Config.Compression != NoCompression,
862 Metadata: s.info.Config.Metadata,
863 LimitMarkerTTL: s.info.Config.SubjectDeleteMarkerTTL,
864 }
865 }
866
867 // Metadata returns the metadata associated with the bucket.
868 func (s *KeyValueBucketStatus) Metadata() map[string]string {
869 return s.info.Config.Metadata
870 }
871
872 type kvLister struct {
873 kvs chan KeyValueStatus
874 kvNames chan string
875 err error
876 }
877
878 func (kl *kvLister) Status() <-chan KeyValueStatus {
879 return kl.kvs
880 }
881
882 func (kl *kvLister) Name() <-chan string {
883 return kl.kvNames
884 }
885
886 func (kl *kvLister) Error() error {
887 return kl.err
888 }
889
890 func (js *jetStream) legacyJetStream() (nats.JetStreamContext, error) {
891 opts := make([]nats.JSOpt, 0)
892 if js.opts.apiPrefix != "" {
893 opts = append(opts, nats.APIPrefix(js.opts.apiPrefix))
894 }
895 if js.opts.ClientTrace != nil {
896 opts = append(opts, nats.ClientTrace{
897 RequestSent: js.opts.ClientTrace.RequestSent,
898 ResponseReceived: js.opts.ClientTrace.ResponseReceived,
899 })
900 }
901 return js.conn.JetStream(opts...)
902 }
903
904 func bucketValid(bucket string) bool {
905 if len(bucket) == 0 {
906 return false
907 }
908 return validBucketRe.MatchString(bucket)
909 }
910
911 func keyValid(key string) bool {
912 if len(key) == 0 || key[0] == '.' || key[len(key)-1] == '.' || strings.Contains(key, "..") {
913 return false
914 }
915 return validKeyRe.MatchString(key)
916 }
917
918 func searchKeyValid(key string) bool {
919 if len(key) == 0 || key[0] == '.' || key[len(key)-1] == '.' || strings.Contains(key, "..") {
920 return false
921 }
922 return validSearchKeyRe.MatchString(key)
923 }
924
925 func (kv *kvs) get(ctx context.Context, key string, revision uint64) (KeyValueEntry, error) {
926 if !keyValid(key) {
927 return nil, ErrInvalidKey
928 }
929
930 var b strings.Builder
931 b.WriteString(kv.pre)
932 b.WriteString(key)
933
934 var m *RawStreamMsg
935 var err error
936
937 if revision == kvLatestRevision {
938 m, err = kv.stream.GetLastMsgForSubject(ctx, b.String())
939 } else {
940 m, err = kv.stream.GetMsg(ctx, revision)
941 // If a sequence was provided, just make sure that the retrieved
942 // message subject matches the request.
943 if err == nil && m.Subject != b.String() {
944 return nil, ErrKeyNotFound
945 }
946 }
947 if err != nil {
948 if errors.Is(err, ErrMsgNotFound) {
949 err = ErrKeyNotFound
950 }
951 return nil, err
952 }
953
954 entry := &kve{
955 bucket: kv.name,
956 key: key,
957 value: m.Data,
958 revision: m.Sequence,
959 created: m.Time,
960 }
961
962 // Double check here that this is not a DEL Operation marker.
963 if len(m.Header) > 0 {
964 if m.Header.Get(kvop) != "" {
965 switch m.Header.Get(kvop) {
966 case kvdel:
967 entry.op = KeyValueDelete
968 case kvpurge:
969 entry.op = KeyValuePurge
970 }
971 } else if m.Header.Get(MarkerReasonHeader) != "" {
972 switch m.Header.Get(MarkerReasonHeader) {
973 case "MaxAge", "Purge":
974 entry.op = KeyValuePurge
975 case "Remove":
976 entry.op = KeyValueDelete
977 }
978 }
979 if entry.op != KeyValuePut {
980 return entry, ErrKeyDeleted
981 }
982 }
983
984 return entry, nil
985 }
986
987 // kve is the implementation of KeyValueEntry
988 type kve struct {
989 bucket string
990 key string
991 value []byte
992 revision uint64
993 delta uint64
994 created time.Time
995 op KeyValueOp
996 }
997
998 func (e *kve) Bucket() string { return e.bucket }
999 func (e *kve) Key() string { return e.key }
1000 func (e *kve) Value() []byte { return e.value }
1001 func (e *kve) Revision() uint64 { return e.revision }
1002 func (e *kve) Created() time.Time { return e.created }
1003 func (e *kve) Delta() uint64 { return e.delta }
1004 func (e *kve) Operation() KeyValueOp { return e.op }
1005
1006 // Get returns the latest value for the key.
1007 func (kv *kvs) Get(ctx context.Context, key string) (KeyValueEntry, error) {
1008 e, err := kv.get(ctx, key, kvLatestRevision)
1009 if err != nil {
1010 if errors.Is(err, ErrKeyDeleted) {
1011 return nil, ErrKeyNotFound
1012 }
1013 return nil, err
1014 }
1015
1016 return e, nil
1017 }
1018
1019 // GetRevision returns a specific revision value for the key.
1020 func (kv *kvs) GetRevision(ctx context.Context, key string, revision uint64) (KeyValueEntry, error) {
1021 e, err := kv.get(ctx, key, revision)
1022 if err != nil {
1023 if errors.Is(err, ErrKeyDeleted) {
1024 return nil, ErrKeyNotFound
1025 }
1026 return nil, err
1027 }
1028
1029 return e, nil
1030 }
1031
1032 // Put will place the new value for the key into the store.
1033 func (kv *kvs) Put(ctx context.Context, key string, value []byte) (uint64, error) {
1034 if !keyValid(key) {
1035 return 0, ErrInvalidKey
1036 }
1037
1038 var b strings.Builder
1039 if kv.useJSPfx {
1040 b.WriteString(kv.js.opts.apiPrefix)
1041 }
1042 if kv.putPre != "" {
1043 b.WriteString(kv.putPre)
1044 } else {
1045 b.WriteString(kv.pre)
1046 }
1047 b.WriteString(key)
1048
1049 pa, err := kv.js.Publish(ctx, b.String(), value)
1050 if err != nil {
1051 return 0, err
1052 }
1053 return pa.Sequence, err
1054 }
1055
1056 // PutString will place the string for the key into the store.
1057 func (kv *kvs) PutString(ctx context.Context, key string, value string) (uint64, error) {
1058 return kv.Put(ctx, key, []byte(value))
1059 }
1060
1061 // Create will add the key/value pair if it does not exist.
1062 func (kv *kvs) Create(ctx context.Context, key string, value []byte, opts ...KVCreateOpt) (revision uint64, err error) {
1063 var o createOpts
1064 for _, opt := range opts {
1065 if opt != nil {
1066 if err := opt.configureCreate(&o); err != nil {
1067 return 0, err
1068 }
1069 }
1070 }
1071
1072 v, err := kv.updateRevision(ctx, key, value, 0, o.ttl)
1073 if err == nil {
1074 return v, nil
1075 }
1076
1077 if e, err := kv.get(ctx, key, kvLatestRevision); errors.Is(err, ErrKeyDeleted) {
1078 return kv.updateRevision(ctx, key, value, e.Revision(), o.ttl)
1079 }
1080
1081 // A wrong-last-sequence response means the key already exists.
1082 if isWrongLastSeqErr(err) {
1083 // 10071 matches ErrKeyExists via its code and keeps its original
1084 // message; 10164 (replicated streams) must wrap ErrKeyExists explicitly.
1085 if errors.Is(err, ErrKeyExists) {
1086 jserr := ErrKeyExists.(*jsError)
1087 return 0, fmt.Errorf("%w: %s", err, jserr.message)
1088 }
1089 return 0, fmt.Errorf("%w: %w", err, ErrKeyExists)
1090 }
1091
1092 return 0, err
1093 }
1094
1095 // isWrongLastSeqErr reports whether err is a "wrong last sequence" API error.
1096 // Replicated (R>1) streams report CAS conflicts as 10164 instead of 10071.
1097 func isWrongLastSeqErr(err error) bool {
1098 var apiErr *APIError
1099 if !errors.As(err, &apiErr) {
1100 return false
1101 }
1102 return apiErr.ErrorCode == JSErrCodeStreamWrongLastSequence ||
1103 apiErr.ErrorCode == JSErrCodeStreamWrongLastSequenceConstant
1104 }
1105
1106 // mapRevisionMismatch wraps a wrong-last-sequence error with
1107 // ErrKeyRevisionMismatch so callers can detect CAS conflicts regardless of
1108 // whether the stream reported code 10071 or 10164.
1109 func mapRevisionMismatch(err error) error {
1110 if err != nil && isWrongLastSeqErr(err) {
1111 return fmt.Errorf("%w: %w", err, ErrKeyRevisionMismatch)
1112 }
1113 return err
1114 }
1115
1116 // Update will update the value if the latest revision matches.
1117 func (kv *kvs) Update(ctx context.Context, key string, value []byte, revision uint64) (uint64, error) {
1118 rev, err := kv.updateRevision(ctx, key, value, revision, 0)
1119 return rev, mapRevisionMismatch(err)
1120 }
1121
1122 func (kv *kvs) updateRevision(ctx context.Context, key string, value []byte, revision uint64, ttl time.Duration) (uint64, error) {
1123 if !keyValid(key) {
1124 return 0, ErrInvalidKey
1125 }
1126
1127 var b strings.Builder
1128 if kv.useJSPfx {
1129 b.WriteString(kv.js.opts.apiPrefix)
1130 }
1131 if kv.putPre != "" {
1132 b.WriteString(kv.putPre)
1133 } else {
1134 b.WriteString(kv.pre)
1135 }
1136 b.WriteString(key)
1137
1138 m := nats.Msg{Subject: b.String(), Header: nats.Header{}, Data: value}
1139 opts := []PublishOpt{
1140 WithExpectLastSequencePerSubject(revision),
1141 }
1142 if ttl > 0 {
1143 opts = append(opts, WithMsgTTL(ttl))
1144 }
1145
1146 pa, err := kv.js.PublishMsg(ctx, &m, opts...)
1147 if err != nil {
1148 return 0, err
1149 }
1150 return pa.Sequence, err
1151 }
1152
1153 // Delete will place a delete marker and leave all revisions.
1154 func (kv *kvs) Delete(ctx context.Context, key string, opts ...KVDeleteOpt) error {
1155 if !keyValid(key) {
1156 return ErrInvalidKey
1157 }
1158
1159 var b strings.Builder
1160 if kv.useJSPfx {
1161 b.WriteString(kv.js.opts.apiPrefix)
1162 }
1163 if kv.putPre != "" {
1164 b.WriteString(kv.putPre)
1165 } else {
1166 b.WriteString(kv.pre)
1167 }
1168 b.WriteString(key)
1169
1170 // DEL op marker. For watch functionality.
1171 m := nats.NewMsg(b.String())
1172
1173 var o deleteOpts
1174 for _, opt := range opts {
1175 if opt != nil {
1176 if err := opt.configureDelete(&o); err != nil {
1177 return err
1178 }
1179 }
1180 }
1181
1182 if o.purge {
1183 m.Header.Set(kvop, kvpurge)
1184 m.Header.Set(MsgRollup, MsgRollupSubject)
1185 } else {
1186 m.Header.Set(kvop, kvdel)
1187 }
1188 pubOpts := make([]PublishOpt, 0)
1189 if o.ttl > 0 && o.purge {
1190 pubOpts = append(pubOpts, WithMsgTTL(o.ttl))
1191 } else if o.ttl > 0 {
1192 return ErrTTLOnDeleteNotSupported
1193 }
1194
1195 if o.revision != 0 {
1196 m.Header.Set(ExpectedLastSubjSeqHeader, strconv.FormatUint(o.revision, 10))
1197 }
1198
1199 _, err := kv.js.PublishMsg(ctx, m, pubOpts...)
1200 return mapRevisionMismatch(err)
1201 }
1202
1203 // Purge will place a delete marker and remove all previous revisions.
1204 func (kv *kvs) Purge(ctx context.Context, key string, opts ...KVDeleteOpt) error {
1205 return kv.Delete(ctx, key, append(opts, purge())...)
1206 }
1207
1208 // purge removes all previous revisions.
1209 func purge() KVDeleteOpt {
1210 return deleteOptFn(func(opts *deleteOpts) error {
1211 opts.purge = true
1212 return nil
1213 })
1214 }
1215
1216 // Implementation for Watch
1217 type watcher struct {
1218 mu sync.Mutex
1219 updates chan KeyValueEntry
1220 sub *nats.Subscription
1221 initDone bool
1222 initPending uint64
1223 received uint64
1224 }
1225
1226 // Updates returns the interior channel.
1227 func (w *watcher) Updates() <-chan KeyValueEntry {
1228 if w == nil {
1229 return nil
1230 }
1231 return w.updates
1232 }
1233
1234 // Stop will unsubscribe from the watcher.
1235 func (w *watcher) Stop() error {
1236 if w == nil {
1237 return nil
1238 }
1239 return w.sub.Unsubscribe()
1240 }
1241
1242 // WatchFiltered will watch for any updates to keys that match the provided
1243 // key filters. It can be configured with the same options as Watch.
1244 func (kv *kvs) WatchFiltered(ctx context.Context, keys []string, opts ...WatchOpt) (KeyWatcher, error) {
1245 for _, key := range keys {
1246 if !searchKeyValid(key) {
1247 return nil, fmt.Errorf("%w: %s", ErrInvalidKey, "key cannot be empty and must be a valid NATS subject")
1248 }
1249 }
1250 var o watchOpts
1251 for _, opt := range opts {
1252 if opt != nil {
1253 if err := opt.configureWatcher(&o); err != nil {
1254 return nil, err
1255 }
1256 }
1257 }
1258
1259 // Could be a pattern so don't check for validity as we normally do.
1260 for i, key := range keys {
1261 var b strings.Builder
1262 b.WriteString(kv.pre)
1263 b.WriteString(key)
1264 keys[i] = b.String()
1265 }
1266
1267 // if no keys are provided, watch all keys
1268 if len(keys) == 0 {
1269 var b strings.Builder
1270 b.WriteString(kv.pre)
1271 b.WriteString(AllKeys)
1272 keys = []string{b.String()}
1273 }
1274
1275 // We will block below on placing items on the chan. That is by design.
1276 w := &watcher{updates: make(chan KeyValueEntry, 256)}
1277
1278 update := func(m *nats.Msg) {
1279 tokens, err := parser.GetMetadataFields(m.Reply)
1280 if err != nil {
1281 return
1282 }
1283 if len(m.Subject) <= len(kv.pre) {
1284 return
1285 }
1286 subj := m.Subject[len(kv.pre):]
1287
1288 var op KeyValueOp
1289 if len(m.Header) > 0 {
1290 if m.Header.Get(kvop) != "" {
1291 switch m.Header.Get(kvop) {
1292 case kvdel:
1293 op = KeyValueDelete
1294 case kvpurge:
1295 op = KeyValuePurge
1296 }
1297 } else if m.Header.Get(MarkerReasonHeader) != "" {
1298 switch m.Header.Get(MarkerReasonHeader) {
1299 case "MaxAge", "Purge":
1300 op = KeyValuePurge
1301 case "Remove":
1302 op = KeyValueDelete
1303 }
1304 }
1305 }
1306 delta := parser.ParseNum(tokens[parser.AckNumPendingTokenPos])
1307 w.mu.Lock()
1308 defer w.mu.Unlock()
1309 if !o.ignoreDeletes || (op != KeyValueDelete && op != KeyValuePurge) {
1310 entry := &kve{
1311 bucket: kv.name,
1312 key: subj,
1313 value: m.Data,
1314 revision: parser.ParseNum(tokens[parser.AckStreamSeqTokenPos]),
1315 created: time.Unix(0, int64(parser.ParseNum(tokens[parser.AckTimestampSeqTokenPos]))),
1316 delta: delta,
1317 op: op,
1318 }
1319 w.updates <- entry
1320 }
1321 // Check if done and initial values.
1322 if !w.initDone {
1323 w.received++
1324 // Use the stable initPending value set at consumer creation.
1325 // We're done if we've received all expected messages OR there are no more pending.
1326 if w.received >= w.initPending || delta == 0 {
1327 w.initDone = true
1328 w.updates <- nil
1329 }
1330 }
1331 }
1332
1333 // Used ordered consumer to deliver results.
1334 subOpts := []nats.SubOpt{nats.BindStream(kv.streamName), nats.OrderedConsumer()}
1335 if !o.includeHistory {
1336 subOpts = append(subOpts, nats.DeliverLastPerSubject())
1337 }
1338 if o.updatesOnly {
1339 subOpts = append(subOpts, nats.DeliverNew())
1340 }
1341 if o.metaOnly {
1342 subOpts = append(subOpts, nats.HeadersOnly())
1343 }
1344 if o.resumeFromRevision > 0 {
1345 subOpts = append(subOpts, nats.StartSequence(o.resumeFromRevision))
1346 }
1347 subOpts = append(subOpts, nats.Context(ctx))
1348 // Create the sub and rest of initialization under the lock.
1349 // We want to prevent the race between this code and the
1350 // update() callback.
1351 w.mu.Lock()
1352 defer w.mu.Unlock()
1353 var sub *nats.Subscription
1354 var err error
1355 if len(keys) == 1 {
1356 sub, err = kv.pushJS.Subscribe(keys[0], update, subOpts...)
1357 } else {
1358 subOpts = append(subOpts, nats.ConsumerFilterSubjects(keys...))
1359 sub, err = kv.pushJS.Subscribe("", update, subOpts...)
1360 }
1361 if err != nil {
1362 return nil, err
1363 }
1364 sub.SetClosedHandler(func(_ string) {
1365 w.mu.Lock()
1366 defer w.mu.Unlock()
1367 close(w.updates)
1368 })
1369 // If there were no pending messages at the time of the creation
1370 // of the consumer, send the marker.
1371 // Skip if UpdatesOnly() is set, since there will never be updates initially.
1372 if !o.updatesOnly {
1373 initialPending, err := sub.InitialConsumerPending()
1374 if err == nil {
1375 if initialPending == 0 {
1376 w.initDone = true
1377 w.updates <- nil
1378 } else {
1379 w.initPending = initialPending
1380 }
1381 }
1382 } else {
1383 // if UpdatesOnly was used, mark initialization as complete
1384 w.initDone = true
1385 }
1386 w.sub = sub
1387 return w, nil
1388 }
1389
1390 // Watch for any updates to keys that match the keys argument which could include wildcards.
1391 // Watch will send a nil entry when it has received all initial values.
1392 func (kv *kvs) Watch(ctx context.Context, keys string, opts ...WatchOpt) (KeyWatcher, error) {
1393 return kv.WatchFiltered(ctx, []string{keys}, opts...)
1394 }
1395
1396 // WatchAll will invoke the callback for all updates.
1397 func (kv *kvs) WatchAll(ctx context.Context, opts ...WatchOpt) (KeyWatcher, error) {
1398 return kv.Watch(ctx, AllKeys, opts...)
1399 }
1400
1401 // Keys will return all keys, filtering out any duplicates.
1402 func (kv *kvs) Keys(ctx context.Context, opts ...WatchOpt) ([]string, error) {
1403 opts = append(opts, IgnoreDeletes(), MetaOnly())
1404 watcher, err := kv.WatchAll(ctx, opts...)
1405 if err != nil {
1406 return nil, err
1407 }
1408 defer watcher.Stop()
1409
1410 var keys []string
1411 for entry := range watcher.Updates() {
1412 if entry == nil {
1413 break
1414 }
1415 keys = append(keys, entry.Key())
1416 }
1417 if len(keys) == 0 {
1418 return nil, ErrNoKeysFound
1419 }
1420 slices.Sort(keys)
1421 return slices.Compact(keys), nil
1422 }
1423
1424 type keyLister struct {
1425 watcher KeyWatcher
1426 keys chan string
1427 }
1428
1429 // ListKeys will return all keys.
1430 // Note: On buckets with a large number of keys and frequent writes,
1431 // duplicate keys may be reported during listing.
1432 func (kv *kvs) ListKeys(ctx context.Context, opts ...WatchOpt) (KeyLister, error) {
1433 opts = append(opts, IgnoreDeletes(), MetaOnly())
1434 watcher, err := kv.WatchAll(ctx, opts...)
1435 if err != nil {
1436 return nil, err
1437 }
1438 kl := &keyLister{watcher: watcher, keys: make(chan string, 256)}
1439
1440 go func() {
1441 defer close(kl.keys)
1442 defer watcher.Stop()
1443 for {
1444 select {
1445 case entry := <-watcher.Updates():
1446 if entry == nil {
1447 return
1448 }
1449 kl.keys <- entry.Key()
1450 case <-ctx.Done():
1451 return
1452 }
1453 }
1454 }()
1455 return kl, nil
1456 }
1457
1458 // ListKeysFiltered returns a KeyLister for filtered keys in the bucket.
1459 // Note: On buckets with a large number of keys and frequent writes,
1460 // duplicate keys may be reported during listing.
1461 func (kv *kvs) ListKeysFiltered(ctx context.Context, filters ...string) (KeyLister, error) {
1462 watcher, err := kv.WatchFiltered(ctx, filters, IgnoreDeletes(), MetaOnly())
1463 if err != nil {
1464 return nil, err
1465 }
1466
1467 // Reuse the existing keyLister implementation
1468 kl := &keyLister{watcher: watcher, keys: make(chan string, 256)}
1469
1470 go func() {
1471 defer close(kl.keys)
1472 defer watcher.Stop()
1473
1474 for {
1475 select {
1476 case entry := <-watcher.Updates():
1477 if entry == nil { // Indicates all initial values are received
1478 return
1479 }
1480 kl.keys <- entry.Key()
1481 case <-ctx.Done():
1482 return
1483 }
1484 }
1485 }()
1486
1487 return kl, nil
1488 }
1489
1490 func (kl *keyLister) Keys() <-chan string {
1491 return kl.keys
1492 }
1493
1494 func (kl *keyLister) Stop() error {
1495 return kl.watcher.Stop()
1496 }
1497
1498 // History will return all historical values for the key.
1499 func (kv *kvs) History(ctx context.Context, key string, opts ...WatchOpt) ([]KeyValueEntry, error) {
1500 opts = append(opts, IncludeHistory())
1501 watcher, err := kv.Watch(ctx, key, opts...)
1502 if err != nil {
1503 return nil, err
1504 }
1505 defer watcher.Stop()
1506
1507 var entries []KeyValueEntry
1508 for entry := range watcher.Updates() {
1509 if entry == nil {
1510 break
1511 }
1512 entries = append(entries, entry)
1513 }
1514 if len(entries) == 0 {
1515 return nil, ErrKeyNotFound
1516 }
1517 return entries, nil
1518 }
1519
1520 // Bucket returns the current bucket name.
1521 func (kv *kvs) Bucket() string {
1522 return kv.name
1523 }
1524
1525 const kvDefaultPurgeDeletesMarkerThreshold = 30 * time.Minute
1526
1527 // PurgeDeletes will remove all current delete markers.
1528 func (kv *kvs) PurgeDeletes(ctx context.Context, opts ...KVPurgeOpt) error {
1529 var o purgeOpts
1530 for _, opt := range opts {
1531 if opt != nil {
1532 if err := opt.configurePurge(&o); err != nil {
1533 return err
1534 }
1535 }
1536 }
1537 watcher, err := kv.WatchAll(ctx)
1538 if err != nil {
1539 return err
1540 }
1541 defer watcher.Stop()
1542
1543 var limit time.Time
1544 olderThan := o.dmthr
1545 // Negative value is used to instruct to always remove markers, regardless
1546 // of age. If set to 0 (or not set), use our default value.
1547 if olderThan == 0 {
1548 olderThan = kvDefaultPurgeDeletesMarkerThreshold
1549 }
1550 if olderThan > 0 {
1551 limit = time.Now().Add(-olderThan)
1552 }
1553
1554 var deleteMarkers []KeyValueEntry
1555 for entry := range watcher.Updates() {
1556 if entry == nil {
1557 break
1558 }
1559 if op := entry.Operation(); op == KeyValueDelete || op == KeyValuePurge {
1560 deleteMarkers = append(deleteMarkers, entry)
1561 }
1562 }
1563 // Stop watcher here so as we purge we do not have the system continually updating numPending.
1564 watcher.Stop()
1565
1566 var b strings.Builder
1567 // Do actual purges here.
1568 for _, entry := range deleteMarkers {
1569 b.WriteString(kv.pre)
1570 b.WriteString(entry.Key())
1571 purgeOpts := []StreamPurgeOpt{WithPurgeSubject(b.String())}
1572 if olderThan > 0 && entry.Created().After(limit) {
1573 purgeOpts = append(purgeOpts, WithPurgeKeep(1))
1574 }
1575 if err := kv.stream.Purge(ctx, purgeOpts...); err != nil {
1576 return err
1577 }
1578 b.Reset()
1579 }
1580 return nil
1581 }
1582
1583 // Status retrieves the status and configuration of a bucket
1584 func (kv *kvs) Status(ctx context.Context) (KeyValueStatus, error) {
1585 nfo, err := kv.stream.Info(ctx)
1586 if err != nil {
1587 return nil, err
1588 }
1589
1590 return &KeyValueBucketStatus{info: nfo, bucket: kv.name}, nil
1591 }
1592
1593 func mapStreamToKVS(js *jetStream, pushJS nats.JetStreamContext, stream Stream) *kvs {
1594 info := stream.CachedInfo()
1595 bucket := strings.TrimPrefix(info.Config.Name, kvBucketNamePre)
1596 kv := &kvs{
1597 name: bucket,
1598 streamName: info.Config.Name,
1599 pre: fmt.Sprintf(kvSubjectsPreTmpl, bucket),
1600 js: js,
1601 pushJS: pushJS,
1602 stream: stream,
1603 // Determine if we need to use the JS prefix in front of Put and Delete operations
1604 useJSPfx: js.opts.apiPrefix != DefaultAPIPrefix,
1605 useDirect: info.Config.AllowDirect,
1606 }
1607
1608 // If we are mirroring, we will have mirror direct on, so just use the mirror name
1609 // and override use
1610 if m := info.Config.Mirror; m != nil {
1611 bucket := strings.TrimPrefix(m.Name, kvBucketNamePre)
1612 if m.External != nil && m.External.APIPrefix != "" {
1613 kv.useJSPfx = false
1614 kv.pre = fmt.Sprintf(kvSubjectsPreTmpl, bucket)
1615 kv.putPre = fmt.Sprintf(kvSubjectsPreDomainTmpl, m.External.APIPrefix, bucket)
1616 } else {
1617 kv.putPre = fmt.Sprintf(kvSubjectsPreTmpl, bucket)
1618 }
1619 }
1620
1621 return kv
1622 }