Debian Codegraph @

jetstream/consumer_config.go

raw
1 // Copyright 2022-2024 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 "encoding/json"
18 "fmt"
19 "time"
20 )
21
22 type (
23 // ConsumerInfo is the detailed information about a JetStream consumer.
24 ConsumerInfo struct {
25 // Stream specifies the name of the stream that the consumer is bound
26 // to.
27 Stream string `json:"stream_name"`
28
29 // Name represents the unique identifier for the consumer. This can be
30 // either set explicitly by the client or generated automatically if not
31 // set.
32 Name string `json:"name"`
33
34 // Created is the timestamp when the consumer was created.
35 Created time.Time `json:"created"`
36
37 // Config contains the configuration settings of the consumer, set when
38 // creating or updating the consumer.
39 Config ConsumerConfig `json:"config"`
40
41 // Delivered holds information about the most recently delivered
42 // message, including its sequence numbers and timestamp.
43 Delivered SequenceInfo `json:"delivered"`
44
45 // AckFloor indicates the message before the first unacknowledged
46 // message.
47 AckFloor SequenceInfo `json:"ack_floor"`
48
49 // NumAckPending is the number of messages that have been delivered but
50 // not yet acknowledged.
51 NumAckPending int `json:"num_ack_pending"`
52
53 // NumRedelivered counts the number of messages that have been
54 // redelivered and not yet acknowledged. Each message is counted only
55 // once, even if it has been redelivered multiple times. This count is
56 // reset when the message is eventually acknowledged.
57 NumRedelivered int `json:"num_redelivered"`
58
59 // NumWaiting is the count of active pull requests. It is only relevant
60 // for pull-based consumers.
61 NumWaiting int `json:"num_waiting"`
62
63 // NumPending is the number of messages that match the consumer's
64 // filter, but have not been delivered yet.
65 NumPending uint64 `json:"num_pending"`
66
67 // Cluster contains information about the cluster to which this consumer
68 // belongs (if applicable).
69 Cluster *ClusterInfo `json:"cluster,omitempty"`
70
71 // PushBound indicates whether at least one subscription exists for the
72 // delivery subject of this consumer. This is only applicable to
73 // push-based consumers.
74 PushBound bool `json:"push_bound,omitempty"`
75
76 // TimeStamp indicates when the info was gathered by the server.
77 TimeStamp time.Time `json:"ts"`
78
79 // PriorityGroups contains the information about the currently defined priority groups
80 PriorityGroups []PriorityGroupState `json:"priority_groups,omitempty"`
81
82 // Paused indicates whether the consumer is paused.
83 Paused bool `json:"paused,omitempty"`
84
85 // PauseRemaining contains the amount of time left until the consumer
86 // unpauses. It will only be non-zero if the consumer is currently paused.
87 PauseRemaining time.Duration `json:"pause_remaining,omitempty"`
88 }
89
90 PriorityGroupState struct {
91 // Group this status is for.
92 Group string `json:"group"`
93
94 // PinnedClientID is the generated ID of the pinned client.
95 PinnedClientID string `json:"pinned_client_id,omitempty"`
96
97 // PinnedTS is the timestamp when the client was pinned.
98 PinnedTS time.Time `json:"pinned_ts,omitempty"`
99 }
100
101 // ConsumerConfig represents the configuration of a JetStream consumer,
102 // encompassing both push and pull consumer settings
103 ConsumerConfig struct {
104 // Name is an optional name for the consumer. If not set, one is
105 // generated automatically.
106 //
107 // Name cannot contain whitespace, ., *, >, path separators (forward or
108 // backwards slash), and non-printable characters.
109 Name string `json:"name,omitempty"`
110
111 // Durable is an optional durable name for the consumer. If both Durable
112 // and Name are set, they have to be equal. Unless InactiveThreshold is set, a
113 // durable consumer will not be cleaned up automatically.
114 //
115 // Durable cannot contain whitespace, ., *, >, path separators (forward or
116 // backwards slash), and non-printable characters.
117 Durable string `json:"durable_name,omitempty"`
118
119 // Description provides an optional description of the consumer.
120 Description string `json:"description,omitempty"`
121
122 // DeliverPolicy defines from which point to start delivering messages
123 // from the stream. Defaults to DeliverAllPolicy.
124 DeliverPolicy DeliverPolicy `json:"deliver_policy"`
125
126 // OptStartSeq is an optional sequence number from which to start
127 // message delivery. Only applicable when DeliverPolicy is set to
128 // DeliverByStartSequencePolicy.
129 OptStartSeq uint64 `json:"opt_start_seq,omitempty"`
130
131 // OptStartTime is an optional time from which to start message
132 // delivery. Only applicable when DeliverPolicy is set to
133 // DeliverByStartTimePolicy.
134 OptStartTime *time.Time `json:"opt_start_time,omitempty"`
135
136 // AckPolicy defines the acknowledgement policy for the consumer.
137 // Defaults to AckExplicitPolicy.
138 AckPolicy AckPolicy `json:"ack_policy"`
139
140 // AckWait defines how long the server will wait for an acknowledgement
141 // before resending a message. If not set, server default is 30 seconds.
142 AckWait time.Duration `json:"ack_wait,omitempty"`
143
144 // MaxDeliver defines the maximum number of delivery attempts for a
145 // message. Applies to any message that is re-sent due to ack policy.
146 // If not set, server default is -1 (unlimited).
147 MaxDeliver int `json:"max_deliver,omitempty"`
148
149 // BackOff specifies the optional back-off intervals for retrying
150 // message delivery after a failed acknowledgement. It overrides
151 // AckWait.
152 //
153 // BackOff only applies to messages not acknowledged in specified time,
154 // not messages that were nack'ed.
155 //
156 // The number of intervals specified must be lower or equal to
157 // MaxDeliver. If the number of intervals is lower, the last interval is
158 // used for all remaining attempts.
159 BackOff []time.Duration `json:"backoff,omitempty"`
160
161 // FilterSubject can be used to filter messages delivered from the
162 // stream. FilterSubject is exclusive with FilterSubjects.
163 FilterSubject string `json:"filter_subject,omitempty"`
164
165 // ReplayPolicy defines the rate at which messages are sent to the
166 // consumer. If ReplayOriginalPolicy is set, messages are sent in the
167 // same intervals in which they were stored on stream. This can be used
168 // e.g. to simulate production traffic in development environments. If
169 // ReplayInstantPolicy is set, messages are sent as fast as possible.
170 // Defaults to ReplayInstantPolicy.
171 ReplayPolicy ReplayPolicy `json:"replay_policy"`
172
173 // RateLimit specifies an optional maximum rate of message delivery in
174 // bits per second.
175 RateLimit uint64 `json:"rate_limit_bps,omitempty"`
176
177 // SampleFrequency is an optional frequency for sampling how often
178 // acknowledgements are sampled for observability. See
179 // https://docs.nats.io/running-a-nats-service/nats_admin/monitoring/monitoring_jetstream
180 SampleFrequency string `json:"sample_freq,omitempty"`
181
182 // MaxWaiting is a maximum number of pull requests waiting to be
183 // fulfilled. If not set, this will inherit settings from stream's
184 // ConsumerLimits or (if those are not set) from account settings. If
185 // neither are set, server default is 512.
186 MaxWaiting int `json:"max_waiting,omitempty"`
187
188 // MaxAckPending is a maximum number of outstanding unacknowledged
189 // messages. Once this limit is reached, the server will suspend sending
190 // messages to the consumer. If not set, server default is 1000.
191 // Set to -1 for unlimited.
192 MaxAckPending int `json:"max_ack_pending,omitempty"`
193
194 // HeadersOnly indicates whether only headers of messages should be sent
195 // (and no payload). Defaults to false.
196 HeadersOnly bool `json:"headers_only,omitempty"`
197
198 // MaxRequestBatch is the optional maximum batch size a single pull
199 // request can make. When set with MaxRequestMaxBytes, the batch size
200 // will be constrained by whichever limit is hit first.
201 MaxRequestBatch int `json:"max_batch,omitempty"`
202
203 // MaxRequestExpires is the maximum duration a single pull request will
204 // wait for messages to be available to pull.
205 MaxRequestExpires time.Duration `json:"max_expires,omitempty"`
206
207 // MaxRequestMaxBytes is the optional maximum total bytes that can be
208 // requested in a given batch. When set with MaxRequestBatch, the batch
209 // size will be constrained by whichever limit is hit first.
210 MaxRequestMaxBytes int `json:"max_bytes,omitempty"`
211
212 // InactiveThreshold is a duration which instructs the server to clean
213 // up the consumer if it has been inactive for the specified duration.
214 // Durable consumers will not be cleaned up by default, but if
215 // InactiveThreshold is set, they will be. If not set, this will inherit
216 // settings from stream's ConsumerLimits. If neither are set, server
217 // default is 5 seconds.
218 //
219 // A consumer is considered inactive if no pull requests are received by
220 // the server (for pull consumers), or no interest is detected on the
221 // deliver subject (for push consumers), not if there are no
222 // messages to be delivered.
223 InactiveThreshold time.Duration `json:"inactive_threshold,omitempty"`
224
225 // Replicas is the number of replicas for the consumer's state. By
226 // default, consumers inherit the number of replicas from the stream.
227 Replicas int `json:"num_replicas"`
228
229 // MemoryStorage is a flag to force the consumer to use memory storage
230 // rather than inherit the storage type from the stream.
231 MemoryStorage bool `json:"mem_storage,omitempty"`
232
233 // FilterSubjects allows filtering messages from a stream by subject.
234 // This field is exclusive with FilterSubject. Requires nats-server
235 // v2.10.0 or later.
236 FilterSubjects []string `json:"filter_subjects,omitempty"`
237
238 // Metadata is a set of application-defined key-value pairs for
239 // associating metadata on the consumer. This feature requires
240 // nats-server v2.10.0 or later.
241 Metadata map[string]string `json:"metadata,omitempty"`
242
243 // PauseUntil is for suspending the consumer until the deadline.
244 PauseUntil *time.Time `json:"pause_until,omitempty"`
245
246 // PriorityPolicy represents the priority policy the consumer is set to.
247 // Requires nats-server v2.11.0 or later.
248 PriorityPolicy PriorityPolicy `json:"priority_policy,omitempty"`
249
250 // PinnedTTL represents the time after which the client will be unpinned
251 // if no new pull requests are sent. Used with PriorityPolicyPinned.
252 // Requires nats-server v2.11.0 or later.
253 PinnedTTL time.Duration `json:"priority_timeout,omitempty"`
254
255 // PriorityGroups is a list of priority groups this consumer supports.
256 PriorityGroups []string `json:"priority_groups,omitempty"`
257
258 // Fields specific to push consumers:
259
260 // DeliverSubject is the subject to deliver messages to for push consumers
261 DeliverSubject string `json:"deliver_subject,omitempty"`
262
263 // DeliverGroup is the group name for push consumers
264 DeliverGroup string `json:"deliver_group,omitempty"`
265
266 // FlowControl is a flag to enable flow control for the consumer.
267 // When set, the server will regularly send an empty message with status
268 // header 100 and a reply subject. Consumers must reply to these
269 // messages to control the rate of message delivery.
270 FlowControl bool `json:"flow_control,omitempty"`
271
272 // IdleHeartbeat enables push consumer idle heartbeat messages.
273 // If the Consumer is idle for more than the set value, an empty message
274 // with Status header 100 will be sent indicating the consumer is still
275 // alive.
276 IdleHeartbeat time.Duration `json:"idle_heartbeat,omitempty"`
277 }
278
279 // OrderedConsumerConfig is the configuration of an ordered JetStream
280 // consumer. For more information, see [Ordered Consumers] in README
281 //
282 // [Ordered Consumers]: https://github.com/nats-io/nats.go/blob/main/jetstream/README.md#ordered-consumers
283 OrderedConsumerConfig struct {
284 // FilterSubjects allows filtering messages from a stream by subject.
285 // This field is exclusive with FilterSubject. Requires nats-server
286 // v2.10.0 or later.
287 FilterSubjects []string `json:"filter_subjects,omitempty"`
288
289 // DeliverPolicy defines from which point to start delivering messages
290 // from the stream. Defaults to DeliverAllPolicy.
291 DeliverPolicy DeliverPolicy `json:"deliver_policy"`
292
293 // OptStartSeq is an optional sequence number from which to start
294 // message delivery. Only applicable when DeliverPolicy is set to
295 // DeliverByStartSequencePolicy.
296 OptStartSeq uint64 `json:"opt_start_seq,omitempty"`
297
298 // OptStartTime is an optional time from which to start message
299 // delivery. Only applicable when DeliverPolicy is set to
300 // DeliverByStartTimePolicy.
301 OptStartTime *time.Time `json:"opt_start_time,omitempty"`
302
303 // ReplayPolicy defines the rate at which messages are sent to the
304 // consumer. If ReplayOriginalPolicy is set, messages are sent in the
305 // same intervals in which they were stored on the stream. This can be
306 // used e.g. to simulate production traffic in development environments.
307 // If ReplayInstantPolicy is set, messages are sent as fast as possible.
308 // Defaults to ReplayInstantPolicy.
309 ReplayPolicy ReplayPolicy `json:"replay_policy"`
310
311 // InactiveThreshold is a duration which instructs the server to clean
312 // up the consumer if it has been inactive for the specified duration.
313 // Defaults to 5m.
314 InactiveThreshold time.Duration `json:"inactive_threshold,omitempty"`
315
316 // HeadersOnly indicates whether only headers of messages should be sent
317 // (and no payload). Defaults to false.
318 HeadersOnly bool `json:"headers_only,omitempty"`
319
320 // MaxResetAttempts is the maximum number of attempts to recreate the
321 // consumer in a single recovery cycle. Defaults to unlimited.
322 MaxResetAttempts int
323
324 // Metadata is a set of application-defined key-value pairs for
325 // associating metadata with the consumer. This feature requires
326 // nats-server v2.10.0 or later.
327 Metadata map[string]string `json:"metadata,omitempty"`
328
329 // NamePrefix is an optional custom prefix for the consumer name.
330 // If provided, ordered consumer names will be generated as:
331 // {NamePrefix}_{sequence_number} (e.g., "custom_1", "custom_2").
332 // If not provided, a unique ID (NUID) will be used as the prefix.
333 NamePrefix string `json:"-"`
334 }
335
336 // DeliverPolicy determines from which point to start delivering messages.
337 DeliverPolicy int
338
339 // AckPolicy determines how the consumer should acknowledge delivered
340 // messages.
341 AckPolicy int
342
343 // ReplayPolicy determines how the consumer should replay messages it
344 // already has queued in the stream.
345 ReplayPolicy int
346
347 // SequenceInfo has both the consumer and the stream sequence and last
348 // activity.
349 SequenceInfo struct {
350 Consumer uint64 `json:"consumer_seq"`
351 Stream uint64 `json:"stream_seq"`
352 Last *time.Time `json:"last_active,omitempty"`
353 }
354
355 // PriorityPolicy determines the priority policy the consumer is set to.
356 PriorityPolicy int
357 )
358
359 const (
360 // PriorityPolicyNone is the default priority policy.
361 PriorityPolicyNone PriorityPolicy = iota
362
363 // PriorityPolicyPinned is the priority policy that pins a consumer to a
364 // specific client.
365 PriorityPolicyPinned
366
367 // PriorityPolicyOverflow is the priority policy that allows for
368 // restricting when a consumer will receive messages based on the number of
369 // pending messages or acks.
370 PriorityPolicyOverflow
371
372 // PriorityPolicyPrioritized is the priority policy that allows for the
373 // server to deliver messages to clients based on their priority (instead
374 // of round-robin). Requires nats-server v2.12.0 or later.
375 PriorityPolicyPrioritized
376 )
377
378 func (p *PriorityPolicy) UnmarshalJSON(data []byte) error {
379 switch string(data) {
380 case jsonString(""):
381 *p = PriorityPolicyNone
382 case jsonString("pinned_client"):
383 *p = PriorityPolicyPinned
384 case jsonString("overflow"):
385 *p = PriorityPolicyOverflow
386 case jsonString("prioritized"):
387 *p = PriorityPolicyPrioritized
388 default:
389 return fmt.Errorf("nats: cannot unmarshal %q", data)
390 }
391 return nil
392 }
393
394 func (p PriorityPolicy) MarshalJSON() ([]byte, error) {
395 switch p {
396 case PriorityPolicyNone:
397 return json.Marshal("")
398 case PriorityPolicyPinned:
399 return json.Marshal("pinned_client")
400 case PriorityPolicyOverflow:
401 return json.Marshal("overflow")
402 case PriorityPolicyPrioritized:
403 return json.Marshal("prioritized")
404 }
405 return nil, fmt.Errorf("nats: unknown priority policy %v", p)
406 }
407
408 const (
409 // DeliverAllPolicy starts delivering messages from the very beginning of a
410 // stream. This is the default.
411 DeliverAllPolicy DeliverPolicy = iota
412
413 // DeliverLastPolicy will start the consumer with the last sequence
414 // received.
415 DeliverLastPolicy
416
417 // DeliverNewPolicy will only deliver new messages that are sent after the
418 // consumer is created.
419 DeliverNewPolicy
420
421 // DeliverByStartSequencePolicy will deliver messages starting from a given
422 // sequence configured with OptStartSeq in ConsumerConfig.
423 DeliverByStartSequencePolicy
424
425 // DeliverByStartTimePolicy will deliver messages starting from a given time
426 // configured with OptStartTime in ConsumerConfig.
427 DeliverByStartTimePolicy
428
429 // DeliverLastPerSubjectPolicy will start the consumer with the last message
430 // for all subjects received.
431 DeliverLastPerSubjectPolicy
432 )
433
434 func (p *DeliverPolicy) UnmarshalJSON(data []byte) error {
435 switch string(data) {
436 case jsonString("all"), jsonString("undefined"):
437 *p = DeliverAllPolicy
438 case jsonString("last"):
439 *p = DeliverLastPolicy
440 case jsonString("new"):
441 *p = DeliverNewPolicy
442 case jsonString("by_start_sequence"):
443 *p = DeliverByStartSequencePolicy
444 case jsonString("by_start_time"):
445 *p = DeliverByStartTimePolicy
446 case jsonString("last_per_subject"):
447 *p = DeliverLastPerSubjectPolicy
448 default:
449 return fmt.Errorf("nats: cannot unmarshal %q", data)
450 }
451
452 return nil
453 }
454
455 func (p DeliverPolicy) MarshalJSON() ([]byte, error) {
456 switch p {
457 case DeliverAllPolicy:
458 return json.Marshal("all")
459 case DeliverLastPolicy:
460 return json.Marshal("last")
461 case DeliverNewPolicy:
462 return json.Marshal("new")
463 case DeliverByStartSequencePolicy:
464 return json.Marshal("by_start_sequence")
465 case DeliverByStartTimePolicy:
466 return json.Marshal("by_start_time")
467 case DeliverLastPerSubjectPolicy:
468 return json.Marshal("last_per_subject")
469 }
470 return nil, fmt.Errorf("nats: unknown deliver policy %v", p)
471 }
472
473 func (p DeliverPolicy) String() string {
474 switch p {
475 case DeliverAllPolicy:
476 return "all"
477 case DeliverLastPolicy:
478 return "last"
479 case DeliverNewPolicy:
480 return "new"
481 case DeliverByStartSequencePolicy:
482 return "by_start_sequence"
483 case DeliverByStartTimePolicy:
484 return "by_start_time"
485 case DeliverLastPerSubjectPolicy:
486 return "last_per_subject"
487 }
488 return ""
489 }
490
491 const (
492 // AckExplicitPolicy requires ack or nack for all messages.
493 AckExplicitPolicy AckPolicy = iota
494
495 // AckAllPolicy when acking a sequence number, this implicitly acks all
496 // sequences below this one as well.
497 AckAllPolicy
498
499 // AckNonePolicy requires no acks for delivered messages.
500 AckNonePolicy
501
502 // AckFlowControlPolicy functions like AckAllPolicy, but acks based on
503 // responses to flow control. Used by durable stream sourcing and
504 // mirroring against an existing durable push consumer.
505 //
506 // This feature requires nats-server v2.14.0 or later.
507 AckFlowControlPolicy
508 )
509
510 func (p *AckPolicy) UnmarshalJSON(data []byte) error {
511 switch string(data) {
512 case jsonString("none"):
513 *p = AckNonePolicy
514 case jsonString("all"):
515 *p = AckAllPolicy
516 case jsonString("explicit"):
517 *p = AckExplicitPolicy
518 case jsonString("flow_control"):
519 *p = AckFlowControlPolicy
520 default:
521 return fmt.Errorf("nats: cannot unmarshal %q", data)
522 }
523 return nil
524 }
525
526 func (p AckPolicy) MarshalJSON() ([]byte, error) {
527 switch p {
528 case AckNonePolicy:
529 return json.Marshal("none")
530 case AckAllPolicy:
531 return json.Marshal("all")
532 case AckExplicitPolicy:
533 return json.Marshal("explicit")
534 case AckFlowControlPolicy:
535 return json.Marshal("flow_control")
536 }
537 return nil, fmt.Errorf("nats: unknown acknowledgement policy %v", p)
538 }
539
540 func (p AckPolicy) String() string {
541 switch p {
542 case AckNonePolicy:
543 return "AckNone"
544 case AckAllPolicy:
545 return "AckAll"
546 case AckExplicitPolicy:
547 return "AckExplicit"
548 case AckFlowControlPolicy:
549 return "AckFlowControl"
550 }
551 return "Unknown AckPolicy"
552 }
553
554 const (
555 // ReplayInstantPolicy will replay messages as fast as possible.
556 ReplayInstantPolicy ReplayPolicy = iota
557
558 // ReplayOriginalPolicy will maintain the same timing as the messages were
559 // received.
560 ReplayOriginalPolicy
561 )
562
563 func (p *ReplayPolicy) UnmarshalJSON(data []byte) error {
564 switch string(data) {
565 case jsonString("instant"):
566 *p = ReplayInstantPolicy
567 case jsonString("original"):
568 *p = ReplayOriginalPolicy
569 default:
570 return fmt.Errorf("nats: cannot unmarshal %q", data)
571 }
572 return nil
573 }
574
575 func (p ReplayPolicy) MarshalJSON() ([]byte, error) {
576 switch p {
577 case ReplayOriginalPolicy:
578 return json.Marshal("original")
579 case ReplayInstantPolicy:
580 return json.Marshal("instant")
581 }
582 return nil, fmt.Errorf("nats: unknown replay policy %v", p)
583 }
584
585 func (p ReplayPolicy) String() string {
586 switch p {
587 case ReplayOriginalPolicy:
588 return "original"
589 case ReplayInstantPolicy:
590 return "instant"
591 }
592 return ""
593 }