Debian Codegraph @

server/memstore.go

raw
1 // Copyright 2019-2025 The NATS Authors
2 // Licensed under the Apache License, Version 2.0 (the "License");
3 // you may not use this file except in compliance with the License.
4 // You may obtain a copy of the License at
5 //
6 // http://www.apache.org/licenses/LICENSE-2.0
7 //
8 // Unless required by applicable law or agreed to in writing, software
9 // distributed under the License is distributed on an "AS IS" BASIS,
10 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11 // See the License for the specific language governing permissions and
12 // limitations under the License.
13
14 package server
15
16 import (
17 crand "crypto/rand"
18 "encoding/binary"
19 "fmt"
20 "math"
21 "slices"
22 "sync"
23 "time"
24
25 "github.com/antithesishq/antithesis-sdk-go/assert"
26 "github.com/nats-io/nats-server/v2/server/ats"
27 "github.com/nats-io/nats-server/v2/server/avl"
28 "github.com/nats-io/nats-server/v2/server/gsl"
29 "github.com/nats-io/nats-server/v2/server/stree"
30 "github.com/nats-io/nats-server/v2/server/thw"
31 )
32
33 // TODO(dlc) - This is a fairly simplistic approach but should do for now.
34 type memStore struct {
35 mu sync.RWMutex
36 cfg StreamConfig
37 state StreamState
38 msgs map[uint64]*StoreMsg
39 fss *stree.SubjectTree[SimpleState]
40 dmap avl.SequenceSet
41 maxp int64
42 scb StorageUpdateHandler
43 rmcb StorageRemoveMsgHandler
44 pmsgcb ProcessJetStreamMsgHandler
45 ageChk *time.Timer // Timer to expire messages.
46 ageChkRun bool // Whether message expiration is currently running.
47 ageChkTime int64 // When the message expiration is scheduled to run.
48 consumers int
49 receivedAny bool
50 ttls *thw.HashWheel
51 scheduling *MsgScheduling
52 sdm *SDMMeta
53 }
54
55 func newMemStore(cfg *StreamConfig) (*memStore, error) {
56 if cfg == nil {
57 return nil, fmt.Errorf("config required")
58 }
59 if cfg.Storage != MemoryStorage {
60 return nil, fmt.Errorf("memStore requires memory storage type in config")
61 }
62 ms := &memStore{
63 msgs: make(map[uint64]*StoreMsg),
64 fss: stree.NewSubjectTree[SimpleState](),
65 maxp: cfg.MaxMsgsPer,
66 cfg: *cfg,
67 }
68 // Only create a THW if we're going to allow TTLs.
69 if cfg.AllowMsgTTL {
70 ms.ttls = thw.NewHashWheel()
71 }
72 if cfg.AllowMsgSchedules {
73 ms.scheduling = newMsgScheduling(ms.runMsgScheduling)
74 }
75 if cfg.FirstSeq > 0 {
76 if _, err := ms.purge(cfg.FirstSeq); err != nil {
77 return nil, err
78 }
79 }
80
81 // Register with access time service.
82 ats.Register()
83
84 return ms, nil
85 }
86
87 func (ms *memStore) UpdateConfig(cfg *StreamConfig) error {
88 if cfg == nil {
89 return fmt.Errorf("config required")
90 }
91 if cfg.Storage != MemoryStorage {
92 return fmt.Errorf("memStore requires memory storage type in config")
93 }
94
95 ms.mu.Lock()
96 ms.cfg = *cfg
97 // Create or delete the THW if needed.
98 if cfg.AllowMsgTTL && ms.ttls == nil {
99 ms.recoverTTLState()
100 } else if !cfg.AllowMsgTTL && ms.ttls != nil {
101 ms.ttls = nil
102 }
103 if cfg.AllowMsgSchedules && ms.scheduling == nil {
104 ms.recoverMsgSchedulingState()
105 } else if !cfg.AllowMsgSchedules && ms.scheduling != nil {
106 ms.scheduling = nil
107 }
108 // Limits checks and enforcement.
109 ms.enforceMsgLimit()
110 ms.enforceBytesLimit()
111 // Do age timers.
112 if ms.ageChk == nil && ms.cfg.MaxAge != 0 {
113 ms.startAgeChk()
114 }
115 if ms.ageChk != nil && ms.cfg.MaxAge == 0 {
116 ms.ageChk.Stop()
117 ms.ageChk = nil
118 ms.ageChkTime = 0
119 }
120 // Make sure to update MaxMsgsPer
121 if cfg.MaxMsgsPer < -1 {
122 cfg.MaxMsgsPer = -1
123 }
124 maxp := ms.maxp
125 ms.maxp = cfg.MaxMsgsPer
126 // If the value is smaller, or was unset before, we need to enforce that.
127 if ms.maxp > 0 && (maxp <= 0 || ms.maxp < maxp) {
128 lm := uint64(ms.maxp)
129 ms.fss.IterFast(func(subj []byte, ss *SimpleState) bool {
130 if ss.Msgs > lm {
131 ms.enforcePerSubjectLimit(bytesToString(subj), ss)
132 }
133 return true
134 })
135 }
136 ms.mu.Unlock()
137
138 if cfg.MaxAge != 0 || cfg.AllowMsgTTL {
139 ms.expireMsgs()
140 }
141 if cfg.AllowMsgSchedules {
142 ms.runMsgScheduling()
143 }
144 return nil
145 }
146
147 // Lock should be held.
148 func (ms *memStore) recoverTTLState() {
149 ms.ttls = thw.NewHashWheel()
150 if ms.state.Msgs == 0 {
151 return
152 }
153
154 var (
155 seq uint64
156 smv StoreMsg
157 sm *StoreMsg
158 )
159 defer ms.resetAgeChk(0)
160 for sm, seq, _ = ms.loadNextMsgLocked(fwcs, true, 0, &smv); sm != nil; sm, seq, _ = ms.loadNextMsgLocked(fwcs, true, seq+1, &smv) {
161 if len(sm.hdr) == 0 {
162 continue
163 }
164 if ttl, _ := getMessageTTL(sm.hdr); ttl > 0 {
165 expires := time.Duration(sm.ts) + (time.Second * time.Duration(ttl))
166 ms.ttls.Add(seq, int64(expires))
167 }
168 }
169 }
170
171 // Lock should be held.
172 func (ms *memStore) recoverMsgSchedulingState() {
173 ms.scheduling = newMsgScheduling(ms.runMsgScheduling)
174 if ms.state.Msgs == 0 {
175 return
176 }
177
178 var (
179 seq uint64
180 smv StoreMsg
181 sm *StoreMsg
182 )
183 defer ms.scheduling.resetTimer()
184 for sm, seq, _ = ms.loadNextMsgLocked(fwcs, true, 0, &smv); sm != nil; sm, seq, _ = ms.loadNextMsgLocked(fwcs, true, seq+1, &smv) {
185 if len(sm.hdr) == 0 {
186 continue
187 }
188 if schedule, apiErr := nextMessageSchedule(sm.hdr, sm.ts); apiErr == nil && !schedule.IsZero() {
189 ms.scheduling.init(seq, sm.subj, schedule.UnixNano())
190 }
191 }
192 }
193
194 // Stores a raw message with expected sequence number and timestamp.
195 // Lock should be held.
196 func (ms *memStore) storeRawMsg(subj string, hdr, msg []byte, seq uint64, ts, ttl int64, discardNewCheck bool) error {
197 if ms.msgs == nil {
198 return ErrStoreClosed
199 }
200
201 // Tracking by subject.
202 var ss *SimpleState
203 var asl bool
204 if len(subj) > 0 {
205 var ok bool
206 if ss, ok = ms.fss.Find(stringToBytes(subj)); ok {
207 asl = ms.maxp > 0 && ss.Msgs >= uint64(ms.maxp)
208 }
209 }
210
211 // Check if we are discarding new messages when we reach the limit.
212 // If we are clustered, we do the enforcement above and should not disqualify
213 // the message here since it could cause replicas to drift.
214 if discardNewCheck && ms.cfg.Discard == DiscardNew {
215 // Allow rollup messages through since they will purge old
216 // messages for the subject after storing, restoring the limit.
217 if asl && ms.cfg.DiscardNewPer && len(sliceHeader(JSMsgRollup, hdr)) == 0 {
218 return ErrMaxMsgsPerSubject
219 }
220 if ms.cfg.MaxMsgs > 0 && ms.state.Msgs >= uint64(ms.cfg.MaxMsgs) {
221 // If we are tracking max messages per subject and are at the limit we will replace, so this is ok.
222 if !asl {
223 return ErrMaxMsgs
224 }
225 }
226 if ms.cfg.MaxBytes > 0 && ms.state.Bytes+memStoreMsgSize(subj, hdr, msg) > uint64(ms.cfg.MaxBytes) {
227 if !asl {
228 return ErrMaxBytes
229 }
230 // If we are here we are at a subject maximum, need to determine if dropping last message gives us enough room.
231 if ss.firstNeedsUpdate || ss.lastNeedsUpdate {
232 ms.recalculateForSubj(subj, ss)
233 }
234 sm, ok := ms.msgs[ss.First]
235 if !ok || memStoreMsgSize(sm.subj, sm.hdr, sm.msg) < memStoreMsgSize(subj, hdr, msg) {
236 return ErrMaxBytes
237 }
238 }
239 }
240
241 if seq != ms.state.LastSeq+1 {
242 if seq > 0 {
243 return ErrSequenceMismatch
244 }
245 seq = ms.state.LastSeq + 1
246 }
247
248 // Adjust first if needed.
249 now := time.Unix(0, ts).UTC()
250 if ms.state.Msgs == 0 {
251 ms.state.FirstSeq = seq
252 ms.state.FirstTime = now
253 }
254
255 // Make copies
256 // TODO(dlc) - Maybe be smarter here.
257 if len(msg) > 0 {
258 msg = copyBytes(msg)
259 }
260 if len(hdr) > 0 {
261 hdr = copyBytes(hdr)
262 }
263
264 // FIXME(dlc) - Could pool at this level?
265 sm := &StoreMsg{subj, nil, nil, make([]byte, 0, len(hdr)+len(msg)), seq, ts}
266 sm.buf = append(sm.buf, hdr...)
267 sm.buf = append(sm.buf, msg...)
268 if len(hdr) > 0 {
269 sm.hdr = sm.buf[:len(hdr)]
270 }
271 sm.msg = sm.buf[len(hdr):]
272 ms.msgs[seq] = sm
273 ms.state.Msgs++
274 ms.state.Bytes += memStoreMsgSize(subj, hdr, msg)
275 ms.state.LastSeq = seq
276 ms.state.LastTime = now
277
278 // Track per subject.
279 if len(subj) > 0 {
280 if ss != nil {
281 ss.Msgs++
282 ss.Last = seq
283 ss.lastNeedsUpdate = false
284 // Check per subject limits.
285 if ms.maxp > 0 && ss.Msgs > uint64(ms.maxp) {
286 ms.enforcePerSubjectLimit(subj, ss)
287 }
288 } else {
289 ms.fss.Insert([]byte(subj), SimpleState{Msgs: 1, First: seq, Last: seq})
290 }
291 }
292
293 // Limits checks and enforcement.
294 ms.enforceMsgLimit()
295 ms.enforceBytesLimit()
296
297 // Per-message TTL.
298 if ms.ttls != nil && ttl > 0 {
299 expires := time.Duration(ts) + (time.Second * time.Duration(ttl))
300 ms.ttls.Add(seq, int64(expires))
301 }
302
303 // Check if we have and need the age expiration timer running.
304 switch {
305 case ms.ttls != nil && ttl > 0:
306 ms.resetAgeChk(0)
307 case ms.ageChk == nil && (ms.cfg.MaxAge > 0 || ms.ttls != nil):
308 ms.startAgeChk()
309 }
310
311 // Message scheduling.
312 if ms.scheduling != nil {
313 if schedule, apiErr := nextMessageSchedule(hdr, ts); apiErr == nil && !schedule.IsZero() {
314 ms.scheduling.add(seq, subj, schedule.UnixNano())
315 } else if getMessageScheduler(hdr) == _EMPTY_ {
316 ms.scheduling.removeSubject(subj)
317 }
318
319 // Check for a repeating schedule and update such that it triggers again.
320 if scheduleNext := bytesToString(sliceHeader(JSScheduleNext, hdr)); scheduleNext != _EMPTY_ && scheduleNext != JSScheduleNextPurge {
321 scheduler := getMessageScheduler(hdr)
322 if next, err := time.Parse(time.RFC3339Nano, scheduleNext); err == nil && scheduler != _EMPTY_ {
323 ms.scheduling.update(scheduler, next.UnixNano())
324 }
325 }
326 }
327
328 return nil
329 }
330
331 // StoreRawMsg stores a raw message with expected sequence number and timestamp.
332 func (ms *memStore) StoreRawMsg(subj string, hdr, msg []byte, seq uint64, ts, ttl int64, discardNewCheck bool) error {
333 ms.mu.Lock()
334 err := ms.storeRawMsg(subj, hdr, msg, seq, ts, ttl, discardNewCheck)
335 cb := ms.scb
336 // Check if first message timestamp requires expiry
337 // sooner than initial replica expiry timer set to MaxAge when initializing.
338 if !ms.receivedAny && ms.cfg.MaxAge != 0 && ts > 0 {
339 ms.receivedAny = true
340 // Calculate duration when the next expireMsgs should be called.
341 ms.resetAgeChk(int64(time.Millisecond) * 50)
342 }
343 ms.mu.Unlock()
344
345 if err == nil && cb != nil {
346 cb(1, int64(memStoreMsgSize(subj, hdr, msg)), seq, subj)
347 }
348
349 return err
350 }
351
352 // Store stores a message.
353 func (ms *memStore) StoreMsg(subj string, hdr, msg []byte, ttl int64) (uint64, int64, error) {
354 ms.mu.Lock()
355 seq, ts := ms.state.LastSeq+1, time.Now().UnixNano()
356 // This is called for a R1 with no expected sequence number, so perform DiscardNew checks on the store-level.
357 err := ms.storeRawMsg(subj, hdr, msg, seq, ts, ttl, true)
358 cb := ms.scb
359 ms.mu.Unlock()
360
361 if err != nil {
362 seq, ts = 0, 0
363 } else if cb != nil {
364 cb(1, int64(memStoreMsgSize(subj, hdr, msg)), seq, subj)
365 }
366
367 return seq, ts, err
368 }
369
370 // SkipMsg will use the next sequence number but not store anything.
371 func (ms *memStore) SkipMsg(seq uint64) (uint64, error) {
372 return ms.skipMsg(seq, false)
373 }
374
375 // SkipMsgNoInterest will use the next sequence number but not store anything.
376 // Unlike SkipMsg it also advances LastTime, which is used for Interest retention.
377 func (ms *memStore) SkipMsgNoInterest(seq uint64) (uint64, error) {
378 return ms.skipMsg(seq, true)
379 }
380
381 func (ms *memStore) skipMsg(seq uint64, noInterest bool) (uint64, error) {
382 ms.mu.Lock()
383 defer ms.mu.Unlock()
384
385 // Check sequence matches our last sequence.
386 if seq != ms.state.LastSeq+1 {
387 if seq > 0 {
388 return 0, ErrSequenceMismatch
389 }
390 seq = ms.state.LastSeq + 1
391 }
392
393 ms.state.LastSeq = seq
394 // Only update time if not already set or for Interest retention.
395 if noInterest || ms.state.LastTime.IsZero() {
396 ms.state.LastTime = time.Unix(0, ats.AccessTime()).UTC()
397 }
398 if ms.state.Msgs == 0 {
399 ms.state.FirstSeq = seq + 1
400 ms.state.FirstTime = time.Time{}
401 } else {
402 ms.dmap.Insert(seq)
403 }
404 return seq, nil
405 }
406
407 // Skip multiple msgs.
408 func (ms *memStore) SkipMsgs(seq uint64, num uint64) error {
409 ms.mu.Lock()
410 defer ms.mu.Unlock()
411
412 // Check sequence matches our last sequence.
413 if seq != ms.state.LastSeq+1 {
414 if seq > 0 {
415 return ErrSequenceMismatch
416 }
417 seq = ms.state.LastSeq + 1
418 }
419 lseq := seq + num - 1
420
421 ms.state.LastSeq = lseq
422 // Only update time if not already set.
423 if ms.state.LastTime.IsZero() {
424 ms.state.LastTime = time.Unix(0, ats.AccessTime()).UTC()
425 }
426 if ms.state.Msgs == 0 {
427 ms.state.FirstSeq, ms.state.FirstTime = lseq+1, time.Time{}
428 } else {
429 for ; seq <= lseq; seq++ {
430 ms.dmap.Insert(seq)
431 }
432 }
433 return nil
434 }
435
436 // FlushAllPending flushes all data that was still pending to be written.
437 func (ms *memStore) FlushAllPending() error {
438 // Noop, in-memory store doesn't use async applying.
439 return nil
440 }
441
442 // RegisterStorageUpdates registers a callback for updates to storage changes.
443 // It will present number of messages and bytes as a signed integer and an
444 // optional sequence number of the message if a single.
445 func (ms *memStore) RegisterStorageUpdates(cb StorageUpdateHandler) {
446 ms.mu.Lock()
447 ms.scb = cb
448 ms.mu.Unlock()
449 }
450
451 // RegisterStorageRemoveMsg registers a callback to remove messages.
452 // Replicated streams should propose removals, R1 can remove inline.
453 func (ms *memStore) RegisterStorageRemoveMsg(cb StorageRemoveMsgHandler) {
454 ms.mu.Lock()
455 ms.rmcb = cb
456 ms.mu.Unlock()
457 }
458
459 // RegisterProcessJetStreamMsg registers a callback to process new JetStream messages.
460 func (ms *memStore) RegisterProcessJetStreamMsg(cb ProcessJetStreamMsgHandler) {
461 ms.mu.Lock()
462 ms.pmsgcb = cb
463 ms.mu.Unlock()
464 }
465
466 // GetSeqFromTime looks for the first sequence number that has the message
467 // with >= timestamp.
468 func (ms *memStore) GetSeqFromTime(t time.Time) uint64 {
469 ts := t.UnixNano()
470 ms.mu.RLock()
471 defer ms.mu.RUnlock()
472 if len(ms.msgs) == 0 {
473 return ms.state.LastSeq + 1
474 }
475 if ts <= ms.msgs[ms.state.FirstSeq].ts {
476 return ms.state.FirstSeq
477 }
478 // LastSeq is not guaranteed to be present since last does not go backwards.
479 var lmsg *StoreMsg
480 for lseq := ms.state.LastSeq; lseq > ms.state.FirstSeq; lseq-- {
481 if lmsg = ms.msgs[lseq]; lmsg != nil {
482 break
483 }
484 }
485 if lmsg == nil {
486 return ms.state.LastSeq + 1
487 }
488
489 last := lmsg.ts
490 if ts == last {
491 return lmsg.seq
492 }
493 if ts > last {
494 return ms.state.LastSeq + 1
495 }
496
497 var (
498 cts int64
499 cseq uint64
500 off uint64
501 )
502
503 // Using a binary search, but need to be aware of interior deletes.
504 fseq := ms.state.FirstSeq
505 lseq := ms.state.LastSeq
506 seq := lseq + 1
507 loop:
508 for fseq <= lseq {
509 mid := fseq + (lseq-fseq)/2
510 off = 0
511 // Potentially skip over gaps. We keep the original middle but keep track of a
512 // potential delete range with an offset.
513 for {
514 msg := ms.msgs[mid+off]
515 if msg == nil {
516 off++
517 if mid+off <= lseq {
518 continue
519 } else {
520 // Continue search to the left. Purposely ignore the skipped deletes here.
521 lseq = mid - 1
522 continue loop
523 }
524 }
525 cts = msg.ts
526 cseq = msg.seq
527 break
528 }
529 if cts >= ts {
530 seq = cseq
531 if mid == fseq {
532 break
533 }
534 // Continue search to the left.
535 lseq = mid - 1
536 } else {
537 // Continue search to the right (potentially skipping over interior deletes).
538 fseq = mid + off + 1
539 }
540 }
541 return seq
542 }
543
544 // FilteredState will return the SimpleState associated with the filtered subject and a proposed starting sequence.
545 func (ms *memStore) FilteredState(sseq uint64, subj string) (SimpleState, error) {
546 // This needs to be a write lock, as filteredStateLocked can
547 // mutate the per-subject state.
548 ms.mu.Lock()
549 defer ms.mu.Unlock()
550
551 return ms.filteredStateLocked(sseq, subj, false), nil
552 }
553
554 func (ms *memStore) filteredStateLocked(sseq uint64, filter string, lastPerSubject bool) SimpleState {
555 if sseq < ms.state.FirstSeq {
556 sseq = ms.state.FirstSeq
557 }
558
559 // If past the end no results.
560 if sseq > ms.state.LastSeq {
561 return SimpleState{}
562 }
563
564 if filter == _EMPTY_ {
565 filter = fwcs
566 }
567 isAll := filter == fwcs
568
569 // First check if we can optimize this part.
570 // This means we want all and the starting sequence was before this block.
571 if isAll && sseq <= ms.state.FirstSeq {
572 total := ms.state.Msgs
573 if lastPerSubject {
574 total = uint64(ms.fss.Size())
575 }
576 return SimpleState{
577 Msgs: total,
578 First: ms.state.FirstSeq,
579 Last: ms.state.LastSeq,
580 }
581 }
582
583 _tsa, _fsa := [32]string{}, [32]string{}
584 tsa, fsa := _tsa[:0], _fsa[:0]
585 wc := subjectHasWildcard(filter)
586 if wc {
587 fsa = tokenizeSubjectIntoSlice(fsa[:0], filter)
588 }
589 // 1. See if we match any subs from fss.
590 // 2. If we match and the sseq is past ss.Last then we can use meta only.
591 // 3. If we match we need to do a partial, break and clear any totals and do a full scan like num pending.
592
593 isMatch := func(subj string) bool {
594 if isAll {
595 return true
596 }
597 if !wc {
598 return subj == filter
599 }
600 tsa = tokenizeSubjectIntoSlice(tsa[:0], subj)
601 return isSubsetMatchTokenized(tsa, fsa)
602 }
603
604 var ss SimpleState
605 update := func(fss *SimpleState) {
606 msgs, first, last := fss.Msgs, fss.First, fss.Last
607 if lastPerSubject {
608 msgs, first = 1, last
609 }
610 ss.Msgs += msgs
611 if ss.First == 0 || first < ss.First {
612 ss.First = first
613 }
614 if last > ss.Last {
615 ss.Last = last
616 }
617 }
618
619 var havePartial bool
620 var totalSkipped uint64
621 // We will track start and end sequences as we go.
622 ms.fss.Match(stringToBytes(filter), func(subj []byte, fss *SimpleState) {
623 if fss.firstNeedsUpdate || fss.lastNeedsUpdate {
624 ms.recalculateForSubj(bytesToString(subj), fss)
625 }
626 if sseq <= fss.First {
627 update(fss)
628 } else if sseq <= fss.Last {
629 // We matched but it is a partial.
630 havePartial = true
631 // Don't break here, we will update to keep tracking last.
632 update(fss)
633 } else {
634 totalSkipped += fss.Msgs
635 }
636 })
637
638 // If we did not encounter any partials we can return here.
639 if !havePartial {
640 return ss
641 }
642
643 // If we are here we need to scan the msgs.
644 // Capture first and last sequences for scan and then clear what we had.
645 first, last := ss.First, ss.Last
646 // To track if we decide to exclude we need to calculate first.
647 var needScanFirst bool
648 if first < sseq {
649 first = sseq
650 needScanFirst = true
651 }
652
653 // Now we want to check if it is better to scan inclusive and recalculate that way
654 // or leave and scan exclusive and adjust our totals.
655 // ss.Last is always correct here.
656 toScan, toExclude := last-first, first-ms.state.FirstSeq+ms.state.LastSeq-ss.Last
657 var seen map[string]bool
658 if lastPerSubject {
659 seen = make(map[string]bool)
660 }
661 if toScan < toExclude {
662 ss.Msgs, ss.First = 0, 0
663
664 update := func(sm *StoreMsg) {
665 ss.Msgs++
666 if ss.First == 0 {
667 ss.First = sm.seq
668 }
669 if seen != nil {
670 seen[sm.subj] = true
671 }
672 }
673 // Check if easier to just scan msgs vs the sequence range.
674 // This can happen with lots of interior deletes.
675 if last-first > uint64(len(ms.msgs)) {
676 for _, sm := range ms.msgs {
677 if sm.seq >= first && sm.seq <= last && !seen[sm.subj] && isMatch(sm.subj) {
678 update(sm)
679 }
680 }
681 } else {
682 for seq := first; seq <= last; seq++ {
683 if sm, ok := ms.msgs[seq]; ok && !seen[sm.subj] && isMatch(sm.subj) {
684 update(sm)
685 }
686 }
687 }
688 } else {
689 // We will adjust from the totals above by scanning what we need to exclude.
690 ss.First = first
691 ss.Msgs += totalSkipped
692 var adjust uint64
693 var tss *SimpleState
694
695 update := func(sm *StoreMsg) {
696 if lastPerSubject {
697 tss, _ = ms.fss.Find(stringToBytes(sm.subj))
698 }
699 if tss == nil {
700 adjust++
701 } else if tss.Last < first {
702 // If we are last per subject, make sure to only adjust if all messages are before our first.
703 adjust += tss.Msgs
704 }
705 if seen != nil {
706 seen[sm.subj] = true
707 }
708 }
709 // Check if easier to just scan msgs vs the sequence range.
710 if first-ms.state.FirstSeq > uint64(len(ms.msgs)) {
711 for _, sm := range ms.msgs {
712 if sm.seq < first && !seen[sm.subj] && isMatch(sm.subj) {
713 update(sm)
714 }
715 }
716 } else {
717 for seq := ms.state.FirstSeq; seq < first; seq++ {
718 if sm, ok := ms.msgs[seq]; ok && !seen[sm.subj] && isMatch(sm.subj) {
719 update(sm)
720 }
721 }
722 }
723 // Now do range at end.
724 for seq := last + 1; seq < ms.state.LastSeq; seq++ {
725 if sm, ok := ms.msgs[seq]; ok && !seen[sm.subj] && isMatch(sm.subj) {
726 adjust++
727 if seen != nil {
728 seen[sm.subj] = true
729 }
730 }
731 }
732 ss.Msgs -= adjust
733 if needScanFirst {
734 // Check if easier to just scan msgs vs the sequence range.
735 // Since we will need to scan all of the msgs vs below where we break on the first match,
736 // we will only do so if a few orders of magnitude lower.
737 if last-first > 100*uint64(len(ms.msgs)) {
738 low := ms.state.LastSeq
739 for _, sm := range ms.msgs {
740 if sm.seq >= first && sm.seq < last && isMatch(sm.subj) {
741 if sm.seq < low {
742 low = sm.seq
743 }
744 }
745 }
746 if low < ms.state.LastSeq {
747 ss.First = low
748 }
749 } else {
750 for seq := first; seq < last; seq++ {
751 if sm, ok := ms.msgs[seq]; ok && isMatch(sm.subj) {
752 ss.First = seq
753 break
754 }
755 }
756 }
757 }
758 }
759
760 return ss
761 }
762
763 // SubjectsState returns a map of SimpleState for all matching subjects.
764 func (ms *memStore) SubjectsState(subject string) map[string]SimpleState {
765 // This needs to be a write lock, as we can mutate the per-subject state.
766 ms.mu.Lock()
767 defer ms.mu.Unlock()
768
769 if ms.fss.Size() == 0 {
770 return nil
771 }
772
773 if subject == _EMPTY_ {
774 subject = fwcs
775 }
776
777 fss := make(map[string]SimpleState)
778 ms.fss.Match(stringToBytes(subject), func(subj []byte, ss *SimpleState) {
779 subjs := string(subj)
780 if ss.firstNeedsUpdate || ss.lastNeedsUpdate {
781 ms.recalculateForSubj(subjs, ss)
782 }
783 oss := fss[subjs]
784 if oss.First == 0 { // New
785 fss[subjs] = *ss
786 } else {
787 // Merge here.
788 oss.Last, oss.Msgs = ss.Last, oss.Msgs+ss.Msgs
789 fss[subjs] = oss
790 }
791 })
792 return fss
793 }
794
795 // AllLastSeqs will return a sorted list of last sequences for all subjects.
796 func (ms *memStore) AllLastSeqs() ([]uint64, error) {
797 ms.mu.RLock()
798 defer ms.mu.RUnlock()
799 return ms.allLastSeqsLocked()
800 }
801
802 // allLastSeqsLocked will return a sorted list of last sequences for all
803 // subjects, but won't take the lock to do it, to avoid the issue of compounding
804 // read locks causing a deadlock with a write lock.
805 func (ms *memStore) allLastSeqsLocked() ([]uint64, error) {
806 if len(ms.msgs) == 0 {
807 return nil, nil
808 }
809
810 seqs := make([]uint64, 0, ms.fss.Size())
811 ms.fss.IterFast(func(subj []byte, ss *SimpleState) bool {
812 // Check if we need to recalculate. We only care about the last sequence.
813 if ss.lastNeedsUpdate {
814 ms.recalculateForSubj(bytesToString(subj), ss)
815 }
816 seqs = append(seqs, ss.Last)
817 return true
818 })
819
820 slices.Sort(seqs)
821 return seqs, nil
822 }
823
824 // Helper to determine if the filter(s) represent all the subjects.
825 // Most clients send in subjects even if they match the stream's ingest subjects.
826 // Lock should be held.
827 func (ms *memStore) filterIsAll(filters []string) bool {
828 if len(filters) == 1 && filters[0] == fwcs {
829 return true
830 }
831 if len(filters) != len(ms.cfg.Subjects) {
832 return false
833 }
834 // Sort so we can compare.
835 subjects := copyStrings(ms.cfg.Subjects)
836 slices.Sort(filters)
837 slices.Sort(subjects)
838 for i, subj := range filters {
839 if !subjectIsSubsetMatch(subjects[i], subj) {
840 return false
841 }
842 }
843 return true
844 }
845
846 // MultiLastSeqs will return a sorted list of sequences that match all subjects presented in filters.
847 // We will not exceed the maxSeq, which if 0 becomes the store's last sequence.
848 func (ms *memStore) MultiLastSeqs(filters []string, maxSeq uint64, maxAllowed int) ([]uint64, error) {
849 ms.mu.Lock()
850 defer ms.mu.Unlock()
851 return ms.multiLastSeqsLocked(filters, maxSeq, maxAllowed)
852 }
853
854 // Write lock should be held, for recalculateForSubj.
855 func (ms *memStore) multiLastSeqsLocked(filters []string, maxSeq uint64, maxAllowed int) ([]uint64, error) {
856 if len(ms.msgs) == 0 {
857 return nil, nil
858 }
859
860 // See if we can short circuit if we think they are asking for all last sequences and have no maxSeq or maxAllowed set.
861 if maxSeq == 0 && maxAllowed <= 0 && ms.filterIsAll(filters) {
862 return ms.allLastSeqsLocked()
863 }
864
865 // Implied last sequence.
866 if maxSeq == 0 {
867 maxSeq = ms.state.LastSeq
868 }
869
870 seqs := make([]uint64, 0, 64)
871 seen := make(map[uint64]struct{})
872
873 addIfNotDupe := func(seq uint64) {
874 if _, ok := seen[seq]; !ok {
875 seqs = append(seqs, seq)
876 seen[seq] = struct{}{}
877 }
878 }
879
880 for _, filter := range filters {
881 ms.fss.Match(stringToBytes(filter), func(subj []byte, ss *SimpleState) {
882 if ss.lastNeedsUpdate {
883 ms.recalculateForSubj(bytesToString(subj), ss)
884 }
885 if ss.Last <= maxSeq {
886 addIfNotDupe(ss.Last)
887 } else if ss.Msgs > 1 {
888 // The last is greater than maxSeq.
889 s := bytesToString(subj)
890 for seq := maxSeq; seq > 0; seq-- {
891 if sm, ok := ms.msgs[seq]; ok && sm.subj == s {
892 addIfNotDupe(seq)
893 break
894 }
895 }
896 }
897 })
898 // If maxAllowed was sepcified check that we will not exceed that.
899 if maxAllowed > 0 && len(seqs) > maxAllowed {
900 return nil, ErrTooManyResults
901 }
902 }
903 slices.Sort(seqs)
904 return seqs, nil
905 }
906
907 // MultiLastMsgs delivers the last message per subject matching the filters,
908 // up to maxSeq and skipping sequences below minSeq, in ascending sequence
909 // order through cb, all within a single read section so the batch is a
910 // point-in-time snapshot of the store.
911 func (ms *memStore) MultiLastMsgs(filters []string, minSeq, maxSeq uint64, maxAllowed int, cb func(sm *StoreMsg, np uint64) bool) (uint64, uint64, error) {
912 ms.mu.Lock()
913 defer ms.mu.Unlock()
914
915 seqs, err := ms.multiLastSeqsLocked(filters, maxSeq, maxAllowed)
916 if err != nil || len(seqs) == 0 {
917 return 0, 0, err
918 }
919 total := uint64(len(seqs))
920 np := total
921 for _, seq := range seqs {
922 if np > 0 {
923 np--
924 }
925 if seq < minSeq {
926 continue
927 }
928 var svp StoreMsg
929 sm, err := ms.loadMsgLocked(seq, &svp, false)
930 if err != nil {
931 return total, np, err
932 }
933 if !cb(sm, np) {
934 break
935 }
936 }
937 return total, np, nil
938 }
939
940 // SubjectsTotals return message totals per subject.
941 func (ms *memStore) SubjectsTotals(filterSubject string) map[string]uint64 {
942 ms.mu.RLock()
943 defer ms.mu.RUnlock()
944 return ms.subjectsTotalsLocked(filterSubject)
945 }
946
947 // Lock should be held.
948 func (ms *memStore) subjectsTotalsLocked(filterSubject string) map[string]uint64 {
949 if ms.fss.Size() == 0 {
950 return nil
951 }
952
953 _tsa, _fsa := [32]string{}, [32]string{}
954 tsa, fsa := _tsa[:0], _fsa[:0]
955 fsa = tokenizeSubjectIntoSlice(fsa[:0], filterSubject)
956 isAll := filterSubject == _EMPTY_ || filterSubject == fwcs
957
958 fst := make(map[string]uint64)
959 ms.fss.Match(stringToBytes(filterSubject), func(subj []byte, ss *SimpleState) {
960 subjs := string(subj)
961 if isAll {
962 fst[subjs] = ss.Msgs
963 } else {
964 if tsa = tokenizeSubjectIntoSlice(tsa[:0], subjs); isSubsetMatchTokenized(tsa, fsa) {
965 fst[subjs] = ss.Msgs
966 }
967 }
968 })
969 return fst
970 }
971
972 // NumPending will return the number of pending messages matching the filter subject starting at sequence.
973 func (ms *memStore) NumPending(sseq uint64, filter string, lastPerSubject bool) (total, validThrough uint64, err error) {
974 // This needs to be a write lock, as filteredStateLocked can mutate the per-subject state.
975 ms.mu.Lock()
976 defer ms.mu.Unlock()
977
978 ss := ms.filteredStateLocked(sseq, filter, lastPerSubject)
979 return ss.Msgs, ms.state.LastSeq, nil
980 }
981
982 // NumPending will return the number of pending messages matching any subject in the sublist starting at sequence.
983 func (ms *memStore) NumPendingMulti(sseq uint64, sl *gsl.SimpleSublist, lastPerSubject bool) (total, validThrough uint64, err error) {
984 if sl == nil {
985 return ms.NumPending(sseq, fwcs, lastPerSubject)
986 }
987
988 // This needs to be a write lock, as we can mutate the per-subject state.
989 ms.mu.Lock()
990 defer ms.mu.Unlock()
991
992 var ss SimpleState
993 if sseq < ms.state.FirstSeq {
994 sseq = ms.state.FirstSeq
995 }
996 // If past the end no results.
997 if sseq > ms.state.LastSeq {
998 return 0, ms.state.LastSeq, nil
999 }
1000
1001 update := func(fss *SimpleState) {
1002 msgs, first, last := fss.Msgs, fss.First, fss.Last
1003 if lastPerSubject {
1004 msgs, first = 1, last
1005 }
1006 ss.Msgs += msgs
1007 if ss.First == 0 || first < ss.First {
1008 ss.First = first
1009 }
1010 if last > ss.Last {
1011 ss.Last = last
1012 }
1013 }
1014
1015 var havePartial bool
1016 var totalSkipped uint64
1017 // We will track start and end sequences as we go.
1018 stree.IntersectGSL[SimpleState](ms.fss, sl, func(subj []byte, fss *SimpleState) bool {
1019 if fss.firstNeedsUpdate || fss.lastNeedsUpdate {
1020 ms.recalculateForSubj(bytesToString(subj), fss)
1021 }
1022 if sseq <= fss.First {
1023 update(fss)
1024 } else if sseq <= fss.Last {
1025 // We matched but it is a partial.
1026 havePartial = true
1027 // Don't break here, we will update to keep tracking last.
1028 update(fss)
1029 } else {
1030 totalSkipped += fss.Msgs
1031 }
1032 return true
1033 })
1034
1035 // If we did not encounter any partials we can return here.
1036 if !havePartial {
1037 return ss.Msgs, ms.state.LastSeq, nil
1038 }
1039
1040 // If we are here we need to scan the msgs.
1041 // Capture first and last sequences for scan and then clear what we had.
1042 first, last := ss.First, ss.Last
1043 // To track if we decide to exclude we need to calculate first.
1044 if first < sseq {
1045 first = sseq
1046 }
1047
1048 // Now we want to check if it is better to scan inclusive and recalculate that way
1049 // or leave and scan exclusive and adjust our totals.
1050 // ss.Last is always correct here.
1051 toScan, toExclude := last-first, first-ms.state.FirstSeq+ms.state.LastSeq-ss.Last
1052 var seen map[string]bool
1053 if lastPerSubject {
1054 seen = make(map[string]bool)
1055 }
1056 if toScan < toExclude {
1057 ss.Msgs, ss.First = 0, 0
1058
1059 update := func(sm *StoreMsg) {
1060 ss.Msgs++
1061 if ss.First == 0 {
1062 ss.First = sm.seq
1063 }
1064 if seen != nil {
1065 seen[sm.subj] = true
1066 }
1067 }
1068 // Check if easier to just scan msgs vs the sequence range.
1069 // This can happen with lots of interior deletes.
1070 if last-first > uint64(len(ms.msgs)) {
1071 for _, sm := range ms.msgs {
1072 if sm.seq >= first && sm.seq <= last && !seen[sm.subj] && sl.HasInterest(sm.subj) {
1073 update(sm)
1074 }
1075 }
1076 } else {
1077 for seq := first; seq <= last; seq++ {
1078 if sm, ok := ms.msgs[seq]; ok && !seen[sm.subj] && sl.HasInterest(sm.subj) {
1079 update(sm)
1080 }
1081 }
1082 }
1083 } else {
1084 // We will adjust from the totals above by scanning what we need to exclude.
1085 ss.First = first
1086 ss.Msgs += totalSkipped
1087 var adjust uint64
1088 var tss *SimpleState
1089
1090 update := func(sm *StoreMsg) {
1091 if lastPerSubject {
1092 tss, _ = ms.fss.Find(stringToBytes(sm.subj))
1093 }
1094 if tss == nil {
1095 adjust++
1096 } else if tss.Last < first {
1097 // If we are last per subject, make sure to only adjust if all messages are before our first.
1098 adjust += tss.Msgs
1099 }
1100 if seen != nil {
1101 seen[sm.subj] = true
1102 }
1103 }
1104 // Check if easier to just scan msgs vs the sequence range.
1105 if first-ms.state.FirstSeq > uint64(len(ms.msgs)) {
1106 for _, sm := range ms.msgs {
1107 if sm.seq < first && !seen[sm.subj] && sl.HasInterest(sm.subj) {
1108 update(sm)
1109 }
1110 }
1111 } else {
1112 for seq := ms.state.FirstSeq; seq < first; seq++ {
1113 if sm, ok := ms.msgs[seq]; ok && !seen[sm.subj] && sl.HasInterest(sm.subj) {
1114 update(sm)
1115 }
1116 }
1117 }
1118 // Now do range at end.
1119 for seq := last + 1; seq < ms.state.LastSeq; seq++ {
1120 if sm, ok := ms.msgs[seq]; ok && !seen[sm.subj] && sl.HasInterest(sm.subj) {
1121 adjust++
1122 if seen != nil {
1123 seen[sm.subj] = true
1124 }
1125 }
1126 }
1127 ss.Msgs -= adjust
1128 }
1129
1130 return ss.Msgs, ms.state.LastSeq, nil
1131 }
1132
1133 // Will check the msg limit for this tracked subject.
1134 // Lock should be held.
1135 func (ms *memStore) enforcePerSubjectLimit(subj string, ss *SimpleState) {
1136 if ms.maxp <= 0 {
1137 return
1138 }
1139 for nmsgs := ss.Msgs; nmsgs > uint64(ms.maxp); nmsgs = ss.Msgs {
1140 if ss.firstNeedsUpdate || ss.lastNeedsUpdate {
1141 ms.recalculateForSubj(subj, ss)
1142 }
1143 if !ms.removeMsg(ss.First, false) {
1144 break
1145 }
1146 }
1147 }
1148
1149 // Will check the msg limit and drop firstSeq msg if needed.
1150 // Lock should be held.
1151 func (ms *memStore) enforceMsgLimit() {
1152 if ms.cfg.Discard != DiscardOld {
1153 return
1154 }
1155 if ms.cfg.MaxMsgs <= 0 || ms.state.Msgs <= uint64(ms.cfg.MaxMsgs) {
1156 return
1157 }
1158 for nmsgs := ms.state.Msgs; nmsgs > uint64(ms.cfg.MaxMsgs); nmsgs = ms.state.Msgs {
1159 ms.deleteFirstMsgOrPanic()
1160 }
1161 }
1162
1163 // Will check the bytes limit and drop msgs if needed.
1164 // Lock should be held.
1165 func (ms *memStore) enforceBytesLimit() {
1166 if ms.cfg.Discard != DiscardOld {
1167 return
1168 }
1169 if ms.cfg.MaxBytes <= 0 || ms.state.Bytes <= uint64(ms.cfg.MaxBytes) {
1170 return
1171 }
1172 for bs := ms.state.Bytes; bs > uint64(ms.cfg.MaxBytes); bs = ms.state.Bytes {
1173 ms.deleteFirstMsgOrPanic()
1174 }
1175 }
1176
1177 // Will start the age check timer.
1178 // Lock should be held.
1179 func (ms *memStore) startAgeChk() {
1180 if ms.ageChk != nil {
1181 return
1182 }
1183 if ms.cfg.MaxAge != 0 || ms.ttls != nil {
1184 ms.ageChk = time.AfterFunc(ms.cfg.MaxAge, ms.expireMsgs)
1185 }
1186 }
1187
1188 // Lock should be held.
1189 func (ms *memStore) resetAgeChk(delta int64) {
1190 // If we're already expiring messages, it will make sure to reset.
1191 // Don't trigger again, as that could result in many expire goroutines.
1192 if ms.ageChkRun {
1193 return
1194 }
1195
1196 var next int64 = math.MaxInt64
1197 if ms.ttls != nil {
1198 next = ms.ttls.GetNextExpiration(next)
1199 }
1200
1201 // If there's no MaxAge and there's nothing waiting to be expired then
1202 // don't bother continuing. The next storeRawMsg() will wake us up if
1203 // needs be.
1204 if ms.cfg.MaxAge <= 0 && next == math.MaxInt64 {
1205 clearTimer(&ms.ageChk)
1206 return
1207 }
1208
1209 // Check to see if we should be firing sooner than MaxAge for an expiring TTL.
1210 fireIn := ms.cfg.MaxAge
1211
1212 // If delta for next-to-expire message is unset, but we still have messages to remove.
1213 // Assume messages are removed through proposals, and we need to speed up subsequent age check.
1214 if delta == 0 && ms.state.Msgs > 0 {
1215 if until := 2 * time.Second; until < fireIn {
1216 fireIn = until
1217 }
1218 }
1219
1220 if next < math.MaxInt64 {
1221 // Looks like there's a next expiration, use it either if there's no
1222 // MaxAge set or if it looks to be sooner than MaxAge is.
1223 if until := time.Until(time.Unix(0, next)); fireIn == 0 || until < fireIn {
1224 fireIn = until
1225 }
1226 }
1227
1228 // If not then look at the delta provided (usually gap to next age expiry).
1229 if delta > 0 {
1230 if fireIn == 0 || time.Duration(delta) < fireIn {
1231 fireIn = time.Duration(delta)
1232 }
1233 }
1234
1235 // Make sure we aren't firing too often either way, otherwise we can
1236 // negatively impact stream ingest performance.
1237 if fireIn < 250*time.Millisecond {
1238 fireIn = 250 * time.Millisecond
1239 }
1240
1241 // If we want to kick the timer to run later than what was assigned before, don't reset it.
1242 // Otherwise, we could get in a situation where the timer is continuously reset, and it never runs.
1243 expires := ats.AccessTime() + fireIn.Nanoseconds()
1244 if ms.ageChkTime > 0 && expires > ms.ageChkTime {
1245 return
1246 }
1247
1248 ms.ageChkTime = expires
1249 if ms.ageChk != nil {
1250 ms.ageChk.Reset(fireIn)
1251 } else {
1252 ms.ageChk = time.AfterFunc(fireIn, ms.expireMsgs)
1253 }
1254 }
1255
1256 // Lock should be held.
1257 func (ms *memStore) cancelAgeChk() {
1258 if ms.ageChk != nil {
1259 ms.ageChk.Stop()
1260 ms.ageChk = nil
1261 ms.ageChkTime = 0
1262 }
1263 }
1264
1265 // Will expire msgs that are too old.
1266 func (ms *memStore) expireMsgs() {
1267 var smv StoreMsg
1268 var sm *StoreMsg
1269 ms.mu.Lock()
1270 maxAge := int64(ms.cfg.MaxAge)
1271 minAge := time.Now().UnixNano() - maxAge
1272 rmcb := ms.rmcb
1273 pmsgcb := ms.pmsgcb
1274 sdmTTL := int64(ms.cfg.SubjectDeleteMarkerTTL.Seconds())
1275 sdmEnabled := sdmTTL > 0
1276
1277 // If SDM is enabled, but handlers aren't set up yet. Try again later.
1278 if sdmEnabled && (rmcb == nil || pmsgcb == nil) {
1279 ms.resetAgeChk(0)
1280 ms.mu.Unlock()
1281 return
1282 }
1283 ms.ageChkRun = true
1284 ms.mu.Unlock()
1285
1286 if maxAge > 0 {
1287 var seq uint64
1288 for sm, seq, _ = ms.LoadNextMsg(fwcs, true, 0, &smv); sm != nil && sm.ts <= minAge; sm, seq, _ = ms.LoadNextMsg(fwcs, true, seq+1, &smv) {
1289 if len(sm.hdr) > 0 {
1290 if ttl, err := getMessageTTL(sm.hdr); err == nil && ttl < 0 {
1291 // The message has a negative TTL, therefore it must "never expire".
1292 minAge = time.Now().UnixNano() - maxAge
1293 continue
1294 }
1295 }
1296 if sdmEnabled {
1297 if last, ok := ms.shouldProcessSdm(seq, sm.subj); ok {
1298 sdm := last && !isSubjectDeleteMarker(sm.hdr)
1299 ms.handleRemovalOrSdm(seq, sm.subj, sdm, sdmTTL)
1300 }
1301 } else {
1302 ms.mu.Lock()
1303 ms.removeMsg(seq, false)
1304 ms.mu.Unlock()
1305 }
1306 // Recalculate in case we are expiring a bunch.
1307 minAge = time.Now().UnixNano() - maxAge
1308 }
1309 }
1310
1311 ms.mu.Lock()
1312 defer ms.mu.Unlock()
1313
1314 // TODO: Not great that we're holding the lock here, but the timed hash wheel isn't thread-safe.
1315 nextTTL := int64(math.MaxInt64)
1316 var rmSeqs []thw.HashWheelEntry
1317 if ms.ttls != nil {
1318 ms.ttls.ExpireTasks(func(seq uint64, ts int64) bool {
1319 rmSeqs = append(rmSeqs, thw.HashWheelEntry{Seq: seq, Expires: ts})
1320 // We might need to remove messages out of band, those can fail, and we can be shutdown halfway
1321 // through so don't remove from THW just yet.
1322 return false
1323 })
1324 if maxAge > 0 {
1325 // Only check if we're expiring something in the next MaxAge interval, saves us a bit
1326 // of work if MaxAge will beat us to the next expiry anyway.
1327 nextTTL = ms.ttls.GetNextExpiration(time.Now().Add(time.Duration(maxAge)).UnixNano())
1328 } else {
1329 nextTTL = ms.ttls.GetNextExpiration(math.MaxInt64)
1330 }
1331 }
1332
1333 // Remove messages collected by THW.
1334 if !sdmEnabled {
1335 for _, rm := range rmSeqs {
1336 ms.removeMsg(rm.Seq, false)
1337 }
1338 } else {
1339 // THW is unordered, so must sort by sequence and must not be holding the lock.
1340 ms.mu.Unlock()
1341 slices.SortFunc(rmSeqs, func(a, b thw.HashWheelEntry) int {
1342 if a.Seq == b.Seq {
1343 return 0
1344 } else if a.Seq < b.Seq {
1345 return -1
1346 } else {
1347 return 1
1348 }
1349 })
1350 for _, rm := range rmSeqs {
1351 // Need to grab subject for the specified sequence if for SDM, and check
1352 // if the message hasn't been removed in the meantime.
1353 // We need to grab the message and check if we should process SDM while holding the lock,
1354 // otherwise we can race if a deletion of this message is in progress.
1355 ms.mu.Lock()
1356 sm, _ = ms.loadMsgLocked(rm.Seq, &smv, false)
1357 if sm == nil {
1358 ms.ttls.Remove(rm.Seq, rm.Expires)
1359 ms.mu.Unlock()
1360 continue
1361 }
1362 last, ok := ms.shouldProcessSdmLocked(rm.Seq, sm.subj)
1363 ms.mu.Unlock()
1364 if ok {
1365 sdm := last && !isSubjectDeleteMarker(sm.hdr)
1366 ms.handleRemovalOrSdm(rm.Seq, sm.subj, sdm, sdmTTL)
1367 }
1368 }
1369 ms.mu.Lock()
1370 }
1371
1372 // Only cancel if no message left, not on potential lookup error that would result in sm == nil.
1373 ms.ageChkRun, ms.ageChkTime = false, 0
1374 if ms.state.Msgs == 0 && nextTTL == math.MaxInt64 {
1375 ms.cancelAgeChk()
1376 } else {
1377 if sm == nil {
1378 ms.resetAgeChk(0)
1379 } else {
1380 ms.resetAgeChk(sm.ts - minAge)
1381 }
1382 }
1383 }
1384
1385 func (ms *memStore) shouldProcessSdm(seq uint64, subj string) (bool, bool) {
1386 ms.mu.Lock()
1387 defer ms.mu.Unlock()
1388 return ms.shouldProcessSdmLocked(seq, subj)
1389 }
1390
1391 // Lock should be held.
1392 func (ms *memStore) shouldProcessSdmLocked(seq uint64, subj string) (bool, bool) {
1393 if ms.sdm == nil {
1394 ms.sdm = newSDMMeta()
1395 }
1396
1397 if p, ok := ms.sdm.pending[seq]; ok {
1398 // Don't allow more proposals for the same sequence if we already did recently.
1399 if time.Since(time.Unix(0, p.ts)) < 2*time.Second {
1400 return p.last, false
1401 }
1402 // If we're about to use the cached value, and we knew it was last before,
1403 // quickly check that we don't have more remaining messages for the subject now.
1404 // Which means we are not the last anymore and must reset to not remove later data.
1405 if p.last {
1406 msgs := ms.subjectsTotalsLocked(subj)[subj]
1407 numPending := ms.sdm.totals[subj]
1408 if remaining := msgs - numPending; remaining > 0 {
1409 p.last = false
1410 }
1411 }
1412 ms.sdm.pending[seq] = SDMBySeq{p.last, time.Now().UnixNano()}
1413 return p.last, true
1414 }
1415
1416 msgs := ms.subjectsTotalsLocked(subj)[subj]
1417 if msgs == 0 {
1418 return false, true
1419 }
1420 numPending := ms.sdm.totals[subj]
1421 remaining := msgs - numPending
1422 return ms.sdm.trackPending(seq, subj, remaining == 1), true
1423 }
1424
1425 func (ms *memStore) handleRemovalOrSdm(seq uint64, subj string, sdm bool, sdmTTL int64) {
1426 if sdm {
1427 var _hdr [128]byte
1428 hdr := fmt.Appendf(
1429 _hdr[:0],
1430 "NATS/1.0\r\n%s: %s\r\n%s: %s\r\n%s: %s\r\n\r\n",
1431 JSMarkerReason, JSMarkerReasonMaxAge,
1432 JSMessageTTL, time.Duration(sdmTTL)*time.Second,
1433 JSMsgRollup, JSMsgRollupSubject,
1434 )
1435 msg := &inMsg{
1436 subj: subj,
1437 hdr: hdr,
1438 }
1439 ms.pmsgcb(msg)
1440 } else {
1441 ms.rmcb(seq)
1442 }
1443 }
1444
1445 // Will run through scheduled messages.
1446 func (ms *memStore) runMsgScheduling() {
1447 // TODO: Not great that we're holding the lock here, but the timed hash wheel and message scheduling isn't thread-safe.
1448 ms.mu.Lock()
1449 defer ms.mu.Unlock()
1450
1451 // If scheduling is enabled, but handler isn't set up yet. Try again later.
1452 if ms.scheduling == nil {
1453 return
1454 }
1455 if ms.pmsgcb == nil {
1456 ms.scheduling.resetTimer()
1457 return
1458 }
1459 ms.scheduling.running = true
1460
1461 scheduledMsgs := ms.scheduling.getScheduledMessages(
1462 func(seq uint64, smv *StoreMsg) *StoreMsg {
1463 sm, _ := ms.loadMsgLocked(seq, smv, false)
1464 return sm
1465 },
1466 func(subj string, smv *StoreMsg) *StoreMsg {
1467 sm, _ := ms.loadLastLocked(subj, smv)
1468 return sm
1469 },
1470 )
1471 if len(scheduledMsgs) > 0 {
1472 ms.mu.Unlock()
1473 for _, msg := range scheduledMsgs {
1474 ms.pmsgcb(msg)
1475 }
1476 ms.mu.Lock()
1477 }
1478
1479 ms.scheduling.running, ms.scheduling.deadline = false, 0
1480 ms.scheduling.resetTimer()
1481 }
1482
1483 // PurgeEx will remove messages based on subject filters, sequence and number of messages to keep.
1484 // Will return the number of purged messages.
1485 func (ms *memStore) PurgeEx(subject string, sequence, keep uint64) (purged uint64, err error) {
1486 // sequence == 1 means "purge up to but not including 1", a no-op.
1487 if sequence == 1 {
1488 return 0, nil
1489 }
1490 if subject == _EMPTY_ || subject == fwcs {
1491 if keep == 0 && sequence == 0 {
1492 return ms.purge(0)
1493 }
1494 if sequence > 1 {
1495 return ms.compact(sequence)
1496 }
1497 // Make sure to not leave subject if empty.
1498 if subject == _EMPTY_ {
1499 subject = fwcs
1500 }
1501 }
1502 eq := compareFn(subject)
1503
1504 // FilteredState narrows the search range.
1505 ss, _ := ms.FilteredState(1, subject)
1506 if ss.Msgs == 0 {
1507 return 0, nil
1508 }
1509 // If we have a "keep" designation need to know how many to purge.
1510 var maxp uint64
1511 if keep > 0 {
1512 if keep >= ss.Msgs {
1513 return 0, nil
1514 }
1515 maxp = ss.Msgs - keep
1516 }
1517 // "Purge up to but not including sequence": sequence == 0 means no
1518 // sequence filter; sequence >= 1 clamps the upper bound to sequence-1
1519 // (so sequence == 1 purges nothing).
1520 last := ss.Last
1521 if sequence >= 1 {
1522 last = sequence - 1
1523 }
1524 var bytes, lowSeq uint64
1525 var lowSubj string
1526 ms.mu.Lock()
1527 for seq := ss.First; seq <= last; seq++ {
1528 if sm, ok := ms.msgs[seq]; ok && eq(sm.subj, subject) {
1529 if subj, sz, ok := ms.removeMsgNoCB(sm.seq, false); ok {
1530 purged++
1531 bytes += sz
1532 if lowSeq == 0 {
1533 lowSeq, lowSubj = sm.seq, subj
1534 }
1535 if maxp > 0 && purged >= maxp {
1536 break
1537 }
1538 }
1539 }
1540 }
1541 cb := ms.scb
1542 ms.mu.Unlock()
1543
1544 if cb != nil && purged > 0 {
1545 if purged == 1 {
1546 cb(-1, -int64(bytes), lowSeq, lowSubj)
1547 } else {
1548 cb(-int64(purged), -int64(bytes), 0, _EMPTY_)
1549 }
1550 }
1551 return purged, nil
1552 }
1553
1554 // Purge will remove all messages from this store.
1555 // Will return the number of purged messages.
1556 func (ms *memStore) Purge() (uint64, error) {
1557 return ms.purge(0)
1558 }
1559
1560 func (ms *memStore) purge(fseq uint64) (uint64, error) {
1561 ms.mu.Lock()
1562 purged := uint64(len(ms.msgs))
1563 cb := ms.scb
1564 bytes := int64(ms.state.Bytes)
1565 if fseq == 0 {
1566 fseq = ms.state.LastSeq + 1
1567 } else if fseq < ms.state.LastSeq {
1568 ms.mu.Unlock()
1569 return 0, fmt.Errorf("partial purges not supported on memory store")
1570 }
1571 ms.state.FirstSeq = fseq
1572 ms.state.LastSeq = fseq - 1
1573 ms.state.FirstTime = time.Time{}
1574 ms.state.Bytes = 0
1575 ms.state.Msgs = 0
1576 if ms.msgs != nil {
1577 ms.msgs = make(map[uint64]*StoreMsg)
1578 }
1579 ms.fss = stree.NewSubjectTree[SimpleState]()
1580 ms.dmap.Empty()
1581 ms.sdm.empty()
1582 ms.mu.Unlock()
1583
1584 if cb != nil {
1585 cb(-int64(purged), -bytes, 0, _EMPTY_)
1586 }
1587
1588 return purged, nil
1589 }
1590
1591 // Compact will remove all messages from this store up to
1592 // but not including the seq parameter.
1593 // Will return the number of purged messages.
1594 func (ms *memStore) Compact(seq uint64) (uint64, error) {
1595 return ms.compact(seq)
1596 }
1597
1598 func (ms *memStore) compact(seq uint64) (uint64, error) {
1599 if seq == 0 {
1600 return ms.Purge()
1601 }
1602
1603 var purged, bytes uint64
1604
1605 ms.mu.Lock()
1606 // Short-circuit if the store was already compacted past this point.
1607 if ms.state.FirstSeq > seq {
1608 ms.mu.Unlock()
1609 return purged, nil
1610 }
1611
1612 cb := ms.scb
1613 if seq <= ms.state.LastSeq {
1614 fseq := ms.state.FirstSeq
1615 // Determine new first sequence.
1616 for ; seq <= ms.state.LastSeq; seq++ {
1617 if sm, ok := ms.msgs[seq]; ok {
1618 ms.state.FirstSeq = seq
1619 ms.state.FirstTime = time.Unix(0, sm.ts).UTC()
1620 break
1621 }
1622 }
1623 for seq := seq - 1; seq >= fseq; seq-- {
1624 if sm := ms.msgs[seq]; sm != nil {
1625 bytes += memStoreMsgSize(sm.subj, sm.hdr, sm.msg)
1626 purged++
1627 ms.removeSeqPerSubject(sm.subj, seq)
1628 // Must delete message after updating per-subject info, to be consistent with file store.
1629 delete(ms.msgs, seq)
1630 } else if !ms.dmap.IsEmpty() {
1631 ms.dmap.Delete(seq)
1632 }
1633 }
1634 if purged > ms.state.Msgs {
1635 purged = ms.state.Msgs
1636 }
1637 ms.state.Msgs -= purged
1638 if ms.state.Msgs == 0 {
1639 ms.state.FirstSeq = ms.state.LastSeq + 1
1640 ms.state.FirstTime = time.Time{}
1641 }
1642 if bytes > ms.state.Bytes {
1643 bytes = ms.state.Bytes
1644 }
1645 ms.state.Bytes -= bytes
1646 } else {
1647 // We are compacting past the end of our range. Do purge and set sequences correctly
1648 // such that the next message placed will have seq.
1649 purged = uint64(len(ms.msgs))
1650 bytes = ms.state.Bytes
1651 ms.state.Bytes = 0
1652 ms.state.Msgs = 0
1653 ms.state.FirstSeq = seq
1654 ms.state.FirstTime = time.Time{}
1655 ms.state.LastSeq = seq - 1
1656 // Reset msgs, fss and dmap.
1657 ms.msgs = make(map[uint64]*StoreMsg)
1658 ms.fss = stree.NewSubjectTree[SimpleState]()
1659 ms.dmap.Empty()
1660 ms.sdm.empty()
1661 }
1662 ms.mu.Unlock()
1663
1664 if cb != nil {
1665 cb(-int64(purged), -int64(bytes), 0, _EMPTY_)
1666 }
1667
1668 return purged, nil
1669 }
1670
1671 // Will completely reset our store.
1672 func (ms *memStore) reset() error {
1673 ms.mu.Lock()
1674 var purged, bytes uint64
1675 cb := ms.scb
1676 if cb != nil {
1677 for _, sm := range ms.msgs {
1678 purged++
1679 bytes += memStoreMsgSize(sm.subj, sm.hdr, sm.msg)
1680 }
1681 }
1682
1683 // Reset
1684 ms.state.FirstSeq = 0
1685 ms.state.FirstTime = time.Time{}
1686 ms.state.LastSeq = 0
1687 ms.state.LastTime = time.Now().UTC()
1688 // Update msgs and bytes.
1689 ms.state.Msgs = 0
1690 ms.state.Bytes = 0
1691 // Reset msgs, fss and dmap.
1692 ms.msgs = make(map[uint64]*StoreMsg)
1693 ms.fss = stree.NewSubjectTree[SimpleState]()
1694 ms.dmap.Empty()
1695 ms.sdm.empty()
1696
1697 ms.mu.Unlock()
1698
1699 if cb != nil {
1700 cb(-int64(purged), -int64(bytes), 0, _EMPTY_)
1701 }
1702
1703 return nil
1704 }
1705
1706 // Truncate will truncate a stream store up to seq. Sequence needs to be valid.
1707 func (ms *memStore) Truncate(seq uint64) error {
1708 // Check for request to reset.
1709 if seq == 0 {
1710 return ms.reset()
1711 }
1712
1713 var purged, bytes uint64
1714
1715 ms.mu.Lock()
1716 lsm, ok := ms.msgs[seq]
1717 lastTime := ms.state.LastTime
1718 if ok && lsm != nil {
1719 lastTime = time.Unix(0, lsm.ts).UTC()
1720 }
1721
1722 for i := ms.state.LastSeq; i > seq; i-- {
1723 if sm := ms.msgs[i]; sm != nil {
1724 purged++
1725 bytes += memStoreMsgSize(sm.subj, sm.hdr, sm.msg)
1726 ms.removeSeqPerSubject(sm.subj, i)
1727 // Must delete message after updating per-subject info, to be consistent with file store.
1728 delete(ms.msgs, i)
1729 } else if !ms.dmap.IsEmpty() {
1730 ms.dmap.Delete(i)
1731 }
1732 }
1733 // Reset last.
1734 ms.state.LastSeq = seq
1735 ms.state.LastTime = lastTime
1736 // Update msgs and bytes.
1737 if purged > ms.state.Msgs {
1738 purged = ms.state.Msgs
1739 }
1740 ms.state.Msgs -= purged
1741 if bytes > ms.state.Bytes {
1742 bytes = ms.state.Bytes
1743 }
1744 ms.state.Bytes -= bytes
1745
1746 cb := ms.scb
1747 ms.mu.Unlock()
1748
1749 if cb != nil {
1750 cb(-int64(purged), -int64(bytes), 0, _EMPTY_)
1751 }
1752
1753 return nil
1754 }
1755
1756 func (ms *memStore) deleteFirstMsgOrPanic() {
1757 if !ms.deleteFirstMsg() {
1758 panic("jetstream memstore has inconsistent state, can't find first seq msg")
1759 }
1760 }
1761
1762 func (ms *memStore) deleteFirstMsg() bool {
1763 return ms.removeMsg(ms.state.FirstSeq, false)
1764 }
1765
1766 // SubjectForSeq will return what the subject is for this sequence if found.
1767 func (ms *memStore) SubjectForSeq(seq uint64) (string, error) {
1768 ms.mu.RLock()
1769 defer ms.mu.RUnlock()
1770 if seq < ms.state.FirstSeq {
1771 return _EMPTY_, ErrStoreMsgNotFound
1772 }
1773 if sm, ok := ms.msgs[seq]; ok {
1774 // Copy the subject, as it's used elsewhere, and we've released the lock in the meantime.
1775 return copyString(sm.subj), nil
1776 }
1777 return _EMPTY_, ErrStoreMsgNotFound
1778 }
1779
1780 // LoadMsg will lookup the message by sequence number and return it if found.
1781 func (ms *memStore) LoadMsg(seq uint64, smp *StoreMsg) (*StoreMsg, error) {
1782 return ms.loadMsgLocked(seq, smp, true)
1783 }
1784
1785 // loadMsgLocked will lookup the message by sequence number and return it if found.
1786 func (ms *memStore) loadMsgLocked(seq uint64, smp *StoreMsg, needMSLock bool) (*StoreMsg, error) {
1787 if needMSLock {
1788 ms.mu.RLock()
1789 }
1790 sm, ok := ms.msgs[seq]
1791 last := ms.state.LastSeq
1792 if needMSLock {
1793 ms.mu.RUnlock()
1794 }
1795
1796 if !ok || sm == nil {
1797 var err = ErrStoreEOF
1798 if seq <= last {
1799 err = ErrStoreMsgNotFound
1800 }
1801 return nil, err
1802 }
1803
1804 if smp == nil {
1805 smp = new(StoreMsg)
1806 }
1807 sm.copy(smp)
1808 return smp, nil
1809 }
1810
1811 // LoadLastMsg will return the last message we have that matches a given subject.
1812 // The subject can be a wildcard.
1813 func (ms *memStore) LoadLastMsg(subject string, smp *StoreMsg) (*StoreMsg, error) {
1814 // This needs to be a write lock, as filteredStateLocked can
1815 // mutate the per-subject state.
1816 ms.mu.Lock()
1817 defer ms.mu.Unlock()
1818 return ms.loadLastLocked(subject, smp)
1819 }
1820
1821 // Lock should be held.
1822 func (ms *memStore) loadLastLocked(subject string, smp *StoreMsg) (*StoreMsg, error) {
1823 var sm *StoreMsg
1824 var ok bool
1825
1826 if subject == _EMPTY_ || subject == fwcs {
1827 sm, ok = ms.msgs[ms.state.LastSeq]
1828 } else if subjectIsLiteral(subject) {
1829 var ss *SimpleState
1830 if ss, ok = ms.fss.Find(stringToBytes(subject)); ok && ss.Msgs > 0 {
1831 // Check if we need to recalculate. We only care about the last sequence.
1832 if ss.lastNeedsUpdate {
1833 ms.recalculateForSubj(subject, ss)
1834 }
1835 sm, ok = ms.msgs[ss.Last]
1836 }
1837 } else if ss := ms.filteredStateLocked(1, subject, true); ss.Msgs > 0 {
1838 sm, ok = ms.msgs[ss.Last]
1839 }
1840 if !ok || sm == nil {
1841 return nil, ErrStoreMsgNotFound
1842 }
1843
1844 if smp == nil {
1845 smp = new(StoreMsg)
1846 }
1847 sm.copy(smp)
1848 return smp, nil
1849 }
1850
1851 // LoadNextMsgMulti will find the next message matching any entry in the sublist.
1852 func (ms *memStore) LoadNextMsgMulti(sl *gsl.SimpleSublist, start uint64, smp *StoreMsg) (sm *StoreMsg, skip uint64, err error) {
1853 // TODO(dlc) - for now simple linear walk to get started.
1854 ms.mu.RLock()
1855 defer ms.mu.RUnlock()
1856
1857 if start < ms.state.FirstSeq {
1858 start = ms.state.FirstSeq
1859 }
1860
1861 // If past the end no results.
1862 if start > ms.state.LastSeq || ms.state.Msgs == 0 {
1863 return nil, ms.state.LastSeq, ErrStoreEOF
1864 }
1865
1866 // Initial setup.
1867 fseq, lseq := start, ms.state.LastSeq
1868
1869 for nseq := fseq; nseq <= lseq; nseq++ {
1870 sm, ok := ms.msgs[nseq]
1871 if !ok {
1872 continue
1873 }
1874 if sl.HasInterest(sm.subj) {
1875 if smp == nil {
1876 smp = new(StoreMsg)
1877 }
1878 sm.copy(smp)
1879 return smp, nseq, nil
1880 }
1881 }
1882 return nil, ms.state.LastSeq, ErrStoreEOF
1883 }
1884
1885 // LoadNextMsg will find the next message matching the filter subject starting at the start sequence.
1886 // The filter subject can be a wildcard.
1887 func (ms *memStore) LoadNextMsg(filter string, wc bool, start uint64, smp *StoreMsg) (*StoreMsg, uint64, error) {
1888 ms.mu.Lock()
1889 defer ms.mu.Unlock()
1890 return ms.loadNextMsgLocked(filter, wc, start, smp)
1891 }
1892
1893 // Find sequence bounds matching a wildcard filter from ms.fss.
1894 // Returns (first, last, true) if there is at least one matching
1895 // subject at or after start (start <= first <= last).
1896 // Returns (0, 0, false) if the subject does not exist or has no
1897 // messages at or after start.
1898 // Lock should be held.
1899 func (ms *memStore) nextWildcardMatchLocked(filter string, start uint64) (uint64, uint64, bool) {
1900 found := false
1901 first, last := ms.state.LastSeq, uint64(0)
1902 ms.fss.MatchUntil(stringToBytes(filter), func(subj []byte, ss *SimpleState) bool {
1903 ms.recalculateForSubj(string(subj), ss)
1904
1905 // Skip matches that are below our starting sequence
1906 if start > ss.Last {
1907 return true
1908 }
1909
1910 // A match was found, adjust the bounds accordingly
1911 found = true
1912 if ss.First < first {
1913 first = ss.First
1914 }
1915 if ss.Last > last {
1916 last = ss.Last
1917 }
1918
1919 // If first > start, there may be more matches between
1920 // start and first, in which case we keep searching.
1921 // If not, we have a match between start and last, we
1922 // can break out of the search.
1923 // This could be further optimized: if first and start
1924 // are "close", we could just extend the linear search,
1925 // especially if we know that the remaining ms.fss to
1926 // explore is large.
1927 return first > start
1928 })
1929 if !found {
1930 return 0, 0, false
1931 }
1932 return max(first, start), last, found
1933 }
1934
1935 // Find sequence bounds matching a literal filter from ms.fss.
1936 // Returns (first, last, true) if there is a matching literal
1937 // subject at or after start (start <= first <= last).
1938 // Returns (0, 0, false) if the subject does not exist or has no
1939 // messages at or after start.
1940 // Lock should be held.
1941 func (ms *memStore) nextLiteralMatchLocked(filter string, start uint64) (uint64, uint64, bool) {
1942 ss, ok := ms.fss.Find(stringToBytes(filter))
1943 if !ok {
1944 return 0, 0, false
1945 }
1946 ms.recalculateForSubj(filter, ss)
1947 if start > ss.Last {
1948 return 0, 0, false
1949 }
1950 return max(start, ss.First), ss.Last, true
1951 }
1952
1953 // Returns true if LoadNextMsg should perform a linear scan,
1954 // false if it should use the subject tree to try to reduce
1955 // the search space.
1956 // Lock should be held.
1957 func (ms *memStore) shouldLinearScan(filter string, wc bool, start uint64) bool {
1958 // Skip scan of ms.fss if number of messages in the block are less than
1959 // 1/2 the number of subjects in ms.fss. Or we have a wc and lots of fss entries.
1960 const linearScanMaxFSS = 256
1961 isAll := filter == fwcs
1962 return isAll || 2*int(ms.state.LastSeq-start) < ms.fss.Size() || (wc && ms.fss.Size() > linearScanMaxFSS)
1963 }
1964
1965 // Lock should be held.
1966 func (ms *memStore) loadNextMsgLocked(filter string, wc bool, start uint64, smp *StoreMsg) (*StoreMsg, uint64, error) {
1967 if start < ms.state.FirstSeq {
1968 start = ms.state.FirstSeq
1969 }
1970
1971 // If past the end no results.
1972 if start > ms.state.LastSeq || ms.state.Msgs == 0 {
1973 return nil, ms.state.LastSeq, ErrStoreEOF
1974 }
1975
1976 if filter == _EMPTY_ {
1977 filter = fwcs
1978 }
1979 isAll := filter == fwcs
1980
1981 // Initial setup.
1982 fseq, lseq := start, ms.state.LastSeq
1983
1984 if !ms.shouldLinearScan(filter, wc, start) {
1985 var found bool
1986 if wc {
1987 fseq, lseq, found = ms.nextWildcardMatchLocked(filter, start)
1988 } else {
1989 fseq, lseq, found = ms.nextLiteralMatchLocked(filter, start)
1990 }
1991 if !found {
1992 return nil, ms.state.LastSeq, ErrStoreEOF
1993 }
1994 }
1995
1996 eq := subjectsEqual
1997 if wc {
1998 eq = matchLiteral
1999 }
2000
2001 for nseq := fseq; nseq <= lseq; nseq++ {
2002 if sm, ok := ms.msgs[nseq]; ok && (isAll || eq(sm.subj, filter)) {
2003 if smp == nil {
2004 smp = new(StoreMsg)
2005 }
2006 sm.copy(smp)
2007 return smp, nseq, nil
2008 }
2009 }
2010 return nil, ms.state.LastSeq, ErrStoreEOF
2011 }
2012
2013 // Will load the previous message matching the filter subject, starting at the start sequence and walking backwards.
2014 func (ms *memStore) LoadPrevMsg(filter string, wc bool, start uint64, smp *StoreMsg) (sm *StoreMsg, skip uint64, err error) {
2015 ms.mu.RLock()
2016 defer ms.mu.RUnlock()
2017
2018 if ms.msgs == nil {
2019 return nil, 0, ErrStoreClosed
2020 }
2021 if ms.state.Msgs == 0 || start < ms.state.FirstSeq {
2022 return nil, ms.state.FirstSeq, ErrStoreEOF
2023 }
2024 if start > ms.state.LastSeq {
2025 start = ms.state.LastSeq
2026 }
2027
2028 if filter == _EMPTY_ {
2029 filter = fwcs
2030 wc = true
2031 }
2032 isAll := filter == fwcs
2033 eq := subjectsEqual
2034 if wc {
2035 eq = matchLiteral
2036 }
2037
2038 for seq := start; seq >= ms.state.FirstSeq; seq-- {
2039 if sm, ok := ms.msgs[seq]; ok && (isAll || eq(sm.subj, filter)) {
2040 if smp == nil {
2041 smp = new(StoreMsg)
2042 }
2043 sm.copy(smp)
2044 return smp, seq, nil
2045 }
2046 }
2047 return nil, ms.state.FirstSeq, ErrStoreEOF
2048 }
2049
2050 // LoadPrevMsgMulti will find the previous message matching any entry in the sublist.
2051 func (ms *memStore) LoadPrevMsgMulti(sl *gsl.SimpleSublist, start uint64, smp *StoreMsg) (sm *StoreMsg, skip uint64, err error) {
2052 // TODO(dlc) - for now simple linear walk to get started.
2053 ms.mu.RLock()
2054 defer ms.mu.RUnlock()
2055
2056 if start > ms.state.LastSeq {
2057 start = ms.state.LastSeq
2058 }
2059
2060 // If past the start no results.
2061 if start < ms.state.FirstSeq || ms.state.Msgs == 0 {
2062 return nil, ms.state.FirstSeq, ErrStoreEOF
2063 }
2064
2065 // Initial setup.
2066 fseq, lseq := start, ms.state.FirstSeq
2067
2068 for nseq := fseq; nseq >= lseq; nseq-- {
2069 sm, ok := ms.msgs[nseq]
2070 if !ok {
2071 continue
2072 }
2073 if sl.HasInterest(sm.subj) {
2074 if smp == nil {
2075 smp = new(StoreMsg)
2076 }
2077 sm.copy(smp)
2078 return smp, nseq, nil
2079 }
2080 }
2081 return nil, ms.state.FirstSeq, ErrStoreEOF
2082 }
2083
2084 // RemoveMsg will remove the message from this store.
2085 // Will return the number of bytes removed.
2086 func (ms *memStore) RemoveMsg(seq uint64) (bool, error) {
2087 ms.mu.Lock()
2088 removed := ms.removeMsg(seq, false)
2089 ms.mu.Unlock()
2090 return removed, nil
2091 }
2092
2093 // EraseMsg will remove the message and rewrite its contents.
2094 func (ms *memStore) EraseMsg(seq uint64) (bool, error) {
2095 ms.mu.Lock()
2096 removed := ms.removeMsg(seq, true)
2097 ms.mu.Unlock()
2098 return removed, nil
2099 }
2100
2101 // Performs logic to update first sequence number.
2102 // Lock should be held.
2103 func (ms *memStore) updateFirstSeq(seq uint64) {
2104 if seq != ms.state.FirstSeq {
2105 // Interior delete.
2106 return
2107 }
2108 var nsm *StoreMsg
2109 var ok bool
2110 for nseq := ms.state.FirstSeq + 1; nseq <= ms.state.LastSeq; nseq++ {
2111 if nsm, ok = ms.msgs[nseq]; ok {
2112 break
2113 }
2114 }
2115 oldFirst := ms.state.FirstSeq
2116 if nsm != nil {
2117 ms.state.FirstSeq = nsm.seq
2118 ms.state.FirstTime = time.Unix(0, nsm.ts).UTC()
2119 } else {
2120 // Like purge.
2121 ms.state.FirstSeq = ms.state.LastSeq + 1
2122 ms.state.FirstTime = time.Time{}
2123 }
2124
2125 if oldFirst == ms.state.FirstSeq-1 {
2126 ms.dmap.Delete(oldFirst)
2127 } else {
2128 for seq := oldFirst; seq < ms.state.FirstSeq; seq++ {
2129 ms.dmap.Delete(seq)
2130 }
2131 }
2132 }
2133
2134 // Remove a seq from the fss and select new first.
2135 // Lock should be held.
2136 func (ms *memStore) removeSeqPerSubject(subj string, seq uint64) {
2137 ss, ok := ms.fss.Find(stringToBytes(subj))
2138 if !ok {
2139 return
2140 }
2141 ms.sdm.removeSeqAndSubject(seq, subj)
2142 if ss.Msgs == 1 {
2143 ms.fss.Delete(stringToBytes(subj))
2144 return
2145 }
2146 ss.Msgs--
2147
2148 // Only one left
2149 if ss.Msgs == 1 {
2150 if !ss.lastNeedsUpdate && seq != ss.Last {
2151 ss.First = ss.Last
2152 ss.firstNeedsUpdate = false
2153 return
2154 }
2155 if !ss.firstNeedsUpdate && seq != ss.First {
2156 ss.Last = ss.First
2157 ss.lastNeedsUpdate = false
2158 return
2159 }
2160 }
2161
2162 // We can lazily calculate the first/last sequence when needed.
2163 ss.firstNeedsUpdate = seq == ss.First || ss.firstNeedsUpdate
2164 ss.lastNeedsUpdate = seq == ss.Last || ss.lastNeedsUpdate
2165 }
2166
2167 // Will recalculate the first and/or last sequence for this subject.
2168 // Lock should be held.
2169 func (ms *memStore) recalculateForSubj(subj string, ss *SimpleState) {
2170 if ss.firstNeedsUpdate {
2171 tseq := ss.First + 1
2172 if tseq < ms.state.FirstSeq {
2173 tseq = ms.state.FirstSeq
2174 }
2175 for ; tseq <= ss.Last; tseq++ {
2176 if sm := ms.msgs[tseq]; sm != nil && sm.subj == subj {
2177 ss.First = tseq
2178 ss.firstNeedsUpdate = false
2179 if ss.Msgs == 1 {
2180 ss.Last = tseq
2181 ss.lastNeedsUpdate = false
2182 return
2183 }
2184 break
2185 }
2186 }
2187 }
2188 if ss.lastNeedsUpdate {
2189 tseq := ss.Last - 1
2190 if tseq > ms.state.LastSeq {
2191 tseq = ms.state.LastSeq
2192 }
2193 for ; tseq >= ss.First; tseq-- {
2194 if sm := ms.msgs[tseq]; sm != nil && sm.subj == subj {
2195 ss.Last = tseq
2196 ss.lastNeedsUpdate = false
2197 if ss.Msgs == 1 {
2198 ss.First = tseq
2199 ss.firstNeedsUpdate = false
2200 }
2201 return
2202 }
2203 }
2204 }
2205 }
2206
2207 // Removes the message referenced by seq.
2208 // Lock should be held.
2209 func (ms *memStore) removeMsg(seq uint64, secure bool) bool {
2210 subj, size, ok := ms.removeMsgNoCB(seq, secure)
2211 if !ok {
2212 return false
2213 }
2214 if ms.scb != nil {
2215 // We do not want to hold any locks here.
2216 ms.mu.Unlock()
2217 if ms.scb != nil {
2218 ms.scb(-1, -int64(size), seq, subj)
2219 }
2220 ms.mu.Lock()
2221 }
2222 return true
2223 }
2224
2225 // Removes the message referenced by seq, but without calling the storage callback.
2226 // Returns the removed message's subject and size.
2227 // Lock should be held.
2228 func (ms *memStore) removeMsgNoCB(seq uint64, secure bool) (subj string, size uint64, ok bool) {
2229 sm, ok := ms.msgs[seq]
2230 if !ok {
2231 return _EMPTY_, 0, false
2232 }
2233
2234 size = memStoreMsgSize(sm.subj, sm.hdr, sm.msg)
2235
2236 if ms.state.Msgs > 0 {
2237 ms.state.Msgs--
2238 if size > ms.state.Bytes {
2239 size = ms.state.Bytes
2240 }
2241 ms.state.Bytes -= size
2242 }
2243 ms.dmap.Insert(seq)
2244 ms.updateFirstSeq(seq)
2245
2246 // Remove any per subject tracking.
2247 ms.removeSeqPerSubject(sm.subj, seq)
2248 if ms.ttls != nil {
2249 if ttl, err := getMessageTTL(sm.hdr); err == nil {
2250 expires := time.Duration(sm.ts) + (time.Second * time.Duration(ttl))
2251 ms.ttls.Remove(seq, int64(expires))
2252 }
2253 }
2254
2255 if secure {
2256 if len(sm.hdr) > 0 {
2257 sm.hdr = make([]byte, len(sm.hdr))
2258 crand.Read(sm.hdr)
2259 }
2260 if len(sm.msg) > 0 {
2261 sm.msg = make([]byte, len(sm.msg))
2262 crand.Read(sm.msg)
2263 }
2264 sm.seq, sm.ts = 0, 0
2265 }
2266
2267 // Must delete message after updating per-subject info, to be consistent with file store.
2268 delete(ms.msgs, seq)
2269
2270 return sm.subj, size, true
2271 }
2272
2273 // Type returns the type of the underlying store.
2274 func (ms *memStore) Type() StorageType {
2275 return MemoryStorage
2276 }
2277
2278 // FastState will fill in state with only the following.
2279 // Msgs, Bytes, First and Last Sequence and Time and NumDeleted.
2280 func (ms *memStore) FastState(state *StreamState) {
2281 ms.mu.RLock()
2282 state.Msgs = ms.state.Msgs
2283 state.Bytes = ms.state.Bytes
2284 state.FirstSeq = ms.state.FirstSeq
2285 state.FirstTime = ms.state.FirstTime
2286 state.LastSeq = ms.state.LastSeq
2287 state.LastTime = ms.state.LastTime
2288 if state.LastSeq > state.FirstSeq {
2289 state.NumDeleted = int((state.LastSeq - state.FirstSeq + 1) - state.Msgs)
2290 if state.NumDeleted < 0 {
2291 state.NumDeleted = 0
2292 }
2293 }
2294 state.Consumers = ms.consumers
2295 state.NumSubjects = ms.fss.Size()
2296 ms.mu.RUnlock()
2297 }
2298
2299 func (ms *memStore) State() StreamState {
2300 ms.mu.Lock()
2301 defer ms.mu.Unlock()
2302
2303 state := ms.state
2304 state.Consumers = ms.consumers
2305 state.NumSubjects = ms.fss.Size()
2306 state.Deleted = nil
2307
2308 // Calculate interior delete details.
2309 if numDeleted := int((state.LastSeq - state.FirstSeq + 1) - state.Msgs); numDeleted > 0 {
2310 state.Deleted = make([]uint64, 0, numDeleted)
2311 fseq, lseq := state.FirstSeq, state.LastSeq
2312 ms.dmap.Range(func(seq uint64) bool {
2313 if seq < fseq || seq > lseq {
2314 ms.dmap.Delete(seq)
2315 } else {
2316 state.Deleted = append(state.Deleted, seq)
2317 }
2318 return true
2319 })
2320 }
2321 if len(state.Deleted) > 0 {
2322 state.NumDeleted = len(state.Deleted)
2323 }
2324
2325 return state
2326 }
2327
2328 func (ms *memStore) Utilization() (total, reported uint64, err error) {
2329 ms.mu.RLock()
2330 defer ms.mu.RUnlock()
2331 return ms.state.Bytes, ms.state.Bytes, nil
2332 }
2333
2334 func memStoreMsgSizeRaw(slen, hlen, mlen int) uint64 {
2335 return uint64(slen + hlen + mlen + 16) // 8*2 for seq + age
2336 }
2337
2338 func memStoreMsgSize(subj string, hdr, msg []byte) uint64 {
2339 return memStoreMsgSizeRaw(len(subj), len(hdr), len(msg))
2340 }
2341
2342 // ResetState resets any state that's temporary. For example when changing leaders.
2343 func (ms *memStore) ResetState() {
2344 ms.mu.Lock()
2345 defer ms.mu.Unlock()
2346 if ms.scheduling != nil {
2347 ms.scheduling.clearInflight()
2348 }
2349 }
2350
2351 // Delete is same as Stop for memory store.
2352 func (ms *memStore) Delete(_ bool) error {
2353 return ms.Stop()
2354 }
2355
2356 func (ms *memStore) Stop() error {
2357 ms.mu.Lock()
2358 if ms.msgs == nil {
2359 ms.mu.Unlock()
2360 return nil
2361 }
2362 if ms.ageChk != nil {
2363 ms.ageChk.Stop()
2364 ms.ageChk = nil
2365 ms.ageChkTime = 0
2366 }
2367 ms.msgs = nil
2368 ms.mu.Unlock()
2369
2370 // These can't come back, so stop is same as Delete.
2371 ms.Purge()
2372
2373 // Unregister from the access time service.
2374 ats.Unregister()
2375
2376 return nil
2377 }
2378
2379 func (ms *memStore) isClosed() bool {
2380 ms.mu.RLock()
2381 defer ms.mu.RUnlock()
2382 return ms.msgs == nil
2383 }
2384
2385 type consumerMemStore struct {
2386 mu sync.Mutex
2387 ms StreamStore
2388 cfg ConsumerConfig
2389 state ConsumerState
2390 closed bool
2391 }
2392
2393 func (ms *memStore) ConsumerStore(name string, _ time.Time, cfg *ConsumerConfig) (ConsumerStore, error) {
2394 if ms == nil {
2395 return nil, fmt.Errorf("memstore is nil")
2396 }
2397 if ms.isClosed() {
2398 return nil, ErrStoreClosed
2399 }
2400 if cfg == nil || name == _EMPTY_ {
2401 return nil, fmt.Errorf("bad consumer config")
2402 }
2403 o := &consumerMemStore{ms: ms, cfg: *cfg}
2404 ms.AddConsumer(o)
2405 return o, nil
2406 }
2407
2408 func (ms *memStore) AddConsumer(o ConsumerStore) error {
2409 ms.mu.Lock()
2410 ms.consumers++
2411 ms.mu.Unlock()
2412 return nil
2413 }
2414
2415 func (ms *memStore) RemoveConsumer(o ConsumerStore) error {
2416 ms.mu.Lock()
2417 if ms.consumers > 0 {
2418 ms.consumers--
2419 }
2420 ms.mu.Unlock()
2421 return nil
2422 }
2423
2424 func (ms *memStore) Snapshot(_ time.Duration, _, _ bool) (*SnapshotResult, error) {
2425 return nil, fmt.Errorf("no impl")
2426 }
2427
2428 // Binary encoded state snapshot, >= v2.10 server.
2429 func (ms *memStore) EncodedStreamState(failed uint64) ([]byte, error) {
2430 ms.mu.RLock()
2431 defer ms.mu.RUnlock()
2432
2433 // Quick calculate num deleted.
2434 numDeleted := int((ms.state.LastSeq - ms.state.FirstSeq + 1) - ms.state.Msgs)
2435 if numDeleted < 0 {
2436 numDeleted = 0
2437 }
2438
2439 // Encoded is Msgs, Bytes, FirstSeq, LastSeq, Failed, NumDeleted and optional DeletedBlocks.
2440 // Calculate the exact encoded size up front so the buffer is allocated once.
2441 total := hdrLen + uvarintLen(ms.state.Msgs) + uvarintLen(ms.state.Bytes) +
2442 uvarintLen(ms.state.FirstSeq) + uvarintLen(ms.state.LastSeq) +
2443 uvarintLen(failed) + uvarintLen(uint64(numDeleted))
2444
2445 if numDeleted > 0 {
2446 total += ms.dmap.EncodeLen()
2447 }
2448
2449 b := make([]byte, 0, total)
2450 b = append(b, streamStateMagic, streamStateVersion)
2451 b = binary.AppendUvarint(b, ms.state.Msgs)
2452 b = binary.AppendUvarint(b, ms.state.Bytes)
2453 b = binary.AppendUvarint(b, ms.state.FirstSeq)
2454 b = binary.AppendUvarint(b, ms.state.LastSeq)
2455 b = binary.AppendUvarint(b, failed)
2456 b = binary.AppendUvarint(b, uint64(numDeleted))
2457
2458 if numDeleted > 0 {
2459 enc := ms.dmap.Encode(b[len(b):])
2460 if n := len(b) + len(enc); n <= cap(b) {
2461 b = b[:n]
2462 } else {
2463 // Fallback if the buffer didn't have spare capacity.
2464 b = append(b, enc...)
2465 }
2466 }
2467
2468 if len(b) != total {
2469 assert.Unreachable("Memstore EncodedStreamState size accounting mismatch", map[string]any{
2470 "name": ms.cfg.Name,
2471 "total": total,
2472 "length": len(b),
2473 })
2474 }
2475 return b, nil
2476 }
2477
2478 // SyncDeleted will make sure this stream has same deleted state as dbs.
2479 func (ms *memStore) SyncDeleted(dbs DeleteBlocks) error {
2480 if len(dbs) == 0 {
2481 return nil
2482 }
2483
2484 ms.mu.Lock()
2485 defer ms.mu.Unlock()
2486
2487 // For now we share one dmap, so if we have one entry here check if states are the same.
2488 // Note this will work for any DeleteBlock type, but we expect this to be a dmap too.
2489 if len(dbs) == 1 {
2490 min, max, num := ms.dmap.State()
2491 if pmin, pmax, pnum := dbs[0].State(); pmin == min && pmax == max && pnum == num {
2492 return nil
2493 }
2494 }
2495 lseq := ms.state.LastSeq
2496 for _, db := range dbs {
2497 // Skip if beyond our current state.
2498 if first, _, _ := db.State(); first > lseq {
2499 continue
2500 }
2501 db.Range(func(seq uint64) bool {
2502 ms.removeMsg(seq, false)
2503 return true
2504 })
2505 }
2506 return nil
2507 }
2508
2509 func (o *consumerMemStore) Update(state *ConsumerState) error {
2510 // Sanity checks.
2511 if state.AckFloor.Consumer > state.Delivered.Consumer {
2512 return fmt.Errorf("bad ack floor for consumer")
2513 }
2514 if state.AckFloor.Stream > state.Delivered.Stream {
2515 return fmt.Errorf("bad ack floor for stream")
2516 }
2517
2518 // Copy to our state.
2519 var pending map[uint64]*Pending
2520 var redelivered map[uint64]uint64
2521 if len(state.Pending) > 0 {
2522 pending = make(map[uint64]*Pending, len(state.Pending))
2523 for seq, p := range state.Pending {
2524 pending[seq] = &Pending{p.Sequence, p.Timestamp}
2525 if seq <= state.AckFloor.Stream || seq > state.Delivered.Stream {
2526 return fmt.Errorf("bad pending entry, sequence [%d] out of range", seq)
2527 }
2528 }
2529 }
2530 if len(state.Redelivered) > 0 {
2531 redelivered = make(map[uint64]uint64, len(state.Redelivered))
2532 for seq, dc := range state.Redelivered {
2533 redelivered[seq] = dc
2534 }
2535 }
2536
2537 // Replace our state.
2538 o.mu.Lock()
2539 defer o.mu.Unlock()
2540
2541 // Check to see if this is an outdated update.
2542 if state.Delivered.Consumer < o.state.Delivered.Consumer || state.AckFloor.Stream < o.state.AckFloor.Stream {
2543 return ErrStoreOldUpdate
2544 }
2545
2546 o.state.Delivered = state.Delivered
2547 o.state.AckFloor = state.AckFloor
2548 o.state.Pending = pending
2549 o.state.Redelivered = redelivered
2550
2551 return nil
2552 }
2553
2554 func (o *consumerMemStore) ForceUpdate(state *ConsumerState) error {
2555 // Sanity checks.
2556 if state.AckFloor.Consumer > state.Delivered.Consumer {
2557 return fmt.Errorf("bad ack floor for consumer")
2558 }
2559 if state.AckFloor.Stream > state.Delivered.Stream {
2560 return fmt.Errorf("bad ack floor for stream")
2561 }
2562
2563 // Copy to our state.
2564 var pending map[uint64]*Pending
2565 var redelivered map[uint64]uint64
2566 if len(state.Pending) > 0 {
2567 pending = make(map[uint64]*Pending, len(state.Pending))
2568 for seq, p := range state.Pending {
2569 pending[seq] = &Pending{p.Sequence, p.Timestamp}
2570 if seq <= state.AckFloor.Stream || seq > state.Delivered.Stream {
2571 return fmt.Errorf("bad pending entry, sequence [%d] out of range", seq)
2572 }
2573 }
2574 }
2575 if len(state.Redelivered) > 0 {
2576 redelivered = make(map[uint64]uint64, len(state.Redelivered))
2577 for seq, dc := range state.Redelivered {
2578 redelivered[seq] = dc
2579 }
2580 }
2581
2582 // Replace our state.
2583 o.mu.Lock()
2584 defer o.mu.Unlock()
2585
2586 o.state.Delivered = state.Delivered
2587 o.state.AckFloor = state.AckFloor
2588 o.state.Pending = pending
2589 o.state.Redelivered = redelivered
2590
2591 return nil
2592 }
2593
2594 // SetStarting sets our starting stream sequence.
2595 func (o *consumerMemStore) SetStarting(sseq uint64) error {
2596 o.mu.Lock()
2597 o.state.Delivered.Stream = sseq
2598 o.state.AckFloor.Stream = sseq
2599 o.mu.Unlock()
2600 return nil
2601 }
2602
2603 // UpdateStarting updates our starting stream sequence.
2604 func (o *consumerMemStore) UpdateStarting(sseq uint64) {
2605 o.mu.Lock()
2606 defer o.mu.Unlock()
2607
2608 if sseq > o.state.Delivered.Stream {
2609 o.state.Delivered.Stream = sseq
2610 // For AckNone just update delivered and ackfloor at the same time.
2611 if o.cfg.AckPolicy == AckNone {
2612 o.state.AckFloor.Stream = sseq
2613 }
2614 }
2615 }
2616
2617 // Reset all values in the store, and reset the starting sequence.
2618 func (o *consumerMemStore) Reset(sseq uint64) error {
2619 o.mu.Lock()
2620 o.state = ConsumerState{}
2621 o.mu.Unlock()
2622 return o.SetStarting(sseq)
2623 }
2624
2625 // HasState returns if this store has a recorded state.
2626 func (o *consumerMemStore) HasState() bool {
2627 o.mu.Lock()
2628 defer o.mu.Unlock()
2629 // We have a running state.
2630 return o.state.Delivered.Consumer != 0 || o.state.Delivered.Stream != 0
2631 }
2632
2633 func (o *consumerMemStore) UpdateDelivered(dseq, sseq, dc uint64, ts int64) error {
2634 o.mu.Lock()
2635 defer o.mu.Unlock()
2636
2637 if dc != 1 && o.cfg.AckPolicy == AckNone {
2638 return ErrNoAckPolicy
2639 }
2640
2641 // On restarts the old leader may get a replay from the raft logs that are old.
2642 if dseq <= o.state.AckFloor.Consumer {
2643 return nil
2644 }
2645
2646 // See if we expect an ack for this.
2647 if o.cfg.AckPolicy != AckNone {
2648 // Need to create pending records here.
2649 if o.state.Pending == nil {
2650 o.state.Pending = make(map[uint64]*Pending)
2651 }
2652 var p *Pending
2653 // Check for an update to a message already delivered.
2654 if sseq <= o.state.Delivered.Stream {
2655 if p = o.state.Pending[sseq]; p != nil {
2656 // Do not update p.Sequence, that should be the original delivery sequence.
2657 p.Timestamp = ts
2658 }
2659 } else {
2660 // Add to pending.
2661 o.state.Pending[sseq] = &Pending{dseq, ts}
2662 }
2663 // Update delivered as needed.
2664 if dseq > o.state.Delivered.Consumer {
2665 o.state.Delivered.Consumer = dseq
2666 }
2667 if sseq > o.state.Delivered.Stream {
2668 o.state.Delivered.Stream = sseq
2669 }
2670
2671 if dc > 1 {
2672 if maxdc := uint64(o.cfg.MaxDeliver); maxdc > 0 && dc > maxdc {
2673 // Make sure to remove from pending.
2674 delete(o.state.Pending, sseq)
2675 }
2676 if o.state.Redelivered == nil {
2677 o.state.Redelivered = make(map[uint64]uint64)
2678 }
2679 // Only update if greater than what we already have.
2680 if o.state.Redelivered[sseq] < dc-1 {
2681 o.state.Redelivered[sseq] = dc - 1
2682 }
2683 }
2684 } else {
2685 // For AckNone just update delivered and ackfloor at the same time.
2686 if dseq > o.state.Delivered.Consumer {
2687 o.state.Delivered.Consumer = dseq
2688 o.state.AckFloor.Consumer = dseq
2689 }
2690 if sseq > o.state.Delivered.Stream {
2691 o.state.Delivered.Stream = sseq
2692 o.state.AckFloor.Stream = sseq
2693 }
2694 }
2695
2696 return nil
2697 }
2698
2699 func (o *consumerMemStore) UpdateAcks(dseq, sseq uint64) error {
2700 o.mu.Lock()
2701 defer o.mu.Unlock()
2702
2703 if o.cfg.AckPolicy == AckNone {
2704 return ErrNoAckPolicy
2705 }
2706
2707 // We do this regardless.
2708 delete(o.state.Redelivered, sseq)
2709
2710 // On restarts the old leader may get a replay from the raft logs that are old.
2711 if dseq <= o.state.AckFloor.Consumer {
2712 return nil
2713 }
2714
2715 if len(o.state.Pending) == 0 || o.state.Pending[sseq] == nil {
2716 return ErrStoreMsgNotFound
2717 }
2718
2719 // Check for AckAll here (or AckFlowControl which functions like AckAll).
2720 if o.cfg.AckPolicy == AckAll || o.cfg.AckPolicy == AckFlowControl {
2721 sgap := sseq - o.state.AckFloor.Stream
2722 o.state.AckFloor.Consumer = dseq
2723 o.state.AckFloor.Stream = sseq
2724 if sgap > uint64(len(o.state.Pending)) {
2725 for seq := range o.state.Pending {
2726 if seq <= sseq {
2727 delete(o.state.Pending, seq)
2728 delete(o.state.Redelivered, seq)
2729 }
2730 }
2731 } else {
2732 for seq := sseq; seq > sseq-sgap && len(o.state.Pending) > 0; seq-- {
2733 delete(o.state.Pending, seq)
2734 delete(o.state.Redelivered, seq)
2735 }
2736 }
2737 return nil
2738 }
2739
2740 // AckExplicit
2741
2742 // First delete from our pending state.
2743 if p, ok := o.state.Pending[sseq]; ok {
2744 delete(o.state.Pending, sseq)
2745 if dseq > p.Sequence && p.Sequence > 0 {
2746 dseq = p.Sequence // Use the original.
2747 }
2748 }
2749
2750 if len(o.state.Pending) == 0 {
2751 o.state.AckFloor.Consumer = o.state.Delivered.Consumer
2752 o.state.AckFloor.Stream = o.state.Delivered.Stream
2753 } else if dseq == o.state.AckFloor.Consumer+1 {
2754 o.state.AckFloor.Consumer = dseq
2755 o.state.AckFloor.Stream = sseq
2756
2757 if o.state.Delivered.Consumer > dseq {
2758 for ss := sseq + 1; ss <= o.state.Delivered.Stream; ss++ {
2759 if p, ok := o.state.Pending[ss]; ok {
2760 if p.Sequence > 0 {
2761 o.state.AckFloor.Consumer = p.Sequence - 1
2762 o.state.AckFloor.Stream = ss - 1
2763 }
2764 break
2765 }
2766 }
2767 }
2768 }
2769
2770 return nil
2771 }
2772
2773 func (o *consumerMemStore) RemoveRedeliveredBelow(seq uint64) {
2774 if seq == 0 {
2775 return
2776 }
2777 o.mu.Lock()
2778 defer o.mu.Unlock()
2779 for s := range o.state.Redelivered {
2780 if s < seq {
2781 delete(o.state.Redelivered, s)
2782 }
2783 }
2784 }
2785
2786 func (o *consumerMemStore) UpdateConfig(cfg *ConsumerConfig) error {
2787 o.mu.Lock()
2788 defer o.mu.Unlock()
2789
2790 // This is mostly unchecked here. We are assuming the upper layers have done sanity checking.
2791 o.cfg = *cfg
2792 return nil
2793 }
2794
2795 func (o *consumerMemStore) Stop() error {
2796 o.mu.Lock()
2797 o.closed = true
2798 ms := o.ms
2799 o.mu.Unlock()
2800 ms.RemoveConsumer(o)
2801 return nil
2802 }
2803
2804 func (o *consumerMemStore) Delete() error {
2805 return o.Stop()
2806 }
2807
2808 func (o *consumerMemStore) StreamDelete() error {
2809 return o.Stop()
2810 }
2811
2812 func (o *consumerMemStore) State() (*ConsumerState, error) {
2813 return o.stateWithCopy(true)
2814 }
2815
2816 // This will not copy pending or redelivered, so should only be done under the
2817 // consumer owner's lock.
2818 func (o *consumerMemStore) BorrowState() (*ConsumerState, error) {
2819 return o.stateWithCopy(false)
2820 }
2821
2822 func (o *consumerMemStore) stateWithCopy(doCopy bool) (*ConsumerState, error) {
2823 o.mu.Lock()
2824 defer o.mu.Unlock()
2825
2826 if o.closed {
2827 return nil, ErrStoreClosed
2828 }
2829
2830 state := &ConsumerState{}
2831
2832 state.Delivered = o.state.Delivered
2833 state.AckFloor = o.state.AckFloor
2834 if len(o.state.Pending) > 0 {
2835 if doCopy {
2836 state.Pending = o.copyPending()
2837 } else {
2838 state.Pending = o.state.Pending
2839 }
2840 }
2841 if len(o.state.Redelivered) > 0 {
2842 if doCopy {
2843 state.Redelivered = o.copyRedelivered()
2844 } else {
2845 state.Redelivered = o.state.Redelivered
2846 }
2847 }
2848 return state, nil
2849 }
2850
2851 // EncodedState for this consumer store.
2852 func (o *consumerMemStore) EncodedState() ([]byte, error) {
2853 o.mu.Lock()
2854 defer o.mu.Unlock()
2855
2856 if o.closed {
2857 return nil, ErrStoreClosed
2858 }
2859
2860 return encodeConsumerState(&o.state), nil
2861 }
2862
2863 func (o *consumerMemStore) copyPending() map[uint64]*Pending {
2864 pending := make(map[uint64]*Pending, len(o.state.Pending))
2865 for seq, p := range o.state.Pending {
2866 pending[seq] = &Pending{p.Sequence, p.Timestamp}
2867 }
2868 return pending
2869 }
2870
2871 func (o *consumerMemStore) copyRedelivered() map[uint64]uint64 {
2872 redelivered := make(map[uint64]uint64, len(o.state.Redelivered))
2873 for seq, dc := range o.state.Redelivered {
2874 redelivered[seq] = dc
2875 }
2876 return redelivered
2877 }
2878
2879 // Type returns the type of the underlying store.
2880 func (o *consumerMemStore) Type() StorageType { return MemoryStorage }