Debian Codegraph @

server/stream.go

raw
1 // Copyright 2019-2026 The NATS Authors
2 // Licensed under the Apache License, Version 2.0 (the "License");
3 // you may not use this file except in compliance with the License.
4 // You may obtain a copy of the License at
5 //
6 // http://www.apache.org/licenses/LICENSE-2.0
7 //
8 // Unless required by applicable law or agreed to in writing, software
9 // distributed under the License is distributed on an "AS IS" BASIS,
10 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11 // See the License for the specific language governing permissions and
12 // limitations under the License.
13
14 package server
15
16 import (
17 "archive/tar"
18 "bytes"
19 "encoding/json"
20 "errors"
21 "fmt"
22 "io"
23 "math"
24 "math/big"
25 "math/rand"
26 "os"
27 "path/filepath"
28 "reflect"
29 "slices"
30 "strconv"
31 "strings"
32 "sync"
33 "sync/atomic"
34 "time"
35
36 "github.com/antithesishq/antithesis-sdk-go/assert"
37 "github.com/klauspost/compress/s2"
38 "github.com/nats-io/nats-server/v2/server/gsl"
39 "github.com/nats-io/nuid"
40 )
41
42 // StreamConfigRequest is used to create or update a stream.
43 type StreamConfigRequest struct {
44 StreamConfig
45 // This is not part of the StreamConfig, because its scoped to request,
46 // and not to the stream itself.
47 Pedantic bool `json:"pedantic,omitempty"`
48 }
49
50 // StreamConfig will determine the name, subjects and retention policy
51 // for a given stream. If subjects is empty the name will be used.
52 type StreamConfig struct {
53 Name string `json:"name"`
54 Description string `json:"description,omitempty"`
55 Subjects []string `json:"subjects,omitempty"`
56 Retention RetentionPolicy `json:"retention"`
57 MaxConsumers int `json:"max_consumers"`
58 MaxMsgs int64 `json:"max_msgs"`
59 MaxBytes int64 `json:"max_bytes"`
60 MaxAge time.Duration `json:"max_age"`
61 MaxMsgsPer int64 `json:"max_msgs_per_subject"`
62 MaxMsgSize int32 `json:"max_msg_size,omitempty"`
63 Discard DiscardPolicy `json:"discard"`
64 Storage StorageType `json:"storage"`
65 Replicas int `json:"num_replicas"`
66 NoAck bool `json:"no_ack,omitempty"`
67 Duplicates time.Duration `json:"duplicate_window,omitempty"`
68 Placement *Placement `json:"placement,omitempty"`
69 Mirror *StreamSource `json:"mirror,omitempty"`
70 Sources []*StreamSource `json:"sources,omitempty"`
71 Compression StoreCompression `json:"compression"`
72 FirstSeq uint64 `json:"first_seq,omitempty"`
73
74 // Allow applying a subject transform to incoming messages before doing anything else
75 SubjectTransform *SubjectTransformConfig `json:"subject_transform,omitempty"`
76
77 // Allow republish of the message after being sequenced and stored.
78 RePublish *RePublish `json:"republish,omitempty"`
79
80 // Allow higher performance, direct access to get individual messages. E.g. KeyValue
81 AllowDirect bool `json:"allow_direct"`
82 // Allow higher performance and unified direct access for mirrors as well.
83 MirrorDirect bool `json:"mirror_direct"`
84
85 // Allow KV like semantics to also discard new on a per subject basis
86 DiscardNewPer bool `json:"discard_new_per_subject,omitempty"`
87
88 // Optional qualifiers. These can not be modified after set to true.
89
90 // Sealed will seal a stream so no messages can get out or in.
91 Sealed bool `json:"sealed"`
92 // DenyDelete will restrict the ability to delete messages.
93 DenyDelete bool `json:"deny_delete"`
94 // DenyPurge will restrict the ability to purge messages.
95 DenyPurge bool `json:"deny_purge"`
96 // AllowRollup allows messages to be placed into the system and purge
97 // all older messages using a special msg header.
98 AllowRollup bool `json:"allow_rollup_hdrs"`
99
100 // The following defaults will apply to consumers when created against
101 // this stream, unless overridden manually.
102 // TODO(nat): Can/should we name these better?
103 ConsumerLimits StreamConsumerLimits `json:"consumer_limits"`
104
105 // AllowMsgTTL allows header initiated per-message TTLs. If disabled,
106 // then the `NATS-TTL` header will be ignored.
107 AllowMsgTTL bool `json:"allow_msg_ttl"`
108
109 // SubjectDeleteMarkerTTL sets the TTL of delete marker messages left behind by
110 // subject delete markers.
111 SubjectDeleteMarkerTTL time.Duration `json:"subject_delete_marker_ttl,omitempty"`
112
113 // AllowMsgCounter allows a stream to use (only) counter CRDTs.
114 AllowMsgCounter bool `json:"allow_msg_counter,omitempty"`
115
116 // AllowAtomicPublish allows atomic batch publishing into the stream.
117 AllowAtomicPublish bool `json:"allow_atomic,omitempty"`
118
119 // AllowMsgSchedules allows the scheduling of messages.
120 AllowMsgSchedules bool `json:"allow_msg_schedules,omitempty"`
121
122 // PersistMode allows to opt-in to different persistence mode settings.
123 PersistMode PersistModeType `json:"persist_mode,omitempty"`
124
125 // AllowBatchPublish allows fast batch publishing into the stream.
126 AllowBatchPublish bool `json:"allow_batched,omitempty"`
127
128 // Metadata is additional metadata for the Stream.
129 Metadata map[string]string `json:"metadata,omitempty"`
130 }
131
132 // clone performs a deep copy of the StreamConfig struct, returning a new clone with
133 // all values copied.
134 func (cfg *StreamConfig) clone() *StreamConfig {
135 clone := *cfg
136 if cfg.Placement != nil {
137 placement := *cfg.Placement
138 clone.Placement = &placement
139 }
140 if cfg.Mirror != nil {
141 mirror := *cfg.Mirror
142 clone.Mirror = &mirror
143 }
144 if len(cfg.Sources) > 0 {
145 clone.Sources = make([]*StreamSource, len(cfg.Sources))
146 for i, cfgSource := range cfg.Sources {
147 source := *cfgSource
148 clone.Sources[i] = &source
149 }
150 }
151 if cfg.SubjectTransform != nil {
152 transform := *cfg.SubjectTransform
153 clone.SubjectTransform = &transform
154 }
155 if cfg.RePublish != nil {
156 rePublish := *cfg.RePublish
157 clone.RePublish = &rePublish
158 }
159 if cfg.Metadata != nil {
160 clone.Metadata = make(map[string]string, len(cfg.Metadata))
161 for k, v := range cfg.Metadata {
162 clone.Metadata[k] = v
163 }
164 }
165 return &clone
166 }
167
168 type StreamConsumerLimits struct {
169 InactiveThreshold time.Duration `json:"inactive_threshold,omitempty"`
170 MaxAckPending int `json:"max_ack_pending,omitempty"`
171 }
172
173 // SubjectTransformConfig is for applying a subject transform (to matching messages) before doing anything else when a new message is received
174 type SubjectTransformConfig struct {
175 Source string `json:"src"`
176 Destination string `json:"dest"`
177 }
178
179 // RePublish is for republishing messages once committed to a stream.
180 type RePublish struct {
181 Source string `json:"src,omitempty"`
182 Destination string `json:"dest"`
183 HeadersOnly bool `json:"headers_only,omitempty"`
184 }
185
186 // PersistModeType determines what persistence mode the stream uses.
187 type PersistModeType int
188
189 const (
190 // DefaultPersistMode specifies the default persist mode. Writes to the stream will immediately be flushed.
191 // The publish acknowledgement will be sent after the persisting completes.
192 DefaultPersistMode = PersistModeType(iota)
193 // AsyncPersistMode specifies writes to the stream will be flushed asynchronously.
194 // The publish acknowledgement may be sent before the persisting completes.
195 // This means writes could be lost if they weren't flushed prior to a hard kill of the server.
196 AsyncPersistMode
197 )
198
199 const (
200 defaultPersistModeJSONString = `"default"`
201 asyncPersistModeJSONString = `"async"`
202 )
203
204 var (
205 defaultPersistModeJSONBytes = []byte(defaultPersistModeJSONString)
206 asyncPersistModeJSONBytes = []byte(asyncPersistModeJSONString)
207 )
208
209 func (wc PersistModeType) String() string {
210 switch wc {
211 case DefaultPersistMode:
212 return "Default"
213 case AsyncPersistMode:
214 return "Async"
215 default:
216 return "Unknown Persist Mode Type"
217 }
218 }
219
220 func (wc PersistModeType) MarshalJSON() ([]byte, error) {
221 switch wc {
222 case DefaultPersistMode:
223 return defaultPersistModeJSONBytes, nil
224 case AsyncPersistMode:
225 return asyncPersistModeJSONBytes, nil
226 default:
227 return nil, fmt.Errorf("can not marshal %v", wc)
228 }
229 }
230
231 func (wc *PersistModeType) UnmarshalJSON(data []byte) error {
232 switch string(data) {
233 case defaultPersistModeJSONString, `""`:
234 *wc = DefaultPersistMode
235 case asyncPersistModeJSONString:
236 *wc = AsyncPersistMode
237 default:
238 return fmt.Errorf("can not unmarshal %q", data)
239 }
240 return nil
241 }
242
243 // JSPubAckResponse is a formal response to a publish operation.
244 type JSPubAckResponse struct {
245 Error *ApiError `json:"error,omitempty"`
246 *PubAck
247 }
248
249 // ToError checks if the response has a error and if it does converts it to an error
250 // avoiding the pitfalls described by https://yourbasic.org/golang/gotcha-why-nil-error-not-equal-nil/
251 func (r *JSPubAckResponse) ToError() error {
252 if r.Error == nil {
253 return nil
254 }
255 return r.Error
256 }
257
258 // PubAck is the detail you get back from a publish to a stream that was successful.
259 // e.g. +OK {"stream": "Orders", "seq": 22}
260 type PubAck struct {
261 Stream string `json:"stream"`
262 Sequence uint64 `json:"seq"`
263 Domain string `json:"domain,omitempty"`
264 Duplicate bool `json:"duplicate,omitempty"`
265 Value string `json:"val,omitempty"`
266 BatchId string `json:"batch,omitempty"`
267 BatchSize uint64 `json:"count,omitempty"`
268 }
269
270 // CounterValue is the body of a message when used as a counter.
271 // e.g. {"val":"123"}
272 type CounterValue struct {
273 Value string `json:"val"`
274 }
275
276 // CounterSources is the body of the Nats-Counter-Sources header.
277 // e.g. {"stream":{"subject":"123"}}
278 type CounterSources map[string]map[string]string
279
280 // BatchFlowAck is used for flow control when fast batch publishing into a stream.
281 // This message is vital to handling acknowledgements and flow control.
282 // These may technically be lost without the client receiving it. The client can retrieve
283 // these by using the "ping" operation if it's expecting acks but not receiving any.
284 type BatchFlowAck struct {
285 // Type: "ack"
286 Type string `json:"type"`
287 // Sequence is the sequence of the message that triggered the ack.
288 // If "gap: fail" this means the messages up to and including Sequence were persisted.
289 // If "gap: ok" this means _some_ of the messages up to and including Sequence were persisted.
290 // But there could have been gaps.
291 Sequence uint64 `json:"seq"`
292 // Messages indicates acknowledgements will be sent every N messages.
293 Messages uint16 `json:"msgs"`
294 }
295
296 func (ack BatchFlowAck) MarshalJSON() ([]byte, error) {
297 type Alias BatchFlowAck
298 a := Alias(ack)
299 a.Type = "ack"
300 return json.Marshal(a)
301 }
302
303 // BatchFlowGap is used for reporting gaps when fast batch publishing into a stream.
304 // This message is purely informational and could technically be lost without the client receiving it.
305 type BatchFlowGap struct {
306 // Type: "gap"
307 Type string `json:"type"`
308 // ExpectedLastSequence is the sequence expected to be received next.
309 // Messages starting from ExpectedLastSequence up to (but not including) CurrentSequence were lost.
310 ExpectedLastSequence uint64 `json:"last_seq"`
311 // CurrentSequence is the sequence of the message that just came in and detected the gap.
312 CurrentSequence uint64 `json:"seq"`
313 }
314
315 func (gap BatchFlowGap) MarshalJSON() ([]byte, error) {
316 type Alias BatchFlowGap
317 a := Alias(gap)
318 a.Type = "gap"
319 return json.Marshal(a)
320 }
321
322 // BatchFlowErr is used for reporting errors when fast batch publishing into a stream.
323 // This message is purely informational and could technically be lost without the client receiving it.
324 type BatchFlowErr struct {
325 // Type: "err"
326 Type string `json:"type"`
327 // Sequence is the sequence of the message that triggered the error.
328 // There are no (relative) guarantees whatsoever about whether the messages up to this sequence were persisted.
329 // Such guarantees require the use of "gap: fail" and listening for BatchFlowAck and PubAck.
330 Sequence uint64 `json:"seq"`
331 // Error is used to return the error for the Sequence.
332 Error *ApiError `json:"error"`
333 }
334
335 func (err BatchFlowErr) MarshalJSON() ([]byte, error) {
336 type Alias BatchFlowErr
337 a := Alias(err)
338 a.Type = "err"
339 return json.Marshal(a)
340 }
341
342 // StreamInfo shows config and current state for this stream.
343 type StreamInfo struct {
344 Config StreamConfig `json:"config"`
345 Created time.Time `json:"created"`
346 State StreamState `json:"state"`
347 Domain string `json:"domain,omitempty"`
348 Cluster *ClusterInfo `json:"cluster,omitempty"`
349 Mirror *StreamSourceInfo `json:"mirror,omitempty"`
350 Sources []*StreamSourceInfo `json:"sources,omitempty"`
351 Alternates []StreamAlternate `json:"alternates,omitempty"`
352 // TimeStamp indicates when the info was gathered
353 TimeStamp time.Time `json:"ts"`
354 }
355
356 // streamInfoClusterResponse is a response used in a cluster to communicate the stream info
357 // back to the meta leader as part of a stream list request.
358 type streamInfoClusterResponse struct {
359 StreamInfo
360 OfflineReason string `json:"offline_reason,omitempty"` // Reporting when a stream is offline.
361 }
362
363 type StreamAlternate struct {
364 Name string `json:"name"`
365 Domain string `json:"domain,omitempty"`
366 Cluster string `json:"cluster"`
367 }
368
369 // ClusterInfo shows information about the underlying set of servers
370 // that make up the stream or consumer.
371 type ClusterInfo struct {
372 Name string `json:"name,omitempty"`
373 RaftGroup string `json:"raft_group,omitempty"`
374 Leader string `json:"leader,omitempty"`
375 LeaderSince *time.Time `json:"leader_since,omitempty"`
376 SystemAcc bool `json:"system_account,omitempty"`
377 TrafficAcc string `json:"traffic_account,omitempty"`
378 Replicas []*PeerInfo `json:"replicas,omitempty"`
379 }
380
381 // PeerInfo shows information about all the peers in the cluster that
382 // are supporting the stream or consumer.
383 type PeerInfo struct {
384 Name string `json:"name"` // Name is the unique name for the peer
385 Current bool `json:"current"` // Current indicates if it was seen recently and fully caught up
386 Offline bool `json:"offline,omitempty"` // Offline indicates if it has not been seen recently
387 Active time.Duration `json:"active"` // Active is the timestamp it was last active
388 Lag uint64 `json:"lag,omitempty"` // Lag is how many operations behind it is
389 Peer string `json:"peer"` // Peer is the unique ID for the peer
390 // For migrations.
391 cluster string
392 }
393
394 // StreamSourceInfo shows information about an upstream stream source.
395 type StreamSourceInfo struct {
396 Name string `json:"name"`
397 External *ExternalStream `json:"external,omitempty"`
398 Lag uint64 `json:"lag"`
399 Active time.Duration `json:"active"`
400 Error *ApiError `json:"error,omitempty"`
401 FilterSubject string `json:"filter_subject,omitempty"`
402 SubjectTransforms []SubjectTransformConfig `json:"subject_transforms,omitempty"`
403 }
404
405 // StreamSource dictates how streams can source from other streams.
406 type StreamSource struct {
407 Name string `json:"name"`
408 OptStartSeq uint64 `json:"opt_start_seq,omitempty"`
409 OptStartTime *time.Time `json:"opt_start_time,omitempty"`
410 FilterSubject string `json:"filter_subject,omitempty"`
411 SubjectTransforms []SubjectTransformConfig `json:"subject_transforms,omitempty"`
412 External *ExternalStream `json:"external,omitempty"`
413 Consumer *StreamConsumerSource `json:"consumer,omitempty"`
414
415 // Internal
416 iname string // For indexing when stream names are the same for multiple sources.
417 }
418
419 // StreamConsumerSource dictates a durable consumer with a specific name is used for sourcing.
420 type StreamConsumerSource struct {
421 Name string `json:"name,omitempty"`
422 DeliverSubject string `json:"deliver_subject,omitempty"`
423 }
424
425 // ExternalStream allows you to qualify access to a stream source in another account or domain.
426 type ExternalStream struct {
427 ApiPrefix string `json:"api"`
428 DeliverPrefix string `json:"deliver"`
429 }
430
431 // Will return the domain for this external stream.
432 func (ext *ExternalStream) Domain() string {
433 if ext == nil || ext.ApiPrefix == _EMPTY_ {
434 return _EMPTY_
435 }
436 return tokenAt(ext.ApiPrefix, 2)
437 }
438
439 // For managing stream ingest.
440 const (
441 streamDefaultMaxQueueMsgs = 100_000
442 streamDefaultMaxQueueBytes = 128 * 1024 * 1024
443 )
444
445 // For managing stream batches.
446 const (
447 streamDefaultMaxBatchTimeout = 10 * time.Second
448 // Atomic batches.
449 streamDefaultMaxAtomicBatchInflightPerStream = 50
450 streamDefaultMaxAtomicBatchInflightTotal = 1000
451 streamDefaultMaxAtomicBatchSize = 1000
452 // Fast batches.
453 streamDefaultMaxFastBatchInflightPerStream = 1000
454 streamDefaultMaxFastBatchInflightTotal = 50_000
455 )
456
457 var (
458 streamMaxBatchTimeout = streamDefaultMaxBatchTimeout
459 // Atomic batches.
460 streamMaxAtomicBatchInflightPerStream = streamDefaultMaxAtomicBatchInflightPerStream
461 streamMaxAtomicBatchInflightTotal = streamDefaultMaxAtomicBatchInflightTotal
462 streamMaxAtomicBatchSize = streamDefaultMaxAtomicBatchSize
463 // Fast batches.
464 streamMaxFastBatchInflightPerStream = streamDefaultMaxFastBatchInflightPerStream
465 streamMaxFastBatchInflightTotal = streamDefaultMaxFastBatchInflightTotal
466 )
467
468 // Stream is a jetstream stream of messages. When we receive a message internally destined
469 // for a Stream we will direct link from the client to this structure.
470 type stream struct {
471 mu sync.RWMutex // Read/write lock for the stream.
472 js *jetStream // The internal *jetStream for the account.
473 jsa *jsAccount // The JetStream account-level information.
474 acc *Account // The account this stream is defined in.
475 srv *Server // The server we are running in.
476 client *client // The internal JetStream client.
477 sysc *client // The internal JetStream system client.
478
479 // Isolates direct get and msg get reads from writes (ingest, atomic batch
480 // commits, purges and deletes), so those reads never observe a partially
481 // applied atomic batch or rollup. Other read paths (consumer delivery,
482 // mirrors/sources, mset.mu-based info) are sequentially consistent and may
483 // observe a prefix of an inflight batch.
484 isolateMu sync.RWMutex
485
486 // The current last subscription ID for the subscriptions through `client`.
487 // Those subscriptions are for the subjects filters being listened to and captured by the stream.
488 sid atomic.Uint64
489
490 // Whether the stream layer has completed leader setup via setLeader. Unlike isLeader(),
491 // which reads the raft node's current state, this tracks our own processed leadership.
492 leader atomic.Bool
493
494 pubAck []byte // The template (prefix) to generate the pubAck responses for this stream quickly.
495 outq *jsOutQ // Queue of *jsPubMsg for sending messages.
496 msgs *ipQueue[*inMsg] // Intra-process queue for the ingress of messages.
497 gets *ipQueue[*directGetReq] // Intra-process queue for the direct get requests.
498 store StreamStore // The storage for this stream.
499 ackq *ipQueue[uint64] // Intra-process queue for acks.
500 lseq uint64 // The sequence number of the last message stored in the stream.
501 term uint64 // Raft term, used to determine if we are still the leader for the current term (if applicable, 0 otherwise).
502 lmsgId string // The de-duplication message ID of the last message stored in the stream.
503 consumers map[string]*consumer // The consumers for this stream.
504 cfg StreamConfig // The stream's config.
505 cfgMu sync.RWMutex // Config mutex used to solve some races with consumer code
506 created time.Time // Time the stream was created.
507 stype StorageType // The storage type.
508 tier string // The tier is the number of replicas for the stream (e.g. "R1" or "R3").
509 ddMu sync.Mutex // Lock for dedupe state.
510 ddmap map[string]*ddentry // The dedupe map.
511 ddarr []*ddentry // The dedupe array.
512 ddindex int // The dedupe index.
513 ddtmr *time.Timer // The dedupe timer.
514 qch chan struct{} // The quit channel.
515 mqch chan struct{} // The monitor's quit channel.
516 active bool // Indicates that there are active internal subscriptions (for the subject filters)
517 // and/or mirror/sources consumers are scheduled to be established or already started.
518 closed atomic.Bool // Set to true when stop() is called on the stream.
519 cisrun atomic.Bool // Indicates one checkInterestState is already running.
520
521 // Mirror
522 mirror *sourceInfo
523 mirrorConsumerSetup *time.Timer
524
525 // Sources
526 sources map[string]*sourceInfo
527 sourceSetupSchedules map[string]*time.Timer
528 sourcesConsumerSetup *time.Timer
529 smsgs *ipQueue[*inMsg] // Intra-process queue for all incoming sourced messages.
530
531 // Indicates we have direct/sourcing consumers.
532 sourcingConsumers int
533
534 // For input subject transform.
535 itr *subjectTransform
536
537 // For republishing.
538 tr *subjectTransform
539
540 // For processing consumers without main stream lock.
541 clsMu sync.RWMutex
542 cList []*consumer // Consumer list.
543 sch chan struct{} // Channel to signal consumers.
544 sigq *ipQueue[*cMsg] // Intra-process queue for the messages to signal to the consumers.
545 csl *gsl.GenericSublist[*consumer] // Consumer subscription list.
546
547 // Leader will store seq/msgTrace in clustering mode. Used in applyStreamEntries
548 // to know if trace event should be sent after processing.
549 mt map[uint64]*msgTrace
550
551 // For non limits policy streams when they process an ack before the actual msg.
552 // Can happen in stretch clusters, multi-cloud, or during catchup for a restarted server.
553 preAcks map[uint64]map[*consumer]struct{}
554
555 // TODO(dlc) - Hide everything below behind two pointers.
556 // Clustered mode.
557 sa *streamAssignment // What the meta controller uses to assign streams to peers.
558 node RaftNode // Our RAFT node for the stream's group.
559 catchup atomic.Bool // Used to signal we are in catchup mode.
560 catchups map[string]uint64 // The number of messages that need to be caught per peer.
561 syncSub *subscription // Internal subscription for sync messages (on "$JSC.SYNC").
562 infoSub *subscription // Internal subscription for stream info requests.
563 clMu sync.Mutex // The mutex for clseq and clfs.
564 clseq uint64 // The current last seq being proposed to the NRG layer.
565 clfs uint64 // The count (offset) of the number of failed NRG sequences used to compute clseq.
566 lqsent time.Time // The time at which the last lost quorum advisory was sent. Used to rate limit.
567 uch chan struct{} // The channel to signal updates to the monitor routine.
568 inMonitor bool // True if the monitor routine has been started.
569 werr error // If a write error was encountered, and if so what error.
570
571 inflight map[string]*inflightSubjectRunningTotal // Inflight message sizes per subject.
572 inflightTransform map[uint64]string // Inflight message's optional transformed subject.
573 clusteredCounterTotal map[string]*msgCounterRunningTotal // Inflight counter totals.
574 expectedPerSubjectSequence map[uint64]string // Inflight 'expected per subject' subjects per clseq.
575 expectedPerSubjectInProcess map[string]struct{} // Current 'expected per subject' subjects in process.
576
577 // Direct get subscription.
578 directLeaderSub *subscription
579 directSub *subscription
580 lastBySub *subscription
581 mirrorDirectSub *subscription // Mirrors only.
582 mirrorLastBySub *subscription // Mirrors only.
583
584 monitorWg sync.WaitGroup // Wait group for the monitor routine.
585 monitorMu sync.Mutex // Serializes monitorWg's Add against Wait to prevent a WaitGroup reuse panic.
586
587 // If standalone/single-server, the offline reason needs to be stored directly in the stream.
588 // Otherwise, if clustered it will be part of the stream assignment.
589 offlineReason string
590
591 batches *batching // Inflight batches prior to committing them.
592 }
593
594 // inflightSubjectRunningTotal stores a running total of inflight messages for a specific subject.
595 type inflightSubjectRunningTotal struct {
596 bytes uint64 // Running total of inflight bytes for inflight messages.
597 ops uint64 // Inflight operations, i.e. inflight messages for this subject. If this reaches zero, we can remove the running total.
598 schedule bool // Marks whether the last message is a schedule.
599 }
600
601 // msgCounterRunningTotal stores a running total and a number of inflight
602 // but not yet applied clustered proposals/operations for this counter.
603 type msgCounterRunningTotal struct {
604 total *big.Int // Running total.
605 sources CounterSources // Last seen counter sources.
606 ops uint64 // Inflight operations. If this reaches zero, we can remove the running total.
607 }
608
609 type sourceInfo struct {
610 name string // The name of the stream being sourced.
611 iname string // The unique index name of this particular source.
612 cname string // The name of the current consumer for this source.
613 sub *subscription // The subscription to the consumer.
614
615 msgs *ipQueue[*inMsg] // Intra-process queue for incoming messages.
616 sseq uint64 // Last stream message sequence number seen from the source.
617 dseq uint64 // Last delivery (i.e. consumer's) sequence number.
618 lag uint64 // 0 or number of messages pending (as last reported by the consumer) - 1.
619 err *ApiError // The API error that caused the last consumer setup to fail.
620 fails int // The number of times trying to setup the consumer failed.
621 last atomic.Int64 // Time the consumer was created or of last message it received.
622 lreq time.Time // The last time setupMirrorConsumer/setupSourceConsumer was called.
623 qch chan struct{} // Quit channel.
624 sip bool // Setup in progress.
625 wg sync.WaitGroup // WaitGroup for the consumer's go routine.
626 sf string // The subject filter.
627 sfs []string // The subject filters.
628 trs []*subjectTransform // The subject transforms.
629 }
630
631 // For mirrors and direct get
632 const (
633 dgetGroup = sysGroup
634 dgetCaughtUpThresh = 10
635 )
636
637 // Headers for published messages.
638 const (
639 JSMsgId = "Nats-Msg-Id"
640 JSExpectedStream = "Nats-Expected-Stream"
641 JSExpectedLastSeq = "Nats-Expected-Last-Sequence"
642 JSExpectedLastSubjSeq = "Nats-Expected-Last-Subject-Sequence"
643 JSExpectedLastSubjSeqSubj = "Nats-Expected-Last-Subject-Sequence-Subject"
644 JSExpectedLastMsgId = "Nats-Expected-Last-Msg-Id"
645 JSStreamSource = "Nats-Stream-Source"
646 JSLastConsumerSeq = "Nats-Last-Consumer"
647 JSLastStreamSeq = "Nats-Last-Stream"
648 JSConsumerStalled = "Nats-Consumer-Stalled"
649 JSMsgRollup = "Nats-Rollup"
650 JSMsgSize = "Nats-Msg-Size"
651 JSResponseType = "Nats-Response-Type"
652 JSMessageTTL = "Nats-TTL"
653 JSMarkerReason = "Nats-Marker-Reason"
654 JSMessageIncr = "Nats-Incr"
655 JSMessageCounterSources = "Nats-Counter-Sources"
656 JSBatchId = "Nats-Batch-Id"
657 JSBatchSeq = "Nats-Batch-Sequence"
658 JSBatchCommit = "Nats-Batch-Commit"
659 JSSchedulePattern = "Nats-Schedule"
660 JSScheduleTimeZone = "Nats-Schedule-Time-Zone"
661 JSScheduleTTL = "Nats-Schedule-TTL"
662 JSScheduleRollup = "Nats-Schedule-Rollup"
663 JSScheduleTarget = "Nats-Schedule-Target"
664 JSScheduleSource = "Nats-Schedule-Source"
665 )
666
667 // Headers for published KV messages.
668 var (
669 KVOperation = "KV-Operation"
670 KVOperationValuePurge = []byte("PURGE")
671 )
672
673 // Headers for scheduled messages.
674 const (
675 JSScheduler = "Nats-Scheduler"
676 JSScheduleNext = "Nats-Schedule-Next"
677 JSScheduleNextPurge = "purge" // If it's a non-repeating/delayed message, the schedule is purged.
678 )
679
680 // Headers for republished messages and direct get responses.
681 const (
682 JSStream = "Nats-Stream"
683 JSSequence = "Nats-Sequence"
684 JSTimeStamp = "Nats-Time-Stamp"
685 JSSubject = "Nats-Subject"
686 JSLastSequence = "Nats-Last-Sequence" // The sequence number of the precedent message either republished or in a batch of responses. 0 in the first message.
687 JSNumPending = "Nats-Num-Pending" // Number of messages pending in the multi/batched get response
688 JSUpToSequence = "Nats-UpTo-Sequence"
689 )
690
691 // Rollups, can be subject only or all messages.
692 const (
693 JSMsgRollupSubject = "sub"
694 JSMsgRollupAll = "all"
695 )
696
697 // Applied limits in the Nats-Applied-Limit header.
698 const (
699 JSMarkerReasonMaxAge = "MaxAge"
700 JSMarkerReasonPurge = "Purge"
701 JSMarkerReasonRemove = "Remove"
702 )
703
704 const (
705 jsCreateResponse = "create"
706 )
707
708 // Dedupe entry
709 type ddentry struct {
710 id string // The unique message ID provided by the client.
711 seq uint64 // The sequence number of the message.
712 ts int64 // The timestamp of the message.
713 }
714
715 // Replicas Range
716 const StreamMaxReplicas = 5
717
718 // AddStream adds a stream for the given account.
719 func (a *Account) addStream(config *StreamConfig) (*stream, error) {
720 return a.addStreamWithAssignment(config, nil, nil, false, false)
721 }
722
723 // recoverStream recovers a stream from disk for the given account.
724 func (a *Account) recoverStream(config *StreamConfig) (*stream, error) {
725 return a.addStreamWithAssignment(config, nil, nil, false, true)
726 }
727
728 // AddStreamWithStore adds a stream for the given account with custome store config options.
729 func (a *Account) addStreamWithStore(config *StreamConfig, fsConfig *FileStoreConfig) (*stream, error) {
730 return a.addStreamWithAssignment(config, fsConfig, nil, false, false)
731 }
732
733 func (a *Account) addStreamPedantic(config *StreamConfig, pedantic bool) (*stream, error) {
734 return a.addStreamWithAssignment(config, nil, nil, pedantic, false)
735 }
736
737 func (a *Account) addStreamWithAssignment(config *StreamConfig, fsConfig *FileStoreConfig, sa *streamAssignment, pedantic, recovering bool) (*stream, error) {
738 s, jsa, err := a.checkForJetStream()
739 if err != nil {
740 return nil, err
741 }
742
743 // If we do not have the stream currently assigned to us in cluster mode we will proceed but warn.
744 // This can happen on startup with restored state where on meta replay we still do not have
745 // the assignment. Running in single server mode this always returns true.
746 if !jsa.streamAssigned(config.Name) {
747 s.Debugf("Stream '%s > %s' does not seem to be assigned to this server", a.Name, config.Name)
748 }
749
750 // Sensible defaults.
751 ccfg, apiErr := s.checkStreamCfg(config, a, pedantic)
752 if apiErr != nil {
753 return nil, apiErr
754 }
755 cfg := &ccfg
756
757 singleServerMode := !s.JetStreamIsClustered() && s.standAloneMode()
758 if singleServerMode && cfg.Replicas > 1 {
759 return nil, ApiErrors[JSStreamReplicasNotSupportedErr]
760 }
761
762 // Make sure we are ok when these are done in parallel.
763 // We used to call Add(1) in the "else" clause of the "if loaded"
764 // statement. This caused a data race because it was possible
765 // that one go routine stores (with count==0) and another routine
766 // gets "loaded==true" and calls wg.Wait() while the other routine
767 // then calls wg.Add(1). It also could mean that two routines execute
768 // the rest of the code concurrently.
769 swg := &sync.WaitGroup{}
770 swg.Add(1)
771 v, loaded := jsa.inflight.LoadOrStore(cfg.Name, swg)
772 wg := v.(*sync.WaitGroup)
773 if loaded {
774 wg.Wait()
775 // This waitgroup is "thrown away" (since there was an existing one).
776 swg.Done()
777 } else {
778 defer func() {
779 jsa.inflight.Delete(cfg.Name)
780 wg.Done()
781 }()
782 }
783
784 // Note that isClustered will be false during recovery, even if we're part of a cluster. It shouldn't be used then.
785 js, isClustered := jsa.jetStreamAndClustered()
786 jsa.mu.Lock()
787 if mset, ok := jsa.streams[cfg.Name]; ok {
788 jsa.mu.Unlock()
789 // Check to see if configs are same.
790 ocfg := mset.config()
791
792 // set the index name on cfg since it would not contain a value for iname while the return from mset.config() does to ensure the DeepEqual works
793 for _, s := range cfg.Sources {
794 s.setIndexName()
795 }
796
797 // Hold lock, because we'll be reading from and writing to a shared object.
798 js.mu.Lock()
799 copyStreamMetadata(cfg, &ocfg)
800 deepEqual := reflect.DeepEqual(cfg, &ocfg)
801 js.mu.Unlock()
802 if deepEqual {
803 if sa != nil {
804 mset.setStreamAssignment(sa)
805 }
806 return mset, nil
807 } else {
808 return nil, ApiErrors[JSStreamNameExistErr]
809 }
810 }
811 jsa.usageMu.RLock()
812 selected, tier, hasTier := jsa.selectLimits(cfg.Replicas)
813 jsa.usageMu.RUnlock()
814
815 if !hasTier {
816 jsa.mu.Unlock()
817 return nil, NewJSNoLimitsError()
818 }
819
820 // Skip if we're recovering.
821 if !recovering {
822 reserved := int64(0)
823 if !isClustered {
824 reserved = jsa.tieredReservation(tier, cfg)
825 }
826 jsa.mu.Unlock()
827 js.mu.RLock()
828 if isClustered {
829 _, reserved = js.tieredStreamAndReservationCount(a.Name, tier, cfg)
830 }
831 if err := js.checkAllLimits(&selected, tier, cfg, reserved, 0); err != nil {
832 js.mu.RUnlock()
833 return nil, err
834 }
835 js.mu.RUnlock()
836 jsa.mu.Lock()
837 }
838
839 // If mirror, check if the transforms (if any) are valid.
840 if cfg.Mirror != nil {
841 if len(cfg.Mirror.SubjectTransforms) == 0 {
842 if cfg.Mirror.FilterSubject != _EMPTY_ && !IsValidSubject(cfg.Mirror.FilterSubject) {
843 jsa.mu.Unlock()
844 return nil, fmt.Errorf("subject filter '%s' for the mirror %w", cfg.Mirror.FilterSubject, ErrBadSubject)
845 }
846 } else {
847 for _, st := range cfg.Mirror.SubjectTransforms {
848 if st.Source != _EMPTY_ && !IsValidSubject(st.Source) {
849 jsa.mu.Unlock()
850 return nil, fmt.Errorf("invalid subject transform source '%s' for the mirror: %w", st.Source, ErrBadSubject)
851 }
852 // check the transform, if any, is valid
853 if st.Destination != _EMPTY_ {
854 if _, err = NewSubjectTransform(st.Source, st.Destination); err != nil {
855 jsa.mu.Unlock()
856 return nil, fmt.Errorf("subject transform from '%s' to '%s' for the mirror: %w", st.Source, st.Destination, err)
857 }
858 }
859 }
860 }
861 }
862
863 // Setup our internal indexed names here for sources and check if the transforms (if any) are valid.
864 for _, ssi := range cfg.Sources {
865 if len(ssi.SubjectTransforms) == 0 {
866 // check the filter, if any, is valid
867 if ssi.FilterSubject != _EMPTY_ && !IsValidSubject(ssi.FilterSubject) {
868 jsa.mu.Unlock()
869 return nil, fmt.Errorf("subject filter '%s' for the source: %w", ssi.FilterSubject, ErrBadSubject)
870 }
871 } else {
872 for _, st := range ssi.SubjectTransforms {
873 if st.Source != _EMPTY_ && !IsValidSubject(st.Source) {
874 jsa.mu.Unlock()
875 return nil, fmt.Errorf("subject filter '%s' for the source: %w", st.Source, ErrBadSubject)
876 }
877 // check the transform, if any, is valid
878 if st.Destination != _EMPTY_ {
879 if _, err = NewSubjectTransform(st.Source, st.Destination); err != nil {
880 jsa.mu.Unlock()
881 return nil, fmt.Errorf("subject transform from '%s' to '%s' for the source: %w", st.Source, st.Destination, err)
882 }
883 }
884 }
885 }
886 }
887
888 // Check for overlapping subjects with other streams.
889 // These are not allowed for now.
890 if jsa.subjectsOverlap(cfg.Subjects, nil) {
891 jsa.mu.Unlock()
892 return nil, NewJSStreamSubjectOverlapError()
893 }
894
895 // Setup the internal clients.
896 c := s.createInternalJetStreamClient()
897 ic := s.createInternalJetStreamClient()
898
899 // Work out the stream ingest limits.
900 mlen := s.opts.StreamMaxBufferedMsgs
901 msz := uint64(s.opts.StreamMaxBufferedSize)
902 if mlen == 0 {
903 mlen = streamDefaultMaxQueueMsgs
904 }
905 if msz == 0 {
906 msz = streamDefaultMaxQueueBytes
907 }
908
909 qpfx := fmt.Sprintf("[ACC:%s] stream '%s' ", a.Name, config.Name)
910 mset := &stream{
911 acc: a,
912 jsa: jsa,
913 cfg: *cfg,
914 js: js,
915 srv: s,
916 client: c,
917 sysc: ic,
918 tier: tier,
919 stype: cfg.Storage,
920 consumers: make(map[string]*consumer),
921 msgs: newIPQueue[*inMsg](s, qpfx+"messages",
922 ipqSizeCalculation(func(msg *inMsg) uint64 {
923 return uint64(len(msg.hdr) + len(msg.msg) + len(msg.rply) + len(msg.subj))
924 }),
925 ipqLimitByLen[*inMsg](mlen),
926 ipqLimitBySize[*inMsg](msz),
927 ),
928 gets: newIPQueue[*directGetReq](s, qpfx+"direct gets"),
929 qch: make(chan struct{}),
930 mqch: make(chan struct{}),
931 uch: make(chan struct{}, 4),
932 sch: make(chan struct{}, 1),
933 created: time.Now().UTC(),
934 }
935
936 // Add created timestamp used for the store, must match that of the stream assignment if it exists.
937 if sa != nil {
938 // The following assignment does not require mutex
939 // protection: sa.Created is immutable.
940 mset.created = sa.Created
941 }
942
943 // Start our signaling routine to process consumers.
944 mset.sigq = newIPQueue[*cMsg](s, qpfx+"obs") // of *cMsg
945 go mset.signalConsumersLoop()
946
947 // For no-ack consumers when we are interest retention.
948 if cfg.Retention != LimitsPolicy {
949 mset.ackq = newIPQueue[uint64](s, qpfx+"acks")
950 }
951
952 // Check for input subject transform
953 if cfg.SubjectTransform != nil {
954 tr, err := NewSubjectTransform(cfg.SubjectTransform.Source, cfg.SubjectTransform.Destination)
955 if err != nil {
956 jsa.mu.Unlock()
957 return nil, fmt.Errorf("stream subject transform from '%s' to '%s': %w", cfg.SubjectTransform.Source, cfg.SubjectTransform.Destination, err)
958 }
959 mset.itr = tr
960 }
961
962 // Check for RePublish.
963 if cfg.RePublish != nil {
964 tr, err := NewSubjectTransform(cfg.RePublish.Source, cfg.RePublish.Destination)
965 if err != nil {
966 jsa.mu.Unlock()
967 return nil, fmt.Errorf("stream republish transform from '%s' to '%s': %w", cfg.RePublish.Source, cfg.RePublish.Destination, err)
968 }
969 // Assign our transform for republishing.
970 mset.tr = tr
971 }
972 storeDir := filepath.Join(jsa.storeDir, streamsDir, cfg.Name)
973 jsa.mu.Unlock()
974
975 // Bind to the user account.
976 c.registerWithAccount(a)
977 // Bind to the system account.
978 ic.registerWithAccount(s.SystemAccount())
979
980 // Create the appropriate storage
981 fsCfg := fsConfig
982 if fsCfg == nil {
983 fsCfg = &FileStoreConfig{}
984 // If we are file based and not explicitly configured
985 // we may be able to auto-tune based on max msgs or bytes.
986 if cfg.Storage == FileStorage {
987 mset.autoTuneFileStorageBlockSize(fsCfg)
988 }
989 }
990 fsCfg.StoreDir = storeDir
991 // Grab configured sync interval.
992 fsCfg.SyncInterval = s.getOpts().SyncInterval
993 fsCfg.SyncAlways = s.getOpts().SyncAlways
994 fsCfg.Compression = config.Compression
995 // Async flushing is only allowed if the stream has a sync log backing it.
996 fsCfg.AsyncFlush = !fsCfg.SyncAlways && config.Replicas > 1
997
998 // Async persist mode opts in to async flushing,
999 // sync always would also be disabled if it was configured.
1000 if config.PersistMode == AsyncPersistMode {
1001 fsCfg.SyncAlways = false
1002 fsCfg.AsyncFlush = true
1003 }
1004 if err := mset.setupStore(fsCfg); err != nil {
1005 mset.stop(true, false)
1006 return nil, NewJSStreamStoreFailedError(err)
1007 }
1008
1009 // Create our pubAck template here. Better than json marshal each time on success.
1010 if domain := s.getOpts().JetStreamDomain; domain != _EMPTY_ {
1011 mset.pubAck = fmt.Appendf(nil, "{%q:%q,%q:%q,%q:", "stream", cfg.Name, "domain", domain, "seq")
1012 } else {
1013 mset.pubAck = fmt.Appendf(nil, "{%q:%q,%q:", "stream", cfg.Name, "seq")
1014 }
1015 end := len(mset.pubAck)
1016 mset.pubAck = mset.pubAck[:end:end]
1017
1018 // Set our known last sequence.
1019 var state StreamState
1020 mset.store.FastState(&state)
1021
1022 // Possible race with consumer.setLeader during recovery.
1023 mset.mu.Lock()
1024 mset.lseq = state.LastSeq
1025
1026 // Ensure dedupe state is loaded.
1027 mset.ddMu.Lock()
1028 mset.rebuildDedupe()
1029 mset.ddMu.Unlock()
1030 mset.mu.Unlock()
1031
1032 // Set our stream assignment if in clustered mode.
1033 reserveResources := true
1034 if sa != nil {
1035 mset.setStreamAssignment(sa)
1036
1037 // If the stream is resetting we must not double-account resources, they were already accounted for.
1038 js.mu.Lock()
1039 if sa.resetting {
1040 reserveResources, sa.resetting = false, false
1041 }
1042 js.mu.Unlock()
1043 }
1044
1045 // Setup our internal send go routine.
1046 mset.setupSendCapabilities()
1047
1048 // Reserve resources if MaxBytes present.
1049 if reserveResources {
1050 mset.js.reserveStreamResources(&mset.cfg)
1051 }
1052
1053 // Call directly to set leader if not in clustered mode.
1054 // This can be called though before we actually setup clustering, so check both.
1055 if singleServerMode {
1056 if err := mset.setLeader(true, 0); err != nil {
1057 mset.stop(true, false)
1058 return nil, err
1059 }
1060 }
1061
1062 // This is always true in single server mode.
1063 if mset.IsLeader() {
1064 // Send advisory.
1065 var suppress bool
1066 if !s.standAloneMode() && sa == nil {
1067 if cfg.Replicas > 1 {
1068 suppress = true
1069 }
1070 } else if sa != nil {
1071 suppress = sa.hasResponded()
1072 }
1073 if !suppress {
1074 mset.sendCreateAdvisory()
1075 }
1076 }
1077
1078 // Register with our account last.
1079 jsa.mu.Lock()
1080 jsa.streams[cfg.Name] = mset
1081 jsa.mu.Unlock()
1082
1083 return mset, nil
1084 }
1085
1086 // Composes the index name. Contains the stream name, subject filter, and transform destination
1087 // when the stream is external we will use the api prefix as part of the index name
1088 // (as the same stream name could be used in multiple JS domains)
1089 func (ssi *StreamSource) composeIName() string {
1090 var iName = ssi.Name
1091
1092 if ssi.External != nil {
1093 iName = iName + ":" + getHash(ssi.External.ApiPrefix)
1094 }
1095 if ssi.Consumer != nil {
1096 iName = iName + ":C=" + getHash(ssi.Consumer.Name)
1097 }
1098
1099 source := ssi.FilterSubject
1100 destination := fwcs
1101
1102 if len(ssi.SubjectTransforms) == 0 {
1103 // normalize filter and destination in case they are empty
1104 if source == _EMPTY_ {
1105 source = fwcs
1106 }
1107 if destination == _EMPTY_ {
1108 destination = fwcs
1109 }
1110 } else {
1111 var sources, destinations []string
1112
1113 for _, tr := range ssi.SubjectTransforms {
1114 trsrc, trdest := tr.Source, tr.Destination
1115 if trsrc == _EMPTY_ {
1116 trsrc = fwcs
1117 }
1118 if trdest == _EMPTY_ {
1119 trdest = fwcs
1120 }
1121 sources = append(sources, trsrc)
1122 destinations = append(destinations, trdest)
1123 }
1124 source = strings.Join(sources, "\f")
1125 destination = strings.Join(destinations, "\f")
1126 }
1127
1128 return strings.Join([]string{iName, source, destination}, " ")
1129 }
1130
1131 // Sets the index name.
1132 func (ssi *StreamSource) setIndexName() {
1133 ssi.iname = ssi.composeIName()
1134 }
1135
1136 // Composes the consumer index name. Contains the stream name and consumer name used for durable sourcing (if any).
1137 // When the stream is external we will use the api prefix as part of the index name
1138 // (as the same stream and consumer names could be used in multiple JS domains)
1139 func (ssi *StreamSource) composeCName() string {
1140 var iName = ssi.Name
1141
1142 if ssi.External != nil {
1143 iName = iName + ":" + getHash(ssi.External.ApiPrefix)
1144 }
1145 var c string
1146 if ssi.Consumer != nil {
1147 c = ssi.Consumer.Name
1148 }
1149
1150 return strings.Join([]string{iName, c}, " ")
1151 }
1152
1153 func (mset *stream) streamAssignment() *streamAssignment {
1154 mset.mu.RLock()
1155 defer mset.mu.RUnlock()
1156 return mset.sa
1157 }
1158
1159 func (mset *stream) setStreamAssignment(sa *streamAssignment) {
1160 var node RaftNode
1161 var peers []string
1162
1163 mset.mu.RLock()
1164 js := mset.js
1165 mset.mu.RUnlock()
1166
1167 if js != nil {
1168 js.mu.RLock()
1169 if sa.Group != nil {
1170 node = sa.Group.node
1171 peers = sa.Group.Peers
1172 }
1173 js.mu.RUnlock()
1174 }
1175
1176 mset.mu.Lock()
1177 defer mset.mu.Unlock()
1178
1179 mset.sa = sa
1180 if sa == nil {
1181 return
1182 }
1183
1184 // Set our node.
1185 mset.node = node
1186 if mset.node != nil {
1187 mset.node.UpdateKnownPeers(peers)
1188 }
1189
1190 // Setup our info sub here as well for all stream members. This is now by design.
1191 if mset.infoSub == nil {
1192 isubj := fmt.Sprintf(clusterStreamInfoT, mset.jsa.acc(), mset.cfg.Name)
1193 // Note below the way we subscribe here is so that we can send requests to ourselves.
1194 mset.infoSub, _ = mset.srv.systemSubscribe(isubj, _EMPTY_, false, mset.sysc, mset.handleClusterStreamInfoRequest)
1195 }
1196
1197 // Trigger update chan.
1198 select {
1199 case mset.uch <- struct{}{}:
1200 default:
1201 }
1202 }
1203
1204 // Returned by monitorQuitC once the monitor was signaled to quit, so a monitor
1205 // that only gets there afterwards still exits immediately.
1206 var closedMonitorQuitC = func() chan struct{} {
1207 ch := make(chan struct{})
1208 close(ch)
1209 return ch
1210 }()
1211
1212 func (mset *stream) monitorQuitC() <-chan struct{} {
1213 if mset == nil {
1214 return nil
1215 }
1216 mset.mu.Lock()
1217 defer mset.mu.Unlock()
1218 // Don't recreate, a concurrent stopMonitoring would wait forever for a monitor
1219 // that can't be signaled anymore. startMonitorWg creates it per generation.
1220 if mset.mqch == nil {
1221 return closedMonitorQuitC
1222 }
1223 return mset.mqch
1224 }
1225
1226 // signalMonitorQuit signals to exit the monitor loop. If there's no Raft node,
1227 // this will be the only way to stop the monitor goroutine.
1228 func (mset *stream) signalMonitorQuit() {
1229 mset.mu.Lock()
1230 defer mset.mu.Unlock()
1231 if mset.mqch != nil {
1232 close(mset.mqch)
1233 mset.mqch = nil
1234 }
1235 }
1236
1237 func (mset *stream) updateC() <-chan struct{} {
1238 if mset == nil {
1239 return nil
1240 }
1241 mset.mu.RLock()
1242 defer mset.mu.RUnlock()
1243 return mset.uch
1244 }
1245
1246 // IsLeader will return if we are the current leader.
1247 func (mset *stream) IsLeader() bool {
1248 mset.mu.RLock()
1249 defer mset.mu.RUnlock()
1250 return mset.isLeader()
1251 }
1252
1253 // Lock should be held.
1254 func (mset *stream) isLeader() bool {
1255 if mset.isClustered() {
1256 return mset.node.Leader()
1257 }
1258 return true
1259 }
1260
1261 // isLeaderNodeState should NOT be used normally, use isLeader instead.
1262 // Returns whether the node thinks it is the leader, regardless of whether applies are up-to-date yet
1263 // (unlike isLeader, which requires applies to be caught up).
1264 // May be used to respond to clients after a leader change, when applying entries from a former leader.
1265 // Lock should be held.
1266 func (mset *stream) isLeaderNodeState() bool {
1267 if mset.isClustered() {
1268 return mset.node.State() == Leader
1269 }
1270 return true
1271 }
1272
1273 // TODO(dlc) - Check to see if we can accept being the leader or we should step down.
1274 func (mset *stream) setLeader(isLeader bool, term uint64) error {
1275 mset.mu.Lock()
1276 wasLeader := mset.leader.Swap(isLeader)
1277
1278 // We can skip the teardown if we were leader before and are still the leader now.
1279 // But only at term 1, since that means scale up from or down to an unreplicated config.
1280 // R1 assets have no raft node and use the coerced term 1.
1281 if term < 1 {
1282 term = 1
1283 }
1284 skipTeardown := wasLeader && isLeader && term == 1
1285 mset.term = term
1286 if !skipTeardown {
1287 // cancel timer to create the source consumers if not fired yet
1288 if mset.sourcesConsumerSetup != nil {
1289 mset.sourcesConsumerSetup.Stop()
1290 mset.sourcesConsumerSetup = nil
1291 } else {
1292 // Stop any source consumers
1293 mset.stopSourceConsumers()
1294 }
1295
1296 // Stop responding to sync requests.
1297 mset.stopClusterSubs()
1298 // Unsubscribe from direct stream.
1299 mset.unsubscribeToStream(false, false)
1300 // Clear catchup state
1301 mset.clearAllCatchupPeers()
1302 mset.store.ResetState()
1303 }
1304
1305 // If we are here we have a change in leader status.
1306 if isLeader {
1307 // Make sure we are listening for sync requests.
1308 // TODO(dlc) - Original design was that all in sync members of the group would do DQ.
1309 if mset.isClustered() {
1310 mset.startClusterSubs()
1311 }
1312
1313 // Setup subscriptions if we were not already the leader.
1314 if err := mset.subscribeToStream(); err != nil {
1315 if mset.isClustered() {
1316 // Stepdown since we have an error.
1317 mset.node.StepDown()
1318 }
1319 mset.mu.Unlock()
1320 return err
1321 }
1322
1323 // Reset any inflight fast batches. We were likely a follower before and need
1324 // to send an ack to the publishers so they know we're still there.
1325 if !skipTeardown && mset.batches != nil {
1326 mset.batches.mu.Lock()
1327 for batchId, b := range mset.batches.fast {
1328 mset.batches.fastBatchReset(mset, batchId, b)
1329 }
1330 mset.batches.mu.Unlock()
1331 }
1332 }
1333 mset.mu.Unlock()
1334
1335 // If we are interest based make sure to check consumers.
1336 // This is to make sure we process any outstanding acks.
1337 mset.checkInterestState()
1338
1339 return nil
1340 }
1341
1342 // Lock should be held.
1343 func (mset *stream) startClusterSubs() {
1344 if mset.syncSub == nil {
1345 mset.syncSub, _ = mset.srv.systemSubscribe(mset.sa.Sync, _EMPTY_, false, mset.sysc, mset.handleClusterSyncRequest)
1346 }
1347 }
1348
1349 // Lock should be held.
1350 func (mset *stream) stopClusterSubs() {
1351 if mset.syncSub != nil {
1352 mset.srv.sysUnsubscribe(mset.syncSub)
1353 mset.syncSub = nil
1354 }
1355 }
1356
1357 // account gets the account for this stream.
1358 func (mset *stream) account() *Account {
1359 return mset.accountLocked(true)
1360 }
1361
1362 func (mset *stream) accountLocked(needLock bool) *Account {
1363 if needLock {
1364 mset.mu.RLock()
1365 }
1366 jsa := mset.jsa
1367 if needLock {
1368 mset.mu.RUnlock()
1369 }
1370 if jsa == nil {
1371 return nil
1372 }
1373 return jsa.acc()
1374 }
1375
1376 // Helper to determine the max msg size for this stream if file based.
1377 func (mset *stream) maxMsgSize() uint64 {
1378 maxMsgSize := mset.cfg.MaxMsgSize
1379 if maxMsgSize <= 0 {
1380 // Pull from the account.
1381 if mset.jsa != nil {
1382 if acc := mset.jsa.acc(); acc != nil {
1383 acc.mu.RLock()
1384 maxMsgSize = acc.mpay
1385 acc.mu.RUnlock()
1386 }
1387 }
1388 // If all else fails use default.
1389 if maxMsgSize <= 0 {
1390 maxMsgSize = MAX_PAYLOAD_SIZE
1391 }
1392 }
1393 // Now determine an estimation for the subjects etc.
1394 maxSubject := -1
1395 for _, subj := range mset.cfg.Subjects {
1396 if subjectIsLiteral(subj) {
1397 if len(subj) > maxSubject {
1398 maxSubject = len(subj)
1399 }
1400 }
1401 }
1402 if maxSubject < 0 {
1403 const defaultMaxSubject = 256
1404 maxSubject = defaultMaxSubject
1405 }
1406 // filestore will add in estimates for record headers, etc.
1407 return fileStoreMsgSizeEstimate(maxSubject, int(maxMsgSize))
1408 }
1409
1410 // If we are file based and the file storage config was not explicitly set
1411 // we can autotune block sizes to better match. Our target will be to store 125%
1412 // of the theoretical limit. We will round up to nearest 100 bytes as well.
1413 func (mset *stream) autoTuneFileStorageBlockSize(fsCfg *FileStoreConfig) {
1414 var totalEstSize uint64
1415
1416 // MaxBytes will take precedence for now.
1417 if mset.cfg.MaxBytes > 0 {
1418 totalEstSize = uint64(mset.cfg.MaxBytes)
1419 } else if mset.cfg.MaxMsgs > 0 {
1420 // Determine max message size to estimate.
1421 totalEstSize = mset.maxMsgSize() * uint64(mset.cfg.MaxMsgs)
1422 } else if mset.cfg.MaxMsgsPer > 0 {
1423 fsCfg.BlockSize = uint64(defaultKVBlockSize)
1424 return
1425 } else {
1426 // If nothing set will let underlying filestore determine blkSize.
1427 return
1428 }
1429
1430 blkSize := (totalEstSize / 4) + 1 // (25% overhead)
1431 // Round up to nearest 100
1432 if m := blkSize % 100; m != 0 {
1433 blkSize += 100 - m
1434 }
1435 if blkSize <= FileStoreMinBlkSize {
1436 blkSize = FileStoreMinBlkSize
1437 } else if blkSize >= FileStoreMaxBlkSize {
1438 blkSize = FileStoreMaxBlkSize
1439 } else {
1440 blkSize = defaultMediumBlockSize
1441 }
1442 fsCfg.BlockSize = uint64(blkSize)
1443 }
1444
1445 // rebuildDedupe will rebuild any dedupe structures needed after recovery of a stream.
1446 // Will be called lazily to avoid penalizing startup times.
1447 // TODO(dlc) - Might be good to know if this should be checked at all for streams with no
1448 // headers and msgId in them. Would need signaling from the storage layer.
1449 // mset.mu and mset.ddMu locks should be held.
1450 func (mset *stream) rebuildDedupe() {
1451 duplicates := mset.cfg.Duplicates
1452 if duplicates <= 0 {
1453 return
1454 }
1455
1456 // We have some messages. Lookup starting sequence by duplicate time window.
1457 sseq := mset.store.GetSeqFromTime(time.Now().Add(-duplicates))
1458 if sseq == 0 {
1459 return
1460 }
1461
1462 var smv StoreMsg
1463 var state StreamState
1464 mset.store.FastState(&state)
1465
1466 for seq := sseq; seq <= state.LastSeq; seq++ {
1467 sm, err := mset.store.LoadMsg(seq, &smv)
1468 if err != nil {
1469 continue
1470 }
1471 var msgId string
1472 if len(sm.hdr) > 0 {
1473 if msgId = getMsgId(sm.hdr); msgId != _EMPTY_ {
1474 mset.storeMsgIdLocked(&ddentry{msgId, sm.seq, sm.ts})
1475 }
1476 }
1477 if seq == state.LastSeq {
1478 mset.lmsgId = msgId
1479 }
1480 }
1481 }
1482
1483 // Lock should be held.
1484 func (mset *stream) lastSeqAndCLFS() (uint64, uint64) {
1485 return mset.lseq, mset.getCLFS()
1486 }
1487
1488 func (mset *stream) getCLFS() uint64 {
1489 if mset == nil {
1490 return 0
1491 }
1492 mset.clMu.Lock()
1493 defer mset.clMu.Unlock()
1494 return mset.clfs
1495 }
1496
1497 func (mset *stream) setCLFS(clfs uint64) {
1498 mset.clMu.Lock()
1499 mset.clfs = clfs
1500 mset.clMu.Unlock()
1501 }
1502
1503 func (mset *stream) lastSeq() uint64 {
1504 mset.mu.RLock()
1505 defer mset.mu.RUnlock()
1506 return mset.lseq
1507 }
1508
1509 func (mset *stream) sendCreateAdvisory() {
1510 mset.mu.RLock()
1511 name := mset.cfg.Name
1512 outq := mset.outq
1513 srv := mset.srv
1514 mset.mu.RUnlock()
1515
1516 if outq == nil {
1517 return
1518 }
1519
1520 // finally send an event that this stream was created
1521 m := JSStreamActionAdvisory{
1522 TypedEvent: TypedEvent{
1523 Type: JSStreamActionAdvisoryType,
1524 ID: nuid.Next(),
1525 Time: time.Now().UTC(),
1526 },
1527 Stream: name,
1528 Action: CreateEvent,
1529 Domain: srv.getOpts().JetStreamDomain,
1530 }
1531
1532 j, err := json.Marshal(m)
1533 if err != nil {
1534 return
1535 }
1536
1537 subj := JSAdvisoryStreamCreatedPre + "." + name
1538 outq.sendMsg(subj, j)
1539 }
1540
1541 func (mset *stream) sendDeleteAdvisoryLocked() {
1542 if mset.outq == nil {
1543 return
1544 }
1545
1546 m := JSStreamActionAdvisory{
1547 TypedEvent: TypedEvent{
1548 Type: JSStreamActionAdvisoryType,
1549 ID: nuid.Next(),
1550 Time: time.Now().UTC(),
1551 },
1552 Stream: mset.cfg.Name,
1553 Action: DeleteEvent,
1554 Domain: mset.srv.getOpts().JetStreamDomain,
1555 }
1556
1557 j, err := json.Marshal(m)
1558 if err == nil {
1559 subj := JSAdvisoryStreamDeletedPre + "." + mset.cfg.Name
1560 mset.outq.sendMsg(subj, j)
1561 }
1562 }
1563
1564 func (mset *stream) sendUpdateAdvisoryLocked() {
1565 if mset.outq == nil {
1566 return
1567 }
1568
1569 m := JSStreamActionAdvisory{
1570 TypedEvent: TypedEvent{
1571 Type: JSStreamActionAdvisoryType,
1572 ID: nuid.Next(),
1573 Time: time.Now().UTC(),
1574 },
1575 Stream: mset.cfg.Name,
1576 Action: ModifyEvent,
1577 Domain: mset.srv.getOpts().JetStreamDomain,
1578 }
1579
1580 j, err := json.Marshal(m)
1581 if err == nil {
1582 subj := JSAdvisoryStreamUpdatedPre + "." + mset.cfg.Name
1583 mset.outq.sendMsg(subj, j)
1584 }
1585 }
1586
1587 func (mset *stream) sendStreamBatchAbandonedAdvisory(batchId string, reason BatchAbandonReason) {
1588 if mset == nil {
1589 return
1590 }
1591 s := mset.srv
1592 stream, acc := mset.name(), mset.account()
1593 subj := JSAdvisoryStreamBatchAbandonedPre + "." + stream
1594 adv := &JSStreamBatchAbandonedAdvisory{
1595 TypedEvent: TypedEvent{
1596 Type: JSStreamBatchAbandonedAdvisoryType,
1597 ID: nuid.Next(),
1598 Time: time.Now().UTC(),
1599 },
1600 Stream: stream,
1601 Domain: s.getOpts().JetStreamDomain,
1602 BatchId: batchId,
1603 Reason: reason,
1604 }
1605
1606 // Send to the user's account if not the system account.
1607 if acc != s.SystemAccount() {
1608 s.publishAdvisory(acc, subj, adv)
1609 }
1610 // Now do system level one. Place account info in adv, and nil account means system.
1611 adv.Account = acc.GetName()
1612 s.publishAdvisory(nil, subj, adv)
1613 }
1614
1615 // Created returns created time.
1616 func (mset *stream) createdTime() time.Time {
1617 mset.mu.RLock()
1618 created := mset.created
1619 mset.mu.RUnlock()
1620 return created
1621 }
1622
1623 // Internal to allow creation time to be restored.
1624 func (mset *stream) setCreatedTime(created time.Time) {
1625 mset.mu.Lock()
1626 mset.created = created
1627 store := mset.store
1628 if fs, ok := store.(*fileStore); ok {
1629 fs.setCreatedTime(created)
1630 }
1631 mset.mu.Unlock()
1632 }
1633
1634 // subjectsOverlap to see if these subjects overlap with existing subjects.
1635 // Use only for non-clustered JetStream
1636 // RLock minimum should be held.
1637 func (jsa *jsAccount) subjectsOverlap(subjects []string, self *stream) bool {
1638 for _, mset := range jsa.streams {
1639 if self != nil && mset == self {
1640 continue
1641 }
1642 // Read the other stream's subjects under its cfgMu.
1643 mset.cfgMu.RLock()
1644 msubjects := mset.cfg.Subjects
1645 mset.cfgMu.RUnlock()
1646 for _, subj := range msubjects {
1647 for _, tsubj := range subjects {
1648 if SubjectsCollide(tsubj, subj) {
1649 return true
1650 }
1651 }
1652 }
1653 }
1654 return false
1655 }
1656
1657 // StreamDefaultDuplicatesWindow default duplicates window.
1658 const StreamDefaultDuplicatesWindow = 2 * time.Minute
1659
1660 func (s *Server) checkStreamCfg(config *StreamConfig, acc *Account, pedantic bool) (StreamConfig, *ApiError) {
1661 lim := &s.getOpts().JetStreamLimits
1662
1663 if config == nil {
1664 return StreamConfig{}, NewJSStreamInvalidConfigError(fmt.Errorf("stream configuration invalid"))
1665 }
1666 if !isValidAssetName(config.Name) {
1667 return StreamConfig{}, NewJSStreamInvalidConfigError(fmt.Errorf("stream name is required and can not contain '.', '*', '>', '\\', '/'"))
1668 }
1669 if len(config.Name) > JSMaxNameLen {
1670 return StreamConfig{}, NewJSStreamInvalidConfigError(fmt.Errorf("stream name is too long, maximum allowed is %d", JSMaxNameLen))
1671 }
1672 if len(config.Description) > JSMaxDescriptionLen {
1673 return StreamConfig{}, NewJSStreamInvalidConfigError(fmt.Errorf("stream description is too long, maximum allowed is %d", JSMaxDescriptionLen))
1674 }
1675
1676 var metadataLen int
1677 for k, v := range config.Metadata {
1678 metadataLen += len(k) + len(v)
1679 }
1680 if metadataLen > JSMaxMetadataLen {
1681 return StreamConfig{}, NewJSStreamInvalidConfigError(fmt.Errorf("stream metadata exceeds maximum size of %d bytes", JSMaxMetadataLen))
1682 }
1683
1684 cfg := *config
1685
1686 if _, err := cfg.Retention.MarshalJSON(); err != nil {
1687 return cfg, NewJSStreamInvalidConfigError(fmt.Errorf("invalid retention"))
1688 }
1689 if _, err := cfg.Discard.MarshalJSON(); err != nil {
1690 return cfg, NewJSStreamInvalidConfigError(fmt.Errorf("invalid discard policy"))
1691 }
1692 if _, err := cfg.Compression.MarshalJSON(); err != nil {
1693 return cfg, NewJSStreamInvalidConfigError(fmt.Errorf("invalid compression"))
1694 }
1695
1696 // Make file the default.
1697 if cfg.Storage == 0 {
1698 cfg.Storage = FileStorage
1699 }
1700 if _, err := cfg.Storage.MarshalJSON(); err != nil {
1701 return cfg, NewJSStreamInvalidConfigError(fmt.Errorf("invalid storage type"))
1702 }
1703
1704 if cfg.Replicas == 0 {
1705 cfg.Replicas = 1
1706 }
1707 if cfg.Replicas > StreamMaxReplicas {
1708 return cfg, NewJSStreamInvalidConfigError(fmt.Errorf("maximum replicas is %d", StreamMaxReplicas))
1709 }
1710 if cfg.Replicas < 0 {
1711 return cfg, NewJSReplicasCountCannotBeNegativeError()
1712 }
1713 if cfg.MaxMsgs == 0 || cfg.MaxMsgs < -1 {
1714 if pedantic && cfg.MaxMsgs < -1 {
1715 return StreamConfig{}, NewJSPedanticError(fmt.Errorf("max_msgs must be set to -1"))
1716 }
1717 cfg.MaxMsgs = -1
1718 }
1719 if cfg.MaxMsgsPer == 0 || cfg.MaxMsgsPer < -1 {
1720 if pedantic && cfg.MaxMsgsPer < -1 {
1721 return StreamConfig{}, NewJSPedanticError(fmt.Errorf("max_msgs_per_subject must be set to -1"))
1722 }
1723 cfg.MaxMsgsPer = -1
1724 }
1725 if cfg.MaxBytes == 0 || cfg.MaxBytes < -1 {
1726 if pedantic && cfg.MaxBytes < -1 {
1727 return StreamConfig{}, NewJSPedanticError(fmt.Errorf("max_bytes must be set to -1"))
1728 }
1729 cfg.MaxBytes = -1
1730 }
1731 if cfg.MaxMsgSize == 0 || cfg.MaxMsgSize < -1 {
1732 if pedantic && cfg.MaxMsgSize < -1 {
1733 return StreamConfig{}, NewJSPedanticError(fmt.Errorf("max_msg_size must be set to -1"))
1734 }
1735 cfg.MaxMsgSize = -1
1736 }
1737 if cfg.MaxConsumers == 0 || cfg.MaxConsumers < -1 {
1738 if pedantic && cfg.MaxConsumers < -1 {
1739 return StreamConfig{}, NewJSPedanticError(fmt.Errorf("max_consumers must be set to -1"))
1740 }
1741 cfg.MaxConsumers = -1
1742 }
1743 if cfg.MaxAge < 0 {
1744 return StreamConfig{}, NewJSStreamInvalidConfigError(fmt.Errorf("max age can not be negative"))
1745 }
1746 if cfg.MaxAge != 0 && cfg.MaxAge < 100*time.Millisecond {
1747 return StreamConfig{}, NewJSStreamInvalidConfigError(fmt.Errorf("max age needs to be >= 100ms"))
1748 }
1749
1750 if cfg.Duplicates == 0 && cfg.Mirror == nil && len(cfg.Sources) == 0 {
1751 maxWindow := StreamDefaultDuplicatesWindow
1752 if lim.Duplicates > 0 && maxWindow > lim.Duplicates {
1753 if pedantic {
1754 return StreamConfig{}, NewJSPedanticError(fmt.Errorf("duplicate window limits are higher than current limits"))
1755 }
1756 maxWindow = lim.Duplicates
1757 }
1758 if cfg.MaxAge != 0 && cfg.MaxAge < maxWindow {
1759 if pedantic {
1760 return StreamConfig{}, NewJSPedanticError(fmt.Errorf("duplicate window cannot be bigger than max age"))
1761 }
1762 cfg.Duplicates = cfg.MaxAge
1763 } else {
1764 cfg.Duplicates = maxWindow
1765 }
1766 }
1767 if cfg.Duplicates < 0 {
1768 return StreamConfig{}, NewJSStreamInvalidConfigError(fmt.Errorf("duplicates window can not be negative"))
1769 }
1770 // Check that duplicates is not larger then age if set.
1771 if cfg.MaxAge != 0 && cfg.Duplicates > cfg.MaxAge {
1772 return StreamConfig{}, NewJSStreamInvalidConfigError(fmt.Errorf("duplicates window can not be larger then max age"))
1773 }
1774 if lim.Duplicates > 0 && cfg.Duplicates > lim.Duplicates {
1775 return StreamConfig{}, NewJSStreamInvalidConfigError(fmt.Errorf("duplicates window can not be larger then server limit of %v",
1776 lim.Duplicates.String()))
1777 }
1778 if cfg.Duplicates > 0 && cfg.Duplicates < 100*time.Millisecond {
1779 return StreamConfig{}, NewJSStreamInvalidConfigError(fmt.Errorf("duplicates window needs to be >= 100ms"))
1780 }
1781
1782 if cfg.DenyPurge && cfg.AllowRollup {
1783 return StreamConfig{}, NewJSStreamInvalidConfigError(fmt.Errorf("roll-ups require the purge permission"))
1784 }
1785
1786 // Counter is not compatible with some settings.
1787 if cfg.AllowMsgCounter {
1788 if cfg.Discard == DiscardNew {
1789 return StreamConfig{}, NewJSStreamInvalidConfigError(fmt.Errorf("counter stream cannot use discard new"))
1790 }
1791 if cfg.AllowMsgTTL {
1792 return StreamConfig{}, NewJSStreamInvalidConfigError(fmt.Errorf("counter stream cannot use message TTLs"))
1793 }
1794 if cfg.AllowMsgSchedules {
1795 return StreamConfig{}, NewJSStreamInvalidConfigError(fmt.Errorf("counter stream cannot use message schedules"))
1796 }
1797 if cfg.Retention != LimitsPolicy {
1798 return StreamConfig{}, NewJSStreamInvalidConfigError(fmt.Errorf("counter stream can only use limits retention"))
1799 }
1800 }
1801
1802 // Check for new discard new per subject, we require the discard policy to also be new.
1803 if cfg.DiscardNewPer {
1804 if cfg.Discard != DiscardNew {
1805 return StreamConfig{}, NewJSStreamInvalidConfigError(fmt.Errorf("discard new per subject requires discard new policy to be set"))
1806 }
1807 if cfg.MaxMsgsPer <= 0 {
1808 return StreamConfig{}, NewJSStreamInvalidConfigError(fmt.Errorf("discard new per subject requires max msgs per subject > 0"))
1809 }
1810 }
1811
1812 if cfg.SubjectDeleteMarkerTTL > 0 {
1813 if cfg.SubjectDeleteMarkerTTL < time.Second {
1814 return StreamConfig{}, NewJSStreamInvalidConfigError(fmt.Errorf("subject delete marker TTL must be at least 1 second"))
1815 }
1816 if !cfg.AllowMsgTTL {
1817 if pedantic {
1818 return StreamConfig{}, NewJSStreamInvalidConfigError(fmt.Errorf("subject delete marker cannot be set if message TTLs are disabled"))
1819 }
1820 cfg.AllowMsgTTL = true
1821 }
1822 if !cfg.AllowRollup {
1823 if pedantic {
1824 return StreamConfig{}, NewJSStreamInvalidConfigError(fmt.Errorf("subject delete marker cannot be set if roll-ups are disabled"))
1825 }
1826 cfg.AllowRollup, cfg.DenyPurge = true, false
1827 }
1828 } else if cfg.SubjectDeleteMarkerTTL < 0 {
1829 return StreamConfig{}, NewJSStreamInvalidConfigError(fmt.Errorf("subject delete marker TTL must not be negative"))
1830 }
1831
1832 if cfg.AllowMsgSchedules {
1833 if cfg.Discard == DiscardNew {
1834 return StreamConfig{}, NewJSStreamInvalidConfigError(fmt.Errorf("message scheduling cannot use discard new"))
1835 }
1836 if !cfg.AllowRollup {
1837 if pedantic {
1838 return StreamConfig{}, NewJSStreamInvalidConfigError(fmt.Errorf("message scheduling cannot be set if roll-ups are disabled"))
1839 }
1840 cfg.AllowRollup, cfg.DenyPurge = true, false
1841 }
1842 }
1843
1844 if cfg.PersistMode == AsyncPersistMode {
1845 if cfg.Storage != FileStorage {
1846 return StreamConfig{}, NewJSStreamInvalidConfigError(fmt.Errorf("async persist mode is only supported on file storage"))
1847 }
1848 if cfg.Replicas > 1 {
1849 return StreamConfig{}, NewJSStreamInvalidConfigError(fmt.Errorf("async persist mode is not supported on replicated streams"))
1850 }
1851 if cfg.AllowAtomicPublish {
1852 return StreamConfig{}, NewJSStreamInvalidConfigError(fmt.Errorf("async persist mode is not supported with atomic batch publish"))
1853 }
1854 }
1855
1856 getStream := func(streamName string) (bool, StreamConfig) {
1857 var exists bool
1858 var cfg StreamConfig
1859 if s.JetStreamIsClustered() {
1860 if js, _ := s.getJetStreamCluster(); js != nil {
1861 js.mu.RLock()
1862 if sa := js.streamAssignment(acc.Name, streamName); sa != nil {
1863 cfg = *sa.Config.clone()
1864 exists = true
1865 }
1866 js.mu.RUnlock()
1867 }
1868 } else if mset, err := acc.lookupStream(streamName); err == nil {
1869 cfg = mset.cfg
1870 exists = true
1871 }
1872 return exists, cfg
1873 }
1874
1875 hasStream := func(streamName string) (bool, int32, []string) {
1876 exists, cfg := getStream(streamName)
1877 return exists, cfg.MaxMsgSize, cfg.Subjects
1878 }
1879
1880 var streamSubs []string
1881 var deliveryPrefixes []string
1882 var apiPrefixes []string
1883
1884 // Do some pre-checking for mirror config to avoid cycles in clustered mode.
1885 if cfg.Mirror != nil {
1886 if cfg.FirstSeq > 0 {
1887 return StreamConfig{}, NewJSMirrorWithFirstSeqError()
1888 }
1889 if len(cfg.Subjects) > 0 {
1890 return StreamConfig{}, NewJSMirrorWithSubjectsError()
1891 }
1892 if len(cfg.Sources) > 0 {
1893 return StreamConfig{}, NewJSMirrorWithSourcesError()
1894 }
1895 if cfg.AllowMsgCounter {
1896 return StreamConfig{}, NewJSMirrorWithCountersError()
1897 }
1898 if cfg.AllowAtomicPublish {
1899 return StreamConfig{}, NewJSMirrorWithAtomicPublishError()
1900 }
1901 if cfg.AllowBatchPublish {
1902 return StreamConfig{}, NewJSMirrorWithBatchPublishError()
1903 }
1904 if cfg.AllowMsgSchedules {
1905 return StreamConfig{}, NewJSMirrorWithMsgSchedulesError()
1906 }
1907 if c := cfg.Mirror.Consumer; c != nil {
1908 if !isValidAssetName(c.Name) {
1909 return StreamConfig{}, NewJSMirrorDurableConsumerCfgInvalidError()
1910 }
1911 if !subjectIsLiteral(c.DeliverSubject) || !IsValidSubject(c.DeliverSubject) {
1912 return StreamConfig{}, NewJSMirrorDurableConsumerCfgInvalidError()
1913 }
1914 if cfg.Mirror.OptStartSeq != 0 || cfg.Mirror.OptStartTime != nil {
1915 return StreamConfig{}, NewJSMirrorDurableConsumerCfgInvalidError()
1916 }
1917 if cfg.Mirror.FilterSubject != _EMPTY_ {
1918 return StreamConfig{}, NewJSMirrorDurableConsumerCfgInvalidError()
1919 }
1920 }
1921 if cfg.Mirror.FilterSubject != _EMPTY_ && len(cfg.Mirror.SubjectTransforms) != 0 {
1922 return StreamConfig{}, NewJSMirrorMultipleFiltersNotAllowedError()
1923 }
1924 if cfg.SubjectDeleteMarkerTTL > 0 {
1925 // Delete markers cannot be configured on a mirror as it would result in new
1926 // tombstones which would use up sequence numbers, diverging from the origin
1927 // stream.
1928 return StreamConfig{}, NewJSStreamInvalidConfigError(fmt.Errorf("subject delete markers forbidden on mirrors"))
1929 }
1930 // Check subject filters overlap.
1931 for outer, tr := range cfg.Mirror.SubjectTransforms {
1932 if tr.Source != _EMPTY_ && !IsValidSubject(tr.Source) {
1933 return StreamConfig{}, NewJSMirrorInvalidSubjectFilterError(fmt.Errorf("%w %s", ErrBadSubject, tr.Source))
1934 }
1935
1936 err := ValidateMapping(tr.Source, tr.Destination)
1937 if err != nil {
1938 return StreamConfig{}, NewJSMirrorInvalidTransformDestinationError(err)
1939 }
1940
1941 for inner, innertr := range cfg.Mirror.SubjectTransforms {
1942 if inner != outer && SubjectsCollide(tr.Source, innertr.Source) {
1943 return StreamConfig{}, NewJSMirrorOverlappingSubjectFiltersError()
1944 }
1945 }
1946 }
1947 // Do not perform checks if External is provided, as it could lead to
1948 // checking against itself (if sourced stream name is the same on different JetStream)
1949 if cfg.Mirror.External == nil {
1950 if !isValidAssetName(cfg.Mirror.Name) {
1951 return StreamConfig{}, NewJSMirrorInvalidStreamNameError()
1952 }
1953 // We do not require other stream to exist anymore, but if we can see it check payloads.
1954 exists, maxMsgSize, subs := hasStream(cfg.Mirror.Name)
1955 if len(subs) > 0 {
1956 streamSubs = append(streamSubs, subs...)
1957 }
1958 if exists {
1959 if cfg.MaxMsgSize > 0 && maxMsgSize > 0 && cfg.MaxMsgSize < maxMsgSize {
1960 return StreamConfig{}, NewJSMirrorMaxMessageSizeTooBigError()
1961 }
1962 }
1963 // Determine if we are inheriting direct gets.
1964 if exists, ocfg := getStream(cfg.Mirror.Name); exists {
1965 if pedantic && cfg.MirrorDirect != ocfg.AllowDirect {
1966 return StreamConfig{}, NewJSPedanticError(fmt.Errorf("origin stream has direct get set, mirror has it disabled"))
1967 }
1968 cfg.MirrorDirect = ocfg.AllowDirect
1969 } else if js := s.getJetStream(); js != nil && js.isClustered() {
1970 // Could not find it here. If we are clustered we can look it up.
1971 js.mu.RLock()
1972 if cc := js.cluster; cc != nil {
1973 if as := cc.streams[acc.Name]; as != nil {
1974 if sa := as[cfg.Mirror.Name]; sa != nil {
1975 if pedantic && cfg.MirrorDirect != sa.Config.AllowDirect {
1976 js.mu.RUnlock()
1977 return StreamConfig{}, NewJSPedanticError(fmt.Errorf("origin stream has direct get set, mirror has it disabled"))
1978 }
1979 cfg.MirrorDirect = sa.Config.AllowDirect
1980 }
1981 }
1982 }
1983 js.mu.RUnlock()
1984 }
1985 } else {
1986 if cfg.Mirror.External.DeliverPrefix != _EMPTY_ {
1987 deliveryPrefixes = append(deliveryPrefixes, cfg.Mirror.External.DeliverPrefix)
1988 }
1989
1990 if cfg.Mirror.External.ApiPrefix != _EMPTY_ {
1991 apiPrefixes = append(apiPrefixes, cfg.Mirror.External.ApiPrefix)
1992 }
1993 }
1994 }
1995
1996 if len(cfg.Sources) > 0 {
1997 if cfg.AllowMsgSchedules {
1998 return StreamConfig{}, NewJSSourceWithMsgSchedulesError()
1999 }
2000 }
2001
2002 // check sources for duplicates
2003 var iNames = make(map[string]struct{})
2004 var cNames = make(map[string]struct{})
2005 for _, src := range cfg.Sources {
2006 if src == nil || !isValidAssetName(src.Name) {
2007 return StreamConfig{}, NewJSSourceInvalidStreamNameError()
2008 }
2009 if _, ok := iNames[src.composeIName()]; !ok {
2010 iNames[src.composeIName()] = struct{}{}
2011 } else {
2012 return StreamConfig{}, NewJSSourceDuplicateDetectedError()
2013 }
2014
2015 if src.FilterSubject != _EMPTY_ && len(src.SubjectTransforms) != 0 {
2016 return StreamConfig{}, NewJSSourceMultipleFiltersNotAllowedError()
2017 }
2018
2019 for _, tr := range src.SubjectTransforms {
2020 if tr.Source != _EMPTY_ && !IsValidSubject(tr.Source) {
2021 return StreamConfig{}, NewJSSourceInvalidSubjectFilterError(fmt.Errorf("%w %s", ErrBadSubject, tr.Source))
2022 }
2023 err := ValidateMapping(tr.Source, tr.Destination)
2024 if err != nil {
2025 return StreamConfig{}, NewJSSourceInvalidTransformDestinationError(err)
2026 }
2027 }
2028
2029 // Check subject filters overlap.
2030 for outer, tr := range src.SubjectTransforms {
2031 for inner, innertr := range src.SubjectTransforms {
2032 if inner != outer && subjectIsSubsetMatch(tr.Source, innertr.Source) {
2033 return StreamConfig{}, NewJSSourceOverlappingSubjectFiltersError()
2034 }
2035 }
2036 }
2037
2038 if c := src.Consumer; c != nil {
2039 if !isValidAssetName(c.Name) {
2040 return StreamConfig{}, NewJSSourceDurableConsumerCfgInvalidError()
2041 }
2042 if !subjectIsLiteral(c.DeliverSubject) || !IsValidSubject(c.DeliverSubject) {
2043 return StreamConfig{}, NewJSSourceDurableConsumerCfgInvalidError()
2044 }
2045 if src.OptStartSeq != 0 || src.OptStartTime != nil {
2046 return StreamConfig{}, NewJSSourceDurableConsumerCfgInvalidError()
2047 }
2048 if src.FilterSubject != _EMPTY_ {
2049 return StreamConfig{}, NewJSSourceDurableConsumerCfgInvalidError()
2050 }
2051 // Reusing the same consumer for multiple sources of the same stream isn't allowed.
2052 if _, ok := cNames[src.composeCName()]; !ok {
2053 cNames[src.composeCName()] = struct{}{}
2054 } else {
2055 return StreamConfig{}, NewJSSourceDurableConsumerDuplicateDetectedError()
2056 }
2057 }
2058
2059 // Do not perform checks if External is provided, as it could lead to
2060 // checking against itself (if sourced stream name is the same on different JetStream)
2061 if src.External == nil {
2062 exists, maxMsgSize, subs := hasStream(src.Name)
2063 if len(subs) > 0 {
2064 streamSubs = append(streamSubs, subs...)
2065 }
2066 if exists {
2067 if cfg.MaxMsgSize > 0 && maxMsgSize > 0 && cfg.MaxMsgSize < maxMsgSize {
2068 return StreamConfig{}, NewJSSourceMaxMessageSizeTooBigError()
2069 }
2070 }
2071 continue
2072 } else {
2073 if src.External.DeliverPrefix != _EMPTY_ {
2074 deliveryPrefixes = append(deliveryPrefixes, src.External.DeliverPrefix)
2075 }
2076 if src.External.ApiPrefix != _EMPTY_ {
2077 apiPrefixes = append(apiPrefixes, src.External.ApiPrefix)
2078 }
2079 }
2080 }
2081
2082 // check prefix overlap with subjects
2083 for _, pfx := range deliveryPrefixes {
2084 if !IsValidPublishSubject(pfx) {
2085 return StreamConfig{}, NewJSStreamInvalidExternalDeliverySubjError(pfx)
2086 }
2087 for _, sub := range streamSubs {
2088 if SubjectsCollide(sub, fmt.Sprintf("%s.%s", pfx, sub)) {
2089 return StreamConfig{}, NewJSStreamExternalDelPrefixOverlapsError(pfx, sub)
2090 }
2091 }
2092 }
2093 // check if api prefixes overlap
2094 for _, apiPfx := range apiPrefixes {
2095 if !IsValidPublishSubject(apiPfx) {
2096 return StreamConfig{}, NewJSStreamInvalidConfigError(
2097 fmt.Errorf("stream external api prefix %q must be a valid subject without wildcards", apiPfx))
2098 }
2099 if SubjectsCollide(apiPfx, JSApiPrefix) {
2100 return StreamConfig{}, NewJSStreamExternalApiOverlapError(apiPfx, JSApiPrefix)
2101 }
2102 }
2103
2104 // cycle check for source cycle
2105 toVisit := []*StreamConfig{&cfg}
2106 visited := make(map[string]struct{})
2107 overlaps := func(subjects []string, filter string) bool {
2108 if filter == _EMPTY_ {
2109 return true
2110 }
2111 for _, subject := range subjects {
2112 if SubjectsCollide(subject, filter) {
2113 return true
2114 }
2115 }
2116 return false
2117 }
2118
2119 for len(toVisit) > 0 {
2120 cfg := toVisit[0]
2121 toVisit = toVisit[1:]
2122 visited[cfg.Name] = struct{}{}
2123 for _, src := range cfg.Sources {
2124 if src.External != nil {
2125 continue
2126 }
2127 // We can detect a cycle between streams, but let's double check that the
2128 // subjects actually form a cycle.
2129 if _, ok := visited[src.Name]; ok {
2130 if overlaps(cfg.Subjects, src.FilterSubject) {
2131 return StreamConfig{}, NewJSStreamInvalidConfigError(errors.New("detected cycle"))
2132 }
2133 } else if exists, cfg := getStream(src.Name); exists {
2134 toVisit = append(toVisit, &cfg)
2135 }
2136 }
2137 // Avoid cycles hiding behind mirrors
2138 if m := cfg.Mirror; m != nil {
2139 if m.External == nil {
2140 if _, ok := visited[m.Name]; ok {
2141 return StreamConfig{}, NewJSStreamInvalidConfigError(errors.New("detected cycle"))
2142 }
2143 if exists, cfg := getStream(m.Name); exists {
2144 toVisit = append(toVisit, &cfg)
2145 }
2146 }
2147 }
2148 }
2149
2150 if len(cfg.Subjects) == 0 {
2151 if cfg.Mirror == nil && len(cfg.Sources) == 0 {
2152 cfg.Subjects = append(cfg.Subjects, cfg.Name)
2153 }
2154 } else {
2155 if cfg.Mirror != nil {
2156 return StreamConfig{}, NewJSMirrorWithSubjectsError()
2157 }
2158
2159 // Check for literal duplication of subject interest in config
2160 // and no overlap with any JS or SYS API subject space.
2161 dset := make(map[string]struct{}, len(cfg.Subjects))
2162 for i, subj := range cfg.Subjects {
2163 // Make sure the subject is valid. Check this first.
2164 if !IsValidSubject(subj) {
2165 return StreamConfig{}, NewJSStreamInvalidConfigError(fmt.Errorf("invalid subject"))
2166 }
2167 if _, ok := dset[subj]; ok {
2168 return StreamConfig{}, NewJSStreamInvalidConfigError(fmt.Errorf("duplicate subjects detected"))
2169 }
2170 // Check for trying to capture everything.
2171 if subj == fwcs {
2172 if !cfg.NoAck {
2173 return StreamConfig{}, NewJSStreamInvalidConfigError(fmt.Errorf("capturing all subjects requires no-ack to be true"))
2174 }
2175 // Capturing everything also will require R1.
2176 if cfg.Replicas != 1 {
2177 return StreamConfig{}, NewJSStreamInvalidConfigError(fmt.Errorf("capturing all subjects requires replicas of 1"))
2178 }
2179 }
2180 // Also check to make sure we do not overlap with our $JS API subjects.
2181 if !cfg.NoAck {
2182 for _, namespace := range []string{"$JS.>", "$JSC.>", "$NRG.>"} {
2183 if SubjectsCollide(subj, namespace) {
2184 // We allow an exception for $JS.EVENT.> since these could have been created in the past.
2185 if !subjectIsSubsetMatch(subj, "$JS.EVENT.>") {
2186 return StreamConfig{}, NewJSStreamInvalidConfigError(fmt.Errorf("subjects that overlap with jetstream api require no-ack to be true"))
2187 }
2188 }
2189 }
2190 if SubjectsCollide(subj, "$SYS.>") {
2191 if !subjectIsSubsetMatch(subj, "$SYS.ACCOUNT.>") {
2192 return StreamConfig{}, NewJSStreamInvalidConfigError(fmt.Errorf("subjects that overlap with system api require no-ack to be true"))
2193 }
2194 }
2195 }
2196 // Now check if we have multiple subjects that we do not overlap ourselves
2197 // which would cause duplicate entries (assuming no MsgID).
2198 for _, tsubj := range cfg.Subjects[i+1:] {
2199 if SubjectsCollide(tsubj, subj) {
2200 return StreamConfig{}, NewJSStreamInvalidConfigError(fmt.Errorf("subject %q overlaps with %q", subj, tsubj))
2201 }
2202 }
2203 // Mark for duplicate check.
2204 dset[subj] = struct{}{}
2205 }
2206 }
2207
2208 if len(cfg.Subjects) == 0 && len(cfg.Sources) == 0 && cfg.Mirror == nil {
2209 return StreamConfig{}, NewJSStreamInvalidConfigError(
2210 fmt.Errorf("stream needs at least one configured subject or be a source/mirror"))
2211 }
2212
2213 // Check for MaxBytes required and it's limit
2214 if required, limit := acc.maxBytesLimits(&cfg); required && cfg.MaxBytes <= 0 {
2215 return StreamConfig{}, NewJSStreamMaxBytesRequiredError()
2216 } else if limit > 0 && cfg.MaxBytes > limit {
2217 return StreamConfig{}, NewJSStreamMaxStreamBytesExceededError()
2218 }
2219
2220 // Check the subject transform if any
2221 if cfg.SubjectTransform != nil {
2222 if cfg.SubjectTransform.Source != _EMPTY_ && !IsValidSubject(cfg.SubjectTransform.Source) {
2223 return StreamConfig{}, NewJSStreamTransformInvalidSourceError(fmt.Errorf("%w %s", ErrBadSubject, cfg.SubjectTransform.Source))
2224 }
2225
2226 err := ValidateMapping(cfg.SubjectTransform.Source, cfg.SubjectTransform.Destination)
2227 if err != nil {
2228 return StreamConfig{}, NewJSStreamTransformInvalidDestinationError(err)
2229 }
2230 }
2231
2232 // If we have a republish directive check if we can create a transform here.
2233 if cfg.RePublish != nil {
2234 // Check to make sure source is a valid subset of the subjects we have.
2235 // Also make sure it does not form a cycle.
2236 // Empty same as all.
2237 if cfg.RePublish.Source == _EMPTY_ {
2238 if pedantic {
2239 return StreamConfig{}, NewJSPedanticError(fmt.Errorf("republish source can not be empty"))
2240 }
2241 cfg.RePublish.Source = fwcs
2242 }
2243 // A RePublish from '>' to '>' could be used, normally this would form a cycle with the stream subjects.
2244 // But if this aligns to a different subject based on the transform, we allow it still.
2245 // The RePublish will be implicit based on the transform, but only if the transform's source
2246 // is the only stream subject.
2247 if cfg.RePublish.Destination == fwcs && cfg.RePublish.Source == fwcs && cfg.SubjectTransform != nil &&
2248 len(cfg.Subjects) == 1 && cfg.SubjectTransform.Source == cfg.Subjects[0] {
2249 if pedantic {
2250 return StreamConfig{}, NewJSPedanticError(fmt.Errorf("implicit republish based on subject transform"))
2251 }
2252 // RePublish all messages with the transformed subject.
2253 cfg.RePublish.Source, cfg.RePublish.Destination = cfg.SubjectTransform.Destination, cfg.SubjectTransform.Destination
2254 }
2255 var formsCycle bool
2256 for _, subj := range cfg.Subjects {
2257 if SubjectsCollide(cfg.RePublish.Destination, subj) {
2258 formsCycle = true
2259 break
2260 }
2261 }
2262 if formsCycle {
2263 return StreamConfig{}, NewJSStreamInvalidConfigError(fmt.Errorf("stream configuration for republish destination forms a cycle"))
2264 }
2265 if _, err := NewSubjectTransform(cfg.RePublish.Source, cfg.RePublish.Destination); err != nil {
2266 return StreamConfig{}, NewJSStreamInvalidConfigError(fmt.Errorf("stream configuration for republish with transform from '%s' to '%s' not valid", cfg.RePublish.Source, cfg.RePublish.Destination))
2267 }
2268 }
2269
2270 // Remove placement if it's an empty object.
2271 if cfg.Placement != nil && reflect.DeepEqual(cfg.Placement, &Placement{}) {
2272 cfg.Placement = nil
2273 }
2274 // For now don't allow preferred server in placement.
2275 if cfg.Placement != nil && cfg.Placement.Preferred != _EMPTY_ {
2276 return StreamConfig{}, NewJSStreamInvalidConfigError(fmt.Errorf("preferred server not permitted in placement"))
2277 }
2278
2279 return cfg, nil
2280 }
2281
2282 // Config returns the stream's configuration.
2283 func (mset *stream) config() StreamConfig {
2284 mset.cfgMu.RLock()
2285 defer mset.cfgMu.RUnlock()
2286 return mset.cfg
2287 }
2288
2289 func (mset *stream) fileStoreConfig() (FileStoreConfig, error) {
2290 mset.mu.Lock()
2291 defer mset.mu.Unlock()
2292 fs, ok := mset.store.(*fileStore)
2293 if !ok {
2294 return FileStoreConfig{}, ErrStoreWrongType
2295 }
2296 return fs.fileStoreConfig(), nil
2297 }
2298
2299 // Do not hold jsAccount or jetStream lock
2300 func (jsa *jsAccount) configUpdateCheck(old, new *StreamConfig, s *Server, pedantic bool) (*StreamConfig, error) {
2301 cfg, apiErr := s.checkStreamCfg(new, jsa.acc(), pedantic)
2302 if apiErr != nil {
2303 return nil, apiErr
2304 }
2305
2306 // Name must match.
2307 if cfg.Name != old.Name {
2308 return nil, NewJSStreamInvalidConfigError(fmt.Errorf("stream configuration name must match original"))
2309 }
2310 singleServerMode := !s.JetStreamIsClustered() && s.standAloneMode()
2311 if singleServerMode && cfg.Replicas > 1 {
2312 return nil, ApiErrors[JSStreamReplicasNotSupportedErr]
2313 }
2314 // Can't change storage types.
2315 if cfg.Storage != old.Storage {
2316 return nil, NewJSStreamInvalidConfigError(fmt.Errorf("stream configuration update can not change storage type"))
2317 }
2318 // Can only change retention from limits to interest or back, not to/from work queue for now.
2319 if cfg.Retention != old.Retention {
2320 if old.Retention == WorkQueuePolicy || cfg.Retention == WorkQueuePolicy {
2321 return nil, NewJSStreamInvalidConfigError(fmt.Errorf("stream configuration update can not change retention policy to/from workqueue"))
2322 }
2323 }
2324 // Can not change from true to false.
2325 if !cfg.Sealed && old.Sealed {
2326 return nil, NewJSStreamInvalidConfigError(fmt.Errorf("stream configuration update can not unseal a sealed stream"))
2327 }
2328 // Can not change from true to false.
2329 if !cfg.DenyDelete && old.DenyDelete {
2330 return nil, NewJSStreamInvalidConfigError(fmt.Errorf("stream configuration update can not cancel deny message deletes"))
2331 }
2332 // Can not change from true to false.
2333 if !cfg.DenyPurge && old.DenyPurge {
2334 return nil, NewJSStreamInvalidConfigError(fmt.Errorf("stream configuration update can not cancel deny purge"))
2335 }
2336 // Check for mirror changes which are not allowed.
2337 // We will allow removing the mirror config to "promote" the mirror to a normal stream.
2338 if cfg.Mirror != nil && !reflect.DeepEqual(cfg.Mirror, old.Mirror) {
2339 return nil, NewJSStreamMirrorNotUpdatableError()
2340 }
2341
2342 // Check on new discard new per subject.
2343 if cfg.DiscardNewPer {
2344 if cfg.Discard != DiscardNew {
2345 return nil, NewJSStreamInvalidConfigError(fmt.Errorf("discard new per subject requires discard new policy to be set"))
2346 }
2347 if cfg.MaxMsgsPer <= 0 {
2348 return nil, NewJSStreamInvalidConfigError(fmt.Errorf("discard new per subject requires max msgs per subject > 0"))
2349 }
2350 }
2351
2352 // Check on the allowed message TTL status.
2353 if old.AllowMsgTTL && !cfg.AllowMsgTTL {
2354 return nil, NewJSStreamInvalidConfigError(fmt.Errorf("message TTL status can not be disabled"))
2355 }
2356
2357 // Can't change counter setting.
2358 if cfg.AllowMsgCounter != old.AllowMsgCounter {
2359 return nil, NewJSStreamInvalidConfigError(fmt.Errorf("stream configuration update can not change message counter setting"))
2360 }
2361
2362 // Can't disable message schedules setting.
2363 if old.AllowMsgSchedules && !cfg.AllowMsgSchedules {
2364 return nil, NewJSStreamInvalidConfigError(fmt.Errorf("message schedules can not be disabled"))
2365 }
2366
2367 if old.PersistMode != cfg.PersistMode {
2368 return nil, NewJSStreamInvalidConfigError(fmt.Errorf("stream configuration update can not change persist mode"))
2369 }
2370
2371 // Do some adjustments for being sealed.
2372 // Pedantic mode will allow those changes to be made, as they are deterministic and important to get a sealed stream.
2373 if cfg.Sealed {
2374 cfg.MaxAge = 0
2375 cfg.Discard = DiscardNew
2376 cfg.DenyDelete, cfg.DenyPurge = true, true
2377 cfg.AllowRollup = false
2378 }
2379
2380 // Check limits. We need some extra handling to allow updating MaxBytes.
2381
2382 // First, let's calculate the difference between the new and old MaxBytes.
2383 maxBytesDiff := max(cfg.MaxBytes, 0) - max(old.MaxBytes, 0)
2384 if maxBytesDiff < 0 {
2385 // If we're updating to a lower MaxBytes (maxBytesDiff is negative),
2386 // then set to zero so checkBytesLimits doesn't set addBytes to 1.
2387 maxBytesDiff = 0
2388 }
2389 // If maxBytesDiff == 0, then that means MaxBytes didn't change.
2390 // If maxBytesDiff > 0, then we want to reserve additional bytes.
2391
2392 // Save the user configured MaxBytes.
2393 newMaxBytes := cfg.MaxBytes
2394
2395 // We temporarily set cfg.MaxBytes to maxBytesDiff because checkAllLimits
2396 // adds cfg.MaxBytes to the current reserved limit and checks if we've gone
2397 // over. However, we don't want an additional cfg.MaxBytes, we only want to
2398 // reserve the difference between the new and the old values.
2399 cfg.MaxBytes = maxBytesDiff
2400
2401 // Check limits.
2402 js, isClustered := jsa.jetStreamAndClustered()
2403 jsa.mu.RLock()
2404 acc := jsa.account
2405 jsa.usageMu.RLock()
2406 selected, tier, hasTier := jsa.selectLimits(cfg.Replicas)
2407 if !hasTier && old.Replicas != cfg.Replicas {
2408 selected, tier, hasTier = jsa.selectLimits(old.Replicas)
2409 }
2410 jsa.usageMu.RUnlock()
2411 reserved := int64(0)
2412 if !isClustered {
2413 reserved = jsa.tieredReservation(tier, &cfg)
2414 }
2415 jsa.mu.RUnlock()
2416 if !hasTier {
2417 return nil, NewJSNoLimitsError()
2418 }
2419 js.mu.RLock()
2420 defer js.mu.RUnlock()
2421 if isClustered {
2422 _, reserved = js.tieredStreamAndReservationCount(acc.Name, tier, &cfg)
2423 }
2424 // reserved covers only the other streams. checkAllLimits adds this stream's
2425 // footprint via cfg.MaxBytes, which is currently maxBytesDiff, so it only
2426 // adds the diff. Add the remaining (newMaxBytes - maxBytesDiff) here so the
2427 // two together equal this stream's true new footprint, even when Replicas
2428 // changes on update.
2429 reserved = addSaturate(reserved, accountReservation(tier, cfg.Replicas, newMaxBytes-maxBytesDiff))
2430 if err := js.checkAllLimits(&selected, tier, &cfg, reserved, 0); err != nil {
2431 return nil, err
2432 }
2433 // Restore the user configured MaxBytes.
2434 cfg.MaxBytes = newMaxBytes
2435 return &cfg, nil
2436 }
2437
2438 // Update will allow certain configuration properties of an existing stream to be updated.
2439 func (mset *stream) update(config *StreamConfig) error {
2440 return mset.updateWithAdvisory(config, true, false)
2441 }
2442
2443 func (mset *stream) updatePedantic(config *StreamConfig, pedantic bool) error {
2444 return mset.updateWithAdvisory(config, true, pedantic)
2445 }
2446
2447 // Update will allow certain configuration properties of an existing stream to be updated.
2448 func (mset *stream) updateWithAdvisory(config *StreamConfig, sendAdvisory bool, pedantic bool) error {
2449 _, jsa, err := mset.acc.checkForJetStream()
2450 if err != nil {
2451 return err
2452 }
2453
2454 mset.mu.RLock()
2455 ocfg := mset.cfg
2456 s := mset.srv
2457 mset.mu.RUnlock()
2458
2459 cfg, err := mset.jsa.configUpdateCheck(&ocfg, config, s, pedantic)
2460 if err != nil {
2461 return NewJSStreamInvalidConfigError(err, Unless(err))
2462 }
2463
2464 // In the event that some of the stream-level limits have changed, yell appropriately
2465 // if any of the consumers exceed that limit.
2466 oldInactiveThreshold, newInactiveThreshold := ocfg.ConsumerLimits.InactiveThreshold, cfg.ConsumerLimits.InactiveThreshold
2467 oldMaxAckPending, newMaxAckPending := ocfg.ConsumerLimits.MaxAckPending, cfg.ConsumerLimits.MaxAckPending
2468 updateLimits := (newInactiveThreshold > 0 && oldInactiveThreshold != newInactiveThreshold) ||
2469 (newMaxAckPending > 0 && oldMaxAckPending != newMaxAckPending)
2470
2471 // Only check if not clustered. The meta leader performs clustered checks.
2472 if updateLimits && !mset.js.isClustered() {
2473 var errorConsumers []string
2474 mset.mu.RLock()
2475 clist := make([]*consumer, 0, len(mset.consumers))
2476 for _, c := range mset.consumers {
2477 clist = append(clist, c)
2478 }
2479 mset.mu.RUnlock()
2480 for _, c := range clist {
2481 c.mu.RLock()
2482 name, ccfg := c.name, c.cfg
2483 if (newInactiveThreshold > 0 && ccfg.InactiveThreshold > newInactiveThreshold) ||
2484 (newMaxAckPending > 0 && ccfg.MaxAckPending > newMaxAckPending) {
2485 errorConsumers = append(errorConsumers, name)
2486 }
2487 c.mu.RUnlock()
2488 }
2489 if len(errorConsumers) > 0 {
2490 // TODO(nat): Return a parsable error so that we can surface something
2491 // sensible through the JS API.
2492 return fmt.Errorf("change to limits violates consumers: %s", strings.Join(errorConsumers, ", "))
2493 }
2494 }
2495
2496 jsa.mu.RLock()
2497 if jsa.subjectsOverlap(cfg.Subjects, mset) {
2498 jsa.mu.RUnlock()
2499 return NewJSStreamSubjectOverlapError()
2500 }
2501 jsa.mu.RUnlock()
2502
2503 mset.mu.Lock()
2504 if mset.active {
2505 // Check for mirror promotion.
2506 if ocfg.Mirror != nil && cfg.Mirror == nil {
2507 // Only try deleting the sourcing consumer if one wasn't provided to us.
2508 if ocfg.Mirror.Consumer == nil {
2509 mset.tryDeleteMirrorConsumer(ocfg.Mirror)
2510 }
2511 mset.cancelMirrorConsumer()
2512 mset.mirror = nil
2513 }
2514
2515 // Now check for subject interest differences.
2516 current := make(map[string]struct{}, len(ocfg.Subjects))
2517 for _, s := range ocfg.Subjects {
2518 current[s] = struct{}{}
2519 }
2520 // Update config with new values. The store update will enforce any stricter limits.
2521
2522 // Now walk new subjects. All of these need to be added, but we will check
2523 // the originals first, since if it is in there we can skip, already added.
2524 for _, s := range cfg.Subjects {
2525 if _, ok := current[s]; !ok {
2526 if _, err := mset.subscribeInternal(s, mset.processInboundJetStreamMsg); err != nil {
2527 mset.mu.Unlock()
2528 return err
2529 }
2530 }
2531 delete(current, s)
2532 }
2533 // What is left in current needs to be deleted.
2534 for s := range current {
2535 if err := mset.unsubscribeInternal(s); err != nil {
2536 mset.mu.Unlock()
2537 return err
2538 }
2539 }
2540
2541 // Check for the Duplicates
2542 mset.ddMu.Lock()
2543 if cfg.Duplicates != ocfg.Duplicates && mset.ddtmr != nil {
2544 // Let it fire right away, it will adjust properly on purge.
2545 mset.ddtmr.Reset(time.Microsecond)
2546 }
2547 mset.ddMu.Unlock()
2548
2549 // Check for Sources.
2550 if len(cfg.Sources) > 0 || len(ocfg.Sources) > 0 {
2551 currentIName := make(map[string]struct{})
2552 currentConsumers := make(map[string]*StreamSource)
2553 needsStartingSeqNum := make(map[string]struct{})
2554
2555 getSourcingConsumerIName := func(ssi *StreamSource, sources []*StreamSource) string {
2556 var iName = ssi.Name
2557 if ssi.External != nil {
2558 iName = iName + ":" + getHash(ssi.External.ApiPrefix)
2559 }
2560 return fmt.Sprintf("%s %s", iName, mset.createSourcingConsumerHash(ssi, sources))
2561 }
2562 for _, s := range ocfg.Sources {
2563 currentIName[s.iname] = struct{}{}
2564 // Only track the sourcing consumer for deletion if one wasn't provided to us.
2565 if s.Consumer == nil {
2566 currentConsumers[getSourcingConsumerIName(s, ocfg.Sources)] = s
2567 }
2568 }
2569 for _, s := range cfg.Sources {
2570 s.setIndexName()
2571 if _, ok := currentIName[s.iname]; !ok {
2572 // new source
2573 if mset.sources == nil {
2574 mset.sources = make(map[string]*sourceInfo)
2575 }
2576 mset.cfgMu.Lock()
2577 mset.cfg.Sources = append(mset.cfg.Sources, s)
2578 mset.cfgMu.Unlock()
2579
2580 var si *sourceInfo
2581
2582 if len(s.SubjectTransforms) == 0 {
2583 si = &sourceInfo{name: s.Name, iname: s.iname, sf: s.FilterSubject}
2584 } else {
2585 si = &sourceInfo{name: s.Name, iname: s.iname}
2586 si.trs = make([]*subjectTransform, len(s.SubjectTransforms))
2587 si.sfs = make([]string, len(s.SubjectTransforms))
2588 for i := range s.SubjectTransforms {
2589 // err can be ignored as already validated in config check
2590 si.sfs[i] = s.SubjectTransforms[i].Source
2591 var err error
2592 si.trs[i], err = NewSubjectTransform(s.SubjectTransforms[i].Source, s.SubjectTransforms[i].Destination)
2593 if err != nil {
2594 mset.mu.Unlock()
2595 return fmt.Errorf("unable to get subject transform for source: %v", err)
2596 }
2597 }
2598 }
2599
2600 mset.sources[s.iname] = si
2601 needsStartingSeqNum[s.iname] = struct{}{}
2602 } else {
2603 // source already exists
2604 delete(currentIName, s.iname)
2605 }
2606
2607 // Remove the source if it still exists, but only if not using a pre-existing consumer.
2608 if s.Consumer == nil {
2609 delete(currentConsumers, getSourcingConsumerIName(s, cfg.Sources))
2610 }
2611 }
2612 // Delete source consumers if any aren't used anymore.
2613 for _, s := range currentConsumers {
2614 id := mset.createSourcingConsumerHash(s, ocfg.Sources)
2615 mset.tryDeleteSourceConsumer(id, s)
2616 }
2617 // What is left in currentIName needs to be deleted.
2618 for iName := range currentIName {
2619 mset.cancelSourceConsumer(iName)
2620 delete(mset.sources, iName)
2621 }
2622 neededCopy := make(map[string]struct{}, len(needsStartingSeqNum))
2623 for iName := range needsStartingSeqNum {
2624 neededCopy[iName] = struct{}{}
2625 }
2626 mset.setStartingSequenceForSources(needsStartingSeqNum)
2627 for iName := range neededCopy {
2628 mset.setupSourceConsumer(iName, mset.sources[iName].sseq+1, time.Time{})
2629 }
2630 }
2631 }
2632
2633 // Check for a change in allow direct/mirror status.
2634 // These will run on all members, so just update as appropriate here.
2635 // We do make sure we are caught up under monitorStream() during initial startup.
2636 if cfg.AllowDirect != ocfg.AllowDirect {
2637 if cfg.AllowDirect {
2638 mset.subscribeToDirect()
2639 } else {
2640 mset.unsubscribeToDirect()
2641 }
2642 }
2643 if cfg.MirrorDirect != ocfg.MirrorDirect {
2644 if cfg.MirrorDirect {
2645 mset.subscribeToMirrorDirect()
2646 } else {
2647 mset.unsubscribeToMirrorDirect()
2648 }
2649 }
2650
2651 // Check for changes to RePublish.
2652 if cfg.RePublish != nil {
2653 // Empty same as all.
2654 if cfg.RePublish.Source == _EMPTY_ {
2655 cfg.RePublish.Source = fwcs
2656 }
2657 if cfg.RePublish.Destination == _EMPTY_ {
2658 cfg.RePublish.Destination = fwcs
2659 }
2660 tr, err := NewSubjectTransform(cfg.RePublish.Source, cfg.RePublish.Destination)
2661 if err != nil {
2662 mset.mu.Unlock()
2663 return fmt.Errorf("stream configuration for republish from '%s' to '%s': %w", cfg.RePublish.Source, cfg.RePublish.Destination, err)
2664 }
2665 // Assign our transform for republishing.
2666 mset.tr = tr
2667 } else {
2668 mset.tr = nil
2669 }
2670
2671 // Check for changes to subject transform
2672 if ocfg.SubjectTransform == nil && cfg.SubjectTransform != nil {
2673 tr, err := NewSubjectTransform(cfg.SubjectTransform.Source, cfg.SubjectTransform.Destination)
2674 if err != nil {
2675 mset.mu.Unlock()
2676 return fmt.Errorf("stream configuration for subject transform from '%s' to '%s': %w", cfg.SubjectTransform.Source, cfg.SubjectTransform.Destination, err)
2677 }
2678 mset.itr = tr
2679 } else if ocfg.SubjectTransform != nil && cfg.SubjectTransform != nil &&
2680 (ocfg.SubjectTransform.Source != cfg.SubjectTransform.Source || ocfg.SubjectTransform.Destination != cfg.SubjectTransform.Destination) {
2681 tr, err := NewSubjectTransform(cfg.SubjectTransform.Source, cfg.SubjectTransform.Destination)
2682 if err != nil {
2683 mset.mu.Unlock()
2684 return fmt.Errorf("stream configuration for subject transform from '%s' to '%s': %w", cfg.SubjectTransform.Source, cfg.SubjectTransform.Destination, err)
2685 }
2686 mset.itr = tr
2687 } else if ocfg.SubjectTransform != nil && cfg.SubjectTransform == nil {
2688 mset.itr = nil
2689 }
2690
2691 js := mset.js
2692
2693 if targetTier := tierName(cfg.Replicas); mset.tier != targetTier {
2694 // In cases such as R1->R3, only one update is needed
2695 jsa.usageMu.RLock()
2696 _, ok := jsa.limits[targetTier]
2697 jsa.usageMu.RUnlock()
2698 if ok {
2699 // error never set
2700 _, reported, _ := mset.store.Utilization()
2701 jsa.updateUsage(mset.tier, mset.stype, -int64(reported))
2702 jsa.updateUsage(targetTier, mset.stype, int64(reported))
2703 mset.tier = targetTier
2704 }
2705 // else in case the new tier does not exist (say on move), keep the old tier around
2706 // a subsequent update to an existing tier will then move from existing past tier to existing new tier
2707 }
2708
2709 if mset.isLeader() && mset.sa != nil && ocfg.Retention != cfg.Retention && cfg.Retention == InterestPolicy {
2710 // Before we can update the retention policy for the consumer, we need
2711 // the replica count of all consumers to match the stream.
2712 for _, c := range mset.sa.consumers {
2713 if c.Config.Replicas > 0 && c.Config.Replicas != cfg.Replicas {
2714 mset.mu.Unlock()
2715 return fmt.Errorf("consumer %q replica count must be %d", c.Name, cfg.Replicas)
2716 }
2717 }
2718 }
2719
2720 // If atomic publish is disabled, delete any in-progress batches.
2721 if !cfg.AllowAtomicPublish {
2722 mset.deleteAtomicBatches(false)
2723 }
2724 // If fast batch publish is disabled, delete any in-progress batches.
2725 if !cfg.AllowBatchPublish {
2726 mset.deleteFastBatches()
2727 }
2728 if !cfg.AllowAtomicPublish && !cfg.AllowBatchPublish {
2729 mset.batches = nil
2730 }
2731
2732 // Now update config and store's version of our config.
2733 // Although we are under the stream write lock, we will also assign the new
2734 // configuration under mset.cfgMu lock. This is so that in places where
2735 // mset.mu cannot be acquired (like many cases in consumer.go where code
2736 // is under the consumer's lock), and the stream's configuration needs to
2737 // be inspected, one can use mset.cfgMu's read lock to do that safely.
2738 mset.cfgMu.Lock()
2739 mset.cfg = *cfg
2740 mset.cfgMu.Unlock()
2741
2742 // If we're changing retention and haven't errored because of consumer
2743 // replicas by now, whip through and update the consumer retention.
2744 if ocfg.Retention != cfg.Retention {
2745 toUpdate := make([]*consumer, 0, len(mset.consumers))
2746 for _, c := range mset.consumers {
2747 toUpdate = append(toUpdate, c)
2748 }
2749 var ss StreamState
2750 mset.store.FastState(&ss)
2751 mset.mu.Unlock()
2752 for _, c := range toUpdate {
2753 c.mu.Lock()
2754 c.retention = cfg.Retention
2755 c.mu.Unlock()
2756 if c.retention == InterestPolicy {
2757 // If we're switching to interest, force a check of the
2758 // interest of existing stream messages.
2759 c.checkStateForInterestStream(&ss)
2760 }
2761 }
2762 mset.mu.Lock()
2763 }
2764
2765 // If we are the leader never suppress update advisory, simply send.
2766 if mset.isLeader() && sendAdvisory {
2767 mset.sendUpdateAdvisoryLocked()
2768 }
2769 mset.mu.Unlock()
2770
2771 if js != nil {
2772 maxBytesDiff := max(cfg.MaxBytes, 0) - max(ocfg.MaxBytes, 0)
2773 if maxBytesDiff > 0 {
2774 // Reserve the difference
2775 js.reserveStreamResources(&StreamConfig{
2776 MaxBytes: maxBytesDiff,
2777 Storage: cfg.Storage,
2778 })
2779 } else if maxBytesDiff < 0 {
2780 // Release the difference
2781 js.releaseStreamResources(&StreamConfig{
2782 MaxBytes: -maxBytesDiff,
2783 Storage: ocfg.Storage,
2784 })
2785 }
2786 }
2787
2788 mset.store.UpdateConfig(cfg)
2789
2790 return nil
2791 }
2792
2793 // tryDeleteMirrorConsumer is a best-effort single try to delete a consumer used for stream mirroring.
2794 // Lock should be held.
2795 func (mset *stream) tryDeleteMirrorConsumer(mirror *StreamSource) {
2796 id := mset.createStableConsumerHash()
2797 consumerName := fmt.Sprintf("JS_MIRROR_%s", id)
2798 log := mset.mirror != nil && mset.mirror.cname == consumerName
2799 mset.tryDeleteSourcingConsumer("mirror", mirror, consumerName, log)
2800 }
2801
2802 // tryDeleteSourceConsumer is a best-effort single try to delete a consumer used for stream sourcing.
2803 // Lock should be held.
2804 func (mset *stream) tryDeleteSourceConsumer(id string, source *StreamSource) {
2805 consumerName := fmt.Sprintf("JS_SRC_%s", id)
2806 si := mset.sources[source.iname]
2807 log := si != nil && si.cname == consumerName
2808 mset.tryDeleteSourcingConsumer("source", source, consumerName, log)
2809 }
2810
2811 // tryDeleteSourcingConsumer is a best-effort single try to delete a sourcing consumer.
2812 // Lock should be held.
2813 func (mset *stream) tryDeleteSourcingConsumer(kind string, source *StreamSource, consumerName string, log bool) {
2814 acc := mset.acc
2815 accName, streamName, sourceName := acc.Name, mset.cfg.Name, source.Name
2816 subject := fmt.Sprintf(JSApiConsumerDeleteT, sourceName, consumerName)
2817 if source.External != nil {
2818 subject = strings.Replace(subject, JSApiPrefix, source.External.ApiPrefix, 1)
2819 subject = strings.ReplaceAll(subject, "..", ".")
2820 }
2821 s := mset.srv
2822 go func() {
2823 warn := func(err error) {
2824 if log {
2825 s.Warnf("Cleanup of %s consumer '%s > %s' failed for stream '%s > %s': %v", kind, sourceName, consumerName, accName, streamName, err)
2826 }
2827 }
2828
2829 respCh := make(chan *JSApiConsumerDeleteResponse, 1)
2830 reply := infoReplySubject()
2831 cdSub, err := acc.subscribeInternal(reply, func(sub *subscription, c *client, _ *Account, subject, reply string, rmsg []byte) {
2832 _, msg := c.msgParts(rmsg)
2833
2834 var cdr JSApiConsumerDeleteResponse
2835 if err := json.Unmarshal(msg, &cdr); err != nil {
2836 warn(err)
2837 return
2838 }
2839 select {
2840 case respCh <- &cdr:
2841 default:
2842 }
2843 })
2844 if err != nil {
2845 warn(err)
2846 return
2847 }
2848 defer acc.unsubscribeInternal(cdSub)
2849
2850 // Send the delete request.
2851 err = s.sendInternalAccountMsgWithReply(acc, subject, reply, nil, nil, false)
2852 if err != nil {
2853 warn(err)
2854 return
2855 }
2856 select {
2857 case cdr := <-respCh:
2858 if cdr.Error != nil {
2859 warn(cdr.Error)
2860 }
2861 case <-time.After(sourceHealthCheckInterval):
2862 warn(errors.New("timed out"))
2863 }
2864 }()
2865 }
2866
2867 // Small helper to return the Name field from mset.cfg, protected by
2868 // the mset.cfgMu mutex. This is simply because we have several places
2869 // in consumer.go where we need it.
2870 func (mset *stream) getCfgName() string {
2871 mset.cfgMu.RLock()
2872 defer mset.cfgMu.RUnlock()
2873 return mset.cfg.Name
2874 }
2875
2876 // Purge will remove all messages from the stream and underlying store based on the request.
2877 func (mset *stream) purge(preq *JSApiStreamPurgeRequest) (purged uint64, err error) {
2878 // Purges mutate message state, so hold the isolation lock like any other
2879 // write so direct get requests don't observe a partially applied purge.
2880 mset.isolateMu.Lock()
2881 defer mset.isolateMu.Unlock()
2882 return mset.purgeLocked(preq, true)
2883 }
2884
2885 func (mset *stream) purgeLocked(preq *JSApiStreamPurgeRequest, needLock bool) (purged uint64, err error) {
2886 if needLock {
2887 mset.mu.Lock()
2888 defer mset.mu.Unlock()
2889 }
2890 if mset.closed.Load() {
2891 return 0, errStreamClosed
2892 }
2893 if mset.cfg.Sealed {
2894 return 0, errors.New("sealed stream")
2895 }
2896 store, mlseq := mset.store, mset.lseq
2897
2898 if preq != nil {
2899 purged, err = mset.store.PurgeEx(preq.Subject, preq.Sequence, preq.Keep)
2900 } else {
2901 purged, err = mset.store.Purge()
2902 }
2903 if err != nil {
2904 return purged, err
2905 }
2906
2907 // Grab our stream state.
2908 var state StreamState
2909 store.FastState(&state)
2910 fseq, lseq := state.FirstSeq, state.LastSeq
2911
2912 // Check if our last has moved past what our original last sequence was, if so reset.
2913 if lseq > mlseq {
2914 mset.lseq = lseq
2915 }
2916
2917 // Clear any pending acks below first seq.
2918 mset.clearAllPreAcksBelowFloor(fseq)
2919
2920 // Purge consumers.
2921 // Check for filtered purge.
2922 if preq != nil && preq.Subject != _EMPTY_ {
2923 ss, err := store.FilteredState(fseq, preq.Subject)
2924 if err != nil {
2925 return purged, err
2926 }
2927 fseq = ss.First
2928 }
2929
2930 // Take a copy of cList to avoid o.purge() potentially taking the stream lock and
2931 // violating the lock ordering.
2932 mset.clsMu.RLock()
2933 cList := slices.Clone(mset.cList)
2934 mset.clsMu.RUnlock()
2935 for _, o := range cList {
2936 start := fseq
2937 o.mu.RLock()
2938 // we update consumer sequences if:
2939 // no subject was specified, we can purge all consumers sequences
2940 doPurge := preq == nil ||
2941 preq.Subject == _EMPTY_ ||
2942 // consumer filter subject is equal to purged subject
2943 // or consumer filter subject is subset of purged subject,
2944 // but not the other way around.
2945 o.isEqualOrSubsetMatch(preq.Subject)
2946 // Check if a consumer has a wider subject space than what we purged
2947 var isWider bool
2948 if !doPurge && preq != nil && o.isFilteredMatch(preq.Subject) {
2949 doPurge, isWider = true, true
2950 start = state.FirstSeq
2951 }
2952 o.mu.RUnlock()
2953 if doPurge {
2954 o.purge(start, lseq, isWider)
2955 }
2956 }
2957
2958 return purged, nil
2959 }
2960
2961 // RemoveMsg will remove a message from a stream.
2962 // FIXME(dlc) - Should pick one and be consistent.
2963 func (mset *stream) removeMsg(seq uint64) (bool, error) {
2964 return mset.deleteMsg(seq)
2965 }
2966
2967 // DeleteMsg will remove a message from a stream.
2968 func (mset *stream) deleteMsg(seq uint64) (bool, error) {
2969 if mset.closed.Load() {
2970 return false, errStreamClosed
2971 }
2972 // Deletes mutate message state, so hold the isolation lock like any other write.
2973 mset.isolateMu.Lock()
2974 defer mset.isolateMu.Unlock()
2975 removed, err := mset.store.RemoveMsg(seq)
2976 if err != nil {
2977 return removed, err
2978 }
2979 mset.mu.Lock()
2980 mset.clearAllPreAcks(seq)
2981 mset.mu.Unlock()
2982 return removed, err
2983 }
2984
2985 // EraseMsg will securely remove a message and rewrite the data with random data.
2986 func (mset *stream) eraseMsg(seq uint64) (bool, error) {
2987 if mset.closed.Load() {
2988 return false, errStreamClosed
2989 }
2990 // Deletes mutate message state, so hold the isolation lock like any other write.
2991 mset.isolateMu.Lock()
2992 defer mset.isolateMu.Unlock()
2993 removed, err := mset.store.EraseMsg(seq)
2994 if err != nil {
2995 return removed, err
2996 }
2997 mset.mu.Lock()
2998 mset.clearAllPreAcks(seq)
2999 mset.mu.Unlock()
3000 return removed, err
3001 }
3002
3003 // Are we a mirror?
3004 func (mset *stream) isMirror() bool {
3005 mset.cfgMu.RLock()
3006 defer mset.cfgMu.RUnlock()
3007 return mset.cfg.Mirror != nil
3008 }
3009
3010 func (mset *stream) sourcesInfo() (sis []*StreamSourceInfo) {
3011 mset.mu.RLock()
3012 defer mset.mu.RUnlock()
3013 sis = make([]*StreamSourceInfo, 0, len(mset.sources))
3014 for _, si := range mset.sources {
3015 sis = append(sis, mset.sourceInfo(si))
3016 }
3017 return sis
3018 }
3019
3020 // Lock should be held
3021 func (mset *stream) sourceInfo(si *sourceInfo) *StreamSourceInfo {
3022 if si == nil {
3023 return nil
3024 }
3025
3026 var ssi = StreamSourceInfo{Name: si.name, Lag: si.lag, Error: si.err, FilterSubject: si.sf}
3027
3028 trConfigs := make([]SubjectTransformConfig, len(si.sfs))
3029 for i := range si.sfs {
3030 var destination string
3031 if si.trs[i] != nil {
3032 destination = si.trs[i].dest
3033 }
3034 trConfigs[i] = SubjectTransformConfig{si.sfs[i], destination}
3035 }
3036
3037 ssi.SubjectTransforms = trConfigs
3038
3039 // If we have not heard from the source, set Active to -1.
3040 if last := si.last.Load(); last == 0 {
3041 ssi.Active = -1
3042 } else {
3043 ssi.Active = time.Since(time.Unix(0, last))
3044 }
3045
3046 var ext *ExternalStream
3047 if mset.cfg.Mirror != nil {
3048 ext = mset.cfg.Mirror.External
3049 } else if ss := mset.streamSource(si.iname); ss != nil && ss.External != nil {
3050 ext = ss.External
3051 }
3052 if ext != nil {
3053 ssi.External = &ExternalStream{
3054 ApiPrefix: ext.ApiPrefix,
3055 DeliverPrefix: ext.DeliverPrefix,
3056 }
3057 }
3058 return &ssi
3059 }
3060
3061 // Return our source info for our mirror.
3062 func (mset *stream) mirrorInfo() *StreamSourceInfo {
3063 mset.mu.RLock()
3064 defer mset.mu.RUnlock()
3065 return mset.sourceInfo(mset.mirror)
3066 }
3067
3068 // retryDisconnectedSyncConsumers() will check if we have any disconnected
3069 // sync consumers for either mirror or a source and will reset and retry to connect.
3070 func (mset *stream) retryDisconnectedSyncConsumers() {
3071 mset.mu.Lock()
3072 defer mset.mu.Unlock()
3073
3074 // Only applicable if we are the stream leader.
3075 if !mset.isLeader() {
3076 return
3077 }
3078
3079 // Not client.isClosed(): internal account clients have nil nc, which would make isClosed always true here.
3080 clientClosed := func(c *client) bool {
3081 return c != nil && (c.flags.isSet(closeConnection) || c.flags.isSet(connMarkedClosed))
3082 }
3083 // Stale sources need to be reset: if not seen past the health check interval, it's stale.
3084 stale := func(si *sourceInfo) bool {
3085 return time.Since(time.Unix(0, si.last.Load())) > sourceHealthCheckInterval
3086 }
3087 shouldRetry := func(si *sourceInfo) bool {
3088 if si != nil && !si.sip && (si.sub == nil || clientClosed(si.sub.client) || stale(si)) {
3089 // Skip if a recreate is already scheduled and we can't cancel it.
3090 if t, ok := mset.sourceSetupSchedules[si.iname]; ok {
3091 if !t.Stop() {
3092 return false
3093 }
3094 delete(mset.sourceSetupSchedules, si.iname)
3095 }
3096 si.fails = 0
3097 mset.cancelSourceInfo(si)
3098 return true
3099 }
3100 return false
3101 }
3102
3103 // Check mirrors first.
3104 if si := mset.mirror; si != nil {
3105 if shouldRetry(si) {
3106 mset.scheduleSetupMirrorConsumerRetry()
3107 }
3108 } else {
3109 for _, si := range mset.sources {
3110 if shouldRetry(si) {
3111 mset.setupSourceConsumer(si.iname, si.sseq+1, time.Time{})
3112 }
3113 }
3114 }
3115 }
3116
3117 const (
3118 // Our consumer HB interval.
3119 sourceHealthHB = 1 * time.Second
3120 // How often we check and our stalled interval.
3121 sourceHealthCheckInterval = 10 * time.Second
3122 )
3123
3124 // Will run as a Go routine to process mirror consumer messages.
3125 func (mset *stream) processMirrorMsgs(mirror *sourceInfo, ready *sync.WaitGroup) {
3126 s := mset.srv
3127 defer func() {
3128 mirror.wg.Done()
3129 s.grWG.Done()
3130 }()
3131
3132 // Grab stream quit channel.
3133 mset.mu.Lock()
3134 msgs, qch, siqch := mirror.msgs, mset.qch, mirror.qch
3135 // If the mirror was already canceled before we got here, exit early.
3136 if siqch == nil {
3137 mset.mu.Unlock()
3138 ready.Done()
3139 return
3140 }
3141 // Set the last seen as now so that we don't fail at the first check.
3142 mirror.last.Store(time.Now().UnixNano())
3143 mset.mu.Unlock()
3144
3145 // Signal the caller that we have captured the above fields.
3146 ready.Done()
3147
3148 // Make sure we have valid ipq for msgs.
3149 if msgs == nil {
3150 mset.mu.Lock()
3151 mset.cancelMirrorConsumer()
3152 mset.mu.Unlock()
3153 return
3154 }
3155
3156 t := time.NewTicker(sourceHealthCheckInterval)
3157 defer t.Stop()
3158
3159 for {
3160 select {
3161 case <-s.quitCh:
3162 return
3163 case <-qch:
3164 return
3165 case <-siqch:
3166 return
3167 case <-msgs.ch:
3168 ims := msgs.pop()
3169 for _, im := range ims {
3170 if !mset.processInboundMirrorMsg(im) {
3171 break
3172 }
3173 im.returnToPool()
3174 }
3175 msgs.recycle(&ims)
3176 case <-t.C:
3177 mset.mu.RLock()
3178 var stalled bool
3179 if mset.mirror != nil {
3180 stalled = time.Since(time.Unix(0, mset.mirror.last.Load())) > sourceHealthCheckInterval
3181 }
3182 isLeader := mset.isLeader()
3183 mset.mu.RUnlock()
3184 // No longer leader.
3185 if !isLeader {
3186 mset.mu.Lock()
3187 mset.cancelMirrorConsumer()
3188 mset.mu.Unlock()
3189 return
3190 }
3191 // We are stalled.
3192 if stalled {
3193 mset.retryMirrorConsumer()
3194 }
3195 }
3196 }
3197 }
3198
3199 // Checks that the message is from our current direct consumer. We can not depend on sub comparison
3200 // since cross account imports break.
3201 func (si *sourceInfo) isCurrentSub(cname string) bool {
3202 return si.cname != _EMPTY_ && si.cname == cname
3203 }
3204
3205 // processInboundMirrorMsg handles processing messages bound for a stream.
3206 func (mset *stream) processInboundMirrorMsg(m *inMsg) bool {
3207 mset.mu.Lock()
3208 if mset.mirror == nil {
3209 mset.mu.Unlock()
3210 return false
3211 }
3212 if !mset.isLeader() {
3213 mset.cancelMirrorConsumer()
3214 mset.mu.Unlock()
3215 return false
3216 }
3217
3218 isControl := m.isControlMsg()
3219 cname := consumerFromAckReply(m.rply)
3220
3221 // Ignore from old subscriptions.
3222 // The reason we can not just compare subs is that on cross account imports they will not match.
3223 if !mset.mirror.isCurrentSub(cname) && !isControl {
3224 mset.mu.Unlock()
3225 return false
3226 }
3227
3228 // Check for heartbeats and flow control messages.
3229 if isControl {
3230 var needsRetry bool
3231 // Flow controls have reply subjects.
3232 if m.rply != _EMPTY_ {
3233 mset.handleFlowControl(m, mset.mirror.dseq, mset.mirror.sseq)
3234 } else {
3235 // For idle heartbeats make sure we did not miss anything and check if we are considered stalled.
3236 if ldseq := parseInt64(sliceHeader(JSLastConsumerSeq, m.hdr)); ldseq > 0 && uint64(ldseq) != mset.mirror.dseq {
3237 needsRetry = true
3238 } else if fcReply := sliceHeader(JSConsumerStalled, m.hdr); len(fcReply) > 0 {
3239 // Other side thinks we are stalled, so send flow control reply.
3240 mset.outq.sendMsg(string(fcReply), nil)
3241 }
3242 }
3243 mset.mu.Unlock()
3244 if needsRetry {
3245 mset.retryMirrorConsumer()
3246 }
3247 return !needsRetry
3248 }
3249
3250 sseq, dseq, dc, ts, pending := ackReplyInfo(m.rply)
3251
3252 if dc > 1 {
3253 mset.mu.Unlock()
3254 return false
3255 }
3256
3257 // Mirror info tracking.
3258 olag, osseq, odseq := mset.mirror.lag, mset.mirror.sseq, mset.mirror.dseq
3259 if sseq <= mset.mirror.sseq {
3260 // Ignore older messages.
3261 // If the deliver sequence matches, we only update delivered accounting.
3262 if dseq == mset.mirror.dseq+1 {
3263 mset.mirror.dseq++
3264 }
3265 mset.mu.Unlock()
3266 return true
3267 } else if sseq == mset.mirror.sseq+1 {
3268 mset.mirror.dseq = dseq
3269 mset.mirror.sseq++
3270 } else if mset.mirror.cname == _EMPTY_ {
3271 mset.mirror.cname = cname
3272 mset.mirror.dseq, mset.mirror.sseq = dseq, sseq
3273 } else {
3274 // If the deliver sequence matches then the upstream stream has expired or deleted messages.
3275 if dseq == mset.mirror.dseq+1 {
3276 if err := mset.skipMsgs(mset.mirror.sseq+1, sseq-1); err != nil {
3277 mset.mirror.sseq = osseq
3278 mset.mirror.dseq = odseq
3279 mset.mu.Unlock()
3280 mset.retryMirrorConsumer()
3281 return false
3282 }
3283 mset.mirror.dseq++
3284 mset.mirror.sseq = sseq
3285 } else {
3286 mset.mu.Unlock()
3287 mset.retryMirrorConsumer()
3288 return false
3289 }
3290 }
3291
3292 if pending == 0 {
3293 mset.mirror.lag = 0
3294 } else {
3295 mset.mirror.lag = pending - 1
3296 }
3297
3298 // Check if we allow mirror direct here. If so check they we have mostly caught up.
3299 // The reason we do not require 0 is if the source is active we may always be slightly behind.
3300 if mset.cfg.MirrorDirect && mset.mirrorDirectSub == nil && pending < dgetCaughtUpThresh {
3301 if err := mset.subscribeToMirrorDirect(); err != nil {
3302 // Disable since we had problems above.
3303 mset.cfgMu.Lock()
3304 mset.cfg.MirrorDirect = false
3305 mset.cfgMu.Unlock()
3306 }
3307 }
3308
3309 // Do the subject transform if there's one
3310 if len(mset.mirror.trs) > 0 {
3311 for _, tr := range mset.mirror.trs {
3312 if tr == nil {
3313 continue
3314 } else {
3315 tsubj, err := tr.Match(m.subj)
3316 if err == nil {
3317 m.subj = tsubj
3318 break
3319 }
3320 }
3321 }
3322 }
3323
3324 s, js, stype := mset.srv, mset.js, mset.cfg.Storage
3325 node, term := mset.node, mset.term
3326 mset.mu.Unlock()
3327
3328 var err error
3329 if node != nil {
3330 if stype == FileStorage && isFileStoreMsgTooLarge(fileStoreMsgSize(m.subj, m.hdr, m.msg)) {
3331 err = ErrMsgTooLarge
3332 } else if js.limitsExceeded(stype) {
3333 s.resourcesExceededError(stype)
3334 err = ApiErrors[JSInsufficientResourcesErr]
3335 } else {
3336 err = node.Propose(term, encodeStreamMsg(m.subj, _EMPTY_, m.hdr, m.msg, sseq-1, ts, true))
3337 }
3338 } else {
3339 err = mset.processJetStreamMsg(m.subj, _EMPTY_, m.hdr, m.msg, sseq-1, ts, nil, true, true)
3340 }
3341 if err != nil {
3342 if strings.Contains(err.Error(), "no space left") {
3343 s.Errorf("JetStream out of space, will be DISABLED")
3344 s.ShutdownJetStream()
3345 return false
3346 }
3347 if err != errLastSeqMismatch {
3348 mset.mu.RLock()
3349 accName, sname := mset.acc.Name, mset.cfg.Name
3350 mset.mu.RUnlock()
3351 s.RateLimitWarnf("Error processing inbound mirror message for '%s' > '%s': %v",
3352 accName, sname, err)
3353 } else {
3354 // We may have missed messages, restart.
3355 lseq := mset.lastSeq()
3356 mset.mu.Lock()
3357 if mset.mirror != nil {
3358 mset.mirror.lag = olag
3359 mset.mirror.dseq = odseq
3360 mset.mirror.sseq = osseq
3361 if sseq <= lseq {
3362 mset.mirror.sseq = lseq
3363 }
3364 }
3365 mset.mu.Unlock()
3366 mset.retryMirrorConsumer()
3367 }
3368 }
3369 return err == nil
3370 }
3371
3372 func (mset *stream) setMirrorErr(err *ApiError) {
3373 mset.mu.Lock()
3374 if mset.mirror != nil {
3375 mset.mirror.err = err
3376 }
3377 mset.mu.Unlock()
3378 }
3379
3380 // Cancels a mirror consumer.
3381 //
3382 // Lock held on entry
3383 func (mset *stream) cancelMirrorConsumer() {
3384 if mset.mirror == nil {
3385 return
3386 }
3387 mset.cancelSourceInfo(mset.mirror)
3388 }
3389
3390 // Similar to setupMirrorConsumer except that it will print a debug statement
3391 // indicating that there is a retry.
3392 //
3393 // Lock is acquired in this function
3394 func (mset *stream) retryMirrorConsumer() error {
3395 mset.mu.Lock()
3396 defer mset.mu.Unlock()
3397 mset.srv.Debugf("Retrying mirror consumer for '%s > %s'", mset.acc.Name, mset.cfg.Name)
3398 mset.cancelMirrorConsumer()
3399 return mset.setupMirrorConsumer()
3400 }
3401
3402 // Lock should be held.
3403 func (mset *stream) skipMsgs(start, end uint64) error {
3404 node, store := mset.node, mset.store
3405 // If we are not clustered we can short circuit now with store.SkipMsgs
3406 if node == nil {
3407 if err := store.SkipMsgs(start, end-start+1); err != nil {
3408 return err
3409 }
3410 mset.lseq = end
3411 return nil
3412 }
3413
3414 // Must only be enabled once every peer in the cluster supports receiving
3415 // deleteRangeOp in the normal apply path; older peers panic on unknown ops.
3416 if mset.srv.getOpts().getFeatureFlag(FeatureFlagJsRaftDeleteRange) {
3417 return node.Propose(mset.term, encodeDeleteRange(&DeleteRange{First: start, Num: end - start + 1}))
3418 }
3419
3420 var entries []*Entry
3421 for seq := start; seq <= end; seq++ {
3422 entries = append(entries, newEntry(EntryNormal, encodeStreamMsg(_EMPTY_, _EMPTY_, nil, nil, seq-1, 0, false)))
3423 // So a single message does not get too big.
3424 if len(entries) > 10_000 {
3425 if err := node.ProposeMulti(mset.term, entries); err != nil {
3426 return err
3427 }
3428 // We need to re-create `entries` because there is a reference
3429 // to it in the node's pae map.
3430 entries = entries[:0]
3431 }
3432 }
3433 // Send all at once.
3434 if len(entries) > 0 {
3435 return node.ProposeMulti(mset.term, entries)
3436 }
3437 return nil
3438 }
3439
3440 const (
3441 // Base retry backoff duration.
3442 retryBackOff = 5 * time.Second
3443 // Maximum amount we will wait.
3444 retryMaximum = 2 * time.Minute
3445 )
3446
3447 // Calculate our backoff based on number of failures.
3448 func calculateRetryBackoff(fails int) time.Duration {
3449 backoff := time.Duration(retryBackOff) * time.Duration(fails*2)
3450 if backoff > retryMaximum {
3451 backoff = retryMaximum
3452 }
3453 return backoff
3454 }
3455
3456 // This will schedule a call to setupMirrorConsumer, taking into account the last
3457 // time it was retried and determine the soonest setupMirrorConsumer can be called
3458 // without tripping the sourceConsumerRetryThreshold. We will also take into account
3459 // number of failures and will back off our retries.
3460 // The mset.mirror pointer has been verified to be not nil by the caller.
3461 //
3462 // Lock held on entry
3463 func (mset *stream) scheduleSetupMirrorConsumerRetry() {
3464 // We are trying to figure out how soon we can retry. setupMirrorConsumer will reject
3465 // a retry if last was done less than "sourceConsumerRetryThreshold" ago.
3466 next := sourceConsumerRetryThreshold - time.Since(mset.mirror.lreq)
3467 if next < 0 {
3468 // It means that we have passed the threshold and so we are ready to go.
3469 next = 0
3470 }
3471 // Take into account failures here.
3472 next += calculateRetryBackoff(mset.mirror.fails)
3473
3474 // Add some jitter.
3475 next += time.Duration(rand.Intn(int(100*time.Millisecond))) + 100*time.Millisecond
3476
3477 stopAndClearTimer(&mset.mirrorConsumerSetup)
3478 mset.mirrorConsumerSetup = time.AfterFunc(next, func() {
3479 mset.mu.Lock()
3480 mset.setupMirrorConsumer()
3481 mset.mu.Unlock()
3482 })
3483 }
3484
3485 // How long we wait for a response from a consumer create request for a source or mirror.
3486 var srcConsumerWaitTime = 30 * time.Second
3487
3488 // Setup our mirror consumer.
3489 // Lock should be held.
3490 func (mset *stream) setupMirrorConsumer() error {
3491 if mset.closed.Load() {
3492 return errStreamClosed
3493 }
3494 if mset.outq == nil {
3495 return errors.New("outq required")
3496 }
3497 // We use to prevent update of a mirror configuration in cluster
3498 // mode but not in standalone. This is now fixed. However, without
3499 // rejecting the update, it could be that if the source stream was
3500 // removed and then later the mirrored stream config changed to
3501 // remove mirror configuration, this function would panic when
3502 // accessing mset.cfg.Mirror fields. Adding this protection in case
3503 // we allow in the future the mirror config to be changed (removed).
3504 if mset.cfg.Mirror == nil {
3505 return errors.New("invalid mirror configuration")
3506 }
3507
3508 // If this is the first time
3509 if mset.mirror == nil {
3510 mset.mirror = &sourceInfo{name: mset.cfg.Mirror.Name}
3511 } else {
3512 mset.cancelSourceInfo(mset.mirror)
3513 mset.mirror.sseq = mset.lseq
3514 }
3515
3516 // If we are no longer the leader stop trying.
3517 if !mset.isLeader() {
3518 return nil
3519 }
3520
3521 mirror := mset.mirror
3522
3523 // We want to throttle here in terms of how fast we request new consumers,
3524 // or if the previous is still in progress.
3525 if last := time.Since(mirror.lreq); last < sourceConsumerRetryThreshold || mirror.sip {
3526 mset.scheduleSetupMirrorConsumerRetry()
3527 return nil
3528 }
3529 mirror.lreq = time.Now()
3530
3531 // Determine subjects etc.
3532 var deliverSubject string
3533 var durableDeliverSubject string
3534 ext := mset.cfg.Mirror.External
3535 if mset.cfg.Mirror.Consumer != nil {
3536 durableDeliverSubject = mset.cfg.Mirror.Consumer.DeliverSubject
3537 mirror.cname = mset.cfg.Mirror.Consumer.Name
3538 } else if ext != nil && ext.DeliverPrefix != _EMPTY_ {
3539 deliverSubject = strings.ReplaceAll(ext.DeliverPrefix+syncSubject(".M"), "..", ".")
3540 } else {
3541 deliverSubject = syncSubject("$JS.M")
3542 }
3543
3544 // Now send off request to create/update our consumer. This will be all API based even in single server mode.
3545 // We calculate durable names apriori so we do not need to save them off.
3546
3547 var state StreamState
3548 mset.store.FastState(&state)
3549
3550 id := mset.createStableConsumerHash()
3551 metadata := map[string]string{}
3552 metadata["_nats.mirror.stream"] = mset.cfg.Name
3553 metadata["_nats.mirror.acc"] = mset.acc.Name
3554 if domain := mset.srv.getOpts().JetStreamDomain; domain != _EMPTY_ {
3555 metadata["_nats.mirror.domain"] = domain
3556 }
3557
3558 req := &CreateConsumerRequest{
3559 Stream: mset.cfg.Mirror.Name,
3560 Config: ConsumerConfig{
3561 Name: fmt.Sprintf("JS_MIRROR_%s", id),
3562 DeliverSubject: deliverSubject,
3563 DeliverPolicy: DeliverByStartSequence,
3564 OptStartSeq: state.LastSeq + 1,
3565 AckPolicy: AckNone,
3566 AckWait: 22 * time.Hour,
3567 MaxDeliver: 1,
3568 Heartbeat: sourceHealthHB,
3569 FlowControl: true,
3570 Direct: true,
3571 Sourcing: true,
3572 InactiveThreshold: sourceHealthCheckInterval,
3573 Metadata: metadata,
3574 },
3575 }
3576
3577 // Only use start optionals on first time.
3578 if state.Msgs == 0 && state.FirstSeq == 0 {
3579 req.Config.OptStartSeq = 0
3580 if mset.cfg.Mirror.OptStartSeq > 0 {
3581 req.Config.OptStartSeq = mset.cfg.Mirror.OptStartSeq
3582 } else if mset.cfg.Mirror.OptStartTime != nil {
3583 req.Config.OptStartTime = mset.cfg.Mirror.OptStartTime
3584 req.Config.DeliverPolicy = DeliverByStartTime
3585 }
3586 }
3587 if req.Config.OptStartSeq == 0 && req.Config.OptStartTime == nil {
3588 // If starting out and lastSeq is 0.
3589 req.Config.DeliverPolicy = DeliverAll
3590 }
3591
3592 // Filters
3593 if mset.cfg.Mirror.FilterSubject != _EMPTY_ {
3594 req.Config.FilterSubject = mset.cfg.Mirror.FilterSubject
3595 mirror.sf = mset.cfg.Mirror.FilterSubject
3596 }
3597
3598 if lst := len(mset.cfg.Mirror.SubjectTransforms); lst > 0 {
3599 sfs := make([]string, lst)
3600 trs := make([]*subjectTransform, lst)
3601
3602 for i, tr := range mset.cfg.Mirror.SubjectTransforms {
3603 // will not fail as already checked before that the transform will work
3604 subjectTransform, err := NewSubjectTransform(tr.Source, tr.Destination)
3605 if err != nil {
3606 mset.srv.Errorf("Unable to get transform for mirror consumer: %v", err)
3607 }
3608 sfs[i] = tr.Source
3609 trs[i] = subjectTransform
3610 }
3611 mirror.sfs = sfs
3612 mirror.trs = trs
3613 // If there was no explicit FilterSubject defined and we have a single
3614 // subject transform, use Config.FilterSubject instead of FilterSubjects
3615 // so that we can use the extended consumer create API down below.
3616 if req.Config.FilterSubject == _EMPTY_ && len(sfs) == 1 {
3617 req.Config.FilterSubject = sfs[0]
3618 } else {
3619 req.Config.FilterSubjects = sfs
3620 }
3621 }
3622
3623 newReplySubscription := func() (string, chan *JSApiConsumerCreateResponse, *subscription, error) {
3624 respCh := make(chan *JSApiConsumerCreateResponse, 1)
3625 reply := infoReplySubject()
3626 crSub, err := mset.subscribeInternal(reply, func(sub *subscription, c *client, _ *Account, subject, reply string, rmsg []byte) {
3627 _, msg := c.msgParts(rmsg)
3628
3629 var ccr JSApiConsumerCreateResponse
3630 if err := json.Unmarshal(msg, &ccr); err != nil {
3631 c.Warnf("JetStream bad mirror consumer create response: %q", msg)
3632 mset.setMirrorErr(ApiErrors[JSInvalidJSONErr])
3633 return
3634 }
3635 select {
3636 case respCh <- &ccr:
3637 default:
3638 }
3639 })
3640 return reply, respCh, crSub, err
3641 }
3642 reply, respCh, crSub, err := newReplySubscription()
3643 if err != nil {
3644 mirror.err = NewJSMirrorConsumerSetupFailedError(err, Unless(err))
3645 mset.scheduleSetupMirrorConsumerRetry()
3646 return nil
3647 }
3648
3649 generateSubject := func() (subject string) {
3650 if durableDeliverSubject != _EMPTY_ {
3651 // If we're using a pre-existing consumer, we'll send a consumer reset request instead.
3652 subject = fmt.Sprintf(JSApiConsumerResetT, mset.cfg.Mirror.Name, mirror.cname)
3653 } else if req.Config.FilterSubject != _EMPTY_ {
3654 subject = fmt.Sprintf(JSApiConsumerCreateExT, mset.cfg.Mirror.Name, req.Config.Name, req.Config.FilterSubject)
3655 } else {
3656 subject = fmt.Sprintf(JSApiConsumerCreateT, mset.cfg.Mirror.Name)
3657 }
3658 if ext != nil {
3659 subject = strings.Replace(subject, JSApiPrefix, ext.ApiPrefix, 1)
3660 subject = strings.ReplaceAll(subject, "..", ".")
3661 }
3662 return subject
3663 }
3664 subject := generateSubject()
3665
3666 // Reset
3667 mirror.msgs = nil
3668 mirror.err = nil
3669 mirror.sip = true
3670
3671 if durableDeliverSubject != _EMPTY_ {
3672 // Send the consumer reset request
3673 mset.outq.send(newJSPubMsg(subject, _EMPTY_, reply, nil, nil, nil, 0))
3674 } else {
3675 // Marshal now that we are done with `req`.
3676 b, _ := json.Marshal(req)
3677
3678 // Send the consumer create request
3679 // Confirm the server supports API level 4, which contains durable sourcing, AckFlowControl, and consumer reset.
3680 hdr := genHeader(nil, JSRequiredApiLevel, "4")
3681 mset.outq.send(newJSPubMsg(subject, _EMPTY_, reply, hdr, b, nil, 0))
3682 }
3683
3684 go func() {
3685
3686 var retry bool
3687 defer func() {
3688 mset.mu.Lock()
3689 // Check that this is still valid and if so, clear the "setup in progress" flag.
3690 if mset.mirror != nil {
3691 mset.mirror.sip = false
3692 // If we need to retry, schedule now
3693 // If sub is not nil means we re-established somewhere else so do not re-attempt here.
3694 if retry && mset.mirror.sub == nil {
3695 mset.mirror.fails++
3696 // Cancel here since we can not do anything with this consumer at this point.
3697 mset.cancelSourceInfo(mset.mirror)
3698 mset.scheduleSetupMirrorConsumerRetry()
3699 } else {
3700 // Clear on success.
3701 mset.mirror.fails = 0
3702 }
3703 }
3704 mset.mu.Unlock()
3705 }()
3706
3707 // Wait for previous processMirrorMsgs go routine to be completely done.
3708 // If none is running, this will not block.
3709 mset.mu.Lock()
3710 if mset.mirror == nil {
3711 // Mirror config has been removed.
3712 mset.unsubscribe(crSub)
3713 mset.mu.Unlock()
3714 return
3715 }
3716 wg := &mset.mirror.wg
3717 mset.mu.Unlock()
3718 wg.Wait()
3719
3720 SELECT:
3721 select {
3722 case ccr := <-respCh:
3723 mset.mu.Lock()
3724 // Mirror config has been removed.
3725 if mset.mirror == nil {
3726 mset.unsubscribe(crSub)
3727 mset.mu.Unlock()
3728 return
3729 }
3730 ready := sync.WaitGroup{}
3731 mirror := mset.mirror
3732 mirror.err = nil
3733
3734 if ccr.Error != nil || ccr.ConsumerInfo == nil || ccr.ConsumerInfo.Config == nil {
3735 // If the responding server doesn't support sourcing consumers, retry without it.
3736 if req.Config.Sourcing && ccr.Error != nil &&
3737 (ccr.Error.ErrCode == uint16(JSRequiredApiLevelErr) || ccr.Error.ErrCode == uint16(JSInvalidJSONErr)) {
3738 // Unset for retry.
3739 req.Config.Sourcing = false
3740 // Specify a unique consumer name, as the other end will not know to do this.
3741 req.Config.Name = fmt.Sprintf("JS_MIRROR_%s_%s", id, createConsumerName())
3742 b, _ := json.Marshal(req)
3743 // Regenerate subject since the previous name could've been included in it.
3744 subject = generateSubject()
3745 // Recreate the reply subscription so we don't get stale responses from other servers.
3746 mset.unsubscribe(crSub)
3747 if reply, respCh, crSub, err = newReplySubscription(); err != nil {
3748 mirror.err = NewJSMirrorConsumerSetupFailedError(err, Unless(err))
3749 retry = true
3750 mset.mu.Unlock()
3751 return
3752 }
3753 mset.outq.send(newJSPubMsg(subject, _EMPTY_, reply, nil, b, nil, 0))
3754 mset.mu.Unlock()
3755 goto SELECT
3756 }
3757 mset.unsubscribe(crSub)
3758 cerr := ccr.Error
3759 if cerr == nil {
3760 cerr = NewJSMirrorConsumerSetupFailedError(errors.New("invalid consumer create response"))
3761 }
3762 mset.srv.Warnf("JetStream error response for create mirror consumer: %+v", cerr)
3763 mirror.err = cerr
3764 // Let's retry as soon as possible, but we are gated by sourceConsumerRetryThreshold
3765 retry = true
3766 mset.mu.Unlock()
3767 return
3768 }
3769
3770 // If using durable sourcing, we need the consumer to use acks based on flow control.
3771 if durableDeliverSubject != _EMPTY_ && ccr.ConsumerInfo.Config.AckPolicy != AckFlowControl {
3772 mset.unsubscribe(crSub)
3773 mirror.err = NewJSMirrorConsumerRequiresAckFCError()
3774 retry = true
3775 mset.mu.Unlock()
3776 return
3777 }
3778
3779 // We can now unsubscribe.
3780 mset.unsubscribe(crSub)
3781
3782 // Setup actual subscription to process messages from our source.
3783 qname := fmt.Sprintf("[ACC:%s] stream mirror '%s' of '%s' msgs", mset.acc.Name, mset.cfg.Name, mset.cfg.Mirror.Name)
3784 // Create a new queue each time
3785 mirror.msgs = newIPQueue[*inMsg](mset.srv, qname)
3786 msgs := mirror.msgs
3787 if durableDeliverSubject != _EMPTY_ {
3788 deliverSubject = durableDeliverSubject
3789 } else {
3790 deliverSubject = ccr.ConsumerInfo.Config.DeliverSubject
3791 }
3792 sub, err := mset.subscribeInternal(deliverSubject, func(sub *subscription, c *client, _ *Account, subject, reply string, rmsg []byte) {
3793 hdr, msg := c.msgParts(copyBytes(rmsg)) // Need to copy.
3794 if len(hdr) > 0 {
3795 // Remove any Nats-Expected- headers as we don't want to validate them.
3796 hdr = removeHeaderIfPrefixPresent(hdr, "Nats-Expected-")
3797 // Remove any Nats-Batch- headers, batching is not supported when mirroring.
3798 hdr = removeHeaderIfPrefixPresent(hdr, "Nats-Batch-")
3799 }
3800 mset.queueInbound(msgs, subject, reply, hdr, msg, nil, nil)
3801 mirror.last.Store(time.Now().UnixNano())
3802 })
3803 if err != nil {
3804 mirror.err = NewJSMirrorConsumerSetupFailedError(err, Unless(err))
3805 retry = true
3806 mset.mu.Unlock()
3807 return
3808 }
3809 // Save our sub.
3810 mirror.sub = sub
3811
3812 // Check if we need to skip messages.
3813 // Re-capture state since the previous may be stale.
3814 state = StreamState{}
3815 mset.store.FastState(&state)
3816 if state.LastSeq < ccr.ConsumerInfo.Delivered.Stream {
3817 // Local helper: abort consumer setup, leaving the mirror in its
3818 // pre-setup state so the retry path can re-create it cleanly.
3819 failSetup := func(setupErr error) {
3820 mset.cancelSourceInfo(mirror)
3821 mirror.err = NewJSMirrorConsumerSetupFailedError(setupErr, Unless(setupErr))
3822 retry = true
3823 mset.mu.Unlock()
3824 }
3825 // Check to see if delivered is past our last and we have no msgs. This will help the
3826 // case when mirroring a stream that has a very high starting sequence number.
3827 if state.Msgs == 0 && ccr.ConsumerInfo.Delivered.Stream > state.LastSeq {
3828 if _, err := mset.store.PurgeEx(_EMPTY_, ccr.ConsumerInfo.Delivered.Stream+1, 0); err != nil {
3829 failSetup(err)
3830 return
3831 }
3832 mset.lseq = ccr.ConsumerInfo.Delivered.Stream
3833 } else if err := mset.skipMsgs(state.LastSeq+1, ccr.ConsumerInfo.Delivered.Stream); err != nil {
3834 failSetup(err)
3835 return
3836 }
3837 }
3838
3839 // Capture consumer name.
3840 mirror.cname = ccr.ConsumerInfo.Name
3841 mirror.dseq = 0
3842 mirror.sseq = max(ccr.ConsumerInfo.Delivered.Stream, state.LastSeq)
3843 mirror.qch = make(chan struct{})
3844 mirror.wg.Add(1)
3845 ready.Add(1)
3846 if !mset.srv.startGoRoutine(
3847 func() { mset.processMirrorMsgs(mirror, &ready) },
3848 pprofLabels{
3849 "type": "mirror",
3850 "account": mset.acc.Name,
3851 "stream": mset.cfg.Name,
3852 "consumer": mirror.cname,
3853 },
3854 ) {
3855 mirror.wg.Done()
3856 ready.Done()
3857 }
3858 mset.mu.Unlock()
3859 ready.Wait()
3860 case <-time.After(srcConsumerWaitTime):
3861 mset.unsubscribe(crSub)
3862 // We already waited 30 seconds, let's retry now.
3863 retry = true
3864 }
3865 }()
3866
3867 return nil
3868 }
3869
3870 func (mset *stream) streamSource(iname string) *StreamSource {
3871 for _, ssi := range mset.cfg.Sources {
3872 if ssi.iname == iname {
3873 return ssi
3874 }
3875 }
3876 return nil
3877 }
3878
3879 // Lock should be held.
3880 func (mset *stream) retrySourceConsumerAtSeq(iName string, seq uint64) {
3881 s := mset.srv
3882
3883 s.Debugf("Retrying source consumer for '%s > %s'", mset.acc.Name, mset.cfg.Name)
3884
3885 // setupSourceConsumer will check that the source is still configured.
3886 mset.setupSourceConsumer(iName, seq, time.Time{})
3887 }
3888
3889 // Lock should be held.
3890 func (mset *stream) cancelSourceConsumer(iname string) {
3891 if si := mset.sources[iname]; si != nil {
3892 mset.cancelSourceInfo(si)
3893 si.sseq, si.dseq = 0, 0
3894 }
3895 }
3896
3897 // The `si` has been verified to be not nil. The sourceInfo's sub will
3898 // be unsubscribed and set to nil (if not already done) and the
3899 // cname will be reset. The message processing's go routine quit channel
3900 // will be closed if still opened.
3901 //
3902 // Lock should be held
3903 func (mset *stream) cancelSourceInfo(si *sourceInfo) {
3904 if si.sub != nil {
3905 mset.unsubscribe(si.sub)
3906 si.sub = nil
3907 }
3908 mset.removeInternalConsumer(si)
3909 if si.qch != nil {
3910 close(si.qch)
3911 si.qch = nil
3912 }
3913 if si.msgs != nil {
3914 si.msgs.drain()
3915 si.msgs.unregister()
3916 }
3917 // If we have a schedule setup go ahead and delete that.
3918 if t := mset.sourceSetupSchedules[si.iname]; t != nil {
3919 t.Stop()
3920 delete(mset.sourceSetupSchedules, si.iname)
3921 }
3922 }
3923
3924 const sourceConsumerRetryThreshold = 2 * time.Second
3925
3926 // This is the main function to call when needing to setup a new consumer for the source.
3927 // It actually only does the scheduling of the execution of trySetupSourceConsumer in order to implement retry backoff
3928 // and throttle the number of requests.
3929 // Lock should be held.
3930 func (mset *stream) setupSourceConsumer(iname string, seq uint64, startTime time.Time) {
3931 if mset.sourceSetupSchedules == nil {
3932 mset.sourceSetupSchedules = map[string]*time.Timer{}
3933 }
3934
3935 if _, ok := mset.sourceSetupSchedules[iname]; ok {
3936 // If there is already a timer scheduled, we don't need to do anything.
3937 return
3938 }
3939
3940 si := mset.sources[iname]
3941 if si == nil || si.sip { // if sourceInfo was removed or setup is in progress, nothing to do
3942 return
3943 }
3944
3945 // First calculate the delay until the next time we can
3946 var scheduleDelay time.Duration
3947
3948 if !si.lreq.IsZero() { // it's not the very first time we are called, compute the delay
3949 // We want to throttle here in terms of how fast we request new consumers
3950 if sinceLast := time.Since(si.lreq); sinceLast < sourceConsumerRetryThreshold {
3951 scheduleDelay = sourceConsumerRetryThreshold - sinceLast
3952 }
3953 // Is it a retry? If so, add a backoff
3954 if si.fails > 0 {
3955 scheduleDelay += calculateRetryBackoff(si.fails)
3956 }
3957 }
3958
3959 // Always add some jitter
3960 scheduleDelay += time.Duration(rand.Intn(int(100*time.Millisecond))) + 100*time.Millisecond
3961
3962 // Schedule the call to trySetupSourceConsumer
3963 mset.sourceSetupSchedules[iname] = time.AfterFunc(scheduleDelay, func() {
3964 mset.mu.Lock()
3965 defer mset.mu.Unlock()
3966
3967 delete(mset.sourceSetupSchedules, iname)
3968 mset.trySetupSourceConsumer(iname, seq, startTime)
3969 })
3970 }
3971
3972 // This is where we will actually try to create a new consumer for the source
3973 // Lock should be held.
3974 func (mset *stream) trySetupSourceConsumer(iname string, seq uint64, startTime time.Time) {
3975 // Ignore if closed or not leader.
3976 if mset.closed.Load() || !mset.isLeader() {
3977 return
3978 }
3979
3980 si := mset.sources[iname]
3981 if si == nil {
3982 return
3983 }
3984
3985 // Cancel previous instance if applicable
3986 mset.cancelSourceInfo(si)
3987
3988 ssi := mset.streamSource(iname)
3989 if ssi == nil {
3990 return
3991 }
3992
3993 si.lreq = time.Now()
3994
3995 // Determine subjects etc.
3996 var deliverSubject string
3997 var durableDeliverSubject string
3998 ext := ssi.External
3999 if ssi.Consumer != nil {
4000 durableDeliverSubject = ssi.Consumer.DeliverSubject
4001 si.cname = ssi.Consumer.Name
4002 } else if ext != nil && ext.DeliverPrefix != _EMPTY_ {
4003 deliverSubject = strings.ReplaceAll(ext.DeliverPrefix+syncSubject(".S"), "..", ".")
4004 } else {
4005 deliverSubject = syncSubject("$JS.S")
4006 }
4007
4008 id := mset.createSourcingConsumerHash(ssi, mset.cfg.Sources)
4009 metadata := map[string]string{}
4010 metadata["_nats.src.stream"] = mset.cfg.Name
4011 metadata["_nats.src.acc"] = mset.acc.Name
4012 if domain := mset.srv.getOpts().JetStreamDomain; domain != _EMPTY_ {
4013 metadata["_nats.src.domain"] = domain
4014 }
4015
4016 req := &CreateConsumerRequest{
4017 Stream: si.name,
4018 Config: ConsumerConfig{
4019 Name: fmt.Sprintf("JS_SRC_%s", id),
4020 DeliverSubject: deliverSubject,
4021 AckPolicy: AckNone,
4022 AckWait: 22 * time.Hour,
4023 MaxDeliver: 1,
4024 Heartbeat: sourceHealthHB,
4025 FlowControl: true,
4026 Direct: true,
4027 Sourcing: true,
4028 InactiveThreshold: sourceHealthCheckInterval,
4029 Metadata: metadata,
4030 },
4031 }
4032
4033 // If starting, check any configs.
4034 if !startTime.IsZero() && seq > 1 {
4035 req.Config.OptStartTime = &startTime
4036 req.Config.DeliverPolicy = DeliverByStartTime
4037 } else if seq <= 1 {
4038 if ssi.OptStartSeq > 0 {
4039 req.Config.OptStartSeq = ssi.OptStartSeq
4040 req.Config.DeliverPolicy = DeliverByStartSequence
4041 } else {
4042 // We have not recovered state so check that configured time is less that our first seq time.
4043 var state StreamState
4044 mset.store.FastState(&state)
4045 if ssi.OptStartTime != nil {
4046 if !state.LastTime.IsZero() && ssi.OptStartTime.Before(state.LastTime) {
4047 req.Config.OptStartTime = &state.LastTime
4048 } else {
4049 req.Config.OptStartTime = ssi.OptStartTime
4050 }
4051 req.Config.DeliverPolicy = DeliverByStartTime
4052 } else if state.FirstSeq > 1 && !state.LastTime.IsZero() {
4053 req.Config.OptStartTime = &state.LastTime
4054 req.Config.DeliverPolicy = DeliverByStartTime
4055 }
4056 }
4057
4058 } else {
4059 req.Config.OptStartSeq = seq
4060 req.Config.DeliverPolicy = DeliverByStartSequence
4061 }
4062 // Filters
4063 if ssi.FilterSubject != _EMPTY_ {
4064 req.Config.FilterSubject = ssi.FilterSubject
4065 }
4066
4067 var filterSubjects []string
4068 for _, tr := range ssi.SubjectTransforms {
4069 filterSubjects = append(filterSubjects, tr.Source)
4070 }
4071 req.Config.FilterSubjects = filterSubjects
4072
4073 newReplySubscription := func() (string, chan *JSApiConsumerCreateResponse, *subscription, error) {
4074 respCh := make(chan *JSApiConsumerCreateResponse, 1)
4075 reply := infoReplySubject()
4076 crSub, err := mset.subscribeInternal(reply, func(sub *subscription, c *client, _ *Account, subject, reply string, rmsg []byte) {
4077 _, msg := c.msgParts(rmsg)
4078 var ccr JSApiConsumerCreateResponse
4079 if err := json.Unmarshal(msg, &ccr); err != nil {
4080 c.Warnf("JetStream bad source consumer create response: %q", msg)
4081 return
4082 }
4083 select {
4084 case respCh <- &ccr:
4085 default:
4086 }
4087 })
4088 return reply, respCh, crSub, err
4089 }
4090 reply, respCh, crSub, err := newReplySubscription()
4091 if err != nil {
4092 si.err = NewJSSourceConsumerSetupFailedError(err, Unless(err))
4093 mset.setupSourceConsumer(iname, seq, startTime)
4094 return
4095 }
4096
4097 generateSubject := func() (subject string) {
4098 if durableDeliverSubject != _EMPTY_ {
4099 // If we're using a pre-existing consumer, we'll send a consumer reset request instead.
4100 subject = fmt.Sprintf(JSApiConsumerResetT, si.name, si.cname)
4101 } else if req.Config.FilterSubject != _EMPTY_ {
4102 subject = fmt.Sprintf(JSApiConsumerCreateExT, si.name, req.Config.Name, req.Config.FilterSubject)
4103 } else if len(req.Config.FilterSubjects) == 1 {
4104 // It is necessary to switch to using FilterSubject here as the extended consumer
4105 // create API checks for it, so as to not accidentally allow multiple filtered subjects.
4106 req.Config.FilterSubject = req.Config.FilterSubjects[0]
4107 req.Config.FilterSubjects = nil
4108 subject = fmt.Sprintf(JSApiConsumerCreateExT, si.name, req.Config.Name, req.Config.FilterSubject)
4109 } else {
4110 subject = fmt.Sprintf(JSApiConsumerCreateT, si.name)
4111 }
4112 if ext != nil {
4113 subject = strings.Replace(subject, JSApiPrefix, ext.ApiPrefix, 1)
4114 subject = strings.ReplaceAll(subject, "..", ".")
4115 }
4116 return subject
4117 }
4118 subject := generateSubject()
4119
4120 // Reset
4121 si.msgs = nil
4122 si.err = nil
4123 si.sip = true
4124
4125 if durableDeliverSubject != _EMPTY_ {
4126 // Send the consumer reset request
4127 mset.outq.send(newJSPubMsg(subject, _EMPTY_, reply, nil, nil, nil, 0))
4128 } else {
4129 // Marshal request.
4130 b, _ := json.Marshal(req)
4131
4132 // Send the consumer create request
4133 // Confirm the server supports API level 4, which contains durable sourcing, AckFlowControl, and consumer reset.
4134 hdr := genHeader(nil, JSRequiredApiLevel, "4")
4135 mset.outq.send(newJSPubMsg(subject, _EMPTY_, reply, hdr, b, nil, 0))
4136 }
4137
4138 go func() {
4139
4140 var retry bool
4141 defer func() {
4142 mset.mu.Lock()
4143 // Check that this is still valid and if so, clear the "setup in progress" flag.
4144 if si := mset.sources[iname]; si != nil {
4145 si.sip = false
4146 // If we need to retry, schedule now
4147 // If sub is not nil means we re-established somewhere else so do not re-attempt here.
4148 if retry && si.sub == nil {
4149 si.fails++
4150 // Cancel here since we can not do anything with this consumer at this point.
4151 mset.cancelSourceInfo(si)
4152 mset.setupSourceConsumer(iname, seq, startTime)
4153 } else {
4154 // Clear on success.
4155 si.fails = 0
4156 }
4157 }
4158 mset.mu.Unlock()
4159 }()
4160
4161 SELECT:
4162 select {
4163 case ccr := <-respCh:
4164 mset.mu.Lock()
4165 // Check that it has not been removed or canceled (si.sub would be nil)
4166 if si := mset.sources[iname]; si == nil {
4167 mset.unsubscribe(crSub)
4168 } else {
4169 si.err = nil
4170
4171 if ccr.Error != nil || ccr.ConsumerInfo == nil || ccr.ConsumerInfo.Config == nil {
4172 // If the responding server doesn't support sourcing consumers, retry without it.
4173 if req.Config.Sourcing && ccr.Error != nil &&
4174 (ccr.Error.ErrCode == uint16(JSRequiredApiLevelErr) || ccr.Error.ErrCode == uint16(JSInvalidJSONErr)) {
4175 // Unset for retry.
4176 req.Config.Sourcing = false
4177 // Specify a unique consumer name, as the other end will not know to do this.
4178 req.Config.Name = fmt.Sprintf("JS_SRC_%s_%s", id, createConsumerName())
4179 b, _ := json.Marshal(req)
4180 // Regenerate subject since the previous name could've been included in it.
4181 subject = generateSubject()
4182 // Recreate the reply subscription so we don't get stale responses from other servers.
4183 mset.unsubscribe(crSub)
4184 if reply, respCh, crSub, err = newReplySubscription(); err != nil {
4185 si.err = NewJSSourceConsumerSetupFailedError(err, Unless(err))
4186 retry = true
4187 mset.mu.Unlock()
4188 return
4189 }
4190 mset.outq.send(newJSPubMsg(subject, _EMPTY_, reply, nil, b, nil, 0))
4191 mset.mu.Unlock()
4192 goto SELECT
4193 }
4194 mset.unsubscribe(crSub)
4195 // Note: this warning can happen a few times when starting up the server when sourcing streams are
4196 // defined, this is normal as the streams are re-created in no particular order and it is possible
4197 // that a stream sourcing another could come up before all of its sources have been recreated.
4198 cerr := ccr.Error
4199 if cerr == nil {
4200 cerr = NewJSSourceConsumerSetupFailedError(errors.New("invalid consumer create response"))
4201 }
4202 mset.srv.Warnf("JetStream error response for stream %s create source consumer %s: %+v", mset.cfg.Name, si.name, cerr)
4203 si.err = cerr
4204 // Let's retry as soon as possible, but we are gated by sourceConsumerRetryThreshold
4205 retry = true
4206 mset.mu.Unlock()
4207 return
4208 }
4209
4210 // If using durable sourcing, we need the consumer to use acks based on flow control.
4211 if durableDeliverSubject != _EMPTY_ && ccr.ConsumerInfo.Config.AckPolicy != AckFlowControl {
4212 mset.unsubscribe(crSub)
4213 si.err = NewJSSourceConsumerRequiresAckFCError()
4214 retry = true
4215 mset.mu.Unlock()
4216 return
4217 }
4218
4219 // We can now unsubscribe.
4220 mset.unsubscribe(crSub)
4221
4222 // Check if our shared msg queue and go routine is running or not.
4223 if mset.smsgs == nil {
4224 qname := fmt.Sprintf("[ACC:%s] stream sources '%s' msgs", mset.acc.Name, mset.cfg.Name)
4225 mset.smsgs = newIPQueue[*inMsg](mset.srv, qname)
4226 mset.srv.startGoRoutine(func() { mset.processAllSourceMsgs() },
4227 pprofLabels{
4228 "type": "source",
4229 "account": mset.acc.Name,
4230 "stream": mset.cfg.Name,
4231 },
4232 )
4233 }
4234
4235 // Setup actual subscription to process messages from our source.
4236 if si.sseq < ccr.ConsumerInfo.Delivered.Stream {
4237 si.sseq = ccr.ConsumerInfo.Delivered.Stream
4238 }
4239 // Capture consumer name.
4240 si.cname = ccr.ConsumerInfo.Name
4241
4242 // Do not set si.sseq to seq here. si.sseq will be set in processInboundSourceMsg
4243 si.dseq = 0
4244 si.qch = make(chan struct{})
4245 // Set the last seen as now so that we don't fail at the first check.
4246 si.last.Store(time.Now().UnixNano())
4247
4248 msgs := mset.smsgs
4249 if durableDeliverSubject != _EMPTY_ {
4250 deliverSubject = durableDeliverSubject
4251 } else {
4252 deliverSubject = ccr.ConsumerInfo.Config.DeliverSubject
4253 }
4254 sub, err := mset.subscribeInternal(deliverSubject, func(sub *subscription, c *client, _ *Account, subject, reply string, rmsg []byte) {
4255 hdr, msg := c.msgParts(copyBytes(rmsg)) // Need to copy.
4256 mset.queueInbound(msgs, subject, reply, hdr, msg, si, nil)
4257 si.last.Store(time.Now().UnixNano())
4258 })
4259 if err != nil {
4260 si.err = NewJSSourceConsumerSetupFailedError(err, Unless(err))
4261 retry = true
4262 mset.mu.Unlock()
4263 return
4264 }
4265 // Save our sub.
4266 si.sub = sub
4267 }
4268 mset.mu.Unlock()
4269 case <-time.After(srcConsumerWaitTime):
4270 mset.unsubscribe(crSub)
4271 // We already waited 30 seconds, let's retry now.
4272 retry = true
4273 }
4274 }()
4275 }
4276
4277 // This will process all inbound source msgs.
4278 // We mux them into one go routine to avoid lock contention and high cpu and thread thrashing.
4279 // TODO(dlc) make this more then one and pin sources to one of a group.
4280 func (mset *stream) processAllSourceMsgs() {
4281 s := mset.srv
4282 defer s.grWG.Done()
4283
4284 mset.mu.RLock()
4285 msgs, qch := mset.smsgs, mset.qch
4286 mset.mu.RUnlock()
4287
4288 t := time.NewTicker(sourceHealthCheckInterval)
4289 defer t.Stop()
4290
4291 // When we detect we are no longer leader, we will cleanup.
4292 // Should always return right after this is called.
4293 cleanUp := func() {
4294 mset.mu.Lock()
4295 defer mset.mu.Unlock()
4296 for _, si := range mset.sources {
4297 mset.cancelSourceConsumer(si.iname)
4298 }
4299 mset.smsgs.drain()
4300 mset.smsgs.unregister()
4301 mset.smsgs = nil
4302 }
4303
4304 for {
4305 select {
4306 case <-s.quitCh:
4307 return
4308 case <-qch:
4309 return
4310 case <-msgs.ch:
4311 ims := msgs.pop()
4312 for _, im := range ims {
4313 if !mset.processInboundSourceMsg(im.si, im) {
4314 // If we are no longer leader bail.
4315 if !mset.IsLeader() {
4316 msgs.recycle(&ims)
4317 cleanUp()
4318 return
4319 }
4320 break
4321 }
4322 im.returnToPool()
4323 }
4324 msgs.recycle(&ims)
4325 case <-t.C:
4326 // If we are no longer leader bail.
4327 if !mset.IsLeader() {
4328 cleanUp()
4329 return
4330 }
4331
4332 // Check health of all sources.
4333 var stalled []*sourceInfo
4334 mset.mu.RLock()
4335 for _, si := range mset.sources {
4336 if time.Since(time.Unix(0, si.last.Load())) > sourceHealthCheckInterval {
4337 stalled = append(stalled, si)
4338 }
4339 }
4340 numSources := len(mset.sources)
4341 mset.mu.RUnlock()
4342
4343 // This can happen on an update when no longer have sources.
4344 if numSources == 0 {
4345 cleanUp()
4346 return
4347 }
4348
4349 // We do not want to block here so do in separate Go routine.
4350 if len(stalled) > 0 {
4351 go func() {
4352 mset.mu.Lock()
4353 defer mset.mu.Unlock()
4354 for _, si := range stalled {
4355 mset.setupSourceConsumer(si.iname, si.sseq+1, time.Time{})
4356 }
4357 }()
4358 }
4359 }
4360 }
4361 }
4362
4363 // isControlMsg determines if this is a control message.
4364 func (m *inMsg) isControlMsg() bool {
4365 return len(m.msg) == 0 && len(m.hdr) > 0 && bytes.HasPrefix(m.hdr, []byte("NATS/1.0 100 "))
4366 }
4367
4368 // Sends a reply to a flow control request.
4369 // Lock should be held.
4370 func (mset *stream) sendFlowControlReply(reply string, hdr []byte) {
4371 if mset.isLeader() && mset.outq != nil {
4372 dseq := parseInt64(sliceHeader(JSLastConsumerSeq, hdr))
4373 sseq := parseInt64(sliceHeader(JSLastStreamSeq, hdr))
4374
4375 // If we're responding to flow control without being delivered messages (for example after a restart),
4376 // we'll only have the stream sequence.
4377 if sseq > 0 {
4378 if dseq < 0 {
4379 dseq = 0
4380 }
4381 const t = "NATS/1.0\r\n%s: %d\r\n%s: %d\r\n\r\n"
4382 hdr = fmt.Appendf(nil, t, JSLastConsumerSeq, dseq, JSLastStreamSeq, sseq)
4383 mset.outq.send(newJSPubMsg(reply, _EMPTY_, _EMPTY_, hdr, nil, nil, 0))
4384 } else {
4385 mset.outq.sendMsg(reply, nil)
4386 }
4387 }
4388 }
4389
4390 // handleFlowControl will properly handle flow control messages for both R==1 and R>1.
4391 // Lock should be held.
4392 func (mset *stream) handleFlowControl(m *inMsg, dseq, sseq uint64) {
4393 // If we are clustered we will send the flow control message through the replication stack.
4394 if mset.isClustered() {
4395 // Append the current delivery and stream sequences, to be sent after replication.
4396 m.hdr = genHeader(m.hdr, JSLastConsumerSeq, strconv.FormatUint(dseq, 10))
4397 m.hdr = genHeader(m.hdr, JSLastStreamSeq, strconv.FormatUint(sseq, 10))
4398 mset.node.Propose(mset.term, encodeStreamMsg(_EMPTY_, m.rply, m.hdr, nil, 0, 0, false))
4399 } else {
4400 const t = "NATS/1.0\r\n%s: %d\r\n%s: %d\r\n\r\n"
4401 hdr := fmt.Appendf(nil, t, JSLastConsumerSeq, dseq, JSLastStreamSeq, sseq)
4402 mset.outq.send(newJSPubMsg(m.rply, _EMPTY_, _EMPTY_, hdr, nil, nil, 0))
4403 }
4404 }
4405
4406 // processInboundSourceMsg handles processing other stream messages bound for this stream.
4407 func (mset *stream) processInboundSourceMsg(si *sourceInfo, m *inMsg) bool {
4408 mset.mu.Lock()
4409 // If we are no longer the leader cancel this subscriber.
4410 if !mset.isLeader() {
4411 mset.cancelSourceConsumer(si.iname)
4412 mset.mu.Unlock()
4413 return false
4414 }
4415
4416 isControl := m.isControlMsg()
4417 cname := consumerFromAckReply(m.rply)
4418
4419 // Ignore from old subscriptions.
4420 if !si.isCurrentSub(cname) && !isControl {
4421 mset.mu.Unlock()
4422 return false
4423 }
4424
4425 // Check for heartbeats and flow control messages.
4426 if isControl {
4427 var needsRetry bool
4428 // Flow controls have reply subjects.
4429 if m.rply != _EMPTY_ {
4430 mset.handleFlowControl(m, si.dseq, si.sseq)
4431 } else {
4432 // For idle heartbeats make sure we did not miss anything.
4433 if ldseq := parseInt64(sliceHeader(JSLastConsumerSeq, m.hdr)); ldseq > 0 && uint64(ldseq) != si.dseq {
4434 needsRetry = true
4435 mset.retrySourceConsumerAtSeq(si.iname, si.sseq+1)
4436 } else if fcReply := sliceHeader(JSConsumerStalled, m.hdr); len(fcReply) > 0 {
4437 // Other side thinks we are stalled, so send flow control reply.
4438 mset.outq.sendMsg(string(fcReply), nil)
4439 }
4440 }
4441 mset.mu.Unlock()
4442 return !needsRetry
4443 }
4444
4445 sseq, dseq, dc, _, pending := ackReplyInfo(m.rply)
4446
4447 if dc > 1 {
4448 mset.mu.Unlock()
4449 return false
4450 }
4451
4452 // Tracking is done here.
4453 osseq, odseq := si.sseq, si.dseq
4454 if sseq <= si.sseq {
4455 // Ignore older messages.
4456 // If the deliver sequence matches, we only update delivered accounting.
4457 if dseq == si.dseq+1 {
4458 si.dseq++
4459 }
4460 mset.mu.Unlock()
4461 return true
4462 } else if dseq == si.dseq+1 {
4463 si.dseq++
4464 si.sseq = sseq
4465 } else if dseq > si.dseq {
4466 if si.cname == _EMPTY_ {
4467 si.cname = cname
4468 si.dseq, si.sseq = dseq, sseq
4469 } else {
4470 mset.retrySourceConsumerAtSeq(si.iname, si.sseq+1)
4471 mset.mu.Unlock()
4472 return false
4473 }
4474 } else {
4475 mset.mu.Unlock()
4476 return false
4477 }
4478
4479 if pending == 0 {
4480 si.lag = 0
4481 } else {
4482 si.lag = pending - 1
4483 }
4484 node := mset.node
4485 mset.mu.Unlock()
4486
4487 hdr, msg := m.hdr, m.msg
4488
4489 // If we are daisy chained here make sure to remove the original one.
4490 if len(hdr) > 0 {
4491 hdr = removeHeaderIfPresent(hdr, JSStreamSource)
4492 // Remove any Nats-Expected- headers as we don't want to validate them.
4493 hdr = removeHeaderIfPrefixPresent(hdr, "Nats-Expected-")
4494 // Remove any Nats-Batch- headers, batching is not supported when sourcing.
4495 hdr = removeHeaderIfPrefixPresent(hdr, "Nats-Batch-")
4496 }
4497 // Hold onto the origin reply which has all the metadata.
4498 hdr = genHeader(hdr, JSStreamSource, si.genSourceHeader(m.subj, m.rply))
4499
4500 // Do the subject transform for the source if there's one
4501 if len(si.trs) > 0 {
4502 for _, tr := range si.trs {
4503 if tr == nil {
4504 continue
4505 } else {
4506 tsubj, err := tr.Match(m.subj)
4507 if err == nil {
4508 m.subj = tsubj
4509 break
4510 }
4511 }
4512 }
4513 }
4514
4515 var err error
4516 // If we are clustered we need to propose this message to the underlying raft group.
4517 if node != nil {
4518 err = mset.processClusteredInboundMsg(m.subj, _EMPTY_, hdr, msg, nil, true)
4519 } else {
4520 err = mset.processJetStreamMsg(m.subj, _EMPTY_, hdr, msg, 0, 0, nil, true, true)
4521 }
4522 if err != nil {
4523 s := mset.srv
4524 if strings.Contains(err.Error(), "no space left") {
4525 s.Errorf("JetStream out of space, will be DISABLED")
4526 s.ShutdownJetStream()
4527 } else {
4528 mset.mu.RLock()
4529 accName, sname, iName := mset.acc.Name, mset.cfg.Name, si.iname
4530 mset.mu.RUnlock()
4531 // Can happen temporarily all the time during normal operations when the sourcing stream is discard new
4532 // (example use case is for sourcing into a work queue)
4533 // TODO - Maybe improve sourcing to WQ with limit and new to use flow control rather than re-creating the consumer.
4534 discardNew := errors.Is(err, ErrMaxMsgs) || errors.Is(err, ErrMaxBytes) || errors.Is(err, ErrMaxMsgsPerSubject)
4535
4536 // Log some warning for errors.
4537 if !discardNew && !errors.Is(err, errLastSeqMismatch) && !errors.Is(err, errMsgIdDuplicate) {
4538 s.RateLimitWarnf("Error processing inbound source %q for '%s' > '%s': %v",
4539 iName, accName, sname, err)
4540 }
4541
4542 // Duplicates can be skipped, continue to the next message.
4543 if errors.Is(err, errMsgIdDuplicate) {
4544 return true
4545 }
4546
4547 // Do not need to do a full retry that includes finding the last sequence in the stream
4548 // for that source. Just re-create starting with the seq we couldn't store instead.
4549 // Especially if we're replicated, we could have inflight proposals that will not be in our store yet.
4550 mset.mu.Lock()
4551 si.dseq = odseq
4552 si.sseq = osseq
4553 mset.retrySourceConsumerAtSeq(iName, sseq)
4554 mset.mu.Unlock()
4555 }
4556 return false
4557 }
4558
4559 return true
4560 }
4561
4562 // Generate a new (2.10) style source header (stream name, sequence number, source filter, source destination transform).
4563 func (si *sourceInfo) genSourceHeader(orig, reply string) string {
4564 var b strings.Builder
4565 iNameParts := strings.Split(si.iname, " ")
4566
4567 b.WriteString(iNameParts[0])
4568 b.WriteByte(' ')
4569 // Grab sequence as text here from reply subject.
4570 var tsa [expectedNumReplyTokensV2]string
4571 start, tokens := 0, tsa[:0]
4572 for i := 0; i < len(reply); i++ {
4573 if reply[i] == btsep {
4574 tokens, start = append(tokens, reply[start:i]), i+1
4575 }
4576 }
4577 tokens = append(tokens, reply[start:])
4578 seq := "1" // Default
4579 if tokens[0] == "$JS" && tokens[1] == "ACK" {
4580 if len(tokens) == expectedNumReplyTokensV1 {
4581 seq = tokens[5]
4582 } else if len(tokens) >= expectedNumReplyTokensV2 {
4583 seq = tokens[7]
4584 }
4585 }
4586 b.WriteString(seq)
4587
4588 b.WriteByte(' ')
4589 b.WriteString(iNameParts[1])
4590 b.WriteByte(' ')
4591 b.WriteString(iNameParts[2])
4592 b.WriteByte(' ')
4593 b.WriteString(orig)
4594 return b.String()
4595 }
4596
4597 // Original version of header that stored ack reply direct.
4598 func streamAndSeqFromAckReply(reply string) (string, string, uint64) {
4599 tsa := [expectedNumReplyTokensV2]string{}
4600 start, tokens := 0, tsa[:0]
4601 for i := 0; i < len(reply); i++ {
4602 if reply[i] == btsep {
4603 tokens, start = append(tokens, reply[start:i]), i+1
4604 }
4605 }
4606 tokens = append(tokens, reply[start:])
4607 if (len(tokens) != expectedNumReplyTokensV1 && len(tokens) < expectedNumReplyTokensV2) || tokens[0] != "$JS" || tokens[1] != "ACK" {
4608 return _EMPTY_, _EMPTY_, 0
4609 }
4610 offset := 2
4611 if len(tokens) >= expectedNumReplyTokensV2 {
4612 offset = 4
4613 }
4614 return tokens[offset], _EMPTY_, uint64(parseAckReplyNum(tokens[offset+3]))
4615 }
4616
4617 func consumerFromAckReply(reply string) string {
4618 tsa := [expectedNumReplyTokensV2]string{}
4619 start, tokens := 0, tsa[:0]
4620 for i := 0; i < len(reply); i++ {
4621 if reply[i] == btsep {
4622 tokens, start = append(tokens, reply[start:i]), i+1
4623 }
4624 }
4625 tokens = append(tokens, reply[start:])
4626 if (len(tokens) != expectedNumReplyTokensV1 && len(tokens) < expectedNumReplyTokensV2) || tokens[0] != "$JS" || tokens[1] != "ACK" {
4627 return _EMPTY_
4628 }
4629 offset := 3
4630 if len(tokens) >= expectedNumReplyTokensV2 {
4631 offset = 5
4632 }
4633 return tokens[offset]
4634 }
4635
4636 // Extract the stream name, the source index name and the message sequence number from the source header.
4637 // Uses the filter and transform arguments to provide backwards compatibility
4638 func streamAndSeq(shdr string) (string, string, uint64) {
4639 if strings.HasPrefix(shdr, jsAckPre) {
4640 return streamAndSeqFromAckReply(shdr)
4641 }
4642 // New version which is stream index name <SPC> sequence
4643 fields := strings.Split(shdr, " ")
4644 nFields := len(fields)
4645
4646 if nFields != 2 && nFields <= 3 {
4647 return _EMPTY_, _EMPTY_, 0
4648 }
4649
4650 if nFields >= 4 {
4651 return fields[0], strings.Join([]string{fields[0], fields[2], fields[3]}, " "), uint64(parseAckReplyNum(fields[1]))
4652 } else {
4653 return fields[0], _EMPTY_, uint64(parseAckReplyNum(fields[1]))
4654 }
4655
4656 }
4657
4658 // Lock should be held.
4659 func (mset *stream) setStartingSequenceForSources(iNames map[string]struct{}) {
4660 var state StreamState
4661 mset.store.FastState(&state)
4662
4663 // Do not reset sseq here so we can remember when purge/expiration happens.
4664 if state.Msgs == 0 {
4665 for iName := range iNames {
4666 si := mset.sources[iName]
4667 if si == nil {
4668 continue
4669 } else {
4670 si.dseq = 0
4671 }
4672 }
4673 return
4674 }
4675
4676 // From the provided list of sources, we build a sublist that contains
4677 // the interested filters (including transforms). As we figure out the
4678 // starting sequence for each source, we will eliminate the source from
4679 // the map and then refresh the sublist, which in turn makes the sublist
4680 // ideally more specific. This allows LoadPrevMsgsMulti to work most
4681 // effectively.
4682 // Because this is a SimpleSublist we can't just remove the entries per
4683 // source so we have no other option but to rebuild it from scratch, but
4684 // this is cheap enough to do so not the end of the world.
4685 var sl *gsl.SimpleSublist
4686 refreshSublist := func() {
4687 sl = gsl.NewSimpleSublist()
4688 for iName := range iNames {
4689 si := mset.sources[iName]
4690 if si == nil {
4691 continue
4692 }
4693 if si.sf == _EMPTY_ {
4694 sl.Insert(fwcs, struct{}{})
4695 } else {
4696 sl.Insert(si.sf, struct{}{})
4697 }
4698 for _, sf := range si.sfs {
4699 if sf == _EMPTY_ {
4700 sl.Insert(fwcs, struct{}{})
4701 } else {
4702 sl.Insert(sf, struct{}{})
4703 }
4704 }
4705 }
4706 }
4707 refreshSublist()
4708
4709 var smv StoreMsg
4710 for last := state.LastSeq; ; {
4711 sm, seq, err := mset.store.LoadPrevMsgMulti(sl, last, &smv)
4712 if err == ErrStoreEOF || err != nil {
4713 break
4714 }
4715 last = seq - 1
4716 if len(sm.hdr) == 0 {
4717 continue
4718 }
4719 ss := sliceHeader(JSStreamSource, sm.hdr)
4720 if len(ss) == 0 {
4721 continue
4722 }
4723
4724 streamName, indexName, sseq := streamAndSeq(bytesToString(ss))
4725 if _, ok := iNames[indexName]; ok {
4726 si := mset.sources[indexName]
4727 si.sseq = sseq
4728 si.dseq = 0
4729 delete(iNames, indexName)
4730 refreshSublist()
4731 } else if indexName == _EMPTY_ && streamName != _EMPTY_ {
4732 for iName := range iNames {
4733 // TODO streamSource is a linear walk, to optimize later
4734 if si := mset.sources[iName]; si != nil && streamName == si.name ||
4735 (mset.streamSource(iName).External != nil && streamName == si.name+":"+getHash(mset.streamSource(iName).External.ApiPrefix)) {
4736 si.sseq = sseq
4737 si.dseq = 0
4738 delete(iNames, iName)
4739 refreshSublist()
4740 break
4741 }
4742 }
4743 }
4744 if len(iNames) == 0 {
4745 break
4746 }
4747 }
4748 }
4749
4750 // Resets the SourceInfo for all the sources
4751 // lock should be held.
4752 func (mset *stream) resetSourceInfo() {
4753 // Reset if needed.
4754 mset.stopSourceConsumers()
4755 mset.sources = make(map[string]*sourceInfo)
4756
4757 for _, ssi := range mset.cfg.Sources {
4758 if ssi.iname == _EMPTY_ {
4759 ssi.setIndexName()
4760 }
4761
4762 var si *sourceInfo
4763
4764 if len(ssi.SubjectTransforms) == 0 {
4765 si = &sourceInfo{name: ssi.Name, iname: ssi.iname, sf: ssi.FilterSubject}
4766 } else {
4767 sfs := make([]string, len(ssi.SubjectTransforms))
4768 trs := make([]*subjectTransform, len(ssi.SubjectTransforms))
4769 for i, str := range ssi.SubjectTransforms {
4770 tr, err := NewSubjectTransform(str.Source, str.Destination)
4771 if err != nil {
4772 mset.srv.Errorf("Unable to get subject transform for source: %v", err)
4773 }
4774 sfs[i] = str.Source
4775 trs[i] = tr
4776 }
4777 si = &sourceInfo{name: ssi.Name, iname: ssi.iname, sfs: sfs, trs: trs}
4778 }
4779 mset.sources[ssi.iname] = si
4780 }
4781 }
4782
4783 // This will do a reverse scan on startup or leader election
4784 // searching for the starting sequence number.
4785 // This can be slow in degenerative cases.
4786 // Lock should be held.
4787 func (mset *stream) startingSequenceForSources() {
4788 if len(mset.cfg.Sources) == 0 {
4789 return
4790 }
4791
4792 // Always reset here.
4793 mset.resetSourceInfo()
4794
4795 var state StreamState
4796 mset.store.FastState(&state)
4797
4798 // Bail if no messages, meaning no context.
4799 if state.Msgs == 0 {
4800 return
4801 }
4802
4803 // For short circuiting return.
4804 expected := len(mset.cfg.Sources)
4805 seqs := make(map[string]uint64)
4806
4807 // Stamp our si seq records on the way out.
4808 defer func() {
4809 for sname, seq := range seqs {
4810 // Ignore if not set.
4811 if seq == 0 {
4812 continue
4813 }
4814 if si := mset.sources[sname]; si != nil {
4815 si.sseq = seq
4816 si.dseq = 0
4817 }
4818 }
4819 }()
4820
4821 // Generate a list of sources and, from that, a sublist that contains
4822 // the interested filters (including transforms). As we figure out the
4823 // starting sequence for each source, we will eliminate the source from
4824 // the map and then refresh the sublist, which in turn makes the sublist
4825 // ideally more specific. This allows LoadPrevMsgsMulti to work most
4826 // effectively.
4827 // Because this is a SimpleSublist we can't just remove the entries per
4828 // source so we have no other option but to rebuild it from scratch, but
4829 // this is cheap enough to do so not the end of the world.
4830 sources := map[string]*StreamSource{}
4831 for _, src := range mset.cfg.Sources {
4832 sources[src.composeIName()] = src
4833 }
4834 var sl *gsl.SimpleSublist
4835 refreshSublist := func() {
4836 sl = gsl.NewSimpleSublist()
4837 for _, src := range sources {
4838 if src.FilterSubject == _EMPTY_ {
4839 sl.Insert(fwcs, struct{}{})
4840 } else {
4841 sl.Insert(src.FilterSubject, struct{}{})
4842 }
4843 for _, tr := range src.SubjectTransforms {
4844 if tr.Destination == _EMPTY_ {
4845 sl.Insert(fwcs, struct{}{})
4846 } else {
4847 sl.Insert(tr.Destination, struct{}{})
4848 }
4849 }
4850 }
4851 }
4852 refreshSublist()
4853
4854 update := func(iName string, seq uint64) {
4855 // Only update active in case we have older ones in here that got configured out.
4856 if si := mset.sources[iName]; si != nil {
4857 if _, ok := seqs[iName]; !ok {
4858 seqs[iName] = seq
4859 delete(sources, iName)
4860 refreshSublist()
4861 }
4862 }
4863 }
4864
4865 var smv StoreMsg
4866 for last := state.LastSeq; ; {
4867 sm, seq, err := mset.store.LoadPrevMsgMulti(sl, last, &smv)
4868 if err == ErrStoreEOF || err != nil {
4869 break
4870 }
4871 last = seq - 1
4872 if len(sm.hdr) == 0 {
4873 continue
4874 }
4875 ss := sliceHeader(JSStreamSource, sm.hdr)
4876 if len(ss) == 0 {
4877 continue
4878 }
4879
4880 streamName, iName, sseq := streamAndSeq(bytesToString(ss))
4881 if iName == _EMPTY_ { // Pre-2.10 message header means it's a match for any source using that stream name
4882 for _, ssi := range mset.cfg.Sources {
4883 if streamName == ssi.Name || (ssi.External != nil && streamName == ssi.Name+":"+getHash(ssi.External.ApiPrefix)) {
4884 update(ssi.iname, sseq)
4885 }
4886 }
4887 } else {
4888 update(iName, sseq)
4889 }
4890 if len(seqs) == expected {
4891 return
4892 }
4893 }
4894 }
4895
4896 // Setup our source consumers.
4897 // Lock should be held.
4898 func (mset *stream) setupSourceConsumers() error {
4899 if mset.outq == nil {
4900 return errors.New("outq required")
4901 }
4902 // Reset if needed.
4903 for _, si := range mset.sources {
4904 if si.sub != nil {
4905 mset.cancelSourceConsumer(si.iname)
4906 }
4907 }
4908
4909 // If we are no longer the leader, give up
4910 if !mset.isLeader() {
4911 return nil
4912 }
4913
4914 mset.startingSequenceForSources()
4915
4916 // Setup our consumers at the proper starting position.
4917 for _, ssi := range mset.cfg.Sources {
4918 if si := mset.sources[ssi.iname]; si != nil {
4919 mset.setupSourceConsumer(ssi.iname, si.sseq+1, time.Time{})
4920 }
4921 }
4922
4923 return nil
4924 }
4925
4926 // Will create internal subscriptions for the stream.
4927 // Lock should be held.
4928 func (mset *stream) subscribeToStream() error {
4929 if mset.active {
4930 return nil
4931 }
4932 for _, subject := range mset.cfg.Subjects {
4933 if _, err := mset.subscribeInternal(subject, mset.processInboundJetStreamMsg); err != nil {
4934 return err
4935 }
4936 }
4937 // Check if we need to setup mirroring.
4938 if mset.cfg.Mirror != nil {
4939 // setup the initial mirror sourceInfo
4940 mset.mirror = &sourceInfo{name: mset.cfg.Mirror.Name}
4941 sfs := make([]string, len(mset.cfg.Mirror.SubjectTransforms))
4942 trs := make([]*subjectTransform, len(mset.cfg.Mirror.SubjectTransforms))
4943
4944 for i, tr := range mset.cfg.Mirror.SubjectTransforms {
4945 // will not fail as already checked before that the transform will work
4946 subjectTransform, err := NewSubjectTransform(tr.Source, tr.Destination)
4947 if err != nil {
4948 mset.srv.Errorf("Unable to get transform for mirror consumer: %v", err)
4949 }
4950
4951 sfs[i] = tr.Source
4952 trs[i] = subjectTransform
4953 }
4954 mset.mirror.sfs = sfs
4955 mset.mirror.trs = trs
4956 // delay the actual mirror consumer creation for after a delay
4957 mset.scheduleSetupMirrorConsumerRetry()
4958 } else if len(mset.cfg.Sources) > 0 && mset.sourcesConsumerSetup == nil {
4959 // Setup the initial source infos for the sources
4960 mset.resetSourceInfo()
4961 // Delay the actual source consumer(s) creation(s) for after a delay if a replicated stream.
4962 // If it's an R1, this is done at startup and we will do inline.
4963 if mset.cfg.Replicas == 1 {
4964 mset.setupSourceConsumers()
4965 } else {
4966 mset.sourcesConsumerSetup = time.AfterFunc(time.Duration(rand.Intn(int(500*time.Millisecond)))+100*time.Millisecond, func() {
4967 mset.mu.Lock()
4968 mset.setupSourceConsumers()
4969 mset.mu.Unlock()
4970 })
4971 }
4972 }
4973 // Check for direct get access.
4974 // We spin up followers for clustered streams in monitorStream().
4975 if mset.cfg.AllowDirect {
4976 if err := mset.subscribeToDirect(); err != nil {
4977 return err
4978 }
4979 }
4980
4981 mset.active = true
4982 return nil
4983 }
4984
4985 // Lock should be held.
4986 func (mset *stream) subscribeToDirect() error {
4987 // We will make this listen on a queue group by default, which can allow mirrors to participate on opt-in basis.
4988 if mset.directSub == nil {
4989 dsubj := fmt.Sprintf(JSDirectMsgGetT, mset.cfg.Name)
4990 if sub, err := mset.queueSubscribeInternal(dsubj, dgetGroup, mset.processDirectGetRequest); err == nil {
4991 mset.directSub = sub
4992 } else {
4993 return err
4994 }
4995 }
4996 // Now the one that will have subject appended past stream name.
4997 if mset.lastBySub == nil {
4998 dsubj := fmt.Sprintf(JSDirectGetLastBySubjectT, mset.cfg.Name, fwcs)
4999 // We will make this listen on a queue group by default, which can allow mirrors to participate on opt-in basis.
5000 if sub, err := mset.queueSubscribeInternal(dsubj, dgetGroup, mset.processDirectGetLastBySubjectRequest); err == nil {
5001 mset.lastBySub = sub
5002 } else {
5003 return err
5004 }
5005 }
5006
5007 return nil
5008 }
5009
5010 // Lock should be held.
5011 func (mset *stream) unsubscribeToDirect() {
5012 if mset.directSub != nil {
5013 mset.unsubscribe(mset.directSub)
5014 mset.directSub = nil
5015 }
5016 if mset.lastBySub != nil {
5017 mset.unsubscribe(mset.lastBySub)
5018 mset.lastBySub = nil
5019 }
5020 }
5021
5022 // Lock should be held.
5023 func (mset *stream) subscribeToMirrorDirect() error {
5024 if mset.cfg.Mirror == nil {
5025 return nil
5026 }
5027 mirrorName := mset.cfg.Mirror.Name
5028
5029 // We will make this listen on a queue group by default, which can allow mirrors to participate on opt-in basis.
5030 if mset.mirrorDirectSub == nil {
5031 dsubj := fmt.Sprintf(JSDirectMsgGetT, mirrorName)
5032 // We will make this listen on a queue group by default, which can allow mirrors to participate on opt-in basis.
5033 if sub, err := mset.queueSubscribeInternal(dsubj, dgetGroup, mset.processDirectGetRequest); err == nil {
5034 mset.mirrorDirectSub = sub
5035 } else {
5036 return err
5037 }
5038 }
5039 // Now the one that will have subject appended past stream name.
5040 if mset.mirrorLastBySub == nil {
5041 dsubj := fmt.Sprintf(JSDirectGetLastBySubjectT, mirrorName, fwcs)
5042 // We will make this listen on a queue group by default, which can allow mirrors to participate on opt-in basis.
5043 if sub, err := mset.queueSubscribeInternal(dsubj, dgetGroup, mset.processDirectGetLastBySubjectRequest); err == nil {
5044 mset.mirrorLastBySub = sub
5045 } else {
5046 return err
5047 }
5048 }
5049
5050 return nil
5051 }
5052
5053 // Lock should be held.
5054 func (mset *stream) unsubscribeToMirrorDirect() {
5055 if mset.mirrorDirectSub != nil {
5056 mset.unsubscribe(mset.mirrorDirectSub)
5057 mset.mirrorDirectSub = nil
5058 }
5059 if mset.mirrorLastBySub != nil {
5060 mset.unsubscribe(mset.mirrorLastBySub)
5061 mset.mirrorLastBySub = nil
5062 }
5063 }
5064
5065 // Stop our source consumers.
5066 // Lock should be held.
5067 func (mset *stream) stopSourceConsumers() {
5068 for _, si := range mset.sources {
5069 mset.cancelSourceInfo(si)
5070 }
5071 }
5072
5073 // Lock should be held.
5074 func (mset *stream) removeInternalConsumer(si *sourceInfo) {
5075 if si == nil || si.cname == _EMPTY_ {
5076 return
5077 }
5078 si.cname = _EMPTY_
5079 }
5080
5081 // Will unsubscribe from the stream.
5082 // Lock should be held.
5083 func (mset *stream) unsubscribeToStream(stopping, shuttingDown bool) error {
5084 for _, subject := range mset.cfg.Subjects {
5085 mset.unsubscribeInternal(subject)
5086 }
5087 if mset.mirror != nil {
5088 mset.cancelSourceInfo(mset.mirror)
5089 mset.mirror = nil
5090 }
5091
5092 if len(mset.sources) > 0 {
5093 mset.stopSourceConsumers()
5094 mset.sources = nil
5095 }
5096 // Clear batching state.
5097 mset.deleteAtomicBatches(shuttingDown)
5098 if stopping || shuttingDown {
5099 mset.deleteFastBatches()
5100 }
5101 if mset.batches != nil {
5102 mset.batches.mu.Lock()
5103 reset := len(mset.batches.atomic) == 0 && len(mset.batches.fast) == 0
5104 mset.batches.mu.Unlock()
5105 if reset {
5106 mset.batches = nil
5107 }
5108 }
5109
5110 if stopping {
5111 // In case we had a direct get subscriptions.
5112 mset.unsubscribeToDirect()
5113 mset.unsubscribeToMirrorDirect()
5114 }
5115
5116 if mset.directLeaderSub == nil {
5117 // Always unsubscribe the leader sub.
5118 mset.unsubscribe(mset.directLeaderSub)
5119 mset.directLeaderSub = nil
5120 }
5121
5122 mset.active = false
5123 return nil
5124 }
5125
5126 // Lock should be held.
5127 func (mset *stream) deleteAtomicBatches(shuttingDown bool) {
5128 if mset.batches != nil {
5129 mset.batches.mu.Lock()
5130 for batchId, b := range mset.batches.atomic {
5131 // If shutting down, do fixup during startup. In-memory batches don't require manual cleanup.
5132 if shuttingDown {
5133 b.stopLocked()
5134 } else {
5135 b.cleanupLocked(batchId, mset.batches)
5136 }
5137 }
5138 mset.batches.atomic = nil
5139 mset.batches.mu.Unlock()
5140 }
5141 }
5142
5143 // Lock should be held.
5144 func (mset *stream) deleteFastBatches() {
5145 if mset.batches != nil {
5146 mset.batches.mu.Lock()
5147 for batchId, b := range mset.batches.fast {
5148 b.cleanupLocked(batchId, mset.batches)
5149 }
5150 mset.batches.fast = nil
5151 mset.batches.mu.Unlock()
5152 }
5153 }
5154
5155 // Lock does NOT need to be held, we set the client on setup and never change it at this point.
5156 func (mset *stream) subscribeInternal(subject string, cb msgHandler) (*subscription, error) {
5157 if mset.closed.Load() {
5158 return nil, errStreamClosed
5159 }
5160 if cb == nil {
5161 return nil, errInvalidMsgHandler
5162 }
5163 c := mset.client
5164 sid := int(mset.sid.Add(1))
5165 // Now create the subscription
5166 return c.processSub([]byte(subject), nil, []byte(strconv.Itoa(sid)), cb, false)
5167 }
5168
5169 // Lock does NOT need to be held, we set the client on setup and never change it at this point.
5170 func (mset *stream) queueSubscribeInternal(subject, group string, cb msgHandler) (*subscription, error) {
5171 if mset.closed.Load() {
5172 return nil, errStreamClosed
5173 }
5174 if cb == nil {
5175 return nil, errInvalidMsgHandler
5176 }
5177 c := mset.client
5178 sid := int(mset.sid.Add(1))
5179 // Now create the subscription
5180 return c.processSub([]byte(subject), []byte(group), []byte(strconv.Itoa(sid)), cb, false)
5181 }
5182
5183 // This will unsubscribe us from the exact subject given.
5184 // We do not currently track the subs so do not have the sid.
5185 // This should be called only on an update.
5186 // Lock does NOT need to be held, we set the client on setup and never change it at this point.
5187 func (mset *stream) unsubscribeInternal(subject string) error {
5188 if mset.closed.Load() {
5189 return errStreamClosed
5190 }
5191 c := mset.client
5192 var sid []byte
5193 c.mu.Lock()
5194 for _, sub := range c.subs {
5195 if subject == string(sub.subject) {
5196 sid = sub.sid
5197 break
5198 }
5199 }
5200 c.mu.Unlock()
5201
5202 if sid != nil {
5203 return c.processUnsub(sid)
5204 }
5205 return nil
5206 }
5207
5208 func (mset *stream) unsubscribe(sub *subscription) {
5209 if sub == nil || mset.closed.Load() {
5210 return
5211 }
5212 mset.client.processUnsub(sub.sid)
5213 }
5214
5215 func (mset *stream) setupStore(fsCfg *FileStoreConfig) error {
5216 mset.mu.Lock()
5217 switch mset.cfg.Storage {
5218 case MemoryStorage:
5219 ms, err := newMemStore(&mset.cfg)
5220 if err != nil {
5221 mset.mu.Unlock()
5222 return err
5223 }
5224 mset.store = ms
5225 case FileStorage:
5226 s := mset.srv
5227 prf := s.jsKeyGen(s.getOpts().JetStreamKey, mset.acc.Name)
5228 if prf != nil {
5229 // We are encrypted here, fill in correct cipher selection.
5230 fsCfg.Cipher = s.getOpts().JetStreamCipher
5231 }
5232 oldprf := s.jsKeyGen(s.getOpts().JetStreamOldKey, mset.acc.Name)
5233 cfg := *fsCfg
5234 cfg.srv = s
5235 fs, err := newFileStoreWithCreated(cfg, mset.cfg, mset.created, prf, oldprf)
5236 if err != nil {
5237 mset.mu.Unlock()
5238 return err
5239 }
5240 mset.store = fs
5241 }
5242 // This will fire the callback but we do not require the lock since md will be 0 here.
5243 mset.store.RegisterStorageUpdates(mset.storeUpdates)
5244 mset.store.RegisterStorageRemoveMsg(func(seq uint64) {
5245 if mset.IsClustered() {
5246 mset.mu.RLock()
5247 if mset.isLeader() {
5248 md := streamMsgDelete{Seq: seq, NoErase: true, Stream: mset.cfg.Name}
5249 mset.node.Propose(mset.term, encodeMsgDelete(&md))
5250 }
5251 mset.mu.RUnlock()
5252 } else {
5253 mset.removeMsg(seq)
5254 }
5255 })
5256 mset.store.RegisterProcessJetStreamMsg(func(im *inMsg) {
5257 if mset.IsClustered() {
5258 if mset.IsLeader() {
5259 mset.processClusteredInboundMsg(im.subj, im.rply, im.hdr, im.msg, im.mt, true)
5260 }
5261 } else {
5262 mset.processJetStreamMsg(im.subj, im.rply, im.hdr, im.msg, 0, 0, im.mt, true, true)
5263 }
5264 })
5265 mset.mu.Unlock()
5266
5267 return nil
5268 }
5269
5270 // Called for any updates to the underlying stream. We pass through the bytes to the
5271 // jetstream account. We do local processing for stream pending for consumers, but only
5272 // for removals.
5273 // Lock should not be held.
5274 func (mset *stream) storeUpdates(md, bd int64, seq uint64, subj string) {
5275 // If we have a single negative update then we will process our consumers for stream pending.
5276 // Purge and Store handled separately inside individual calls.
5277 if md == -1 && seq > 0 && subj != _EMPTY_ {
5278 // We use our consumer list mutex here instead of the main stream lock since it may be held already.
5279 mset.clsMu.RLock()
5280 if mset.csl != nil {
5281 mset.csl.Match(subj, func(o *consumer) {
5282 o.decStreamPending(seq, subj)
5283 })
5284 } else {
5285 for _, o := range mset.cList {
5286 o.decStreamPending(seq, subj)
5287 }
5288 }
5289 mset.clsMu.RUnlock()
5290 } else if md < 0 {
5291 // Batch decrements we need to force consumers to re-calculate num pending.
5292 var ss StreamState
5293 mset.store.FastState(&ss)
5294 mset.clsMu.RLock()
5295 for _, o := range mset.cList {
5296 o.streamNumPendingLocked()
5297 o.removeRedeliveredBelow(ss.FirstSeq)
5298 }
5299 mset.clsMu.RUnlock()
5300 }
5301
5302 if mset.jsa != nil {
5303 mset.jsa.updateUsage(mset.tier, mset.stype, bd)
5304 }
5305 }
5306
5307 // NumMsgIds returns the number of message ids being tracked for duplicate suppression.
5308 func (mset *stream) numMsgIds() int {
5309 mset.ddMu.Lock()
5310 defer mset.ddMu.Unlock()
5311 return len(mset.ddmap)
5312 }
5313
5314 // checkMsgId will process and check for duplicates.
5315 // mset.ddMu lock should be held.
5316 func (mset *stream) checkMsgId(id string) *ddentry {
5317 if id == _EMPTY_ || len(mset.ddmap) == 0 {
5318 return nil
5319 }
5320 return mset.ddmap[id]
5321 }
5322
5323 // Will purge the entries that are past the window.
5324 // Should be called from a timer.
5325 func (mset *stream) purgeMsgIds() {
5326 now := time.Now().UnixNano()
5327 mset.cfgMu.RLock()
5328 tmrNext := mset.cfg.Duplicates
5329 mset.cfgMu.RUnlock()
5330 window := int64(tmrNext)
5331
5332 mset.ddMu.Lock()
5333 defer mset.ddMu.Unlock()
5334
5335 for i, dde := range mset.ddarr[mset.ddindex:] {
5336 if now-dde.ts >= window {
5337 delete(mset.ddmap, dde.id)
5338 } else {
5339 mset.ddindex += i
5340 // Check if we should garbage collect here if we are 1/3 total size.
5341 if cap(mset.ddarr) > 3*(len(mset.ddarr)-mset.ddindex) {
5342 mset.ddarr = append([]*ddentry(nil), mset.ddarr[mset.ddindex:]...)
5343 mset.ddindex = 0
5344 }
5345 tmrNext = time.Duration(window - (now - dde.ts))
5346 break
5347 }
5348 }
5349 if len(mset.ddmap) > 0 {
5350 // Make sure to not fire too quick
5351 const minFire = 50 * time.Millisecond
5352 if tmrNext < minFire {
5353 tmrNext = minFire
5354 }
5355 if mset.ddtmr != nil {
5356 mset.ddtmr.Reset(tmrNext)
5357 } else {
5358 mset.ddtmr = time.AfterFunc(tmrNext, mset.purgeMsgIds)
5359 }
5360 } else {
5361 if mset.ddtmr != nil {
5362 mset.ddtmr.Stop()
5363 mset.ddtmr = nil
5364 }
5365 mset.ddmap = nil
5366 mset.ddarr = nil
5367 mset.ddindex = 0
5368 }
5369 }
5370
5371 // storeMsgId will store the message id for duplicate detection.
5372 func (mset *stream) storeMsgId(dde *ddentry) {
5373 mset.ddMu.Lock()
5374 defer mset.ddMu.Unlock()
5375 mset.storeMsgIdLocked(dde)
5376 }
5377
5378 // storeMsgIdLocked will store the message id for duplicate detection.
5379 // mset.ddMu lock should be held.
5380 func (mset *stream) storeMsgIdLocked(dde *ddentry) {
5381 // Zero means disabled.
5382 if mset.cfg.Duplicates <= 0 {
5383 return
5384 }
5385
5386 if mset.ddmap == nil {
5387 mset.ddmap = make(map[string]*ddentry)
5388 }
5389 mset.ddmap[dde.id] = dde
5390 mset.ddarr = append(mset.ddarr, dde)
5391 if mset.ddtmr == nil {
5392 mset.ddtmr = time.AfterFunc(mset.cfg.Duplicates, mset.purgeMsgIds)
5393 }
5394 }
5395
5396 // Fast lookup of msgId.
5397 func getMsgId(hdr []byte) string {
5398 return string(getHeader(JSMsgId, hdr))
5399 }
5400
5401 // Fast lookup of expected last msgId.
5402 func getExpectedLastMsgId(hdr []byte) string {
5403 return string(getHeader(JSExpectedLastMsgId, hdr))
5404 }
5405
5406 // Fast lookup of expected stream.
5407 func getExpectedStream(hdr []byte) string {
5408 return string(getHeader(JSExpectedStream, hdr))
5409 }
5410
5411 // Fast lookup of expected last sequence.
5412 func getExpectedLastSeq(hdr []byte) (uint64, bool) {
5413 bseq := sliceHeader(JSExpectedLastSeq, hdr)
5414 if len(bseq) == 0 {
5415 return 0, false
5416 }
5417 return uint64(parseInt64(bseq)), true
5418 }
5419
5420 // Fast lookup of rollups.
5421 func getRollup(hdr []byte) string {
5422 r := getHeader(JSMsgRollup, hdr)
5423 if len(r) == 0 {
5424 return _EMPTY_
5425 }
5426 return strings.ToLower(string(r))
5427 }
5428
5429 // Fast lookup of expected stream sequence per subject.
5430 func getExpectedLastSeqPerSubject(hdr []byte) (uint64, bool) {
5431 bseq := sliceHeader(JSExpectedLastSubjSeq, hdr)
5432 if len(bseq) == 0 {
5433 return 0, false
5434 }
5435 return uint64(parseInt64(bseq)), true
5436 }
5437
5438 // Fast lookup of expected subject for the expected stream sequence per subject.
5439 func getExpectedLastSeqPerSubjectForSubject(hdr []byte) string {
5440 return bytesToString(sliceHeader(JSExpectedLastSubjSeqSubj, hdr))
5441 }
5442
5443 // Fast lookup of the message TTL from headers:
5444 // - Positive return value: duration in seconds.
5445 // - Zero return value: no TTL or parse error.
5446 // - Negative return value: never expires.
5447 func getMessageTTL(hdr []byte) (int64, error) {
5448 ttl := getHeader(JSMessageTTL, hdr)
5449 if len(ttl) == 0 {
5450 return 0, nil
5451 }
5452 return parseMessageTTL(bytesToString(ttl))
5453 }
5454
5455 // - Positive return value: duration in seconds.
5456 // - Zero return value: no TTL or parse error.
5457 // - Negative return value: never expires.
5458 func parseMessageTTL(ttl string) (int64, error) {
5459 if strings.ToLower(ttl) == "never" {
5460 return -1, nil
5461 }
5462 dur, err := time.ParseDuration(ttl)
5463 if err == nil {
5464 if dur < time.Second {
5465 return 0, NewJSMessageTTLInvalidError()
5466 }
5467 return int64(dur.Seconds()), nil
5468 }
5469 t := parseInt64(stringToBytes(ttl))
5470 if t < 0 {
5471 // This probably means a parse failure, hence why
5472 // we have a special case "never" for returning -1.
5473 // Otherwise we can't know if it's a genuine TTL
5474 // that says never expire or if it's a parse error.
5475 return 0, NewJSMessageTTLInvalidError()
5476 }
5477 return t, nil
5478 }
5479
5480 // Fast lookup of the message Incr from headers.
5481 // Return includes the value or nil, and success.
5482 func getMessageIncr(hdr []byte) (*big.Int, bool) {
5483 incr := sliceHeader(JSMessageIncr, hdr)
5484 if len(incr) == 0 {
5485 return nil, true
5486 }
5487 var v big.Int
5488 return v.SetString(bytesToString(incr), 10)
5489 }
5490
5491 // Fast lookup of message schedule.
5492 func getMessageSchedule(hdr []byte) (time.Time, *ApiError) {
5493 if len(hdr) == 0 {
5494 return time.Time{}, nil
5495 }
5496 return nextMessageSchedule(hdr, time.Now().UTC().UnixNano())
5497 }
5498
5499 // Fast lookup and calculation of next message schedule.
5500 func nextMessageSchedule(hdr []byte, ts int64) (time.Time, *ApiError) {
5501 if len(hdr) == 0 {
5502 return time.Time{}, nil
5503 }
5504 loc, apiErr := loadMessageScheduleLocation(hdr)
5505 if apiErr != nil {
5506 return time.Time{}, apiErr
5507 }
5508 val := bytesToString(sliceHeader(JSSchedulePattern, hdr))
5509 schedule, _, ok := parseMsgSchedule(val, loc, ts)
5510 if !ok {
5511 return time.Time{}, NewJSMessageSchedulesPatternInvalidError()
5512 }
5513 return schedule, nil
5514 }
5515
5516 // loadMessageScheduleLocation returns the *time.Location for the schedule's
5517 // time zone header. Returns nil loc when the header is absent. A header that
5518 // is present but empty or names an unknown zone yields a TimeZoneInvalid error.
5519 func loadMessageScheduleLocation(hdr []byte) (*time.Location, *ApiError) {
5520 tz := sliceHeader(JSScheduleTimeZone, hdr)
5521 if tz == nil {
5522 return nil, nil
5523 }
5524 if len(tz) == 0 {
5525 return nil, NewJSMessageSchedulesTimeZoneInvalidError()
5526 }
5527 loc, err := time.LoadLocation(bytesToString(tz))
5528 if err != nil {
5529 return nil, NewJSMessageSchedulesTimeZoneInvalidError()
5530 }
5531 return loc, nil
5532 }
5533
5534 // Fast lookup of the message schedule TTL from headers.
5535 // The TTL is confirmed to be valid, but the raw TTL string is returned.
5536 func getMessageScheduleTTL(hdr []byte) (string, bool) {
5537 ttl := getHeader(JSScheduleTTL, hdr)
5538 if len(ttl) == 0 {
5539 return _EMPTY_, true
5540 }
5541 if _, err := parseMessageTTL(bytesToString(ttl)); err != nil {
5542 return _EMPTY_, false
5543 }
5544 return string(ttl), true
5545 }
5546
5547 // Fast lookup of the message schedule rollup from headers.
5548 func getMessageScheduleRollup(hdr []byte) string {
5549 return string(sliceHeader(JSScheduleRollup, hdr))
5550 }
5551
5552 // Fast lookup of message schedule target.
5553 func getMessageScheduleTarget(hdr []byte) string {
5554 if len(hdr) == 0 {
5555 return _EMPTY_
5556 }
5557 return string(getHeader(JSScheduleTarget, hdr))
5558 }
5559
5560 // Fast lookup of message schedule source.
5561 func getMessageScheduleSource(hdr []byte) string {
5562 if len(hdr) == 0 {
5563 return _EMPTY_
5564 }
5565 return string(getHeader(JSScheduleSource, hdr))
5566 }
5567
5568 // Fast lookup of message scheduler.
5569 func getMessageScheduler(hdr []byte) string {
5570 if len(hdr) == 0 {
5571 return _EMPTY_
5572 }
5573 return string(getHeader(JSScheduler, hdr))
5574 }
5575
5576 // Fast lookup of batch ID.
5577 func getBatchId(hdr []byte) string {
5578 if len(hdr) == 0 {
5579 return _EMPTY_
5580 }
5581 if atomicBatchId := sliceHeader(JSBatchId, hdr); atomicBatchId != nil {
5582 return string(atomicBatchId)
5583 }
5584 return _EMPTY_
5585 }
5586
5587 type FastBatch struct {
5588 id string
5589 seq uint64
5590 flow uint16
5591 ping bool
5592 gapOk bool
5593 commit bool
5594 commitEob bool
5595 }
5596
5597 const (
5598 FastBatchSuffix = ".$FI"
5599 FastBatchGapFail = "fail"
5600 FastBatchGapOk = "ok"
5601 )
5602
5603 const (
5604 FastBatchOpStart = iota
5605 FastBatchOpAppend
5606 FastBatchOpCommit
5607 FastBatchOpCommitEob
5608 FastBatchOpPing
5609 )
5610
5611 var fastBatchPool sync.Pool
5612
5613 func getFastBatchFromPool() *FastBatch {
5614 idx := fastBatchPool.Get()
5615 if idx != nil {
5616 return idx.(*FastBatch)
5617 }
5618 return new(FastBatch)
5619 }
5620
5621 func (b *FastBatch) returnToPool() {
5622 if b == nil {
5623 return
5624 }
5625 // Nil out all values.
5626 *b = FastBatch{}
5627 fastBatchPool.Put(b)
5628 }
5629
5630 // getFastBatch gets fast batch info from the reply subject in the form:
5631 // <prefix>.<uuid>.<initial flow>.<gap mode>.<batch seq>.<operation>.$FI
5632 func getFastBatch(reply string, hdr []byte) (*FastBatch, bool) {
5633 lreply := len(reply)
5634 if lreply <= 4 || reply[lreply-4:] != FastBatchSuffix {
5635 if !isServiceReply(stringToBytes(reply)) {
5636 return nil, false
5637 }
5638 // If account imports/exports are used, the reply might be internal.
5639 // Check the client header for the original reply subject.
5640 ci := sliceHeader(ClientInfoHdr, hdr)
5641 if ci == nil {
5642 return nil, false
5643 }
5644 var cis ClientInfo
5645 if err := json.Unmarshal(ci, &cis); err != nil || cis.Reply == _EMPTY_ {
5646 return nil, false
5647 }
5648 reply = cis.Reply
5649 lreply = len(reply)
5650 if lreply <= 4 || reply[lreply-4:] != FastBatchSuffix {
5651 return nil, false
5652 }
5653 }
5654
5655 n := lreply - 4 // Move to just before the dot
5656 o := strings.LastIndexByte(reply[:n], '.')
5657 if o == -1 {
5658 return nil, true
5659 }
5660 // Batch operation.
5661 ops := reply[o+1 : n]
5662 op := parseInt64(stringToBytes(ops))
5663 if op < FastBatchOpStart || op > FastBatchOpPing {
5664 return nil, true
5665 }
5666
5667 b := getFastBatchFromPool()
5668 b.ping = op == FastBatchOpPing
5669 b.commitEob = op == FastBatchOpCommitEob
5670 b.commit = b.commitEob || op == FastBatchOpCommit
5671 p := o
5672
5673 // Batch seq.
5674 if o = strings.LastIndexByte(reply[:o], '.'); o == -1 {
5675 return nil, true
5676 }
5677 seq, ok := parseUint64(stringToBytes(reply[o+1 : p]))
5678 // Reject math.MaxUint64 to prevent b.lseq overflowing on the next b.lseq++.
5679 if !ok || seq == 0 || seq == math.MaxUint64 {
5680 return nil, true
5681 }
5682 b.seq = seq
5683 p = o
5684 if b.seq == 1 && b.commitEob {
5685 return nil, true
5686 }
5687 if op == FastBatchOpStart && b.seq != 1 {
5688 return nil, true
5689 } else if op == FastBatchOpAppend && b.seq <= 1 {
5690 return nil, true
5691 }
5692
5693 // Gap mode.
5694 if o = strings.LastIndexByte(reply[:o], '.'); o == -1 {
5695 return nil, true
5696 }
5697 gapMode := reply[o+1 : p]
5698 if gapMode != FastBatchGapFail && gapMode != FastBatchGapOk {
5699 return nil, true // Not recognized.
5700 }
5701 b.gapOk = gapMode == FastBatchGapOk
5702 p = o
5703
5704 // Ack flow.
5705 if o = strings.LastIndexByte(reply[:o], '.'); o == -1 {
5706 return nil, true
5707 }
5708 a := parseInt64(stringToBytes(reply[o+1 : p]))
5709 if a <= 0 {
5710 a = 10
5711 } else if a > math.MaxUint16 {
5712 a = math.MaxUint16
5713 }
5714 b.flow = uint16(a)
5715 p = o
5716
5717 // Batch id.
5718 if o = strings.LastIndexByte(reply[:o], '.'); o == -1 {
5719 return nil, true
5720 }
5721 b.id = reply[o+1 : p]
5722 return b, false
5723 }
5724
5725 // Fast lookup of batch sequence.
5726 func getBatchSequence(hdr []byte) (uint64, bool) {
5727 bseq := sliceHeader(JSBatchSeq, hdr)
5728 if len(bseq) == 0 {
5729 return 0, false
5730 }
5731 return parseUint64(bseq)
5732 }
5733
5734 // Signal if we are clustered. Will acquire rlock.
5735 func (mset *stream) IsClustered() bool {
5736 mset.mu.RLock()
5737 defer mset.mu.RUnlock()
5738 return mset.isClustered()
5739 }
5740
5741 // Lock should be held.
5742 func (mset *stream) isClustered() bool {
5743 return mset.node != nil
5744 }
5745
5746 // Used if we have to queue things internally to avoid the route/gw path.
5747 type inMsg struct {
5748 subj string
5749 rply string
5750 hdr []byte
5751 msg []byte
5752 si *sourceInfo
5753 mt *msgTrace
5754 seq uint64 // seq that can be optionally used for sorting out-of-band.
5755 }
5756
5757 var inMsgPool = sync.Pool{
5758 New: func() any {
5759 return &inMsg{}
5760 },
5761 }
5762
5763 func (im *inMsg) returnToPool() {
5764 im.subj, im.rply, im.hdr, im.msg, im.si, im.mt = _EMPTY_, _EMPTY_, nil, nil, nil, nil
5765 inMsgPool.Put(im)
5766 }
5767
5768 func (mset *stream) queueInbound(ib *ipQueue[*inMsg], subj, rply string, hdr, msg []byte, si *sourceInfo, mt *msgTrace) {
5769 im := inMsgPool.Get().(*inMsg)
5770 im.subj, im.rply, im.hdr, im.msg, im.si, im.mt = subj, rply, hdr, msg, si, mt
5771 if _, err := ib.push(im); err != nil {
5772 im.returnToPool()
5773 streamName := mset.getCfgName()
5774 mset.srv.RateLimitWarnf("Dropping messages due to excessive stream ingest rate on '%s' > '%s': %s", mset.acc.Name, streamName, err)
5775 if rply != _EMPTY_ {
5776 hdr := []byte("NATS/1.0 429 Too Many Requests\r\n\r\n")
5777 b, _ := json.Marshal(&JSPubAckResponse{PubAck: &PubAck{Stream: streamName}, Error: NewJSStreamTooManyRequestsError()})
5778 mset.outq.send(newJSPubMsg(rply, _EMPTY_, _EMPTY_, hdr, b, nil, 0))
5779 }
5780 }
5781 }
5782
5783 var dgPool = sync.Pool{
5784 New: func() any {
5785 return &directGetReq{}
5786 },
5787 }
5788
5789 // For when we need to not inline the request.
5790 type directGetReq struct {
5791 // Copy of this is correct for this.
5792 req JSApiMsgGetRequest
5793 reply string
5794 }
5795
5796 // processDirectGetRequest handles direct get request for stream messages.
5797 func (mset *stream) processDirectGetRequest(_ *subscription, c *client, _ *Account, subject, reply string, rmsg []byte) {
5798 if len(reply) == 0 {
5799 return
5800 }
5801 hdr, msg := c.msgParts(rmsg)
5802 if errorOnRequiredApiLevel(hdr) {
5803 hdr := []byte("NATS/1.0 412 Required Api Level\r\n\r\n")
5804 mset.outq.send(newJSPubMsg(reply, _EMPTY_, _EMPTY_, hdr, nil, nil, 0))
5805 return
5806 }
5807 if len(msg) == 0 {
5808 hdr := []byte("NATS/1.0 408 Empty Request\r\n\r\n")
5809 mset.outq.send(newJSPubMsg(reply, _EMPTY_, _EMPTY_, hdr, nil, nil, 0))
5810 return
5811 }
5812 var req JSApiMsgGetRequest
5813 err := json.Unmarshal(msg, &req)
5814 if err != nil {
5815 hdr := []byte("NATS/1.0 408 Malformed Request\r\n\r\n")
5816 mset.outq.send(newJSPubMsg(reply, _EMPTY_, _EMPTY_, hdr, nil, nil, 0))
5817 return
5818 }
5819 // Check if nothing set.
5820 if req.Seq == 0 && req.LastFor == _EMPTY_ && req.NextFor == _EMPTY_ && len(req.MultiLastFor) == 0 && req.StartTime == nil {
5821 hdr := []byte("NATS/1.0 408 Empty Request\r\n\r\n")
5822 mset.outq.send(newJSPubMsg(reply, _EMPTY_, _EMPTY_, hdr, nil, nil, 0))
5823 return
5824 }
5825 // Check we don't have conflicting options set.
5826 // We do not allow batch mode for lastFor requests.
5827 if (req.Seq > 0 && req.LastFor != _EMPTY_) ||
5828 (req.Seq > 0 && req.StartTime != nil) ||
5829 (req.StartTime != nil && req.LastFor != _EMPTY_) ||
5830 (req.LastFor != _EMPTY_ && req.NextFor != _EMPTY_) ||
5831 (req.LastFor != _EMPTY_ && req.Batch > 0) ||
5832 (req.LastFor != _EMPTY_ && len(req.MultiLastFor) > 0) ||
5833 (req.NextFor != _EMPTY_ && len(req.MultiLastFor) > 0) ||
5834 (req.UpToSeq > 0 && req.UpToTime != nil) {
5835 hdr := []byte("NATS/1.0 408 Bad Request\r\n\r\n")
5836 mset.outq.send(newJSPubMsg(reply, _EMPTY_, _EMPTY_, hdr, nil, nil, 0))
5837 return
5838 }
5839
5840 inlineOk := c.kind != ROUTER && c.kind != GATEWAY && c.kind != LEAF
5841 if !inlineOk {
5842 dg := dgPool.Get().(*directGetReq)
5843 dg.req, dg.reply = req, reply
5844 mset.gets.push(dg)
5845 } else {
5846 mset.getDirectRequest(&req, reply)
5847 }
5848 }
5849
5850 // This is for direct get by last subject which is part of the subject itself.
5851 func (mset *stream) processDirectGetLastBySubjectRequest(_ *subscription, c *client, _ *Account, subject, reply string, rmsg []byte) {
5852 if len(reply) == 0 {
5853 return
5854 }
5855 hdr, msg := c.msgParts(rmsg)
5856 if errorOnRequiredApiLevel(hdr) {
5857 hdr := []byte("NATS/1.0 412 Required Api Level\r\n\r\n")
5858 mset.outq.send(newJSPubMsg(reply, _EMPTY_, _EMPTY_, hdr, nil, nil, 0))
5859 return
5860 }
5861
5862 var req JSApiMsgGetRequest
5863 if len(msg) > 0 {
5864 err := json.Unmarshal(msg, &req)
5865 if err != nil {
5866 hdr := []byte("NATS/1.0 408 Malformed Request\r\n\r\n")
5867 mset.outq.send(newJSPubMsg(reply, _EMPTY_, _EMPTY_, hdr, nil, nil, 0))
5868 return
5869 }
5870 }
5871
5872 // Extract the key.
5873 var key string
5874 for i, n := 0, 0; i < len(subject); i++ {
5875 if subject[i] == btsep {
5876 if n == 4 {
5877 if start := i + 1; start < len(subject) {
5878 key = subject[i+1:]
5879 }
5880 break
5881 }
5882 n++
5883 }
5884 }
5885 if len(key) == 0 {
5886 hdr := []byte("NATS/1.0 408 Bad Request\r\n\r\n")
5887 mset.outq.send(newJSPubMsg(reply, _EMPTY_, _EMPTY_, hdr, nil, nil, 0))
5888 return
5889 }
5890
5891 // Error if request fields are provided that don't make sense for this endpoint.
5892 switch {
5893 case req.LastFor != _EMPTY_, req.NextFor != _EMPTY_,
5894 len(req.MultiLastFor) > 0, req.Seq != 0, req.Batch != 0,
5895 req.StartTime != nil, req.UpToSeq != 0, req.UpToTime != nil:
5896 hdr := []byte("NATS/1.0 408 Bad Request\r\n\r\n")
5897 mset.outq.send(newJSPubMsg(reply, _EMPTY_, _EMPTY_, hdr, nil, nil, 0))
5898 return
5899 default:
5900 req.LastFor = key
5901 }
5902
5903 inlineOk := c.kind != ROUTER && c.kind != GATEWAY && c.kind != LEAF
5904 if !inlineOk {
5905 dg := dgPool.Get().(*directGetReq)
5906 dg.req, dg.reply = req, reply
5907 mset.gets.push(dg)
5908 } else {
5909 mset.getDirectRequest(&req, reply)
5910 }
5911 }
5912
5913 // For direct get batch and multi requests.
5914 const (
5915 dg = "NATS/1.0\r\nNats-Stream: %s\r\nNats-Subject: %s\r\nNats-Sequence: %d\r\nNats-Time-Stamp: %s\r\n\r\n"
5916 dgb = "NATS/1.0\r\nNats-Stream: %s\r\nNats-Subject: %s\r\nNats-Sequence: %d\r\nNats-Time-Stamp: %s\r\nNats-Num-Pending: %d\r\nNats-Last-Sequence: %d\r\n\r\n"
5917 eob = "NATS/1.0 204 EOB\r\nNats-Num-Pending: %d\r\nNats-Last-Sequence: %d\r\n\r\n"
5918 eobm = "NATS/1.0 204 EOB\r\nNats-Num-Pending: %d\r\nNats-Last-Sequence: %d\r\nNats-UpTo-Sequence: %d\r\n\r\n"
5919 )
5920
5921 // Handle a multi request.
5922 func (mset *stream) getDirectMulti(req *JSApiMsgGetRequest, reply string) {
5923 // TODO(dlc) - Make configurable?
5924 const maxAllowedResponses = 1024
5925
5926 store, s := mset.store, mset.srv
5927 name := mset.getCfgName()
5928
5929 // Ensure this read request is isolated and doesn't interleave with writes.
5930 mset.isolateMu.RLock()
5931 defer mset.isolateMu.RUnlock()
5932
5933 // Grab MaxBytes
5934 mb := req.MaxBytes
5935 if mb == 0 && s != nil {
5936 // Fill in with the server's MaxPending.
5937 mb = int(s.opts.MaxPending)
5938 }
5939
5940 upToSeq := req.UpToSeq
5941 // If we have UpToTime set get the proper sequence.
5942 if req.UpToTime != nil {
5943 upToSeq = store.GetSeqFromTime((*req.UpToTime).UTC())
5944 var state StreamState
5945 store.FastState(&state)
5946 // Avoid selecting a first sequence that will take us to before the stream first
5947 // sequence, otherwise we can return messages after the supplied UpToTime.
5948 if upToSeq <= state.FirstSeq {
5949 hdr := []byte("NATS/1.0 404 No Results\r\n\r\n")
5950 mset.outq.send(newJSPubMsg(reply, _EMPTY_, _EMPTY_, hdr, nil, nil, 0))
5951 return
5952 }
5953 // We need to back off one since this is used to determine start sequence normally,
5954 // whereas here we want it to be the ceiling.
5955 upToSeq--
5956 }
5957 // If not set, set to the last sequence and remember that for EOB.
5958 if upToSeq == 0 {
5959 var state StreamState
5960 store.FastState(&state)
5961 upToSeq = state.LastSeq
5962 }
5963
5964 var lseq uint64
5965 var sentBytes, sent int
5966 total, np, err := store.MultiLastMsgs(req.MultiLastFor, req.Seq, upToSeq, maxAllowedResponses, func(sm *StoreMsg, np uint64) bool {
5967 hdr := sm.hdr
5968 ts := time.Unix(0, sm.ts).UTC()
5969
5970 if len(hdr) == 0 {
5971 hdr = fmt.Appendf(nil, dgb, name, sm.subj, sm.seq, ts.Format(time.RFC3339Nano), np, lseq)
5972 } else {
5973 hdr = copyBytes(hdr)
5974 hdr = genHeader(hdr, JSStream, name)
5975 hdr = genHeader(hdr, JSSubject, sm.subj)
5976 hdr = genHeader(hdr, JSSequence, strconv.FormatUint(sm.seq, 10))
5977 hdr = genHeader(hdr, JSTimeStamp, ts.Format(time.RFC3339Nano))
5978 hdr = genHeader(hdr, JSNumPending, strconv.FormatUint(np, 10))
5979 hdr = genHeader(hdr, JSLastSequence, strconv.FormatUint(lseq, 10))
5980 }
5981 // Track our lseq
5982 lseq = sm.seq
5983 // Send out our message.
5984 mset.outq.send(newJSPubMsg(reply, _EMPTY_, _EMPTY_, hdr, sm.msg, nil, 0))
5985 // Check if we have exceeded max bytes.
5986 sentBytes += len(sm.subj) + len(sm.hdr) + len(sm.msg)
5987 if sentBytes >= mb {
5988 return false
5989 }
5990 sent++
5991 if req.Batch > 0 && sent >= req.Batch {
5992 return false
5993 }
5994 return true
5995 })
5996 if err != nil {
5997 var hdr []byte
5998 switch {
5999 case err == ErrTooManyResults:
6000 hdr = []byte("NATS/1.0 413 Too Many Results\r\n\r\n")
6001 case total > 0:
6002 // A resolved message failed to load. Errors are folded into a 404
6003 // regardless of cause, so internal errors don't leak to clients.
6004 hdr = []byte("NATS/1.0 404 Message Not Found\r\n\r\n")
6005 default:
6006 hdr = []byte(fmt.Sprintf("NATS/1.0 500 %v\r\n\r\n", err))
6007 }
6008 mset.outq.send(newJSPubMsg(reply, _EMPTY_, _EMPTY_, hdr, nil, nil, 0))
6009 return
6010 }
6011 if total == 0 {
6012 hdr := []byte("NATS/1.0 404 No Results\r\n\r\n")
6013 mset.outq.send(newJSPubMsg(reply, _EMPTY_, _EMPTY_, hdr, nil, nil, 0))
6014 return
6015 }
6016
6017 // Send out EOB
6018 hdr := fmt.Appendf(nil, eobm, np, lseq, upToSeq)
6019 mset.outq.send(newJSPubMsg(reply, _EMPTY_, _EMPTY_, hdr, nil, nil, 0))
6020 }
6021
6022 // Do actual work on a direct msg request.
6023 // This could be called in a Go routine if we are inline for a non-client connection.
6024 func (mset *stream) getDirectRequest(req *JSApiMsgGetRequest, reply string) {
6025 // Handle multi in separate function.
6026 if len(req.MultiLastFor) > 0 {
6027 mset.getDirectMulti(req, reply)
6028 return
6029 }
6030
6031 store, s := mset.store, mset.srv
6032 name := mset.getCfgName()
6033
6034 // Ensure this read request is isolated and doesn't interleave with writes.
6035 mset.isolateMu.RLock()
6036 defer mset.isolateMu.RUnlock()
6037
6038 var seq uint64
6039 // Lookup start seq if AsOfTime is set.
6040 if req.StartTime != nil {
6041 seq = store.GetSeqFromTime(*req.StartTime)
6042 } else {
6043 seq = req.Seq
6044 }
6045
6046 wc := subjectHasWildcard(req.NextFor)
6047 // For tracking num pending if we are batch.
6048 var np, lseq, validThrough uint64
6049 var isBatchRequest bool
6050 batch := req.Batch
6051 if batch == 0 {
6052 batch = 1
6053 } else {
6054 // This is a batch request, capture initial numPending.
6055 isBatchRequest = true
6056 var err error
6057 if np, validThrough, err = store.NumPending(seq, req.NextFor, false); err != nil {
6058 return
6059 }
6060 }
6061
6062 // Grab MaxBytes
6063 mb := req.MaxBytes
6064 if mb == 0 && s != nil {
6065 // Fill in with the server's MaxPending.
6066 mb = int(s.opts.MaxPending)
6067 }
6068 // Track what we have sent.
6069 var sentBytes int
6070
6071 // Loop over batch, which defaults to 1.
6072 for i := 0; i < batch; i++ {
6073 var (
6074 svp StoreMsg
6075 sm *StoreMsg
6076 err error
6077 )
6078 if seq > 0 && req.NextFor == _EMPTY_ {
6079 // Only do direct lookup for a non batch.
6080 if i == 0 && !isBatchRequest {
6081 sm, err = store.LoadMsg(seq, &svp)
6082 } else {
6083 // We want to use load next with fwcs to step over deleted msgs.
6084 sm, seq, err = store.LoadNextMsg(fwcs, true, seq, &svp)
6085 }
6086 // Bump for next loop if applicable.
6087 seq++
6088 } else if req.NextFor != _EMPTY_ {
6089 sm, seq, err = store.LoadNextMsg(req.NextFor, wc, seq, &svp)
6090 seq++
6091 } else {
6092 // Batch is not applicable here, this is checked before we get here.
6093 sm, err = store.LoadLastMsg(req.LastFor, &svp)
6094 }
6095 if err != nil {
6096 // For batches, if we stop early we want to do EOB logic below.
6097 if batch > 1 && i > 0 {
6098 break
6099 }
6100 hdr := []byte("NATS/1.0 404 Message Not Found\r\n\r\n")
6101 mset.outq.send(newJSPubMsg(reply, _EMPTY_, _EMPTY_, hdr, nil, nil, 0))
6102 return
6103 }
6104
6105 ts := time.Unix(0, sm.ts).UTC()
6106 var hdr []byte
6107 if !req.NoHeaders {
6108 hdr = sm.hdr
6109 if isBatchRequest {
6110 // Decrement num pending. This is an optimization, and we do not continue to look it up for these operations.
6111 if np > 0 {
6112 np--
6113 }
6114 if len(hdr) == 0 {
6115 hdr = fmt.Appendf(nil, dgb, name, sm.subj, sm.seq, ts.Format(time.RFC3339Nano), np, lseq)
6116 } else {
6117 hdr = copyBytes(hdr)
6118 hdr = genHeader(hdr, JSStream, name)
6119 hdr = genHeader(hdr, JSSubject, sm.subj)
6120 hdr = genHeader(hdr, JSSequence, strconv.FormatUint(sm.seq, 10))
6121 hdr = genHeader(hdr, JSTimeStamp, ts.Format(time.RFC3339Nano))
6122 hdr = genHeader(hdr, JSNumPending, strconv.FormatUint(np, 10))
6123 hdr = genHeader(hdr, JSLastSequence, strconv.FormatUint(lseq, 10))
6124 }
6125 } else {
6126 if len(hdr) == 0 {
6127 hdr = fmt.Appendf(nil, dg, name, sm.subj, sm.seq, ts.Format(time.RFC3339Nano))
6128 } else {
6129 hdr = copyBytes(hdr)
6130 hdr = genHeader(hdr, JSStream, name)
6131 hdr = genHeader(hdr, JSSubject, sm.subj)
6132 hdr = genHeader(hdr, JSSequence, strconv.FormatUint(sm.seq, 10))
6133 hdr = genHeader(hdr, JSTimeStamp, ts.Format(time.RFC3339Nano))
6134 }
6135 }
6136 }
6137 // Track our lseq
6138 lseq = sm.seq
6139 // Send out our message.
6140 mset.outq.send(newJSPubMsg(reply, _EMPTY_, _EMPTY_, hdr, sm.msg, nil, 0))
6141 // Check if we have exceeded max bytes.
6142 sentBytes += len(sm.subj) + len(sm.hdr) + len(sm.msg)
6143 if sentBytes >= mb {
6144 break
6145 }
6146 }
6147
6148 // If batch was requested send EOB.
6149 if isBatchRequest {
6150 // Update if the stream's last sequence has moved past our validThrough.
6151 var state StreamState
6152 store.FastState(&state)
6153 if state.LastSeq > validThrough {
6154 var err error
6155 if np, _, err = store.NumPending(seq, req.NextFor, false); err != nil {
6156 return
6157 }
6158 }
6159 hdr := fmt.Appendf(nil, eob, np, lseq)
6160 mset.outq.send(newJSPubMsg(reply, _EMPTY_, _EMPTY_, hdr, nil, nil, 0))
6161 }
6162 }
6163
6164 // processInboundJetStreamMsg handles processing messages bound for a stream.
6165 func (mset *stream) processInboundJetStreamMsg(_ *subscription, c *client, _ *Account, subject, reply string, rmsg []byte) {
6166 hdr, msg := c.msgParts(copyBytes(rmsg)) // Need to copy.
6167 hdr = removeHeaderStatusIfPresent(hdr)
6168 if mt, traceOnly := c.isMsgTraceEnabled(); mt != nil {
6169 // If message is delivered, we need to disable the message trace headers
6170 // to prevent a trace event to be generated when a stored message
6171 // is delivered to a consumer and routed.
6172 if !traceOnly {
6173 hdr = setHeader(MsgTraceDest, MsgTraceDestDisabled, hdr)
6174 }
6175 // This will add the jetstream event while in the client read loop.
6176 // Since the event will be updated in a different go routine, the
6177 // tracing object will have a separate reference to the JS trace
6178 // object.
6179 mt.addJetStreamEvent(mset.name())
6180 }
6181 mset.queueInbound(mset.msgs, subject, reply, hdr, msg, nil, c.pa.trace)
6182 }
6183
6184 var (
6185 errLastSeqMismatch = errors.New("last sequence mismatch")
6186 errMsgIdDuplicate = errors.New("msgid is duplicate")
6187 errStreamClosed = errors.New("stream closed")
6188 errInvalidMsgHandler = errors.New("undefined message handler")
6189 errStreamMismatch = errors.New("expected stream does not match")
6190 errMsgTTLDisabled = errors.New("message TTL disabled")
6191 )
6192
6193 // processJetStreamMsg is where we try to actually process the stream msg.
6194 // needIsolation should be false only if the caller already holds isolateMu
6195 // across a whole atomic batch; mset.mu must NOT be held by the caller.
6196 func (mset *stream) processJetStreamMsg(subject, reply string, hdr, msg []byte, lseq uint64, ts int64, mt *msgTrace, sourced bool, needIsolation bool) error {
6197 return mset.processJetStreamMsgWithBatch(subject, reply, hdr, msg, lseq, ts, mt, sourced, needIsolation, nil)
6198 }
6199
6200 func (mset *stream) processJetStreamMsgWithBatch(subject, reply string, hdr, msg []byte, lseq uint64, ts int64, mt *msgTrace, sourced bool, needIsolation bool, fastBatch *FastBatch) (retErr error) {
6201 if mt != nil {
6202 // Only the leader/standalone will have mt!=nil. On exit, send the
6203 // message trace event.
6204 defer func() {
6205 mt.sendEventFromJetStream(retErr)
6206 }()
6207 }
6208
6209 if mset == nil || mset.closed.Load() {
6210 return errStreamClosed
6211 }
6212
6213 // Hold lock while storing the message, and potentially purging as part of a rollup.
6214 // If we're writing an atomic batch of multiple messages, the lock is already held.
6215 if needIsolation {
6216 mset.isolateMu.Lock()
6217 defer mset.isolateMu.Unlock()
6218 }
6219 // Hold the stream lock for the lifetime of processing a single message.
6220 mset.mu.Lock()
6221 defer mset.mu.Unlock()
6222
6223 s, store := mset.srv, mset.store
6224
6225 traceOnly := mt.traceOnly()
6226 bumpCLFS := func() {
6227 // Do not bump if tracing and not doing message delivery.
6228 if traceOnly {
6229 return
6230 }
6231 mset.clMu.Lock()
6232 mset.clfs++
6233 mset.clMu.Unlock()
6234 }
6235
6236 // Apply the input subject transform if any
6237 if mset.itr != nil {
6238 ts, err := mset.itr.Match(subject)
6239 if err == nil {
6240 // no filtering: if the subject doesn't map the source of the transform, don't change it
6241 subject = ts
6242 }
6243 }
6244
6245 var accName string
6246 if mset.acc != nil {
6247 accName = mset.acc.Name
6248 }
6249
6250 js, jsa, doAck := mset.js, mset.jsa, !mset.cfg.NoAck
6251 name, stype := mset.cfg.Name, mset.cfg.Storage
6252 maxMsgSize := int(mset.cfg.MaxMsgSize)
6253 numConsumers := len(mset.consumers)
6254 interestRetention := mset.cfg.Retention == InterestPolicy
6255 allowMsgCounter, allowMsgSchedules := mset.cfg.AllowMsgCounter, mset.cfg.AllowMsgSchedules
6256 allowRollupPurge := mset.cfg.AllowRollup && !mset.cfg.DenyPurge
6257 // Snapshot if we are the leader and if we can respond.
6258 isLeader, isSealed := mset.isLeaderNodeState(), mset.cfg.Sealed
6259 isClustered, isMirror := mset.isClustered(), mset.cfg.Mirror != nil
6260 canConsistencyCheck := !isClustered || traceOnly
6261 canRespond := doAck && len(reply) > 0 && isLeader
6262 outq := mset.outq
6263
6264 var resp = &JSPubAckResponse{}
6265
6266 if canConsistencyCheck && stype == FileStorage && isFileStoreMsgTooLarge(fileStoreMsgSize(subject, hdr, msg)) {
6267 if canRespond {
6268 resp.PubAck = &PubAck{Stream: name}
6269 resp.Error = NewJSStreamStoreFailedError(ErrMsgTooLarge)
6270 response, _ := json.Marshal(resp)
6271 outq.sendMsg(reply, response)
6272 }
6273 return ErrMsgTooLarge
6274 }
6275
6276 var (
6277 batchId string
6278 batchSeq uint64
6279 )
6280 // Populate batch details.
6281 if fastBatch != nil {
6282 // For R1 we can reuse without regenerating.
6283 batchId, batchSeq = fastBatch.id, fastBatch.seq
6284 // Disable consistency checking if this was already done
6285 // earlier as part of the batch consistency check.
6286 canConsistencyCheck = traceOnly
6287 } else if fastBatch, _ = getFastBatch(reply, hdr); fastBatch != nil {
6288 defer fastBatch.returnToPool()
6289 batchId, batchSeq = fastBatch.id, fastBatch.seq
6290 // Disable consistency checking if this was already done
6291 // earlier as part of the batch consistency check.
6292 canConsistencyCheck = traceOnly
6293 }
6294 if len(hdr) > 0 && batchId == _EMPTY_ {
6295 if batchId = getBatchId(hdr); batchId != _EMPTY_ {
6296 batchSeq, _ = getBatchSequence(hdr)
6297 // Disable consistency checking if this was already done
6298 // earlier as part of the batch consistency check.
6299 canConsistencyCheck = traceOnly
6300 }
6301 }
6302
6303 // Bail here if sealed.
6304 if canConsistencyCheck && isSealed {
6305 if canRespond && outq != nil {
6306 resp.PubAck = &PubAck{Stream: name}
6307 resp.Error = ApiErrors[JSStreamSealedErr]
6308 b, _ := json.Marshal(resp)
6309 outq.sendMsg(reply, b)
6310 }
6311 return ApiErrors[JSStreamSealedErr]
6312 }
6313
6314 var buf [256]byte
6315 pubAck := append(buf[:0], mset.pubAck...)
6316
6317 // If this is a non-clustered msg and we are not considered active, meaning no active subscription, do not process.
6318 if lseq == 0 && ts == 0 && !mset.active {
6319 return nil
6320 }
6321
6322 // For clustering the lower layers will pass our expected lseq. If it is present check for that here.
6323 var clfs uint64
6324 if lseq > 0 {
6325 clfs = mset.getCLFS()
6326 if lseq != (mset.lseq + clfs) {
6327 isMisMatch := true
6328 // We may be able to recover here if we have no state whatsoever, or we are a mirror.
6329 // See if we have to adjust our starting sequence.
6330 if mset.lseq == 0 || isMirror {
6331 var state StreamState
6332 mset.store.FastState(&state)
6333 if state.FirstSeq == 0 {
6334 if _, err := mset.store.Compact(lseq + 1); err != nil {
6335 return err
6336 }
6337 mset.lseq = lseq
6338 isMisMatch = false
6339 }
6340 }
6341 // Really is a mismatch.
6342 if isMisMatch {
6343 if canRespond && outq != nil {
6344 resp.PubAck = &PubAck{Stream: name}
6345 resp.Error = ApiErrors[JSStreamSequenceNotMatchErr]
6346 b, _ := json.Marshal(resp)
6347 outq.sendMsg(reply, b)
6348 }
6349 return errLastSeqMismatch
6350 }
6351 }
6352 }
6353
6354 // If we have received this message across an account we may have request information attached.
6355 // For now remove. TODO(dlc) - Should this be opt-in or opt-out?
6356 if len(hdr) > 0 {
6357 hdr = removeHeaderIfPresent(hdr, ClientInfoHdr)
6358 }
6359
6360 // Process additional msg headers if still present.
6361 var msgId string
6362 var incr *big.Int
6363 var rollupSub, rollupAll bool
6364
6365 if len(hdr) > 0 {
6366 // Certain checks have already been performed if in clustered mode, so only check if not.
6367 // Note, for cluster mode but with message tracing (without message delivery), we need
6368 // to do this check here since it was not done in processClusteredInboundMsg().
6369 if canConsistencyCheck {
6370 // Counter increments.
6371 // Only supported on counter streams, and payload must be empty (if not coming from a source).
6372 var ok bool
6373 if incr, ok = getMessageIncr(hdr); !ok {
6374 apiErr := NewJSMessageIncrInvalidError()
6375 if canRespond {
6376 resp.PubAck = &PubAck{Stream: name}
6377 resp.Error = apiErr
6378 b, _ := json.Marshal(resp)
6379 outq.sendMsg(reply, b)
6380 }
6381 return apiErr
6382 } else if incr != nil && !sourced {
6383 // Only do checks if the message isn't sourced. Otherwise, we need to store verbatim.
6384 if !allowMsgCounter {
6385 apiErr := NewJSMessageIncrDisabledError()
6386 if canRespond {
6387 resp.PubAck = &PubAck{Stream: name}
6388 resp.Error = apiErr
6389 b, _ := json.Marshal(resp)
6390 outq.sendMsg(reply, b)
6391 }
6392 return apiErr
6393 } else if len(msg) > 0 {
6394 apiErr := NewJSMessageIncrPayloadError()
6395 if canRespond {
6396 resp.PubAck = &PubAck{Stream: name}
6397 resp.Error = apiErr
6398 b, _ := json.Marshal(resp)
6399 outq.sendMsg(reply, b)
6400 }
6401 return apiErr
6402 } else {
6403 // Check for incompatible headers.
6404 var doErr bool
6405 if getRollup(hdr) != _EMPTY_ ||
6406 getExpectedStream(hdr) != _EMPTY_ ||
6407 getExpectedLastMsgId(hdr) != _EMPTY_ ||
6408 getExpectedLastSeqPerSubjectForSubject(hdr) != _EMPTY_ {
6409 doErr = true
6410 } else if _, ok := getExpectedLastSeq(hdr); ok {
6411 doErr = true
6412 } else if _, ok := getExpectedLastSeqPerSubject(hdr); ok {
6413 doErr = true
6414 }
6415
6416 if doErr {
6417 apiErr := NewJSMessageIncrInvalidError()
6418 if canRespond {
6419 resp.PubAck = &PubAck{Stream: name}
6420 resp.Error = apiErr
6421 b, _ := json.Marshal(resp)
6422 outq.sendMsg(reply, b)
6423 }
6424 return apiErr
6425 }
6426 }
6427 }
6428
6429 // Expected stream.
6430 if sname := getExpectedStream(hdr); sname != _EMPTY_ && sname != name {
6431 if canRespond {
6432 resp.PubAck = &PubAck{Stream: name}
6433 resp.Error = NewJSStreamNotMatchError()
6434 b, _ := json.Marshal(resp)
6435 outq.sendMsg(reply, b)
6436 }
6437 return errStreamMismatch
6438 }
6439
6440 // TTL'd messages are rejected entirely if TTLs are not enabled on the stream.
6441 // Shouldn't happen in clustered mode since we should have already caught this
6442 // in processClusteredInboundMsg, but needed here for non-clustered etc.
6443 if ttl, _ := getMessageTTL(hdr); !sourced && ttl != 0 && !mset.cfg.AllowMsgTTL {
6444 if canRespond {
6445 resp.PubAck = &PubAck{Stream: name}
6446 resp.Error = NewJSMessageTTLDisabledError()
6447 b, _ := json.Marshal(resp)
6448 outq.sendMsg(reply, b)
6449 }
6450 return errMsgTTLDisabled
6451 }
6452
6453 // Expected last sequence per subject.
6454 if seq, exists := getExpectedLastSeqPerSubject(hdr); exists {
6455 // Allow override of the subject used for the check.
6456 seqSubj := subject
6457 if optSubj := getExpectedLastSeqPerSubjectForSubject(hdr); optSubj != _EMPTY_ {
6458 seqSubj = optSubj
6459 }
6460
6461 // TODO(dlc) - We could make a new store func that does this all in one.
6462 var smv StoreMsg
6463 var fseq uint64
6464 sm, err := store.LoadLastMsg(seqSubj, &smv)
6465 if sm != nil {
6466 fseq = sm.seq
6467 }
6468 if err == ErrStoreMsgNotFound && seq == 0 {
6469 fseq, err = 0, nil
6470 }
6471 if err != nil || fseq != seq {
6472 if canRespond {
6473 resp.PubAck = &PubAck{Stream: name}
6474 resp.Error = NewJSStreamWrongLastSequenceError(fseq)
6475 b, _ := json.Marshal(resp)
6476 outq.sendMsg(reply, b)
6477 }
6478 return fmt.Errorf("last sequence by subject mismatch: %d vs %d", seq, fseq)
6479 }
6480 } else if getExpectedLastSeqPerSubjectForSubject(hdr) != _EMPTY_ {
6481 apiErr := NewJSStreamExpectedLastSeqPerSubjectInvalidError()
6482 if canRespond {
6483 resp.PubAck = &PubAck{Stream: name}
6484 resp.Error = apiErr
6485 b, _ := json.Marshal(resp)
6486 outq.sendMsg(reply, b)
6487 }
6488 return apiErr
6489 }
6490
6491 // Expected last sequence.
6492 if seq, exists := getExpectedLastSeq(hdr); exists && seq != mset.lseq {
6493 mlseq := mset.lseq
6494 if canRespond {
6495 resp.PubAck = &PubAck{Stream: name}
6496 resp.Error = NewJSStreamWrongLastSequenceError(mlseq)
6497 b, _ := json.Marshal(resp)
6498 outq.sendMsg(reply, b)
6499 }
6500 return fmt.Errorf("last sequence mismatch: %d vs %d", seq, mlseq)
6501 }
6502
6503 // Message scheduling.
6504 if sourced {
6505 // noop, sourced messages were already validated by the origin stream.
6506 } else if schedule, apiErr := getMessageSchedule(hdr); apiErr != nil {
6507 if !allowMsgSchedules {
6508 apiErr = NewJSMessageSchedulesDisabledError()
6509 }
6510 if canRespond {
6511 resp.PubAck = &PubAck{Stream: name}
6512 resp.Error = apiErr
6513 b, _ := json.Marshal(resp)
6514 outq.sendMsg(reply, b)
6515 }
6516 return apiErr
6517 } else if !schedule.IsZero() {
6518 if !allowMsgSchedules {
6519 apiErr := NewJSMessageSchedulesDisabledError()
6520 if canRespond {
6521 resp.PubAck = &PubAck{Stream: name}
6522 resp.Error = apiErr
6523 b, _ := json.Marshal(resp)
6524 outq.sendMsg(reply, b)
6525 }
6526 return apiErr
6527 } else if scheduleTtl, ok := getMessageScheduleTTL(hdr); !ok {
6528 apiErr := NewJSMessageSchedulesTTLInvalidError()
6529 if canRespond {
6530 resp.PubAck = &PubAck{Stream: name}
6531 resp.Error = apiErr
6532 b, _ := json.Marshal(resp)
6533 outq.sendMsg(reply, b)
6534 }
6535 return apiErr
6536 } else if scheduleRollup := getMessageScheduleRollup(hdr); scheduleRollup != _EMPTY_ && scheduleRollup != JSMsgRollupSubject {
6537 apiErr := NewJSMessageSchedulesRollupInvalidError()
6538 if canRespond {
6539 resp.PubAck = &PubAck{Stream: name}
6540 resp.Error = apiErr
6541 b, _ := json.Marshal(resp)
6542 outq.sendMsg(reply, b)
6543 }
6544 return apiErr
6545 } else if scheduleTtl != _EMPTY_ && !mset.cfg.AllowMsgTTL {
6546 if canRespond {
6547 resp.PubAck = &PubAck{Stream: name}
6548 resp.Error = NewJSMessageTTLDisabledError()
6549 b, _ := json.Marshal(resp)
6550 outq.sendMsg(reply, b)
6551 }
6552 return errMsgTTLDisabled
6553 } else if scheduleTarget := getMessageScheduleTarget(hdr); scheduleTarget == _EMPTY_ ||
6554 !IsValidPublishSubject(scheduleTarget) || scheduleTarget == subject {
6555 apiErr := NewJSMessageSchedulesTargetInvalidError()
6556 if canRespond {
6557 resp.PubAck = &PubAck{Stream: name}
6558 resp.Error = apiErr
6559 b, _ := json.Marshal(resp)
6560 outq.sendMsg(reply, b)
6561 }
6562 return apiErr
6563 } else if scheduleSource := getMessageScheduleSource(hdr); scheduleSource != _EMPTY_ &&
6564 (scheduleSource == scheduleTarget || scheduleSource == subject || !IsValidPublishSubject(scheduleSource)) {
6565 apiErr := NewJSMessageSchedulesSourceInvalidError()
6566 if canRespond {
6567 resp.PubAck = &PubAck{Stream: name}
6568 resp.Error = apiErr
6569 b, _ := json.Marshal(resp)
6570 outq.sendMsg(reply, b)
6571 }
6572 return apiErr
6573 } else {
6574 match := slices.ContainsFunc(mset.cfg.Subjects, func(subj string) bool {
6575 return SubjectsCollide(subj, scheduleTarget)
6576 })
6577 if !match {
6578 apiErr := NewJSMessageSchedulesTargetInvalidError()
6579 if canRespond {
6580 resp.PubAck = &PubAck{Stream: name}
6581 resp.Error = apiErr
6582 b, _ := json.Marshal(resp)
6583 outq.sendMsg(reply, b)
6584 }
6585 return apiErr
6586 }
6587 if scheduleSource != _EMPTY_ {
6588 match = slices.ContainsFunc(mset.cfg.Subjects, func(subj string) bool {
6589 return SubjectsCollide(subj, scheduleSource)
6590 })
6591 if !match {
6592 apiErr := NewJSMessageSchedulesSourceInvalidError()
6593 if canRespond {
6594 resp.PubAck = &PubAck{Stream: name}
6595 resp.Error = apiErr
6596 b, _ := json.Marshal(resp)
6597 outq.sendMsg(reply, b)
6598 }
6599 return apiErr
6600 }
6601 }
6602
6603 // Add a rollup sub header if it doesn't already exist.
6604 // Otherwise, it must exist already as a rollup on the subject.
6605 if rollup := getRollup(hdr); rollup == _EMPTY_ {
6606 hdr = genHeader(hdr, JSMsgRollup, JSMsgRollupSubject)
6607 } else if rollup != JSMsgRollupSubject {
6608 apiErr := NewJSMessageSchedulesRollupInvalidError()
6609 if canRespond {
6610 resp.PubAck = &PubAck{Stream: name}
6611 resp.Error = apiErr
6612 b, _ := json.Marshal(resp)
6613 outq.sendMsg(reply, b)
6614 }
6615 return apiErr
6616 }
6617 }
6618 }
6619 if scheduleNext := sliceHeader(JSScheduleNext, hdr); len(scheduleNext) > 0 && !sourced {
6620 // Clients may only use Nats-Schedule-Next to purge a schedule.
6621 if bytesToString(scheduleNext) != JSScheduleNextPurge {
6622 apiErr := NewJSMessageSchedulesSchedulerInvalidError()
6623 if canRespond {
6624 resp.PubAck = &PubAck{Stream: name}
6625 resp.Error = apiErr
6626 b, _ := json.Marshal(resp)
6627 outq.sendMsg(reply, b)
6628 }
6629 return apiErr
6630 }
6631 // Nats-Scheduler must accompany the purge and:
6632 // - it must NOT be empty.
6633 // - it must NOT match the publish subject.
6634 if scheduler := sliceHeader(JSScheduler, hdr); len(scheduler) == 0 ||
6635 bytesToString(scheduler) == subject || !IsValidPublishSubject(bytesToString(scheduler)) {
6636 apiErr := NewJSMessageSchedulesSchedulerInvalidError()
6637 if canRespond {
6638 resp.PubAck = &PubAck{Stream: name}
6639 resp.Error = apiErr
6640 b, _ := json.Marshal(resp)
6641 outq.sendMsg(reply, b)
6642 }
6643 return apiErr
6644 } else if !allowMsgSchedules {
6645 apiErr := NewJSMessageSchedulesDisabledError()
6646 if canRespond {
6647 resp.PubAck = &PubAck{Stream: name}
6648 resp.Error = apiErr
6649 b, _ := json.Marshal(resp)
6650 outq.sendMsg(reply, b)
6651 }
6652 return apiErr
6653 } else {
6654 // Check that the to-be-purged subject is a schedule message.
6655 // We still allow this message through if there exists no message for this subject,
6656 // to remain backward-compatible. An "expected at sequence" check can still be
6657 // performed to make this stricter.
6658 var smv StoreMsg
6659 sm, _ := store.LoadLastMsg(bytesToString(scheduler), &smv)
6660 if sm != nil && len(sliceHeader(JSSchedulePattern, sm.hdr)) == 0 {
6661 apiErr := NewJSMessageSchedulesSchedulerInvalidError()
6662 if canRespond {
6663 resp.PubAck = &PubAck{Stream: name}
6664 resp.Error = apiErr
6665 b, _ := json.Marshal(resp)
6666 outq.sendMsg(reply, b)
6667 }
6668 return apiErr
6669 }
6670 }
6671 } else if !sourced && len(sliceHeader(JSScheduler, hdr)) > 0 {
6672 // Clients may only use Nats-Scheduler alongside Nats-Schedule-Next.
6673 apiErr := NewJSMessageSchedulesSchedulerInvalidError()
6674 if canRespond {
6675 resp.PubAck = &PubAck{Stream: name}
6676 resp.Error = apiErr
6677 b, _ := json.Marshal(resp)
6678 outq.sendMsg(reply, b)
6679 }
6680 return apiErr
6681 }
6682 }
6683
6684 // Dedupe detection. This is done at the cluster level for dedupe detection above the
6685 // lower layers. But we still need to pull out the msgId.
6686 if msgId = getMsgId(hdr); msgId != _EMPTY_ {
6687 // Do real check only if not clustered or traceOnly flag is set.
6688 // If we're mirroring we can't deduplicate on our own.
6689 if canConsistencyCheck && !isMirror {
6690 var seq uint64
6691 mset.ddMu.Lock()
6692 dde := mset.checkMsgId(msgId)
6693 if dde != nil {
6694 seq = dde.seq
6695 }
6696 mset.ddMu.Unlock()
6697 if seq > 0 {
6698 if canRespond {
6699 response := append(pubAck, strconv.FormatUint(seq, 10)...)
6700 response = append(response, ",\"duplicate\": true}"...)
6701 outq.sendMsg(reply, response)
6702 }
6703 return errMsgIdDuplicate
6704 }
6705 }
6706 }
6707
6708 // Expected last msgId.
6709 if lmsgId := getExpectedLastMsgId(hdr); lmsgId != _EMPTY_ {
6710 if lmsgId != mset.lmsgId {
6711 last := mset.lmsgId
6712 bumpCLFS()
6713 if canRespond {
6714 resp.PubAck = &PubAck{Stream: name}
6715 resp.Error = NewJSStreamWrongLastMsgIDError(last)
6716 b, _ := json.Marshal(resp)
6717 outq.sendMsg(reply, b)
6718 }
6719 return fmt.Errorf("last msgid mismatch: %q vs %q", lmsgId, last)
6720 }
6721 }
6722 // Check for any rollups.
6723 if rollup := getRollup(hdr); rollup != _EMPTY_ {
6724 if canConsistencyCheck && !allowRollupPurge && !sourced {
6725 err := errors.New("rollup not permitted")
6726 if canRespond {
6727 resp.PubAck = &PubAck{Stream: name}
6728 resp.Error = NewJSStreamRollupFailedError(err)
6729 b, _ := json.Marshal(resp)
6730 outq.sendMsg(reply, b)
6731 }
6732 return err
6733 }
6734 switch rollup {
6735 case JSMsgRollupSubject:
6736 rollupSub = true
6737 case JSMsgRollupAll:
6738 rollupAll = true
6739 default:
6740 if canConsistencyCheck {
6741 err := fmt.Errorf("rollup value invalid: %q", rollup)
6742 if canRespond {
6743 resp.PubAck = &PubAck{Stream: name}
6744 resp.Error = NewJSStreamRollupFailedError(err)
6745 b, _ := json.Marshal(resp)
6746 outq.sendMsg(reply, b)
6747 }
6748 return err
6749 }
6750 }
6751 }
6752 }
6753
6754 if canConsistencyCheck && incr == nil && allowMsgCounter {
6755 apiErr := NewJSMessageIncrMissingError()
6756 if canRespond {
6757 resp.PubAck = &PubAck{Stream: name}
6758 resp.Error = apiErr
6759 b, _ := json.Marshal(resp)
6760 outq.sendMsg(reply, b)
6761 }
6762 return apiErr
6763 }
6764
6765 // Response Ack.
6766 var (
6767 response []byte
6768 seq uint64
6769 err error
6770 )
6771
6772 // Apply increment for counter.
6773 // But only if it's allowed for this stream. This can happen when we store verbatim for a sourced stream.
6774 if canConsistencyCheck && incr != nil && allowMsgCounter {
6775 var initial big.Int
6776 var sources CounterSources
6777 var smv StoreMsg
6778 sm, err := store.LoadLastMsg(subject, &smv)
6779 if err == nil && sm != nil {
6780 var val CounterValue
6781 // Return an error if the counter is broken somehow.
6782 if json.Unmarshal(sm.msg, &val) != nil {
6783 apiErr := NewJSMessageCounterBrokenError()
6784 if canRespond {
6785 resp.PubAck = &PubAck{Stream: name}
6786 resp.Error = apiErr
6787 b, _ := json.Marshal(resp)
6788 outq.sendMsg(reply, b)
6789 }
6790 return apiErr
6791 }
6792 if ncs := sliceHeader(JSMessageCounterSources, sm.hdr); len(ncs) > 0 {
6793 if err := json.Unmarshal(ncs, &sources); err != nil {
6794 apiErr := NewJSMessageCounterBrokenError()
6795 if canRespond {
6796 resp.PubAck = &PubAck{Stream: name}
6797 resp.Error = apiErr
6798 b, _ := json.Marshal(resp)
6799 outq.sendMsg(reply, b)
6800 }
6801 return apiErr
6802 }
6803 }
6804 initial.SetString(val.Value, 10)
6805 }
6806 srchdr := sliceHeader(JSStreamSource, hdr)
6807 if len(srchdr) > 0 {
6808 // This is a sourced message, so we can't apply Nats-Incr but
6809 // instead should just update the source count header.
6810 fields := strings.Split(string(srchdr), " ")
6811 origStream := fields[0]
6812 origSubj := subject
6813 if len(fields) >= 5 {
6814 origSubj = fields[4]
6815 }
6816 var val CounterValue
6817 if json.Unmarshal(msg, &val) != nil {
6818 apiErr := NewJSMessageCounterBrokenError()
6819 if canRespond {
6820 resp.PubAck = &PubAck{Stream: name}
6821 resp.Error = apiErr
6822 b, _ := json.Marshal(resp)
6823 outq.sendMsg(reply, b)
6824 }
6825 return apiErr
6826 }
6827 var sourced big.Int
6828 sourced.SetString(val.Value, 10)
6829 if sources == nil {
6830 sources = map[string]map[string]string{}
6831 }
6832 if sources[origStream] == nil {
6833 sources[origStream] = map[string]string{}
6834 }
6835 prevVal := sources[origStream][origSubj]
6836 sources[origStream][origSubj] = sourced.String()
6837 // We will also replace the Nats-Incr header with the diff
6838 // between our last value from this source and this one, so
6839 // that the arithmetic is always correct.
6840 var previous big.Int
6841 previous.SetString(prevVal, 10)
6842 incr.Sub(&sourced, &previous)
6843 hdr = setHeader(JSMessageIncr, incr.String(), hdr)
6844 }
6845 // Now make the change.
6846 initial.Add(&initial, incr)
6847 // Generate the new payload.
6848 var _msg [128]byte
6849 msg = fmt.Appendf(_msg[:0], "{%q:%q}", "val", initial.String())
6850 // Write the updated source count headers.
6851 if len(sources) > 0 {
6852 nhdr, err := json.Marshal(sources)
6853 if err != nil {
6854 if canRespond {
6855 resp.PubAck = &PubAck{Stream: name}
6856 resp.Error = NewJSMessageCounterBrokenError()
6857 response, _ = json.Marshal(resp)
6858 outq.sendMsg(reply, response)
6859 }
6860 return err
6861 }
6862 hdr = setHeader(JSMessageCounterSources, string(nhdr), hdr)
6863 }
6864
6865 // Check to see if we are over the max msg size.
6866 // Subtract to prevent against overflows.
6867 maxPayload := int64(mset.srv.getOpts().MaxPayload)
6868 hdrLen, msgLen := int64(len(hdr)), int64(len(msg))
6869 if hdrLen > maxPayload || msgLen > maxPayload-hdrLen {
6870 if canRespond {
6871 resp.PubAck = &PubAck{Stream: name}
6872 resp.Error = NewJSStreamMessageExceedsMaximumError()
6873 response, _ = json.Marshal(resp)
6874 outq.sendMsg(reply, response)
6875 }
6876 return ErrMaxPayload
6877 }
6878 }
6879
6880 // Check to see if we are over the max msg size.
6881 // Subtract to prevent against overflows.
6882 if canConsistencyCheck && maxMsgSize >= 0 && (len(hdr) > maxMsgSize || len(msg) > maxMsgSize-len(hdr)) {
6883 if canRespond {
6884 resp.PubAck = &PubAck{Stream: name}
6885 resp.Error = NewJSStreamMessageExceedsMaximumError()
6886 response, _ = json.Marshal(resp)
6887 outq.sendMsg(reply, response)
6888 }
6889 return ErrMaxPayload
6890 }
6891
6892 if canConsistencyCheck && len(hdr) > math.MaxUint16 {
6893 if canRespond {
6894 resp.PubAck = &PubAck{Stream: name}
6895 resp.Error = NewJSStreamHeaderExceedsMaximumError()
6896 response, _ = json.Marshal(resp)
6897 outq.sendMsg(reply, response)
6898 }
6899 return ErrMaxPayload
6900 }
6901
6902 // Check to see if we have exceeded our limits.
6903 // Don't error and log/stepdown if we're tracing when clustered.
6904 if !isClustered && js.limitsExceeded(stype) {
6905 s.resourcesExceededError(stype)
6906 if canRespond {
6907 resp.PubAck = &PubAck{Stream: name}
6908 resp.Error = NewJSInsufficientResourcesError()
6909 response, _ = json.Marshal(resp)
6910 outq.sendMsg(reply, response)
6911 }
6912 // Stepdown regardless.
6913 if node := mset.node; node != nil {
6914 node.StepDown()
6915 }
6916 return NewJSInsufficientResourcesError()
6917 }
6918
6919 var noInterest bool
6920
6921 // If we are interest based retention and have no consumers then we can skip.
6922 if interestRetention {
6923 mset.clsMu.RLock()
6924 noInterest = numConsumers == 0 || mset.csl == nil || !mset.csl.HasInterest(subject)
6925 mset.clsMu.RUnlock()
6926 }
6927
6928 // Grab timestamp if not already set.
6929 if ts == 0 && lseq > 0 {
6930 ts = time.Now().UnixNano()
6931 }
6932
6933 mt.updateJetStreamEvent(subject, noInterest)
6934 if traceOnly {
6935 return nil
6936 }
6937
6938 // Skip msg here.
6939 if noInterest {
6940 mset.lseq, _ = store.SkipMsgNoInterest(0)
6941 mset.lmsgId = msgId
6942 // If we have a msgId make sure to save.
6943 if msgId != _EMPTY_ {
6944 mset.storeMsgId(&ddentry{msgId, mset.lseq, ts})
6945 }
6946 if allowRollupPurge {
6947 if err = mset.processJetStreamMsgWithRollup(subject, rollupSub, rollupAll, hdr, 0); err != nil {
6948 return err
6949 }
6950 }
6951 // If using fast batch publish, we occasionally send flow control messages.
6952 // And, we need to ensure a PubAck is sent if the commit happens through EOB.
6953 if fastBatch != nil {
6954 if mset.batches == nil {
6955 mset.batches = &batching{}
6956 }
6957 mset.batches.mu.Lock()
6958 // Check full leader state so we only send the client an update once we're caught up.
6959 commit := mset.batches.fastBatchRegisterSequences(mset, reply, mset.lseq, mset.isLeader(), fastBatch)
6960 mset.batches.mu.Unlock()
6961 if !commit {
6962 reply = _EMPTY_
6963 canRespond = false
6964 }
6965 }
6966 if canRespond {
6967 response = append(pubAck, strconv.FormatUint(mset.lseq, 10)...)
6968 if batchId != _EMPTY_ {
6969 response = append(response, fmt.Sprintf(",\"batch\":%q,\"count\":%d}", batchId, batchSeq)...)
6970 } else {
6971 response = append(response, '}')
6972 }
6973 outq.sendMsg(reply, response)
6974 }
6975 return nil
6976 }
6977
6978 // Republish state if needed.
6979 var tsubj string
6980 var tlseq uint64
6981 var thdrsOnly bool
6982 if mset.tr != nil {
6983 tsubj, _ = mset.tr.Match(subject)
6984 if tsubj != _EMPTY_ && !IsValidPublishSubject(tsubj) {
6985 s.RateLimitWarnf("Stream '%s > %s' suppressing republish with invalid subject %q", accName, name, tsubj)
6986 tsubj = _EMPTY_ // ... stops the republish.
6987 }
6988 if mset.cfg.RePublish != nil {
6989 thdrsOnly = mset.cfg.RePublish.HeadersOnly
6990 }
6991 }
6992 republish := tsubj != _EMPTY_ && isLeader
6993
6994 // If we are republishing grab last sequence for this exact subject. Aids in gap detection for lightweight clients.
6995 if republish {
6996 var smv StoreMsg
6997 if sm, _ := store.LoadLastMsg(subject, &smv); sm != nil {
6998 tlseq = sm.seq
6999 }
7000 }
7001
7002 // If clustered this was already checked and we do not want to check here and possibly introduce skew.
7003 // Don't error and log if we're tracing when clustered.
7004 if !isClustered {
7005 if exceeded, err := jsa.wouldExceedLimits(stype, mset.tier, mset.cfg.Replicas, subject, hdr, msg); exceeded {
7006 if err == nil {
7007 err = NewJSAccountResourcesExceededError()
7008 }
7009 s.RateLimitWarnf("JetStream %s resource limits exceeded for account: %q", strings.ToLower(stype.String()), accName)
7010 if canRespond {
7011 resp.PubAck = &PubAck{Stream: name}
7012 resp.Error = err
7013 response, _ = json.Marshal(resp)
7014 outq.send(newJSPubMsg(reply, _EMPTY_, _EMPTY_, nil, response, nil, 0))
7015 }
7016 return err
7017 }
7018 }
7019
7020 // Find the message TTL if any.
7021 ttl, err := getMessageTTL(hdr)
7022 if err != nil {
7023 if canRespond {
7024 resp.PubAck = &PubAck{Stream: name}
7025 resp.Error = NewJSMessageTTLInvalidError()
7026 response, _ = json.Marshal(resp)
7027 outq.send(newJSPubMsg(reply, _EMPTY_, _EMPTY_, nil, response, nil, 0))
7028 }
7029 return err
7030 }
7031
7032 // If subject delete markers are used, ensure message TTL is that at minimum.
7033 // Otherwise, subject delete markers could be missed if one already exists for this subject.
7034 // MaxMsgsPer=1 is an exception, because we'll only ever have one message.
7035 if ttl > 0 && mset.cfg.SubjectDeleteMarkerTTL > 0 && mset.cfg.MaxMsgsPer != 1 {
7036 if minTtl := int64(mset.cfg.SubjectDeleteMarkerTTL.Seconds()); ttl < minTtl {
7037 ttl = minTtl
7038 hdr = removeHeaderIfPresent(hdr, JSMessageTTL)
7039 hdr = genHeader(hdr, JSMessageTTL, strconv.FormatInt(ttl, 10))
7040 }
7041 }
7042
7043 // Store actual msg.
7044 if lseq == 0 && ts == 0 {
7045 seq, ts, err = store.StoreMsg(subject, hdr, msg, ttl)
7046 } else {
7047 // Make sure to take into account any message assignments that we had to skip (clfs).
7048 seq = lseq + 1 - clfs
7049 err = store.StoreRawMsg(subject, hdr, msg, seq, ts, ttl, canConsistencyCheck)
7050 }
7051
7052 if err != nil {
7053 if isPermissionError(err) {
7054 // messages in block cache could be lost in the worst case.
7055 // In the clustered mode it is very highly unlikely as a result of replication.
7056 go mset.srv.ShutdownJetStream()
7057 mset.srv.Warnf("Filesystem permission denied while writing msg, disabling JetStream: %v", err)
7058 return err
7059 }
7060
7061 switch err {
7062 case ErrMaxMsgs, ErrMaxBytes, ErrMaxMsgsPerSubject, ErrMsgTooLarge:
7063 s.RateLimitDebugf("JetStream failed to store a msg on stream '%s > %s': %v", accName, name, err)
7064 case ErrStoreClosed:
7065 default:
7066 // We don't want to respond back to the user, and definitely not up CLFS either.
7067 // This was likely an IO issue, so only log and return the error. This will stop
7068 // the stream if it was replicated.
7069 s.RateLimitErrorf("JetStream failed to store a msg on stream '%s > %s': %v", accName, name, err)
7070 mset.setWriteErrLocked(err)
7071 return err
7072 }
7073
7074 // If we did not succeed increment clfs in case we are clustered.
7075 bumpCLFS()
7076 if canRespond {
7077 resp.PubAck = &PubAck{Stream: name}
7078 resp.Error = NewJSStreamStoreFailedError(err, Unless(err))
7079 response, _ = json.Marshal(resp)
7080 outq.sendMsg(reply, response)
7081 }
7082 return err
7083 }
7084
7085 // Check for preAcks and the need to clear it.
7086 if mset.hasAllPreAcks(seq, subject) {
7087 mset.clearAllPreAcks(seq)
7088 // If we're clustered and the stream leader, we can now propose deleting this message.
7089 // We still store it below, so we remain properly synchronized with our followers.
7090 // If this proposal fails, we retry out-of-band.
7091 if isClustered && isLeader {
7092 md := streamMsgDelete{Seq: seq, NoErase: true, Stream: mset.cfg.Name}
7093 _ = mset.node.Propose(mset.term, encodeMsgDelete(&md))
7094 }
7095 }
7096
7097 // If here we succeeded in storing the message.
7098 mset.lmsgId = msgId
7099 mset.lseq = seq
7100
7101 // If we have a msgId make sure to save.
7102 // This will replace our estimate from the cluster layer if we are clustered.
7103 if msgId != _EMPTY_ {
7104 mset.ddMu.Lock()
7105 if isClustered && isLeader && mset.ddmap != nil {
7106 if dde := mset.ddmap[msgId]; dde != nil {
7107 dde.seq, dde.ts = seq, ts
7108 } else {
7109 mset.storeMsgIdLocked(&ddentry{msgId, seq, ts})
7110 }
7111 } else {
7112 // R1 or not leader..
7113 mset.storeMsgIdLocked(&ddentry{msgId, seq, ts})
7114 }
7115 mset.ddMu.Unlock()
7116 }
7117
7118 // No errors, this is the normal path.
7119 if allowRollupPurge {
7120 if err = mset.processJetStreamMsgWithRollup(subject, rollupSub, rollupAll, hdr, 1); err != nil {
7121 return err
7122 }
7123 }
7124
7125 // Check for republish.
7126 if republish {
7127 const ht = "NATS/1.0\r\nNats-Stream: %s\r\nNats-Subject: %s\r\nNats-Sequence: %d\r\nNats-Time-Stamp: %s\r\nNats-Last-Sequence: %d\r\n\r\n"
7128 const htho = "NATS/1.0\r\nNats-Stream: %s\r\nNats-Subject: %s\r\nNats-Sequence: %d\r\nNats-Time-Stamp: %s\r\nNats-Last-Sequence: %d\r\nNats-Msg-Size: %d\r\n\r\n"
7129 // When adding to existing headers, will use the fmt.Append version so this skips the headers from above.
7130 const hoff = 10
7131
7132 tsStr := time.Unix(0, ts).UTC().Format(time.RFC3339Nano)
7133 var rpMsg []byte
7134 if len(hdr) == 0 {
7135 if !thdrsOnly {
7136 hdr = fmt.Appendf(nil, ht, name, subject, seq, tsStr, tlseq)
7137 rpMsg = copyBytes(msg)
7138 } else {
7139 hdr = fmt.Appendf(nil, htho, name, subject, seq, tsStr, tlseq, len(msg))
7140 }
7141 } else {
7142 // use hdr[:end:end] to make sure as we add we copy the original hdr.
7143 end := len(hdr) - LEN_CR_LF
7144 if !thdrsOnly {
7145 hdr = fmt.Appendf(hdr[:end:end], ht[hoff:], name, subject, seq, tsStr, tlseq)
7146 rpMsg = copyBytes(msg)
7147 } else {
7148 hdr = fmt.Appendf(hdr[:end:end], htho[hoff:], name, subject, seq, tsStr, tlseq, len(msg))
7149 }
7150 }
7151 outq.send(newJSPubMsg(tsubj, _EMPTY_, _EMPTY_, hdr, rpMsg, nil, seq))
7152 }
7153
7154 // If using fast batch publish, we occasionally send flow control messages.
7155 // And, we need to ensure a PubAck is sent if the commit happens through EOB.
7156 if fastBatch != nil {
7157 if mset.batches == nil {
7158 mset.batches = &batching{}
7159 }
7160 mset.batches.mu.Lock()
7161 // Check full leader state so we only send the client an update once we're caught up.
7162 commit := mset.batches.fastBatchRegisterSequences(mset, reply, mset.lseq, mset.isLeader(), fastBatch)
7163 mset.batches.mu.Unlock()
7164 if !commit {
7165 reply = _EMPTY_
7166 canRespond = false
7167 }
7168 }
7169
7170 // Send response here.
7171 if canRespond {
7172 response = append(pubAck, strconv.FormatUint(seq, 10)...)
7173 if batchId != _EMPTY_ {
7174 response = append(response, fmt.Sprintf(",\"batch\":%q,\"count\":%d}", batchId, batchSeq)...)
7175 } else if allowMsgCounter {
7176 var counter CounterValue
7177 json.Unmarshal(msg, &counter)
7178 response = append(response, fmt.Sprintf(",\"val\":%q}", counter.Value)...)
7179 } else {
7180 response = append(response, '}')
7181 }
7182 outq.sendMsg(reply, response)
7183 }
7184
7185 // Signal consumers for new messages.
7186 if numConsumers > 0 {
7187 mset.sigq.push(newCMsg(subject, seq))
7188 select {
7189 case mset.sch <- struct{}{}:
7190 default:
7191 }
7192 }
7193
7194 return nil
7195 }
7196
7197 // Lock should be held.
7198 func (mset *stream) processJetStreamMsgWithRollup(subject string, rollupSub, rollupAll bool, hdr []byte, keep uint64) error {
7199 if rollupSub {
7200 if _, err := mset.purgeLocked(&JSApiStreamPurgeRequest{Subject: subject, Keep: keep}, false); err != nil {
7201 return err
7202 }
7203 } else if rollupAll {
7204 if _, err := mset.purgeLocked(&JSApiStreamPurgeRequest{Keep: keep}, false); err != nil {
7205 return err
7206 }
7207 }
7208 if scheduleNext := sliceHeader(JSScheduleNext, hdr); len(scheduleNext) > 0 && bytesToString(scheduleNext) == JSScheduleNextPurge {
7209 // Purge the message schedule.
7210 scheduler := getMessageScheduler(hdr)
7211 if scheduler != _EMPTY_ {
7212 if _, err := mset.purgeLocked(&JSApiStreamPurgeRequest{Subject: scheduler}, false); err != nil {
7213 return err
7214 }
7215 }
7216 }
7217 return nil
7218 }
7219
7220 // processJetStreamAtomicBatchMsg processes a JetStream message that's part of an atomic batch publish.
7221 // Handles constraints around the batch, storing messages, doing consistency checks, and performing the commit.
7222 func (mset *stream) processJetStreamAtomicBatchMsg(batchId, subject, reply string, hdr, msg []byte, mt *msgTrace) (retErr error) {
7223 mset.mu.RLock()
7224 canRespond := !mset.cfg.NoAck && len(reply) > 0
7225 name, stype := mset.cfg.Name, mset.cfg.Storage
7226 discard, discardNewPer, maxMsgs, maxMsgsPer, maxBytes := mset.cfg.Discard, mset.cfg.DiscardNewPer, mset.cfg.MaxMsgs, mset.cfg.MaxMsgsPer, mset.cfg.MaxBytes
7227 s, js, jsa, r, tierName, outq, node := mset.srv, mset.js, mset.jsa, mset.cfg.Replicas, mset.tier, mset.outq, mset.node
7228 maxMsgSize, lseq := int(mset.cfg.MaxMsgSize), mset.lseq
7229 isLeader, isClustered, isSealed, allowRollup, denyPurge, allowTTL, allowMsgCounter, allowMsgSchedules, allowAtomicPublish := mset.isLeader(), mset.isClustered(), mset.cfg.Sealed, mset.cfg.AllowRollup, mset.cfg.DenyPurge, mset.cfg.AllowMsgTTL, mset.cfg.AllowMsgCounter, mset.cfg.AllowMsgSchedules, mset.cfg.AllowAtomicPublish
7230 mset.mu.RUnlock()
7231
7232 // If message tracing (with message delivery), we will need to send the
7233 // event on exit in case there was an error (if message was not proposed).
7234 // Otherwise, the event will be sent from processJetStreamMsg when
7235 // invoked by the leader (from applyStreamEntries).
7236 if mt != nil {
7237 defer func() {
7238 if retErr != nil {
7239 mt.sendEventFromJetStream(retErr)
7240 }
7241 }()
7242 }
7243
7244 // Check that we are the leader. This can be false if we have scaled up from an R1 that had inbound queued messages.
7245 if !isLeader {
7246 return NewJSClusterNotLeaderError()
7247 }
7248
7249 respondError := func(apiErr *ApiError) error {
7250 if canRespond {
7251 buf, _ := json.Marshal(&JSPubAckResponse{PubAck: &PubAck{Stream: name}, Error: apiErr})
7252 outq.sendMsg(reply, buf)
7253 }
7254 return apiErr
7255 }
7256
7257 // Bail here if sealed.
7258 if isSealed {
7259 return respondError(NewJSStreamSealedError())
7260 }
7261
7262 // Check here pre-emptively if we have exceeded this server limits.
7263 if js.limitsExceeded(stype) {
7264 s.resourcesExceededError(stype)
7265 // Stepdown regardless.
7266 if node := mset.raftNode(); node != nil {
7267 node.StepDown()
7268 }
7269 return respondError(NewJSInsufficientResourcesError())
7270 }
7271
7272 // Check here pre-emptively if we have exceeded our account limits.
7273 if exceeded, err := jsa.wouldExceedLimits(stype, tierName, r, subject, hdr, msg); exceeded {
7274 if err == nil {
7275 err = NewJSAccountResourcesExceededError()
7276 }
7277 s.RateLimitWarnf("JetStream account limits exceeded for '%s': %s", jsa.acc().GetName(), err.Error())
7278 return respondError(err)
7279 }
7280
7281 // Check msgSize if we have a limit set there. Again this works if it goes through but better to be pre-emptive.
7282 // Subtract to prevent against overflows.
7283 if maxMsgSize >= 0 && (len(hdr) > maxMsgSize || len(msg) > maxMsgSize-len(hdr)) {
7284 err := fmt.Errorf("JetStream message size exceeds limits for '%s > %s'", jsa.acc().Name, mset.cfg.Name)
7285 s.RateLimitWarnf("%s", err.Error())
7286 _ = respondError(NewJSStreamMessageExceedsMaximumError())
7287 return err
7288 }
7289
7290 if !allowAtomicPublish {
7291 return respondError(NewJSAtomicPublishDisabledError())
7292 }
7293
7294 // Batch ID is too long.
7295 if len(batchId) > 64 {
7296 return respondError(NewJSAtomicPublishInvalidBatchIDError())
7297 }
7298
7299 batchSeq, exists := getBatchSequence(hdr)
7300 if !exists {
7301 return respondError(NewJSAtomicPublishMissingSeqError())
7302 }
7303
7304 jsa.mu.RLock()
7305 storeDir := jsa.storeDir
7306 jsa.mu.RUnlock()
7307
7308 // Parse the batch commit header.
7309 var commit, commitEob, commitInvalid bool
7310 if c := sliceHeader(JSBatchCommit, hdr); c != nil {
7311 commitEob = bytes.Equal(c, []byte("eob"))
7312 commitInvalid = !commitEob && !bytes.Equal(c, []byte("1"))
7313 commit = true
7314 }
7315
7316 // If not clustered, the commit message runs the consistency checks and
7317 // commits straight to the store below, so hold the isolation lock across
7318 // that whole section.
7319 if !isClustered && commit {
7320 mset.isolateMu.Lock()
7321 defer mset.isolateMu.Unlock()
7322 }
7323 mset.mu.Lock()
7324 if mset.batches == nil {
7325 mset.batches = &batching{}
7326 }
7327 batches := mset.batches
7328 // Acquire the batches lock.
7329 // Can't release the stream lock now, we need to keep holding it while we hold the batches lock.
7330 // Re-acquiring the stream lock with the batches lock already held would be a lock inversion.
7331 batches.mu.Lock()
7332
7333 respondIncompleteBatch := func() error {
7334 return respondError(NewJSAtomicPublishIncompleteBatchError())
7335 }
7336
7337 // Get batch.
7338 b, ok := batches.atomic[batchId]
7339 if !ok {
7340 if batchSeq != 1 {
7341 batches.mu.Unlock()
7342 mset.mu.Unlock()
7343 maxBatchSize := streamMaxAtomicBatchSize
7344 opts := s.getOpts()
7345 if opts.JetStreamLimits.MaxBatchSize > 0 {
7346 maxBatchSize = opts.JetStreamLimits.MaxBatchSize
7347 }
7348 size := batchSeq
7349 // Don't count the "End Of Batch" marker toward the batch size.
7350 if commitEob {
7351 size--
7352 }
7353 if size > uint64(maxBatchSize) {
7354 err := NewJSAtomicPublishTooLargeBatchError(maxBatchSize)
7355 return respondError(err)
7356 }
7357 return respondIncompleteBatch()
7358 }
7359
7360 // Limits.
7361 maxInflightPerStream := streamMaxAtomicBatchInflightPerStream
7362 maxInflightTotal := streamMaxAtomicBatchInflightTotal
7363 opts := s.getOpts()
7364 if opts.JetStreamLimits.MaxBatchInflightPerStream > 0 {
7365 maxInflightPerStream = opts.JetStreamLimits.MaxBatchInflightPerStream
7366 }
7367 if opts.JetStreamLimits.MaxBatchInflightTotal > 0 {
7368 maxInflightTotal = opts.JetStreamLimits.MaxBatchInflightTotal
7369 }
7370
7371 // Confirm we can facilitate an additional batch.
7372 if len(batches.atomic)+1 > maxInflightPerStream {
7373 batches.mu.Unlock()
7374 mset.mu.Unlock()
7375 return respondError(NewJSAtomicPublishTooManyInflightError())
7376 }
7377
7378 // Confirm we'll not exceed the server limit.
7379 if globalInflightAtomicBatches.Add(1) > int64(maxInflightTotal) {
7380 globalInflightAtomicBatches.Add(-1)
7381 batches.mu.Unlock()
7382 mset.mu.Unlock()
7383 return respondError(NewJSAtomicPublishTooManyInflightError())
7384 }
7385
7386 var err error
7387 b, err = batches.newAtomicBatch(mset, batchId, r, stype, storeDir, name)
7388 if err != nil {
7389 globalInflightAtomicBatches.Add(-1)
7390 batches.mu.Unlock()
7391 mset.mu.Unlock()
7392 return respondIncompleteBatch()
7393 }
7394 if batches.atomic == nil {
7395 batches.atomic = make(map[string]*atomicBatch, 1)
7396 }
7397 batches.atomic[batchId] = b
7398 }
7399
7400 // Reject the batch if the commit is not recognized.
7401 if commitInvalid {
7402 b.cleanupLocked(batchId, batches)
7403 batches.mu.Unlock()
7404 mset.mu.Unlock()
7405 err := NewJSAtomicPublishInvalidBatchCommitError()
7406 return respondError(err)
7407 }
7408
7409 // The required API level can have the batch be rejected. But the header is always removed.
7410 if len(sliceHeader(JSRequiredApiLevel, hdr)) != 0 {
7411 if errorOnRequiredApiLevel(hdr) {
7412 b.cleanupLocked(batchId, batches)
7413 batches.mu.Unlock()
7414 mset.mu.Unlock()
7415 mset.sendStreamBatchAbandonedAdvisory(batchId, BatchRequirementsNotMet)
7416 err := NewJSRequiredApiLevelError()
7417 return respondError(err)
7418 }
7419 hdr = removeHeaderIfPresent(hdr, JSRequiredApiLevel)
7420 }
7421
7422 // If cleanup has already happened, we can't continue.
7423 cleanup := !b.resetCleanupTimer(mset)
7424
7425 // Detect gaps.
7426 b.lseq++
7427 if b.lseq != batchSeq || cleanup || (batchSeq == 1 && commitEob) {
7428 b.cleanupLocked(batchId, batches)
7429 batches.mu.Unlock()
7430 mset.mu.Unlock()
7431 mset.sendStreamBatchAbandonedAdvisory(batchId, BatchIncomplete)
7432 return respondIncompleteBatch()
7433 }
7434
7435 // Confirm the batch doesn't exceed the allowed size.
7436 maxSize := streamMaxAtomicBatchSize
7437 if maxBatchSize := s.getOpts().JetStreamLimits.MaxBatchSize; maxBatchSize > 0 {
7438 maxSize = maxBatchSize
7439 }
7440 size := batchSeq
7441 // Don't count the "End Of Batch" marker toward the batch size.
7442 if commitEob {
7443 size--
7444 }
7445 if size > uint64(maxSize) {
7446 b.cleanupLocked(batchId, batches)
7447 batches.mu.Unlock()
7448 mset.mu.Unlock()
7449 mset.sendStreamBatchAbandonedAdvisory(batchId, BatchLarge)
7450 err := NewJSAtomicPublishTooLargeBatchError(maxSize)
7451 return respondError(err)
7452 }
7453
7454 // Persist, but optimize if we're committing because we already know last.
7455 // If the underlying store is file-based we need to persist everything to survive hard kills, because we're R1.
7456 if !commit || b.store.Type() == FileStorage {
7457 seq, _, err := b.store.StoreMsg(subject, hdr, msg, 0)
7458 if err != nil || seq != batchSeq {
7459 b.cleanupLocked(batchId, batches)
7460 batches.mu.Unlock()
7461 mset.mu.Unlock()
7462 mset.sendStreamBatchAbandonedAdvisory(batchId, BatchIncomplete)
7463 return respondIncompleteBatch()
7464 }
7465 }
7466 if !commit {
7467 batches.mu.Unlock()
7468 mset.mu.Unlock()
7469 // Send empty ack to let them know we've persisted the data prior to commit.
7470 if canRespond {
7471 outq.sendMsg(reply, nil)
7472 }
7473 return nil
7474 }
7475
7476 // Ensure the batch is prepared for the commit and will not be cleaned up while committing.
7477 if abandonReason := b.readyForCommit(); abandonReason != nil {
7478 // Don't do cleanup, this is already done.
7479 batches.mu.Unlock()
7480 mset.mu.Unlock()
7481 mset.sendStreamBatchAbandonedAdvisory(batchId, *abandonReason)
7482 return respondIncompleteBatch()
7483 }
7484
7485 // Proceed with proposing the batch.
7486 ts := time.Now().UnixNano()
7487
7488 // Need to hold this lock even if we're not clustered, because we'll
7489 // be accessing state that requires this lock (even if it's empty).
7490 mset.clMu.Lock()
7491
7492 // If not clustered, set up the last sequence.
7493 if !isClustered {
7494 mset.clseq, mset.clfs = mset.lseq, 0
7495 }
7496
7497 // We only use mset.clseq for clustering and in case we run ahead of actual commits.
7498 // Check if we need to set initial value here
7499 if isClustered && (mset.clseq == 0 || mset.clseq < lseq+mset.clfs) {
7500 lseq = recalculateClusteredSeq(mset, false)
7501 }
7502
7503 oclseq := mset.clseq
7504 rollback := func() {
7505 if isClustered {
7506 // Only need to move the clustered sequence back if the batch fails to commit.
7507 // Other changes were staged but not applied, so this is the only thing we need to do.
7508 mset.clseq = oclseq
7509 }
7510 mset.clMu.Unlock()
7511 }
7512
7513 errorOnUnsupported := func(header string) *ApiError {
7514 apiErr := NewJSAtomicPublishUnsupportedHeaderBatchError(header)
7515 rollback()
7516 b.cleanupLocked(batchId, batches)
7517 batches.mu.Unlock()
7518 mset.mu.Unlock()
7519 _ = respondError(apiErr)
7520 return apiErr
7521 }
7522
7523 type checkedMsg struct {
7524 subj string
7525 hdr []byte
7526 msg []byte
7527 }
7528 var (
7529 entries []*Entry
7530 checked []checkedMsg
7531 bsubj string
7532 bhdr []byte
7533 bmsg []byte
7534 apiErr *ApiError
7535 err error
7536 smv StoreMsg
7537 sm *StoreMsg
7538 sz int
7539 )
7540
7541 // If the commit ends with an "End Of Batch" message, we don't store this.
7542 if commitEob {
7543 batchSeq--
7544 }
7545
7546 diff := &batchStagedDiff{}
7547 for seq := uint64(1); seq <= batchSeq; seq++ {
7548 if seq == batchSeq && !commitEob && b.store.Type() != FileStorage {
7549 bsubj, bhdr, bmsg = subject, hdr, msg
7550 } else if sm, err = b.store.LoadMsg(seq, &smv); sm != nil && err == nil {
7551 bsubj, bhdr, bmsg = sm.subj, sm.hdr, sm.msg
7552 } else {
7553 rollback()
7554 b.cleanupLocked(batchId, batches)
7555 batches.mu.Unlock()
7556 mset.mu.Unlock()
7557 return respondIncompleteBatch()
7558 }
7559
7560 // Apply the input subject transform if any
7561 csubj := bsubj
7562 if mset.itr != nil {
7563 ts, err := mset.itr.Match(csubj)
7564 if err == nil {
7565 // no filtering: if the subject doesn't map the source of the transform, don't change it
7566 csubj = ts
7567 }
7568 }
7569
7570 // Reject unsupported headers.
7571 if getExpectedLastMsgId(bhdr) != _EMPTY_ {
7572 return errorOnUnsupported(JSExpectedLastMsgId)
7573 }
7574
7575 if bhdr, bmsg, _, apiErr, err = checkMsgHeadersPreClusteredProposal(diff, mset, csubj, bsubj, bhdr, bmsg, false, name, jsa, allowRollup, denyPurge, allowTTL, allowMsgCounter, allowMsgSchedules, discard, discardNewPer, maxMsgSize, maxMsgs, maxMsgsPer, maxBytes); err != nil {
7576 rollback()
7577 b.cleanupLocked(batchId, batches)
7578 batches.mu.Unlock()
7579 mset.mu.Unlock()
7580 _ = respondError(apiErr)
7581 return err
7582 }
7583
7584 if isClustered {
7585 var _reply string
7586 isCommit := seq == batchSeq
7587 if isCommit {
7588 _reply = reply
7589 // If committed by EOB, the last message must get the normal commit header.
7590 if commitEob {
7591 bhdr = genHeader(bhdr, JSBatchCommit, "1")
7592 }
7593 }
7594 esm := encodeStreamMsgAllowCompressAndBatch(bsubj, _reply, bhdr, bmsg, mset.clseq, ts, false, batchId, seq, isCommit)
7595 entries = append(entries, newEntry(EntryNormal, esm))
7596 sz += len(esm)
7597 } else {
7598 // Preserve the (possibly rewritten) headers and message, for example for counters and
7599 // scheduled messages, so the commit below stores the transformed message.
7600 // Need to copy, the staged message buffer is reused on every load.
7601 checked = append(checked, checkedMsg{bsubj, copyBytes(bhdr), copyBytes(bmsg)})
7602 }
7603 mset.clseq++
7604 }
7605
7606 // Commit batch.
7607 if !isClustered {
7608 // Reset, we only used this to do the batching checks.
7609 mset.clseq, mset.clfs = 0, 0
7610 mset.clMu.Unlock()
7611
7612 // Ensure the whole batch is fully isolated, and reads can only happen
7613 // after the full batch is committed. isolateMu stays held until return
7614 // via the defer above, but release mset.mu and batches.mu.
7615 mset.mu.Unlock()
7616 batches.mu.Unlock()
7617 for seq := uint64(1); seq <= batchSeq; seq++ {
7618 // Use the checked (and possibly rewritten) message from above, not the raw staged
7619 // message, so transformations like counter increments and scheduled message
7620 // rollups are persisted just like in the clustered proposal path.
7621 cm := checked[seq-1]
7622 bsubj, bhdr, bmsg = cm.subj, cm.hdr, cm.msg
7623 var _reply string
7624 if seq == batchSeq {
7625 _reply = reply
7626 // If committed by EOB, the last message must get the normal commit header.
7627 if commitEob {
7628 bhdr = genHeader(bhdr, JSBatchCommit, "1")
7629 }
7630 }
7631 // If errored, assume all subsequent calls will fail too (for example, store is closed).
7632 // Don't clean up the batch so that a restart can try to recover it.
7633 if err = mset.processJetStreamMsg(bsubj, _reply, bhdr, bmsg, 0, 0, mt, false, false); err != nil {
7634 return err
7635 }
7636 }
7637 // Re-acquire for the cleanup below. If a concurrent staging error
7638 // already cleaned the batch up, cleanupLocked is a no-op.
7639 batches.mu.Lock()
7640 } else {
7641 term := mset.term
7642 mset.mu.Unlock()
7643 // Do a single multi proposal. This ensures we get to push all entries to the proposal queue in-order
7644 // and not interleaved with other proposals.
7645 if err = node.ProposeMulti(term, entries); err == nil {
7646 diff.commit(mset)
7647 mset.trackReplicationTraffic(node, sz, r)
7648
7649 // Check to see if we are being overrun.
7650 // TODO(dlc) - Make this a limit where we drop messages to protect ourselves, but allow to be configured.
7651 if mset.clseq-(lseq+mset.clfs) > streamLagWarnThreshold {
7652 lerr := fmt.Errorf("JetStream stream '%s > %s' has high message lag", jsa.acc().Name, name)
7653 s.RateLimitWarnf("%s", lerr.Error())
7654 }
7655 } else {
7656 mset.clseq = oclseq
7657 }
7658 mset.clMu.Unlock()
7659 }
7660 b.cleanupLocked(batchId, batches)
7661 batches.mu.Unlock()
7662 return err
7663 }
7664
7665 // processJetStreamFastBatchMsg processes a JetStream message that's part of an atomic batch publish.
7666 // Handles constraints around the batch, storing messages, doing consistency checks, and performing the commit.
7667 func (mset *stream) processJetStreamFastBatchMsg(batch *FastBatch, subject, reply string, hdr, msg []byte, mt *msgTrace) (retErr error) {
7668 mset.mu.RLock()
7669 canRespond := !mset.cfg.NoAck && len(reply) > 0
7670 name, stype := mset.cfg.Name, mset.cfg.Storage
7671 discard, discardNewPer, maxMsgs, maxMsgsPer, maxBytes := mset.cfg.Discard, mset.cfg.DiscardNewPer, mset.cfg.MaxMsgs, mset.cfg.MaxMsgsPer, mset.cfg.MaxBytes
7672 s, js, jsa, st, r, tierName, outq, node, term := mset.srv, mset.js, mset.jsa, mset.cfg.Storage, mset.cfg.Replicas, mset.tier, mset.outq, mset.node, mset.term
7673 maxMsgSize, lseq := int(mset.cfg.MaxMsgSize), mset.lseq
7674 isLeader, isClustered, isSealed, allowRollup, denyPurge, allowTTL, allowMsgCounter, allowMsgSchedules, allowBatchPublish := mset.isLeader(), mset.isClustered(), mset.cfg.Sealed, mset.cfg.AllowRollup, mset.cfg.DenyPurge, mset.cfg.AllowMsgTTL, mset.cfg.AllowMsgCounter, mset.cfg.AllowMsgSchedules, mset.cfg.AllowBatchPublish
7675
7676 // Apply the input subject transform if any
7677 csubject := subject
7678 if mset.itr != nil {
7679 ts, err := mset.itr.Match(csubject)
7680 if err == nil {
7681 // no filtering: if the subject doesn't map the source of the transform, don't change it
7682 csubject = ts
7683 }
7684 }
7685 mset.mu.RUnlock()
7686
7687 // If message tracing (with message delivery), we will need to send the
7688 // event on exit in case there was an error (if message was not proposed).
7689 // Otherwise, the event will be sent from processJetStreamMsg when
7690 // invoked by the leader (from applyStreamEntries).
7691 if mt != nil {
7692 defer func() {
7693 if retErr != nil {
7694 mt.sendEventFromJetStream(retErr)
7695 }
7696 }()
7697 }
7698
7699 // Check that we are the leader. This can be false if we have scaled up from an R1 that had inbound queued messages.
7700 if !isLeader {
7701 return NewJSClusterNotLeaderError()
7702 }
7703
7704 respondError := func(apiErr *ApiError) error {
7705 if canRespond {
7706 buf, _ := json.Marshal(&JSPubAckResponse{PubAck: &PubAck{Stream: name}, Error: apiErr})
7707 outq.sendMsg(reply, buf)
7708 }
7709 return apiErr
7710 }
7711
7712 // Bail here if sealed.
7713 if isSealed {
7714 return respondError(NewJSStreamSealedError())
7715 }
7716
7717 // Check here pre-emptively if we have exceeded this server limits.
7718 if js.limitsExceeded(stype) {
7719 s.resourcesExceededError(stype)
7720 // Stepdown regardless.
7721 if node := mset.raftNode(); node != nil {
7722 node.StepDown()
7723 }
7724 return respondError(NewJSInsufficientResourcesError())
7725 }
7726
7727 // Check here pre-emptively if we have exceeded our account limits.
7728 if exceeded, err := jsa.wouldExceedLimits(st, tierName, r, csubject, hdr, msg); exceeded {
7729 if err == nil {
7730 err = NewJSAccountResourcesExceededError()
7731 }
7732 s.RateLimitWarnf("JetStream account limits exceeded for '%s': %s", jsa.acc().GetName(), err.Error())
7733 return respondError(err)
7734 }
7735
7736 // Check msgSize if we have a limit set there. Again this works if it goes through but better to be pre-emptive.
7737 // Subtract to prevent against overflows.
7738 if maxMsgSize >= 0 && (len(hdr) > maxMsgSize || len(msg) > maxMsgSize-len(hdr)) {
7739 err := fmt.Errorf("JetStream message size exceeds limits for '%s > %s'", jsa.acc().Name, mset.cfg.Name)
7740 s.RateLimitWarnf("%s", err.Error())
7741 _ = respondError(NewJSStreamMessageExceedsMaximumError())
7742 return err
7743 }
7744
7745 if !allowBatchPublish {
7746 return respondError(NewJSBatchPublishDisabledError())
7747 }
7748
7749 if batch == nil {
7750 return respondError(NewJSBatchPublishInvalidPatternError())
7751 }
7752
7753 // Batch ID is too long.
7754 if len(batch.id) > 64 {
7755 return respondError(NewJSBatchPublishInvalidBatchIDError())
7756 }
7757
7758 mset.mu.Lock()
7759 if mset.batches == nil {
7760 mset.batches = &batching{}
7761 }
7762 batches := mset.batches
7763 // Acquire the batches lock.
7764 // Can't release the stream lock now, we need to keep holding it while we hold the batches lock.
7765 // Re-acquiring the stream lock with the batches lock already held would be a lock inversion.
7766 batches.mu.Lock()
7767
7768 // Get batch.
7769 b, ok := batches.fast[batch.id]
7770 if !ok {
7771 if batch.seq != 1 {
7772 batches.mu.Unlock()
7773 mset.mu.Unlock()
7774 return respondError(NewJSBatchPublishUnknownBatchIDError())
7775 }
7776
7777 // Limits.
7778 maxInflightPerStream := streamMaxFastBatchInflightPerStream
7779 maxInflightTotal := streamMaxFastBatchInflightTotal
7780 opts := s.getOpts()
7781 if opts.JetStreamLimits.MaxBatchInflightPerStream > 0 {
7782 maxInflightPerStream = opts.JetStreamLimits.MaxBatchInflightPerStream
7783 }
7784 if opts.JetStreamLimits.MaxBatchInflightTotal > 0 {
7785 maxInflightTotal = opts.JetStreamLimits.MaxBatchInflightTotal
7786 }
7787
7788 // Confirm we can facilitate an additional batch.
7789 if len(batches.fast)+1 > maxInflightPerStream {
7790 batches.mu.Unlock()
7791 mset.mu.Unlock()
7792 return respondError(NewJSBatchPublishTooManyInflightError())
7793 }
7794
7795 // Confirm we'll not exceed the server limit.
7796 if globalInflightFastBatches.Add(1) > int64(maxInflightTotal) {
7797 globalInflightFastBatches.Add(-1)
7798 batches.mu.Unlock()
7799 mset.mu.Unlock()
7800 return respondError(NewJSBatchPublishTooManyInflightError())
7801 }
7802
7803 // We'll need a copy as we'll use it as a key and later for cleanup.
7804 batchId := copyString(batch.id)
7805 b = batches.newFastBatch(mset, batchId, batch.gapOk, batch.flow)
7806 }
7807
7808 // The required API level can have the batch be rejected. But the header is always removed.
7809 if len(sliceHeader(JSRequiredApiLevel, hdr)) != 0 {
7810 if errorOnRequiredApiLevel(hdr) {
7811 b.cleanupLocked(batch.id, batches)
7812 batches.mu.Unlock()
7813 mset.mu.Unlock()
7814 return respondError(NewJSRequiredApiLevelError())
7815 }
7816 hdr = removeHeaderIfPresent(hdr, JSRequiredApiLevel)
7817 }
7818
7819 // Fast publishing resets the cleanup timer.
7820 // If cleanup has already happened, we can't continue.
7821 cleanup := !b.resetCleanupTimer(mset)
7822
7823 // A ping operation confirms we've received a minimum amount of data and resends ack messages.
7824 if batch.ping {
7825 sendFlowControl := true
7826 // Detect a gap or if the batch was cleaned up in the meantime.
7827 if batch.seq > b.lseq || cleanup {
7828 // If a gap is detected, we always report about it.
7829 buf, _ := BatchFlowGap{ExpectedLastSequence: b.lseq + 1, CurrentSequence: batch.seq + 1}.MarshalJSON()
7830 outq.sendMsg(reply, buf)
7831 // If the gap is okay, we can continue without rejecting.
7832 if b.gapOk && !cleanup {
7833 b.lseq = batch.seq
7834 if b.pending == 0 {
7835 b.pseq = b.lseq
7836 }
7837 sendFlowControl = !b.checkFlowControl(mset, reply, batches)
7838 } else if cleanup = batches.fastBatchCommit(b, batch.id, mset, reply); cleanup {
7839 b.cleanupLocked(batch.id, batches)
7840 sendFlowControl = false
7841 }
7842 }
7843 if sendFlowControl {
7844 b.sendFlowControl(b.fseq, mset, reply)
7845 }
7846 batches.mu.Unlock()
7847 mset.mu.Unlock()
7848 return nil
7849 }
7850
7851 // If the batch is committing, due to an error, we can't add more messages.
7852 // We simply skip, since the client will be waiting for the PubAck.
7853 if b.commit {
7854 // MUST NOT clean up, that will happen when the commit completes.
7855 batches.mu.Unlock()
7856 mset.mu.Unlock()
7857 return nil
7858 }
7859
7860 // Detect gaps.
7861 b.lseq++
7862 if b.lseq != batch.seq || cleanup {
7863 // If a forward gap is detected, we always report about it.
7864 if batch.seq > b.lseq {
7865 buf, _ := BatchFlowGap{ExpectedLastSequence: b.lseq, CurrentSequence: batch.seq}.MarshalJSON()
7866 outq.sendMsg(reply, buf)
7867 }
7868 // If the forward gap is okay, we can continue without rejecting.
7869 if b.gapOk && !cleanup && batch.seq > b.lseq {
7870 b.lseq = batch.seq
7871 } else {
7872 // We've reached either a backward gap, or were cleaned up already, or it's gap-fail mode.
7873 // Revert, since we incremented for the gap check.
7874 b.lseq--
7875 if cleanup = batches.fastBatchCommit(b, batch.id, mset, reply); cleanup {
7876 b.cleanupLocked(batch.id, batches)
7877 }
7878 batches.mu.Unlock()
7879 mset.mu.Unlock()
7880 return nil
7881 }
7882 }
7883
7884 if batch.commit {
7885 if batch.commitEob {
7886 // Revert, since we incremented for the gap check.
7887 b.lseq--
7888 // If there is none pending, correct the persisted sequence as we need to commit below.
7889 if b.pending == 0 {
7890 b.pseq = b.lseq
7891 }
7892 }
7893 // We'll try to immediately send a PubAck if we can.
7894 // Only possible if EOB is used and the last message was already persisted
7895 // Otherwise, this sets up the commit for the last message we're about to propose.
7896 cleanup = batches.fastBatchCommit(b, batch.id, mset, reply)
7897 if batch.commitEob {
7898 if cleanup {
7899 b.cleanupLocked(batch.id, batches)
7900 }
7901 batches.mu.Unlock()
7902 mset.mu.Unlock()
7903 return nil
7904 }
7905 }
7906
7907 // The first message in the batch responds with the settings used for flow control.
7908 // If committing immediately, we only send the PubAck.
7909 if batch.seq == 1 && canRespond && !batch.commit {
7910 buf, _ := BatchFlowAck{Sequence: 0, Messages: b.ackMessages}.MarshalJSON()
7911 outq.sendMsg(reply, buf)
7912 }
7913
7914 // Proceed with proposing this message.
7915
7916 // We only use mset.clseq for clustering and in case we run ahead of actual commits.
7917 // Check if we need to set initial value here
7918 mset.clMu.Lock()
7919 if mset.clseq == 0 || mset.clseq < lseq+mset.clfs {
7920 lseq = recalculateClusteredSeq(mset, false)
7921 }
7922 // We can now unlock, since we've potentially recalculated the clustered seq above.
7923 mset.mu.Unlock()
7924
7925 var (
7926 dseq uint64
7927 apiErr *ApiError
7928 err error
7929 )
7930 diff := &batchStagedDiff{}
7931 if hdr, msg, dseq, apiErr, err = checkMsgHeadersPreClusteredProposal(diff, mset, csubject, subject, hdr, msg, false, name, jsa, allowRollup, denyPurge, allowTTL, allowMsgCounter, allowMsgSchedules, discard, discardNewPer, maxMsgSize, maxMsgs, maxMsgsPer, maxBytes); err != nil {
7932 mset.clMu.Unlock()
7933
7934 // If the message is a duplicate, and we have no pending messages, we should check if we need to
7935 // send the flow control message here.
7936 if err == errMsgIdDuplicate {
7937 if b.pending == 0 {
7938 b.pseq = batch.seq
7939 b.checkFlowControl(mset, reply, batches)
7940 }
7941 if !batch.commit {
7942 // Otherwise, just skip.
7943 batches.mu.Unlock()
7944 return err
7945 }
7946 }
7947
7948 // If a batch immediately errors, we send the same response as we would a normal publish.
7949 if !batch.gapOk && b.lseq == 1 {
7950 var response []byte
7951 if err == errMsgIdDuplicate && dseq > 0 {
7952 var buf [256]byte
7953 response = append(buf[:0], mset.pubAck...)
7954 response = append(response, strconv.FormatUint(dseq, 10)...)
7955 response = append(response, fmt.Sprintf(",\"duplicate\": true,\"batch\":%q,\"count\":%d}", batch.id, batch.seq)...)
7956 } else {
7957 response, _ = json.Marshal(&JSPubAckResponse{PubAck: &PubAck{Stream: name}, Error: apiErr})
7958 }
7959 b.cleanupLocked(batch.id, batches)
7960 batches.mu.Unlock()
7961 outq.sendMsg(reply, response)
7962 return err
7963 }
7964
7965 // We always return the error to the client, unless it's a duplicate.
7966 if err != errMsgIdDuplicate {
7967 buf, _ := BatchFlowErr{Sequence: batch.seq, Error: apiErr}.MarshalJSON()
7968 outq.sendMsg(reply, buf)
7969 }
7970
7971 // If gaps are okay, we just allow them to continue.
7972 // Unless this is the commit message, in which case we must still complete it below.
7973 if batch.gapOk && !batch.commit {
7974 batches.mu.Unlock()
7975 return err
7976 }
7977
7978 // Revert the last sequence, we might be able to immediately return the PubAck as part of the commit.
7979 // Otherwise, the batch is cleaned up automatically later.
7980 if err != errMsgIdDuplicate {
7981 b.lseq--
7982 // If there is none pending, correct the persisted sequence as we need to commit below.
7983 if b.pending == 0 {
7984 b.pseq = b.lseq
7985 }
7986 }
7987 if cleanup = batches.fastBatchCommit(b, batch.id, mset, reply); cleanup {
7988 b.cleanupLocked(batch.id, batches)
7989 }
7990 batches.mu.Unlock()
7991 return err
7992 }
7993 b.pending++
7994 batches.mu.Unlock()
7995 if !isClustered {
7996 mset.clMu.Unlock()
7997 return mset.processJetStreamMsgWithBatch(subject, reply, hdr, msg, 0, 0, mt, false, true, batch)
7998 }
7999 err = commitSingleMsg(diff, mset, subject, reply, hdr, msg, name, jsa, mt, node, term, r, lseq)
8000 mset.clMu.Unlock()
8001 return err
8002 }
8003
8004 // Used to signal inbound message to registered consumers.
8005 type cMsg struct {
8006 seq uint64
8007 subj string
8008 }
8009
8010 // Pool to recycle consumer bound msgs.
8011 var cMsgPool sync.Pool
8012
8013 // Used to queue up consumer bound msgs for signaling.
8014 func newCMsg(subj string, seq uint64) *cMsg {
8015 var m *cMsg
8016 cm := cMsgPool.Get()
8017 if cm != nil {
8018 m = cm.(*cMsg)
8019 } else {
8020 m = new(cMsg)
8021 }
8022 m.subj, m.seq = subj, seq
8023
8024 return m
8025 }
8026
8027 func (m *cMsg) returnToPool() {
8028 if m == nil {
8029 return
8030 }
8031 m.subj, m.seq = _EMPTY_, 0
8032 cMsgPool.Put(m)
8033 }
8034
8035 // Go routine to signal consumers.
8036 // Offloaded from stream msg processing.
8037 func (mset *stream) signalConsumersLoop() {
8038 mset.mu.RLock()
8039 s, qch, sch, msgs := mset.srv, mset.qch, mset.sch, mset.sigq
8040 mset.mu.RUnlock()
8041
8042 for {
8043 select {
8044 case <-s.quitCh:
8045 return
8046 case <-qch:
8047 return
8048 case <-sch:
8049 cms := msgs.pop()
8050 for _, m := range cms {
8051 seq, subj := m.seq, m.subj
8052 m.returnToPool()
8053 // Signal all appropriate consumers.
8054 mset.signalConsumers(subj, seq)
8055 }
8056 msgs.recycle(&cms)
8057 }
8058 }
8059 }
8060
8061 // This will update and signal all consumers that match.
8062 func (mset *stream) signalConsumers(subj string, seq uint64) {
8063 mset.clsMu.RLock()
8064 defer mset.clsMu.RUnlock()
8065 csl := mset.csl
8066 if csl == nil {
8067 return
8068 }
8069 csl.Match(subj, func(o *consumer) {
8070 o.processStreamSignal(seq)
8071 })
8072 }
8073
8074 // Internal message for use by jetstream subsystem.
8075 type jsPubMsg struct {
8076 dsubj string // Subject to send to, e.g. _INBOX.xxx
8077 reply string
8078 StoreMsg
8079 o *consumer
8080 }
8081
8082 var jsPubMsgPool = sync.Pool{
8083 New: func() any {
8084 return &jsPubMsg{}
8085 },
8086 }
8087
8088 func newJSPubMsg(dsubj, subj, reply string, hdr, msg []byte, o *consumer, seq uint64) *jsPubMsg {
8089 m := getJSPubMsgFromPool()
8090 if m.buf == nil {
8091 m.buf = make([]byte, 0, len(hdr)+len(msg))
8092 }
8093 buf := append(m.buf[:0], hdr...)
8094 buf = append(buf, msg...)
8095 hdr = buf[:len(hdr):len(hdr)]
8096 msg = buf[len(hdr):]
8097 // When getting something from a pool it is critical that all fields are
8098 // initialized. Doing this way guarantees that if someone adds a field to
8099 // the structure, the compiler will fail the build if this line is not updated.
8100 (*m) = jsPubMsg{dsubj, reply, StoreMsg{subj, hdr, msg, buf, seq, 0}, o}
8101 return m
8102 }
8103
8104 // Gets a jsPubMsg from the pool.
8105 func getJSPubMsgFromPool() *jsPubMsg {
8106 return jsPubMsgPool.Get().(*jsPubMsg)
8107 }
8108
8109 func (pm *jsPubMsg) returnToPool() {
8110 if pm == nil {
8111 return
8112 }
8113 pm.subj, pm.dsubj, pm.reply, pm.hdr, pm.msg, pm.o = _EMPTY_, _EMPTY_, _EMPTY_, nil, nil, nil
8114 if len(pm.buf) > 0 {
8115 pm.buf = pm.buf[:0]
8116 }
8117 jsPubMsgPool.Put(pm)
8118 }
8119
8120 func (pm *jsPubMsg) size() int {
8121 if pm == nil {
8122 return 0
8123 }
8124 return len(pm.dsubj) + len(pm.reply) + len(pm.hdr) + len(pm.msg)
8125 }
8126
8127 // Queue of *jsPubMsg for sending internal system messages.
8128 type jsOutQ struct {
8129 *ipQueue[*jsPubMsg]
8130 }
8131
8132 func (q *jsOutQ) sendMsg(subj string, msg []byte) {
8133 if q != nil {
8134 q.send(newJSPubMsg(subj, _EMPTY_, _EMPTY_, nil, msg, nil, 0))
8135 }
8136 }
8137
8138 func (q *jsOutQ) send(msg *jsPubMsg) {
8139 if q == nil || msg == nil {
8140 return
8141 }
8142 q.push(msg)
8143 }
8144
8145 func (q *jsOutQ) unregister() {
8146 if q == nil {
8147 return
8148 }
8149 q.ipQueue.unregister()
8150 }
8151
8152 // StoredMsg is for raw access to messages in a stream.
8153 type StoredMsg struct {
8154 Subject string `json:"subject"`
8155 Sequence uint64 `json:"seq"`
8156 Header []byte `json:"hdrs,omitempty"`
8157 Data []byte `json:"data,omitempty"`
8158 Time time.Time `json:"time"`
8159 }
8160
8161 // This is similar to system semantics but did not want to overload the single system sendq,
8162 // or require system account when doing simple setup with jetstream.
8163 func (mset *stream) setupSendCapabilities() {
8164 mset.mu.Lock()
8165 defer mset.mu.Unlock()
8166 if mset.outq != nil {
8167 return
8168 }
8169 qname := fmt.Sprintf("[ACC:%s] stream '%s' sendQ", mset.acc.Name, mset.cfg.Name)
8170 mset.outq = &jsOutQ{newIPQueue[*jsPubMsg](mset.srv, qname)}
8171 go mset.internalLoop()
8172 }
8173
8174 // Returns the associated account name.
8175 func (mset *stream) accName() string {
8176 if mset == nil {
8177 return _EMPTY_
8178 }
8179 mset.mu.RLock()
8180 acc := mset.acc
8181 mset.mu.RUnlock()
8182 return acc.Name
8183 }
8184
8185 // Name returns the stream name.
8186 func (mset *stream) name() string {
8187 return mset.nameLocked(true)
8188 }
8189
8190 func (mset *stream) nameLocked(needLock bool) string {
8191 if mset == nil {
8192 return _EMPTY_
8193 }
8194 if needLock {
8195 mset.mu.RLock()
8196 defer mset.mu.RUnlock()
8197 }
8198 return mset.cfg.Name
8199 }
8200
8201 func (mset *stream) internalLoop() {
8202 mset.mu.RLock()
8203 setGoRoutineLabels(pprofLabels{
8204 "account": mset.acc.Name,
8205 "stream": mset.cfg.Name,
8206 })
8207 s := mset.srv
8208 c := s.createInternalJetStreamClient()
8209 c.registerWithAccount(mset.acc)
8210 defer c.closeConnection(ClientClosed)
8211 outq, qch, msgs, gets := mset.outq, mset.qch, mset.msgs, mset.gets
8212
8213 // For the ack msgs queue for interest retention.
8214 var (
8215 amch chan struct{}
8216 ackq *ipQueue[uint64]
8217 )
8218 if mset.ackq != nil {
8219 ackq, amch = mset.ackq, mset.ackq.ch
8220 }
8221 mset.mu.RUnlock()
8222
8223 // Raw scratch buffer.
8224 // This should be rarely used now so can be smaller.
8225 var _r [1024]byte
8226
8227 // To optimize for not converting a string to a []byte slice.
8228 var (
8229 subj [256]byte
8230 dsubj [256]byte
8231 rply [256]byte
8232 szb [10]byte
8233 hdb [10]byte
8234 )
8235
8236 for {
8237 select {
8238 case <-outq.ch:
8239 pms := outq.pop()
8240 for _, pm := range pms {
8241 c.pa.subject = append(dsubj[:0], pm.dsubj...)
8242 c.pa.deliver = append(subj[:0], pm.subj...)
8243 c.pa.size = len(pm.msg) + len(pm.hdr)
8244 c.pa.szb = append(szb[:0], strconv.Itoa(c.pa.size)...)
8245 if len(pm.reply) > 0 {
8246 c.pa.reply = append(rply[:0], pm.reply...)
8247 } else {
8248 c.pa.reply = nil
8249 }
8250
8251 // If we have an underlying buf that is the wire contents for hdr + msg, else construct on the fly.
8252 var msg []byte
8253 if len(pm.buf) > 0 {
8254 msg = pm.buf
8255 } else {
8256 if len(pm.hdr) > 0 {
8257 msg = pm.hdr
8258 if len(pm.msg) > 0 {
8259 msg = _r[:0]
8260 msg = append(msg, pm.hdr...)
8261 msg = append(msg, pm.msg...)
8262 }
8263 } else if len(pm.msg) > 0 {
8264 // We own this now from a low level buffer perspective so can use directly here.
8265 msg = pm.msg
8266 }
8267 }
8268
8269 if len(pm.hdr) > 0 {
8270 c.pa.hdr = len(pm.hdr)
8271 c.pa.hdb = []byte(strconv.Itoa(c.pa.hdr))
8272 c.pa.hdb = append(hdb[:0], strconv.Itoa(c.pa.hdr)...)
8273 } else {
8274 c.pa.hdr = -1
8275 c.pa.hdb = nil
8276 }
8277
8278 msg = append(msg, _CRLF_...)
8279
8280 didDeliver, _ := c.processInboundClientMsg(msg)
8281 c.pa.szb, c.pa.subject, c.pa.deliver = nil, nil, nil
8282
8283 // Check to see if this is a delivery for a consumer and
8284 // we failed to deliver the message. If so alert the consumer.
8285 if pm.o != nil && pm.seq > 0 && !didDeliver {
8286 pm.o.didNotDeliver(pm.seq, pm.dsubj)
8287 }
8288 pm.returnToPool()
8289 }
8290 // TODO: Move in the for-loop?
8291 c.flushClients(0)
8292 outq.recycle(&pms)
8293 case <-msgs.ch:
8294 // This can possibly change now so needs to be checked here.
8295 isClustered := mset.IsClustered()
8296 ims := msgs.pop()
8297 for _, im := range ims {
8298 // If we are clustered we need to propose this message to the underlying raft group.
8299 if batch, err := getFastBatch(im.rply, im.hdr); batch != nil || err {
8300 mset.processJetStreamFastBatchMsg(batch, im.subj, im.rply, im.hdr, im.msg, im.mt)
8301 batch.returnToPool()
8302 } else if batchId := getBatchId(im.hdr); batchId != _EMPTY_ {
8303 mset.processJetStreamAtomicBatchMsg(batchId, im.subj, im.rply, im.hdr, im.msg, im.mt)
8304 } else if isClustered {
8305 mset.processClusteredInboundMsg(im.subj, im.rply, im.hdr, im.msg, im.mt, false)
8306 } else {
8307 mset.processJetStreamMsg(im.subj, im.rply, im.hdr, im.msg, 0, 0, im.mt, false, true)
8308 }
8309 im.returnToPool()
8310 }
8311 msgs.recycle(&ims)
8312 case <-gets.ch:
8313 dgs := gets.pop()
8314 for _, dg := range dgs {
8315 mset.getDirectRequest(&dg.req, dg.reply)
8316 dgPool.Put(dg)
8317 }
8318 gets.recycle(&dgs)
8319
8320 case <-amch:
8321 seqs := ackq.pop()
8322 for _, seq := range seqs {
8323 mset.ackMsg(nil, seq)
8324 }
8325 ackq.recycle(&seqs)
8326 case <-qch:
8327 return
8328 case <-s.quitCh:
8329 return
8330 }
8331 }
8332 }
8333
8334 // Used to break consumers out of their monitorConsumer go routines.
8335 func (mset *stream) resetAndWaitOnConsumers() {
8336 mset.mu.RLock()
8337 consumers := make([]*consumer, 0, len(mset.consumers))
8338 for _, o := range mset.consumers {
8339 consumers = append(consumers, o)
8340 }
8341 mset.mu.RUnlock()
8342
8343 for _, o := range consumers {
8344 if node := o.raftNode(); node != nil {
8345 node.StepDown()
8346 node.Stop()
8347 }
8348 o.stopMonitoring()
8349 }
8350 }
8351
8352 // Internal function to delete a stream.
8353 func (mset *stream) delete() error {
8354 if mset == nil {
8355 return nil
8356 }
8357 return mset.stop(true, true)
8358 }
8359
8360 // Internal function to stop or delete the stream.
8361 func (mset *stream) stop(deleteFlag, advisory bool) error {
8362 mset.mu.RLock()
8363 js, jsa, name, offlineReason := mset.js, mset.jsa, mset.cfg.Name, mset.offlineReason
8364 mset.mu.RUnlock()
8365
8366 if jsa == nil {
8367 return NewJSNotEnabledForAccountError()
8368 }
8369
8370 isShuttingDown := js.isShuttingDown()
8371
8372 // Remove from our account map first.
8373 jsa.mu.Lock()
8374 // Preserve in the account if it's marked offline, to have it remain queryable.
8375 if deleteFlag || offlineReason == _EMPTY_ {
8376 delete(jsa.streams, name)
8377 }
8378 accName := jsa.account.Name
8379 jsa.mu.Unlock()
8380
8381 // Kick monitor and collect consumers first.
8382 mset.mu.Lock()
8383
8384 // Mark closed.
8385 mset.closed.Store(true)
8386
8387 // Both flags set mean a delete where we are the stream leader.
8388 // Try to clean up any consumers used for sourcing (if one wasn't provided to us).
8389 if deleteFlag && advisory {
8390 if mset.cfg.Mirror != nil && mset.cfg.Mirror.Consumer == nil {
8391 mset.tryDeleteMirrorConsumer(mset.cfg.Mirror)
8392 }
8393 for _, s := range mset.cfg.Sources {
8394 if s.Consumer == nil {
8395 id := mset.createSourcingConsumerHash(s, mset.cfg.Sources)
8396 mset.tryDeleteSourceConsumer(id, s)
8397 }
8398 }
8399 }
8400
8401 // Signal to the monitor loop.
8402 // Can't use qch here.
8403 if mset.mqch != nil {
8404 close(mset.mqch)
8405 mset.mqch = nil
8406 }
8407
8408 // Stop responding to sync requests.
8409 mset.stopClusterSubs()
8410 // Unsubscribe from direct stream.
8411 mset.unsubscribeToStream(true, isShuttingDown)
8412
8413 // Our info sub if we spun it up.
8414 if mset.infoSub != nil {
8415 mset.srv.sysUnsubscribe(mset.infoSub)
8416 mset.infoSub = nil
8417 }
8418
8419 // Clean up consumers.
8420 var obs []*consumer
8421 for _, o := range mset.consumers {
8422 obs = append(obs, o)
8423 }
8424 // Preserve the consumers if it's marked offline, to have them remain queryable.
8425 if deleteFlag || offlineReason == _EMPTY_ {
8426 mset.clsMu.Lock()
8427 mset.consumers, mset.cList, mset.csl = nil, nil, nil
8428 mset.clsMu.Unlock()
8429 }
8430
8431 // Check if we are a mirror.
8432 if mset.mirror != nil && mset.mirror.sub != nil {
8433 mset.unsubscribe(mset.mirror.sub)
8434 mset.mirror.sub = nil
8435 mset.removeInternalConsumer(mset.mirror)
8436 }
8437 // Now check for sources.
8438 if len(mset.sources) > 0 {
8439 for _, si := range mset.sources {
8440 mset.cancelSourceConsumer(si.iname)
8441 }
8442 }
8443 mset.mu.Unlock()
8444
8445 // If we're shutting down, wait for the monitor routine, which attempts to snapshot.
8446 if isShuttingDown && !deleteFlag {
8447 mset.stopMonitoring()
8448 }
8449
8450 for _, o := range obs {
8451 if !o.isClosed() {
8452 // Third flag says do not broadcast a signal.
8453 // TODO(dlc) - If we have an err here we don't want to stop
8454 // but should we log?
8455 o.stopWithFlags(deleteFlag, deleteFlag, false, advisory)
8456 if !isShuttingDown {
8457 o.stopMonitoring()
8458 }
8459 }
8460 }
8461
8462 mset.mu.Lock()
8463 // Send stream delete advisory after the consumers.
8464 if deleteFlag && advisory {
8465 mset.sendDeleteAdvisoryLocked()
8466 }
8467
8468 // Quit channel, do this after sending the delete advisory
8469 if mset.qch != nil {
8470 close(mset.qch)
8471 mset.qch = nil
8472 }
8473
8474 // Cluster cleanup
8475 var sa *streamAssignment
8476 if n := mset.node; n != nil {
8477 if deleteFlag {
8478 n.Delete()
8479 sa = mset.sa
8480 } else if !isShuttingDown {
8481 // Stop Raft, unless JetStream is already shutting down, in which case they'll be stopped separately.
8482 n.Stop()
8483 }
8484 }
8485
8486 // Cleanup duplicate timer if running.
8487 mset.ddMu.Lock()
8488 if mset.ddtmr != nil {
8489 mset.ddtmr.Stop()
8490 mset.ddtmr = nil
8491 mset.ddmap = nil
8492 mset.ddarr = nil
8493 mset.ddindex = 0
8494 }
8495 mset.ddMu.Unlock()
8496
8497 sysc := mset.sysc
8498 mset.sysc = nil
8499
8500 if deleteFlag {
8501 // Unregistering ipQueues do not prevent them from push/pop
8502 // just will remove them from the central monitoring map
8503 mset.msgs.unregister()
8504 mset.ackq.unregister()
8505 mset.outq.unregister()
8506 mset.sigq.unregister()
8507 mset.smsgs.unregister()
8508 }
8509
8510 // Snapshot store.
8511 store := mset.store
8512 c := mset.client
8513
8514 // Clustered cleanup.
8515 mset.mu.Unlock()
8516
8517 // Check if the stream assignment has the group node specified.
8518 // We need this cleared for if the stream gets reassigned here.
8519 if sa != nil {
8520 js.mu.Lock()
8521 if sa.Group != nil {
8522 sa.Group.node = nil
8523 }
8524 js.mu.Unlock()
8525 }
8526
8527 if c != nil {
8528 c.closeConnection(ClientClosed)
8529 }
8530
8531 if sysc != nil {
8532 sysc.closeConnection(ClientClosed)
8533 }
8534
8535 if deleteFlag {
8536 // cleanup directories after the stream
8537 accDir := filepath.Join(js.config.StoreDir, accName)
8538 if store != nil {
8539 // Ignore errors.
8540 store.Delete(false)
8541 } else {
8542 streamDir := filepath.Join(accDir, streamsDir)
8543 os.RemoveAll(filepath.Join(streamDir, name))
8544 }
8545 // Release any resources.
8546 js.releaseStreamResources(&mset.cfg)
8547 // Do cleanup in separate go routine similar to how fs will use purge here..
8548 go func() {
8549 // no op if not empty
8550 os.Remove(filepath.Join(accDir, streamsDir))
8551 os.Remove(accDir)
8552 }()
8553 } else if store != nil {
8554 // Ignore errors.
8555 store.Stop()
8556 }
8557
8558 return nil
8559 }
8560
8561 func (mset *stream) getMsg(seq uint64) (*StoredMsg, error) {
8562 var smv StoreMsg
8563 sm, err := mset.store.LoadMsg(seq, &smv)
8564 if err != nil {
8565 return nil, err
8566 }
8567 // This only used in tests directly so no need to pool etc.
8568 return &StoredMsg{
8569 Subject: sm.subj,
8570 Sequence: sm.seq,
8571 Header: sm.hdr,
8572 Data: sm.msg,
8573 Time: time.Unix(0, sm.ts).UTC(),
8574 }, nil
8575 }
8576
8577 // getConsumers will return a copy of all the current consumers for this stream.
8578 func (mset *stream) getConsumers() []*consumer {
8579 mset.clsMu.RLock()
8580 defer mset.clsMu.RUnlock()
8581 return append([]*consumer(nil), mset.cList...)
8582 }
8583
8584 // numLimitableConsumers returns the number of consumers that are not direct/sourcing consumers.
8585 // Used to limit the number of consumers for MaxConsumers limits or WQ exclusivity.
8586 // Lock should be held for this one.
8587 func (mset *stream) numLimitableConsumers() int {
8588 return len(mset.consumers) - mset.sourcingConsumers
8589 }
8590
8591 // This returns all consumers that are not DIRECT.
8592 func (mset *stream) getPublicConsumers() []*consumer {
8593 mset.clsMu.RLock()
8594 defer mset.clsMu.RUnlock()
8595
8596 var obs []*consumer
8597 for _, o := range mset.cList {
8598 if !o.direct {
8599 obs = append(obs, o)
8600 }
8601 }
8602 return obs
8603 }
8604
8605 // This returns all consumers that are DIRECT.
8606 func (mset *stream) getDirectConsumers() []*consumer {
8607 mset.clsMu.RLock()
8608 defer mset.clsMu.RUnlock()
8609
8610 var obs []*consumer
8611 for _, o := range mset.cList {
8612 if o.direct {
8613 obs = append(obs, o)
8614 }
8615 }
8616 return obs
8617 }
8618
8619 // 2 minutes plus up to 30s jitter.
8620 const (
8621 defaultCheckInterestStateT = 2 * time.Minute
8622 defaultCheckInterestStateJ = 30
8623 )
8624
8625 var (
8626 checkInterestStateT = defaultCheckInterestStateT // Interval
8627 checkInterestStateJ = defaultCheckInterestStateJ // Jitter (secs)
8628 )
8629
8630 // Will check for interest retention and make sure messages
8631 // that have been acked are processed and removed.
8632 // This will check the ack floors of all consumers, and adjust our first sequence accordingly.
8633 func (mset *stream) checkInterestState() {
8634 if mset == nil || !mset.isInterestRetention() {
8635 // If we are limits based nothing to do.
8636 return
8637 }
8638
8639 // Ensure only one of these runs at the same time.
8640 if !mset.cisrun.CompareAndSwap(false, true) {
8641 return
8642 }
8643 defer mset.cisrun.Store(false)
8644
8645 var ss StreamState
8646 mset.store.FastState(&ss)
8647
8648 asflr := uint64(math.MaxUint64)
8649 for _, o := range mset.getConsumers() {
8650 o.checkStateForInterestStream(&ss)
8651 o.mu.RLock()
8652 chkflr := o.chkflr
8653 o.mu.RUnlock()
8654 asflr = min(asflr, chkflr)
8655 }
8656
8657 mset.cfgMu.RLock()
8658 rp := mset.cfg.Retention
8659 mset.cfgMu.RUnlock()
8660 // Remove as many messages from the "head" of the stream if there's no interest anymore.
8661 if rp == InterestPolicy && asflr != math.MaxUint64 {
8662 mset.store.Compact(asflr)
8663 }
8664 }
8665
8666 func (mset *stream) isInterestRetention() bool {
8667 mset.mu.RLock()
8668 defer mset.mu.RUnlock()
8669 return mset.cfg.Retention != LimitsPolicy
8670 }
8671
8672 // NumConsumers reports on number of active consumers for this stream.
8673 func (mset *stream) numConsumers() int {
8674 mset.mu.RLock()
8675 defer mset.mu.RUnlock()
8676 return len(mset.consumers)
8677 }
8678
8679 // Lock should be held.
8680 func (mset *stream) setConsumer(o *consumer) {
8681 if _, ok := mset.consumers[o.name]; ok {
8682 return
8683 }
8684 mset.consumers[o.name] = o
8685 if o.direct || o.sourcing {
8686 mset.sourcingConsumers++
8687 }
8688 // Now update consumers list as well
8689 mset.clsMu.Lock()
8690 mset.cList = append(mset.cList, o)
8691 if mset.csl == nil {
8692 mset.csl = gsl.NewSublist[*consumer]()
8693 }
8694 for _, sub := range o.signalSubs() {
8695 mset.csl.Insert(sub, o)
8696 }
8697 mset.clsMu.Unlock()
8698 }
8699
8700 // Lock should be held.
8701 func (mset *stream) removeConsumer(o *consumer) {
8702 if c, ok := mset.consumers[o.name]; !ok || c != o {
8703 return
8704 }
8705 delete(mset.consumers, o.name)
8706
8707 if (o.direct || o.sourcing) && mset.sourcingConsumers > 0 {
8708 mset.sourcingConsumers--
8709 }
8710
8711 // Now update consumers list as well
8712 mset.clsMu.Lock()
8713 for i, ol := range mset.cList {
8714 if ol == o {
8715 mset.cList = append(mset.cList[:i], mset.cList[i+1:]...)
8716 break
8717 }
8718 }
8719 // Always remove from the leader sublist.
8720 if mset.csl != nil {
8721 for _, sub := range o.signalSubs() {
8722 mset.csl.Remove(sub, o)
8723 }
8724 }
8725 mset.clsMu.Unlock()
8726 }
8727
8728 // swapSigSubs will update signal Subs for a new subject filter.
8729 // consumer lock should not be held.
8730 func (mset *stream) swapSigSubs(o *consumer, newFilters []string) {
8731 mset.clsMu.Lock()
8732 o.mu.Lock()
8733
8734 if o.closed || o.mset == nil {
8735 o.mu.Unlock()
8736 mset.clsMu.Unlock()
8737 return
8738 }
8739
8740 if o.sigSubs != nil {
8741 if mset.csl != nil {
8742 for _, sub := range o.sigSubs {
8743 mset.csl.Remove(sub, o)
8744 }
8745 }
8746 o.sigSubs = nil
8747 }
8748
8749 if mset.csl == nil {
8750 mset.csl = gsl.NewSublist[*consumer]()
8751 }
8752 // If no filters are present, add fwcs to sublist for that consumer.
8753 if newFilters == nil {
8754 mset.csl.Insert(fwcs, o)
8755 o.sigSubs = append(o.sigSubs, fwcs)
8756 } else {
8757 // If there are filters, add their subjects to sublist.
8758 for _, filter := range newFilters {
8759 mset.csl.Insert(filter, o)
8760 o.sigSubs = append(o.sigSubs, filter)
8761 }
8762 }
8763 o.mu.Unlock()
8764 mset.clsMu.Unlock()
8765 }
8766
8767 // lookupConsumer will retrieve a consumer by name.
8768 func (mset *stream) lookupConsumer(name string) *consumer {
8769 mset.mu.RLock()
8770 defer mset.mu.RUnlock()
8771 return mset.consumers[name]
8772 }
8773
8774 func (mset *stream) numDirectConsumers() (num int) {
8775 mset.clsMu.RLock()
8776 defer mset.clsMu.RUnlock()
8777
8778 // Consumers that are direct are not recorded at the store level.
8779 for _, o := range mset.cList {
8780 if o.direct {
8781 num++
8782 }
8783 }
8784 return num
8785 }
8786
8787 // State will return the current state for this stream.
8788 func (mset *stream) state() StreamState {
8789 return mset.stateWithDetail(false)
8790 }
8791
8792 func (mset *stream) stateWithDetail(details bool) StreamState {
8793 // mset.store does not change once set, so ok to reference here directly.
8794 // We do this elsewhere as well.
8795 store := mset.store
8796 if store == nil {
8797 return StreamState{}
8798 }
8799
8800 // Currently rely on store for details.
8801 if details {
8802 return store.State()
8803 }
8804 // Here we do the fast version.
8805 var state StreamState
8806 store.FastState(&state)
8807 return state
8808 }
8809
8810 func (mset *stream) Store() StreamStore {
8811 mset.mu.RLock()
8812 defer mset.mu.RUnlock()
8813 return mset.store
8814 }
8815
8816 // Determines if the new proposed partition is unique amongst all public consumers.
8817 // Lock should be held.
8818 func (mset *stream) partitionUnique(name string, partitions []string) bool {
8819 for _, partition := range partitions {
8820 for n, o := range mset.consumers {
8821 // Skip the consumer being checked.
8822 if n == name {
8823 continue
8824 }
8825 // Ignore direct/sourcing consumers.
8826 if o.direct || o.sourcing {
8827 continue
8828 }
8829 o.mu.RLock()
8830 if o.subjf == nil {
8831 o.mu.RUnlock()
8832 return false
8833 }
8834 for _, filter := range o.subjf {
8835 if SubjectsCollide(partition, filter.subject) {
8836 o.mu.RUnlock()
8837 return false
8838 }
8839 }
8840 o.mu.RUnlock()
8841 }
8842 }
8843 return true
8844 }
8845
8846 // Lock should be held.
8847 func (mset *stream) potentialFilteredConsumers() bool {
8848 numSubjects := len(mset.cfg.Subjects)
8849 if len(mset.consumers) == 0 || numSubjects == 0 {
8850 return false
8851 }
8852 if numSubjects > 1 || subjectHasWildcard(mset.cfg.Subjects[0]) {
8853 return true
8854 }
8855 return false
8856 }
8857
8858 // Check if there is no interest in this sequence number across our consumers.
8859 // The consumer passed is optional if we are processing the ack for that consumer.
8860 // Write lock should be held.
8861 func (mset *stream) noInterest(seq uint64, obs *consumer) bool {
8862 return !mset.checkForInterest(seq, obs)
8863 }
8864
8865 // Check if there is no interest in this sequence number and subject across our consumers.
8866 // The consumer passed is optional if we are processing the ack for that consumer.
8867 // Write lock should be held.
8868 func (mset *stream) noInterestWithSubject(seq uint64, subj string, obs *consumer) bool {
8869 return !mset.checkForInterestWithSubject(seq, subj, obs)
8870 }
8871
8872 // Write lock should be held here for the stream to avoid race conditions on state.
8873 func (mset *stream) checkForInterest(seq uint64, obs *consumer) bool {
8874 var subj string
8875 if mset.potentialFilteredConsumers() {
8876 pmsg := getJSPubMsgFromPool()
8877 defer pmsg.returnToPool()
8878 sm, err := mset.store.LoadMsg(seq, &pmsg.StoreMsg)
8879 if err != nil {
8880 if err == ErrStoreEOF {
8881 // Register this as a preAck.
8882 mset.registerPreAck(obs, seq)
8883 return true
8884 }
8885 mset.clearAllPreAcks(seq)
8886 return false
8887 }
8888 subj = sm.subj
8889 }
8890 return mset.checkForInterestWithSubject(seq, subj, obs)
8891 }
8892
8893 // Checks for interest given a sequence and subject.
8894 func (mset *stream) checkForInterestWithSubject(seq uint64, subj string, obs *consumer) bool {
8895 for _, o := range mset.consumers {
8896 // If this is us or we have a registered preAck for this consumer continue inspecting.
8897 if o == obs || mset.hasPreAck(o, seq) {
8898 continue
8899 }
8900 // Check if we need an ack.
8901 if o.needAck(seq, subj) {
8902 return true
8903 }
8904 }
8905 mset.clearAllPreAcks(seq)
8906 return false
8907 }
8908
8909 // Check if we have a pre-registered ack for this sequence.
8910 // Write lock should be held.
8911 func (mset *stream) hasPreAck(o *consumer, seq uint64) bool {
8912 if o == nil || len(mset.preAcks) == 0 {
8913 return false
8914 }
8915 consumers := mset.preAcks[seq]
8916 if len(consumers) == 0 {
8917 return false
8918 }
8919 _, found := consumers[o]
8920 return found
8921 }
8922
8923 // Check if we have all consumers pre-acked for this sequence and subject.
8924 // Write lock should be held.
8925 func (mset *stream) hasAllPreAcks(seq uint64, subj string) bool {
8926 if len(mset.preAcks) == 0 || len(mset.preAcks[seq]) == 0 {
8927 return false
8928 }
8929 // Since these can be filtered and mutually exclusive,
8930 // if we have some preAcks we need to check all interest here.
8931 return mset.noInterestWithSubject(seq, subj, nil)
8932 }
8933
8934 // Check if we have all consumers pre-acked.
8935 // Write lock should be held.
8936 func (mset *stream) clearAllPreAcks(seq uint64) {
8937 delete(mset.preAcks, seq)
8938 }
8939
8940 // Clear all preAcks below floor.
8941 // Write lock should be held.
8942 func (mset *stream) clearAllPreAcksBelowFloor(floor uint64) {
8943 for seq := range mset.preAcks {
8944 if seq < floor {
8945 delete(mset.preAcks, seq)
8946 }
8947 }
8948 }
8949
8950 // Clear all preAcks in [first, last]. Iterates the preAcks map, not the
8951 // range, so callers can pass very wide ranges cheaply.
8952 // Write lock should be held.
8953 func (mset *stream) clearAllPreAcksInRange(first, last uint64) {
8954 for seq := range mset.preAcks {
8955 if seq >= first && seq <= last {
8956 delete(mset.preAcks, seq)
8957 }
8958 }
8959 }
8960
8961 // This will register an ack for a consumer if it arrives before the actual message.
8962 func (mset *stream) registerPreAckLock(o *consumer, seq uint64) {
8963 mset.mu.Lock()
8964 defer mset.mu.Unlock()
8965 mset.registerPreAck(o, seq)
8966 }
8967
8968 // This will register an ack for a consumer if it arrives before
8969 // the actual message.
8970 // Write lock should be held.
8971 func (mset *stream) registerPreAck(o *consumer, seq uint64) {
8972 if o == nil {
8973 return
8974 }
8975 if mset.preAcks == nil {
8976 mset.preAcks = make(map[uint64]map[*consumer]struct{})
8977 }
8978 if mset.preAcks[seq] == nil {
8979 mset.preAcks[seq] = make(map[*consumer]struct{})
8980 }
8981 mset.preAcks[seq][o] = struct{}{}
8982 }
8983
8984 // This will clear an ack for a consumer.
8985 // Write lock should be held.
8986 func (mset *stream) clearPreAck(o *consumer, seq uint64) {
8987 if o == nil || len(mset.preAcks) == 0 {
8988 return
8989 }
8990 if consumers := mset.preAcks[seq]; len(consumers) > 0 {
8991 delete(consumers, o)
8992 if len(consumers) == 0 {
8993 delete(mset.preAcks, seq)
8994 }
8995 }
8996 }
8997
8998 // ackMsg is called into from a consumer when we have a WorkQueue or Interest Retention Policy.
8999 // Returns whether the message at seq was removed as a result of the ACK.
9000 // (Or should be removed in the case of clustered streams, since it requires a message delete proposal)
9001 func (mset *stream) ackMsg(o *consumer, seq uint64) bool {
9002 if seq == 0 {
9003 return false
9004 }
9005
9006 // Don't make this RLock(). We need to have only 1 running at a time to gauge interest across all consumers.
9007 mset.mu.Lock()
9008 if mset.closed.Load() || mset.cfg.Retention == LimitsPolicy {
9009 mset.mu.Unlock()
9010 return false
9011 }
9012
9013 store := mset.store
9014 var state StreamState
9015 store.FastState(&state)
9016
9017 // If this has arrived before we have processed the message itself.
9018 if seq > state.LastSeq {
9019 mset.registerPreAck(o, seq)
9020 mset.mu.Unlock()
9021 // We have not removed the message, but should still signal so we could retry later
9022 // since we potentially need to remove it then.
9023 return true
9024 }
9025
9026 // Always clear pre-ack if here.
9027 mset.clearPreAck(o, seq)
9028
9029 // Make sure this sequence is not below our first sequence.
9030 if seq < state.FirstSeq {
9031 mset.mu.Unlock()
9032 return false
9033 }
9034
9035 // If there's no interest left on this message for all consumers, we can remove it.
9036 shouldRemove := mset.noInterest(seq, nil)
9037
9038 // If nothing else to do.
9039 if !shouldRemove {
9040 mset.mu.Unlock()
9041 return false
9042 }
9043
9044 if !mset.isClustered() {
9045 mset.mu.Unlock()
9046 // If we are here we should attempt to remove.
9047 if _, err := store.RemoveMsg(seq); err == ErrStoreEOF {
9048 // This should not happen, but being pedantic.
9049 mset.registerPreAckLock(o, seq)
9050 }
9051 return true
9052 }
9053
9054 // Only propose message deletion to the stream if we're the leader, otherwise followers would also propose.
9055 // We must be the stream leader, since we are the only one that can guarantee message ordering and ack handling.
9056 // Either we've stored the message, and we know for sure all consumers have acked the message.
9057 // Or, we've not stored the message yet (rare), and all consumers have registered as pre-acks,
9058 // then we do the message delete proposal after we've stored the message instead.
9059 // Except for a Direct AckNone consumer, as that has a nil consumer here, we still forward the delete proposal.
9060 if o != nil && !mset.isLeader() {
9061 // Currently, interest-based streams can race on "no interest" because consumer creates/updates go over
9062 // the meta layer and published messages go over the stream layer. Some servers could then either store
9063 // or not store some initial set of messages that gained new interest. To get the stream back in sync,
9064 // we allow moving the first sequence up.
9065 // TODO(mvv): later on only the stream leader should determine "no interest"
9066 interestRaiseFirst := mset.cfg.Retention == InterestPolicy && seq == state.FirstSeq
9067 mset.mu.Unlock()
9068 if interestRaiseFirst {
9069 if _, err := store.RemoveMsg(seq); err == ErrStoreEOF {
9070 // This should not happen, but being pedantic.
9071 mset.registerPreAckLock(o, seq)
9072 }
9073 }
9074 // Must still mark as removal if follower. If we become leader later, we must be able to retry the proposal.
9075 return true
9076 }
9077
9078 md := streamMsgDelete{Seq: seq, NoErase: true, Stream: mset.cfg.Name}
9079 // Directly proposes if stream leader, otherwise forwards it.
9080 mset.node.ForwardProposal(encodeMsgDelete(&md))
9081 mset.mu.Unlock()
9082 return true
9083 }
9084
9085 // Snapshot creates a snapshot for the stream and possibly consumers.
9086 func (mset *stream) snapshot(deadline time.Duration, checkMsgs, includeConsumers bool) (*SnapshotResult, error) {
9087 if mset.closed.Load() {
9088 return nil, errStreamClosed
9089 }
9090 store := mset.store
9091 return store.Snapshot(deadline, checkMsgs, includeConsumers)
9092 }
9093
9094 const snapsDir = "__snapshots__"
9095
9096 // RestoreStream will restore a stream from a snapshot.
9097 func (a *Account) RestoreStream(ncfg *StreamConfig, r io.Reader) (*stream, error) {
9098 if ncfg == nil {
9099 return nil, errors.New("nil config on stream restore")
9100 }
9101
9102 s, jsa, err := a.checkForJetStream()
9103 if err != nil {
9104 return nil, err
9105 }
9106 js := jsa.js
9107 if js == nil {
9108 return nil, NewJSNotEnabledForAccountError()
9109 }
9110
9111 cfg, apiErr := s.checkStreamCfg(ncfg, a, false)
9112 if apiErr != nil {
9113 return nil, apiErr
9114 }
9115
9116 sd := filepath.Join(jsa.storeDir, snapsDir)
9117 if _, err := os.Stat(sd); os.IsNotExist(err) {
9118 if err := os.MkdirAll(sd, defaultDirPerms); err != nil {
9119 return nil, fmt.Errorf("could not create snapshots directory - %v", err)
9120 }
9121 }
9122 sdir, err := os.MkdirTemp(sd, "snap-")
9123 if err != nil {
9124 return nil, err
9125 }
9126 if _, err := os.Stat(sdir); os.IsNotExist(err) {
9127 if err := os.MkdirAll(sdir, defaultDirPerms); err != nil {
9128 return nil, fmt.Errorf("could not create snapshots directory - %v", err)
9129 }
9130 }
9131 defer os.RemoveAll(sdir)
9132
9133 logAndReturnError := func() error {
9134 a.mu.RLock()
9135 err := fmt.Errorf("unexpected content (account=%s)", a.Name)
9136 if a.srv != nil {
9137 a.srv.Errorf("Stream restore failed due to %v", err)
9138 }
9139 a.mu.RUnlock()
9140 return err
9141 }
9142 sdirCheck := filepath.Clean(sdir) + string(os.PathSeparator)
9143
9144 _, isClustered := jsa.jetStreamAndClustered()
9145 jsa.usageMu.RLock()
9146 selected, tier, hasTier := jsa.selectLimits(cfg.Replicas)
9147 jsa.usageMu.RUnlock()
9148 reserved := int64(0)
9149 if hasTier {
9150 if isClustered {
9151 js.mu.RLock()
9152 _, reserved = js.tieredStreamAndReservationCount(a.Name, tier, &cfg)
9153 js.mu.RUnlock()
9154 } else {
9155 reserved = jsa.tieredReservation(tier, &cfg)
9156 }
9157 }
9158
9159 var bc int64
9160 tr := tar.NewReader(s2.NewReader(r))
9161 for {
9162 hdr, err := tr.Next()
9163 if err == io.EOF {
9164 break // End of snapshot
9165 }
9166 if err != nil {
9167 return nil, err
9168 }
9169 if hdr.Typeflag != tar.TypeReg {
9170 return nil, logAndReturnError()
9171 }
9172 bc += hdr.Size
9173 js.mu.RLock()
9174 err = js.checkAllLimits(&selected, tier, &cfg, reserved, bc)
9175 js.mu.RUnlock()
9176 if err != nil {
9177 return nil, err
9178 }
9179 fpath := filepath.Join(sdir, filepath.Clean(hdr.Name))
9180 if !strings.HasPrefix(fpath, sdirCheck) {
9181 return nil, logAndReturnError()
9182 }
9183 os.MkdirAll(filepath.Dir(fpath), defaultDirPerms)
9184 fd, err := os.OpenFile(fpath, os.O_CREATE|os.O_RDWR, 0600)
9185 if err != nil {
9186 return nil, err
9187 }
9188 _, err = io.Copy(fd, tr)
9189 fd.Close()
9190 if err != nil {
9191 return nil, err
9192 }
9193 }
9194
9195 // Check metadata.
9196 // The cfg passed in will be the new identity for the stream.
9197 var fcfg FileStreamInfo
9198 b, err := os.ReadFile(filepath.Join(sdir, JetStreamMetaFile))
9199 if err != nil {
9200 return nil, err
9201 }
9202 if err := json.Unmarshal(b, &fcfg); err != nil {
9203 return nil, err
9204 }
9205
9206 // Check to make sure names match.
9207 if fcfg.Name != cfg.Name {
9208 return nil, errors.New("stream names do not match")
9209 }
9210
9211 // See if this stream already exists.
9212 if _, err := a.lookupStream(cfg.Name); err == nil {
9213 return nil, NewJSStreamNameExistRestoreFailedError()
9214 }
9215 // Move into the correct place here.
9216 ndir := filepath.Join(jsa.storeDir, streamsDir, cfg.Name)
9217 // Remove old one if for some reason it is still here.
9218 if _, err := os.Stat(ndir); err == nil {
9219 os.RemoveAll(ndir)
9220 }
9221 // Make sure our destination streams directory exists.
9222 if err := os.MkdirAll(filepath.Join(jsa.storeDir, streamsDir), defaultDirPerms); err != nil {
9223 return nil, err
9224 }
9225 // Move into new location.
9226 if err := os.Rename(sdir, ndir); err != nil {
9227 return nil, err
9228 }
9229
9230 mset, err := a.addStream(&cfg)
9231 if err != nil {
9232 // Make sure to clean up after ourselves here.
9233 os.RemoveAll(ndir)
9234 return nil, err
9235 }
9236 if !fcfg.Created.IsZero() {
9237 mset.setCreatedTime(fcfg.Created)
9238 }
9239
9240 // Make sure we do an update if the configs have changed.
9241 if !reflect.DeepEqual(fcfg.StreamConfig, cfg) {
9242 if err := mset.update(&cfg); err != nil {
9243 return nil, err
9244 }
9245 }
9246
9247 // Now do consumers.
9248 odir := filepath.Join(ndir, consumerDir)
9249 ofis, _ := os.ReadDir(odir)
9250 for _, ofi := range ofis {
9251 metafile := filepath.Join(odir, ofi.Name(), JetStreamMetaFile)
9252 metasum := filepath.Join(odir, ofi.Name(), JetStreamMetaFileSum)
9253 if _, err := os.Stat(metafile); os.IsNotExist(err) {
9254 mset.stop(true, false)
9255 return nil, fmt.Errorf("error restoring consumer [%q]: %v", ofi.Name(), err)
9256 }
9257 buf, err := os.ReadFile(metafile)
9258 if err != nil {
9259 mset.stop(true, false)
9260 return nil, fmt.Errorf("error restoring consumer [%q]: %v", ofi.Name(), err)
9261 }
9262 if _, err := os.Stat(metasum); os.IsNotExist(err) {
9263 mset.stop(true, false)
9264 return nil, fmt.Errorf("error restoring consumer [%q]: %v", ofi.Name(), err)
9265 }
9266 var cfg FileConsumerInfo
9267 if err := json.Unmarshal(buf, &cfg); err != nil {
9268 mset.stop(true, false)
9269 return nil, fmt.Errorf("error restoring consumer [%q]: %v", ofi.Name(), err)
9270 }
9271 isEphemeral := !isDurableConsumer(&cfg.ConsumerConfig)
9272 if isEphemeral {
9273 // This is an ephermal consumer and this could fail on restart until
9274 // the consumer can reconnect. We will create it as a durable and switch it.
9275 cfg.ConsumerConfig.Durable = ofi.Name()
9276 }
9277 obs, err := mset.addConsumer(&cfg.ConsumerConfig)
9278 if err != nil {
9279 mset.stop(true, false)
9280 return nil, fmt.Errorf("error restoring consumer [%q]: %v", ofi.Name(), err)
9281 }
9282 if isEphemeral {
9283 obs.switchToEphemeral()
9284 }
9285 if !cfg.Created.IsZero() {
9286 obs.setCreatedTime(cfg.Created)
9287 }
9288 obs.mu.Lock()
9289 err = obs.readStoredState()
9290 obs.mu.Unlock()
9291 if err != nil {
9292 mset.stop(true, false)
9293 return nil, fmt.Errorf("error restoring consumer [%q]: %v", ofi.Name(), err)
9294 }
9295 }
9296 return mset, nil
9297 }
9298
9299 // This is to check for dangling messages on interest retention streams. Only called on account enable.
9300 // Issue https://github.com/nats-io/nats-server/issues/3612
9301 func (mset *stream) checkForOrphanMsgs() {
9302 mset.mu.RLock()
9303 consumers := make([]*consumer, 0, len(mset.consumers))
9304 for _, o := range mset.consumers {
9305 consumers = append(consumers, o)
9306 }
9307 accName, stream := mset.acc.Name, mset.cfg.Name
9308
9309 var ss StreamState
9310 mset.store.FastState(&ss)
9311 mset.mu.RUnlock()
9312
9313 for _, o := range consumers {
9314 if err := o.checkStateForInterestStream(&ss); err == errAckFloorHigherThanLastSeq {
9315 o.mu.RLock()
9316 s, consumer := o.srv, o.name
9317 state, _ := o.store.State()
9318 asflr := state.AckFloor.Stream
9319 o.mu.RUnlock()
9320 // Warn about stream state vs our ack floor.
9321 s.RateLimitWarnf("Detected consumer '%s > %s > %s' ack floor %d is ahead of stream's last sequence %d",
9322 accName, stream, consumer, asflr, ss.LastSeq)
9323 }
9324 }
9325 }
9326
9327 // Check on startup to make sure that consumers replication matches us.
9328 // Interest retention requires replication matches.
9329 func (mset *stream) checkConsumerReplication() {
9330 mset.mu.RLock()
9331 defer mset.mu.RUnlock()
9332
9333 if mset.cfg.Retention != InterestPolicy {
9334 return
9335 }
9336
9337 s, acc := mset.srv, mset.acc
9338 for _, o := range mset.consumers {
9339 o.mu.RLock()
9340 // Consumer replicas 0 can be a legit config for the replicas and we will inherit from the stream
9341 // when this is the case.
9342 if mset.cfg.Replicas != o.cfg.Replicas && o.cfg.Replicas != 0 {
9343 s.Errorf("consumer '%s > %s > %s' MUST match replication (%d vs %d) of stream with interest policy",
9344 acc, mset.cfg.Name, o.cfg.Name, mset.cfg.Replicas, o.cfg.Replicas)
9345 }
9346 o.mu.RUnlock()
9347 }
9348 }
9349
9350 // startMonitorWg registers a pending monitor goroutine on monitorWg. It is
9351 // held under monitorMu so that the monitorWg.Add can never race a concurrent
9352 // monitorWg.Wait in stopMonitoring. The corresponding monitorWg.Done is done by
9353 // the monitor goroutine directly and must not be wrapped with monitorMu.
9354 func (mset *stream) startMonitorWg() {
9355 mset.monitorMu.Lock()
9356 // Quit channel for this new monitor generation. Not if the stream is (being)
9357 // stopped, stop won't signal again so the monitor must exit right away instead.
9358 mset.mu.Lock()
9359 if mset.mqch == nil && !mset.closed.Load() {
9360 mset.mqch = make(chan struct{})
9361 }
9362 mset.mu.Unlock()
9363 mset.monitorWg.Add(1)
9364 mset.monitorMu.Unlock()
9365 }
9366
9367 // stopMonitoring signals any running monitor goroutine to quit and waits for
9368 // it to fully exit.
9369 func (mset *stream) stopMonitoring() {
9370 // monitorMu is held across both the quit signal and the wait so that a
9371 // concurrent startMonitorWg cannot slip a new monitor generation in
9372 // between.
9373 mset.monitorMu.Lock()
9374 defer mset.monitorMu.Unlock()
9375 mset.signalMonitorQuit()
9376 mset.monitorWg.Wait()
9377 }
9378
9379 // Will check if we are running in the monitor already and if not set the appropriate flag.
9380 func (mset *stream) checkInMonitor() bool {
9381 mset.mu.Lock()
9382 defer mset.mu.Unlock()
9383
9384 if mset.inMonitor {
9385 return true
9386 }
9387 mset.inMonitor = true
9388 return false
9389 }
9390
9391 // Clear us being in the monitor routine.
9392 func (mset *stream) clearMonitorRunning() {
9393 mset.mu.Lock()
9394 defer mset.mu.Unlock()
9395 mset.inMonitor = false
9396 }
9397
9398 // Check if our monitor is running.
9399 func (mset *stream) isMonitorRunning() bool {
9400 mset.mu.RLock()
9401 defer mset.mu.RUnlock()
9402 return mset.inMonitor
9403 }
9404
9405 // setWriteErr stores the write error in the stream.
9406 func (mset *stream) setWriteErr(err error) {
9407 mset.mu.Lock()
9408 defer mset.mu.Unlock()
9409 mset.setWriteErrLocked(err)
9410 }
9411
9412 func (mset *stream) setWriteErrLocked(err error) {
9413 if mset.werr != nil {
9414 return
9415 }
9416 // Ignore non-write errors.
9417 if err == ErrStoreClosed {
9418 return
9419 }
9420 mset.srv.Errorf("JetStream stream '%s > %s' critical write error: %v", mset.acc.Name, mset.cfg.Name, err)
9421 mset.werr = err
9422 assert.Unreachable("Stream encountered write error", map[string]any{
9423 "account": mset.acc.Name,
9424 "stream": mset.cfg.Name,
9425 "err": err,
9426 })
9427
9428 // If stream is replicated, put it in observer mode to make sure another server can pick it up.
9429 if node := mset.node; node != nil {
9430 node.StepDown()
9431 node.SetObserver(true)
9432 }
9433 }
9434
9435 // getWriteErr returns the write error stored in the stream (if any).
9436 func (mset *stream) getWriteErr() error {
9437 mset.mu.RLock()
9438 defer mset.mu.RUnlock()
9439 return mset.werr
9440 }
9441
9442 // Adjust accounting for sent messages as part of replication.
9443 func (mset *stream) trackReplicationTraffic(node RaftNode, sz int, r int) {
9444 // If we are using the system account for NRG, add in the extra sent msgs and bytes to our account
9445 // so that the end user / account owner has visibility.
9446 if node.IsSystemAccount() && mset.acc != nil && r > 1 {
9447 outMsgs := int64(r - 1)
9448 outBytes := int64(sz * (r - 1))
9449
9450 mset.acc.stats.Lock()
9451 mset.acc.stats.outMsgs += outMsgs
9452 mset.acc.stats.outBytes += outBytes
9453 mset.acc.stats.rt.outMsgs += outMsgs
9454 mset.acc.stats.rt.outBytes += outBytes
9455 mset.acc.stats.Unlock()
9456 }
9457 }