Debian Codegraph @

jetstream/consumer.go

raw
1 // Copyright 2022-2025 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 "crypto/sha256"
19 "encoding/json"
20 "fmt"
21 "strings"
22 "time"
23
24 "github.com/nats-io/nats.go/internal/syncx"
25 "github.com/nats-io/nuid"
26 )
27
28 type (
29
30 // Consumer contains methods for fetching/processing messages from a stream,
31 // as well as fetching consumer info.
32 //
33 // This package provides two implementations of Consumer interface:
34 //
35 // - Standard named/ephemeral pull consumers. These consumers are created using
36 // CreateConsumer method on Stream or JetStream interface. They can be
37 // explicitly configured (using [ConsumerConfig]) and managed by the user,
38 // either from this package or externally.
39 //
40 // - Ordered consumers. These consumers are created using OrderedConsumer
41 // method on Stream or JetStream interface. They are managed by the library
42 // and provide a simple way to consume messages from a stream. Ordered
43 // consumers are ephemeral in-memory pull consumers and are resilient to
44 // deletes and restarts. They provide limited configuration options
45 // using [OrderedConsumerConfig].
46 //
47 // Consumer provides methods for optimized continuous consumption of messages
48 // using Consume and Messages methods, as well as simple one-off messages
49 // retrieval using Fetch and Next methods.
50 Consumer interface {
51 // Fetch is used to retrieve up to a provided number of messages from a
52 // stream. This method will send a single request and deliver either all
53 // requested messages unless the timeout is met earlier. Fetch timeout
54 // defaults to 30 seconds and can be configured using FetchMaxWait
55 // option.
56 //
57 // By default, Fetch uses a 5s idle heartbeat for requests longer than
58 // 10 seconds. For shorter requests, the idle heartbeat is disabled.
59 // This can be configured using FetchHeartbeat option. If a client does
60 // not receive a heartbeat message from a stream for more than 2 times
61 // the idle heartbeat setting, Fetch will return [ErrNoHeartbeat].
62 //
63 // Fetch is non-blocking and returns MessageBatch, exposing a channel
64 // for delivered messages.
65 //
66 // Messages channel is always closed, thus it is safe to range over it
67 // without additional checks. After the channel is closed,
68 // MessageBatch.Error() should be checked to see if there was an error
69 // during message delivery (e.g. missing heartbeat).
70 //
71 // NOTE: Fetch has worse performance when used to continuously retrieve
72 // messages in comparison to Messages or Consume methods, as it does not
73 // perform any optimizations (e.g. overlapping pull requests) and new
74 // subscription is created for each execution.
75 Fetch(batch int, opts ...FetchOpt) (MessageBatch, error)
76
77 // FetchBytes is used to retrieve up to a provided number of bytes from
78 // the stream. This method will send a single request and deliver the
79 // provided number of bytes unless the timeout is met earlier. FetchBytes
80 // timeout defaults to 30 seconds and can be configured using
81 // FetchMaxWait option.
82 //
83 // By default, FetchBytes uses a 5s idle heartbeat for requests longer than
84 // 10 seconds. For shorter requests, the idle heartbeat is disabled.
85 // This can be configured using FetchHeartbeat option. If a client does
86 // not receive a heartbeat message from a stream for more than 2 times
87 // the idle heartbeat setting, FetchBytes will return [ErrNoHeartbeat].
88 //
89 // FetchBytes is non-blocking and returns MessageBatch, exposing a channel
90 // for delivered messages.
91 //
92 // Messages channel is always closed, thus it is safe to range over it
93 // without additional checks. After the channel is closed,
94 // MessageBatch.Error() should be checked to see if there was an error
95 // during message delivery (e.g. missing heartbeat).
96 //
97 // NOTE: FetchBytes has worse performance when used to continuously
98 // retrieve messages in comparison to Messages or Consume methods, as it
99 // does not perform any optimizations (e.g. overlapping pull requests)
100 // and new subscription is created for each execution.
101 FetchBytes(maxBytes int, opts ...FetchOpt) (MessageBatch, error)
102
103 // FetchNoWait is used to retrieve up to a provided number of messages
104 // from a stream. Unlike Fetch, FetchNoWait will only deliver messages
105 // that are currently available in the stream and will not wait for new
106 // messages to arrive, even if batch size is not met.
107 //
108 // FetchNoWait is non-blocking and returns MessageBatch, exposing a
109 // channel for delivered messages.
110 //
111 // Messages channel is always closed, thus it is safe to range over it
112 // without additional checks. After the channel is closed,
113 // MessageBatch.Error() should be checked to see if there was an error
114 // during message delivery (e.g. missing heartbeat).
115 //
116 // NOTE: FetchNoWait has worse performance when used to continuously
117 // retrieve messages in comparison to Messages or Consume methods, as it
118 // does not perform any optimizations (e.g. overlapping pull requests)
119 // and new subscription is created for each execution.
120 FetchNoWait(batch int) (MessageBatch, error)
121
122 // Consume will continuously receive messages and handle them
123 // with the provided callback function. Consume can be configured using
124 // PullConsumeOpt options:
125 //
126 // - Error handling and monitoring can be configured using ConsumeErrHandler
127 // option, which provides information about errors encountered during
128 // consumption (both transient and terminal)
129 // - Consume can be configured to stop after a certain number of
130 // messages have been received using StopAfter option.
131 // - Consume can be optimized for throughput or memory usage using
132 // PullExpiry, PullMaxMessages, PullMaxBytes and PullHeartbeat options.
133 // Unless there is a specific use case, these options should not be used.
134 //
135 // Consume returns a ConsumeContext, which can be used to stop or drain
136 // the consumer.
137 Consume(handler MessageHandler, opts ...PullConsumeOpt) (ConsumeContext, error)
138
139 // Messages returns MessagesContext, allowing continuous iteration
140 // over messages in a stream. Messages can be configured using
141 // PullMessagesOpt options:
142 //
143 // - Messages can be optimized for throughput or memory usage using
144 // PullExpiry, PullMaxMessages, PullMaxBytes and PullHeartbeat options.
145 // Unless there is a specific use case, these options should not be used.
146 // - WithMessagesErrOnMissingHeartbeat can be used to enable/disable
147 // erroring out on MessagesContext.Next when a heartbeat is missing.
148 // This option is enabled by default.
149 Messages(opts ...PullMessagesOpt) (MessagesContext, error)
150
151 // Next is used to retrieve the next message from the consumer. This
152 // method will block until the message is retrieved or the timeout
153 // is reached.
154 Next(opts ...FetchOpt) (Msg, error)
155
156 // Info fetches current ConsumerInfo from the server.
157 Info(context.Context) (*ConsumerInfo, error)
158
159 // CachedInfo returns ConsumerInfo currently cached on this consumer.
160 // This method does not perform any network requests. The cached
161 // ConsumerInfo is updated on every call to Info and Update.
162 CachedInfo() *ConsumerInfo
163 }
164
165 PushConsumer interface {
166 // Consume will continuously receive messages and handle them
167 // with the provided callback function. Consume can be configured using
168 // PushConsumeOpt options:
169 //
170 // - Error handling and monitoring can be configured using ConsumeErrHandler.
171 Consume(handler MessageHandler, opts ...PushConsumeOpt) (ConsumeContext, error)
172
173 // Info fetches current ConsumerInfo from the server.
174 Info(context.Context) (*ConsumerInfo, error)
175
176 // CachedInfo returns ConsumerInfo currently cached on this consumer.
177 CachedInfo() *ConsumerInfo
178 }
179
180 createConsumerRequest struct {
181 Stream string `json:"stream_name"`
182 Config *ConsumerConfig `json:"config"`
183 Action string `json:"action"`
184 }
185 )
186
187 // Info fetches current ConsumerInfo from the server.
188 func (p *pullConsumer) Info(ctx context.Context) (*ConsumerInfo, error) {
189 ctx, cancel := p.js.wrapContextWithoutDeadline(ctx)
190 if cancel != nil {
191 defer cancel()
192 }
193 infoSubject := fmt.Sprintf(apiConsumerInfoT, p.stream, p.name)
194 var resp consumerInfoResponse
195
196 if _, err := p.js.apiRequestJSON(ctx, infoSubject, &resp); err != nil {
197 return nil, err
198 }
199 if resp.Error != nil {
200 if resp.Error.ErrorCode == JSErrCodeConsumerNotFound {
201 return nil, ErrConsumerNotFound
202 }
203 return nil, resp.Error
204 }
205 if resp.Error == nil && resp.ConsumerInfo == nil {
206 return nil, ErrConsumerNotFound
207 }
208
209 p.info = resp.ConsumerInfo
210 return resp.ConsumerInfo, nil
211 }
212
213 // CachedInfo returns ConsumerInfo currently cached on this consumer.
214 // This method does not perform any network requests. The cached
215 // ConsumerInfo is updated on every call to Info and Update.
216 func (p *pullConsumer) CachedInfo() *ConsumerInfo {
217 return p.info
218 }
219
220 // Info fetches current ConsumerInfo from the server.
221 func (p *pushConsumer) Info(ctx context.Context) (*ConsumerInfo, error) {
222 ctx, cancel := p.js.wrapContextWithoutDeadline(ctx)
223 if cancel != nil {
224 defer cancel()
225 }
226 infoSubject := fmt.Sprintf(apiConsumerInfoT, p.stream, p.name)
227 var resp consumerInfoResponse
228
229 if _, err := p.js.apiRequestJSON(ctx, infoSubject, &resp); err != nil {
230 return nil, err
231 }
232 if resp.Error != nil {
233 if resp.Error.ErrorCode == JSErrCodeConsumerNotFound {
234 return nil, ErrConsumerNotFound
235 }
236 return nil, resp.Error
237 }
238 if resp.Error == nil && resp.ConsumerInfo == nil {
239 return nil, ErrConsumerNotFound
240 }
241
242 p.info = resp.ConsumerInfo
243 return resp.ConsumerInfo, nil
244 }
245
246 // CachedInfo returns ConsumerInfo currently cached on this consumer.
247 // This method does not perform any network requests. The cached
248 // ConsumerInfo is updated on every call to Info and Update.
249 func (p *pushConsumer) CachedInfo() *ConsumerInfo {
250 return p.info
251 }
252
253 func upsertPullConsumer(ctx context.Context, js *jetStream, stream string, cfg ConsumerConfig, action string) (Consumer, error) {
254 resp, err := upsertConsumer(ctx, js, stream, cfg, action)
255 if err != nil {
256 return nil, err
257 }
258
259 return &pullConsumer{
260 js: js,
261 stream: stream,
262 name: resp.Name,
263 durable: cfg.Durable != "",
264 info: resp.ConsumerInfo,
265 subs: syncx.Map[string, *pullSubscription]{},
266 }, nil
267 }
268
269 func upsertPushConsumer(ctx context.Context, js *jetStream, stream string, cfg ConsumerConfig, action string) (PushConsumer, error) {
270 if cfg.DeliverSubject == "" {
271 return nil, ErrNotPushConsumer
272 }
273
274 resp, err := upsertConsumer(ctx, js, stream, cfg, action)
275 if err != nil {
276 return nil, err
277 }
278
279 return &pushConsumer{
280 js: js,
281 stream: stream,
282 name: resp.Name,
283 info: resp.ConsumerInfo,
284 }, nil
285 }
286
287 func upsertConsumer(ctx context.Context, js *jetStream, stream string, cfg ConsumerConfig, action string) (*consumerInfoResponse, error) {
288 ctx, cancel := js.wrapContextWithoutDeadline(ctx)
289 if cancel != nil {
290 defer cancel()
291 }
292 req := createConsumerRequest{
293 Stream: stream,
294 Config: &cfg,
295 Action: action,
296 }
297 reqJSON, err := json.Marshal(req)
298 if err != nil {
299 return nil, err
300 }
301
302 consumerName := cfg.Name
303 if consumerName == "" {
304 if cfg.Durable != "" {
305 consumerName = cfg.Durable
306 } else {
307 consumerName = generateConsName()
308 }
309 }
310 if err := validateConsumerName(consumerName); err != nil {
311 return nil, err
312 }
313
314 var ccSubj string
315 if cfg.FilterSubject != "" && len(cfg.FilterSubjects) == 0 {
316 if err := validateSubject(cfg.FilterSubject); err != nil {
317 return nil, err
318 }
319 ccSubj = fmt.Sprintf(apiConsumerCreateWithFilterSubjectT, stream, consumerName, cfg.FilterSubject)
320 } else {
321 ccSubj = fmt.Sprintf(apiConsumerCreateT, stream, consumerName)
322 }
323 var resp consumerInfoResponse
324
325 if _, err := js.apiRequestJSON(ctx, ccSubj, &resp, reqJSON); err != nil {
326 return nil, err
327 }
328 if resp.Error != nil {
329 if resp.Error.ErrorCode == JSErrCodeStreamNotFound {
330 return nil, ErrStreamNotFound
331 }
332 if resp.Error.ErrorCode == JSErrCodeMaximumConsumersLimit {
333 return nil, ErrMaximumConsumersLimit
334 }
335
336 return nil, resp.Error
337 }
338
339 if resp.Error == nil && resp.ConsumerInfo == nil {
340 return nil, ErrConsumerCreationResponseEmpty
341 }
342
343 // check whether multiple filter subjects (if used) are reflected in the returned ConsumerInfo
344 if len(cfg.FilterSubjects) != 0 && len(resp.Config.FilterSubjects) == 0 {
345 return nil, ErrConsumerMultipleFilterSubjectsNotSupported
346 }
347
348 return &resp, nil
349 }
350
351 const (
352 consumerActionCreate = "create"
353 consumerActionUpdate = "update"
354 consumerActionCreateOrUpdate = ""
355 )
356
357 func generateConsName() string {
358 name := nuid.Next()
359 sha := sha256.New()
360 sha.Write([]byte(name))
361 b := sha.Sum(nil)
362 for i := 0; i < 8; i++ {
363 b[i] = rdigits[int(b[i]%base)]
364 }
365 return string(b[:8])
366 }
367
368 func getConsumer(ctx context.Context, js *jetStream, stream, name string) (Consumer, error) {
369 info, err := fetchConsumerInfo(ctx, js, stream, name)
370 if err != nil {
371 return nil, err
372 }
373
374 if info.Config.DeliverSubject != "" {
375 return nil, ErrNotPullConsumer
376 }
377
378 cons := &pullConsumer{
379 js: js,
380 stream: stream,
381 name: name,
382 durable: info.Config.Durable != "",
383 info: info,
384 subs: syncx.Map[string, *pullSubscription]{},
385 }
386
387 return cons, nil
388 }
389
390 func getPushConsumer(ctx context.Context, js *jetStream, stream, name string) (PushConsumer, error) {
391 info, err := fetchConsumerInfo(ctx, js, stream, name)
392 if err != nil {
393 return nil, err
394 }
395
396 if info.Config.DeliverSubject == "" {
397 return nil, ErrNotPushConsumer
398 }
399
400 cons := &pushConsumer{
401 js: js,
402 stream: stream,
403 name: name,
404 info: info,
405 }
406
407 return cons, nil
408 }
409
410 func fetchConsumerInfo(ctx context.Context, js *jetStream, stream, name string) (*ConsumerInfo, error) {
411 ctx, cancel := js.wrapContextWithoutDeadline(ctx)
412 if cancel != nil {
413 defer cancel()
414 }
415 if err := validateConsumerName(name); err != nil {
416 return nil, err
417 }
418 infoSubject := fmt.Sprintf(apiConsumerInfoT, stream, name)
419
420 var resp consumerInfoResponse
421
422 if _, err := js.apiRequestJSON(ctx, infoSubject, &resp); err != nil {
423 return nil, err
424 }
425 if resp.Error != nil {
426 if resp.Error.ErrorCode == JSErrCodeConsumerNotFound {
427 return nil, ErrConsumerNotFound
428 }
429 return nil, resp.Error
430 }
431 if resp.Error == nil && resp.ConsumerInfo == nil {
432 return nil, ErrConsumerNotFound
433 }
434
435 return resp.ConsumerInfo, nil
436 }
437
438 func deleteConsumer(ctx context.Context, js *jetStream, stream, consumer string) error {
439 ctx, cancel := js.wrapContextWithoutDeadline(ctx)
440 if cancel != nil {
441 defer cancel()
442 }
443 if err := validateConsumerName(consumer); err != nil {
444 return err
445 }
446 deleteSubject := fmt.Sprintf(apiConsumerDeleteT, stream, consumer)
447
448 var resp consumerDeleteResponse
449
450 if _, err := js.apiRequestJSON(ctx, deleteSubject, &resp); err != nil {
451 return err
452 }
453 if resp.Error != nil {
454 if resp.Error.ErrorCode == JSErrCodeConsumerNotFound {
455 return ErrConsumerNotFound
456 }
457 return resp.Error
458 }
459 return nil
460 }
461
462 func pauseConsumer(ctx context.Context, js *jetStream, stream, consumer string, pauseUntil *time.Time) (*ConsumerPauseResponse, error) {
463 ctx, cancel := js.wrapContextWithoutDeadline(ctx)
464 if cancel != nil {
465 defer cancel()
466 }
467 if err := validateConsumerName(consumer); err != nil {
468 return nil, err
469 }
470 subject := fmt.Sprintf(apiConsumerPauseT, stream, consumer)
471
472 var resp consumerPauseApiResponse
473 req, err := json.Marshal(consumerPauseRequest{
474 PauseUntil: pauseUntil,
475 })
476 if err != nil {
477 return nil, err
478 }
479 if _, err := js.apiRequestJSON(ctx, subject, &resp, req); err != nil {
480 return nil, err
481 }
482 if resp.Error != nil {
483 if resp.Error.ErrorCode == JSErrCodeConsumerNotFound {
484 return nil, ErrConsumerNotFound
485 }
486 return nil, resp.Error
487 }
488 return &ConsumerPauseResponse{
489 Paused: resp.Paused,
490 PauseUntil: resp.PauseUntil,
491 PauseRemaining: resp.PauseRemaining,
492 }, nil
493 }
494
495 func resumeConsumer(ctx context.Context, js *jetStream, stream, consumer string) (*ConsumerPauseResponse, error) {
496 return pauseConsumer(ctx, js, stream, consumer, nil)
497 }
498
499 func resetConsumer(ctx context.Context, js *jetStream, stream, consumer string, seq uint64) (*ConsumerResetResponse, error) {
500 ctx, cancel := js.wrapContextWithoutDeadline(ctx)
501 if cancel != nil {
502 defer cancel()
503 }
504 if err := validateConsumerName(consumer); err != nil {
505 return nil, err
506 }
507 subject := fmt.Sprintf(apiConsumerResetT, stream, consumer)
508
509 req, err := json.Marshal(consumerResetRequest{Seq: seq})
510 if err != nil {
511 return nil, err
512 }
513
514 var resp consumerResetApiResponse
515 if _, err := js.apiRequestJSON(ctx, subject, &resp, req); err != nil {
516 return nil, err
517 }
518 if resp.Error != nil {
519 if resp.Error.ErrorCode == JSErrCodeConsumerInvalidReset {
520 return nil, ErrConsumerInvalidReset
521 }
522 return nil, resp.Error
523 }
524 if resp.ConsumerInfo == nil {
525 return nil, ErrConsumerResetResponseEmpty
526 }
527 return &resp.ConsumerResetResponse, nil
528 }
529
530 func validateConsumerName(name string) error {
531 if name == "" {
532 return fmt.Errorf("%w: name is required", ErrInvalidConsumerName)
533 }
534 if strings.ContainsAny(name, ">*. /\\\t\r\n") {
535 return fmt.Errorf("%w: %q", ErrInvalidConsumerName, name)
536 }
537 return nil
538 }
539
540 func unpinConsumer(ctx context.Context, js *jetStream, stream, consumer, group string) error {
541 ctx, cancel := js.wrapContextWithoutDeadline(ctx)
542 if cancel != nil {
543 defer cancel()
544 }
545 if err := validateConsumerName(consumer); err != nil {
546 return err
547 }
548 unpinSubject := fmt.Sprintf(apiConsumerUnpinT, stream, consumer)
549
550 var req = consumerUnpinRequest{
551 Group: group,
552 }
553
554 reqJSON, err := json.Marshal(req)
555 if err != nil {
556 return err
557 }
558
559 var resp apiResponse
560
561 if _, err := js.apiRequestJSON(ctx, unpinSubject, &resp, reqJSON); err != nil {
562 return err
563 }
564 if resp.Error != nil {
565 if resp.Error.ErrorCode == JSErrCodeConsumerNotFound {
566 return ErrConsumerNotFound
567 }
568 return resp.Error
569 }
570
571 return nil
572 }