Debian Codegraph @

jetstream/README.md

raw
1
2 # JetStream Simplified Client [![JetStream API Reference](https://pkg.go.dev/badge/github.com/nats-io/nats.go/jetstream.svg)](https://pkg.go.dev/github.com/nats-io/nats.go/jetstream)
3
4 This doc covers the basic usage of the `jetstream` package in `nats.go` client.
5
6 - [Overview](#overview)
7 - [Basic usage](#basic-usage)
8 - [Streams](#streams)
9 - [Stream management (CRUD)](#stream-management-crud)
10 - [Listing streams and stream names](#listing-streams-and-stream-names)
11 - [Stream-specific operations](#stream-specific-operations)
12 - [Consumers](#consumers)
13 - [Consumers management](#consumers-management)
14 - [Listing consumers and consumer names](#listing-consumers-and-consumer-names)
15 - [Ordered consumers](#ordered-consumers)
16 - [Receiving messages from pull consumers](#receiving-messages-from-pull-consumers)
17 - [Single fetch](#single-fetch)
18 - [Continuous polling](#continuous-polling)
19 - [Using `Consume()` receive messages in a callback](#using-consume-receive-messages-in-a-callback)
20 - [Using `Messages()` to iterate over incoming messages](#using-messages-to-iterate-over-incoming-messages)
21 - [Receiving messages from push consumers](#receiving-messages-from-push-consumers)
22 - [Publishing on stream](#publishing-on-stream)
23 - [Synchronous publish](#synchronous-publish)
24 - [Async publish](#async-publish)
25 - [KeyValue Store](#keyvalue-store)
26 - [Basic usage of KV bucket](#basic-usage-of-kv-bucket)
27 - [Watching for changes on a bucket](#watching-for-changes-on-a-bucket)
28 - [Additional operations on a bucket](#additional-operations-on-a-bucket)
29 - [Object Store](#object-store)
30 - [Basic usage of Object Store](#basic-usage-of-object-store)
31 - [Watching for changes on a store](#watching-for-changes-on-a-store)
32 - [Additional operations on a store](#additional-operations-on-a-store)
33 - [Examples](#examples)
34
35 ## Overview
36
37 `jetstream` package is a new client API to interact with NATS JetStream, aiming
38 to replace the JetStream client implementation from `nats` package. The main
39 goal of this package is to provide a simple and clear way to interact with
40 JetStream API. Key differences between `jetstream` and `nats` packages include:
41
42 - Using smaller, simpler interfaces to manage streams and consumers
43 - Using more granular and predictable approach to consuming messages from a
44 stream, instead of relying on often complicated and unpredictable
45 `Subscribe()` method (and all of its flavors)
46 - Allowing the usage of pull consumers to continuously receive incoming messages
47 (including ordered consumer functionality)
48 - Separating JetStream context from core NATS
49
50 `jetstream` package provides several ways of interacting with the API:
51
52 - `JetStream` - top-level interface, used to create and manage streams,
53 consumers and publishing messages
54 - `Stream` - used to manage consumers for a specific stream, as well as
55 performing stream-specific operations (purging, fetching and deleting messages
56 by sequence number, fetching stream info)
57 - `Consumer` - used to get information about a consumer as well as consuming
58 messages
59 - `Msg` - used for message-specific operations - reading data, headers and
60 metadata, as well as performing various types of acknowledgements
61
62 Additionally, `jetstream` exposes [KeyValue Store](#keyvalue-store) and
63 [ObjectStore](#object-store) capabilities. KV and Object stores are abstraction
64 layers on top of JetStream Streams, simplifying key value and large data
65 storage on Streams.
66
67 > __NOTE__: `jetstream` requires nats-server >= 2.9.0 to work correctly.
68
69 ## Basic usage
70
71 ```go
72 package main
73
74 import (
75 "context"
76 "fmt"
77 "strconv"
78 "time"
79
80 "github.com/nats-io/nats.go"
81 "github.com/nats-io/nats.go/jetstream"
82 )
83
84 func main() {
85 // In the `jetstream` package, almost all API calls rely on `context.Context` for timeout/cancellation handling
86 ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
87 defer cancel()
88 nc, _ := nats.Connect(nats.DefaultURL)
89
90 // Create a JetStream management interface
91 js, _ := jetstream.New(nc)
92
93 // Create a stream
94 s, _ := js.CreateStream(ctx, jetstream.StreamConfig{
95 Name: "ORDERS",
96 Subjects: []string{"ORDERS.*"},
97 })
98
99 // Publish some messages
100 for i := 0; i < 100; i++ {
101 js.Publish(ctx, "ORDERS.new", []byte("hello message "+strconv.Itoa(i)))
102 fmt.Printf("Published hello message %d\n", i)
103 }
104
105 // Create durable consumer
106 c, _ := s.CreateOrUpdateConsumer(ctx, jetstream.ConsumerConfig{
107 Durable: "CONS",
108 AckPolicy: jetstream.AckExplicitPolicy,
109 })
110
111 // Get 10 messages from the consumer
112 messageCounter := 0
113 msgs, err := c.Fetch(10)
114 if err != nil {
115 // handle error
116 }
117
118 for msg := range msgs.Messages() {
119 msg.Ack()
120 fmt.Printf("Received a JetStream message via fetch: %s\n", string(msg.Data()))
121 messageCounter++
122 }
123
124 fmt.Printf("Received %d messages\n", messageCounter)
125
126 if msgs.Error() != nil {
127 fmt.Println("Error during Fetch(): ", msgs.Error())
128 }
129
130 // Receive messages continuously in a callback
131 cons, _ := c.Consume(func(msg jetstream.Msg) {
132 msg.Ack()
133 fmt.Printf("Received a JetStream message via callback: %s\n", string(msg.Data()))
134 messageCounter++
135 })
136 defer cons.Stop()
137
138 // Iterate over messages continuously
139 it, _ := c.Messages()
140 for i := 0; i < 10; i++ {
141 msg, _ := it.Next()
142 msg.Ack()
143 fmt.Printf("Received a JetStream message via iterator: %s\n", string(msg.Data()))
144 messageCounter++
145 }
146 it.Stop()
147
148 // block until all 100 published messages have been processed
149 for messageCounter < 100 {
150 time.Sleep(10 * time.Millisecond)
151 }
152 }
153 ```
154
155 ## Streams
156
157 `jetstream` provides methods to manage and list streams, as well as perform
158 stream-specific operations (purging, fetching/deleting messages by sequence id)
159
160 ### Stream management (CRUD)
161
162 ```go
163 js, _ := jetstream.New(nc)
164
165 // create a stream (this is an idempotent operation)
166 s, _ := js.CreateStream(ctx, jetstream.StreamConfig{
167 Name: "ORDERS",
168 Subjects: []string{"ORDERS.*"},
169 })
170
171 // update a stream
172 s, _ = js.UpdateStream(ctx, jetstream.StreamConfig{
173 Name: "ORDERS",
174 Subjects: []string{"ORDERS.*"},
175 Description: "updated stream",
176 })
177
178 // get stream handle
179 s, _ = js.Stream(ctx, "ORDERS")
180
181 // delete a stream
182 js.DeleteStream(ctx, "ORDERS")
183 ```
184
185 ### Listing streams and stream names
186
187 ```go
188 // list streams
189 streams := js.ListStreams(ctx)
190 for s := range streams.Info() {
191 fmt.Println(s.Config.Name)
192 }
193 if streams.Err() != nil {
194 fmt.Println("Unexpected error occurred")
195 }
196
197 // list stream names
198 names := js.StreamNames(ctx)
199 for name := range names.Name() {
200 fmt.Println(name)
201 }
202 if names.Err() != nil {
203 fmt.Println("Unexpected error occurred")
204 }
205 ```
206
207 ### Stream-specific operations
208
209 Using `Stream` interface, it is also possible to:
210
211 - Purge a stream
212
213 ```go
214 // remove all messages from a stream
215 _ = s.Purge(ctx)
216
217 // remove all messages from a stream that are stored on a specific subject
218 _ = s.Purge(ctx, jetstream.WithPurgeSubject("ORDERS.new"))
219
220 // remove all messages up to specified sequence number
221 _ = s.Purge(ctx, jetstream.WithPurgeSequence(100))
222
223 // remove messages, but keep 10 newest
224 _ = s.Purge(ctx, jetstream.WithPurgeKeep(10))
225 ```
226
227 - Get and delete messages from a stream
228
229 ```go
230 // get message from stream with sequence number == 100
231 msg, _ := s.GetMsg(ctx, 100)
232
233 // get last message from "ORDERS.new" subject
234 msg, _ = s.GetLastMsgForSubject(ctx, "ORDERS.new")
235
236 // delete a message with sequence number == 100
237 _ = s.DeleteMsg(ctx, 100)
238 ```
239
240 - Get information about a stream
241
242 ```go
243 // Fetches the latest stream info from server
244 info, _ := s.Info(ctx)
245 fmt.Println(info.Config.Name)
246
247 // Returns the most recently fetched StreamInfo, without making an API call to the server
248 cachedInfo := s.CachedInfo()
249 fmt.Println(cachedInfo.Config.Name)
250 ```
251
252 ## Consumers
253
254 Both pull and push consumers are supported in `jetstream` package. For most use
255 cases, we recommend using pull consumers as they allow for more fine-grained
256 control over the message processing and can often prevent issues such as slow
257 consumers. However, unlike the JetStream API in `nats` package, pull consumers
258 allow for continuous message retrieval (similarly to how `nats.Subscribe()`
259 works). Because of that, push consumers can be easily replaced by pull
260 consumers for most of the use cases. Push consumers are supported mainly for
261 the purpose of ease of migration from `nats` package. The interfaces for
262 consuming messages via push and pull consumers are similar, with the main
263 difference being that push consumers do not support fetching individual batches
264 of messages.
265
266 ### Consumers management
267
268 Both pull and push consumers can be managed using `jetstream` package. The
269 following example demonstrates how to create, update, fetch and delete a pull
270 consumer. Push consumers can be managed in a similar way, with method names
271 containing `Push` (e.g. `CreatePushConsumer`, `UpdatePushConsumer`,
272 `DeletePushConsumer`).
273
274 > __NOTE__: It is important to use `CreateConsumer` and `CreatePushConsumer`
275 methods to create the respective consumer types as they return the correct
276 interface (different for push and pull consumers). `DeliverSubject` is mandatory
277 when creating a push consumer and cannot be provided when creating a pull
278 consumer. Similarly, an attempt to get a push consumer using `Consumer` method
279 will result in an error (and vice versa).
280
281 CRUD operations on pull consumers can be achieved on 2 levels:
282
283 - on `JetStream` interface
284
285 ```go
286 js, _ := jetstream.New(nc)
287
288 // create a consumer (this is an idempotent operation)
289 // an error will be returned if consumer already exists and has different configuration.
290 cons, _ := js.CreateConsumer(ctx, "ORDERS", jetstream.ConsumerConfig{
291 Durable: "foo",
292 AckPolicy: jetstream.AckExplicitPolicy,
293 })
294
295 // create an ephemeral pull consumer by not providing `Durable`
296 ephemeral, _ := js.CreateConsumer(ctx, "ORDERS", jetstream.ConsumerConfig{
297 AckPolicy: jetstream.AckExplicitPolicy,
298 })
299
300
301 // consumer can also be created using CreateOrUpdateConsumer
302 // this method will either create a consumer if it does not exist
303 // or update existing consumer (if possible)
304 cons2 := js.CreateOrUpdateConsumer(ctx, "ORDERS", jetstream.ConsumerConfig{
305 Name: "bar",
306 })
307
308 // consumers can be updated
309 // an error will be returned if consumer with given name does not exist
310 // or an illegal property is to be updated (e.g. AckPolicy)
311 updated, _ := js.UpdateConsumer(ctx, "ORDERS", jetstream.ConsumerConfig{
312 AckPolicy: jetstream.AckExplicitPolicy,
313 Description: "updated consumer",
314 })
315
316 // get consumer handle
317 cons, _ = js.Consumer(ctx, "ORDERS", "foo")
318
319 // delete a consumer
320 js.DeleteConsumer(ctx, "ORDERS", "foo")
321 ```
322
323 - on `Stream` interface
324
325 ```go
326 // Create a JetStream management interface
327 js, _ := jetstream.New(nc)
328
329 // get stream handle
330 stream, _ := js.Stream(ctx, "ORDERS")
331
332 // create consumer
333 cons, _ := stream.CreateConsumer(ctx, jetstream.ConsumerConfig{
334 Durable: "foo",
335 AckPolicy: jetstream.AckExplicitPolicy,
336 })
337
338 // get consumer handle
339 cons, _ = stream.Consumer(ctx, "foo")
340
341 // delete a consumer
342 stream.DeleteConsumer(ctx, "foo")
343 ```
344
345 `Consumer` interface, returned when creating/fetching consumers, allows fetching
346 `ConsumerInfo`:
347
348 ```go
349 // Fetches latest consumer info from server
350 info, _ := cons.Info(ctx)
351 fmt.Println(info.Config.Durable)
352
353 // Returns the most recently fetched ConsumerInfo, without making an API call to the server
354 cachedInfo := cons.CachedInfo()
355 fmt.Println(cachedInfo.Config.Durable)
356 ```
357
358 ### Listing consumers and consumer names
359
360 ```go
361 // list consumers
362 consumers := s.ListConsumers(ctx)
363 for cons := range consumers.Info() {
364 fmt.Println(cons.Name)
365 }
366 if consumers.Err() != nil {
367 fmt.Println("Unexpected error occurred")
368 }
369
370 // list consumer names
371 names := s.ConsumerNames(ctx)
372 for name := range names.Name() {
373 fmt.Println(name)
374 }
375 if names.Err() != nil {
376 fmt.Println("Unexpected error occurred")
377 }
378 ```
379
380 ### Ordered consumers
381
382 `jetstream`, in addition to basic named/ephemeral consumers, supports ordered
383 consumer functionality. Ordered is strictly processing messages in the order
384 that they were stored on the stream, providing a consistent and deterministic
385 message ordering. It is also resilient to consumer deletion.
386
387 Ordered consumers present the same set of message consumption methods as
388 standard pull consumers.
389
390 > __NOTE__: Ordered consumers are not supported for push consumers.
391
392 ```go
393 js, _ := jetstream.New(nc)
394
395 // create a consumer (this is an idempotent operation)
396 cons, _ := js.OrderedConsumer(ctx, "ORDERS", jetstream.OrderedConsumerConfig{
397 // Filter results from "ORDERS" stream by specific subject
398 FilterSubjects: []string{"ORDERS.A"},
399 })
400 ```
401
402 ### Receiving messages from pull consumers
403
404 The `Consumer` interface allows fetching messages on demand, with a
405 pre-defined batch size or byte limit, or continuous push-like receiving of
406 messages.
407
408 #### __Single fetch__
409
410 This pattern allows fetching a defined number of messages in a single RPC.
411
412 - Using `Fetch` or `FetchBytes`, consumer will return up to the provided number
413 of messages/bytes. By default, `Fetch()` will wait 30 seconds before timing out
414 (this behavior can be configured using `FetchMaxWait()` option):
415
416 ```go
417 // receive up to 10 messages from the stream
418 msgs, err := c.Fetch(10)
419 if err != nil {
420 // handle error
421 }
422
423 for msg := range msgs.Messages() {
424 fmt.Printf("Received a JetStream message: %s\n", string(msg.Data()))
425 }
426
427 if msgs.Error() != nil {
428 // handle error
429 }
430
431 // receive up to 1024 B of data
432 msgs, err := c.FetchBytes(1024)
433 if err != nil {
434 // handle error
435 }
436
437 for msg := range msgs.Messages() {
438 fmt.Printf("Received a JetStream message: %s\n", string(msg.Data()))
439 }
440
441 if msgs.Error() != nil {
442 // handle error
443 }
444 ```
445
446 Similarly, `FetchNoWait()` can be used in order to only return messages from the
447 stream available at the time of sending request:
448
449 ```go
450 // FetchNoWait will not wait for new messages if the whole batch is not available at the time of sending request.
451 msgs, err := c.FetchNoWait(10)
452 if err != nil {
453 // handle error
454 }
455
456 for msg := range msgs.Messages() {
457 fmt.Printf("Received a JetStream message: %s\n", string(msg.Data()))
458 }
459
460 if msgs.Error() != nil {
461 // handle error
462 }
463 ```
464
465 > __Warning__: Both `Fetch()` and `FetchNoWait()` have worse performance when
466 > used to continuously retrieve messages in comparison to `Messages()` or
467 `Consume()` methods, as they do not perform any optimizations (pre-buffering)
468 and new subscription is created for each execution.
469
470 #### Continuous polling
471
472 There are 2 ways to achieve push-like behavior using pull consumers in
473 `jetstream` package. Both `Messages()` and `Consume()` methods perform similar optimizations
474 and for most cases can be used interchangeably.
475
476 There is an advantage of using `Messages()` instead of `Consume()` for work-queue scenarios,
477 where messages should be fetched one by one, as it allows for finer control over fetching
478 single messages on demand.
479
480 Subject filtering is achieved by configuring a consumer with a `FilterSubject`
481 value.
482
483 ##### Using `Consume()` to receive messages in a callback
484
485 ```go
486 cons, _ := js.CreateOrUpdateConsumer(ctx, "ORDERS", jetstream.ConsumerConfig{
487 AckPolicy: jetstream.AckExplicitPolicy,
488 // receive messages from ORDERS.A subject only
489 FilterSubject: "ORDERS.A"
490 })
491
492 consContext, _ := c.Consume(func(msg jetstream.Msg) {
493 fmt.Printf("Received a JetStream message: %s\n", string(msg.Data()))
494 // messages are not acknowledged automatically
495 msg.Ack()
496 })
497 defer consContext.Stop()
498 ```
499
500 Similar to `Messages()`, `Consume()` can be supplied with options to modify
501 the behavior of a single pull request:
502
503 - `PullMaxMessages(int)` - up to provided number of messages will be buffered
504 - `PullMaxBytes(int)` - up to provided number of bytes will be buffered. This
505 setting and `PullMaxMessages` are mutually exclusive.
506 The value should be set to a high enough value to accommodate the largest
507 message expected from the server. Note that it may not be sufficient to set
508 this value to the maximum message size, as this setting controls the client
509 buffer size, not the max bytes requested from the server within a single pull
510 request. If the value is set too low, the consumer will stall and not be able
511 to consume messages.
512 - `PullExpiry(time.Duration)` - timeout on a single pull request to the server
513 - `PullThresholdMessages(int)` - amount of messages which triggers refilling the
514 buffer
515 - `PullThresholdBytes(int)` - amount of bytes which triggers refilling the
516 buffer
517 - `PullHeartbeat(time.Duration)` - idle heartbeat duration for a single pull
518 request. An error will be triggered if at least 2 heartbeats are missed
519 - `ConsumeErrHandler(func (ConsumeContext, error))` - when used, sets a
520 custom error handler on `Consume()`, allowing e.g. tracking missing
521 heartbeats.
522 - `PullMaxMessagesWithBytesLimit(int, int)` - up to the provided number of messages
523 will be buffered and a single fetch size will be limited to the provided value.
524 This is an advanced option and should be used with caution. Most of the time,
525 `PullMaxMessages` or `PullMaxBytes` should be used instead. Note that the byte
526 limit should never be set to a value lower than the maximum message size that
527 can be expected from the server. If the byte limit is lower than the maximum
528 message size, the consumer will stall and not be able to consume messages.
529
530 > __NOTE__: `Stop()` should always be called on `ConsumeContext` to avoid
531 > leaking goroutines.
532
533 ##### Using `Messages()` to iterate over incoming messages
534
535 ```go
536 iter, _ := cons.Messages()
537 for {
538 msg, err := iter.Next()
539 // Next can return error, e.g. when iterator is closed or no heartbeats were received
540 if err != nil {
541 //handle error
542 }
543 fmt.Printf("Received a JetStream message: %s\n", string(msg.Data()))
544 msg.Ack()
545 }
546 iter.Stop()
547 ```
548
549 It can also be configured to only store up to defined number of messages/bytes
550 in the buffer.
551
552 ```go
553 // a maximum of 10 messages or 1024 bytes will be stored in memory (whichever is encountered first)
554 iter, _ := cons.Messages(jetstream.PullMaxMessages(10), jetstream.PullMaxBytes(1024))
555 ```
556
557 `Messages()` exposes the following options:
558
559 - `PullMaxMessages(int)` - up to provided number of messages will be buffered
560 - `PullMaxBytes(int)` - up to provided number of bytes will be buffered. This
561 setting and `PullMaxMessages` are mutually exclusive.
562 The value should be set to a high enough value to accommodate the largest
563 message expected from the server. Note that it may not be sufficient to set
564 this value to the maximum message size, as this setting controls the client
565 buffer size, not the max bytes requested from the server within a single pull
566 request. If the value is set too low, the consumer will stall and not be able
567 to consume messages.
568 - `PullExpiry(time.Duration)` - timeout on a single pull request to the server
569 - `PullThresholdMessages(int)` - amount of messages which triggers refilling the
570 buffer
571 - `PullThresholdBytes(int)` - amount of bytes which triggers refilling the
572 buffer
573 - `PullHeartbeat(time.Duration)` - idle heartbeat duration for a single pull
574 request. An error will be triggered if at least 2 heartbeats are missed (unless
575 `WithMessagesErrOnMissingHeartbeat(false)` is used)
576 - `PullMaxMessagesWithBytesLimit(int, int)` - up to the provided number of messages
577 will be buffered and a single fetch size will be limited to the provided value.
578 This is an advanced option and should be used with caution. Most of the time,
579 `PullMaxMessages` or `PullMaxBytes` should be used instead. Note that the byte
580 limit should never be set to a value lower than the maximum message size that
581 can be expected from the server. If the byte limit is lower than the maximum
582 message size, the consumer will stall and not be able to consume messages.
583
584 ##### Using `Messages()` to fetch single messages one by one
585
586 When implementing work queue, it is possible to use `Messages()` in order to
587 fetch messages from the server one-by-one, without optimizations and
588 pre-buffering (to avoid redeliveries when processing messages at slow rate).
589
590 ```go
591 // PullMaxMessages determines how many messages will be sent to the client in a single pull request
592 iter, _ := cons.Messages(jetstream.PullMaxMessages(1))
593 numWorkers := 5
594 sem := make(chan struct{}, numWorkers)
595 for {
596 sem <- struct{}{}
597 go func() {
598 defer func() {
599 <-sem
600 }()
601 msg, err := iter.Next()
602 if err != nil {
603 // handle err
604 }
605 fmt.Printf("Processing msg: %s\n", string(msg.Data()))
606 doWork()
607 msg.Ack()
608 }()
609 }
610 ```
611
612 #### Receiving messages from push consumers
613
614 The `PushConsumer` interface currently only allows message processing in a
615 callback using `Consume()`.
616
617 As heartbeat for push consumers is not managed when using `Consume()`, it is
618 important to set `IdleHeartbeat` on the consumer level. Similarly, `FlowControl`
619 can be set to prevent the consumer from receiving more messages than it can
620 handle.
621
622 ```go
623 cons, _ := js.CreateOrUpdatePushConsumer(ctx, "ORDERS", jetstream.ConsumerConfig{
624 DeliverSubject: nats.NewInbox()
625 AckPolicy: jetstream.AckExplicitPolicy,
626 // receive messages from ORDERS.A subject only
627 FilterSubject: "ORDERS.A",
628 // unlike pull consumers, idle heartbeat is configured on the consumer level
629 IdleHeartbeat: 30 * time.Second
630 })
631
632 consContext, _ := c.Consume(func(msg jetstream.Msg) {
633 fmt.Printf("Received a JetStream message: %s\n", string(msg.Data()))
634 // messages are not acknowledged automatically
635 msg.Ack()
636 })
637 defer consContext.Stop()
638 ```
639
640 `Consume()` on `PushConsumer` can be supplied with `ConsumeErrHandler` option
641 to set a custom error handler allowing e.g. tracking missing heartbeats.
642
643 > __NOTE__: `Stop()` should always be called on `ConsumeContext` to avoid
644 > leaking goroutines.
645
646 ## Publishing on stream
647
648 `JetStream` interface allows publishing messages on stream in 2 ways:
649
650 ### __Synchronous publish__
651
652 ```go
653 js, _ := jetstream.New(nc)
654
655 // Publish message on subject ORDERS.new
656 // Given subject has to belong to a stream
657 ack, err := js.PublishMsg(ctx, &nats.Msg{
658 Data: []byte("hello"),
659 Subject: "ORDERS.new",
660 })
661 fmt.Printf("Published msg with sequence number %d on stream %q", ack.Sequence, ack.Stream)
662
663 // A helper method accepting subject and data as parameters
664 ack, err = js.Publish(ctx, "ORDERS.new", []byte("hello"))
665 ```
666
667 Both `Publish()` and `PublishMsg()` can be supplied with options allowing
668 setting various headers. Additionally, for `PublishMsg()` headers can be set
669 directly on `nats.Msg`.
670
671 ```go
672 // All 3 implementations work identically
673 ack, err := js.PublishMsg(ctx, &nats.Msg{
674 Data: []byte("hello"),
675 Subject: "ORDERS.new",
676 Header: nats.Header{
677 "Nats-Msg-Id": []string{"id"},
678 },
679 })
680
681 ack, err = js.PublishMsg(ctx, &nats.Msg{
682 Data: []byte("hello"),
683 Subject: "ORDERS.new",
684 }, jetstream.WithMsgID("id"))
685
686 ack, err = js.Publish(ctx, "ORDERS.new", []byte("hello"), jetstream.WithMsgID("id"))
687 ```
688
689 ### __Async publish__
690
691 ```go
692 js, _ := jetstream.New(nc)
693
694 // publish message and do not wait for ack
695 ackF, err := js.PublishMsgAsync(ctx, &nats.Msg{
696 Data: []byte("hello"),
697 Subject: "ORDERS.new",
698 })
699
700 // block and wait for ack
701 select {
702 case ack := <-ackF.Ok():
703 fmt.Printf("Published msg with sequence number %d on stream %q", ack.Sequence, ack.Stream)
704 case err := <-ackF.Err():
705 fmt.Println(err)
706 }
707
708 // similarly to synchronous publish, there is a helper method accepting subject and data
709 ackF, err = js.PublishAsync("ORDERS.new", []byte("hello"))
710 ```
711
712 Just as for synchronous publish, `PublishAsync()` and `PublishMsgAsync()` accept
713 options for setting headers.
714
715 ## KeyValue Store
716
717 JetStream KeyValue Stores offer a straightforward method for storing key-value
718 pairs within JetStream. These stores are supported by a specially configured
719 stream, designed to efficiently and compactly store these pairs. This structure
720 ensures rapid and convenient access to the data.
721
722 The KV Store, also known as a bucket, enables the execution of various operations:
723
724 - create/update a value for a given key
725 - get a value for a given key
726 - delete a value for a given key
727 - purge all values from a bucket
728 - list all keys in a bucket
729 - watch for changes on given key set or the whole bucket
730 - retrieve history of changes for a given key
731
732 ### Basic usage of KV bucket
733
734 The most basic usage of KV bucket is to create or retrieve a bucket and perform
735 basic CRUD operations on keys.
736
737 ```go
738 js, _ := jetstream.New(nc)
739 ctx := context.Background()
740
741 // Create a new bucket. Bucket name is required and has to be unique within a JetStream account.
742 kv, _ := js.CreateKeyValue(ctx, jetstream.KeyValueConfig{Bucket: "profiles"})
743
744 // Set a value for a given key
745 // Put will either create or update a value for a given key
746 kv.Put(ctx, "sue.color", []byte("blue"))
747
748 // Get an entry for a given key
749 // Entry contains key/value, but also metadata (revision, timestamp, etc.))
750 entry, _ := kv.Get(ctx, "sue.color")
751
752 // Prints `sue.color @ 1 -> "blue"`
753 fmt.Printf("%s @ %d -> %q\n", entry.Key(), entry.Revision(), string(entry.Value()))
754
755 // Update a value for a given key
756 // Update will fail if the key does not exist or the revision has changed
757 kv.Update(ctx, "sue.color", []byte("red"), 1)
758
759 // Create will fail if the key already exists
760 _, err := kv.Create(ctx, "sue.color", []byte("purple"))
761 fmt.Println(err) // prints `nats: key exists`
762
763 // Delete a value for a given key.
764 // Delete is not destructive, it will add a delete marker for a given key
765 // and all previous revisions will still be available
766 kv.Delete(ctx, "sue.color")
767
768 // getting a deleted key will return an error
769 _, err = kv.Get(ctx, "sue.color")
770 fmt.Println(err) // prints `nats: key not found`
771
772 // A bucket can be deleted once it is no longer needed
773 js.DeleteKeyValue(ctx, "profiles")
774 ```
775
776 ### Watching for changes on a bucket
777
778 KV buckets support Watchers, which can be used to watch for changes on a given
779 key or the whole bucket. Watcher will receive a notification on a channel when a
780 change occurs. By default, watcher will return initial values for all matching
781 keys. After sending all initial values, watcher will send nil on the channel to
782 signal that all initial values have been sent and it will start sending updates when
783 changes occur.
784
785 Watcher supports several configuration options:
786
787 - `IncludeHistory` will have the key watcher send all historical values
788 for each key (up to KeyValueMaxHistory).
789 - `IgnoreDeletes` will have the key watcher not pass any keys with
790 delete markers.
791 - `UpdatesOnly` will have the key watcher only pass updates on values
792 (without values already present when starting).
793 - `MetaOnly` will have the key watcher retrieve only the entry metadata, not the entry value.
794 - `ResumeFromRevision` instructs the key watcher to resume from a
795 specific revision number.
796
797 ```go
798 js, _ := jetstream.New(nc)
799 ctx := context.Background()
800 kv, _ := js.CreateKeyValue(ctx, jetstream.KeyValueConfig{Bucket: "profiles"})
801
802 kv.Put(ctx, "sue.color", []byte("blue"))
803
804 // A watcher can be created to watch for changes on a given key or the whole bucket
805 // By default, watcher will return most recent values for all matching keys.
806 // Watcher can be configured to only return updates by using jetstream.UpdatesOnly() option.
807 watcher, _ := kv.Watch(ctx, "sue.*")
808 defer watcher.Stop()
809
810 kv.Put(ctx, "sue.age", []byte("43"))
811 kv.Put(ctx, "sue.color", []byte("red"))
812
813 // First, the watcher sends most recent values for all matching keys.
814 // In this case, it will send a single entry for `sue.color`.
815 entry := <-watcher.Updates()
816 // Prints `sue.color @ 1 -> "blue"`
817 fmt.Printf("%s @ %d -> %q\n", entry.Key(), entry.Revision(), string(entry.Value()))
818
819 // After all current values have been sent, watcher will send nil on the channel.
820 entry = <-watcher.Updates()
821 if entry != nil {
822 fmt.Println("Unexpected entry received")
823 }
824
825 // After that, watcher will send updates when changes occur
826 // In this case, it will send an entry for `sue.color` and `sue.age`.
827
828 entry = <-watcher.Updates()
829 // Prints `sue.age @ 2 -> "43"`
830 fmt.Printf("%s @ %d -> %q\n", entry.Key(), entry.Revision(), string(entry.Value()))
831
832 entry = <-watcher.Updates()
833 // Prints `sue.color @ 3 -> "red"`
834 fmt.Printf("%s @ %d -> %q\n", entry.Key(), entry.Revision(), string(entry.Value()))
835 ```
836
837 ### Additional operations on a bucket
838
839 In addition to basic CRUD operations and watching for changes, KV buckets
840 support several additional operations:
841
842 - `ListKeys` will return all keys in a bucket
843
844 ```go
845 js, _ := jetstream.New(nc)
846 ctx := context.Background()
847 kv, _ := js.CreateKeyValue(ctx, jetstream.KeyValueConfig{Bucket: "profiles"})
848
849 kv.Put(ctx, "sue.color", []byte("blue"))
850 kv.Put(ctx, "sue.age", []byte("43"))
851 kv.Put(ctx, "bucket", []byte("profiles"))
852
853 keys, _ := kv.ListKeys(ctx)
854
855 // Prints all 3 keys
856 for key := range keys.Keys() {
857 fmt.Println(key)
858 }
859 ```
860
861 - `Purge` and `PurgeDeletes` for removing all keys from a bucket
862
863 ```go
864 js, _ := jetstream.New(nc)
865 ctx := context.Background()
866 kv, _ := js.CreateKeyValue(ctx, jetstream.KeyValueConfig{Bucket: "profiles"})
867
868 kv.Put(ctx, "sue.color", []byte("blue"))
869 kv.Put(ctx, "sue.age", []byte("43"))
870 kv.Put(ctx, "bucket", []byte("profiles"))
871
872 // Purge will remove all keys from a bucket.
873 // The latest revision of each key will be kept
874 // with a delete marker, all previous revisions will be removed
875 // permanently.
876 kv.Purge(ctx)
877
878 // PurgeDeletes will remove all keys from a bucket
879 // with a delete marker.
880 kv.PurgeDeletes(ctx)
881 ```
882
883 - `Status` will return the current status of a bucket
884
885 ```go
886 js, _ := jetstream.New(nc)
887 ctx := context.Background()
888 kv, _ := js.CreateKeyValue(ctx, jetstream.KeyValueConfig{Bucket: "profiles"})
889
890 kv.Put(ctx, "sue.color", []byte("blue"))
891 kv.Put(ctx, "sue.age", []byte("43"))
892 kv.Put(ctx, "bucket", []byte("profiles"))
893
894 status, _ := kv.Status(ctx)
895
896 fmt.Println(status.Bucket()) // prints `profiles`
897 fmt.Println(status.Values()) // prints `3`
898 fmt.Println(status.Bytes()) // prints the size of all values in bytes
899 ```
900
901 ## Object Store
902
903 JetStream Object Stores offer a straightforward method for storing large objects
904 within JetStream. These stores are backed by a specially configured streams,
905 designed to efficiently and compactly store these objects.
906
907 The Object Store, also known as a bucket, enables the execution of various
908 operations:
909
910 - create/update an object
911 - get an object
912 - delete an object
913 - list all objects in a bucket
914 - watch for changes on objects in a bucket
915 - create links to other objects or other buckets
916
917 ### Basic usage of Object Store
918
919 The most basic usage of Object bucket is to create or retrieve a bucket and
920 perform basic CRUD operations on objects.
921
922 ```go
923 js, _ := jetstream.New(nc)
924 ctx := context.Background()
925
926 // Create a new bucket. Bucket name is required and has to be unique within a JetStream account.
927 os, _ := js.CreateObjectStore(ctx, jetstream.ObjectStoreConfig{Bucket: "configs"})
928
929 config1 := bytes.NewBufferString("first config")
930 // Put an object in a bucket. Put expects an object metadata and a reader
931 // to read the object data from.
932 os.Put(ctx, jetstream.ObjectMeta{Name: "config-1"}, config1)
933
934 // Objects can also be created using various helper methods
935
936 // 1. As raw strings
937 os.PutString(ctx, "config-2", "second config")
938
939 // 2. As raw bytes
940 os.PutBytes(ctx, "config-3", []byte("third config"))
941
942 // 3. As a file
943 os.PutFile(ctx, "config-4.txt")
944
945 // Get an object
946 // Get returns a reader and object info
947 // Similar to Put, Get can also be used with helper methods
948 // to retrieve object data as a string, bytes or to save it to a file
949 object, _ := os.Get(ctx, "config-1")
950 data, _ := io.ReadAll(object)
951 info, _ := object.Info()
952
953 // Prints `configs.config-1 -> "first config"`
954 fmt.Printf("%s.%s -> %q\n", info.Bucket, info.Name, string(data))
955
956 // Delete an object.
957 // Delete will remove object data from stream, but object metadata will be kept
958 // with a delete marker.
959 os.Delete(ctx, "config-1")
960
961 // getting a deleted object will return an error
962 _, err := os.Get(ctx, "config-1")
963 fmt.Println(err) // prints `nats: object not found`
964
965 // A bucket can be deleted once it is no longer needed
966 js.DeleteObjectStore(ctx, "configs")
967 ```
968
969 ### Watching for changes on a store
970
971 Object Stores support Watchers, which can be used to watch for changes on
972 objects in a given bucket. Watcher will receive a notification on a channel when
973 a change occurs. By default, watcher will return the latest information for all
974 objects in a bucket. After sending all initial values, watcher will send nil on
975 the channel to signal that all initial values have been sent and it will start
976 sending updates when changes occur.
977
978 >__NOTE:__ Watchers do not retrieve values for objects, only metadata (containing
979 >information such as object name, bucket name, object size etc.). If object data
980 >is required, the `Get` method should be used.
981
982 Watcher supports several configuration options:
983
984 - `IncludeHistory` will have the watcher send historical updates for each
985 object.
986 - `IgnoreDeletes` will have the watcher not pass any objects with delete
987 markers.
988 - `UpdatesOnly` will have the watcher only pass updates on objects (without
989 objects already present when starting).
990
991 ```go
992 js, _ := jetstream.New(nc)
993 ctx := context.Background()
994 os, _ := js.CreateObjectStore(ctx, jetstream.ObjectStoreConfig{Bucket: "configs"})
995
996 os.PutString(ctx, "config-1", "first config")
997
998 // By default, watcher will return most recent values for all objects in a bucket.
999 // Watcher can be configured to only return updates by using jetstream.UpdatesOnly() option.
1000 watcher, _ := os.Watch(ctx)
1001 defer watcher.Stop()
1002
1003 // create a second object
1004 os.PutString(ctx, "config-2", "second config")
1005
1006 // update metadata of the first object
1007 os.UpdateMeta(ctx, "config-1", jetstream.ObjectMeta{Name: "config-1", Description: "updated config"})
1008
1009 // First, the watcher sends most recent values for all matching objects.
1010 // In this case, it will send a single entry for `config-1`.
1011 object := <-watcher.Updates()
1012 // Prints `configs.config-1 -> ""`
1013 fmt.Printf("%s.%s -> %q\n", object.Bucket, object.Name, object.Description)
1014
1015 // After all current values have been sent, watcher will send nil on the channel.
1016 object = <-watcher.Updates()
1017 if object != nil {
1018 fmt.Println("Unexpected object received")
1019 }
1020
1021 // After that, watcher will send updates when changes occur
1022 // In this case, it will send an entry for `config-2` and `config-1`.
1023 object = <-watcher.Updates()
1024 // Prints `configs.config-2 -> ""`
1025 fmt.Printf("%s.%s -> %q\n", object.Bucket, object.Name, object.Description)
1026
1027 object = <-watcher.Updates()
1028 // Prints `configs.config-1 -> "updated config"`
1029 fmt.Printf("%s.%s -> %q\n", object.Bucket, object.Name, object.Description)
1030 ```
1031
1032 ### Additional operations on a store
1033
1034 In addition to basic CRUD operations and watching for changes, Object Stores
1035 support several additional operations:
1036
1037 - `UpdateMeta` for updating object metadata, such as name, description, etc.
1038
1039 ```go
1040 js, _ := jetstream.New(nc)
1041 ctx := context.Background()
1042 os, _ := js.CreateObjectStore(ctx, jetstream.ObjectStoreConfig{Bucket: "configs"})
1043
1044 os.PutString(ctx, "config", "data")
1045
1046 // update metadata of the object to e.g. add a description
1047 os.UpdateMeta(ctx, "config", jetstream.ObjectMeta{Name: "config", Description: "this is a config"})
1048
1049 // object can be moved under a new name (unless it already exists)
1050 os.UpdateMeta(ctx, "config", jetstream.ObjectMeta{Name: "config-1", Description: "updated config"})
1051 ```
1052
1053 - `List` for listing information about all objects in a bucket:
1054
1055 ```go
1056 js, _ := jetstream.New(nc)
1057 ctx := context.Background()
1058 os, _ := js.CreateObjectStore(ctx, jetstream.ObjectStoreConfig{Bucket: "configs"})
1059
1060 os.PutString(ctx, "config-1", "cfg1")
1061 os.PutString(ctx, "config-2", "cfg1")
1062 os.PutString(ctx, "config-3", "cfg1")
1063
1064 // List will return information about all objects in a bucket
1065 objects, _ := os.List(ctx)
1066
1067 // Prints all 3 objects
1068 for _, object := range objects {
1069 fmt.Println(object.Name)
1070 }
1071 ```
1072
1073 - `Status` will return the current status of a bucket
1074
1075 ```go
1076 js, _ := jetstream.New(nc)
1077 ctx := context.Background()
1078 os, _ := js.CreateObjectStore(ctx, jetstream.ObjectStoreConfig{Bucket: "configs"})
1079
1080 os.PutString(ctx, "config-1", "cfg1")
1081 os.PutString(ctx, "config-2", "cfg1")
1082 os.PutString(ctx, "config-3", "cfg1")
1083
1084 status, _ := os.Status(ctx)
1085
1086 fmt.Println(status.Bucket()) // prints `configs`
1087 fmt.Println(status.Size()) // prints the size of the bucket in bytes
1088 ```
1089
1090 ## Examples
1091
1092 You can find more examples of `jetstream` usage [here](https://github.com/nats-io/nats.go/tree/main/examples/jetstream).