Debian Codegraph @

server/consumer.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 "bytes"
18 "encoding/binary"
19 "encoding/json"
20 "errors"
21 "fmt"
22 "math"
23 "math/rand"
24 "os"
25 "path/filepath"
26 "reflect"
27 "regexp"
28 "slices"
29 "strconv"
30 "strings"
31 "sync"
32 "sync/atomic"
33 "time"
34
35 "github.com/nats-io/nats-server/v2/server/avl"
36 "github.com/nats-io/nats-server/v2/server/gsl"
37 "github.com/nats-io/nuid"
38 "golang.org/x/time/rate"
39 )
40
41 // Headers sent with Request Timeout
42 const (
43 JSPullRequestPendingMsgs = "Nats-Pending-Messages"
44 JSPullRequestPendingBytes = "Nats-Pending-Bytes"
45 JSPullRequestNatsPinId = "Nats-Pin-Id"
46 )
47
48 var (
49 validGroupName = regexp.MustCompile(`^[a-zA-Z0-9/_=-]{1,16}$`)
50 )
51
52 // Headers sent when batch size was completed, but there were remaining bytes.
53 const JsPullRequestRemainingBytesT = "NATS/1.0 409 Batch Completed\r\n%s: %d\r\n%s: %d\r\n\r\n"
54
55 type ConsumerInfo struct {
56 Stream string `json:"stream_name"`
57 Name string `json:"name"`
58 Created time.Time `json:"created"`
59 Config *ConsumerConfig `json:"config,omitempty"`
60 Delivered SequenceInfo `json:"delivered"`
61 AckFloor SequenceInfo `json:"ack_floor"`
62 NumAckPending int `json:"num_ack_pending"`
63 NumRedelivered int `json:"num_redelivered"`
64 NumWaiting int `json:"num_waiting"`
65 NumPending uint64 `json:"num_pending"`
66 Cluster *ClusterInfo `json:"cluster,omitempty"`
67 PushBound bool `json:"push_bound,omitempty"`
68 Paused bool `json:"paused,omitempty"`
69 PauseRemaining time.Duration `json:"pause_remaining,omitempty"`
70 // TimeStamp indicates when the info was gathered
71 TimeStamp time.Time `json:"ts"`
72 PriorityGroups []PriorityGroupState `json:"priority_groups,omitempty"`
73 }
74
75 // consumerInfoClusterResponse is a response used in a cluster to communicate the consumer info
76 // back to the meta leader as part of a consumer list request.
77 type consumerInfoClusterResponse struct {
78 ConsumerInfo
79 OfflineReason string `json:"offline_reason,omitempty"` // Reporting when a consumer is offline.
80 }
81
82 type PriorityGroupState struct {
83 Group string `json:"group"`
84 PinnedClientID string `json:"pinned_client_id,omitempty"`
85 PinnedTS time.Time `json:"pinned_ts,omitempty"`
86 }
87
88 type ConsumerConfig struct {
89 Durable string `json:"durable_name,omitempty"`
90 Name string `json:"name,omitempty"`
91 Description string `json:"description,omitempty"`
92 DeliverPolicy DeliverPolicy `json:"deliver_policy"`
93 OptStartSeq uint64 `json:"opt_start_seq,omitempty"`
94 OptStartTime *time.Time `json:"opt_start_time,omitempty"`
95 AckPolicy AckPolicy `json:"ack_policy"`
96 AckWait time.Duration `json:"ack_wait,omitempty"`
97 MaxDeliver int `json:"max_deliver,omitempty"`
98 BackOff []time.Duration `json:"backoff,omitempty"`
99 FilterSubject string `json:"filter_subject,omitempty"`
100 FilterSubjects []string `json:"filter_subjects,omitempty"`
101 ReplayPolicy ReplayPolicy `json:"replay_policy"`
102 RateLimit uint64 `json:"rate_limit_bps,omitempty"` // Bits per sec
103 SampleFrequency string `json:"sample_freq,omitempty"`
104 MaxWaiting int `json:"max_waiting,omitempty"`
105 MaxAckPending int `json:"max_ack_pending,omitempty"`
106 FlowControl bool `json:"flow_control,omitempty"`
107 HeadersOnly bool `json:"headers_only,omitempty"`
108
109 // Pull based options.
110 MaxRequestBatch int `json:"max_batch,omitempty"`
111 MaxRequestExpires time.Duration `json:"max_expires,omitempty"`
112 MaxRequestMaxBytes int `json:"max_bytes,omitempty"`
113
114 // Push based consumers.
115 DeliverSubject string `json:"deliver_subject,omitempty"`
116 DeliverGroup string `json:"deliver_group,omitempty"`
117 Heartbeat time.Duration `json:"idle_heartbeat,omitempty"`
118
119 // Ephemeral inactivity threshold.
120 InactiveThreshold time.Duration `json:"inactive_threshold,omitempty"`
121
122 // Generally inherited by parent stream and other markers, now can be configured directly.
123 Replicas int `json:"num_replicas"`
124 // Force memory storage.
125 MemoryStorage bool `json:"mem_storage,omitempty"`
126
127 // Don't add to general clients.
128 Direct bool `json:"direct,omitempty"`
129 Sourcing bool `json:"sourcing,omitempty"`
130
131 // Metadata is additional metadata for the Consumer.
132 Metadata map[string]string `json:"metadata,omitempty"`
133
134 // PauseUntil is for suspending the consumer until the deadline.
135 PauseUntil *time.Time `json:"pause_until,omitempty"`
136
137 // Priority groups
138 PriorityGroups []string `json:"priority_groups,omitempty"`
139 PriorityPolicy PriorityPolicy `json:"priority_policy,omitempty"`
140 PinnedTTL time.Duration `json:"priority_timeout,omitempty"`
141 }
142
143 // SequenceInfo has both the consumer and the stream sequence and last activity.
144 type SequenceInfo struct {
145 Consumer uint64 `json:"consumer_seq"`
146 Stream uint64 `json:"stream_seq"`
147 Last *time.Time `json:"last_active,omitempty"`
148 }
149
150 type CreateConsumerRequest struct {
151 Stream string `json:"stream_name"`
152 Config ConsumerConfig `json:"config"`
153 Action ConsumerAction `json:"action"`
154 Pedantic bool `json:"pedantic,omitempty"`
155 }
156
157 type ConsumerAction int
158
159 const (
160 ActionCreateOrUpdate ConsumerAction = iota
161 ActionUpdate
162 ActionCreate
163 )
164
165 const (
166 actionUpdateJSONString = `"update"`
167 actionCreateJSONString = `"create"`
168 actionCreateOrUpdateJSONString = `""`
169 )
170
171 var (
172 actionUpdateJSONBytes = []byte(actionUpdateJSONString)
173 actionCreateJSONBytes = []byte(actionCreateJSONString)
174 actionCreateOrUpdateJSONBytes = []byte(actionCreateOrUpdateJSONString)
175 )
176
177 func (a ConsumerAction) String() string {
178 switch a {
179 case ActionCreateOrUpdate:
180 return actionCreateOrUpdateJSONString
181 case ActionCreate:
182 return actionCreateJSONString
183 case ActionUpdate:
184 return actionUpdateJSONString
185 }
186 return actionCreateOrUpdateJSONString
187 }
188
189 func (a ConsumerAction) MarshalJSON() ([]byte, error) {
190 switch a {
191 case ActionCreate:
192 return actionCreateJSONBytes, nil
193 case ActionUpdate:
194 return actionUpdateJSONBytes, nil
195 case ActionCreateOrUpdate:
196 return actionCreateOrUpdateJSONBytes, nil
197 default:
198 return nil, fmt.Errorf("can not marshal %v", a)
199 }
200 }
201
202 func (a *ConsumerAction) UnmarshalJSON(data []byte) error {
203 switch string(data) {
204 case actionCreateJSONString:
205 *a = ActionCreate
206 case actionUpdateJSONString:
207 *a = ActionUpdate
208 case actionCreateOrUpdateJSONString:
209 *a = ActionCreateOrUpdate
210 default:
211 return fmt.Errorf("unknown consumer action: %v", string(data))
212 }
213 return nil
214 }
215
216 // ConsumerNakOptions is for optional NAK values, e.g. delay.
217 type ConsumerNakOptions struct {
218 Delay time.Duration `json:"delay"`
219 }
220
221 // PriorityPolicy determines policy for selecting messages based on priority.
222 type PriorityPolicy int
223
224 const (
225 // No priority policy.
226 PriorityNone PriorityPolicy = iota
227 // Clients will get the messages only if certain criteria are specified.
228 PriorityOverflow
229 // Single client takes over handling of the messages, while others are on standby.
230 PriorityPinnedClient
231 // Clients with lowest priority will be selected first.
232 PriorityPrioritized
233 )
234
235 const (
236 PriorityNoneJSONString = `"none"`
237 PriorityOverflowJSONString = `"overflow"`
238 PriorityPinnedClientJSONString = `"pinned_client"`
239 PriorityPrioritizedJSONString = `"prioritized"`
240 )
241
242 var (
243 PriorityNoneJSONBytes = []byte(PriorityNoneJSONString)
244 PriorityOverflowJSONBytes = []byte(PriorityOverflowJSONString)
245 PriorityPinnedClientJSONBytes = []byte(PriorityPinnedClientJSONString)
246 PriorityPrioritizedJSONBytes = []byte(PriorityPrioritizedJSONString)
247 )
248
249 func (pp PriorityPolicy) String() string {
250 switch pp {
251 case PriorityOverflow:
252 return PriorityOverflowJSONString
253 case PriorityPinnedClient:
254 return PriorityPinnedClientJSONString
255 case PriorityPrioritized:
256 return PriorityPrioritizedJSONString
257 default:
258 return PriorityNoneJSONString
259 }
260 }
261
262 func (pp PriorityPolicy) MarshalJSON() ([]byte, error) {
263 switch pp {
264 case PriorityOverflow:
265 return PriorityOverflowJSONBytes, nil
266 case PriorityPinnedClient:
267 return PriorityPinnedClientJSONBytes, nil
268 case PriorityPrioritized:
269 return PriorityPrioritizedJSONBytes, nil
270 case PriorityNone:
271 return PriorityNoneJSONBytes, nil
272 default:
273 return nil, fmt.Errorf("unknown priority policy: %v", pp)
274 }
275 }
276
277 func (pp *PriorityPolicy) UnmarshalJSON(data []byte) error {
278 switch string(data) {
279 case PriorityOverflowJSONString:
280 *pp = PriorityOverflow
281 case PriorityPinnedClientJSONString:
282 *pp = PriorityPinnedClient
283 case PriorityPrioritizedJSONString:
284 *pp = PriorityPrioritized
285 case PriorityNoneJSONString:
286 *pp = PriorityNone
287 default:
288 return fmt.Errorf("unknown priority policy: %v", string(data))
289 }
290 return nil
291 }
292
293 // DeliverPolicy determines how the consumer should select the first message to deliver.
294 type DeliverPolicy int
295
296 const (
297 // DeliverAll will be the default so can be omitted from the request.
298 DeliverAll DeliverPolicy = iota
299 // DeliverLast will start the consumer with the last sequence received.
300 DeliverLast
301 // DeliverNew will only deliver new messages that are sent after the consumer is created.
302 DeliverNew
303 // DeliverByStartSequence will look for a defined starting sequence to start.
304 DeliverByStartSequence
305 // DeliverByStartTime will select the first messsage with a timestamp >= to StartTime.
306 DeliverByStartTime
307 // DeliverLastPerSubject will start the consumer with the last message for all subjects received.
308 DeliverLastPerSubject
309 )
310
311 func (dp DeliverPolicy) String() string {
312 switch dp {
313 case DeliverAll:
314 return "all"
315 case DeliverLast:
316 return "last"
317 case DeliverNew:
318 return "new"
319 case DeliverByStartSequence:
320 return "by_start_sequence"
321 case DeliverByStartTime:
322 return "by_start_time"
323 case DeliverLastPerSubject:
324 return "last_per_subject"
325 default:
326 return "undefined"
327 }
328 }
329
330 // AckPolicy determines how the consumer should acknowledge delivered messages.
331 type AckPolicy int
332
333 const (
334 // AckNone requires no acks for delivered messages.
335 AckNone AckPolicy = iota
336 // AckAll when acking a sequence number, this implicitly acks all sequences below this one as well.
337 AckAll
338 // AckExplicit requires ack or nack for all messages.
339 AckExplicit
340 // AckFlowControl functions like AckAll, but acks based on responses to flow control.
341 AckFlowControl
342 )
343
344 func (a AckPolicy) String() string {
345 switch a {
346 case AckNone:
347 return "none"
348 case AckAll:
349 return "all"
350 case AckFlowControl:
351 return "flow_control"
352 default:
353 return "explicit"
354 }
355 }
356
357 // ReplayPolicy determines how the consumer should replay messages it already has queued in the stream.
358 type ReplayPolicy int
359
360 const (
361 // ReplayInstant will replay messages as fast as possible.
362 ReplayInstant ReplayPolicy = iota
363 // ReplayOriginal will maintain the same timing as the messages were received.
364 ReplayOriginal
365 )
366
367 func (r ReplayPolicy) String() string {
368 switch r {
369 case ReplayInstant:
370 return replayInstantPolicyJSONString
371 default:
372 return replayOriginalPolicyJSONString
373 }
374 }
375
376 // OK
377 const OK = "+OK"
378
379 // Ack responses. Note that a nil or no payload is same as AckAck
380 var (
381 // Ack
382 AckAck = []byte("+ACK") // nil or no payload to ack subject also means ACK
383 AckOK = []byte(OK) // deprecated but +OK meant ack as well.
384
385 // Nack
386 AckNak = []byte("-NAK")
387 // Progress indicator
388 AckProgress = []byte("+WPI")
389 // Ack + Deliver the next message(s).
390 AckNext = []byte("+NXT")
391 // Terminate delivery of the message.
392 AckTerm = []byte("+TERM")
393 )
394
395 const (
396 // reasons to supply when terminating messages using limits
397 ackTermLimitsReason = "Message deleted by stream limits"
398 ackTermUnackedLimitsReason = "Unacknowledged message was deleted"
399 )
400
401 // Calculate accurate replicas for the consumer config with the parent stream config.
402 func (consCfg ConsumerConfig) replicas(strCfg *StreamConfig) int {
403 if consCfg.Replicas == 0 || consCfg.Replicas > strCfg.Replicas {
404 if !isDurableConsumer(&consCfg) && strCfg.Retention == LimitsPolicy && consCfg.Replicas == 0 {
405 // Matches old-school ephemerals only, where the replica count is 0.
406 return 1
407 }
408 return strCfg.Replicas
409 }
410 return consCfg.Replicas
411 }
412
413 // Consumer is a jetstream consumer.
414 type consumer struct {
415 // Atomic used to notify that we want to process an ack.
416 // This will be checked in checkPending to abort processing
417 // and let ack be processed in priority.
418 awl int64
419 leader atomic.Bool
420 mu sync.RWMutex
421 js *jetStream
422 mset *stream
423 acc *Account
424 srv *Server
425 client *client
426 sysc *client
427 sid int
428 name string
429 stream string
430 sseq uint64 // next stream sequence
431 subjf subjectFilters // subject filters and their sequences
432 filters *gsl.SimpleSublist // When we have multiple filters we will use LoadNextMsgMulti and pass this in.
433 dseq uint64 // delivered consumer sequence
434 adflr uint64 // ack delivery floor
435 asflr uint64 // ack store floor
436 chkflr uint64 // our check floor, interest streams only.
437 npc int64 // Num Pending Count
438 npf uint64 // Num Pending Floor Sequence
439 dsubj string
440 qgroup string
441 lss *lastSeqSkipList
442 rlimit *rate.Limiter
443 reqSub *subscription
444 resetSub *subscription
445 ackSubOld *subscription
446 ackReplyOldT string
447 ackSubjOld string
448 ackSub *subscription
449 ackReplyT string
450 ackSubj string
451 fcPreOld string
452 fcSubjOld string
453 fcPre string
454 fcSubj string
455 nextMsgSubj string
456 nextMsgReqs *ipQueue[*nextMsgReq]
457 resetSubj string
458 maxp int
459 pblimit int
460 maxpb int
461 pbytes int
462 fcsz int
463 fcid string
464 fcSubOld *subscription
465 fcSub *subscription
466 outq *jsOutQ
467 pending map[uint64]*Pending
468 ptmr *time.Timer
469 ptmrEnd time.Time
470 rdq []uint64
471 rdqi avl.SequenceSet
472 rdc map[uint64]uint64
473 replies map[uint64]string
474 pendingDeliveries map[uint64]*jsPubMsg // Messages that can be delivered after achieving quorum.
475 waitingDeliveries map[string]*waitingDelivery // (Optional) request timeout messages that need to wait for replicated deliveries first.
476 maxdc uint64
477 waiting *waitQueue
478 cfg ConsumerConfig
479 direct bool // Immutable, enforced by checkNewConsumerConfig. Read without o.mu.
480 sourcing bool // Immutable, enforced by checkNewConsumerConfig. Read without o.mu.
481 ici *ConsumerInfo
482 store ConsumerStore
483 active bool
484 replay bool
485 useV2Ack bool
486 dtmr *time.Timer
487 uptmr *time.Timer // Unpause timer
488 gwdtmr *time.Timer
489 dthresh time.Duration
490 mch chan struct{} // Message channel
491 qch chan struct{} // Quit channel
492 mqch chan struct{} // The monitor's quit channel.
493 inch chan bool // Interest change channel
494 sfreq int32
495 ackEventT string
496 nakEventT string
497 deliveryExcEventT string
498 created time.Time
499 ldt time.Time
500 lat time.Time
501 lwqic time.Time
502 closed bool
503
504 // Clustered.
505 ca *consumerAssignment
506 node RaftNode
507 term uint64 // Raft term, used to determine if we are still the leader for the current term (if applicable, 0 otherwise).
508 infoSub *subscription
509 lqsent time.Time
510 prm map[string]struct{}
511 rsm map[string]bool // Reset requests that need to be responded to on the internal sys account (if true).
512 prOk bool
513 uch chan struct{}
514 retention RetentionPolicy
515
516 monitorWg sync.WaitGroup
517 monitorMu sync.Mutex // Serializes monitorWg's Add against Wait to prevent a WaitGroup reuse panic.
518 inMonitor bool
519
520 // R>1 proposals
521 pch chan struct{}
522 phead *proposal
523 ptail *proposal
524
525 // Ack queue
526 ackMsgs *ipQueue[*jsAckMsg]
527
528 // for stream signaling when multiple filters are set.
529 sigSubs []string
530
531 // Priority groups
532 // Details described in ADR-42.
533
534 // currentPinId is the current nuid for the pinned consumer.
535 // If the Consumer is running in `PriorityPinnedClient` mode, server will
536 // pick up a new nuid and assign it to first pending pull request.
537 currentPinId string
538 /// pinnedTtl is the remaining time before the current PinId expires.
539 pinnedTtl *time.Timer
540 pinnedTS time.Time
541
542 // If standalone/single-server, the offline reason needs to be stored directly in the consumer.
543 // Otherwise, if clustered it will be part of the consumer assignment.
544 offlineReason string
545 }
546
547 // A single subject filter.
548 type subjectFilter struct {
549 subject string
550 tokenizedSubject []string
551 hasWildcard bool
552 }
553
554 type subjectFilters []*subjectFilter
555
556 // subjects is a helper function used for updating consumers.
557 // It is not used and should not be used in hotpath.
558 func (s subjectFilters) subjects() []string {
559 subjects := make([]string, 0, len(s))
560 for _, filter := range s {
561 subjects = append(subjects, filter.subject)
562 }
563 return subjects
564 }
565
566 type proposal struct {
567 data []byte
568 next *proposal
569 }
570
571 const (
572 // JsAckWaitDefault is the default AckWait, only applicable on explicit ack policy consumers.
573 JsAckWaitDefault = 30 * time.Second
574 // JsDeleteWaitTimeDefault is the default amount of time we will wait for non-durable
575 // consumers to be in an inactive state before deleting them.
576 JsDeleteWaitTimeDefault = 5 * time.Second
577 // JsFlowControlMaxPending specifies default pending bytes during flow control that can be outstanding.
578 JsFlowControlMaxPending = 32 * 1024 * 1024
579 // JsDefaultMaxAckPending is set for consumers with explicit ack that do not set the max ack pending.
580 JsDefaultMaxAckPending = 1000
581 // JsDefaultPinnedTTL is the default grace period for the pinned consumer to send a new request before a new pin
582 // is picked by a server.
583 JsDefaultPinnedTTL = 2 * time.Minute
584 )
585
586 // Helper function to set consumer config defaults from above.
587 func setConsumerConfigDefaults(config *ConsumerConfig, streamCfg *StreamConfig, lim *JSLimitOpts, accLim *JetStreamAccountLimits, pedantic bool) *ApiError {
588 // Setup default of -1, meaning no limit for MaxDeliver.
589 if config.MaxDeliver == 0 || config.MaxDeliver < -1 {
590 if pedantic && config.MaxDeliver < -1 {
591 return NewJSPedanticError(errors.New("max_deliver must be set to -1"))
592 }
593 config.MaxDeliver = -1
594 }
595 // Setup zero defaults.
596 if config.MaxWaiting < 0 {
597 if pedantic {
598 return NewJSPedanticError(errors.New("max_waiting must not be negative"))
599 }
600 config.MaxWaiting = 0
601 }
602 if config.MaxAckPending < -1 {
603 if pedantic {
604 return NewJSPedanticError(errors.New("max_ack_pending must be set to -1"))
605 }
606 config.MaxAckPending = -1
607 }
608 if config.MaxRequestBatch < 0 {
609 if pedantic {
610 return NewJSPedanticError(errors.New("max_batch must not be negative"))
611 }
612 config.MaxRequestBatch = 0
613 }
614 if config.MaxRequestExpires < 0 {
615 if pedantic {
616 return NewJSPedanticError(errors.New("max_expires must not be negative"))
617 }
618 config.MaxRequestExpires = 0
619 }
620 if config.MaxRequestMaxBytes < 0 {
621 if pedantic {
622 return NewJSPedanticError(errors.New("max_bytes must not be negative"))
623 }
624 config.MaxRequestMaxBytes = 0
625 }
626 if config.Heartbeat < 0 {
627 if pedantic {
628 return NewJSPedanticError(errors.New("idle_heartbeat must not be negative"))
629 }
630 config.Heartbeat = 0
631 }
632 if config.InactiveThreshold < 0 {
633 if pedantic {
634 return NewJSPedanticError(errors.New("inactive_threshold must not be negative"))
635 }
636 config.InactiveThreshold = 0
637 }
638 if config.PinnedTTL < 0 {
639 if pedantic {
640 return NewJSPedanticError(errors.New("priority_timeout must not be negative"))
641 }
642 config.PinnedTTL = 0
643 }
644
645 // Set to default if not specified.
646 if config.DeliverSubject == _EMPTY_ && config.MaxWaiting == 0 {
647 config.MaxWaiting = JSWaitQueueDefaultMax
648 }
649 // Setup proper default for ack wait if we are in explicit ack mode.
650 if config.AckWait == 0 && (config.AckPolicy == AckExplicit || config.AckPolicy == AckAll) {
651 config.AckWait = JsAckWaitDefault
652 }
653 // If BackOff was specified that will override the AckWait and the MaxDeliver.
654 if len(config.BackOff) > 0 {
655 if pedantic && config.AckWait != config.BackOff[0] {
656 return NewJSPedanticError(errors.New("first backoff value has to equal batch AckWait"))
657 }
658 config.AckWait = config.BackOff[0]
659 }
660 if config.MaxAckPending == 0 {
661 if pedantic && streamCfg.ConsumerLimits.MaxAckPending > 0 {
662 return NewJSPedanticError(errors.New("max_ack_pending must be set if it's configured in stream limits"))
663 }
664 config.MaxAckPending = streamCfg.ConsumerLimits.MaxAckPending
665 }
666 if config.InactiveThreshold == 0 {
667 if pedantic && streamCfg.ConsumerLimits.InactiveThreshold > 0 {
668 return NewJSPedanticError(errors.New("inactive_threshold must be set if it's configured in stream limits"))
669 }
670 config.InactiveThreshold = streamCfg.ConsumerLimits.InactiveThreshold
671 }
672 // Set proper default for max ack pending if we are ack explicit and none has been set.
673 if config.MaxAckPending == 0 && config.AckPolicy != AckNone {
674 ackPending := JsDefaultMaxAckPending
675 if lim.MaxAckPending > 0 && lim.MaxAckPending < ackPending {
676 ackPending = lim.MaxAckPending
677 }
678 if accLim.MaxAckPending > 0 && accLim.MaxAckPending < ackPending {
679 ackPending = accLim.MaxAckPending
680 }
681 config.MaxAckPending = ackPending
682 }
683 // if applicable set max request batch size
684 if config.DeliverSubject == _EMPTY_ && config.MaxRequestBatch == 0 && lim.MaxRequestBatch > 0 {
685 if pedantic {
686 return NewJSPedanticError(errors.New("max_request_batch must be set if it's JetStream limits are set"))
687 }
688 config.MaxRequestBatch = lim.MaxRequestBatch
689 }
690
691 // set the default value only if pinned policy is used.
692 if config.PriorityPolicy == PriorityPinnedClient && config.PinnedTTL == 0 {
693 config.PinnedTTL = JsDefaultPinnedTTL
694 }
695
696 // Set default values for flow control policy.
697 if config.AckPolicy == AckFlowControl && !pedantic {
698 config.FlowControl = true
699 config.Heartbeat = sourceHealthHB
700 }
701 return nil
702 }
703
704 // Check the consumer config. If we are recovering don't check filter subjects.
705 func checkConsumerCfg(
706 config *ConsumerConfig,
707 srvLim *JSLimitOpts,
708 cfg *StreamConfig,
709 _ *Account,
710 accLim *JetStreamAccountLimits,
711 isRecovering bool,
712 ) *ApiError {
713
714 if config.Name != _EMPTY_ && !isValidAssetName(config.Name) {
715 return NewJSStreamInvalidConfigError(errors.New("consumer name can not contain '.', '*', '>', '\\', '/'"))
716 }
717 if config.Durable != _EMPTY_ && !isValidAssetName(config.Durable) {
718 return NewJSStreamInvalidConfigError(errors.New("consumer durable name can not contain '.', '*', '>', '\\', '/'"))
719 }
720
721 // Check if replicas is defined but exceeds parent stream.
722 if config.Replicas > 0 && config.Replicas > cfg.Replicas {
723 return NewJSConsumerReplicasExceedsStreamError()
724 }
725 // Check that it is not negative
726 if config.Replicas < 0 {
727 return NewJSReplicasCountCannotBeNegativeError()
728 }
729 // If the stream is interest or workqueue retention make sure the replicas
730 // match that of the stream. This is REQUIRED for now.
731 if cfg.Retention == InterestPolicy || cfg.Retention == WorkQueuePolicy {
732 // Only error here if not recovering.
733 // We handle recovering in a different spot to allow consumer to come up
734 // if previous version allowed it to be created. We do not want it to not come up.
735 if !isRecovering && config.Replicas != 0 && config.Replicas != cfg.Replicas {
736 return NewJSConsumerReplicasShouldMatchStreamError()
737 }
738 }
739
740 if _, err := config.AckPolicy.MarshalJSON(); err != nil {
741 return NewJSConsumerAckPolicyInvalidError()
742 }
743 if _, err := config.ReplayPolicy.MarshalJSON(); err != nil {
744 return NewJSConsumerReplayPolicyInvalidError()
745 }
746
747 // Check not negative AckWait/BackOff
748 for _, backoff := range config.BackOff {
749 if backoff < 0 {
750 return NewJSConsumerBackOffNegativeError()
751 }
752 }
753 if config.AckWait < 0 {
754 return NewJSConsumerAckWaitNegativeError()
755 }
756
757 // Ack Flow Control policy requires push-based flow-controlled consumer.
758 if config.AckPolicy == AckFlowControl {
759 if config.DeliverSubject == _EMPTY_ {
760 return NewJSConsumerAckFCRequiresPushError()
761 }
762 if !config.FlowControl {
763 return NewJSConsumerAckFCRequiresFCError()
764 }
765 // We currently limit using heartbeat of 1s, since those are used for ephemeral sourcing consumers as well.
766 // We could decide to relax this in the future, but need to be careful to not allow a heartbeat larger
767 // than the stalled source timeout.
768 if config.Heartbeat != sourceHealthHB {
769 return NewJSStreamInvalidConfigError(fmt.Errorf("flow control ack policy heartbeat needs to be 1s"))
770 }
771 if config.MaxAckPending <= 0 {
772 return NewJSConsumerAckFCRequiresMaxAckPendingError()
773 }
774 if config.AckWait != 0 || len(config.BackOff) > 0 {
775 return NewJSConsumerAckFCRequiresNoAckWaitError()
776 }
777 if config.MaxDeliver > 0 {
778 return NewJSConsumerAckFCRequiresNoMaxDeliverError()
779 }
780 }
781
782 // Check if we have a BackOff defined that MaxDeliver is within range etc.
783 if lbo := len(config.BackOff); lbo > 0 && config.MaxDeliver != -1 && lbo > config.MaxDeliver {
784 return NewJSConsumerMaxDeliverBackoffError()
785 }
786
787 if len(config.Description) > JSMaxDescriptionLen {
788 return NewJSConsumerDescriptionTooLongError(JSMaxDescriptionLen)
789 }
790
791 // For now expect a literal subject if its not empty. Empty means work queue mode (pull mode).
792 if config.DeliverSubject != _EMPTY_ {
793 if !subjectIsLiteral(config.DeliverSubject) {
794 return NewJSConsumerDeliverToWildcardsError()
795 }
796 if !IsValidSubject(config.DeliverSubject) {
797 return NewJSConsumerInvalidDeliverSubjectError()
798 }
799 if deliveryFormsCycle(cfg, config.DeliverSubject) {
800 return NewJSConsumerDeliverCycleError()
801 }
802 if config.MaxWaiting != 0 {
803 return NewJSConsumerPushMaxWaitingError()
804 }
805 if config.MaxAckPending > 0 && config.AckPolicy == AckNone {
806 return NewJSConsumerMaxPendingAckPolicyRequiredError()
807 }
808 if config.Heartbeat > 0 && config.Heartbeat < 100*time.Millisecond {
809 return NewJSConsumerSmallHeartbeatError()
810 }
811 } else {
812 // Pull mode with work queue retention from the stream requires an explicit ack.
813 if config.AckPolicy == AckNone && cfg.Retention == WorkQueuePolicy {
814 return NewJSConsumerPullRequiresAckError()
815 }
816 if config.RateLimit > 0 {
817 return NewJSConsumerPullWithRateLimitError()
818 }
819 if config.MaxWaiting < 0 {
820 return NewJSConsumerMaxWaitingNegativeError()
821 }
822 if config.Heartbeat > 0 {
823 return NewJSConsumerHBRequiresPushError()
824 }
825 if config.FlowControl {
826 return NewJSConsumerFCRequiresPushError()
827 }
828 if config.MaxRequestBatch < 0 {
829 return NewJSConsumerMaxRequestBatchNegativeError()
830 }
831 if config.MaxRequestExpires != 0 && config.MaxRequestExpires < time.Millisecond {
832 return NewJSConsumerMaxRequestExpiresTooSmallError()
833 }
834 if srvLim.MaxRequestBatch > 0 && config.MaxRequestBatch > srvLim.MaxRequestBatch {
835 return NewJSConsumerMaxRequestBatchExceededError(srvLim.MaxRequestBatch)
836 }
837 }
838 if srvLim.MaxAckPending > 0 && config.MaxAckPending > srvLim.MaxAckPending {
839 return NewJSConsumerMaxPendingAckExcessError(srvLim.MaxAckPending)
840 }
841 if accLim.MaxAckPending > 0 && config.MaxAckPending > accLim.MaxAckPending {
842 return NewJSConsumerMaxPendingAckExcessError(accLim.MaxAckPending)
843 }
844 if cfg.ConsumerLimits.MaxAckPending > 0 && config.MaxAckPending > cfg.ConsumerLimits.MaxAckPending {
845 return NewJSConsumerMaxPendingAckExcessError(cfg.ConsumerLimits.MaxAckPending)
846 }
847 if cfg.ConsumerLimits.InactiveThreshold > 0 && config.InactiveThreshold > cfg.ConsumerLimits.InactiveThreshold {
848 return NewJSConsumerInactiveThresholdExcessError(cfg.ConsumerLimits.InactiveThreshold)
849 }
850
851 // Direct need to be non-mapped ephemerals.
852 if config.Direct {
853 if config.DeliverSubject == _EMPTY_ {
854 return NewJSConsumerDirectRequiresPushError()
855 }
856 if isDurableConsumer(config) {
857 return NewJSConsumerDirectRequiresEphemeralError()
858 }
859 }
860
861 // Do not allow specifying both FilterSubject and FilterSubjects,
862 // as that's probably unintentional without any difference from passing
863 // all filters in FilterSubjects.
864 if config.FilterSubject != _EMPTY_ && len(config.FilterSubjects) > 0 {
865 return NewJSConsumerDuplicateFilterSubjectsError()
866 }
867
868 if config.FilterSubject != _EMPTY_ && !IsValidSubject(config.FilterSubject) {
869 return NewJSStreamInvalidConfigError(ErrBadSubject)
870 }
871
872 // We treat FilterSubjects: []string{""} as a misconfig, so we validate against it.
873 for _, filter := range config.FilterSubjects {
874 if filter == _EMPTY_ {
875 return NewJSConsumerEmptyFilterError()
876 }
877 }
878 subjectFilters := gatherSubjectFilters(config.FilterSubject, config.FilterSubjects)
879
880 // Check subject filters do not overlap.
881 for outer, subject := range subjectFilters {
882 if !IsValidSubject(subject) {
883 return NewJSStreamInvalidConfigError(ErrBadSubject)
884 }
885 for inner, ssubject := range subjectFilters {
886 if inner != outer && subjectIsSubsetMatch(subject, ssubject) {
887 return NewJSConsumerOverlappingSubjectFiltersError()
888 }
889 }
890 }
891
892 // Helper function to formulate similar errors.
893 badStart := func(dp, start string) error {
894 return fmt.Errorf("consumer delivery policy is deliver %s, but optional start %s is also set", dp, start)
895 }
896 notSet := func(dp, notSet string) error {
897 return fmt.Errorf("consumer delivery policy is deliver %s, but optional %s is not set", dp, notSet)
898 }
899
900 // Check on start position conflicts.
901 switch config.DeliverPolicy {
902 case DeliverAll:
903 if config.OptStartSeq > 0 {
904 return NewJSConsumerInvalidPolicyError(badStart("all", "sequence"))
905 }
906 if config.OptStartTime != nil {
907 return NewJSConsumerInvalidPolicyError(badStart("all", "time"))
908 }
909 case DeliverLast:
910 if config.OptStartSeq > 0 {
911 return NewJSConsumerInvalidPolicyError(badStart("last", "sequence"))
912 }
913 if config.OptStartTime != nil {
914 return NewJSConsumerInvalidPolicyError(badStart("last", "time"))
915 }
916 case DeliverLastPerSubject:
917 if config.OptStartSeq > 0 {
918 return NewJSConsumerInvalidPolicyError(badStart("last per subject", "sequence"))
919 }
920 if config.OptStartTime != nil {
921 return NewJSConsumerInvalidPolicyError(badStart("last per subject", "time"))
922 }
923 if config.FilterSubject == _EMPTY_ && len(config.FilterSubjects) == 0 {
924 return NewJSConsumerInvalidPolicyError(notSet("last per subject", "filter subject"))
925 }
926 case DeliverNew:
927 if config.OptStartSeq > 0 {
928 return NewJSConsumerInvalidPolicyError(badStart("new", "sequence"))
929 }
930 if config.OptStartTime != nil {
931 return NewJSConsumerInvalidPolicyError(badStart("new", "time"))
932 }
933 case DeliverByStartSequence:
934 if config.OptStartSeq == 0 {
935 return NewJSConsumerInvalidPolicyError(notSet("by start sequence", "start sequence"))
936 }
937 if config.OptStartTime != nil {
938 return NewJSConsumerInvalidPolicyError(badStart("by start sequence", "time"))
939 }
940 case DeliverByStartTime:
941 if config.OptStartTime == nil {
942 return NewJSConsumerInvalidPolicyError(notSet("by start time", "start time"))
943 }
944 if config.OptStartSeq != 0 {
945 return NewJSConsumerInvalidPolicyError(badStart("by start time", "start sequence"))
946 }
947 }
948
949 if config.SampleFrequency != _EMPTY_ {
950 s := strings.TrimSuffix(config.SampleFrequency, "%")
951 if sampleFreq, err := strconv.Atoi(s); err != nil || sampleFreq < 0 {
952 return NewJSConsumerInvalidSamplingError(err)
953 }
954 }
955
956 // We reject if flow control is set without heartbeats.
957 if config.FlowControl && config.Heartbeat == 0 {
958 return NewJSConsumerWithFlowControlNeedsHeartbeatsError()
959 }
960
961 if config.Durable != _EMPTY_ && config.Name != _EMPTY_ {
962 if config.Name != config.Durable {
963 return NewJSConsumerCreateDurableAndNameMismatchError()
964 }
965 }
966
967 var metadataLen int
968 for k, v := range config.Metadata {
969 metadataLen += len(k) + len(v)
970 }
971 if metadataLen > JSMaxMetadataLen {
972 return NewJSConsumerMetadataLengthError(fmt.Sprintf("%dKB", JSMaxMetadataLen/1024))
973 }
974
975 if config.PriorityPolicy != PriorityNone {
976 if config.DeliverSubject != "" {
977 return NewJSConsumerPushWithPriorityGroupError()
978 }
979 if len(config.PriorityGroups) == 0 {
980 return NewJSConsumerPriorityPolicyWithoutGroupError()
981 }
982
983 for _, group := range config.PriorityGroups {
984 if group == _EMPTY_ {
985 return NewJSConsumerEmptyGroupNameError()
986 }
987 if !validGroupName.MatchString(group) {
988 return NewJSConsumerInvalidGroupNameError()
989 }
990 }
991 } else {
992 // If PriorityPolicy is None or not set, reject if PriorityGroups or PinnedTTL are set
993 if len(config.PriorityGroups) > 0 {
994 return NewJSConsumerPriorityGroupWithPolicyNoneError()
995 }
996 if config.PinnedTTL > 0 {
997 return NewJSConsumerPinnedTTLWithoutPriorityPolicyNoneError()
998 }
999 }
1000
1001 // For now don't allow preferred server in placement.
1002 if cfg.Placement != nil && cfg.Placement.Preferred != _EMPTY_ {
1003 return NewJSStreamInvalidConfigError(fmt.Errorf("preferred server not permitted in placement"))
1004 }
1005
1006 return nil
1007 }
1008
1009 func (mset *stream) addConsumerWithAction(config *ConsumerConfig, action ConsumerAction, pedantic bool) (*consumer, error) {
1010 return mset.addConsumerWithAssignment(config, _EMPTY_, nil, false, action, pedantic)
1011 }
1012
1013 func (mset *stream) addConsumer(config *ConsumerConfig) (*consumer, error) {
1014 return mset.addConsumerWithAction(config, ActionCreateOrUpdate, false)
1015 }
1016
1017 func (mset *stream) addConsumerWithAssignment(config *ConsumerConfig, oname string, ca *consumerAssignment, isRecovering bool, action ConsumerAction, pedantic bool) (*consumer, error) {
1018 // Check if this stream has closed.
1019 if mset.closed.Load() {
1020 return nil, NewJSStreamInvalidError()
1021 }
1022
1023 mset.mu.RLock()
1024 s, js, jsa, cfg, acc, lseq := mset.srv, mset.js, mset.jsa, mset.cfg, mset.acc, mset.lseq
1025 mset.mu.RUnlock()
1026
1027 // If we do not have the consumer currently assigned to us in cluster mode we will proceed but warn.
1028 // This can happen on startup with restored state where on meta replay we still do not have
1029 // the assignment. Running in single server mode this always returns true.
1030 if oname != _EMPTY_ && !jsa.consumerAssigned(mset.name(), oname) {
1031 s.Debugf("Consumer %q > %q does not seem to be assigned to this server", mset.name(), oname)
1032 }
1033
1034 if config == nil {
1035 return nil, NewJSConsumerConfigRequiredError()
1036 }
1037
1038 selectedLimits, _, _, _ := acc.selectLimits(config.replicas(&cfg))
1039 if selectedLimits == nil {
1040 return nil, NewJSNoLimitsError()
1041 }
1042
1043 srvLim := &s.getOpts().JetStreamLimits
1044 // Make sure we have sane defaults. Do so with the JS lock, otherwise a
1045 // badly timed meta snapshot can result in a race condition.
1046 mset.js.mu.Lock()
1047 err := setConsumerConfigDefaults(config, &cfg, srvLim, selectedLimits, pedantic)
1048 mset.js.mu.Unlock()
1049 if err != nil {
1050 return nil, err
1051 }
1052
1053 if err := checkConsumerCfg(config, srvLim, &cfg, acc, selectedLimits, isRecovering); err != nil {
1054 return nil, err
1055 }
1056 sampleFreq := 0
1057 if config.SampleFrequency != _EMPTY_ {
1058 // Can't fail as checkConsumerCfg checks correct format
1059 sampleFreq, _ = strconv.Atoi(strings.TrimSuffix(config.SampleFrequency, "%"))
1060 }
1061
1062 // Grab the client, account and server reference.
1063 c := mset.client
1064 if c == nil {
1065 return nil, NewJSStreamInvalidError()
1066 }
1067 var accName string
1068 c.mu.Lock()
1069 s, a := c.srv, c.acc
1070 if a != nil {
1071 accName = a.Name
1072 }
1073 c.mu.Unlock()
1074
1075 // Hold mset lock here.
1076 mset.mu.Lock()
1077 if mset.client == nil || mset.store == nil || mset.consumers == nil {
1078 mset.mu.Unlock()
1079 return nil, NewJSStreamInvalidError()
1080 }
1081
1082 // If this one is durable and already exists, we let that be ok as long as only updating what should be allowed.
1083 var cName string
1084 if isDurableConsumer(config) {
1085 cName = config.Durable
1086 } else if config.Name != _EMPTY_ {
1087 cName = config.Name
1088 }
1089 if cName != _EMPTY_ {
1090 if eo, ok := mset.consumers[cName]; ok {
1091 if action == ActionCreate {
1092 ocfg := eo.config()
1093 copyConsumerMetadata(config, &ocfg)
1094 if !reflect.DeepEqual(config, &ocfg) {
1095 mset.mu.Unlock()
1096 return nil, NewJSConsumerAlreadyExistsError()
1097 }
1098 }
1099 // Check for overlapping subjects if we are a workqueue
1100 if cfg.Retention == WorkQueuePolicy {
1101 subjects := gatherSubjectFilters(config.FilterSubject, config.FilterSubjects)
1102 if !mset.partitionUnique(cName, subjects) {
1103 mset.mu.Unlock()
1104 return nil, NewJSConsumerWQConsumerNotUniqueError()
1105 }
1106 }
1107 mset.mu.Unlock()
1108 err := eo.updateConfig(config)
1109 if err == nil {
1110 return eo, nil
1111 }
1112 return nil, NewJSConsumerCreateError(err, Unless(err))
1113 }
1114 }
1115 if action == ActionUpdate {
1116 mset.mu.Unlock()
1117 return nil, NewJSConsumerDoesNotExistError()
1118 }
1119
1120 standalone := !s.JetStreamIsClustered() && s.standAloneMode()
1121
1122 // If we're clustered we've already done this check, only do this if we're a standalone server.
1123 // But if we're standalone, only enforce if we're not recovering, since the MaxConsumers could've
1124 // been updated while we already had more consumers on disk.
1125 if standalone && !isRecovering {
1126 // Check for any limits, if the config for the consumer sets a limit we check against that
1127 // but if not we use the value from account limits, if account limits is more restrictive
1128 // than stream config we prefer the account limits to handle cases where account limits are
1129 // updated during the lifecycle of the stream
1130 maxc := cfg.MaxConsumers
1131 if maxc <= 0 || (selectedLimits.MaxConsumers > 0 && selectedLimits.MaxConsumers < maxc) {
1132 maxc = selectedLimits.MaxConsumers
1133 }
1134 if maxc > 0 && mset.numLimitableConsumers() >= maxc {
1135 mset.mu.Unlock()
1136 return nil, NewJSMaximumConsumersLimitError()
1137 }
1138 }
1139
1140 // Check on stream type conflicts with WorkQueues.
1141 if cfg.Retention == WorkQueuePolicy && !config.Direct && !config.Sourcing {
1142 // Force explicit acks here.
1143 if config.AckPolicy != AckExplicit && config.AckPolicy != AckFlowControl {
1144 mset.mu.Unlock()
1145 return nil, NewJSConsumerWQRequiresExplicitAckError()
1146 }
1147 if config.DeliverPolicy != DeliverAll {
1148 mset.mu.Unlock()
1149 return nil, NewJSConsumerWQConsumerNotDeliverAllError()
1150 }
1151 if mset.numLimitableConsumers() > 0 {
1152 subjects := gatherSubjectFilters(config.FilterSubject, config.FilterSubjects)
1153 if len(subjects) == 0 {
1154 mset.mu.Unlock()
1155 return nil, NewJSConsumerWQMultipleUnfilteredError()
1156 } else if !mset.partitionUnique(cName, subjects) {
1157 // Prior to v2.9.7, on a stream with WorkQueue policy, the servers
1158 // were not catching the error of having multiple consumers with
1159 // overlapping filter subjects depending on the scope, for instance
1160 // creating "foo.*.bar" and then "foo.>" was not detected, while
1161 // "foo.>" and then "foo.*.bar" would have been. Failing here
1162 // in recovery mode would leave the rejected consumer in a bad state,
1163 // so we will simply warn here, asking the user to remove this
1164 // consumer administratively. Otherwise, if this is the creation
1165 // of a new consumer, we will return the error.
1166 if isRecovering {
1167 s.Warnf("Consumer %q > %q has a filter subject that overlaps "+
1168 "with other consumers, which is not allowed for a stream "+
1169 "with WorkQueue policy, it should be administratively deleted",
1170 cfg.Name, cName)
1171 } else {
1172 // We have a partition but it is not unique amongst the others.
1173 mset.mu.Unlock()
1174 return nil, NewJSConsumerWQConsumerNotUniqueError()
1175 }
1176 }
1177 }
1178 }
1179
1180 // Set name, which will be durable name if set, otherwise we create one at random.
1181 o := &consumer{
1182 mset: mset,
1183 js: s.getJetStream(),
1184 acc: a,
1185 srv: s,
1186 client: s.createInternalJetStreamClient(),
1187 sysc: s.createInternalJetStreamClient(),
1188 cfg: *config,
1189 direct: config.Direct,
1190 sourcing: config.Sourcing,
1191 dsubj: config.DeliverSubject,
1192 outq: mset.outq,
1193 active: true,
1194 qch: make(chan struct{}),
1195 mqch: make(chan struct{}),
1196 uch: make(chan struct{}, 1),
1197 mch: make(chan struct{}, 1),
1198 sfreq: int32(sampleFreq),
1199 maxdc: uint64(max(config.MaxDeliver, 0)), // MaxDeliver is negative (-1) when infinite.
1200 maxp: config.MaxAckPending,
1201 retention: cfg.Retention,
1202 created: time.Now().UTC(),
1203 }
1204
1205 // Add created timestamp used for the store, must match that of the consumer assignment if it exists.
1206 if ca != nil {
1207 js.mu.RLock()
1208 o.created = ca.Created
1209 js.mu.RUnlock()
1210 }
1211
1212 // Bind internal client to the user account.
1213 o.client.registerWithAccount(a)
1214 // Bind to the system account.
1215 o.sysc.registerWithAccount(s.SystemAccount())
1216
1217 if isDurableConsumer(config) {
1218 if len(config.Durable) > JSMaxNameLen {
1219 mset.mu.Unlock()
1220 // Release the temporary consumer we built; it was never registered.
1221 _ = o.stop()
1222 return nil, NewJSConsumerNameTooLongError(JSMaxNameLen)
1223 }
1224 o.name = config.Durable
1225 } else if oname != _EMPTY_ {
1226 o.name = oname
1227 } else {
1228 if config.Name != _EMPTY_ {
1229 o.name = config.Name
1230 } else {
1231 // Legacy ephemeral auto-generated.
1232 for {
1233 o.name = createConsumerName()
1234 if _, ok := mset.consumers[o.name]; !ok {
1235 break
1236 }
1237 }
1238 config.Name = o.name
1239 }
1240 }
1241 // already under lock, mset.Name() would deadlock
1242 o.stream = cfg.Name
1243 o.ackEventT = JSMetricConsumerAckPre + "." + o.stream + "." + o.name
1244 o.nakEventT = JSAdvisoryConsumerMsgNakPre + "." + o.stream + "." + o.name
1245 o.deliveryExcEventT = JSAdvisoryConsumerMaxDeliveryExceedPre + "." + o.stream + "." + o.name
1246
1247 if !isValidAssetName(o.name) {
1248 mset.mu.Unlock()
1249 // Release the temporary consumer we built; it was never registered.
1250 _ = o.stop()
1251 return nil, NewJSConsumerBadDurableNameError()
1252 }
1253
1254 // Check if we already have this one registered.
1255 if eo, ok := mset.consumers[o.name]; ok {
1256 mset.mu.Unlock()
1257 if !o.isDurable() || !o.isPushMode() {
1258 _ = o.stop()
1259 return nil, NewJSConsumerNameExistError()
1260 }
1261 // If we are here we have already registered this durable. If it is still active that is an error.
1262 if eo.isActive() {
1263 _ = o.stop()
1264 return nil, NewJSConsumerExistingActiveError()
1265 }
1266 // Since we are here this means we have a potentially new durable so we should update here.
1267 // Check that configs are the same.
1268 if !configsEqualSansDelivery(o.cfg, eo.cfg) {
1269 _ = o.stop()
1270 return nil, NewJSConsumerReplacementWithDifferentNameError()
1271 }
1272 // Once we are here we have a replacement push-based durable.
1273 eo.updateDeliverSubject(o.cfg.DeliverSubject)
1274 // Release the temporary consumer we built; it was never registered.
1275 _ = o.stop()
1276 return eo, nil
1277 }
1278
1279 // Setup our storage if not a direct consumer.
1280 if !config.Direct {
1281 store, err := mset.store.ConsumerStore(o.name, o.created, config)
1282 if err != nil {
1283 mset.mu.Unlock()
1284 // Store creation failed, so just cleanup.
1285 _ = o.stop()
1286 return nil, NewJSConsumerStoreFailedError(err)
1287 }
1288 o.store = store
1289 }
1290
1291 for _, filter := range gatherSubjectFilters(o.cfg.FilterSubject, o.cfg.FilterSubjects) {
1292 sub := &subjectFilter{
1293 subject: filter,
1294 hasWildcard: subjectHasWildcard(filter),
1295 tokenizedSubject: tokenizeSubjectIntoSlice(nil, filter),
1296 }
1297 o.subjf = append(o.subjf, sub)
1298 }
1299
1300 // If we have multiple filter subjects, create a sublist which we will use
1301 // in calling store.LoadNextMsgMulti.
1302 if len(o.subjf) <= 1 {
1303 o.filters = nil
1304 } else {
1305 o.filters = gsl.NewSublist[struct{}]()
1306 for _, filter := range o.subjf {
1307 o.filters.Insert(filter.subject, struct{}{})
1308 }
1309 }
1310
1311 if o.store != nil && o.store.HasState() {
1312 // Restore our saved state.
1313 o.mu.Lock()
1314 o.readStoredState()
1315
1316 replicas := o.cfg.replicas(&mset.cfg)
1317
1318 // Starting sequence represents the next sequence to be delivered, so decrement it
1319 // since that's the minimum amount the stream should have as its last sequence.
1320 sseq := o.sseq
1321 if sseq > 0 {
1322 sseq--
1323 }
1324
1325 o.mu.Unlock()
1326
1327 // A stream observing data loss rolls back in its sequence. Check if we need to reconcile the consumer state
1328 // to ensure new messages aren't skipped.
1329 // Only performed for non-replicated consumers for now.
1330 if replicas == 1 && lseq < sseq && isRecovering {
1331 s.Warnf("JetStream consumer '%s > %s > %s' delivered sequence %d past last stream sequence of %d",
1332 o.acc.Name, o.stream, o.name, sseq, lseq)
1333
1334 o.mu.Lock()
1335 o.reconcileStateWithStream(lseq)
1336
1337 // Save the reconciled state
1338 state := &ConsumerState{
1339 Delivered: SequencePair{
1340 Stream: o.sseq - 1,
1341 Consumer: o.dseq - 1,
1342 },
1343 AckFloor: SequencePair{
1344 Stream: o.asflr,
1345 Consumer: o.adflr,
1346 },
1347 Pending: o.pending,
1348 Redelivered: o.rdc,
1349 }
1350 err := o.store.ForceUpdate(state)
1351 o.mu.Unlock()
1352 if err != nil {
1353 s.Errorf("JetStream consumer '%s > %s > %s' errored while updating state: %v", o.acc.Name, o.stream, o.name, err)
1354 mset.mu.Unlock()
1355 // Release the temporary consumer we built; it was never registered.
1356 _ = o.stop()
1357 return nil, NewJSConsumerStoreFailedError(err)
1358 }
1359 }
1360 } else if config.Direct || standalone {
1361 // Clustered non-direct consumers defer this to setLeader so the
1362 // expensive store scans don't block the meta apply goroutine.
1363 if err := o.selectStartingSeqNo(); err != nil {
1364 // Delete our store while holding the stream lock, so a concurrent create
1365 // for the same name cannot have registered and be sharing this on-disk
1366 // directory. Then release the rest of the consumer non-destructively.
1367 if o.store != nil {
1368 _ = o.store.Delete()
1369 o.store = nil
1370 }
1371 mset.mu.Unlock()
1372 _ = o.stop()
1373 return nil, err
1374 }
1375 }
1376
1377 // Create ackMsgs queue now that we have a consumer name
1378 o.ackMsgs = newIPQueue[*jsAckMsg](s, fmt.Sprintf("[ACC:%s] consumer '%s' on stream '%s' ackMsgs", accName, o.name, cfg.Name))
1379
1380 // Create our request waiting queue.
1381 if o.isPullMode() {
1382 o.waiting = newWaitQueue(config.MaxWaiting)
1383 o.nextMsgReqs = newIPQueue[*nextMsgReq](s, fmt.Sprintf("[ACC:%s] consumer '%s' on stream '%s' pull requests", accName, o.name, cfg.Name))
1384 }
1385
1386 // Set up the ack subscription for this consumer. Will use wildcard for all acks.
1387 // We will remember the template to generate replies with sequence numbers and use
1388 // that to scanf them back in.
1389 // Escape '%' in consumer and stream names, as `pre` is used as a template later
1390 // in consumer.ackReply(), resulting in erroneous formatting of the ack subject.
1391 mn := strings.ReplaceAll(cfg.Name, "%", "%%")
1392 on := strings.ReplaceAll(o.name, "%", "%%")
1393 domain := o.srv.getOpts().JetStreamDomain
1394 if domain == _EMPTY_ {
1395 domain = "_"
1396 }
1397 dn := strings.ReplaceAll(domain, "%", "%%")
1398 accHash := getHash(accName)
1399
1400 o.useV2Ack = s.getOpts().getFeatureFlag(FeatureFlagJsAckFormatV2)
1401
1402 // v1 format: $JS.(ACK|FC).<stream>.<consumer>.etc.
1403 o.fcPreOld = jsFlowControlPre
1404 o.fcSubjOld = fmt.Sprintf(jsFlowControl, cfg.Name, o.name)
1405 preOld := fmt.Sprintf(jsAckT, mn, on)
1406 o.ackReplyOldT = fmt.Sprintf("%s.%%d.%%d.%%d.%%d.%%d", preOld)
1407 o.ackSubjOld = fmt.Sprintf(jsAckT+".*.*.*.*.*", cfg.Name, o.name)
1408
1409 // v2 format: $JS.(ACK|FC).<domain>.<accHash>.<stream>.<consumer>.etc.
1410 o.fcPre = fmt.Sprintf("%s%s.%s.", jsFlowControlPre, domain, accHash)
1411 o.fcSubj = fmt.Sprintf(jsFlowControlV2, domain, accHash, cfg.Name, o.name)
1412 pre := fmt.Sprintf(jsAckTv2, dn, accHash, mn, on)
1413 o.ackReplyT = fmt.Sprintf("%s.%%d.%%d.%%d.%%d.%%d", pre)
1414 // Subscribe on this ack subject for v2, we require 11 tokens, but allow for more tokens/extension.
1415 o.ackSubj = fmt.Sprintf(jsAckTv2+".*.*.*.*.>", domain, accHash, cfg.Name, o.name)
1416
1417 o.nextMsgSubj = fmt.Sprintf(JSApiRequestNextT, cfg.Name, o.name)
1418 o.resetSubj = fmt.Sprintf(JSApiConsumerResetT, cfg.Name, o.name)
1419
1420 // Check/update the inactive threshold
1421 o.updateInactiveThreshold(&o.cfg)
1422
1423 if o.isPushMode() {
1424 // Check if we are running only 1 replica and that the delivery subject has interest.
1425 // Check in place here for interest. Will setup properly in setLeader.
1426 if config.replicas(&cfg) == 1 {
1427 interest := o.acc.sl.HasInterest(o.cfg.DeliverSubject)
1428 if !o.hasDeliveryInterest(interest) {
1429 // Let the interest come to us eventually, but setup delete timer.
1430 o.updateDeliveryInterest(false)
1431 }
1432 }
1433 }
1434
1435 // Set our ca.
1436 if ca != nil {
1437 o.setConsumerAssignment(ca)
1438 }
1439
1440 // Check if we have a rate limit set.
1441 if config.RateLimit != 0 {
1442 o.setRateLimit(config.RateLimit)
1443 }
1444
1445 mset.setConsumer(o)
1446 mset.mu.Unlock()
1447
1448 if config.Sourcing && standalone {
1449 o.resetStartingSeq(0, _EMPTY_, false)
1450 }
1451 if config.Direct || standalone {
1452 o.setLeader(true, 0)
1453 }
1454
1455 // This is always true in single server mode.
1456 if o.IsLeader() {
1457 // Send advisory.
1458 var suppress bool
1459 if !s.standAloneMode() && ca == nil {
1460 suppress = true
1461 } else if ca != nil {
1462 suppress = ca.hasResponded()
1463 }
1464 if !suppress {
1465 o.sendCreateAdvisory()
1466 }
1467 }
1468
1469 return o, nil
1470 }
1471
1472 // Updates the consumer `dthresh` delete timer duration and set
1473 // cfg.InactiveThreshold to JsDeleteWaitTimeDefault for ephemerals
1474 // if not explicitly already specified by the user.
1475 // Lock should be held.
1476 func (o *consumer) updateInactiveThreshold(cfg *ConsumerConfig) {
1477 // Ephemerals will always have inactive thresholds.
1478 if !o.isDurable() && cfg.InactiveThreshold <= 0 {
1479 // Add in 1 sec of jitter above and beyond the default of 5s.
1480 o.dthresh = JsDeleteWaitTimeDefault + 100*time.Millisecond + time.Duration(rand.Int63n(900))*time.Millisecond
1481 // Only stamp config with default sans jitter.
1482 cfg.InactiveThreshold = JsDeleteWaitTimeDefault
1483 } else if cfg.InactiveThreshold > 0 {
1484 // Add in up to 1 sec of jitter if pull mode.
1485 if o.isPullMode() {
1486 o.dthresh = cfg.InactiveThreshold + 100*time.Millisecond + time.Duration(rand.Int63n(900))*time.Millisecond
1487 } else {
1488 o.dthresh = cfg.InactiveThreshold
1489 }
1490 } else if cfg.InactiveThreshold <= 0 {
1491 // We accept InactiveThreshold be set to 0 (for durables)
1492 o.dthresh = 0
1493 }
1494 }
1495
1496 // Updates the paused state. If we are the leader and the pause deadline
1497 // hasn't passed yet then we will start a timer to kick the consumer once
1498 // that deadline is reached. Lock should be held.
1499 func (o *consumer) updatePauseState(cfg *ConsumerConfig) {
1500 if o.uptmr != nil {
1501 stopAndClearTimer(&o.uptmr)
1502 }
1503 if !o.isLeader() {
1504 // Only the leader will run the timer as only the leader will run
1505 // loopAndGatherMsgs.
1506 return
1507 }
1508 if cfg.PauseUntil == nil || cfg.PauseUntil.IsZero() || cfg.PauseUntil.Before(time.Now()) {
1509 // Either the PauseUntil is unset (is effectively zero) or the
1510 // deadline has already passed, in which case there is nothing
1511 // to do.
1512 return
1513 }
1514 o.uptmr = time.AfterFunc(time.Until(*cfg.PauseUntil), func() {
1515 o.mu.Lock()
1516 defer o.mu.Unlock()
1517
1518 stopAndClearTimer(&o.uptmr)
1519 o.sendPauseAdvisoryLocked(&o.cfg)
1520 o.signalNewMessages()
1521 })
1522 }
1523
1524 func (o *consumer) consumerAssignment() *consumerAssignment {
1525 o.mu.RLock()
1526 defer o.mu.RUnlock()
1527 return o.ca
1528 }
1529
1530 func (o *consumer) setConsumerAssignment(ca *consumerAssignment) {
1531 o.mu.Lock()
1532 defer o.mu.Unlock()
1533
1534 o.ca = ca
1535 if ca == nil {
1536 return
1537 }
1538 // Set our node.
1539 o.node = ca.Group.node
1540
1541 // Trigger update chan.
1542 select {
1543 case o.uch <- struct{}{}:
1544 default:
1545 }
1546 }
1547
1548 func (o *consumer) monitorQuitC() <-chan struct{} {
1549 if o == nil {
1550 return nil
1551 }
1552 o.mu.Lock()
1553 defer o.mu.Unlock()
1554 // Recreate if a prior monitor routine was stopped.
1555 if o.mqch == nil {
1556 o.mqch = make(chan struct{})
1557 }
1558 return o.mqch
1559 }
1560
1561 // signalMonitorQuit signals to exit the monitor loop. If there's no Raft node,
1562 // this will be the only way to stop the monitor goroutine.
1563 func (o *consumer) signalMonitorQuit() {
1564 o.mu.Lock()
1565 defer o.mu.Unlock()
1566 if o.mqch != nil {
1567 close(o.mqch)
1568 o.mqch = nil
1569 }
1570 }
1571
1572 func (o *consumer) updateC() <-chan struct{} {
1573 o.mu.RLock()
1574 defer o.mu.RUnlock()
1575 return o.uch
1576 }
1577
1578 // checkQueueInterest will check on our interest's queue group status.
1579 // Lock should be held.
1580 func (o *consumer) checkQueueInterest() {
1581 if !o.active || o.cfg.DeliverSubject == _EMPTY_ {
1582 return
1583 }
1584 subj := o.dsubj
1585 if subj == _EMPTY_ {
1586 subj = o.cfg.DeliverSubject
1587 }
1588
1589 if rr := o.acc.sl.Match(subj); len(rr.qsubs) > 0 {
1590 // Just grab first
1591 if qsubs := rr.qsubs[0]; len(qsubs) > 0 {
1592 if sub := rr.qsubs[0][0]; len(sub.queue) > 0 {
1593 o.qgroup = string(sub.queue)
1594 }
1595 }
1596 }
1597 }
1598
1599 // clears our node if we have one. When we scale down to 1.
1600 func (o *consumer) clearNode() {
1601 o.mu.Lock()
1602 defer o.mu.Unlock()
1603 if o.node != nil {
1604 o.node.Delete()
1605 o.node = nil
1606 }
1607 }
1608
1609 // IsLeader will return if we are the current leader.
1610 func (o *consumer) IsLeader() bool {
1611 return o.isLeader()
1612 }
1613
1614 // Lock should be held.
1615 func (o *consumer) isLeader() bool {
1616 return o.leader.Load()
1617 }
1618
1619 func (o *consumer) setLeader(isLeader bool, term uint64) error {
1620 o.mu.Lock()
1621 mset, closed := o.mset, o.closed
1622 wasLeader := o.leader.Swap(isLeader)
1623
1624 // For clustered new consumers, starting seq selection was deferred from
1625 // addConsumerWithAssignment so the scan wouldn't block the meta apply
1626 // goroutine, run it here on leader-elect instead.
1627 needsSelect := isLeader && !wasLeader && o.dseq == 0 && (o.store == nil || !o.store.HasState())
1628
1629 // We can skip the teardown if we were leader before and are still the leader now.
1630 // But only at term 1, since that means scale up from or down to an unreplicated config.
1631 // R1 assets have no raft node and use the coerced term 1.
1632 if term < 1 {
1633 term = 1
1634 }
1635 skipTeardown := wasLeader && isLeader && term == 1
1636 o.term = term
1637
1638 if skipTeardown {
1639 movingToClustered := o.node != nil && o.pch == nil
1640 movingToNonClustered := o.node == nil && o.pch != nil
1641
1642 // If we detect we are scaling up, make sure to create clustered routines and channels.
1643 if movingToClustered {
1644 // We are moving from R1 to clustered.
1645 o.pch = make(chan struct{}, 1)
1646 go o.loopAndForwardProposals(o.node, o.qch, o.pch, term)
1647 if o.phead != nil {
1648 select {
1649 case o.pch <- struct{}{}:
1650 default:
1651 }
1652 }
1653 } else if movingToNonClustered {
1654 // We are moving from clustered to non-clustered now.
1655 // Set pch to nil so if we scale back up we will recreate the loopAndForward from above.
1656 pch := o.pch
1657 o.pch = nil
1658 select {
1659 case pch <- struct{}{}:
1660 default:
1661 }
1662 }
1663 o.mu.Unlock()
1664 return nil
1665 }
1666
1667 // Shutdown the go routines and the subscriptions.
1668 if o.qch != nil {
1669 close(o.qch)
1670 o.qch = nil
1671 }
1672 // Stop any inactivity timers. Should only be running on leaders.
1673 stopAndClearTimer(&o.dtmr)
1674 // Stop any unpause timers. Should only be running on leaders.
1675 stopAndClearTimer(&o.uptmr)
1676 // Make sure to clear out any re-deliver queues
1677 o.stopAndClearPtmr()
1678 o.rdc = nil
1679 o.rdq = nil
1680 o.rdqi.Empty()
1681 o.pending = nil
1682 o.rsm = nil
1683 o.resetPendingDeliveries()
1684 // Reset num pending, these are only authoritative on the leader.
1685 o.npc, o.npf = 0, 0
1686 // Reset flow control accounting.
1687 o.pbytes, o.fcsz, o.fcid = 0, 0, _EMPTY_
1688 // ok if they are nil, we protect inside unsubscribe()
1689 o.unsubscribe(o.ackSubOld)
1690 o.unsubscribe(o.ackSub)
1691 o.unsubscribe(o.reqSub)
1692 o.unsubscribe(o.resetSub)
1693 o.unsubscribe(o.fcSubOld)
1694 o.unsubscribe(o.fcSub)
1695 o.ackSubOld, o.ackSub, o.reqSub, o.resetSub, o.fcSubOld, o.fcSub = nil, nil, nil, nil, nil, nil
1696 if o.infoSub != nil {
1697 o.srv.sysUnsubscribe(o.infoSub)
1698 o.infoSub = nil
1699 }
1700 // Reset waiting if we are in pull mode.
1701 if o.isPullMode() {
1702 o.waiting = newWaitQueue(o.cfg.MaxWaiting)
1703 o.nextMsgReqs.drain()
1704 } else if o.srv.gateway.enabled {
1705 stopAndClearTimer(&o.gwdtmr)
1706 }
1707 o.unassignPinId()
1708
1709 // Make sure to drain queued up acks.
1710 o.ackMsgs.drain()
1711 // Reset amount of acks that need to be processed.
1712 atomic.StoreInt64(&o.awl, 0)
1713 // Also remove any pending replies since we should not be the one to respond at this point.
1714 o.replies = nil
1715
1716 // Set pch to nil, we will recreate the loopAndForwardProposals for the new term.
1717 if pch := o.pch; pch != nil {
1718 o.pch = nil
1719 select {
1720 case pch <- struct{}{}:
1721 default:
1722 }
1723 }
1724 // Clear proposals, none are valid anymore.
1725 o.phead, o.ptail = nil, nil
1726 o.mu.Unlock()
1727
1728 // If we are here we have a change in leader status.
1729 if isLeader {
1730 if closed || mset == nil {
1731 return nil
1732 }
1733
1734 if needsSelect {
1735 o.mu.Lock()
1736 if err := o.selectStartingSeqNo(); err != nil {
1737 o.srv.Errorf("JetStream consumer '%s > %s > %s' select starting seq failed: %v",
1738 o.acc.Name, o.stream, o.name, err)
1739 o.leader.Store(false)
1740 node := o.node
1741 o.mu.Unlock()
1742 if node != nil {
1743 _ = node.StepDown()
1744 }
1745 return err
1746 }
1747 o.mu.Unlock()
1748 }
1749
1750 mset.mu.RLock()
1751 s, jsa, stream := mset.srv, mset.jsa, mset.getCfgName()
1752 mset.mu.RUnlock()
1753
1754 o.mu.Lock()
1755 o.rdq = nil
1756 o.rdqi.Empty()
1757
1758 // Restore our saved state.
1759 // During non-leader status we just update our underlying store when not clustered.
1760 // If clustered we need to propose our initial (possibly skipped ahead) o.sseq to the group.
1761 if o.node == nil || o.dseq > 1 || (o.store != nil && o.store.HasState()) {
1762 o.readStoredState()
1763 } else if o.node != nil && o.sseq >= 1 {
1764 o.updateSkipped(o.sseq)
1765 }
1766
1767 // Setup initial num pending.
1768 o.streamNumPending()
1769
1770 // Cleanup lss when we take over in clustered mode.
1771 if o.hasSkipListPending() && o.sseq >= o.lss.resume {
1772 o.lss = nil
1773 }
1774
1775 // Do info sub.
1776 if o.infoSub == nil && jsa != nil {
1777 isubj := fmt.Sprintf(clusterConsumerInfoT, jsa.acc(), stream, o.name)
1778 // Note below the way we subscribe here is so that we can send requests to ourselves.
1779 o.infoSub, _ = s.systemSubscribe(isubj, _EMPTY_, false, o.sysc, o.handleClusterConsumerInfoRequest)
1780 }
1781
1782 var err error
1783 if o.cfg.AckPolicy != AckNone && o.cfg.AckPolicy != AckFlowControl {
1784 if o.ackSubOld, err = o.subscribeInternal(o.ackSubjOld, o.pushAck); err != nil {
1785 o.mu.Unlock()
1786 return nil
1787 }
1788 if o.ackSub, err = o.subscribeInternal(o.ackSubj, o.pushAck); err != nil {
1789 o.mu.Unlock()
1790 return nil
1791 }
1792 }
1793
1794 // Setup the internal sub for next message requests regardless.
1795 // Will error if wrong mode to provide feedback to users.
1796 if o.reqSub, err = o.subscribeInternal(o.nextMsgSubj, o.processNextMsgReq); err != nil {
1797 o.mu.Unlock()
1798 return nil
1799 }
1800 if o.resetSub, err = o.subscribeInternal(o.resetSubj, o.processResetReq); err != nil {
1801 o.mu.Unlock()
1802 return nil
1803 }
1804
1805 // Check on flow control settings.
1806 if o.cfg.FlowControl {
1807 o.setMaxPendingBytes(JsFlowControlMaxPending)
1808 if o.fcSubOld, err = o.subscribeInternal(o.fcSubjOld, o.processFlowControl); err != nil {
1809 o.mu.Unlock()
1810 return nil
1811 }
1812 if o.fcSub, err = o.subscribeInternal(o.fcSubj, o.processFlowControl); err != nil {
1813 o.mu.Unlock()
1814 return nil
1815 }
1816 }
1817
1818 // If push mode, register for notifications on interest.
1819 if o.isPushMode() {
1820 o.inch = make(chan bool, 8)
1821 o.acc.sl.registerNotification(o.cfg.DeliverSubject, o.cfg.DeliverGroup, o.inch)
1822 if o.active = <-o.inch; o.active {
1823 o.checkQueueInterest()
1824 }
1825
1826 // Check gateways in case they are enabled.
1827 if s.gateway.enabled {
1828 if !o.active {
1829 o.active = s.hasGatewayInterest(o.acc.Name, o.cfg.DeliverSubject)
1830 }
1831 stopAndClearTimer(&o.gwdtmr)
1832 o.gwdtmr = time.AfterFunc(time.Second, func() { o.watchGWinterest() })
1833 }
1834 }
1835
1836 if o.dthresh > 0 && (o.isPullMode() || !o.active) {
1837 // Pull consumer. We run the dtmr all the time for this one.
1838 stopAndClearTimer(&o.dtmr)
1839 o.dtmr = time.AfterFunc(o.dthresh, o.deleteNotActive)
1840 }
1841
1842 // Update the consumer pause tracking.
1843 o.updatePauseState(&o.cfg)
1844
1845 // If we are not in ReplayInstant mode mark us as in replay state until resolved.
1846 if o.cfg.ReplayPolicy != ReplayInstant {
1847 o.replay = true
1848 }
1849
1850 // Recreate quit channel.
1851 o.qch = make(chan struct{})
1852 qch := o.qch
1853 node := o.node
1854 var pch chan struct{}
1855 if node != nil && o.pch == nil {
1856 o.pch = make(chan struct{}, 1)
1857 pch = o.pch
1858 }
1859 pullMode := o.isPullMode()
1860 o.mu.Unlock()
1861
1862 // Check if there are any pending we might need to clean up etc.
1863 o.checkPending()
1864
1865 // Snapshot initial info.
1866 o.infoWithSnap(true)
1867
1868 // These are the labels we will use to annotate our goroutines.
1869 labels := pprofLabels{
1870 "type": "consumer",
1871 "account": mset.accName(),
1872 "stream": mset.name(),
1873 "consumer": o.name,
1874 }
1875
1876 // Now start up Go routine to deliver msgs.
1877 go func() {
1878 setGoRoutineLabels(labels)
1879 o.loopAndGatherMsgs(qch)
1880 }()
1881
1882 // Now start up Go routine to process acks.
1883 go func() {
1884 setGoRoutineLabels(labels)
1885 o.processInboundAcks(qch)
1886 }()
1887
1888 if pullMode {
1889 // Now start up Go routine to process inbound next message requests.
1890 go func() {
1891 setGoRoutineLabels(labels)
1892 o.processInboundNextMsgReqs(qch)
1893 }()
1894 }
1895
1896 // If we are R>1 spin up our proposal loop.
1897 if node != nil && pch != nil {
1898 // Determine if we can send pending requests info to the group.
1899 // They must be on server versions >= 2.7.1
1900 o.checkAndSetPendingRequestsOk()
1901 o.checkPendingRequests()
1902 go func() {
1903 setGoRoutineLabels(labels)
1904 o.loopAndForwardProposals(node, qch, pch, term)
1905 }()
1906 }
1907 }
1908 return nil
1909 }
1910
1911 // This is coming on the wire so do not block here.
1912 func (o *consumer) handleClusterConsumerInfoRequest(sub *subscription, c *client, _ *Account, subject, reply string, msg []byte) {
1913 go o.infoWithSnapAndReply(false, reply)
1914 }
1915
1916 // Lock should be held.
1917 func (o *consumer) subscribeInternal(subject string, cb msgHandler) (*subscription, error) {
1918 c := o.client
1919 if c == nil {
1920 return nil, fmt.Errorf("invalid consumer")
1921 }
1922 if !c.srv.EventsEnabled() {
1923 return nil, ErrNoSysAccount
1924 }
1925 if cb == nil {
1926 return nil, fmt.Errorf("undefined message handler")
1927 }
1928
1929 o.sid++
1930
1931 // Now create the subscription
1932 return c.processSub([]byte(subject), nil, []byte(strconv.Itoa(o.sid)), cb, false)
1933 }
1934
1935 // Unsubscribe from our subscription.
1936 // Lock should be held.
1937 func (o *consumer) unsubscribe(sub *subscription) {
1938 if sub == nil || o.client == nil {
1939 return
1940 }
1941 o.client.processUnsub(sub.sid)
1942 }
1943
1944 // We need to make sure we protect access to the outq.
1945 // Do all advisory sends here.
1946 func (o *consumer) sendAdvisory(subject string, e any) {
1947 if o.acc == nil {
1948 return
1949 }
1950
1951 // If there is no one listening for this advisory then save ourselves the effort
1952 // and don't bother encoding the JSON or sending it.
1953 if sl := o.acc.sl; (sl != nil && !sl.HasInterest(subject)) && !o.srv.hasGatewayInterest(o.acc.Name, subject) {
1954 return
1955 }
1956
1957 j, err := json.Marshal(e)
1958 if err != nil {
1959 return
1960 }
1961
1962 o.outq.sendMsg(subject, j)
1963 }
1964
1965 func (o *consumer) sendDeleteAdvisoryLocked() {
1966 e := JSConsumerActionAdvisory{
1967 TypedEvent: TypedEvent{
1968 Type: JSConsumerActionAdvisoryType,
1969 ID: nuid.Next(),
1970 Time: time.Now().UTC(),
1971 },
1972 Stream: o.stream,
1973 Consumer: o.name,
1974 Action: DeleteEvent,
1975 Domain: o.srv.getOpts().JetStreamDomain,
1976 }
1977
1978 subj := JSAdvisoryConsumerDeletedPre + "." + o.stream + "." + o.name
1979 o.sendAdvisory(subj, e)
1980 }
1981
1982 func (o *consumer) sendPinnedAdvisoryLocked(group string) {
1983 e := JSConsumerGroupPinnedAdvisory{
1984 TypedEvent: TypedEvent{
1985 Type: JSConsumerGroupPinnedAdvisoryType,
1986 ID: nuid.Next(),
1987 Time: time.Now().UTC(),
1988 },
1989 Account: o.acc.Name,
1990 Stream: o.stream,
1991 Consumer: o.name,
1992 Domain: o.srv.getOpts().JetStreamDomain,
1993 PinnedClientId: o.currentPinId,
1994 Group: group,
1995 }
1996
1997 subj := JSAdvisoryConsumerPinnedPre + "." + o.stream + "." + o.name
1998 o.sendAdvisory(subj, e)
1999
2000 }
2001 func (o *consumer) sendUnpinnedAdvisoryLocked(group string, reason string) {
2002 e := JSConsumerGroupUnpinnedAdvisory{
2003 TypedEvent: TypedEvent{
2004 Type: JSConsumerGroupUnpinnedAdvisoryType,
2005 ID: nuid.Next(),
2006 Time: time.Now().UTC(),
2007 },
2008 Account: o.acc.Name,
2009 Stream: o.stream,
2010 Consumer: o.name,
2011 Domain: o.srv.getOpts().JetStreamDomain,
2012 Group: group,
2013 Reason: reason,
2014 }
2015
2016 subj := JSAdvisoryConsumerUnpinnedPre + "." + o.stream + "." + o.name
2017 o.sendAdvisory(subj, e)
2018
2019 }
2020
2021 func (o *consumer) sendCreateAdvisory() {
2022 o.mu.Lock()
2023 defer o.mu.Unlock()
2024
2025 e := JSConsumerActionAdvisory{
2026 TypedEvent: TypedEvent{
2027 Type: JSConsumerActionAdvisoryType,
2028 ID: nuid.Next(),
2029 Time: time.Now().UTC(),
2030 },
2031 Stream: o.stream,
2032 Consumer: o.name,
2033 Action: CreateEvent,
2034 Domain: o.srv.getOpts().JetStreamDomain,
2035 }
2036
2037 subj := JSAdvisoryConsumerCreatedPre + "." + o.stream + "." + o.name
2038 o.sendAdvisory(subj, e)
2039 }
2040
2041 func (o *consumer) sendPauseAdvisoryLocked(cfg *ConsumerConfig) {
2042 e := JSConsumerPauseAdvisory{
2043 TypedEvent: TypedEvent{
2044 Type: JSConsumerPauseAdvisoryType,
2045 ID: nuid.Next(),
2046 Time: time.Now().UTC(),
2047 },
2048 Stream: o.stream,
2049 Consumer: o.name,
2050 Domain: o.srv.getOpts().JetStreamDomain,
2051 }
2052
2053 if cfg.PauseUntil != nil {
2054 e.PauseUntil = *cfg.PauseUntil
2055 e.Paused = time.Now().Before(e.PauseUntil)
2056 }
2057
2058 subj := JSAdvisoryConsumerPausePre + "." + o.stream + "." + o.name
2059 o.sendAdvisory(subj, e)
2060 }
2061
2062 // Created returns created time.
2063 func (o *consumer) createdTime() time.Time {
2064 o.mu.Lock()
2065 created := o.created
2066 o.mu.Unlock()
2067 return created
2068 }
2069
2070 // Internal to allow creation time to be restored.
2071 func (o *consumer) setCreatedTime(created time.Time) {
2072 o.mu.Lock()
2073 o.created = created
2074 o.mu.Unlock()
2075 }
2076
2077 // This will check for extended interest in a subject. If we have local interest we just return
2078 // that, but in the absence of local interest and presence of gateways or service imports we need
2079 // to check those as well.
2080 func (o *consumer) hasDeliveryInterest(localInterest bool) bool {
2081 o.mu.RLock()
2082 mset := o.mset
2083 if mset == nil {
2084 o.mu.RUnlock()
2085 return false
2086 }
2087 acc := o.acc
2088 deliver := o.cfg.DeliverSubject
2089 o.mu.RUnlock()
2090
2091 if localInterest {
2092 return true
2093 }
2094
2095 // If we are here check gateways.
2096 if s := acc.srv; s != nil && s.hasGatewayInterest(acc.Name, deliver) {
2097 return true
2098 }
2099 return false
2100 }
2101
2102 func (s *Server) hasGatewayInterest(account, subject string) bool {
2103 gw := s.gateway
2104 if !gw.enabled {
2105 return false
2106 }
2107 gw.RLock()
2108 defer gw.RUnlock()
2109 for _, gwc := range gw.outo {
2110 psi, qr := gwc.gatewayInterest(account, stringToBytes(subject))
2111 if psi || qr != nil {
2112 return true
2113 }
2114 }
2115 return false
2116 }
2117
2118 // This processes an update to the local interest for a deliver subject.
2119 func (o *consumer) updateDeliveryInterest(localInterest bool) bool {
2120 interest := o.hasDeliveryInterest(localInterest)
2121
2122 o.mu.Lock()
2123 defer o.mu.Unlock()
2124
2125 mset := o.mset
2126 if mset == nil || o.isPullMode() {
2127 return false
2128 }
2129
2130 if interest && !o.active {
2131 o.signalNewMessages()
2132 }
2133 // Update active status, if not active clear any queue group we captured.
2134 if o.active = interest; !o.active {
2135 o.qgroup = _EMPTY_
2136 } else {
2137 o.checkQueueInterest()
2138 }
2139
2140 // If the delete timer has already been set do not clear here and return.
2141 // Note that durable can now have an inactive threshold, so don't check
2142 // for durable status, instead check for dthresh > 0.
2143 if o.dtmr != nil && o.dthresh > 0 && !interest {
2144 return true
2145 }
2146
2147 // Stop and clear the delete timer always.
2148 stopAndClearTimer(&o.dtmr)
2149
2150 // If we do not have interest anymore and have a delete threshold set, then set
2151 // a timer to delete us. We wait for a bit in case of server reconnect.
2152 if !interest && o.dthresh > 0 {
2153 o.dtmr = time.AfterFunc(o.dthresh, o.deleteNotActive)
2154 return true
2155 }
2156 return false
2157 }
2158
2159 const (
2160 defaultConsumerNotActiveStartInterval = 30 * time.Second
2161 defaultConsumerNotActiveMaxInterval = 5 * time.Minute
2162 )
2163
2164 var (
2165 consumerNotActiveStartInterval = defaultConsumerNotActiveStartInterval
2166 consumerNotActiveMaxInterval = defaultConsumerNotActiveMaxInterval
2167 )
2168
2169 // deleteNotActive must only be called from time.AfterFunc or in its own
2170 // goroutine, as it can block on clean-up.
2171 func (o *consumer) deleteNotActive() {
2172 // Take a copy of these when the goroutine starts, mostly it avoids a
2173 // race condition with tests that modify these consts, such as
2174 // TestJetStreamClusterGhostEphemeralsAfterRestart.
2175 cnaMax := consumerNotActiveMaxInterval
2176 cnaStart := consumerNotActiveStartInterval
2177
2178 o.mu.Lock()
2179 if o.mset == nil || !o.isLeader() {
2180 o.mu.Unlock()
2181 return
2182 }
2183 // Push mode just look at active.
2184 if o.isPushMode() {
2185 // If we are active simply return.
2186 if o.active {
2187 o.mu.Unlock()
2188 return
2189 }
2190 } else {
2191 // Pull mode.
2192 elapsed := time.Since(o.waiting.last)
2193 if elapsed < o.dthresh {
2194 // These need to keep firing so reset but use delta.
2195 if o.dtmr != nil {
2196 o.dtmr.Reset(o.dthresh - elapsed)
2197 } else {
2198 o.dtmr = time.AfterFunc(o.dthresh-elapsed, o.deleteNotActive)
2199 }
2200 o.mu.Unlock()
2201 return
2202 }
2203 // Check if we still have valid requests waiting.
2204 if o.checkWaitingForInterest() {
2205 if o.dtmr != nil {
2206 o.dtmr.Reset(o.dthresh)
2207 } else {
2208 o.dtmr = time.AfterFunc(o.dthresh, o.deleteNotActive)
2209 }
2210 o.mu.Unlock()
2211 return
2212 }
2213
2214 // We now know we have no waiting requests, and our last request was long ago.
2215 // However, based on AckWait the consumer could still be actively processing,
2216 // even if we haven't been informed if there were no acks in the meantime.
2217 // We must wait for the message that expires last and start counting down the
2218 // inactive threshold from there.
2219 now := time.Now().UnixNano()
2220 l := len(o.cfg.BackOff)
2221 var delay time.Duration
2222 var ackWait time.Duration
2223 for seq, p := range o.pending {
2224 if l == 0 {
2225 ackWait = o.ackWait(0)
2226 } else {
2227 bi := int(o.rdc[seq])
2228 if bi < 0 {
2229 bi = 0
2230 } else if bi >= l {
2231 bi = l - 1
2232 }
2233 ackWait = o.ackWait(o.cfg.BackOff[bi])
2234 }
2235 if ts := p.Timestamp + ackWait.Nanoseconds() + o.dthresh.Nanoseconds(); ts > now {
2236 delay = max(delay, time.Duration(ts-now))
2237 }
2238 }
2239 // We'll wait for the latest time we expect an ack, plus the inactive threshold.
2240 // Acknowledging a message will reset this back down to just the inactive threshold.
2241 if delay > 0 {
2242 if o.dtmr != nil {
2243 o.dtmr.Reset(delay)
2244 } else {
2245 o.dtmr = time.AfterFunc(delay, o.deleteNotActive)
2246 }
2247 o.mu.Unlock()
2248 return
2249 }
2250 }
2251
2252 s, js := o.mset.srv, o.srv.js.Load()
2253 acc, stream, name, isDirect := o.acc.Name, o.stream, o.name, o.direct
2254 // Capture our own view of the assignment while we still hold the lock.
2255 ca := o.ca
2256 var qch, cqch chan struct{}
2257 if o.srv != nil {
2258 qch = o.srv.quitCh
2259 }
2260 oqch := o.qch
2261 o.mu.Unlock()
2262 if js != nil {
2263 cqch = js.clusterQuitC()
2264 }
2265
2266 // Useful for pprof.
2267 setGoRoutineLabels(pprofLabels{
2268 "account": acc,
2269 "stream": stream,
2270 "consumer": name,
2271 })
2272
2273 // If we are clustered, check if we still have this consumer assigned.
2274 // If we do forward a proposal to delete ourselves to the metacontroller leader.
2275 if !isDirect && s.JetStreamIsClustered() {
2276 js.mu.RLock()
2277 var (
2278 meta RaftNode
2279 removeEntry []byte
2280 )
2281 nca := js.consumerAssignment(acc, stream, name)
2282 // Only propose the delete if the meta-layer assignment still refers to
2283 // the consumer we captured, otherwise we'd be racing a recreated
2284 // consumer with the same name.
2285 if cc := js.cluster; cc != nil && ca != nil && ca.sameIdentity(nca) {
2286 meta = cc.meta
2287 cca := ca.clone()
2288 cca.Reply = _EMPTY_
2289 removeEntry = encodeDeleteConsumerAssignment(cca)
2290 meta.ForwardProposal(removeEntry)
2291 }
2292 js.mu.RUnlock()
2293
2294 if ca != nil && meta != nil {
2295 // Check to make sure we went away.
2296 // Don't think this needs to be a monitored go routine.
2297 jitter := time.Duration(rand.Int63n(int64(cnaStart)))
2298 interval := cnaStart + jitter
2299 ticker := time.NewTicker(interval)
2300 defer ticker.Stop()
2301 for {
2302 select {
2303 case <-ticker.C:
2304 case <-qch:
2305 return
2306 case <-cqch:
2307 return
2308 case <-oqch:
2309 // The consumer has stopped already, likely by an earlier delete proposal being applied.
2310 return
2311 }
2312 js.mu.RLock()
2313 if js.shuttingDown {
2314 js.mu.RUnlock()
2315 return
2316 }
2317 nca = js.consumerAssignment(acc, stream, name)
2318 // Make sure this is the same consumer assignment, and not a new consumer with the same name.
2319 match := ca.sameIdentity(nca)
2320 js.mu.RUnlock()
2321 if match {
2322 s.Warnf("Consumer assignment for '%s > %s > %s' not cleaned up, retrying", acc, stream, name)
2323 meta.ForwardProposal(removeEntry)
2324 if interval < cnaMax {
2325 interval *= 2
2326 ticker.Reset(interval)
2327 }
2328 continue
2329 }
2330 // We saw that consumer has been removed, all done.
2331 return
2332 }
2333 }
2334 } else {
2335 // Otherwise, we can delete locally. Either a consumer that's not tracked
2336 // by the meta layer (direct), or a standalone non-clustered server.
2337 o.delete()
2338 }
2339 }
2340
2341 func (o *consumer) watchGWinterest() {
2342 pa := o.isActive()
2343 // If there is no local interest...
2344 if o.hasNoLocalInterest() {
2345 o.updateDeliveryInterest(false)
2346 if !pa && o.isActive() {
2347 o.signalNewMessages()
2348 }
2349 }
2350
2351 // We want this to always be running so we can also pick up on interest returning.
2352 o.mu.Lock()
2353 if o.gwdtmr != nil {
2354 o.gwdtmr.Reset(time.Second)
2355 } else {
2356 stopAndClearTimer(&o.gwdtmr)
2357 o.gwdtmr = time.AfterFunc(time.Second, func() { o.watchGWinterest() })
2358 }
2359 o.mu.Unlock()
2360 }
2361
2362 // Config returns the consumer's configuration.
2363 func (o *consumer) config() ConsumerConfig {
2364 o.mu.Lock()
2365 defer o.mu.Unlock()
2366 return o.cfg
2367 }
2368
2369 // Check if we have hit max deliveries. If so do notification and cleanup.
2370 // Return whether or not the max was hit.
2371 // Lock should be held.
2372 func (o *consumer) hasMaxDeliveries(seq uint64) bool {
2373 if o.maxdc == 0 {
2374 return false
2375 }
2376 if dc := o.deliveryCount(seq); dc >= o.maxdc {
2377 // We have hit our max deliveries for this sequence.
2378 // Only send the advisory once.
2379 if dc == o.maxdc {
2380 o.notifyDeliveryExceeded(seq, dc)
2381 }
2382 // Determine if we signal to start flow of messages again.
2383 if o.maxp > 0 && len(o.pending) >= o.maxp {
2384 o.signalNewMessages()
2385 }
2386 // Make sure to remove from pending.
2387 if p, ok := o.pending[seq]; ok && p != nil {
2388 delete(o.pending, seq)
2389 // Increment by one, since the delivery count hasn't been increased above.
2390 o.updateDelivered(p.Sequence, seq, dc+1, p.Timestamp)
2391 o.moveAckFloor(p.Sequence, seq)
2392 }
2393 // Ensure redelivered state is set, if not already.
2394 if o.rdc == nil {
2395 o.rdc = make(map[uint64]uint64)
2396 }
2397 o.rdc[seq] = dc
2398 return true
2399 }
2400 return false
2401 }
2402
2403 // Force expiration of all pending.
2404 // Lock should be held.
2405 func (o *consumer) forceExpirePending() {
2406 var expired []uint64
2407 for seq := range o.pending {
2408 if !o.onRedeliverQueue(seq) && !o.hasMaxDeliveries(seq) {
2409 expired = append(expired, seq)
2410 }
2411 }
2412 if len(expired) > 0 {
2413 slices.Sort(expired)
2414 o.addToRedeliverQueue(expired...)
2415 // Now we should update the timestamp here since we are redelivering.
2416 // We will use an incrementing time to preserve order for any other redelivery.
2417 off := time.Now().UnixNano() - o.pending[expired[0]].Timestamp
2418 for _, seq := range expired {
2419 if p, ok := o.pending[seq]; ok && p != nil {
2420 p.Timestamp += off
2421 }
2422 }
2423 o.resetPtmr(o.ackWait(0))
2424 }
2425 o.signalNewMessages()
2426 }
2427
2428 // Acquire proper locks and update rate limit.
2429 // Will use what is in config.
2430 func (o *consumer) setRateLimitNeedsLocks() {
2431 o.mu.RLock()
2432 mset := o.mset
2433 o.mu.RUnlock()
2434
2435 if mset == nil {
2436 return
2437 }
2438
2439 mset.mu.RLock()
2440 o.mu.Lock()
2441 o.setRateLimit(o.cfg.RateLimit)
2442 o.mu.Unlock()
2443 mset.mu.RUnlock()
2444 }
2445
2446 // Set the rate limiter
2447 // Both mset and consumer lock should be held.
2448 func (o *consumer) setRateLimit(bps uint64) {
2449 if bps == 0 {
2450 o.rlimit = nil
2451 return
2452 }
2453
2454 // TODO(dlc) - Make sane values or error if not sane?
2455 // We are configured in bits per sec so adjust to bytes.
2456 rl := rate.Limit(bps / 8)
2457 mset := o.mset
2458
2459 // Burst should be set to maximum msg size for this account, etc.
2460 var burst int
2461 // We don't need to get cfgMu's rlock here since this function
2462 // is already invoked under mset.mu.RLock(), which superseeds cfgMu.
2463 if mset.cfg.MaxMsgSize > 0 {
2464 burst = int(mset.cfg.MaxMsgSize)
2465 } else {
2466 acc := mset.jsa.account
2467 acc.mu.RLock()
2468 mpay := acc.mpay
2469 acc.mu.RUnlock()
2470 if mpay > 0 {
2471 burst = int(mpay)
2472 } else {
2473 burst = int(acc.srv.getOpts().MaxPayload)
2474 }
2475 }
2476
2477 o.rlimit = rate.NewLimiter(rl, burst)
2478 }
2479
2480 // Check if new consumer config allowed vs old.
2481 func (acc *Account) checkNewConsumerConfig(cfg, ncfg *ConsumerConfig) error {
2482 if reflect.DeepEqual(cfg, ncfg) {
2483 return nil
2484 }
2485 // Something different, so check since we only allow certain things to be updated.
2486 if cfg.DeliverPolicy != ncfg.DeliverPolicy {
2487 return errors.New("deliver policy can not be updated")
2488 }
2489 if cfg.MemoryStorage != ncfg.MemoryStorage {
2490 return errors.New("storage type can not be updated")
2491 }
2492 // Direct and Sourcing classify the consumer for its whole lifetime, which the
2493 // stream relies on when walking its consumer list, so they can not change.
2494 if cfg.Direct != ncfg.Direct {
2495 return errors.New("direct can not be updated")
2496 }
2497 if cfg.Sourcing != ncfg.Sourcing {
2498 return errors.New("sourcing can not be updated")
2499 }
2500 if cfg.OptStartSeq != ncfg.OptStartSeq {
2501 return errors.New("start sequence can not be updated")
2502 }
2503 if cfg.OptStartTime != nil && ncfg.OptStartTime != nil {
2504 // Both have start times set, compare them directly:
2505 if !cfg.OptStartTime.Equal(*ncfg.OptStartTime) {
2506 return errors.New("start time can not be updated")
2507 }
2508 } else if cfg.OptStartTime != nil || ncfg.OptStartTime != nil {
2509 // At least one start time is set and the other is not
2510 return errors.New("start time can not be updated")
2511 }
2512 if cfg.AckPolicy != ncfg.AckPolicy {
2513 return errors.New("ack policy can not be updated")
2514 }
2515 if cfg.ReplayPolicy != ncfg.ReplayPolicy {
2516 return errors.New("replay policy can not be updated")
2517 }
2518 if cfg.Heartbeat != ncfg.Heartbeat {
2519 return errors.New("heart beats can not be updated")
2520 }
2521 if cfg.FlowControl != ncfg.FlowControl {
2522 return errors.New("flow control can not be updated")
2523 }
2524
2525 // Deliver Subject is conditional on if its bound.
2526 if cfg.DeliverSubject != ncfg.DeliverSubject {
2527 if cfg.DeliverSubject == _EMPTY_ {
2528 return errors.New("can not update pull consumer to push based")
2529 }
2530 if ncfg.DeliverSubject == _EMPTY_ {
2531 return errors.New("can not update push consumer to pull based")
2532 }
2533 if acc.sl.HasInterest(cfg.DeliverSubject) {
2534 return NewJSConsumerNameExistError()
2535 }
2536 }
2537
2538 if cfg.MaxWaiting != ncfg.MaxWaiting {
2539 return errors.New("max waiting can not be updated")
2540 }
2541
2542 // Check if BackOff is defined, MaxDeliver is within range.
2543 if lbo := len(ncfg.BackOff); lbo > 0 && ncfg.MaxDeliver != -1 && lbo > ncfg.MaxDeliver {
2544 return NewJSConsumerMaxDeliverBackoffError()
2545 }
2546
2547 return nil
2548 }
2549
2550 // Update the config based on the new config, or error if update not allowed.
2551 func (o *consumer) updateConfig(cfg *ConsumerConfig) error {
2552 o.mu.Lock()
2553 defer o.mu.Unlock()
2554
2555 if o.closed || o.mset == nil {
2556 return NewJSConsumerDoesNotExistError()
2557 }
2558
2559 if err := o.acc.checkNewConsumerConfig(&o.cfg, cfg); err != nil {
2560 return err
2561 }
2562
2563 // Make sure we always store PauseUntil in UTC.
2564 if cfg.PauseUntil != nil {
2565 utc := (*cfg.PauseUntil).UTC()
2566 cfg.PauseUntil = &utc
2567 }
2568
2569 if o.store != nil {
2570 // Update local state always.
2571 if err := o.store.UpdateConfig(cfg); err != nil {
2572 return err
2573 }
2574 }
2575
2576 // DeliverSubject
2577 if cfg.DeliverSubject != o.cfg.DeliverSubject {
2578 o.updateDeliverSubjectLocked(cfg.DeliverSubject)
2579 }
2580
2581 // MaxAckPending
2582 if cfg.MaxAckPending != o.cfg.MaxAckPending {
2583 o.maxp = cfg.MaxAckPending
2584 o.signalNewMessages()
2585 // If MaxAckPending is lowered, we could have allocated a pending deliveries map of larger size.
2586 // Reset it here, so we can shrink the map.
2587 if cfg.MaxAckPending < o.cfg.MaxAckPending {
2588 o.resetPendingDeliveries()
2589 }
2590 }
2591 // AckWait
2592 if cfg.AckWait != o.cfg.AckWait {
2593 if o.ptmr != nil {
2594 o.resetPtmr(100 * time.Millisecond)
2595 }
2596 }
2597 // Rate Limit
2598 if cfg.RateLimit != o.cfg.RateLimit {
2599 // We need both locks here so do in Go routine.
2600 go o.setRateLimitNeedsLocks()
2601 }
2602 if cfg.SampleFrequency != o.cfg.SampleFrequency {
2603 s := strings.TrimSuffix(cfg.SampleFrequency, "%")
2604 if sampleFreq, err := strconv.ParseInt(s, 10, 32); err == nil {
2605 o.sfreq = int32(sampleFreq)
2606 }
2607 }
2608 // Set MaxDeliver if changed
2609 if cfg.MaxDeliver != o.cfg.MaxDeliver {
2610 // MaxDeliver is negative (-1) when infinite.
2611 o.maxdc = uint64(max(cfg.MaxDeliver, 0))
2612 }
2613 // Set InactiveThreshold if changed.
2614 if val := cfg.InactiveThreshold; val != o.cfg.InactiveThreshold {
2615 o.updateInactiveThreshold(cfg)
2616 stopAndClearTimer(&o.dtmr)
2617 // Restart timer only if we are the leader.
2618 if o.isLeader() && o.dthresh > 0 {
2619 o.dtmr = time.AfterFunc(o.dthresh, o.deleteNotActive)
2620 }
2621 }
2622 // Check whether the pause has changed
2623 {
2624 var old, new time.Time
2625 if o.cfg.PauseUntil != nil {
2626 old = *o.cfg.PauseUntil
2627 }
2628 if cfg.PauseUntil != nil {
2629 new = *cfg.PauseUntil
2630 }
2631 if !old.Equal(new) {
2632 o.updatePauseState(cfg)
2633 if o.isLeader() {
2634 o.sendPauseAdvisoryLocked(cfg)
2635 }
2636 }
2637 }
2638
2639 // Check for Subject Filters update.
2640 newSubjects := gatherSubjectFilters(cfg.FilterSubject, cfg.FilterSubjects)
2641 updatedFilters := !subjectSliceEqual(newSubjects, o.subjf.subjects())
2642 if updatedFilters {
2643 newSubjf := make(subjectFilters, 0, len(newSubjects))
2644 for _, newFilter := range newSubjects {
2645 fs := &subjectFilter{
2646 subject: newFilter,
2647 hasWildcard: subjectHasWildcard(newFilter),
2648 tokenizedSubject: tokenizeSubjectIntoSlice(nil, newFilter),
2649 }
2650 newSubjf = append(newSubjf, fs)
2651 }
2652 // Make sure we have correct signaling setup.
2653 // Consumer lock can not be held.
2654 mset := o.mset
2655 o.mu.Unlock()
2656 mset.swapSigSubs(o, newSubjf.subjects())
2657 o.mu.Lock()
2658
2659 // When we're done with signaling, we can replace the subjects.
2660 // If filters were removed, set `o.subjf` to nil.
2661 if len(newSubjf) == 0 {
2662 o.subjf = nil
2663 o.filters = nil
2664 } else {
2665 o.subjf = newSubjf
2666 if len(o.subjf) == 1 {
2667 o.filters = nil
2668 } else {
2669 o.filters = gsl.NewSublist[struct{}]()
2670 for _, filter := range o.subjf {
2671 o.filters.Insert(filter.subject, struct{}{})
2672 }
2673 }
2674 }
2675 }
2676
2677 // Record new config for others that do not need special handling.
2678 // Allowed but considered no-op, [Description, SampleFrequency, MaxWaiting, HeadersOnly]
2679 o.cfg = *cfg
2680
2681 if cfg.Sourcing && (!o.srv.JetStreamIsClustered() && o.srv.standAloneMode()) {
2682 o.resetStartingSeqLocked(0, _EMPTY_, false)
2683 }
2684 if updatedFilters {
2685 // Cleanup messages that lost interest.
2686 if o.retention == InterestPolicy {
2687 // Capture mset under the lock.
2688 mset := o.mset
2689 o.mu.Unlock()
2690 if mset != nil {
2691 o.cleanupNoInterestMessages(mset, false)
2692 }
2693 o.mu.Lock()
2694 }
2695
2696 // Re-calculate num pending on update.
2697 o.streamNumPending()
2698 }
2699
2700 return nil
2701 }
2702
2703 // This is a config change for the delivery subject for a
2704 // push based consumer.
2705 func (o *consumer) updateDeliverSubject(newDeliver string) {
2706 // Update the config and the dsubj
2707 o.mu.Lock()
2708 defer o.mu.Unlock()
2709 o.updateDeliverSubjectLocked(newDeliver)
2710 }
2711
2712 // This is a config change for the delivery subject for a
2713 // push based consumer.
2714 func (o *consumer) updateDeliverSubjectLocked(newDeliver string) {
2715 if o.closed || o.isPullMode() || o.cfg.DeliverSubject == newDeliver {
2716 return
2717 }
2718
2719 // Force redeliver of all pending on change of delivery subject.
2720 if len(o.pending) > 0 {
2721 o.forceExpirePending()
2722 }
2723
2724 o.acc.sl.clearNotification(o.dsubj, o.cfg.DeliverGroup, o.inch)
2725 o.dsubj, o.cfg.DeliverSubject = newDeliver, newDeliver
2726 // When we register new one it will deliver to update state loop.
2727 o.acc.sl.registerNotification(newDeliver, o.cfg.DeliverGroup, o.inch)
2728 }
2729
2730 // Check that configs are equal but allow delivery subjects to be different.
2731 func configsEqualSansDelivery(a, b ConsumerConfig) bool {
2732 // These were copied in so can set Delivery here.
2733 a.DeliverSubject, b.DeliverSubject = _EMPTY_, _EMPTY_
2734 return reflect.DeepEqual(a, b)
2735 }
2736
2737 // Helper to send a reply to an ack.
2738 func (o *consumer) sendAckReply(subj string) {
2739 o.mu.RLock()
2740 defer o.mu.RUnlock()
2741 o.outq.sendMsg(subj, nil)
2742 }
2743
2744 type jsAckMsg struct {
2745 subject string
2746 reply string
2747 hdr int
2748 msg []byte
2749 }
2750
2751 var jsAckMsgPool sync.Pool
2752
2753 func newJSAckMsg(subj, reply string, hdr int, msg []byte) *jsAckMsg {
2754 var m *jsAckMsg
2755 am := jsAckMsgPool.Get()
2756 if am != nil {
2757 m = am.(*jsAckMsg)
2758 } else {
2759 m = &jsAckMsg{}
2760 }
2761 // When getting something from a pool it is critical that all fields are
2762 // initialized. Doing this way guarantees that if someone adds a field to
2763 // the structure, the compiler will fail the build if this line is not updated.
2764 (*m) = jsAckMsg{subj, reply, hdr, msg}
2765 return m
2766 }
2767
2768 func (am *jsAckMsg) returnToPool() {
2769 if am == nil {
2770 return
2771 }
2772 am.subject, am.reply, am.hdr, am.msg = _EMPTY_, _EMPTY_, -1, nil
2773 jsAckMsgPool.Put(am)
2774 }
2775
2776 // Push the ack message to the consumer's ackMsgs queue
2777 func (o *consumer) pushAck(_ *subscription, c *client, _ *Account, subject, reply string, rmsg []byte) {
2778 atomic.AddInt64(&o.awl, 1)
2779 o.ackMsgs.push(newJSAckMsg(subject, reply, c.pa.hdr, copyBytes(rmsg)))
2780 }
2781
2782 // Processes a message for the ack reply subject delivered with a message.
2783 func (o *consumer) processAck(subject, reply string, hdr int, rmsg []byte) {
2784 defer atomic.AddInt64(&o.awl, -1)
2785
2786 var msg []byte
2787 if hdr > 0 {
2788 msg = rmsg[hdr:]
2789 } else {
2790 msg = rmsg
2791 }
2792
2793 sseq, dseq, dc, _, _ := ackReplyInfo(subject)
2794
2795 skipAckReply := sseq == 0
2796
2797 switch {
2798 case len(msg) == 0, bytes.Equal(msg, AckAck), bytes.Equal(msg, AckOK):
2799 if !o.processAckMsg(sseq, dseq, dc, reply, true) {
2800 // We handle replies for acks in updateAcks
2801 skipAckReply = true
2802 }
2803 case bytes.HasPrefix(msg, AckNext):
2804 o.processAckMsg(sseq, dseq, dc, _EMPTY_, true)
2805 o.processNextMsgRequest(reply, msg[len(AckNext):])
2806 skipAckReply = true
2807 case bytes.HasPrefix(msg, AckNak):
2808 o.processNak(sseq, dseq, dc, msg)
2809 case bytes.Equal(msg, AckProgress):
2810 o.progressUpdate(sseq)
2811 case bytes.HasPrefix(msg, AckTerm):
2812 var reason string
2813 if buf := msg[len(AckTerm):]; len(buf) > 0 {
2814 reason = string(bytes.TrimSpace(buf))
2815 }
2816 if !o.processTerm(sseq, dseq, dc, reason, reply) {
2817 // We handle replies for acks in updateAcks
2818 skipAckReply = true
2819 }
2820 }
2821
2822 // Ack the ack if requested.
2823 if len(reply) > 0 && !skipAckReply {
2824 o.sendAckReply(reply)
2825 }
2826 }
2827
2828 // Used to process a working update to delay redelivery.
2829 func (o *consumer) progressUpdate(seq uint64) {
2830 o.mu.Lock()
2831 defer o.mu.Unlock()
2832
2833 if p, ok := o.pending[seq]; ok {
2834 p.Timestamp = time.Now().UnixNano()
2835 // Update store system.
2836 o.updateDelivered(p.Sequence, seq, 1, p.Timestamp)
2837 }
2838 }
2839
2840 // Lock should be held.
2841 func (o *consumer) updateSkipped(seq uint64) {
2842 // Clustered mode and R>1 only.
2843 if o.node == nil || !o.isLeader() {
2844 return
2845 }
2846 var b [1 + 8]byte
2847 b[0] = byte(updateSkipOp)
2848 var le = binary.LittleEndian
2849 le.PutUint64(b[1:], seq)
2850 o.propose(b[:])
2851 }
2852
2853 func (o *consumer) resetStartingSeq(seq uint64, reply string, internal bool) (uint64, bool, error) {
2854 o.mu.Lock()
2855 defer o.mu.Unlock()
2856 return o.resetStartingSeqLocked(seq, reply, internal)
2857 }
2858
2859 // Lock should be held.
2860 func (o *consumer) resetStartingSeqLocked(seq uint64, reply string, internal bool) (uint64, bool, error) {
2861 // Reset to a specific sequence, or back to the ack floor.
2862 if seq == 0 {
2863 seq = o.asflr + 1
2864 } else if o.cfg.DeliverPolicy == DeliverAll {
2865 // Always allowed.
2866 goto VALID
2867 } else if o.cfg.DeliverPolicy == DeliverByStartSequence {
2868 // Only allowed if not going below what's configured.
2869 if seq < o.cfg.OptStartSeq {
2870 return 0, false, errors.New("below start seq")
2871 }
2872 goto VALID
2873 } else if o.cfg.DeliverPolicy == DeliverByStartTime && o.mset != nil {
2874 // Only allowed if not going below what's configured.
2875 nseq := o.mset.store.GetSeqFromTime(*o.cfg.OptStartTime)
2876 if seq < nseq {
2877 return 0, false, errors.New("below start time")
2878 }
2879 goto VALID
2880 } else {
2881 return 0, false, errors.New("not allowed")
2882 }
2883
2884 VALID:
2885 // Must be a minimum of 1.
2886 if seq <= 0 {
2887 seq = 1
2888 }
2889 // The replicated path requires quorum first before the reset actually takes effect.
2890 if o.node != nil {
2891 if !o.isLeader() {
2892 return 0, false, nil
2893 }
2894 b := make([]byte, 1+8+len(reply))
2895 b[0] = byte(resetSeqOp)
2896 var le = binary.LittleEndian
2897 le.PutUint64(b[1:], seq)
2898 copy(b[1+8:], reply)
2899 o.propose(b[:])
2900 if reply != _EMPTY_ {
2901 if o.rsm == nil {
2902 o.rsm = make(map[string]bool, 1)
2903 }
2904 o.rsm[reply] = internal
2905 }
2906 return seq, false, nil
2907 }
2908 o.resetLocalStartingSeq(seq)
2909 if o.store != nil {
2910 o.store.Reset(seq - 1)
2911 // Cleanup messages that lost interest.
2912 if o.retention == InterestPolicy {
2913 if mset := o.mset; mset != nil {
2914 o.mu.Unlock()
2915 ss := mset.state()
2916 o.checkStateForInterestStream(&ss)
2917 o.mu.Lock()
2918 }
2919 }
2920
2921 // Recalculate pending, and re-trigger message delivery.
2922 o.streamNumPending()
2923 o.signalNewMessages()
2924 return seq, true, nil
2925 }
2926 return seq, false, nil
2927 }
2928
2929 // Lock should be held.
2930 func (o *consumer) resetLocalStartingSeq(seq uint64) {
2931 o.pending, o.rdc = nil, nil
2932 o.rdq = nil
2933 o.rdqi.Empty()
2934 o.sseq, o.dseq = seq, 1
2935 o.adflr, o.asflr = o.dseq-1, o.sseq-1
2936 o.ldt, o.lat = time.Time{}, time.Time{}
2937 }
2938
2939 func (o *consumer) loopAndForwardProposals(node RaftNode, qch, pch chan struct{}, term uint64) {
2940 if node == nil || qch == nil || pch == nil {
2941 return
2942 }
2943
2944 forwardProposals := func() error {
2945 o.mu.Lock()
2946 if node == nil || !node.Leader() || o.term != term {
2947 o.mu.Unlock()
2948 return errors.New("no longer leader")
2949 }
2950 proposal := o.phead
2951 o.phead, o.ptail = nil, nil
2952 o.mu.Unlock()
2953 // 256k max for now per batch.
2954 const maxBatch = 256 * 1024
2955 var entries []*Entry
2956 for sz := 0; proposal != nil; proposal = proposal.next {
2957 entries = append(entries, newEntry(EntryNormal, proposal.data))
2958 sz += len(proposal.data)
2959 if sz > maxBatch {
2960 node.ProposeMulti(term, entries)
2961 // We need to re-create `entries` because there is a reference
2962 // to it in the node's pae map.
2963 sz, entries = 0, nil
2964 }
2965 }
2966 if len(entries) > 0 {
2967 node.ProposeMulti(term, entries)
2968 }
2969 return nil
2970 }
2971
2972 // In case we have anything pending on entry.
2973 forwardProposals()
2974
2975 for {
2976 select {
2977 case <-qch:
2978 forwardProposals()
2979 return
2980 case <-pch:
2981 if err := forwardProposals(); err != nil {
2982 return
2983 }
2984 }
2985 }
2986 }
2987
2988 // Lock should be held.
2989 func (o *consumer) propose(entry []byte) {
2990 p := &proposal{data: entry}
2991 if o.phead == nil {
2992 o.phead = p
2993 } else {
2994 o.ptail.next = p
2995 }
2996 o.ptail = p
2997
2998 // Kick our looper routine.
2999 select {
3000 case o.pch <- struct{}{}:
3001 default:
3002 }
3003 }
3004
3005 // Lock should be held.
3006 func (o *consumer) updateDelivered(dseq, sseq, dc uint64, ts int64) {
3007 // Clustered mode and R>1.
3008 if o.node != nil {
3009 // Inline for now, use variable compression.
3010 var b [4*binary.MaxVarintLen64 + 1]byte
3011 b[0] = byte(updateDeliveredOp)
3012 n := 1
3013 n += binary.PutUvarint(b[n:], dseq)
3014 n += binary.PutUvarint(b[n:], sseq)
3015 n += binary.PutUvarint(b[n:], dc)
3016 n += binary.PutVarint(b[n:], ts)
3017 o.propose(b[:n])
3018 } else if o.store != nil {
3019 o.store.UpdateDelivered(dseq, sseq, dc, ts)
3020 }
3021 // Update activity.
3022 o.ldt = time.Now()
3023 }
3024
3025 // Used to remember a pending ack reply in a replicated consumer.
3026 // Lock should be held.
3027 func (o *consumer) addAckReply(sseq uint64, reply string) {
3028 if o.replies == nil {
3029 o.replies = make(map[uint64]string)
3030 }
3031 o.replies[sseq] = reply
3032 }
3033
3034 // Used to remember messages that need to be sent for a replicated consumer, after delivered quorum.
3035 // Lock should be held.
3036 func (o *consumer) addReplicatedQueuedMsg(pmsg *jsPubMsg) {
3037 // Is not explicitly limited in size, but will at most hold maximum ack pending.
3038 if o.pendingDeliveries == nil {
3039 o.pendingDeliveries = make(map[uint64]*jsPubMsg)
3040 }
3041 o.pendingDeliveries[pmsg.seq] = pmsg
3042
3043 // Is not explicitly limited in size, but will at most hold maximum waiting requests.
3044 if o.waitingDeliveries == nil {
3045 o.waitingDeliveries = make(map[string]*waitingDelivery)
3046 }
3047 if wd, ok := o.waitingDeliveries[pmsg.dsubj]; ok {
3048 wd.seq = pmsg.seq
3049 } else {
3050 wd := wdPool.Get().(*waitingDelivery)
3051 wd.seq = pmsg.seq
3052 o.waitingDeliveries[pmsg.dsubj] = wd
3053 }
3054 }
3055
3056 // Lock should be held.
3057 func (o *consumer) updateAcks(dseq, sseq uint64, reply string) {
3058 if o.node != nil {
3059 // Inline for now, use variable compression.
3060 var b [2*binary.MaxVarintLen64 + 1]byte
3061 b[0] = byte(updateAcksOp)
3062 n := 1
3063 n += binary.PutUvarint(b[n:], dseq)
3064 n += binary.PutUvarint(b[n:], sseq)
3065 o.propose(b[:n])
3066 if reply != _EMPTY_ {
3067 o.addAckReply(sseq, reply)
3068 }
3069 } else if o.store != nil {
3070 o.store.UpdateAcks(dseq, sseq)
3071 if reply != _EMPTY_ {
3072 // Already locked so send direct.
3073 o.outq.sendMsg(reply, nil)
3074 }
3075 }
3076 // Update activity.
3077 o.lat = time.Now()
3078 }
3079
3080 // Communicate to the cluster an addition of a pending request.
3081 // Lock should be held.
3082 func (o *consumer) addClusterPendingRequest(reply string) {
3083 if o.node == nil || !o.pendingRequestsOk() {
3084 return
3085 }
3086 b := make([]byte, len(reply)+1)
3087 b[0] = byte(addPendingRequest)
3088 copy(b[1:], reply)
3089 o.propose(b)
3090 }
3091
3092 // Communicate to the cluster a removal of a pending request.
3093 // Lock should be held.
3094 func (o *consumer) removeClusterPendingRequest(reply string) {
3095 if o.node == nil || !o.pendingRequestsOk() {
3096 return
3097 }
3098 b := make([]byte, len(reply)+1)
3099 b[0] = byte(removePendingRequest)
3100 copy(b[1:], reply)
3101 o.propose(b)
3102 }
3103
3104 // Set whether or not we can send pending requests to followers.
3105 func (o *consumer) setPendingRequestsOk(ok bool) {
3106 o.mu.Lock()
3107 o.prOk = ok
3108 o.mu.Unlock()
3109 }
3110
3111 // Lock should be held.
3112 func (o *consumer) pendingRequestsOk() bool {
3113 return o.prOk
3114 }
3115
3116 // Set whether or not we can send info about pending pull requests to our group.
3117 // Will require all peers have a minimum version.
3118 func (o *consumer) checkAndSetPendingRequestsOk() {
3119 o.mu.RLock()
3120 s, isValid := o.srv, o.mset != nil
3121 o.mu.RUnlock()
3122 if !isValid {
3123 return
3124 }
3125
3126 if ca := o.consumerAssignment(); ca != nil && len(ca.Group.Peers) > 1 {
3127 for _, pn := range ca.Group.Peers {
3128 if si, ok := s.nodeToInfo.Load(pn); ok {
3129 if !versionAtLeast(si.(nodeInfo).version, 2, 7, 1) {
3130 // We expect all of our peers to eventually be up to date.
3131 // So check again in awhile.
3132 time.AfterFunc(eventsHBInterval, func() { o.checkAndSetPendingRequestsOk() })
3133 o.setPendingRequestsOk(false)
3134 return
3135 }
3136 }
3137 }
3138 }
3139 o.setPendingRequestsOk(true)
3140 }
3141
3142 // On leadership change make sure we alert the pending requests that they are no longer valid.
3143 func (o *consumer) checkPendingRequests() {
3144 o.mu.Lock()
3145 defer o.mu.Unlock()
3146 if o.mset == nil || o.outq == nil {
3147 return
3148 }
3149 hdr := []byte("NATS/1.0 409 Leadership Change\r\n\r\n")
3150 for reply := range o.prm {
3151 o.outq.send(newJSPubMsg(reply, _EMPTY_, _EMPTY_, hdr, nil, nil, 0))
3152 }
3153 o.prm = nil
3154 }
3155
3156 // This will release any pending pull requests if applicable.
3157 // Should be called only by the leader being deleted or stopped.
3158 // Lock should be held.
3159 func (o *consumer) releaseAnyPendingRequests(isAssigned bool) {
3160 if o.mset == nil || o.outq == nil || o.waiting.len() == 0 {
3161 return
3162 }
3163 wq := o.waiting
3164 for wr := wq.head; wr != nil; {
3165 if !isAssigned {
3166 hdr := []byte("NATS/1.0 409 Consumer Deleted\r\n\r\n")
3167 o.outq.send(newJSPubMsg(wr.reply, _EMPTY_, _EMPTY_, hdr, nil, nil, 0))
3168 }
3169 next := wr.next
3170 wr.recycle()
3171 wr = next
3172 }
3173 // Nil out old queue.
3174 o.waiting = nil
3175 }
3176
3177 // Process a NAK.
3178 func (o *consumer) processNak(sseq, dseq, dc uint64, nak []byte) {
3179 o.mu.Lock()
3180 defer o.mu.Unlock()
3181
3182 // Check for out of range.
3183 if dseq <= o.adflr || dseq > o.dseq {
3184 return
3185 }
3186 // If we are explicit ack make sure this is still on our pending list.
3187 if _, ok := o.pending[sseq]; !ok {
3188 return
3189 }
3190
3191 // Deliver an advisory
3192 e := JSConsumerDeliveryNakAdvisory{
3193 TypedEvent: TypedEvent{
3194 Type: JSConsumerDeliveryNakAdvisoryType,
3195 ID: nuid.Next(),
3196 Time: time.Now().UTC(),
3197 },
3198 Stream: o.stream,
3199 Consumer: o.name,
3200 ConsumerSeq: dseq,
3201 StreamSeq: sseq,
3202 Deliveries: dc,
3203 Domain: o.srv.getOpts().JetStreamDomain,
3204 }
3205
3206 o.sendAdvisory(o.nakEventT, e)
3207
3208 // Check to see if we have delays attached.
3209 if len(nak) > len(AckNak) {
3210 arg := bytes.TrimSpace(nak[len(AckNak):])
3211 if len(arg) > 0 {
3212 var d time.Duration
3213 var err error
3214 if arg[0] == '{' {
3215 var nd ConsumerNakOptions
3216 if err = json.Unmarshal(arg, &nd); err == nil {
3217 d = nd.Delay
3218 }
3219 } else {
3220 d, err = time.ParseDuration(string(arg))
3221 }
3222 if err != nil {
3223 // Treat this as normal NAK.
3224 o.srv.Warnf("JetStream consumer '%s > %s > %s' bad NAK delay value: %q", o.acc.Name, o.stream, o.name, arg)
3225 } else {
3226 // We have a parsed duration that the user wants us to wait before retrying.
3227 // Make sure we are not on the rdq.
3228 o.removeFromRedeliverQueue(sseq)
3229 if p, ok := o.pending[sseq]; ok {
3230 // now - ackWait is expired now, so offset from there.
3231 p.Timestamp = time.Now().Add(-o.cfg.AckWait).Add(d).UnixNano()
3232 // Update store system which will update followers as well.
3233 o.updateDelivered(p.Sequence, sseq, dc, p.Timestamp)
3234 if o.ptmr != nil {
3235 // Want checkPending to run and figure out the next timer ttl.
3236 // TODO(dlc) - We could optimize this maybe a bit more and track when we expect the timer to fire.
3237 o.resetPtmr(10 * time.Millisecond)
3238 }
3239 }
3240 // Nothing else for use to do now so return.
3241 return
3242 }
3243 }
3244 }
3245
3246 // If already queued up also ignore.
3247 if !o.onRedeliverQueue(sseq) {
3248 o.addToRedeliverQueue(sseq)
3249 }
3250
3251 o.signalNewMessages()
3252 }
3253
3254 // Process a TERM
3255 // Returns `true` if the ack was processed in place and the sender can now respond
3256 // to the client, or `false` if there was an error or the ack is replicated (in which
3257 // case the reply will be sent later).
3258 func (o *consumer) processTerm(sseq, dseq, dc uint64, reason, reply string) bool {
3259 return o.processTermLocked(sseq, dseq, dc, reason, reply, true)
3260 }
3261
3262 func (o *consumer) processTermLocked(sseq, dseq, dc uint64, reason, reply string, needLock bool) bool {
3263 // Treat like an ack to suppress redelivery.
3264 ackedInPlace := o.processAckMsgLocked(sseq, dseq, dc, reply, false, needLock)
3265
3266 if needLock {
3267 o.mu.Lock()
3268 defer o.mu.Unlock()
3269 }
3270
3271 // Deliver an advisory
3272 e := JSConsumerDeliveryTerminatedAdvisory{
3273 TypedEvent: TypedEvent{
3274 Type: JSConsumerDeliveryTerminatedAdvisoryType,
3275 ID: nuid.Next(),
3276 Time: time.Now().UTC(),
3277 },
3278 Stream: o.stream,
3279 Consumer: o.name,
3280 ConsumerSeq: dseq,
3281 StreamSeq: sseq,
3282 Deliveries: dc,
3283 Reason: reason,
3284 Domain: o.srv.getOpts().JetStreamDomain,
3285 }
3286
3287 subj := JSAdvisoryConsumerMsgTerminatedPre + "." + o.stream + "." + o.name
3288 o.sendAdvisory(subj, e)
3289 return ackedInPlace
3290 }
3291
3292 // Introduce a small delay in when timer fires to check pending.
3293 // Allows bursts to be treated in same time frame.
3294 const ackWaitDelay = time.Millisecond
3295
3296 // ackWait returns how long to wait to fire the pending timer.
3297 func (o *consumer) ackWait(next time.Duration) time.Duration {
3298 if next > 0 {
3299 return next + ackWaitDelay
3300 }
3301 return o.cfg.AckWait + ackWaitDelay
3302 }
3303
3304 func (o *consumer) removeRedeliveredBelow(seq uint64) {
3305 if seq == 0 {
3306 return
3307 }
3308 o.mu.Lock()
3309 for sseq := range o.rdc {
3310 if sseq < seq {
3311 delete(o.rdc, sseq)
3312 o.removeFromRedeliverQueue(sseq)
3313 }
3314 }
3315 o.mu.Unlock()
3316
3317 if o.store != nil {
3318 o.store.RemoveRedeliveredBelow(seq)
3319 }
3320 }
3321
3322 // checkRedelivered drops rdq entries at/below asflr or below stream's first sequence.
3323 // But rdc is kept until the message leaves the stream: needAck relies on rdc to mark
3324 // messages past MaxDeliver.
3325 // Lock should be held.
3326 func (o *consumer) checkRedelivered() {
3327 if o.mset == nil {
3328 return
3329 }
3330 var ss StreamState
3331 o.mset.store.FastState(&ss)
3332
3333 var shouldUpdateState bool
3334 for sseq := range o.rdc {
3335 if sseq <= o.asflr || sseq < ss.FirstSeq {
3336 o.removeFromRedeliverQueue(sseq)
3337 }
3338 if sseq < ss.FirstSeq {
3339 delete(o.rdc, sseq)
3340 shouldUpdateState = true
3341 }
3342 }
3343 if shouldUpdateState {
3344 if err := o.writeStoreStateUnlocked(); err != nil && o.srv != nil && o.mset != nil && !o.closed {
3345 s, acc, mset, name := o.srv, o.acc, o.mset, o.name
3346 s.Warnf("Consumer '%s > %s > %s' error on write store state from check redelivered: %v", acc, mset.getCfgName(), name, err)
3347 }
3348 }
3349 }
3350
3351 // This will restore the state from disk.
3352 // Lock should be held.
3353 func (o *consumer) readStoredState() error {
3354 if o.store == nil {
3355 return nil
3356 }
3357 state, err := o.store.State()
3358 if err == nil {
3359 o.applyState(state)
3360 if len(o.rdc) > 0 {
3361 o.checkRedelivered()
3362 }
3363 }
3364 return err
3365 }
3366
3367 // Apply the consumer stored state.
3368 // Lock should be held.
3369 func (o *consumer) applyState(state *ConsumerState) {
3370 if state == nil {
3371 return
3372 }
3373
3374 o.sseq = state.Delivered.Stream + 1
3375 o.dseq = state.Delivered.Consumer + 1
3376 o.adflr = state.AckFloor.Consumer
3377 o.asflr = state.AckFloor.Stream
3378 o.pending = state.Pending
3379 o.rdc = state.Redelivered
3380
3381 // Setup tracking timer if we have restored pending.
3382 if o.isLeader() && len(o.pending) > 0 {
3383 // This is on startup or leader change. We want to check pending
3384 // sooner in case there are inconsistencies etc. Pick between 500ms - 1.5s
3385 delay := 500*time.Millisecond + time.Duration(rand.Int63n(1000))*time.Millisecond
3386
3387 // If normal is lower than this just use that.
3388 if o.cfg.AckWait < delay {
3389 delay = o.ackWait(0)
3390 }
3391 o.resetPtmr(delay)
3392 }
3393 }
3394
3395 // Sets our store state from another source. Used in clustered mode on snapshot restore.
3396 // Lock should be held.
3397 func (o *consumer) setStoreState(state *ConsumerState) error {
3398 if state == nil || o.store == nil {
3399 return nil
3400 }
3401 err := o.store.Update(state)
3402 if err == nil {
3403 o.applyState(state)
3404 } else if err == ErrStoreOldUpdate {
3405 // Our store already has a newer state, which is normal during recovery
3406 // when the consumer was loaded from disk before the meta snapshot state
3407 // was applied.
3408 return nil
3409 }
3410 return err
3411 }
3412
3413 // Update our state to the store.
3414 func (o *consumer) writeStoreState() error {
3415 o.mu.Lock()
3416 defer o.mu.Unlock()
3417 return o.writeStoreStateUnlocked()
3418 }
3419
3420 // Update our state to the store.
3421 // Lock should be held.
3422 func (o *consumer) writeStoreStateUnlocked() error {
3423 if o.store == nil {
3424 return nil
3425 }
3426 state := ConsumerState{
3427 Delivered: SequencePair{
3428 Consumer: o.dseq - 1,
3429 Stream: o.sseq - 1,
3430 },
3431 AckFloor: SequencePair{
3432 Consumer: o.adflr,
3433 Stream: o.asflr,
3434 },
3435 Pending: o.pending,
3436 Redelivered: o.rdc,
3437 }
3438 return o.store.Update(&state)
3439 }
3440
3441 // Returns an initial info. Only applicable for non-clustered consumers.
3442 // We will clear after we return it, so one shot.
3443 func (o *consumer) initialInfo() *ConsumerInfo {
3444 o.mu.Lock()
3445 ici := o.ici
3446 o.ici = nil // gc friendly
3447 o.mu.Unlock()
3448 if ici == nil {
3449 ici = o.info()
3450 }
3451 return ici
3452 }
3453
3454 // Clears our initial info.
3455 // Used when we have a leader change in cluster mode but do not send a response.
3456 func (o *consumer) clearInitialInfo() {
3457 o.mu.Lock()
3458 o.ici = nil // gc friendly
3459 o.mu.Unlock()
3460 }
3461
3462 // Info returns our current consumer state.
3463 func (o *consumer) info() *ConsumerInfo {
3464 return o.infoWithSnap(false)
3465 }
3466
3467 func (o *consumer) infoWithSnap(snap bool) *ConsumerInfo {
3468 return o.infoWithSnapAndReply(snap, _EMPTY_)
3469 }
3470
3471 func (o *consumer) infoWithSnapAndReply(snap bool, reply string) *ConsumerInfo {
3472 o.mu.Lock()
3473 mset := o.mset
3474 if o.closed || mset == nil || mset.srv == nil {
3475 o.mu.Unlock()
3476 return nil
3477 }
3478 js := o.js
3479 if js == nil {
3480 o.mu.Unlock()
3481 return nil
3482 }
3483
3484 // Capture raftGroup.
3485 var rg *raftGroup
3486 if o.ca != nil {
3487 rg = o.ca.Group
3488 }
3489
3490 priorityGroups := []PriorityGroupState{}
3491 // TODO(jrm): when we introduce supporting many priority groups, we need to update assigning `o.currentNuid` for each group.
3492 if len(o.cfg.PriorityGroups) > 0 {
3493 priorityGroups = append(priorityGroups, PriorityGroupState{
3494 Group: o.cfg.PriorityGroups[0],
3495 PinnedClientID: o.currentPinId,
3496 PinnedTS: o.pinnedTS,
3497 })
3498 }
3499
3500 np, err := o.checkNumPending()
3501 if err != nil {
3502 o.mu.Unlock()
3503 return nil
3504 }
3505
3506 dseq, sseq := o.dseq, o.sseq
3507 if dseq <= 0 {
3508 dseq = 1
3509 }
3510 if sseq <= 0 {
3511 sseq = 1
3512 }
3513
3514 cfg := o.cfg
3515 info := &ConsumerInfo{
3516 Stream: o.stream,
3517 Name: o.name,
3518 Created: o.created,
3519 Config: &cfg,
3520 Delivered: SequenceInfo{
3521 Consumer: dseq - 1,
3522 Stream: sseq - 1,
3523 },
3524 AckFloor: SequenceInfo{
3525 Consumer: o.adflr,
3526 Stream: o.asflr,
3527 },
3528 NumAckPending: len(o.pending),
3529 NumRedelivered: len(o.rdc),
3530 NumPending: np,
3531 PushBound: o.isPushMode() && o.active,
3532 TimeStamp: time.Now().UTC(),
3533 PriorityGroups: priorityGroups,
3534 }
3535 // Reset redelivered for MaxDeliver 1. Redeliveries are disabled so must not report it (is confusing otherwise).
3536 // The state does still keep track of these messages.
3537 if o.cfg.MaxDeliver == 1 {
3538 info.NumRedelivered = 0
3539 }
3540 if o.cfg.PauseUntil != nil {
3541 p := *o.cfg.PauseUntil
3542 if info.Paused = time.Now().Before(p); info.Paused {
3543 info.PauseRemaining = time.Until(p)
3544 }
3545 }
3546
3547 // We always need to pull certain data from our store.
3548 if o.store != nil {
3549 state, err := o.store.BorrowState()
3550 if err != nil {
3551 o.mu.Unlock()
3552 return nil
3553 }
3554
3555 // If we are the leader we could have o.sseq that is skipped ahead.
3556 // To maintain consistency in reporting (e.g. jsz) we always take the state for our delivered/ackfloor stream sequence.
3557 // Only use skipped ahead o.sseq if we're a new consumer and have not yet replicated this state yet.
3558 leader := o.isLeader()
3559 if !leader || o.store.HasState() {
3560 info.Delivered.Consumer, info.Delivered.Stream = state.Delivered.Consumer, state.Delivered.Stream
3561 }
3562 info.AckFloor.Consumer, info.AckFloor.Stream = state.AckFloor.Consumer, state.AckFloor.Stream
3563 if !leader {
3564 info.NumAckPending = len(state.Pending)
3565 info.NumRedelivered = len(state.Redelivered)
3566 }
3567 }
3568
3569 // Adjust active based on non-zero etc. Also make UTC here.
3570 if !o.ldt.IsZero() {
3571 ldt := o.ldt.UTC() // This copies as well.
3572 info.Delivered.Last = &ldt
3573 }
3574 if !o.lat.IsZero() {
3575 lat := o.lat.UTC() // This copies as well.
3576 info.AckFloor.Last = &lat
3577 }
3578
3579 // If we are a pull mode consumer, report on number of waiting requests.
3580 if o.isPullMode() {
3581 o.processWaiting(false)
3582 info.NumWaiting = o.waiting.len()
3583 }
3584 // If we were asked to snapshot do so here.
3585 if snap {
3586 o.ici = info
3587 }
3588 sysc := o.sysc
3589 o.mu.Unlock()
3590
3591 // Do cluster.
3592 if rg != nil {
3593 info.Cluster = js.clusterInfo(rg)
3594 }
3595
3596 // If we have a reply subject send the response here.
3597 if reply != _EMPTY_ && sysc != nil {
3598 sysc.sendInternalMsg(reply, _EMPTY_, nil, info)
3599 }
3600
3601 return info
3602 }
3603
3604 // Will signal us that new messages are available. Will break out of waiting.
3605 func (o *consumer) signalNewMessages() {
3606 // Kick our new message channel
3607 select {
3608 case o.mch <- struct{}{}:
3609 default:
3610 }
3611 }
3612
3613 // shouldSample lets us know if we are sampling metrics on acks.
3614 func (o *consumer) shouldSample() bool {
3615 switch {
3616 case o.sfreq <= 0:
3617 return false
3618 case o.sfreq >= 100:
3619 return true
3620 }
3621
3622 // TODO(ripienaar) this is a tad slow so we need to rethink here, however this will only
3623 // hit for those with sampling enabled and its not the default
3624 return rand.Int31n(100) <= o.sfreq
3625 }
3626
3627 func (o *consumer) sampleAck(sseq, dseq, dc uint64) {
3628 if !o.shouldSample() {
3629 return
3630 }
3631
3632 now := time.Now().UTC()
3633 unow := now.UnixNano()
3634
3635 e := JSConsumerAckMetric{
3636 TypedEvent: TypedEvent{
3637 Type: JSConsumerAckMetricType,
3638 ID: nuid.Next(),
3639 Time: now,
3640 },
3641 Stream: o.stream,
3642 Consumer: o.name,
3643 ConsumerSeq: dseq,
3644 StreamSeq: sseq,
3645 Delay: unow - o.pending[sseq].Timestamp,
3646 Deliveries: dc,
3647 Domain: o.srv.getOpts().JetStreamDomain,
3648 }
3649
3650 o.sendAdvisory(o.ackEventT, e)
3651 }
3652
3653 // Process an ACK.
3654 // Returns `true` if the ack was processed in place and the sender can now respond
3655 // to the client, or `false` if there was an error or the ack is replicated (in which
3656 // case the reply will be sent later).
3657 func (o *consumer) processAckMsg(sseq, dseq, dc uint64, reply string, doSample bool) bool {
3658 return o.processAckMsgLocked(sseq, dseq, dc, reply, doSample, true)
3659 }
3660
3661 func (o *consumer) processAckMsgLocked(sseq, dseq, dc uint64, reply string, doSample bool, needLock bool) bool {
3662 lock := func() {
3663 if needLock {
3664 o.mu.Lock()
3665 }
3666 }
3667 unlock := func() {
3668 if needLock {
3669 o.mu.Unlock()
3670 }
3671 }
3672 lock()
3673 if o.closed {
3674 unlock()
3675 return false
3676 }
3677
3678 mset := o.mset
3679 if mset == nil || mset.closed.Load() {
3680 unlock()
3681 return false
3682 }
3683
3684 // Check if this ack is above the current pointer to our next to deliver.
3685 // Ignore if it's a flow-controlled consumer, its state could end up further ahead
3686 // since its state is not replicated before delivery.
3687 if sseq >= o.sseq && !o.cfg.FlowControl {
3688 // Let's make sure this is valid.
3689 // This is only received on the consumer leader, so should never be higher
3690 // than the last stream sequence. But could happen if we've just become
3691 // consumer leader, and we are not up-to-date on the stream yet.
3692 var ss StreamState
3693 mset.store.FastState(&ss)
3694 if sseq > ss.LastSeq {
3695 o.srv.Warnf("JetStream consumer '%s > %s > %s' ACK sequence %d past last stream sequence of %d",
3696 o.acc.Name, o.stream, o.name, sseq, ss.LastSeq)
3697 // FIXME(dlc) - For 2.11 onwards should we return an error here to the caller?
3698 }
3699 // Even though another leader must have delivered a message with this sequence, we must not adjust
3700 // the current pointer. This could otherwise result in a stuck consumer, where messages below this
3701 // sequence can't be redelivered, and we'll have incorrect pending state and ack floors.
3702 unlock()
3703 return false
3704 }
3705
3706 // Let the owning stream know if we are interest or workqueue retention based.
3707 // If this consumer is clustered (o.node != nil) this will be handled by
3708 // processReplicatedAck after the ack has propagated.
3709 // If we're already holding the lock we can't ack in place, since that will
3710 // violate lock ordering with respect to the stream.
3711 ackInPlace := o.node == nil && o.retention != LimitsPolicy && needLock
3712
3713 var ackAllSeqs []uint64
3714 var needSignal bool
3715
3716 switch o.cfg.AckPolicy {
3717 case AckExplicit:
3718 if p, ok := o.pending[sseq]; ok {
3719 if doSample {
3720 o.sampleAck(sseq, dseq, dc)
3721 }
3722 if o.maxp > 0 && len(o.pending) >= o.maxp {
3723 needSignal = true
3724 }
3725 delete(o.pending, sseq)
3726 // Use the original deliver sequence from our pending record.
3727 dseq = p.Sequence
3728 o.moveAckFloor(dseq, sseq)
3729 }
3730 delete(o.rdc, sseq)
3731 o.removeFromRedeliverQueue(sseq)
3732 case AckAll, AckFlowControl:
3733 // no-op
3734 if dseq <= o.adflr || sseq <= o.asflr {
3735 unlock()
3736 // Return true to let caller respond back to the client.
3737 return true
3738 }
3739 if o.maxp > 0 && len(o.pending) >= o.maxp {
3740 needSignal = true
3741 }
3742 sgap := sseq - o.asflr
3743 o.adflr, o.asflr = dseq, sseq
3744
3745 // Only needed if we ack in place, otherwise we'd never collect anything.
3746 // At most the pending entries below the ack, don't over-allocate.
3747 if ackInPlace {
3748 ackAllSeqs = make([]uint64, 0, min(uint64(len(o.pending)), sgap-1))
3749 }
3750
3751 remove := func(seq uint64) {
3752 // Only collect what was actually delivered to us.
3753 if ackInPlace && seq != sseq {
3754 if _, ok := o.pending[seq]; ok {
3755 ackAllSeqs = append(ackAllSeqs, seq)
3756 }
3757 }
3758 delete(o.pending, seq)
3759 delete(o.rdc, seq)
3760 o.removeFromRedeliverQueue(seq)
3761 }
3762 // Determine if smarter to walk all of pending vs the sequence range.
3763 if sgap > uint64(len(o.pending)) {
3764 for seq := range o.pending {
3765 if seq <= sseq {
3766 remove(seq)
3767 }
3768 }
3769 } else {
3770 for seq := sseq; seq > sseq-sgap && len(o.pending) > 0; seq-- {
3771 remove(seq)
3772 }
3773 }
3774 case AckNone:
3775 // FIXME(dlc) - This is error but do we care?
3776 unlock()
3777 return ackInPlace
3778 }
3779
3780 // No ack replication, so we set reply to "" so that updateAcks does not
3781 // send the reply. The caller will.
3782 if ackInPlace {
3783 reply = _EMPTY_
3784 }
3785 // Update underlying store.
3786 o.updateAcks(dseq, sseq, reply)
3787 unlock()
3788
3789 if ackInPlace {
3790 mset.ackMsg(o, sseq)
3791 for _, seq := range ackAllSeqs {
3792 mset.ackMsg(o, seq)
3793 }
3794 }
3795
3796 // If we had max ack pending set and were at limit we need to unblock ourselves.
3797 if needSignal {
3798 o.signalNewMessages()
3799 }
3800 return ackInPlace
3801 }
3802
3803 // Lock should be held.
3804 func (o *consumer) moveAckFloor(dseq, sseq uint64) {
3805 // Only move floors if we matched an existing pending.
3806 if len(o.pending) == 0 {
3807 o.adflr = o.dseq - 1
3808 o.asflr = o.sseq - 1
3809 } else if dseq == o.adflr+1 {
3810 o.adflr, o.asflr = dseq, sseq
3811 for ss := sseq + 1; ss < o.sseq; ss++ {
3812 if p, ok := o.pending[ss]; ok {
3813 if p.Sequence > 0 {
3814 o.adflr, o.asflr = p.Sequence-1, ss-1
3815 }
3816 break
3817 }
3818 }
3819 }
3820 }
3821
3822 // Determine if this is a truly filtered consumer. Modern clients will place filtered subjects
3823 // even if the stream only has a single non-wildcard subject designation.
3824 // Read lock should be held.
3825 func (o *consumer) isFiltered() bool {
3826 if o.subjf == nil {
3827 return false
3828 }
3829 // If we are here we want to check if the filtered subject is
3830 // a direct match for our only listed subject.
3831 mset := o.mset
3832 if mset == nil {
3833 return true
3834 }
3835
3836 // Protect access to mset.cfg with the cfgMu mutex.
3837 mset.cfgMu.RLock()
3838 msetSubjects := mset.cfg.Subjects
3839 mset.cfgMu.RUnlock()
3840
3841 // `isFiltered` need to be performant, so we do
3842 // as any checks as possible to avoid unnecessary work.
3843 // Here we avoid iteration over slices if there is only one subject in stream
3844 // and one filter for the consumer.
3845 if len(msetSubjects) == 1 && len(o.subjf) == 1 {
3846 return msetSubjects[0] != o.subjf[0].subject
3847 }
3848
3849 // if the list is not equal length, we can return early, as this is filtered.
3850 if len(msetSubjects) != len(o.subjf) {
3851 return true
3852 }
3853
3854 // if in rare case scenario that user passed all stream subjects as consumer filters,
3855 // we need to do a more expensive operation.
3856 // reflect.DeepEqual would return false if the filters are the same, but in different order
3857 // so it can't be used here.
3858 cfilters := make(map[string]struct{}, len(o.subjf))
3859 for _, val := range o.subjf {
3860 cfilters[val.subject] = struct{}{}
3861 }
3862 for _, val := range msetSubjects {
3863 if _, ok := cfilters[val]; !ok {
3864 return true
3865 }
3866 }
3867 return false
3868 }
3869
3870 // Check if we need an ack for this store seq.
3871 // This is called for interest based retention streams to remove messages.
3872 func (o *consumer) needAck(sseq uint64, subj string) bool {
3873 var needAck bool
3874 var asflr, osseq uint64
3875 var pending map[uint64]*Pending
3876 var rdc map[uint64]uint64
3877
3878 o.mu.RLock()
3879 defer o.mu.RUnlock()
3880
3881 isFiltered := o.isFiltered()
3882 if isFiltered && o.mset == nil {
3883 return false
3884 }
3885
3886 // Check if we are filtered, and if so check if this is even applicable to us.
3887 if isFiltered {
3888 if subj == _EMPTY_ {
3889 var err error
3890 if subj, err = o.mset.store.SubjectForSeq(sseq); err != nil {
3891 return false
3892 }
3893 }
3894 if !o.isFilteredMatch(subj) {
3895 return false
3896 }
3897 }
3898 if o.isLeader() {
3899 asflr, osseq = o.asflr, o.sseq
3900 pending, rdc = o.pending, o.rdc
3901 } else {
3902 if o.store == nil {
3903 return false
3904 }
3905 state, err := o.store.BorrowState()
3906 if err != nil || state == nil {
3907 // Fall back to what we track internally for now.
3908 return sseq > o.asflr && !o.isFiltered()
3909 }
3910 // If loading state as here, the osseq is +1.
3911 asflr, osseq, pending, rdc = state.AckFloor.Stream, state.Delivered.Stream+1, state.Pending, state.Redelivered
3912 }
3913
3914 switch o.cfg.AckPolicy {
3915 case AckNone, AckAll, AckFlowControl:
3916 needAck = sseq > asflr
3917 case AckExplicit:
3918 if sseq > asflr {
3919 if sseq >= osseq {
3920 needAck = true
3921 } else {
3922 _, needAck = pending[sseq]
3923 }
3924 }
3925 }
3926
3927 // Finally check if redelivery of this message is tracked.
3928 // If the message is not pending, it should be preserved if it reached max delivery.
3929 if !needAck {
3930 _, needAck = rdc[sseq]
3931 }
3932
3933 return needAck
3934 }
3935
3936 type PriorityGroup struct {
3937 Group string `json:"group,omitempty"`
3938 MinPending int64 `json:"min_pending,omitempty"`
3939 MinAckPending int64 `json:"min_ack_pending,omitempty"`
3940 Id string `json:"id,omitempty"`
3941 Priority int `json:"priority,omitempty"`
3942 }
3943
3944 // Used in nextReqFromMsg, since the json.Unmarshal causes the request
3945 // struct to escape to the heap always. This should reduce GC pressure.
3946 var jsGetNextPool = sync.Pool{
3947 New: func() any {
3948 return &JSApiConsumerGetNextRequest{}
3949 },
3950 }
3951
3952 // Helper for the next message requests.
3953 func nextReqFromMsg(msg []byte) (time.Time, int, int, bool, time.Duration, time.Time, *PriorityGroup, error) {
3954 req := bytes.TrimSpace(msg)
3955
3956 switch {
3957 case len(req) == 0:
3958 return time.Time{}, 1, 0, false, 0, time.Time{}, nil, nil
3959
3960 case req[0] == '{':
3961 cr := jsGetNextPool.Get().(*JSApiConsumerGetNextRequest)
3962 defer func() {
3963 *cr = JSApiConsumerGetNextRequest{}
3964 jsGetNextPool.Put(cr)
3965 }()
3966 if err := json.Unmarshal(req, &cr); err != nil {
3967 return time.Time{}, -1, 0, false, 0, time.Time{}, nil, err
3968 }
3969 var hbt time.Time
3970 if cr.Heartbeat > 0 {
3971 if cr.Heartbeat*2 > cr.Expires {
3972 return time.Time{}, 1, 0, false, 0, time.Time{}, nil, errors.New("heartbeat value too large")
3973 }
3974 hbt = time.Now().Add(cr.Heartbeat)
3975 }
3976 priorityGroup := cr.PriorityGroup
3977 if cr.Expires == time.Duration(0) {
3978 return time.Time{}, cr.Batch, cr.MaxBytes, cr.NoWait, cr.Heartbeat, hbt, &priorityGroup, nil
3979 }
3980 return time.Now().Add(cr.Expires), cr.Batch, cr.MaxBytes, cr.NoWait, cr.Heartbeat, hbt, &priorityGroup, nil
3981 default:
3982 if n, err := strconv.Atoi(string(req)); err == nil {
3983 return time.Time{}, n, 0, false, 0, time.Time{}, nil, nil
3984 }
3985 }
3986
3987 return time.Time{}, 1, 0, false, 0, time.Time{}, nil, nil
3988 }
3989
3990 // Represents a request that is on the internal waiting queue
3991 type waitingRequest struct {
3992 next *waitingRequest
3993 acc *Account
3994 interest string
3995 reply string
3996 n int // For batching
3997 d int // num delivered
3998 b int // For max bytes tracking
3999 expires time.Time
4000 received time.Time
4001 hb time.Duration
4002 hbt time.Time
4003 noWait bool
4004 priorityGroup *PriorityGroup
4005 }
4006
4007 // sync.Pool for waiting requests.
4008 var wrPool = sync.Pool{
4009 New: func() any {
4010 return new(waitingRequest)
4011 },
4012 }
4013
4014 // Recycle this request. This request can not be accessed after this call.
4015 func (wr *waitingRequest) recycleIfDone() bool {
4016 if wr != nil && wr.n <= 0 {
4017 wr.recycle()
4018 return true
4019 }
4020 return false
4021 }
4022
4023 // Force a recycle.
4024 func (wr *waitingRequest) recycle() {
4025 if wr != nil {
4026 wr.next, wr.acc, wr.interest, wr.reply = nil, nil, _EMPTY_, _EMPTY_
4027 wrPool.Put(wr)
4028 }
4029 }
4030
4031 // Represents an (optional) request timeout that's sent after waiting for replicated deliveries.
4032 type waitingDelivery struct {
4033 seq uint64
4034 pn int // Pending messages.
4035 pb int // Pending bytes.
4036 }
4037
4038 // sync.Pool for waiting deliveries.
4039 var wdPool = sync.Pool{
4040 New: func() any {
4041 return new(waitingDelivery)
4042 },
4043 }
4044
4045 // Force a recycle.
4046 func (wd *waitingDelivery) recycle() {
4047 if wd != nil {
4048 wd.seq, wd.pn, wd.pb = 0, 0, 0
4049 wdPool.Put(wd)
4050 }
4051 }
4052
4053 // waiting queue for requests that are waiting for new messages to arrive.
4054 type waitQueue struct {
4055 n, max int
4056 last time.Time
4057 head *waitingRequest
4058 tail *waitingRequest
4059 }
4060
4061 // Create a new ring buffer with at most max items.
4062 func newWaitQueue(max int) *waitQueue {
4063 return &waitQueue{max: max}
4064 }
4065
4066 var (
4067 errWaitQueueFull = errors.New("wait queue is full")
4068 errWaitQueueNil = errors.New("wait queue is nil")
4069 )
4070
4071 // insertSorted inserts wr at the correct position based on priority
4072 func (wq *waitQueue) insertSorted(wr *waitingRequest) {
4073
4074 // Handle empty queue
4075 if wq.head == nil {
4076 wq.head = wr
4077 wq.tail = wr
4078 wr.next = nil
4079 return
4080 }
4081 insertAtPosition(wr, wq)
4082 }
4083
4084 func (wq *waitQueue) addPrioritized(wr *waitingRequest) error {
4085 if wq == nil {
4086 return errWaitQueueNil
4087 }
4088 if wq.isFull() {
4089 return errWaitQueueFull
4090 }
4091
4092 wq.insertSorted(wr)
4093 wq.n++
4094 wq.last = wr.received
4095 return nil
4096 }
4097
4098 // Adds in a new request.
4099 func (wq *waitQueue) add(wr *waitingRequest) error {
4100 if wq == nil {
4101 return errWaitQueueNil
4102 }
4103 if wq.isFull() {
4104 return errWaitQueueFull
4105 }
4106 if wq.head == nil {
4107 wq.head = wr
4108 } else {
4109 wq.tail.next = wr
4110 }
4111 // Always set tail.
4112 wq.tail = wr
4113 // Make sure nil
4114 wr.next = nil
4115
4116 // Track last active via when we receive a request.
4117 wq.last = wr.received
4118 wq.n++
4119 return nil
4120 }
4121
4122 func (wq *waitQueue) isFull() bool {
4123 if wq == nil {
4124 return false
4125 }
4126 return wq.n == wq.max
4127 }
4128
4129 func (wq *waitQueue) isEmpty() bool {
4130 if wq == nil {
4131 return true
4132 }
4133 return wq.n == 0
4134 }
4135
4136 func (wq *waitQueue) len() int {
4137 if wq == nil {
4138 return 0
4139 }
4140 return wq.n
4141 }
4142
4143 // Peek will return the next request waiting or nil if empty.
4144 func (wq *waitQueue) peek() *waitingRequest {
4145 if wq == nil {
4146 return nil
4147 }
4148 return wq.head
4149 }
4150
4151 func (wq *waitQueue) cycle() {
4152 wr := wq.peek()
4153 if wr != nil {
4154 // Always remove current now on a pop, and move to end if still valid.
4155 // If we were the only one don't need to remove since this can be a no-op.
4156 wq.removeCurrent()
4157 wq.add(wr)
4158 }
4159 }
4160
4161 func (wq *waitQueue) popOrPopAndRequeue(priority PriorityPolicy) *waitingRequest {
4162 if wq == nil || wq.head == nil {
4163 return nil
4164 }
4165
4166 if priority == PriorityPrioritized {
4167 return wq.popAndRequeue()
4168 }
4169 return wq.pop()
4170 }
4171
4172 // pop will return the next request and move the read cursor.
4173 // This will now place a request that still has pending items at the ends of the list.
4174 func (wq *waitQueue) pop() *waitingRequest {
4175 wr := wq.peek()
4176 if wr != nil {
4177 wr.d++
4178 wr.n--
4179 // Always remove current now on a pop, and move to end if still valid.
4180 // If we were the only one don't need to remove since this can be a no-op.
4181 if wr.n > 0 && wq.n > 1 {
4182 wq.removeCurrent()
4183 wq.add(wr)
4184 } else if wr.n <= 0 {
4185 wq.removeCurrent()
4186 }
4187 }
4188 return wr
4189 }
4190
4191 // popAndRequeue pops the head element and requeues it at the end of its priority group.
4192 // This maintains FIFO order within the same priority level.
4193 func (wq *waitQueue) popAndRequeue() *waitingRequest {
4194 if wq == nil || wq.head == nil {
4195 return nil
4196 }
4197
4198 // Save the head
4199 wr := wq.head
4200
4201 if wr == nil {
4202 return wr
4203 }
4204
4205 wr.d++
4206 wr.n--
4207
4208 if wr.n > 0 && wq.n > 1 {
4209 if wr.next == nil {
4210 return wr
4211 }
4212 wq.head = wq.head.next
4213 wr.next = nil
4214
4215 insertAtPosition(wr, wq)
4216
4217 } else if wr.n <= 0 {
4218 wq.removeCurrent()
4219 return wr
4220
4221 }
4222
4223 return wr
4224 }
4225
4226 func insertAtPosition(wr *waitingRequest, wq *waitQueue) {
4227 priority := math.MaxInt32
4228 if wr.priorityGroup != nil {
4229 priority = wr.priorityGroup.Priority
4230 }
4231
4232 var prev *waitingRequest
4233 current := wq.head
4234 for current != nil {
4235 currentPriority := math.MaxInt32
4236 if current.priorityGroup != nil {
4237 currentPriority = current.priorityGroup.Priority
4238 }
4239 if currentPriority > priority {
4240 break
4241 }
4242 prev = current
4243 current = current.next
4244 }
4245
4246 if prev == nil {
4247 // All remaining elements have higher priority
4248 wr.next = wq.head
4249 wq.head = wr
4250 } else {
4251 wr.next = prev.next
4252 prev.next = wr
4253 if wr.next == nil {
4254 wq.tail = wr
4255 }
4256 }
4257 }
4258
4259 // Removes the current read pointer (head FIFO) entry.
4260 func (wq *waitQueue) removeCurrent() {
4261 wq.remove(nil, wq.head)
4262 }
4263
4264 // Remove the wr element from the wait queue.
4265 func (wq *waitQueue) remove(pre, wr *waitingRequest) {
4266 if wr == nil {
4267 return
4268 }
4269 if pre != nil {
4270 pre.next = wr.next
4271 } else if wr == wq.head {
4272 // We are removing head here.
4273 wq.head = wr.next
4274 }
4275 // Check if wr was our tail.
4276 if wr == wq.tail {
4277 // Check if we need to assign to pre.
4278 if wr.next == nil {
4279 wq.tail = pre
4280 } else {
4281 wq.tail = wr.next
4282 }
4283 }
4284 wq.n--
4285 }
4286
4287 // Return the map of pending requests keyed by the reply subject.
4288 // No-op if push consumer or invalid etc.
4289 func (o *consumer) pendingRequests() map[string]*waitingRequest {
4290 if o.waiting == nil {
4291 return nil
4292 }
4293 wq, m := o.waiting, make(map[string]*waitingRequest)
4294 for wr := wq.head; wr != nil; wr = wr.next {
4295 m[wr.reply] = wr
4296 }
4297
4298 return m
4299 }
4300
4301 func (o *consumer) setPinnedTimer(priorityGroup string) {
4302 if o.pinnedTtl != nil {
4303 o.pinnedTtl.Reset(o.cfg.PinnedTTL)
4304 } else {
4305 o.pinnedTtl = time.AfterFunc(o.cfg.PinnedTTL, func() {
4306 o.mu.Lock()
4307 // Skip if already unset.
4308 if o.currentPinId == _EMPTY_ {
4309 o.mu.Unlock()
4310 return
4311 }
4312 o.unassignPinId()
4313 o.sendUnpinnedAdvisoryLocked(priorityGroup, "timeout")
4314 o.mu.Unlock()
4315 o.signalNewMessages()
4316 })
4317 }
4318 }
4319
4320 // Lock should be held.
4321 func (o *consumer) assignNewPinId(wr *waitingRequest) {
4322 if wr.priorityGroup == nil || wr.priorityGroup.Group == _EMPTY_ {
4323 return
4324 }
4325 o.currentPinId = nuid.Next()
4326 o.pinnedTS = time.Now().UTC()
4327 wr.priorityGroup.Id = o.currentPinId
4328 o.setPinnedTimer(wr.priorityGroup.Group)
4329 o.sendPinnedAdvisoryLocked(wr.priorityGroup.Group)
4330 }
4331
4332 // Lock should be held.
4333 func (o *consumer) unassignPinId() {
4334 o.currentPinId = _EMPTY_
4335 o.pinnedTS = time.Time{}
4336 if o.pinnedTtl != nil {
4337 o.pinnedTtl.Stop()
4338 o.pinnedTtl = nil
4339 }
4340 }
4341
4342 // Return next waiting request. This will check for expirations but not noWait or interest.
4343 // That will be handled by processWaiting.
4344 // Lock should be held.
4345 func (o *consumer) nextWaiting(sz int) *waitingRequest {
4346 if o.waiting == nil || o.waiting.isEmpty() {
4347 return nil
4348 }
4349
4350 // Check if server needs to assign a new pin id.
4351 needNewPin := o.currentPinId == _EMPTY_ && o.cfg.PriorityPolicy == PriorityPinnedClient
4352
4353 numCycled := 0
4354 for wr := o.waiting.peek(); !o.waiting.isEmpty(); wr = o.waiting.peek() {
4355 if wr == nil {
4356 break
4357 }
4358
4359 if wr.expires.IsZero() || time.Now().Before(wr.expires) {
4360 // Track whether this iteration just claimed a new pin for this request.
4361 assignedPin := false
4362 if needNewPin {
4363 if wr.priorityGroup == nil || wr.priorityGroup.Id == _EMPTY_ {
4364 o.assignNewPinId(wr)
4365 assignedPin = true
4366 } else {
4367 // There is pin id set, but not a matching one. Send a notification to the client and remove the request.
4368 // Probably this is the old pin id.
4369 hdr := fmt.Appendf(nil, "NATS/1.0 423 Nats-Wrong-Pin-Id\r\n%s: %d\r\n%s: %d\r\n\r\n", JSPullRequestPendingMsgs, wr.n, JSPullRequestPendingBytes, wr.b)
4370 o.outq.send(newJSPubMsg(wr.reply, _EMPTY_, _EMPTY_, hdr, nil, nil, 0))
4371 o.waiting.removeCurrent()
4372 if o.node != nil {
4373 o.removeClusterPendingRequest(wr.reply)
4374 }
4375 wr.recycle()
4376 continue
4377 }
4378 } else if o.currentPinId != _EMPTY_ {
4379 // Check if we have a match on the currentNuid
4380 if wr.priorityGroup != nil && wr.priorityGroup.Id == o.currentPinId {
4381 // If we have a match, we do nothing here and will deliver the message later down the code path.
4382 } else if wr.priorityGroup == nil || wr.priorityGroup.Id == _EMPTY_ {
4383 o.waiting.cycle()
4384 numCycled++
4385 if numCycled >= o.waiting.len() {
4386 return nil
4387 }
4388 continue
4389 } else {
4390 // There is pin id set, but not a matching one. Send a notification to the client and remove the request.
4391 hdr := fmt.Appendf(nil, "NATS/1.0 423 Nats-Wrong-Pin-Id\r\n%s: %d\r\n%s: %d\r\n\r\n", JSPullRequestPendingMsgs, wr.n, JSPullRequestPendingBytes, wr.b)
4392 o.outq.send(newJSPubMsg(wr.reply, _EMPTY_, _EMPTY_, hdr, nil, nil, 0))
4393 o.waiting.removeCurrent()
4394 if o.node != nil {
4395 o.removeClusterPendingRequest(wr.reply)
4396 }
4397 wr.recycle()
4398 continue
4399 }
4400 }
4401
4402 if o.cfg.PriorityPolicy == PriorityOverflow {
4403 if wr.priorityGroup != nil &&
4404 // If both limits are zero we don't cycle and the request will be fulfilled.
4405 (wr.priorityGroup.MinPending > 0 || wr.priorityGroup.MinAckPending > 0) &&
4406 // We need to check o.npc+1, because before calling nextWaiting, we do o.npc--
4407 // If one OR the other limit is exceeded, we want to fulfill the request.
4408 // This is an inverted check. For clarity, we check the positive condition and negate.
4409 !((wr.priorityGroup.MinPending > 0 && wr.priorityGroup.MinPending <= o.npc+1) ||
4410 (wr.priorityGroup.MinAckPending > 0 && wr.priorityGroup.MinAckPending <= int64(len(o.pending)))) {
4411 o.waiting.cycle()
4412 numCycled++
4413 // We're done cycling through the requests.
4414 if numCycled >= o.waiting.len() {
4415 return nil
4416 }
4417 continue
4418 }
4419 }
4420 // Check if we have max bytes set.
4421 if wr.b > 0 {
4422 if sz <= wr.b {
4423 wr.b -= sz
4424 // If we are right now at zero, set batch to 1 to deliver this one but stop after.
4425 if wr.b == 0 {
4426 wr.n = 1
4427 }
4428 } else {
4429 // Since we can't send that message to the requestor, we need to
4430 // notify that we are closing the request.
4431 const maxBytesT = "NATS/1.0 409 Message Size Exceeds MaxBytes\r\n%s: %d\r\n%s: %d\r\n\r\n"
4432 hdr := fmt.Appendf(nil, maxBytesT, JSPullRequestPendingMsgs, wr.n, JSPullRequestPendingBytes, wr.b)
4433 o.outq.send(newJSPubMsg(wr.reply, _EMPTY_, _EMPTY_, hdr, nil, nil, 0))
4434 // If we just claimed the pin for this request, release it.
4435 if assignedPin {
4436 o.unassignPinId()
4437 }
4438 // Remove the current one, no longer valid due to max bytes limit.
4439 o.waiting.removeCurrent()
4440 if o.node != nil {
4441 o.removeClusterPendingRequest(wr.reply)
4442 }
4443 wr.recycle()
4444 continue
4445 }
4446 }
4447
4448 if wr.acc.sl.HasInterest(wr.interest) {
4449 return o.waiting.popOrPopAndRequeue(o.cfg.PriorityPolicy)
4450 } else if time.Since(wr.received) < defaultGatewayRecentSubExpiration && (o.srv.leafNodeEnabled || o.srv.gateway.enabled) {
4451 return o.waiting.popOrPopAndRequeue(o.cfg.PriorityPolicy)
4452 } else if o.srv.gateway.enabled && o.srv.hasGatewayInterest(wr.acc.Name, wr.interest) {
4453 return o.waiting.popOrPopAndRequeue(o.cfg.PriorityPolicy)
4454 }
4455 } else {
4456 // We do check for expiration in `processWaiting`, but it is possible to hit the expiry here, and not there.
4457 rdWait := o.replicateDeliveries()
4458 if rdWait {
4459 // Check if we need to send the timeout after pending replicated deliveries, or can do so immediately.
4460 if wd, ok := o.waitingDeliveries[wr.reply]; !ok {
4461 rdWait = false
4462 } else {
4463 wd.pn, wd.pb = wr.n, wr.b
4464 }
4465 }
4466 if !rdWait {
4467 hdr := fmt.Appendf(nil, "NATS/1.0 408 Request Timeout\r\n%s: %d\r\n%s: %d\r\n\r\n", JSPullRequestPendingMsgs, wr.n, JSPullRequestPendingBytes, wr.b)
4468 o.outq.send(newJSPubMsg(wr.reply, _EMPTY_, _EMPTY_, hdr, nil, nil, 0))
4469 }
4470 o.waiting.removeCurrent()
4471 if o.node != nil {
4472 o.removeClusterPendingRequest(wr.reply)
4473 }
4474 wr.recycle()
4475 continue
4476
4477 }
4478 if wr.interest != wr.reply {
4479 const intExpT = "NATS/1.0 408 Interest Expired\r\n%s: %d\r\n%s: %d\r\n\r\n"
4480 hdr := fmt.Appendf(nil, intExpT, JSPullRequestPendingMsgs, wr.n, JSPullRequestPendingBytes, wr.b)
4481 o.outq.send(newJSPubMsg(wr.reply, _EMPTY_, _EMPTY_, hdr, nil, nil, 0))
4482 }
4483 // Remove the current one, no longer valid.
4484 o.waiting.removeCurrent()
4485 if o.node != nil {
4486 o.removeClusterPendingRequest(wr.reply)
4487 }
4488 wr.recycle()
4489 }
4490
4491 return nil
4492 }
4493
4494 // Next message request.
4495 type nextMsgReq struct {
4496 reply string
4497 msg []byte
4498 }
4499
4500 var nextMsgReqPool sync.Pool
4501
4502 func newNextMsgReq(reply string, msg []byte) *nextMsgReq {
4503 var nmr *nextMsgReq
4504 m := nextMsgReqPool.Get()
4505 if m != nil {
4506 nmr = m.(*nextMsgReq)
4507 } else {
4508 nmr = &nextMsgReq{}
4509 }
4510 // When getting something from a pool it is critical that all fields are
4511 // initialized. Doing this way guarantees that if someone adds a field to
4512 // the structure, the compiler will fail the build if this line is not updated.
4513 (*nmr) = nextMsgReq{reply, msg}
4514 return nmr
4515 }
4516
4517 func (nmr *nextMsgReq) returnToPool() {
4518 if nmr == nil {
4519 return
4520 }
4521 nmr.reply, nmr.msg = _EMPTY_, nil
4522 nextMsgReqPool.Put(nmr)
4523 }
4524
4525 // processNextMsgReq will process a request for the next message available. A nil message payload means deliver
4526 // a single message. If the payload is a formal request or a number parseable with Atoi(), then we will send a
4527 // batch of messages without requiring another request to this endpoint, or an ACK.
4528 func (o *consumer) processNextMsgReq(_ *subscription, c *client, _ *Account, _, reply string, rmsg []byte) {
4529 if reply == _EMPTY_ {
4530 return
4531 }
4532
4533 // Short circuit error here.
4534 if o.nextMsgReqs == nil {
4535 hdr := []byte("NATS/1.0 409 Consumer is push based\r\n\r\n")
4536 o.outq.send(newJSPubMsg(reply, _EMPTY_, _EMPTY_, hdr, nil, nil, 0))
4537 return
4538 }
4539
4540 hdr, msg := c.msgParts(rmsg)
4541 if errorOnRequiredApiLevel(hdr) {
4542 hdr = []byte("NATS/1.0 412 Required Api Level\r\n\r\n")
4543 o.outq.send(newJSPubMsg(reply, _EMPTY_, _EMPTY_, hdr, nil, nil, 0))
4544 return
4545 }
4546 o.nextMsgReqs.push(newNextMsgReq(reply, copyBytes(msg)))
4547 }
4548
4549 // processResetReq will reset a consumer to a new starting sequence.
4550 func (o *consumer) processResetReq(_ *subscription, c *client, a *Account, _, reply string, rmsg []byte) {
4551 if reply == _EMPTY_ {
4552 return
4553 }
4554
4555 s := o.srv
4556 var resp = JSApiConsumerResetResponse{ApiResponse: ApiResponse{Type: JSApiConsumerResetResponseType}}
4557
4558 hdr, msg := c.msgParts(rmsg)
4559 if errorOnRequiredApiLevel(hdr) {
4560 resp.Error = NewJSRequiredApiLevelError()
4561 s.sendInternalAccountMsg(a, reply, s.jsonResponse(&resp))
4562 return
4563 }
4564
4565 // An empty message resets back to the ack floor, otherwise a custom sequence can be used.
4566 var req JSApiConsumerResetRequest
4567 if len(msg) > 0 {
4568 if err := json.Unmarshal(msg, &req); err != nil {
4569 resp.Error = NewJSInvalidJSONError(err)
4570 s.sendInternalAccountMsg(a, reply, s.jsonResponse(&resp))
4571 return
4572 }
4573 }
4574 resetSeq, canRespond, err := o.resetStartingSeq(req.Seq, reply, false)
4575 if err != nil {
4576 resp.Error = NewJSConsumerInvalidResetError(err)
4577 s.sendInternalAccountMsg(a, reply, s.jsonResponse(&resp))
4578 } else if canRespond {
4579 resp.ConsumerInfo = setDynamicConsumerInfoMetadata(o.info())
4580 resp.ResetSeq = resetSeq
4581 s.sendInternalAccountMsg(a, reply, s.jsonResponse(&resp))
4582 }
4583 }
4584
4585 func (o *consumer) processNextMsgRequest(reply string, msg []byte) {
4586 o.mu.Lock()
4587 defer o.mu.Unlock()
4588
4589 mset := o.mset
4590 if mset == nil {
4591 return
4592 }
4593
4594 sendErr := func(status int, description string) {
4595 hdr := fmt.Appendf(nil, "NATS/1.0 %d %s\r\n\r\n", status, description)
4596 o.outq.send(newJSPubMsg(reply, _EMPTY_, _EMPTY_, hdr, nil, nil, 0))
4597 }
4598
4599 if o.isPushMode() || o.waiting == nil {
4600 sendErr(409, "Consumer is push based")
4601 return
4602 }
4603
4604 // Check payload here to see if they sent in batch size or a formal request.
4605 expires, batchSize, maxBytes, noWait, hb, hbt, priorityGroup, err := nextReqFromMsg(msg)
4606 if err != nil {
4607 sendErr(400, fmt.Sprintf("Bad Request - %v", err))
4608 return
4609 }
4610
4611 // Check for request limits
4612 if o.cfg.MaxRequestBatch > 0 && batchSize > o.cfg.MaxRequestBatch {
4613 sendErr(409, fmt.Sprintf("Exceeded MaxRequestBatch of %d", o.cfg.MaxRequestBatch))
4614 return
4615 }
4616
4617 if !expires.IsZero() && o.cfg.MaxRequestExpires > 0 && expires.After(time.Now().Add(o.cfg.MaxRequestExpires)) {
4618 sendErr(409, fmt.Sprintf("Exceeded MaxRequestExpires of %v", o.cfg.MaxRequestExpires))
4619 return
4620 }
4621
4622 if maxBytes > 0 && o.cfg.MaxRequestMaxBytes > 0 && maxBytes > o.cfg.MaxRequestMaxBytes {
4623 sendErr(409, fmt.Sprintf("Exceeded MaxRequestMaxBytes of %v", o.cfg.MaxRequestMaxBytes))
4624 return
4625 }
4626
4627 if priorityGroup != nil {
4628 if (priorityGroup.MinPending != 0 || priorityGroup.MinAckPending != 0) && o.cfg.PriorityPolicy != PriorityOverflow {
4629 sendErr(400, "Bad Request - Not a Overflow Priority consumer")
4630 return
4631 }
4632 if priorityGroup.Id != _EMPTY_ && o.cfg.PriorityPolicy != PriorityPinnedClient {
4633 sendErr(400, "Bad Request - Not a Pinned Client Priority consumer")
4634 return
4635 }
4636 if priorityGroup.Priority < 0 || priorityGroup.Priority > 9 {
4637 sendErr(400, "Bad Request - Priority must be between 0 and 9")
4638 return
4639 }
4640 }
4641
4642 if priorityGroup != nil && o.cfg.PriorityPolicy != PriorityNone {
4643 if priorityGroup.Group == _EMPTY_ {
4644 sendErr(400, "Bad Request - Priority Group missing")
4645 return
4646 }
4647 if !slices.Contains(o.cfg.PriorityGroups, priorityGroup.Group) {
4648 sendErr(400, "Bad Request - Invalid Priority Group")
4649 return
4650 }
4651
4652 if o.currentPinId != _EMPTY_ {
4653 if priorityGroup.Id == o.currentPinId {
4654 o.setPinnedTimer(priorityGroup.Group)
4655 } else if priorityGroup.Id != _EMPTY_ {
4656 sendErr(423, "Nats-Pin-Id mismatch")
4657 return
4658 }
4659 }
4660 }
4661
4662 // If we have the max number of requests already pending try to expire.
4663 if o.waiting.isFull() {
4664 // Try to expire some of the requests.
4665 // We do not want to push too hard here so at maximum process once per sec.
4666 if time.Since(o.lwqic) > time.Second {
4667 o.processWaiting(false)
4668 }
4669 }
4670
4671 // If the request is for noWait and we have pending requests already, check if we have room.
4672 if noWait {
4673 msgsPending := o.numPending() + uint64(len(o.rdq))
4674 // If no pending at all, decide what to do with request.
4675 // If no expires was set then fail.
4676 if msgsPending == 0 && expires.IsZero() {
4677 o.waiting.last = time.Now()
4678 sendErr(404, "No Messages")
4679 return
4680 }
4681 if msgsPending > 0 {
4682 _, _, batchPending, _ := o.processWaiting(false)
4683 if msgsPending < uint64(batchPending) {
4684 o.waiting.last = time.Now()
4685 sendErr(408, "Requests Pending")
4686 return
4687 }
4688 }
4689 // If we are here this should be considered a one-shot situation.
4690 // We will wait for expires but will return as soon as we have any messages.
4691 }
4692
4693 // If we receive this request though an account export, we need to track that interest subject and account.
4694 acc, interest := trackDownAccountAndInterest(o.acc, reply)
4695
4696 // Create a waiting request.
4697 wr := wrPool.Get().(*waitingRequest)
4698 wr.acc, wr.interest, wr.reply, wr.n, wr.d, wr.noWait, wr.expires, wr.hb, wr.hbt, wr.priorityGroup = acc, interest, reply, batchSize, 0, noWait, expires, hb, hbt, priorityGroup
4699 wr.b = maxBytes
4700 wr.received = time.Now()
4701
4702 if o.cfg.PriorityPolicy == PriorityPrioritized {
4703 if err := o.waiting.addPrioritized(wr); err != nil {
4704 if hb == 0 {
4705 sendErr(409, "Exceeded MaxWaiting")
4706 }
4707 wr.recycle()
4708 return
4709 }
4710 } else {
4711 if err := o.waiting.add(wr); err != nil {
4712 // If the client has a heartbeat interval set, don't bother responding with a 409,
4713 // otherwise we can end up in a hot loop with the client re-requesting instead of
4714 // waiting for the missing heartbeats instead and retrying.
4715 if hb == 0 {
4716 sendErr(409, "Exceeded MaxWaiting")
4717 }
4718 wr.recycle()
4719 return
4720 }
4721 }
4722 o.signalNewMessages()
4723 // If we are clustered update our followers about this request.
4724 if o.node != nil {
4725 o.addClusterPendingRequest(wr.reply)
4726 }
4727 }
4728
4729 func trackDownAccountAndInterest(acc *Account, interest string) (*Account, string) {
4730 for strings.HasPrefix(interest, replyPrefix) {
4731 oa := acc
4732 oa.mu.RLock()
4733 if oa.exports.responses == nil {
4734 oa.mu.RUnlock()
4735 break
4736 }
4737 si := oa.exports.responses[interest]
4738 if si == nil {
4739 oa.mu.RUnlock()
4740 break
4741 }
4742 acc, interest = si.acc, si.to
4743 oa.mu.RUnlock()
4744 }
4745 return acc, interest
4746 }
4747
4748 // Return current delivery count for a given sequence.
4749 func (o *consumer) deliveryCount(seq uint64) uint64 {
4750 if o.rdc == nil {
4751 return 1
4752 }
4753 if dc := o.rdc[seq]; dc >= 1 {
4754 return dc
4755 }
4756 return 1
4757 }
4758
4759 // Increase the delivery count for this message.
4760 // ONLY used on redelivery semantics.
4761 // Lock should be held.
4762 func (o *consumer) incDeliveryCount(sseq uint64) uint64 {
4763 if o.rdc == nil {
4764 o.rdc = make(map[uint64]uint64)
4765 }
4766 o.rdc[sseq] += 1
4767 return o.rdc[sseq] + 1
4768 }
4769
4770 // Used if we have to adjust on failed delivery or bad lookups.
4771 // Those failed attempts should not increase deliver count.
4772 // Lock should be held.
4773 func (o *consumer) decDeliveryCount(sseq uint64) {
4774 if o.rdc == nil {
4775 return
4776 }
4777 dc, ok := o.rdc[sseq]
4778 if !ok {
4779 return
4780 }
4781 // Mirror incDeliveryCount, which goes from "no entry" to 1 on the first
4782 // redelivery. Going back to the initial delivery therefore has to remove
4783 // the entry rather than leave a zero behind, since a number of call sites
4784 // (needAck, decStreamPending) test for key presence rather than value.
4785 if dc > 1 {
4786 o.rdc[sseq] = dc - 1
4787 } else {
4788 delete(o.rdc, sseq)
4789 }
4790 }
4791
4792 // send a delivery exceeded advisory.
4793 func (o *consumer) notifyDeliveryExceeded(sseq, dc uint64) {
4794 e := JSConsumerDeliveryExceededAdvisory{
4795 TypedEvent: TypedEvent{
4796 Type: JSConsumerDeliveryExceededAdvisoryType,
4797 ID: nuid.Next(),
4798 Time: time.Now().UTC(),
4799 },
4800 Stream: o.stream,
4801 Consumer: o.name,
4802 StreamSeq: sseq,
4803 Deliveries: dc,
4804 Domain: o.srv.getOpts().JetStreamDomain,
4805 }
4806
4807 o.sendAdvisory(o.deliveryExcEventT, e)
4808 }
4809
4810 // Check if the candidate subject matches a filter if its present.
4811 // Lock should be held.
4812 func (o *consumer) isFilteredMatch(subj string) bool {
4813 // No filter is automatic match.
4814 if o.subjf == nil {
4815 return true
4816 }
4817 for _, filter := range o.subjf {
4818 if !filter.hasWildcard && subj == filter.subject {
4819 return true
4820 }
4821 }
4822 // It's quicker to first check for non-wildcard filters, then
4823 // iterate again to check for subset match.
4824 tsa := [32]string{}
4825 tts := tokenizeSubjectIntoSlice(tsa[:0], subj)
4826 for _, filter := range o.subjf {
4827 if isSubsetMatchTokenized(tts, filter.tokenizedSubject) {
4828 return true
4829 }
4830 }
4831 return false
4832 }
4833
4834 // Check if the candidate filter subject is equal to or a subset match
4835 // of one of the filter subjects.
4836 // Lock should be held.
4837 func (o *consumer) isEqualOrSubsetMatch(subj string) bool {
4838 for _, filter := range o.subjf {
4839 if !filter.hasWildcard && subj == filter.subject {
4840 return true
4841 }
4842 }
4843 tsa := [32]string{}
4844 tts := tokenizeSubjectIntoSlice(tsa[:0], subj)
4845 for _, filter := range o.subjf {
4846 if isSubsetMatchTokenized(filter.tokenizedSubject, tts) {
4847 return true
4848 }
4849 }
4850 return false
4851 }
4852
4853 var (
4854 errMaxAckPending = errors.New("max ack pending reached")
4855 errBadConsumer = errors.New("consumer not valid")
4856 errNoInterest = errors.New("consumer requires interest for delivery subject when ephemeral")
4857 )
4858
4859 // Get next available message from underlying store.
4860 // Is partition aware and redeliver aware.
4861 // Lock should be held.
4862 func (o *consumer) getNextMsg() (*jsPubMsg, uint64, error) {
4863 if o.mset == nil || o.mset.store == nil {
4864 return nil, 0, errBadConsumer
4865 }
4866 // Process redelivered messages before looking at possibly "skip list" (deliver last per subject)
4867 if o.hasRedeliveries() {
4868 var seq, dc uint64
4869 for seq = o.getNextToRedeliver(); seq > 0; seq = o.getNextToRedeliver() {
4870 dc = o.incDeliveryCount(seq)
4871 if o.maxdc > 0 && dc > o.maxdc {
4872 // Only send once
4873 if dc == o.maxdc+1 {
4874 o.notifyDeliveryExceeded(seq, dc-1)
4875 }
4876 // Make sure to remove from pending.
4877 if p, ok := o.pending[seq]; ok && p != nil {
4878 delete(o.pending, seq)
4879 // The delivery count has already been incremented once.
4880 o.updateDelivered(p.Sequence, seq, dc, p.Timestamp)
4881 o.moveAckFloor(p.Sequence, seq)
4882 }
4883 continue
4884 }
4885 pmsg := getJSPubMsgFromPool()
4886 sm, err := o.mset.store.LoadMsg(seq, &pmsg.StoreMsg)
4887 if sm == nil || err != nil {
4888 pmsg.returnToPool()
4889 pmsg = nil
4890 // Adjust back deliver count.
4891 o.decDeliveryCount(seq)
4892 }
4893 // Message was scheduled for redelivery but was removed in the meantime.
4894 if err == ErrStoreMsgNotFound || err == errDeletedMsg {
4895 // This is a race condition where the message is still in o.pending and
4896 // scheduled for redelivery, but it has been removed from the stream.
4897 // o.processTerm is called in a goroutine so would normally run. However,
4898 // if we get here this likely didn't fire, or we are replicated and changed leaders.
4899 // That will correct the pending state and delivery/ack floors, so just skip here.
4900 pmsg.returnToPool()
4901 pmsg = nil
4902 if p, ok := o.pending[seq]; ok {
4903 o.processTermLocked(seq, p.Sequence, dc-1, ackTermUnackedLimitsReason, _EMPTY_, false)
4904 }
4905 continue
4906 }
4907 return pmsg, dc, err
4908 }
4909 }
4910
4911 // Check if we have max pending.
4912 if o.maxp > 0 && len(o.pending) >= o.maxp {
4913 // maxp only set when ack policy != AckNone and user set MaxAckPending
4914 // Stall if we have hit max pending.
4915 return nil, 0, errMaxAckPending
4916 }
4917
4918 if o.hasSkipListPending() {
4919 seq := o.lss.seqs[0]
4920 if len(o.lss.seqs) == 1 {
4921 o.sseq = o.lss.resume
4922 o.lss = nil
4923 o.updateSkipped(o.sseq)
4924 } else {
4925 o.lss.seqs = o.lss.seqs[1:]
4926 o.sseq = seq
4927 }
4928 pmsg := getJSPubMsgFromPool()
4929 sm, err := o.mset.store.LoadMsg(seq, &pmsg.StoreMsg)
4930 if sm == nil || err != nil {
4931 pmsg.returnToPool()
4932 pmsg = nil
4933 }
4934 o.sseq++
4935 return pmsg, 1, err
4936 }
4937
4938 var sseq uint64
4939 var err error
4940 var sm *StoreMsg
4941 var pmsg = getJSPubMsgFromPool()
4942
4943 // Grab next message applicable to us.
4944 filters, subjf, fseq := o.filters, o.subjf, o.sseq
4945 // Check if we are multi-filtered or not.
4946 if filters != nil {
4947 sm, sseq, err = o.mset.store.LoadNextMsgMulti(filters, fseq, &pmsg.StoreMsg)
4948 } else if len(subjf) > 0 { // Means single filtered subject since o.filters means > 1.
4949 filter, wc := subjf[0].subject, subjf[0].hasWildcard
4950 sm, sseq, err = o.mset.store.LoadNextMsg(filter, wc, fseq, &pmsg.StoreMsg)
4951 } else {
4952 // No filter here.
4953 sm, sseq, err = o.mset.store.LoadNextMsg(_EMPTY_, false, fseq, &pmsg.StoreMsg)
4954 }
4955 if sm == nil {
4956 pmsg.returnToPool()
4957 pmsg = nil
4958 }
4959 // Check if we should move our o.sseq.
4960 if sseq >= o.sseq {
4961 // If we are moving step by step then sseq == o.sseq.
4962 // If we have jumped we should update skipped for other replicas.
4963 if sseq != o.sseq && err == ErrStoreEOF {
4964 o.updateSkipped(sseq + 1)
4965 }
4966 o.sseq = sseq + 1
4967 }
4968 return pmsg, 1, err
4969 }
4970
4971 // Will check for expiration and lack of interest on waiting requests.
4972 // Will also do any heartbeats and return the next expiration or HB interval.
4973 func (o *consumer) processWaiting(eos bool) (int, int, int, time.Time) {
4974 var fexp time.Time
4975 if o.srv == nil || o.waiting.isEmpty() {
4976 return 0, 0, 0, fexp
4977 }
4978 // Mark our last check time.
4979 o.lwqic = time.Now()
4980
4981 var expired, brp int
4982 s, now := o.srv, time.Now()
4983
4984 wq := o.waiting
4985 remove := func(pre, wr *waitingRequest) *waitingRequest {
4986 expired++
4987 if o.node != nil {
4988 o.removeClusterPendingRequest(wr.reply)
4989 }
4990 next := wr.next
4991 wq.remove(pre, wr)
4992 wr.recycle()
4993 return next
4994 }
4995
4996 var pre *waitingRequest
4997 for wr := wq.head; wr != nil; {
4998 // Check expiration.
4999 expires := !wr.expires.IsZero() && now.After(wr.expires)
5000 if (eos && wr.noWait) || expires {
5001 rdWait := o.replicateDeliveries()
5002 if rdWait {
5003 // Check if we need to send the timeout after pending replicated deliveries, or can do so immediately.
5004 if wd, ok := o.waitingDeliveries[wr.reply]; !ok {
5005 rdWait = false
5006 } else {
5007 wd.pn, wd.pb = wr.n, wr.b
5008 }
5009 // If we still need to wait for replicated deliveries, remove from waiting list.
5010 if rdWait {
5011 wr = remove(pre, wr)
5012 continue
5013 }
5014 }
5015 // Normally it's a timeout.
5016 if expires {
5017 hdr := fmt.Appendf(nil, "NATS/1.0 408 Request Timeout\r\n%s: %d\r\n%s: %d\r\n\r\n", JSPullRequestPendingMsgs, wr.n, JSPullRequestPendingBytes, wr.b)
5018 o.outq.send(newJSPubMsg(wr.reply, _EMPTY_, _EMPTY_, hdr, nil, nil, 0))
5019 wr = remove(pre, wr)
5020 continue
5021 } else if wr.expires.IsZero() || wr.d > 0 {
5022 // But if we're NoWait without expiry, we've reached the end of the stream, and we've not delivered any messages.
5023 // Return no messages instead, which is the same as if we'd rejected the pull request initially.
5024 hdr := fmt.Appendf(nil, "NATS/1.0 404 No Messages\r\n\r\n")
5025 o.outq.send(newJSPubMsg(wr.reply, _EMPTY_, _EMPTY_, hdr, nil, nil, 0))
5026 wr = remove(pre, wr)
5027 continue
5028 }
5029 }
5030 // Now check interest.
5031 interest := wr.acc.sl.HasInterest(wr.interest)
5032 if !interest && (s.leafNodeEnabled || s.gateway.enabled) {
5033 // If we are here check on gateways and leaf nodes (as they can mask gateways on the other end).
5034 // If we have interest or the request is too young break and do not expire.
5035 if time.Since(wr.received) < defaultGatewayRecentSubExpiration {
5036 interest = true
5037 } else if s.gateway.enabled && s.hasGatewayInterest(wr.acc.Name, wr.interest) {
5038 interest = true
5039 }
5040 }
5041 // Check if we have interest.
5042 if !interest {
5043 // No more interest here so go ahead and remove this one from our list.
5044 wr = remove(pre, wr)
5045 continue
5046 }
5047
5048 // If interest, update batch pending requests counter and update fexp timer.
5049 brp += wr.n
5050 if !wr.hbt.IsZero() {
5051 if now.After(wr.hbt) {
5052 // Fire off a heartbeat here.
5053 o.sendIdleHeartbeat(wr.reply)
5054 // Update next HB.
5055 wr.hbt = now.Add(wr.hb)
5056 }
5057 if fexp.IsZero() || wr.hbt.Before(fexp) {
5058 fexp = wr.hbt
5059 }
5060 }
5061 if !wr.expires.IsZero() && (fexp.IsZero() || wr.expires.Before(fexp)) {
5062 fexp = wr.expires
5063 }
5064 // Update pre and wr here.
5065 pre = wr
5066 wr = wr.next
5067 }
5068
5069 return expired, wq.len(), brp, fexp
5070 }
5071
5072 // Will check to make sure those waiting still have registered interest.
5073 func (o *consumer) checkWaitingForInterest() bool {
5074 o.processWaiting(true)
5075 return o.waiting.len() > 0
5076 }
5077
5078 // Lock should be held.
5079 func (o *consumer) hbTimer() (time.Duration, *time.Timer) {
5080 if o.cfg.Heartbeat == 0 {
5081 return 0, nil
5082 }
5083 return o.cfg.Heartbeat, time.NewTimer(o.cfg.Heartbeat)
5084 }
5085
5086 // Check here for conditions when our ack floor may have drifted below the streams first sequence.
5087 // In general this is accounted for in normal operations, but if the consumer misses the signal from
5088 // the stream it will not clear the message and move the ack state.
5089 // Should only be called from consumer leader.
5090 func (o *consumer) checkAckFloor() {
5091 o.mu.RLock()
5092 mset, closed, asflr, numPending := o.mset, o.closed, o.asflr, len(o.pending)
5093 o.mu.RUnlock()
5094
5095 if asflr == 0 || closed || mset == nil {
5096 return
5097 }
5098
5099 var ss StreamState
5100 mset.store.FastState(&ss)
5101
5102 // If our floor is equal or greater that is normal and nothing for us to do.
5103 if ss.FirstSeq == 0 || asflr >= ss.FirstSeq-1 {
5104 return
5105 }
5106
5107 // Check which linear space is less to walk.
5108 if ss.FirstSeq-asflr-1 < uint64(numPending) {
5109 // Process all messages that no longer exist.
5110 for seq := asflr + 1; seq < ss.FirstSeq; seq++ {
5111 // Check if this message was pending.
5112 o.mu.RLock()
5113 p, isPending := o.pending[seq]
5114 rdc := o.deliveryCount(seq)
5115 o.mu.RUnlock()
5116 // If it was pending for us, get rid of it.
5117 if isPending {
5118 o.processTerm(seq, p.Sequence, rdc, ackTermLimitsReason, _EMPTY_)
5119 }
5120 }
5121 } else if numPending > 0 {
5122 // here it is shorter to walk pending.
5123 // toTerm is seq, dseq, rcd for each entry.
5124 toTerm := make([]uint64, 0, numPending*3)
5125 o.mu.RLock()
5126 for seq, p := range o.pending {
5127 if seq < ss.FirstSeq {
5128 var dseq uint64 = 1
5129 if p != nil {
5130 dseq = p.Sequence
5131 }
5132 rdc := o.deliveryCount(seq)
5133 toTerm = append(toTerm, seq, dseq, rdc)
5134 }
5135 }
5136 o.mu.RUnlock()
5137
5138 for i := 0; i < len(toTerm); i += 3 {
5139 seq, dseq, rdc := toTerm[i], toTerm[i+1], toTerm[i+2]
5140 o.processTerm(seq, dseq, rdc, ackTermLimitsReason, _EMPTY_)
5141 }
5142 }
5143
5144 // Do one final check here.
5145 o.mu.Lock()
5146 defer o.mu.Unlock()
5147
5148 // If we are closed do not change anything and simply return.
5149 if o.closed {
5150 return
5151 }
5152
5153 // If we are here, and this should be rare, we still are off with our ack floor.
5154 // We will make sure we are not doing un-necessary work here if only off by a bit
5155 // since this could be normal for a high activity wq or stream.
5156 // We will set it explicitly to 1 behind our current lowest in pending, or if
5157 // pending is empty, to our current delivered -1.
5158 const minOffThreshold = 50
5159 if ss.FirstSeq >= minOffThreshold && o.asflr < ss.FirstSeq-minOffThreshold {
5160 var psseq, pdseq uint64
5161 for seq, p := range o.pending {
5162 if psseq == 0 || seq < psseq {
5163 psseq, pdseq = seq, p.Sequence
5164 }
5165 }
5166 // If we still have none, set to current delivered -1.
5167 if psseq == 0 {
5168 psseq, pdseq = o.sseq-1, o.dseq-1
5169 // If still not adjusted.
5170 if psseq < ss.FirstSeq-1 {
5171 psseq = ss.FirstSeq - 1
5172 }
5173 } else {
5174 // Since this was set via the pending, we should not include
5175 // it directly but set floors to -1.
5176 psseq, pdseq = psseq-1, pdseq-1
5177 }
5178 o.asflr, o.adflr = psseq, pdseq
5179 }
5180 }
5181
5182 func (o *consumer) processInboundAcks(qch chan struct{}) {
5183 // Grab the server lock to watch for server quit.
5184 o.mu.RLock()
5185 s, mset := o.srv, o.mset
5186 hasInactiveThresh := o.cfg.InactiveThreshold > 0
5187
5188 o.mu.RUnlock()
5189
5190 if s == nil || mset == nil {
5191 return
5192 }
5193
5194 // We will check this on entry and periodically.
5195 o.checkAckFloor()
5196
5197 // How often we will check for ack floor drift.
5198 // Spread these out for large numbers on a server restart.
5199 delta := time.Duration(rand.Int63n(int64(time.Minute)))
5200 ticker := time.NewTicker(time.Minute + delta)
5201 defer ticker.Stop()
5202
5203 for {
5204 select {
5205 case <-o.ackMsgs.ch:
5206 // If we have an inactiveThreshold set, mark our activity.
5207 // Do this before processing acks, otherwise we might race if there are no pending messages
5208 // anymore and the inactivity threshold kicks in before we're able to mark activity.
5209 if hasInactiveThresh {
5210 o.suppressDeletion()
5211 }
5212
5213 acks := o.ackMsgs.pop()
5214 for _, ack := range acks {
5215 o.processAck(ack.subject, ack.reply, ack.hdr, ack.msg)
5216 ack.returnToPool()
5217 }
5218 o.ackMsgs.recycle(&acks)
5219 case <-ticker.C:
5220 o.checkAckFloor()
5221 case <-qch:
5222 return
5223 case <-s.quitCh:
5224 return
5225 }
5226 }
5227 }
5228
5229 // Process inbound next message requests.
5230 func (o *consumer) processInboundNextMsgReqs(qch chan struct{}) {
5231 // Grab the server lock to watch for server quit.
5232 o.mu.RLock()
5233 s := o.srv
5234 o.mu.RUnlock()
5235
5236 for {
5237 select {
5238 case <-o.nextMsgReqs.ch:
5239 reqs := o.nextMsgReqs.pop()
5240 for _, req := range reqs {
5241 o.processNextMsgRequest(req.reply, req.msg)
5242 req.returnToPool()
5243 }
5244 o.nextMsgReqs.recycle(&reqs)
5245 case <-qch:
5246 return
5247 case <-s.quitCh:
5248 return
5249 }
5250 }
5251 }
5252
5253 // Suppress auto cleanup on ack activity of any kind.
5254 func (o *consumer) suppressDeletion() {
5255 o.mu.Lock()
5256 defer o.mu.Unlock()
5257
5258 if o.closed {
5259 return
5260 }
5261
5262 if o.isPushMode() && o.dtmr != nil {
5263 // if dtmr is not nil we have started the countdown, simply reset to threshold.
5264 o.dtmr.Reset(o.dthresh)
5265 } else if o.isPullMode() && o.waiting != nil {
5266 // Pull mode always has timer running, update last on waiting queue.
5267 o.waiting.last = time.Now()
5268 if o.dtmr != nil {
5269 o.dtmr.Reset(o.dthresh)
5270 }
5271 }
5272 }
5273
5274 // loopAndGatherMsgs waits for messages for the consumer. qch is the quit channel,
5275 // upch is the unpause channel which fires when the PauseUntil deadline is reached.
5276 func (o *consumer) loopAndGatherMsgs(qch chan struct{}) {
5277 // On startup check to see if we are in a reply situation where replay policy is not instant.
5278 var (
5279 lts int64 // last time stamp seen, used for replay.
5280 lseq uint64
5281 )
5282
5283 o.mu.RLock()
5284 mset := o.mset
5285 getLSeq := o.replay
5286 o.mu.RUnlock()
5287 // consumer is closed when mset is set to nil.
5288 if mset == nil {
5289 return
5290 }
5291 if getLSeq {
5292 lseq = mset.state().LastSeq
5293 }
5294
5295 o.mu.Lock()
5296 s := o.srv
5297 // need to check again if consumer is closed
5298 if o.mset == nil {
5299 o.mu.Unlock()
5300 return
5301 }
5302 // For idle heartbeat support.
5303 var hbc <-chan time.Time
5304 hbd, hb := o.hbTimer()
5305 if hb != nil {
5306 hbc = hb.C
5307 }
5308 // Interest changes.
5309 inch := o.inch
5310 o.mu.Unlock()
5311
5312 // Grab the stream's retention policy and name
5313 mset.cfgMu.RLock()
5314 stream, rp := mset.cfg.Name, mset.cfg.Retention
5315 mset.cfgMu.RUnlock()
5316
5317 var err error
5318
5319 // Deliver all the msgs we have now, once done or on a condition, we wait for new ones.
5320 for {
5321 var (
5322 pmsg *jsPubMsg
5323 dc uint64
5324 dsubj string
5325 ackReply string
5326 delay time.Duration
5327 sz int
5328 wrn, wrb int
5329 )
5330
5331 o.mu.Lock()
5332
5333 // consumer is closed when mset is set to nil.
5334 if o.closed || o.mset == nil {
5335 o.mu.Unlock()
5336 return
5337 }
5338
5339 // Clear last error.
5340 err = nil
5341
5342 // If the consumer is paused then stop sending.
5343 if o.cfg.PauseUntil != nil && !o.cfg.PauseUntil.IsZero() && time.Now().Before(*o.cfg.PauseUntil) {
5344 // If the consumer is paused and we haven't reached the deadline yet then
5345 // go back to waiting.
5346 goto waitForMsgs
5347 }
5348
5349 // If we are in push mode and not active or under flowcontrol let's stop sending.
5350 if o.isPushMode() {
5351 if !o.active || (o.maxpb > 0 && o.pbytes > o.maxpb) {
5352 goto waitForMsgs
5353 }
5354 } else if o.waiting.isEmpty() {
5355 // If we are in pull mode and no one is waiting already break and wait.
5356 goto waitForMsgs
5357 }
5358
5359 // Grab our next msg.
5360 pmsg, dc, err = o.getNextMsg()
5361
5362 // We can release the lock now under getNextMsg so need to check this condition again here.
5363 if o.closed || o.mset == nil {
5364 o.mu.Unlock()
5365 return
5366 }
5367
5368 // On error either wait or return.
5369 if err != nil || pmsg == nil {
5370 // On EOF we can optionally fast sync num pending state.
5371 if err == ErrStoreEOF {
5372 o.checkNumPendingOnEOF()
5373 }
5374 if err == ErrStoreMsgNotFound || err == errDeletedMsg || err == ErrStoreEOF || err == errMaxAckPending {
5375 goto waitForMsgs
5376 } else {
5377 if pmsg != nil {
5378 s.Errorf("Received an error looking up message with sequence %d for consumer '%s > %s > %s': %v",
5379 pmsg.seq, o.mset.acc, stream, o.cfg.Name, err)
5380 } else {
5381 s.Errorf("Received an error looking up message for consumer '%s > %s > %s': %v",
5382 o.mset.acc, stream, o.cfg.Name, err)
5383 }
5384 goto waitForMsgs
5385 }
5386 }
5387
5388 // Update our cached num pending here first.
5389 if dc == 1 {
5390 o.npc--
5391 }
5392 // Pre-calculate ackReply
5393 ackReply = o.ackReply(pmsg.seq, o.dseq, dc, pmsg.ts, o.numPending())
5394
5395 // If headers only do not send msg payload.
5396 // Add in msg size itself as header.
5397 if o.cfg.HeadersOnly {
5398 convertToHeadersOnly(pmsg)
5399 }
5400 // Calculate payload size. This can be calculated on client side.
5401 // We do not include transport subject here since not generally known on client.
5402 sz = len(pmsg.subj) + len(ackReply) + len(pmsg.hdr) + len(pmsg.msg)
5403
5404 if o.isPushMode() {
5405 dsubj = o.dsubj
5406 } else if wr := o.nextWaiting(sz); wr != nil {
5407 wrn, wrb = wr.n, wr.b
5408 dsubj = wr.reply
5409 if o.cfg.PriorityPolicy == PriorityPinnedClient {
5410 pmsg.hdr = genHeader(pmsg.hdr, JSPullRequestNatsPinId, o.currentPinId)
5411 pmsg.buf = append(pmsg.hdr, pmsg.msg...)
5412 sz = len(pmsg.subj) + len(ackReply) + len(pmsg.hdr) + len(pmsg.msg)
5413 }
5414 if done := wr.recycleIfDone(); done && o.node != nil {
5415 o.removeClusterPendingRequest(dsubj)
5416 } else if !done && wr.hb > 0 {
5417 wr.hbt = time.Now().Add(wr.hb)
5418 }
5419 } else {
5420 // We will redo this one as long as this is not a redelivery.
5421 // Need to also test that this is not going backwards since if
5422 // we fail to deliver we can end up here from rdq but we do not
5423 // want to decrement o.sseq if that is the case.
5424 if dc == 1 && pmsg.seq == o.sseq-1 {
5425 o.sseq--
5426 o.npc++
5427 } else if !o.onRedeliverQueue(pmsg.seq) {
5428 // We are not on the rdq so decrement the delivery count
5429 // and add it back.
5430 o.decDeliveryCount(pmsg.seq)
5431 o.addToRedeliverQueue(pmsg.seq)
5432 }
5433 pmsg.returnToPool()
5434 pmsg = nil
5435 goto waitForMsgs
5436 }
5437
5438 // If we are in a replay scenario and have not caught up check if we need to delay here.
5439 if o.replay && lts > 0 {
5440 if delay = time.Duration(pmsg.ts - lts); delay > time.Millisecond {
5441 o.mu.Unlock()
5442 select {
5443 case <-qch:
5444 pmsg.returnToPool()
5445 pmsg = nil
5446 return
5447 case <-time.After(delay):
5448 }
5449 o.mu.Lock()
5450 }
5451 }
5452
5453 // Track this regardless.
5454 lts = pmsg.ts
5455
5456 // If we have a rate limit set make sure we check that here.
5457 if o.rlimit != nil {
5458 now := time.Now()
5459 r := o.rlimit.ReserveN(now, sz)
5460 delay := r.DelayFrom(now)
5461 if delay > 0 {
5462 o.mu.Unlock()
5463 select {
5464 case <-qch:
5465 pmsg.returnToPool()
5466 pmsg = nil
5467 return
5468 case <-time.After(delay):
5469 }
5470 o.mu.Lock()
5471 }
5472 }
5473
5474 // Do actual delivery.
5475 o.deliverMsg(dsubj, ackReply, pmsg, dc, rp)
5476
5477 // If given request fulfilled batch size, but there are still pending bytes, send information about it.
5478 if wrn <= 0 && wrb > 0 {
5479 msg := fmt.Appendf(nil, JsPullRequestRemainingBytesT, JSPullRequestPendingMsgs, wrn, JSPullRequestPendingBytes, wrb)
5480 o.outq.send(newJSPubMsg(dsubj, _EMPTY_, _EMPTY_, msg, nil, nil, 0))
5481 }
5482 // Reset our idle heartbeat timer if set.
5483 if hb != nil {
5484 hb.Reset(hbd)
5485 }
5486
5487 o.mu.Unlock()
5488 continue
5489
5490 waitForMsgs:
5491 // If we were in a replay state check to see if we are caught up. If so clear.
5492 if o.replay && o.sseq > lseq {
5493 o.replay = false
5494 }
5495
5496 // Make sure to process any expired requests that are pending.
5497 var wrExp <-chan time.Time
5498 if o.isPullMode() {
5499 // Dont expire oneshots if we are here because of max ack pending limit.
5500 _, _, _, fexp := o.processWaiting(err != errMaxAckPending)
5501 if !fexp.IsZero() {
5502 expires := time.Until(fexp)
5503 if expires <= 0 {
5504 expires = time.Millisecond
5505 }
5506 wrExp = time.NewTimer(expires).C
5507 }
5508 }
5509
5510 // We will wait here for new messages to arrive.
5511 mch, odsubj := o.mch, o.cfg.DeliverSubject
5512 o.mu.Unlock()
5513
5514 select {
5515 case <-mch:
5516 // Messages are waiting.
5517 case interest := <-inch:
5518 // inch can be nil on pull-based, but then this will
5519 // just block and not fire.
5520 o.updateDeliveryInterest(interest)
5521 case <-qch:
5522 return
5523 case <-wrExp:
5524 o.mu.Lock()
5525 o.processWaiting(true)
5526 o.mu.Unlock()
5527 case <-hbc:
5528 if o.isActive() {
5529 o.mu.Lock()
5530 o.sendIdleHeartbeat(odsubj)
5531 // Send flow control on EOS if it's used for acknowledgements.
5532 if o.cfg.AckPolicy == AckFlowControl && len(o.pending) > 0 && o.fcid == _EMPTY_ {
5533 o.sendFlowControl()
5534 }
5535 o.mu.Unlock()
5536 }
5537 // Reset our idle heartbeat timer.
5538 hb.Reset(hbd)
5539 }
5540 }
5541 }
5542
5543 // Lock should be held.
5544 func (o *consumer) sendIdleHeartbeat(subj string) {
5545 const t = "NATS/1.0 100 Idle Heartbeat\r\n%s: %d\r\n%s: %d\r\n\r\n"
5546 sseq, dseq := o.sseq-1, o.dseq-1
5547 hdr := fmt.Appendf(nil, t, JSLastConsumerSeq, dseq, JSLastStreamSeq, sseq)
5548 if fcp := o.fcid; fcp != _EMPTY_ {
5549 // Add in that we are stalled on flow control here.
5550 addOn := fmt.Appendf(nil, "%s: %s\r\n\r\n", JSConsumerStalled, fcp)
5551 hdr = append(hdr[:len(hdr)-LEN_CR_LF], []byte(addOn)...)
5552 }
5553 o.outq.send(newJSPubMsg(subj, _EMPTY_, _EMPTY_, hdr, nil, nil, 0))
5554 }
5555
5556 func (o *consumer) ackReply(sseq, dseq, dc uint64, ts int64, pending uint64) string {
5557 if o.useV2Ack {
5558 return fmt.Sprintf(o.ackReplyT, dc, sseq, dseq, ts, pending)
5559 }
5560 return fmt.Sprintf(o.ackReplyOldT, dc, sseq, dseq, ts, pending)
5561 }
5562
5563 // Used mostly for testing. Sets max pending bytes for flow control setups.
5564 func (o *consumer) setMaxPendingBytes(limit int) {
5565 o.pblimit = limit
5566 o.maxpb = limit / 16
5567 if o.maxpb == 0 {
5568 o.maxpb = 1
5569 }
5570 }
5571
5572 // Does some sanity checks to see if we should re-calculate.
5573 // Since there is a race when decrementing when there is contention at the beginning of the stream.
5574 // The race is a getNextMsg skips a deleted msg, and then the decStreamPending call fires.
5575 // This does some quick sanity checks to see if we should re-calculate num pending.
5576 // Lock should be held.
5577 func (o *consumer) checkNumPending() (uint64, error) {
5578 if o.mset != nil && o.mset.store != nil {
5579 var state StreamState
5580 o.mset.store.FastState(&state)
5581 npc := o.numPending()
5582 // Make sure we can't report more messages than there are.
5583 // TODO(nat): It's not great that this means consumer info has side effects,
5584 // since we can't know whether anyone will call it or not. The previous num
5585 // pending calculation that this replaces had the same problem though.
5586 if o.sseq > state.LastSeq {
5587 o.npc = 0
5588 } else if npc > 0 {
5589 o.npc = int64(min(npc, state.Msgs, state.LastSeq-o.sseq+1))
5590 }
5591 }
5592 return o.numPending(), nil
5593 }
5594
5595 // Lock should be held.
5596 func (o *consumer) numPending() uint64 {
5597 if o.npc < 0 {
5598 return 0
5599 }
5600 return uint64(o.npc)
5601 }
5602
5603 // This will do a quick sanity check on num pending when we encounter
5604 // and EOF in the loop and gather.
5605 // Lock should be held.
5606 func (o *consumer) checkNumPendingOnEOF() {
5607 if o.mset == nil {
5608 return
5609 }
5610 var state StreamState
5611 o.mset.store.FastState(&state)
5612 if o.sseq > state.LastSeq && o.npc != 0 {
5613 // We know here we can reset our running state for num pending.
5614 o.npc, o.npf = 0, state.LastSeq
5615 }
5616 }
5617
5618 // Call into streamNumPending after acquiring the consumer lock.
5619 func (o *consumer) streamNumPendingLocked() (uint64, error) {
5620 o.mu.Lock()
5621 defer o.mu.Unlock()
5622 return o.streamNumPending()
5623 }
5624
5625 // Will force a set from the stream store of num pending on the consumer leader.
5626 // Depends on delivery policy, for last per subject we calculate differently.
5627 // Lock should be held.
5628 func (o *consumer) streamNumPending() (uint64, error) {
5629 if o.mset == nil || o.mset.store == nil || !o.isLeader() {
5630 o.npc, o.npf = 0, 0
5631 return 0, nil
5632 }
5633 npc, npf, err := o.calculateNumPending()
5634 if err != nil {
5635 return 0, err
5636 }
5637 o.npc, o.npf = int64(npc), npf
5638 return o.numPending(), nil
5639 }
5640
5641 // Will calculate num pending but only requires a read lock.
5642 // Depends on delivery policy, for last per subject we calculate differently.
5643 // At least RLock should be held.
5644 func (o *consumer) calculateNumPending() (npc, npf uint64, err error) {
5645 if o.mset == nil || o.mset.store == nil {
5646 return 0, 0, nil
5647 }
5648
5649 isLastPerSubject := o.cfg.DeliverPolicy == DeliverLastPerSubject
5650 filters, subjf := o.filters, o.subjf
5651
5652 if filters != nil {
5653 return o.mset.store.NumPendingMulti(o.sseq, filters, isLastPerSubject)
5654 } else if len(subjf) > 0 {
5655 filter := subjf[0].subject
5656 return o.mset.store.NumPending(o.sseq, filter, isLastPerSubject)
5657 }
5658 return o.mset.store.NumPending(o.sseq, _EMPTY_, isLastPerSubject)
5659 }
5660
5661 func convertToHeadersOnly(pmsg *jsPubMsg) {
5662 // If headers only do not send msg payload.
5663 // Add in msg size itself as header.
5664 hdr, msg := pmsg.hdr, pmsg.msg
5665 var bb bytes.Buffer
5666 if len(hdr) == 0 {
5667 bb.WriteString(hdrLine)
5668 } else {
5669 bb.Write(hdr)
5670 bb.Truncate(len(hdr) - LEN_CR_LF)
5671 }
5672 bb.WriteString(JSMsgSize)
5673 bb.WriteString(": ")
5674 bb.WriteString(strconv.FormatInt(int64(len(msg)), 10))
5675 bb.WriteString(CR_LF)
5676 bb.WriteString(CR_LF)
5677 // Replace underlying buf which we can use directly when we send.
5678 // TODO(dlc) - Probably just use directly when forming bytes.Buffer?
5679 pmsg.buf = pmsg.buf[:0]
5680 pmsg.buf = append(pmsg.buf, bb.Bytes()...)
5681 // Replace with new header.
5682 pmsg.hdr = pmsg.buf
5683 // Cancel msg payload
5684 pmsg.msg = nil
5685 }
5686
5687 // Deliver a msg to the consumer.
5688 // Lock should be held and o.mset validated to be non-nil.
5689 func (o *consumer) deliverMsg(dsubj, ackReply string, pmsg *jsPubMsg, dc uint64, rp RetentionPolicy) {
5690 if o.mset == nil {
5691 pmsg.returnToPool()
5692 return
5693 }
5694
5695 dseq := o.dseq
5696 o.dseq++
5697
5698 pmsg.dsubj, pmsg.reply, pmsg.o = dsubj, ackReply, o
5699 psz := pmsg.size()
5700
5701 if o.maxpb > 0 {
5702 o.pbytes += psz
5703 }
5704
5705 mset := o.mset
5706 ap := o.cfg.AckPolicy
5707
5708 // Cant touch pmsg after this sending so capture what we need.
5709 seq, ts := pmsg.seq, pmsg.ts
5710
5711 // Update delivered first.
5712 o.updateDelivered(dseq, seq, dc, ts)
5713
5714 if ap == AckNone {
5715 o.adflr = dseq
5716 o.asflr = seq
5717 } else {
5718 o.trackPending(seq, dseq)
5719 }
5720
5721 // Send message.
5722 if o.replicateDeliveries() {
5723 o.addReplicatedQueuedMsg(pmsg)
5724 } else {
5725 o.outq.send(pmsg)
5726 }
5727
5728 // Flow control.
5729 if o.maxpb > 0 && o.needFlowControl(psz) {
5730 o.sendFlowControl()
5731 }
5732
5733 // If pull mode and we have inactivity threshold, signaled by dthresh, update last activity.
5734 if o.isPullMode() && o.dthresh > 0 {
5735 o.waiting.last = time.Now()
5736 }
5737
5738 // If we are ack none and mset is interest only we should make sure stream removes interest.
5739 if ap == AckNone && rp != LimitsPolicy {
5740 if mset != nil && mset.ackq != nil && (o.node == nil || o.direct) {
5741 mset.ackq.push(seq)
5742 } else {
5743 o.updateAcks(dseq, seq, _EMPTY_)
5744 }
5745 }
5746 }
5747
5748 // replicateDeliveries returns whether deliveries should be replicated before sending them.
5749 // If we're replicated we MUST only send the message AFTER we've got quorum for updating
5750 // delivered state. Otherwise, we could be in an invalid state after a leader change.
5751 // We can send immediately if not replicated, not using acks, or using flow control (incompatible).
5752 // Lock should be held.
5753 func (o *consumer) replicateDeliveries() bool {
5754 return o.node != nil && o.cfg.AckPolicy != AckNone && !o.cfg.FlowControl
5755 }
5756
5757 func (o *consumer) needFlowControl(sz int) bool {
5758 if o.maxpb == 0 {
5759 return false
5760 }
5761 // Decide whether to send a flow control message which we will need the user to respond.
5762 // We send when we are over 50% of our current window limit.
5763 if o.fcid == _EMPTY_ && o.pbytes > o.maxpb/2 {
5764 return true
5765 }
5766 // Or, when acking based on flow control, we need to send it if we've hit the max pending limit earlier.
5767 if o.fcid == _EMPTY_ && o.cfg.AckPolicy == AckFlowControl && o.maxp > 0 && len(o.pending) >= o.maxp {
5768 return true
5769 }
5770 // If we have an existing outstanding FC, check to see if we need to expand the o.fcsz
5771 if o.fcid != _EMPTY_ && (o.pbytes-o.fcsz) >= o.maxpb {
5772 o.fcsz += sz
5773 }
5774 return false
5775 }
5776
5777 func (o *consumer) processFlowControl(_ *subscription, c *client, _ *Account, subj, _ string, rmsg []byte) {
5778 o.mu.Lock()
5779
5780 // Ignore if not the latest we have sent out.
5781 if subj != o.fcid {
5782 o.mu.Unlock()
5783 return
5784 }
5785
5786 // For slow starts and ramping up.
5787 if o.maxpb < o.pblimit {
5788 o.maxpb *= 2
5789 if o.maxpb > o.pblimit {
5790 o.maxpb = o.pblimit
5791 }
5792 }
5793
5794 // Update accounting.
5795 o.pbytes -= o.fcsz
5796 if o.pbytes < 0 {
5797 o.pbytes = 0
5798 }
5799 o.fcid, o.fcsz = _EMPTY_, 0
5800
5801 o.signalNewMessages()
5802 ackFlowControl := o.cfg.AckPolicy == AckFlowControl
5803 o.mu.Unlock()
5804
5805 if !ackFlowControl {
5806 return
5807 }
5808 hdr, _ := c.msgParts(rmsg)
5809 if len(hdr) > 0 {
5810 ldseq := parseInt64(sliceHeader(JSLastConsumerSeq, hdr))
5811 lsseq := parseInt64(sliceHeader(JSLastStreamSeq, hdr))
5812 if lsseq > 0 {
5813 // Delivered sequence is allowed to be zero as a response
5814 // to flow control without any deliveries.
5815 if ldseq <= 0 {
5816 ldseq = 0
5817 }
5818 o.processAckMsg(uint64(lsseq), uint64(ldseq), 1, _EMPTY_, false)
5819 }
5820 }
5821 }
5822
5823 // Lock should be held.
5824 func (o *consumer) fcReply() string {
5825 var sb strings.Builder
5826 if o.useV2Ack {
5827 sb.WriteString(o.fcPre)
5828 } else {
5829 sb.WriteString(o.fcPreOld)
5830 }
5831 sb.WriteString(o.stream)
5832 sb.WriteByte(btsep)
5833 sb.WriteString(o.name)
5834 sb.WriteByte(btsep)
5835 var b [4]byte
5836 rn := rand.Int63()
5837 for i, l := 0, rn; i < len(b); i++ {
5838 b[i] = digits[l%base]
5839 l /= base
5840 }
5841 sb.Write(b[:])
5842 return sb.String()
5843 }
5844
5845 // sendFlowControl will send a flow control packet to the consumer.
5846 // Lock should be held.
5847 func (o *consumer) sendFlowControl() {
5848 if !o.isPushMode() {
5849 return
5850 }
5851 subj, rply := o.cfg.DeliverSubject, o.fcReply()
5852 o.fcsz, o.fcid = o.pbytes, rply
5853 hdr := []byte("NATS/1.0 100 FlowControl Request\r\n\r\n")
5854 o.outq.send(newJSPubMsg(subj, _EMPTY_, rply, hdr, nil, nil, 0))
5855 }
5856
5857 // Tracks our outstanding pending acks. Only applicable to AckExplicit mode.
5858 // Lock should be held.
5859 func (o *consumer) trackPending(sseq, dseq uint64) {
5860 if o.pending == nil {
5861 o.pending = make(map[uint64]*Pending)
5862 }
5863
5864 now := time.Now()
5865 if p, ok := o.pending[sseq]; ok {
5866 // Update timestamp but keep original consumer delivery sequence.
5867 // So do not update p.Sequence.
5868 p.Timestamp = now.UnixNano()
5869 } else {
5870 o.pending[sseq] = &Pending{dseq, now.UnixNano()}
5871 }
5872
5873 // We could have a backoff that set a timer higher than what we need for this message.
5874 // In that case, reset to lowest backoff required for a message redelivery.
5875 minDelay := o.ackWait(0)
5876 if l := len(o.cfg.BackOff); l > 0 {
5877 bi := int(o.rdc[sseq])
5878 if bi < 0 {
5879 bi = 0
5880 } else if bi >= l {
5881 bi = l - 1
5882 }
5883 minDelay = o.ackWait(o.cfg.BackOff[bi])
5884 }
5885 minDeadline := now.Add(minDelay)
5886 if o.ptmr == nil || o.ptmrEnd.After(minDeadline) {
5887 o.resetPtmr(minDelay)
5888 }
5889 }
5890
5891 // Credit back a failed delivery.
5892 // lock should be held.
5893 func (o *consumer) creditWaitingRequest(reply string) {
5894 wq := o.waiting
5895 for wr := wq.head; wr != nil; wr = wr.next {
5896 if wr.reply == reply {
5897 wr.n++
5898 wr.d--
5899 return
5900 }
5901 }
5902 }
5903
5904 // didNotDeliver is called when a delivery for a consumer message failed.
5905 // Depending on our state, we will process the failure.
5906 func (o *consumer) didNotDeliver(seq uint64, subj string) {
5907 o.mu.Lock()
5908 mset := o.mset
5909 if mset == nil {
5910 o.mu.Unlock()
5911 return
5912 }
5913 // Adjust back deliver count.
5914 o.decDeliveryCount(seq)
5915
5916 var checkDeliveryInterest bool
5917 if o.isPushMode() {
5918 o.active = false
5919 checkDeliveryInterest = true
5920 } else if o.pending != nil {
5921 // Good chance we did not deliver because no interest so force a check.
5922 o.processWaiting(false)
5923 // If it is still there credit it back.
5924 o.creditWaitingRequest(subj)
5925 // pull mode and we have pending.
5926 if _, ok := o.pending[seq]; ok {
5927 // We found this messsage on pending, we need
5928 // to queue it up for immediate redelivery since
5929 // we know it was not delivered
5930 if !o.onRedeliverQueue(seq) {
5931 o.addToRedeliverQueue(seq)
5932 if !o.waiting.isEmpty() {
5933 o.signalNewMessages()
5934 }
5935 }
5936 }
5937 }
5938 o.mu.Unlock()
5939
5940 if checkDeliveryInterest {
5941 localInterest := !o.hasNoLocalInterest()
5942 o.updateDeliveryInterest(localInterest)
5943 }
5944 }
5945
5946 // Lock should be held.
5947 func (o *consumer) addToRedeliverQueue(seqs ...uint64) {
5948 o.rdq = append(o.rdq, seqs...)
5949 for _, seq := range seqs {
5950 o.rdqi.Insert(seq)
5951 }
5952 }
5953
5954 // Lock should be held.
5955 func (o *consumer) hasRedeliveries() bool {
5956 return len(o.rdq) > 0
5957 }
5958
5959 func (o *consumer) getNextToRedeliver() uint64 {
5960 if len(o.rdq) == 0 {
5961 return 0
5962 }
5963 seq := o.rdq[0]
5964 if len(o.rdq) == 1 {
5965 o.rdq = nil
5966 o.rdqi.Empty()
5967 } else {
5968 o.rdq = append(o.rdq[:0], o.rdq[1:]...)
5969 o.rdqi.Delete(seq)
5970 }
5971 return seq
5972 }
5973
5974 // This checks if we already have this sequence queued for redelivery.
5975 // FIXME(dlc) - This is O(n) but should be fast with small redeliver size.
5976 // Lock should be held.
5977 func (o *consumer) onRedeliverQueue(seq uint64) bool {
5978 return o.rdqi.Exists(seq)
5979 }
5980
5981 // Remove a sequence from the redelivery queue.
5982 // Lock should be held.
5983 func (o *consumer) removeFromRedeliverQueue(seq uint64) bool {
5984 if !o.onRedeliverQueue(seq) {
5985 return false
5986 }
5987 for i, rseq := range o.rdq {
5988 if rseq == seq {
5989 if len(o.rdq) == 1 {
5990 o.rdq = nil
5991 o.rdqi.Empty()
5992 } else {
5993 o.rdq = append(o.rdq[:i], o.rdq[i+1:]...)
5994 o.rdqi.Delete(seq)
5995 }
5996 return true
5997 }
5998 }
5999 return false
6000 }
6001
6002 // Checks the pending messages.
6003 func (o *consumer) checkPending() {
6004 o.mu.Lock()
6005 defer o.mu.Unlock()
6006
6007 mset := o.mset
6008 ttl := int64(o.cfg.AckWait)
6009 // On stop, mset and timer will be nil.
6010 if o.closed || mset == nil || o.ptmr == nil || ttl == 0 {
6011 o.stopAndClearPtmr()
6012 return
6013 }
6014
6015 var shouldUpdateState bool
6016 var state StreamState
6017 mset.store.FastState(&state)
6018 fseq := state.FirstSeq
6019
6020 now := time.Now().UnixNano()
6021 next := int64(o.ackWait(0))
6022 // However, if there is backoff, initializes with the largest backoff.
6023 // It will be adjusted as needed.
6024 if l := len(o.cfg.BackOff); l > 0 {
6025 next = int64(o.cfg.BackOff[l-1])
6026 }
6027
6028 // Since we can update timestamps, we have to review all pending.
6029 // We will now bail if we see an ack pending inbound to us via o.awl.
6030 var expired []uint64
6031 check := len(o.pending) > 1024
6032 for seq, p := range o.pending {
6033 if check && atomic.LoadInt64(&o.awl) > 0 {
6034 o.resetPtmr(100 * time.Millisecond)
6035 return
6036 }
6037 // Check if these are no longer valid.
6038 if seq < fseq || seq <= o.asflr {
6039 delete(o.pending, seq)
6040 delete(o.rdc, seq)
6041 o.removeFromRedeliverQueue(seq)
6042 shouldUpdateState = true
6043 // Check if we need to move ack floors.
6044 if seq > o.asflr {
6045 o.asflr = seq
6046 }
6047 if p.Sequence > o.adflr {
6048 o.adflr = p.Sequence
6049 }
6050 continue
6051 }
6052 elapsed, deadline := now-p.Timestamp, ttl
6053 if len(o.cfg.BackOff) > 0 {
6054 // This is ok even if o.rdc is nil, we would get dc == 0, which is what we want.
6055 dc := int(o.rdc[seq])
6056 if dc < 0 {
6057 // Prevent consumer backoff from going backwards.
6058 dc = 0
6059 }
6060 // This will be the index for the next backoff, will set to last element if needed.
6061 nbi := dc + 1
6062 if dc+1 >= len(o.cfg.BackOff) {
6063 dc = len(o.cfg.BackOff) - 1
6064 nbi = dc
6065 }
6066 deadline = int64(o.cfg.BackOff[dc])
6067 // Set `next` to the next backoff (if smaller than current `next` value).
6068 if nextBackoff := int64(o.cfg.BackOff[nbi]); nextBackoff < next {
6069 next = nextBackoff
6070 }
6071 }
6072 if elapsed >= deadline {
6073 // We will check if we have hit our max deliveries. Previously we would do this on getNextMsg() which
6074 // worked well for push consumers, but with pull based consumers would require a new pull request to be
6075 // present to process and redelivered could be reported incorrectly.
6076 if !o.onRedeliverQueue(seq) && !o.hasMaxDeliveries(seq) {
6077 expired = append(expired, seq)
6078 }
6079 } else if deadline-elapsed < next {
6080 // Update when we should fire next.
6081 next = deadline - elapsed
6082 }
6083 }
6084
6085 if len(expired) > 0 {
6086 // We need to sort.
6087 slices.Sort(expired)
6088 o.addToRedeliverQueue(expired...)
6089 // Now we should update the timestamp here since we are redelivering.
6090 // We will use an incrementing time to preserve order for any other redelivery.
6091 off := now - o.pending[expired[0]].Timestamp
6092 for _, seq := range expired {
6093 if p, ok := o.pending[seq]; ok {
6094 p.Timestamp += off
6095 }
6096 }
6097 o.signalNewMessages()
6098 }
6099
6100 if len(o.pending) > 0 {
6101 o.resetPtmr(time.Duration(next))
6102 } else {
6103 // Make sure to stop timer and clear out any re delivery queues
6104 o.stopAndClearPtmr()
6105 o.rdq = nil
6106 o.rdqi.Empty()
6107 o.pending = nil
6108 // Mimic behavior in processAckMsg when pending is empty.
6109 o.adflr, o.asflr = o.dseq-1, o.sseq-1
6110 }
6111
6112 // Update our state if needed.
6113 if shouldUpdateState {
6114 if err := o.writeStoreStateUnlocked(); err != nil && o.srv != nil && o.mset != nil && !o.closed {
6115 s, acc, mset, name := o.srv, o.acc, o.mset, o.name
6116 s.Warnf("Consumer '%s > %s > %s' error on write store state from check pending: %v", acc, mset.getCfgName(), name, err)
6117 }
6118 }
6119 }
6120
6121 // SeqFromReply will extract a sequence number from a reply subject.
6122 func (o *consumer) seqFromReply(reply string) uint64 {
6123 _, dseq, _, _, _ := ackReplyInfo(reply)
6124 return dseq
6125 }
6126
6127 // StreamSeqFromReply will extract the stream sequence from the reply subject.
6128 func (o *consumer) streamSeqFromReply(reply string) uint64 {
6129 sseq, _, _, _, _ := ackReplyInfo(reply)
6130 return sseq
6131 }
6132
6133 // Quick parser for positive numbers in ack reply encoding.
6134 func parseAckReplyNum(d string) (n int64) {
6135 if len(d) == 0 {
6136 return -1
6137 }
6138 for _, dec := range d {
6139 if dec < asciiZero || dec > asciiNine {
6140 return -1
6141 }
6142 n = n*10 + (int64(dec) - asciiZero)
6143 }
6144 return n
6145 }
6146
6147 const (
6148 expectedNumReplyTokensV1 = 9
6149 expectedNumReplyTokensV2 = 11
6150 )
6151
6152 // Grab encoded information in the reply subject for a delivered message.
6153 func ackReplyInfo(subject string) (sseq, dseq, dc uint64, ts int64, pending uint64) {
6154 tsa := [expectedNumReplyTokensV2]string{}
6155 start, tokens := 0, tsa[:0]
6156 for i := 0; i < len(subject); i++ {
6157 if subject[i] == btsep {
6158 tokens = append(tokens, subject[start:i])
6159 start = i + 1
6160 }
6161 }
6162 tokens = append(tokens, subject[start:])
6163 if (len(tokens) != expectedNumReplyTokensV1 && len(tokens) < expectedNumReplyTokensV2) || tokens[0] != "$JS" || tokens[1] != "ACK" {
6164 return 0, 0, 0, 0, 0
6165 }
6166 offset := 2
6167 if len(tokens) >= expectedNumReplyTokensV2 {
6168 offset = 4
6169 }
6170 // TODO(dlc) - Should we error if we do not match consumer name?
6171 // stream is tokens[offset], consumer is offset+1.
6172 dc = uint64(parseAckReplyNum(tokens[offset+2]))
6173 sseq, dseq = uint64(parseAckReplyNum(tokens[offset+3])), uint64(parseAckReplyNum(tokens[offset+4]))
6174 ts = parseAckReplyNum(tokens[offset+5])
6175 pending = uint64(parseAckReplyNum(tokens[offset+6]))
6176
6177 return sseq, dseq, dc, ts, pending
6178 }
6179
6180 // NextSeq returns the next delivered sequence number for this consumer.
6181 func (o *consumer) nextSeq() uint64 {
6182 o.mu.RLock()
6183 dseq := o.dseq
6184 o.mu.RUnlock()
6185 return dseq
6186 }
6187
6188 // Used to hold skip list when deliver policy is last per subject.
6189 type lastSeqSkipList struct {
6190 resume uint64
6191 seqs []uint64
6192 }
6193
6194 // Let's us know we have a skip list, which is for deliver last per subject and we are just starting.
6195 // Lock should be held.
6196 func (o *consumer) hasSkipListPending() bool {
6197 return o.lss != nil && len(o.lss.seqs) > 0
6198 }
6199
6200 // reconcileStateWithStream reconciles consumer state when the stream has reverted
6201 // due to data loss (e.g., VM crash). This handles the case where consumer state
6202 // is ahead of the stream's last sequence.
6203 // Lock should be held.
6204 func (o *consumer) reconcileStateWithStream(streamLastSeq uint64) {
6205 // If an ack floor is higher than stream last sequence,
6206 // reset back down but keep the highest known sequences.
6207 if o.asflr > streamLastSeq {
6208 o.asflr = streamLastSeq
6209 // Delivery floor is one below the delivered sequence,
6210 // but if it is zero somehow, ensure we don't underflow.
6211 o.adflr = o.dseq
6212 if o.adflr > 0 {
6213 o.adflr--
6214 }
6215 o.pending = nil
6216 o.rdc = nil
6217 }
6218
6219 // Remove pending entries that are beyond the stream's last sequence
6220 if len(o.pending) > 0 {
6221 for seq := range o.pending {
6222 if seq > streamLastSeq {
6223 delete(o.pending, seq)
6224 }
6225 }
6226 }
6227
6228 // Remove redelivered entries that are beyond the stream's last sequence
6229 if len(o.rdc) > 0 {
6230 for seq := range o.rdc {
6231 if seq > streamLastSeq {
6232 delete(o.rdc, seq)
6233 }
6234 }
6235 }
6236
6237 // Update starting sequence and delivery sequence based on pending state
6238 if len(o.pending) == 0 {
6239 o.sseq = o.asflr + 1
6240 o.dseq = o.adflr + 1
6241 } else {
6242 // Find highest stream sequence in pending
6243 var maxStreamSeq uint64
6244 var maxConsumerSeq uint64
6245
6246 for streamSeq, p := range o.pending {
6247 if streamSeq > maxStreamSeq {
6248 maxStreamSeq = streamSeq
6249 }
6250 if p.Sequence > maxConsumerSeq {
6251 maxConsumerSeq = p.Sequence
6252 }
6253 }
6254
6255 // Set next sequences based on highest pending
6256 o.sseq = maxStreamSeq + 1
6257 o.dseq = maxConsumerSeq + 1
6258 }
6259 }
6260
6261 // Will select the starting sequence.
6262 func (o *consumer) selectStartingSeqNo() error {
6263 if o.mset == nil || o.mset.store == nil {
6264 o.sseq = 1
6265 } else {
6266 var state StreamState
6267 o.mset.store.FastState(&state)
6268 if o.cfg.OptStartSeq == 0 {
6269 if o.cfg.DeliverPolicy == DeliverAll {
6270 o.sseq = state.FirstSeq
6271 } else if o.cfg.DeliverPolicy == DeliverLast {
6272 if o.subjf == nil {
6273 o.sseq = state.LastSeq
6274 } else {
6275 // If we are partitioned here this will be properly set when we become leader.
6276 for _, filter := range o.subjf {
6277 ss, err := o.mset.store.FilteredState(1, filter.subject)
6278 if err != nil {
6279 return err
6280 }
6281 if ss.Last > o.sseq {
6282 o.sseq = ss.Last
6283 }
6284 }
6285 }
6286 } else if o.cfg.DeliverPolicy == DeliverLastPerSubject {
6287 // If our parent stream is set to max msgs per subject of 1 this is just
6288 // a normal consumer at this point. We can avoid any heavy lifting.
6289 o.mset.cfgMu.RLock()
6290 mmp := o.mset.cfg.MaxMsgsPer
6291 o.mset.cfgMu.RUnlock()
6292 if mmp == 1 {
6293 o.sseq = state.FirstSeq
6294 } else {
6295 filters := make([]string, 0, len(o.subjf))
6296 if o.subjf == nil {
6297 filters = append(filters, o.cfg.FilterSubject)
6298 } else {
6299 for _, filter := range o.subjf {
6300 filters = append(filters, filter.subject)
6301 }
6302 }
6303
6304 lss := &lastSeqSkipList{resume: state.LastSeq}
6305 lss.seqs, _ = o.mset.store.MultiLastSeqs(filters, 0, 0)
6306
6307 if len(lss.seqs) == 0 {
6308 o.sseq = state.LastSeq
6309 } else {
6310 o.sseq = lss.seqs[0]
6311 }
6312 // Assign skip list.
6313 o.lss = lss
6314 }
6315 } else if o.cfg.OptStartTime != nil {
6316 // If we are here we are time based.
6317 // TODO(dlc) - Once clustered can't rely on this.
6318 o.sseq = o.mset.store.GetSeqFromTime(*o.cfg.OptStartTime)
6319 // Here we want to see if we are filtered, and if so possibly close the gap
6320 // to the nearest first given our starting sequence from time. This is so we do
6321 // not force the system to do a linear walk between o.sseq and the real first.
6322 if len(o.subjf) > 0 {
6323 nseq := state.LastSeq
6324 for _, filter := range o.subjf {
6325 // Use first sequence since this is more optimized atm.
6326 ss, err := o.mset.store.FilteredState(state.FirstSeq, filter.subject)
6327 if err != nil {
6328 return err
6329 }
6330 if ss.First >= o.sseq && ss.First < nseq {
6331 nseq = ss.First
6332 }
6333 }
6334 // Skip ahead if possible.
6335 if nseq > o.sseq && nseq < state.LastSeq {
6336 o.sseq = nseq
6337 }
6338 }
6339 } else {
6340 // DeliverNew
6341 o.sseq = state.LastSeq + 1
6342 }
6343 } else {
6344 o.sseq = o.cfg.OptStartSeq
6345 }
6346
6347 if state.FirstSeq == 0 && (o.cfg.Direct || o.cfg.OptStartSeq == 0) {
6348 // If the stream is empty, deliver only new.
6349 // But only if mirroring/sourcing, or start seq is unset, otherwise need to respect provided value.
6350 o.sseq = 1
6351 } else if o.sseq > state.LastSeq && (o.cfg.Direct || o.cfg.OptStartSeq == 0) {
6352 // If selected sequence is in the future, clamp back down.
6353 // But only if mirroring/sourcing, or start seq is unset, otherwise need to respect provided value.
6354 o.sseq = state.LastSeq + 1
6355 } else if o.sseq < state.FirstSeq {
6356 // If the first sequence is further ahead than the starting sequence,
6357 // there are no messages there anymore, so move the sequence up.
6358 o.sseq = state.FirstSeq
6359 }
6360 }
6361
6362 // Always set delivery sequence to 1.
6363 o.dseq = 1
6364 // Set ack delivery floor to delivery-1
6365 o.adflr = o.dseq - 1
6366 // Set ack store floor to store-1
6367 o.asflr = o.sseq - 1
6368 // Set our starting sequence state.
6369 // But only if we're not clustered, if clustered we propose upon becoming leader.
6370 o.mset.cfgMu.RLock()
6371 isR1 := o.cfg.replicas(&o.mset.cfg) == 1
6372 o.mset.cfgMu.RUnlock()
6373 if o.store != nil && o.sseq > 0 && isR1 {
6374 if err := o.store.SetStarting(o.sseq - 1); err != nil {
6375 return err
6376 }
6377 }
6378 return nil
6379 }
6380
6381 // Test whether a config represents a durable subscriber.
6382 func isDurableConsumer(config *ConsumerConfig) bool {
6383 return config != nil && config.Durable != _EMPTY_
6384 }
6385
6386 func (o *consumer) isDurable() bool {
6387 return o.cfg.Durable != _EMPTY_
6388 }
6389
6390 // Are we in push mode, delivery subject, etc.
6391 func (o *consumer) isPushMode() bool {
6392 return o.cfg.DeliverSubject != _EMPTY_
6393 }
6394
6395 func (o *consumer) isPullMode() bool {
6396 return o.cfg.DeliverSubject == _EMPTY_
6397 }
6398
6399 // Name returns the name of this consumer.
6400 func (o *consumer) String() string {
6401 o.mu.RLock()
6402 n := o.name
6403 o.mu.RUnlock()
6404 return n
6405 }
6406
6407 func createConsumerName() string {
6408 return getHash(nuid.Next())
6409 }
6410
6411 // Lock should be held.
6412 func (mset *stream) createStableConsumerHash() string {
6413 id := fmt.Sprintf("%s %s", mset.cfg.Name, mset.acc.Name)
6414 if domain := mset.srv.getOpts().JetStreamDomain; domain != _EMPTY_ {
6415 id = fmt.Sprintf("%s %s", id, domain)
6416 }
6417 return getHash(id)
6418 }
6419
6420 // Lock should be held.
6421 func (mset *stream) createSourcingConsumerHash(ssi *StreamSource, sources []*StreamSource) string {
6422 id := mset.createStableConsumerHash()
6423
6424 // If the stream sources contain the same stream at least twice, we use a more strict hash of
6425 // an ID that also contains filter subjects etc. If the stream name is only used once, we can
6426 // support the stable identifier above.
6427 var once bool
6428 for _, src := range sources {
6429 if src.Name == ssi.Name {
6430 if once {
6431 if ssi.iname == _EMPTY_ {
6432 ssi.setIndexName()
6433 }
6434 // Append identifying information of the filter subjects, etc. to make it unique
6435 id = fmt.Sprintf("%s %s", id, ssi.iname)
6436 break
6437 } else {
6438 once = true
6439 }
6440 }
6441 }
6442
6443 return getHash(id)
6444 }
6445
6446 // deleteConsumer will delete the consumer from this stream.
6447 func (mset *stream) deleteConsumer(o *consumer) error {
6448 return o.delete()
6449 }
6450
6451 func (o *consumer) getStream() *stream {
6452 o.mu.RLock()
6453 mset := o.mset
6454 o.mu.RUnlock()
6455 return mset
6456 }
6457
6458 func (o *consumer) streamName() string {
6459 o.mu.RLock()
6460 mset := o.mset
6461 o.mu.RUnlock()
6462 if mset != nil {
6463 return mset.name()
6464 }
6465 return _EMPTY_
6466 }
6467
6468 // Active indicates if this consumer is still active.
6469 func (o *consumer) isActive() bool {
6470 o.mu.RLock()
6471 active := o.active && o.mset != nil
6472 o.mu.RUnlock()
6473 return active
6474 }
6475
6476 // hasNoLocalInterest return true if we have no local interest.
6477 func (o *consumer) hasNoLocalInterest() bool {
6478 o.mu.RLock()
6479 interest := o.acc.sl.HasInterest(o.cfg.DeliverSubject)
6480 o.mu.RUnlock()
6481 return !interest
6482 }
6483
6484 // This is when the underlying stream has been purged.
6485 // sseq is the new first seq for the stream after purge.
6486 // Consumer lock should NOT be held but the parent stream
6487 // lock MUST be held.
6488 func (o *consumer) purge(sseq uint64, slseq uint64, isWider bool) {
6489 // Do not update our state unless we know we are the leader.
6490 if !o.isLeader() {
6491 return
6492 }
6493 // Signals all have been purged for this consumer.
6494 if sseq == 0 && !isWider {
6495 sseq = slseq + 1
6496 }
6497
6498 var store StreamStore
6499 if isWider {
6500 o.mu.RLock()
6501 if o.mset != nil {
6502 store = o.mset.store
6503 }
6504 o.mu.RUnlock()
6505 }
6506
6507 o.mu.Lock()
6508 // Do not go backwards
6509 if o.sseq < sseq {
6510 o.sseq = sseq
6511 }
6512
6513 if o.asflr < sseq {
6514 o.asflr = sseq - 1
6515 // We need to remove those no longer relevant from pending.
6516 for seq, p := range o.pending {
6517 if seq <= o.asflr {
6518 if p.Sequence > o.adflr {
6519 o.adflr = p.Sequence
6520 if o.adflr > o.dseq {
6521 o.dseq = o.adflr
6522 }
6523 }
6524 delete(o.pending, seq)
6525 delete(o.rdc, seq)
6526 o.updateAcks(p.Sequence, seq, _EMPTY_)
6527 // rdq handled below.
6528 } else if isWider && store != nil {
6529 // Our filtered subject, which could be all, is wider than the underlying purge.
6530 // We need to check if the pending items left are still valid.
6531 var smv StoreMsg
6532 if _, err := store.LoadMsg(seq, &smv); err == errDeletedMsg || err == ErrStoreMsgNotFound {
6533 if p.Sequence > o.adflr {
6534 o.adflr = p.Sequence
6535 if o.adflr > o.dseq {
6536 o.dseq = o.adflr
6537 }
6538 }
6539 delete(o.pending, seq)
6540 delete(o.rdc, seq)
6541 o.updateAcks(p.Sequence, seq, _EMPTY_)
6542 }
6543 }
6544 }
6545 }
6546
6547 // This means we can reset everything at this point.
6548 if len(o.pending) == 0 {
6549 o.pending, o.rdc = nil, nil
6550 o.adflr, o.asflr = o.dseq-1, o.sseq-1
6551 }
6552
6553 // We need to remove all those being queued for redelivery under o.rdq
6554 if len(o.rdq) > 0 {
6555 rdq := o.rdq
6556 o.rdq = nil
6557 o.rdqi.Empty()
6558 for _, sseq := range rdq {
6559 if sseq >= o.sseq {
6560 o.addToRedeliverQueue(sseq)
6561 }
6562 }
6563 }
6564 // Grab some info in case of error below.
6565 s, acc, mset, name := o.srv, o.acc, o.mset, o.name
6566 o.mu.Unlock()
6567
6568 if err := o.writeStoreState(); err != nil && s != nil && mset != nil {
6569 s.Warnf("Consumer '%s > %s > %s' error on write store state from purge: %v", acc, mset.nameLocked(false), name, err)
6570 }
6571 }
6572
6573 func stopAndClearTimer(tp **time.Timer) {
6574 if *tp == nil {
6575 return
6576 }
6577 // Will get drained in normal course, do not try to
6578 // drain here.
6579 (*tp).Stop()
6580 *tp = nil
6581 }
6582
6583 // Stop will shutdown the consumer for the associated stream.
6584 func (o *consumer) stop() error {
6585 return o.stopWithFlags(false, false, true, false)
6586 }
6587
6588 func (o *consumer) deleteWithoutAdvisory() error {
6589 return o.stopWithFlags(true, false, true, false)
6590 }
6591
6592 // Delete will delete the consumer for the associated stream and send advisories.
6593 func (o *consumer) delete() error {
6594 return o.stopWithFlags(true, false, true, true)
6595 }
6596
6597 // To test for closed state.
6598 func (o *consumer) isClosed() bool {
6599 o.mu.RLock()
6600 defer o.mu.RUnlock()
6601 return o.closed
6602 }
6603
6604 func (o *consumer) stopWithFlags(dflag, sdflag, doSignal, advisory bool) error {
6605 // If dflag is true determine if we are still assigned.
6606 var isAssigned bool
6607 if dflag {
6608 o.mu.RLock()
6609 acc, stream, consumer := o.acc, o.stream, o.name
6610 isClustered := o.js != nil && o.js.isClustered()
6611 o.mu.RUnlock()
6612 if isClustered {
6613 // Grab jsa to check assignment.
6614 var jsa *jsAccount
6615 if acc != nil {
6616 // Need lock here to avoid data race.
6617 acc.mu.RLock()
6618 jsa = acc.js
6619 acc.mu.RUnlock()
6620 }
6621 if jsa != nil {
6622 isAssigned = jsa.consumerAssigned(stream, consumer)
6623 }
6624 }
6625 }
6626
6627 o.mu.Lock()
6628 if o.closed {
6629 o.mu.Unlock()
6630 return nil
6631 }
6632 o.closed = true
6633
6634 // Signal to the monitor loop.
6635 // Can't use only qch here, since that's used when stepping down as a leader.
6636 if o.mqch != nil {
6637 close(o.mqch)
6638 o.mqch = nil
6639 }
6640
6641 // Check if we are the leader and are being deleted (as a node).
6642 if dflag && o.isLeader() {
6643 // If we are clustered and node leader (probable from above), stepdown.
6644 if node := o.node; node != nil {
6645 node.StepDown()
6646 }
6647
6648 // dflag does not necessarily mean that the consumer is being deleted,
6649 // just that the consumer node is being removed from this peer, so we
6650 // send delete advisories only if we are no longer assigned at the meta layer,
6651 // or we are not clustered.
6652 if !isAssigned && advisory {
6653 o.sendDeleteAdvisoryLocked()
6654 }
6655 if o.isPullMode() {
6656 // Release any pending.
6657 o.releaseAnyPendingRequests(isAssigned)
6658 }
6659 }
6660
6661 if o.qch != nil {
6662 close(o.qch)
6663 o.qch = nil
6664 }
6665
6666 a := o.acc
6667 store := o.store
6668 mset := o.mset
6669 o.mset = nil
6670 o.active = false
6671 o.unsubscribe(o.ackSubOld)
6672 o.unsubscribe(o.ackSub)
6673 o.unsubscribe(o.reqSub)
6674 o.unsubscribe(o.resetSub)
6675 o.unsubscribe(o.fcSubOld)
6676 o.unsubscribe(o.fcSub)
6677 o.ackSubOld = nil
6678 o.ackSub = nil
6679 o.reqSub = nil
6680 o.resetSub = nil
6681 o.fcSubOld = nil
6682 o.fcSub = nil
6683 if o.infoSub != nil {
6684 o.srv.sysUnsubscribe(o.infoSub)
6685 o.infoSub = nil
6686 }
6687 c := o.client
6688 o.client = nil
6689 sysc := o.sysc
6690 o.sysc = nil
6691 o.stopAndClearPtmr()
6692 stopAndClearTimer(&o.dtmr)
6693 stopAndClearTimer(&o.gwdtmr)
6694 delivery := o.cfg.DeliverSubject
6695 o.waiting = nil
6696 // Break us out of the readLoop.
6697 if doSignal {
6698 o.signalNewMessages()
6699 }
6700 n := o.node
6701 qgroup := o.cfg.DeliverGroup
6702 o.ackMsgs.unregister()
6703 if o.nextMsgReqs != nil {
6704 o.nextMsgReqs.unregister()
6705 }
6706
6707 // For cleaning up the node assignment.
6708 var ca *consumerAssignment
6709 if dflag {
6710 ca = o.ca
6711 }
6712 js := o.js
6713 o.mu.Unlock()
6714
6715 if c != nil {
6716 c.closeConnection(ClientClosed)
6717 }
6718 if sysc != nil {
6719 sysc.closeConnection(ClientClosed)
6720 }
6721
6722 if delivery != _EMPTY_ {
6723 a.sl.clearNotification(delivery, qgroup, o.inch)
6724 }
6725
6726 var rp RetentionPolicy
6727 if mset != nil {
6728 mset.mu.Lock()
6729 mset.removeConsumer(o)
6730 // No need for cfgMu's lock since mset.mu.Lock superseeds it.
6731 rp = mset.cfg.Retention
6732 mset.mu.Unlock()
6733 }
6734
6735 // Cleanup messages that lost interest.
6736 if dflag && rp == InterestPolicy {
6737 o.cleanupNoInterestMessages(mset, true)
6738 }
6739
6740 // Cluster cleanup.
6741 if n != nil {
6742 if dflag {
6743 n.Delete()
6744 } else {
6745 n.Stop()
6746 }
6747 }
6748
6749 if ca != nil {
6750 js.mu.Lock()
6751 if ca.Group != nil {
6752 ca.Group.node = nil
6753 }
6754 js.mu.Unlock()
6755 }
6756
6757 // Clean up our store.
6758 var err error
6759 if store != nil {
6760 if dflag {
6761 if sdflag {
6762 err = store.StreamDelete()
6763 } else {
6764 err = store.Delete()
6765 }
6766 } else {
6767 err = store.Stop()
6768 }
6769 } else if dflag {
6770 // If there's no store (for example, when it's offline), manually delete the directories.
6771 o.mu.RLock()
6772 stream, consumer := o.stream, o.name
6773 o.mu.RUnlock()
6774 accDir := filepath.Join(js.config.StoreDir, a.GetName())
6775 consumersDir := filepath.Join(accDir, streamsDir, stream, consumerDir)
6776 os.RemoveAll(filepath.Join(consumersDir, consumer))
6777 }
6778
6779 return err
6780 }
6781
6782 // We need to optionally remove all messages since we are interest based retention.
6783 // We will do this consistently on all replicas. Note that if in clustered mode the non-leader
6784 // consumers will need to restore state first.
6785 // ignoreInterest marks whether the consumer should be ignored when determining interest.
6786 // No lock held on entry.
6787 func (o *consumer) cleanupNoInterestMessages(mset *stream, ignoreInterest bool) {
6788 o.mu.Lock()
6789 if !o.isLeader() {
6790 o.readStoredState()
6791 }
6792 start := o.asflr
6793 o.mu.Unlock()
6794
6795 // Make sure we start at worst with first sequence in the stream.
6796 state := mset.state()
6797 if start < state.FirstSeq {
6798 start = state.FirstSeq
6799 }
6800 stop := state.LastSeq
6801
6802 // Consumer's interests are ignored by default. If we should not ignore interest, unset.
6803 co := o
6804 if !ignoreInterest {
6805 co = nil
6806 }
6807
6808 var rmseqs []uint64
6809 mset.mu.RLock()
6810
6811 // If over this amount of messages to check, optimistically call to checkInterestState().
6812 // It will not always do the right thing in removing messages that lost interest, but ensures
6813 // we don't degrade performance by doing a linear scan through the whole stream.
6814 // Messages might need to expire based on limits to be cleaned up.
6815 // TODO(dlc) - Better way?
6816 const bailThresh = 100_000
6817
6818 // Check if we would be spending too much time here and defer to separate go routine.
6819 if len(mset.consumers) == 0 {
6820 mset.mu.RUnlock()
6821 mset.mu.Lock()
6822 defer mset.mu.Unlock()
6823 mset.store.Purge()
6824 var state StreamState
6825 mset.store.FastState(&state)
6826 mset.lseq = state.LastSeq
6827 // Also make sure we clear any pending acks.
6828 mset.clearAllPreAcksBelowFloor(state.FirstSeq)
6829 return
6830 } else if stop-start > bailThresh {
6831 mset.mu.RUnlock()
6832 go mset.checkInterestState()
6833 return
6834 }
6835
6836 mset.mu.RUnlock()
6837 mset.mu.Lock()
6838 for seq := start; seq <= stop; seq++ {
6839 if mset.noInterest(seq, co) {
6840 rmseqs = append(rmseqs, seq)
6841 }
6842 }
6843 mset.mu.Unlock()
6844
6845 // These can be removed.
6846 for _, seq := range rmseqs {
6847 mset.store.RemoveMsg(seq)
6848 }
6849 }
6850
6851 // Check that we do not form a cycle by delivering to a delivery subject
6852 // that is part of the interest group.
6853 func deliveryFormsCycle(cfg *StreamConfig, deliverySubject string) bool {
6854 for _, subject := range cfg.Subjects {
6855 if subjectIsSubsetMatch(deliverySubject, subject) {
6856 return true
6857 }
6858 }
6859 return false
6860 }
6861
6862 // switchToEphemeral is called on startup when recovering ephemerals.
6863 func (o *consumer) switchToEphemeral() {
6864 o.mu.Lock()
6865 o.cfg.Durable = _EMPTY_
6866 store, ok := o.store.(*consumerFileStore)
6867 interest := o.acc.sl.HasInterest(o.cfg.DeliverSubject)
6868 // Setup dthresh.
6869 o.updateInactiveThreshold(&o.cfg)
6870 o.updatePauseState(&o.cfg)
6871 o.mu.Unlock()
6872
6873 // Update interest
6874 o.updateDeliveryInterest(interest)
6875 // Write out new config
6876 if ok {
6877 store.updateConfig(o.cfg)
6878 }
6879 }
6880
6881 // RequestNextMsgSubject returns the subject to request the next message when in pull or worker mode.
6882 // Returns empty otherwise.
6883 func (o *consumer) requestNextMsgSubject() string {
6884 return o.nextMsgSubj
6885 }
6886
6887 func (o *consumer) decStreamPending(sseq uint64, subj string) {
6888 o.mu.Lock()
6889
6890 // Update our cached num pending only if we think deliverMsg has not done so.
6891 if sseq >= o.sseq && o.isFilteredMatch(subj) {
6892 o.npc--
6893 }
6894
6895 // Check if this message was pending.
6896 p, wasPending := o.pending[sseq]
6897 var rdc uint64
6898 if wasPending {
6899 rdc = o.deliveryCount(sseq)
6900 } else if _, ok := o.rdc[sseq]; ok && o.isLeader() {
6901 delete(o.rdc, sseq)
6902 // Pass 0 as the delivered sequence to only remove the redelivered state.
6903 o.updateAcks(0, sseq, _EMPTY_)
6904 }
6905
6906 o.mu.Unlock()
6907
6908 // If it was pending process it like an ack.
6909 if wasPending {
6910 // We could have the lock for the stream so do this in a go routine.
6911 // TODO(dlc) - We should do this with ipq vs naked go routines.
6912 go o.processTerm(sseq, p.Sequence, rdc, ackTermUnackedLimitsReason, _EMPTY_)
6913 }
6914 }
6915
6916 func (o *consumer) account() *Account {
6917 o.mu.RLock()
6918 a := o.acc
6919 o.mu.RUnlock()
6920 return a
6921 }
6922
6923 // Creates a sublist for consumer.
6924 // All subjects share the same callback.
6925 func (o *consumer) signalSubs() []string {
6926 o.mu.Lock()
6927 defer o.mu.Unlock()
6928
6929 if o.sigSubs != nil {
6930 return o.sigSubs
6931 }
6932
6933 if len(o.subjf) == 0 {
6934 subs := []string{fwcs}
6935 o.sigSubs = subs
6936 return subs
6937 }
6938
6939 subs := make([]string, 0, len(o.subjf))
6940 for _, filter := range o.subjf {
6941 subs = append(subs, filter.subject)
6942 }
6943 o.sigSubs = subs
6944 return subs
6945 }
6946
6947 // This is what will be called when our parent stream wants to kick us regarding a new message.
6948 // We know that this subject matches us by how the parent handles registering us with the signaling sublist,
6949 // but we must check if we are leader.
6950 // We do need the sequence of the message however and we use the msg as the encoded seq.
6951 func (o *consumer) processStreamSignal(seq uint64) {
6952 // We can get called here now when not leader, so bail fast
6953 // and without acquiring any locks.
6954 if !o.leader.Load() {
6955 return
6956 }
6957 o.mu.Lock()
6958 defer o.mu.Unlock()
6959 if o.mset == nil {
6960 return
6961 }
6962 if seq > o.npf {
6963 o.npc++
6964 }
6965 if seq < o.sseq {
6966 return
6967 }
6968 if o.isPushMode() && o.active || o.isPullMode() && !o.waiting.isEmpty() {
6969 o.signalNewMessages()
6970 }
6971 }
6972
6973 // Used to compare if two multiple filtered subject lists are equal.
6974 func subjectSliceEqual(slice1 []string, slice2 []string) bool {
6975 if len(slice1) != len(slice2) {
6976 return false
6977 }
6978 set2 := make(map[string]struct{}, len(slice2))
6979 for _, val := range slice2 {
6980 set2[val] = struct{}{}
6981 }
6982 for _, val := range slice1 {
6983 if _, ok := set2[val]; !ok {
6984 return false
6985 }
6986 }
6987 return true
6988 }
6989
6990 // Utility for simpler if conditions in Consumer config checks.
6991 // In future iteration, we can immediately create `o.subjf` and
6992 // use it to validate things.
6993 func gatherSubjectFilters(filter string, filters []string) []string {
6994 if filter != _EMPTY_ {
6995 filters = append(filters, filter)
6996 }
6997 // list of filters should never contain non-empty filter.
6998 return filters
6999 }
7000
7001 // shouldStartMonitor will return true if we should start a monitor
7002 // goroutine or will return false if one is already running.
7003 func (o *consumer) shouldStartMonitor() bool {
7004 // monitorMu is held across the monitorWg.Add below so that it cannot race
7005 // a concurrent monitorWg.Wait in stopMonitoring. It is taken before o.mu to
7006 // keep a consistent lock ordering.
7007 o.monitorMu.Lock()
7008 defer o.monitorMu.Unlock()
7009
7010 o.mu.Lock()
7011 if o.inMonitor {
7012 o.mu.Unlock()
7013 return false
7014 }
7015 o.inMonitor = true
7016 o.mu.Unlock()
7017
7018 o.monitorWg.Add(1)
7019 return true
7020 }
7021
7022 // Clear the monitor running state. The monitor goroutine should
7023 // call this in a defer to clean up on exit.
7024 func (o *consumer) clearMonitorRunning() {
7025 o.mu.Lock()
7026 defer o.mu.Unlock()
7027
7028 if o.inMonitor {
7029 o.monitorWg.Done()
7030 o.inMonitor = false
7031 }
7032 }
7033
7034 // stopMonitoring signals any running monitor goroutine to quit and waits for
7035 // it to fully exit.
7036 func (o *consumer) stopMonitoring() {
7037 // monitorMu is held across both the quit signal and the wait so that a
7038 // concurrent shouldStartMonitor cannot slip a new monitor generation in
7039 // between.
7040 o.monitorMu.Lock()
7041 defer o.monitorMu.Unlock()
7042 o.signalMonitorQuit()
7043 o.monitorWg.Wait()
7044 }
7045
7046 // Test whether we are in the monitor routine.
7047 func (o *consumer) isMonitorRunning() bool {
7048 o.mu.RLock()
7049 defer o.mu.RUnlock()
7050 return o.inMonitor
7051 }
7052
7053 // If we detect that our ackfloor is higher than the stream's last sequence, return this error.
7054 var errAckFloorHigherThanLastSeq = errors.New("consumer ack floor is higher than streams last sequence")
7055 var errAckFloorInvalid = errors.New("consumer ack floor is invalid")
7056
7057 // If we are a consumer of an interest or workqueue policy stream, process that state and make sure consistent.
7058 func (o *consumer) checkStateForInterestStream(ss *StreamState) error {
7059 o.mu.RLock()
7060 // See if we need to process this update if our parent stream is not a limits policy stream.
7061 mset := o.mset
7062 shouldProcessState := mset != nil && o.retention != LimitsPolicy
7063 if o.closed || !shouldProcessState || o.store == nil || ss == nil {
7064 o.mu.RUnlock()
7065 return nil
7066 }
7067 store := mset.store
7068 state, err := o.store.State()
7069
7070 filters, subjf, filter := o.filters, o.subjf, _EMPTY_
7071 var wc bool
7072 if filters == nil && subjf != nil {
7073 filter, wc = subjf[0].subject, subjf[0].hasWildcard
7074 }
7075 chkfloor := o.chkflr
7076 o.mu.RUnlock()
7077
7078 if err != nil {
7079 return err
7080 }
7081
7082 asflr := state.AckFloor.Stream
7083 // Protect ourselves against rolling backwards.
7084 if asflr&(1<<63) != 0 {
7085 return errAckFloorInvalid
7086 }
7087 dflr := asflr
7088 if len(state.Pending) > 0 && state.Delivered.Stream > dflr {
7089 dflr = state.Delivered.Stream
7090 }
7091
7092 // Check if the underlying stream's last sequence is less than our floor.
7093 // This can happen if the stream has been reset and has not caught up yet.
7094 if asflr > ss.LastSeq {
7095 return errAckFloorHigherThanLastSeq
7096 }
7097
7098 var smv StoreMsg
7099 var seq, nseq uint64
7100 // Start at first stream seq or a previous check floor, whichever is higher.
7101 // Note this will really help for interest retention, with WQ the loadNextMsg
7102 // gets us a long way already since it will skip deleted msgs not for our filter.
7103 fseq := ss.FirstSeq
7104 if chkfloor > fseq {
7105 fseq = chkfloor
7106 }
7107
7108 var retryAsflr uint64
7109 for seq = fseq; dflr > 0 && seq <= dflr; seq++ {
7110 if filters != nil {
7111 _, nseq, err = store.LoadNextMsgMulti(filters, seq, &smv)
7112 } else {
7113 _, nseq, err = store.LoadNextMsg(filter, wc, seq, &smv)
7114 }
7115 // if we advanced sequence update our seq. This can be on no error and EOF.
7116 if nseq > seq {
7117 seq = nseq
7118 }
7119 if err == nil {
7120 // Only ack though if no error and seq <= ack floor.
7121 if seq <= asflr {
7122 didRemove := mset.ackMsg(o, seq)
7123 // Removing the message could fail. For example if clustered since we need to propose it.
7124 // Overwrite retry floor (only the first time) to allow us to check next time if the removal was successful.
7125 if didRemove && retryAsflr == 0 {
7126 retryAsflr = seq
7127 }
7128 } else if seq <= dflr {
7129 // Store the first entry above our ack floor, so we don't need to look it up again on retryAsflr=0.
7130 if retryAsflr == 0 {
7131 retryAsflr = seq
7132 }
7133 // If we have pending, we will need to walk through to delivered in case we missed any of those acks as well.
7134 if _, ok := state.Pending[seq]; !ok {
7135 // The filters are already taken into account,
7136 mset.ackMsg(o, seq)
7137 }
7138 }
7139 } else if err == ErrStoreEOF {
7140 break
7141 }
7142 }
7143 // If retry floor was not overwritten, set to ack floor+1, we don't need to account for any retries below it.
7144 // However, our ack floor may be lower than the next message we can receive, so we correct it upward if needed.
7145 if retryAsflr == 0 {
7146 if filters != nil {
7147 _, nseq, err = store.LoadNextMsgMulti(filters, asflr+1, &smv)
7148 } else {
7149 _, nseq, err = store.LoadNextMsg(filter, wc, asflr+1, &smv)
7150 }
7151 if err == nil {
7152 retryAsflr = max(asflr+1, nseq)
7153 } else if err == ErrStoreEOF {
7154 retryAsflr = ss.LastSeq + 1
7155 }
7156 }
7157
7158 o.mu.Lock()
7159 // Update our check floor.
7160 // Check floor must never be greater than ack floor+1, otherwise subsequent calls to this function would skip work.
7161 if retryAsflr > o.chkflr {
7162 o.chkflr = retryAsflr
7163 }
7164 o.mu.Unlock()
7165 return nil
7166 }
7167
7168 func (o *consumer) resetPtmr(delay time.Duration) {
7169 // A delay of zero means it should be stopped.
7170 if delay == 0 {
7171 o.stopAndClearPtmr()
7172 return
7173 }
7174
7175 if o.ptmr == nil {
7176 o.ptmr = time.AfterFunc(delay, o.checkPending)
7177 } else {
7178 o.ptmr.Reset(delay)
7179 }
7180 o.ptmrEnd = time.Now().Add(delay)
7181 }
7182
7183 func (o *consumer) stopAndClearPtmr() {
7184 // If the end time is unset, short-circuit since the timer will already be stopped.
7185 if o.ptmrEnd.IsZero() {
7186 return
7187 }
7188 stopAndClearTimer(&o.ptmr)
7189 o.ptmrEnd = time.Time{}
7190 }
7191
7192 func (o *consumer) resetPendingDeliveries() {
7193 for _, pmsg := range o.pendingDeliveries {
7194 pmsg.returnToPool()
7195 }
7196 o.pendingDeliveries = nil
7197 for _, wd := range o.waitingDeliveries {
7198 wd.recycle()
7199 }
7200 o.waitingDeliveries = nil
7201 }