Debian Codegraph @

jetstream/message.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 "bytes"
18 "context"
19 "errors"
20 "fmt"
21 "strconv"
22 "strings"
23 "sync"
24 "time"
25
26 "github.com/nats-io/nats.go"
27 "github.com/nats-io/nats.go/internal/parser"
28 )
29
30 type (
31 // Msg contains methods to operate on a JetStream message. Metadata, Data,
32 // Headers, Subject and Reply can be used to retrieve the specific parts of
33 // the underlying message. Ack, DoubleAck, Nak, NakWithDelay, InProgress and
34 // Term are various flavors of ack requests.
35 Msg interface {
36 // Metadata returns [MsgMetadata] for a JetStream message.
37 Metadata() (*MsgMetadata, error)
38
39 // Data returns the message body.
40 Data() []byte
41
42 // Headers returns a map of headers for a message.
43 Headers() nats.Header
44
45 // Subject returns a subject on which a message was published/received.
46 Subject() string
47
48 // Reply returns a reply subject for a message.
49 Reply() string
50
51 // Ack acknowledges a message. This tells the server that the message was
52 // successfully processed and it can move on to the next message.
53 Ack() error
54
55 // DoubleAck acknowledges a message and waits for ack reply from the server.
56 // While it impacts performance, it is useful for scenarios where
57 // message loss is not acceptable.
58 DoubleAck(context.Context) error
59
60 // Nak negatively acknowledges a message. This tells the server to
61 // redeliver the message.
62 //
63 // Nak does not adhere to AckWait or Backoff configured on the consumer
64 // and triggers instant redelivery. For a delayed redelivery, use
65 // NakWithDelay.
66 Nak() error
67
68 // NakWithDelay negatively acknowledges a message. This tells the server
69 // to redeliver the message after the given delay.
70 NakWithDelay(delay time.Duration) error
71
72 // InProgress tells the server that this message is being worked on. It
73 // resets the redelivery timer on the server.
74 InProgress() error
75
76 // Term tells the server to not redeliver this message, regardless of
77 // the value of MaxDeliver.
78 Term() error
79
80 // TermWithReason tells the server to not redeliver this message, regardless of
81 // the value of MaxDeliver. The provided reason will be included in JetStream
82 // advisory event sent by the server.
83 //
84 // Note: This will only work with JetStream servers >= 2.10.4.
85 // For older servers, TermWithReason will be ignored by the server and the message
86 // will not be terminated.
87 TermWithReason(reason string) error
88 }
89
90 // MsgMetadata is the JetStream metadata associated with received messages.
91 MsgMetadata struct {
92 // Sequence is the sequence information for the message.
93 Sequence SequencePair
94
95 // NumDelivered is the number of times this message was delivered to the
96 // consumer.
97 NumDelivered uint64
98
99 // NumPending is the number of messages that match the consumer's
100 // filter, but have not been delivered yet.
101 NumPending uint64
102
103 // Timestamp is the time the message was originally stored on a stream.
104 Timestamp time.Time
105
106 // Stream is the stream name this message is stored on.
107 Stream string
108
109 // Consumer is the consumer name this message was delivered to.
110 Consumer string
111
112 // Domain is the domain this message was received on.
113 Domain string
114 }
115
116 // SequencePair includes the consumer and stream sequence numbers for a
117 // message.
118 SequencePair struct {
119 // Consumer is the consumer sequence number for message deliveries. This
120 // is the total number of messages the consumer has seen (including
121 // redeliveries).
122 Consumer uint64 `json:"consumer_seq"`
123
124 // Stream is the stream sequence number for a message.
125 Stream uint64 `json:"stream_seq"`
126 }
127
128 jetStreamMsg struct {
129 msg *nats.Msg
130 ackd bool
131 js *jetStream
132 sync.Mutex
133 }
134
135 ackOpts struct {
136 nakDelay time.Duration
137 termReason string
138 }
139
140 ackType []byte
141 )
142
143 const (
144 statusControlMsg = "100"
145 statusBadRequest = "400"
146 statusNoMsgs = "404"
147 statusTimeout = "408"
148 statusConflict = "409"
149 statusNoResponders = "503"
150 statusPinIdMismatch = "423"
151
152 fcRequestDescr = "flowcontrol request"
153 idleHeartbeatDescr = "idle heartbeat"
154 consumerDeleted = "consumer deleted"
155 leadershipChange = "leadership change"
156 maxBytesExceeded = "message size exceeds maxbytes"
157 batchCompleted = "batch completed"
158 serverShutdown = "server shutdown"
159 )
160
161 // Headers used when publishing messages.
162 const (
163 // MsgIdHeader is used to specify a user-defined message ID. It can be used
164 // e.g. for deduplication in conjunction with the Duplicates duration on
165 // ConsumerConfig or to provide optimistic concurrency safety together with
166 // [ExpectedLastMsgIDHeader].
167 //
168 // This can be set when publishing messages using [WithMsgID] option.
169 MsgIDHeader = "Nats-Msg-Id"
170
171 // ExpectedStreamHeader contains stream name and is used to assure that the
172 // published message is received by expected stream. Server will reject the
173 // message if it is not the case.
174 //
175 // This can be set when publishing messages using [WithExpectStream] option.
176 ExpectedStreamHeader = "Nats-Expected-Stream"
177
178 // ExpectedLastSeqHeader contains the expected last sequence number of the
179 // stream and can be used to apply optimistic concurrency control at stream
180 // level. Server will reject the message if it is not the case.
181 //
182 // This can be set when publishing messages using [WithExpectLastSequence]
183 // option.
184 ExpectedLastSeqHeader = "Nats-Expected-Last-Sequence"
185
186 // ExpectedLastSubjSeqHeader contains the expected last sequence number on
187 // the subject and can be used to apply optimistic concurrency control at
188 // subject level. Server will reject the message if it is not the case.
189 //
190 // This can be set when publishing messages using
191 // [WithExpectLastSequencePerSubject] option.
192 ExpectedLastSubjSeqHeader = "Nats-Expected-Last-Subject-Sequence"
193
194 // ExpectedLastSubjSeqSubjHeader contains the subject for which the
195 // expected last sequence number is set. This is used together with
196 // [ExpectedLastSubjSeqHeader] to apply optimistic concurrency control at
197 // subject level. Server will reject the message if it is not the case.
198 ExpectedLastSubjSeqSubjHeader = "Nats-Expected-Last-Subject-Sequence-Subject"
199
200 // ExpectedLastMsgIDHeader contains the expected last message ID on the
201 // subject and can be used to apply optimistic concurrency control at
202 // stream level. Server will reject the message if it is not the case.
203 //
204 // This can be set when publishing messages using [WithExpectLastMsgID]
205 // option.
206 ExpectedLastMsgIDHeader = "Nats-Expected-Last-Msg-Id"
207
208 // MsgTTLHeader is used to specify the TTL for a specific message. This will
209 // override the default TTL for the stream.
210 MsgTTLHeader = "Nats-TTL"
211
212 // MsgRollup is used to apply a purge of all prior messages in the stream
213 // ("all") or at the subject ("sub") before this message.
214 MsgRollup = "Nats-Rollup"
215
216 // MarkerReasonHeader is used to specify a reason for message deletion.
217 MarkerReasonHeader = "Nats-Marker-Reason"
218
219 // ScheduleHeader is used to specify a schedule expression for a message.
220 // Valid values include "@at <RFC3339>", "@every <duration>", 6-field cron
221 // expressions, and predefined schedules (@yearly, @monthly, @weekly,
222 // @daily, @hourly).
223 //
224 // This can be set when publishing messages using [WithScheduleAt],
225 // [WithScheduleEvery], or [WithScheduleCron] options.
226 // Requires [StreamConfig.AllowMsgSchedules] to be enabled.
227 ScheduleHeader = "Nats-Schedule"
228
229 // ScheduleTargetHeader specifies the subject where scheduled messages
230 // will be delivered.
231 //
232 // This can be set when publishing messages using [WithScheduleTarget] option.
233 ScheduleTargetHeader = "Nats-Schedule-Target"
234
235 // ScheduleSourceHeader instructs the scheduler to read the latest message
236 // from the given subject and republish it on schedule. Used for data
237 // sampling use cases.
238 //
239 // This can be set when publishing messages using [WithScheduleSource] option.
240 ScheduleSourceHeader = "Nats-Schedule-Source"
241
242 // ScheduleTTLHeader sets a TTL on messages generated by the scheduler.
243 // The server default is "5m". Use "never" to disable TTL on generated
244 // messages.
245 //
246 // This can be set when publishing messages using [WithScheduleTTL] or
247 // [WithScheduleTTLNever] options.
248 // Requires [StreamConfig.AllowMsgTTL] to be enabled on the stream.
249 ScheduleTTLHeader = "Nats-Schedule-TTL"
250
251 // ScheduleTimeZoneHeader sets the time zone for cron schedule expressions.
252 // Must be a valid IANA time zone name (e.g., "America/New_York").
253 // Only valid with cron schedule expressions.
254 //
255 // This can be set when publishing messages using [WithScheduleTimeZone] option.
256 ScheduleTimeZoneHeader = "Nats-Schedule-Time-Zone"
257
258 // ScheduleRollupHeader sets a rollup on messages generated by the
259 // scheduler. Only [MsgRollupSubject] is a valid value.
260 //
261 // This can be set when publishing messages using [WithScheduleRollup] option.
262 ScheduleRollupHeader = "Nats-Schedule-Rollup"
263 )
264
265 // Headers for republished messages and direct gets. Those headers are set by
266 // the server and should not be set by the client.
267 const (
268 // StreamHeader contains the stream name the message was republished from or
269 // the stream name the message was retrieved from using direct get.
270 StreamHeader = "Nats-Stream"
271
272 // SequenceHeader contains the original sequence number of the message.
273 SequenceHeader = "Nats-Sequence"
274
275 // TimeStampHeaer contains the original timestamp of the message.
276 TimeStampHeaer = "Nats-Time-Stamp"
277
278 // SubjectHeader contains the original subject the message was published to.
279 SubjectHeader = "Nats-Subject"
280
281 // SchedulerHeader is set by the server on messages generated by a schedule.
282 // Contains the subject holding the schedule definition.
283 SchedulerHeader = "Nats-Scheduler"
284
285 // ScheduleNextHeader is set by the server on generated messages. Contains
286 // the timestamp of the next invocation, or "purge" for one-time schedules.
287 ScheduleNextHeader = "Nats-Schedule-Next"
288
289 // LastSequenceHeader contains the last sequence of the message having the
290 // same subject, otherwise zero if this is the first message for the
291 // subject.
292 LastSequenceHeader = "Nats-Last-Sequence"
293 )
294
295 // Rollups, can be subject only or all messages.
296 const (
297 // MsgRollupSubject is used to purge all messages before this message on the
298 // message subject.
299 MsgRollupSubject = "sub"
300
301 // MsgRollupAll is used to purge all messages before this message on the
302 // stream.
303 MsgRollupAll = "all"
304 )
305
306 var (
307 ackAck ackType = []byte("+ACK")
308 ackNak ackType = []byte("-NAK")
309 ackProgress ackType = []byte("+WPI")
310 ackTerm ackType = []byte("+TERM")
311 )
312
313 // Metadata returns [MsgMetadata] for a JetStream message.
314 func (m *jetStreamMsg) Metadata() (*MsgMetadata, error) {
315 if err := m.checkReply(); err != nil {
316 return nil, err
317 }
318
319 tokens, err := parser.GetMetadataFields(m.msg.Reply)
320 if err != nil {
321 return nil, fmt.Errorf("%w: %s", ErrNotJSMessage, err)
322 }
323
324 meta := &MsgMetadata{
325 Domain: tokens[parser.AckDomainTokenPos],
326 NumDelivered: parser.ParseNum(tokens[parser.AckNumDeliveredTokenPos]),
327 NumPending: parser.ParseNum(tokens[parser.AckNumPendingTokenPos]),
328 Timestamp: time.Unix(0, int64(parser.ParseNum(tokens[parser.AckTimestampSeqTokenPos]))),
329 Stream: tokens[parser.AckStreamTokenPos],
330 Consumer: tokens[parser.AckConsumerTokenPos],
331 }
332 meta.Sequence.Stream = parser.ParseNum(tokens[parser.AckStreamSeqTokenPos])
333 meta.Sequence.Consumer = parser.ParseNum(tokens[parser.AckConsumerSeqTokenPos])
334 return meta, nil
335 }
336
337 // Data returns the message body.
338 func (m *jetStreamMsg) Data() []byte {
339 return m.msg.Data
340 }
341
342 // Headers returns a map of headers for a message.
343 func (m *jetStreamMsg) Headers() nats.Header {
344 return m.msg.Header
345 }
346
347 // Subject returns a subject on which a message was published/received.
348 func (m *jetStreamMsg) Subject() string {
349 return m.msg.Subject
350 }
351
352 // Reply returns a reply subject for a JetStream message.
353 func (m *jetStreamMsg) Reply() string {
354 return m.msg.Reply
355 }
356
357 // Ack acknowledges a message. This tells the server that the message was
358 // successfully processed and it can move on to the next message.
359 func (m *jetStreamMsg) Ack() error {
360 return m.ackReply(context.Background(), ackAck, false, ackOpts{})
361 }
362
363 // DoubleAck acknowledges a message and waits for ack reply from the server.
364 // While it impacts performance, it is useful for scenarios where
365 // message loss is not acceptable.
366 func (m *jetStreamMsg) DoubleAck(ctx context.Context) error {
367 return m.ackReply(ctx, ackAck, true, ackOpts{})
368 }
369
370 // Nak negatively acknowledges a message. This tells the server to
371 // redeliver the message.
372 func (m *jetStreamMsg) Nak() error {
373 return m.ackReply(context.Background(), ackNak, false, ackOpts{})
374 }
375
376 // NakWithDelay negatively acknowledges a message. This tells the server
377 // to redeliver the message after the given delay.
378 func (m *jetStreamMsg) NakWithDelay(delay time.Duration) error {
379 return m.ackReply(context.Background(), ackNak, false, ackOpts{nakDelay: delay})
380 }
381
382 // InProgress tells the server that this message is being worked on. It
383 // resets the redelivery timer on the server.
384 func (m *jetStreamMsg) InProgress() error {
385 return m.ackReply(context.Background(), ackProgress, false, ackOpts{})
386 }
387
388 // Term tells the server to not redeliver this message, regardless of
389 // the value of MaxDeliver.
390 func (m *jetStreamMsg) Term() error {
391 return m.ackReply(context.Background(), ackTerm, false, ackOpts{})
392 }
393
394 // TermWithReason tells the server to not redeliver this message, regardless of
395 // the value of MaxDeliver. The provided reason will be included in JetStream
396 // advisory event sent by the server.
397 //
398 // Note: This will only work with JetStream servers >= 2.10.4.
399 // For older servers, TermWithReason will be ignored by the server and the message
400 // will not be terminated.
401 func (m *jetStreamMsg) TermWithReason(reason string) error {
402 return m.ackReply(context.Background(), ackTerm, false, ackOpts{termReason: reason})
403 }
404
405 func (m *jetStreamMsg) ackReply(ctx context.Context, ackType ackType, sync bool, opts ackOpts) error {
406 err := m.checkReply()
407 if err != nil {
408 return err
409 }
410
411 m.Lock()
412 if m.ackd {
413 m.Unlock()
414 return ErrMsgAlreadyAckd
415 }
416 m.Unlock()
417
418 if sync {
419 var cancel context.CancelFunc
420 ctx, cancel = m.js.wrapContextWithoutDeadline(ctx)
421 if cancel != nil {
422 defer cancel()
423 }
424 }
425
426 var body []byte
427 if opts.nakDelay > 0 {
428 body = []byte(fmt.Sprintf("%s {\"delay\": %d}", ackType, opts.nakDelay.Nanoseconds()))
429 } else if opts.termReason != "" {
430 body = []byte(fmt.Sprintf("%s %s", ackType, opts.termReason))
431 } else {
432 body = ackType
433 }
434
435 if sync {
436 _, err = m.js.conn.RequestWithContext(ctx, m.msg.Reply, body)
437 } else {
438 err = m.js.conn.Publish(m.msg.Reply, body)
439 }
440 if err != nil {
441 return err
442 }
443
444 // Mark that the message has been acked unless it is ackProgress
445 // which can be sent many times.
446 if !bytes.Equal(ackType, ackProgress) {
447 m.Lock()
448 m.ackd = true
449 m.Unlock()
450 }
451 return nil
452 }
453
454 func (m *jetStreamMsg) checkReply() error {
455 if m == nil || m.msg.Sub == nil {
456 return ErrMsgNotBound
457 }
458 if m.msg.Reply == "" {
459 return ErrMsgNoReply
460 }
461 return nil
462 }
463
464 // checkMsg returns whether the given message is a user message or a control message.
465 // If the status header is present, it returns an appropriate error based
466 // on the status code (404, etc.)
467 func checkMsg(msg *nats.Msg) (bool, error) {
468 // If payload or no header, consider this a user message
469 if len(msg.Data) > 0 || len(msg.Header) == 0 {
470 return true, nil
471 }
472 // Look for status header
473 val := msg.Header.Get("Status")
474 descr := msg.Header.Get("Description")
475 // If not present, then this is considered a user message
476 if val == "" {
477 return true, nil
478 }
479
480 switch val {
481 case statusBadRequest:
482 return false, ErrBadRequest
483 case statusNoResponders:
484 return false, nats.ErrNoResponders
485 case statusNoMsgs:
486 // 404 indicates that there are no messages.
487 return false, ErrNoMessages
488 case statusTimeout:
489 return false, nats.ErrTimeout
490 case statusControlMsg:
491 return false, nil
492 case statusPinIdMismatch:
493 return false, ErrPinIDMismatch
494 case statusConflict:
495 if strings.Contains(strings.ToLower(descr), maxBytesExceeded) {
496 return false, ErrMaxBytesExceeded
497 }
498 if strings.Contains(strings.ToLower(descr), batchCompleted) {
499 return false, ErrBatchCompleted
500 }
501 if strings.Contains(strings.ToLower(descr), consumerDeleted) {
502 return false, ErrConsumerDeleted
503 }
504 if strings.Contains(strings.ToLower(descr), leadershipChange) {
505 return false, ErrConsumerLeadershipChanged
506 }
507 if strings.Contains(strings.ToLower(descr), serverShutdown) {
508 return false, ErrServerShutdown
509 }
510 }
511 return false, fmt.Errorf("nats: %s", msg.Header.Get("Description"))
512 }
513
514 func parsePending(msg *nats.Msg) (int, int, error) {
515 msgsLeftStr := msg.Header.Get("Nats-Pending-Messages")
516 var msgsLeft int
517 var err error
518 if msgsLeftStr != "" {
519 msgsLeft, err = strconv.Atoi(msgsLeftStr)
520 if err != nil {
521 return 0, 0, errors.New("nats: invalid format of Nats-Pending-Messages")
522 }
523 }
524 bytesLeftStr := msg.Header.Get("Nats-Pending-Bytes")
525 var bytesLeft int
526 if bytesLeftStr != "" {
527 bytesLeft, err = strconv.Atoi(bytesLeftStr)
528 if err != nil {
529 return 0, 0, errors.New("nats: invalid format of Nats-Pending-Bytes")
530 }
531 }
532 return msgsLeft, bytesLeft, nil
533 }
534
535 // toJSMsg converts core [nats.Msg] to [jetStreamMsg], exposing JetStream-specific operations
536 func (js *jetStream) toJSMsg(msg *nats.Msg) *jetStreamMsg {
537 return &jetStreamMsg{
538 msg: msg,
539 js: js,
540 }
541 }