Debian Codegraph @

js.go

raw
1 // Copyright 2020-2026 The NATS Authors
2 // Licensed under the Apache License, Version 2.0 (the "License");
3 // you may not use this file except in compliance with the License.
4 // You may obtain a copy of the License at
5 //
6 // http://www.apache.org/licenses/LICENSE-2.0
7 //
8 // Unless required by applicable law or agreed to in writing, software
9 // distributed under the License is distributed on an "AS IS" BASIS,
10 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11 // See the License for the specific language governing permissions and
12 // limitations under the License.
13
14 package nats
15
16 import (
17 "bytes"
18 "context"
19 "crypto/sha256"
20 "encoding/json"
21 "errors"
22 "fmt"
23 "math/rand"
24 "strconv"
25 "strings"
26 "sync"
27 "sync/atomic"
28 "time"
29
30 "github.com/nats-io/nats.go/internal/parser"
31 "github.com/nats-io/nuid"
32 )
33
34 // JetStream allows persistent messaging through JetStream.
35 //
36 // NOTE: JetStream is part of legacy API.
37 // Users are encouraged to switch to the new JetStream API for enhanced capabilities and
38 // simplified API. Please refer to the `jetstream` package.
39 // See: https://github.com/nats-io/nats.go/blob/main/jetstream/README.md
40 type JetStream interface {
41 // Publish publishes a message to JetStream.
42 Publish(subj string, data []byte, opts ...PubOpt) (*PubAck, error)
43
44 // PublishMsg publishes a Msg to JetStream.
45 PublishMsg(m *Msg, opts ...PubOpt) (*PubAck, error)
46
47 // PublishAsync publishes a message to JetStream and returns a PubAckFuture.
48 // The data should not be changed until the PubAckFuture has been processed.
49 PublishAsync(subj string, data []byte, opts ...PubOpt) (PubAckFuture, error)
50
51 // PublishMsgAsync publishes a Msg to JetStream and returns a PubAckFuture.
52 // The message should not be changed until the PubAckFuture has been processed.
53 PublishMsgAsync(m *Msg, opts ...PubOpt) (PubAckFuture, error)
54
55 // PublishAsyncPending returns the number of async publishes outstanding for this context.
56 PublishAsyncPending() int
57
58 // PublishAsyncComplete returns a channel that will be closed when all outstanding messages are ack'd.
59 PublishAsyncComplete() <-chan struct{}
60
61 // CleanupPublisher will cleanup the publishing side of JetStreamContext.
62 //
63 // This will unsubscribe from the internal reply subject if needed.
64 // All pending async publishes will fail with ErrJetStreamPublisherClosed.
65 //
66 // If an error handler was provided, it will be called for each pending async
67 // publish and PublishAsyncComplete will be closed.
68 //
69 // After completing JetStreamContext is still usable - internal subscription
70 // will be recreated on next publish, but the acks from previous publishes will
71 // be lost.
72 CleanupPublisher()
73
74 // Subscribe creates an async Subscription for JetStream.
75 // The stream and consumer names can be provided with the nats.Bind() option.
76 // For creating an ephemeral (where the consumer name is picked by the server),
77 // you can provide the stream name with nats.BindStream().
78 // If no stream name is specified, the library will attempt to figure out which
79 // stream the subscription is for. See important notes below for more details.
80 //
81 // IMPORTANT NOTES:
82 // * If none of the options Bind() nor Durable() are specified, the library will
83 // send a request to the server to create an ephemeral JetStream consumer,
84 // which will be deleted after an Unsubscribe() or Drain(), or automatically
85 // by the server after a short period of time after the NATS subscription is
86 // gone.
87 // * If Durable() option is specified, the library will attempt to lookup a JetStream
88 // consumer with this name, and if found, will bind to it and not attempt to
89 // delete it. However, if not found, the library will send a request to
90 // create such durable JetStream consumer. Note that the library will delete
91 // the JetStream consumer after an Unsubscribe() or Drain() only if it
92 // created the durable consumer while subscribing. If the durable consumer
93 // already existed prior to subscribing it won't be deleted.
94 // * If Bind() option is provided, the library will attempt to lookup the
95 // consumer with the given name, and if successful, bind to it. If the lookup fails,
96 // then the Subscribe() call will return an error.
97 Subscribe(subj string, cb MsgHandler, opts ...SubOpt) (*Subscription, error)
98
99 // SubscribeSync creates a Subscription that can be used to process messages synchronously.
100 // See important note in Subscribe()
101 SubscribeSync(subj string, opts ...SubOpt) (*Subscription, error)
102
103 // ChanSubscribe creates channel based Subscription.
104 // See important note in Subscribe()
105 ChanSubscribe(subj string, ch chan *Msg, opts ...SubOpt) (*Subscription, error)
106
107 // ChanQueueSubscribe creates channel based Subscription with a queue group.
108 // See important note in QueueSubscribe()
109 ChanQueueSubscribe(subj, queue string, ch chan *Msg, opts ...SubOpt) (*Subscription, error)
110
111 // QueueSubscribe creates a Subscription with a queue group.
112 // If no optional durable name nor binding options are specified, the queue name will be used as a durable name.
113 // See important note in Subscribe()
114 QueueSubscribe(subj, queue string, cb MsgHandler, opts ...SubOpt) (*Subscription, error)
115
116 // QueueSubscribeSync creates a Subscription with a queue group that can be used to process messages synchronously.
117 // See important note in QueueSubscribe()
118 QueueSubscribeSync(subj, queue string, opts ...SubOpt) (*Subscription, error)
119
120 // PullSubscribe creates a Subscription that can fetch messages.
121 // See important note in Subscribe(). Additionally, for an ephemeral pull consumer, the "durable" value must be
122 // set to an empty string.
123 // When using PullSubscribe, the messages are fetched using Fetch() and FetchBatch() methods.
124 PullSubscribe(subj, durable string, opts ...SubOpt) (*Subscription, error)
125 }
126
127 // JetStreamContext allows JetStream messaging and stream management.
128 //
129 // NOTE: JetStreamContext is part of legacy API.
130 // Users are encouraged to switch to the new JetStream API for enhanced capabilities and
131 // simplified API. Please refer to the `jetstream` package.
132 // See: https://github.com/nats-io/nats.go/blob/main/jetstream/README.md
133 type JetStreamContext interface {
134 JetStream
135 JetStreamManager
136 KeyValueManager
137 ObjectStoreManager
138 }
139
140 // Request API subjects for JetStream.
141 const (
142 // defaultAPIPrefix is the default prefix for the JetStream API.
143 defaultAPIPrefix = "$JS.API."
144
145 // jsDomainT is used to create JetStream API prefix by specifying only Domain
146 jsDomainT = "$JS.%s.API."
147
148 // jsExtDomainT is used to create a StreamSource External APIPrefix
149 jsExtDomainT = "$JS.%s.API"
150
151 // apiAccountInfo is for obtaining general information about JetStream.
152 apiAccountInfo = "INFO"
153
154 // apiConsumerCreateT is used to create consumers.
155 // it accepts stream name and consumer name.
156 apiConsumerCreateT = "CONSUMER.CREATE.%s.%s"
157
158 // apiConsumerCreateT is used to create consumers.
159 // it accepts stream name, consumer name and filter subject
160 apiConsumerCreateWithFilterSubjectT = "CONSUMER.CREATE.%s.%s.%s"
161
162 // apiLegacyConsumerCreateT is used to create consumers.
163 // this is a legacy endpoint to support creating ephemerals before nats-server v2.9.0.
164 apiLegacyConsumerCreateT = "CONSUMER.CREATE.%s"
165
166 // apiDurableCreateT is used to create durable consumers.
167 // this is a legacy endpoint to support creating durable consumers before nats-server v2.9.0.
168 apiDurableCreateT = "CONSUMER.DURABLE.CREATE.%s.%s"
169
170 // apiConsumerInfoT is used to create consumers.
171 apiConsumerInfoT = "CONSUMER.INFO.%s.%s"
172
173 // apiRequestNextT is the prefix for the request next message(s) for a consumer in worker/pull mode.
174 apiRequestNextT = "CONSUMER.MSG.NEXT.%s.%s"
175
176 // apiConsumerDeleteT is used to delete consumers.
177 apiConsumerDeleteT = "CONSUMER.DELETE.%s.%s"
178
179 // apiConsumerListT is used to return all detailed consumer information
180 apiConsumerListT = "CONSUMER.LIST.%s"
181
182 // apiConsumerNamesT is used to return a list with all consumer names for the stream.
183 apiConsumerNamesT = "CONSUMER.NAMES.%s"
184
185 // apiStreams can lookup a stream by subject.
186 apiStreams = "STREAM.NAMES"
187
188 // apiStreamCreateT is the endpoint to create new streams.
189 apiStreamCreateT = "STREAM.CREATE.%s"
190
191 // apiStreamInfoT is the endpoint to get information on a stream.
192 apiStreamInfoT = "STREAM.INFO.%s"
193
194 // apiStreamUpdateT is the endpoint to update existing streams.
195 apiStreamUpdateT = "STREAM.UPDATE.%s"
196
197 // apiStreamDeleteT is the endpoint to delete streams.
198 apiStreamDeleteT = "STREAM.DELETE.%s"
199
200 // apiStreamPurgeT is the endpoint to purge streams.
201 apiStreamPurgeT = "STREAM.PURGE.%s"
202
203 // apiStreamListT is the endpoint that will return all detailed stream information
204 apiStreamListT = "STREAM.LIST"
205
206 // apiMsgGetT is the endpoint to get a message.
207 apiMsgGetT = "STREAM.MSG.GET.%s"
208
209 // apiMsgGetT is the endpoint to perform a direct get of a message.
210 apiDirectMsgGetT = "DIRECT.GET.%s"
211
212 // apiDirectMsgGetLastBySubjectT is the endpoint to perform a direct get of a message by subject.
213 apiDirectMsgGetLastBySubjectT = "DIRECT.GET.%s.%s"
214
215 // apiMsgDeleteT is the endpoint to remove a message.
216 apiMsgDeleteT = "STREAM.MSG.DELETE.%s"
217
218 // orderedHeartbeatsInterval is how fast we want HBs from the server during idle.
219 orderedHeartbeatsInterval = 5 * time.Second
220
221 // Scale for threshold of missed HBs or lack of activity.
222 hbcThresh = 2
223
224 // For ChanSubscription, we can't update sub.delivered as we do for other
225 // type of subscriptions, since the channel is user provided.
226 // With flow control in play, we will check for flow control on incoming
227 // messages (as opposed to when they are delivered), but also from a go
228 // routine. Without this, the subscription would possibly stall until
229 // a new message or heartbeat/fc are received.
230 chanSubFCCheckInterval = 250 * time.Millisecond
231
232 // Default time wait between retries on Publish iff err is NoResponders.
233 DefaultPubRetryWait = 250 * time.Millisecond
234
235 // Default number of retries
236 DefaultPubRetryAttempts = 2
237
238 // defaultAsyncPubAckInflight is the number of async pub acks inflight.
239 defaultAsyncPubAckInflight = 4000
240 )
241
242 // Types of control messages, so far heartbeat and flow control
243 const (
244 jsCtrlHB = 1
245 jsCtrlFC = 2
246 )
247
248 // js is an internal struct from a JetStreamContext.
249 type js struct {
250 nc *Conn
251 opts *jsOpts
252
253 // For async publish context.
254 mu sync.RWMutex
255 rpre string
256 rsub *Subscription
257 pafs map[string]*pubAckFuture
258 stc chan struct{}
259 dch chan struct{}
260 rr *rand.Rand
261 connStatusCh chan (Status)
262 replyPrefix string
263 replyPrefixLen int
264 }
265
266 type jsOpts struct {
267 ctx context.Context
268 // For importing JetStream from other accounts.
269 pre string
270 // Amount of time to wait for API requests.
271 wait time.Duration
272 // For async publish error handling.
273 aecb MsgErrHandler
274 // Max async pub ack in flight
275 maxpa int
276 // ackTimeout is the max time to wait for an ack in async publish.
277 ackTimeout time.Duration
278 // the domain that produced the pre
279 domain string
280 // enables protocol tracing
281 ctrace ClientTrace
282 shouldTrace bool
283 // purgeOpts contains optional stream purge options
284 purgeOpts *StreamPurgeRequest
285 // streamInfoOpts contains optional stream info options
286 streamInfoOpts *StreamInfoRequest
287 // streamListSubject is used for subject filtering when listing streams / stream names
288 streamListSubject string
289 // For direct get message requests
290 directGet bool
291 // For direct get next message
292 directNextFor string
293
294 // featureFlags are used to enable/disable specific JetStream features
295 featureFlags featureFlags
296 }
297
298 const (
299 defaultRequestWait = 5 * time.Second
300 )
301
302 // JetStream returns a JetStreamContext for messaging and stream management.
303 // Errors are only returned if inconsistent options are provided.
304 //
305 // NOTE: JetStreamContext is part of legacy API.
306 // Users are encouraged to switch to the new JetStream API for enhanced capabilities and
307 // simplified API. Please refer to the `jetstream` package.
308 // See: https://github.com/nats-io/nats.go/blob/main/jetstream/README.md
309 func (nc *Conn) JetStream(opts ...JSOpt) (JetStreamContext, error) {
310 js := &js{
311 nc: nc,
312 opts: &jsOpts{
313 pre: defaultAPIPrefix,
314 wait: defaultRequestWait,
315 maxpa: defaultAsyncPubAckInflight,
316 },
317 }
318 inboxPrefix := InboxPrefix
319 if js.nc.Opts.InboxPrefix != _EMPTY_ {
320 inboxPrefix = js.nc.Opts.InboxPrefix + "."
321 }
322 js.replyPrefix = inboxPrefix
323 js.replyPrefixLen = len(js.replyPrefix) + aReplyTokensize + 1
324
325 for _, opt := range opts {
326 if err := opt.configureJSContext(js.opts); err != nil {
327 return nil, err
328 }
329 }
330 return js, nil
331 }
332
333 // JSOpt configures a JetStreamContext.
334 type JSOpt interface {
335 configureJSContext(opts *jsOpts) error
336 }
337
338 // jsOptFn configures an option for the JetStreamContext.
339 type jsOptFn func(opts *jsOpts) error
340
341 func (opt jsOptFn) configureJSContext(opts *jsOpts) error {
342 return opt(opts)
343 }
344
345 type featureFlags struct {
346 useDurableConsumerCreate bool
347 }
348
349 // UseLegacyDurableConsumers makes JetStream use the legacy (pre nats-server v2.9.0) subjects for consumer creation.
350 // If this option is used when creating JetStreamContext, $JS.API.CONSUMER.DURABLE.CREATE.<stream>.<consumer> will be used
351 // to create a consumer with Durable provided, rather than $JS.API.CONSUMER.CREATE.<stream>.<consumer>.
352 func UseLegacyDurableConsumers() JSOpt {
353 return jsOptFn(func(opts *jsOpts) error {
354 opts.featureFlags.useDurableConsumerCreate = true
355 return nil
356 })
357 }
358
359 // ClientTrace can be used to trace API interactions for the JetStream Context.
360 type ClientTrace struct {
361 RequestSent func(subj string, payload []byte)
362 ResponseReceived func(subj string, payload []byte, hdr Header)
363 }
364
365 func (ct ClientTrace) configureJSContext(js *jsOpts) error {
366 js.ctrace = ct
367 js.shouldTrace = true
368 return nil
369 }
370
371 // Domain changes the domain part of JetStream API prefix.
372 func Domain(domain string) JSOpt {
373 if domain == _EMPTY_ {
374 return APIPrefix(_EMPTY_)
375 }
376
377 return jsOptFn(func(js *jsOpts) error {
378 js.domain = domain
379 js.pre = fmt.Sprintf(jsDomainT, domain)
380
381 return nil
382 })
383
384 }
385
386 func (s *StreamPurgeRequest) configureJSContext(js *jsOpts) error {
387 js.purgeOpts = s
388 return nil
389 }
390
391 func (s *StreamInfoRequest) configureJSContext(js *jsOpts) error {
392 js.streamInfoOpts = s
393 return nil
394 }
395
396 // APIPrefix changes the default prefix used for the JetStream API.
397 func APIPrefix(pre string) JSOpt {
398 return jsOptFn(func(js *jsOpts) error {
399 if pre == _EMPTY_ {
400 return nil
401 }
402
403 js.pre = pre
404 if !strings.HasSuffix(js.pre, ".") {
405 js.pre = js.pre + "."
406 }
407
408 return nil
409 })
410 }
411
412 // DirectGet is an option that can be used to make GetMsg() or GetLastMsg()
413 // retrieve message directly from a group of servers (leader and replicas)
414 // if the stream was created with the AllowDirect option.
415 func DirectGet() JSOpt {
416 return jsOptFn(func(js *jsOpts) error {
417 js.directGet = true
418 return nil
419 })
420 }
421
422 // DirectGetNext is an option that can be used to make GetMsg() retrieve message
423 // directly from a group of servers (leader and replicas) if the stream was
424 // created with the AllowDirect option.
425 // The server will find the next message matching the filter `subject` starting
426 // at the start sequence (argument in GetMsg()). The filter `subject` can be a
427 // wildcard.
428 func DirectGetNext(subject string) JSOpt {
429 return jsOptFn(func(js *jsOpts) error {
430 js.directGet = true
431 js.directNextFor = subject
432 return nil
433 })
434 }
435
436 // StreamListFilter is an option that can be used to configure `StreamsInfo()` and `StreamNames()` requests.
437 // It allows filtering the returned streams by subject associated with each stream.
438 // Wildcards can be used. For example, `StreamListFilter(FOO.*.A) will return
439 // all streams which have at least one subject matching the provided pattern (e.g. FOO.TEST.A).
440 func StreamListFilter(subject string) JSOpt {
441 return jsOptFn(func(opts *jsOpts) error {
442 opts.streamListSubject = subject
443 return nil
444 })
445 }
446
447 func (js *js) apiSubj(subj string) string {
448 return apiSubjWithPrefix(js.opts.pre, subj)
449 }
450
451 func apiSubjWithPrefix(pre, subj string) string {
452 if pre == _EMPTY_ {
453 return subj
454 }
455 var b strings.Builder
456 b.WriteString(pre)
457 b.WriteString(subj)
458 return b.String()
459 }
460
461 func (o *jsOpts) apiSubj(subj string) string {
462 return apiSubjWithPrefix(o.pre, subj)
463 }
464
465 // PubOpt configures options for publishing JetStream messages.
466 type PubOpt interface {
467 configurePublish(opts *pubOpts) error
468 }
469
470 // pubOptFn is a function option used to configure JetStream Publish.
471 type pubOptFn func(opts *pubOpts) error
472
473 func (opt pubOptFn) configurePublish(opts *pubOpts) error {
474 return opt(opts)
475 }
476
477 type pubOpts struct {
478 ctx context.Context
479 ttl time.Duration
480 id string
481 lid string // Expected last msgId
482 str string // Expected stream name
483 seq *uint64 // Expected last sequence
484 lss *uint64 // Expected last sequence per subject
485 msgTTL time.Duration // Message TTL
486
487 // Publish retries for NoResponders err.
488 rwait time.Duration // Retry wait between attempts
489 rnum int // Retry attempts
490
491 // stallWait is the max wait of a async pub ack.
492 stallWait time.Duration
493
494 // internal option to re-use existing paf in case of retry.
495 pafRetry *pubAckFuture
496 }
497
498 // pubAckResponse is the ack response from the JetStream API when publishing a message.
499 type pubAckResponse struct {
500 apiResponse
501 *PubAck
502 }
503
504 // PubAck is an ack received after successfully publishing a message.
505 type PubAck struct {
506 Stream string `json:"stream"`
507 Sequence uint64 `json:"seq"`
508 Duplicate bool `json:"duplicate,omitempty"`
509 Domain string `json:"domain,omitempty"`
510 }
511
512 // Headers for published messages.
513 const (
514 MsgIdHdr = "Nats-Msg-Id"
515 ExpectedStreamHdr = "Nats-Expected-Stream"
516 ExpectedLastSeqHdr = "Nats-Expected-Last-Sequence"
517 ExpectedLastSubjSeqHdr = "Nats-Expected-Last-Subject-Sequence"
518 ExpectedLastMsgIdHdr = "Nats-Expected-Last-Msg-Id"
519 MsgRollup = "Nats-Rollup"
520 MsgTTLHdr = "Nats-TTL"
521 )
522
523 // Headers for republished messages and direct gets.
524 const (
525 JSStream = "Nats-Stream"
526 JSSequence = "Nats-Sequence"
527 JSTimeStamp = "Nats-Time-Stamp"
528 JSSubject = "Nats-Subject"
529 JSLastSequence = "Nats-Last-Sequence"
530 )
531
532 // MsgSize is a header that will be part of a consumer's delivered message if HeadersOnly requested.
533 const MsgSize = "Nats-Msg-Size"
534
535 // Rollups, can be subject only or all messages.
536 const (
537 MsgRollupSubject = "sub"
538 MsgRollupAll = "all"
539 )
540
541 // PublishMsg publishes a Msg to a stream from JetStream.
542 func (js *js) PublishMsg(m *Msg, opts ...PubOpt) (*PubAck, error) {
543 var o = pubOpts{rwait: DefaultPubRetryWait, rnum: DefaultPubRetryAttempts}
544 if len(opts) > 0 {
545 if m.Header == nil {
546 m.Header = Header{}
547 }
548 for _, opt := range opts {
549 if err := opt.configurePublish(&o); err != nil {
550 return nil, err
551 }
552 }
553 }
554 // Check for option collisions. Right now just timeout and context.
555 if o.ctx != nil && o.ttl != 0 {
556 return nil, ErrContextAndTimeout
557 }
558 if o.ttl == 0 && o.ctx == nil {
559 o.ttl = js.opts.wait
560 }
561 if o.stallWait > 0 {
562 return nil, errors.New("nats: stall wait cannot be set to sync publish")
563 }
564
565 if o.id != _EMPTY_ {
566 m.Header.Set(MsgIdHdr, o.id)
567 }
568 if o.lid != _EMPTY_ {
569 m.Header.Set(ExpectedLastMsgIdHdr, o.lid)
570 }
571 if o.str != _EMPTY_ {
572 m.Header.Set(ExpectedStreamHdr, o.str)
573 }
574 if o.seq != nil {
575 m.Header.Set(ExpectedLastSeqHdr, strconv.FormatUint(*o.seq, 10))
576 }
577 if o.lss != nil {
578 m.Header.Set(ExpectedLastSubjSeqHdr, strconv.FormatUint(*o.lss, 10))
579 }
580 if o.msgTTL > 0 {
581 m.Header.Set(MsgTTLHdr, o.msgTTL.String())
582 }
583
584 var resp *Msg
585 var err error
586
587 if o.ttl > 0 {
588 resp, err = js.nc.RequestMsg(m, time.Duration(o.ttl))
589 } else {
590 resp, err = js.nc.RequestMsgWithContext(o.ctx, m)
591 }
592
593 if err != nil {
594 for r, ttl := 0, o.ttl; errors.Is(err, ErrNoResponders) && (r < o.rnum || o.rnum < 0); r++ {
595 // To protect against small blips in leadership changes etc, if we get a no responders here retry.
596 if o.ctx != nil {
597 select {
598 case <-o.ctx.Done():
599 case <-time.After(o.rwait):
600 }
601 } else {
602 time.Sleep(o.rwait)
603 }
604 if o.ttl > 0 {
605 ttl -= o.rwait
606 if ttl <= 0 {
607 err = ErrTimeout
608 break
609 }
610 resp, err = js.nc.RequestMsg(m, time.Duration(ttl))
611 } else {
612 resp, err = js.nc.RequestMsgWithContext(o.ctx, m)
613 }
614 }
615 if err != nil {
616 if errors.Is(err, ErrNoResponders) {
617 err = ErrNoStreamResponse
618 }
619 return nil, err
620 }
621 }
622
623 var pa pubAckResponse
624 if err := json.Unmarshal(resp.Data, &pa); err != nil {
625 return nil, ErrInvalidJSAck
626 }
627 if pa.Error != nil {
628 return nil, pa.Error
629 }
630 if pa.PubAck == nil || pa.PubAck.Stream == _EMPTY_ {
631 return nil, ErrInvalidJSAck
632 }
633 return pa.PubAck, nil
634 }
635
636 // Publish publishes a message to a stream from JetStream.
637 func (js *js) Publish(subj string, data []byte, opts ...PubOpt) (*PubAck, error) {
638 return js.PublishMsg(&Msg{Subject: subj, Data: data}, opts...)
639 }
640
641 // PubAckFuture is a future for a PubAck.
642 type PubAckFuture interface {
643 // Ok returns a receive only channel that can be used to get a PubAck.
644 Ok() <-chan *PubAck
645
646 // Err returns a receive only channel that can be used to get the error from an async publish.
647 Err() <-chan error
648
649 // Msg returns the message that was sent to the server.
650 Msg() *Msg
651 }
652
653 type pubAckFuture struct {
654 js *js
655 msg *Msg
656 pa *PubAck
657 st time.Time
658 err error
659 errCh chan error
660 doneCh chan *PubAck
661 retries int
662 maxRetries int
663 retryWait time.Duration
664 reply string
665 timeout *time.Timer
666 }
667
668 func (paf *pubAckFuture) Ok() <-chan *PubAck {
669 paf.js.mu.Lock()
670 defer paf.js.mu.Unlock()
671
672 if paf.doneCh == nil {
673 paf.doneCh = make(chan *PubAck, 1)
674 if paf.pa != nil {
675 paf.doneCh <- paf.pa
676 }
677 }
678
679 return paf.doneCh
680 }
681
682 func (paf *pubAckFuture) Err() <-chan error {
683 paf.js.mu.Lock()
684 defer paf.js.mu.Unlock()
685
686 if paf.errCh == nil {
687 paf.errCh = make(chan error, 1)
688 if paf.err != nil {
689 paf.errCh <- paf.err
690 }
691 }
692
693 return paf.errCh
694 }
695
696 func (paf *pubAckFuture) Msg() *Msg {
697 paf.js.mu.RLock()
698 defer paf.js.mu.RUnlock()
699 return paf.msg
700 }
701
702 // For quick token lookup etc.
703 const aReplyTokensize = 6
704
705 func (js *js) newAsyncReply() string {
706 js.mu.Lock()
707 if js.rsub == nil {
708 // Create our wildcard reply subject.
709 sha := sha256.New()
710 sha.Write([]byte(nuid.Next()))
711 b := sha.Sum(nil)
712 for i := 0; i < aReplyTokensize; i++ {
713 b[i] = rdigits[int(b[i]%base)]
714 }
715 js.rpre = fmt.Sprintf("%s%s.", js.replyPrefix, b[:aReplyTokensize])
716 sub, err := js.nc.Subscribe(fmt.Sprintf("%s*", js.rpre), js.handleAsyncReply)
717 if err != nil {
718 js.mu.Unlock()
719 return _EMPTY_
720 }
721 js.rsub = sub
722 js.rr = rand.New(rand.NewSource(time.Now().UnixNano()))
723 }
724 if js.connStatusCh == nil {
725 js.connStatusCh = js.nc.StatusChanged(RECONNECTING, CLOSED)
726 go js.resetPendingAcksOnReconnect()
727 }
728 var sb strings.Builder
729 sb.Grow(len(js.rpre) + aReplyTokensize)
730 sb.WriteString(js.rpre)
731 for {
732 rn := js.rr.Int63()
733 var b [aReplyTokensize]byte
734 for i, l := 0, rn; i < len(b); i++ {
735 b[i] = rdigits[l%base]
736 l /= base
737 }
738 if _, ok := js.pafs[string(b[:])]; ok {
739 continue
740 }
741 sb.Write(b[:])
742 break
743 }
744 js.mu.Unlock()
745 return sb.String()
746 }
747
748 func (js *js) resetPendingAcksOnReconnect() {
749 js.mu.Lock()
750 connStatusCh := js.connStatusCh
751 js.mu.Unlock()
752 for {
753 newStatus, ok := <-connStatusCh
754 if !ok || newStatus == CLOSED {
755 return
756 }
757 js.mu.Lock()
758 errCb := js.opts.aecb
759 for id, paf := range js.pafs {
760 paf.err = ErrDisconnected
761 if paf.errCh != nil {
762 paf.errCh <- paf.err
763 }
764 if errCb != nil {
765 defer errCb(js, paf.msg, ErrDisconnected)
766 }
767 delete(js.pafs, id)
768 }
769 if js.dch != nil {
770 close(js.dch)
771 js.dch = nil
772 }
773 js.mu.Unlock()
774 }
775 }
776
777 // CleanupPublisher will cleanup the publishing side of JetStreamContext.
778 //
779 // This will unsubscribe from the internal reply subject if needed.
780 // All pending async publishes will fail with ErrJetStreamContextClosed.
781 //
782 // If an error handler was provided, it will be called for each pending async
783 // publish and PublishAsyncComplete will be closed.
784 //
785 // After completing JetStreamContext is still usable - internal subscription
786 // will be recreated on next publish, but the acks from previous publishes will
787 // be lost.
788 func (js *js) CleanupPublisher() {
789 js.cleanupReplySub()
790 js.mu.Lock()
791 errCb := js.opts.aecb
792 for id, paf := range js.pafs {
793 paf.err = ErrJetStreamPublisherClosed
794 if paf.errCh != nil {
795 paf.errCh <- paf.err
796 }
797 if errCb != nil {
798 defer errCb(js, paf.msg, ErrJetStreamPublisherClosed)
799 }
800 delete(js.pafs, id)
801 }
802 if js.dch != nil {
803 close(js.dch)
804 js.dch = nil
805 }
806 js.mu.Unlock()
807 }
808
809 func (js *js) cleanupReplySub() {
810 js.mu.Lock()
811 if js.rsub != nil {
812 js.rsub.Unsubscribe()
813 js.rsub = nil
814 }
815 if js.connStatusCh != nil {
816 close(js.connStatusCh)
817 js.connStatusCh = nil
818 }
819 js.mu.Unlock()
820 }
821
822 // registerPAF will register for a PubAckFuture.
823 func (js *js) registerPAF(id string, paf *pubAckFuture) (int, int) {
824 js.mu.Lock()
825 if js.pafs == nil {
826 js.pafs = make(map[string]*pubAckFuture)
827 }
828 paf.js = js
829 js.pafs[id] = paf
830 np := len(js.pafs)
831 maxpa := js.opts.maxpa
832 js.mu.Unlock()
833 return np, maxpa
834 }
835
836 // Lock should be held.
837 func (js *js) getPAF(id string) *pubAckFuture {
838 if js.pafs == nil {
839 return nil
840 }
841 return js.pafs[id]
842 }
843
844 // clearPAF will remove a PubAckFuture that was registered.
845 func (js *js) clearPAF(id string) {
846 js.mu.Lock()
847 delete(js.pafs, id)
848 js.mu.Unlock()
849 }
850
851 // PublishAsyncPending returns how many PubAckFutures are pending.
852 func (js *js) PublishAsyncPending() int {
853 js.mu.RLock()
854 defer js.mu.RUnlock()
855 return len(js.pafs)
856 }
857
858 func (js *js) asyncStall() <-chan struct{} {
859 js.mu.Lock()
860 if js.stc == nil {
861 js.stc = make(chan struct{})
862 }
863 stc := js.stc
864 js.mu.Unlock()
865 return stc
866 }
867
868 // Handle an async reply from PublishAsync.
869 func (js *js) handleAsyncReply(m *Msg) {
870 if len(m.Subject) <= js.replyPrefixLen {
871 return
872 }
873 id := m.Subject[js.replyPrefixLen:]
874
875 js.mu.Lock()
876 paf := js.getPAF(id)
877 if paf == nil {
878 js.mu.Unlock()
879 return
880 }
881
882 closeStc := func() {
883 // Check on anyone stalled and waiting.
884 if js.stc != nil && len(js.pafs) < js.opts.maxpa {
885 close(js.stc)
886 js.stc = nil
887 }
888 }
889
890 closeDchFn := func() func() {
891 var dch chan struct{}
892 // Check on anyone one waiting on done status.
893 if js.dch != nil && len(js.pafs) == 0 {
894 dch = js.dch
895 js.dch = nil
896 }
897 // Return function to close done channel which
898 // should be deferred so that error is processed and
899 // can be checked.
900 return func() {
901 if dch != nil {
902 close(dch)
903 }
904 }
905 }
906
907 doErr := func(err error) {
908 paf.err = err
909 if paf.errCh != nil {
910 paf.errCh <- paf.err
911 }
912 cb := js.opts.aecb
913 js.mu.Unlock()
914 if cb != nil {
915 cb(paf.js, paf.msg, err)
916 }
917 }
918
919 if paf.timeout != nil {
920 paf.timeout.Stop()
921 }
922
923 // Process no responders etc.
924 if len(m.Data) == 0 && m.Header.Get(statusHdr) == noResponders {
925 if paf.retries < paf.maxRetries {
926 paf.retries++
927 time.AfterFunc(paf.retryWait, func() {
928 js.mu.Lock()
929 paf := js.getPAF(id)
930 js.mu.Unlock()
931 if paf == nil {
932 return
933 }
934 _, err := js.PublishMsgAsync(paf.msg, pubOptFn(func(po *pubOpts) error {
935 po.pafRetry = paf
936 return nil
937 }))
938 if err != nil {
939 js.mu.Lock()
940 doErr(err)
941 }
942 })
943 js.mu.Unlock()
944 return
945 }
946 delete(js.pafs, id)
947 closeStc()
948 defer closeDchFn()()
949 doErr(ErrNoResponders)
950 return
951 }
952
953 //remove
954 delete(js.pafs, id)
955 closeStc()
956 defer closeDchFn()()
957
958 var pa pubAckResponse
959 if err := json.Unmarshal(m.Data, &pa); err != nil {
960 doErr(ErrInvalidJSAck)
961 return
962 }
963 if pa.Error != nil {
964 doErr(pa.Error)
965 return
966 }
967 if pa.PubAck == nil || pa.PubAck.Stream == _EMPTY_ {
968 doErr(ErrInvalidJSAck)
969 return
970 }
971
972 // So here we have received a proper puback.
973 paf.pa = pa.PubAck
974 if paf.doneCh != nil {
975 paf.doneCh <- paf.pa
976 }
977 js.mu.Unlock()
978 }
979
980 // MsgErrHandler is used to process asynchronous errors from
981 // JetStream PublishAsync. It will return the original
982 // message sent to the server for possible retransmitting and the error encountered.
983 type MsgErrHandler func(JetStream, *Msg, error)
984
985 // PublishAsyncErrHandler sets the error handler for async publishes in JetStream.
986 func PublishAsyncErrHandler(cb MsgErrHandler) JSOpt {
987 return jsOptFn(func(js *jsOpts) error {
988 js.aecb = cb
989 return nil
990 })
991 }
992
993 // PublishAsyncMaxPending sets the maximum outstanding async publishes that can be inflight at one time.
994 func PublishAsyncMaxPending(max int) JSOpt {
995 return jsOptFn(func(js *jsOpts) error {
996 if max < 1 {
997 return errors.New("nats: max ack pending should be >= 1")
998 }
999 js.maxpa = max
1000 return nil
1001 })
1002 }
1003
1004 // PublishAsyncTimeout sets the timeout for async message publish.
1005 // If not provided, timeout is disabled.
1006 func PublishAsyncTimeout(dur time.Duration) JSOpt {
1007 return jsOptFn(func(opts *jsOpts) error {
1008 opts.ackTimeout = dur
1009 return nil
1010 })
1011 }
1012
1013 // PublishAsync publishes a message to JetStream and returns a PubAckFuture
1014 func (js *js) PublishAsync(subj string, data []byte, opts ...PubOpt) (PubAckFuture, error) {
1015 return js.PublishMsgAsync(&Msg{Subject: subj, Data: data}, opts...)
1016 }
1017
1018 const defaultStallWait = 200 * time.Millisecond
1019
1020 func (js *js) PublishMsgAsync(m *Msg, opts ...PubOpt) (PubAckFuture, error) {
1021 var o pubOpts
1022 if len(opts) > 0 {
1023 if m.Header == nil {
1024 m.Header = Header{}
1025 }
1026 for _, opt := range opts {
1027 if err := opt.configurePublish(&o); err != nil {
1028 return nil, err
1029 }
1030 }
1031 }
1032
1033 if o.rnum < 0 {
1034 return nil, fmt.Errorf("%w: retry attempts cannot be negative", ErrInvalidArg)
1035 }
1036
1037 // Timeouts and contexts do not make sense for these.
1038 if o.ttl != 0 || o.ctx != nil {
1039 return nil, ErrContextAndTimeout
1040 }
1041 stallWait := defaultStallWait
1042 if o.stallWait > 0 {
1043 stallWait = o.stallWait
1044 }
1045
1046 // FIXME(dlc) - Make common.
1047 if o.id != _EMPTY_ {
1048 m.Header.Set(MsgIdHdr, o.id)
1049 }
1050 if o.lid != _EMPTY_ {
1051 m.Header.Set(ExpectedLastMsgIdHdr, o.lid)
1052 }
1053 if o.str != _EMPTY_ {
1054 m.Header.Set(ExpectedStreamHdr, o.str)
1055 }
1056 if o.seq != nil {
1057 m.Header.Set(ExpectedLastSeqHdr, strconv.FormatUint(*o.seq, 10))
1058 }
1059 if o.lss != nil {
1060 m.Header.Set(ExpectedLastSubjSeqHdr, strconv.FormatUint(*o.lss, 10))
1061 }
1062 if o.msgTTL > 0 {
1063 m.Header.Set(MsgTTLHdr, o.msgTTL.String())
1064 }
1065
1066 // Reply
1067 paf := o.pafRetry
1068 if paf == nil && m.Reply != _EMPTY_ {
1069 return nil, errors.New("nats: reply subject should be empty")
1070 }
1071 var id string
1072 var reply string
1073
1074 // register new paf if not retrying
1075 if paf == nil {
1076 reply = js.newAsyncReply()
1077
1078 if reply == _EMPTY_ {
1079 return nil, errors.New("nats: error creating async reply handler")
1080 }
1081
1082 id = reply[js.replyPrefixLen:]
1083 paf = &pubAckFuture{msg: m, st: time.Now(), maxRetries: o.rnum, retryWait: o.rwait, reply: reply}
1084 numPending, maxPending := js.registerPAF(id, paf)
1085
1086 if maxPending > 0 && numPending > maxPending {
1087 select {
1088 case <-js.asyncStall():
1089 case <-time.After(stallWait):
1090 js.clearPAF(id)
1091 return nil, ErrTooManyStalledMsgs
1092 }
1093 }
1094 if js.opts.ackTimeout > 0 {
1095 paf.timeout = time.AfterFunc(js.opts.ackTimeout, func() {
1096 js.mu.Lock()
1097 defer js.mu.Unlock()
1098
1099 if _, ok := js.pafs[id]; !ok {
1100 // paf has already been resolved
1101 // while waiting for the lock
1102 return
1103 }
1104
1105 // ack timed out, remove from pending acks
1106 delete(js.pafs, id)
1107
1108 // check on anyone stalled and waiting.
1109 if js.stc != nil && len(js.pafs) < js.opts.maxpa {
1110 close(js.stc)
1111 js.stc = nil
1112 }
1113
1114 // send error to user
1115 paf.err = ErrAsyncPublishTimeout
1116 if paf.errCh != nil {
1117 paf.errCh <- paf.err
1118 }
1119
1120 // call error callback if set
1121 if js.opts.aecb != nil {
1122 js.opts.aecb(js, paf.msg, ErrAsyncPublishTimeout)
1123 }
1124
1125 // check on anyone one waiting on done status.
1126 if js.dch != nil && len(js.pafs) == 0 {
1127 close(js.dch)
1128 js.dch = nil
1129 }
1130 })
1131 }
1132 } else {
1133 reply = paf.reply
1134 if paf.timeout != nil {
1135 paf.timeout.Reset(js.opts.ackTimeout)
1136 }
1137 id = reply[js.replyPrefixLen:]
1138 }
1139 hdr, err := m.headerBytes()
1140 if err != nil {
1141 return nil, err
1142 }
1143 if err := js.nc.publish(m.Subject, reply, false, hdr, m.Data); err != nil {
1144 js.clearPAF(id)
1145 return nil, err
1146 }
1147
1148 return paf, nil
1149 }
1150
1151 // PublishAsyncComplete returns a channel that will be closed when all outstanding messages have been ack'd.
1152 func (js *js) PublishAsyncComplete() <-chan struct{} {
1153 js.mu.Lock()
1154 defer js.mu.Unlock()
1155 if js.dch == nil {
1156 js.dch = make(chan struct{})
1157 }
1158 dch := js.dch
1159 if len(js.pafs) == 0 {
1160 close(js.dch)
1161 js.dch = nil
1162 }
1163 return dch
1164 }
1165
1166 // MsgId sets the message ID used for deduplication.
1167 func MsgId(id string) PubOpt {
1168 return pubOptFn(func(opts *pubOpts) error {
1169 opts.id = id
1170 return nil
1171 })
1172 }
1173
1174 // ExpectStream sets the expected stream to respond from the publish.
1175 func ExpectStream(stream string) PubOpt {
1176 return pubOptFn(func(opts *pubOpts) error {
1177 opts.str = stream
1178 return nil
1179 })
1180 }
1181
1182 // ExpectLastSequence sets the expected sequence in the response from the publish.
1183 func ExpectLastSequence(seq uint64) PubOpt {
1184 return pubOptFn(func(opts *pubOpts) error {
1185 opts.seq = &seq
1186 return nil
1187 })
1188 }
1189
1190 // ExpectLastSequencePerSubject sets the expected sequence per subject in the response from the publish.
1191 func ExpectLastSequencePerSubject(seq uint64) PubOpt {
1192 return pubOptFn(func(opts *pubOpts) error {
1193 opts.lss = &seq
1194 return nil
1195 })
1196 }
1197
1198 // ExpectLastMsgId sets the expected last msgId in the response from the publish.
1199 func ExpectLastMsgId(id string) PubOpt {
1200 return pubOptFn(func(opts *pubOpts) error {
1201 opts.lid = id
1202 return nil
1203 })
1204 }
1205
1206 // RetryWait sets the retry wait time when ErrNoResponders is encountered.
1207 func RetryWait(dur time.Duration) PubOpt {
1208 return pubOptFn(func(opts *pubOpts) error {
1209 opts.rwait = dur
1210 return nil
1211 })
1212 }
1213
1214 // RetryAttempts sets the retry number of attempts when ErrNoResponders is encountered.
1215 func RetryAttempts(num int) PubOpt {
1216 return pubOptFn(func(opts *pubOpts) error {
1217 opts.rnum = num
1218 return nil
1219 })
1220 }
1221
1222 // StallWait sets the max wait when the producer becomes stall producing messages.
1223 func StallWait(ttl time.Duration) PubOpt {
1224 return pubOptFn(func(opts *pubOpts) error {
1225 if ttl <= 0 {
1226 return errors.New("nats: stall wait should be more than 0")
1227 }
1228 opts.stallWait = ttl
1229 return nil
1230 })
1231 }
1232
1233 // MsgTTL sets per msg TTL.
1234 // Requires [StreamConfig.AllowMsgTTL] to be enabled.
1235 func MsgTTL(dur time.Duration) PubOpt {
1236 return pubOptFn(func(opts *pubOpts) error {
1237 opts.msgTTL = dur
1238 return nil
1239 })
1240 }
1241
1242 type ackOpts struct {
1243 ttl time.Duration
1244 ctx context.Context
1245 nakDelay time.Duration
1246 }
1247
1248 // AckOpt are the options that can be passed when acknowledge a message.
1249 type AckOpt interface {
1250 configureAck(opts *ackOpts) error
1251 }
1252
1253 // MaxWait sets the maximum amount of time we will wait for a response.
1254 type MaxWait time.Duration
1255
1256 func (ttl MaxWait) configureJSContext(js *jsOpts) error {
1257 js.wait = time.Duration(ttl)
1258 return nil
1259 }
1260
1261 func (ttl MaxWait) configurePull(opts *pullOpts) error {
1262 opts.ttl = time.Duration(ttl)
1263 return nil
1264 }
1265
1266 // AckWait sets the maximum amount of time we will wait for an ack.
1267 type AckWait time.Duration
1268
1269 func (ttl AckWait) configurePublish(opts *pubOpts) error {
1270 opts.ttl = time.Duration(ttl)
1271 return nil
1272 }
1273
1274 func (ttl AckWait) configureSubscribe(opts *subOpts) error {
1275 opts.cfg.AckWait = time.Duration(ttl)
1276 return nil
1277 }
1278
1279 func (ttl AckWait) configureAck(opts *ackOpts) error {
1280 opts.ttl = time.Duration(ttl)
1281 return nil
1282 }
1283
1284 // ContextOpt is an option used to set a context.Context.
1285 type ContextOpt struct {
1286 context.Context
1287 }
1288
1289 func (ctx ContextOpt) configureJSContext(opts *jsOpts) error {
1290 opts.ctx = ctx
1291 return nil
1292 }
1293
1294 func (ctx ContextOpt) configurePublish(opts *pubOpts) error {
1295 opts.ctx = ctx
1296 return nil
1297 }
1298
1299 func (ctx ContextOpt) configureSubscribe(opts *subOpts) error {
1300 opts.ctx = ctx
1301 return nil
1302 }
1303
1304 func (ctx ContextOpt) configurePull(opts *pullOpts) error {
1305 opts.ctx = ctx
1306 return nil
1307 }
1308
1309 func (ctx ContextOpt) configureAck(opts *ackOpts) error {
1310 opts.ctx = ctx
1311 return nil
1312 }
1313
1314 // Context returns an option that can be used to configure a context for APIs
1315 // that are context aware such as those part of the JetStream interface.
1316 func Context(ctx context.Context) ContextOpt {
1317 return ContextOpt{ctx}
1318 }
1319
1320 type nakDelay time.Duration
1321
1322 func (d nakDelay) configureAck(opts *ackOpts) error {
1323 opts.nakDelay = time.Duration(d)
1324 return nil
1325 }
1326
1327 // Subscribe
1328
1329 // ConsumerConfig is the configuration of a JetStream consumer.
1330 type ConsumerConfig struct {
1331 Durable string `json:"durable_name,omitempty"`
1332 Name string `json:"name,omitempty"`
1333 Description string `json:"description,omitempty"`
1334 DeliverPolicy DeliverPolicy `json:"deliver_policy"`
1335 OptStartSeq uint64 `json:"opt_start_seq,omitempty"`
1336 OptStartTime *time.Time `json:"opt_start_time,omitempty"`
1337 AckPolicy AckPolicy `json:"ack_policy"`
1338 AckWait time.Duration `json:"ack_wait,omitempty"`
1339 MaxDeliver int `json:"max_deliver,omitempty"`
1340 BackOff []time.Duration `json:"backoff,omitempty"`
1341 FilterSubject string `json:"filter_subject,omitempty"`
1342 FilterSubjects []string `json:"filter_subjects,omitempty"`
1343 ReplayPolicy ReplayPolicy `json:"replay_policy"`
1344 RateLimit uint64 `json:"rate_limit_bps,omitempty"` // Bits per sec
1345 SampleFrequency string `json:"sample_freq,omitempty"`
1346 MaxWaiting int `json:"max_waiting,omitempty"`
1347 MaxAckPending int `json:"max_ack_pending,omitempty"`
1348 FlowControl bool `json:"flow_control,omitempty"`
1349 Heartbeat time.Duration `json:"idle_heartbeat,omitempty"`
1350 HeadersOnly bool `json:"headers_only,omitempty"`
1351
1352 // Pull based options.
1353 MaxRequestBatch int `json:"max_batch,omitempty"`
1354 MaxRequestExpires time.Duration `json:"max_expires,omitempty"`
1355 MaxRequestMaxBytes int `json:"max_bytes,omitempty"`
1356
1357 // Push based consumers.
1358 DeliverSubject string `json:"deliver_subject,omitempty"`
1359 DeliverGroup string `json:"deliver_group,omitempty"`
1360
1361 // Inactivity threshold.
1362 InactiveThreshold time.Duration `json:"inactive_threshold,omitempty"`
1363
1364 // Generally inherited by parent stream and other markers, now can be configured directly.
1365 Replicas int `json:"num_replicas"`
1366 // Force memory storage.
1367 MemoryStorage bool `json:"mem_storage,omitempty"`
1368
1369 // Metadata is additional metadata for the Consumer.
1370 // Keys starting with `_nats` are reserved.
1371 // NOTE: Metadata requires nats-server v2.10.0+
1372 Metadata map[string]string `json:"metadata,omitempty"`
1373 }
1374
1375 // ConsumerInfo is the info from a JetStream consumer.
1376 type ConsumerInfo struct {
1377 Stream string `json:"stream_name"`
1378 Name string `json:"name"`
1379 Created time.Time `json:"created"`
1380 Config ConsumerConfig `json:"config"`
1381 Delivered SequenceInfo `json:"delivered"`
1382 AckFloor SequenceInfo `json:"ack_floor"`
1383 NumAckPending int `json:"num_ack_pending"`
1384 NumRedelivered int `json:"num_redelivered"`
1385 NumWaiting int `json:"num_waiting"`
1386 NumPending uint64 `json:"num_pending"`
1387 Cluster *ClusterInfo `json:"cluster,omitempty"`
1388 PushBound bool `json:"push_bound,omitempty"`
1389 }
1390
1391 // SequenceInfo has both the consumer and the stream sequence and last activity.
1392 type SequenceInfo struct {
1393 Consumer uint64 `json:"consumer_seq"`
1394 Stream uint64 `json:"stream_seq"`
1395 Last *time.Time `json:"last_active,omitempty"`
1396 }
1397
1398 // SequencePair includes the consumer and stream sequence info from a JetStream consumer.
1399 type SequencePair struct {
1400 Consumer uint64 `json:"consumer_seq"`
1401 Stream uint64 `json:"stream_seq"`
1402 }
1403
1404 // nextRequest is for getting next messages for pull based consumers from JetStream.
1405 type nextRequest struct {
1406 Expires time.Duration `json:"expires,omitempty"`
1407 Batch int `json:"batch,omitempty"`
1408 NoWait bool `json:"no_wait,omitempty"`
1409 MaxBytes int `json:"max_bytes,omitempty"`
1410 Heartbeat time.Duration `json:"idle_heartbeat,omitempty"`
1411 }
1412
1413 // jsSub includes JetStream subscription info.
1414 type jsSub struct {
1415 js *js
1416
1417 // For pull subscribers, this is the next message subject to send requests to.
1418 nms string
1419
1420 psubj string // the subject that was passed by user to the subscribe calls
1421 consumer string
1422 stream string
1423 deliver string
1424 pull bool
1425 dc bool // Delete JS consumer
1426 ackNone bool
1427
1428 // This is ConsumerInfo's Pending+Consumer.Delivered that we get from the
1429 // add consumer response. Note that some versions of the server gather the
1430 // consumer info *after* the creation of the consumer, which means that
1431 // some messages may have been already delivered. So the sum of the two
1432 // is a more accurate representation of the number of messages pending or
1433 // in the process of being delivered to the subscription when created.
1434 pending uint64
1435
1436 // Ordered consumers
1437 ordered bool
1438 dseq uint64
1439 sseq uint64
1440 ccreq *createConsumerRequest
1441 // A reset waits for the buffer to drain, see tryResetOrderedConsumer.
1442 resetPending bool
1443
1444 // Heartbeats and Flow Control handling from push consumers.
1445 hbc *time.Timer
1446 hbi time.Duration
1447 active bool
1448 cmeta string
1449 fcr string
1450 fcd uint64
1451 fciseq uint64
1452 csfct *time.Timer
1453
1454 // context set on js.Subscribe used e.g. to recreate ordered consumer
1455 ctx context.Context
1456
1457 // Cancellation function to cancel context on drain/unsubscribe.
1458 cancel func()
1459 }
1460
1461 // Deletes the JS Consumer.
1462 // No connection nor subscription lock must be held on entry.
1463 func (sub *Subscription) deleteConsumer() error {
1464 sub.mu.Lock()
1465 jsi := sub.jsi
1466 if jsi == nil {
1467 sub.mu.Unlock()
1468 return nil
1469 }
1470 if jsi.stream == _EMPTY_ || jsi.consumer == _EMPTY_ {
1471 sub.mu.Unlock()
1472 return nil
1473 }
1474 stream, consumer := jsi.stream, jsi.consumer
1475 js := jsi.js
1476 sub.mu.Unlock()
1477
1478 return js.DeleteConsumer(stream, consumer)
1479 }
1480
1481 // SubOpt configures options for subscribing to JetStream consumers.
1482 type SubOpt interface {
1483 configureSubscribe(opts *subOpts) error
1484 }
1485
1486 // subOptFn is a function option used to configure a JetStream Subscribe.
1487 type subOptFn func(opts *subOpts) error
1488
1489 func (opt subOptFn) configureSubscribe(opts *subOpts) error {
1490 return opt(opts)
1491 }
1492
1493 // Subscribe creates an async Subscription for JetStream.
1494 // The stream and consumer names can be provided with the nats.Bind() option.
1495 // For creating an ephemeral (where the consumer name is picked by the server),
1496 // you can provide the stream name with nats.BindStream().
1497 // If no stream name is specified, the library will attempt to figure out which
1498 // stream the subscription is for. See important notes below for more details.
1499 //
1500 // IMPORTANT NOTES:
1501 // * If none of the options Bind() nor Durable() are specified, the library will
1502 // send a request to the server to create an ephemeral JetStream consumer,
1503 // which will be deleted after an Unsubscribe() or Drain(), or automatically
1504 // by the server after a short period of time after the NATS subscription is
1505 // gone.
1506 // * If Durable() option is specified, the library will attempt to lookup a JetStream
1507 // consumer with this name, and if found, will bind to it and not attempt to
1508 // delete it. However, if not found, the library will send a request to create
1509 // such durable JetStream consumer. The library will delete the JetStream consumer
1510 // after an Unsubscribe() or Drain().
1511 // * If Bind() option is provided, the library will attempt to lookup the
1512 // consumer with the given name, and if successful, bind to it. If the lookup fails,
1513 // then the Subscribe() call will return an error.
1514 func (js *js) Subscribe(subj string, cb MsgHandler, opts ...SubOpt) (*Subscription, error) {
1515 if cb == nil {
1516 return nil, ErrBadSubscription
1517 }
1518 return js.subscribe(subj, _EMPTY_, cb, nil, false, false, opts)
1519 }
1520
1521 // SubscribeSync creates a Subscription that can be used to process messages synchronously.
1522 // See important note in Subscribe()
1523 func (js *js) SubscribeSync(subj string, opts ...SubOpt) (*Subscription, error) {
1524 mch := make(chan *Msg, js.nc.Opts.SubChanLen)
1525 return js.subscribe(subj, _EMPTY_, nil, mch, true, false, opts)
1526 }
1527
1528 // QueueSubscribe creates a Subscription with a queue group.
1529 // If no optional durable name nor binding options are specified, the queue name will be used as a durable name.
1530 // See important note in Subscribe()
1531 func (js *js) QueueSubscribe(subj, queue string, cb MsgHandler, opts ...SubOpt) (*Subscription, error) {
1532 if cb == nil {
1533 return nil, ErrBadSubscription
1534 }
1535 return js.subscribe(subj, queue, cb, nil, false, false, opts)
1536 }
1537
1538 // QueueSubscribeSync creates a Subscription with a queue group that can be used to process messages synchronously.
1539 // See important note in QueueSubscribe()
1540 func (js *js) QueueSubscribeSync(subj, queue string, opts ...SubOpt) (*Subscription, error) {
1541 mch := make(chan *Msg, js.nc.Opts.SubChanLen)
1542 return js.subscribe(subj, queue, nil, mch, true, false, opts)
1543 }
1544
1545 // ChanSubscribe creates channel based Subscription.
1546 // Using ChanSubscribe without buffered capacity is not recommended since
1547 // it will be prone to dropping messages with a slow consumer error. Make sure to give the channel enough
1548 // capacity to handle bursts in traffic, for example other Subscribe APIs use a default of 512k capacity in comparison.
1549 // See important note in Subscribe()
1550 func (js *js) ChanSubscribe(subj string, ch chan *Msg, opts ...SubOpt) (*Subscription, error) {
1551 return js.subscribe(subj, _EMPTY_, nil, ch, false, false, opts)
1552 }
1553
1554 // ChanQueueSubscribe creates channel based Subscription with a queue group.
1555 // See important note in QueueSubscribe()
1556 func (js *js) ChanQueueSubscribe(subj, queue string, ch chan *Msg, opts ...SubOpt) (*Subscription, error) {
1557 return js.subscribe(subj, queue, nil, ch, false, false, opts)
1558 }
1559
1560 // PullSubscribe creates a Subscription that can fetch messages.
1561 // See important note in Subscribe()
1562 func (js *js) PullSubscribe(subj, durable string, opts ...SubOpt) (*Subscription, error) {
1563 mch := make(chan *Msg, js.nc.Opts.SubChanLen)
1564 if durable != "" {
1565 opts = append(opts, Durable(durable))
1566 }
1567 return js.subscribe(subj, _EMPTY_, nil, mch, true, true, opts)
1568 }
1569
1570 func processConsInfo(info *ConsumerInfo, userCfg *ConsumerConfig, isPullMode bool, subj, queue string) (string, error) {
1571 ccfg := &info.Config
1572
1573 // Make sure this new subject matches or is a subset.
1574 if ccfg.FilterSubject != _EMPTY_ && subj != ccfg.FilterSubject {
1575 return _EMPTY_, ErrSubjectMismatch
1576 }
1577
1578 // Prevent binding a subscription against incompatible consumer types.
1579 if isPullMode && ccfg.DeliverSubject != _EMPTY_ {
1580 return _EMPTY_, ErrPullSubscribeToPushConsumer
1581 } else if !isPullMode && ccfg.DeliverSubject == _EMPTY_ {
1582 return _EMPTY_, ErrPullSubscribeRequired
1583 }
1584
1585 // If pull mode, nothing else to check here.
1586 if isPullMode {
1587 return _EMPTY_, checkConfig(ccfg, userCfg)
1588 }
1589
1590 // At this point, we know the user wants push mode, and the JS consumer is
1591 // really push mode.
1592
1593 dg := info.Config.DeliverGroup
1594 if dg == _EMPTY_ {
1595 // Prevent an user from attempting to create a queue subscription on
1596 // a JS consumer that was not created with a deliver group.
1597 if queue != _EMPTY_ {
1598 return _EMPTY_, errors.New("cannot create a queue subscription for a consumer without a deliver group")
1599 } else if info.PushBound {
1600 // Need to reject a non queue subscription to a non queue consumer
1601 // if the consumer is already bound.
1602 return _EMPTY_, errors.New("consumer is already bound to a subscription")
1603 }
1604 } else {
1605 // If the JS consumer has a deliver group, we need to fail a non queue
1606 // subscription attempt:
1607 if queue == _EMPTY_ {
1608 return _EMPTY_, fmt.Errorf("cannot create a subscription for a consumer with a deliver group %q", dg)
1609 } else if queue != dg {
1610 // Here the user's queue group name does not match the one associated
1611 // with the JS consumer.
1612 return _EMPTY_, fmt.Errorf("cannot create a queue subscription %q for a consumer with a deliver group %q",
1613 queue, dg)
1614 }
1615 }
1616 if err := checkConfig(ccfg, userCfg); err != nil {
1617 return _EMPTY_, err
1618 }
1619 return ccfg.DeliverSubject, nil
1620 }
1621
1622 func checkConfig(s, u *ConsumerConfig) error {
1623 makeErr := func(fieldName string, usrVal, srvVal any) error {
1624 return fmt.Errorf("nats: configuration requests %s to be %v, but consumer's value is %v", fieldName, usrVal, srvVal)
1625 }
1626
1627 if u.Durable != _EMPTY_ && u.Durable != s.Durable {
1628 return makeErr("durable", u.Durable, s.Durable)
1629 }
1630 if u.Description != _EMPTY_ && u.Description != s.Description {
1631 return makeErr("description", u.Description, s.Description)
1632 }
1633 if u.DeliverPolicy != deliverPolicyNotSet && u.DeliverPolicy != s.DeliverPolicy {
1634 return makeErr("deliver policy", u.DeliverPolicy, s.DeliverPolicy)
1635 }
1636 if u.OptStartSeq > 0 && u.OptStartSeq != s.OptStartSeq {
1637 return makeErr("optional start sequence", u.OptStartSeq, s.OptStartSeq)
1638 }
1639 if u.OptStartTime != nil && !u.OptStartTime.IsZero() && !(*u.OptStartTime).Equal(*s.OptStartTime) {
1640 return makeErr("optional start time", u.OptStartTime, s.OptStartTime)
1641 }
1642 if u.AckPolicy != ackPolicyNotSet && u.AckPolicy != s.AckPolicy {
1643 return makeErr("ack policy", u.AckPolicy, s.AckPolicy)
1644 }
1645 if u.AckWait > 0 && u.AckWait != s.AckWait {
1646 return makeErr("ack wait", u.AckWait, s.AckWait)
1647 }
1648 if u.MaxDeliver > 0 && u.MaxDeliver != s.MaxDeliver {
1649 return makeErr("max deliver", u.MaxDeliver, s.MaxDeliver)
1650 }
1651 if u.ReplayPolicy != replayPolicyNotSet && u.ReplayPolicy != s.ReplayPolicy {
1652 return makeErr("replay policy", u.ReplayPolicy, s.ReplayPolicy)
1653 }
1654 if u.RateLimit > 0 && u.RateLimit != s.RateLimit {
1655 return makeErr("rate limit", u.RateLimit, s.RateLimit)
1656 }
1657 if u.SampleFrequency != _EMPTY_ && u.SampleFrequency != s.SampleFrequency {
1658 return makeErr("sample frequency", u.SampleFrequency, s.SampleFrequency)
1659 }
1660 if u.MaxWaiting > 0 && u.MaxWaiting != s.MaxWaiting {
1661 return makeErr("max waiting", u.MaxWaiting, s.MaxWaiting)
1662 }
1663 if u.MaxAckPending > 0 && u.MaxAckPending != s.MaxAckPending {
1664 return makeErr("max ack pending", u.MaxAckPending, s.MaxAckPending)
1665 }
1666 // For flow control, we want to fail if the user explicit wanted it, but
1667 // it is not set in the existing consumer. If it is not asked by the user,
1668 // the library still handles it and so no reason to fail.
1669 if u.FlowControl && !s.FlowControl {
1670 return makeErr("flow control", u.FlowControl, s.FlowControl)
1671 }
1672 if u.Heartbeat > 0 && u.Heartbeat != s.Heartbeat {
1673 return makeErr("heartbeat", u.Heartbeat, s.Heartbeat)
1674 }
1675 if u.Replicas > 0 && u.Replicas != s.Replicas {
1676 return makeErr("replicas", u.Replicas, s.Replicas)
1677 }
1678 if u.MemoryStorage && !s.MemoryStorage {
1679 return makeErr("memory storage", u.MemoryStorage, s.MemoryStorage)
1680 }
1681 return nil
1682 }
1683
1684 func (js *js) subscribe(subj, queue string, cb MsgHandler, ch chan *Msg, isSync, isPullMode bool, opts []SubOpt) (*Subscription, error) {
1685 cfg := ConsumerConfig{
1686 DeliverPolicy: deliverPolicyNotSet,
1687 AckPolicy: ackPolicyNotSet,
1688 ReplayPolicy: replayPolicyNotSet,
1689 }
1690 o := subOpts{cfg: &cfg}
1691 if len(opts) > 0 {
1692 for _, opt := range opts {
1693 if opt == nil {
1694 continue
1695 }
1696 if err := opt.configureSubscribe(&o); err != nil {
1697 return nil, err
1698 }
1699 }
1700 }
1701
1702 // If no stream name is specified, the subject cannot be empty.
1703 if subj == _EMPTY_ && o.stream == _EMPTY_ {
1704 return nil, errors.New("nats: subject required")
1705 }
1706
1707 // Note that these may change based on the consumer info response we may get.
1708 hasHeartbeats := o.cfg.Heartbeat > 0
1709 hasFC := o.cfg.FlowControl
1710
1711 // Some checks for pull subscribers
1712 if isPullMode {
1713 // No deliver subject should be provided
1714 if o.cfg.DeliverSubject != _EMPTY_ {
1715 return nil, ErrPullSubscribeToPushConsumer
1716 }
1717 }
1718
1719 // Some check/setting specific to queue subs
1720 if queue != _EMPTY_ {
1721 // Queue subscriber cannot have HB or FC (since messages will be randomly dispatched
1722 // to members). We may in the future have a separate NATS subscription that all members
1723 // would subscribe to and server would send on.
1724 if o.cfg.Heartbeat > 0 || o.cfg.FlowControl {
1725 // Not making this a public ErrXXX in case we allow in the future.
1726 return nil, errors.New("nats: queue subscription doesn't support idle heartbeat nor flow control")
1727 }
1728
1729 // If this is a queue subscription and no consumer nor durable name was specified,
1730 // then we will use the queue name as a durable name.
1731 if o.consumer == _EMPTY_ && o.cfg.Durable == _EMPTY_ {
1732 if err := checkConsumerName(queue); err != nil {
1733 return nil, err
1734 }
1735 o.cfg.Durable = queue
1736 }
1737 }
1738
1739 var (
1740 err error
1741 shouldCreate bool
1742 info *ConsumerInfo
1743 deliver string
1744 stream = o.stream
1745 consumer = o.consumer
1746 isDurable = o.cfg.Durable != _EMPTY_
1747 consumerBound = o.bound
1748 ctx = o.ctx
1749 skipCInfo = o.skipCInfo
1750 notFoundErr bool
1751 lookupErr bool
1752 nc = js.nc
1753 nms string
1754 hbi time.Duration
1755 ccreq *createConsumerRequest // In case we need to hold onto it for ordered consumers.
1756 maxap int
1757 )
1758
1759 // Do some quick checks here for ordered consumers. We do these here instead of spread out
1760 // in the individual SubOpts.
1761 if o.ordered {
1762 // Make sure we are not durable.
1763 if isDurable {
1764 return nil, errors.New("nats: durable can not be set for an ordered consumer")
1765 }
1766 // Check ack policy.
1767 if o.cfg.AckPolicy != ackPolicyNotSet {
1768 return nil, errors.New("nats: ack policy can not be set for an ordered consumer")
1769 }
1770 // Check max deliver.
1771 if o.cfg.MaxDeliver != 1 && o.cfg.MaxDeliver != 0 {
1772 return nil, errors.New("nats: max deliver can not be set for an ordered consumer")
1773 }
1774 // No deliver subject, we pick our own.
1775 if o.cfg.DeliverSubject != _EMPTY_ {
1776 return nil, errors.New("nats: deliver subject can not be set for an ordered consumer")
1777 }
1778 // Queue groups not allowed.
1779 if queue != _EMPTY_ {
1780 return nil, errors.New("nats: queues not be set for an ordered consumer")
1781 }
1782 // Check for bound consumers.
1783 if consumer != _EMPTY_ {
1784 return nil, errors.New("nats: can not bind existing consumer for an ordered consumer")
1785 }
1786 // Check for pull mode.
1787 if isPullMode {
1788 return nil, errors.New("nats: can not use pull mode for an ordered consumer")
1789 }
1790 // Setup how we need it to be here.
1791 o.cfg.FlowControl = true
1792 o.cfg.AckPolicy = AckNonePolicy
1793 o.cfg.MaxDeliver = 1
1794 o.cfg.AckWait = 22 * time.Hour // Just set to something known, not utilized.
1795 // Force R1 and MemoryStorage for these.
1796 o.cfg.Replicas = 1
1797 o.cfg.MemoryStorage = true
1798
1799 if !hasHeartbeats {
1800 o.cfg.Heartbeat = orderedHeartbeatsInterval
1801 }
1802 hasFC, hasHeartbeats = true, true
1803 o.mack = true // To avoid auto-ack wrapping call below.
1804 hbi = o.cfg.Heartbeat
1805 }
1806
1807 // In case a consumer has not been set explicitly, then the
1808 // durable name will be used as the consumer name.
1809 if consumer == _EMPTY_ {
1810 consumer = o.cfg.Durable
1811 }
1812
1813 // Find the stream mapped to the subject if not bound to a stream already.
1814 if stream == _EMPTY_ {
1815 stream, err = js.StreamNameBySubject(subj)
1816 if err != nil {
1817 return nil, err
1818 }
1819 }
1820
1821 // With an explicit durable name, we can lookup the consumer first
1822 // to which it should be attaching to.
1823 // If SkipConsumerLookup was used, do not call consumer info.
1824 if consumer != _EMPTY_ && !o.skipCInfo {
1825 info, err = js.ConsumerInfo(stream, consumer)
1826 notFoundErr = errors.Is(err, ErrConsumerNotFound)
1827 lookupErr = err == ErrJetStreamNotEnabled || errors.Is(err, ErrTimeout) || errors.Is(err, context.DeadlineExceeded)
1828 }
1829
1830 switch {
1831 case info != nil:
1832 deliver, err = processConsInfo(info, o.cfg, isPullMode, subj, queue)
1833 if err != nil {
1834 return nil, err
1835 }
1836 icfg := &info.Config
1837 hasFC, hbi = icfg.FlowControl, icfg.Heartbeat
1838 hasHeartbeats = hbi > 0
1839 maxap = icfg.MaxAckPending
1840 case (err != nil && !notFoundErr) || (notFoundErr && consumerBound):
1841 // If the consumer is being bound and we got an error on pull subscribe then allow the error.
1842 if !(isPullMode && lookupErr && consumerBound) {
1843 return nil, err
1844 }
1845 case skipCInfo:
1846 // When skipping consumer info, need to rely on the manually passed sub options
1847 // to match the expected behavior from the subscription.
1848 hasFC, hbi = o.cfg.FlowControl, o.cfg.Heartbeat
1849 hasHeartbeats = hbi > 0
1850 maxap = o.cfg.MaxAckPending
1851 deliver = o.cfg.DeliverSubject
1852 if consumerBound {
1853 break
1854 }
1855
1856 // When not bound to a consumer already, proceed to create.
1857 fallthrough
1858 default:
1859 // Attempt to create consumer if not found nor using Bind.
1860 shouldCreate = true
1861 if o.cfg.DeliverSubject != _EMPTY_ {
1862 deliver = o.cfg.DeliverSubject
1863 } else if !isPullMode {
1864 deliver = nc.NewInbox()
1865 cfg.DeliverSubject = deliver
1866 }
1867 // Do filtering always, server will clear as needed.
1868 cfg.FilterSubject = subj
1869
1870 // Pass the queue to the consumer config
1871 if queue != _EMPTY_ {
1872 cfg.DeliverGroup = queue
1873 }
1874
1875 // If not set, default to deliver all
1876 if cfg.DeliverPolicy == deliverPolicyNotSet {
1877 cfg.DeliverPolicy = DeliverAllPolicy
1878 }
1879 // If not set, default to ack explicit.
1880 if cfg.AckPolicy == ackPolicyNotSet {
1881 cfg.AckPolicy = AckExplicitPolicy
1882 }
1883 // If not set, default to instant
1884 if cfg.ReplayPolicy == replayPolicyNotSet {
1885 cfg.ReplayPolicy = ReplayInstantPolicy
1886 }
1887
1888 // If we have acks at all and the MaxAckPending is not set go ahead
1889 // and set to the internal max for channel based consumers
1890 if cfg.MaxAckPending == 0 && ch != nil && cfg.AckPolicy != AckNonePolicy {
1891 cfg.MaxAckPending = cap(ch)
1892 }
1893 // Create request here.
1894 ccreq = &createConsumerRequest{
1895 Stream: stream,
1896 Config: &cfg,
1897 }
1898 hbi = cfg.Heartbeat
1899 }
1900
1901 if isPullMode {
1902 nms = fmt.Sprintf(js.apiSubj(apiRequestNextT), stream, consumer)
1903 deliver = nc.NewInbox()
1904 // for pull consumers, create a wildcard subscription to differentiate pull requests
1905 deliver += ".*"
1906 }
1907
1908 // In case this has a context, then create a child context that
1909 // is possible to cancel via unsubscribe / drain.
1910 var cancel func()
1911 if ctx != nil {
1912 ctx, cancel = context.WithCancel(ctx)
1913 }
1914
1915 jsi := &jsSub{
1916 js: js,
1917 stream: stream,
1918 consumer: consumer,
1919 deliver: deliver,
1920 hbi: hbi,
1921 ordered: o.ordered,
1922 ccreq: ccreq,
1923 dseq: 1,
1924 pull: isPullMode,
1925 nms: nms,
1926 psubj: subj,
1927 cancel: cancel,
1928 ackNone: o.cfg.AckPolicy == AckNonePolicy,
1929 ctx: o.ctx,
1930 }
1931
1932 // Auto acknowledge unless manual ack is set or policy is set to AckNonePolicy
1933 if cb != nil && !o.mack && o.cfg.AckPolicy != AckNonePolicy {
1934 ocb := cb
1935 cb = func(m *Msg) { ocb(m); m.Ack() }
1936 }
1937 sub, err := nc.subscribe(deliver, queue, cb, ch, nil, isSync, jsi)
1938 if err != nil {
1939 return nil, err
1940 }
1941
1942 // If we fail and we had the sub we need to cleanup, but can't just do a straight Unsubscribe or Drain.
1943 // We need to clear the jsi so we do not remove any durables etc.
1944 cleanUpSub := func() {
1945 if sub != nil {
1946 sub.mu.Lock()
1947 sub.jsi = nil
1948 sub.mu.Unlock()
1949 sub.Unsubscribe()
1950 }
1951 }
1952
1953 // If we are creating or updating let's process that request.
1954 consName := o.cfg.Name
1955 if shouldCreate {
1956 if cfg.Durable != "" {
1957 consName = cfg.Durable
1958 } else if consName == "" {
1959 consName = getHash(nuid.Next())
1960 }
1961 if o.ctx != nil {
1962 info, err = js.upsertConsumer(stream, consName, ccreq.Config, Context(o.ctx))
1963 } else {
1964 info, err = js.upsertConsumer(stream, consName, ccreq.Config)
1965 }
1966 if err != nil {
1967 var apiErr *APIError
1968 if ok := errors.As(err, &apiErr); !ok {
1969 cleanUpSub()
1970 return nil, err
1971 }
1972 lookupConsumer := consumer
1973 if lookupConsumer == _EMPTY_ {
1974 lookupConsumer = consName
1975 }
1976 if lookupConsumer == _EMPTY_ ||
1977 (apiErr.ErrorCode != JSErrCodeConsumerAlreadyExists && apiErr.ErrorCode != JSErrCodeConsumerNameExists) {
1978 cleanUpSub()
1979 if errors.Is(apiErr, ErrStreamNotFound) {
1980 return nil, ErrStreamNotFound
1981 }
1982 return nil, err
1983 }
1984 // We will not be using this sub here if we were push based.
1985 if !isPullMode {
1986 cleanUpSub()
1987 }
1988
1989 info, err = js.ConsumerInfo(stream, lookupConsumer)
1990 if err != nil {
1991 return nil, err
1992 }
1993 deliver, err = processConsInfo(info, o.cfg, isPullMode, subj, queue)
1994 if err != nil {
1995 return nil, err
1996 }
1997
1998 if !isPullMode {
1999 // We can't reuse the channel, so if one was passed, we need to create a new one.
2000 if isSync {
2001 ch = make(chan *Msg, cap(ch))
2002 } else if ch != nil {
2003 // User provided (ChanSubscription), simply try to drain it.
2004 for done := false; !done; {
2005 select {
2006 case <-ch:
2007 default:
2008 done = true
2009 }
2010 }
2011 }
2012 jsi.deliver = deliver
2013 jsi.hbi = info.Config.Heartbeat
2014
2015 // Recreate the subscription here.
2016 sub, err = nc.subscribe(jsi.deliver, queue, cb, ch, nil, isSync, jsi)
2017 if err != nil {
2018 return nil, err
2019 }
2020 hasFC = info.Config.FlowControl
2021 hasHeartbeats = info.Config.Heartbeat > 0
2022 }
2023 } else {
2024 // Since the library created the JS consumer, it will delete it on Unsubscribe()/Drain()
2025 sub.mu.Lock()
2026 sub.jsi.dc = true
2027 sub.jsi.pending = info.NumPending + info.Delivered.Consumer
2028 // If this is an ephemeral, we did not have a consumer name, we get it from the info
2029 // after the AddConsumer returns.
2030 if consumer == _EMPTY_ {
2031 sub.jsi.consumer = info.Name
2032 if isPullMode {
2033 sub.jsi.nms = fmt.Sprintf(js.apiSubj(apiRequestNextT), stream, info.Name)
2034 }
2035 }
2036 sub.mu.Unlock()
2037 }
2038 // Capture max ack pending from the info response here which covers both
2039 // success and failure followed by consumer lookup.
2040 maxap = info.Config.MaxAckPending
2041 }
2042
2043 // If maxap is greater than the default sub's pending limit, use that.
2044 if maxap > DefaultSubPendingMsgsLimit {
2045 // For bytes limit, use the min of maxp*1MB or DefaultSubPendingBytesLimit
2046 bl := max(maxap*1024*1024, DefaultSubPendingBytesLimit)
2047 if err := sub.SetPendingLimits(maxap, bl); err != nil {
2048 return nil, err
2049 }
2050 }
2051
2052 // Do heartbeats last if needed.
2053 if hasHeartbeats {
2054 sub.scheduleHeartbeatCheck()
2055 }
2056 // For ChanSubscriptions, if we know that there is flow control, we will
2057 // start a go routine that evaluates the number of delivered messages
2058 // and process flow control.
2059 if sub.Type() == ChanSubscription && hasFC {
2060 sub.chanSubcheckForFlowControlResponse()
2061 }
2062
2063 // Wait for context to get canceled if there is one.
2064 if ctx != nil {
2065 go func() {
2066 <-ctx.Done()
2067 sub.Unsubscribe()
2068 }()
2069 }
2070
2071 return sub, nil
2072 }
2073
2074 // InitialConsumerPending returns the number of messages pending to be
2075 // delivered to the consumer when the subscription was created.
2076 func (sub *Subscription) InitialConsumerPending() (uint64, error) {
2077 sub.mu.Lock()
2078 defer sub.mu.Unlock()
2079 if sub.jsi == nil || sub.jsi.consumer == _EMPTY_ {
2080 return 0, fmt.Errorf("%w: not a JetStream subscription", ErrTypeSubscription)
2081 }
2082 return sub.jsi.pending, nil
2083 }
2084
2085 // This long-lived routine is used per ChanSubscription to check
2086 // on the number of delivered messages and check for flow control response.
2087 func (sub *Subscription) chanSubcheckForFlowControlResponse() {
2088 sub.mu.Lock()
2089 // We don't use defer since if we need to send an RC reply, we need
2090 // to do it outside the sub's lock. So doing explicit unlock...
2091 if sub.closed {
2092 sub.mu.Unlock()
2093 return
2094 }
2095 var fcReply string
2096 var nc *Conn
2097
2098 jsi := sub.jsi
2099 if jsi.csfct == nil {
2100 jsi.csfct = time.AfterFunc(chanSubFCCheckInterval, sub.chanSubcheckForFlowControlResponse)
2101 } else {
2102 fcReply = sub.checkForFlowControlResponse()
2103 nc = sub.conn
2104 // Do the reset here under the lock, it's ok...
2105 jsi.csfct.Reset(chanSubFCCheckInterval)
2106 }
2107 sub.mu.Unlock()
2108 // This call will return an error (which we don't care here)
2109 // if nc is nil or fcReply is empty.
2110 nc.Publish(fcReply, nil)
2111 }
2112
2113 // ErrConsumerSequenceMismatch represents an error from a consumer
2114 // that received a Heartbeat including sequence different to the
2115 // one expected from the view of the client.
2116 type ErrConsumerSequenceMismatch struct {
2117 // StreamResumeSequence is the stream sequence from where the consumer
2118 // should resume consuming from the stream.
2119 StreamResumeSequence uint64
2120
2121 // ConsumerSequence is the sequence of the consumer that is behind.
2122 ConsumerSequence uint64
2123
2124 // LastConsumerSequence is the sequence of the consumer when the heartbeat
2125 // was received.
2126 LastConsumerSequence uint64
2127 }
2128
2129 func (ecs *ErrConsumerSequenceMismatch) Error() string {
2130 return fmt.Sprintf("nats: sequence mismatch for consumer at sequence %d (%d sequences behind), should restart consumer from stream sequence %d",
2131 ecs.ConsumerSequence,
2132 ecs.LastConsumerSequence-ecs.ConsumerSequence,
2133 ecs.StreamResumeSequence,
2134 )
2135 }
2136
2137 // isJSControlMessage will return true if this is an empty control status message
2138 // and indicate what type of control message it is, say jsCtrlHB or jsCtrlFC
2139 func isJSControlMessage(msg *Msg) (bool, int) {
2140 if len(msg.Data) > 0 || msg.Header.Get(statusHdr) != controlMsg {
2141 return false, 0
2142 }
2143 val := msg.Header.Get(descrHdr)
2144 if strings.HasPrefix(val, "Idle") {
2145 return true, jsCtrlHB
2146 }
2147 if strings.HasPrefix(val, "Flow") {
2148 return true, jsCtrlFC
2149 }
2150 return true, 0
2151 }
2152
2153 // Keeps track of the incoming message's reply subject so that the consumer's
2154 // state (deliver sequence, etc..) can be checked against heartbeats.
2155 // We will also bump the incoming data message sequence that is used in FC cases.
2156 // Runs under the subscription lock
2157 func (sub *Subscription) trackSequences(reply string) {
2158 // For flow control, keep track of incoming message sequence.
2159 sub.jsi.fciseq++
2160 sub.jsi.cmeta = reply
2161 }
2162
2163 // orderedSeqs carries the sequences of a message that passed the ordering check
2164 // but has not yet been handed off for delivery.
2165 type orderedSeqs struct {
2166 dseq, sseq uint64
2167 }
2168
2169 // Check to make sure messages are arriving in order.
2170 // Returns true when m is not the message the ordered consumer was expecting
2171 // next. The tracker is not advanced here; the returned sequences are applied
2172 // with commitOrderedMsg once m is queued for delivery.
2173 // Lock should be held.
2174 func (sub *Subscription) checkOrderedMsgs(m *Msg) (bool, orderedSeqs) {
2175 // Ignore msgs with no reply like HBs and flow control, they are handled elsewhere.
2176 if m.Reply == _EMPTY_ {
2177 return false, orderedSeqs{}
2178 }
2179
2180 // Normal message here.
2181 tokens, err := parser.GetMetadataFields(m.Reply)
2182 if err != nil {
2183 return false, orderedSeqs{}
2184 }
2185 sseq, dseq := parser.ParseNum(tokens[parser.AckStreamSeqTokenPos]), parser.ParseNum(tokens[parser.AckConsumerSeqTokenPos])
2186
2187 jsi := sub.jsi
2188 if dseq != jsi.dseq {
2189 return true, orderedSeqs{}
2190 }
2191 return false, orderedSeqs{dseq: dseq, sseq: sseq}
2192 }
2193
2194 // commitOrderedMsg advances the ordered consumer tracker for a message that has
2195 // been queued for delivery. Pairs with checkOrderedMsgs.
2196 // Lock should be held.
2197 func (sub *Subscription) commitOrderedMsg(seqs orderedSeqs) {
2198 if seqs.dseq == 0 {
2199 return
2200 }
2201 sub.jsi.dseq, sub.jsi.sseq = seqs.dseq+1, seqs.sseq
2202 }
2203
2204 // jsMsgAction tells processMsg what to do with a message once the ordered
2205 // consumer checks have run against it.
2206 type jsMsgAction int
2207
2208 const (
2209 jsMsgDeliver jsMsgAction = iota
2210 // Cannot be delivered. The caller's slow consumer path counts it and
2211 // releases the pending accounting reserved for it.
2212 jsMsgDrop
2213 // Out of order and fully handled. The caller only unlocks and returns.
2214 jsMsgDropGap
2215 )
2216
2217 // checkOrderedDelivery validates an ordered consumer message's place in the
2218 // sequence and reports what processMsg should do with it.
2219 //
2220 // The caller has verified that sub.jsi != nil and that the consumer is ordered.
2221 // Lock is held on entry and on return, but a reset releases and reacquires it
2222 // to recreate the consumer.
2223 func (sub *Subscription) checkOrderedDelivery(m *Msg) (jsMsgAction, orderedSeqs) {
2224 jsi := sub.jsi
2225 // Everything still arriving belongs to the consumer about to be replaced
2226 // and is refetched by the reset, which may have room by now.
2227 if jsi.resetPending {
2228 sub.tryResetOrderedConsumer()
2229 return jsMsgDrop, orderedSeqs{}
2230 }
2231 // A full channel would drop the message below anyway; checking first keeps
2232 // the drop from reading as a gap.
2233 if sub.mch != nil && cap(sub.mch) > 0 && len(sub.mch) == cap(sub.mch) {
2234 return jsMsgDrop, orderedSeqs{}
2235 }
2236
2237 gap, seqs := sub.checkOrderedMsgs(m)
2238 if !gap {
2239 return jsMsgDeliver, seqs
2240 }
2241
2242 // An unbuffered channel has no capacity signal. With nothing delivered
2243 // since the last reset, resetting again would just refetch into the same
2244 // wall, so leave it to the heartbeat. Once something has been delivered
2245 // the reader is there and a drop means it was merely busy, so reset at
2246 // once; deferring to the heartbeat here would drain a backlog one message
2247 // per interval.
2248 if sub.mch != nil && cap(sub.mch) == 0 && jsi.dseq == 1 {
2249 return jsMsgDrop, orderedSeqs{}
2250 }
2251 sub.releaseReserved(m)
2252 sub.tryResetOrderedConsumer()
2253 return jsMsgDropGap, orderedSeqs{}
2254 }
2255
2256 // tryResetOrderedConsumer recreates the consumer after a gap, or defers that
2257 // while more than half of the subscription's buffer is in use, so the refetch
2258 // is not dropped into a buffer that is still nearly full. A deferred reset is
2259 // retried as messages are delivered and as messages and heartbeats arrive.
2260 // Lock should be held.
2261 func (sub *Subscription) tryResetOrderedConsumer() {
2262 jsi := sub.jsi
2263 if (sub.pMsgsLimit > 0 && sub.pMsgs > sub.pMsgsLimit/2) ||
2264 (sub.pBytesLimit > 0 && sub.pBytes > sub.pBytesLimit/2) ||
2265 (sub.mch != nil && len(sub.mch) > cap(sub.mch)/2) {
2266 jsi.resetPending = true
2267 return
2268 }
2269 sub.resetOrderedConsumer(jsi.sseq + 1)
2270 }
2271
2272 // Update and replace sid. Returns the old and the new sid. Returns ok == false,
2273 // leaving everything untouched, if the subscription is no longer registered on
2274 // the connection.
2275 // Lock should be held on entry but will be unlocked to prevent lock inversion.
2276 func (sub *Subscription) applyNewSID() (osid, nsid int64, ok bool) {
2277 nc := sub.conn
2278 sub.mu.Unlock()
2279
2280 nc.subsMu.Lock()
2281 osid = sub.sid
2282 // removeSub or close() may have run while sub.mu was released;
2283 // re-registering would resurrect the sub or write to a nil nc.subs.
2284 if nc.subs[osid] != sub {
2285 nc.subsMu.Unlock()
2286 sub.mu.Lock()
2287 return osid, 0, false
2288 }
2289 delete(nc.subs, osid)
2290 // Place new one.
2291 nc.ssid++
2292 nsid = nc.ssid
2293 nc.subs[nsid] = sub
2294 sub.sid = nsid
2295 nc.subsMu.Unlock()
2296
2297 sub.mu.Lock()
2298 return osid, nsid, true
2299 }
2300
2301 // We are here if we have detected a gap with an ordered consumer.
2302 // We will create a new consumer and rewire the low level subscription.
2303 // Lock should be held.
2304 func (sub *Subscription) resetOrderedConsumer(sseq uint64) {
2305 nc := sub.conn
2306 if sub.jsi == nil || nc == nil || sub.closed || sub.draining {
2307 return
2308 }
2309 sub.jsi.resetPending = false
2310
2311 var maxStr string
2312 // If there was an AUTO_UNSUB done, we need to adjust the new value
2313 // to send after the SUB for the new sid.
2314 if sub.max > 0 {
2315 if sub.jsi.fciseq < sub.max {
2316 adjustedMax := sub.max - sub.jsi.fciseq
2317 maxStr = strconv.Itoa(int(adjustedMax))
2318 } else {
2319 // We are already at the max, so we should just unsub the
2320 // existing sub and be done. The sid is read in the go routine
2321 // because it is protected by subsMu, which cannot be acquired
2322 // here since sub.mu is held.
2323 go func() {
2324 nc.mu.Lock()
2325 nc.subsMu.RLock()
2326 sid := sub.sid
2327 nc.subsMu.RUnlock()
2328 nc.bw.appendString(fmt.Sprintf(unsubProto, sid, _EMPTY_))
2329 nc.kickFlusher()
2330 nc.mu.Unlock()
2331 }()
2332 return
2333 }
2334 }
2335
2336 // Quick unsubscribe. Since we know this is a simple push subscriber we do in place.
2337 osid, nsid, ok := sub.applyNewSID()
2338 if !ok {
2339 return
2340 }
2341
2342 // Grab new inbox.
2343 newDeliver := nc.NewInbox()
2344 sub.Subject = newDeliver
2345
2346 // We are still in the low level readLoop for the connection so we need
2347 // to spin a go routine to try to create the new consumer.
2348 go func() {
2349 // Unsubscribe and subscribe with new inbox and sid.
2350 // Remap a new low level sub into this sub since its client accessible.
2351 // This is done here in this go routine to prevent lock inversion.
2352 if !nc.rewireOrderedSub(sub, osid, nsid, newDeliver, maxStr) {
2353 return
2354 }
2355
2356 pushErr := func(err error) {
2357 nc.handleConsumerSequenceMismatch(sub, fmt.Errorf("%w: recreating ordered consumer", err))
2358 nc.unsubscribe(sub, 0, true)
2359 }
2360
2361 sub.mu.Lock()
2362 jsi := sub.jsi
2363 // Reset some items in jsi.
2364 jsi.dseq = 1
2365 jsi.cmeta = _EMPTY_
2366 jsi.fcr, jsi.fcd = _EMPTY_, 0
2367 jsi.deliver = newDeliver
2368 // Reset consumer request for starting policy. Take a value copy of the
2369 // ConsumerConfig so concurrent activityCheck-spawned resets don't race
2370 // on a shared *ConsumerConfig — a later goroutine's writes here would
2371 // otherwise overlap an earlier goroutine's json.Marshal in
2372 // upsertConsumer below (called outside sub.mu).
2373 cfgCopy := *jsi.ccreq.Config
2374 cfg := &cfgCopy
2375 cfg.DeliverSubject = newDeliver
2376 cfg.DeliverPolicy = DeliverByStartSequencePolicy
2377 cfg.OptStartSeq = sseq
2378 // In case the consumer was created with a start time, we need to clear it
2379 // since we are now using a start sequence.
2380 cfg.OptStartTime = nil
2381
2382 js := jsi.js
2383 sub.mu.Unlock()
2384
2385 sub.mu.Lock()
2386 // Attempt to delete the existing consumer.
2387 // We don't wait for the response since even if it's unsuccessful,
2388 // inactivity threshold will kick in and delete it.
2389 if jsi.consumer != _EMPTY_ {
2390 go js.DeleteConsumer(jsi.stream, jsi.consumer)
2391 }
2392 jsi.consumer = ""
2393 sub.mu.Unlock()
2394 consName := getHash(nuid.Next())
2395 var cinfo *ConsumerInfo
2396 var err error
2397 if js.opts.ctx != nil {
2398 cinfo, err = js.upsertConsumer(jsi.stream, consName, cfg, Context(js.opts.ctx))
2399 } else {
2400 cinfo, err = js.upsertConsumer(jsi.stream, consName, cfg)
2401 }
2402 if err != nil {
2403 var apiErr *APIError
2404 if errors.Is(err, ErrJetStreamNotEnabled) || errors.Is(err, ErrTimeout) || errors.Is(err, context.DeadlineExceeded) {
2405 // if creating consumer failed, retry
2406 return
2407 } else if errors.As(err, &apiErr) && apiErr.ErrorCode == JSErrCodeInsufficientResourcesErr {
2408 // retry for insufficient resources, as it may mean that client is connected to a running
2409 // server in cluster while the server hosting R1 JetStream resources is restarting
2410 return
2411 } else if errors.As(err, &apiErr) && apiErr.ErrorCode == JSErrCodeJetStreamNotAvailable {
2412 // retry if JetStream meta leader is temporarily unavailable
2413 return
2414 }
2415 pushErr(err)
2416 return
2417 }
2418
2419 sub.mu.Lock()
2420 if sub.closed || sub.draining {
2421 // Unsubscribed or drained while the consumer was being created.
2422 // The consumer is not attached to anything anymore, so delete it
2423 // rather than waiting for the inactivity threshold.
2424 sub.mu.Unlock()
2425 go js.DeleteConsumer(jsi.stream, cinfo.Name)
2426 return
2427 }
2428 jsi.consumer = cinfo.Name
2429 sub.mu.Unlock()
2430 }()
2431 }
2432
2433 // rewireOrderedSub moves the subscription from osid to nsid on the server.
2434 // The old sid is always unsubscribed; the new one is only subscribed if the
2435 // subscription is still registered and not draining, so that no interest is
2436 // created for a subscription that will not accept messages anymore. Returns
2437 // whether that happened. unsubscribe runs under nc.mu too, so the check is
2438 // exact.
2439 func (nc *Conn) rewireOrderedSub(sub *Subscription, osid, nsid int64, deliver, maxStr string) bool {
2440 nc.mu.Lock()
2441 defer nc.mu.Unlock()
2442
2443 nc.bw.appendString(fmt.Sprintf(unsubProto, osid, _EMPTY_))
2444 nc.subsMu.RLock()
2445 sub.mu.Lock()
2446 // A draining subscription is only removed from nc.subs once the drain
2447 // completes, and that removal sends no UNSUB, so subscribing the new sid
2448 // here would leave interest on the server for the life of the connection.
2449 registered := nc.subs[nsid] == sub && !sub.draining
2450 sub.mu.Unlock()
2451 nc.subsMu.RUnlock()
2452 if registered {
2453 nc.bw.appendString(fmt.Sprintf(subProto, deliver, _EMPTY_, nsid))
2454 if maxStr != _EMPTY_ {
2455 nc.bw.appendString(fmt.Sprintf(unsubProto, nsid, maxStr))
2456 }
2457 }
2458 nc.kickFlusher()
2459 return registered
2460 }
2461
2462 // For jetstream subscriptions, returns the number of delivered messages.
2463 // For ChanSubscription, this value is computed based on the known number
2464 // of messages added to the channel minus the current size of that channel.
2465 // Lock held on entry
2466 func (sub *Subscription) getJSDelivered() uint64 {
2467 if sub.typ == ChanSubscription {
2468 return sub.jsi.fciseq - uint64(len(sub.mch))
2469 }
2470 return sub.delivered
2471 }
2472
2473 // checkForFlowControlResponse will check to see if we should send a flow control response
2474 // based on the subscription current delivered index and the target.
2475 // Runs under subscription lock
2476 func (sub *Subscription) checkForFlowControlResponse() string {
2477 // Caller has verified that there is a sub.jsi and fc
2478 jsi := sub.jsi
2479 jsi.active = true
2480 if sub.getJSDelivered() >= jsi.fcd {
2481 fcr := jsi.fcr
2482 jsi.fcr, jsi.fcd = _EMPTY_, 0
2483 return fcr
2484 }
2485 return _EMPTY_
2486 }
2487
2488 // Record an inbound flow control message.
2489 // Runs under subscription lock
2490 func (sub *Subscription) scheduleFlowControlResponse(reply string) {
2491 sub.jsi.fcr, sub.jsi.fcd = reply, sub.jsi.fciseq
2492 }
2493
2494 // Checks for activity from our consumer.
2495 // If we do not think we are active send an async error.
2496 func (sub *Subscription) activityCheck() {
2497 sub.mu.Lock()
2498 jsi := sub.jsi
2499 if jsi == nil || sub.closed {
2500 sub.mu.Unlock()
2501 return
2502 }
2503
2504 active := jsi.active
2505 jsi.hbc.Reset(jsi.hbi * hbcThresh)
2506 jsi.active = false
2507 nc := sub.conn
2508 sub.mu.Unlock()
2509
2510 if !active {
2511 if !jsi.ordered || nc.Status() != CONNECTED {
2512 nc.mu.Lock()
2513 if errCB := nc.Opts.AsyncErrorCB; errCB != nil {
2514 nc.ach.push(func() { errCB(nc, sub, ErrConsumerNotActive) })
2515 }
2516 nc.mu.Unlock()
2517 return
2518 }
2519 sub.mu.Lock()
2520 sub.tryResetOrderedConsumer()
2521 sub.mu.Unlock()
2522 }
2523 }
2524
2525 // scheduleHeartbeatCheck sets up the timer check to make sure we are active
2526 // or receiving idle heartbeats..
2527 func (sub *Subscription) scheduleHeartbeatCheck() {
2528 sub.mu.Lock()
2529 defer sub.mu.Unlock()
2530
2531 jsi := sub.jsi
2532 if jsi == nil {
2533 return
2534 }
2535
2536 if jsi.hbc == nil {
2537 jsi.hbc = time.AfterFunc(jsi.hbi*hbcThresh, sub.activityCheck)
2538 } else {
2539 jsi.hbc.Reset(jsi.hbi * hbcThresh)
2540 }
2541 }
2542
2543 // handleConsumerSequenceMismatch will send an async error that can be used to restart a push based consumer.
2544 func (nc *Conn) handleConsumerSequenceMismatch(sub *Subscription, err error) {
2545 nc.mu.Lock()
2546 errCB := nc.Opts.AsyncErrorCB
2547 if errCB != nil {
2548 nc.ach.push(func() { errCB(nc, sub, err) })
2549 }
2550 nc.mu.Unlock()
2551 }
2552
2553 // checkForSequenceMismatch will make sure we have not missed any messages since last seen.
2554 func (nc *Conn) checkForSequenceMismatch(msg *Msg, s *Subscription, jsi *jsSub) {
2555 // Process heartbeat received, get latest control metadata if present.
2556 s.mu.Lock()
2557 ctrl, ordered := jsi.cmeta, jsi.ordered
2558 jsi.active = true
2559 s.mu.Unlock()
2560
2561 // The server reports the last consumer sequence it delivered.
2562 var ldseq string
2563 if hdr := msg.Header[lastConsumerSeqHdr]; len(hdr) == 1 {
2564 ldseq = hdr[0]
2565 }
2566
2567 if ordered {
2568 if ldseq == _EMPTY_ {
2569 return
2570 }
2571 // jsi.dseq is the next sequence expected and advances only for messages
2572 // handed off for delivery, so caught up means ldseq == jsi.dseq-1 and
2573 // ldseq >= jsi.dseq means there is a gap.
2574 s.mu.Lock()
2575 if parser.ParseNum(ldseq) >= jsi.dseq {
2576 s.tryResetOrderedConsumer()
2577 }
2578 s.mu.Unlock()
2579 return
2580 }
2581
2582 if ctrl == _EMPTY_ {
2583 return
2584 }
2585
2586 tokens, err := parser.GetMetadataFields(ctrl)
2587 if err != nil {
2588 return
2589 }
2590
2591 // Consumer sequence.
2592 dseq := tokens[parser.AckConsumerSeqTokenPos]
2593
2594 // Detect consumer sequence mismatch and whether
2595 // should restart the consumer.
2596 if ldseq != dseq {
2597 // Dispatch async error including details such as
2598 // from where the consumer could be restarted.
2599 sseq := parser.ParseNum(tokens[parser.AckStreamSeqTokenPos])
2600 ecs := &ErrConsumerSequenceMismatch{
2601 StreamResumeSequence: uint64(sseq),
2602 ConsumerSequence: parser.ParseNum(dseq),
2603 LastConsumerSequence: parser.ParseNum(ldseq),
2604 }
2605 nc.handleConsumerSequenceMismatch(s, ecs)
2606 }
2607 }
2608
2609 type streamRequest struct {
2610 Subject string `json:"subject,omitempty"`
2611 }
2612
2613 type streamNamesResponse struct {
2614 apiResponse
2615 apiPaged
2616 Streams []string `json:"streams"`
2617 }
2618
2619 type subOpts struct {
2620 // For attaching.
2621 stream, consumer string
2622 // For creating or updating.
2623 cfg *ConsumerConfig
2624 // For binding a subscription to a consumer without creating it.
2625 bound bool
2626 // For manual ack
2627 mack bool
2628 // For an ordered consumer.
2629 ordered bool
2630 ctx context.Context
2631
2632 // To disable calling ConsumerInfo
2633 skipCInfo bool
2634 }
2635
2636 // SkipConsumerLookup will omit looking up consumer when [Bind], [Durable]
2637 // or [ConsumerName] are provided.
2638 //
2639 // NOTE: This setting may cause an existing consumer to be overwritten. Also,
2640 // because consumer lookup is skipped, all consumer options like AckPolicy,
2641 // DeliverSubject etc. need to be provided even if consumer already exists.
2642 func SkipConsumerLookup() SubOpt {
2643 return subOptFn(func(opts *subOpts) error {
2644 opts.skipCInfo = true
2645 return nil
2646 })
2647 }
2648
2649 // OrderedConsumer will create a FIFO direct/ephemeral consumer for in order delivery of messages.
2650 // There are no redeliveries and no acks, and flow control and heartbeats will be added but
2651 // will be taken care of without additional client code.
2652 func OrderedConsumer() SubOpt {
2653 return subOptFn(func(opts *subOpts) error {
2654 opts.ordered = true
2655 return nil
2656 })
2657 }
2658
2659 // ManualAck disables auto ack functionality for async subscriptions.
2660 func ManualAck() SubOpt {
2661 return subOptFn(func(opts *subOpts) error {
2662 opts.mack = true
2663 return nil
2664 })
2665 }
2666
2667 // Description will set the description for the created consumer.
2668 func Description(description string) SubOpt {
2669 return subOptFn(func(opts *subOpts) error {
2670 opts.cfg.Description = description
2671 return nil
2672 })
2673 }
2674
2675 // Durable defines the consumer name for JetStream durable subscribers.
2676 // This function will return ErrInvalidConsumerName if the name contains
2677 // any dot ".".
2678 func Durable(consumer string) SubOpt {
2679 return subOptFn(func(opts *subOpts) error {
2680 if opts.cfg.Durable != _EMPTY_ {
2681 return errors.New("nats: option Durable set more than once")
2682 }
2683 if opts.consumer != _EMPTY_ && opts.consumer != consumer {
2684 return fmt.Errorf("nats: duplicate consumer names (%s and %s)", opts.consumer, consumer)
2685 }
2686 if err := checkConsumerName(consumer); err != nil {
2687 return err
2688 }
2689
2690 opts.cfg.Durable = consumer
2691 return nil
2692 })
2693 }
2694
2695 // DeliverAll will configure a Consumer to receive all the
2696 // messages from a Stream.
2697 func DeliverAll() SubOpt {
2698 return subOptFn(func(opts *subOpts) error {
2699 opts.cfg.DeliverPolicy = DeliverAllPolicy
2700 return nil
2701 })
2702 }
2703
2704 // DeliverLast configures a Consumer to receive messages
2705 // starting with the latest one.
2706 func DeliverLast() SubOpt {
2707 return subOptFn(func(opts *subOpts) error {
2708 opts.cfg.DeliverPolicy = DeliverLastPolicy
2709 return nil
2710 })
2711 }
2712
2713 // DeliverLastPerSubject configures a Consumer to receive messages
2714 // starting with the latest one for each filtered subject.
2715 func DeliverLastPerSubject() SubOpt {
2716 return subOptFn(func(opts *subOpts) error {
2717 opts.cfg.DeliverPolicy = DeliverLastPerSubjectPolicy
2718 return nil
2719 })
2720 }
2721
2722 // DeliverNew configures a Consumer to receive messages
2723 // published after the subscription.
2724 func DeliverNew() SubOpt {
2725 return subOptFn(func(opts *subOpts) error {
2726 opts.cfg.DeliverPolicy = DeliverNewPolicy
2727 return nil
2728 })
2729 }
2730
2731 // StartSequence configures a Consumer to receive
2732 // messages from a start sequence.
2733 func StartSequence(seq uint64) SubOpt {
2734 return subOptFn(func(opts *subOpts) error {
2735 opts.cfg.DeliverPolicy = DeliverByStartSequencePolicy
2736 opts.cfg.OptStartSeq = seq
2737 return nil
2738 })
2739 }
2740
2741 // StartTime configures a Consumer to receive
2742 // messages from a start time.
2743 func StartTime(startTime time.Time) SubOpt {
2744 return subOptFn(func(opts *subOpts) error {
2745 opts.cfg.DeliverPolicy = DeliverByStartTimePolicy
2746 opts.cfg.OptStartTime = &startTime
2747 return nil
2748 })
2749 }
2750
2751 // AckNone requires no acks for delivered messages.
2752 func AckNone() SubOpt {
2753 return subOptFn(func(opts *subOpts) error {
2754 opts.cfg.AckPolicy = AckNonePolicy
2755 return nil
2756 })
2757 }
2758
2759 // AckAll when acking a sequence number, this implicitly acks all sequences
2760 // below this one as well.
2761 func AckAll() SubOpt {
2762 return subOptFn(func(opts *subOpts) error {
2763 opts.cfg.AckPolicy = AckAllPolicy
2764 return nil
2765 })
2766 }
2767
2768 // AckExplicit requires ack or nack for all messages.
2769 func AckExplicit() SubOpt {
2770 return subOptFn(func(opts *subOpts) error {
2771 opts.cfg.AckPolicy = AckExplicitPolicy
2772 return nil
2773 })
2774 }
2775
2776 // MaxDeliver sets the number of redeliveries for a message.
2777 func MaxDeliver(n int) SubOpt {
2778 return subOptFn(func(opts *subOpts) error {
2779 opts.cfg.MaxDeliver = n
2780 return nil
2781 })
2782 }
2783
2784 // MaxAckPending sets the number of outstanding acks that are allowed before
2785 // message delivery is halted.
2786 func MaxAckPending(n int) SubOpt {
2787 return subOptFn(func(opts *subOpts) error {
2788 opts.cfg.MaxAckPending = n
2789 return nil
2790 })
2791 }
2792
2793 // ReplayOriginal replays the messages at the original speed.
2794 func ReplayOriginal() SubOpt {
2795 return subOptFn(func(opts *subOpts) error {
2796 opts.cfg.ReplayPolicy = ReplayOriginalPolicy
2797 return nil
2798 })
2799 }
2800
2801 // ReplayInstant replays the messages as fast as possible.
2802 func ReplayInstant() SubOpt {
2803 return subOptFn(func(opts *subOpts) error {
2804 opts.cfg.ReplayPolicy = ReplayInstantPolicy
2805 return nil
2806 })
2807 }
2808
2809 // RateLimit is the Bits per sec rate limit applied to a push consumer.
2810 func RateLimit(n uint64) SubOpt {
2811 return subOptFn(func(opts *subOpts) error {
2812 opts.cfg.RateLimit = n
2813 return nil
2814 })
2815 }
2816
2817 // BackOff is an array of time durations that represent the time to delay based on delivery count.
2818 func BackOff(backOff []time.Duration) SubOpt {
2819 return subOptFn(func(opts *subOpts) error {
2820 opts.cfg.BackOff = backOff
2821 return nil
2822 })
2823 }
2824
2825 // BindStream binds a consumer to a stream explicitly based on a name.
2826 // When a stream name is not specified, the library uses the subscribe
2827 // subject as a way to find the stream name. It is done by making a request
2828 // to the server to get list of stream names that have a filter for this
2829 // subject. If the returned list contains a single stream, then this
2830 // stream name will be used, otherwise the `ErrNoMatchingStream` is returned.
2831 // To avoid the stream lookup, provide the stream name with this function.
2832 // See also `Bind()`.
2833 func BindStream(stream string) SubOpt {
2834 return subOptFn(func(opts *subOpts) error {
2835 if opts.stream != _EMPTY_ && opts.stream != stream {
2836 return fmt.Errorf("nats: duplicate stream name (%s and %s)", opts.stream, stream)
2837 }
2838
2839 opts.stream = stream
2840 return nil
2841 })
2842 }
2843
2844 // Bind binds a subscription to an existing consumer from a stream without attempting to create.
2845 // The first argument is the stream name and the second argument will be the consumer name.
2846 func Bind(stream, consumer string) SubOpt {
2847 return subOptFn(func(opts *subOpts) error {
2848 if stream == _EMPTY_ {
2849 return ErrStreamNameRequired
2850 }
2851 if consumer == _EMPTY_ {
2852 return ErrConsumerNameRequired
2853 }
2854
2855 // In case of pull subscribers, the durable name is a required parameter
2856 // so check that they are not different.
2857 if opts.cfg.Durable != _EMPTY_ && opts.cfg.Durable != consumer {
2858 return fmt.Errorf("nats: duplicate consumer names (%s and %s)", opts.cfg.Durable, consumer)
2859 }
2860 if opts.stream != _EMPTY_ && opts.stream != stream {
2861 return fmt.Errorf("nats: duplicate stream name (%s and %s)", opts.stream, stream)
2862 }
2863 opts.stream = stream
2864 opts.consumer = consumer
2865 opts.bound = true
2866 return nil
2867 })
2868 }
2869
2870 // EnableFlowControl enables flow control for a push based consumer.
2871 func EnableFlowControl() SubOpt {
2872 return subOptFn(func(opts *subOpts) error {
2873 opts.cfg.FlowControl = true
2874 return nil
2875 })
2876 }
2877
2878 // IdleHeartbeat enables push based consumers to have idle heartbeats delivered.
2879 // For pull consumers, idle heartbeat has to be set on each [Fetch] call.
2880 func IdleHeartbeat(duration time.Duration) SubOpt {
2881 return subOptFn(func(opts *subOpts) error {
2882 opts.cfg.Heartbeat = duration
2883 return nil
2884 })
2885 }
2886
2887 // DeliverSubject specifies the JetStream consumer deliver subject.
2888 //
2889 // This option is used only in situations where the consumer does not exist
2890 // and a creation request is sent to the server. If not provided, an inbox
2891 // will be selected.
2892 // If a consumer exists, then the NATS subscription will be created on
2893 // the JetStream consumer's DeliverSubject, not necessarily this subject.
2894 func DeliverSubject(subject string) SubOpt {
2895 return subOptFn(func(opts *subOpts) error {
2896 opts.cfg.DeliverSubject = subject
2897 return nil
2898 })
2899 }
2900
2901 // HeadersOnly() will instruct the consumer to only deliver headers and no payloads.
2902 func HeadersOnly() SubOpt {
2903 return subOptFn(func(opts *subOpts) error {
2904 opts.cfg.HeadersOnly = true
2905 return nil
2906 })
2907 }
2908
2909 // MaxRequestBatch sets the maximum pull consumer batch size that a Fetch()
2910 // can request.
2911 func MaxRequestBatch(max int) SubOpt {
2912 return subOptFn(func(opts *subOpts) error {
2913 opts.cfg.MaxRequestBatch = max
2914 return nil
2915 })
2916 }
2917
2918 // MaxRequestExpires sets the maximum pull consumer request expiration that a
2919 // Fetch() can request (using the Fetch's timeout value).
2920 func MaxRequestExpires(max time.Duration) SubOpt {
2921 return subOptFn(func(opts *subOpts) error {
2922 opts.cfg.MaxRequestExpires = max
2923 return nil
2924 })
2925 }
2926
2927 // MaxRequesMaxBytes sets the maximum pull consumer request bytes that a
2928 // Fetch() can receive.
2929 func MaxRequestMaxBytes(bytes int) SubOpt {
2930 return subOptFn(func(opts *subOpts) error {
2931 opts.cfg.MaxRequestMaxBytes = bytes
2932 return nil
2933 })
2934 }
2935
2936 // InactiveThreshold indicates how long the server should keep a consumer
2937 // after detecting a lack of activity. In NATS Server 2.8.4 and earlier, this
2938 // option only applies to ephemeral consumers. In NATS Server 2.9.0 and later,
2939 // this option applies to both ephemeral and durable consumers, allowing durable
2940 // consumers to also be deleted automatically after the inactivity threshold has
2941 // passed.
2942 func InactiveThreshold(threshold time.Duration) SubOpt {
2943 return subOptFn(func(opts *subOpts) error {
2944 if threshold < 0 {
2945 return fmt.Errorf("invalid InactiveThreshold value (%v), needs to be greater or equal to 0", threshold)
2946 }
2947 opts.cfg.InactiveThreshold = threshold
2948 return nil
2949 })
2950 }
2951
2952 // ConsumerReplicas sets the number of replica count for a consumer.
2953 func ConsumerReplicas(replicas int) SubOpt {
2954 return subOptFn(func(opts *subOpts) error {
2955 if replicas < 1 {
2956 return fmt.Errorf("invalid ConsumerReplicas value (%v), needs to be greater than 0", replicas)
2957 }
2958 opts.cfg.Replicas = replicas
2959 return nil
2960 })
2961 }
2962
2963 // ConsumerMemoryStorage sets the memory storage to true for a consumer.
2964 func ConsumerMemoryStorage() SubOpt {
2965 return subOptFn(func(opts *subOpts) error {
2966 opts.cfg.MemoryStorage = true
2967 return nil
2968 })
2969 }
2970
2971 // ConsumerName sets the name for a consumer.
2972 func ConsumerName(name string) SubOpt {
2973 return subOptFn(func(opts *subOpts) error {
2974 opts.cfg.Name = name
2975 return nil
2976 })
2977 }
2978
2979 // ConsumerFilterSubjects can be used to set multiple subject filters on the consumer.
2980 // It has to be used in conjunction with [nats.BindStream] and
2981 // with empty 'subject' parameter.
2982 func ConsumerFilterSubjects(subjects ...string) SubOpt {
2983 return subOptFn(func(opts *subOpts) error {
2984 opts.cfg.FilterSubjects = subjects
2985 return nil
2986 })
2987 }
2988
2989 func (sub *Subscription) ConsumerInfo() (*ConsumerInfo, error) {
2990 sub.mu.Lock()
2991 // TODO(dlc) - Better way to mark especially if we attach.
2992 if sub.jsi == nil {
2993 sub.mu.Unlock()
2994 return nil, ErrTypeSubscription
2995 } else if sub.jsi.consumer == _EMPTY_ {
2996 ordered := sub.jsi.ordered
2997 sub.mu.Unlock()
2998 if ordered {
2999 return nil, ErrConsumerInfoOnOrderedReset
3000 }
3001 return nil, ErrTypeSubscription
3002 }
3003
3004 // Consumer info lookup should fail if in direct mode.
3005 js := sub.jsi.js
3006 stream, consumer := sub.jsi.stream, sub.jsi.consumer
3007 sub.mu.Unlock()
3008
3009 return js.getConsumerInfo(stream, consumer)
3010 }
3011
3012 type pullOpts struct {
3013 maxBytes int
3014 ttl time.Duration
3015 ctx context.Context
3016 hb time.Duration
3017 }
3018
3019 // PullOpt are the options that can be passed when pulling a batch of messages.
3020 type PullOpt interface {
3021 configurePull(opts *pullOpts) error
3022 }
3023
3024 // PullMaxWaiting defines the max inflight pull requests.
3025 func PullMaxWaiting(n int) SubOpt {
3026 return subOptFn(func(opts *subOpts) error {
3027 opts.cfg.MaxWaiting = n
3028 return nil
3029 })
3030 }
3031
3032 type PullHeartbeat time.Duration
3033
3034 func (h PullHeartbeat) configurePull(opts *pullOpts) error {
3035 if h <= 0 {
3036 return fmt.Errorf("%w: idle heartbeat has to be greater than 0", ErrInvalidArg)
3037 }
3038 opts.hb = time.Duration(h)
3039 return nil
3040 }
3041
3042 // PullMaxBytes defines the max bytes allowed for a fetch request.
3043 type PullMaxBytes int
3044
3045 func (n PullMaxBytes) configurePull(opts *pullOpts) error {
3046 opts.maxBytes = int(n)
3047 return nil
3048 }
3049
3050 var (
3051 // errNoMessages is an error that a Fetch request using no_wait can receive to signal
3052 // that there are no more messages available.
3053 errNoMessages = errors.New("nats: no messages")
3054
3055 // errRequestsPending is an error that represents a sub.Fetch requests that was using
3056 // no_wait and expires time got discarded by the server.
3057 errRequestsPending = errors.New("nats: requests pending")
3058 )
3059
3060 // Returns if the given message is a user message or not, and if
3061 // `checkSts` is true, returns appropriate error based on the
3062 // content of the status (404, etc..)
3063 func checkMsg(msg *Msg, checkSts, isNoWait bool) (usrMsg bool, err error) {
3064 // Assume user message
3065 usrMsg = true
3066
3067 // If payload or no header, consider this a user message
3068 if len(msg.Data) > 0 || len(msg.Header) == 0 {
3069 return
3070 }
3071 // Look for status header
3072 val := msg.Header.Get(statusHdr)
3073 // If not present, then this is considered a user message
3074 if val == _EMPTY_ {
3075 return
3076 }
3077 // At this point, this is not a user message since there is
3078 // no payload and a "Status" header.
3079 usrMsg = false
3080
3081 // If we don't care about status, we are done.
3082 if !checkSts {
3083 return
3084 }
3085
3086 // if it's a heartbeat message, report as not user msg
3087 if isHb, _ := isJSControlMessage(msg); isHb {
3088 return
3089 }
3090 switch val {
3091 case noResponders:
3092 err = ErrNoResponders
3093 case noMessagesSts:
3094 // 404 indicates that there are no messages.
3095 err = errNoMessages
3096 case reqTimeoutSts:
3097 // In case of a fetch request with no wait request and expires time,
3098 // need to skip 408 errors and retry.
3099 if isNoWait {
3100 err = errRequestsPending
3101 } else {
3102 // Older servers may send a 408 when a request in the server was expired
3103 // and interest is still found, which will be the case for our
3104 // implementation. Regardless, ignore 408 errors until receiving at least
3105 // one message when making requests without no_wait.
3106 err = ErrTimeout
3107 }
3108 case jetStream409Sts:
3109 if strings.Contains(strings.ToLower(msg.Header.Get(descrHdr)), "consumer deleted") {
3110 err = ErrConsumerDeleted
3111 break
3112 }
3113
3114 if strings.Contains(strings.ToLower(msg.Header.Get(descrHdr)), "leadership change") {
3115 err = ErrConsumerLeadershipChanged
3116 break
3117 }
3118 fallthrough
3119 default:
3120 err = fmt.Errorf("nats: %s", msg.Header.Get(descrHdr))
3121 }
3122 return
3123 }
3124
3125 // Fetch pulls a batch of messages from a stream for a pull consumer.
3126 func (sub *Subscription) Fetch(batch int, opts ...PullOpt) ([]*Msg, error) {
3127 if sub == nil {
3128 return nil, ErrBadSubscription
3129 }
3130 if batch < 1 {
3131 return nil, ErrInvalidArg
3132 }
3133
3134 var o pullOpts
3135 for _, opt := range opts {
3136 if err := opt.configurePull(&o); err != nil {
3137 return nil, err
3138 }
3139 }
3140 if o.ctx != nil && o.ttl != 0 {
3141 return nil, ErrContextAndTimeout
3142 }
3143
3144 sub.mu.Lock()
3145 jsi := sub.jsi
3146 // Reject if this is not a pull subscription. Note that sub.typ is SyncSubscription,
3147 // so check for jsi.pull boolean instead.
3148 if jsi == nil || !jsi.pull {
3149 sub.mu.Unlock()
3150 return nil, ErrTypeSubscription
3151 }
3152
3153 nc := sub.conn
3154 nms := sub.jsi.nms
3155 rply, _ := newFetchInbox(jsi.deliver)
3156 js := sub.jsi.js
3157 pmc := len(sub.mch) > 0
3158
3159 // All fetch requests have an expiration, in case of no explicit expiration
3160 // then the default timeout of the JetStream context is used.
3161 ttl := o.ttl
3162 if ttl == 0 {
3163 ttl = js.opts.wait
3164 }
3165 sub.mu.Unlock()
3166
3167 // Use the given context or setup a default one for the span
3168 // of the pull batch request.
3169 var (
3170 ctx = o.ctx
3171 err error
3172 cancel context.CancelFunc
3173 )
3174 if ctx == nil {
3175 ctx, cancel = context.WithTimeout(context.Background(), ttl)
3176 } else if _, hasDeadline := ctx.Deadline(); !hasDeadline {
3177 // Prevent from passing the background context which will just block
3178 // and cannot be canceled either.
3179 if octx, ok := ctx.(ContextOpt); ok && octx.Context == context.Background() {
3180 return nil, ErrNoDeadlineContext
3181 }
3182
3183 // If the context did not have a deadline, then create a new child context
3184 // that will use the default timeout from the JS context.
3185 ctx, cancel = context.WithTimeout(ctx, ttl)
3186 } else {
3187 ctx, cancel = context.WithCancel(ctx)
3188 }
3189 defer cancel()
3190
3191 // if heartbeat is set, validate it against the context timeout
3192 if o.hb > 0 {
3193 deadline, _ := ctx.Deadline()
3194 if 2*o.hb >= time.Until(deadline) {
3195 return nil, fmt.Errorf("%w: idle heartbeat value too large", ErrInvalidArg)
3196 }
3197 }
3198
3199 // Check if context not done already before making the request.
3200 select {
3201 case <-ctx.Done():
3202 if o.ctx != nil { // Timeout or Cancel triggered by context object option
3203 err = ctx.Err()
3204 } else { // Timeout triggered by timeout option
3205 err = ErrTimeout
3206 }
3207 default:
3208 }
3209 if err != nil {
3210 return nil, err
3211 }
3212
3213 var (
3214 msgs = make([]*Msg, 0, batch)
3215 msg *Msg
3216 )
3217 for pmc && len(msgs) < batch {
3218 // Check next msg with booleans that say that this is an internal call
3219 // for a pull subscribe (so don't reject it) and don't wait if there
3220 // are no messages.
3221 msg, err = sub.nextMsgWithContext(ctx, true, false)
3222 if err != nil {
3223 if errors.Is(err, errNoMessages) {
3224 err = nil
3225 }
3226 break
3227 }
3228 // Check msg but just to determine if this is a user message
3229 // or status message, however, we don't care about values of status
3230 // messages at this point in the Fetch() call, so checkMsg can't
3231 // return an error.
3232 if usrMsg, _ := checkMsg(msg, false, false); usrMsg {
3233 msgs = append(msgs, msg)
3234 }
3235 }
3236 var hbTimer *time.Timer
3237 defer func() {
3238 if hbTimer != nil {
3239 hbTimer.Stop()
3240 }
3241 }()
3242 var hbErr error
3243 sub.mu.Lock()
3244 subClosed := sub.closed || sub.draining
3245 sub.mu.Unlock()
3246 if subClosed {
3247 err = errors.Join(ErrBadSubscription, ErrSubscriptionClosed)
3248 }
3249 hbLock := sync.Mutex{}
3250 var disconnected atomic.Bool
3251 if err == nil && len(msgs) < batch && !subClosed {
3252 // For batch real size of 1, it does not make sense to set no_wait in
3253 // the request.
3254 noWait := batch-len(msgs) > 1
3255
3256 var nr nextRequest
3257
3258 sendReq := func() error {
3259 // The current deadline for the context will be used
3260 // to set the expires TTL for a fetch request.
3261 deadline, _ := ctx.Deadline()
3262 ttl = time.Until(deadline)
3263
3264 // Check if context has already been canceled or expired.
3265 select {
3266 case <-ctx.Done():
3267 return ctx.Err()
3268 default:
3269 }
3270
3271 // Make our request expiration a bit shorter than the current timeout.
3272 expiresDiff := min(time.Duration(float64(ttl)*0.1), 5*time.Second)
3273 expires := ttl - expiresDiff
3274
3275 nr.Batch = batch - len(msgs)
3276 nr.Expires = expires
3277 nr.NoWait = noWait
3278 nr.MaxBytes = o.maxBytes
3279 if 2*o.hb < expires {
3280 nr.Heartbeat = o.hb
3281 } else {
3282 nr.Heartbeat = 0
3283 }
3284 req, _ := json.Marshal(nr)
3285 if err := nc.PublishRequest(nms, rply, req); err != nil {
3286 return err
3287 }
3288 if o.hb > 0 {
3289 if hbTimer == nil {
3290 hbTimer = time.AfterFunc(2*o.hb, func() {
3291 hbLock.Lock()
3292 hbErr = ErrNoHeartbeat
3293 hbLock.Unlock()
3294 cancel()
3295 })
3296 } else {
3297 hbTimer.Reset(2 * o.hb)
3298 }
3299 }
3300 return nil
3301 }
3302 connStatusChanged := nc.StatusChanged()
3303 go func() {
3304 select {
3305 case <-ctx.Done():
3306 case <-connStatusChanged:
3307 disconnected.Store(true)
3308 cancel()
3309 }
3310 nc.RemoveStatusListener(connStatusChanged)
3311 }()
3312 err = sendReq()
3313 for err == nil && len(msgs) < batch {
3314 // Ask for next message and wait if there are no messages
3315 msg, err = sub.nextMsgWithContext(ctx, true, true)
3316 if err == nil {
3317 if hbTimer != nil {
3318 hbTimer.Reset(2 * o.hb)
3319 }
3320 var usrMsg bool
3321
3322 usrMsg, err = checkMsg(msg, true, noWait)
3323 if err == nil && usrMsg {
3324 msgs = append(msgs, msg)
3325 } else if noWait && (errors.Is(err, errNoMessages) || errors.Is(err, errRequestsPending)) && len(msgs) == 0 {
3326 // If we have a 404/408 for our "no_wait" request and have
3327 // not collected any message, then resend request to
3328 // wait this time.
3329 noWait = false
3330 err = sendReq()
3331 } else if errors.Is(err, ErrTimeout) && len(msgs) == 0 {
3332 // If we get a 408, we will bail if we already collected some
3333 // messages, otherwise ignore and go back calling nextMsg.
3334 err = nil
3335 }
3336 }
3337 }
3338 }
3339 // If there is at least a message added to msgs, then need to return OK and no error
3340 if err != nil && len(msgs) == 0 {
3341 hbLock.Lock()
3342 defer hbLock.Unlock()
3343 if hbErr != nil {
3344 return nil, hbErr
3345 }
3346 if disconnected.Load() {
3347 return nil, ErrFetchDisconnected
3348 }
3349 return nil, o.checkCtxErr(err)
3350 }
3351 return msgs, nil
3352 }
3353
3354 // newFetchInbox returns subject used as reply subject when sending pull requests
3355 // as well as request ID. For non-wildcard subject, request ID is empty and
3356 // passed subject is not transformed
3357 func newFetchInbox(subj string) (string, string) {
3358 if !strings.HasSuffix(subj, ".*") {
3359 return subj, ""
3360 }
3361 reqID := nuid.Next()
3362 var sb strings.Builder
3363 sb.Grow(len(subj) - 1 + nuidSize)
3364 sb.WriteString(subj[:len(subj)-1])
3365 sb.WriteString(reqID)
3366 return sb.String(), reqID
3367 }
3368
3369 func subjectMatchesReqID(subject, reqID string) bool {
3370 subjectParts := strings.Split(subject, ".")
3371 if len(subjectParts) < 2 {
3372 return false
3373 }
3374 return subjectParts[len(subjectParts)-1] == reqID
3375 }
3376
3377 // MessageBatch provides methods to retrieve messages consumed using [Subscribe.FetchBatch].
3378 type MessageBatch interface {
3379 // Messages returns a channel on which messages will be published.
3380 Messages() <-chan *Msg
3381
3382 // Error returns an error encountered when fetching messages.
3383 Error() error
3384
3385 // Done signals end of execution.
3386 Done() <-chan struct{}
3387 }
3388
3389 type messageBatch struct {
3390 sync.Mutex
3391 msgs chan *Msg
3392 err error
3393 done chan struct{}
3394 }
3395
3396 func (mb *messageBatch) Messages() <-chan *Msg {
3397 mb.Lock()
3398 defer mb.Unlock()
3399 return mb.msgs
3400 }
3401
3402 func (mb *messageBatch) Error() error {
3403 mb.Lock()
3404 defer mb.Unlock()
3405 return mb.err
3406 }
3407
3408 func (mb *messageBatch) Done() <-chan struct{} {
3409 mb.Lock()
3410 defer mb.Unlock()
3411 return mb.done
3412 }
3413
3414 // FetchBatch pulls a batch of messages from a stream for a pull consumer.
3415 // Unlike [Subscription.Fetch], it is non blocking and returns [MessageBatch],
3416 // allowing to retrieve incoming messages from a channel.
3417 // The returned channel is always closed after all messages for a batch have been
3418 // delivered by the server - it is safe to iterate over it using range.
3419 //
3420 // To avoid using default JetStream timeout as fetch expiry time, use [nats.MaxWait]
3421 // or [nats.Context] (with deadline set).
3422 //
3423 // This method will not return error in case of pull request expiry (even if there are no messages).
3424 // Any other error encountered when receiving messages will cause FetchBatch to stop receiving new messages.
3425 func (sub *Subscription) FetchBatch(batch int, opts ...PullOpt) (MessageBatch, error) {
3426 if sub == nil {
3427 return nil, ErrBadSubscription
3428 }
3429 if batch < 1 {
3430 return nil, ErrInvalidArg
3431 }
3432
3433 var o pullOpts
3434 for _, opt := range opts {
3435 if err := opt.configurePull(&o); err != nil {
3436 return nil, err
3437 }
3438 }
3439 if o.ctx != nil && o.ttl != 0 {
3440 return nil, ErrContextAndTimeout
3441 }
3442 sub.mu.Lock()
3443 jsi := sub.jsi
3444 // Reject if this is not a pull subscription. Note that sub.typ is SyncSubscription,
3445 // so check for jsi.pull boolean instead.
3446 if jsi == nil || !jsi.pull {
3447 sub.mu.Unlock()
3448 return nil, ErrTypeSubscription
3449 }
3450
3451 nc := sub.conn
3452 nms := sub.jsi.nms
3453 rply, reqID := newFetchInbox(sub.jsi.deliver)
3454 js := sub.jsi.js
3455 pmc := len(sub.mch) > 0
3456
3457 // All fetch requests have an expiration, in case of no explicit expiration
3458 // then the default timeout of the JetStream context is used.
3459 ttl := o.ttl
3460 if ttl == 0 {
3461 ttl = js.opts.wait
3462 }
3463 sub.mu.Unlock()
3464
3465 // Use the given context or setup a default one for the span
3466 // of the pull batch request.
3467 var (
3468 ctx = o.ctx
3469 cancel context.CancelFunc
3470 cancelContext = true
3471 )
3472 if ctx == nil {
3473 ctx, cancel = context.WithTimeout(context.Background(), ttl)
3474 } else if _, hasDeadline := ctx.Deadline(); !hasDeadline {
3475 // Prevent from passing the background context which will just block
3476 // and cannot be canceled either.
3477 if octx, ok := ctx.(ContextOpt); ok && octx.Context == context.Background() {
3478 return nil, ErrNoDeadlineContext
3479 }
3480
3481 // If the context did not have a deadline, then create a new child context
3482 // that will use the default timeout from the JS context.
3483 ctx, cancel = context.WithTimeout(ctx, ttl)
3484 } else {
3485 ctx, cancel = context.WithCancel(ctx)
3486 }
3487 defer func() {
3488 // only cancel the context here if we are sure the fetching goroutine has not been started yet
3489 if cancelContext {
3490 cancel()
3491 }
3492 }()
3493
3494 // if heartbeat is set, validate it against the context timeout
3495 if o.hb > 0 {
3496 deadline, _ := ctx.Deadline()
3497 if 2*o.hb >= time.Until(deadline) {
3498 return nil, fmt.Errorf("%w: idle heartbeat value too large", ErrInvalidArg)
3499 }
3500 }
3501
3502 // Check if context not done already before making the request.
3503 select {
3504 case <-ctx.Done():
3505 if o.ctx != nil { // Timeout or Cancel triggered by context object option
3506 return nil, ctx.Err()
3507 } else { // Timeout triggered by timeout option
3508 return nil, ErrTimeout
3509 }
3510 default:
3511 }
3512
3513 result := &messageBatch{
3514 msgs: make(chan *Msg, batch),
3515 done: make(chan struct{}, 1),
3516 }
3517 var msg *Msg
3518 for pmc && len(result.msgs) < batch {
3519 // Check next msg with booleans that say that this is an internal call
3520 // for a pull subscribe (so don't reject it) and don't wait if there
3521 // are no messages.
3522 msg, err := sub.nextMsgWithContext(ctx, true, false)
3523 if err != nil {
3524 if errors.Is(err, errNoMessages) {
3525 err = nil
3526 }
3527 result.err = err
3528 break
3529 }
3530 // Check msg but just to determine if this is a user message
3531 // or status message, however, we don't care about values of status
3532 // messages at this point in the Fetch() call, so checkMsg can't
3533 // return an error.
3534 if usrMsg, _ := checkMsg(msg, false, false); usrMsg {
3535 result.msgs <- msg
3536 }
3537 }
3538 sub.mu.Lock()
3539 subClosed := sub.closed || sub.draining
3540 sub.mu.Unlock()
3541 if len(result.msgs) == batch || result.err != nil || subClosed {
3542 close(result.msgs)
3543 if subClosed && len(result.msgs) == 0 {
3544 return nil, errors.Join(ErrBadSubscription, ErrSubscriptionClosed)
3545 }
3546 result.done <- struct{}{}
3547 return result, nil
3548 }
3549
3550 deadline, _ := ctx.Deadline()
3551 ttl = time.Until(deadline)
3552
3553 // Make our request expiration a bit shorter than the current timeout.
3554 expiresDiff := min(time.Duration(float64(ttl)*0.1), 5*time.Second)
3555 expires := ttl - expiresDiff
3556
3557 connStatusChanged := nc.StatusChanged()
3558 var disconnected atomic.Bool
3559 go func() {
3560 select {
3561 case <-ctx.Done():
3562 case <-connStatusChanged:
3563 disconnected.Store(true)
3564 cancel()
3565 }
3566 nc.RemoveStatusListener(connStatusChanged)
3567 }()
3568 requestBatch := batch - len(result.msgs)
3569 req := nextRequest{
3570 Expires: expires,
3571 Batch: requestBatch,
3572 MaxBytes: o.maxBytes,
3573 Heartbeat: o.hb,
3574 }
3575 reqJSON, err := json.Marshal(req)
3576 if err != nil {
3577 close(result.msgs)
3578 result.done <- struct{}{}
3579 result.err = err
3580 return result, nil
3581 }
3582 if err := nc.PublishRequest(nms, rply, reqJSON); err != nil {
3583 if len(result.msgs) == 0 {
3584 return nil, err
3585 }
3586 close(result.msgs)
3587 result.done <- struct{}{}
3588 result.err = err
3589 return result, nil
3590 }
3591 var hbTimer *time.Timer
3592 defer func() {
3593 if hbTimer != nil {
3594 hbTimer.Stop()
3595 }
3596 }()
3597 var hbErr error
3598 if o.hb > 0 {
3599 hbTimer = time.AfterFunc(2*o.hb, func() {
3600 result.Lock()
3601 hbErr = ErrNoHeartbeat
3602 result.Unlock()
3603 cancel()
3604 })
3605 }
3606 cancelContext = false
3607 go func() {
3608 defer cancel()
3609 var requestMsgs int
3610 for requestMsgs < requestBatch {
3611 // Ask for next message and wait if there are no messages
3612 msg, err = sub.nextMsgWithContext(ctx, true, true)
3613 if err != nil {
3614 break
3615 }
3616 if hbTimer != nil {
3617 hbTimer.Reset(2 * o.hb)
3618 }
3619 var usrMsg bool
3620
3621 usrMsg, err = checkMsg(msg, true, false)
3622 if err != nil {
3623 if errors.Is(err, ErrTimeout) {
3624 if reqID != "" && !subjectMatchesReqID(msg.Subject, reqID) {
3625 // ignore timeout message from server if it comes from a different pull request
3626 continue
3627 }
3628 err = nil
3629 }
3630 break
3631 }
3632 if usrMsg {
3633 result.Lock()
3634 result.msgs <- msg
3635 result.Unlock()
3636 requestMsgs++
3637 }
3638 }
3639 if err != nil {
3640 result.Lock()
3641 if hbErr != nil {
3642 result.err = hbErr
3643 } else if disconnected.Load() {
3644 result.err = ErrFetchDisconnected
3645 } else {
3646 result.err = o.checkCtxErr(err)
3647 }
3648 result.Unlock()
3649 }
3650 close(result.msgs)
3651 result.Lock()
3652 result.done <- struct{}{}
3653 result.Unlock()
3654 }()
3655 return result, nil
3656 }
3657
3658 // checkCtxErr is used to determine whether ErrTimeout should be returned in case of context timeout
3659 func (o *pullOpts) checkCtxErr(err error) error {
3660 if o.ctx == nil && errors.Is(err, context.DeadlineExceeded) {
3661 return ErrTimeout
3662 }
3663 return err
3664 }
3665
3666 func (js *js) getConsumerInfo(stream, consumer string) (*ConsumerInfo, error) {
3667 ctx, cancel := context.WithTimeout(context.Background(), js.opts.wait)
3668 defer cancel()
3669 return js.getConsumerInfoContext(ctx, stream, consumer, js.opts)
3670 }
3671
3672 func (js *js) getConsumerInfoContext(ctx context.Context, stream, consumer string, o *jsOpts) (*ConsumerInfo, error) {
3673 ccInfoSubj := fmt.Sprintf(apiConsumerInfoT, stream, consumer)
3674 resp, err := js.apiRequestWithContext(ctx, o.apiSubj(ccInfoSubj), nil)
3675 if err != nil {
3676 if errors.Is(err, ErrNoResponders) {
3677 err = ErrJetStreamNotEnabled
3678 }
3679 return nil, err
3680 }
3681
3682 var info consumerResponse
3683 if err := json.Unmarshal(resp.Data, &info); err != nil {
3684 return nil, err
3685 }
3686 if info.Error != nil {
3687 if errors.Is(info.Error, ErrConsumerNotFound) {
3688 return nil, ErrConsumerNotFound
3689 }
3690 if errors.Is(info.Error, ErrStreamNotFound) {
3691 return nil, ErrStreamNotFound
3692 }
3693 return nil, info.Error
3694 }
3695 if info.Error == nil && info.ConsumerInfo == nil {
3696 return nil, ErrConsumerNotFound
3697 }
3698 return info.ConsumerInfo, nil
3699 }
3700
3701 // a RequestWithContext with tracing via TraceCB
3702 func (js *js) apiRequestWithContext(ctx context.Context, subj string, data []byte) (*Msg, error) {
3703 if js.opts.shouldTrace {
3704 ctrace := js.opts.ctrace
3705 if ctrace.RequestSent != nil {
3706 ctrace.RequestSent(subj, data)
3707 }
3708 }
3709 resp, err := js.nc.RequestWithContext(ctx, subj, data)
3710 if err != nil {
3711 return nil, err
3712 }
3713 if js.opts.shouldTrace {
3714 ctrace := js.opts.ctrace
3715 if ctrace.ResponseReceived != nil {
3716 ctrace.ResponseReceived(subj, resp.Data, resp.Header)
3717 }
3718 }
3719
3720 return resp, nil
3721 }
3722
3723 func (m *Msg) checkReply() error {
3724 if m == nil || m.Sub == nil {
3725 return ErrMsgNotBound
3726 }
3727 if m.Reply == _EMPTY_ {
3728 return ErrMsgNoReply
3729 }
3730 return nil
3731 }
3732
3733 // ackReply handles all acks. Will do the right thing for pull and sync mode.
3734 // It ensures that an ack is only sent a single time, regardless of
3735 // how many times it is being called to avoid duplicated acks.
3736 func (m *Msg) ackReply(ackType []byte, sync bool, opts ...AckOpt) error {
3737 var o ackOpts
3738 for _, opt := range opts {
3739 if err := opt.configureAck(&o); err != nil {
3740 return err
3741 }
3742 }
3743
3744 if err := m.checkReply(); err != nil {
3745 return err
3746 }
3747
3748 var ackNone bool
3749 var js *js
3750
3751 sub := m.Sub
3752 sub.mu.Lock()
3753 nc := sub.conn
3754 if jsi := sub.jsi; jsi != nil {
3755 js = jsi.js
3756 ackNone = jsi.ackNone
3757 }
3758 sub.mu.Unlock()
3759
3760 // Skip if already acked.
3761 if atomic.LoadUint32(&m.ackd) == 1 {
3762 return ErrMsgAlreadyAckd
3763 }
3764 if ackNone {
3765 return ErrCantAckIfConsumerAckNone
3766 }
3767
3768 usesCtx := o.ctx != nil
3769 usesWait := o.ttl > 0
3770
3771 // Only allow either AckWait or Context option to set the timeout.
3772 if usesWait && usesCtx {
3773 return ErrContextAndTimeout
3774 }
3775
3776 sync = sync || usesCtx || usesWait
3777 ctx := o.ctx
3778 wait := defaultRequestWait
3779 if usesWait {
3780 wait = o.ttl
3781 } else if js != nil {
3782 wait = js.opts.wait
3783 }
3784
3785 var body []byte
3786 var err error
3787 // This will be > 0 only when called from NakWithDelay()
3788 if o.nakDelay > 0 {
3789 body = []byte(fmt.Sprintf("%s {\"delay\": %d}", ackType, o.nakDelay.Nanoseconds()))
3790 } else {
3791 body = ackType
3792 }
3793
3794 if sync {
3795 if usesCtx {
3796 _, err = nc.RequestWithContext(ctx, m.Reply, body)
3797 } else {
3798 _, err = nc.Request(m.Reply, body, wait)
3799 }
3800 } else {
3801 err = nc.Publish(m.Reply, body)
3802 }
3803
3804 // Mark that the message has been acked unless it is ackProgress
3805 // which can be sent many times.
3806 if err == nil && !bytes.Equal(ackType, ackProgress) {
3807 atomic.StoreUint32(&m.ackd, 1)
3808 }
3809
3810 return err
3811 }
3812
3813 // Ack acknowledges a message. This tells the server that the message was
3814 // successfully processed and it can move on to the next message.
3815 func (m *Msg) Ack(opts ...AckOpt) error {
3816 return m.ackReply(ackAck, false, opts...)
3817 }
3818
3819 // AckSync is the synchronous version of Ack. This indicates successful message
3820 // processing.
3821 func (m *Msg) AckSync(opts ...AckOpt) error {
3822 return m.ackReply(ackAck, true, opts...)
3823 }
3824
3825 // Nak negatively acknowledges a message. This tells the server to redeliver
3826 // the message. You can configure the number of redeliveries by passing
3827 // nats.MaxDeliver when you Subscribe. The default is infinite redeliveries.
3828 func (m *Msg) Nak(opts ...AckOpt) error {
3829 return m.ackReply(ackNak, false, opts...)
3830 }
3831
3832 // Nak negatively acknowledges a message. This tells the server to redeliver
3833 // the message after the give `delay` duration. You can configure the number
3834 // of redeliveries by passing nats.MaxDeliver when you Subscribe.
3835 // The default is infinite redeliveries.
3836 func (m *Msg) NakWithDelay(delay time.Duration, opts ...AckOpt) error {
3837 if delay > 0 {
3838 opts = append(opts, nakDelay(delay))
3839 }
3840 return m.ackReply(ackNak, false, opts...)
3841 }
3842
3843 // Term tells the server to not redeliver this message, regardless of the value
3844 // of nats.MaxDeliver.
3845 func (m *Msg) Term(opts ...AckOpt) error {
3846 return m.ackReply(ackTerm, false, opts...)
3847 }
3848
3849 // InProgress tells the server that this message is being worked on. It resets
3850 // the redelivery timer on the server.
3851 func (m *Msg) InProgress(opts ...AckOpt) error {
3852 return m.ackReply(ackProgress, false, opts...)
3853 }
3854
3855 // MsgMetadata is the JetStream metadata associated with received messages.
3856 type MsgMetadata struct {
3857 Sequence SequencePair
3858 NumDelivered uint64
3859 NumPending uint64
3860 Timestamp time.Time
3861 Stream string
3862 Consumer string
3863 Domain string
3864 }
3865
3866 // Metadata retrieves the metadata from a JetStream message. This method will
3867 // return an error for non-JetStream Msgs.
3868 func (m *Msg) Metadata() (*MsgMetadata, error) {
3869 if err := m.checkReply(); err != nil {
3870 return nil, err
3871 }
3872
3873 tokens, err := parser.GetMetadataFields(m.Reply)
3874 if err != nil {
3875 return nil, err
3876 }
3877
3878 meta := &MsgMetadata{
3879 Domain: tokens[parser.AckDomainTokenPos],
3880 NumDelivered: parser.ParseNum(tokens[parser.AckNumDeliveredTokenPos]),
3881 NumPending: parser.ParseNum(tokens[parser.AckNumPendingTokenPos]),
3882 Timestamp: time.Unix(0, int64(parser.ParseNum(tokens[parser.AckTimestampSeqTokenPos]))),
3883 Stream: tokens[parser.AckStreamTokenPos],
3884 Consumer: tokens[parser.AckConsumerTokenPos],
3885 }
3886 meta.Sequence.Stream = parser.ParseNum(tokens[parser.AckStreamSeqTokenPos])
3887 meta.Sequence.Consumer = parser.ParseNum(tokens[parser.AckConsumerSeqTokenPos])
3888 return meta, nil
3889 }
3890
3891 // AckPolicy determines how the consumer should acknowledge delivered messages.
3892 type AckPolicy int
3893
3894 const (
3895 // AckNonePolicy requires no acks for delivered messages.
3896 AckNonePolicy AckPolicy = iota
3897
3898 // AckAllPolicy when acking a sequence number, this implicitly acks all
3899 // sequences below this one as well.
3900 AckAllPolicy
3901
3902 // AckExplicitPolicy requires ack or nack for all messages.
3903 AckExplicitPolicy
3904
3905 // AckFlowControlPolicy functions like AckAllPolicy, but acks based on
3906 // responses to flow control. Used by durable stream sourcing and
3907 // mirroring against an existing durable push consumer.
3908 //
3909 // This feature requires nats-server v2.14.0 or later.
3910 AckFlowControlPolicy
3911
3912 // For configuration mismatch check
3913 ackPolicyNotSet = 99
3914 )
3915
3916 func jsonString(s string) string {
3917 return "\"" + s + "\""
3918 }
3919
3920 func (p *AckPolicy) UnmarshalJSON(data []byte) error {
3921 switch string(data) {
3922 case jsonString("none"):
3923 *p = AckNonePolicy
3924 case jsonString("all"):
3925 *p = AckAllPolicy
3926 case jsonString("explicit"):
3927 *p = AckExplicitPolicy
3928 case jsonString("flow_control"):
3929 *p = AckFlowControlPolicy
3930 default:
3931 return fmt.Errorf("nats: can not unmarshal %q", data)
3932 }
3933
3934 return nil
3935 }
3936
3937 func (p AckPolicy) MarshalJSON() ([]byte, error) {
3938 switch p {
3939 case AckNonePolicy:
3940 return json.Marshal("none")
3941 case AckAllPolicy:
3942 return json.Marshal("all")
3943 case AckExplicitPolicy:
3944 return json.Marshal("explicit")
3945 case AckFlowControlPolicy:
3946 return json.Marshal("flow_control")
3947 default:
3948 return nil, fmt.Errorf("nats: unknown acknowledgement policy %v", p)
3949 }
3950 }
3951
3952 func (p AckPolicy) String() string {
3953 switch p {
3954 case AckNonePolicy:
3955 return "AckNone"
3956 case AckAllPolicy:
3957 return "AckAll"
3958 case AckExplicitPolicy:
3959 return "AckExplicit"
3960 case AckFlowControlPolicy:
3961 return "AckFlowControl"
3962 case ackPolicyNotSet:
3963 return "Not Initialized"
3964 default:
3965 return "Unknown AckPolicy"
3966 }
3967 }
3968
3969 // ReplayPolicy determines how the consumer should replay messages it already has queued in the stream.
3970 type ReplayPolicy int
3971
3972 const (
3973 // ReplayInstantPolicy will replay messages as fast as possible.
3974 ReplayInstantPolicy ReplayPolicy = iota
3975
3976 // ReplayOriginalPolicy will maintain the same timing as the messages were received.
3977 ReplayOriginalPolicy
3978
3979 // For configuration mismatch check
3980 replayPolicyNotSet = 99
3981 )
3982
3983 func (p *ReplayPolicy) UnmarshalJSON(data []byte) error {
3984 switch string(data) {
3985 case jsonString("instant"):
3986 *p = ReplayInstantPolicy
3987 case jsonString("original"):
3988 *p = ReplayOriginalPolicy
3989 default:
3990 return fmt.Errorf("nats: can not unmarshal %q", data)
3991 }
3992
3993 return nil
3994 }
3995
3996 func (p ReplayPolicy) MarshalJSON() ([]byte, error) {
3997 switch p {
3998 case ReplayOriginalPolicy:
3999 return json.Marshal("original")
4000 case ReplayInstantPolicy:
4001 return json.Marshal("instant")
4002 default:
4003 return nil, fmt.Errorf("nats: unknown replay policy %v", p)
4004 }
4005 }
4006
4007 var (
4008 ackAck = []byte("+ACK")
4009 ackNak = []byte("-NAK")
4010 ackProgress = []byte("+WPI")
4011 ackTerm = []byte("+TERM")
4012 )
4013
4014 // DeliverPolicy determines how the consumer should select the first message to deliver.
4015 type DeliverPolicy int
4016
4017 const (
4018 // DeliverAllPolicy starts delivering messages from the very beginning of a
4019 // stream. This is the default.
4020 DeliverAllPolicy DeliverPolicy = iota
4021
4022 // DeliverLastPolicy will start the consumer with the last sequence
4023 // received.
4024 DeliverLastPolicy
4025
4026 // DeliverNewPolicy will only deliver new messages that are sent after the
4027 // consumer is created.
4028 DeliverNewPolicy
4029
4030 // DeliverByStartSequencePolicy will deliver messages starting from a given
4031 // sequence.
4032 DeliverByStartSequencePolicy
4033
4034 // DeliverByStartTimePolicy will deliver messages starting from a given
4035 // time.
4036 DeliverByStartTimePolicy
4037
4038 // DeliverLastPerSubjectPolicy will start the consumer with the last message
4039 // for all subjects received.
4040 DeliverLastPerSubjectPolicy
4041
4042 // For configuration mismatch check
4043 deliverPolicyNotSet = 99
4044 )
4045
4046 func (p *DeliverPolicy) UnmarshalJSON(data []byte) error {
4047 switch string(data) {
4048 case jsonString("all"), jsonString("undefined"):
4049 *p = DeliverAllPolicy
4050 case jsonString("last"):
4051 *p = DeliverLastPolicy
4052 case jsonString("new"):
4053 *p = DeliverNewPolicy
4054 case jsonString("by_start_sequence"):
4055 *p = DeliverByStartSequencePolicy
4056 case jsonString("by_start_time"):
4057 *p = DeliverByStartTimePolicy
4058 case jsonString("last_per_subject"):
4059 *p = DeliverLastPerSubjectPolicy
4060 }
4061
4062 return nil
4063 }
4064
4065 func (p DeliverPolicy) MarshalJSON() ([]byte, error) {
4066 switch p {
4067 case DeliverAllPolicy:
4068 return json.Marshal("all")
4069 case DeliverLastPolicy:
4070 return json.Marshal("last")
4071 case DeliverNewPolicy:
4072 return json.Marshal("new")
4073 case DeliverByStartSequencePolicy:
4074 return json.Marshal("by_start_sequence")
4075 case DeliverByStartTimePolicy:
4076 return json.Marshal("by_start_time")
4077 case DeliverLastPerSubjectPolicy:
4078 return json.Marshal("last_per_subject")
4079 default:
4080 return nil, fmt.Errorf("nats: unknown deliver policy %v", p)
4081 }
4082 }
4083
4084 // RetentionPolicy determines how messages in a set are retained.
4085 type RetentionPolicy int
4086
4087 const (
4088 // LimitsPolicy (default) means that messages are retained until any given limit is reached.
4089 // This could be one of MaxMsgs, MaxBytes, or MaxAge.
4090 LimitsPolicy RetentionPolicy = iota
4091 // InterestPolicy specifies that when all known observables have acknowledged a message it can be removed.
4092 InterestPolicy
4093 // WorkQueuePolicy specifies that when the first worker or subscriber acknowledges the message it can be removed.
4094 WorkQueuePolicy
4095 )
4096
4097 // DiscardPolicy determines how to proceed when limits of messages or bytes are
4098 // reached.
4099 type DiscardPolicy int
4100
4101 const (
4102 // DiscardOld will remove older messages to return to the limits. This is
4103 // the default.
4104 DiscardOld DiscardPolicy = iota
4105 //DiscardNew will fail to store new messages.
4106 DiscardNew
4107 )
4108
4109 const (
4110 limitsPolicyString = "limits"
4111 interestPolicyString = "interest"
4112 workQueuePolicyString = "workqueue"
4113 )
4114
4115 func (rp RetentionPolicy) String() string {
4116 switch rp {
4117 case LimitsPolicy:
4118 return "Limits"
4119 case InterestPolicy:
4120 return "Interest"
4121 case WorkQueuePolicy:
4122 return "WorkQueue"
4123 default:
4124 return "Unknown Retention Policy"
4125 }
4126 }
4127
4128 func (rp RetentionPolicy) MarshalJSON() ([]byte, error) {
4129 switch rp {
4130 case LimitsPolicy:
4131 return json.Marshal(limitsPolicyString)
4132 case InterestPolicy:
4133 return json.Marshal(interestPolicyString)
4134 case WorkQueuePolicy:
4135 return json.Marshal(workQueuePolicyString)
4136 default:
4137 return nil, fmt.Errorf("nats: can not marshal %v", rp)
4138 }
4139 }
4140
4141 func (rp *RetentionPolicy) UnmarshalJSON(data []byte) error {
4142 switch string(data) {
4143 case jsonString(limitsPolicyString):
4144 *rp = LimitsPolicy
4145 case jsonString(interestPolicyString):
4146 *rp = InterestPolicy
4147 case jsonString(workQueuePolicyString):
4148 *rp = WorkQueuePolicy
4149 default:
4150 return fmt.Errorf("nats: can not unmarshal %q", data)
4151 }
4152 return nil
4153 }
4154
4155 func (dp DiscardPolicy) String() string {
4156 switch dp {
4157 case DiscardOld:
4158 return "DiscardOld"
4159 case DiscardNew:
4160 return "DiscardNew"
4161 default:
4162 return "Unknown Discard Policy"
4163 }
4164 }
4165
4166 func (dp DiscardPolicy) MarshalJSON() ([]byte, error) {
4167 switch dp {
4168 case DiscardOld:
4169 return json.Marshal("old")
4170 case DiscardNew:
4171 return json.Marshal("new")
4172 default:
4173 return nil, fmt.Errorf("nats: can not marshal %v", dp)
4174 }
4175 }
4176
4177 func (dp *DiscardPolicy) UnmarshalJSON(data []byte) error {
4178 switch strings.ToLower(string(data)) {
4179 case jsonString("old"):
4180 *dp = DiscardOld
4181 case jsonString("new"):
4182 *dp = DiscardNew
4183 default:
4184 return fmt.Errorf("nats: can not unmarshal %q", data)
4185 }
4186 return nil
4187 }
4188
4189 // StorageType determines how messages are stored for retention.
4190 type StorageType int
4191
4192 const (
4193 // FileStorage specifies on disk storage. It's the default.
4194 FileStorage StorageType = iota
4195 // MemoryStorage specifies in memory only.
4196 MemoryStorage
4197 )
4198
4199 const (
4200 memoryStorageString = "memory"
4201 fileStorageString = "file"
4202 )
4203
4204 func (st StorageType) String() string {
4205 switch st {
4206 case MemoryStorage:
4207 return "Memory"
4208 case FileStorage:
4209 return "File"
4210 default:
4211 return "Unknown Storage Type"
4212 }
4213 }
4214
4215 func (st StorageType) MarshalJSON() ([]byte, error) {
4216 switch st {
4217 case MemoryStorage:
4218 return json.Marshal(memoryStorageString)
4219 case FileStorage:
4220 return json.Marshal(fileStorageString)
4221 default:
4222 return nil, fmt.Errorf("nats: can not marshal %v", st)
4223 }
4224 }
4225
4226 func (st *StorageType) UnmarshalJSON(data []byte) error {
4227 switch string(data) {
4228 case jsonString(memoryStorageString):
4229 *st = MemoryStorage
4230 case jsonString(fileStorageString):
4231 *st = FileStorage
4232 default:
4233 return fmt.Errorf("nats: can not unmarshal %q", data)
4234 }
4235 return nil
4236 }
4237
4238 type StoreCompression uint8
4239
4240 const (
4241 NoCompression StoreCompression = iota
4242 S2Compression
4243 )
4244
4245 func (alg StoreCompression) String() string {
4246 switch alg {
4247 case NoCompression:
4248 return "None"
4249 case S2Compression:
4250 return "S2"
4251 default:
4252 return "Unknown StoreCompression"
4253 }
4254 }
4255
4256 func (alg StoreCompression) MarshalJSON() ([]byte, error) {
4257 var str string
4258 switch alg {
4259 case S2Compression:
4260 str = "s2"
4261 case NoCompression:
4262 str = "none"
4263 default:
4264 return nil, errors.New("unknown compression algorithm")
4265 }
4266 return json.Marshal(str)
4267 }
4268
4269 func (alg *StoreCompression) UnmarshalJSON(b []byte) error {
4270 var str string
4271 if err := json.Unmarshal(b, &str); err != nil {
4272 return err
4273 }
4274 switch str {
4275 case "s2":
4276 *alg = S2Compression
4277 case "none":
4278 *alg = NoCompression
4279 default:
4280 return errors.New("unknown compression algorithm")
4281 }
4282 return nil
4283 }
4284
4285 // Length of our hash used for named consumers.
4286 const nameHashLen = 8
4287
4288 // Computes a hash for the given `name`.
4289 func getHash(name string) string {
4290 sha := sha256.New()
4291 sha.Write([]byte(name))
4292 b := sha.Sum(nil)
4293 for i := 0; i < nameHashLen; i++ {
4294 b[i] = rdigits[int(b[i]%base)]
4295 }
4296 return string(b[:nameHashLen])
4297 }