Debian Codegraph @

server/jetstream_batching.go

raw
1 // Copyright 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 server
15
16 import (
17 "encoding/json"
18 "errors"
19 "fmt"
20 "maps"
21 "math"
22 "math/big"
23 "path/filepath"
24 "slices"
25 "strconv"
26 "strings"
27 "sync"
28 "sync/atomic"
29 "time"
30 )
31
32 var (
33 // Tracks the total inflight batches, across all streams and accounts that enable batching.
34 globalInflightAtomicBatches atomic.Int64
35 globalInflightFastBatches atomic.Int64
36 )
37
38 type batching struct {
39 mu sync.Mutex
40 atomic map[string]*atomicBatch
41 fast map[string]*fastBatch
42 }
43
44 type atomicBatch struct {
45 timer *time.Timer // Inactivity timer for the batch.
46 lseq uint64 // The highest sequence for this batch.
47 store StreamStore // Where the batch is staged before committing.
48 }
49
50 type fastBatch struct {
51 timer *time.Timer // Inactivity timer for the batch.
52 lseq uint64 // The highest sequence for this batch.
53 sseq uint64 // Last persisted stream sequence.
54 pseq uint64 // Last persisted batch sequence (is always lower or equal to lseq).
55 fseq uint64 // Sequence of when we last sent a flow message (is always lower or equal to pseq).
56 pending uint32 // Number of pending messages in the batch waiting to be persisted.
57 ackMessages uint16 // Ack will be sent every N messages.
58 maxAckMessages uint16 // Maximum ackMessages value the client allows.
59 reply string // The last reply subject seen when persisting a message.
60 gapOk bool // Whether a gap is okay, if not, the batch would be rejected.
61 commit bool // If the batch is committed.
62 }
63
64 // newAtomicBatch creates an atomic batch publish object.
65 // Lock should be held.
66 func (batches *batching) newAtomicBatch(mset *stream, batchId string, replicas int, storage StorageType, storeDir, streamName string) (*atomicBatch, error) {
67 store, err := newBatchStore(mset, batchId, replicas, storage, storeDir, streamName)
68 if err != nil {
69 return nil, err
70 }
71 b := &atomicBatch{store: store}
72 b.setupCleanupTimer(mset, batchId, batches)
73 return b, nil
74 }
75
76 // setupCleanupTimer sets up a timer to clean up the batch after a timeout.
77 func (b *atomicBatch) setupCleanupTimer(mset *stream, batchId string, batches *batching) {
78 // Create a timer to clean up after timeout.
79 timeout := getCleanupTimeout(mset)
80 b.timer = time.AfterFunc(timeout, func() {
81 b.cleanup(batchId, batches)
82 mset.sendStreamBatchAbandonedAdvisory(batchId, BatchTimeout)
83 })
84 }
85
86 // resetCleanupTimer resets the cleanup timer, allowing to extend the lifetime of the batch.
87 // Returns whether the timer was reset without it having expired before.
88 func (b *atomicBatch) resetCleanupTimer(mset *stream) bool {
89 timeout := getCleanupTimeout(mset)
90 return b.timer.Reset(timeout)
91 }
92
93 // cleanup deletes underlying resources associated with the batch and unregisters it from the stream's batches.
94 func (b *atomicBatch) cleanup(batchId string, batches *batching) {
95 batches.mu.Lock()
96 defer batches.mu.Unlock()
97 b.cleanupLocked(batchId, batches)
98 }
99
100 // Lock should be held.
101 func (b *atomicBatch) cleanupLocked(batchId string, batches *batching) {
102 if b.timer == nil {
103 return
104 }
105 globalInflightAtomicBatches.Add(-1)
106 b.timer.Stop()
107 b.store.Delete(true)
108 delete(batches.atomic, batchId)
109 // Reset so that another invocation doesn't double-account.
110 b.timer = nil
111 }
112
113 // Lock should be held.
114 func (b *atomicBatch) stopLocked() {
115 if b.timer == nil {
116 return
117 }
118 globalInflightAtomicBatches.Add(-1)
119 b.timer.Stop()
120 b.store.Stop()
121 // Reset so that another invocation doesn't double-account.
122 b.timer = nil
123 }
124
125 func getBatchStoreDir(storeDir, streamName, batchId string) (string, string) {
126 bname := getHash(batchId)
127 return bname, filepath.Join(storeDir, streamsDir, streamName, batchesDir, bname)
128 }
129
130 func newBatchStore(mset *stream, batchId string, replicas int, storage StorageType, storeDir, streamName string) (StreamStore, error) {
131 if replicas == 1 && storage == FileStorage {
132 bname, storeDir := getBatchStoreDir(storeDir, streamName, batchId)
133 s := mset.srv
134 fcfg := FileStoreConfig{AsyncFlush: true, BlockSize: defaultLargeBlockSize, StoreDir: storeDir, srv: s}
135 prf := s.jsKeyGen(s.getOpts().JetStreamKey, mset.acc.Name)
136 if prf != nil {
137 // We are encrypted here, fill in correct cipher selection.
138 fcfg.Cipher = s.getOpts().JetStreamCipher
139 }
140 oldprf := s.jsKeyGen(s.getOpts().JetStreamOldKey, mset.acc.Name)
141 cfg := StreamConfig{Name: bname, Storage: FileStorage}
142 return newFileStoreWithCreated(fcfg, cfg, time.Time{}, prf, oldprf)
143 }
144 return newMemStore(&StreamConfig{Name: _EMPTY_, Storage: MemoryStorage})
145 }
146
147 // readyForCommit indicates the batch is ready to be committed.
148 // If the timer has already cleaned up the batch, we can't commit.
149 // Otherwise, we ensure the timer does not clean up the batch in the meantime.
150 // Lock should be held.
151 func (b *atomicBatch) readyForCommit() *BatchAbandonReason {
152 if !b.timer.Stop() {
153 return &BatchTimeout
154 }
155 if b.store.FlushAllPending() != nil {
156 return &BatchIncomplete
157 }
158 return nil
159 }
160
161 // newFastBatch creates a fast batch publish object and registers it in batches.fast.
162 // Lock should be held.
163 func (batches *batching) newFastBatch(mset *stream, batchId string, gapOk bool, maxAckMessages uint16) *fastBatch {
164 b := &fastBatch{gapOk: gapOk, maxAckMessages: maxAckMessages}
165 if batches.fast == nil {
166 batches.fast = make(map[string]*fastBatch, 1)
167 }
168 batches.fast[batchId] = b
169 batches.fastBatchInit(b)
170 b.setupCleanupTimer(mset, batchId, batches)
171 return b
172 }
173
174 // fastBatchInit (re)initializes the ackMessages field for a fast batch.
175 // The batch must already be registered in batches.fast.
176 // Lock should be held.
177 func (batches *batching) fastBatchInit(b *fastBatch) {
178 // If it's the only batch, just allow what the client wants, otherwise we'll
179 // need to coordinate and slowly ramp up this publisher.
180 // TODO(mvv): fast ingest's initial flow value improvements?
181 ackMessages := min(500, b.maxAckMessages)
182 if len(batches.fast) > 1 {
183 ackMessages = 1
184 }
185 b.ackMessages = ackMessages
186 }
187
188 // fastBatchReset resets the fast batch to an empty state and sends a flow control message.
189 // Lock should be held.
190 func (batches *batching) fastBatchReset(mset *stream, batchId string, b *fastBatch) {
191 // If the timer already stopped before we could commit, we clean it up.
192 if b.timer == nil || (!b.commit && !b.timer.Stop()) {
193 b.cleanupLocked(batchId, batches)
194 return
195 }
196 // Otherwise, reset the state.
197 batches.fastBatchInit(b)
198 b.timer.Reset(getCleanupTimeout(mset))
199 b.commit = false
200 b.pending = 0
201 b.fseq, b.lseq = b.pseq, b.pseq
202 b.sendFlowControl(b.fseq, mset, b.reply)
203 }
204
205 // fastBatchRegisterSequences registers the highest stored batch and stream sequence and returns
206 // whether a PubAck should be sent if the batch has been committed.
207 // If this is called on a follower, it only registers the highest stream and persisted batch sequences.
208 // Lock should be held.
209 func (batches *batching) fastBatchRegisterSequences(mset *stream, reply string, streamSeq uint64, isLeader bool, batch *FastBatch) bool {
210 b, ok := batches.fast[batch.id]
211 if !ok || !isLeader {
212 // If this batch has committed, we can clean it up.
213 if batch.commit {
214 if b != nil {
215 b.cleanupLocked(batch.id, batches)
216 }
217 return false
218 }
219 // Otherwise, even as a follower, we record the latest state of this batch.
220 if b == nil || !b.resetCleanupTimer(mset) {
221 if b != nil {
222 // The timer couldn't be reset, this means the timer already runs and is likely
223 // waiting to acquire the lock. We reset the timer here so it doesn't clean up
224 // this batch that we're about to overwrite.
225 b.timer = nil
226 } else {
227 // If this is a new batch for us, even though we're a follower, we still need
228 // to account toward the global inflight limit.
229 globalInflightFastBatches.Add(1)
230 }
231 // We'll need a copy as we'll use it as a key and later for cleanup.
232 batchId := copyString(batch.id)
233 b = batches.newFastBatch(mset, batchId, batch.gapOk, batch.flow)
234 }
235 b.sseq = streamSeq
236 b.pseq, b.lseq = batch.seq, batch.seq
237 b.reply = reply
238 return false
239 }
240 b.reply = reply
241 if b.pending > 0 {
242 b.pending--
243 }
244 b.sseq = streamSeq
245 // Store last persisted batch sequence.
246 // If we have no remaining pending writes, we might have had duplicate messages
247 // and need to send additional flow control messages.
248 var skipped bool
249 if b.pending == 0 {
250 skipped = true
251 b.pseq = b.lseq
252 } else {
253 b.pseq = batch.seq
254 }
255 // If the PubAck needs to be sent now as a result of a commit.
256 if b.lseq == b.pseq && b.commit {
257 b.cleanupLocked(batch.id, batches)
258 // If we skipped ahead due to duplicate messages, send the PubAck with the highest sequence.
259 if skipped {
260 var buf [256]byte
261 pubAck := append(buf[:0], mset.pubAck...)
262 response := append(pubAck, strconv.FormatUint(b.sseq, 10)...)
263 response = append(response, fmt.Sprintf(",\"batch\":%q,\"count\":%d}", batch.id, b.lseq)...)
264 if len(reply) > 0 {
265 mset.outq.sendMsg(reply, response)
266 }
267 return false
268 }
269 return true
270 }
271 b.checkFlowControl(mset, reply, batches)
272 return false
273 }
274
275 // checkFlowControl checks whether a flow control message should be sent.
276 // If so, it updates the flow values to speed up or slow down the publisher if needed.
277 // Returns whether a flow control message was sent.
278 // Lock should be held.
279 func (b *fastBatch) checkFlowControl(mset *stream, reply string, batches *batching) bool {
280 am := uint64(b.ackMessages)
281 if b.pseq < b.fseq+am {
282 return false
283 }
284 // Instead of sending multiple flow control messages, skip ahead to only send the last.
285 steps := (b.pseq - b.fseq) / am
286 b.fseq += steps * am
287
288 // TODO(mvv): fast ingest's dynamic flow value improvements?
289 // This is currently just a simple value to have a working version. Should take average
290 // message sizes into account and compare how much this client is contributing to the
291 // ingest IPQ total size and messages and have publishers share based on that.
292 maxAckMessages := uint16(500 / len(batches.fast))
293 if maxAckMessages < 1 {
294 maxAckMessages = 1
295 }
296 // Limit to the client's allowed maximum.
297 if maxAckMessages > b.maxAckMessages {
298 maxAckMessages = b.maxAckMessages
299 }
300
301 if b.ackMessages < maxAckMessages {
302 // Ramp up.
303 b.ackMessages *= 2
304 if b.ackMessages > maxAckMessages {
305 b.ackMessages = maxAckMessages
306 }
307 } else if b.ackMessages > maxAckMessages {
308 // Slow down.
309 b.ackMessages /= 2
310 if b.ackMessages <= maxAckMessages {
311 b.ackMessages = maxAckMessages
312 }
313 }
314
315 // Finally, send the flow control message.
316 b.sendFlowControl(b.fseq, mset, reply)
317 return true
318 }
319
320 // sendFlowControl sends a fast batch flow control message for the current highest sequence.
321 // Lock should be held.
322 func (b *fastBatch) sendFlowControl(batchSeq uint64, mset *stream, reply string) {
323 if len(reply) == 0 {
324 return
325 }
326 response, _ := BatchFlowAck{Sequence: batchSeq, Messages: b.ackMessages}.MarshalJSON()
327 mset.outq.sendMsg(reply, response)
328 }
329
330 // fastBatchCommit ends the batch and commits the data up to that point. If all messages
331 // have already been persisted, a PubAck is sent immediately. Otherwise, it will be sent
332 // after the last message has been persisted.
333 // Lock should be held.
334 func (batches *batching) fastBatchCommit(b *fastBatch, batchId string, mset *stream, reply string) bool {
335 // Either we commit now, or we clean up later, so stop the timer.
336 if b.timer == nil || (!b.commit && !b.timer.Stop()) {
337 // Shouldn't be possible for the timer to already be stopped if we haven't committed yet,
338 // since we pre-check being able to reset the timer. But guard against it anyhow.
339 return true
340 }
341 // Mark that this batch commits.
342 b.commit = true
343 // If the whole batch has been persisted, we can respond with the PubAck now.
344 if b.lseq == b.pseq {
345 b.cleanupLocked(batchId, batches)
346 var buf [256]byte
347 pubAck := append(buf[:0], mset.pubAck...)
348 response := append(pubAck, strconv.FormatUint(b.sseq, 10)...)
349 response = append(response, fmt.Sprintf(",\"batch\":%q,\"count\":%d}", batchId, b.lseq)...)
350 if len(reply) > 0 {
351 mset.outq.sendMsg(reply, response)
352 }
353 return true
354 }
355 // Otherwise, we need to wait and the PubAck will be sent when the last message is persisted.
356 return false
357 }
358
359 // setupCleanupTimer sets up a timer to clean up the batch after a timeout.
360 func (b *fastBatch) setupCleanupTimer(mset *stream, batchId string, batches *batching) {
361 // Create a timer to clean up after timeout.
362 timeout := getCleanupTimeout(mset)
363 b.timer = time.AfterFunc(timeout, func() {
364 b.cleanup(batchId, batches)
365 })
366 }
367
368 // resetCleanupTimer resets the cleanup timer, allowing to extend the lifetime of the batch.
369 // Returns whether the timer was reset without it having expired before.
370 func (b *fastBatch) resetCleanupTimer(mset *stream) bool {
371 if b.commit {
372 return true
373 }
374 if b.timer == nil {
375 return false
376 }
377 timeout := getCleanupTimeout(mset)
378 return b.timer.Reset(timeout)
379 }
380
381 // cleanup deletes underlying resources associated with the batch and unregisters it from the stream's batches.
382 func (b *fastBatch) cleanup(batchId string, batches *batching) {
383 batches.mu.Lock()
384 defer batches.mu.Unlock()
385 b.cleanupLocked(batchId, batches)
386 }
387
388 // Lock should be held.
389 func (b *fastBatch) cleanupLocked(batchId string, batches *batching) {
390 // If the timer is nil, it means this batch has been replaced with a new one.
391 // This can happen on a follower depending on timing.
392 if b.timer == nil {
393 return
394 }
395 globalInflightFastBatches.Add(-1)
396 b.timer.Stop()
397 delete(batches.fast, batchId)
398 // Reset so that another invocation doesn't double-account.
399 b.timer = nil
400 }
401
402 // getCleanupTimeout returns the timeout for the batch, taking into account the server's limits.
403 func getCleanupTimeout(mset *stream) time.Duration {
404 timeout := streamMaxBatchTimeout
405 if maxBatchTimeout := mset.srv.getOpts().JetStreamLimits.MaxBatchTimeout; maxBatchTimeout > 0 {
406 timeout = maxBatchTimeout
407 }
408 return timeout
409 }
410
411 // batchStagedDiff stages all changes for consistency checks until commit.
412 type batchStagedDiff struct {
413 msgIds map[string]struct{}
414 counter map[string]*msgCounterRunningTotal
415 inflight map[string]*inflightSubjectRunningTotal
416 inflightTransform map[uint64]string
417 expectedPerSubject map[string]*batchExpectedPerSubject
418 }
419
420 type batchExpectedPerSubject struct {
421 sseq uint64 // Stream sequence.
422 clseq uint64 // Clustered proposal sequence.
423 }
424
425 // copyCounterSources returns a deep copy of the given counter sources.
426 func copyCounterSources(src CounterSources) CounterSources {
427 if src == nil {
428 return nil
429 }
430 dst := make(CounterSources, len(src))
431 for stream, subjects := range src {
432 dst[stream] = maps.Clone(subjects)
433 }
434 return dst
435 }
436
437 func (diff *batchStagedDiff) commit(mset *stream) {
438 if len(diff.msgIds) > 0 {
439 ts := time.Now().UnixNano()
440 mset.ddMu.Lock()
441 for msgId := range diff.msgIds {
442 // We stage with zero, and will update in processJetStreamMsg once we know the sequence.
443 mset.storeMsgIdLocked(&ddentry{msgId, 0, ts})
444 }
445 mset.ddMu.Unlock()
446 }
447
448 // Store running totals for counters, we could have multiple counter increments proposed, but not applied yet.
449 if len(diff.counter) > 0 {
450 if mset.clusteredCounterTotal == nil {
451 mset.clusteredCounterTotal = make(map[string]*msgCounterRunningTotal, len(diff.counter))
452 }
453 for k, c := range diff.counter {
454 mset.clusteredCounterTotal[k] = c
455 }
456 }
457
458 // Track inflight.
459 if len(diff.inflight) > 0 {
460 if mset.inflight == nil {
461 mset.inflight = make(map[string]*inflightSubjectRunningTotal, len(diff.inflight))
462 }
463 for subj, i := range diff.inflight {
464 if c, ok := mset.inflight[subj]; ok {
465 c.bytes += i.bytes
466 c.ops += i.ops
467 c.schedule = i.schedule
468 } else {
469 mset.inflight[subj] = i
470 }
471 }
472 }
473
474 // Track inflight subject transforms.
475 if len(diff.inflightTransform) > 0 {
476 if mset.inflightTransform == nil {
477 mset.inflightTransform = make(map[uint64]string, len(diff.inflightTransform))
478 }
479 for clseq, subj := range diff.inflightTransform {
480 mset.inflightTransform[clseq] = subj
481 }
482 }
483
484 // Track sequence and subject.
485 if len(diff.expectedPerSubject) > 0 {
486 if mset.expectedPerSubjectSequence == nil {
487 mset.expectedPerSubjectSequence = make(map[uint64]string, len(diff.expectedPerSubject))
488 }
489 if mset.expectedPerSubjectInProcess == nil {
490 mset.expectedPerSubjectInProcess = make(map[string]struct{}, len(diff.expectedPerSubject))
491 }
492 for subj, e := range diff.expectedPerSubject {
493 mset.expectedPerSubjectSequence[e.clseq] = subj
494 mset.expectedPerSubjectInProcess[subj] = struct{}{}
495 }
496 }
497 }
498
499 type batchApply struct {
500 id string // ID of the current batch.
501 count uint64 // Number of entries in the batch, for consistency checks.
502 entries []*CommittedEntry // Previous entries that are part of this batch.
503 entryStart int // The index into an entry indicating the first message of the batch.
504 maxApplied uint64 // Applied value before the entry containing the first message of the batch.
505 }
506
507 // clearBatchState clears in-memory apply-batch-related state.
508 func (batch *batchApply) clearBatchState() {
509 batch.id = _EMPTY_
510 batch.count = 0
511 batch.entries = nil
512 batch.entryStart = 0
513 batch.maxApplied = 0
514 }
515
516 // rejectBatchStateLocked rejects the batch and clears in-memory apply-batch-related state.
517 // Corrects mset.clfs to take the failed batch into account.
518 func (batch *batchApply) rejectBatchState(mset *stream) {
519 mset.clMu.Lock()
520 mset.clfs += batch.count
521 mset.clMu.Unlock()
522 // We're rejecting the batch, so all entries need to be returned to the pool.
523 for _, bce := range batch.entries {
524 bce.ReturnToPool()
525 }
526 batch.clearBatchState()
527 }
528
529 // checkMsgHeadersPreClusteredProposal checks the message for expected/consistency headers.
530 // mset.mu lock must NOT be held or used.
531 // mset.clMu lock must be held.
532 func checkMsgHeadersPreClusteredProposal(
533 diff *batchStagedDiff, mset *stream, subject, rsubject string, hdr []byte, msg []byte, sourced bool, name string,
534 jsa *jsAccount, allowRollup, denyPurge, allowTTL, allowMsgCounter, allowMsgSchedules bool,
535 discard DiscardPolicy, discardNewPer bool, maxMsgSize int, maxMsgs int64, maxMsgsPer int64, maxBytes int64,
536 ) ([]byte, []byte, uint64, *ApiError, error) {
537 var incr *big.Int
538 var hasSchedule bool
539
540 // Do this before staging any proposal state. All clustered publish paths,
541 // including atomic and fast batches, use this helper.
542 if mset.store.Type() == FileStorage && isFileStoreMsgTooLarge(fileStoreMsgSize(subject, hdr, msg)) {
543 return hdr, msg, 0, NewJSStreamStoreFailedError(ErrMsgTooLarge), ErrMsgTooLarge
544 }
545
546 // Some header checks must be checked pre proposal.
547 if len(hdr) > 0 {
548 // Since we encode header len as u16 make sure we do not exceed.
549 // Again this works if it goes through but better to be pre-emptive.
550 if len(hdr) > math.MaxUint16 {
551 err := fmt.Errorf("JetStream header size exceeds limits for '%s > %s'", jsa.acc().Name, name)
552 return hdr, msg, 0, NewJSStreamHeaderExceedsMaximumError(), err
553 }
554 // Counter increments.
555 // Only supported on counter streams, and payload must be empty (if not coming from a source).
556 var ok bool
557 if incr, ok = getMessageIncr(hdr); !ok {
558 apiErr := NewJSMessageIncrInvalidError()
559 return hdr, msg, 0, apiErr, apiErr
560 } else if incr != nil && !sourced {
561 // Only do checks if the message isn't sourced. Otherwise, we need to store verbatim.
562 if !allowMsgCounter {
563 apiErr := NewJSMessageIncrDisabledError()
564 return hdr, msg, 0, apiErr, apiErr
565 } else if len(msg) > 0 {
566 apiErr := NewJSMessageIncrPayloadError()
567 return hdr, msg, 0, apiErr, apiErr
568 } else {
569 // Check for incompatible headers.
570 var doErr bool
571 if getRollup(hdr) != _EMPTY_ ||
572 getExpectedStream(hdr) != _EMPTY_ ||
573 getExpectedLastMsgId(hdr) != _EMPTY_ ||
574 getExpectedLastSeqPerSubjectForSubject(hdr) != _EMPTY_ {
575 doErr = true
576 } else if _, ok = getExpectedLastSeq(hdr); ok {
577 doErr = true
578 } else if _, ok = getExpectedLastSeqPerSubject(hdr); ok {
579 doErr = true
580 }
581
582 if doErr {
583 apiErr := NewJSMessageIncrInvalidError()
584 return hdr, msg, 0, apiErr, apiErr
585 }
586 }
587 }
588 // Expected stream name can also be pre-checked.
589 if sname := getExpectedStream(hdr); sname != _EMPTY_ && sname != name {
590 return hdr, msg, 0, NewJSStreamNotMatchError(), errStreamMismatch
591 }
592 // TTL'd messages are rejected entirely if TTLs are not enabled on the stream, or if the TTL is invalid.
593 if ttl, err := getMessageTTL(hdr); !sourced && (ttl != 0 || err != nil) {
594 if !allowTTL {
595 return hdr, msg, 0, NewJSMessageTTLDisabledError(), errMsgTTLDisabled
596 } else if err != nil {
597 return hdr, msg, 0, NewJSMessageTTLInvalidError(), err
598 }
599 }
600 // Check for MsgIds here at the cluster level to avoid excessive CLFS accounting.
601 // Will help during restarts.
602 if msgId := getMsgId(hdr); msgId != _EMPTY_ {
603 // Dedupe if staged.
604 if _, ok = diff.msgIds[msgId]; ok {
605 return hdr, msg, 0, NewJSAtomicPublishContainsDuplicateMessageError(), errMsgIdDuplicate
606 }
607 mset.ddMu.Lock()
608 if dde := mset.checkMsgId(msgId); dde != nil {
609 seq := dde.seq
610 mset.ddMu.Unlock()
611 // Should not return an invalid sequence, in that case error.
612 if seq > 0 {
613 return hdr, msg, seq, NewJSAtomicPublishContainsDuplicateMessageError(), errMsgIdDuplicate
614 } else {
615 return hdr, msg, 0, NewJSStreamDuplicateMessageConflictError(), errMsgIdDuplicate
616 }
617 }
618 if diff.msgIds == nil {
619 diff.msgIds = map[string]struct{}{msgId: {}}
620 } else {
621 diff.msgIds[msgId] = struct{}{}
622 }
623 mset.ddMu.Unlock()
624 }
625 }
626
627 // Apply increment for counter.
628 // But only if it's allowed for this stream. This can happen when we store verbatim for a sourced stream.
629 if incr == nil && allowMsgCounter {
630 apiErr := NewJSMessageIncrMissingError()
631 return hdr, msg, 0, apiErr, apiErr
632 }
633 if incr != nil && allowMsgCounter {
634 var initial big.Int
635 var sources CounterSources
636
637 // If we've got a running total, update that, since we have inflight proposals updating the same counter.
638 var ok bool
639 var counter *msgCounterRunningTotal
640 if counter, ok = diff.counter[subject]; ok {
641 initial = *counter.total
642 sources = counter.sources
643 } else if counter, ok = mset.clusteredCounterTotal[subject]; ok {
644 // Make an explicit copy to separate the staged data from what's committed.
645 initial.Set(counter.total)
646 sources = copyCounterSources(counter.sources)
647 // Don't need to initialize all values, they'll be overwritten later.
648 counter = &msgCounterRunningTotal{ops: counter.ops}
649 } else {
650 // Load last message, and store as inflight running total.
651 var smv StoreMsg
652 sm, err := mset.store.LoadLastMsg(subject, &smv)
653 if err == nil && sm != nil {
654 var val CounterValue
655 // Return an error if the counter is broken somehow.
656 if json.Unmarshal(sm.msg, &val) != nil {
657 apiErr := NewJSMessageCounterBrokenError()
658 return hdr, msg, 0, apiErr, apiErr
659 }
660 if ncs := sliceHeader(JSMessageCounterSources, sm.hdr); len(ncs) > 0 {
661 if err := json.Unmarshal(ncs, &sources); err != nil {
662 apiErr := NewJSMessageCounterBrokenError()
663 return hdr, msg, 0, apiErr, apiErr
664 }
665 }
666 initial.SetString(val.Value, 10)
667 }
668 }
669 srchdr := sliceHeader(JSStreamSource, hdr)
670 if len(srchdr) > 0 {
671 // This is a sourced message, so we can't apply Nats-Incr but
672 // instead should just update the source count header.
673 fields := strings.Split(string(srchdr), " ")
674 origStream := fields[0]
675 origSubj := subject
676 if len(fields) >= 5 {
677 origSubj = fields[4]
678 }
679 var val CounterValue
680 if json.Unmarshal(msg, &val) != nil {
681 apiErr := NewJSMessageCounterBrokenError()
682 return hdr, msg, 0, apiErr, apiErr
683 }
684 var sourced big.Int
685 sourced.SetString(val.Value, 10)
686 if sources == nil {
687 sources = map[string]map[string]string{}
688 }
689 if sources[origStream] == nil {
690 sources[origStream] = map[string]string{}
691 }
692 prevVal := sources[origStream][origSubj]
693 sources[origStream][origSubj] = sourced.String()
694 // We will also replace the Nats-Incr header with the diff
695 // between our last value from this source and this one, so
696 // that the arithmetic is always correct.
697 var previous big.Int
698 previous.SetString(prevVal, 10)
699 incr.Sub(&sourced, &previous)
700 hdr = setHeader(JSMessageIncr, incr.String(), hdr)
701 }
702 // Now make the change.
703 initial.Add(&initial, incr)
704 // Generate the new payload.
705 var _msg [128]byte
706 msg = fmt.Appendf(_msg[:0], "{%q:%q}", "val", initial.String())
707 // Write the updated source count headers.
708 if len(sources) > 0 {
709 nhdr, err := json.Marshal(sources)
710 if err != nil {
711 return hdr, msg, 0, NewJSMessageCounterBrokenError(), err
712 }
713 hdr = setHeader(JSMessageCounterSources, string(nhdr), hdr)
714 }
715
716 // Check to see if we are over the max msg size.
717 maxSize := int64(mset.srv.getOpts().MaxPayload)
718 if maxMsgSize >= 0 && int64(maxMsgSize) < maxSize {
719 maxSize = int64(maxMsgSize)
720 }
721 hdrLen, msgLen := int64(len(hdr)), int64(len(msg))
722 // Subtract to prevent against overflows.
723 if hdrLen > maxSize || msgLen > maxSize-hdrLen {
724 return hdr, msg, 0, NewJSStreamMessageExceedsMaximumError(), ErrMaxPayload
725 }
726
727 // Keep the in-memory counters up-to-date.
728 if counter == nil {
729 counter = &msgCounterRunningTotal{}
730 }
731 counter.total = &initial
732 counter.sources = sources
733 counter.ops++
734 if diff.counter == nil {
735 diff.counter = map[string]*msgCounterRunningTotal{subject: counter}
736 } else {
737 diff.counter[subject] = counter
738 }
739 }
740
741 if len(hdr) > 0 {
742 // Expected last sequence.
743 if seq, exists := getExpectedLastSeq(hdr); exists && seq != mset.clseq-mset.clfs {
744 mlseq := mset.clseq - mset.clfs
745 err := fmt.Errorf("last sequence mismatch: %d vs %d", seq, mlseq)
746 return hdr, msg, 0, NewJSStreamWrongLastSequenceError(mlseq), err
747 } else if exists && len(diff.inflight) > 0 {
748 // Only the first message in a batch can contain an expected last sequence.
749 err := fmt.Errorf("last sequence mismatch")
750 return hdr, msg, 0, NewJSStreamWrongLastSequenceConstantError(), err
751 }
752
753 // Expected last sequence per subject.
754 if seq, exists := getExpectedLastSeqPerSubject(hdr); exists {
755 // Allow override of the subject used for the check.
756 seqSubj := subject
757 if optSubj := getExpectedLastSeqPerSubjectForSubject(hdr); optSubj != _EMPTY_ {
758 seqSubj = copyString(optSubj)
759 }
760
761 // The subject is already written to in this batch, we can't allow
762 // expected checks since they would be incorrect.
763 if _, ok := diff.inflight[seqSubj]; ok {
764 err := errors.New("last sequence by subject mismatch")
765 return hdr, msg, 0, NewJSStreamWrongLastSequenceConstantError(), err
766 }
767
768 // If the subject is already in process, block as otherwise we could have
769 // multiple messages inflight with the same subject.
770 if _, found := mset.expectedPerSubjectInProcess[seqSubj]; found {
771 err := errors.New("last sequence by subject mismatch")
772 return hdr, msg, 0, NewJSStreamWrongLastSequenceConstantError(), err
773 }
774
775 // If the subject is already in process but without expected headers, block as we would have
776 // multiple messages inflight with the same subject.
777 if _, ok := mset.inflight[seqSubj]; ok {
778 err := errors.New("last sequence by subject mismatch")
779 return hdr, msg, 0, NewJSStreamWrongLastSequenceConstantError(), err
780 }
781
782 // If we've already done an expected-check on this subject, use the cached result.
783 if e, ok := diff.expectedPerSubject[seqSubj]; ok {
784 if e.sseq != seq {
785 err := fmt.Errorf("last sequence by subject mismatch: %d vs %d", seq, e.sseq)
786 return hdr, msg, 0, NewJSStreamWrongLastSequenceError(e.sseq), err
787 }
788 e.clseq = mset.clseq
789 } else {
790 var smv StoreMsg
791 var fseq uint64
792 sm, err := mset.store.LoadLastMsg(seqSubj, &smv)
793 if sm != nil {
794 fseq = sm.seq
795 }
796 if err == ErrStoreMsgNotFound && seq == 0 {
797 fseq, err = 0, nil
798 }
799 if err != nil || fseq != seq {
800 err = fmt.Errorf("last sequence by subject mismatch: %d vs %d", seq, fseq)
801 return hdr, msg, 0, NewJSStreamWrongLastSequenceError(fseq), err
802 }
803
804 e = &batchExpectedPerSubject{sseq: fseq, clseq: mset.clseq}
805 if diff.expectedPerSubject == nil {
806 diff.expectedPerSubject = map[string]*batchExpectedPerSubject{seqSubj: e}
807 } else {
808 diff.expectedPerSubject[seqSubj] = e
809 }
810 }
811 } else if getExpectedLastSeqPerSubjectForSubject(hdr) != _EMPTY_ {
812 apiErr := NewJSStreamExpectedLastSeqPerSubjectInvalidError()
813 return hdr, msg, 0, apiErr, apiErr
814 }
815
816 // Message scheduling.
817 if sourced {
818 // noop, sourced messages were already validated by the origin stream.
819 } else if schedule, apiErr := getMessageSchedule(hdr); apiErr != nil {
820 if !allowMsgSchedules {
821 apiErr = NewJSMessageSchedulesDisabledError()
822 }
823 return hdr, msg, 0, apiErr, apiErr
824 } else if !schedule.IsZero() {
825 hasSchedule = true
826 if !allowMsgSchedules {
827 apiErr := NewJSMessageSchedulesDisabledError()
828 return hdr, msg, 0, apiErr, apiErr
829 } else if scheduleTtl, ok := getMessageScheduleTTL(hdr); !ok {
830 apiErr := NewJSMessageSchedulesTTLInvalidError()
831 return hdr, msg, 0, apiErr, apiErr
832 } else if scheduleRollup := getMessageScheduleRollup(hdr); scheduleRollup != _EMPTY_ && scheduleRollup != JSMsgRollupSubject {
833 apiErr := NewJSMessageSchedulesRollupInvalidError()
834 return hdr, msg, 0, apiErr, apiErr
835 } else if scheduleTtl != _EMPTY_ && !allowTTL {
836 return hdr, msg, 0, NewJSMessageTTLDisabledError(), errMsgTTLDisabled
837 } else if scheduleTarget := getMessageScheduleTarget(hdr); scheduleTarget == _EMPTY_ ||
838 !IsValidPublishSubject(scheduleTarget) || scheduleTarget == subject {
839 apiErr := NewJSMessageSchedulesTargetInvalidError()
840 return hdr, msg, 0, apiErr, apiErr
841 } else if scheduleSource := getMessageScheduleSource(hdr); scheduleSource != _EMPTY_ &&
842 (scheduleSource == scheduleTarget || scheduleSource == subject || !IsValidPublishSubject(scheduleSource)) {
843 apiErr := NewJSMessageSchedulesSourceInvalidError()
844 return hdr, msg, 0, apiErr, apiErr
845 } else {
846 mset.cfgMu.RLock()
847 match := slices.ContainsFunc(mset.cfg.Subjects, func(subj string) bool {
848 return SubjectsCollide(subj, scheduleTarget)
849 })
850 if !match {
851 mset.cfgMu.RUnlock()
852 apiErr := NewJSMessageSchedulesTargetInvalidError()
853 return hdr, msg, 0, apiErr, apiErr
854 }
855 if scheduleSource != _EMPTY_ {
856 match = slices.ContainsFunc(mset.cfg.Subjects, func(subj string) bool {
857 return SubjectsCollide(subj, scheduleSource)
858 })
859 if !match {
860 mset.cfgMu.RUnlock()
861 apiErr := NewJSMessageSchedulesSourceInvalidError()
862 return hdr, msg, 0, apiErr, apiErr
863 }
864 }
865 mset.cfgMu.RUnlock()
866
867 // Add a rollup sub header if it doesn't already exist.
868 // Otherwise, it must exist already as a rollup on the subject.
869 if rollup := getRollup(hdr); rollup == _EMPTY_ {
870 hdr = genHeader(hdr, JSMsgRollup, JSMsgRollupSubject)
871 } else if rollup != JSMsgRollupSubject {
872 apiErr := NewJSMessageSchedulesRollupInvalidError()
873 return hdr, msg, 0, apiErr, apiErr
874 }
875 }
876 }
877 if scheduleNext := sliceHeader(JSScheduleNext, hdr); len(scheduleNext) > 0 && !sourced {
878 // Clients may only use Nats-Schedule-Next to purge a schedule.
879 if bytesToString(scheduleNext) != JSScheduleNextPurge {
880 apiErr := NewJSMessageSchedulesSchedulerInvalidError()
881 return hdr, msg, 0, apiErr, apiErr
882 }
883 // Nats-Scheduler must accompany the purge and:
884 // - it must NOT be empty.
885 // - it must NOT match the publish subject.
886 if scheduler := sliceHeader(JSScheduler, hdr); len(scheduler) == 0 ||
887 bytesToString(scheduler) == subject || !IsValidPublishSubject(bytesToString(scheduler)) {
888 apiErr := NewJSMessageSchedulesSchedulerInvalidError()
889 return hdr, msg, 0, apiErr, apiErr
890 } else if !allowMsgSchedules {
891 apiErr := NewJSMessageSchedulesDisabledError()
892 return hdr, msg, 0, apiErr, apiErr
893 } else {
894 // Check that the to-be-purged subject is a schedule message.
895 // We still allow this message through if there exists no message for this subject,
896 // to remain backward-compatible. An "expected at sequence" check can still be
897 // performed to make this stricter.
898 schedSubj := bytesToString(scheduler)
899 var invalid bool
900 if i, ok := diff.inflight[schedSubj]; ok {
901 invalid = !i.schedule
902 } else if i, ok = mset.inflight[schedSubj]; ok {
903 invalid = !i.schedule
904 } else {
905 var smv StoreMsg
906 sm, _ := mset.store.LoadLastMsg(schedSubj, &smv)
907 invalid = sm != nil && len(sliceHeader(JSSchedulePattern, sm.hdr)) == 0
908 }
909 if invalid {
910 apiErr := NewJSMessageSchedulesSchedulerInvalidError()
911 return hdr, msg, 0, apiErr, apiErr
912 }
913 }
914 } else if !sourced && len(sliceHeader(JSScheduler, hdr)) > 0 {
915 // Clients may only use Nats-Scheduler alongside Nats-Schedule-Next.
916 apiErr := NewJSMessageSchedulesSchedulerInvalidError()
917 return hdr, msg, 0, apiErr, apiErr
918 }
919
920 // Check for any rollups.
921 if rollup := getRollup(hdr); rollup != _EMPTY_ {
922 if (!allowRollup || denyPurge) && !sourced {
923 err := errors.New("rollup not permitted")
924 return hdr, msg, 0, NewJSStreamRollupFailedError(err), err
925 }
926 switch rollup {
927 case JSMsgRollupSubject:
928 // Rolling up the subject is only allowed if the first occurrence of this subject in the batch.
929 if _, ok := diff.inflight[subject]; ok {
930 err := errors.New("batch rollup sub invalid")
931 return hdr, msg, 0, NewJSStreamRollupFailedError(err), err
932 }
933 case JSMsgRollupAll:
934 // Rolling up the whole stream is only allowed if this is the first message of the batch.
935 if len(diff.inflight) > 0 {
936 err := errors.New("batch rollup all invalid")
937 return hdr, msg, 0, NewJSStreamRollupFailedError(err), err
938 }
939 default:
940 err := fmt.Errorf("rollup value invalid: %q", rollup)
941 return hdr, msg, 0, NewJSStreamRollupFailedError(err), err
942 }
943 }
944 }
945
946 // Track inflight.
947 // Store the subject to ensure other messages in this batch using
948 // an expected check or rollup on the same subject fail.
949 if diff.inflight == nil {
950 diff.inflight = make(map[string]*inflightSubjectRunningTotal, 1)
951 }
952 var sz uint64
953 if mset.store.Type() == FileStorage {
954 sz = fileStoreMsgSizeRaw(len(subject), len(hdr), len(msg))
955 } else {
956 sz = memStoreMsgSizeRaw(len(subject), len(hdr), len(msg))
957 }
958 var (
959 i *inflightSubjectRunningTotal
960 ok bool
961 err error
962 )
963 if i, ok = diff.inflight[subject]; ok {
964 i.bytes += sz
965 i.ops++
966 i.schedule = hasSchedule
967 } else {
968 i = &inflightSubjectRunningTotal{bytes: sz, ops: 1, schedule: hasSchedule}
969 diff.inflight[subject] = i
970 }
971
972 // Subject transform.
973 if subject != rsubject {
974 // The 'subject' is a transformed subject used for consistency checks.
975 // But since we propose the original (raw) subject to our peers, we need
976 // to store the transformed subject separately for when we apply.
977 // TODO(mvv): since subject transforms are handled by each replica individually, this has a
978 // potential for desync given out-of-order stream subject transform updates.
979 if diff.inflightTransform == nil {
980 diff.inflightTransform = make(map[uint64]string, 1)
981 }
982 diff.inflightTransform[mset.clseq] = subject
983 }
984
985 // Check if we have discard new with max msgs or bytes.
986 // We need to deny here otherwise we'd need to bump CLFS, and it could succeed on some
987 // peers and not others depending on consumer ack state (if interest policy).
988 // So we deny here, if we allow that means we know it would succeed on every peer.
989 if discard == DiscardNew {
990 if maxMsgs > 0 || maxBytes > 0 {
991 // Track usual max msgs/bytes thresholds for DiscardNew.
992 var state StreamState
993 mset.store.FastState(&state)
994
995 totalMsgs := state.Msgs
996 totalBytes := state.Bytes
997 for _, i = range mset.inflight {
998 totalMsgs += i.ops
999 totalBytes += i.bytes
1000 }
1001 for _, i = range diff.inflight {
1002 totalMsgs += i.ops
1003 totalBytes += i.bytes
1004 }
1005
1006 if maxMsgs > 0 && totalMsgs > uint64(maxMsgs) {
1007 err = ErrMaxMsgs
1008 } else if maxBytes > 0 && totalBytes > uint64(maxBytes) {
1009 err = ErrMaxBytes
1010 }
1011 if err != nil {
1012 return hdr, msg, 0, NewJSStreamStoreFailedError(err, Unless(err)), err
1013 }
1014 }
1015
1016 // Similarly, check DiscardNew per-subject threshold to not need to bump CLFS.
1017 // Allow rollup messages through since they will purge after storing.
1018 if discardNewPer && maxMsgsPer > 0 && len(sliceHeader(JSMsgRollup, hdr)) == 0 {
1019 // Get the current total for this subject.
1020 totalMsgsForSubject := mset.store.SubjectsTotals(subject)[subject]
1021 // Add inflight count in this batch and for this stream.
1022 totalMsgsForSubject += i.ops
1023 if i, ok = mset.inflight[subject]; ok {
1024 totalMsgsForSubject += i.ops
1025 }
1026 if totalMsgsForSubject > uint64(maxMsgsPer) {
1027 err = ErrMaxMsgsPerSubject
1028 return hdr, msg, 0, NewJSStreamStoreFailedError(err, Unless(err)), err
1029 }
1030 }
1031 }
1032
1033 return hdr, msg, 0, nil, nil
1034 }
1035
1036 // recalculateClusteredSeq initializes or updates mset.clseq, for example after a leader change.
1037 // This is reused for normal clustered publishing into a stream, and for atomic and fast batch publishing.
1038 // mset.clMu lock must be held.
1039 func recalculateClusteredSeq(mset *stream, needStreamLock bool) (lseq uint64) {
1040 // Need to unlock and re-acquire the locks in the proper order.
1041 // Locking order is stream -> clMu
1042 if needStreamLock {
1043 mset.clMu.Unlock()
1044 mset.mu.RLock()
1045 mset.clMu.Lock()
1046 }
1047 // Re-capture
1048 lseq = mset.lseq
1049 mset.clseq = lseq + mset.clfs
1050 // Keep hold of the mset.clMu, but unlock the others.
1051 if needStreamLock {
1052 mset.mu.RUnlock()
1053 }
1054 return lseq
1055 }
1056
1057 // commitSingleMsg commits and proposes a single message to the node.
1058 // This is reused both for normal publishing into a stream, and for fast batch publishing.
1059 // mset.clMu lock must be held.
1060 func commitSingleMsg(
1061 diff *batchStagedDiff, mset *stream, subject string, reply string, hdr []byte, msg []byte, name string,
1062 jsa *jsAccount, mt *msgTrace, node RaftNode, term uint64, replicas int, lseq uint64,
1063 ) error {
1064 // Do proposal.
1065 esm := encodeStreamMsgAllowCompress(subject, reply, hdr, msg, mset.clseq, time.Now().UnixNano(), false)
1066 if err := node.Propose(term, esm); err != nil {
1067 return err
1068 }
1069
1070 var mtKey uint64
1071 if mt != nil {
1072 mtKey = mset.clseq
1073 if mset.mt == nil {
1074 mset.mt = make(map[uint64]*msgTrace)
1075 }
1076 mset.mt[mtKey] = mt
1077 }
1078
1079 diff.commit(mset)
1080 mset.clseq++
1081 mset.trackReplicationTraffic(node, len(esm), replicas)
1082
1083 // Check to see if we are being overrun.
1084 // TODO(dlc) - Make this a limit where we drop messages to protect ourselves, but allow to be configured.
1085 if mset.clseq-(lseq+mset.clfs) > streamLagWarnThreshold {
1086 lerr := fmt.Errorf("JetStream stream '%s > %s' has high message lag", jsa.acc().Name, name)
1087 mset.srv.RateLimitWarnf("%s", lerr.Error())
1088 }
1089 return nil
1090 }