Debian Codegraph @

jetstream/jetstream.go

raw
1 // Copyright 2022-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 jetstream
15
16 import (
17 "context"
18 "encoding/json"
19 "errors"
20 "fmt"
21 "regexp"
22 "slices"
23 "strings"
24 "time"
25
26 "github.com/nats-io/nats.go"
27 "github.com/nats-io/nuid"
28 )
29
30 type (
31
32 // JetStream is the top-level interface for interacting with JetStream.
33 // The capabilities of JetStream include:
34 //
35 // - Publishing messages to a stream using [Publisher].
36 // - Managing streams using [StreamManager].
37 // - Managing consumers using [StreamConsumerManager]. These are the same
38 // methods available on [Stream], but exposed here as a shortcut that bypasses
39 // stream lookup.
40 // - Managing KeyValue stores using [KeyValueManager].
41 // - Managing Object Stores using [ObjectStoreManager].
42 //
43 // JetStream can be created using [New], [NewWithAPIPrefix] or
44 // [NewWithDomain] methods.
45 JetStream interface {
46 // AccountInfo fetches account information from the server, containing details
47 // about the account associated with this JetStream connection. If account is
48 // not enabled for JetStream, ErrJetStreamNotEnabledForAccount is returned. If
49 // the server does not have JetStream enabled, ErrJetStreamNotEnabled is
50 // returned.
51 AccountInfo(ctx context.Context) (*AccountInfo, error)
52
53 // Conn returns the underlying NATS connection.
54 Conn() *nats.Conn
55
56 // Options returns read-only JetStreamOptions used
57 // when making requests to JetStream.
58 Options() JetStreamOptions
59
60 StreamConsumerManager
61 StreamManager
62 Publisher
63 KeyValueManager
64 ObjectStoreManager
65 }
66
67 // Publisher provides methods for publishing messages to a stream.
68 // It is available as a part of [JetStream] interface.
69 // The behavior of Publisher can be customized using [PublishOpt] options.
70 Publisher interface {
71 // Publish performs a synchronous publish to a stream and waits for ack
72 // from server. It accepts subject name (which must be bound to a stream)
73 // and message payload.
74 Publish(ctx context.Context, subject string, payload []byte, opts ...PublishOpt) (*PubAck, error)
75
76 // PublishMsg performs a synchronous publish to a stream and waits for
77 // ack from server. It accepts [nats.Msg] (whose Subject must be bound
78 // to a stream) as payload.
79 PublishMsg(ctx context.Context, msg *nats.Msg, opts ...PublishOpt) (*PubAck, error)
80
81 // PublishAsync performs a publish to a stream and returns
82 // [PubAckFuture] interface, not blocking while waiting for an
83 // acknowledgement. It accepts subject name (which must be bound to a
84 // stream) and message payload.
85 //
86 // PublishAsync does not guarantee that the message has been
87 // received by the server. It only guarantees that the message has been
88 // sent to the server and thus messages can be stored in the stream
89 // out of order in case of retries.
90 PublishAsync(subject string, payload []byte, opts ...PublishOpt) (PubAckFuture, error)
91
92 // PublishMsgAsync performs a publish to a stream and returns
93 // [PubAckFuture] interface, not blocking while waiting for an
94 // acknowledgement. It accepts [nats.Msg] (whose Subject must be bound
95 // to a stream) as payload.
96 //
97 // PublishMsgAsync does not guarantee that the message has been
98 // received by the server. It only guarantees that the message has been
99 // sent to the server and thus messages can be stored in the stream
100 // out of order in case of retries.
101 PublishMsgAsync(msg *nats.Msg, opts ...PublishOpt) (PubAckFuture, error)
102
103 // PublishAsyncPending returns the number of async publishes outstanding
104 // for this context. An outstanding publish is one that has been
105 // sent by the publisher but has not yet received an ack.
106 PublishAsyncPending() int
107
108 // PublishAsyncComplete returns a channel that will be closed when all
109 // outstanding asynchronously published messages are acknowledged by the
110 // server.
111 PublishAsyncComplete() <-chan struct{}
112
113 // CleanupPublisher will clean up the publishing side of JetStreamContext.
114 //
115 // This will unsubscribe from the internal reply subject if needed.
116 // All pending async publishes will fail with ErrJetStreamContextClosed.
117 //
118 // If an error handler was provided, it will be called for each pending async
119 // publish and PublishAsyncComplete will be closed.
120 //
121 // After completing JetStreamContext is still usable - internal subscription
122 // will be recreated on next publish, but the acks from previous publishes will
123 // be lost.
124 CleanupPublisher()
125 }
126
127 // StreamManager provides CRUD API for managing streams. It is available as
128 // a part of [JetStream] interface. CreateStream, UpdateStream,
129 // CreateOrUpdateStream and Stream methods return a [Stream] interface, allowing
130 // to operate on a stream.
131 StreamManager interface {
132 // CreateStream creates a new stream with the given config and returns an
133 // interface to operate on it. If stream with given name already exists
134 // and its configuration differs from the provided one,
135 // ErrStreamNameAlreadyInUse is returned.
136 CreateStream(ctx context.Context, cfg StreamConfig) (Stream, error)
137
138 // UpdateStream updates an existing stream. If stream does not exist,
139 // ErrStreamNotFound is returned.
140 UpdateStream(ctx context.Context, cfg StreamConfig) (Stream, error)
141
142 // CreateOrUpdateStream creates a stream with the given config. If stream
143 // already exists, it will be updated (if possible).
144 CreateOrUpdateStream(ctx context.Context, cfg StreamConfig) (Stream, error)
145
146 // Stream fetches [StreamInfo] and returns a [Stream] interface for a given stream name.
147 // If stream does not exist, ErrStreamNotFound is returned.
148 Stream(ctx context.Context, stream string) (Stream, error)
149
150 // StreamNameBySubject returns the name of the stream that listens on the given
151 // subject. If no stream is bound to given subject, ErrStreamNotFound
152 // is returned.
153 StreamNameBySubject(ctx context.Context, subject string) (string, error)
154
155 // DeleteStream removes a stream with given name. If stream does not
156 // exist, ErrStreamNotFound is returned.
157 DeleteStream(ctx context.Context, stream string) error
158
159 // ListStreams returns StreamInfoLister, enabling iteration over a
160 // channel of stream infos.
161 ListStreams(context.Context, ...StreamListOpt) StreamInfoLister
162
163 // StreamNames returns a StreamNameLister, enabling iteration over a
164 // channel of stream names.
165 StreamNames(context.Context, ...StreamListOpt) StreamNameLister
166 }
167
168 // StreamConsumerManager provides CRUD API for managing consumers. It is
169 // available as a part of [JetStream] interface. This is an alternative to
170 // [Stream] interface, allowing to bypass stream lookup. CreateConsumer,
171 // UpdateConsumer, CreateOrUpdateConsumer and Consumer methods return a
172 // [Consumer] interface, allowing operation on a consumer (e.g. consume
173 // messages).
174 StreamConsumerManager interface {
175 // CreateOrUpdateConsumer creates a consumer on a given stream with
176 // the given config. If consumer already exists, it will be updated (if
177 // possible). Consumer interface is returned, allowing to operate on a
178 // consumer (e.g. fetch messages).
179 CreateOrUpdateConsumer(ctx context.Context, stream string, cfg ConsumerConfig) (Consumer, error)
180
181 // CreateConsumer creates a consumer on a given stream with given
182 // config. If consumer already exists and the provided configuration
183 // differs from its configuration, ErrConsumerExists is returned. If the
184 // provided configuration is the same as the existing consumer, the
185 // existing consumer is returned. Consumer interface is returned,
186 // allowing to operate on a consumer (e.g. fetch messages).
187 CreateConsumer(ctx context.Context, stream string, cfg ConsumerConfig) (Consumer, error)
188
189 // UpdateConsumer updates an existing consumer. If consumer does not
190 // exist, ErrConsumerDoesNotExist is returned. Consumer interface is
191 // returned, allowing to operate on a consumer (e.g. fetch messages).
192 UpdateConsumer(ctx context.Context, stream string, cfg ConsumerConfig) (Consumer, error)
193
194 // OrderedConsumer returns a client-managed ordered consumer for the given stream.
195 // Ordered consumers use ephemeral pull consumers and automatically reset
196 // themselves when ordering is lost. The client tracks state in memory and
197 // recreates the underlying consumer as needed, making them resilient to deletes
198 // and restarts while ensuring message order is preserved.
199 OrderedConsumer(ctx context.Context, stream string, cfg OrderedConsumerConfig) (Consumer, error)
200
201 // Consumer returns an interface to an existing consumer, allowing processing
202 // of messages. If consumer does not exist, ErrConsumerNotFound is
203 // returned.
204 Consumer(ctx context.Context, stream string, consumer string) (Consumer, error)
205
206 // DeleteConsumer removes a consumer with given name from a stream.
207 // If consumer does not exist, ErrConsumerNotFound is returned.
208 DeleteConsumer(ctx context.Context, stream string, consumer string) error
209
210 // PauseConsumer pauses a consumer until the given time.
211 PauseConsumer(ctx context.Context, stream string, consumer string, pauseUntil time.Time) (*ConsumerPauseResponse, error)
212
213 // ResumeConsumer resumes a paused consumer.
214 ResumeConsumer(ctx context.Context, stream string, consumer string) (*ConsumerPauseResponse, error)
215
216 // ResetConsumer resets a consumer's delivery state. The consumer is
217 // reset to deliver from ack_floor + 1.
218 ResetConsumer(ctx context.Context, stream, consumer string) (*ConsumerResetResponse, error)
219
220 // ResetConsumerToSequence resets a consumer's delivery state to the
221 // given stream sequence. The seq must be compatible with the
222 // consumer's DeliverPolicy. If incompatible, ErrConsumerInvalidReset
223 // is returned.
224 ResetConsumerToSequence(ctx context.Context, stream, consumer string, seq uint64) (*ConsumerResetResponse, error)
225
226 // CreateOrUpdatePushConsumer creates a push consumer on a given stream with
227 // the given config. If consumer already exists, it will be updated (if
228 // possible). Consumer interface is returned, allowing to consume messages.
229 CreateOrUpdatePushConsumer(ctx context.Context, stream string, cfg ConsumerConfig) (PushConsumer, error)
230
231 // CreatePushConsumer creates a push consumer on a given stream with given
232 // config. If consumer already exists and the provided configuration
233 // differs from its configuration, ErrConsumerExists is returned. If the
234 // provided configuration is the same as the existing consumer, the
235 // existing consumer is returned. Consumer interface is returned,
236 // allowing to consume messages.
237 CreatePushConsumer(ctx context.Context, stream string, cfg ConsumerConfig) (PushConsumer, error)
238
239 // UpdatePushConsumer updates an existing push consumer. If consumer does not
240 // exist, ErrConsumerDoesNotExist is returned. Consumer interface is
241 // returned, allowing to consume messages.
242 UpdatePushConsumer(ctx context.Context, stream string, cfg ConsumerConfig) (PushConsumer, error)
243
244 // PushConsumer returns an interface to an existing push consumer, allowing processing
245 // of messages. If consumer does not exist, ErrConsumerNotFound is
246 // returned.
247 //
248 // It returns ErrNotPushConsumer if the consumer is not a push consumer (delivery subject is not set).
249 PushConsumer(ctx context.Context, stream string, consumer string) (PushConsumer, error)
250 }
251
252 // StreamListOpt is a functional option for [StreamManager.ListStreams] and
253 // [StreamManager.StreamNames] methods.
254 StreamListOpt func(*streamsRequest) error
255
256 // AccountInfo contains information about the JetStream usage from the
257 // current account.
258 AccountInfo struct {
259 // Tier is the current account usage tier.
260 Tier
261
262 // Domain is the domain name associated with this account.
263 Domain string `json:"domain"`
264
265 // API is the API usage statistics for this account.
266 API APIStats `json:"api"`
267
268 // Tiers is the list of available tiers for this account.
269 Tiers map[string]Tier `json:"tiers"`
270 }
271
272 // Tier represents a JetStream account usage tier.
273 Tier struct {
274 // Memory is the memory storage being used for Stream Message storage.
275 Memory uint64 `json:"memory"`
276
277 // Store is the disk storage being used for Stream Message storage.
278 Store uint64 `json:"storage"`
279
280 // ReservedMemory is the number of bytes reserved for memory usage by
281 // this account on the server
282 ReservedMemory uint64 `json:"reserved_memory"`
283
284 // ReservedStore is the number of bytes reserved for disk usage by this
285 // account on the server
286 ReservedStore uint64 `json:"reserved_storage"`
287
288 // Streams is the number of streams currently defined for this account.
289 Streams int `json:"streams"`
290
291 // Consumers is the number of consumers currently defined for this
292 // account.
293 Consumers int `json:"consumers"`
294
295 // Limits are the JetStream limits for this account.
296 Limits AccountLimits `json:"limits"`
297 }
298
299 // APIStats reports on API calls to JetStream for this account.
300 APIStats struct {
301 // Level is the API level for this account.
302 Level int `json:"level"`
303
304 // Total is the total number of API calls.
305 Total uint64 `json:"total"`
306
307 // Errors is the total number of API errors.
308 Errors uint64 `json:"errors"`
309
310 // Inflight is the number of API calls currently in flight.
311 Inflight uint64 `json:"inflight,omitempty"`
312 }
313
314 // AccountLimits includes the JetStream limits of the current account.
315 AccountLimits struct {
316 // MaxMemory is the maximum amount of memory available for this account.
317 MaxMemory int64 `json:"max_memory"`
318
319 // MaxStore is the maximum amount of disk storage available for this
320 // account.
321 MaxStore int64 `json:"max_storage"`
322
323 // MaxStreams is the maximum number of streams allowed for this account.
324 MaxStreams int `json:"max_streams"`
325
326 // MaxConsumers is the maximum number of consumers allowed for this
327 // account.
328 MaxConsumers int `json:"max_consumers"`
329
330 // MaxAckPending is the maximum number of outstanding ACKs any consumer
331 // may configure.
332 MaxAckPending int `json:"max_ack_pending"`
333
334 // MemoryMaxStreamBytes is is the maximum size any single memory based
335 // stream may be.
336 MemoryMaxStreamBytes int64 `json:"memory_max_stream_bytes"`
337
338 // StoreMaxStreamBytes is the maximum size any single storage based
339 // stream may be.
340 StoreMaxStreamBytes int64 `json:"storage_max_stream_bytes"`
341
342 // MaxBytesRequired indicates if max bytes is required to be set for
343 // streams in this account.
344 MaxBytesRequired bool `json:"max_bytes_required"`
345 }
346
347 jetStream struct {
348 conn *nats.Conn
349 opts JetStreamOptions
350
351 publisher *jetStreamClient
352 }
353
354 // JetStreamOpt is a functional option for [New], [NewWithAPIPrefix] and
355 // [NewWithDomain] methods.
356 JetStreamOpt func(*JetStreamOptions) error
357
358 // JetStreamOptions are used to configure JetStream.
359 JetStreamOptions struct {
360 // APIPrefix is the prefix used for JetStream API requests.
361 APIPrefix string
362
363 // Domain is the domain name token used when sending JetStream requests.
364 Domain string
365
366 // DefaultTimeout is the default timeout used for JetStream API requests.
367 // This applies when the context passed to JetStream methods does not have
368 // a deadline set.
369 DefaultTimeout time.Duration
370
371 // ClientTrace enables request/response API calls tracing.
372 ClientTrace *ClientTrace
373
374 publisherOpts asyncPublisherOpts
375
376 // this is the actual prefix used in the API requests
377 // it is either APIPrefix or a domain specific prefix
378 apiPrefix string
379 replyPrefix string
380 replyPrefixLen int
381 }
382
383 // ClientTrace can be used to trace API interactions for [JetStream].
384 ClientTrace struct {
385 // RequestSent is called when an API request is sent to the server.
386 RequestSent func(subj string, payload []byte)
387
388 // ResponseReceived is called when a response is received from the
389 // server.
390 ResponseReceived func(subj string, payload []byte, hdr nats.Header)
391 }
392 streamInfoResponse struct {
393 apiResponse
394 apiPaged
395 *StreamInfo
396 }
397
398 accountInfoResponse struct {
399 apiResponse
400 AccountInfo
401 }
402
403 streamDeleteResponse struct {
404 apiResponse
405 Success bool `json:"success,omitempty"`
406 }
407
408 // StreamInfoLister is used to iterate over a channel of stream infos.
409 // Err method can be used to check for errors encountered during iteration.
410 // Info channel is always closed and therefore can be used in a range loop.
411 StreamInfoLister interface {
412 Info() <-chan *StreamInfo
413 Err() error
414 }
415
416 // StreamNameLister is used to iterate over a channel of stream names.
417 // Err method can be used to check for errors encountered during iteration.
418 // Name channel is always closed and therefore can be used in a range loop.
419 StreamNameLister interface {
420 Name() <-chan string
421 Err() error
422 }
423
424 apiPagedRequest struct {
425 Offset int `json:"offset"`
426 }
427
428 streamLister struct {
429 js *jetStream
430 offset int
431 pageInfo *apiPaged
432
433 streams chan *StreamInfo
434 names chan string
435 err error
436 }
437
438 streamListResponse struct {
439 apiResponse
440 apiPaged
441 Streams []*StreamInfo `json:"streams"`
442 }
443
444 streamNamesResponse struct {
445 apiResponse
446 apiPaged
447 Streams []string `json:"streams"`
448 }
449
450 streamsRequest struct {
451 apiPagedRequest
452 Subject string `json:"subject,omitempty"`
453 }
454 )
455
456 // defaultAPITimeout is used if context.Background() or context.TODO() is passed to API calls.
457 const defaultAPITimeout = 5 * time.Second
458
459 var subjectRegexp = regexp.MustCompile(`^[^ >]*[>]?$`)
460
461 // New returns a new JetStream instance.
462 // It uses default API prefix ($JS.API) for JetStream API requests.
463 // If a custom API prefix is required, use [NewWithAPIPrefix] or [NewWithDomain].
464 //
465 // Available options:
466 // - [WithClientTrace] - enables request/response tracing.
467 // - [WithPublishAsyncErrHandler] - sets error handler for async message publish.
468 // - [WithPublishAsyncAckHandler] - sets ack handler for async message publish.
469 // - [WithPublishAsyncMaxPending] - sets the maximum outstanding async publishes
470 // that can be inflight at one time.
471 func New(nc *nats.Conn, opts ...JetStreamOpt) (JetStream, error) {
472 jsOpts := JetStreamOptions{
473 apiPrefix: DefaultAPIPrefix,
474 publisherOpts: asyncPublisherOpts{
475 maxpa: defaultAsyncPubAckInflight,
476 },
477 DefaultTimeout: defaultAPITimeout,
478 }
479 setReplyPrefix(nc, &jsOpts)
480 for _, opt := range opts {
481 if err := opt(&jsOpts); err != nil {
482 return nil, err
483 }
484 }
485 js := &jetStream{
486 conn: nc,
487 opts: jsOpts,
488 publisher: &jetStreamClient{asyncPublisherOpts: jsOpts.publisherOpts},
489 }
490
491 return js, nil
492 }
493
494 const (
495 // defaultAsyncPubAckInflight is the number of async pub acks inflight.
496 defaultAsyncPubAckInflight = 4000
497 )
498
499 func setReplyPrefix(nc *nats.Conn, jsOpts *JetStreamOptions) {
500 jsOpts.replyPrefix = nats.InboxPrefix
501 if nc.Opts.InboxPrefix != "" {
502 jsOpts.replyPrefix = nc.Opts.InboxPrefix + "."
503 }
504 // Add 1 for the dot separator.
505 jsOpts.replyPrefixLen = len(jsOpts.replyPrefix) + aReplyTokensize + 1
506
507 }
508
509 // NewWithAPIPrefix returns a new JetStream instance and sets the API prefix to be used in requests to JetStream API.
510 // The API prefix will be used in API requests to JetStream, e.g. <prefix>.STREAM.INFO.<stream>.
511 //
512 // Available options:
513 // - [WithClientTrace] - enables request/response tracing.
514 // - [WithPublishAsyncErrHandler] - sets error handler for async message publish.
515 // - [WithPublishAsyncAckHandler] - sets ack handler for async message publish.
516 // - [WithPublishAsyncMaxPending] - sets the maximum outstanding async publishes
517 // that can be inflight at one time.
518 func NewWithAPIPrefix(nc *nats.Conn, apiPrefix string, opts ...JetStreamOpt) (JetStream, error) {
519 jsOpts := JetStreamOptions{
520 publisherOpts: asyncPublisherOpts{
521 maxpa: defaultAsyncPubAckInflight,
522 },
523 APIPrefix: apiPrefix,
524 DefaultTimeout: defaultAPITimeout,
525 }
526 setReplyPrefix(nc, &jsOpts)
527 for _, opt := range opts {
528 if err := opt(&jsOpts); err != nil {
529 return nil, err
530 }
531 }
532 if apiPrefix == "" {
533 return nil, errors.New("API prefix cannot be empty")
534 }
535 if !strings.HasSuffix(apiPrefix, ".") {
536 jsOpts.apiPrefix = fmt.Sprintf("%s.", apiPrefix)
537 } else {
538 jsOpts.apiPrefix = apiPrefix
539 }
540 js := &jetStream{
541 conn: nc,
542 opts: jsOpts,
543 publisher: &jetStreamClient{asyncPublisherOpts: jsOpts.publisherOpts},
544 }
545 return js, nil
546 }
547
548 // NewWithDomain returns a new JetStream instance and sets the domain name token used when sending JetStream requests.
549 // The domain name token will be used in API requests to JetStream, e.g. $JS.<domain>.API.STREAM.INFO.<stream>.
550 //
551 // Available options:
552 // - [WithClientTrace] - enables request/response tracing.
553 // - [WithPublishAsyncErrHandler] - sets error handler for async message publish.
554 // - [WithPublishAsyncAckHandler] - sets ack handler for async message publish.
555 // - [WithPublishAsyncMaxPending] - sets the maximum outstanding async publishes
556 // that can be inflight at one time.
557 func NewWithDomain(nc *nats.Conn, domain string, opts ...JetStreamOpt) (JetStream, error) {
558 jsOpts := JetStreamOptions{
559 publisherOpts: asyncPublisherOpts{
560 maxpa: defaultAsyncPubAckInflight,
561 },
562 Domain: domain,
563 DefaultTimeout: defaultAPITimeout,
564 }
565 setReplyPrefix(nc, &jsOpts)
566 for _, opt := range opts {
567 if err := opt(&jsOpts); err != nil {
568 return nil, err
569 }
570 }
571 if domain == "" {
572 return nil, errors.New("domain cannot be empty")
573 }
574 jsOpts.apiPrefix = fmt.Sprintf(jsDomainT, domain)
575 js := &jetStream{
576 conn: nc,
577 opts: jsOpts,
578 publisher: &jetStreamClient{asyncPublisherOpts: jsOpts.publisherOpts},
579 }
580 return js, nil
581 }
582
583 // Conn returns the underlying NATS connection.
584 func (js *jetStream) Conn() *nats.Conn {
585 return js.conn
586 }
587
588 func (js *jetStream) Options() JetStreamOptions {
589 opts := js.opts
590 // Return a copy of ClientTrace to prevent modification
591 if opts.ClientTrace != nil {
592 clientTraceCopy := *opts.ClientTrace
593 opts.ClientTrace = &clientTraceCopy
594 }
595 return opts
596 }
597
598 // CreateStream creates a new stream with the given config and returns an
599 // interface to operate on it. If stream with given name already exists,
600 // ErrStreamNameAlreadyInUse is returned.
601 func (js *jetStream) CreateStream(ctx context.Context, cfg StreamConfig) (Stream, error) {
602 if err := validateStreamName(cfg.Name); err != nil {
603 return nil, err
604 }
605 ctx, cancel := js.wrapContextWithoutDeadline(ctx)
606 if cancel != nil {
607 defer cancel()
608 }
609
610 ncfg, err := convertStreamConfigDomains(cfg)
611 if err != nil {
612 return nil, err
613 }
614
615 req, err := json.Marshal(ncfg)
616 if err != nil {
617 return nil, err
618 }
619
620 createSubject := fmt.Sprintf(apiStreamCreateT, cfg.Name)
621 var resp streamInfoResponse
622
623 if _, err = js.apiRequestJSON(ctx, createSubject, &resp, req); err != nil {
624 return nil, err
625 }
626 if resp.Error != nil {
627 if resp.Error.ErrorCode == JSErrCodeStreamNameInUse {
628 return nil, ErrStreamNameAlreadyInUse
629 }
630 return nil, resp.Error
631 }
632 if resp.StreamInfo == nil {
633 return nil, ErrInvalidJetStreamResponse
634 }
635
636 // check that input subject transform (if used) is reflected in the returned StreamInfo
637 if cfg.SubjectTransform != nil && resp.StreamInfo.Config.SubjectTransform == nil {
638 return nil, ErrStreamSubjectTransformNotSupported
639 }
640
641 if len(cfg.Sources) != 0 {
642 if len(cfg.Sources) != len(resp.Config.Sources) {
643 return nil, ErrStreamSourceNotSupported
644 }
645
646 // the sources list in the response is not ordered
647 cfgNumTransforms := make([]int, len(cfg.Sources))
648 respNumTransforms := make([]int, len(resp.Config.Sources))
649 for i, cfgSource := range cfg.Sources {
650 cfgNumTransforms[i] = len(cfgSource.SubjectTransforms)
651 respNumTransforms[i] = len(resp.Config.Sources[i].SubjectTransforms)
652 }
653 slices.Sort(cfgNumTransforms)
654 slices.Sort(respNumTransforms)
655 if !slices.Equal(cfgNumTransforms, respNumTransforms) {
656 return nil, ErrStreamSubjectTransformNotSupported
657 }
658 }
659
660 return &stream{
661 js: js,
662 name: cfg.Name,
663 info: resp.StreamInfo,
664 }, nil
665 }
666
667 // If we have a Domain, convert to the appropriate ext.APIPrefix.
668 // This will change the stream source, so should be a copy passed in.
669 func (ss *StreamSource) convertDomain() error {
670 if ss.Domain == "" {
671 return nil
672 }
673 if ss.External != nil {
674 return errors.New("nats: domain and external are both set")
675 }
676 ss.External = &ExternalStream{APIPrefix: fmt.Sprintf(jsExtDomainT, ss.Domain)}
677 return nil
678 }
679
680 // Helper for copying when we do not want to change user's version.
681 func (ss *StreamSource) copy() *StreamSource {
682 nss := *ss
683 // Check pointers
684 if ss.OptStartTime != nil {
685 t := *ss.OptStartTime
686 nss.OptStartTime = &t
687 }
688 if ss.External != nil {
689 ext := *ss.External
690 nss.External = &ext
691 }
692 return &nss
693 }
694
695 // convertStreamConfigDomains converts domain configurations to external configurations
696 // in both mirror and sources of a StreamConfig. It creates a copy of the config to avoid
697 // modifying the caller's version.
698 func convertStreamConfigDomains(cfg StreamConfig) (StreamConfig, error) {
699 ncfg := cfg
700 // If we have a mirror and an external domain, convert to ext.APIPrefix.
701 if ncfg.Mirror != nil && ncfg.Mirror.Domain != "" {
702 // Copy so we do not change the caller's version.
703 ncfg.Mirror = ncfg.Mirror.copy()
704 if err := ncfg.Mirror.convertDomain(); err != nil {
705 return StreamConfig{}, err
706 }
707 }
708
709 // Check sources for the same conversion.
710 if len(ncfg.Sources) > 0 {
711 ncfg.Sources = append([]*StreamSource(nil), ncfg.Sources...)
712 for i, ss := range ncfg.Sources {
713 if ss.Domain != "" {
714 ncfg.Sources[i] = ss.copy()
715 if err := ncfg.Sources[i].convertDomain(); err != nil {
716 return StreamConfig{}, err
717 }
718 }
719 }
720 }
721
722 return ncfg, nil
723 }
724
725 // UpdateStream updates an existing stream. If stream does not exist,
726 // ErrStreamNotFound is returned.
727 func (js *jetStream) UpdateStream(ctx context.Context, cfg StreamConfig) (Stream, error) {
728 if err := validateStreamName(cfg.Name); err != nil {
729 return nil, err
730 }
731 ctx, cancel := js.wrapContextWithoutDeadline(ctx)
732 if cancel != nil {
733 defer cancel()
734 }
735
736 ncfg, err := convertStreamConfigDomains(cfg)
737 if err != nil {
738 return nil, err
739 }
740
741 req, err := json.Marshal(ncfg)
742 if err != nil {
743 return nil, err
744 }
745
746 updateSubject := fmt.Sprintf(apiStreamUpdateT, cfg.Name)
747 var resp streamInfoResponse
748
749 if _, err = js.apiRequestJSON(ctx, updateSubject, &resp, req); err != nil {
750 return nil, err
751 }
752 if resp.Error != nil {
753 if resp.Error.ErrorCode == JSErrCodeStreamNotFound {
754 return nil, ErrStreamNotFound
755 }
756 return nil, resp.Error
757 }
758 if resp.StreamInfo == nil {
759 return nil, ErrInvalidJetStreamResponse
760 }
761
762 // check that input subject transform (if used) is reflected in the returned StreamInfo
763 if cfg.SubjectTransform != nil && resp.StreamInfo.Config.SubjectTransform == nil {
764 return nil, ErrStreamSubjectTransformNotSupported
765 }
766
767 if len(cfg.Sources) != 0 {
768 if len(cfg.Sources) != len(resp.Config.Sources) {
769 return nil, ErrStreamSourceNotSupported
770 }
771
772 // the sources list in the response is not ordered
773 cfgNumTransforms := make([]int, len(cfg.Sources))
774 respNumTransforms := make([]int, len(resp.Config.Sources))
775 for i, cfgSource := range cfg.Sources {
776 cfgNumTransforms[i] = len(cfgSource.SubjectTransforms)
777 respNumTransforms[i] = len(resp.Config.Sources[i].SubjectTransforms)
778 }
779 slices.Sort(cfgNumTransforms)
780 slices.Sort(respNumTransforms)
781 if !slices.Equal(cfgNumTransforms, respNumTransforms) {
782 return nil, ErrStreamSubjectTransformNotSupported
783 }
784 }
785
786 return &stream{
787 js: js,
788 name: cfg.Name,
789 info: resp.StreamInfo,
790 }, nil
791 }
792
793 // CreateOrUpdateStream creates a stream with the given config. If stream
794 // already exists, it will be updated (if possible).
795 func (js *jetStream) CreateOrUpdateStream(ctx context.Context, cfg StreamConfig) (Stream, error) {
796 s, err := js.UpdateStream(ctx, cfg)
797 if err != nil {
798 if !errors.Is(err, ErrStreamNotFound) {
799 return nil, err
800 }
801 return js.CreateStream(ctx, cfg)
802 }
803
804 return s, nil
805 }
806
807 // Stream fetches [StreamInfo] and returns a [Stream] interface for a given stream name.
808 // If stream does not exist, ErrStreamNotFound is returned.
809 func (js *jetStream) Stream(ctx context.Context, name string) (Stream, error) {
810 if err := validateStreamName(name); err != nil {
811 return nil, err
812 }
813 ctx, cancel := js.wrapContextWithoutDeadline(ctx)
814 if cancel != nil {
815 defer cancel()
816 }
817 infoSubject := fmt.Sprintf(apiStreamInfoT, name)
818
819 var resp streamInfoResponse
820
821 if _, err := js.apiRequestJSON(ctx, infoSubject, &resp); err != nil {
822 return nil, err
823 }
824 if resp.Error != nil {
825 if resp.Error.ErrorCode == JSErrCodeStreamNotFound {
826 return nil, ErrStreamNotFound
827 }
828 return nil, resp.Error
829 }
830 if resp.StreamInfo == nil {
831 return nil, ErrInvalidJetStreamResponse
832 }
833 return &stream{
834 js: js,
835 name: name,
836 info: resp.StreamInfo,
837 }, nil
838 }
839
840 // DeleteStream removes a stream with given name
841 func (js *jetStream) DeleteStream(ctx context.Context, name string) error {
842 if err := validateStreamName(name); err != nil {
843 return err
844 }
845 ctx, cancel := js.wrapContextWithoutDeadline(ctx)
846 if cancel != nil {
847 defer cancel()
848 }
849 deleteSubject := fmt.Sprintf(apiStreamDeleteT, name)
850 var resp streamDeleteResponse
851
852 if _, err := js.apiRequestJSON(ctx, deleteSubject, &resp); err != nil {
853 return err
854 }
855 if resp.Error != nil {
856 if resp.Error.ErrorCode == JSErrCodeStreamNotFound {
857 return ErrStreamNotFound
858 }
859 return resp.Error
860 }
861 return nil
862 }
863
864 // CreateOrUpdateConsumer creates a consumer on a given stream with
865 // the given config. If consumer already exists, it will be updated (if
866 // possible). Consumer interface is returned, allowing to operate on a
867 // consumer (e.g. fetch messages).
868 func (js *jetStream) CreateOrUpdateConsumer(ctx context.Context, stream string, cfg ConsumerConfig) (Consumer, error) {
869 if err := validateStreamName(stream); err != nil {
870 return nil, err
871 }
872 return upsertPullConsumer(ctx, js, stream, cfg, consumerActionCreateOrUpdate)
873 }
874
875 // CreateConsumer creates a consumer on a given stream with given
876 // config. If consumer already exists and the provided configuration
877 // differs from its configuration, ErrConsumerExists is returned. If the
878 // provided configuration is the same as the existing consumer, the
879 // existing consumer is returned. Consumer interface is returned,
880 // allowing to operate on a consumer (e.g. fetch messages).
881 func (js *jetStream) CreateConsumer(ctx context.Context, stream string, cfg ConsumerConfig) (Consumer, error) {
882 if err := validateStreamName(stream); err != nil {
883 return nil, err
884 }
885 return upsertPullConsumer(ctx, js, stream, cfg, consumerActionCreate)
886 }
887
888 // UpdateConsumer updates an existing consumer. If consumer does not
889 // exist, ErrConsumerDoesNotExist is returned. Consumer interface is
890 // returned, allowing to operate on a consumer (e.g. fetch messages).
891 func (js *jetStream) UpdateConsumer(ctx context.Context, stream string, cfg ConsumerConfig) (Consumer, error) {
892 if err := validateStreamName(stream); err != nil {
893 return nil, err
894 }
895 return upsertPullConsumer(ctx, js, stream, cfg, consumerActionUpdate)
896 }
897
898 // OrderedConsumer returns an OrderedConsumer instance. OrderedConsumer
899 // are managed by the library and provide a simple way to consume
900 // messages from a stream. Ordered consumers are ephemeral in-memory
901 // pull consumers and are resilient to deletes and restarts.
902 func (js *jetStream) OrderedConsumer(ctx context.Context, stream string, cfg OrderedConsumerConfig) (Consumer, error) {
903 if err := validateStreamName(stream); err != nil {
904 return nil, err
905 }
906 namePrefix := cfg.NamePrefix
907 if namePrefix == "" {
908 namePrefix = nuid.Next()
909 }
910 oc := &orderedConsumer{
911 js: js,
912 cfg: &cfg,
913 stream: stream,
914 namePrefix: namePrefix,
915 doReset: make(chan struct{}, 1),
916 }
917 consCfg := oc.getConsumerConfig()
918 cons, err := js.CreateOrUpdateConsumer(ctx, stream, *consCfg)
919 if err != nil {
920 return nil, err
921 }
922 oc.currentConsumer = cons.(*pullConsumer)
923
924 return oc, nil
925 }
926
927 // Consumer returns an interface to an existing consumer, allowing processing
928 // of messages. If consumer does not exist, ErrConsumerNotFound is
929 // returned.
930 func (js *jetStream) Consumer(ctx context.Context, stream string, name string) (Consumer, error) {
931 if err := validateStreamName(stream); err != nil {
932 return nil, err
933 }
934 return getConsumer(ctx, js, stream, name)
935 }
936
937 // DeleteConsumer removes a consumer with given name from a stream.
938 // If consumer does not exist, ErrConsumerNotFound is returned.
939 func (js *jetStream) DeleteConsumer(ctx context.Context, stream string, name string) error {
940 if err := validateStreamName(stream); err != nil {
941 return err
942 }
943 return deleteConsumer(ctx, js, stream, name)
944 }
945
946 // CreateOrUpdatePushConsumer creates a push consumer on a given stream with
947 // the given config. If consumer already exists, it will be updated (if
948 // possible). Consumer interface is returned, allowing to consume messages.
949 func (js *jetStream) CreateOrUpdatePushConsumer(ctx context.Context, stream string, cfg ConsumerConfig) (PushConsumer, error) {
950 if err := validateStreamName(stream); err != nil {
951 return nil, err
952 }
953 return upsertPushConsumer(ctx, js, stream, cfg, consumerActionCreateOrUpdate)
954 }
955
956 // CreatePushConsumer creates a push consumer on a given stream with given
957 // config. If consumer already exists and the provided configuration
958 // differs from its configuration, ErrConsumerExists is returned. If the
959 // provided configuration is the same as the existing consumer, the
960 // existing consumer is returned. Consumer interface is returned,
961 // allowing to consume messages.
962 func (js *jetStream) CreatePushConsumer(ctx context.Context, stream string, cfg ConsumerConfig) (PushConsumer, error) {
963 if err := validateStreamName(stream); err != nil {
964 return nil, err
965 }
966 return upsertPushConsumer(ctx, js, stream, cfg, consumerActionCreate)
967 }
968
969 // UpdatePushConsumer updates an existing push consumer. If consumer does not
970 // exist, ErrConsumerDoesNotExist is returned. Consumer interface is
971 // returned, allowing to consume messages.
972 func (js *jetStream) UpdatePushConsumer(ctx context.Context, stream string, cfg ConsumerConfig) (PushConsumer, error) {
973 if err := validateStreamName(stream); err != nil {
974 return nil, err
975 }
976 return upsertPushConsumer(ctx, js, stream, cfg, consumerActionUpdate)
977 }
978
979 // PushConsumer returns an interface to an existing consumer, allowing processing
980 // of messages. If consumer does not exist, ErrConsumerNotFound is
981 // returned.
982 func (js *jetStream) PushConsumer(ctx context.Context, stream string, name string) (PushConsumer, error) {
983 if err := validateStreamName(stream); err != nil {
984 return nil, err
985 }
986 return getPushConsumer(ctx, js, stream, name)
987 }
988
989 func (js *jetStream) PauseConsumer(ctx context.Context, stream string, consumer string, pauseUntil time.Time) (*ConsumerPauseResponse, error) {
990 if err := validateStreamName(stream); err != nil {
991 return nil, err
992 }
993 return pauseConsumer(ctx, js, stream, consumer, &pauseUntil)
994 }
995
996 func (js *jetStream) ResumeConsumer(ctx context.Context, stream string, consumer string) (*ConsumerPauseResponse, error) {
997 if err := validateStreamName(stream); err != nil {
998 return nil, err
999 }
1000 return resumeConsumer(ctx, js, stream, consumer)
1001 }
1002
1003 func (js *jetStream) ResetConsumer(ctx context.Context, stream, consumer string) (*ConsumerResetResponse, error) {
1004 if err := validateStreamName(stream); err != nil {
1005 return nil, err
1006 }
1007 return resetConsumer(ctx, js, stream, consumer, 0)
1008 }
1009
1010 func (js *jetStream) ResetConsumerToSequence(ctx context.Context, stream, consumer string, seq uint64) (*ConsumerResetResponse, error) {
1011 if err := validateStreamName(stream); err != nil {
1012 return nil, err
1013 }
1014 return resetConsumer(ctx, js, stream, consumer, seq)
1015 }
1016
1017 func validateStreamName(stream string) error {
1018 if stream == "" {
1019 return ErrStreamNameRequired
1020 }
1021 if strings.ContainsAny(stream, ">*. /\\\t\r\n") {
1022 return fmt.Errorf("%w: %q", ErrInvalidStreamName, stream)
1023 }
1024 return nil
1025 }
1026
1027 func validateSubject(subject string) error {
1028 if subject == "" {
1029 return fmt.Errorf("%w: %s", ErrInvalidSubject, "subject cannot be empty")
1030 }
1031 if subject[0] == '.' || subject[len(subject)-1] == '.' || !subjectRegexp.MatchString(subject) {
1032 return fmt.Errorf("%w: %s", ErrInvalidSubject, subject)
1033 }
1034 return nil
1035 }
1036
1037 // AccountInfo fetches account information from the server, containing details
1038 // about the account associated with this JetStream connection. If account is
1039 // not enabled for JetStream, ErrJetStreamNotEnabledForAccount is returned.
1040 //
1041 // If the server does not have JetStream enabled, ErrJetStreamNotEnabled is
1042 // returned (for a single server setup). For clustered topologies, AccountInfo
1043 // will time out.
1044 func (js *jetStream) AccountInfo(ctx context.Context) (*AccountInfo, error) {
1045 ctx, cancel := js.wrapContextWithoutDeadline(ctx)
1046 if cancel != nil {
1047 defer cancel()
1048 }
1049 var resp accountInfoResponse
1050
1051 if _, err := js.apiRequestJSON(ctx, apiAccountInfo, &resp); err != nil {
1052 if errors.Is(err, nats.ErrNoResponders) {
1053 return nil, ErrJetStreamNotEnabled
1054 }
1055 return nil, err
1056 }
1057 if resp.Error != nil {
1058 if resp.Error.ErrorCode == JSErrCodeJetStreamNotEnabledForAccount {
1059 return nil, ErrJetStreamNotEnabledForAccount
1060 }
1061 if resp.Error.ErrorCode == JSErrCodeJetStreamNotEnabled {
1062 return nil, ErrJetStreamNotEnabled
1063 }
1064 return nil, resp.Error
1065 }
1066
1067 return &resp.AccountInfo, nil
1068 }
1069
1070 // ListStreams returns StreamInfoLister, enabling iteration over a
1071 // channel of stream infos.
1072 func (js *jetStream) ListStreams(ctx context.Context, opts ...StreamListOpt) StreamInfoLister {
1073 l := &streamLister{
1074 js: js,
1075 streams: make(chan *StreamInfo),
1076 }
1077 var streamsReq streamsRequest
1078 for _, opt := range opts {
1079 if err := opt(&streamsReq); err != nil {
1080 l.err = err
1081 close(l.streams)
1082 return l
1083 }
1084 }
1085 go func() {
1086 defer close(l.streams)
1087 ctx, cancel := js.wrapContextWithoutDeadline(ctx)
1088 if cancel != nil {
1089 defer cancel()
1090 }
1091 for {
1092 page, err := l.streamInfos(ctx, streamsReq)
1093 if err != nil && !errors.Is(err, ErrEndOfData) {
1094 l.err = err
1095 return
1096 }
1097 for _, info := range page {
1098 select {
1099 case l.streams <- info:
1100 case <-ctx.Done():
1101 l.err = ctx.Err()
1102 return
1103 }
1104 }
1105 if errors.Is(err, ErrEndOfData) {
1106 return
1107 }
1108 }
1109 }()
1110
1111 return l
1112 }
1113
1114 // Info returns a channel allowing retrieval of stream infos returned by [ListStreams]
1115 func (s *streamLister) Info() <-chan *StreamInfo {
1116 return s.streams
1117 }
1118
1119 // Err returns an error channel which will be populated with error from [ListStreams] or [StreamNames] request
1120 func (s *streamLister) Err() error {
1121 return s.err
1122 }
1123
1124 // StreamNames returns a StreamNameLister, enabling iteration over a
1125 // channel of stream names.
1126 func (js *jetStream) StreamNames(ctx context.Context, opts ...StreamListOpt) StreamNameLister {
1127 l := &streamLister{
1128 js: js,
1129 names: make(chan string),
1130 }
1131 var streamsReq streamsRequest
1132 for _, opt := range opts {
1133 if err := opt(&streamsReq); err != nil {
1134 l.err = err
1135 close(l.names)
1136 return l
1137 }
1138 }
1139 go func() {
1140 ctx, cancel := js.wrapContextWithoutDeadline(ctx)
1141 if cancel != nil {
1142 defer cancel()
1143 }
1144 defer close(l.names)
1145 for {
1146 page, err := l.streamNames(ctx, streamsReq)
1147 if err != nil && !errors.Is(err, ErrEndOfData) {
1148 l.err = err
1149 return
1150 }
1151 for _, info := range page {
1152 select {
1153 case l.names <- info:
1154 case <-ctx.Done():
1155 l.err = ctx.Err()
1156 return
1157 }
1158 }
1159 if errors.Is(err, ErrEndOfData) {
1160 return
1161 }
1162 }
1163 }()
1164
1165 return l
1166 }
1167
1168 // StreamNameBySubject returns the name of the stream bound to the given
1169 // subject. If no stream is bound to given subject, ErrStreamNotFound
1170 // is returned.
1171 func (js *jetStream) StreamNameBySubject(ctx context.Context, subject string) (string, error) {
1172 ctx, cancel := js.wrapContextWithoutDeadline(ctx)
1173 if cancel != nil {
1174 defer cancel()
1175 }
1176 if err := validateSubject(subject); err != nil {
1177 return "", err
1178 }
1179
1180 r := &streamsRequest{Subject: subject}
1181 req, err := json.Marshal(r)
1182 if err != nil {
1183 return "", err
1184 }
1185 var resp streamNamesResponse
1186 _, err = js.apiRequestJSON(ctx, apiStreams, &resp, req)
1187 if err != nil {
1188 return "", err
1189 }
1190 if resp.Error != nil {
1191 return "", resp.Error
1192 }
1193 if len(resp.Streams) == 0 {
1194 return "", ErrStreamNotFound
1195 }
1196
1197 return resp.Streams[0], nil
1198 }
1199
1200 // Name returns a channel allowing retrieval of stream names returned by [StreamNames]
1201 func (s *streamLister) Name() <-chan string {
1202 return s.names
1203 }
1204
1205 // infos fetches the next [StreamInfo] page
1206 func (s *streamLister) streamInfos(ctx context.Context, streamsReq streamsRequest) ([]*StreamInfo, error) {
1207 if s.pageInfo != nil && s.offset >= s.pageInfo.Total {
1208 return nil, ErrEndOfData
1209 }
1210
1211 req := streamsRequest{
1212 apiPagedRequest: apiPagedRequest{
1213 Offset: s.offset,
1214 },
1215 Subject: streamsReq.Subject,
1216 }
1217 reqJSON, err := json.Marshal(req)
1218 if err != nil {
1219 return nil, err
1220 }
1221
1222 var resp streamListResponse
1223 _, err = s.js.apiRequestJSON(ctx, apiStreamListT, &resp, reqJSON)
1224 if err != nil {
1225 return nil, err
1226 }
1227 if resp.Error != nil {
1228 return nil, resp.Error
1229 }
1230
1231 s.pageInfo = &resp.apiPaged
1232 s.offset += len(resp.Streams)
1233 return resp.Streams, nil
1234 }
1235
1236 // streamNames fetches the next stream names page
1237 func (s *streamLister) streamNames(ctx context.Context, streamsReq streamsRequest) ([]string, error) {
1238 if s.pageInfo != nil && s.offset >= s.pageInfo.Total {
1239 return nil, ErrEndOfData
1240 }
1241
1242 req := streamsRequest{
1243 apiPagedRequest: apiPagedRequest{
1244 Offset: s.offset,
1245 },
1246 Subject: streamsReq.Subject,
1247 }
1248 reqJSON, err := json.Marshal(req)
1249 if err != nil {
1250 return nil, err
1251 }
1252
1253 var resp streamNamesResponse
1254 _, err = s.js.apiRequestJSON(ctx, apiStreams, &resp, reqJSON)
1255 if err != nil {
1256 return nil, err
1257 }
1258 if resp.Error != nil {
1259 return nil, resp.Error
1260 }
1261
1262 s.pageInfo = &resp.apiPaged
1263 s.offset += len(resp.Streams)
1264 return resp.Streams, nil
1265 }
1266
1267 // wrapContextWithoutDeadline wraps context without deadline with default timeout.
1268 // If deadline is already set, it will be returned as is, and cancel() will be nil.
1269 // Caller should check if cancel() is nil before calling it.
1270 func (js *jetStream) wrapContextWithoutDeadline(ctx context.Context) (context.Context, context.CancelFunc) {
1271 if _, ok := ctx.Deadline(); ok {
1272 return ctx, nil
1273 }
1274 return context.WithTimeout(ctx, js.opts.DefaultTimeout)
1275 }
1276
1277 // CleanupPublisher will cleanup the publishing side of JetStreamContext.
1278 //
1279 // This will unsubscribe from the internal reply subject if needed.
1280 // All pending async publishes will fail with ErrJetStreamContextClosed.
1281 //
1282 // If an error handler was provided, it will be called for each pending async
1283 // publish and PublishAsyncComplete will be closed.
1284 //
1285 // After completing JetStreamContext is still usable - internal subscription
1286 // will be recreated on next publish, but the acks from previous publishes will
1287 // be lost.
1288 func (js *jetStream) CleanupPublisher() {
1289 js.cleanupReplySub()
1290 js.publisher.Lock()
1291 errCb := js.publisher.aecb
1292 for id, paf := range js.publisher.acks {
1293 paf.err = ErrJetStreamPublisherClosed
1294 if paf.errCh != nil {
1295 paf.errCh <- paf.err
1296 }
1297 if errCb != nil {
1298 // call error handler after releasing the mutex to avoid contention
1299 defer errCb(js, paf.msg, ErrJetStreamPublisherClosed)
1300 }
1301 delete(js.publisher.acks, id)
1302 }
1303 if js.publisher.doneCh != nil {
1304 close(js.publisher.doneCh)
1305 js.publisher.doneCh = nil
1306 }
1307 js.publisher.Unlock()
1308 }
1309
1310 func (js *jetStream) cleanupReplySub() {
1311 if js.publisher == nil {
1312 return
1313 }
1314 js.publisher.Lock()
1315 if js.publisher.replySub != nil {
1316 js.publisher.replySub.Unsubscribe()
1317 js.publisher.replySub = nil
1318 }
1319 if js.publisher.connStatusCh != nil {
1320 js.conn.RemoveStatusListener(js.publisher.connStatusCh)
1321 js.publisher.connStatusCh = nil
1322 }
1323 js.publisher.Unlock()
1324 }