Debian Codegraph @

jetstream/stream.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 "strconv"
22 "time"
23
24 "github.com/nats-io/nats.go"
25 "github.com/nats-io/nuid"
26 )
27
28 type (
29 // Stream contains CRUD methods on a consumer via [ConsumerManager], as well
30 // as operations on an existing stream. It allows fetching and removing
31 // messages from a stream, as well as purging a stream.
32 Stream interface {
33 ConsumerManager
34
35 // Info returns StreamInfo from the server.
36 Info(ctx context.Context, opts ...StreamInfoOpt) (*StreamInfo, error)
37
38 // CachedInfo returns ConsumerInfo currently cached on this stream.
39 // This method does not perform any network requests. The cached
40 // StreamInfo is updated on every call to Info and Update.
41 CachedInfo() *StreamInfo
42
43 // Purge removes messages from a stream. It is a destructive operation.
44 // Use with caution. See StreamPurgeOpt for available options.
45 Purge(ctx context.Context, opts ...StreamPurgeOpt) error
46
47 // GetMsg retrieves a raw stream message stored in JetStream by sequence number.
48 GetMsg(ctx context.Context, seq uint64, opts ...GetMsgOpt) (*RawStreamMsg, error)
49
50 // GetLastMsgForSubject retrieves the last raw stream message stored in
51 // JetStream on a given subject.
52 GetLastMsgForSubject(ctx context.Context, subject string) (*RawStreamMsg, error)
53
54 // DeleteMsg deletes a message from a stream.
55 // On the server, the message is marked as erased, but not overwritten.
56 DeleteMsg(ctx context.Context, seq uint64) error
57
58 // SecureDeleteMsg deletes a message from a stream. The deleted message
59 // is overwritten with random data. As a result, this operation is slower
60 // than DeleteMsg.
61 SecureDeleteMsg(ctx context.Context, seq uint64) error
62 }
63
64 // ConsumerManager provides CRUD API for managing consumers. It is
65 // available as a part of [Stream] interface. CreateConsumer,
66 // UpdateConsumer, CreateOrUpdateConsumer and Consumer methods return a
67 // [Consumer] interface, allowing to operate on a consumer (e.g. consume
68 // messages).
69 ConsumerManager interface {
70 // CreateOrUpdateConsumer creates a pull consumer on a given stream with
71 // given config. If consumer already exists, it will be updated (if
72 // possible). Consumer interface is returned, allowing to operate on a
73 // consumer (e.g. fetch messages).
74 CreateOrUpdateConsumer(ctx context.Context, cfg ConsumerConfig) (Consumer, error)
75
76 // CreateConsumer creates a pull consumer on a given stream with given
77 // config. If consumer already exists and the provided configuration
78 // differs from its configuration, ErrConsumerExists is returned. If the
79 // provided configuration is the same as the existing consumer, the
80 // existing consumer is returned. Consumer interface is returned,
81 // allowing to operate on a consumer (e.g. fetch messages).
82 CreateConsumer(ctx context.Context, cfg ConsumerConfig) (Consumer, error)
83
84 // UpdateConsumer updates an existing pull consumer. If consumer does not
85 // exist, ErrConsumerDoesNotExist is returned. Consumer interface is
86 // returned, allowing to operate on a consumer (e.g. fetch messages).
87 UpdateConsumer(ctx context.Context, cfg ConsumerConfig) (Consumer, error)
88
89 // OrderedConsumer returns an OrderedConsumer instance. OrderedConsumer
90 // are managed by the library and provide a simple way to consume
91 // messages from a stream. Ordered consumers are ephemeral in-memory
92 // pull consumers and are resilient to deletes and restarts.
93 OrderedConsumer(ctx context.Context, cfg OrderedConsumerConfig) (Consumer, error)
94
95 // Consumer returns an interface to an existing consumer, allowing processing
96 // of messages. If consumer does not exist, ErrConsumerNotFound is
97 // returned.
98 //
99 // It returns ErrNotPullConsumer if the consumer is not a pull consumer (deliver subject is not set).
100 Consumer(ctx context.Context, consumer string) (Consumer, error)
101
102 // DeleteConsumer removes a consumer with given name from a stream.
103 // If consumer does not exist, ErrConsumerNotFound is returned.
104 DeleteConsumer(ctx context.Context, consumer string) error
105
106 // PauseConsumer pauses a consumer.
107 PauseConsumer(ctx context.Context, consumer string, pauseUntil time.Time) (*ConsumerPauseResponse, error)
108
109 // ResumeConsumer resumes a consumer.
110 ResumeConsumer(ctx context.Context, consumer string) (*ConsumerPauseResponse, error)
111
112 // ListConsumers returns ConsumerInfoLister enabling iterating over a
113 // channel of consumer infos.
114 ListConsumers(context.Context) ConsumerInfoLister
115
116 // ConsumerNames returns a ConsumerNameLister enabling iterating over a
117 // channel of consumer names.
118 ConsumerNames(context.Context) ConsumerNameLister
119
120 // UnpinConsumer unpins the currently pinned client for a consumer for the given group name.
121 // If consumer does not exist, ErrConsumerNotFound is returned.
122 UnpinConsumer(ctx context.Context, consumer string, group string) error
123
124 // ResetConsumer resets a consumer's delivery state without deleting
125 // and recreating it. The consumer is reset to deliver from
126 // ack_floor + 1.
127 ResetConsumer(ctx context.Context, consumer string) (*ConsumerResetResponse, error)
128
129 // ResetConsumerToSequence resets a consumer's delivery state to the
130 // given stream sequence. The seq must be compatible with the
131 // consumer's DeliverPolicy (e.g. for DeliverByStartSequencePolicy,
132 // seq must be >= OptStartSeq). If incompatible,
133 // ErrConsumerInvalidReset is returned.
134 ResetConsumerToSequence(ctx context.Context, consumer string, seq uint64) (*ConsumerResetResponse, error)
135
136 // CreateOrUpdatePushConsumer creates a push consumer on a given stream with
137 // given config. If consumer already exists, it will be updated (if
138 // possible). Consumer interface is returned, allowing to consume messages.
139 CreateOrUpdatePushConsumer(ctx context.Context, cfg ConsumerConfig) (PushConsumer, error)
140
141 // CreatePushConsumer creates a push consumer on a given stream with given
142 // config. If consumer already exists and the provided configuration
143 // differs from its configuration, ErrConsumerExists is returned. If the
144 // provided configuration is the same as the existing consumer, the
145 // existing consumer is returned. Consumer interface is returned,
146 // allowing to consume messages.
147 CreatePushConsumer(ctx context.Context, cfg ConsumerConfig) (PushConsumer, error)
148
149 // UpdatePushConsumer updates an existing push consumer. If consumer does not
150 // exist, ErrConsumerDoesNotExist is returned. Consumer interface is
151 // returned, allowing to consume messages.
152 UpdatePushConsumer(ctx context.Context, cfg ConsumerConfig) (PushConsumer, error)
153
154 // PushConsumer returns an interface to an existing push consumer, allowing processing
155 // of messages. If consumer does not exist, ErrConsumerNotFound is
156 // returned.
157 //
158 // It returns ErrNotPushConsumer if the consumer is not a push consumer (deliver subject is not set).
159 PushConsumer(ctx context.Context, consumer string) (PushConsumer, error)
160 }
161
162 RawStreamMsg struct {
163 Subject string
164 Sequence uint64
165 Header nats.Header
166 Data []byte
167 Time time.Time
168 }
169
170 stream struct {
171 name string
172 info *StreamInfo
173 js *jetStream
174 }
175
176 // StreamInfoOpt is a function setting options for [Stream.Info]
177 StreamInfoOpt func(*streamInfoRequest) error
178
179 streamInfoRequest struct {
180 apiPagedRequest
181 DeletedDetails bool `json:"deleted_details,omitempty"`
182 SubjectFilter string `json:"subjects_filter,omitempty"`
183 }
184
185 consumerInfoResponse struct {
186 apiResponse
187 *ConsumerInfo
188 }
189
190 // StreamPurgeOpt is a function setting options for [Stream.Purge]
191 StreamPurgeOpt func(*StreamPurgeRequest) error
192
193 // StreamPurgeRequest is an API request body to purge a stream.
194
195 StreamPurgeRequest struct {
196 // Purge up to but not including sequence.
197 Sequence uint64 `json:"seq,omitempty"`
198 // Subject to match against messages for the purge command.
199 Subject string `json:"filter,omitempty"`
200 // Number of messages to keep.
201 Keep uint64 `json:"keep,omitempty"`
202 }
203
204 streamPurgeResponse struct {
205 apiResponse
206 Success bool `json:"success,omitempty"`
207 Purged uint64 `json:"purged"`
208 }
209
210 consumerDeleteResponse struct {
211 apiResponse
212 Success bool `json:"success,omitempty"`
213 }
214
215 consumerPauseRequest struct {
216 PauseUntil *time.Time `json:"pause_until,omitempty"`
217 }
218
219 ConsumerPauseResponse struct {
220 // Paused is true if the consumer is paused.
221 Paused bool `json:"paused"`
222 // PauseUntil is the time until the consumer is paused.
223 PauseUntil time.Time `json:"pause_until"`
224 // PauseRemaining is the time remaining until the consumer is paused.
225 PauseRemaining time.Duration `json:"pause_remaining,omitempty"`
226 }
227
228 consumerPauseApiResponse struct {
229 apiResponse
230 ConsumerPauseResponse
231 }
232
233 consumerResetRequest struct {
234 Seq uint64 `json:"seq,omitempty"`
235 }
236
237 // ConsumerResetResponse contains the result of a consumer reset operation.
238 // It carries the updated ConsumerInfo together with the stream sequence the
239 // server actually reset the consumer to.
240 //
241 // The embedded *ConsumerInfo is guaranteed non-nil on a successful response;
242 // the helper returns ErrConsumerResetResponseEmpty if the server omits it.
243 ConsumerResetResponse struct {
244 *ConsumerInfo
245 // ResetSeq is the stream sequence the consumer was reset to. When
246 // ResetConsumer is called without an explicit sequence, this is the
247 // server-resolved value (typically ack_floor + 1).
248 ResetSeq uint64 `json:"reset_seq"`
249 }
250
251 consumerResetApiResponse struct {
252 apiResponse
253 ConsumerResetResponse
254 }
255
256 // GetMsgOpt is a function setting options for [Stream.GetMsg]
257 GetMsgOpt func(*apiMsgGetRequest) error
258
259 apiMsgGetRequest struct {
260 Seq uint64 `json:"seq,omitempty"`
261 LastFor string `json:"last_by_subj,omitempty"`
262 NextFor string `json:"next_by_subj,omitempty"`
263 }
264
265 // apiMsgGetResponse is the response for a Stream get request.
266 apiMsgGetResponse struct {
267 apiResponse
268 Message *storedMsg `json:"message,omitempty"`
269 }
270
271 // storedMsg is a raw message stored in JetStream.
272 storedMsg struct {
273 Subject string `json:"subject"`
274 Sequence uint64 `json:"seq"`
275 Header []byte `json:"hdrs,omitempty"`
276 Data []byte `json:"data,omitempty"`
277 Time time.Time `json:"time"`
278 }
279
280 msgDeleteRequest struct {
281 Seq uint64 `json:"seq"`
282 NoErase bool `json:"no_erase,omitempty"`
283 }
284
285 msgDeleteResponse struct {
286 apiResponse
287 Success bool `json:"success,omitempty"`
288 }
289
290 // ConsumerInfoLister is used to iterate over a channel of consumer infos.
291 // Err method can be used to check for errors encountered during iteration.
292 // Info channel is always closed and therefore can be used in a range loop.
293 ConsumerInfoLister interface {
294 Info() <-chan *ConsumerInfo
295 Err() error
296 }
297
298 // ConsumerNameLister is used to iterate over a channel of consumer names.
299 // Err method can be used to check for errors encountered during iteration.
300 // Name channel is always closed and therefore can be used in a range loop.
301 ConsumerNameLister interface {
302 Name() <-chan string
303 Err() error
304 }
305
306 consumerLister struct {
307 js *jetStream
308 offset int
309 pageInfo *apiPaged
310
311 consumers chan *ConsumerInfo
312 names chan string
313 err error
314 }
315
316 consumerListResponse struct {
317 apiResponse
318 apiPaged
319 Consumers []*ConsumerInfo `json:"consumers"`
320 }
321
322 consumerNamesResponse struct {
323 apiResponse
324 apiPaged
325 Consumers []string `json:"consumers"`
326 }
327
328 consumerUnpinRequest struct {
329 Group string `json:"group"`
330 }
331 )
332
333 // CreateOrUpdateConsumer creates a consumer on a given stream with
334 // given config. If consumer already exists, it will be updated (if
335 // possible). Consumer interface is returned, allowing to operate on a
336 // consumer (e.g. fetch messages).
337 func (s *stream) CreateOrUpdateConsumer(ctx context.Context, cfg ConsumerConfig) (Consumer, error) {
338 return upsertPullConsumer(ctx, s.js, s.name, cfg, consumerActionCreateOrUpdate)
339 }
340
341 // CreateConsumer creates a consumer on a given stream with given
342 // config. If consumer already exists and the provided configuration
343 // differs from its configuration, ErrConsumerExists is returned. If the
344 // provided configuration is the same as the existing consumer, the
345 // existing consumer is returned. Consumer interface is returned,
346 // allowing to operate on a consumer (e.g. fetch messages).
347 func (s *stream) CreateConsumer(ctx context.Context, cfg ConsumerConfig) (Consumer, error) {
348 return upsertPullConsumer(ctx, s.js, s.name, cfg, consumerActionCreate)
349 }
350
351 // UpdateConsumer updates an existing consumer. If consumer does not
352 // exist, ErrConsumerDoesNotExist is returned. Consumer interface is
353 // returned, allowing to operate on a consumer (e.g. fetch messages).
354 func (s *stream) UpdateConsumer(ctx context.Context, cfg ConsumerConfig) (Consumer, error) {
355 return upsertPullConsumer(ctx, s.js, s.name, cfg, consumerActionUpdate)
356 }
357
358 // CreateOrUpdatePushConsumer creates a consumer on a given stream with
359 // given config. If consumer already exists, it will be updated (if
360 // possible). Consumer interface is returned, allowing to consume messages.
361 func (s *stream) CreateOrUpdatePushConsumer(ctx context.Context, cfg ConsumerConfig) (PushConsumer, error) {
362 return upsertPushConsumer(ctx, s.js, s.name, cfg, consumerActionCreateOrUpdate)
363 }
364
365 // CreatePushConsumer creates a consumer on a given stream with given
366 // config. If consumer already exists and the provided configuration
367 // differs from its configuration, ErrConsumerExists is returned. If the
368 // provided configuration is the same as the existing consumer, the
369 // existing consumer is returned. Consumer interface is returned,
370 // allowing to consume messages.
371 func (s *stream) CreatePushConsumer(ctx context.Context, cfg ConsumerConfig) (PushConsumer, error) {
372 return upsertPushConsumer(ctx, s.js, s.name, cfg, consumerActionCreate)
373 }
374
375 // UpdatePushConsumer updates an existing consumer. If consumer does not
376 // exist, ErrConsumerDoesNotExist is returned. Consumer interface is
377 // returned, allowing to consume messages.
378 func (s *stream) UpdatePushConsumer(ctx context.Context, cfg ConsumerConfig) (PushConsumer, error) {
379 return upsertPushConsumer(ctx, s.js, s.name, cfg, consumerActionUpdate)
380 }
381
382 // OrderedConsumer returns an OrderedConsumer instance. OrderedConsumer
383 // are managed by the library and provide a simple way to consume
384 // messages from a stream. Ordered consumers are ephemeral in-memory
385 // pull consumers and are resilient to deletes and restarts.
386 func (s *stream) OrderedConsumer(ctx context.Context, cfg OrderedConsumerConfig) (Consumer, error) {
387 namePrefix := cfg.NamePrefix
388 if namePrefix == "" {
389 namePrefix = nuid.Next()
390 }
391 oc := &orderedConsumer{
392 js: s.js,
393 cfg: &cfg,
394 stream: s.name,
395 namePrefix: namePrefix,
396 doReset: make(chan struct{}, 1),
397 }
398 consCfg := oc.getConsumerConfig()
399 cons, err := s.CreateOrUpdateConsumer(ctx, *consCfg)
400 if err != nil {
401 return nil, err
402 }
403 oc.currentConsumer = cons.(*pullConsumer)
404
405 return oc, nil
406 }
407
408 // Consumer returns an interface to an existing consumer, allowing processing
409 // of messages. If consumer does not exist, ErrConsumerNotFound is
410 // returned.
411 func (s *stream) Consumer(ctx context.Context, name string) (Consumer, error) {
412 return getConsumer(ctx, s.js, s.name, name)
413 }
414
415 func (s *stream) PushConsumer(ctx context.Context, name string) (PushConsumer, error) {
416 return getPushConsumer(ctx, s.js, s.name, name)
417 }
418
419 // DeleteConsumer removes a consumer with given name from a stream.
420 // If consumer does not exist, ErrConsumerNotFound is returned.
421 func (s *stream) DeleteConsumer(ctx context.Context, name string) error {
422 return deleteConsumer(ctx, s.js, s.name, name)
423 }
424
425 // PauseConsumer pauses a consumer.
426 func (s *stream) PauseConsumer(ctx context.Context, name string, pauseUntil time.Time) (*ConsumerPauseResponse, error) {
427 return pauseConsumer(ctx, s.js, s.name, name, &pauseUntil)
428 }
429
430 // ResumeConsumer resumes a consumer.
431 func (s *stream) ResumeConsumer(ctx context.Context, name string) (*ConsumerPauseResponse, error) {
432 return resumeConsumer(ctx, s.js, s.name, name)
433 }
434
435 // Info returns StreamInfo from the server.
436 func (s *stream) Info(ctx context.Context, opts ...StreamInfoOpt) (*StreamInfo, error) {
437 ctx, cancel := s.js.wrapContextWithoutDeadline(ctx)
438 if cancel != nil {
439 defer cancel()
440 }
441 var infoReq *streamInfoRequest
442 for _, opt := range opts {
443 if infoReq == nil {
444 infoReq = &streamInfoRequest{}
445 }
446 if err := opt(infoReq); err != nil {
447 return nil, err
448 }
449 }
450 var req []byte
451 var err error
452 var subjectMap map[string]uint64
453 var offset int
454
455 infoSubject := fmt.Sprintf(apiStreamInfoT, s.name)
456 var info *StreamInfo
457 for {
458 if infoReq != nil {
459 if infoReq.SubjectFilter != "" {
460 if subjectMap == nil {
461 subjectMap = make(map[string]uint64)
462 }
463 infoReq.Offset = offset
464 }
465 req, err = json.Marshal(infoReq)
466 if err != nil {
467 return nil, err
468 }
469 }
470 var resp streamInfoResponse
471 if _, err = s.js.apiRequestJSON(ctx, infoSubject, &resp, req); err != nil {
472 return nil, err
473 }
474 if resp.Error != nil {
475 if resp.Error.ErrorCode == JSErrCodeStreamNotFound {
476 return nil, ErrStreamNotFound
477 }
478 return nil, resp.Error
479 }
480 if resp.StreamInfo == nil {
481 return nil, ErrInvalidJetStreamResponse
482 }
483 info = resp.StreamInfo
484 var total int
485 if resp.Total != 0 {
486 total = resp.Total
487 }
488 if len(resp.StreamInfo.State.Subjects) > 0 {
489 for subj, msgs := range resp.StreamInfo.State.Subjects {
490 subjectMap[subj] = msgs
491 }
492 offset = len(subjectMap)
493 }
494 if total == 0 || total <= offset {
495 info.State.Subjects = nil
496 // we don't want to store subjects in cache
497 cached := *info
498 s.info = &cached
499 info.State.Subjects = subjectMap
500 break
501 }
502 }
503
504 return info, nil
505 }
506
507 // CachedInfo returns ConsumerInfo currently cached on this stream.
508 // This method does not perform any network requests. The cached
509 // StreamInfo is updated on every call to Info and Update.
510 func (s *stream) CachedInfo() *StreamInfo {
511 return s.info
512 }
513
514 // Purge removes messages from a stream. It is a destructive operation.
515 // Use with caution. See StreamPurgeOpt for available options.
516 func (s *stream) Purge(ctx context.Context, opts ...StreamPurgeOpt) error {
517 ctx, cancel := s.js.wrapContextWithoutDeadline(ctx)
518 if cancel != nil {
519 defer cancel()
520 }
521 var purgeReq StreamPurgeRequest
522 for _, opt := range opts {
523 if err := opt(&purgeReq); err != nil {
524 return err
525 }
526 }
527 var req []byte
528 var err error
529 req, err = json.Marshal(purgeReq)
530 if err != nil {
531 return err
532 }
533
534 purgeSubject := fmt.Sprintf(apiStreamPurgeT, s.name)
535
536 var resp streamPurgeResponse
537 if _, err = s.js.apiRequestJSON(ctx, purgeSubject, &resp, req); err != nil {
538 return err
539 }
540 if resp.Error != nil {
541 return resp.Error
542 }
543
544 return nil
545 }
546
547 // GetMsg retrieves a raw stream message stored in JetStream by sequence number.
548 func (s *stream) GetMsg(ctx context.Context, seq uint64, opts ...GetMsgOpt) (*RawStreamMsg, error) {
549 req := &apiMsgGetRequest{Seq: seq}
550 for _, opt := range opts {
551 if err := opt(req); err != nil {
552 return nil, err
553 }
554 }
555 return s.getMsg(ctx, req)
556 }
557
558 // GetLastMsgForSubject retrieves the last raw stream message stored in
559 // JetStream on a given subject subject.
560 func (s *stream) GetLastMsgForSubject(ctx context.Context, subject string) (*RawStreamMsg, error) {
561 return s.getMsg(ctx, &apiMsgGetRequest{LastFor: subject})
562 }
563
564 func (s *stream) getMsg(ctx context.Context, mreq *apiMsgGetRequest) (*RawStreamMsg, error) {
565 ctx, cancel := s.js.wrapContextWithoutDeadline(ctx)
566 if cancel != nil {
567 defer cancel()
568 }
569 req, err := json.Marshal(mreq)
570 if err != nil {
571 return nil, err
572 }
573
574 var gmSubj string
575
576 // handle direct gets
577 if s.info.Config.AllowDirect {
578 if mreq.LastFor != "" {
579 gmSubj = fmt.Sprintf(apiDirectMsgGetLastBySubjectT, s.name, mreq.LastFor)
580 r, err := s.js.apiRequest(ctx, gmSubj, nil)
581 if err != nil {
582 return nil, err
583 }
584 return convertDirectGetMsgResponseToMsg(r.msg)
585 }
586 gmSubj = fmt.Sprintf(apiDirectMsgGetT, s.name)
587 r, err := s.js.apiRequest(ctx, gmSubj, req)
588 if err != nil {
589 return nil, err
590 }
591 return convertDirectGetMsgResponseToMsg(r.msg)
592 }
593
594 var resp apiMsgGetResponse
595 dsSubj := fmt.Sprintf(apiMsgGetT, s.name)
596 _, err = s.js.apiRequestJSON(ctx, dsSubj, &resp, req)
597 if err != nil {
598 return nil, err
599 }
600
601 if resp.Error != nil {
602 if resp.Error.ErrorCode == JSErrCodeMessageNotFound {
603 return nil, ErrMsgNotFound
604 }
605 return nil, resp.Error
606 }
607 if resp.Message == nil {
608 return nil, ErrInvalidJetStreamResponse
609 }
610
611 msg := resp.Message
612
613 var hdr nats.Header
614 if len(msg.Header) > 0 {
615 hdr, err = nats.DecodeHeadersMsg(msg.Header)
616 if err != nil {
617 return nil, err
618 }
619 }
620
621 return &RawStreamMsg{
622 Subject: msg.Subject,
623 Sequence: msg.Sequence,
624 Header: hdr,
625 Data: msg.Data,
626 Time: msg.Time,
627 }, nil
628 }
629
630 func convertDirectGetMsgResponseToMsg(r *nats.Msg) (*RawStreamMsg, error) {
631 // Check for 404/408. We would get a no-payload message and a "Status" header
632 if len(r.Data) == 0 {
633 val := r.Header.Get(statusHdr)
634 if val != "" {
635 switch val {
636 case statusNoMsgs:
637 return nil, ErrMsgNotFound
638 default:
639 desc := r.Header.Get("Description")
640 if desc == "" {
641 desc = "unable to get message"
642 }
643 return nil, fmt.Errorf("nats: %s", desc)
644 }
645 }
646 }
647
648 // Check for headers that give us the required information to
649 // reconstruct the message.
650 if len(r.Header) == 0 {
651 return nil, errors.New("nats: response should have headers")
652 }
653 stream := r.Header.Get(StreamHeader)
654 if stream == "" {
655 return nil, errors.New("nats: missing stream header")
656 }
657
658 seqStr := r.Header.Get(SequenceHeader)
659 if seqStr == "" {
660 return nil, errors.New("nats: missing sequence header")
661 }
662 seq, err := strconv.ParseUint(seqStr, 10, 64)
663 if err != nil {
664 return nil, fmt.Errorf("nats: invalid sequence header '%s': %v", seqStr, err)
665 }
666 timeStr := r.Header.Get(TimeStampHeaer)
667 if timeStr == "" {
668 return nil, errors.New("nats: missing timestamp header")
669 }
670
671 tm, err := time.Parse(time.RFC3339Nano, timeStr)
672 if err != nil {
673 return nil, fmt.Errorf("nats: invalid timestamp header '%s': %v", timeStr, err)
674 }
675 subj := r.Header.Get(SubjectHeader)
676 if subj == "" {
677 return nil, errors.New("nats: missing subject header")
678 }
679 return &RawStreamMsg{
680 Subject: subj,
681 Sequence: seq,
682 Header: r.Header,
683 Data: r.Data,
684 Time: tm,
685 }, nil
686 }
687
688 // DeleteMsg deletes a message from a stream.
689 // On the server, the message is marked as erased, but not overwritten.
690 func (s *stream) DeleteMsg(ctx context.Context, seq uint64) error {
691 return s.deleteMsg(ctx, &msgDeleteRequest{Seq: seq, NoErase: true})
692 }
693
694 // SecureDeleteMsg deletes a message from a stream. The deleted message
695 // is overwritten with random data. As a result, this operation is slower
696 // than DeleteMsg.
697 func (s *stream) SecureDeleteMsg(ctx context.Context, seq uint64) error {
698 return s.deleteMsg(ctx, &msgDeleteRequest{Seq: seq})
699 }
700
701 func (s *stream) deleteMsg(ctx context.Context, req *msgDeleteRequest) error {
702 ctx, cancel := s.js.wrapContextWithoutDeadline(ctx)
703 if cancel != nil {
704 defer cancel()
705 }
706 r, err := json.Marshal(req)
707 if err != nil {
708 return err
709 }
710 subj := fmt.Sprintf(apiMsgDeleteT, s.name)
711 var resp msgDeleteResponse
712 if _, err = s.js.apiRequestJSON(ctx, subj, &resp, r); err != nil {
713 return err
714 }
715 if !resp.Success {
716 return fmt.Errorf("%w: %s", ErrMsgDeleteUnsuccessful, resp.Error.Error())
717 }
718 return nil
719 }
720
721 // ListConsumers returns ConsumerInfoLister enabling iterating over a
722 // channel of consumer infos.
723 func (s *stream) ListConsumers(ctx context.Context) ConsumerInfoLister {
724 l := &consumerLister{
725 js: s.js,
726 consumers: make(chan *ConsumerInfo),
727 }
728 go func() {
729 defer close(l.consumers)
730 ctx, cancel := s.js.wrapContextWithoutDeadline(ctx)
731 if cancel != nil {
732 defer cancel()
733 }
734 for {
735 page, err := l.consumerInfos(ctx, s.name)
736 if err != nil && !errors.Is(err, ErrEndOfData) {
737 l.err = err
738 return
739 }
740 for _, info := range page {
741 select {
742 case <-ctx.Done():
743 l.err = ctx.Err()
744 return
745 default:
746 }
747 if info != nil {
748 l.consumers <- info
749 }
750 }
751 if errors.Is(err, ErrEndOfData) {
752 return
753 }
754 }
755 }()
756
757 return l
758 }
759
760 func (s *consumerLister) Info() <-chan *ConsumerInfo {
761 return s.consumers
762 }
763
764 func (s *consumerLister) Err() error {
765 return s.err
766 }
767
768 // ConsumerNames returns a ConsumerNameLister enabling iterating over a
769 // channel of consumer names.
770 func (s *stream) ConsumerNames(ctx context.Context) ConsumerNameLister {
771 l := &consumerLister{
772 js: s.js,
773 names: make(chan string),
774 }
775 go func() {
776 defer close(l.names)
777 ctx, cancel := s.js.wrapContextWithoutDeadline(ctx)
778 if cancel != nil {
779 defer cancel()
780 }
781 for {
782 page, err := l.consumerNames(ctx, s.name)
783 if err != nil && !errors.Is(err, ErrEndOfData) {
784 l.err = err
785 return
786 }
787 for _, info := range page {
788 select {
789 case l.names <- info:
790 case <-ctx.Done():
791 l.err = ctx.Err()
792 return
793 }
794 }
795 if errors.Is(err, ErrEndOfData) {
796 return
797 }
798 }
799 }()
800
801 return l
802 }
803
804 func (s *consumerLister) Name() <-chan string {
805 return s.names
806 }
807
808 // consumerInfos fetches the next ConsumerInfo page
809 func (s *consumerLister) consumerInfos(ctx context.Context, stream string) ([]*ConsumerInfo, error) {
810 if s.pageInfo != nil && s.offset >= s.pageInfo.Total {
811 return nil, ErrEndOfData
812 }
813
814 req, err := json.Marshal(
815 apiPagedRequest{Offset: s.offset},
816 )
817 if err != nil {
818 return nil, err
819 }
820
821 slSubj := fmt.Sprintf(apiConsumerListT, stream)
822 var resp consumerListResponse
823 _, err = s.js.apiRequestJSON(ctx, slSubj, &resp, req)
824 if err != nil {
825 return nil, err
826 }
827 if resp.Error != nil {
828 return nil, resp.Error
829 }
830
831 s.pageInfo = &resp.apiPaged
832 s.offset += len(resp.Consumers)
833 return resp.Consumers, nil
834 }
835
836 // consumerNames fetches the next consumer names page
837 func (s *consumerLister) consumerNames(ctx context.Context, stream string) ([]string, error) {
838 if s.pageInfo != nil && s.offset >= s.pageInfo.Total {
839 return nil, ErrEndOfData
840 }
841
842 req, err := json.Marshal(
843 apiPagedRequest{Offset: s.offset},
844 )
845 if err != nil {
846 return nil, err
847 }
848
849 slSubj := fmt.Sprintf(apiConsumerNamesT, stream)
850 var resp consumerNamesResponse
851 _, err = s.js.apiRequestJSON(ctx, slSubj, &resp, req)
852 if err != nil {
853 return nil, err
854 }
855 if resp.Error != nil {
856 return nil, resp.Error
857 }
858
859 s.pageInfo = &resp.apiPaged
860 s.offset += len(resp.Consumers)
861 return resp.Consumers, nil
862 }
863
864 // UnpinConsumer unpins the currently pinned client for a consumer for the given group name.
865 // If consumer does not exist, ErrConsumerNotFound is returned.
866 func (s *stream) UnpinConsumer(ctx context.Context, consumer string, group string) error {
867 return unpinConsumer(ctx, s.js, s.name, consumer, group)
868 }
869
870 // ResetConsumer resets a consumer's delivery state. See [Stream.ResetConsumer].
871 func (s *stream) ResetConsumer(ctx context.Context, consumer string) (*ConsumerResetResponse, error) {
872 return resetConsumer(ctx, s.js, s.name, consumer, 0)
873 }
874
875 // ResetConsumerToSequence resets a consumer's delivery state to the given
876 // stream sequence. See [Stream.ResetConsumerToSequence].
877 func (s *stream) ResetConsumerToSequence(ctx context.Context, consumer string, seq uint64) (*ConsumerResetResponse, error) {
878 return resetConsumer(ctx, s.js, s.name, consumer, seq)
879 }