Debian Codegraph @

jsm.go

raw
1 // Copyright 2021-2023 The NATS Authors
2 // Licensed under the Apache License, Version 2.0 (the "License");
3 // you may not use this file except in compliance with the License.
4 // You may obtain a copy of the License at
5 //
6 // http://www.apache.org/licenses/LICENSE-2.0
7 //
8 // Unless required by applicable law or agreed to in writing, software
9 // distributed under the License is distributed on an "AS IS" BASIS,
10 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11 // See the License for the specific language governing permissions and
12 // limitations under the License.
13
14 package nats
15
16 import (
17 "context"
18 "encoding/json"
19 "errors"
20 "fmt"
21 "strconv"
22 "strings"
23 "time"
24 )
25
26 // JetStreamManager manages JetStream Streams and Consumers.
27 type JetStreamManager interface {
28 // AddStream creates a stream.
29 AddStream(cfg *StreamConfig, opts ...JSOpt) (*StreamInfo, error)
30
31 // UpdateStream updates a stream.
32 UpdateStream(cfg *StreamConfig, opts ...JSOpt) (*StreamInfo, error)
33
34 // DeleteStream deletes a stream.
35 DeleteStream(name string, opts ...JSOpt) error
36
37 // StreamInfo retrieves information from a stream.
38 StreamInfo(stream string, opts ...JSOpt) (*StreamInfo, error)
39
40 // PurgeStream purges a stream messages.
41 PurgeStream(name string, opts ...JSOpt) error
42
43 // StreamsInfo can be used to retrieve a list of StreamInfo objects.
44 // Deprecated: Use Streams() instead.
45 StreamsInfo(opts ...JSOpt) <-chan *StreamInfo
46
47 // Streams can be used to retrieve a list of StreamInfo objects.
48 Streams(opts ...JSOpt) <-chan *StreamInfo
49
50 // StreamNames is used to retrieve a list of Stream names.
51 StreamNames(opts ...JSOpt) <-chan string
52
53 // GetMsg retrieves a raw stream message stored in JetStream by sequence number.
54 // Use options nats.DirectGet() or nats.DirectGetNext() to trigger retrieval
55 // directly from a distributed group of servers (leader and replicas).
56 // The stream must have been created/updated with the AllowDirect boolean.
57 GetMsg(name string, seq uint64, opts ...JSOpt) (*RawStreamMsg, error)
58
59 // GetLastMsg retrieves the last raw stream message stored in JetStream by subject.
60 // Use option nats.DirectGet() to trigger retrieval
61 // directly from a distributed group of servers (leader and replicas).
62 // The stream must have been created/updated with the AllowDirect boolean.
63 GetLastMsg(name, subject string, opts ...JSOpt) (*RawStreamMsg, error)
64
65 // DeleteMsg deletes a message from a stream. The message is marked as erased, but its value is not overwritten.
66 DeleteMsg(name string, seq uint64, opts ...JSOpt) error
67
68 // SecureDeleteMsg deletes a message from a stream. The deleted message is overwritten with random data
69 // As a result, this operation is slower than DeleteMsg()
70 SecureDeleteMsg(name string, seq uint64, opts ...JSOpt) error
71
72 // AddConsumer adds a consumer to a stream.
73 // If the consumer already exists, and the configuration is the same, it
74 // will return the existing consumer.
75 // If the consumer already exists, and the configuration is different, it
76 // will return ErrConsumerNameAlreadyInUse.
77 AddConsumer(stream string, cfg *ConsumerConfig, opts ...JSOpt) (*ConsumerInfo, error)
78
79 // UpdateConsumer updates an existing consumer.
80 UpdateConsumer(stream string, cfg *ConsumerConfig, opts ...JSOpt) (*ConsumerInfo, error)
81
82 // DeleteConsumer deletes a consumer.
83 DeleteConsumer(stream, consumer string, opts ...JSOpt) error
84
85 // ConsumerInfo retrieves information of a consumer from a stream.
86 ConsumerInfo(stream, name string, opts ...JSOpt) (*ConsumerInfo, error)
87
88 // ConsumersInfo is used to retrieve a list of ConsumerInfo objects.
89 // Deprecated: Use Consumers() instead.
90 ConsumersInfo(stream string, opts ...JSOpt) <-chan *ConsumerInfo
91
92 // Consumers is used to retrieve a list of ConsumerInfo objects.
93 Consumers(stream string, opts ...JSOpt) <-chan *ConsumerInfo
94
95 // ConsumerNames is used to retrieve a list of Consumer names.
96 ConsumerNames(stream string, opts ...JSOpt) <-chan string
97
98 // AccountInfo retrieves info about the JetStream usage from an account.
99 AccountInfo(opts ...JSOpt) (*AccountInfo, error)
100
101 // StreamNameBySubject returns a stream matching given subject.
102 StreamNameBySubject(string, ...JSOpt) (string, error)
103 }
104
105 // StreamConfig will determine the properties for a stream.
106 // There are sensible defaults for most. If no subjects are
107 // given the name will be used as the only subject.
108 type StreamConfig struct {
109 // Name is the name of the stream. It is required and must be unique
110 // across the JetStream account.
111 //
112 // Name Names cannot contain whitespace, ., *, >, path separators
113 // (forward or backwards slash), and non-printable characters.
114 Name string `json:"name"`
115
116 // Description is an optional description of the stream.
117 Description string `json:"description,omitempty"`
118
119 // Subjects is a list of subjects that the stream is listening on.
120 // Wildcards are supported. Subjects cannot be set if the stream is
121 // created as a mirror.
122 Subjects []string `json:"subjects,omitempty"`
123
124 // Retention defines the message retention policy for the stream.
125 // Defaults to LimitsPolicy.
126 Retention RetentionPolicy `json:"retention"`
127
128 // MaxConsumers specifies the maximum number of consumers allowed for
129 // the stream.
130 MaxConsumers int `json:"max_consumers"`
131
132 // MaxMsgs is the maximum number of messages the stream will store.
133 // After reaching the limit, stream adheres to the discard policy.
134 // If not set, server default is -1 (unlimited).
135 MaxMsgs int64 `json:"max_msgs"`
136
137 // MaxBytes is the maximum total size of messages the stream will store.
138 // After reaching the limit, stream adheres to the discard policy.
139 // If not set, server default is -1 (unlimited).
140 MaxBytes int64 `json:"max_bytes"`
141
142 // Discard defines the policy for handling messages when the stream
143 // reaches its limits in terms of number of messages or total bytes.
144 Discard DiscardPolicy `json:"discard"`
145
146 // DiscardNewPerSubject is a flag to enable discarding new messages per
147 // subject when limits are reached. Requires DiscardPolicy to be
148 // DiscardNew and the MaxMsgsPerSubject to be set.
149 DiscardNewPerSubject bool `json:"discard_new_per_subject,omitempty"`
150
151 // MaxAge is the maximum age of messages that the stream will retain.
152 MaxAge time.Duration `json:"max_age"`
153
154 // MaxMsgsPerSubject is the maximum number of messages per subject that
155 // the stream will retain.
156 MaxMsgsPerSubject int64 `json:"max_msgs_per_subject"`
157
158 // MaxMsgSize is the maximum size of any single message in the stream.
159 MaxMsgSize int32 `json:"max_msg_size,omitempty"`
160
161 // Storage specifies the type of storage backend used for the stream
162 // (file or memory).
163 Storage StorageType `json:"storage"`
164
165 // Replicas is the number of stream replicas in clustered JetStream.
166 // Defaults to 1, maximum is 5.
167 Replicas int `json:"num_replicas"`
168
169 // NoAck is a flag to disable acknowledging messages received by this
170 // stream.
171 //
172 // If set to true, publish methods from the JetStream client will not
173 // work as expected, since they rely on acknowledgements. Core NATS
174 // publish methods should be used instead. Note that this will make
175 // message delivery less reliable.
176 NoAck bool `json:"no_ack,omitempty"`
177
178 // Duplicates is the window within which to track duplicate messages.
179 // If not set, server default is 2 minutes.
180 Duplicates time.Duration `json:"duplicate_window,omitempty"`
181
182 // Placement is used to declare where the stream should be placed via
183 // tags and/or an explicit cluster name.
184 Placement *Placement `json:"placement,omitempty"`
185
186 // Mirror defines the configuration for mirroring another stream.
187 Mirror *StreamSource `json:"mirror,omitempty"`
188
189 // Sources is a list of other streams this stream sources messages from.
190 Sources []*StreamSource `json:"sources,omitempty"`
191
192 // Sealed streams do not allow messages to be published or deleted via limits or API,
193 // sealed streams can not be unsealed via configuration update. Can only
194 // be set on already created streams via the Update API.
195 Sealed bool `json:"sealed,omitempty"`
196
197 // DenyDelete restricts the ability to delete messages from a stream via
198 // the API. Defaults to false.
199 DenyDelete bool `json:"deny_delete,omitempty"`
200
201 // DenyPurge restricts the ability to purge messages from a stream via
202 // the API. Defaults to false.
203 DenyPurge bool `json:"deny_purge,omitempty"`
204
205 // AllowRollup allows the use of the Nats-Rollup header to replace all
206 // contents of a stream, or subject in a stream, with a single new
207 // message.
208 AllowRollup bool `json:"allow_rollup_hdrs,omitempty"`
209
210 // Compression specifies the message storage compression algorithm.
211 // Defaults to NoCompression.
212 Compression StoreCompression `json:"compression"`
213
214 // FirstSeq is the initial sequence number of the first message in the
215 // stream.
216 FirstSeq uint64 `json:"first_seq,omitempty"`
217
218 // SubjectTransform allows applying a transformation to matching
219 // messages' subjects.
220 SubjectTransform *SubjectTransformConfig `json:"subject_transform,omitempty"`
221
222 // RePublish allows immediate republishing a message to the configured
223 // subject after it's stored.
224 RePublish *RePublish `json:"republish,omitempty"`
225
226 // AllowDirect enables direct access to individual messages using direct
227 // get API. Defaults to false.
228 AllowDirect bool `json:"allow_direct"`
229
230 // MirrorDirect enables direct access to individual messages from the
231 // origin stream using direct get API. Defaults to false.
232 MirrorDirect bool `json:"mirror_direct"`
233
234 // ConsumerLimits defines limits of certain values that consumers can
235 // set, defaults for those who don't set these settings
236 ConsumerLimits StreamConsumerLimits `json:"consumer_limits,omitempty"`
237
238 // Metadata is a set of application-defined key-value pairs for
239 // associating metadata on the stream. This feature requires nats-server
240 // v2.10.0 or later.
241 Metadata map[string]string `json:"metadata,omitempty"`
242
243 // Template identifies the template that manages the Stream. Deprecated:
244 // This feature is no longer supported.
245 Template string `json:"template_owner,omitempty"`
246
247 // AllowMsgTTL allows header initiated per-message TTLs.
248 // This feature requires nats-server v2.11.0 or later.
249 AllowMsgTTL bool `json:"allow_msg_ttl"`
250
251 // Enables and sets a duration for adding server markers for delete, purge and max age limits.
252 // This feature requires nats-server v2.11.0 or later.
253 SubjectDeleteMarkerTTL time.Duration `json:"subject_delete_marker_ttl,omitempty"`
254 }
255
256 // SubjectTransformConfig is for applying a subject transform (to matching messages) before doing anything else when a new message is received.
257 type SubjectTransformConfig struct {
258 Source string `json:"src,omitempty"`
259 Destination string `json:"dest"`
260 }
261
262 // RePublish is for republishing messages once committed to a stream. The original
263 // subject cis remapped from the subject pattern to the destination pattern.
264 type RePublish struct {
265 Source string `json:"src,omitempty"`
266 Destination string `json:"dest"`
267 HeadersOnly bool `json:"headers_only,omitempty"`
268 }
269
270 // Placement is used to guide placement of streams in clustered JetStream.
271 type Placement struct {
272 Cluster string `json:"cluster"`
273 Tags []string `json:"tags,omitempty"`
274 }
275
276 // StreamSource dictates how streams can source from other streams.
277 type StreamSource struct {
278 Name string `json:"name"`
279 OptStartSeq uint64 `json:"opt_start_seq,omitempty"`
280 OptStartTime *time.Time `json:"opt_start_time,omitempty"`
281 FilterSubject string `json:"filter_subject,omitempty"`
282 SubjectTransforms []SubjectTransformConfig `json:"subject_transforms,omitempty"`
283 External *ExternalStream `json:"external,omitempty"`
284 Domain string `json:"-"`
285 }
286
287 // ExternalStream allows you to qualify access to a stream source in another
288 // account.
289 type ExternalStream struct {
290 APIPrefix string `json:"api"`
291 DeliverPrefix string `json:"deliver,omitempty"`
292 }
293
294 // StreamConsumerLimits are the limits for a consumer on a stream.
295 // These can be overridden on a per consumer basis.
296 type StreamConsumerLimits struct {
297 InactiveThreshold time.Duration `json:"inactive_threshold,omitempty"`
298 MaxAckPending int `json:"max_ack_pending,omitempty"`
299 }
300
301 // Helper for copying when we do not want to change user's version.
302 func (ss *StreamSource) copy() *StreamSource {
303 nss := *ss
304 // Check pointers
305 if ss.OptStartTime != nil {
306 t := *ss.OptStartTime
307 nss.OptStartTime = &t
308 }
309 if ss.External != nil {
310 ext := *ss.External
311 nss.External = &ext
312 }
313 return &nss
314 }
315
316 // If we have a Domain, convert to the appropriate ext.APIPrefix.
317 // This will change the stream source, so should be a copy passed in.
318 func (ss *StreamSource) convertDomain() error {
319 if ss.Domain == _EMPTY_ {
320 return nil
321 }
322 if ss.External != nil {
323 // These should be mutually exclusive.
324 // TODO(dlc) - Make generic?
325 return errors.New("nats: domain and external are both set")
326 }
327 ss.External = &ExternalStream{APIPrefix: fmt.Sprintf(jsExtDomainT, ss.Domain)}
328 return nil
329 }
330
331 // apiResponse is a standard response from the JetStream JSON API
332 type apiResponse struct {
333 Type string `json:"type"`
334 Error *APIError `json:"error,omitempty"`
335 }
336
337 // apiPaged includes variables used to create paged responses from the JSON API
338 type apiPaged struct {
339 Total int `json:"total"`
340 Offset int `json:"offset"`
341 Limit int `json:"limit"`
342 }
343
344 // apiPagedRequest includes parameters allowing specific pages to be requested
345 // from APIs responding with apiPaged.
346 type apiPagedRequest struct {
347 Offset int `json:"offset,omitempty"`
348 }
349
350 // AccountInfo contains info about the JetStream usage from the current account.
351 type AccountInfo struct {
352 Tier
353 Domain string `json:"domain"`
354 API APIStats `json:"api"`
355 Tiers map[string]Tier `json:"tiers"`
356 }
357
358 type Tier struct {
359 Memory uint64 `json:"memory"`
360 Store uint64 `json:"storage"`
361 ReservedMemory uint64 `json:"reserved_memory"`
362 ReservedStore uint64 `json:"reserved_storage"`
363 Streams int `json:"streams"`
364 Consumers int `json:"consumers"`
365 Limits AccountLimits `json:"limits"`
366 }
367
368 // APIStats reports on API calls to JetStream for this account.
369 type APIStats struct {
370 Level int `json:"level"`
371 Total uint64 `json:"total"`
372 Errors uint64 `json:"errors"`
373 Inflight uint64 `json:"inflight,omitempty"`
374 }
375
376 // AccountLimits includes the JetStream limits of the current account.
377 type AccountLimits struct {
378 MaxMemory int64 `json:"max_memory"`
379 MaxStore int64 `json:"max_storage"`
380 MaxStreams int `json:"max_streams"`
381 MaxConsumers int `json:"max_consumers"`
382 MaxAckPending int `json:"max_ack_pending"`
383 MemoryMaxStreamBytes int64 `json:"memory_max_stream_bytes"`
384 StoreMaxStreamBytes int64 `json:"storage_max_stream_bytes"`
385 MaxBytesRequired bool `json:"max_bytes_required"`
386 }
387
388 type accountInfoResponse struct {
389 apiResponse
390 AccountInfo
391 }
392
393 // AccountInfo fetches account information from the server, containing details
394 // about the account associated with this JetStream connection. If account is
395 // not enabled for JetStream, ErrJetStreamNotEnabledForAccount is returned.
396 //
397 // If the server does not have JetStream enabled, ErrJetStreamNotEnabled is
398 // returned (for a single server setup). For clustered topologies, AccountInfo
399 // will time out.
400 func (js *js) AccountInfo(opts ...JSOpt) (*AccountInfo, error) {
401 o, cancel, err := getJSContextOpts(js.opts, opts...)
402 if err != nil {
403 return nil, err
404 }
405 if cancel != nil {
406 defer cancel()
407 }
408
409 resp, err := js.apiRequestWithContext(o.ctx, o.apiSubj(apiAccountInfo), nil)
410 if err != nil {
411 // todo maybe nats server should never have no responder on this subject and always respond if they know there is no js to be had
412 if errors.Is(err, ErrNoResponders) {
413 err = ErrJetStreamNotEnabled
414 }
415 return nil, err
416 }
417 var info accountInfoResponse
418 if err := json.Unmarshal(resp.Data, &info); err != nil {
419 return nil, err
420 }
421 if info.Error != nil {
422 // Internally checks based on error code instead of description match.
423 if errors.Is(info.Error, ErrJetStreamNotEnabledForAccount) {
424 return nil, ErrJetStreamNotEnabledForAccount
425 }
426 return nil, info.Error
427 }
428
429 return &info.AccountInfo, nil
430 }
431
432 type createConsumerRequest struct {
433 Stream string `json:"stream_name"`
434 Config *ConsumerConfig `json:"config"`
435 }
436
437 type consumerResponse struct {
438 apiResponse
439 *ConsumerInfo
440 }
441
442 // AddConsumer adds a consumer to a stream.
443 // If the consumer already exists, and the configuration is the same, it
444 // will return the existing consumer.
445 // If the consumer already exists, and the configuration is different, it
446 // will return ErrConsumerNameAlreadyInUse.
447 func (js *js) AddConsumer(stream string, cfg *ConsumerConfig, opts ...JSOpt) (*ConsumerInfo, error) {
448 if cfg == nil {
449 cfg = &ConsumerConfig{}
450 }
451 consumerName := cfg.Name
452 if consumerName == _EMPTY_ {
453 consumerName = cfg.Durable
454 }
455 if consumerName != _EMPTY_ {
456 consInfo, err := js.ConsumerInfo(stream, consumerName, opts...)
457 if err != nil && !errors.Is(err, ErrConsumerNotFound) && !errors.Is(err, ErrStreamNotFound) {
458 return nil, err
459 }
460
461 if consInfo != nil {
462 sameConfig := checkConfig(&consInfo.Config, cfg)
463 if sameConfig != nil {
464 return nil, fmt.Errorf("%w: creating consumer %q on stream %q", ErrConsumerNameAlreadyInUse, consumerName, stream)
465 } else {
466 return consInfo, nil
467 }
468 }
469 }
470
471 return js.upsertConsumer(stream, consumerName, cfg, opts...)
472 }
473
474 func (js *js) UpdateConsumer(stream string, cfg *ConsumerConfig, opts ...JSOpt) (*ConsumerInfo, error) {
475 if cfg == nil {
476 return nil, ErrConsumerConfigRequired
477 }
478 consumerName := cfg.Name
479 if consumerName == _EMPTY_ {
480 consumerName = cfg.Durable
481 }
482 if consumerName == _EMPTY_ {
483 return nil, ErrConsumerNameRequired
484 }
485 return js.upsertConsumer(stream, consumerName, cfg, opts...)
486 }
487
488 func (js *js) upsertConsumer(stream, consumerName string, cfg *ConsumerConfig, opts ...JSOpt) (*ConsumerInfo, error) {
489 if err := checkStreamName(stream); err != nil {
490 return nil, err
491 }
492 o, cancel, err := getJSContextOpts(js.opts, opts...)
493 if err != nil {
494 return nil, err
495 }
496 if cancel != nil {
497 defer cancel()
498 }
499
500 req, err := json.Marshal(&createConsumerRequest{Stream: stream, Config: cfg})
501 if err != nil {
502 return nil, err
503 }
504
505 var ccSubj string
506 if consumerName == _EMPTY_ {
507 // if consumer name is empty (neither Durable nor Name is set), use the legacy ephemeral endpoint
508 ccSubj = fmt.Sprintf(apiLegacyConsumerCreateT, stream)
509 } else if err := checkConsumerName(consumerName); err != nil {
510 return nil, err
511 } else if js.nc.serverMinVersion(2, 9, 0) {
512 if cfg.Durable != "" && js.opts.featureFlags.useDurableConsumerCreate {
513 // if user set the useDurableConsumerCreate flag, use the legacy DURABLE.CREATE endpoint
514 ccSubj = fmt.Sprintf(apiDurableCreateT, stream, consumerName)
515 } else if cfg.FilterSubject == _EMPTY_ || cfg.FilterSubject == ">" {
516 // if filter subject is empty or ">", use the endpoint without filter subject
517 ccSubj = fmt.Sprintf(apiConsumerCreateT, stream, consumerName)
518 } else {
519 // safeguard against passing invalid filter subject in request subject
520 if cfg.FilterSubject[0] == '.' || cfg.FilterSubject[len(cfg.FilterSubject)-1] == '.' {
521 return nil, fmt.Errorf("%w: %q", ErrInvalidFilterSubject, cfg.FilterSubject)
522 }
523 // if filter subject is not empty, use the endpoint with filter subject
524 ccSubj = fmt.Sprintf(apiConsumerCreateWithFilterSubjectT, stream, consumerName, cfg.FilterSubject)
525 }
526 } else {
527 if cfg.Durable != "" {
528 // if Durable is set, use the DURABLE.CREATE endpoint
529 ccSubj = fmt.Sprintf(apiDurableCreateT, stream, consumerName)
530 } else {
531 // if Durable is not set, use the legacy ephemeral endpoint
532 ccSubj = fmt.Sprintf(apiLegacyConsumerCreateT, stream)
533 }
534 }
535
536 resp, err := js.apiRequestWithContext(o.ctx, o.apiSubj(ccSubj), req)
537 if err != nil {
538 if errors.Is(err, ErrNoResponders) {
539 err = ErrJetStreamNotEnabled
540 }
541 return nil, err
542 }
543 var info consumerResponse
544 err = json.Unmarshal(resp.Data, &info)
545 if err != nil {
546 return nil, err
547 }
548 if info.Error != nil {
549 if errors.Is(info.Error, ErrStreamNotFound) {
550 return nil, ErrStreamNotFound
551 }
552 if errors.Is(info.Error, ErrConsumerNotFound) {
553 return nil, ErrConsumerNotFound
554 }
555 return nil, info.Error
556 }
557
558 if info.Error == nil && info.ConsumerInfo == nil {
559 return nil, ErrConsumerCreationResponseEmpty
560 }
561
562 // check whether multiple filter subjects (if used) are reflected in the returned ConsumerInfo
563 if len(cfg.FilterSubjects) != 0 && len(info.Config.FilterSubjects) == 0 {
564 return nil, ErrConsumerMultipleFilterSubjectsNotSupported
565 }
566 return info.ConsumerInfo, nil
567 }
568
569 // consumerDeleteResponse is the response for a Consumer delete request.
570 type consumerDeleteResponse struct {
571 apiResponse
572 Success bool `json:"success,omitempty"`
573 }
574
575 func checkStreamName(stream string) error {
576 if stream == _EMPTY_ {
577 return ErrStreamNameRequired
578 }
579 if strings.ContainsAny(stream, ". ") {
580 return ErrInvalidStreamName
581 }
582 return nil
583 }
584
585 // Check that the consumer name is not empty and is valid (does not contain "." and " ").
586 // Additional consumer name validation is done in nats-server.
587 // Returns ErrConsumerNameRequired if consumer name is empty, ErrInvalidConsumerName is invalid, otherwise nil
588 func checkConsumerName(consumer string) error {
589 if consumer == _EMPTY_ {
590 return ErrConsumerNameRequired
591 }
592 if strings.ContainsAny(consumer, ". ") {
593 return ErrInvalidConsumerName
594 }
595 return nil
596 }
597
598 // DeleteConsumer deletes a Consumer.
599 func (js *js) DeleteConsumer(stream, consumer string, opts ...JSOpt) error {
600 if err := checkStreamName(stream); err != nil {
601 return err
602 }
603 if err := checkConsumerName(consumer); err != nil {
604 return err
605 }
606 o, cancel, err := getJSContextOpts(js.opts, opts...)
607 if err != nil {
608 return err
609 }
610 if cancel != nil {
611 defer cancel()
612 }
613
614 dcSubj := o.apiSubj(fmt.Sprintf(apiConsumerDeleteT, stream, consumer))
615 r, err := js.apiRequestWithContext(o.ctx, dcSubj, nil)
616 if err != nil {
617 return err
618 }
619 var resp consumerDeleteResponse
620 if err := json.Unmarshal(r.Data, &resp); err != nil {
621 return err
622 }
623
624 if resp.Error != nil {
625 if errors.Is(resp.Error, ErrConsumerNotFound) {
626 return ErrConsumerNotFound
627 }
628 return resp.Error
629 }
630 return nil
631 }
632
633 // ConsumerInfo returns information about a Consumer.
634 func (js *js) ConsumerInfo(stream, consumer string, opts ...JSOpt) (*ConsumerInfo, error) {
635 if err := checkStreamName(stream); err != nil {
636 return nil, err
637 }
638 if err := checkConsumerName(consumer); err != nil {
639 return nil, err
640 }
641 o, cancel, err := getJSContextOpts(js.opts, opts...)
642 if err != nil {
643 return nil, err
644 }
645 if cancel != nil {
646 defer cancel()
647 }
648 return js.getConsumerInfoContext(o.ctx, stream, consumer, o)
649 }
650
651 // consumerLister fetches pages of ConsumerInfo objects. This object is not
652 // safe to use for multiple threads.
653 type consumerLister struct {
654 stream string
655 js *js
656
657 err error
658 offset int
659 page []*ConsumerInfo
660 pageInfo *apiPaged
661 }
662
663 // consumersRequest is the type used for Consumers requests.
664 type consumersRequest struct {
665 apiPagedRequest
666 }
667
668 // consumerListResponse is the response for a Consumers List request.
669 type consumerListResponse struct {
670 apiResponse
671 apiPaged
672 Consumers []*ConsumerInfo `json:"consumers"`
673 }
674
675 // Next fetches the next ConsumerInfo page.
676 func (c *consumerLister) Next() bool {
677 if c.err != nil {
678 return false
679 }
680 if err := checkStreamName(c.stream); err != nil {
681 c.err = err
682 return false
683 }
684 if c.pageInfo != nil && c.offset >= c.pageInfo.Total {
685 return false
686 }
687
688 req, err := json.Marshal(consumersRequest{
689 apiPagedRequest: apiPagedRequest{Offset: c.offset},
690 })
691 if err != nil {
692 c.err = err
693 return false
694 }
695
696 var cancel context.CancelFunc
697 ctx := c.js.opts.ctx
698 if ctx == nil {
699 ctx, cancel = context.WithTimeout(context.Background(), c.js.opts.wait)
700 defer cancel()
701 }
702
703 clSubj := c.js.apiSubj(fmt.Sprintf(apiConsumerListT, c.stream))
704 r, err := c.js.apiRequestWithContext(ctx, clSubj, req)
705 if err != nil {
706 c.err = err
707 return false
708 }
709 var resp consumerListResponse
710 if err := json.Unmarshal(r.Data, &resp); err != nil {
711 c.err = err
712 return false
713 }
714 if resp.Error != nil {
715 c.err = resp.Error
716 return false
717 }
718
719 c.pageInfo = &resp.apiPaged
720 c.page = resp.Consumers
721 c.offset += len(c.page)
722 return true
723 }
724
725 // Page returns the current ConsumerInfo page.
726 func (c *consumerLister) Page() []*ConsumerInfo {
727 return c.page
728 }
729
730 // Err returns any errors found while fetching pages.
731 func (c *consumerLister) Err() error {
732 return c.err
733 }
734
735 // Consumers is used to retrieve a list of ConsumerInfo objects.
736 func (jsc *js) Consumers(stream string, opts ...JSOpt) <-chan *ConsumerInfo {
737 o, cancel, err := getJSContextOpts(jsc.opts, opts...)
738 if err != nil {
739 return nil
740 }
741
742 ch := make(chan *ConsumerInfo)
743 l := &consumerLister{js: &js{nc: jsc.nc, opts: o}, stream: stream}
744 go func() {
745 if cancel != nil {
746 defer cancel()
747 }
748 defer close(ch)
749 for l.Next() {
750 for _, info := range l.Page() {
751 select {
752 case ch <- info:
753 case <-o.ctx.Done():
754 return
755 }
756 }
757 }
758 }()
759
760 return ch
761 }
762
763 // ConsumersInfo is used to retrieve a list of ConsumerInfo objects.
764 // Deprecated: Use Consumers() instead.
765 func (jsc *js) ConsumersInfo(stream string, opts ...JSOpt) <-chan *ConsumerInfo {
766 return jsc.Consumers(stream, opts...)
767 }
768
769 type consumerNamesLister struct {
770 stream string
771 js *js
772
773 err error
774 offset int
775 page []string
776 pageInfo *apiPaged
777 }
778
779 // consumerNamesListResponse is the response for a Consumers Names List request.
780 type consumerNamesListResponse struct {
781 apiResponse
782 apiPaged
783 Consumers []string `json:"consumers"`
784 }
785
786 // Next fetches the next consumer names page.
787 func (c *consumerNamesLister) Next() bool {
788 if c.err != nil {
789 return false
790 }
791 if err := checkStreamName(c.stream); err != nil {
792 c.err = err
793 return false
794 }
795 if c.pageInfo != nil && c.offset >= c.pageInfo.Total {
796 return false
797 }
798
799 var cancel context.CancelFunc
800 ctx := c.js.opts.ctx
801 if ctx == nil {
802 ctx, cancel = context.WithTimeout(context.Background(), c.js.opts.wait)
803 defer cancel()
804 }
805
806 req, err := json.Marshal(consumersRequest{
807 apiPagedRequest: apiPagedRequest{Offset: c.offset},
808 })
809 if err != nil {
810 c.err = err
811 return false
812 }
813 clSubj := c.js.apiSubj(fmt.Sprintf(apiConsumerNamesT, c.stream))
814 r, err := c.js.apiRequestWithContext(ctx, clSubj, req)
815 if err != nil {
816 c.err = err
817 return false
818 }
819 var resp consumerNamesListResponse
820 if err := json.Unmarshal(r.Data, &resp); err != nil {
821 c.err = err
822 return false
823 }
824 if resp.Error != nil {
825 c.err = resp.Error
826 return false
827 }
828
829 c.pageInfo = &resp.apiPaged
830 c.page = resp.Consumers
831 c.offset += len(c.page)
832 return true
833 }
834
835 // Page returns the current ConsumerInfo page.
836 func (c *consumerNamesLister) Page() []string {
837 return c.page
838 }
839
840 // Err returns any errors found while fetching pages.
841 func (c *consumerNamesLister) Err() error {
842 return c.err
843 }
844
845 // ConsumerNames is used to retrieve a list of Consumer names.
846 func (jsc *js) ConsumerNames(stream string, opts ...JSOpt) <-chan string {
847 o, cancel, err := getJSContextOpts(jsc.opts, opts...)
848 if err != nil {
849 return nil
850 }
851
852 ch := make(chan string)
853 l := &consumerNamesLister{stream: stream, js: &js{nc: jsc.nc, opts: o}}
854 go func() {
855 if cancel != nil {
856 defer cancel()
857 }
858 defer close(ch)
859 for l.Next() {
860 for _, info := range l.Page() {
861 select {
862 case ch <- info:
863 case <-o.ctx.Done():
864 return
865 }
866 }
867 }
868 }()
869
870 return ch
871 }
872
873 // streamCreateResponse stream creation.
874 type streamCreateResponse struct {
875 apiResponse
876 *StreamInfo
877 }
878
879 func (js *js) AddStream(cfg *StreamConfig, opts ...JSOpt) (*StreamInfo, error) {
880 if cfg == nil {
881 return nil, ErrStreamConfigRequired
882 }
883 if err := checkStreamName(cfg.Name); err != nil {
884 return nil, err
885 }
886 o, cancel, err := getJSContextOpts(js.opts, opts...)
887 if err != nil {
888 return nil, err
889 }
890 if cancel != nil {
891 defer cancel()
892 }
893
894 // In case we need to change anything, copy so we do not change the caller's version.
895 ncfg := *cfg
896
897 // If we have a mirror and an external domain, convert to ext.APIPrefix.
898 if cfg.Mirror != nil && cfg.Mirror.Domain != _EMPTY_ {
899 // Copy so we do not change the caller's version.
900 ncfg.Mirror = ncfg.Mirror.copy()
901 if err := ncfg.Mirror.convertDomain(); err != nil {
902 return nil, err
903 }
904 }
905 // Check sources for the same.
906 if len(ncfg.Sources) > 0 {
907 ncfg.Sources = append([]*StreamSource(nil), ncfg.Sources...)
908 for i, ss := range ncfg.Sources {
909 if ss.Domain != _EMPTY_ {
910 ncfg.Sources[i] = ss.copy()
911 if err := ncfg.Sources[i].convertDomain(); err != nil {
912 return nil, err
913 }
914 }
915 }
916 }
917
918 req, err := json.Marshal(&ncfg)
919 if err != nil {
920 return nil, err
921 }
922
923 csSubj := o.apiSubj(fmt.Sprintf(apiStreamCreateT, cfg.Name))
924 r, err := js.apiRequestWithContext(o.ctx, csSubj, req)
925 if err != nil {
926 return nil, err
927 }
928 var resp streamCreateResponse
929 if err := json.Unmarshal(r.Data, &resp); err != nil {
930 return nil, err
931 }
932 if resp.Error != nil {
933 if errors.Is(resp.Error, ErrStreamNameAlreadyInUse) {
934 return nil, ErrStreamNameAlreadyInUse
935 }
936 return nil, resp.Error
937 }
938
939 // check that input subject transform (if used) is reflected in the returned ConsumerInfo
940 if cfg.SubjectTransform != nil && resp.StreamInfo.Config.SubjectTransform == nil {
941 return nil, ErrStreamSubjectTransformNotSupported
942 }
943 if len(cfg.Sources) != 0 {
944 if len(cfg.Sources) != len(resp.Config.Sources) {
945 return nil, ErrStreamSourceNotSupported
946 }
947 for i := range cfg.Sources {
948 if len(cfg.Sources[i].SubjectTransforms) != 0 && len(resp.Sources[i].SubjectTransforms) == 0 {
949 return nil, ErrStreamSourceMultipleSubjectTransformsNotSupported
950 }
951 }
952 }
953
954 return resp.StreamInfo, nil
955 }
956
957 type (
958 // StreamInfoRequest contains additional option to return
959 StreamInfoRequest struct {
960 apiPagedRequest
961 // DeletedDetails when true includes information about deleted messages
962 DeletedDetails bool `json:"deleted_details,omitempty"`
963 // SubjectsFilter when set, returns information on the matched subjects
964 SubjectsFilter string `json:"subjects_filter,omitempty"`
965 }
966 streamInfoResponse = struct {
967 apiResponse
968 apiPaged
969 *StreamInfo
970 }
971 )
972
973 func (js *js) StreamInfo(stream string, opts ...JSOpt) (*StreamInfo, error) {
974 if err := checkStreamName(stream); err != nil {
975 return nil, err
976 }
977 o, cancel, err := getJSContextOpts(js.opts, opts...)
978 if err != nil {
979 return nil, err
980 }
981 if cancel != nil {
982 defer cancel()
983 }
984
985 var i int
986 var subjectMessagesMap map[string]uint64
987 var req []byte
988 var requestPayload bool
989
990 var siOpts StreamInfoRequest
991 if o.streamInfoOpts != nil {
992 requestPayload = true
993 siOpts = *o.streamInfoOpts
994 }
995
996 for {
997 if requestPayload {
998 siOpts.Offset = i
999 if req, err = json.Marshal(&siOpts); err != nil {
1000 return nil, err
1001 }
1002 }
1003
1004 siSubj := o.apiSubj(fmt.Sprintf(apiStreamInfoT, stream))
1005
1006 r, err := js.apiRequestWithContext(o.ctx, siSubj, req)
1007 if err != nil {
1008 return nil, err
1009 }
1010
1011 var resp streamInfoResponse
1012 if err := json.Unmarshal(r.Data, &resp); err != nil {
1013 return nil, err
1014 }
1015
1016 if resp.Error != nil {
1017 if errors.Is(resp.Error, ErrStreamNotFound) {
1018 return nil, ErrStreamNotFound
1019 }
1020 return nil, resp.Error
1021 }
1022
1023 var total int
1024 // for backwards compatibility
1025 if resp.Total != 0 {
1026 total = resp.Total
1027 } else {
1028 total = len(resp.State.Subjects)
1029 }
1030
1031 if requestPayload && len(resp.StreamInfo.State.Subjects) > 0 {
1032 if subjectMessagesMap == nil {
1033 subjectMessagesMap = make(map[string]uint64, total)
1034 }
1035
1036 for k, j := range resp.State.Subjects {
1037 subjectMessagesMap[k] = j
1038 i++
1039 }
1040 }
1041
1042 if i >= total {
1043 if requestPayload {
1044 resp.StreamInfo.State.Subjects = subjectMessagesMap
1045 }
1046 return resp.StreamInfo, nil
1047 }
1048 }
1049 }
1050
1051 // StreamInfo shows config and current state for this stream.
1052 type StreamInfo struct {
1053 Config StreamConfig `json:"config"`
1054 Created time.Time `json:"created"`
1055 State StreamState `json:"state"`
1056 Cluster *ClusterInfo `json:"cluster,omitempty"`
1057 Mirror *StreamSourceInfo `json:"mirror,omitempty"`
1058 Sources []*StreamSourceInfo `json:"sources,omitempty"`
1059 Alternates []*StreamAlternate `json:"alternates,omitempty"`
1060 }
1061
1062 // StreamAlternate is an alternate stream represented by a mirror.
1063 type StreamAlternate struct {
1064 Name string `json:"name"`
1065 Domain string `json:"domain,omitempty"`
1066 Cluster string `json:"cluster"`
1067 }
1068
1069 // StreamSourceInfo shows information about an upstream stream source.
1070 type StreamSourceInfo struct {
1071 Name string `json:"name"`
1072 Lag uint64 `json:"lag"`
1073 Seq uint64 `json:"seq,omitempty"`
1074 Active time.Duration `json:"active"`
1075 External *ExternalStream `json:"external"`
1076 Error *APIError `json:"error"`
1077 FilterSubject string `json:"filter_subject,omitempty"`
1078 SubjectTransforms []SubjectTransformConfig `json:"subject_transforms,omitempty"`
1079 }
1080
1081 // StreamState is information about the given stream.
1082 type StreamState struct {
1083 Msgs uint64 `json:"messages"`
1084 Bytes uint64 `json:"bytes"`
1085 FirstSeq uint64 `json:"first_seq"`
1086 FirstTime time.Time `json:"first_ts"`
1087 LastSeq uint64 `json:"last_seq"`
1088 LastTime time.Time `json:"last_ts"`
1089 Consumers int `json:"consumer_count"`
1090 Deleted []uint64 `json:"deleted"`
1091 NumDeleted int `json:"num_deleted"`
1092 NumSubjects uint64 `json:"num_subjects"`
1093 Subjects map[string]uint64 `json:"subjects"`
1094 }
1095
1096 // ClusterInfo shows information about the underlying set of servers
1097 // that make up the stream or consumer.
1098 type ClusterInfo struct {
1099 Name string `json:"name,omitempty"`
1100 RaftGroup string `json:"raft_group,omitempty"`
1101 Leader string `json:"leader,omitempty"`
1102 LeaderSince *time.Time `json:"leader_since,omitempty"`
1103 SystemAcc bool `json:"system_account,omitempty"`
1104 TrafficAcc string `json:"traffic_account,omitempty"`
1105 Replicas []*PeerInfo `json:"replicas,omitempty"`
1106 Desired *DesiredClusterInfo `json:"desired,omitempty"`
1107 }
1108
1109 // DesiredClusterInfo shows the desired set of servers that should make up
1110 // the stream or consumer.
1111 type DesiredClusterInfo struct {
1112 Created time.Time `json:"created"`
1113 Name string `json:"name,omitempty"`
1114 Replicas []*DesiredPeerInfo `json:"replicas,omitempty"`
1115 Origin *DesiredClusterInfoOrigin `json:"origin,omitempty"`
1116 Status *DesiredClusterInfoStatus `json:"status,omitempty"`
1117 }
1118
1119 // DesiredClusterInfoOrigin is the configuration the reconfiguration can be
1120 // rolled back to if it is canceled.
1121 type DesiredClusterInfoOrigin struct {
1122 Replicas int `json:"replicas"`
1123 Placement *Placement `json:"placement,omitempty"`
1124 Retention *RetentionPolicy `json:"retention,omitempty"`
1125 }
1126
1127 // DesiredPeerInfo is a minimal version of PeerInfo describing a peer in the
1128 // desired peer set.
1129 type DesiredPeerInfo struct {
1130 Name string `json:"name"`
1131 Offline bool `json:"offline,omitempty"`
1132 Peer string `json:"peer"`
1133 }
1134
1135 // DesiredClusterInfoStatus is what the group leader is currently doing to
1136 // reach the desired state, or what it is waiting on.
1137 type DesiredClusterInfoStatus struct {
1138 Description string `json:"description"`
1139 Type MigrationStatusType `json:"type"`
1140 Err string `json:"err,omitempty"`
1141 }
1142
1143 // MigrationStatusType classifies a migration status by what has to change
1144 // for the migration to advance.
1145 type MigrationStatusType string
1146
1147 const (
1148 MigrationStatusMeta MigrationStatusType = "meta"
1149 MigrationStatusMembership MigrationStatusType = "membership"
1150 MigrationStatusSnapshot MigrationStatusType = "snapshot"
1151 MigrationStatusCatchup MigrationStatusType = "catchup"
1152 MigrationStatusQuorum MigrationStatusType = "quorum"
1153 MigrationStatusBlocked MigrationStatusType = "blocked"
1154 MigrationStatusUnavailable MigrationStatusType = "unavailable"
1155 )
1156
1157 // PeerInfo shows information about all the peers in the cluster that
1158 // are supporting the stream or consumer.
1159 type PeerInfo struct {
1160 Name string `json:"name"`
1161 Current bool `json:"current"`
1162 Offline bool `json:"offline,omitempty"`
1163 Active time.Duration `json:"active"`
1164 Lag uint64 `json:"lag,omitempty"`
1165 Peer string `json:"peer"`
1166 Pending bool `json:"pending,omitempty"`
1167 }
1168
1169 // UpdateStream updates a Stream.
1170 func (js *js) UpdateStream(cfg *StreamConfig, opts ...JSOpt) (*StreamInfo, error) {
1171 if cfg == nil {
1172 return nil, ErrStreamConfigRequired
1173 }
1174 if err := checkStreamName(cfg.Name); err != nil {
1175 return nil, err
1176 }
1177 o, cancel, err := getJSContextOpts(js.opts, opts...)
1178 if err != nil {
1179 return nil, err
1180 }
1181 if cancel != nil {
1182 defer cancel()
1183 }
1184
1185 req, err := json.Marshal(cfg)
1186 if err != nil {
1187 return nil, err
1188 }
1189
1190 usSubj := o.apiSubj(fmt.Sprintf(apiStreamUpdateT, cfg.Name))
1191 r, err := js.apiRequestWithContext(o.ctx, usSubj, req)
1192 if err != nil {
1193 return nil, err
1194 }
1195 var resp streamInfoResponse
1196 if err := json.Unmarshal(r.Data, &resp); err != nil {
1197 return nil, err
1198 }
1199 if resp.Error != nil {
1200 if errors.Is(resp.Error, ErrStreamNotFound) {
1201 return nil, ErrStreamNotFound
1202 }
1203 return nil, resp.Error
1204 }
1205
1206 // check that input subject transform (if used) is reflected in the returned StreamInfo
1207 if cfg.SubjectTransform != nil && resp.StreamInfo.Config.SubjectTransform == nil {
1208 return nil, ErrStreamSubjectTransformNotSupported
1209 }
1210
1211 if len(cfg.Sources) != 0 {
1212 if len(cfg.Sources) != len(resp.Config.Sources) {
1213 return nil, ErrStreamSourceNotSupported
1214 }
1215 for i := range cfg.Sources {
1216 if len(cfg.Sources[i].SubjectTransforms) != 0 && len(resp.Sources[i].SubjectTransforms) == 0 {
1217 return nil, ErrStreamSourceMultipleSubjectTransformsNotSupported
1218 }
1219 }
1220 }
1221
1222 return resp.StreamInfo, nil
1223 }
1224
1225 // streamDeleteResponse is the response for a Stream delete request.
1226 type streamDeleteResponse struct {
1227 apiResponse
1228 Success bool `json:"success,omitempty"`
1229 }
1230
1231 // DeleteStream deletes a Stream.
1232 func (js *js) DeleteStream(name string, opts ...JSOpt) error {
1233 if err := checkStreamName(name); err != nil {
1234 return err
1235 }
1236 o, cancel, err := getJSContextOpts(js.opts, opts...)
1237 if err != nil {
1238 return err
1239 }
1240 if cancel != nil {
1241 defer cancel()
1242 }
1243
1244 dsSubj := o.apiSubj(fmt.Sprintf(apiStreamDeleteT, name))
1245 r, err := js.apiRequestWithContext(o.ctx, dsSubj, nil)
1246 if err != nil {
1247 return err
1248 }
1249 var resp streamDeleteResponse
1250 if err := json.Unmarshal(r.Data, &resp); err != nil {
1251 return err
1252 }
1253
1254 if resp.Error != nil {
1255 if errors.Is(resp.Error, ErrStreamNotFound) {
1256 return ErrStreamNotFound
1257 }
1258 return resp.Error
1259 }
1260 return nil
1261 }
1262
1263 type apiMsgGetRequest struct {
1264 Seq uint64 `json:"seq,omitempty"`
1265 LastFor string `json:"last_by_subj,omitempty"`
1266 NextFor string `json:"next_by_subj,omitempty"`
1267 }
1268
1269 // RawStreamMsg is a raw message stored in JetStream.
1270 type RawStreamMsg struct {
1271 Subject string
1272 Sequence uint64
1273 Header Header
1274 Data []byte
1275 Time time.Time
1276 }
1277
1278 // storedMsg is a raw message stored in JetStream.
1279 type storedMsg struct {
1280 Subject string `json:"subject"`
1281 Sequence uint64 `json:"seq"`
1282 Header []byte `json:"hdrs,omitempty"`
1283 Data []byte `json:"data,omitempty"`
1284 Time time.Time `json:"time"`
1285 }
1286
1287 // apiMsgGetResponse is the response for a Stream get request.
1288 type apiMsgGetResponse struct {
1289 apiResponse
1290 Message *storedMsg `json:"message,omitempty"`
1291 }
1292
1293 // GetLastMsg retrieves the last raw stream message stored in JetStream by subject.
1294 func (js *js) GetLastMsg(name, subject string, opts ...JSOpt) (*RawStreamMsg, error) {
1295 return js.getMsg(name, &apiMsgGetRequest{LastFor: subject}, opts...)
1296 }
1297
1298 // GetMsg retrieves a raw stream message stored in JetStream by sequence number.
1299 func (js *js) GetMsg(name string, seq uint64, opts ...JSOpt) (*RawStreamMsg, error) {
1300 return js.getMsg(name, &apiMsgGetRequest{Seq: seq}, opts...)
1301 }
1302
1303 // Low level getMsg
1304 func (js *js) getMsg(name string, mreq *apiMsgGetRequest, opts ...JSOpt) (*RawStreamMsg, error) {
1305 o, cancel, err := getJSContextOpts(js.opts, opts...)
1306 if err != nil {
1307 return nil, err
1308 }
1309 if cancel != nil {
1310 defer cancel()
1311 }
1312
1313 if err := checkStreamName(name); err != nil {
1314 return nil, err
1315 }
1316
1317 var apiSubj string
1318 if o.directGet && mreq.LastFor != _EMPTY_ {
1319 apiSubj = apiDirectMsgGetLastBySubjectT
1320 dsSubj := o.apiSubj(fmt.Sprintf(apiSubj, name, mreq.LastFor))
1321 r, err := js.apiRequestWithContext(o.ctx, dsSubj, nil)
1322 if err != nil {
1323 return nil, err
1324 }
1325 return convertDirectGetMsgResponseToMsg(name, r)
1326 }
1327
1328 if o.directGet {
1329 apiSubj = apiDirectMsgGetT
1330 mreq.NextFor = o.directNextFor
1331 } else {
1332 apiSubj = apiMsgGetT
1333 }
1334
1335 req, err := json.Marshal(mreq)
1336 if err != nil {
1337 return nil, err
1338 }
1339
1340 dsSubj := o.apiSubj(fmt.Sprintf(apiSubj, name))
1341 r, err := js.apiRequestWithContext(o.ctx, dsSubj, req)
1342 if err != nil {
1343 return nil, err
1344 }
1345
1346 if o.directGet {
1347 return convertDirectGetMsgResponseToMsg(name, r)
1348 }
1349
1350 var resp apiMsgGetResponse
1351 if err := json.Unmarshal(r.Data, &resp); err != nil {
1352 return nil, err
1353 }
1354 if resp.Error != nil {
1355 if errors.Is(resp.Error, ErrMsgNotFound) {
1356 return nil, ErrMsgNotFound
1357 }
1358 if errors.Is(resp.Error, ErrStreamNotFound) {
1359 return nil, ErrStreamNotFound
1360 }
1361 return nil, resp.Error
1362 }
1363
1364 msg := resp.Message
1365
1366 var hdr Header
1367 if len(msg.Header) > 0 {
1368 hdr, err = DecodeHeadersMsg(msg.Header)
1369 if err != nil {
1370 return nil, err
1371 }
1372 }
1373
1374 return &RawStreamMsg{
1375 Subject: msg.Subject,
1376 Sequence: msg.Sequence,
1377 Header: hdr,
1378 Data: msg.Data,
1379 Time: msg.Time,
1380 }, nil
1381 }
1382
1383 func convertDirectGetMsgResponseToMsg(name string, r *Msg) (*RawStreamMsg, error) {
1384 // Check for 404/408. We would get a no-payload message and a "Status" header
1385 if len(r.Data) == 0 {
1386 val := r.Header.Get(statusHdr)
1387 if val != _EMPTY_ {
1388 switch val {
1389 case noMessagesSts:
1390 return nil, ErrMsgNotFound
1391 default:
1392 desc := r.Header.Get(descrHdr)
1393 if desc == _EMPTY_ {
1394 desc = "unable to get message"
1395 }
1396 return nil, fmt.Errorf("nats: %s", desc)
1397 }
1398 }
1399 }
1400 // Check for headers that give us the required information to
1401 // reconstruct the message.
1402 if len(r.Header) == 0 {
1403 return nil, errors.New("nats: response should have headers")
1404 }
1405 stream := r.Header.Get(JSStream)
1406 if stream == _EMPTY_ {
1407 return nil, errors.New("nats: missing stream header")
1408 }
1409
1410 // Mirrors can now answer direct gets, so removing check for name equality.
1411 // TODO(dlc) - We could have server also have a header with origin and check that?
1412
1413 seqStr := r.Header.Get(JSSequence)
1414 if seqStr == _EMPTY_ {
1415 return nil, errors.New("nats: missing sequence header")
1416 }
1417 seq, err := strconv.ParseUint(seqStr, 10, 64)
1418 if err != nil {
1419 return nil, fmt.Errorf("nats: invalid sequence header '%s': %v", seqStr, err)
1420 }
1421 timeStr := r.Header.Get(JSTimeStamp)
1422 if timeStr == _EMPTY_ {
1423 return nil, errors.New("nats: missing timestamp header")
1424 }
1425 // Temporary code: the server in main branch is sending with format
1426 // "2006-01-02 15:04:05.999999999 +0000 UTC", but will be changed
1427 // to use format RFC3339Nano. Because of server test deps/cycle,
1428 // support both until the server PR lands.
1429 tm, err := time.Parse(time.RFC3339Nano, timeStr)
1430 if err != nil {
1431 tm, err = time.Parse("2006-01-02 15:04:05.999999999 +0000 UTC", timeStr)
1432 if err != nil {
1433 return nil, fmt.Errorf("nats: invalid timestamp header '%s': %v", timeStr, err)
1434 }
1435 }
1436 subj := r.Header.Get(JSSubject)
1437 if subj == _EMPTY_ {
1438 return nil, errors.New("nats: missing subject header")
1439 }
1440 return &RawStreamMsg{
1441 Subject: subj,
1442 Sequence: seq,
1443 Header: r.Header,
1444 Data: r.Data,
1445 Time: tm,
1446 }, nil
1447 }
1448
1449 type msgDeleteRequest struct {
1450 Seq uint64 `json:"seq"`
1451 NoErase bool `json:"no_erase,omitempty"`
1452 }
1453
1454 // msgDeleteResponse is the response for a Stream delete request.
1455 type msgDeleteResponse struct {
1456 apiResponse
1457 Success bool `json:"success,omitempty"`
1458 }
1459
1460 // DeleteMsg deletes a message from a stream.
1461 // The message is marked as erased, but not overwritten
1462 func (js *js) DeleteMsg(name string, seq uint64, opts ...JSOpt) error {
1463 o, cancel, err := getJSContextOpts(js.opts, opts...)
1464 if err != nil {
1465 return err
1466 }
1467 if cancel != nil {
1468 defer cancel()
1469 }
1470
1471 return js.deleteMsg(o, name, &msgDeleteRequest{Seq: seq, NoErase: true})
1472 }
1473
1474 // SecureDeleteMsg deletes a message from a stream. The deleted message is overwritten with random data
1475 // As a result, this operation is slower than DeleteMsg()
1476 func (js *js) SecureDeleteMsg(name string, seq uint64, opts ...JSOpt) error {
1477 o, cancel, err := getJSContextOpts(js.opts, opts...)
1478 if err != nil {
1479 return err
1480 }
1481 if cancel != nil {
1482 defer cancel()
1483 }
1484
1485 return js.deleteMsg(o, name, &msgDeleteRequest{Seq: seq})
1486 }
1487
1488 func (js *js) deleteMsg(o *jsOpts, stream string, req *msgDeleteRequest) error {
1489 if err := checkStreamName(stream); err != nil {
1490 return err
1491 }
1492 reqJSON, err := json.Marshal(req)
1493 if err != nil {
1494 return err
1495 }
1496
1497 dsSubj := o.apiSubj(fmt.Sprintf(apiMsgDeleteT, stream))
1498 r, err := js.apiRequestWithContext(o.ctx, dsSubj, reqJSON)
1499 if err != nil {
1500 return err
1501 }
1502 var resp msgDeleteResponse
1503 if err := json.Unmarshal(r.Data, &resp); err != nil {
1504 return err
1505 }
1506 if resp.Error != nil {
1507 return resp.Error
1508 }
1509 return nil
1510 }
1511
1512 // StreamPurgeRequest is optional request information to the purge API.
1513 type StreamPurgeRequest struct {
1514 // Purge up to but not including sequence.
1515 Sequence uint64 `json:"seq,omitempty"`
1516 // Subject to match against messages for the purge command.
1517 Subject string `json:"filter,omitempty"`
1518 // Number of messages to keep.
1519 Keep uint64 `json:"keep,omitempty"`
1520 }
1521
1522 type streamPurgeResponse struct {
1523 apiResponse
1524 Success bool `json:"success,omitempty"`
1525 Purged uint64 `json:"purged"`
1526 }
1527
1528 // PurgeStream purges messages on a Stream.
1529 func (js *js) PurgeStream(stream string, opts ...JSOpt) error {
1530 if err := checkStreamName(stream); err != nil {
1531 return err
1532 }
1533 var req *StreamPurgeRequest
1534 var ok bool
1535 for _, opt := range opts {
1536 // For PurgeStream, only request body opt is relevant
1537 if req, ok = opt.(*StreamPurgeRequest); ok {
1538 break
1539 }
1540 }
1541 return js.purgeStream(stream, req)
1542 }
1543
1544 func (js *js) purgeStream(stream string, req *StreamPurgeRequest, opts ...JSOpt) error {
1545 o, cancel, err := getJSContextOpts(js.opts, opts...)
1546 if err != nil {
1547 return err
1548 }
1549 if cancel != nil {
1550 defer cancel()
1551 }
1552
1553 var b []byte
1554 if req != nil {
1555 if b, err = json.Marshal(req); err != nil {
1556 return err
1557 }
1558 }
1559
1560 psSubj := o.apiSubj(fmt.Sprintf(apiStreamPurgeT, stream))
1561 r, err := js.apiRequestWithContext(o.ctx, psSubj, b)
1562 if err != nil {
1563 return err
1564 }
1565 var resp streamPurgeResponse
1566 if err := json.Unmarshal(r.Data, &resp); err != nil {
1567 return err
1568 }
1569 if resp.Error != nil {
1570 if errors.Is(resp.Error, ErrBadRequest) {
1571 return fmt.Errorf("%w: %s", ErrBadRequest, "invalid purge request body")
1572 }
1573 return resp.Error
1574 }
1575 return nil
1576 }
1577
1578 // streamLister fetches pages of StreamInfo objects. This object is not safe
1579 // to use for multiple threads.
1580 type streamLister struct {
1581 js *js
1582 page []*StreamInfo
1583 err error
1584
1585 offset int
1586 pageInfo *apiPaged
1587 }
1588
1589 // streamListResponse list of detailed stream information.
1590 // A nil request is valid and means all streams.
1591 type streamListResponse struct {
1592 apiResponse
1593 apiPaged
1594 Streams []*StreamInfo `json:"streams"`
1595 }
1596
1597 // streamNamesRequest is used for Stream Name requests.
1598 type streamNamesRequest struct {
1599 apiPagedRequest
1600 // These are filters that can be applied to the list.
1601 Subject string `json:"subject,omitempty"`
1602 }
1603
1604 // Next fetches the next StreamInfo page.
1605 func (s *streamLister) Next() bool {
1606 if s.err != nil {
1607 return false
1608 }
1609 if s.pageInfo != nil && s.offset >= s.pageInfo.Total {
1610 return false
1611 }
1612
1613 req, err := json.Marshal(streamNamesRequest{
1614 apiPagedRequest: apiPagedRequest{Offset: s.offset},
1615 Subject: s.js.opts.streamListSubject,
1616 })
1617 if err != nil {
1618 s.err = err
1619 return false
1620 }
1621
1622 var cancel context.CancelFunc
1623 ctx := s.js.opts.ctx
1624 if ctx == nil {
1625 ctx, cancel = context.WithTimeout(context.Background(), s.js.opts.wait)
1626 defer cancel()
1627 }
1628
1629 slSubj := s.js.apiSubj(apiStreamListT)
1630 r, err := s.js.apiRequestWithContext(ctx, slSubj, req)
1631 if err != nil {
1632 s.err = err
1633 return false
1634 }
1635 var resp streamListResponse
1636 if err := json.Unmarshal(r.Data, &resp); err != nil {
1637 s.err = err
1638 return false
1639 }
1640 if resp.Error != nil {
1641 s.err = resp.Error
1642 return false
1643 }
1644
1645 s.pageInfo = &resp.apiPaged
1646 s.page = resp.Streams
1647 s.offset += len(s.page)
1648 return true
1649 }
1650
1651 // Page returns the current StreamInfo page.
1652 func (s *streamLister) Page() []*StreamInfo {
1653 return s.page
1654 }
1655
1656 // Err returns any errors found while fetching pages.
1657 func (s *streamLister) Err() error {
1658 return s.err
1659 }
1660
1661 // Streams can be used to retrieve a list of StreamInfo objects.
1662 func (jsc *js) Streams(opts ...JSOpt) <-chan *StreamInfo {
1663 o, cancel, err := getJSContextOpts(jsc.opts, opts...)
1664 if err != nil {
1665 return nil
1666 }
1667
1668 ch := make(chan *StreamInfo)
1669 l := &streamLister{js: &js{nc: jsc.nc, opts: o}}
1670 go func() {
1671 if cancel != nil {
1672 defer cancel()
1673 }
1674 defer close(ch)
1675 for l.Next() {
1676 for _, info := range l.Page() {
1677 select {
1678 case ch <- info:
1679 case <-o.ctx.Done():
1680 return
1681 }
1682 }
1683 }
1684 }()
1685
1686 return ch
1687 }
1688
1689 // StreamsInfo can be used to retrieve a list of StreamInfo objects.
1690 // Deprecated: Use Streams() instead.
1691 func (jsc *js) StreamsInfo(opts ...JSOpt) <-chan *StreamInfo {
1692 return jsc.Streams(opts...)
1693 }
1694
1695 type streamNamesLister struct {
1696 js *js
1697
1698 err error
1699 offset int
1700 page []string
1701 pageInfo *apiPaged
1702 }
1703
1704 // Next fetches the next stream names page.
1705 func (l *streamNamesLister) Next() bool {
1706 if l.err != nil {
1707 return false
1708 }
1709 if l.pageInfo != nil && l.offset >= l.pageInfo.Total {
1710 return false
1711 }
1712
1713 var cancel context.CancelFunc
1714 ctx := l.js.opts.ctx
1715 if ctx == nil {
1716 ctx, cancel = context.WithTimeout(context.Background(), l.js.opts.wait)
1717 defer cancel()
1718 }
1719
1720 req, err := json.Marshal(streamNamesRequest{
1721 apiPagedRequest: apiPagedRequest{Offset: l.offset},
1722 Subject: l.js.opts.streamListSubject,
1723 })
1724 if err != nil {
1725 l.err = err
1726 return false
1727 }
1728 r, err := l.js.apiRequestWithContext(ctx, l.js.apiSubj(apiStreams), req)
1729 if err != nil {
1730 l.err = err
1731 return false
1732 }
1733 var resp streamNamesResponse
1734 if err := json.Unmarshal(r.Data, &resp); err != nil {
1735 l.err = err
1736 return false
1737 }
1738 if resp.Error != nil {
1739 l.err = resp.Error
1740 return false
1741 }
1742
1743 l.pageInfo = &resp.apiPaged
1744 l.page = resp.Streams
1745 l.offset += len(l.page)
1746 return true
1747 }
1748
1749 // Page returns the current ConsumerInfo page.
1750 func (l *streamNamesLister) Page() []string {
1751 return l.page
1752 }
1753
1754 // Err returns any errors found while fetching pages.
1755 func (l *streamNamesLister) Err() error {
1756 return l.err
1757 }
1758
1759 // StreamNames is used to retrieve a list of Stream names.
1760 func (jsc *js) StreamNames(opts ...JSOpt) <-chan string {
1761 o, cancel, err := getJSContextOpts(jsc.opts, opts...)
1762 if err != nil {
1763 return nil
1764 }
1765
1766 ch := make(chan string)
1767 l := &streamNamesLister{js: &js{nc: jsc.nc, opts: o}}
1768 go func() {
1769 if cancel != nil {
1770 defer cancel()
1771 }
1772 defer close(ch)
1773 for l.Next() {
1774 for _, info := range l.Page() {
1775 select {
1776 case ch <- info:
1777 case <-o.ctx.Done():
1778 return
1779 }
1780 }
1781 }
1782 }()
1783
1784 return ch
1785 }
1786
1787 // StreamNameBySubject returns a stream name that matches the subject.
1788 func (jsc *js) StreamNameBySubject(subj string, opts ...JSOpt) (string, error) {
1789 o, cancel, err := getJSContextOpts(jsc.opts, opts...)
1790 if err != nil {
1791 return "", err
1792 }
1793 if cancel != nil {
1794 defer cancel()
1795 }
1796
1797 var slr streamNamesResponse
1798 req := &streamRequest{subj}
1799 j, err := json.Marshal(req)
1800 if err != nil {
1801 return _EMPTY_, err
1802 }
1803
1804 resp, err := jsc.apiRequestWithContext(o.ctx, o.apiSubj(apiStreams), j)
1805 if err != nil {
1806 if errors.Is(err, ErrNoResponders) {
1807 err = ErrJetStreamNotEnabled
1808 }
1809 return _EMPTY_, err
1810 }
1811 if err := json.Unmarshal(resp.Data, &slr); err != nil {
1812 return _EMPTY_, err
1813 }
1814
1815 if slr.Error != nil || len(slr.Streams) != 1 {
1816 return _EMPTY_, ErrNoMatchingStream
1817 }
1818 return slr.Streams[0], nil
1819 }
1820
1821 func getJSContextOpts(defs *jsOpts, opts ...JSOpt) (*jsOpts, context.CancelFunc, error) {
1822 var o jsOpts
1823 for _, opt := range opts {
1824 if err := opt.configureJSContext(&o); err != nil {
1825 return nil, nil, err
1826 }
1827 }
1828
1829 // Check for option collisions. Right now just timeout and context.
1830 if o.ctx != nil && o.wait != 0 {
1831 return nil, nil, ErrContextAndTimeout
1832 }
1833 if o.wait == 0 && o.ctx == nil {
1834 o.wait = defs.wait
1835 }
1836 var cancel context.CancelFunc
1837 if o.ctx == nil && o.wait > 0 {
1838 o.ctx, cancel = context.WithTimeout(context.Background(), o.wait)
1839 }
1840 if o.pre == _EMPTY_ {
1841 o.pre = defs.pre
1842 }
1843 if o.ctx != nil {
1844 // if context does not have a deadline, use timeout from js context
1845 if _, hasDeadline := o.ctx.Deadline(); !hasDeadline {
1846 o.ctx, cancel = context.WithTimeout(o.ctx, defs.wait)
1847 }
1848 }
1849 return &o, cancel, nil
1850 }