Debian Codegraph @

server/filestore.go

raw
1 // Copyright 2019-2026 The NATS Authors
2 // Licensed under the Apache License, Version 2.0 (the "License");
3 // you may not use this file except in compliance with the License.
4 // You may obtain a copy of the License at
5 //
6 // http://www.apache.org/licenses/LICENSE-2.0
7 //
8 // Unless required by applicable law or agreed to in writing, software
9 // distributed under the License is distributed on an "AS IS" BASIS,
10 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11 // See the License for the specific language governing permissions and
12 // limitations under the License.
13
14 package server
15
16 import (
17 "archive/tar"
18 "bytes"
19 "cmp"
20 "crypto/aes"
21 "crypto/cipher"
22 "crypto/rand"
23 "crypto/sha256"
24 "encoding/binary"
25 "encoding/hex"
26 "encoding/json"
27 "errors"
28 "fmt"
29 "io"
30 "io/fs"
31 "math"
32 mrand "math/rand"
33 "net"
34 "os"
35 "path/filepath"
36 "runtime"
37 "runtime/debug"
38 "slices"
39 "sort"
40 "strings"
41 "sync"
42 "sync/atomic"
43 "time"
44
45 "github.com/antithesishq/antithesis-sdk-go/assert"
46 "github.com/klauspost/compress/s2"
47 "github.com/minio/highwayhash"
48 "github.com/nats-io/nats-server/v2/server/ats"
49 "github.com/nats-io/nats-server/v2/server/avl"
50 "github.com/nats-io/nats-server/v2/server/elastic"
51 "github.com/nats-io/nats-server/v2/server/gsl"
52 "github.com/nats-io/nats-server/v2/server/stree"
53 "github.com/nats-io/nats-server/v2/server/thw"
54 "golang.org/x/crypto/chacha20"
55 "golang.org/x/crypto/chacha20poly1305"
56 )
57
58 type FileStoreConfig struct {
59 // Where the parent directory for all storage will be located.
60 StoreDir string
61 // BlockSize is the file block size. This also represents the maximum overhead size.
62 BlockSize uint64
63 // CacheExpire is how long with no activity until we expire the cache.
64 CacheExpire time.Duration
65 // SubjectStateExpire is how long with no activity until we expire a msg block's subject state.
66 SubjectStateExpire time.Duration
67 // SyncInterval is how often we sync to disk in the background.
68 SyncInterval time.Duration
69 // SyncAlways is when the stream should sync all data writes.
70 SyncAlways bool
71 // AsyncFlush allows async flush to batch write operations.
72 AsyncFlush bool
73 // Cipher is the cipher to use when encrypting.
74 Cipher StoreCipher
75 // Compression is the algorithm to use when compressing.
76 Compression StoreCompression
77
78 // Internal reference to our server.
79 srv *Server
80 }
81
82 // FileStreamInfo allows us to remember created time.
83 type FileStreamInfo struct {
84 Created time.Time
85 StreamConfig
86 }
87
88 type StoreCipher int
89
90 const (
91 ChaCha StoreCipher = iota
92 AES
93 NoCipher
94 )
95
96 func (cipher StoreCipher) String() string {
97 switch cipher {
98 case ChaCha:
99 return "ChaCha20-Poly1305"
100 case AES:
101 return "AES-GCM"
102 case NoCipher:
103 return "None"
104 default:
105 return "Unknown StoreCipher"
106 }
107 }
108
109 type StoreCompression uint8
110
111 const (
112 NoCompression StoreCompression = iota
113 S2Compression
114 )
115
116 func (alg StoreCompression) String() string {
117 switch alg {
118 case NoCompression:
119 return "None"
120 case S2Compression:
121 return "S2"
122 default:
123 return "Unknown StoreCompression"
124 }
125 }
126
127 func (alg StoreCompression) MarshalJSON() ([]byte, error) {
128 var str string
129 switch alg {
130 case S2Compression:
131 str = "s2"
132 case NoCompression:
133 str = "none"
134 default:
135 return nil, fmt.Errorf("unknown compression algorithm")
136 }
137 return json.Marshal(str)
138 }
139
140 func (alg *StoreCompression) UnmarshalJSON(b []byte) error {
141 var str string
142 if err := json.Unmarshal(b, &str); err != nil {
143 return err
144 }
145 switch str {
146 case "s2":
147 *alg = S2Compression
148 case "none":
149 *alg = NoCompression
150 default:
151 return fmt.Errorf("unknown compression algorithm")
152 }
153 return nil
154 }
155
156 // File ConsumerInfo is used for creating consumer stores.
157 type FileConsumerInfo struct {
158 Created time.Time
159 Name string
160 ConsumerConfig
161 }
162
163 // Default file and directory permissions.
164 const (
165 defaultDirPerms = os.FileMode(0700)
166 defaultFilePerms = os.FileMode(0600)
167 )
168
169 type psi struct {
170 total uint64
171 fblk uint32
172 lblk uint32
173 }
174
175 type fileStore struct {
176 srv *Server
177 mu sync.RWMutex
178 state StreamState
179 tombs []uint64
180 ld *LostStreamData
181 scb StorageUpdateHandler
182 rmcb StorageRemoveMsgHandler
183 pmsgcb ProcessJetStreamMsgHandler
184 ageChk *time.Timer // Timer to expire messages.
185 ageChkRun bool // Whether message expiration is currently running.
186 ageChkTime int64 // When the message expiration is scheduled to run.
187 syncTmr *time.Timer
188 cfg FileStreamInfo
189 fcfg FileStoreConfig
190 syncAlways atomic.Bool // Mirrors FileStoreConfig.SyncAlways for lock-free reads from writeFileWithOptionalSync.
191 prf keyGen
192 oldprf keyGen
193 aek cipher.AEAD
194 lmb *msgBlock
195 blks []*msgBlock
196 bim map[uint32]*msgBlock
197 psim *stree.SubjectTree[psi]
198 tsl int
199 wfsmu sync.Mutex // Only one writeFullState at a time to protect from overwrites.
200 wfsrun atomic.Int64 // Is writeFullState already running? For timer check only
201 wfsadml int // writeFullState average dmap length, protected by wfsmu.
202 hh *highwayhash.Digest64
203 qch chan struct{}
204 fsld chan struct{}
205 cmu sync.RWMutex
206 cfs []ConsumerStore
207 werr error
208 sips int
209 dirty int
210 closing bool
211 closed atomic.Bool // Atomic to reduce contention on ConsumerStores.
212 fip bool
213 receivedAny bool
214 firstMoved bool
215 ttls *thw.HashWheel
216 scheduling *MsgScheduling
217 sdm *SDMMeta
218 lpex time.Time // Last PurgeEx call.
219 dios *diskIOSemaphore
220 }
221
222 // Represents a message store block and its data.
223 type msgBlock struct {
224 // Here for 32bit systems and atomic.
225 first msgId
226 last msgId
227 mu sync.RWMutex
228 fs *fileStore
229 aek cipher.AEAD
230 bek cipher.Stream
231 seed []byte
232 nonce []byte
233 mfn string
234 mfd *os.File
235 cmp StoreCompression // Effective compression at the time of loading the block
236 liwsz int64
237 index uint32
238 bytes uint64 // User visible bytes count.
239 rbytes uint64 // Total bytes (raw) including deleted. Used for rolling to new blk.
240 cbytes uint64 // Bytes count after last compaction. 0 if no compaction happened yet.
241 msgs uint64 // User visible message count.
242 fss *stree.SubjectTree[SimpleState]
243 kfn string
244 lwts int64
245 llts int64
246 lrts int64
247 lsts int64
248 llseq uint64
249 hh *highwayhash.Digest64
250 ecache elastic.Pointer[cache]
251 cache *cache
252 cloads uint64
253 cexp time.Duration
254 fexp time.Duration
255 ctmr *time.Timer
256 werr error
257 dmap avl.SequenceSet
258 fch chan struct{}
259 qch chan struct{}
260 lchk [8]byte
261 loading bool
262 flusher bool
263 noTrack bool
264 needSync bool
265 needKeySync bool // Key file is written once and immutable, cleared after its one sync.
266 syncAlways bool
267 noCompact bool
268 closed bool
269 ttls uint64 // How many msgs have TTLs?
270 schedules uint64 // How many msgs have schedules?
271
272 // Used to mock write failures.
273 mockWriteErr bool
274 }
275
276 // Write through caching layer that is also used on loading messages.
277 type cache struct {
278 buf []byte
279 wp int
280 idx []uint32
281 fseq uint64
282 nra bool
283 // When GC collects this cache due to it being a weak pointer,
284 // recycle the buf back into the block buffer pools.
285 clean runtime.Cleanup
286 }
287
288 type msgId struct {
289 seq uint64
290 ts int64
291 }
292
293 const (
294 // Magic is used to identify the file store files.
295 magic = uint8(22)
296 // Version
297 version = uint8(1)
298 // New IndexInfo Version
299 newVersion = uint8(2)
300 // hdrLen
301 hdrLen = 2
302 // This is where we keep the streams.
303 streamsDir = "streams"
304 // This is where we keep inflight batches for streams.
305 batchesDir = "batches"
306 // This is where we keep the message store blocks.
307 msgDir = "msgs"
308 // This is where we temporarily move the messages dir.
309 purgeDir = "__msgs__"
310 // This is where we temporarily move the new message block during purge.
311 newMsgDir = "__new_msgs__"
312 // used to scan blk file names.
313 blkScan = "%d.blk"
314 // suffix of a block file
315 blkSuffix = ".blk"
316 // used for compacted blocks that are staged.
317 newScan = "%d.new"
318 // used to scan index file names.
319 indexScan = "%d.idx"
320 // used to store our block encryption key.
321 keyScan = "%d.key"
322 // to look for orphans
323 keyScanAll = "*.key"
324 // This is where we keep state on consumers.
325 consumerDir = "obs"
326 // Index file for a consumer.
327 consumerState = "o.dat"
328 // The suffix that will be given to a new temporary block for compression or when rewriting the full file.
329 blkTmpSuffix = ".tmp"
330 // default cache buffer expiration
331 defaultCacheBufferExpiration = 10 * time.Second
332 // default sync interval
333 defaultSyncInterval = 2 * time.Minute
334 // default idle timeout to close FDs.
335 closeFDsIdle = 30 * time.Second
336 // default expiration time for mb.fss when idle.
337 defaultFssExpiration = 2 * time.Minute
338 // coalesceMinimum
339 coalesceMinimum = 16 * 1024
340 // maxFlushWait is maximum we will wait to gather messages to flush.
341 maxFlushWait = 8 * time.Millisecond
342
343 // Metafiles for streams and consumers.
344 JetStreamMetaFile = "meta.inf"
345 JetStreamMetaFileSum = "meta.sum"
346 JetStreamMetaFileKey = "meta.key"
347
348 // This is the full snapshotted state for the stream.
349 streamStreamStateFile = "index.db"
350
351 // This is the encoded time hash wheel for TTLs.
352 ttlStreamStateFile = "thw.db"
353
354 // This is the encoded message scheduling file.
355 msgSchedulingStreamStateFile = "sched.db"
356
357 // AEK key sizes
358 minMetaKeySize = 64
359 minBlkKeySize = 64
360
361 // Default stream block size.
362 defaultLargeBlockSize = 8 * 1024 * 1024 // 8MB
363 // Default for workqueue or interest based.
364 defaultMediumBlockSize = 4 * 1024 * 1024 // 4MB
365 // For smaller reuse buffers. Usually being generated during contention on the lead write buffer.
366 // E.g. mirrors/sources etc.
367 defaultSmallBlockSize = 1 * 1024 * 1024 // 1MB
368 // NOT an actual block size, but used for the sync.Pools, so that we don't allocate huge buffers
369 // unnecessarily until there are enough writes to justify it.
370 defaultTinyBlockSize = 1 * 1024 * 256 // 256KB
371 // Maximum size for the encrypted head block.
372 maximumEncryptedBlockSize = 2 * 1024 * 1024 // 2MB
373 // Default for KV based
374 defaultKVBlockSize = defaultMediumBlockSize
375 // max block size for now.
376 maxBlockSize = defaultLargeBlockSize
377 // Compact minimum threshold.
378 compactMinimum = 2 * 1024 * 1024 // 2MB
379 // FileStoreMinBlkSize is minimum size we will do for a blk size.
380 FileStoreMinBlkSize = 32 * 1000 // 32kib
381 // FileStoreMaxBlkSize is maximum size we will do for a blk size.
382 FileStoreMaxBlkSize = maxBlockSize
383 // Check for bad record length value due to corrupt data.
384 rlBadThresh = 32 * 1024 * 1024
385 // Checksum size for hash for msg records.
386 recordHashSize = 8
387
388 // Above this number of subjects, index.db may not be written regularly anymore, and
389 // certain psim optimisations may not be used.
390 highCardinalityThreshold = 1_000_000
391 )
392
393 func newFileStore(fcfg FileStoreConfig, cfg StreamConfig) (*fileStore, error) {
394 return newFileStoreWithCreated(fcfg, cfg, time.Now().UTC(), nil, nil)
395 }
396
397 func newFileStoreWithCreated(fcfg FileStoreConfig, cfg StreamConfig, created time.Time, prf, oldprf keyGen) (fs *fileStore, err error) {
398 if cfg.Name == _EMPTY_ {
399 return nil, fmt.Errorf("name required")
400 }
401 if cfg.Storage != FileStorage {
402 return nil, fmt.Errorf("fileStore requires file storage type in config")
403 }
404 // Default values.
405 if fcfg.BlockSize == 0 {
406 fcfg.BlockSize = dynBlkSize(cfg.Retention, cfg.MaxBytes, prf != nil)
407 }
408 if fcfg.BlockSize > maxBlockSize {
409 return nil, fmt.Errorf("filestore max block size is %s", friendlyBytes(maxBlockSize))
410 }
411 if fcfg.CacheExpire == 0 {
412 fcfg.CacheExpire = defaultCacheBufferExpiration
413 }
414 if fcfg.SubjectStateExpire == 0 {
415 fcfg.SubjectStateExpire = defaultFssExpiration
416 }
417 if fcfg.SyncInterval == 0 {
418 fcfg.SyncInterval = defaultSyncInterval
419 }
420 dios := fcfg.srv.diskIOSemaphore()
421
422 // Check the directory
423 if stat, err := os.Stat(fcfg.StoreDir); os.IsNotExist(err) {
424 if err := os.MkdirAll(fcfg.StoreDir, defaultDirPerms); err != nil {
425 return nil, fmt.Errorf("could not create storage directory - %v", err)
426 }
427 } else if stat == nil || !stat.IsDir() {
428 return nil, fmt.Errorf("storage directory is not a directory")
429 }
430 tmpfile, err := os.CreateTemp(fcfg.StoreDir, "_test_")
431 if err != nil {
432 return nil, fmt.Errorf("storage directory is not writable")
433 }
434
435 tmpfile.Close()
436 dios.acquire()
437 os.Remove(tmpfile.Name())
438 dios.release()
439
440 fs = &fileStore{
441 fcfg: fcfg,
442 dios: dios,
443 psim: stree.NewSubjectTree[psi](),
444 bim: make(map[uint32]*msgBlock),
445 cfg: FileStreamInfo{Created: created, StreamConfig: cfg},
446 prf: prf,
447 oldprf: oldprf,
448 qch: make(chan struct{}),
449 fsld: make(chan struct{}),
450 srv: fcfg.srv,
451 }
452 fs.syncAlways.Store(fcfg.SyncAlways)
453
454 // Register with access time service.
455 ats.Register()
456
457 // If we error before completion make sure to cleanup.
458 defer func() {
459 if err != nil {
460 ats.Unregister()
461 }
462 }()
463
464 // Only create a THW if we're going to allow TTLs.
465 if cfg.AllowMsgTTL {
466 fs.ttls = thw.NewHashWheel()
467 }
468 // Only create scheduling data structure if we're going to allow message schedules.
469 if cfg.AllowMsgSchedules {
470 fs.scheduling = newMsgScheduling(fs.runMsgScheduling)
471 }
472
473 // Set flush in place to AsyncFlush which by default is false.
474 fs.fip = !fcfg.AsyncFlush
475
476 // Check if this is a new setup.
477 mdir := filepath.Join(fcfg.StoreDir, msgDir)
478 odir := filepath.Join(fcfg.StoreDir, consumerDir)
479 if err := os.MkdirAll(mdir, defaultDirPerms); err != nil {
480 return nil, fmt.Errorf("could not create message storage directory - %v", err)
481 }
482 if err := os.MkdirAll(odir, defaultDirPerms); err != nil {
483 return nil, fmt.Errorf("could not create consumer storage directory - %v", err)
484 }
485
486 // Create highway hash for message blocks. Use sha256 of directory as key.
487 key := sha256.Sum256([]byte(cfg.Name))
488 fs.hh, err = highwayhash.NewDigest64(key[:])
489 if err != nil {
490 return nil, fmt.Errorf("could not create hash: %v", err)
491 }
492
493 keyFile := filepath.Join(fs.fcfg.StoreDir, JetStreamMetaFileKey)
494 _, err = os.Stat(keyFile)
495 // Either the file should exist (err=nil), or it shouldn't. Any other error is reported.
496 if err != nil && !os.IsNotExist(err) {
497 return nil, err
498 }
499 // Make sure we do not have an encrypted store underneath of us but no main key.
500 if fs.prf == nil && err == nil {
501 return nil, errNoMainKey
502 } else if fs.prf != nil && err == nil {
503 // If encryption is configured and the key file exists, recover our keys.
504 if err = fs.recoverAEK(); err != nil {
505 return nil, err
506 }
507 }
508
509 // Attempt to recover our state.
510 err = fs.recoverFullState()
511 if err != nil {
512 if !os.IsNotExist(err) {
513 fs.warn("Recovering stream state from index errored: %v", err)
514 }
515 // Hold onto state
516 prior := fs.state
517 // Reset anything that could have been set from above.
518 fs.state = StreamState{}
519 fs.psim, fs.tsl = fs.psim.Empty(), 0
520 fs.bim = make(map[uint32]*msgBlock)
521 fs.blks = nil
522 fs.tombs = nil
523
524 // Recover our message state the old way
525 if err := fs.recoverMsgs(); err != nil {
526 return nil, err
527 }
528
529 fs.mu.Lock()
530 // Check if our prior state remembers a last sequence past where we can see.
531 // Unless we're async flushing, in which case this can happen if some blocks weren't flushed.
532 if prior.LastSeq > fs.state.LastSeq && !fs.fcfg.AsyncFlush {
533 if mb, err := fs.newMsgBlockForWrite(); err != nil {
534 fs.mu.Unlock()
535 return nil, err
536 } else if err = mb.writeTombstone(prior.LastSeq, prior.LastTime.UnixNano()); err != nil {
537 fs.mu.Unlock()
538 return nil, err
539 }
540 fs.state.LastSeq, fs.state.LastTime = prior.LastSeq, prior.LastTime
541 if fs.state.Msgs == 0 {
542 fs.state.FirstSeq = fs.state.LastSeq + 1
543 fs.state.FirstTime = time.Time{}
544 }
545 }
546 // Since we recovered here, make sure to kick ourselves to write out our stream state.
547 fs.dirty++
548 fs.mu.Unlock()
549 }
550
551 // Lock during the remainder of the recovery.
552 fs.mu.Lock()
553 // Use defer to ensure the lock is released if any of the enforcement operations
554 // run into issues to avoid potential deadlocks on exit.
555 unlocked := false
556 defer func() {
557 if !unlocked {
558 fs.mu.Unlock()
559 }
560 }()
561
562 // See if we can bring back our TTL timed hash wheel state from disk.
563 if cfg.AllowMsgTTL {
564 if err = fs.recoverTTLState(); err != nil && !os.IsNotExist(err) {
565 fs.warn("Recovering TTL state from index errored: %v", err)
566 }
567 }
568
569 // See if we can bring back our message scheduling state from disk.
570 if cfg.AllowMsgSchedules {
571 if err = fs.recoverMsgSchedulingState(); err != nil && !os.IsNotExist(err) {
572 fs.warn("Recovering message scheduling state from index errored: %v", err)
573 }
574 }
575
576 // Also make sure we get rid of old idx and fss files on return.
577 // Do this in separate go routine vs inline and at end of processing.
578 defer func() {
579 if fs != nil {
580 go fs.cleanupOldMeta()
581 }
582 }()
583
584 // Check if we have any left over tombstones to process.
585 if len(fs.tombs) > 0 {
586 for _, seq := range fs.tombs {
587 _, err = fs.removeMsg(seq, false, true, false)
588 if err != nil && err != ErrStoreEOF && err != ErrStoreMsgNotFound {
589 return nil, err
590 }
591 fs.removeFromLostData(seq)
592 }
593 // Not needed after this phase.
594 fs.tombs = nil
595 }
596
597 // Limits checks and enforcement.
598 if err = fs.enforceMsgLimit(); err != nil {
599 return nil, err
600 }
601 if err = fs.enforceBytesLimit(); err != nil {
602 return nil, err
603 }
604
605 // Do age checks too, make sure to call in place.
606 if fs.cfg.MaxAge != 0 {
607 if err = fs.expireMsgsOnRecover(); err != nil {
608 return nil, err
609 }
610 fs.startAgeChk()
611 }
612
613 // If we have max msgs per subject make sure the is also enforced.
614 if fs.cfg.MaxMsgsPer > 0 {
615 if err = fs.enforceMsgPerSubjectLimit(false); err != nil {
616 return nil, err
617 }
618 }
619
620 // Grab first sequence for check below while we have lock.
621 firstSeq := fs.state.FirstSeq
622 fs.mu.Unlock()
623 unlocked = true
624
625 // If the stream has an initial sequence number then make sure we
626 // have purged up until that point. We will do this only if the
627 // recovered first sequence number is before our configured first
628 // sequence. Need to do this locked as by now the age check timer
629 // has started.
630 if cfg.FirstSeq > 0 && firstSeq < cfg.FirstSeq {
631 if _, err := fs.purge(cfg.FirstSeq); err != nil {
632 return nil, err
633 }
634 }
635
636 // Write our meta data if it does not exist or is zero'd out.
637 meta := filepath.Join(fcfg.StoreDir, JetStreamMetaFile)
638 fi, err := os.Stat(meta)
639 if err != nil && os.IsNotExist(err) || fi != nil && fi.Size() == 0 {
640 if err := fs.writeStreamMeta(); err != nil {
641 return nil, err
642 }
643 }
644
645 // If we expect to be encrypted check that what we are restoring is not plaintext.
646 // This can happen on snapshot restores or conversions.
647 if fs.prf != nil {
648 if _, err := os.Stat(keyFile); err != nil && os.IsNotExist(err) {
649 if err := fs.writeStreamMeta(); err != nil {
650 return nil, err
651 }
652 }
653 }
654
655 // Setup our sync timer.
656 fs.setSyncTimer()
657
658 // Spin up the go routine that will write out our full state stream index.
659 go fs.flushStreamStateLoop(fs.qch, fs.fsld)
660
661 return fs, nil
662 }
663
664 // Lock all existing message blocks.
665 // Lock held on entry.
666 func (fs *fileStore) lockAllMsgBlocks() {
667 for _, mb := range fs.blks {
668 mb.mu.Lock()
669 }
670 }
671
672 // Unlock all existing message blocks.
673 // Lock held on entry.
674 func (fs *fileStore) unlockAllMsgBlocks() {
675 for _, mb := range fs.blks {
676 mb.mu.Unlock()
677 }
678 }
679
680 func (fs *fileStore) setCreatedTime(created time.Time) {
681 fs.mu.Lock()
682 fs.cfg.Created = created
683 fs.mu.Unlock()
684 }
685
686 func (fs *fileStore) UpdateConfig(cfg *StreamConfig) error {
687 start := time.Now()
688 defer func() {
689 if took := time.Since(start); took > time.Minute {
690 fs.warn("UpdateConfig took %v", took.Round(time.Millisecond))
691 }
692 }()
693
694 if fs.isClosed() {
695 return ErrStoreClosed
696 }
697 if cfg.Name == _EMPTY_ {
698 return fmt.Errorf("name required")
699 }
700 if cfg.Storage != FileStorage {
701 return fmt.Errorf("fileStore requires file storage type in config")
702 }
703 if cfg.MaxMsgsPer < -1 {
704 cfg.MaxMsgsPer = -1
705 }
706
707 fs.mu.Lock()
708 new_cfg := FileStreamInfo{Created: fs.cfg.Created, StreamConfig: *cfg}
709 old_cfg := fs.cfg
710 // The reference story has changed here, so this full msg block lock
711 // may not be needed.
712 fs.lockAllMsgBlocks()
713 fs.cfg = new_cfg
714 fs.unlockAllMsgBlocks()
715 if err := fs.writeStreamMeta(); err != nil {
716 fs.lockAllMsgBlocks()
717 fs.cfg = old_cfg
718 fs.unlockAllMsgBlocks()
719 fs.mu.Unlock()
720 return err
721 }
722
723 // Create or delete the THW if needed.
724 if cfg.AllowMsgTTL && fs.ttls == nil {
725 if err := fs.recoverTTLState(); err != nil {
726 fs.mu.Unlock()
727 return err
728 }
729 } else if !cfg.AllowMsgTTL && fs.ttls != nil {
730 fs.ttls = nil
731 }
732 // Create or delete the message scheduling state if needed.
733 if cfg.AllowMsgSchedules && fs.scheduling == nil {
734 if err := fs.recoverMsgSchedulingState(); err != nil {
735 fs.mu.Unlock()
736 return err
737 }
738 } else if !cfg.AllowMsgSchedules && fs.scheduling != nil {
739 fs.scheduling = nil
740 }
741
742 // Limits checks and enforcement.
743 if err := fs.enforceMsgLimit(); err != nil {
744 fs.mu.Unlock()
745 return err
746 }
747 if err := fs.enforceBytesLimit(); err != nil {
748 fs.mu.Unlock()
749 return err
750 }
751
752 // Do age timers.
753 if fs.ageChk == nil && fs.cfg.MaxAge != 0 {
754 fs.startAgeChk()
755 }
756 if fs.ageChk != nil && fs.cfg.MaxAge == 0 {
757 fs.ageChk.Stop()
758 fs.ageChk = nil
759 fs.ageChkTime = 0
760 }
761
762 if fs.cfg.MaxMsgsPer > 0 && (old_cfg.MaxMsgsPer <= 0 || fs.cfg.MaxMsgsPer < old_cfg.MaxMsgsPer) {
763 if err := fs.enforceMsgPerSubjectLimit(true); err != nil {
764 fs.mu.Unlock()
765 return err
766 }
767 }
768
769 if lmb := fs.lmb; lmb != nil {
770 // Enable/disable async flush depending on if it's supported and already initialized.
771 supportsAsyncFlush := !fs.fcfg.SyncAlways && cfg.Replicas > 1
772
773 // Async persist mode opts in to async flushing,
774 // sync always would also be disabled if it was configured.
775 if cfg.PersistMode == AsyncPersistMode {
776 supportsAsyncFlush = true
777 fs.fcfg.SyncAlways = false
778 fs.syncAlways.Store(false)
779 lmb.mu.Lock()
780 lmb.syncAlways = false
781 lmb.mu.Unlock()
782 }
783
784 if supportsAsyncFlush && !fs.fcfg.AsyncFlush {
785 fs.fcfg.AsyncFlush = true
786 lmb.spinUpFlushLoop()
787 } else if !supportsAsyncFlush && fs.fcfg.AsyncFlush {
788 fs.fcfg.AsyncFlush = false
789 lmb.mu.Lock()
790 // Quit the flush loop.
791 if lmb.qch != nil {
792 close(lmb.qch)
793 lmb.qch = nil
794 }
795 _, err := lmb.flushPendingMsgsLocked()
796 lmb.mu.Unlock()
797 if err != nil {
798 fs.mu.Unlock()
799 return err
800 }
801 }
802 // Set flush in place to AsyncFlush which by default is false.
803 fs.fip = !fs.fcfg.AsyncFlush
804 }
805 fs.mu.Unlock()
806
807 if cfg.MaxAge != 0 || cfg.AllowMsgTTL {
808 fs.expireMsgs()
809 }
810 if cfg.AllowMsgSchedules {
811 fs.runMsgScheduling()
812 }
813 return nil
814 }
815
816 func dynBlkSize(retention RetentionPolicy, maxBytes int64, encrypted bool) uint64 {
817 if maxBytes > 0 {
818 blkSize := (maxBytes / 4) + 1 // (25% overhead)
819 // Round up to nearest 100
820 if m := blkSize % 100; m != 0 {
821 blkSize += 100 - m
822 }
823 if blkSize <= FileStoreMinBlkSize {
824 blkSize = FileStoreMinBlkSize
825 } else if blkSize >= FileStoreMaxBlkSize {
826 blkSize = FileStoreMaxBlkSize
827 } else {
828 blkSize = defaultMediumBlockSize
829 }
830 if encrypted && blkSize > maximumEncryptedBlockSize {
831 // Notes on this below.
832 blkSize = maximumEncryptedBlockSize
833 }
834 return uint64(blkSize)
835 }
836
837 switch {
838 case encrypted:
839 // In the case of encrypted stores, large blocks can result in worsened perf
840 // since many writes on disk involve re-encrypting the entire block. For now,
841 // we will enforce a cap on the block size when encryption is enabled to avoid
842 // this.
843 return maximumEncryptedBlockSize
844 case retention == LimitsPolicy:
845 // TODO(dlc) - Make the blocksize relative to this if set.
846 return defaultLargeBlockSize
847 default:
848 // TODO(dlc) - Make the blocksize relative to this if set.
849 return defaultMediumBlockSize
850 }
851 }
852
853 func genEncryptionKey(sc StoreCipher, seed []byte) (ek cipher.AEAD, err error) {
854 if sc == ChaCha {
855 ek, err = chacha20poly1305.NewX(seed)
856 } else if sc == AES {
857 block, e := aes.NewCipher(seed)
858 if e != nil {
859 return nil, e
860 }
861 ek, err = cipher.NewGCMWithNonceSize(block, block.BlockSize())
862 } else {
863 err = errUnknownCipher
864 }
865 return ek, err
866 }
867
868 // Generate an asset encryption key from the context and server PRF.
869 func (fs *fileStore) genEncryptionKeys(context string) (aek cipher.AEAD, bek cipher.Stream, seed, encrypted []byte, err error) {
870 if fs.prf == nil {
871 return nil, nil, nil, nil, errNoEncryption
872 }
873 // Generate key encryption key.
874 rb, err := fs.prf([]byte(context))
875 if err != nil {
876 return nil, nil, nil, nil, err
877 }
878
879 sc := fs.fcfg.Cipher
880
881 kek, err := genEncryptionKey(sc, rb)
882 if err != nil {
883 return nil, nil, nil, nil, err
884 }
885 // Generate random asset encryption key seed.
886
887 const seedSize = 32
888 seed = make([]byte, seedSize)
889 if n, err := rand.Read(seed); err != nil {
890 return nil, nil, nil, nil, err
891 } else if n != seedSize {
892 return nil, nil, nil, nil, fmt.Errorf("not enough seed bytes read (%d != %d", n, seedSize)
893 }
894
895 aek, err = genEncryptionKey(sc, seed)
896 if err != nil {
897 return nil, nil, nil, nil, err
898 }
899
900 // Generate our nonce. Use same buffer to hold encrypted seed.
901 nonce := make([]byte, kek.NonceSize(), kek.NonceSize()+len(seed)+kek.Overhead())
902 if n, err := rand.Read(nonce); err != nil {
903 return nil, nil, nil, nil, err
904 } else if n != len(nonce) {
905 return nil, nil, nil, nil, fmt.Errorf("not enough nonce bytes read (%d != %d)", n, len(nonce))
906 }
907
908 bek, err = genBlockEncryptionKey(sc, seed[:], nonce)
909 if err != nil {
910 return nil, nil, nil, nil, err
911 }
912
913 return aek, bek, seed, kek.Seal(nonce, nonce, seed, nil), nil
914 }
915
916 // Will generate the block encryption key.
917 func genBlockEncryptionKey(sc StoreCipher, seed, nonce []byte) (cipher.Stream, error) {
918 if sc == ChaCha {
919 return chacha20.NewUnauthenticatedCipher(seed, nonce)
920 } else if sc == AES {
921 block, err := aes.NewCipher(seed)
922 if err != nil {
923 return nil, err
924 }
925 return cipher.NewCTR(block, nonce), nil
926 }
927 return nil, errUnknownCipher
928 }
929
930 // Lock should be held.
931 func (fs *fileStore) recoverAEK() error {
932 if fs.prf != nil && fs.aek == nil {
933 ekey, err := os.ReadFile(filepath.Join(fs.fcfg.StoreDir, JetStreamMetaFileKey))
934 if err != nil {
935 return err
936 }
937 rb, err := fs.prf([]byte(fs.cfg.Name))
938 if err != nil {
939 return err
940 }
941 kek, err := genEncryptionKey(fs.fcfg.Cipher, rb)
942 if err != nil {
943 return err
944 }
945 ns := kek.NonceSize()
946 seed, err := kek.Open(nil, ekey[:ns], ekey[ns:], nil)
947 if err != nil {
948 return err
949 }
950 aek, err := genEncryptionKey(fs.fcfg.Cipher, seed)
951 if err != nil {
952 return err
953 }
954 fs.aek = aek
955 }
956 return nil
957 }
958
959 // Lock should be held.
960 func (fs *fileStore) setupAEK() error {
961 if fs.prf != nil && fs.aek == nil {
962 key, _, _, encrypted, err := fs.genEncryptionKeys(fs.cfg.Name)
963 if err != nil {
964 return err
965 }
966 keyFile := filepath.Join(fs.fcfg.StoreDir, JetStreamMetaFileKey)
967 if _, err := os.Stat(keyFile); err != nil && !os.IsNotExist(err) {
968 return err
969 }
970 err = fs.writeFileWithOptionalSync(keyFile, encrypted, defaultFilePerms)
971 if err != nil {
972 return err
973 }
974 // Set our aek.
975 fs.aek = key
976 }
977 return nil
978 }
979
980 // Write out meta and the checksum.
981 // Lock should be held.
982 func (fs *fileStore) writeStreamMeta() error {
983 if err := fs.setupAEK(); err != nil {
984 return err
985 }
986
987 meta := filepath.Join(fs.fcfg.StoreDir, JetStreamMetaFile)
988 if _, err := os.Stat(meta); err != nil && !os.IsNotExist(err) {
989 return err
990 }
991 b, err := json.Marshal(fs.cfg)
992 if err != nil {
993 return err
994 }
995 // Encrypt if needed.
996 if fs.aek != nil {
997 nonce := make([]byte, fs.aek.NonceSize(), fs.aek.NonceSize()+len(b)+fs.aek.Overhead())
998 if n, err := rand.Read(nonce); err != nil {
999 return err
1000 } else if n != len(nonce) {
1001 return fmt.Errorf("not enough nonce bytes read (%d != %d)", n, len(nonce))
1002 }
1003 b = fs.aek.Seal(nonce, nonce, b, nil)
1004 }
1005
1006 err = fs.writeFileWithOptionalSync(meta, b, defaultFilePerms)
1007 if err != nil {
1008 return err
1009 }
1010 fs.hh.Reset()
1011 fs.hh.Write(b)
1012 var hb [highwayhash.Size64]byte
1013 checksum := hex.EncodeToString(fs.hh.Sum(hb[:0]))
1014 sum := filepath.Join(fs.fcfg.StoreDir, JetStreamMetaFileSum)
1015 err = fs.writeFileWithOptionalSync(sum, []byte(checksum), defaultFilePerms)
1016 if err != nil {
1017 return err
1018 }
1019 return nil
1020 }
1021
1022 // Pools to recycle the blocks to help with memory pressure.
1023 var blkPoolTiny = &sync.Pool{
1024 New: func() any {
1025 b := [defaultTinyBlockSize]byte{}
1026 return &b
1027 },
1028 }
1029 var blkPoolSmall = &sync.Pool{
1030 New: func() any {
1031 b := [defaultSmallBlockSize]byte{}
1032 return &b
1033 },
1034 }
1035 var blkPoolMedium = &sync.Pool{
1036 New: func() any {
1037 b := [defaultMediumBlockSize]byte{}
1038 return &b
1039 },
1040 }
1041 var blkPoolBig = &sync.Pool{
1042 New: func() any {
1043 b := [defaultLargeBlockSize]byte{}
1044 return &b
1045 },
1046 }
1047
1048 // Get a new msg block based on sz estimate.
1049 func getMsgBlockBuf(sz int) (buf []byte) {
1050 switch {
1051 case sz <= defaultTinyBlockSize:
1052 return blkPoolTiny.Get().(*[defaultTinyBlockSize]byte)[:0]
1053 case sz <= defaultSmallBlockSize:
1054 return blkPoolSmall.Get().(*[defaultSmallBlockSize]byte)[:0]
1055 case sz <= defaultMediumBlockSize:
1056 return blkPoolMedium.Get().(*[defaultMediumBlockSize]byte)[:0]
1057 case sz <= defaultLargeBlockSize:
1058 return blkPoolBig.Get().(*[defaultLargeBlockSize]byte)[:0]
1059 default:
1060 // Ideally this should not happen, once we return a buffer that's
1061 // larger than defaultLargeBlockSize then we will refuse to recycle
1062 // it to stop the pools from bloating excessively.
1063 return make([]byte, 0, sz)
1064 }
1065 }
1066
1067 // registerRecycle arranges for the cache's buffer to be returned to the
1068 // block buffer pools when the cache itself is garbage collected due to it
1069 // remaining as a weak pointer. Without it, subsequent block loads would
1070 // allocate fresh buffers, which could result in GC re-running, which is
1071 // pathological under sustained block loads.
1072 func (c *cache) registerRecycle() {
1073 if c == nil {
1074 return
1075 }
1076 // Any previous registration is canceled first.
1077 c.stopRecycle()
1078 // Skip if recycle isn't allowed or nothing to recycle.
1079 if c.nra || cap(c.buf) == 0 {
1080 return
1081 }
1082 // Don't make this cleanup conditional (e.g. skip if under memory pressure), GC
1083 // will drain the block buffer pools separately, so this doesn't pin memory.
1084 // Skipping would be worse, we'd delay freeing the buffer until the next GC cycle.
1085 c.clean = runtime.AddCleanup(c, recycleMsgBlockBuf, c.buf)
1086 }
1087
1088 // stopRecycle cancels a pending recycle registration. Must be called before
1089 // the buffer is recycled or handed off explicitly, otherwise the cleanup
1090 // could return the same buffer to the pool a second time while it is in use.
1091 func (c *cache) stopRecycle() {
1092 if c.clean != (runtime.Cleanup{}) {
1093 c.clean.Stop()
1094 c.clean = runtime.Cleanup{}
1095 }
1096 }
1097
1098 // Recycle the msg block.
1099 func recycleMsgBlockBuf(buf []byte) {
1100 switch cap(buf) {
1101 case defaultTinyBlockSize:
1102 b := (*[defaultTinyBlockSize]byte)(buf[0:defaultTinyBlockSize])
1103 blkPoolTiny.Put(b)
1104 case defaultSmallBlockSize:
1105 b := (*[defaultSmallBlockSize]byte)(buf[0:defaultSmallBlockSize])
1106 blkPoolSmall.Put(b)
1107 case defaultMediumBlockSize:
1108 b := (*[defaultMediumBlockSize]byte)(buf[0:defaultMediumBlockSize])
1109 blkPoolMedium.Put(b)
1110 case defaultLargeBlockSize:
1111 b := (*[defaultLargeBlockSize]byte)(buf[0:defaultLargeBlockSize])
1112 blkPoolBig.Put(b)
1113 default:
1114 // Too large, let the GC collect it instead.
1115 }
1116 }
1117
1118 const (
1119 msgHdrSize = 22
1120 checksumSize = 8
1121 emptyRecordLen = msgHdrSize + checksumSize
1122 )
1123
1124 // Lock should be held.
1125 func (fs *fileStore) noTrackSubjects() bool {
1126 return !(fs.psim.Size() > 0 || len(fs.cfg.Subjects) > 0 || fs.cfg.Mirror != nil || len(fs.cfg.Sources) > 0)
1127 }
1128
1129 // Will init the basics for a message block.
1130 func (fs *fileStore) initMsgBlock(index uint32) *msgBlock {
1131 mb := &msgBlock{
1132 fs: fs,
1133 index: index,
1134 cexp: fs.fcfg.CacheExpire,
1135 fexp: fs.fcfg.SubjectStateExpire,
1136 noTrack: fs.noTrackSubjects(),
1137 syncAlways: fs.fcfg.SyncAlways,
1138 }
1139
1140 mdir := filepath.Join(fs.fcfg.StoreDir, msgDir)
1141 mb.mfn = filepath.Join(mdir, fmt.Sprintf(blkScan, index))
1142
1143 if mb.hh == nil {
1144 key := sha256.Sum256(fs.hashKeyForBlock(index))
1145 mb.hh, _ = highwayhash.NewDigest64(key[:])
1146 }
1147 return mb
1148 }
1149
1150 // Check for encryption, we do not load keys on startup anymore so might need to load them here.
1151 // Lock for fs should be held.
1152 func (mb *msgBlock) checkAndLoadEncryption() error {
1153 if mb.fs != nil && mb.fs.prf != nil && (mb.aek == nil || mb.bek == nil) {
1154 if err := mb.fs.loadEncryptionForMsgBlock(mb); err != nil {
1155 return err
1156 }
1157 }
1158 return nil
1159 }
1160
1161 // Lock for fs should be held.
1162 func (fs *fileStore) loadEncryptionForMsgBlock(mb *msgBlock) error {
1163 if fs.prf == nil {
1164 return nil
1165 }
1166
1167 var createdKeys bool
1168 mdir := filepath.Join(fs.fcfg.StoreDir, msgDir)
1169 ekey, err := os.ReadFile(filepath.Join(mdir, fmt.Sprintf(keyScan, mb.index)))
1170 if err != nil {
1171 // We do not seem to have keys even though we should. Could be a plaintext conversion.
1172 // Create the keys and we will double check below.
1173 if err := fs.genEncryptionKeysForBlock(mb); err != nil {
1174 return err
1175 }
1176 createdKeys = true
1177 } else {
1178 if len(ekey) < minBlkKeySize {
1179 return errBadKeySize
1180 }
1181 // Recover key encryption key.
1182 rb, err := fs.prf([]byte(fmt.Sprintf("%s:%d", fs.cfg.Name, mb.index)))
1183 if err != nil {
1184 return err
1185 }
1186
1187 sc := fs.fcfg.Cipher
1188 kek, err := genEncryptionKey(sc, rb)
1189 if err != nil {
1190 return err
1191 }
1192 ns := kek.NonceSize()
1193 seed, err := kek.Open(nil, ekey[:ns], ekey[ns:], nil)
1194 if err != nil {
1195 // We may be here on a cipher conversion, so attempt to convert.
1196 if err = mb.convertCipher(); err != nil {
1197 return err
1198 }
1199 } else {
1200 mb.seed, mb.nonce = seed, ekey[:ns]
1201 }
1202 mb.aek, err = genEncryptionKey(sc, mb.seed)
1203 if err != nil {
1204 return err
1205 }
1206 if mb.bek, err = genBlockEncryptionKey(sc, mb.seed, mb.nonce); err != nil {
1207 return err
1208 }
1209 }
1210
1211 // If we created keys here, let's check the data and if it is plaintext convert here.
1212 if createdKeys {
1213 if err := mb.convertToEncrypted(); err != nil {
1214 return err
1215 }
1216 }
1217
1218 return nil
1219 }
1220
1221 // Load a last checksum if needed from the block file.
1222 // Lock should be held.
1223 func (mb *msgBlock) ensureLastChecksumLoaded() {
1224 var empty [8]byte
1225 if mb.lchk != empty {
1226 return
1227 }
1228 copy(mb.lchk[0:], mb.lastChecksum())
1229 }
1230
1231 // Lock held on entry
1232 func (fs *fileStore) recoverMsgBlock(index uint32) (*msgBlock, error) {
1233 mb := fs.initMsgBlock(index)
1234 // Open up the message file, but we will try to recover from the index file.
1235 // We will check that the last checksums match.
1236 file, err := mb.openBlock()
1237 if err != nil {
1238 return nil, err
1239 }
1240 defer file.Close()
1241
1242 if fi, err := file.Stat(); fi != nil {
1243 mb.rbytes = uint64(fi.Size())
1244 } else {
1245 return nil, err
1246 }
1247
1248 // Make sure encryption loaded if needed.
1249 if err = fs.loadEncryptionForMsgBlock(mb); err != nil {
1250 // If the encryption key is truncated or unrecoverable, return the block so it can be deleted.
1251 if err == errBadKeySize || err == errKeyInvalid {
1252 return mb, err
1253 }
1254 return nil, err
1255 }
1256
1257 // Grab last checksum from main block file.
1258 var lchk [8]byte
1259 if mb.rbytes >= checksumSize {
1260 if mb.bek != nil {
1261 // We pass nil, so get a buf from the block pool, we'll need to recycle it afterward.
1262 buf, _ := mb.loadBlock(nil)
1263 if len(buf) >= checksumSize {
1264 mb.bek.XORKeyStream(buf, buf)
1265 copy(lchk[0:], buf[len(buf)-checksumSize:])
1266 }
1267 // We can recycle it now.
1268 recycleMsgBlockBuf(buf)
1269 } else if _, err = file.ReadAt(lchk[:], int64(mb.rbytes)-checksumSize); err != nil {
1270 return nil, err
1271 }
1272 }
1273
1274 if err = file.Close(); err != nil {
1275 return nil, err
1276 }
1277
1278 // Read our index file. Use this as source of truth if possible.
1279 // This not applicable in >= 2.10 servers. Here for upgrade paths from < 2.10.
1280 if err := mb.readIndexInfo(); err == nil {
1281 // Quick sanity check here.
1282 // Note this only checks that the message blk file is not newer then this file, or is empty and we expect empty.
1283 if (mb.rbytes == 0 && mb.msgs == 0) || bytes.Equal(lchk[:], mb.lchk[:]) {
1284 if mb.msgs > 0 && !mb.noTrack && fs.psim != nil {
1285 if err = fs.populateGlobalPerSubjectInfo(mb); err != nil {
1286 return nil, err
1287 }
1288 // Try to dump any state we needed on recovery.
1289 mb.tryForceExpireCacheLocked()
1290 }
1291 fs.addMsgBlock(mb)
1292 return mb, nil
1293 }
1294 }
1295
1296 // If we get data loss rebuilding the message block state record that with the fs itself.
1297 ld, tombs, err := mb.rebuildState()
1298 if err != nil {
1299 return nil, err
1300 } else if ld != nil {
1301 fs.addLostData(ld)
1302 }
1303 // Collect all tombstones.
1304 if len(tombs) > 0 {
1305 fs.tombs = append(fs.tombs, tombs...)
1306 }
1307
1308 if mb.msgs > 0 && !mb.noTrack && fs.psim != nil {
1309 if err = fs.populateGlobalPerSubjectInfo(mb); err != nil {
1310 return nil, err
1311 }
1312 // Try to dump any state we needed on recovery.
1313 mb.tryForceExpireCacheLocked()
1314 }
1315
1316 if err = mb.closeFDs(); err != nil {
1317 return nil, err
1318 }
1319 fs.addMsgBlock(mb)
1320
1321 return mb, nil
1322 }
1323
1324 func (fs *fileStore) lostData() *LostStreamData {
1325 fs.mu.RLock()
1326 defer fs.mu.RUnlock()
1327 if fs.ld == nil {
1328 return nil
1329 }
1330 nld := *fs.ld
1331 return &nld
1332 }
1333
1334 // Lock should be held.
1335 func (fs *fileStore) addLostData(ld *LostStreamData) {
1336 if ld == nil {
1337 return
1338 }
1339 if fs.ld != nil {
1340 var added bool
1341 for _, seq := range ld.Msgs {
1342 if _, found := fs.ld.exists(seq); !found {
1343 fs.ld.Msgs = append(fs.ld.Msgs, seq)
1344 added = true
1345 }
1346 }
1347 if added {
1348 msgs := fs.ld.Msgs
1349 slices.Sort(msgs)
1350 fs.ld.Bytes += ld.Bytes
1351 }
1352 } else {
1353 fs.ld = ld
1354 }
1355 }
1356
1357 // Helper to see if we already have this sequence reported in our lost data.
1358 func (ld *LostStreamData) exists(seq uint64) (int, bool) {
1359 i := slices.IndexFunc(ld.Msgs, func(i uint64) bool {
1360 return i == seq
1361 })
1362 return i, i > -1
1363 }
1364
1365 func (fs *fileStore) removeFromLostData(seq uint64) {
1366 if fs.ld == nil {
1367 return
1368 }
1369 if i, found := fs.ld.exists(seq); found {
1370 fs.ld.Msgs = append(fs.ld.Msgs[:i], fs.ld.Msgs[i+1:]...)
1371 if len(fs.ld.Msgs) == 0 {
1372 fs.ld = nil
1373 }
1374 }
1375 }
1376
1377 func (fs *fileStore) rebuildState(ld *LostStreamData) {
1378 fs.mu.Lock()
1379 defer fs.mu.Unlock()
1380 fs.rebuildStateLocked(ld)
1381 }
1382
1383 // Lock should be held.
1384 func (fs *fileStore) rebuildStateLocked(ld *LostStreamData) {
1385 fs.addLostData(ld)
1386
1387 fs.state.Msgs, fs.state.Bytes = 0, 0
1388 fs.state.FirstSeq, fs.state.LastSeq = 0, 0
1389
1390 for _, mb := range fs.blks {
1391 mb.mu.RLock()
1392 fs.state.Msgs += mb.msgs
1393 fs.state.Bytes += mb.bytes
1394 fseq := atomic.LoadUint64(&mb.first.seq)
1395 if fs.state.FirstSeq == 0 || (fseq < fs.state.FirstSeq && mb.first.ts != 0) {
1396 fs.state.FirstSeq = fseq
1397 if mb.first.ts == 0 {
1398 fs.state.FirstTime = time.Time{}
1399 } else {
1400 fs.state.FirstTime = time.Unix(0, mb.first.ts).UTC()
1401 }
1402 }
1403 // Preserve last time, could have erased the last message in one block, and then
1404 // have a tombstone with the proper timestamp afterward in another block
1405 if lseq := atomic.LoadUint64(&mb.last.seq); lseq >= fs.state.LastSeq {
1406 fs.state.LastSeq = lseq
1407 if mb.last.ts == 0 {
1408 fs.state.LastTime = time.Time{}
1409 } else {
1410 fs.state.LastTime = time.Unix(0, mb.last.ts).UTC()
1411 }
1412 }
1413 mb.mu.RUnlock()
1414 }
1415 }
1416
1417 // Attempt to convert the cipher used for this message block.
1418 func (mb *msgBlock) convertCipher() error {
1419 fs := mb.fs
1420 sc := fs.fcfg.Cipher
1421
1422 var osc StoreCipher
1423 switch sc {
1424 case ChaCha:
1425 osc = AES
1426 case AES:
1427 osc = ChaCha
1428 }
1429
1430 mdir := filepath.Join(fs.fcfg.StoreDir, msgDir)
1431 ekey, err := os.ReadFile(filepath.Join(mdir, fmt.Sprintf(keyScan, mb.index)))
1432 if err != nil {
1433 return err
1434 }
1435 if len(ekey) < minBlkKeySize {
1436 return errBadKeySize
1437 }
1438 type prfWithCipher struct {
1439 keyGen
1440 StoreCipher
1441 }
1442 var prfs []prfWithCipher
1443 if fs.prf != nil {
1444 prfs = append(prfs, prfWithCipher{fs.prf, sc})
1445 prfs = append(prfs, prfWithCipher{fs.prf, osc})
1446 }
1447 if fs.oldprf != nil {
1448 prfs = append(prfs, prfWithCipher{fs.oldprf, sc})
1449 prfs = append(prfs, prfWithCipher{fs.oldprf, osc})
1450 }
1451
1452 for _, prf := range prfs {
1453 // Recover key encryption key.
1454 rb, err := prf.keyGen([]byte(fmt.Sprintf("%s:%d", fs.cfg.Name, mb.index)))
1455 if err != nil {
1456 continue
1457 }
1458 kek, err := genEncryptionKey(prf.StoreCipher, rb)
1459 if err != nil {
1460 continue
1461 }
1462 ns := kek.NonceSize()
1463 seed, err := kek.Open(nil, ekey[:ns], ekey[ns:], nil)
1464 if err != nil {
1465 continue
1466 }
1467 nonce := ekey[:ns]
1468 bek, err := genBlockEncryptionKey(prf.StoreCipher, seed, nonce)
1469 if err != nil {
1470 return err
1471 }
1472
1473 buf, _ := mb.loadBlock(nil)
1474 bek.XORKeyStream(buf, buf)
1475 // Check for compression, and make sure we can parse with old cipher and key file.
1476 if nbuf, err := mb.decompressIfNeeded(buf); err != nil {
1477 return err
1478 } else if _, _, err = mb.rebuildStateFromBufLocked(nbuf, false); err != nil {
1479 return err
1480 } else if err = mb.indexCacheBuf(nbuf); err != nil {
1481 return err
1482 }
1483
1484 // Reset the cache since we just read everything in.
1485 mb.cache.stopRecycle()
1486 mb.cache = nil
1487 mb.ecache.Set(nil)
1488
1489 // Generate new keys. If we error for some reason then we will put
1490 // the old keyfile back.
1491 if err := fs.genEncryptionKeysForBlock(mb); err != nil {
1492 keyFile := filepath.Join(mdir, fmt.Sprintf(keyScan, mb.index))
1493 writeFileWithSync(fs.dios, keyFile, ekey, defaultFilePerms)
1494 return err
1495 }
1496 mb.bek.XORKeyStream(buf, buf)
1497 mb.fs.dios.acquire()
1498 err = os.WriteFile(mb.mfn, buf, defaultFilePerms)
1499 mb.fs.dios.release()
1500 if err != nil {
1501 return err
1502 }
1503 return nil
1504 }
1505 return errKeyInvalid
1506 }
1507
1508 // Convert a plaintext block to encrypted.
1509 func (mb *msgBlock) convertToEncrypted() error {
1510 if mb.bek == nil {
1511 return nil
1512 }
1513 buf, err := mb.loadBlock(nil)
1514 if err != nil {
1515 return err
1516 }
1517 // Check for compression.
1518 if buf, err = mb.decompressIfNeeded(buf); err != nil {
1519 return err
1520 } else if _, _, err = mb.rebuildStateFromBufLocked(buf, false); err != nil {
1521 return err
1522 } else if err = mb.indexCacheBuf(buf); err != nil {
1523 // This likely indicates this was already encrypted or corrupt.
1524 mb.cache = nil
1525 mb.ecache.Set(nil)
1526 return err
1527 }
1528 // Undo cache from above for later.
1529 mb.cache.stopRecycle()
1530 mb.cache = nil
1531 mb.ecache.Set(nil)
1532 // Regenerate mb.bek so that the keystream offset is at zero. This matches
1533 // what encryptOrDecryptIfNeeded does on read-back, otherwise re-entering
1534 // convertToEncrypted with a previously-used mb.bek would write ciphertext at
1535 // the wrong stream offset and silently corrupt the block.
1536 if mb.bek, err = genBlockEncryptionKey(mb.fs.fcfg.Cipher, mb.seed, mb.nonce); err != nil {
1537 return err
1538 }
1539 mb.bek.XORKeyStream(buf, buf)
1540 mb.fs.dios.acquire()
1541 err = os.WriteFile(mb.mfn, buf, defaultFilePerms)
1542 mb.fs.dios.release()
1543 if err != nil {
1544 return err
1545 }
1546 return nil
1547 }
1548
1549 // Return the mb's index.
1550 func (mb *msgBlock) getIndex() uint32 {
1551 mb.mu.RLock()
1552 defer mb.mu.RUnlock()
1553 return mb.index
1554 }
1555
1556 // Rebuild the state of the blk based on what we have on disk in the N.blk file.
1557 // We will return any lost data, and we will return any delete tombstones we encountered.
1558 func (mb *msgBlock) rebuildState() (*LostStreamData, []uint64, error) {
1559 mb.mu.Lock()
1560 defer mb.mu.Unlock()
1561 return mb.rebuildStateLocked()
1562 }
1563
1564 // Rebuild the state of the blk based on what we have on disk in the N.blk file.
1565 // Lock should be held.
1566 func (mb *msgBlock) rebuildStateLocked() (*LostStreamData, []uint64, error) {
1567 // Remove the .fss file and clear any cache we have set.
1568 mb.clearCacheAndOffset()
1569
1570 buf, err := mb.loadBlock(nil)
1571 defer recycleMsgBlockBuf(buf)
1572
1573 if err != nil || len(buf) == 0 {
1574 // Only allow continuing to mark lost data if the file itself doesn't exist, or was empty.
1575 if err != nil && err != errNoBlkData {
1576 return nil, nil, err
1577 }
1578 var ld *LostStreamData
1579 // No data to rebuild from here.
1580 if mb.msgs > 0 {
1581 // We need to declare lost data here.
1582 ld = &LostStreamData{Msgs: make([]uint64, 0, mb.msgs), Bytes: mb.bytes}
1583 firstSeq, lastSeq := atomic.LoadUint64(&mb.first.seq), atomic.LoadUint64(&mb.last.seq)
1584 for seq := firstSeq; seq <= lastSeq; seq++ {
1585 if !mb.dmap.Exists(seq) {
1586 ld.Msgs = append(ld.Msgs, seq)
1587 }
1588 }
1589 // Clear invalid state. We will let this blk be added in here.
1590 mb.msgs, mb.bytes, mb.rbytes, mb.fss = 0, 0, 0, nil
1591 mb.dmap.Empty()
1592 atomic.StoreUint64(&mb.first.seq, atomic.LoadUint64(&mb.last.seq)+1)
1593 }
1594 return ld, nil, nil
1595 }
1596
1597 // Check if we need to decrypt.
1598 if err = mb.encryptOrDecryptIfNeeded(buf); err != nil {
1599 return nil, nil, err
1600 }
1601 // Check for compression.
1602 if buf, err = mb.decompressIfNeeded(buf); err != nil {
1603 return nil, nil, err
1604 }
1605 return mb.rebuildStateFromBufLocked(buf, true)
1606 }
1607
1608 // Lock should be held.
1609 func (mb *msgBlock) rebuildStateFromBufLocked(buf []byte, allowTruncate bool) (*LostStreamData, []uint64, error) {
1610 var err error
1611 startLastSeq := atomic.LoadUint64(&mb.last.seq)
1612
1613 // Clear state we need to rebuild.
1614 mb.msgs, mb.bytes, mb.rbytes, mb.fss = 0, 0, 0, nil
1615 atomic.StoreUint64(&mb.last.seq, 0)
1616 mb.last.ts = 0
1617 firstNeedsSet := true
1618
1619 mb.rbytes = uint64(len(buf))
1620
1621 addToDmap := func(seq uint64) {
1622 if seq == 0 {
1623 return
1624 }
1625 mb.dmap.Insert(seq)
1626 }
1627
1628 // For tombstones that we find and collect.
1629 var (
1630 tombstones []uint64
1631 maxTombstoneSeq uint64
1632 maxTombstoneTs int64
1633 )
1634
1635 defer func() {
1636 // For empty msg blocks make sure we recover last seq correctly based off of first.
1637 // Or if we seem to have no messages but had a tombstone, which we use to remember
1638 // sequences and timestamps now, use that to properly setup the first and last.
1639 if mb.msgs == 0 {
1640 fseq := atomic.LoadUint64(&mb.first.seq)
1641 if fseq > 0 {
1642 atomic.StoreUint64(&mb.last.seq, fseq-1)
1643 } else if fseq == 0 && maxTombstoneSeq > 0 {
1644 atomic.StoreUint64(&mb.first.seq, maxTombstoneSeq+1)
1645 mb.first.ts = 0
1646 if mb.last.seq == 0 {
1647 atomic.StoreUint64(&mb.last.seq, maxTombstoneSeq)
1648 mb.last.ts = maxTombstoneTs
1649 }
1650 }
1651 }
1652 }()
1653
1654 var le = binary.LittleEndian
1655
1656 // There are cases where we're not allowed to truncate, like for an encrypted or compressed
1657 // block since the index will be the decrypted and decompressed index.
1658 truncate := func(index uint32) error {
1659 var fd *os.File
1660 if mb.mfd != nil {
1661 fd = mb.mfd
1662 } else {
1663 mb.fs.dios.acquire()
1664 fd, err = os.OpenFile(mb.mfn, os.O_RDWR, defaultFilePerms)
1665 mb.fs.dios.release()
1666 if err == nil {
1667 defer fd.Close()
1668 }
1669 }
1670 if fd == nil {
1671 return nil
1672 }
1673 if err := fd.Truncate(int64(index)); err != nil {
1674 return err
1675 }
1676
1677 // Update our checksum.
1678 if index >= 8 {
1679 var lchk [8]byte
1680 if _, err = fd.ReadAt(lchk[:], int64(index-8)); err != nil {
1681 return err
1682 }
1683 copy(mb.lchk[0:], lchk[:])
1684 }
1685 if err = fd.Sync(); err != nil {
1686 return err
1687 }
1688 return nil
1689 }
1690
1691 gatherLost := func(lb uint32) *LostStreamData {
1692 var ld LostStreamData
1693 for seq := atomic.LoadUint64(&mb.last.seq) + 1; seq <= startLastSeq; seq++ {
1694 ld.Msgs = append(ld.Msgs, seq)
1695 }
1696 ld.Bytes = uint64(lb)
1697 return &ld
1698 }
1699
1700 // To detect gaps from compaction, and to ensure the sequence keeps moving up.
1701 var last uint64
1702 var hb [highwayhash.Size64]byte
1703
1704 updateLast := func(seq uint64, ts int64) {
1705 // The sequence needs to only ever move up.
1706 if seq <= last {
1707 return
1708 }
1709
1710 // Check for any gaps from compaction, meaning no ebit entry.
1711 if last > 0 && seq != last+1 && mb.msgs != 0 {
1712 for dseq := last + 1; dseq < seq; dseq++ {
1713 addToDmap(dseq)
1714 }
1715 }
1716 last = seq
1717 atomic.StoreUint64(&mb.last.seq, last)
1718 mb.last.ts = ts
1719 }
1720
1721 for index, lbuf := uint32(0), uint32(len(buf)); index < lbuf; {
1722 if index+msgHdrSize > lbuf {
1723 err = errBadMsg{mb.mfn, fmt.Sprintf("message overrun (index %d lbuf %d)", index, lbuf)}
1724 if allowTruncate {
1725 if err = truncate(index); err != nil {
1726 return nil, nil, err
1727 }
1728 }
1729 return gatherLost(lbuf - index), tombstones, err
1730 }
1731
1732 hdr := buf[index : index+msgHdrSize]
1733 rl, slen := le.Uint32(hdr[0:]), int(le.Uint16(hdr[20:]))
1734
1735 hasHeaders := rl&hbit != 0
1736 // Clear any headers bit that could be set.
1737 rl &^= hbit
1738 shlen := slen
1739 if hasHeaders {
1740 shlen += 4
1741 }
1742 dlen := int(rl) - msgHdrSize
1743 // Do some quick sanity checks here.
1744 if dlen < 0 || shlen > (dlen-recordHashSize) || dlen > int(rl) || index+rl > lbuf || rl > rlBadThresh {
1745 err = errBadMsg{mb.mfn, fmt.Sprintf("sanity check failed (dlen %d slen %d rl %d index %d lbuf %d)", dlen, slen, rl, index, lbuf)}
1746 if allowTruncate {
1747 if err = truncate(index); err != nil {
1748 return nil, nil, err
1749 }
1750 }
1751 return gatherLost(lbuf - index), tombstones, err
1752 }
1753
1754 // Check for checksum failures before additional processing.
1755 data := buf[index+msgHdrSize : index+rl]
1756 subj := data[:slen]
1757 if hh := mb.hh; hh != nil {
1758 hh.Reset()
1759 hh.Write(hdr[4:20])
1760 hh.Write(subj)
1761 if hasHeaders {
1762 hh.Write(data[slen+4 : dlen-recordHashSize])
1763 } else {
1764 hh.Write(data[slen : dlen-recordHashSize])
1765 }
1766 checksum := hh.Sum(hb[:0])
1767 if !bytes.Equal(checksum, data[len(data)-recordHashSize:]) {
1768 err = errBadMsg{mb.mfn, "invalid checksum"}
1769 if allowTruncate {
1770 if err = truncate(index); err != nil {
1771 return nil, nil, err
1772 }
1773 }
1774 return gatherLost(lbuf - index), tombstones, err
1775 }
1776 copy(mb.lchk[0:], checksum)
1777 }
1778
1779 // Grab our sequence and timestamp.
1780 seq := le.Uint64(hdr[4:])
1781 ts := int64(le.Uint64(hdr[12:]))
1782
1783 // Check if this is a delete tombstone.
1784 if seq&tbit != 0 {
1785 seq = seq &^ tbit
1786 // Need to process this here and make sure we have accounted for this properly.
1787 tombstones = append(tombstones, seq)
1788 if maxTombstoneSeq == 0 || seq > maxTombstoneSeq {
1789 maxTombstoneSeq, maxTombstoneTs = seq, ts
1790 }
1791 index += rl
1792 continue
1793 }
1794
1795 fseq := atomic.LoadUint64(&mb.first.seq)
1796 // This is an old erased message, or a new one that we can track.
1797 if seq == 0 || seq&ebit != 0 || seq < fseq {
1798 seq = seq &^ ebit
1799 if seq >= fseq {
1800 updateLast(seq, ts)
1801 if mb.msgs == 0 {
1802 atomic.StoreUint64(&mb.first.seq, seq+1)
1803 mb.first.ts = 0
1804 } else if seq != 0 {
1805 // Only add to dmap if past recorded first seq and non-zero.
1806 addToDmap(seq)
1807 }
1808 }
1809 index += rl
1810 continue
1811 }
1812
1813 // This is for when we have index info that adjusts for deleted messages
1814 // at the head. So the first.seq will be already set here. If this is larger
1815 // replace what we have with this seq.
1816 if firstNeedsSet && seq >= fseq {
1817 atomic.StoreUint64(&mb.first.seq, seq)
1818 firstNeedsSet, mb.first.ts = false, ts
1819 }
1820
1821 // The sequence needs to only ever move up.
1822 if seq <= last {
1823 // Advance to next record.
1824 // We've already accounted for this sequence and marked it as deleted.
1825 index += rl
1826 continue
1827 }
1828 if !mb.dmap.Exists(seq) {
1829 mb.msgs++
1830 mb.bytes += uint64(rl)
1831 }
1832
1833 updateLast(seq, ts)
1834
1835 // Advance to next record.
1836 index += rl
1837 }
1838
1839 // For empty msg blocks make sure we recover last seq correctly based off of first.
1840 // Or if we seem to have no messages but had a tombstone, which we use to remember
1841 // sequences and timestamps now, use that to properly setup the first and last.
1842 if mb.msgs == 0 {
1843 fseq := atomic.LoadUint64(&mb.first.seq)
1844 if fseq > 0 {
1845 atomic.StoreUint64(&mb.last.seq, fseq-1)
1846 } else if fseq == 0 && maxTombstoneSeq > 0 {
1847 atomic.StoreUint64(&mb.first.seq, maxTombstoneSeq+1)
1848 mb.first.ts = 0
1849 if lseq := atomic.LoadUint64(&mb.last.seq); lseq == 0 {
1850 atomic.StoreUint64(&mb.last.seq, maxTombstoneSeq)
1851 mb.last.ts = maxTombstoneTs
1852 }
1853 }
1854 }
1855
1856 return nil, tombstones, nil
1857 }
1858
1859 // For doing warn logging.
1860 // Lock should be held.
1861 func (fs *fileStore) warn(format string, args ...any) {
1862 // No-op if no server configured.
1863 if fs.srv == nil {
1864 return
1865 }
1866 fs.srv.Warnf(fmt.Sprintf("Filestore [%s] %s", fs.cfg.Name, format), args...)
1867 }
1868
1869 // For doing rate-limited warn logging.
1870 // Lock should be held.
1871 func (fs *fileStore) rateLimitWarn(format string, args ...any) {
1872 // No-op if no server configured.
1873 if fs.srv == nil {
1874 return
1875 }
1876 fs.srv.RateLimitWarnf(fmt.Sprintf("Filestore [%s] %s", fs.cfg.Name, format), args...)
1877 }
1878
1879 // For doing error logging.
1880 // Lock should be held.
1881 func (fs *fileStore) error(format string, args ...any) {
1882 // No-op if no server configured.
1883 if fs.srv == nil {
1884 return
1885 }
1886 fs.srv.Errorf(fmt.Sprintf("Filestore [%s] %s", fs.cfg.Name, format), args...)
1887 }
1888
1889 // For doing debug logging.
1890 // Lock should be held.
1891 func (fs *fileStore) debug(format string, args ...any) {
1892 // No-op if no server configured.
1893 if fs.srv == nil {
1894 return
1895 }
1896 fs.srv.Debugf(fmt.Sprintf("Filestore [%s] %s", fs.cfg.Name, format), args...)
1897 }
1898
1899 // Track local state but ignore timestamps here.
1900 func updateTrackingState(state *StreamState, mb *msgBlock) {
1901 first := atomic.LoadUint64(&mb.first.seq)
1902 last := atomic.LoadUint64(&mb.last.seq)
1903 if state.FirstSeq == 0 {
1904 state.FirstSeq = first
1905 } else if first < state.FirstSeq && mb.first.ts != 0 {
1906 state.FirstSeq = first
1907 }
1908 if last > state.LastSeq {
1909 state.LastSeq = last
1910 }
1911 state.Msgs += mb.msgs
1912 state.Bytes += mb.bytes
1913 }
1914
1915 // Determine if our tracking states are the same.
1916 func trackingStatesEqual(fs, mb *StreamState) bool {
1917 // When a fs is brand new the fs state will have first seq of 0, but tracking mb may have 1.
1918 // If either has a first sequence that is not 0 or 1 we will check if they are the same, otherwise skip.
1919 if (fs.FirstSeq > 1 && mb.FirstSeq > 1) || mb.FirstSeq > 1 {
1920 return fs.Msgs == mb.Msgs && fs.FirstSeq == mb.FirstSeq && fs.LastSeq == mb.LastSeq && fs.Bytes == mb.Bytes
1921 }
1922 return fs.Msgs == mb.Msgs && fs.LastSeq == mb.LastSeq && fs.Bytes == mb.Bytes
1923 }
1924
1925 // recoverFullState will attempt to receover our last full state and re-process any state changes
1926 // that happened afterwards.
1927 func (fs *fileStore) recoverFullState() (rerr error) {
1928 fs.mu.Lock()
1929 defer fs.mu.Unlock()
1930
1931 // Check for any left over purged messages.
1932 fs.dios.acquire()
1933 if err := fs.recoverPartialPurge(); err != nil {
1934 fs.dios.release()
1935 return err
1936 }
1937 // Grab our stream state file and load it in.
1938 fn := filepath.Join(fs.fcfg.StoreDir, msgDir, streamStreamStateFile)
1939 buf, err := os.ReadFile(fn)
1940 fs.dios.release()
1941
1942 if err != nil {
1943 if !os.IsNotExist(err) {
1944 fs.warn("Could not read stream state file: %v", err)
1945 }
1946 return err
1947 }
1948
1949 const minLen = 32
1950 if len(buf) < minLen {
1951 _ = os.Remove(fn)
1952 fs.warn("Stream state too short (%d bytes)", len(buf))
1953 return errCorruptState
1954 }
1955
1956 // The highwayhash will be on the end. Check that it still matches.
1957 h := buf[len(buf)-highwayhash.Size64:]
1958 buf = buf[:len(buf)-highwayhash.Size64]
1959 fs.hh.Reset()
1960 fs.hh.Write(buf)
1961 var hb [highwayhash.Size64]byte
1962 if !bytes.Equal(h, fs.hh.Sum(hb[:0])) {
1963 _ = os.Remove(fn)
1964 fs.warn("Stream state checksum did not match")
1965 return errCorruptState
1966 }
1967
1968 // Decrypt if needed.
1969 // We can be setup for encryption but if this is a snapshot restore we will be missing the keyfile
1970 // since snapshots strip encryption.
1971 if fs.prf != nil && fs.aek != nil {
1972 ns := fs.aek.NonceSize()
1973 buf, err = fs.aek.Open(nil, buf[:ns], buf[ns:], nil)
1974 if err != nil {
1975 fs.warn("Stream state error reading encryption key: %v", err)
1976 return err
1977 }
1978 }
1979
1980 version := buf[1]
1981 if buf[0] != fullStateMagic || version < fullStateMinVersion || version > fullStateVersion {
1982 _ = os.Remove(fn)
1983 fs.warn("Stream state magic and version mismatch")
1984 return errCorruptState
1985 }
1986
1987 bi := hdrLen
1988
1989 readU64 := func() uint64 {
1990 if bi < 0 {
1991 return 0
1992 }
1993 v, n := binary.Uvarint(buf[bi:])
1994 if n <= 0 {
1995 bi = -1
1996 return 0
1997 }
1998 bi += n
1999 return v
2000 }
2001 readI64 := func() int64 {
2002 if bi < 0 {
2003 return 0
2004 }
2005 v, n := binary.Varint(buf[bi:])
2006 if n <= 0 {
2007 bi = -1
2008 return -1
2009 }
2010 bi += n
2011 return v
2012 }
2013
2014 setTime := func(t *time.Time, ts int64) {
2015 if ts == 0 {
2016 *t = time.Time{}
2017 } else {
2018 *t = time.Unix(0, ts).UTC()
2019 }
2020 }
2021
2022 var state StreamState
2023 state.Msgs = readU64()
2024 state.Bytes = readU64()
2025 state.FirstSeq = readU64()
2026 baseTime := readI64()
2027 setTime(&state.FirstTime, baseTime)
2028 state.LastSeq = readU64()
2029 setTime(&state.LastTime, readI64())
2030
2031 // Check for per subject info.
2032 if numSubjects := int(readU64()); numSubjects > 0 {
2033 fs.psim, fs.tsl = fs.psim.Empty(), 0
2034 for i := 0; i < numSubjects; i++ {
2035 if lsubj := int(readU64()); lsubj > 0 {
2036 if bi+lsubj > len(buf) {
2037 _ = os.Remove(fn)
2038 fs.warn("Stream state bad subject len (%d)", lsubj)
2039 return errCorruptState
2040 }
2041 // If we have lots of subjects this will alloc for each one.
2042 // We could reference the underlying buffer, but we could guess wrong if
2043 // number of blocks is large and subjects is low, since we would reference buf.
2044 subj := buf[bi : bi+lsubj]
2045 // We had a bug that could cause memory corruption in the PSIM that could have gotten stored to disk.
2046 // Only would affect subjects, so do quick check.
2047 if !isValidSubject(bytesToString(subj), true) {
2048 _ = os.Remove(fn)
2049 fs.warn("Stream state corrupt subject detected")
2050 return errCorruptState
2051 }
2052 bi += lsubj
2053 psi := psi{total: readU64(), fblk: uint32(readU64())}
2054 if psi.total > 1 || version >= 4 {
2055 psi.lblk = uint32(readU64())
2056 } else {
2057 psi.lblk = psi.fblk
2058 }
2059 fs.psim.Insert(subj, psi)
2060 fs.tsl += lsubj
2061 }
2062 }
2063 }
2064
2065 // Track the state as represented by the blocks themselves.
2066 var mstate StreamState
2067
2068 if numBlocks := readU64(); numBlocks > 0 {
2069 lastIndex := int(numBlocks - 1)
2070 fs.blks = make([]*msgBlock, 0, numBlocks)
2071 for i := 0; i < int(numBlocks); i++ {
2072 index, nbytes, fseq, fts, lseq, lts, numDeleted := uint32(readU64()), readU64(), readU64(), readI64(), readU64(), readI64(), readU64()
2073 var ttls uint64
2074 if version >= 2 {
2075 ttls = readU64()
2076 }
2077 var schedules uint64
2078 if version >= 3 {
2079 schedules = readU64()
2080 }
2081 if bi < 0 {
2082 _ = os.Remove(fn)
2083 return errCorruptState
2084 }
2085 mb := fs.initMsgBlock(index)
2086 atomic.StoreUint64(&mb.first.seq, fseq)
2087 atomic.StoreUint64(&mb.last.seq, lseq)
2088 mb.msgs, mb.bytes = lseq-fseq+1, nbytes
2089 mb.first.ts, mb.last.ts = fts+baseTime, lts+baseTime
2090 mb.ttls = ttls
2091 mb.schedules = schedules
2092 if numDeleted > 0 {
2093 dmap, n, err := avl.Decode(buf[bi:])
2094 if err != nil {
2095 _ = os.Remove(fn)
2096 fs.warn("Stream state error decoding avl dmap: %v", err)
2097 return errCorruptState
2098 }
2099 mb.dmap = *dmap
2100 if mb.msgs > numDeleted {
2101 mb.msgs -= numDeleted
2102 } else {
2103 mb.msgs = 0
2104 }
2105 bi += n
2106 }
2107
2108 // Pre-emptively mark block as closed, we'll confirm this block
2109 // still exists on disk and report it as lost if not.
2110 mb.closed = true
2111
2112 // Only add in if not empty or the lmb.
2113 if mb.msgs > 0 || i == lastIndex {
2114 fs.addMsgBlock(mb)
2115 updateTrackingState(&mstate, mb)
2116 } else {
2117 // Mark dirty to cleanup.
2118 fs.dirty++
2119 }
2120 }
2121 }
2122
2123 // Pull in last block index for the block that had last checksum when we wrote the full state.
2124 blkIndex := uint32(readU64())
2125 var lchk [8]byte
2126 if bi+len(lchk) > len(buf) {
2127 bi = -1
2128 } else {
2129 copy(lchk[0:], buf[bi:bi+len(lchk)])
2130 }
2131
2132 // Check if we had any errors.
2133 if bi < 0 {
2134 _ = os.Remove(fn)
2135 fs.warn("Stream state has no checksum present")
2136 return errCorruptState
2137 }
2138
2139 // Move into place our state, msgBlks and subject info.
2140 fs.state = state
2141
2142 // First let's check the happy path, open the blk file that was the lmb when we created the full state.
2143 // See if we have the last block available.
2144 var matched bool
2145 mb := fs.lmb
2146 if mb == nil || mb.index != blkIndex {
2147 _ = os.Remove(fn)
2148 fs.warn("Stream state block does not exist or index mismatch")
2149 return errCorruptState
2150 }
2151 if _, err := os.Stat(mb.mfn); err != nil && os.IsNotExist(err) {
2152 // If our saved state is past what we see on disk, fallback and rebuild.
2153 if ld, _, _ := mb.rebuildState(); ld != nil {
2154 fs.addLostData(ld)
2155 }
2156 fs.warn("Stream state detected prior state, could not locate msg block %d", blkIndex)
2157 return errPriorState
2158 }
2159 if matched = bytes.Equal(mb.lastChecksum(), lchk[:]); !matched {
2160 // Detected a stale index.db, we didn't write it upon shutdown so can't rely on it being correct.
2161 fs.warn("Stream state outdated, last block has additional entries, will rebuild")
2162 return errPriorState
2163 }
2164
2165 // We need to see if any blocks exist after our last one even though we matched the last record exactly.
2166 mdir := filepath.Join(fs.fcfg.StoreDir, msgDir)
2167 var dirs []os.DirEntry
2168
2169 fs.dios.acquire()
2170 if f, err := os.Open(mdir); err == nil {
2171 dirs, _ = f.ReadDir(-1)
2172 f.Close()
2173 }
2174 fs.dios.release()
2175
2176 var index uint32
2177 for _, fi := range dirs {
2178 // Ensure it's actually a block file, otherwise fmt.Sscanf also matches %d.blk.tmp
2179 if !strings.HasSuffix(fi.Name(), blkSuffix) {
2180 continue
2181 }
2182 if n, err := fmt.Sscanf(fi.Name(), blkScan, &index); err == nil && n == 1 {
2183 if index > blkIndex {
2184 fs.warn("Stream state outdated, found extra blocks, will rebuild")
2185 return errPriorState
2186 } else if mb, ok := fs.bim[index]; ok {
2187 mb.closed = false
2188 }
2189 }
2190 }
2191
2192 var rebuild bool
2193 for _, mb := range fs.blks {
2194 if mb.closed {
2195 rebuild = true
2196 if ld, _, _ := mb.rebuildState(); ld != nil {
2197 fs.addLostData(ld)
2198 }
2199 fs.warn("Stream state detected prior state, could not locate msg block %d", mb.index)
2200 }
2201 }
2202 if rebuild {
2203 return errPriorState
2204 }
2205
2206 // We check first and last seq and number of msgs and bytes. If there is a difference,
2207 // return and error so we rebuild from the message block state on disk.
2208 if !trackingStatesEqual(&fs.state, &mstate) {
2209 _ = os.Remove(fn)
2210 fs.warn("Stream state encountered internal inconsistency on recover")
2211 return errCorruptState
2212 }
2213
2214 return nil
2215 }
2216
2217 // Lock should be held.
2218 func (fs *fileStore) recoverTTLState() error {
2219 // See if we have a timed hash wheel for TTLs.
2220 fs.dios.acquire()
2221 fn := filepath.Join(fs.fcfg.StoreDir, msgDir, ttlStreamStateFile)
2222 buf, err := os.ReadFile(fn)
2223 fs.dios.release()
2224
2225 if err != nil && !os.IsNotExist(err) {
2226 return err
2227 }
2228
2229 fs.ttls = thw.NewHashWheel()
2230
2231 var ttlseq uint64
2232 if err == nil {
2233 ttlseq, err = fs.ttls.Decode(buf)
2234 if err != nil {
2235 fs.warn("Error decoding TTL state: %s", err)
2236 // Remove the file, and reset collected state (if any).
2237 _ = os.Remove(fn)
2238 fs.ttls = thw.NewHashWheel()
2239 }
2240 }
2241
2242 if ttlseq < fs.state.FirstSeq {
2243 ttlseq = fs.state.FirstSeq
2244 }
2245
2246 defer fs.resetAgeChk(0)
2247 if fs.state.Msgs > 0 && ttlseq <= fs.state.LastSeq {
2248 fs.warn("TTL state is outdated; attempting to recover using linear scan (seq %d to %d)", ttlseq, fs.state.LastSeq)
2249 var (
2250 mb *msgBlock
2251 sm StoreMsg
2252 mblseq uint64
2253 )
2254 for seq := ttlseq; seq <= fs.state.LastSeq; seq++ {
2255 retry:
2256 if mb == nil {
2257 if mb = fs.selectMsgBlock(seq); mb == nil {
2258 // Selecting the message block should return a block that contains this sequence,
2259 // or a later block if it can't be found.
2260 // It's an error if we can't find any block within the bounds of first and last seq.
2261 fs.warn("Error loading msg block with seq %d for recovering TTL", seq)
2262 continue
2263 }
2264 seq = atomic.LoadUint64(&mb.first.seq)
2265 mblseq = atomic.LoadUint64(&mb.last.seq)
2266 }
2267 if mb.ttls == 0 {
2268 // None of the messages in the block have message TTLs so don't
2269 // bother doing anything further with this block, skip to the end.
2270 seq = atomic.LoadUint64(&mb.last.seq) + 1
2271 }
2272 if seq > mblseq {
2273 // We've reached the end of the loaded block, so let's go back to the
2274 // beginning and process the next block.
2275 mb.tryForceExpireCache()
2276 mb = nil
2277 if seq <= fs.state.LastSeq {
2278 goto retry
2279 }
2280 // Done.
2281 break
2282 }
2283 mb.mu.Lock()
2284 msg, _, err := mb.fetchMsgNoCopyLocked(seq, &sm)
2285 if err != nil {
2286 mb.finishedWithCache()
2287 mb.mu.Unlock()
2288 fs.warn("Error loading msg seq %d for recovering TTL: %s", seq, err)
2289 continue
2290 }
2291 if len(msg.hdr) > 0 {
2292 if ttl, _ := getMessageTTL(msg.hdr); ttl > 0 {
2293 expires := time.Duration(msg.ts) + (time.Second * time.Duration(ttl))
2294 fs.ttls.Add(seq, int64(expires))
2295 }
2296 }
2297 mb.finishedWithCache()
2298 mb.mu.Unlock()
2299 }
2300 }
2301 return nil
2302 }
2303
2304 // Lock should be held.
2305 func (fs *fileStore) recoverMsgSchedulingState() error {
2306 // See if we have a timed hash wheel for TTLs.
2307 fs.dios.acquire()
2308 fn := filepath.Join(fs.fcfg.StoreDir, msgDir, msgSchedulingStreamStateFile)
2309 buf, err := os.ReadFile(fn)
2310 fs.dios.release()
2311
2312 if err != nil && !os.IsNotExist(err) {
2313 return err
2314 }
2315
2316 fs.scheduling = newMsgScheduling(fs.runMsgScheduling)
2317
2318 var schedSeq uint64
2319 if err == nil {
2320 schedSeq, err = fs.scheduling.decode(buf)
2321 if err != nil {
2322 fs.warn("Error decoding message scheduling state: %s", err)
2323 // Remove the file, and reset collected state (if any).
2324 _ = os.Remove(fn)
2325 fs.scheduling = newMsgScheduling(fs.runMsgScheduling)
2326 }
2327 }
2328
2329 if schedSeq < fs.state.FirstSeq {
2330 schedSeq = fs.state.FirstSeq
2331 }
2332
2333 defer fs.scheduling.resetTimer()
2334 if fs.state.Msgs > 0 && schedSeq <= fs.state.LastSeq {
2335 fs.warn("Message scheduling state is outdated; attempting to recover using linear scan (seq %d to %d)", schedSeq, fs.state.LastSeq)
2336 var (
2337 mb *msgBlock
2338 sm StoreMsg
2339 mblseq uint64
2340 )
2341 for seq := schedSeq; seq <= fs.state.LastSeq; seq++ {
2342 retry:
2343 if mb == nil {
2344 if mb = fs.selectMsgBlock(seq); mb == nil {
2345 // Selecting the message block should return a block that contains this sequence,
2346 // or a later block if it can't be found.
2347 // It's an error if we can't find any block within the bounds of first and last seq.
2348 fs.warn("Error loading msg block with seq %d for recovering message schedules", seq)
2349 continue
2350 }
2351 seq = atomic.LoadUint64(&mb.first.seq)
2352 mblseq = atomic.LoadUint64(&mb.last.seq)
2353 }
2354 if mb.schedules == 0 {
2355 // None of the messages in the block have message schedules, so don't
2356 // bother doing anything further with this block, skip to the end.
2357 seq = atomic.LoadUint64(&mb.last.seq) + 1
2358 }
2359 if seq > mblseq {
2360 // We've reached the end of the loaded block, so let's go back to the
2361 // beginning and process the next block.
2362 mb.tryForceExpireCache()
2363 mb = nil
2364 if seq <= fs.state.LastSeq {
2365 goto retry
2366 }
2367 // Done.
2368 break
2369 }
2370 mb.mu.Lock()
2371 msg, _, err := mb.fetchMsgNoCopyLocked(seq, &sm)
2372 if err != nil {
2373 mb.finishedWithCache()
2374 mb.mu.Unlock()
2375 fs.warn("Error loading msg seq %d for recovering message schedules: %s", seq, err)
2376 continue
2377 }
2378 if len(msg.hdr) > 0 {
2379 if schedule, apiErr := nextMessageSchedule(msg.hdr, msg.ts); apiErr == nil && !schedule.IsZero() {
2380 // Copy the subject, as it's stored in the scheduling maps and the backing cache could be reused in the meantime.
2381 fs.scheduling.init(seq, copyString(msg.subj), schedule.UnixNano())
2382 }
2383 }
2384 mb.finishedWithCache()
2385 mb.mu.Unlock()
2386 }
2387 }
2388 return nil
2389 }
2390
2391 // Grabs last checksum for the named block file.
2392 // Takes into account encryption etc.
2393 func (mb *msgBlock) lastChecksum() []byte {
2394 f, err := mb.openBlock()
2395 if err != nil {
2396 return nil
2397 }
2398 defer f.Close()
2399
2400 var lchk [8]byte
2401 if fi, _ := f.Stat(); fi != nil {
2402 mb.rbytes = uint64(fi.Size())
2403 }
2404 if mb.rbytes < checksumSize {
2405 return lchk[:]
2406 }
2407 // Encrypted?
2408 if err = mb.checkAndLoadEncryption(); err != nil {
2409 return nil
2410 }
2411 if mb.bek != nil {
2412 if buf, _ := mb.loadBlock(nil); len(buf) >= checksumSize {
2413 if err = mb.encryptOrDecryptIfNeeded(buf); err != nil {
2414 return nil
2415 }
2416 copy(lchk[0:], buf[len(buf)-checksumSize:])
2417 } else {
2418 return nil
2419 }
2420 } else if _, err = f.ReadAt(lchk[:], int64(mb.rbytes)-checksumSize); err != nil {
2421 return nil
2422 }
2423 return lchk[:]
2424 }
2425
2426 // This will make sure we clean up old idx and fss files.
2427 func (fs *fileStore) cleanupOldMeta() {
2428 fs.mu.RLock()
2429 mdir := filepath.Join(fs.fcfg.StoreDir, msgDir)
2430 fs.mu.RUnlock()
2431
2432 fs.dios.acquire()
2433 f, err := os.Open(mdir)
2434 fs.dios.release()
2435 if err != nil {
2436 return
2437 }
2438
2439 dirs, _ := f.ReadDir(-1)
2440 f.Close()
2441
2442 const (
2443 minLen = 4
2444 idxSuffix = ".idx"
2445 fssSuffix = ".fss"
2446 )
2447 for _, fi := range dirs {
2448 if name := fi.Name(); strings.HasSuffix(name, idxSuffix) || strings.HasSuffix(name, fssSuffix) {
2449 os.Remove(filepath.Join(mdir, name))
2450 }
2451 }
2452 }
2453
2454 func (fs *fileStore) recoverMsgs() error {
2455 fs.mu.Lock()
2456 defer fs.mu.Unlock()
2457
2458 // Check for any left over purged messages.
2459 fs.dios.acquire()
2460 if err := fs.recoverPartialPurge(); err != nil {
2461 fs.dios.release()
2462 return err
2463 }
2464 mdir := filepath.Join(fs.fcfg.StoreDir, msgDir)
2465 f, err := os.Open(mdir)
2466 if err != nil {
2467 fs.dios.release()
2468 return errNotReadable
2469 }
2470 dirs, err := f.ReadDir(-1)
2471 f.Close()
2472 fs.dios.release()
2473
2474 if err != nil {
2475 return errNotReadable
2476 }
2477
2478 indices := make(sort.IntSlice, 0, len(dirs))
2479 var index int
2480 for _, fi := range dirs {
2481 // Ensure it's actually a block file, otherwise fmt.Sscanf also matches %d.blk.tmp
2482 if !strings.HasSuffix(fi.Name(), blkSuffix) {
2483 continue
2484 }
2485 if n, err := fmt.Sscanf(fi.Name(), blkScan, &index); err == nil && n == 1 {
2486 indices = append(indices, index)
2487 }
2488 }
2489 indices.Sort()
2490
2491 // Recover all of the msg blocks.
2492 // We now guarantee they are coming in order.
2493 for _, index := range indices {
2494 if mb, err := fs.recoverMsgBlock(uint32(index)); err == nil && mb != nil {
2495 // This is a truncate block with possibly no index. If the OS got shutdown
2496 // out from underneath of us this is possible.
2497 mb.mu.Lock()
2498 if atomic.LoadUint64(&mb.first.seq) == 0 {
2499 if err := mb.dirtyCloseWithRemove(true); err != nil {
2500 mb.mu.Unlock()
2501 return err
2502 }
2503 fs.removeMsgBlockFromList(mb)
2504 mb.mu.Unlock()
2505 continue
2506 }
2507 // If the stream is empty, reset the first/last sequences so these can
2508 // properly move up based purely on tombstones spread over multiple blocks.
2509 if fs.state.Msgs == 0 {
2510 fs.state.FirstSeq, fs.state.LastSeq = 0, 0
2511 fs.state.FirstTime, fs.state.LastTime = time.Time{}, time.Time{}
2512 }
2513 fseq := atomic.LoadUint64(&mb.first.seq)
2514 if fs.state.FirstSeq == 0 || (fseq < fs.state.FirstSeq && mb.first.ts != 0) {
2515 fs.state.FirstSeq = fseq
2516 if mb.first.ts == 0 {
2517 fs.state.FirstTime = time.Time{}
2518 } else {
2519 fs.state.FirstTime = time.Unix(0, mb.first.ts).UTC()
2520 }
2521 }
2522 // Preserve last time, could have erased the last message in one block, and then
2523 // have a tombstone with the proper timestamp afterward in another block
2524 if lseq := atomic.LoadUint64(&mb.last.seq); lseq >= fs.state.LastSeq {
2525 fs.state.LastSeq = lseq
2526 if mb.last.ts == 0 {
2527 fs.state.LastTime = time.Time{}
2528 } else {
2529 fs.state.LastTime = time.Unix(0, mb.last.ts).UTC()
2530 }
2531 }
2532 fs.state.Msgs += mb.msgs
2533 fs.state.Bytes += mb.bytes
2534 // If the block is empty, correct the sequences to be aligned with the current filestore state.
2535 if mb.msgs == 0 {
2536 atomic.StoreUint64(&mb.first.seq, fs.state.LastSeq+1)
2537 mb.first.ts = 0
2538 atomic.StoreUint64(&mb.last.seq, fs.state.LastSeq)
2539 mb.last.ts = fs.state.LastTime.UnixNano()
2540 }
2541 mb.mu.Unlock()
2542 } else if (err == errBadKeySize || err == errKeyInvalid) && mb != nil {
2543 // If we can't load the encryption key, we can't decrypt the block's data.
2544 // We'll revert to deleting this block until there is peer-based recovery. This still
2545 // catches up from the leader if it happened in the stream's tail.
2546 mb.mu.Lock()
2547 if err := mb.dirtyCloseWithRemove(true); err != nil {
2548 mb.mu.Unlock()
2549 return err
2550 }
2551 fs.removeMsgBlockFromList(mb)
2552 mb.mu.Unlock()
2553 continue
2554 } else {
2555 return err
2556 }
2557 }
2558
2559 if len(fs.blks) > 0 {
2560 fs.lmb = fs.blks[len(fs.blks)-1]
2561 } else if _, err = fs.newMsgBlockForWrite(); err != nil {
2562 return err
2563 }
2564
2565 // Check if we encountered any lost data.
2566 if fs.ld != nil {
2567 var emptyBlks []*msgBlock
2568 for _, mb := range fs.blks {
2569 if mb.msgs == 0 && mb.rbytes == 0 && mb != fs.lmb {
2570 emptyBlks = append(emptyBlks, mb)
2571 }
2572 }
2573 for _, mb := range emptyBlks {
2574 // Need the mb lock here.
2575 mb.mu.Lock()
2576 err = fs.forceRemoveMsgBlock(mb)
2577 mb.mu.Unlock()
2578 if err != nil {
2579 return err
2580 }
2581 }
2582 }
2583
2584 // Check for keyfiles orphans.
2585 if kms, err := filepath.Glob(filepath.Join(mdir, keyScanAll)); err == nil && len(kms) > 0 {
2586 valid := make(map[uint32]bool)
2587 for _, mb := range fs.blks {
2588 valid[mb.index] = true
2589 }
2590 for _, fn := range kms {
2591 var index uint32
2592 shouldRemove := true
2593 if n, err := fmt.Sscanf(filepath.Base(fn), keyScan, &index); err == nil && n == 1 && valid[index] {
2594 shouldRemove = false
2595 }
2596 if shouldRemove {
2597 os.Remove(fn)
2598 }
2599 }
2600 }
2601
2602 return nil
2603 }
2604
2605 // Will expire msgs that have aged out on restart.
2606 // We will treat this differently in case we have a recovery
2607 // that will expire alot of messages on startup.
2608 // Should only be called on startup.
2609 func (fs *fileStore) expireMsgsOnRecover() error {
2610 if fs.state.Msgs == 0 {
2611 return nil
2612 }
2613
2614 // If subject delete markers is configured, can't expire on recover.
2615 // When clustered we need to go through proposals.
2616 if fs.cfg.SubjectDeleteMarkerTTL > 0 {
2617 return nil
2618 }
2619
2620 var minAge = time.Now().UnixNano() - int64(fs.cfg.MaxAge)
2621 var purged, bytes uint64
2622 var deleted int
2623 var nts int64
2624
2625 // If we expire all make sure to write out a tombstone. Need to be done by hand here,
2626 // usually taken care of by fs.removeMsgBlock() but we do not call that here.
2627 var last msgId
2628
2629 deleteEmptyBlock := func(mb *msgBlock) error {
2630 // If we are the last keep state to remember first/last sequence.
2631 // Do this part by hand since not deleting one by one.
2632 if mb == fs.lmb {
2633 last.seq = atomic.LoadUint64(&mb.last.seq)
2634 last.ts = mb.last.ts
2635 }
2636 // Make sure we do subject cleanup as well.
2637 if err := mb.ensurePerSubjectInfoLoaded(); err != nil {
2638 return err
2639 }
2640 mb.fss.IterOrdered(func(bsubj []byte, ss *SimpleState) bool {
2641 subj := bytesToString(bsubj)
2642 for i := uint64(0); i < ss.Msgs; i++ {
2643 fs.removePerSubject(subj)
2644 }
2645 return true
2646 })
2647 if err := mb.dirtyCloseWithRemove(true); err != nil {
2648 return err
2649 }
2650 deleted++
2651 return nil
2652 }
2653
2654 for _, mb := range fs.blks {
2655 mb.mu.Lock()
2656 if minAge < mb.first.ts {
2657 nts = mb.first.ts
2658 mb.mu.Unlock()
2659 break
2660 }
2661 // Can we remove whole block here?
2662 if mb.last.ts <= minAge {
2663 purged += mb.msgs
2664 bytes += mb.bytes
2665 err := deleteEmptyBlock(mb)
2666 mb.mu.Unlock()
2667 if err != nil {
2668 return err
2669 }
2670 continue
2671 }
2672
2673 // If we are here we have to process the interior messages of this blk.
2674 // This will load fss as well.
2675 if err := mb.loadMsgsWithLock(); err != nil {
2676 mb.mu.Unlock()
2677 return err
2678 }
2679
2680 var smv StoreMsg
2681 var needNextFirst bool
2682
2683 // Walk messages and remove if expired.
2684 fseq, lseq := atomic.LoadUint64(&mb.first.seq), atomic.LoadUint64(&mb.last.seq)
2685 for seq := fseq; seq <= lseq; seq++ {
2686 sm, err := mb.cacheLookupNoCopy(seq, &smv)
2687 // Process interior deleted msgs.
2688 if err == errDeletedMsg {
2689 // Update dmap.
2690 if mb.dmap.Exists(seq) {
2691 mb.dmap.Delete(seq)
2692 }
2693 // Keep this updated just in case since we are removing dmap entries.
2694 atomic.StoreUint64(&mb.first.seq, seq)
2695 needNextFirst = true
2696 continue
2697 }
2698 // Break on other errors.
2699 if err != nil || sm == nil {
2700 atomic.StoreUint64(&mb.first.seq, seq)
2701 needNextFirst = true
2702 break
2703 }
2704
2705 // No error and sm != nil from here onward.
2706
2707 // Check for done.
2708 if minAge < sm.ts {
2709 atomic.StoreUint64(&mb.first.seq, sm.seq)
2710 mb.first.ts = sm.ts
2711 needNextFirst = false
2712 nts = sm.ts
2713 break
2714 }
2715
2716 // Delete the message here.
2717 if mb.msgs > 0 {
2718 atomic.StoreUint64(&mb.first.seq, seq)
2719 needNextFirst = true
2720 sz := fileStoreMsgSize(sm.subj, sm.hdr, sm.msg)
2721 if sz > mb.bytes {
2722 sz = mb.bytes
2723 }
2724 mb.bytes -= sz
2725 bytes += sz
2726 mb.msgs--
2727 purged++
2728 }
2729 // Update fss
2730 // Make sure we have fss loaded.
2731 if _, err = mb.removeSeqPerSubject(sm.subj, seq); err != nil {
2732 mb.finishedWithCache()
2733 mb.mu.Unlock()
2734 return err
2735 }
2736 fs.removePerSubject(sm.subj)
2737 }
2738 // Make sure we have a proper next first sequence.
2739 if needNextFirst {
2740 mb.selectNextFirst()
2741 }
2742 // Check if empty after processing, could happen if tail of messages are all deleted.
2743 var err error
2744 if mb.msgs == 0 {
2745 err = deleteEmptyBlock(mb)
2746 }
2747 mb.finishedWithCache()
2748 mb.mu.Unlock()
2749 if err != nil {
2750 return err
2751 }
2752 break
2753 }
2754
2755 if nts > 0 {
2756 // Make sure to set age check based on this value.
2757 fs.resetAgeChk(nts - minAge)
2758 }
2759
2760 if deleted > 0 {
2761 // Update block map.
2762 if fs.bim != nil {
2763 for _, mb := range fs.blks[:deleted] {
2764 delete(fs.bim, mb.index)
2765 }
2766 }
2767 // Update blks slice.
2768 fs.blks = copyMsgBlocks(fs.blks[deleted:])
2769 if lb := len(fs.blks); lb == 0 {
2770 fs.lmb = nil
2771 } else {
2772 fs.lmb = fs.blks[lb-1]
2773 }
2774 }
2775 // Update top level accounting.
2776 if purged < fs.state.Msgs {
2777 fs.state.Msgs -= purged
2778 } else {
2779 fs.state.Msgs = 0
2780 }
2781 if bytes < fs.state.Bytes {
2782 fs.state.Bytes -= bytes
2783 } else {
2784 fs.state.Bytes = 0
2785 }
2786 // Make sure to we properly set the fs first sequence and timestamp.
2787 if err := fs.selectNextFirst(); err != nil {
2788 return err
2789 }
2790
2791 // Check if we have no messages and blocks left.
2792
2793 if fs.lmb == nil && last.seq != 0 {
2794 if lmb, err := fs.newMsgBlockForWrite(); err != nil || lmb == nil {
2795 if err == nil {
2796 err = errors.New("lmb missing")
2797 }
2798 return err
2799 } else if err = fs.writeTombstone(last.seq, last.ts); err != nil {
2800 return err
2801 }
2802 // Clear any global subject state.
2803 fs.psim, fs.tsl = fs.psim.Empty(), 0
2804 }
2805
2806 // If we purged anything, make sure we kick flush state loop.
2807 if purged > 0 {
2808 fs.dirty++
2809 }
2810 return nil
2811 }
2812
2813 func copyMsgBlocks(src []*msgBlock) []*msgBlock {
2814 if src == nil {
2815 return nil
2816 }
2817 dst := make([]*msgBlock, len(src))
2818 copy(dst, src)
2819 return dst
2820 }
2821
2822 // GetSeqFromTime looks for the first sequence number that has
2823 // the message with >= timestamp.
2824 func (fs *fileStore) GetSeqFromTime(t time.Time) uint64 {
2825 fs.mu.RLock()
2826 lastSeq := fs.state.LastSeq
2827 closed := fs.isClosed()
2828 fs.mu.RUnlock()
2829
2830 if closed {
2831 return 0
2832 }
2833
2834 mb := fs.selectMsgBlockForStart(t)
2835 if mb == nil {
2836 return lastSeq + 1
2837 }
2838
2839 fseq := atomic.LoadUint64(&mb.first.seq)
2840 lseq := atomic.LoadUint64(&mb.last.seq)
2841
2842 var (
2843 smv StoreMsg
2844 cts int64
2845 cseq uint64
2846 off uint64
2847 )
2848 ts := t.UnixNano()
2849
2850 // Using a binary search, but need to be aware of interior deletes in the block.
2851 seq := lseq + 1
2852 mb.mu.Lock()
2853 loop:
2854 for fseq <= lseq {
2855 mid := fseq + (lseq-fseq)/2
2856 off = 0
2857 // Potentially skip over gaps. We keep the original middle but keep track of a
2858 // potential delete range with an offset.
2859 for {
2860 sm, _, err := mb.fetchMsgNoCopyLocked(mid+off, &smv)
2861 if err != nil || sm == nil {
2862 off++
2863 if mid+off <= lseq {
2864 continue
2865 } else {
2866 // Continue search to the left. Purposely ignore the skipped deletes here.
2867 lseq = mid - 1
2868 continue loop
2869 }
2870 }
2871 cts = sm.ts
2872 cseq = sm.seq
2873 break
2874 }
2875 if cts >= ts {
2876 seq = cseq
2877 if mid == fseq {
2878 break
2879 }
2880 // Continue search to the left.
2881 lseq = mid - 1
2882 } else {
2883 // Continue search to the right (potentially skipping over interior deletes).
2884 fseq = mid + off + 1
2885 }
2886 }
2887 mb.finishedWithCache()
2888 mb.mu.Unlock()
2889 return seq
2890 }
2891
2892 // Find the first matching message against a sublist.
2893 func (mb *msgBlock) firstMatchingMulti(sl *gsl.SimpleSublist, start uint64, sm *StoreMsg) (*StoreMsg, bool, error) {
2894 mb.mu.Lock()
2895 var didLoad bool
2896 var updateLLTS bool
2897 defer func() {
2898 if updateLLTS {
2899 mb.llts = ats.AccessTime()
2900 }
2901 mb.finishedWithCache()
2902 mb.mu.Unlock()
2903 }()
2904
2905 if mb.fssNotLoaded() {
2906 // Make sure we have fss loaded.
2907 if err := mb.loadMsgsWithLock(); err != nil {
2908 return nil, false, err
2909 }
2910 didLoad = true
2911 }
2912 // Mark fss activity.
2913 mb.lsts = ats.AccessTime()
2914
2915 // Make sure to start at mb.first.seq if fseq < mb.first.seq
2916 if seq := atomic.LoadUint64(&mb.first.seq); seq > start {
2917 start = seq
2918 }
2919 lseq := atomic.LoadUint64(&mb.last.seq)
2920
2921 // If the FSS state has fewer entries than sequences in the linear scan,
2922 // then use intersection instead as likely going to be cheaper. This will
2923 // often be the case with high numbers of deletes, as well as a smaller
2924 // number of subjects in the block.
2925 if uint64(mb.fss.Size()) < lseq-start {
2926 // If there are no subject matches then this is effectively no-op.
2927 hseq := uint64(math.MaxUint64)
2928 var ierr error
2929 stree.IntersectGSL(mb.fss, sl, func(subj []byte, ss *SimpleState) bool {
2930 if ss.firstNeedsUpdate || ss.lastNeedsUpdate {
2931 // mb is already loaded into the cache so should be fast-ish.
2932 if ierr = mb.recalculateForSubj(bytesToString(subj), ss); ierr != nil {
2933 return false
2934 }
2935 }
2936 first := max(start, ss.First)
2937 if first > ss.Last || first >= hseq {
2938 // The start cutoff is after the last sequence for this subject,
2939 // or we think we already know of a subject with an earlier msg
2940 // than our first seq for this subject.
2941 return true
2942 }
2943 // Need messages loaded from here on out.
2944 if mb.cacheNotLoaded() {
2945 if ierr = mb.loadMsgsWithLock(); ierr != nil {
2946 return false
2947 }
2948 didLoad = true
2949 }
2950 if sm == nil {
2951 sm = new(StoreMsg)
2952 }
2953 if first == ss.First {
2954 // If the start floor is below where this subject starts then we can
2955 // short-circuit, avoiding needing to scan for the next message.
2956 if fsm, err := mb.cacheLookup(ss.First, sm); err == nil {
2957 sm = fsm
2958 hseq = ss.First
2959 }
2960 return true
2961 }
2962 for seq := first; seq <= ss.Last; seq++ {
2963 // Otherwise we have a start floor that intersects where this subject
2964 // has messages in the block, so we need to walk up until we find a
2965 // message matching the subject.
2966 if mb.dmap.Exists(seq) {
2967 // Optimisation to avoid calling cacheLookup which hits time.Now().
2968 // Instead we will update it only once in a defer.
2969 updateLLTS = true
2970 continue
2971 }
2972 llseq := mb.llseq
2973 fsm, err := mb.cacheLookup(seq, sm)
2974 if err != nil {
2975 continue
2976 }
2977 updateLLTS = false // cacheLookup already updated it.
2978 if sl.HasInterest(fsm.subj) {
2979 hseq = seq
2980 sm = fsm
2981 break
2982 }
2983 // If we are here we did not match, so put the llseq back.
2984 mb.llseq = llseq
2985 }
2986 return true
2987 })
2988 if ierr != nil {
2989 return nil, false, ierr
2990 }
2991 if hseq < uint64(math.MaxUint64) && sm != nil {
2992 return sm, didLoad && start == lseq, nil
2993 }
2994 } else {
2995 // Need messages loaded from here on out.
2996 if mb.cacheNotLoaded() {
2997 if err := mb.loadMsgsWithLock(); err != nil {
2998 return nil, false, err
2999 }
3000 didLoad = true
3001 }
3002 if sm == nil {
3003 sm = new(StoreMsg)
3004 }
3005
3006 for seq := start; seq <= lseq; seq++ {
3007 if mb.dmap.Exists(seq) {
3008 // Optimisation to avoid calling cacheLookup which hits time.Now().
3009 // Instead we will update it only once in a defer.
3010 updateLLTS = true
3011 continue
3012 }
3013 llseq := mb.llseq
3014 fsm, err := mb.cacheLookup(seq, sm)
3015 if err != nil {
3016 continue
3017 }
3018 expireOk := seq == lseq && mb.llseq != llseq && mb.llseq == seq
3019 updateLLTS = false // cacheLookup already updated it.
3020 if sl.HasInterest(fsm.subj) {
3021 return fsm, expireOk, nil
3022 }
3023 // If we are here we did not match, so put the llseq back.
3024 mb.llseq = llseq
3025 }
3026 }
3027
3028 return nil, didLoad, ErrStoreMsgNotFound
3029 }
3030
3031 // Find the first matching message.
3032 // fs lock should be held.
3033 func (mb *msgBlock) firstMatching(filter string, wc bool, start uint64, sm *StoreMsg) (*StoreMsg, bool, error) {
3034 mb.mu.Lock()
3035 var updateLLTS bool
3036 defer func() {
3037 if updateLLTS {
3038 mb.llts = ats.AccessTime()
3039 }
3040 mb.finishedWithCache()
3041 mb.mu.Unlock()
3042 }()
3043
3044 fseq, isAll := start, filter == _EMPTY_ || filter == fwcs
3045
3046 var didLoad bool
3047 if mb.fssNotLoaded() {
3048 // Make sure we have fss loaded.
3049 if err := mb.loadMsgsWithLock(); err != nil {
3050 return nil, false, err
3051 }
3052 didLoad = true
3053 }
3054 // Mark fss activity.
3055 mb.lsts = ats.AccessTime()
3056
3057 if filter == _EMPTY_ {
3058 filter = fwcs
3059 wc = true
3060 }
3061
3062 // If we only have 1 subject currently and it matches our filter we can also set isAll.
3063 if !isAll && mb.fss.Size() == 1 {
3064 if !wc {
3065 _, isAll = mb.fss.Find(stringToBytes(filter))
3066 } else {
3067 // Since mb.fss.Find won't work if filter is a wildcard, need to use Match instead.
3068 mb.fss.Match(stringToBytes(filter), func(subject []byte, _ *SimpleState) {
3069 isAll = true
3070 })
3071 }
3072 // If the only subject in this block isn't our filter, can simply short-circuit.
3073 if !isAll {
3074 return nil, didLoad, ErrStoreMsgNotFound
3075 }
3076 }
3077 // Make sure to start at mb.first.seq if fseq < mb.first.seq
3078 fseq = max(fseq, atomic.LoadUint64(&mb.first.seq))
3079 lseq := atomic.LoadUint64(&mb.last.seq)
3080
3081 // Optionally build the isMatch for wildcard filters.
3082 var isMatch func(subj string) bool
3083 // Decide to build.
3084 if wc {
3085 _tsa, _fsa := [32]string{}, [32]string{}
3086 tsa, fsa := _tsa[:0], tokenizeSubjectIntoSlice(_fsa[:0], filter)
3087 isMatch = func(subj string) bool {
3088 tsa = tokenizeSubjectIntoSlice(tsa[:0], subj)
3089 return isSubsetMatchTokenized(tsa, fsa)
3090 }
3091 }
3092
3093 subjs := mb.fs.cfg.Subjects
3094 // If isAll or our single filter matches the filter arg do linear scan.
3095 doLinearScan := isAll || (wc && len(subjs) == 1 && subjs[0] == filter)
3096 // If we do not think we should do a linear scan check how many fss we
3097 // would need to scan vs the full range of the linear walk. Optimize for
3098 // 25th quantile of a match in a linear walk. Filter should be a wildcard.
3099 // We should consult fss if our cache is not loaded and we only have fss loaded.
3100 if !doLinearScan && wc && mb.cacheAlreadyLoaded() {
3101 doLinearScan = mb.fss.Size()*4 > int(lseq-fseq)
3102 }
3103
3104 if !doLinearScan {
3105 // If we have a wildcard match against all tracked subjects we know about.
3106 fseq = lseq + 1
3107 if bfilter := stringToBytes(filter); wc {
3108 var ierr error
3109 mb.fss.Match(bfilter, func(bsubj []byte, ss *SimpleState) {
3110 if ierr != nil {
3111 return
3112 }
3113 if ss.firstNeedsUpdate || ss.lastNeedsUpdate {
3114 if ierr = mb.recalculateForSubj(bytesToString(bsubj), ss); ierr != nil {
3115 return
3116 }
3117 }
3118 if start <= ss.Last {
3119 fseq = min(fseq, max(start, ss.First))
3120 }
3121 })
3122 if ierr != nil {
3123 return nil, false, ierr
3124 }
3125 } else if ss, _ := mb.fss.Find(bfilter); ss != nil {
3126 if ss.firstNeedsUpdate || ss.lastNeedsUpdate {
3127 if err := mb.recalculateForSubj(filter, ss); err != nil {
3128 return nil, false, err
3129 }
3130 }
3131 if start <= ss.Last {
3132 fseq = min(fseq, max(start, ss.First))
3133 }
3134 }
3135 }
3136
3137 if fseq > lseq {
3138 return nil, didLoad, ErrStoreMsgNotFound
3139 }
3140
3141 // Need messages loaded from here on out.
3142 if mb.cacheNotLoaded() {
3143 if err := mb.loadMsgsWithLock(); err != nil {
3144 return nil, false, err
3145 }
3146 didLoad = true
3147 }
3148
3149 if sm == nil {
3150 sm = new(StoreMsg)
3151 }
3152
3153 for seq := fseq; seq <= lseq; seq++ {
3154 if mb.dmap.Exists(seq) {
3155 // Optimisation to avoid calling cacheLookup which hits time.Now().
3156 // Instead we will update it only once in a defer.
3157 updateLLTS = true
3158 continue
3159 }
3160 llseq := mb.llseq
3161 fsm, err := mb.cacheLookup(seq, sm)
3162 if err != nil {
3163 if err == errPartialCache || err == errNoCache {
3164 return nil, false, err
3165 }
3166 continue
3167 }
3168 updateLLTS = false // cacheLookup already updated it.
3169 expireOk := seq == lseq && mb.llseq != llseq && mb.llseq == seq
3170 if isAll {
3171 return fsm, expireOk, nil
3172 }
3173 if wc && isMatch(sm.subj) {
3174 return fsm, expireOk, nil
3175 } else if !wc && fsm.subj == filter {
3176 return fsm, expireOk, nil
3177 }
3178 // If we are here we did not match, so put the llseq back.
3179 mb.llseq = llseq
3180 }
3181
3182 return nil, didLoad, ErrStoreMsgNotFound
3183 }
3184
3185 // Find the previous matching message against a sublist, working BACKWARDS from start.
3186 func (mb *msgBlock) prevMatchingMulti(sl *gsl.SimpleSublist, start uint64, sm *StoreMsg) (*StoreMsg, bool, error) {
3187 mb.mu.Lock()
3188 var didLoad bool
3189 var updateLLTS bool
3190 defer func() {
3191 if updateLLTS {
3192 mb.llts = ats.AccessTime()
3193 }
3194 mb.finishedWithCache()
3195 mb.mu.Unlock()
3196 }()
3197
3198 // Need messages loaded from here on out.
3199 if mb.cacheNotLoaded() {
3200 if err := mb.loadMsgsWithLock(); err != nil {
3201 return nil, false, err
3202 }
3203 didLoad = true
3204 }
3205
3206 // Make sure to start at mb.last.seq if lseq < mb.last.seq
3207 if seq := atomic.LoadUint64(&mb.last.seq); start > seq {
3208 start = seq
3209 }
3210 lseq := atomic.LoadUint64(&mb.first.seq)
3211
3212 if sm == nil {
3213 sm = new(StoreMsg)
3214 }
3215
3216 // If the FSS state has fewer entries than sequences in the linear scan,
3217 // then use intersection instead as likely going to be cheaper. This will
3218 // often be the case with high numbers of deletes, as well as a smaller
3219 // number of subjects in the block.
3220 if uint64(mb.fss.Size()) < start-lseq {
3221 // If there are no subject matches then this is effectively no-op.
3222 hseq := uint64(0)
3223 var ierr error
3224 stree.IntersectGSL(mb.fss, sl, func(subj []byte, ss *SimpleState) bool {
3225 if ss.firstNeedsUpdate || ss.lastNeedsUpdate {
3226 // mb is already loaded into the cache so should be fast-ish.
3227 if ierr = mb.recalculateForSubj(bytesToString(subj), ss); ierr != nil {
3228 return false
3229 }
3230 }
3231 first := min(start, ss.Last)
3232 // Skip if cutoff is before this subject's first, or if we already
3233 // have a higher-or-equal candidate (hseq holds the highest found).
3234 if first < ss.First || first <= hseq {
3235 // The start cutoff is before the first sequence for this subject,
3236 // or we already know of a subject with a later-or-equal msg.
3237 return true
3238 }
3239 if first == ss.Last {
3240 // If the start floor is above where this subject starts then we can
3241 // short-circuit, avoiding needing to scan for the next message.
3242 if fsm, err := mb.cacheLookup(ss.Last, sm); err == nil {
3243 sm = fsm
3244 hseq = ss.Last
3245 }
3246 return true
3247 }
3248 for seq := first; seq >= ss.First; seq-- {
3249 // Otherwise we have a start floor that intersects where this subject
3250 // has messages in the block, so we need to walk up until we find a
3251 // message matching the subject.
3252 if mb.dmap.Exists(seq) {
3253 // Optimisation to avoid calling cacheLookup which hits time.Now().
3254 // Instead we will update it only once in a defer.
3255 updateLLTS = true
3256 continue
3257 }
3258 llseq := mb.llseq
3259 fsm, err := mb.cacheLookup(seq, sm)
3260 if err != nil {
3261 continue
3262 }
3263 updateLLTS = false // cacheLookup already updated it.
3264 if sl.HasInterest(fsm.subj) {
3265 hseq = seq
3266 sm = fsm
3267 break
3268 }
3269 // If we are here we did not match, so put the llseq back.
3270 mb.llseq = llseq
3271 }
3272 return true
3273 })
3274 if ierr != nil {
3275 return nil, false, ierr
3276 }
3277 if hseq > 0 && sm != nil {
3278 return sm, didLoad && start == lseq, nil
3279 }
3280 } else {
3281 for seq := start; seq >= lseq; seq-- {
3282 if mb.dmap.Exists(seq) {
3283 // Optimisation to avoid calling cacheLookup which hits time.Now().
3284 // Instead we will update it only once in a defer.
3285 updateLLTS = true
3286 continue
3287 }
3288 llseq := mb.llseq
3289 fsm, err := mb.cacheLookup(seq, sm)
3290 if err != nil {
3291 continue
3292 }
3293 expireOk := seq == lseq && mb.llseq != llseq && mb.llseq == seq
3294 updateLLTS = false // cacheLookup already updated it.
3295 if sl.HasInterest(fsm.subj) {
3296 return fsm, expireOk, nil
3297 }
3298 // If we are here we did not match, so put the llseq back.
3299 mb.llseq = llseq
3300 }
3301 }
3302
3303 return nil, didLoad, ErrStoreMsgNotFound
3304 }
3305
3306 // This will traverse a message block and generate the filtered pending.
3307 func (mb *msgBlock) filteredPending(subj string, wc bool, seq uint64) (total, first, last uint64, err error) {
3308 mb.mu.Lock()
3309 defer mb.mu.Unlock()
3310 return mb.filteredPendingLocked(subj, wc, seq)
3311 }
3312
3313 // This will traverse a message block and generate the filtered pending.
3314 // Lock should be held.
3315 func (mb *msgBlock) filteredPendingLocked(filter string, wc bool, sseq uint64) (total, first, last uint64, err error) {
3316 isAll := filter == _EMPTY_ || filter == fwcs
3317
3318 // First check if we can optimize this part.
3319 // This means we want all and the starting sequence was before this block.
3320 if isAll {
3321 if fseq := atomic.LoadUint64(&mb.first.seq); sseq <= fseq {
3322 return mb.msgs, fseq, atomic.LoadUint64(&mb.last.seq), nil
3323 }
3324 }
3325
3326 needsCleanup := mb.cache == nil
3327 defer func() {
3328 if needsCleanup {
3329 mb.finishedWithCache()
3330 }
3331 }()
3332
3333 if filter == _EMPTY_ {
3334 filter, wc = fwcs, true
3335 }
3336
3337 update := func(ss *SimpleState) {
3338 total += ss.Msgs
3339 if first == 0 || ss.First < first {
3340 first = ss.First
3341 }
3342 if ss.Last > last {
3343 last = ss.Last
3344 }
3345 }
3346
3347 // Make sure we have fss loaded.
3348 if err = mb.ensurePerSubjectInfoLoaded(); err != nil {
3349 return 0, 0, 0, err
3350 }
3351
3352 var havePartial bool
3353
3354 // If we are not a wildcard just use Find() here. Avoids allocations.
3355 if !wc {
3356 if ss, ok := mb.fss.Find(stringToBytes(filter)); ok && ss != nil {
3357 if ss.firstNeedsUpdate || ss.lastNeedsUpdate {
3358 if err = mb.recalculateForSubj(filter, ss); err != nil {
3359 return 0, 0, 0, err
3360 }
3361 }
3362 if sseq <= ss.First {
3363 update(ss)
3364 } else if sseq <= ss.Last {
3365 // We matched but its a partial.
3366 havePartial = true
3367 }
3368 }
3369 } else {
3370 mb.fss.Match(stringToBytes(filter), func(bsubj []byte, ss *SimpleState) {
3371 if err != nil {
3372 return
3373 }
3374 if havePartial {
3375 // If we already found a partial then don't do anything else.
3376 return
3377 }
3378 if ss.firstNeedsUpdate || ss.lastNeedsUpdate {
3379 if err = mb.recalculateForSubj(bytesToString(bsubj), ss); err != nil {
3380 return
3381 }
3382 }
3383 if sseq <= ss.First {
3384 update(ss)
3385 } else if sseq <= ss.Last {
3386 // We matched but its a partial.
3387 havePartial = true
3388 }
3389 })
3390 if err != nil {
3391 return 0, 0, 0, err
3392 }
3393 }
3394
3395 // If we did not encounter any partials we can return here.
3396 if !havePartial {
3397 return total, first, last, nil
3398 }
3399
3400 // If we are here we need to scan the msgs.
3401 // Clear what we had.
3402 total, first, last = 0, 0, 0
3403
3404 // If we load the cache for a linear scan we want to expire that cache upon exit.
3405 var shouldExpire bool
3406 if mb.cacheNotLoaded() {
3407 if err = mb.loadMsgsWithLock(); err != nil {
3408 return 0, 0, 0, err
3409 }
3410 shouldExpire = true
3411 }
3412
3413 _tsa, _fsa := [32]string{}, [32]string{}
3414 tsa, fsa := _tsa[:0], _fsa[:0]
3415 var isMatch func(subj string) bool
3416
3417 if !wc {
3418 isMatch = func(subj string) bool { return subj == filter }
3419 } else {
3420 fsa = tokenizeSubjectIntoSlice(fsa[:0], filter)
3421 isMatch = func(subj string) bool {
3422 tsa = tokenizeSubjectIntoSlice(tsa[:0], subj)
3423 return isSubsetMatchTokenized(tsa, fsa)
3424 }
3425 }
3426
3427 // 1. See if we match any subs from fss.
3428 // 2. If we match and the sseq is past ss.Last then we can use meta only.
3429 // 3. If we match and we need to do a partial, break and clear any totals and do a full scan like num pending.
3430
3431 var smv StoreMsg
3432 for seq, lseq := sseq, atomic.LoadUint64(&mb.last.seq); seq <= lseq; seq++ {
3433 sm, _ := mb.cacheLookupNoCopy(seq, &smv)
3434 if sm == nil {
3435 continue
3436 }
3437 if isAll || isMatch(sm.subj) {
3438 total++
3439 if first == 0 || seq < first {
3440 first = seq
3441 }
3442 if seq > last {
3443 last = seq
3444 }
3445 }
3446 }
3447 // If we loaded this block for this operation go ahead and expire it here.
3448 if shouldExpire {
3449 mb.tryForceExpireCacheLocked()
3450 }
3451
3452 return total, first, last, nil
3453 }
3454
3455 // FilteredState will return the SimpleState associated with the filtered subject and a proposed starting sequence.
3456 func (fs *fileStore) FilteredState(sseq uint64, subj string) (SimpleState, error) {
3457 fs.mu.RLock()
3458 defer fs.mu.RUnlock()
3459
3460 lseq := fs.state.LastSeq
3461 if sseq < fs.state.FirstSeq {
3462 sseq = fs.state.FirstSeq
3463 }
3464
3465 // Returned state.
3466 var ss SimpleState
3467
3468 // If past the end no results.
3469 if sseq > lseq {
3470 // Make sure we track sequences
3471 ss.First = fs.state.FirstSeq
3472 ss.Last = fs.state.LastSeq
3473 return ss, nil
3474 }
3475
3476 // If we want all msgs that match we can shortcircuit.
3477 // TODO(dlc) - This can be extended for all cases but would
3478 // need to be careful on total msgs calculations etc.
3479 if sseq == fs.state.FirstSeq {
3480 if err := fs.numFilteredPending(subj, &ss); err != nil {
3481 return ss, err
3482 }
3483 } else {
3484 wc := subjectHasWildcard(subj)
3485 // Tracking subject state.
3486 // TODO(dlc) - Optimize for 2.10 with avl tree and no atomics per block.
3487 for _, mb := range fs.blks {
3488 // Skip blocks that are less than our starting sequence.
3489 if sseq > atomic.LoadUint64(&mb.last.seq) {
3490 continue
3491 }
3492 t, f, l, err := mb.filteredPending(subj, wc, sseq)
3493 if err != nil {
3494 return ss, err
3495 }
3496 ss.Msgs += t
3497 if ss.First == 0 || (f > 0 && f < ss.First) {
3498 ss.First = f
3499 }
3500 if l > ss.Last {
3501 ss.Last = l
3502 }
3503 }
3504 }
3505
3506 return ss, nil
3507 }
3508
3509 // This is used to see if we can selectively jump start blocks based on filter subject and a starting block index.
3510 // Will return -1 and ErrStoreEOF if no matches at all or no more from where we are.
3511 func (fs *fileStore) checkSkipFirstBlock(filter string, wc bool, bi int) (int, error) {
3512 // If we match everything, just move to next blk.
3513 if filter == _EMPTY_ || filter == fwcs {
3514 return bi + 1, nil
3515 }
3516 // Move through psim to gather start and stop bounds.
3517 start, stop := uint32(math.MaxUint32), uint32(0)
3518 if wc {
3519 if fs.psim.Size() > highCardinalityThreshold {
3520 return bi + 1, nil
3521 }
3522 fs.psim.Match(stringToBytes(filter), func(_ []byte, psi *psi) {
3523 if psi.fblk < start {
3524 start = psi.fblk
3525 }
3526 if psi.lblk > stop {
3527 stop = psi.lblk
3528 }
3529 })
3530 } else if psi, ok := fs.psim.Find(stringToBytes(filter)); ok {
3531 start, stop = psi.fblk, psi.lblk
3532 }
3533 // Nothing was found.
3534 if start == uint32(math.MaxUint32) {
3535 return -1, ErrStoreEOF
3536 }
3537 return fs.selectSkipFirstBlock(bi, start, stop)
3538 }
3539
3540 // This is used to see if we can selectively jump start blocks based on filter subjects and a starting block index.
3541 // Will return -1 and ErrStoreEOF if no matches at all or no more from where we are.
3542 func (fs *fileStore) checkSkipFirstBlockMulti(sl *gsl.SimpleSublist, bi int) (int, error) {
3543 // Don't bother if full wildcard.
3544 if sl.MatchesFullWildcard() || fs.psim.Size() > highCardinalityThreshold {
3545 return bi + 1, nil
3546 }
3547 // Move through psim to gather start and stop bounds.
3548 start, stop := uint32(math.MaxUint32), uint32(0)
3549 guard := fs.blks[bi].getIndex() + 1
3550 stree.IntersectGSL(fs.psim, sl, func(subj []byte, psi *psi) bool {
3551 if psi.fblk < start {
3552 start = psi.fblk
3553 }
3554 if start == guard {
3555 // One of the subjects matches the next block, so there's no point in carrying on trying to skip.
3556 return false
3557 }
3558 if psi.lblk > stop {
3559 stop = psi.lblk
3560 }
3561 return true
3562 })
3563 if start == guard {
3564 return bi + 1, nil
3565 }
3566 // Nothing was found.
3567 if start == uint32(math.MaxUint32) {
3568 return -1, ErrStoreEOF
3569 }
3570 return fs.selectSkipFirstBlock(bi, start, stop)
3571 }
3572
3573 func (fs *fileStore) selectSkipFirstBlock(bi int, start, stop uint32) (int, error) {
3574 // Can not be nil so ok to inline dereference.
3575 mbi := fs.blks[bi].getIndex()
3576 // All matching msgs are behind us.
3577 // Less than AND equal is important because we were called because we missed searching bi.
3578 if stop <= mbi {
3579 return -1, ErrStoreEOF
3580 }
3581 // If start is > index return dereference of fs.blks index.
3582 if start > mbi {
3583 if mb := fs.bim[start]; mb != nil {
3584 ni, _ := fs.selectMsgBlockWithIndex(atomic.LoadUint64(&mb.last.seq))
3585 return ni, nil
3586 }
3587 }
3588 // Otherwise just bump to the next one.
3589 return bi + 1, nil
3590 }
3591
3592 // Optimized way for getting all num pending matching a filter subject.
3593 // Lock should be held.
3594 func (fs *fileStore) numFilteredPending(filter string, ss *SimpleState) error {
3595 return fs.numFilteredPendingWithLast(filter, true, ss)
3596 }
3597
3598 // Optimized way for getting all num pending matching a filter subject and first sequence only.
3599 // Lock should be held.
3600 func (fs *fileStore) numFilteredPendingNoLast(filter string, ss *SimpleState) error {
3601 return fs.numFilteredPendingWithLast(filter, false, ss)
3602 }
3603
3604 // Optimized way for getting all num pending matching a filter subject.
3605 // Optionally look up last sequence. Sometimes do not need last and this avoids cost.
3606 // Read lock should be held.
3607 func (fs *fileStore) numFilteredPendingWithLast(filter string, last bool, ss *SimpleState) error {
3608 isAll := filter == _EMPTY_ || filter == fwcs
3609
3610 // If isAll we do not need to do anything special to calculate the first and last and total.
3611 if isAll {
3612 ss.First = fs.state.FirstSeq
3613 ss.Last = fs.state.LastSeq
3614 ss.Msgs = fs.state.Msgs
3615 return nil
3616 }
3617 // Always reset.
3618 ss.First, ss.Last, ss.Msgs = 0, 0, 0
3619
3620 // We do need to figure out the first and last sequences.
3621 wc := subjectHasWildcard(filter)
3622 start, stop := uint32(math.MaxUint32), uint32(0)
3623
3624 if wc {
3625 fs.psim.Match(stringToBytes(filter), func(_ []byte, psi *psi) {
3626 ss.Msgs += psi.total
3627 // Keep track of start and stop indexes for this subject.
3628 if psi.fblk < start {
3629 start = psi.fblk
3630 }
3631 if psi.lblk > stop {
3632 stop = psi.lblk
3633 }
3634 })
3635 } else if psi, ok := fs.psim.Find(stringToBytes(filter)); ok {
3636 ss.Msgs += psi.total
3637 start, stop = psi.fblk, psi.lblk
3638 }
3639
3640 // Did not find anything.
3641 if stop == 0 {
3642 return nil
3643 }
3644
3645 // Do start
3646 mb := fs.bim[start]
3647 if mb != nil {
3648 _, f, _, err := mb.filteredPending(filter, wc, 0)
3649 if err != nil {
3650 return err
3651 }
3652 ss.First = f
3653 }
3654
3655 if ss.First == 0 {
3656 // This is a miss. This can happen since psi.fblk is lazy.
3657 // We will make sure to update fblk.
3658
3659 // Hold this outside loop for psim fblk updates when done.
3660 i := start + 1
3661 for ; i <= stop; i++ {
3662 mb := fs.bim[i]
3663 if mb == nil {
3664 continue
3665 }
3666 if _, f, _, err := mb.filteredPending(filter, wc, 0); err != nil {
3667 return err
3668 } else if f > 0 {
3669 ss.First = f
3670 break
3671 }
3672 }
3673 // Update fblk since fblk was outdated.
3674 // We only require read lock here as that is desirable,
3675 // so we need to do this in a go routine to acquire write lock.
3676 go func() {
3677 fs.mu.Lock()
3678 defer fs.mu.Unlock()
3679 if !wc {
3680 if info, ok := fs.psim.Find(stringToBytes(filter)); ok {
3681 if i > info.fblk {
3682 info.fblk = i
3683 }
3684 }
3685 } else {
3686 fs.psim.Match(stringToBytes(filter), func(subj []byte, psi *psi) {
3687 if i > psi.fblk {
3688 psi.fblk = i
3689 }
3690 })
3691 }
3692 }()
3693 }
3694 // Now gather last sequence if asked to do so.
3695 if last {
3696 if mb = fs.bim[stop]; mb != nil {
3697 _, _, l, err := mb.filteredPending(filter, wc, 0)
3698 if err != nil {
3699 return err
3700 }
3701 ss.Last = l
3702 }
3703 }
3704 return nil
3705 }
3706
3707 // SubjectsState returns a map of SimpleState for all matching subjects.
3708 func (fs *fileStore) SubjectsState(subject string) map[string]SimpleState {
3709 fs.mu.RLock()
3710 defer fs.mu.RUnlock()
3711
3712 if fs.state.Msgs == 0 || fs.noTrackSubjects() {
3713 return nil
3714 }
3715
3716 if subject == _EMPTY_ {
3717 subject = fwcs
3718 }
3719
3720 start, stop := fs.blks[0], fs.lmb
3721 // We can short circuit if not a wildcard using psim for start and stop.
3722 if !subjectHasWildcard(subject) {
3723 info, ok := fs.psim.Find(stringToBytes(subject))
3724 if !ok {
3725 return nil
3726 }
3727 if f := fs.bim[info.fblk]; f != nil {
3728 start = f
3729 }
3730 if l := fs.bim[info.lblk]; l != nil {
3731 stop = l
3732 }
3733 }
3734
3735 // Aggregate fss.
3736 fss := make(map[string]SimpleState)
3737 var startFound bool
3738
3739 for _, mb := range fs.blks {
3740 if !startFound {
3741 if mb != start {
3742 continue
3743 }
3744 startFound = true
3745 }
3746
3747 mb.mu.Lock()
3748 var shouldExpire bool
3749 if mb.fssNotLoaded() {
3750 // Make sure we have fss loaded.
3751 if err := mb.loadMsgsWithLock(); err != nil {
3752 mb.mu.Unlock()
3753 return nil
3754 }
3755 shouldExpire = true
3756 }
3757 // Mark fss activity.
3758 mb.lsts = ats.AccessTime()
3759 var ierr error
3760 mb.fss.Match(stringToBytes(subject), func(bsubj []byte, ss *SimpleState) {
3761 if ierr != nil {
3762 return
3763 }
3764 subj := string(bsubj)
3765 if ss.firstNeedsUpdate || ss.lastNeedsUpdate {
3766 if ierr = mb.recalculateForSubj(subj, ss); ierr != nil {
3767 return
3768 }
3769 }
3770 oss := fss[subj]
3771 if oss.First == 0 { // New
3772 fss[subj] = *ss
3773 } else {
3774 // Merge here.
3775 oss.Last, oss.Msgs = ss.Last, oss.Msgs+ss.Msgs
3776 fss[subj] = oss
3777 }
3778 })
3779 if shouldExpire {
3780 // Expire this cache before moving on.
3781 mb.tryForceExpireCacheLocked()
3782 } else {
3783 mb.finishedWithCache()
3784 }
3785 mb.mu.Unlock()
3786 if ierr != nil {
3787 return nil
3788 }
3789 if mb == stop {
3790 break
3791 }
3792 }
3793
3794 return fss
3795 }
3796
3797 // AllLastSeqs will return a sorted list of last sequences for all subjects.
3798 func (fs *fileStore) AllLastSeqs() ([]uint64, error) {
3799 fs.mu.RLock()
3800 defer fs.mu.RUnlock()
3801 return fs.allLastSeqsLocked()
3802 }
3803
3804 // allLastSeqsLocked will return a sorted list of last sequences for all
3805 // subjects, but won't take the lock to do it, to avoid the issue of compounding
3806 // read locks causing a deadlock with a write lock.
3807 func (fs *fileStore) allLastSeqsLocked() ([]uint64, error) {
3808 if fs.state.Msgs == 0 || fs.noTrackSubjects() {
3809 return nil, nil
3810 }
3811
3812 numSubjects := fs.psim.Size()
3813 seqs := make([]uint64, 0, numSubjects)
3814 subs := make(map[string]struct{}, numSubjects)
3815
3816 for i := len(fs.blks) - 1; i >= 0; i-- {
3817 if len(subs) == numSubjects {
3818 break
3819 }
3820 mb := fs.blks[i]
3821 mb.mu.Lock()
3822
3823 var shouldExpire bool
3824 if mb.fssNotLoaded() {
3825 // Make sure we have fss loaded.
3826 if err := mb.loadMsgsWithLock(); err != nil {
3827 mb.mu.Unlock()
3828 return nil, err
3829 }
3830 shouldExpire = true
3831 }
3832
3833 var ierr error
3834 mb.fss.IterFast(func(bsubj []byte, ss *SimpleState) bool {
3835 // Check if already been processed and accounted.
3836 if _, ok := subs[string(bsubj)]; !ok {
3837 // Check if we need to recalculate. We only care about the last sequence.
3838 if ss.lastNeedsUpdate {
3839 // mb is already loaded into the cache so should be fast-ish.
3840 if ierr = mb.recalculateForSubj(bytesToString(bsubj), ss); ierr != nil {
3841 return false
3842 }
3843 }
3844 seqs = append(seqs, ss.Last)
3845 subs[string(bsubj)] = struct{}{}
3846 }
3847 return true
3848 })
3849 if shouldExpire {
3850 // Expire this cache before moving on.
3851 mb.tryForceExpireCacheLocked()
3852 }
3853 mb.finishedWithCache()
3854 mb.mu.Unlock()
3855 if ierr != nil {
3856 return nil, ierr
3857 }
3858 }
3859
3860 slices.Sort(seqs)
3861 return seqs, nil
3862 }
3863
3864 // Helper to determine if the filter(s) represent all the subjects.
3865 // Most clients send in subjects even if they match the stream's ingest subjects.
3866 // Lock should be held.
3867 func (fs *fileStore) filterIsAll(filters []string) bool {
3868 if len(filters) == 1 && filters[0] == fwcs {
3869 return true
3870 }
3871 if len(filters) != len(fs.cfg.Subjects) {
3872 return false
3873 }
3874 // Sort so we can compare.
3875 subjects := copyStrings(fs.cfg.Subjects)
3876 slices.Sort(filters)
3877 slices.Sort(subjects)
3878 for i, subj := range filters {
3879 if !subjectIsSubsetMatch(subjects[i], subj) {
3880 return false
3881 }
3882 }
3883 return true
3884 }
3885
3886 // MultiLastSeqs will return a sorted list of sequences that match all subjects presented in filters.
3887 // We will not exceed the maxSeq, which if 0 becomes the store's last sequence.
3888 func (fs *fileStore) MultiLastSeqs(filters []string, maxSeq uint64, maxAllowed int) ([]uint64, error) {
3889 fs.mu.RLock()
3890 defer fs.mu.RUnlock()
3891 return fs.multiLastSeqsLocked(filters, maxSeq, maxAllowed)
3892 }
3893
3894 // Lock should be held.
3895 func (fs *fileStore) multiLastSeqsLocked(filters []string, maxSeq uint64, maxAllowed int) ([]uint64, error) {
3896 if fs.state.Msgs == 0 || fs.noTrackSubjects() {
3897 return nil, nil
3898 }
3899
3900 // See if we can short circuit if we think they are asking for all last sequences and have no maxSeq or maxAllowed set.
3901 if maxSeq == 0 && maxAllowed <= 0 && fs.filterIsAll(filters) {
3902 return fs.allLastSeqsLocked()
3903 }
3904
3905 lastBlkIndex := len(fs.blks) - 1
3906 lastMB := fs.blks[lastBlkIndex]
3907
3908 // Implied last sequence.
3909 if maxSeq == 0 {
3910 maxSeq = fs.state.LastSeq
3911 } else {
3912 // Udate last mb index if not last seq.
3913 lastBlkIndex, lastMB = fs.selectMsgBlockWithIndex(maxSeq)
3914 }
3915 // Make sure non-nil
3916 if lastMB == nil {
3917 return nil, nil
3918 }
3919
3920 // Grab our last mb index (not same as blk index).
3921 lastMB.mu.RLock()
3922 lastMBIndex := lastMB.index
3923 lastMB.mu.RUnlock()
3924
3925 subs := make(map[string]*psi)
3926 var numLess int
3927 var maxBlk uint32
3928
3929 for _, filter := range filters {
3930 fs.psim.Match(stringToBytes(filter), func(subj []byte, psi *psi) {
3931 subs[string(subj)] = psi
3932 if psi.lblk < lastMBIndex {
3933 numLess++
3934 if psi.lblk > maxBlk {
3935 maxBlk = psi.lblk
3936 }
3937 }
3938 })
3939 }
3940
3941 // If all subjects have a lower last index, select the largest for our walk backwards.
3942 if numLess == len(subs) {
3943 lastMB = fs.bim[maxBlk]
3944 }
3945
3946 // Collect all sequences needed.
3947 seqs := make([]uint64, 0, len(subs))
3948
3949 // If covering the whole stream, check fast path of visiting only last blocks.
3950 if maxSeq >= fs.state.LastSeq {
3951 if maxAllowed > 0 && len(subs) > maxAllowed {
3952 return nil, ErrTooManyResults
3953 }
3954 if err := fs.multiLastSeqsByLastBlockLocked(subs, &seqs); err != nil {
3955 return nil, err
3956 }
3957 }
3958
3959 for i, lnf := lastBlkIndex, false; i >= 0; i-- {
3960 if len(subs) == 0 {
3961 break
3962 }
3963 mb := fs.blks[i]
3964 if !lnf {
3965 if mb != lastMB {
3966 continue
3967 }
3968 lnf = true
3969 }
3970 // We can start properly looking here.
3971 mb.mu.Lock()
3972 var ierr error
3973 if ierr = mb.ensurePerSubjectInfoLoaded(); ierr != nil {
3974 mb.mu.Unlock()
3975 return nil, ierr
3976 }
3977
3978 // Iterate the fss and check against our subs. We will delete from subs as we add.
3979 // Once len(subs) == 0 we are done.
3980 mb.fss.IterFast(func(bsubj []byte, ss *SimpleState) bool {
3981 // Already been processed and accounted for was not matched in the first place.
3982 if subs[string(bsubj)] == nil {
3983 return true
3984 }
3985 // Check if we need to recalculate. We only care about the last sequence.
3986 if ss.lastNeedsUpdate {
3987 // mb is already loaded into the cache so should be fast-ish.
3988 if ierr = mb.recalculateForSubj(bytesToString(bsubj), ss); ierr != nil {
3989 return false
3990 }
3991 }
3992 // If we are equal or below just add to seqs slice.
3993 if ss.Last <= maxSeq {
3994 seqs = append(seqs, ss.Last)
3995 delete(subs, bytesToString(bsubj))
3996 } else {
3997 // Need to search for the real last since recorded last is > maxSeq.
3998 needsCleanup := mb.cache == nil
3999 if mb.cacheNotLoaded() {
4000 if ierr = mb.loadMsgsWithLock(); ierr != nil {
4001 if needsCleanup {
4002 mb.finishedWithCache()
4003 }
4004 return false
4005 }
4006 }
4007 var smv StoreMsg
4008 fseq := atomic.LoadUint64(&mb.first.seq)
4009 lseq := min(atomic.LoadUint64(&mb.last.seq), maxSeq)
4010 ssubj := bytesToString(bsubj)
4011 for seq := lseq; seq >= fseq; seq-- {
4012 sm, _ := mb.cacheLookupNoCopy(seq, &smv)
4013 if sm == nil || sm.subj != ssubj {
4014 continue
4015 }
4016 seqs = append(seqs, sm.seq)
4017 delete(subs, ssubj)
4018 break
4019 }
4020 if needsCleanup {
4021 mb.finishedWithCache()
4022 }
4023 }
4024 return true
4025 })
4026 mb.mu.Unlock()
4027 if ierr != nil {
4028 return nil, ierr
4029 }
4030
4031 // If maxAllowed was sepcified check that we will not exceed that.
4032 if maxAllowed > 0 && len(seqs) > maxAllowed {
4033 return nil, ErrTooManyResults
4034 }
4035 }
4036 if len(seqs) == 0 {
4037 return nil, nil
4038 }
4039 slices.Sort(seqs)
4040 return seqs, nil
4041 }
4042
4043 // MultiLastMsgs delivers the last message per subject matching the filters,
4044 // up to maxSeq and skipping sequences below minSeq, in ascending sequence
4045 // order through cb, all within a single read section so the batch is a
4046 // point-in-time snapshot of the store.
4047 func (fs *fileStore) MultiLastMsgs(filters []string, minSeq, maxSeq uint64, maxAllowed int, cb func(sm *StoreMsg, np uint64) bool) (uint64, uint64, error) {
4048 fs.mu.RLock()
4049 defer fs.mu.RUnlock()
4050
4051 seqs, err := fs.multiLastSeqsLocked(filters, maxSeq, maxAllowed)
4052 if err != nil || len(seqs) == 0 {
4053 return 0, 0, err
4054 }
4055 total := uint64(len(seqs))
4056 np := total
4057 for _, seq := range seqs {
4058 if np > 0 {
4059 np--
4060 }
4061 if seq < minSeq {
4062 continue
4063 }
4064 var svp StoreMsg
4065 sm, err := fs.msgForSeqLocked(seq, &svp, false)
4066 if err != nil {
4067 return total, np, err
4068 }
4069 if !cb(sm, np) {
4070 break
4071 }
4072 }
4073 return total, np, nil
4074 }
4075
4076 // multiLastSeqsByLastBlockLocked resolves last sequences via each subject's
4077 // last block (psi.lblk), moving resolved subjects from subs into seqs and
4078 // leaving unresolved ones (e.g. stale lblk) in subs for the caller.
4079 // Lock should be held.
4080 func (fs *fileStore) multiLastSeqsByLastBlockLocked(subs map[string]*psi, seqs *[]uint64) error {
4081 // Sort requested subjects by their last block so each block is visited
4082 // once and in order, one flat slice instead of per-block map bookkeeping.
4083 type lblkSubj struct {
4084 lblk uint32
4085 subj string
4086 info *psi
4087 }
4088 pairs := make([]lblkSubj, 0, len(subs))
4089 for subj, info := range subs {
4090 pairs = append(pairs, lblkSubj{info.lblk, subj, info})
4091 }
4092 slices.SortFunc(pairs, func(a, b lblkSubj) int {
4093 return cmp.Compare(a.lblk, b.lblk)
4094 })
4095
4096 var unresolved []lblkSubj
4097 for i := 0; i < len(pairs); {
4098 blkIdx := pairs[i].lblk
4099 j := i + 1
4100 for j < len(pairs) && pairs[j].lblk == blkIdx {
4101 j++
4102 }
4103 mb := fs.bim[blkIdx]
4104 if mb == nil {
4105 unresolved = append(unresolved, pairs[i:j]...)
4106 i = j
4107 continue
4108 }
4109 mb.mu.Lock()
4110 if err := mb.ensurePerSubjectInfoLoaded(); err != nil {
4111 mb.mu.Unlock()
4112 return err
4113 }
4114 for ; i < j; i++ {
4115 subj := pairs[i].subj
4116 ss, ok := mb.fss.Find(stringToBytes(subj))
4117 if !ok || ss == nil {
4118 unresolved = append(unresolved, pairs[i])
4119 continue
4120 }
4121 // Check if we need to recalculate. We only care about the last sequence.
4122 if ss.lastNeedsUpdate {
4123 if err := mb.recalculateForSubj(subj, ss); err != nil {
4124 mb.mu.Unlock()
4125 return err
4126 }
4127 }
4128 *seqs = append(*seqs, ss.Last)
4129 }
4130 mb.mu.Unlock()
4131 }
4132
4133 // Shrink subs down to only the unresolved subjects, clearing wholesale
4134 // rather than deleting per resolved subject.
4135 if len(unresolved) < len(subs) {
4136 clear(subs)
4137 for _, p := range unresolved {
4138 subs[p.subj] = p.info
4139 }
4140 }
4141 return nil
4142 }
4143
4144 // NumPending will return the number of pending messages matching the filter subject starting at sequence.
4145 // Optimized for stream num pending calculations for consumers.
4146 func (fs *fileStore) NumPending(sseq uint64, filter string, lastPerSubject bool) (total, validThrough uint64, err error) {
4147 fs.mu.RLock()
4148 defer fs.mu.RUnlock()
4149
4150 // This can always be last for these purposes.
4151 validThrough = fs.state.LastSeq
4152
4153 if fs.state.Msgs == 0 || sseq > fs.state.LastSeq {
4154 return 0, validThrough, nil
4155 }
4156
4157 // If sseq is less then our first set to first.
4158 if sseq < fs.state.FirstSeq {
4159 sseq = fs.state.FirstSeq
4160 }
4161 // Track starting for both block for the sseq and staring block that matches any subject.
4162 var seqStart int
4163 // See if we need to figure out starting block per sseq.
4164 if sseq > fs.state.FirstSeq {
4165 // This should not, but can return -1, so make sure we check to avoid panic below.
4166 if seqStart, _ = fs.selectMsgBlockWithIndex(sseq); seqStart < 0 {
4167 seqStart = 0
4168 }
4169 }
4170
4171 isAll := filter == _EMPTY_ || filter == fwcs
4172 if isAll && filter == _EMPTY_ {
4173 filter = fwcs
4174 }
4175 wc := subjectHasWildcard(filter)
4176
4177 // See if filter was provided but its the only subject.
4178 if !isAll && !wc && fs.psim.Size() == 1 {
4179 _, isAll = fs.psim.Find(stringToBytes(filter))
4180 }
4181 // If we are isAll and have no deleted we can do a simpler calculation.
4182 if !lastPerSubject && isAll && (fs.state.LastSeq-fs.state.FirstSeq+1) == fs.state.Msgs {
4183 if sseq == 0 {
4184 return fs.state.Msgs, validThrough, nil
4185 }
4186 return fs.state.LastSeq - sseq + 1, validThrough, nil
4187 }
4188
4189 _tsa, _fsa := [32]string{}, [32]string{}
4190 tsa, fsa := _tsa[:0], _fsa[:0]
4191 if wc {
4192 fsa = tokenizeSubjectIntoSlice(fsa[:0], filter)
4193 }
4194
4195 isMatch := func(subj string) bool {
4196 if isAll {
4197 return true
4198 }
4199 if !wc {
4200 return subj == filter
4201 }
4202 tsa = tokenizeSubjectIntoSlice(tsa[:0], subj)
4203 return isSubsetMatchTokenized(tsa, fsa)
4204 }
4205
4206 // Handle last by subject a bit differently.
4207 // We will scan PSIM since we accurately track the last block we have seen the subject in. This
4208 // allows us to only need to load at most one block now.
4209 // For the last block, we need to track the subjects that we know are in that block, and track seen
4210 // while in the block itself, but complexity there worth it.
4211 if lastPerSubject {
4212 // If we want all and our start sequence is equal or less than first return number of subjects.
4213 if isAll && sseq <= fs.state.FirstSeq {
4214 return uint64(fs.psim.Size()), validThrough, nil
4215 }
4216 // If we are here we need to scan. We are going to scan the PSIM looking for lblks that are >= seqStart.
4217 // This will build up a list of all subjects from the selected block onward.
4218 lbm := make(map[string]bool)
4219 mb := fs.blks[seqStart]
4220 bi := mb.index
4221
4222 fs.psim.Match(stringToBytes(filter), func(subj []byte, psi *psi) {
4223 // If the select blk start is greater than entry's last blk skip.
4224 if bi > psi.lblk {
4225 return
4226 }
4227 total++
4228 // We will track the subjects that are an exact match to the last block.
4229 // This is needed for last block processing.
4230 if psi.lblk == bi {
4231 lbm[string(subj)] = true
4232 }
4233 })
4234
4235 // Now check if we need to inspect the seqStart block.
4236 // Grab write lock in case we need to load in msgs.
4237 mb.mu.Lock()
4238 var updateLLTS bool
4239 var shouldExpire bool
4240 // We need to walk this block to correct accounting from above.
4241 if sseq > mb.first.seq {
4242 // Track the ones we add back in case more than one.
4243 seen := make(map[string]bool)
4244 // We need to discount the total by subjects seen before sseq, but also add them right back in if they are >= sseq for this blk.
4245 // This only should be subjects we know have the last blk in this block.
4246 if mb.cacheNotLoaded() {
4247 if err = mb.loadMsgsWithLock(); err != nil {
4248 mb.mu.Unlock()
4249 return 0, 0, err
4250 }
4251 shouldExpire = true
4252 }
4253 var smv StoreMsg
4254 for seq, lseq := atomic.LoadUint64(&mb.first.seq), atomic.LoadUint64(&mb.last.seq); seq <= lseq; seq++ {
4255 if mb.dmap.Exists(seq) {
4256 // Optimisation to avoid calling cacheLookup which hits time.Now().
4257 updateLLTS = true
4258 continue
4259 }
4260 sm, _ := mb.cacheLookupNoCopy(seq, &smv)
4261 if sm == nil || sm.subj == _EMPTY_ || !lbm[sm.subj] {
4262 continue
4263 }
4264 updateLLTS = false // cacheLookup already updated it.
4265 if isMatch(sm.subj) {
4266 // If less than sseq adjust off of total as long as this subject matched the last block.
4267 if seq < sseq {
4268 if !seen[sm.subj] {
4269 total--
4270 seen[sm.subj] = true
4271 }
4272 } else if seen[sm.subj] {
4273 // This is equal or more than sseq, so add back in.
4274 total++
4275 // Make sure to not process anymore.
4276 delete(seen, sm.subj)
4277 }
4278 }
4279 }
4280 }
4281 // If we loaded the block try to force expire.
4282 if shouldExpire {
4283 mb.tryForceExpireCacheLocked()
4284 } else {
4285 mb.finishedWithCache()
4286 }
4287 if updateLLTS {
4288 mb.llts = ats.AccessTime()
4289 }
4290 mb.mu.Unlock()
4291 return total, validThrough, nil
4292 }
4293
4294 // If we would need to scan more from the beginning, revert back to calculating directly here.
4295 // TODO(dlc) - Redo properly with sublists etc for subject-based filtering.
4296 if seqStart >= (len(fs.blks) / 2) {
4297 for i := seqStart; i < len(fs.blks); i++ {
4298 var shouldExpire bool
4299 mb := fs.blks[i]
4300 // Hold write lock in case we need to load cache.
4301 mb.mu.Lock()
4302 if isAll && sseq <= atomic.LoadUint64(&mb.first.seq) {
4303 total += mb.msgs
4304 mb.mu.Unlock()
4305 continue
4306 }
4307 // If we are here we need to at least scan the subject fss.
4308 // Make sure we have fss loaded.
4309 if mb.fssNotLoaded() {
4310 if err = mb.loadMsgsWithLock(); err != nil {
4311 mb.mu.Unlock()
4312 return 0, 0, err
4313 }
4314 shouldExpire = true
4315 }
4316 // Mark fss activity.
4317 mb.lsts = ats.AccessTime()
4318
4319 var t uint64
4320 var ierr error
4321 var havePartial bool
4322 mb.fss.Match(stringToBytes(filter), func(bsubj []byte, ss *SimpleState) {
4323 if ierr != nil {
4324 return
4325 }
4326 if havePartial {
4327 // If we already found a partial then don't do anything else.
4328 return
4329 }
4330 subj := bytesToString(bsubj)
4331 if ss.firstNeedsUpdate || ss.lastNeedsUpdate {
4332 if ierr = mb.recalculateForSubj(subj, ss); ierr != nil {
4333 return
4334 }
4335 }
4336 if sseq <= ss.First {
4337 t += ss.Msgs
4338 } else if sseq <= ss.Last {
4339 // We matched but its a partial.
4340 havePartial = true
4341 }
4342 })
4343 if ierr != nil {
4344 mb.mu.Unlock()
4345 return 0, 0, ierr
4346 }
4347
4348 // See if we need to scan msgs here.
4349 if havePartial {
4350 // Make sure we have the cache loaded.
4351 if mb.cacheNotLoaded() {
4352 if err = mb.loadMsgsWithLock(); err != nil {
4353 mb.mu.Unlock()
4354 return 0, 0, err
4355 }
4356 shouldExpire = true
4357 }
4358 // Clear on partial.
4359 t = 0
4360 start := sseq
4361 if fseq := atomic.LoadUint64(&mb.first.seq); fseq > start {
4362 start = fseq
4363 }
4364 var smv StoreMsg
4365 for seq, lseq := start, atomic.LoadUint64(&mb.last.seq); seq <= lseq; seq++ {
4366 if sm, _ := mb.cacheLookupNoCopy(seq, &smv); sm != nil && isMatch(sm.subj) {
4367 t++
4368 }
4369 }
4370 }
4371 // If we loaded this block for this operation go ahead and expire it here.
4372 if shouldExpire {
4373 mb.tryForceExpireCacheLocked()
4374 } else {
4375 mb.finishedWithCache()
4376 }
4377 mb.mu.Unlock()
4378 total += t
4379 }
4380 return total, validThrough, nil
4381 }
4382
4383 // If we are here it's better to calculate totals from psim and adjust downward by scanning less blocks.
4384 // TODO(dlc) - Eventually when sublist uses generics, make this sublist driven instead.
4385 start := uint32(math.MaxUint32)
4386 fs.psim.Match(stringToBytes(filter), func(_ []byte, psi *psi) {
4387 total += psi.total
4388 // Keep track of start index for this subject.
4389 if psi.fblk < start {
4390 start = psi.fblk
4391 }
4392 })
4393 // See if we were asked for all, if so we are done.
4394 if sseq <= fs.state.FirstSeq {
4395 return total, validThrough, nil
4396 }
4397
4398 // If we are here we need to calculate partials for the first blocks.
4399 firstSubjBlk := fs.bim[start]
4400 var firstSubjBlkFound bool
4401 // Adjust in case not found.
4402 if firstSubjBlk == nil {
4403 firstSubjBlkFound = true
4404 }
4405
4406 // Track how many we need to adjust against the total.
4407 var adjust uint64
4408 for i := 0; i <= seqStart; i++ {
4409 mb := fs.blks[i]
4410 // We can skip blks if we know they are below the first one that has any subject matches.
4411 if !firstSubjBlkFound {
4412 if firstSubjBlkFound = (mb == firstSubjBlk); !firstSubjBlkFound {
4413 continue
4414 }
4415 }
4416 // We need to scan this block.
4417 var shouldExpire bool
4418 var updateLLTS bool
4419 mb.mu.Lock()
4420 // Check if we should include all of this block in adjusting. If so work with metadata.
4421 if sseq > atomic.LoadUint64(&mb.last.seq) {
4422 if isAll {
4423 adjust += mb.msgs
4424 } else {
4425 // We need to adjust for all matches in this block.
4426 // Make sure we have fss loaded. This loads whole block now.
4427 if mb.fssNotLoaded() {
4428 if err = mb.loadMsgsWithLock(); err != nil {
4429 mb.mu.Unlock()
4430 return 0, 0, err
4431 }
4432 shouldExpire = true
4433 }
4434 // Mark fss activity.
4435 mb.lsts = ats.AccessTime()
4436
4437 mb.fss.Match(stringToBytes(filter), func(bsubj []byte, ss *SimpleState) {
4438 adjust += ss.Msgs
4439 })
4440 }
4441 } else {
4442 // This is the last block. We need to scan per message here.
4443 if mb.cacheNotLoaded() {
4444 if err = mb.loadMsgsWithLock(); err != nil {
4445 mb.mu.Unlock()
4446 return 0, 0, err
4447 }
4448 shouldExpire = true
4449 }
4450 var last = atomic.LoadUint64(&mb.last.seq)
4451 if sseq < last {
4452 last = sseq
4453 }
4454 // We need to walk all messages in this block
4455 var smv StoreMsg
4456 for seq := atomic.LoadUint64(&mb.first.seq); seq < last; seq++ {
4457 if mb.dmap.Exists(seq) {
4458 // Optimisation to avoid calling cacheLookup which hits time.Now().
4459 updateLLTS = true
4460 continue
4461 }
4462 sm, _ := mb.cacheLookupNoCopy(seq, &smv)
4463 if sm == nil || sm.subj == _EMPTY_ {
4464 continue
4465 }
4466 updateLLTS = false // cacheLookup already updated it.
4467 // Check if it matches our filter.
4468 if sm.seq < sseq && isMatch(sm.subj) {
4469 adjust++
4470 }
4471 }
4472 }
4473 // If we loaded the block try to force expire.
4474 if shouldExpire {
4475 mb.tryForceExpireCacheLocked()
4476 } else {
4477 mb.finishedWithCache()
4478 }
4479 if updateLLTS {
4480 mb.llts = ats.AccessTime()
4481 }
4482 mb.mu.Unlock()
4483 }
4484 // Make final adjustment.
4485 if adjust > total {
4486 total = 0
4487 } else {
4488 total -= adjust
4489 }
4490
4491 return total, validThrough, nil
4492 }
4493
4494 // NumPending will return the number of pending messages matching any subject in the sublist starting at sequence.
4495 // Optimized for stream num pending calculations for consumers with lots of filtered subjects.
4496 // Subjects should not overlap, this property is held when doing multi-filtered consumers.
4497 func (fs *fileStore) NumPendingMulti(sseq uint64, sl *gsl.SimpleSublist, lastPerSubject bool) (total, validThrough uint64, err error) {
4498 fs.mu.RLock()
4499 defer fs.mu.RUnlock()
4500
4501 // This can always be last for these purposes.
4502 validThrough = fs.state.LastSeq
4503
4504 if fs.state.Msgs == 0 || sseq > fs.state.LastSeq {
4505 return 0, validThrough, nil
4506 }
4507
4508 // If sseq is less then our first set to first.
4509 if sseq < fs.state.FirstSeq {
4510 sseq = fs.state.FirstSeq
4511 }
4512 // Track starting for both block for the sseq and staring block that matches any subject.
4513 var seqStart int
4514 // See if we need to figure out starting block per sseq.
4515 if sseq > fs.state.FirstSeq {
4516 // This should not, but can return -1, so make sure we check to avoid panic below.
4517 if seqStart, _ = fs.selectMsgBlockWithIndex(sseq); seqStart < 0 {
4518 seqStart = 0
4519 }
4520 }
4521
4522 isAll := sl == nil
4523
4524 // See if filter was provided but its the only subject.
4525 if !isAll && fs.psim.Size() == 1 {
4526 fs.psim.IterFast(func(subject []byte, _ *psi) bool {
4527 isAll = sl.HasInterest(bytesToString(subject))
4528 return true
4529 })
4530 }
4531 // If we are isAll and have no deleted we can do a simpler calculation.
4532 if !lastPerSubject && isAll && (fs.state.LastSeq-fs.state.FirstSeq+1) == fs.state.Msgs {
4533 if sseq == 0 {
4534 return fs.state.Msgs, validThrough, nil
4535 }
4536 return fs.state.LastSeq - sseq + 1, validThrough, nil
4537 }
4538 // Setup the isMatch function.
4539 isMatch := func(subj string) bool {
4540 if isAll {
4541 return true
4542 }
4543 return sl.HasInterest(subj)
4544 }
4545
4546 // Handle last by subject a bit differently.
4547 // We will scan PSIM since we accurately track the last block we have seen the subject in. This
4548 // allows us to only need to load at most one block now.
4549 // For the last block, we need to track the subjects that we know are in that block, and track seen
4550 // while in the block itself, but complexity there worth it.
4551 if lastPerSubject {
4552 // If we want all and our start sequence is equal or less than first return number of subjects.
4553 if isAll && sseq <= fs.state.FirstSeq {
4554 return uint64(fs.psim.Size()), validThrough, nil
4555 }
4556 // If we are here we need to scan. We are going to scan the PSIM looking for lblks that are >= seqStart.
4557 // This will build up a list of all subjects from the selected block onward.
4558 lbm := make(map[string]bool)
4559 mb := fs.blks[seqStart]
4560 bi := mb.index
4561
4562 stree.IntersectGSL(fs.psim, sl, func(subj []byte, psi *psi) bool {
4563 // If the select blk start is greater than entry's last blk skip.
4564 if bi > psi.lblk {
4565 return true
4566 }
4567 total++
4568 // We will track the subjects that are an exact match to the last block.
4569 // This is needed for last block processing.
4570 if psi.lblk == bi {
4571 lbm[string(subj)] = true
4572 }
4573 return true
4574 })
4575
4576 // Now check if we need to inspect the seqStart block.
4577 // Grab write lock in case we need to load in msgs.
4578 mb.mu.Lock()
4579 var shouldExpire bool
4580 var updateLLTS bool
4581 // We need to walk this block to correct accounting from above.
4582 if sseq > atomic.LoadUint64(&mb.first.seq) {
4583 // Track the ones we add back in case more than one.
4584 seen := make(map[string]bool)
4585 // We need to discount the total by subjects seen before sseq, but also add them right back in if they are >= sseq for this blk.
4586 // This only should be subjects we know have the last blk in this block.
4587 if mb.cacheNotLoaded() {
4588 if err = mb.loadMsgsWithLock(); err != nil {
4589 mb.mu.Unlock()
4590 return 0, 0, err
4591 }
4592 shouldExpire = true
4593 }
4594 var smv StoreMsg
4595 for seq, lseq := atomic.LoadUint64(&mb.first.seq), atomic.LoadUint64(&mb.last.seq); seq <= lseq; seq++ {
4596 if mb.dmap.Exists(seq) {
4597 // Optimisation to avoid calling cacheLookup which hits time.Now().
4598 updateLLTS = true
4599 continue
4600 }
4601 sm, _ := mb.cacheLookupNoCopy(seq, &smv)
4602 if sm == nil || sm.subj == _EMPTY_ || !lbm[sm.subj] {
4603 continue
4604 }
4605 updateLLTS = false // cacheLookup already updated it.
4606 if isMatch(sm.subj) {
4607 // If less than sseq adjust off of total as long as this subject matched the last block.
4608 if seq < sseq {
4609 if !seen[sm.subj] {
4610 total--
4611 seen[sm.subj] = true
4612 }
4613 } else if seen[sm.subj] {
4614 // This is equal or more than sseq, so add back in.
4615 total++
4616 // Make sure to not process anymore.
4617 delete(seen, sm.subj)
4618 }
4619 }
4620 }
4621 }
4622 // If we loaded the block try to force expire.
4623 if shouldExpire {
4624 mb.tryForceExpireCacheLocked()
4625 } else {
4626 mb.finishedWithCache()
4627 }
4628 if updateLLTS {
4629 mb.llts = ats.AccessTime()
4630 }
4631 mb.mu.Unlock()
4632 return total, validThrough, nil
4633 }
4634
4635 // If we would need to scan more from the beginning, revert back to calculating directly here.
4636 if seqStart >= (len(fs.blks) / 2) {
4637 for i := seqStart; i < len(fs.blks); i++ {
4638 var shouldExpire bool
4639 mb := fs.blks[i]
4640 // Hold write lock in case we need to load cache.
4641 mb.mu.Lock()
4642 if isAll && sseq <= atomic.LoadUint64(&mb.first.seq) {
4643 total += mb.msgs
4644 mb.mu.Unlock()
4645 continue
4646 }
4647 // If we are here we need to at least scan the subject fss.
4648 // Make sure we have fss loaded.
4649 if mb.fssNotLoaded() {
4650 if err = mb.loadMsgsWithLock(); err != nil {
4651 mb.mu.Unlock()
4652 return 0, 0, err
4653 }
4654 shouldExpire = true
4655 }
4656 // Mark fss activity.
4657 mb.lsts = ats.AccessTime()
4658
4659 var t uint64
4660 var ierr error
4661 var havePartial bool
4662 var updateLLTS bool
4663 stree.IntersectGSL[SimpleState](mb.fss, sl, func(bsubj []byte, ss *SimpleState) bool {
4664 subj := bytesToString(bsubj)
4665 if ss.firstNeedsUpdate || ss.lastNeedsUpdate {
4666 if ierr = mb.recalculateForSubj(subj, ss); ierr != nil {
4667 return false
4668 }
4669 }
4670 if sseq <= ss.First {
4671 t += ss.Msgs
4672 } else if sseq <= ss.Last {
4673 // We matched but its a partial.
4674 havePartial = true
4675 return false
4676 }
4677 return true
4678 })
4679 if ierr != nil {
4680 mb.mu.Unlock()
4681 return 0, 0, ierr
4682 }
4683
4684 // See if we need to scan msgs here.
4685 if havePartial {
4686 // Make sure we have the cache loaded.
4687 if mb.cacheNotLoaded() {
4688 if err = mb.loadMsgsWithLock(); err != nil {
4689 mb.mu.Unlock()
4690 return 0, 0, err
4691 }
4692 shouldExpire = true
4693 }
4694 // Clear on partial.
4695 t = 0
4696 start := sseq
4697 if fseq := atomic.LoadUint64(&mb.first.seq); fseq > start {
4698 start = fseq
4699 }
4700 var smv StoreMsg
4701 for seq, lseq := start, atomic.LoadUint64(&mb.last.seq); seq <= lseq; seq++ {
4702 if mb.dmap.Exists(seq) {
4703 // Optimisation to avoid calling cacheLookup which hits time.Now().
4704 updateLLTS = true
4705 continue
4706 }
4707 if sm, _ := mb.cacheLookupNoCopy(seq, &smv); sm != nil && isMatch(sm.subj) {
4708 t++
4709 updateLLTS = false // cacheLookup already updated it.
4710 }
4711 }
4712 }
4713 // If we loaded this block for this operation go ahead and expire it here.
4714 if shouldExpire {
4715 mb.tryForceExpireCacheLocked()
4716 } else {
4717 mb.finishedWithCache()
4718 }
4719 if updateLLTS {
4720 mb.llts = ats.AccessTime()
4721 }
4722 mb.mu.Unlock()
4723 total += t
4724 }
4725 return total, validThrough, nil
4726 }
4727
4728 // If we are here it's better to calculate totals from psim and adjust downward by scanning less blocks.
4729 start := uint32(math.MaxUint32)
4730 stree.IntersectGSL(fs.psim, sl, func(subj []byte, psi *psi) bool {
4731 total += psi.total
4732 // Keep track of start index for this subject.
4733 if psi.fblk < start {
4734 start = psi.fblk
4735 }
4736 return true
4737 })
4738
4739 // See if we were asked for all, if so we are done.
4740 if sseq <= fs.state.FirstSeq {
4741 return total, validThrough, nil
4742 }
4743
4744 // If we are here we need to calculate partials for the first blocks.
4745 firstSubjBlk := fs.bim[start]
4746 var firstSubjBlkFound bool
4747 // Adjust in case not found.
4748 if firstSubjBlk == nil {
4749 firstSubjBlkFound = true
4750 }
4751
4752 // Track how many we need to adjust against the total.
4753 var adjust uint64
4754 for i := 0; i <= seqStart; i++ {
4755 mb := fs.blks[i]
4756 // We can skip blks if we know they are below the first one that has any subject matches.
4757 if !firstSubjBlkFound {
4758 if firstSubjBlkFound = (mb == firstSubjBlk); !firstSubjBlkFound {
4759 continue
4760 }
4761 }
4762 // We need to scan this block.
4763 var shouldExpire bool
4764 var updateLLTS bool
4765 mb.mu.Lock()
4766 // Check if we should include all of this block in adjusting. If so work with metadata.
4767 if sseq > atomic.LoadUint64(&mb.last.seq) {
4768 if isAll {
4769 adjust += mb.msgs
4770 } else {
4771 // We need to adjust for all matches in this block.
4772 // Make sure we have fss loaded. This loads whole block now.
4773 if mb.fssNotLoaded() {
4774 if err = mb.loadMsgsWithLock(); err != nil {
4775 mb.mu.Unlock()
4776 return 0, 0, err
4777 }
4778 shouldExpire = true
4779 }
4780 // Mark fss activity.
4781 mb.lsts = ats.AccessTime()
4782 stree.IntersectGSL(mb.fss, sl, func(bsubj []byte, ss *SimpleState) bool {
4783 adjust += ss.Msgs
4784 return true
4785 })
4786 }
4787 } else {
4788 // This is the last block. We need to scan per message here.
4789 if mb.cacheNotLoaded() {
4790 if err = mb.loadMsgsWithLock(); err != nil {
4791 mb.mu.Unlock()
4792 return 0, 0, err
4793 }
4794 shouldExpire = true
4795 }
4796 var last = atomic.LoadUint64(&mb.last.seq)
4797 if sseq < last {
4798 last = sseq
4799 }
4800 // We need to walk all messages in this block
4801 var smv StoreMsg
4802 for seq := atomic.LoadUint64(&mb.first.seq); seq < last; seq++ {
4803 if mb.dmap.Exists(seq) {
4804 // Optimisation to avoid calling cacheLookup which hits time.Now().
4805 updateLLTS = true
4806 continue
4807 }
4808 sm, _ := mb.cacheLookupNoCopy(seq, &smv)
4809 if sm == nil || sm.subj == _EMPTY_ {
4810 continue
4811 }
4812 updateLLTS = false // cacheLookup already updated it.
4813 // Check if it matches our filter.
4814 if sm.seq < sseq && isMatch(sm.subj) {
4815 adjust++
4816 }
4817 }
4818 }
4819 // If we loaded the block try to force expire.
4820 if shouldExpire {
4821 mb.tryForceExpireCacheLocked()
4822 } else {
4823 mb.finishedWithCache()
4824 }
4825 if updateLLTS {
4826 mb.llts = ats.AccessTime()
4827 }
4828 mb.mu.Unlock()
4829 }
4830 // Make final adjustment.
4831 if adjust > total {
4832 total = 0
4833 } else {
4834 total -= adjust
4835 }
4836
4837 return total, validThrough, nil
4838 }
4839
4840 // SubjectsTotals return message totals per subject.
4841 func (fs *fileStore) SubjectsTotals(filter string) map[string]uint64 {
4842 fs.mu.RLock()
4843 defer fs.mu.RUnlock()
4844 return fs.subjectsTotalsLocked(filter)
4845 }
4846
4847 // Lock should be held.
4848 func (fs *fileStore) subjectsTotalsLocked(filter string) map[string]uint64 {
4849 if fs.psim.Size() == 0 {
4850 return nil
4851 }
4852 // Match all if no filter given.
4853 if filter == _EMPTY_ {
4854 filter = fwcs
4855 }
4856 fst := make(map[string]uint64)
4857 fs.psim.Match(stringToBytes(filter), func(subj []byte, psi *psi) {
4858 fst[string(subj)] = psi.total
4859 })
4860 return fst
4861 }
4862
4863 // RegisterStorageUpdates registers a callback for updates to storage changes.
4864 // It will present number of messages and bytes as a signed integer and an
4865 // optional sequence number of the message if a single.
4866 func (fs *fileStore) RegisterStorageUpdates(cb StorageUpdateHandler) {
4867 fs.mu.Lock()
4868 fs.scb = cb
4869 bsz := fs.state.Bytes
4870 fs.mu.Unlock()
4871 if cb != nil && bsz > 0 {
4872 cb(0, int64(bsz), 0, _EMPTY_)
4873 }
4874 }
4875
4876 // RegisterStorageRemoveMsg registers a callback to remove messages.
4877 // Replicated streams should propose removals, R1 can remove inline.
4878 func (fs *fileStore) RegisterStorageRemoveMsg(cb StorageRemoveMsgHandler) {
4879 fs.mu.Lock()
4880 fs.rmcb = cb
4881 fs.mu.Unlock()
4882 }
4883
4884 // RegisterProcessJetStreamMsg registers a callback to process new JetStream messages.
4885 func (fs *fileStore) RegisterProcessJetStreamMsg(cb ProcessJetStreamMsgHandler) {
4886 fs.mu.Lock()
4887 fs.pmsgcb = cb
4888 fs.mu.Unlock()
4889 }
4890
4891 // Helper to get hash key for specific message block.
4892 // Lock should be held
4893 func (fs *fileStore) hashKeyForBlock(index uint32) []byte {
4894 return []byte(fmt.Sprintf("%s-%d", fs.cfg.Name, index))
4895 }
4896
4897 func (mb *msgBlock) setupWriteCache(buf []byte) error {
4898 // Not safe to use mb.cacheAlreadyLoaded() here as the heuristic
4899 // is wrong for writing to the beginning of an empty block cache.
4900 if mb.cache != nil {
4901 return nil
4902 }
4903 if mb.cache = mb.ecache.Value(); mb.cache != nil {
4904 return nil
4905 }
4906
4907 // If there's an existing block on disk then we'll load it in.
4908 var fi os.FileInfo
4909 if mb.mfd != nil {
4910 fi, _ = mb.mfd.Stat()
4911 } else if mb.mfn != _EMPTY_ {
4912 fi, _ = os.Stat(mb.mfn)
4913 }
4914 if fi != nil {
4915 return mb.loadMsgsWithLock()
4916 }
4917
4918 // Looks like there isn't an existing file on disk, mint a new cache.
4919 mb.cache = &cache{buf: buf}
4920 mb.cache.registerRecycle()
4921 mb.ecache.Set(mb.cache)
4922 mb.llts = ats.AccessTime()
4923 mb.startCacheExpireTimer()
4924 return nil
4925 }
4926
4927 // finishedWithCache removes the strong reference to the cache, instead
4928 // returning it to the elastic pointer. Note that the elastic pointer can
4929 // be either weak or strong, they are strengthened when there are pending
4930 // writes and weak otherwise.
4931 // Lock must be held.
4932 func (mb *msgBlock) finishedWithCache() {
4933 if mb.cache != nil && mb.pendingWriteSizeLocked() == 0 {
4934 mb.cache = nil
4935 }
4936 }
4937
4938 // This rolls to a new append msg block.
4939 // Lock should be held.
4940 func (fs *fileStore) newMsgBlockForWrite() (*msgBlock, error) {
4941 index := uint32(1)
4942 var rbuf []byte
4943
4944 if lmb := fs.lmb; lmb != nil {
4945 lmb.mu.Lock()
4946 index = lmb.index + 1
4947
4948 // Quit our loops.
4949 if lmb.qch != nil {
4950 close(lmb.qch)
4951 lmb.qch = nil
4952 }
4953 // If we had a write error before, don't allow continuing into a new block.
4954 if err := lmb.werr; err != nil {
4955 lmb.mu.Unlock()
4956 return nil, err
4957 }
4958 // Flush any pending messages.
4959 if _, err := lmb.flushPendingMsgsLocked(); err != nil {
4960 lmb.mu.Unlock()
4961 return nil, err
4962 }
4963 // Determine if we can reclaim any resources here.
4964 lmb.closeFDsLockedNoCheck()
4965 if lmb.cache != nil {
4966 // Reset write timestamp and see if we can expire this cache.
4967 rbuf = lmb.tryExpireWriteCache()
4968 }
4969 lmb.mu.Unlock()
4970
4971 if fs.fcfg.Compression != NoCompression {
4972 // We've now reached the end of this message block, if we want
4973 // to compress blocks then now's the time to do it.
4974 go func() {
4975 lmb.mu.Lock()
4976 defer lmb.mu.Unlock()
4977 // Might error, but we can't handle it here anyway.
4978 _ = lmb.recompressOnDiskIfNeeded()
4979 }()
4980 }
4981 }
4982
4983 mb := fs.initMsgBlock(index)
4984 // Lock should be held to quiet race detector.
4985 mb.mu.Lock()
4986 if err := mb.setupWriteCache(rbuf); err != nil {
4987 mb.mu.Unlock()
4988 return nil, err
4989 }
4990 mb.fss = stree.NewSubjectTree[SimpleState]()
4991
4992 // Set cache time to creation time to start.
4993 mb.llts, mb.lwts = 0, ats.AccessTime()
4994 // Remember our last sequence number.
4995 atomic.StoreUint64(&mb.first.seq, fs.state.LastSeq+1)
4996 atomic.StoreUint64(&mb.last.seq, fs.state.LastSeq)
4997 mb.mu.Unlock()
4998
4999 // Now do local hash.
5000 key := sha256.Sum256(fs.hashKeyForBlock(index))
5001 hh, err := highwayhash.NewDigest64(key[:])
5002 if err != nil {
5003 return nil, fmt.Errorf("could not create hash: %v", err)
5004 }
5005 mb.hh = hh
5006
5007 fs.dios.acquire()
5008 mfd, err := os.OpenFile(mb.mfn, os.O_CREATE|os.O_RDWR, defaultFilePerms)
5009 fs.dios.release()
5010
5011 if err != nil {
5012 if isPermissionError(err) {
5013 return nil, err
5014 }
5015 _ = mb.dirtyCloseWithRemove(true)
5016 return nil, fmt.Errorf("Error creating msg block file: %v", err)
5017 }
5018 mb.mfd = mfd
5019
5020 // Check if encryption is enabled.
5021 if fs.prf != nil {
5022 if err := fs.genEncryptionKeysForBlock(mb); err != nil {
5023 return nil, err
5024 }
5025 }
5026
5027 // If we know we will need this so go ahead and spin up.
5028 if !fs.fip {
5029 mb.spinUpFlushLoop()
5030 }
5031
5032 // Add to our list of blocks and mark as last.
5033 fs.addMsgBlock(mb)
5034
5035 return mb, nil
5036 }
5037
5038 // Generate the keys for this message block and write them out.
5039 func (fs *fileStore) genEncryptionKeysForBlock(mb *msgBlock) error {
5040 if mb == nil {
5041 return nil
5042 }
5043 key, bek, seed, encrypted, err := fs.genEncryptionKeys(fmt.Sprintf("%s:%d", fs.cfg.Name, mb.index))
5044 if err != nil {
5045 return err
5046 }
5047 mb.aek, mb.bek, mb.seed, mb.nonce = key, bek, seed, encrypted[:key.NonceSize()]
5048 mdir := filepath.Join(fs.fcfg.StoreDir, msgDir)
5049 keyFile := filepath.Join(mdir, fmt.Sprintf(keyScan, mb.index))
5050 if _, err := os.Stat(keyFile); err != nil && !os.IsNotExist(err) {
5051 return err
5052 }
5053 sync := fs.syncAlways.Load()
5054 err = writeAtomically(fs.dios, keyFile, encrypted, defaultFilePerms, sync)
5055 if err != nil {
5056 return err
5057 }
5058 mb.kfn = keyFile
5059 // If we did not sync the key file above, mark it to be synced on the next syncBlocks pass.
5060 mb.needKeySync = !sync
5061 return nil
5062 }
5063
5064 // Stores a raw message with expected sequence number and timestamp.
5065 // Lock should be held.
5066 func (fs *fileStore) storeRawMsg(subj string, hdr, msg []byte, seq uint64, ts, ttl int64, discardNewCheck bool) (err error) {
5067 if fs.isClosed() {
5068 return ErrStoreClosed
5069 }
5070
5071 // Per subject max check needed.
5072 mmp := uint64(fs.cfg.MaxMsgsPer)
5073 var psmc uint64
5074 psmax := mmp > 0 && len(subj) > 0
5075 var info *psi
5076 if psmax {
5077 if info, _ = fs.psim.Find(stringToBytes(subj)); info != nil {
5078 // Take current total, but add 1 for the message we are about to store.
5079 psmc = info.total + 1
5080 }
5081 }
5082
5083 var fseq uint64
5084 // Check if we are discarding new messages when we reach the limit.
5085 // If we are clustered, we do the enforcement above and should not disqualify
5086 // the message here since it could cause replicas to drift.
5087 if discardNewCheck && fs.cfg.Discard == DiscardNew {
5088 var asl bool
5089 if psmax && psmc > mmp {
5090 // If we are instructed to discard new per subject, this is an error.
5091 // However, allow rollup messages through since they will purge old
5092 // messages for the subject after storing, restoring the limit.
5093 if fs.cfg.DiscardNewPer && len(sliceHeader(JSMsgRollup, hdr)) == 0 {
5094 return ErrMaxMsgsPerSubject
5095 }
5096 if fseq, err = fs.firstSeqForSubj(subj); err != nil {
5097 return err
5098 }
5099 // fs.firstSeqForSubj releases and re-acquires the lock, need to fetch the state again.
5100 if info, _ = fs.psim.Find(stringToBytes(subj)); info != nil {
5101 // Take current total, but add 1 for the message we are about to store.
5102 psmc = info.total + 1
5103 }
5104 asl = psmc > mmp
5105 }
5106 if fs.cfg.MaxMsgs > 0 && fs.state.Msgs >= uint64(fs.cfg.MaxMsgs) && !asl {
5107 return ErrMaxMsgs
5108 }
5109 if fs.cfg.MaxBytes > 0 && fs.state.Bytes+fileStoreMsgSize(subj, hdr, msg) > uint64(fs.cfg.MaxBytes) {
5110 if !asl || fs.sizeForSeq(fseq) < int(fileStoreMsgSize(subj, hdr, msg)) {
5111 return ErrMaxBytes
5112 }
5113 }
5114 }
5115
5116 // Check sequence.
5117 if seq != fs.state.LastSeq+1 {
5118 if seq > 0 {
5119 return ErrSequenceMismatch
5120 }
5121 seq = fs.state.LastSeq + 1
5122 }
5123
5124 // Return previous write errors immediately.
5125 if fs.werr != nil {
5126 return fs.werr
5127 }
5128 // Persist any returned errors to be used in the future.
5129 defer func() {
5130 if err != nil {
5131 fs.setWriteErr(err)
5132 }
5133 }()
5134
5135 // Write msg record.
5136 // Add expiry bit to sequence if needed. This is so that if we need to
5137 // rebuild, we know which messages to look at more quickly.
5138 n, err := fs.writeMsgRecord(seq, ts, subj, hdr, msg)
5139 if err != nil {
5140 return err
5141 }
5142
5143 // Adjust top level tracking of per subject msg counts.
5144 if len(subj) > 0 && fs.psim != nil {
5145 index := fs.lmb.index
5146 if info == nil {
5147 info, _ = fs.psim.Find(stringToBytes(subj))
5148 }
5149 if info != nil {
5150 info.total++
5151 if index > info.lblk {
5152 info.lblk = index
5153 }
5154 } else {
5155 info, _ = fs.psim.Insert(stringToBytes(subj), psi{total: 1, fblk: index, lblk: index})
5156 fs.tsl += len(subj)
5157 }
5158 }
5159
5160 // Adjust first if needed.
5161 now := time.Unix(0, ts).UTC()
5162 if fs.state.Msgs == 0 {
5163 fs.state.FirstSeq = seq
5164 fs.state.FirstTime = now
5165 }
5166
5167 fs.state.Msgs++
5168 fs.state.Bytes += n
5169 fs.state.LastSeq = seq
5170 fs.state.LastTime = now
5171
5172 // Enforce per message limits.
5173 for psmax && psmc > mmp {
5174 // We may have done this above.
5175 if fseq == 0 {
5176 fseq, err = fs.firstSeqForSubj(subj)
5177 if err != nil {
5178 return err
5179 } else if fseq == 0 {
5180 break
5181 }
5182 // fs.firstSeqForSubj releases and re-acquires the lock, need to fetch the state again.
5183 if info, _ = fs.psim.Find(stringToBytes(subj)); info != nil {
5184 psmc = info.total
5185 } else {
5186 break
5187 }
5188 // Re-check if we're at the limit.
5189 continue
5190 }
5191 if _, err = fs.removeMsgViaLimits(fseq); err != nil && err != ErrStoreMsgNotFound {
5192 return err
5193 }
5194 fseq = 0
5195 // fs.removeMsgViaLimits releases and re-acquires the lock, need to fetch the state again.
5196 if info, _ = fs.psim.Find(stringToBytes(subj)); info != nil {
5197 psmc = info.total
5198 } else {
5199 break
5200 }
5201 }
5202 // If we only ever store one/last message for a subject, can correct the first block to where we've just written.
5203 if info != nil && info.total == 1 && mmp == 1 {
5204 info.fblk = info.lblk
5205 }
5206
5207 // Limits checks and enforcement.
5208 // If they do any deletions they will update the
5209 // byte count on their own, so no need to compensate.
5210 if err = fs.enforceMsgLimit(); err != nil {
5211 return err
5212 }
5213 if err = fs.enforceBytesLimit(); err != nil {
5214 return err
5215 }
5216
5217 // Per-message TTL.
5218 if ttl > 0 {
5219 if fs.ttls != nil {
5220 expires := time.Duration(ts) + (time.Second * time.Duration(ttl))
5221 fs.ttls.Add(seq, int64(expires))
5222 }
5223 // Need to count these regardless as we might want to enable TTLs
5224 // later via UpdateConfig.
5225 fs.lmb.mu.Lock()
5226 fs.lmb.ttls++
5227 fs.lmb.mu.Unlock()
5228 }
5229
5230 // Check if we have and need the age expiration timer running.
5231 switch {
5232 case fs.ttls != nil && ttl > 0:
5233 fs.resetAgeChk(0)
5234 case fs.ageChk == nil && (fs.cfg.MaxAge > 0 || fs.ttls != nil):
5235 fs.startAgeChk()
5236 }
5237
5238 // Message scheduling.
5239 if fs.scheduling != nil {
5240 if schedule, apiErr := nextMessageSchedule(hdr, ts); apiErr == nil && !schedule.IsZero() {
5241 fs.scheduling.add(seq, subj, schedule.UnixNano())
5242 fs.lmb.mu.Lock()
5243 fs.lmb.schedules++
5244 fs.lmb.mu.Unlock()
5245 } else if getMessageScheduler(hdr) == _EMPTY_ {
5246 fs.scheduling.removeSubject(subj)
5247 }
5248
5249 // Check for a repeating schedule and update such that it triggers again.
5250 if scheduleNext := bytesToString(sliceHeader(JSScheduleNext, hdr)); scheduleNext != _EMPTY_ && scheduleNext != JSScheduleNextPurge {
5251 scheduler := getMessageScheduler(hdr)
5252 if next, err := time.Parse(time.RFC3339Nano, scheduleNext); err == nil && scheduler != _EMPTY_ {
5253 fs.scheduling.update(scheduler, next.UnixNano())
5254 }
5255 }
5256 }
5257
5258 return nil
5259 }
5260
5261 // isReadErr reports whether err originated from reading or interpreting
5262 // existing on-disk data rather than from a failed write. These surface through
5263 // cache/load paths and should not permanently disable writes.
5264 func isReadErr(err error) bool {
5265 var badMsg errBadMsg
5266 return errors.Is(err, errNoCache) ||
5267 errors.Is(err, errDeletedMsg) ||
5268 errors.Is(err, errPartialCache) ||
5269 errors.Is(err, errCorruptState) ||
5270 errors.Is(err, errPriorState) ||
5271 errors.Is(err, io.ErrUnexpectedEOF) ||
5272 errors.Is(err, errMsgBlkTooBig) ||
5273 errors.As(err, &badMsg)
5274 }
5275
5276 // Lock should be held.
5277 func (fs *fileStore) setWriteErr(err error) {
5278 if fs.werr != nil {
5279 return
5280 }
5281 // Ignore non-write errors.
5282 if err == ErrStoreClosed {
5283 return
5284 }
5285 // If this is a not found report but do not disable.
5286 if os.IsNotExist(err) {
5287 fs.warn("Resource not found: %v", err)
5288 return
5289 }
5290 // Read/decode errors surfaced from existing on-disk data are not write failures.
5291 // Log and continue instead of disabling writes.
5292 if isReadErr(err) {
5293 fs.rateLimitWarn("Ignoring non-write error: %v", err)
5294 assert.Unreachable("Filestore encountered read error", map[string]any{
5295 "name": fs.cfg.Name,
5296 "err": err,
5297 "stack": string(debug.Stack()),
5298 })
5299 return
5300 }
5301 fs.error("Critical write error: %v", err)
5302 fs.werr = err
5303 assert.Unreachable("Filestore encountered write error", map[string]any{
5304 "name": fs.cfg.Name,
5305 "err": err,
5306 "stack": string(debug.Stack()),
5307 })
5308 }
5309
5310 // StoreRawMsg stores a raw message with expected sequence number and timestamp.
5311 func (fs *fileStore) StoreRawMsg(subj string, hdr, msg []byte, seq uint64, ts, ttl int64, discardNewCheck bool) error {
5312 fs.mu.Lock()
5313 // Always return previous write errors.
5314 if err := fs.werr; err != nil {
5315 fs.mu.Unlock()
5316 return err
5317 }
5318 err := fs.storeRawMsg(subj, hdr, msg, seq, ts, ttl, discardNewCheck)
5319 cb := fs.scb
5320 // Check if first message timestamp requires expiry
5321 // sooner than initial replica expiry timer set to MaxAge when initializing.
5322 if !fs.receivedAny && fs.cfg.MaxAge != 0 && ts > 0 {
5323 fs.receivedAny = true
5324 fs.resetAgeChk(0)
5325 }
5326 fs.mu.Unlock()
5327
5328 if err == nil && cb != nil {
5329 cb(1, int64(fileStoreMsgSize(subj, hdr, msg)), seq, subj)
5330 }
5331
5332 return err
5333 }
5334
5335 // Store stores a message. We hold the main filestore lock for any write operation.
5336 func (fs *fileStore) StoreMsg(subj string, hdr, msg []byte, ttl int64) (uint64, int64, error) {
5337 fs.mu.Lock()
5338 // Always return previous write errors.
5339 if err := fs.werr; err != nil {
5340 fs.mu.Unlock()
5341 return 0, 0, err
5342 }
5343 seq, ts := fs.state.LastSeq+1, time.Now().UnixNano()
5344 // This is called for a R1 with no expected sequence number, so perform DiscardNew checks on the store-level.
5345 err := fs.storeRawMsg(subj, hdr, msg, seq, ts, ttl, true)
5346 cb := fs.scb
5347 fs.mu.Unlock()
5348
5349 if err != nil {
5350 seq, ts = 0, 0
5351 } else if cb != nil {
5352 cb(1, int64(fileStoreMsgSize(subj, hdr, msg)), seq, subj)
5353 }
5354
5355 return seq, ts, err
5356 }
5357
5358 // skipMsg will update this message block for a skipped message.
5359 // If we do not have any messages, just update the metadata, otherwise
5360 // we will place an empty record marking the sequence as used. The
5361 // sequence will be marked erased.
5362 // fs lock should be held.
5363 func (mb *msgBlock) skipMsg(seq uint64, ts int64) error {
5364 if mb == nil {
5365 return nil
5366 }
5367 var needsRecord bool
5368
5369 mb.mu.Lock()
5370 if err := mb.werr; err != nil {
5371 mb.mu.Unlock()
5372 return err
5373 }
5374 // If we are empty can just do meta.
5375 if mb.msgs == 0 {
5376 atomic.StoreUint64(&mb.last.seq, seq)
5377 mb.last.ts = ts
5378 atomic.StoreUint64(&mb.first.seq, seq+1)
5379 mb.first.ts = 0
5380 needsRecord = mb == mb.fs.lmb
5381 } else {
5382 needsRecord = true
5383 mb.dmap.Insert(seq)
5384 }
5385 if needsRecord {
5386 if err := mb.writeMsgRecordLocked(emptyRecordLen, seq|ebit, _EMPTY_, nil, nil, ts, true, true); err != nil {
5387 mb.mu.Unlock()
5388 return err
5389 }
5390 }
5391 mb.mu.Unlock()
5392 if !needsRecord {
5393 mb.kickFlusher()
5394 }
5395 return nil
5396 }
5397
5398 // SkipMsg will use the next sequence number but not store anything.
5399 func (fs *fileStore) SkipMsg(seq uint64) (uint64, error) {
5400 return fs.skipMsg(seq, false)
5401 }
5402
5403 // SkipMsgNoInterest will use the next sequence number but not store anything.
5404 // Unlike SkipMsg it also advances LastTime, which is used for Interest retention.
5405 func (fs *fileStore) SkipMsgNoInterest(seq uint64) (uint64, error) {
5406 return fs.skipMsg(seq, true)
5407 }
5408
5409 func (fs *fileStore) skipMsg(seq uint64, noInterest bool) (uint64, error) {
5410 fs.mu.Lock()
5411 defer fs.mu.Unlock()
5412
5413 // Always return previous write errors.
5414 if err := fs.werr; err != nil {
5415 return 0, err
5416 }
5417
5418 // Check sequence matches our last sequence.
5419 if seq != fs.state.LastSeq+1 {
5420 if seq > 0 {
5421 return 0, ErrSequenceMismatch
5422 }
5423 seq = fs.state.LastSeq + 1
5424 }
5425
5426 // Grab our current last message block.
5427 mb, err := fs.checkLastBlock(emptyRecordLen)
5428 if err != nil {
5429 return 0, err
5430 }
5431
5432 // Only update time if not already set or for Interest retention.
5433 var ts int64
5434 updateTime := noInterest || fs.state.LastTime.IsZero()
5435 if updateTime {
5436 ts = ats.AccessTime()
5437 } else {
5438 ts = fs.state.LastTime.UnixNano()
5439 }
5440
5441 // Write skip msg.
5442 if err = mb.skipMsg(seq, ts); err != nil {
5443 fs.setWriteErr(err)
5444 return 0, err
5445 }
5446
5447 // Update fs state.
5448 fs.state.LastSeq = seq
5449 if updateTime {
5450 fs.state.LastTime = time.Unix(0, ts).UTC()
5451 }
5452 if fs.state.Msgs == 0 {
5453 fs.state.FirstSeq, fs.state.FirstTime = seq, time.Time{}
5454 }
5455 if seq == fs.state.FirstSeq {
5456 fs.state.FirstSeq, fs.state.FirstTime = seq+1, time.Time{}
5457 }
5458 // Mark as dirty for stream state.
5459 fs.dirty++
5460
5461 return seq, nil
5462 }
5463
5464 // SkipMsgs skips multiple msgs. We will determine if we can fit into current lmb or we need to create a new block.
5465 func (fs *fileStore) SkipMsgs(seq uint64, num uint64) error {
5466 fs.mu.Lock()
5467 defer fs.mu.Unlock()
5468
5469 // Always return previous write errors.
5470 if err := fs.werr; err != nil {
5471 return err
5472 }
5473
5474 // Check sequence matches our last sequence.
5475 if seq != fs.state.LastSeq+1 {
5476 if seq > 0 {
5477 return ErrSequenceMismatch
5478 }
5479 seq = fs.state.LastSeq + 1
5480 }
5481
5482 // Limit number of dmap entries
5483 const maxDeletes = 64 * 1024
5484 mb := fs.lmb
5485
5486 var msgs uint64
5487 numDeletes := int(num)
5488 if mb != nil {
5489 mb.mu.RLock()
5490 numDeletes += mb.dmap.Size()
5491 msgs = mb.msgs
5492 mb.mu.RUnlock()
5493 }
5494 if mb == nil || numDeletes > maxDeletes && msgs > 0 || msgs > 0 && mb.blkSize()+emptyRecordLen > fs.fcfg.BlockSize {
5495 var err error
5496 if mb, err = fs.newMsgBlockForWrite(); err != nil {
5497 return err
5498 }
5499 }
5500
5501 // Insert into dmap all entries and place last as marker.
5502 var ts int64
5503 if !fs.state.LastTime.IsZero() {
5504 ts = fs.state.LastTime.UnixNano()
5505 } else {
5506 ts = ats.AccessTime()
5507 }
5508 lseq := seq + num - 1
5509
5510 mb.mu.Lock()
5511 if err := mb.werr; err != nil {
5512 mb.mu.Unlock()
5513 return err
5514 }
5515 // If we are empty update meta directly.
5516 if mb.msgs == 0 {
5517 atomic.StoreUint64(&mb.last.seq, lseq)
5518 mb.last.ts = ts
5519 atomic.StoreUint64(&mb.first.seq, lseq+1)
5520 mb.first.ts = 0
5521 } else {
5522 for ; seq <= lseq; seq++ {
5523 mb.dmap.Insert(seq)
5524 }
5525 }
5526 // Write out our placeholder.
5527 err := mb.writeMsgRecordLocked(emptyRecordLen, lseq|ebit, _EMPTY_, nil, nil, ts, true, true)
5528 mb.mu.Unlock()
5529 if err != nil {
5530 fs.setWriteErr(err)
5531 return err
5532 }
5533
5534 // Now update FS accounting.
5535 // Update fs state.
5536 fs.state.LastSeq = lseq
5537 if fs.state.LastTime.IsZero() {
5538 fs.state.LastTime = time.Unix(0, ts).UTC()
5539 }
5540 if fs.state.Msgs == 0 {
5541 fs.state.FirstSeq, fs.state.FirstTime = lseq+1, time.Time{}
5542 }
5543
5544 // Mark as dirty for stream state.
5545 fs.dirty++
5546
5547 return nil
5548 }
5549
5550 // FlushAllPending flushes all data that was still pending to be written.
5551 func (fs *fileStore) FlushAllPending() error {
5552 fs.mu.Lock()
5553 defer fs.mu.Unlock()
5554 // Return previous write errors immediately.
5555 if fs.werr != nil {
5556 return fs.werr
5557 }
5558 return fs.checkAndFlushLastBlock()
5559 }
5560
5561 // Lock should be held.
5562 func (fs *fileStore) rebuildFirst() error {
5563 if len(fs.blks) == 0 {
5564 return nil
5565 }
5566 fmb := fs.blks[0]
5567 if fmb == nil {
5568 return nil
5569 }
5570
5571 ld, _, _ := fmb.rebuildState()
5572 fmb.mu.RLock()
5573 isEmpty := fmb.msgs == 0
5574 fmb.mu.RUnlock()
5575 if isEmpty {
5576 fmb.mu.Lock()
5577 err := fs.forceRemoveMsgBlock(fmb)
5578 fmb.mu.Unlock()
5579 if err != nil {
5580 return err
5581 }
5582 }
5583 if err := fs.selectNextFirst(); err != nil {
5584 return err
5585 }
5586 fs.rebuildStateLocked(ld)
5587 return nil
5588 }
5589
5590 // Optimized helper function to return first sequence.
5591 // subj will always be publish subject here, meaning non-wildcard.
5592 // We assume a fast check that this subj even exists already happened.
5593 // Write lock should be held.
5594 func (fs *fileStore) firstSeqForSubj(subj string) (uint64, error) {
5595 if len(fs.blks) == 0 {
5596 return 0, nil
5597 }
5598
5599 // See if we can optimize where we start.
5600 start, stop := fs.blks[0].index, fs.lmb.index
5601 if info, ok := fs.psim.Find(stringToBytes(subj)); ok {
5602 start, stop = info.fblk, info.lblk
5603 }
5604
5605 for i := start; i <= stop; i++ {
5606 mb := fs.bim[i]
5607 if mb == nil {
5608 continue
5609 }
5610 // If we need to load msgs here and we need to walk multiple blocks this
5611 // could tie up the upper fs lock, so release while dealing with the block.
5612 fs.mu.Unlock()
5613
5614 mb.mu.Lock()
5615 // If marked closed, the block is already gone.
5616 if mb.closed {
5617 mb.mu.Unlock()
5618 fs.mu.Lock()
5619 continue
5620 }
5621 needsCleanup := mb.cache == nil
5622 var shouldExpire bool
5623 if mb.fssNotLoaded() {
5624 // Make sure we have fss loaded.
5625 if err := mb.loadMsgsWithLock(); err != nil {
5626 if needsCleanup {
5627 mb.finishedWithCache()
5628 }
5629 mb.mu.Unlock()
5630 // Re-acquire fs lock
5631 fs.mu.Lock()
5632 return 0, err
5633 }
5634 shouldExpire = true
5635 }
5636 // Mark fss activity.
5637 mb.lsts = ats.AccessTime()
5638
5639 bsubj := stringToBytes(subj)
5640 if ss, ok := mb.fss.Find(bsubj); ok && ss != nil {
5641 var err error
5642 if ss.firstNeedsUpdate || ss.lastNeedsUpdate {
5643 err = mb.recalculateForSubj(subj, ss)
5644 }
5645 if needsCleanup {
5646 mb.finishedWithCache()
5647 }
5648 mb.mu.Unlock()
5649 // Re-acquire fs lock
5650 fs.mu.Lock()
5651 // Adjust first if it was not where we thought it should be.
5652 if i != start {
5653 if info, ok := fs.psim.Find(bsubj); ok {
5654 info.fblk = i
5655 }
5656 }
5657 if err != nil {
5658 return 0, err
5659 }
5660 return ss.First, nil
5661 }
5662 // If we did not find it and we loaded this msgBlock try to expire as long as not the last.
5663 if shouldExpire {
5664 // Expire this cache before moving on.
5665 mb.tryForceExpireCacheLocked()
5666 } else if needsCleanup {
5667 mb.finishedWithCache()
5668 }
5669 mb.mu.Unlock()
5670 // Re-acquire fs lock
5671 fs.mu.Lock()
5672 }
5673 return 0, nil
5674 }
5675
5676 // Will check the msg limit and drop firstSeq msg if needed.
5677 // Lock should be held.
5678 func (fs *fileStore) enforceMsgLimit() error {
5679 if fs.cfg.Discard != DiscardOld {
5680 return nil
5681 }
5682 if fs.cfg.MaxMsgs <= 0 || fs.state.Msgs <= uint64(fs.cfg.MaxMsgs) {
5683 return nil
5684 }
5685 for nmsgs := fs.state.Msgs; nmsgs > uint64(fs.cfg.MaxMsgs); nmsgs = fs.state.Msgs {
5686 // If the first block can be removed fully, purge it entirely without needing to walk sequences.
5687 if len(fs.blks) > 0 {
5688 fmb := fs.blks[0]
5689 fmb.mu.RLock()
5690 msgs := fmb.msgs
5691 fmb.mu.RUnlock()
5692 if nmsgs-msgs > uint64(fs.cfg.MaxMsgs) {
5693 if err := fs.purgeMsgBlock(fmb); err != nil {
5694 return err
5695 }
5696 continue
5697 }
5698 }
5699 if removed, err := fs.deleteFirstMsg(); err != nil {
5700 return err
5701 } else if !removed {
5702 return fs.rebuildFirst()
5703 }
5704 }
5705 return nil
5706 }
5707
5708 // Will check the bytes limit and drop msgs if needed.
5709 // Lock should be held.
5710 func (fs *fileStore) enforceBytesLimit() error {
5711 if fs.cfg.Discard != DiscardOld {
5712 return nil
5713 }
5714 if fs.cfg.MaxBytes <= 0 || fs.state.Bytes <= uint64(fs.cfg.MaxBytes) {
5715 return nil
5716 }
5717 for bs := fs.state.Bytes; bs > uint64(fs.cfg.MaxBytes); bs = fs.state.Bytes {
5718 // If the first block can be removed fully, purge it entirely without needing to walk sequences.
5719 if len(fs.blks) > 0 {
5720 fmb := fs.blks[0]
5721 fmb.mu.RLock()
5722 bytes := fmb.bytes
5723 fmb.mu.RUnlock()
5724 if bs-bytes > uint64(fs.cfg.MaxBytes) {
5725 if err := fs.purgeMsgBlock(fmb); err != nil {
5726 return err
5727 }
5728 continue
5729 }
5730 }
5731 if removed, err := fs.deleteFirstMsg(); err != nil {
5732 return err
5733 } else if !removed {
5734 return fs.rebuildFirst()
5735 }
5736 }
5737 return nil
5738 }
5739
5740 // Will make sure we have limits honored for max msgs per subject on recovery or config update.
5741 // We will make sure to go through all msg blocks etc. but in practice this
5742 // will most likely only be the last one, so can take a more conservative approach.
5743 // Lock should be held.
5744 func (fs *fileStore) enforceMsgPerSubjectLimit(fireCallback bool) error {
5745 start := time.Now()
5746 defer func() {
5747 if took := time.Since(start); took > time.Minute {
5748 fs.warn("enforceMsgPerSubjectLimit took %v", took.Round(time.Millisecond))
5749 }
5750 }()
5751
5752 maxMsgsPer := uint64(fs.cfg.MaxMsgsPer)
5753
5754 // We may want to suppress callbacks from remove during this process
5755 // since these should have already been deleted and accounted for.
5756 if !fireCallback {
5757 cb := fs.scb
5758 fs.scb = nil
5759 defer func() { fs.scb = cb }()
5760 }
5761
5762 var numMsgs uint64
5763
5764 // collect all that are not correct.
5765 needAttention := stree.NewSubjectTree[uint64]()
5766 fblk, lblk := uint32(math.MaxUint32), uint32(0)
5767 fs.psim.IterFast(func(subj []byte, psi *psi) bool {
5768 numMsgs += psi.total
5769 if psi.total > maxMsgsPer {
5770 needAttention.Insert(subj, psi.total)
5771 if psi.fblk < fblk {
5772 fblk = psi.fblk
5773 }
5774 if psi.lblk > lblk {
5775 lblk = psi.lblk
5776 }
5777 }
5778 return true
5779 })
5780
5781 // We had an issue with a use case where psim (and hence fss) were correct but idx was not and was not properly being caught.
5782 // So do a quick sanity check here. If we detect a skew do a rebuild then re-check.
5783 if numMsgs != fs.state.Msgs {
5784 fs.warn("Detected skew in subject-based total (%d) vs raw total (%d), rebuilding", numMsgs, fs.state.Msgs)
5785 // Clear any global subject state.
5786 fs.psim, fs.tsl = fs.psim.Empty(), 0
5787 for _, mb := range fs.blks {
5788 ld, _, err := mb.rebuildState()
5789 if err != nil {
5790 return err
5791 } else if ld != nil {
5792 fs.addLostData(ld)
5793 }
5794 if err = fs.populateGlobalPerSubjectInfo(mb); err != nil {
5795 return err
5796 }
5797 }
5798 // Rebuild fs state too.
5799 fs.rebuildStateLocked(nil)
5800 // Need to redo blocks that need attention.
5801 needAttention.Empty()
5802 fblk, lblk = uint32(math.MaxUint32), uint32(0)
5803 fs.psim.IterFast(func(subj []byte, psi *psi) bool {
5804 if psi.total > maxMsgsPer {
5805 needAttention.Insert(subj, psi.total)
5806 if psi.fblk < fblk {
5807 fblk = psi.fblk
5808 }
5809 if psi.lblk > lblk {
5810 lblk = psi.lblk
5811 }
5812 }
5813 return true
5814 })
5815 }
5816
5817 // If nothing to do then stop.
5818 if fblk == math.MaxUint32 {
5819 return nil
5820 }
5821
5822 // Collect all the msgBlks we alter.
5823 blks := make(map[*msgBlock]struct{})
5824
5825 // For re-use below.
5826 var sm StoreMsg
5827 var fss *stree.SubjectTree[*SimpleState]
5828 for i := fblk; i <= lblk; i++ {
5829 mb := fs.bim[i]
5830 if mb == nil {
5831 continue
5832 }
5833 mb.mu.Lock()
5834 if err := mb.ensurePerSubjectInfoLoaded(); err != nil {
5835 mb.mu.Unlock()
5836 return err
5837 }
5838 // It isn't safe to intersect mb.fss directly, because removeMsgViaLimits modifies it
5839 // during the iteration, which can cause us to miss keys. We won't copy the entire
5840 // SimpleState structs though but rather just take pointers for speed.
5841 fss = fss.Empty()
5842 mb.fss.IterFast(func(subject []byte, val *SimpleState) bool {
5843 fss.Insert(subject, val)
5844 return true
5845 })
5846 mb.mu.Unlock()
5847 var ierr error
5848 stree.LazyIntersect(needAttention, fss, func(subj []byte, total *uint64, ssptr **SimpleState) {
5849 if ssptr == nil || total == nil || ierr != nil {
5850 return
5851 }
5852 ss := *ssptr
5853 if ss.firstNeedsUpdate || ss.lastNeedsUpdate {
5854 mb.mu.Lock()
5855 ierr = mb.recalculateForSubj(bytesToString(subj), ss)
5856 mb.mu.Unlock()
5857 if ierr != nil {
5858 return
5859 }
5860 }
5861 for first := ss.First; *total > maxMsgsPer && first <= ss.Last; {
5862 m, _, err := mb.firstMatching(bytesToString(subj), false, first, &sm)
5863 if err != nil {
5864 break
5865 }
5866 first = m.seq + 1
5867 if removed, _ := fs.removeMsgViaLimits(m.seq); removed {
5868 blks[mb] = struct{}{}
5869 *total--
5870 }
5871 }
5872 })
5873 if ierr != nil {
5874 return ierr
5875 }
5876 }
5877
5878 // Expire the cache if we can.
5879 for mb := range blks {
5880 mb.mu.Lock()
5881 if mb.msgs > 0 {
5882 mb.tryForceExpireCacheLocked()
5883 }
5884 mb.mu.Unlock()
5885 }
5886 return nil
5887 }
5888
5889 // Lock should be held.
5890 func (fs *fileStore) deleteFirstMsg() (bool, error) {
5891 return fs.removeMsgViaLimits(fs.state.FirstSeq)
5892 }
5893
5894 // If we remove via limits that can always be recovered on a restart we
5895 // do not force the system to update the index file.
5896 // Lock should be held.
5897 func (fs *fileStore) removeMsgViaLimits(seq uint64) (bool, error) {
5898 return fs.removeMsg(seq, false, true, false)
5899 }
5900
5901 // RemoveMsg will remove the message from this store.
5902 // Will return the number of bytes removed.
5903 func (fs *fileStore) RemoveMsg(seq uint64) (bool, error) {
5904 return fs.removeMsg(seq, false, false, true)
5905 }
5906
5907 func (fs *fileStore) EraseMsg(seq uint64) (bool, error) {
5908 return fs.removeMsg(seq, true, false, true)
5909 }
5910
5911 // Convenience function to remove per subject tracking at the filestore level.
5912 // Lock should be held.
5913 func (fs *fileStore) removePerSubject(subj string) uint64 {
5914 if len(subj) == 0 || fs.psim == nil {
5915 return 0
5916 }
5917 // We do not update sense of fblk here but will do so when we resolve during lookup.
5918 bsubj := stringToBytes(subj)
5919 if info, ok := fs.psim.Find(bsubj); ok {
5920 info.total--
5921 if info.total == 0 {
5922 if _, ok = fs.psim.Delete(bsubj); ok {
5923 fs.tsl -= len(subj)
5924 return 0
5925 }
5926 }
5927 return info.total
5928 }
5929 return 0
5930 }
5931
5932 // Remove a message, optionally rewriting the mb file.
5933 func (fs *fileStore) removeMsg(seq uint64, secure, viaLimits, needFSLock bool) (bool, error) {
5934 if seq == 0 {
5935 return false, ErrStoreMsgNotFound
5936 }
5937 fsLock := func() {
5938 if needFSLock {
5939 fs.mu.Lock()
5940 }
5941 }
5942 fsUnlock := func() {
5943 if needFSLock {
5944 fs.mu.Unlock()
5945 }
5946 }
5947
5948 fsLock()
5949 defer fsUnlock()
5950
5951 if fs.isClosed() {
5952 return false, ErrStoreClosed
5953 }
5954 // Always return previous write errors.
5955 if err := fs.werr; err != nil {
5956 return false, err
5957 }
5958 // If in encrypted mode negate secure rewrite here.
5959 if secure && fs.prf != nil {
5960 secure = false
5961 }
5962
5963 mb := fs.selectMsgBlock(seq)
5964 if mb == nil {
5965 var err = ErrStoreEOF
5966 if seq <= fs.state.LastSeq {
5967 err = ErrStoreMsgNotFound
5968 }
5969 return false, err
5970 }
5971
5972 return fs.removeMsgFromBlock(mb, seq, secure, viaLimits)
5973 }
5974
5975 // Remove a message from the given block, optionally rewriting the mb file.
5976 // fs lock should be held.
5977 func (fs *fileStore) removeMsgFromBlock(mb *msgBlock, seq uint64, secure, viaLimits bool) (removed bool, rerr error) {
5978 mb.mu.Lock()
5979
5980 // See if we are closed or the sequence number is still relevant or if we know its deleted.
5981 if mb.closed || seq < atomic.LoadUint64(&mb.first.seq) || mb.dmap.Exists(seq) {
5982 mb.mu.Unlock()
5983 return false, nil
5984 }
5985
5986 // Persist any write errors.
5987 defer func() {
5988 if rerr != nil {
5989 fs.setWriteErr(rerr)
5990 }
5991 }()
5992
5993 fifo := seq == atomic.LoadUint64(&mb.first.seq)
5994 isLastBlock := mb == fs.lmb
5995 isEmpty := mb.msgs == 1 // ... about to be zero though.
5996
5997 // We used to not have to load in the messages except with callbacks or the filtered subject state (which is now always on).
5998 // Now just load regardless.
5999 // TODO(dlc) - Figure out a way not to have to load it in, we need subject tracking outside main data block.
6000 needsCleanup := mb.cache == nil
6001 if mb.cacheNotLoaded() {
6002 if err := mb.loadMsgsWithLock(); err != nil {
6003 if needsCleanup {
6004 mb.finishedWithCache()
6005 }
6006 mb.mu.Unlock()
6007 return false, err
6008 }
6009 }
6010 finishedWithCache := func() {
6011 if needsCleanup {
6012 mb.finishedWithCache()
6013 }
6014 }
6015
6016 var (
6017 smv StoreMsg
6018 subj string
6019 ts int64
6020 lhdr, lmsg int
6021 ttl int64
6022 )
6023 sm, err := mb.cacheLookupNoCopy(seq, &smv)
6024 if err != nil {
6025 finishedWithCache()
6026 mb.mu.Unlock()
6027 // Mimic err behavior from above check to dmap. No error returned if already removed.
6028 if err == ErrStoreMsgNotFound || err == errDeletedMsg {
6029 err = nil
6030 }
6031 return false, err
6032 } else if sm != nil {
6033 // subj aliases mb.cache.buf; copy now because the cache may be erased or
6034 // recycled after we drop mb.mu. The rest are scalars stashed for later use.
6035 subj = copyString(sm.subj)
6036 ts = sm.ts
6037 lhdr = len(sm.hdr)
6038 lmsg = len(sm.msg)
6039 ttl, _ = getMessageTTL(sm.hdr)
6040 }
6041
6042 // Check if we need to write a deleted record tombstone.
6043 // This is for user initiated removes or to hold the first seq
6044 // when the last block is empty.
6045 // If not via limits and not empty (empty writes tombstone below if last) write tombstone.
6046 if !viaLimits && !isEmpty && sm != nil {
6047 mb.mu.Unlock() // Only safe way to checkLastBlock is to unlock here...
6048 lmb, err := fs.checkLastBlock(emptyRecordLen)
6049 if err != nil {
6050 mb.mu.Lock()
6051 finishedWithCache()
6052 mb.mu.Unlock()
6053 return false, err
6054 }
6055 if err := lmb.writeTombstone(seq, ts); err != nil {
6056 mb.mu.Lock()
6057 finishedWithCache()
6058 mb.mu.Unlock()
6059 return false, err
6060 }
6061 mb.mu.Lock() // We'll need the lock back to carry on safely.
6062 }
6063
6064 // Grab size
6065 msz := fileStoreMsgSizeRaw(len(subj), lhdr, lmsg)
6066
6067 // Set cache timestamp for last remove.
6068 mb.lrts = ats.AccessTime()
6069
6070 // Must always perform the erase, even if the block is empty as it could contain tombstones.
6071 if secure {
6072 // Grab record info, but use the pre-computed record length.
6073 ri, _, _, err := mb.slotInfo(int(seq - mb.cache.fseq))
6074 if err != nil {
6075 finishedWithCache()
6076 mb.mu.Unlock()
6077 return false, err
6078 }
6079 if err := mb.eraseMsg(seq, int(ri), int(msz), isLastBlock); err != nil {
6080 finishedWithCache()
6081 mb.mu.Unlock()
6082 return false, err
6083 }
6084 }
6085
6086 // Global stats
6087 if fs.state.Msgs > 0 {
6088 fs.state.Msgs--
6089 }
6090 if msz < fs.state.Bytes {
6091 fs.state.Bytes -= msz
6092 } else {
6093 fs.state.Bytes = 0
6094 }
6095
6096 // Now local mb updates.
6097 if mb.msgs > 0 {
6098 mb.msgs--
6099 }
6100 if msz < mb.bytes {
6101 mb.bytes -= msz
6102 } else {
6103 mb.bytes = 0
6104 }
6105
6106 // Allow us to check compaction again.
6107 mb.noCompact = false
6108
6109 // Mark as dirty for stream state.
6110 fs.dirty++
6111
6112 // If we are tracking subjects here make sure we update that accounting.
6113 if err = mb.ensurePerSubjectInfoLoaded(); err != nil {
6114 finishedWithCache()
6115 mb.mu.Unlock()
6116 return false, err
6117 }
6118
6119 // If we are tracking multiple subjects here make sure we update that accounting.
6120 if _, err = mb.removeSeqPerSubject(subj, seq); err != nil {
6121 finishedWithCache()
6122 mb.mu.Unlock()
6123 return false, err
6124 }
6125 fs.removePerSubject(subj)
6126 if fs.ttls != nil && ttl > 0 {
6127 expires := time.Duration(ts) + (time.Second * time.Duration(ttl))
6128 fs.ttls.Remove(seq, int64(expires))
6129 }
6130
6131 if fifo {
6132 mb.selectNextFirst()
6133 if !isEmpty {
6134 // Can update this one in place.
6135 if seq == fs.state.FirstSeq {
6136 fs.state.FirstSeq = atomic.LoadUint64(&mb.first.seq) // new one.
6137 if mb.first.ts == 0 {
6138 fs.state.FirstTime = time.Time{}
6139 } else {
6140 fs.state.FirstTime = time.Unix(0, mb.first.ts).UTC()
6141 }
6142 }
6143 }
6144 } else if !isEmpty {
6145 // Out of order delete.
6146 mb.dmap.Insert(seq)
6147 // Make simple check here similar to Compact(). If we can save 50% and over a certain threshold do inline.
6148 // All other more thorough cleanup will happen in syncBlocks logic.
6149 // Note that we do not have to store empty records for the deleted, so don't use to calculate.
6150 // TODO(dlc) - This should not be inline, should kick the sync routine.
6151 if !isLastBlock && mb.shouldCompactInline() {
6152 if err = mb.compact(); err != nil {
6153 finishedWithCache()
6154 mb.mu.Unlock()
6155 return false, err
6156 }
6157 }
6158 }
6159
6160 if secure {
6161 if ld, _ := mb.flushPendingMsgsLocked(); ld != nil {
6162 // We have the mb lock here, this needs the mb locks so do in its own go routine.
6163 go fs.rebuildState(ld)
6164 }
6165 }
6166
6167 // If empty remove this block and check if we need to update first sequence.
6168 // We will write a tombstone at the end.
6169 var firstSeqNeedsUpdate bool
6170 if isEmpty {
6171 // This writes tombstone iff mb == lmb, so no need to do above.
6172 if err = fs.removeMsgBlock(mb); err != nil {
6173 finishedWithCache()
6174 mb.mu.Unlock()
6175 return false, err
6176 }
6177 firstSeqNeedsUpdate = seq == fs.state.FirstSeq
6178 }
6179 finishedWithCache()
6180 mb.mu.Unlock()
6181
6182 // If we emptied the current message block and the seq was state.FirstSeq
6183 // then we need to jump message blocks. We will also write the index so
6184 // we don't lose track of the first sequence.
6185 if firstSeqNeedsUpdate {
6186 if err = fs.selectNextFirst(); err != nil {
6187 return false, err
6188 }
6189 }
6190
6191 if cb := fs.scb; cb != nil {
6192 // If we have a callback registered we need to release lock regardless since cb might need it to lookup msg, etc.
6193 fs.mu.Unlock()
6194 // Storage updates.
6195 delta := int64(msz)
6196 cb(-1, -delta, seq, subj)
6197
6198 fs.mu.Lock()
6199 }
6200
6201 return true, nil
6202 }
6203
6204 // Remove all messages in the range [first, last]
6205 // Lock should be held.
6206 func (fs *fileStore) removeMsgsInRange(first, last uint64, viaLimits bool) error {
6207 last = min(last, fs.state.LastSeq)
6208 if first > last {
6209 return nil
6210 }
6211
6212 firstBlock := sort.Search(len(fs.blks), func(i int) bool {
6213 return atomic.LoadUint64(&fs.blks[i].last.seq) >= first
6214 })
6215 if firstBlock >= len(fs.blks) {
6216 return nil
6217 }
6218
6219 for i := firstBlock; i < len(fs.blks); {
6220 mb := fs.blks[i]
6221 mbFirstSeq := atomic.LoadUint64(&mb.first.seq)
6222 mbLastSeq := atomic.LoadUint64(&mb.last.seq)
6223 if mbFirstSeq > last {
6224 break
6225 }
6226 if mbFirstSeq >= first && mbLastSeq <= last && mb.numPriorTombs() == 0 {
6227 // If this block stores no tombstones for previous blocks,
6228 // and its sequences are within the range to be removed,
6229 // we can get rid of the block entirely. To do that we use
6230 // purgeMgsBlock, which also removes the block from fs.blks.
6231 // After purgeMsgBlock, i will be the index of the following
6232 // msgBlock, if any. Therefore, continue without incrementing i.
6233 if err := fs.purgeMsgBlock(mb); err != nil {
6234 return err
6235 }
6236 } else {
6237 from := max(first, mbFirstSeq)
6238 to := min(last, mbLastSeq)
6239 for seq := from; seq <= to; seq++ {
6240 if _, err := fs.removeMsgFromBlock(mb, seq, false, viaLimits); err != nil {
6241 return err
6242 }
6243 }
6244 i++
6245 }
6246 }
6247 return nil
6248 }
6249
6250 // Tests whether we should try to compact this block while inline removing msgs.
6251 // We will want rbytes to be over the minimum and have a 2x potential savings.
6252 // If we compacted before but rbytes didn't improve much, guard against constantly compacting.
6253 // Lock should be held.
6254 func (mb *msgBlock) shouldCompactInline() bool {
6255 return mb.rbytes > compactMinimum && mb.bytes*2 < mb.rbytes && (mb.cbytes == 0 || mb.bytes*2 < mb.cbytes)
6256 }
6257
6258 // Tests whether we should try to compact this block while running periodic sync.
6259 // We will want rbytes to be over the minimum and have a 2x potential savings.
6260 // Ignores 2MB minimum.
6261 // Lock should be held.
6262 func (mb *msgBlock) shouldCompactSync() bool {
6263 return mb.bytes*2 < mb.rbytes && !mb.noCompact
6264 }
6265
6266 // This will compact and rewrite this block. This version will not process any tombstone cleanup.
6267 // Write lock needs to be held.
6268 func (mb *msgBlock) compact() error {
6269 return mb.compactWithFloor(0, nil)
6270 }
6271
6272 // This will compact and rewrite this block. This should only be called when we know we want to rewrite this block.
6273 // This should not be called on the lmb since we will prune tail deleted messages which could cause issues with
6274 // writing new messages. We will silently bail on any issues with the underlying block and let someone else detect.
6275 // if fseq > 0 we will attempt to cleanup stale tombstones.
6276 // Write lock needs to be held.
6277 func (mb *msgBlock) compactWithFloor(floor uint64, fsDmap *interiorDeletes) error {
6278 wasLoaded := mb.cache != nil && mb.cacheAlreadyLoaded()
6279 if !wasLoaded {
6280 if err := mb.loadMsgsWithLock(); err != nil {
6281 return err
6282 }
6283 }
6284 defer mb.finishedWithCache()
6285
6286 buf := mb.cache.buf
6287 nbuf := getMsgBlockBuf(len(buf))
6288 // Recycle our nbuf when we are done.
6289 defer recycleMsgBlockBuf(nbuf)
6290
6291 var le = binary.LittleEndian
6292 var firstSet bool
6293 var last uint64
6294 var msgs uint64
6295
6296 fseq := atomic.LoadUint64(&mb.first.seq)
6297 lseq := atomic.LoadUint64(&mb.last.seq)
6298 isDeleted := func(seq uint64) bool {
6299 return seq == 0 || seq&ebit != 0 || mb.dmap.Exists(seq) || seq < fseq
6300 }
6301
6302 for index, lbuf := uint32(0), uint32(len(buf)); index < lbuf; {
6303 if index+msgHdrSize > lbuf {
6304 return fmt.Errorf("message overrun")
6305 }
6306 hdr := buf[index : index+msgHdrSize]
6307 rl, slen := le.Uint32(hdr[0:]), int(le.Uint16(hdr[20:]))
6308 hasHeaders := rl&hbit != 0
6309 // Clear any headers bit that could be set.
6310 rl &^= hbit
6311 shlen := slen
6312 if hasHeaders {
6313 shlen += 4
6314 }
6315 dlen := int(rl) - msgHdrSize
6316 // Do some quick sanity checks here.
6317 if dlen < 0 || shlen > (dlen-recordHashSize) || dlen > int(rl) || index+rl > lbuf || rl > rlBadThresh {
6318 return fmt.Errorf("sanity check failed")
6319 }
6320 // Only need to process non-deleted messages.
6321 seq := le.Uint64(hdr[4:])
6322 ts := int64(le.Uint64(hdr[12:]))
6323
6324 if !isDeleted(seq) {
6325 // Check for tombstones.
6326 if seq&tbit != 0 {
6327 seq = seq &^ tbit
6328 // If this entry is for a lower seq than ours then keep around.
6329 // We also check that it is greater than our floor. Floor is zero on normal
6330 // calls to compact.
6331 // If the global delete map is set, check if a tombstone is still
6332 // referencing a message in another block. If not, it can be removed.
6333 if seq < fseq && seq >= floor && (fsDmap == nil || fsDmap.Exists(seq)) {
6334 nbuf = append(nbuf, buf[index:index+rl]...)
6335 }
6336 } else {
6337 // Normal message here.
6338 msgs++
6339 nbuf = append(nbuf, buf[index:index+rl]...)
6340 if !firstSet {
6341 firstSet = true
6342 atomic.StoreUint64(&mb.first.seq, seq)
6343 }
6344 if seq >= last {
6345 last = seq
6346 atomic.StoreUint64(&mb.last.seq, last)
6347 mb.last.ts = ts
6348 }
6349 }
6350 }
6351 // Advance to next record.
6352 index += rl
6353 }
6354
6355 // Handle compression
6356 if mb.cmp != NoCompression && len(nbuf) > 0 {
6357 originalSize := len(nbuf)
6358 var err error
6359 if nbuf, err = mb.cmp.Compress(nbuf); err != nil {
6360 return err
6361 }
6362 meta := &CompressionInfo{
6363 Algorithm: mb.cmp,
6364 OriginalSize: uint64(originalSize),
6365 }
6366 nbuf = append(meta.MarshalMetadata(), nbuf...)
6367 }
6368
6369 // Check for encryption.
6370 if mb.bek != nil && len(nbuf) > 0 {
6371 // Recreate to reset counter.
6372 rbek, err := genBlockEncryptionKey(mb.fs.fcfg.Cipher, mb.seed, mb.nonce)
6373 if err != nil {
6374 return err
6375 }
6376 rbek.XORKeyStream(nbuf, nbuf)
6377 }
6378
6379 // Close FDs first.
6380 mb.closeFDsLocked()
6381
6382 // We will write to a new file and mv/rename it in case of failure.
6383 mfn := filepath.Join(mb.fs.fcfg.StoreDir, msgDir, fmt.Sprintf(newScan, mb.index))
6384 sync := mb.syncAlways
6385 if err := writeAtomicallyWithTemp(mb.fs.dios, mfn, mb.mfn, nbuf, defaultFilePerms, sync); err != nil {
6386 return err
6387 }
6388
6389 // Make sure to sync if we have not done so yet
6390 mb.needSync = !sync
6391
6392 // Capture the updated rbytes.
6393 if rbytes := uint64(len(nbuf)); rbytes == mb.rbytes {
6394 // No change, so set our noCompact bool here to avoid attempting to continually compress in syncBlocks.
6395 mb.noCompact = true
6396 } else {
6397 mb.rbytes = rbytes
6398 }
6399 mb.cbytes = mb.bytes
6400
6401 // Remove any seqs from the beginning of the blk.
6402 for seq, nfseq := fseq, atomic.LoadUint64(&mb.first.seq); seq < nfseq; seq++ {
6403 mb.dmap.Delete(seq)
6404 }
6405 // Remove any seqs from the ending of the blk.
6406 for seq, nlseq := lseq, atomic.LoadUint64(&mb.last.seq); seq > nlseq; seq-- {
6407 mb.dmap.Delete(seq)
6408 }
6409 // If the block itself has no messages anymore (could still contain tombstones though),
6410 // then we need to account for that by resetting the last sequence and timestamp.
6411 if msgs == 0 {
6412 atomic.StoreUint64(&mb.last.seq, fseq-1)
6413 mb.last.ts = 0
6414 mb.dmap.Empty()
6415 }
6416 // Make sure we clear the cache since no longer valid.
6417 mb.clearCacheAndOffset()
6418 // If we entered with the msgs loaded make sure to reload them.
6419 if wasLoaded {
6420 if err := mb.loadMsgsWithLock(); err != nil {
6421 return err
6422 }
6423 }
6424 return nil
6425 }
6426
6427 // Grab info from a slot.
6428 // Lock should be held.
6429 func (mb *msgBlock) slotInfo(slot int) (uint32, uint32, bool, error) {
6430 switch {
6431 case mb.cache == nil: // Shouldn't be possible, but check it anyway.
6432 return 0, 0, false, errNoCache
6433 case slot < 0:
6434 mb.fs.warn("Partial cache: offset slot index %d is less zero", slot)
6435 return 0, 0, false, errPartialCache
6436 case slot >= len(mb.cache.idx):
6437 mb.fs.warn("Partial cache: offset slot index %d is greater than index len %d", slot, len(mb.cache.idx))
6438 return 0, 0, false, errPartialCache
6439 }
6440
6441 bi := mb.cache.idx[slot]
6442 ri, hashChecked := (bi &^ cbit), (bi&cbit) != 0
6443
6444 // If this is a deleted slot return here.
6445 if bi == dbit {
6446 return 0, 0, false, errDeletedMsg
6447 }
6448
6449 // Determine record length
6450 var rl uint32
6451 // Need to account for dbit markers in idx.
6452 // So we will walk until we find valid idx slot to calculate rl.
6453 for i := 1; slot+i < len(mb.cache.idx); i++ {
6454 ni := mb.cache.idx[slot+i] &^ cbit
6455 if ni == dbit {
6456 continue
6457 }
6458 rl = ni - ri
6459 break
6460 }
6461 // check if we had all trailing dbits.
6462 // If so use len of cache buf minus ri.
6463 if rl == 0 {
6464 rl = uint32(len(mb.cache.buf)) - ri
6465 }
6466 if rl < msgHdrSize {
6467 return 0, 0, false, errBadMsg{mb.mfn, fmt.Sprintf("length too short for slot %d", slot)}
6468 }
6469 return uint32(ri), rl, hashChecked, nil
6470 }
6471
6472 func (fs *fileStore) isClosed() bool {
6473 return fs.closed.Load()
6474 }
6475
6476 // Will spin up our flush loop.
6477 func (mb *msgBlock) spinUpFlushLoop() {
6478 mb.mu.Lock()
6479 defer mb.mu.Unlock()
6480 mb.spinUpFlushLoopLocked()
6481 }
6482
6483 // Will spin up our flush loop.
6484 // Lock should be held.
6485 func (mb *msgBlock) spinUpFlushLoopLocked() {
6486 // Are we already running or closed?
6487 if mb.flusher || mb.closed {
6488 return
6489 }
6490 mb.flusher = true
6491 mb.fch = make(chan struct{}, 1)
6492 mb.qch = make(chan struct{})
6493 fch, qch := mb.fch, mb.qch
6494
6495 go mb.flushLoop(fch, qch)
6496 }
6497
6498 // Raw low level kicker for flush loops.
6499 func kickFlusher(fch chan struct{}) {
6500 if fch != nil {
6501 select {
6502 case fch <- struct{}{}:
6503 default:
6504 }
6505 }
6506 }
6507
6508 // Kick flusher for this message block.
6509 func (mb *msgBlock) kickFlusher() {
6510 mb.mu.RLock()
6511 defer mb.mu.RUnlock()
6512 kickFlusher(mb.fch)
6513 }
6514
6515 func (mb *msgBlock) setInFlusher() {
6516 mb.mu.Lock()
6517 mb.flusher = true
6518 mb.mu.Unlock()
6519 }
6520
6521 func (mb *msgBlock) clearInFlusher() {
6522 mb.mu.Lock()
6523 mb.flusher = false
6524 if mb.qch != nil {
6525 close(mb.qch)
6526 mb.qch = nil
6527 }
6528 if mb.fch != nil {
6529 close(mb.fch)
6530 mb.fch = nil
6531 }
6532 mb.mu.Unlock()
6533 }
6534
6535 // flushLoop watches for messages, index info, or recently closed msg block updates.
6536 func (mb *msgBlock) flushLoop(fch, qch chan struct{}) {
6537 mb.setInFlusher()
6538 defer mb.clearInFlusher()
6539
6540 for {
6541 select {
6542 case <-fch:
6543 // If we have pending messages process them first.
6544 if waiting := mb.pendingWriteSize(); waiting != 0 {
6545 ts := 1 * time.Millisecond
6546 var waited time.Duration
6547
6548 for waiting < coalesceMinimum {
6549 time.Sleep(ts)
6550 select {
6551 case <-qch:
6552 return
6553 default:
6554 }
6555 newWaiting := mb.pendingWriteSize()
6556 if waited = waited + ts; waited > maxFlushWait || newWaiting <= waiting {
6557 break
6558 }
6559 waiting = newWaiting
6560 ts *= 2
6561 }
6562
6563 // Ignore error here, the error is persisted as mb.werr and will be bubbled up later.
6564 _ = mb.flushPendingMsgs()
6565 }
6566
6567 // Check if we are no longer the last message block. If we are
6568 // not we can close FDs and exit.
6569 mb.fs.mu.RLock()
6570 notLast := mb != mb.fs.lmb
6571 mb.fs.mu.RUnlock()
6572
6573 if notLast {
6574 if err := mb.closeFDs(); err == nil {
6575 return
6576 }
6577 }
6578 case <-qch:
6579 return
6580 }
6581 }
6582 }
6583
6584 // Lock should be held.
6585 func (mb *msgBlock) eraseMsg(seq uint64, ri, rl int, isLastBlock bool) error {
6586 var le = binary.LittleEndian
6587 var hdr [msgHdrSize]byte
6588
6589 le.PutUint32(hdr[0:], uint32(rl))
6590 le.PutUint64(hdr[4:], seq|ebit)
6591 le.PutUint64(hdr[12:], 0)
6592 le.PutUint16(hdr[20:], 0)
6593
6594 // Randomize record
6595 data := make([]byte, rl-emptyRecordLen)
6596 if n, err := rand.Read(data); err != nil {
6597 return err
6598 } else if n != len(data) {
6599 return fmt.Errorf("not enough overwrite bytes read (%d != %d)", n, len(data))
6600 }
6601
6602 // Now write to underlying buffer.
6603 var b bytes.Buffer
6604 b.Write(hdr[:])
6605 b.Write(data)
6606
6607 // Calculate hash.
6608 mb.hh.Reset()
6609 mb.hh.Write(hdr[4:20])
6610 mb.hh.Write(data)
6611 var hb [highwayhash.Size64]byte
6612 checksum := mb.hh.Sum(hb[:0])
6613 // Write to msg record.
6614 b.Write(checksum)
6615
6616 // Update both cache and disk.
6617 nbytes := b.Bytes()
6618
6619 // Cache
6620 if ri+rl <= len(mb.cache.buf) {
6621 copy(mb.cache.buf[ri:ri+rl], nbytes)
6622 }
6623
6624 // Disk
6625 if mb.cache.wp > ri {
6626 if err := mb.atomicOverwriteFile(mb.cache.buf, !isLastBlock); err != nil {
6627 return err
6628 }
6629 }
6630 return nil
6631 }
6632
6633 // Truncate this message block to the tseq and ts.
6634 // Lock should be held.
6635 func (mb *msgBlock) truncate(tseq uint64, ts int64) (nmsgs, nbytes uint64, err error) {
6636 // Make sure we are loaded to process messages etc.
6637 if err := mb.loadMsgsWithLock(); err != nil {
6638 return 0, 0, err
6639 }
6640 defer mb.finishedWithCache()
6641
6642 // Calculate new eof using slot info from our new last sm.
6643 ri, rl, _, err := mb.slotInfo(int(tseq - mb.cache.fseq))
6644 if err != nil {
6645 return 0, 0, err
6646 }
6647 // Calculate new eof.
6648 eof := int64(ri + rl)
6649
6650 // FIXME(dlc) - We could be smarter here.
6651 if buf, _ := mb.bytesPending(); len(buf) > 0 {
6652 ld, err := mb.flushPendingMsgsLocked()
6653 if ld != nil && mb.fs != nil {
6654 // We do not know if fs is locked or not at this point.
6655 // This should be an exceptional condition so do so in Go routine.
6656 go mb.fs.rebuildState(ld)
6657 }
6658 if err != nil {
6659 return 0, 0, err
6660 }
6661 }
6662
6663 var purged, bytes uint64
6664
6665 checkDmap := mb.dmap.Size() > 0
6666 var smv StoreMsg
6667
6668 for seq := atomic.LoadUint64(&mb.last.seq); seq > tseq; seq-- {
6669 if checkDmap {
6670 if mb.dmap.Exists(seq) {
6671 // Delete and skip to next.
6672 mb.dmap.Delete(seq)
6673 checkDmap = !mb.dmap.IsEmpty()
6674 continue
6675 }
6676 }
6677 // We should have a valid msg to calculate removal stats.
6678 if m, err := mb.cacheLookupNoCopy(seq, &smv); err == nil {
6679 if mb.msgs > 0 {
6680 rl := fileStoreMsgSize(m.subj, m.hdr, m.msg)
6681 mb.msgs--
6682 if rl > mb.bytes {
6683 rl = mb.bytes
6684 }
6685 mb.bytes -= rl
6686 mb.rbytes -= rl
6687 // For return accounting.
6688 purged++
6689 bytes += uint64(rl)
6690 }
6691 }
6692 }
6693
6694 // If the block is compressed/encrypted then we have to load it into memory
6695 // and decompress/decrypt it, truncate it and then write it back out.
6696 // Otherwise, truncate the file itself and close the descriptor.
6697 if mb.cmp != NoCompression || mb.bek != nil {
6698 buf, err := mb.loadBlock(nil)
6699 if err != nil {
6700 return 0, 0, fmt.Errorf("failed to load block from disk: %w", err)
6701 }
6702 if err = mb.encryptOrDecryptIfNeeded(buf); err != nil {
6703 return 0, 0, err
6704 }
6705 if buf, err = mb.decompressIfNeeded(buf); err != nil {
6706 return 0, 0, fmt.Errorf("failed to decompress block: %w", err)
6707 }
6708 buf = buf[:eof]
6709 copy(mb.lchk[0:], buf[len(buf)-checksumSize:])
6710 // We did decompress but don't recompress the truncated buffer here since we're the last block
6711 // and would otherwise have compressed data and allow to write uncompressed data in the same block.
6712 if err = mb.atomicOverwriteFile(buf, false); err != nil {
6713 return 0, 0, err
6714 }
6715 } else if mb.mfd != nil {
6716 if err = mb.mfd.Truncate(eof); err != nil {
6717 return 0, 0, err
6718 }
6719 if err = mb.mfd.Sync(); err != nil {
6720 return 0, 0, err
6721 }
6722 // Update our checksum.
6723 var lchk [8]byte
6724 if _, err = mb.mfd.ReadAt(lchk[:], eof-8); err != nil {
6725 return 0, 0, err
6726 }
6727 copy(mb.lchk[0:], lchk[:])
6728 } else {
6729 return 0, 0, fmt.Errorf("failed to truncate msg block %d, file not open", mb.index)
6730 }
6731
6732 // Update our last msg.
6733 atomic.StoreUint64(&mb.last.seq, tseq)
6734 mb.last.ts = ts
6735
6736 // Clear our cache.
6737 mb.clearCacheAndOffset()
6738
6739 // Redo per subject info for this block.
6740 if err = mb.resetPerSubjectInfo(); err != nil {
6741 return purged, bytes, err
6742 }
6743
6744 // Load msgs again.
6745 return purged, bytes, mb.loadMsgsWithLock()
6746 }
6747
6748 // Helper to determine if the mb is empty.
6749 func (mb *msgBlock) isEmpty() bool {
6750 return atomic.LoadUint64(&mb.first.seq) > atomic.LoadUint64(&mb.last.seq)
6751 }
6752
6753 // Lock should be held.
6754 func (mb *msgBlock) selectNextFirst() {
6755 var seq uint64
6756 fseq, lseq := atomic.LoadUint64(&mb.first.seq), atomic.LoadUint64(&mb.last.seq)
6757 for seq = fseq + 1; seq <= lseq; seq++ {
6758 if mb.dmap.Exists(seq) {
6759 // We will move past this so we can delete the entry.
6760 mb.dmap.Delete(seq)
6761 } else {
6762 break
6763 }
6764 }
6765 // Set new first sequence.
6766 atomic.StoreUint64(&mb.first.seq, seq)
6767
6768 // Check if we are empty..
6769 if seq > lseq {
6770 mb.first.ts = 0
6771 return
6772 }
6773
6774 // Need to get the timestamp.
6775 // We will try the cache direct and fallback if needed.
6776 var smv StoreMsg
6777 sm, _ := mb.cacheLookupNoCopy(seq, &smv)
6778 if sm == nil {
6779 // Slow path, cache not loaded.
6780 sm, _, _ = mb.fetchMsgNoCopyLocked(seq, &smv)
6781 mb.finishedWithCache()
6782 }
6783 if sm != nil {
6784 mb.first.ts = sm.ts
6785 } else {
6786 mb.first.ts = 0
6787 }
6788 }
6789
6790 // Select the next FirstSeq
6791 // Also cleans up empty blocks at the start only containing tombstones.
6792 // Lock should be held.
6793 func (fs *fileStore) selectNextFirst() error {
6794 if len(fs.blks) > 0 {
6795 for len(fs.blks) > 1 {
6796 mb := fs.blks[0]
6797 mb.mu.Lock()
6798 empty := mb.msgs == 0
6799 if !empty {
6800 mb.mu.Unlock()
6801 break
6802 }
6803 err := fs.forceRemoveMsgBlock(mb)
6804 mb.mu.Unlock()
6805 if err != nil {
6806 return err
6807 }
6808 }
6809 mb := fs.blks[0]
6810 mb.mu.RLock()
6811 fs.state.FirstSeq = atomic.LoadUint64(&mb.first.seq)
6812 if mb.first.ts == 0 {
6813 fs.state.FirstTime = time.Time{}
6814 } else {
6815 fs.state.FirstTime = time.Unix(0, mb.first.ts).UTC()
6816 }
6817 mb.mu.RUnlock()
6818 } else {
6819 // Could not find anything, so treat like purge
6820 fs.state.FirstSeq = fs.state.LastSeq + 1
6821 fs.state.FirstTime = time.Time{}
6822 }
6823 // Mark first as moved. Plays into tombstone cleanup for syncBlocks.
6824 fs.firstMoved = true
6825 return nil
6826 }
6827
6828 // Lock should be held.
6829 func (mb *msgBlock) resetCacheExpireTimer(td time.Duration) {
6830 if td == 0 {
6831 td = mb.cexp + 100*time.Millisecond
6832 }
6833 if mb.ctmr == nil {
6834 mb.ctmr = time.AfterFunc(td, mb.tryExpireCache)
6835 } else {
6836 mb.ctmr.Reset(td)
6837 }
6838 }
6839
6840 // Lock should be held.
6841 func (mb *msgBlock) startCacheExpireTimer() {
6842 mb.resetCacheExpireTimer(0)
6843 }
6844
6845 // Used when we load in a message block.
6846 // Lock should be held.
6847 func (mb *msgBlock) clearCacheAndOffset() {
6848 // Reset linear scan tracker.
6849 mb.llseq = 0
6850 mb.clearCache()
6851 }
6852
6853 // Lock should be held.
6854 func (mb *msgBlock) clearCache() {
6855 if mb.ctmr != nil {
6856 tsla := mb.sinceLastActivity()
6857 if mb.fss == nil || tsla > mb.fexp {
6858 // Force
6859 mb.fss = nil
6860 mb.ctmr.Stop()
6861 mb.ctmr = nil
6862 } else {
6863 mb.resetCacheExpireTimer(mb.fexp - tsla)
6864 }
6865 }
6866
6867 mbcache := mb.cache
6868 if mbcache == nil {
6869 mbcache = mb.ecache.Value()
6870 }
6871 if mbcache == nil {
6872 return
6873 }
6874
6875 buf := mbcache.buf
6876 mb.cache = nil
6877 mb.ecache.Set(nil)
6878 mbcache.stopRecycle()
6879 recycleMsgBlockBuf(buf)
6880 }
6881
6882 // Called to possibly expire a message block cache.
6883 func (mb *msgBlock) tryExpireCache() {
6884 mb.mu.Lock()
6885 defer mb.mu.Unlock()
6886 mb.tryExpireCacheLocked()
6887 }
6888
6889 func (mb *msgBlock) tryForceExpireCache() {
6890 mb.mu.Lock()
6891 defer mb.mu.Unlock()
6892 mb.tryForceExpireCacheLocked()
6893 }
6894
6895 // We will attempt to force expire this by temporarily clearing the last load time.
6896 func (mb *msgBlock) tryForceExpireCacheLocked() {
6897 llts := mb.llts
6898 mb.llts = 0
6899 mb.tryExpireCacheLocked()
6900 mb.llts = llts
6901 }
6902
6903 // This is for expiration of the write cache, which will be partial with fip.
6904 // So we want to bypass the Pools here.
6905 // Lock should be held.
6906 func (mb *msgBlock) tryExpireWriteCache() []byte {
6907 if mb.cache == nil {
6908 return nil
6909 }
6910 lwts, buf, llts, nra := mb.lwts, mb.cache.buf, mb.llts, mb.cache.nra
6911 mb.lwts, mb.cache.nra = 0, true
6912 mb.tryExpireCacheLocked()
6913 mb.lwts = lwts
6914 if mb.cache != nil {
6915 mb.cache.nra = nra
6916 }
6917 // We could check for a certain time since last load, but to be safe just reuse if no loads at all.
6918 if llts == 0 && (mb.cache == nil || mb.cache.buf == nil) {
6919 // Clear last write time since we now are about to move on to a new lmb.
6920 mb.lwts = 0
6921 return buf[:0]
6922 }
6923 // The cache may have expired above without recycling the buffer.
6924 if mb.cache == nil && !nra {
6925 recycleMsgBlockBuf(buf)
6926 }
6927 return nil
6928 }
6929
6930 // Lock should be held.
6931 func (mb *msgBlock) tryExpireCacheLocked() {
6932 var strengthened bool
6933 if mb.cache == nil {
6934 mb.cache = mb.ecache.Value()
6935 strengthened = true
6936 }
6937 if mb.cache == nil && mb.fss == nil {
6938 if mb.ctmr != nil {
6939 mb.ctmr.Stop()
6940 mb.ctmr = nil
6941 }
6942 return
6943 }
6944
6945 // Can't expire if we still have pending.
6946 if mb.cache != nil && len(mb.cache.buf)-int(mb.cache.wp) > 0 {
6947 mb.resetCacheExpireTimer(mb.cexp)
6948 if strengthened {
6949 mb.finishedWithCache()
6950 }
6951 return
6952 }
6953
6954 // Grab timestamp to compare.
6955 tns := ats.AccessTime()
6956
6957 // For the core buffer of messages, we care about reads and writes, but not removes.
6958 bufts := mb.llts
6959 if mb.lwts > bufts {
6960 bufts = mb.lwts
6961 }
6962
6963 // Check for activity on the cache that would prevent us from expiring.
6964 // Both tns and bufts come from ats.AccessTime(), which means bufts can understate
6965 // how recent the last activity actually was by up to one tick.
6966 if delta := tns - bufts; delta <= int64(mb.cexp)+int64(ats.TickInterval) {
6967 td := mb.cexp - time.Duration(delta)
6968 if td <= 0 {
6969 td = ats.TickInterval
6970 }
6971 mb.resetCacheExpireTimer(td)
6972 if strengthened {
6973 mb.finishedWithCache()
6974 }
6975 return
6976 }
6977
6978 // If we are here we will at least expire the core msg buffer.
6979 // We need to capture offset in case we do a write next before a full load.
6980 if mb.cache != nil {
6981 mb.cache.stopRecycle()
6982 if !mb.cache.nra {
6983 recycleMsgBlockBuf(mb.cache.buf)
6984 }
6985 mb.cache.buf = nil
6986 mb.cache.idx = mb.cache.idx[:0]
6987 mb.cache.wp = 0
6988 }
6989
6990 // Check if we can clear out our idx unless under force expire.
6991 // fss we keep longer and expire under sync timer checks.
6992 mb.clearCache()
6993 }
6994
6995 func (fs *fileStore) startAgeChk() {
6996 if fs.ageChk != nil {
6997 return
6998 }
6999 if fs.cfg.MaxAge != 0 || fs.ttls != nil {
7000 fs.ageChk = time.AfterFunc(fs.cfg.MaxAge, fs.expireMsgs)
7001 }
7002 }
7003
7004 // Lock should be held.
7005 func (fs *fileStore) resetAgeChk(delta int64) {
7006 // If we're already expiring messages, it will make sure to reset.
7007 // Don't trigger again, as that could result in many expire goroutines.
7008 if fs.ageChkRun {
7009 return
7010 }
7011
7012 var next int64 = math.MaxInt64
7013 if fs.ttls != nil {
7014 next = fs.ttls.GetNextExpiration(next)
7015 }
7016
7017 // If there's no MaxAge and there's nothing waiting to be expired then
7018 // don't bother continuing. The next storeRawMsg() will wake us up if
7019 // needs be.
7020 if fs.cfg.MaxAge <= 0 && next == math.MaxInt64 {
7021 clearTimer(&fs.ageChk)
7022 return
7023 }
7024
7025 // Check to see if we should be firing sooner than MaxAge for an expiring TTL.
7026 fireIn := fs.cfg.MaxAge
7027
7028 // If delta for next-to-expire message is unset, but we still have messages to remove.
7029 // Assume messages are removed through proposals, and we need to speed up subsequent age check.
7030 if delta == 0 && fs.state.Msgs > 0 {
7031 if until := 2 * time.Second; until < fireIn {
7032 fireIn = until
7033 }
7034 }
7035
7036 if next < math.MaxInt64 {
7037 // Looks like there's a next expiration, use it either if there's no
7038 // MaxAge set or if it looks to be sooner than MaxAge is.
7039 if until := time.Until(time.Unix(0, next)); fireIn == 0 || until < fireIn {
7040 fireIn = until
7041 }
7042 }
7043
7044 // If not then look at the delta provided (usually gap to next age expiry).
7045 if delta > 0 {
7046 if fireIn == 0 || time.Duration(delta) < fireIn {
7047 fireIn = time.Duration(delta)
7048 }
7049 }
7050
7051 // Make sure we aren't firing too often either way, otherwise we can
7052 // negatively impact stream ingest performance.
7053 if fireIn < 250*time.Millisecond {
7054 fireIn = 250 * time.Millisecond
7055 }
7056
7057 // If we want to kick the timer to run later than what was assigned before, don't reset it.
7058 // Otherwise, we could get in a situation where the timer is continuously reset, and it never runs.
7059 expires := ats.AccessTime() + fireIn.Nanoseconds()
7060 if fs.ageChkTime > 0 && expires > fs.ageChkTime {
7061 return
7062 }
7063
7064 fs.ageChkTime = expires
7065 if fs.ageChk != nil {
7066 fs.ageChk.Reset(fireIn)
7067 } else {
7068 fs.ageChk = time.AfterFunc(fireIn, fs.expireMsgs)
7069 }
7070 }
7071
7072 // Lock should be held.
7073 func (fs *fileStore) cancelAgeChk() {
7074 if fs.ageChk != nil {
7075 fs.ageChk.Stop()
7076 fs.ageChk = nil
7077 fs.ageChkTime = 0
7078 }
7079 }
7080
7081 // Will expire msgs that are too old.
7082 func (fs *fileStore) expireMsgs() {
7083 // We need to delete one by one here and can not optimize for the time being.
7084 // Reason is that we need more information to adjust ack pending in consumers.
7085 var smv StoreMsg
7086 var sm *StoreMsg
7087
7088 fs.mu.Lock()
7089 maxAge := int64(fs.cfg.MaxAge)
7090 minAge := ats.AccessTime() - maxAge
7091 rmcb := fs.rmcb
7092 pmsgcb := fs.pmsgcb
7093 sdmTTL := int64(fs.cfg.SubjectDeleteMarkerTTL.Seconds())
7094 sdmEnabled := sdmTTL > 0
7095
7096 // If SDM is enabled, but handlers aren't set up yet. Try again later.
7097 if sdmEnabled && (rmcb == nil || pmsgcb == nil) {
7098 fs.resetAgeChk(0)
7099 fs.mu.Unlock()
7100 return
7101 }
7102 fs.ageChkRun = true
7103 fs.mu.Unlock()
7104
7105 if maxAge > 0 {
7106 var seq uint64
7107 for sm, seq, _ = fs.LoadNextMsg(fwcs, true, 0, &smv); sm != nil && sm.ts <= minAge; sm, seq, _ = fs.LoadNextMsg(fwcs, true, seq+1, &smv) {
7108 if len(sm.hdr) > 0 {
7109 if ttl, err := getMessageTTL(sm.hdr); err == nil && ttl < 0 {
7110 // The message has a negative TTL, therefore it must "never expire".
7111 minAge = ats.AccessTime() - maxAge
7112 continue
7113 }
7114 }
7115 // Remove the message and then, if LimitsTTL is enabled, try and work out
7116 // if it was the last message of that particular subject that we just deleted.
7117 if sdmEnabled {
7118 if last, ok := fs.shouldProcessSdm(seq, sm.subj); ok {
7119 sdm := last && !isSubjectDeleteMarker(sm.hdr)
7120 fs.handleRemovalOrSdm(seq, sm.subj, sdm, sdmTTL)
7121 }
7122 } else {
7123 fs.mu.Lock()
7124 fs.removeMsgViaLimits(sm.seq)
7125 fs.mu.Unlock()
7126 }
7127 // Recalculate in case we are expiring a bunch.
7128 minAge = ats.AccessTime() - maxAge
7129 }
7130 }
7131 var ageDelta int64
7132 if sm != nil {
7133 ageDelta = sm.ts - minAge
7134 }
7135
7136 fs.mu.Lock()
7137 defer fs.mu.Unlock()
7138
7139 // TODO: Not great that we're holding the lock here, but the timed hash wheel isn't thread-safe.
7140 nextTTL := int64(math.MaxInt64)
7141 var rmSeqs []thw.HashWheelEntry
7142 if fs.ttls != nil {
7143 fs.ttls.ExpireTasks(func(seq uint64, ts int64) bool {
7144 rmSeqs = append(rmSeqs, thw.HashWheelEntry{Seq: seq, Expires: ts})
7145 // We might need to remove messages out of band, those can fail, and we can be shutdown halfway
7146 // through so don't remove from THW just yet.
7147 return false
7148 })
7149 nextTTL = fs.ttls.GetNextExpiration(math.MaxInt64)
7150 }
7151
7152 // Remove messages collected by THW.
7153 if !sdmEnabled {
7154 for _, rm := range rmSeqs {
7155 fs.removeMsg(rm.Seq, false, false, false)
7156 }
7157 } else {
7158 // THW is unordered, so must sort by sequence and must not be holding the lock.
7159 fs.mu.Unlock()
7160 slices.SortFunc(rmSeqs, func(a, b thw.HashWheelEntry) int {
7161 if a.Seq == b.Seq {
7162 return 0
7163 } else if a.Seq < b.Seq {
7164 return -1
7165 } else {
7166 return 1
7167 }
7168 })
7169 for _, rm := range rmSeqs {
7170 // Need to grab subject for the specified sequence if for SDM, and check
7171 // if the message hasn't been removed in the meantime.
7172 // We need to grab the message and check if we should process SDM while holding the lock,
7173 // otherwise we can race if a deletion of this message is in progress.
7174 fs.mu.Lock()
7175 sm, _ = fs.msgForSeqLocked(rm.Seq, &smv, false)
7176 if sm == nil {
7177 fs.ttls.Remove(rm.Seq, rm.Expires)
7178 fs.mu.Unlock()
7179 continue
7180 }
7181 last, ok := fs.shouldProcessSdmLocked(rm.Seq, sm.subj)
7182 fs.mu.Unlock()
7183 if ok {
7184 sdm := last && !isSubjectDeleteMarker(sm.hdr)
7185 fs.handleRemovalOrSdm(rm.Seq, sm.subj, sdm, sdmTTL)
7186 }
7187 }
7188 fs.mu.Lock()
7189 }
7190
7191 // Only cancel if no message left, not on potential lookup error that would result in sm == nil.
7192 fs.ageChkRun, fs.ageChkTime = false, 0
7193 if fs.state.Msgs == 0 && nextTTL == math.MaxInt64 {
7194 fs.cancelAgeChk()
7195 } else {
7196 fs.resetAgeChk(ageDelta)
7197 }
7198 }
7199
7200 func (fs *fileStore) shouldProcessSdm(seq uint64, subj string) (bool, bool) {
7201 fs.mu.Lock()
7202 defer fs.mu.Unlock()
7203 return fs.shouldProcessSdmLocked(seq, subj)
7204 }
7205
7206 // Lock should be held.
7207 func (fs *fileStore) shouldProcessSdmLocked(seq uint64, subj string) (bool, bool) {
7208 if fs.sdm == nil {
7209 fs.sdm = newSDMMeta()
7210 }
7211
7212 if p, ok := fs.sdm.pending[seq]; ok {
7213 // Don't allow more proposals for the same sequence if we already did recently.
7214 if time.Since(time.Unix(0, p.ts)) < 2*time.Second {
7215 return p.last, false
7216 }
7217 // If we're about to use the cached value, and we knew it was last before,
7218 // quickly check that we don't have more remaining messages for the subject now.
7219 // Which means we are not the last anymore and must reset to not remove later data.
7220 if p.last {
7221 msgs := fs.subjectsTotalsLocked(subj)[subj]
7222 numPending := fs.sdm.totals[subj]
7223 if remaining := msgs - numPending; remaining > 0 {
7224 p.last = false
7225 }
7226 }
7227 fs.sdm.pending[seq] = SDMBySeq{p.last, time.Now().UnixNano()}
7228 return p.last, true
7229 }
7230
7231 msgs := fs.subjectsTotalsLocked(subj)[subj]
7232 if msgs == 0 {
7233 return false, true
7234 }
7235 numPending := fs.sdm.totals[subj]
7236 remaining := msgs - numPending
7237 return fs.sdm.trackPending(seq, subj, remaining == 1), true
7238 }
7239
7240 func (fs *fileStore) handleRemovalOrSdm(seq uint64, subj string, sdm bool, sdmTTL int64) {
7241 if sdm {
7242 var _hdr [128]byte
7243 hdr := fmt.Appendf(
7244 _hdr[:0],
7245 "NATS/1.0\r\n%s: %s\r\n%s: %s\r\n%s: %s\r\n\r\n",
7246 JSMarkerReason, JSMarkerReasonMaxAge,
7247 JSMessageTTL, time.Duration(sdmTTL)*time.Second,
7248 JSMsgRollup, JSMsgRollupSubject,
7249 )
7250 msg := &inMsg{
7251 subj: subj,
7252 hdr: hdr,
7253 }
7254 fs.pmsgcb(msg)
7255 } else {
7256 fs.rmcb(seq)
7257 }
7258 }
7259
7260 // Will run through scheduled messages.
7261 func (fs *fileStore) runMsgScheduling() {
7262 // TODO: Not great that we're holding the lock here, but the timed hash wheel and message scheduling isn't thread-safe.
7263 fs.mu.Lock()
7264 defer fs.mu.Unlock()
7265
7266 // If scheduling is enabled, but handler isn't set up yet. Try again later.
7267 if fs.scheduling == nil {
7268 return
7269 }
7270 if fs.pmsgcb == nil {
7271 fs.scheduling.resetTimer()
7272 return
7273 }
7274 fs.scheduling.running = true
7275
7276 scheduledMsgs := fs.scheduling.getScheduledMessages(
7277 func(seq uint64, smv *StoreMsg) *StoreMsg {
7278 sm, _ := fs.msgForSeqLocked(seq, smv, false)
7279 return sm
7280 },
7281 func(subj string, smv *StoreMsg) *StoreMsg {
7282 sm, _ := fs.loadLastLocked(subj, smv)
7283 return sm
7284 },
7285 )
7286 if len(scheduledMsgs) > 0 {
7287 fs.mu.Unlock()
7288 for _, msg := range scheduledMsgs {
7289 fs.pmsgcb(msg)
7290 }
7291 fs.mu.Lock()
7292 }
7293
7294 fs.scheduling.running, fs.scheduling.deadline = false, 0
7295 fs.scheduling.resetTimer()
7296 }
7297
7298 // Lock should be held.
7299 func (fs *fileStore) checkAndFlushLastBlock() error {
7300 lmb := fs.lmb
7301 if lmb == nil {
7302 return nil
7303 }
7304 lmb.mu.Lock()
7305 if err := lmb.werr; err != nil {
7306 lmb.mu.Unlock()
7307 return err
7308 }
7309
7310 if lmb.pendingWriteSizeLocked() == 0 {
7311 lmb.mu.Unlock()
7312 return nil
7313 }
7314 ld, err := lmb.flushPendingMsgsLocked()
7315 lmb.mu.Unlock()
7316 if err != nil {
7317 return err
7318 }
7319 // Since fs lock is held need to unlock the mb in case we need to rebuild state.
7320 if ld != nil {
7321 fs.rebuildStateLocked(ld)
7322 }
7323 return nil
7324 }
7325
7326 // This will check all the checksums on messages and report back any sequence numbers with errors.
7327 func (fs *fileStore) checkMsgs() (*LostStreamData, error) {
7328 fs.mu.Lock()
7329 defer fs.mu.Unlock()
7330
7331 var firstErr error
7332 storeErr := func(err error) error {
7333 fs.warn("checkMsgs: %v", err)
7334 if firstErr == nil {
7335 firstErr = err
7336 }
7337 return err
7338 }
7339
7340 if err := fs.checkAndFlushLastBlock(); err != nil {
7341 return nil, storeErr(fmt.Errorf("flush of last block failed: %w", err))
7342 }
7343
7344 // Clear any global subject state.
7345 fs.psim, fs.tsl = fs.psim.Empty(), 0
7346
7347 for _, mb := range fs.blks {
7348 // Make sure encryption loaded if needed for the block.
7349 if err := fs.loadEncryptionForMsgBlock(mb); err != nil {
7350 _ = storeErr(fmt.Errorf("loading encryption for block %d failed: %w", mb.index, err))
7351 continue
7352 }
7353 // FIXME(dlc) - check tombstones here too?
7354 ld, _, err := mb.rebuildState()
7355 if err != nil {
7356 _ = storeErr(fmt.Errorf("rebuildState for block %d failed: %w", mb.index, err))
7357 continue
7358 }
7359 if ld != nil {
7360 // Rebuild fs state too.
7361 fs.rebuildStateLocked(ld)
7362 }
7363 if err = fs.populateGlobalPerSubjectInfo(mb); err != nil {
7364 _ = storeErr(fmt.Errorf("populating per-subject info for block %d failed: %w", mb.index, err))
7365 continue
7366 }
7367 }
7368
7369 return fs.ld, firstErr
7370 }
7371
7372 // Lock should be held.
7373 func (mb *msgBlock) enableForWriting(fip bool) error {
7374 if mb == nil {
7375 return errNoMsgBlk
7376 }
7377 if mb.mfd != nil {
7378 return nil
7379 }
7380 mb.fs.dios.acquire()
7381 mfd, err := os.OpenFile(mb.mfn, os.O_CREATE|os.O_RDWR, defaultFilePerms)
7382 mb.fs.dios.release()
7383 if err != nil {
7384 return fmt.Errorf("error opening msg block file [%q]: %v", mb.mfn, err)
7385 }
7386 mb.mfd = mfd
7387
7388 // Spin up our flusher loop if needed.
7389 if !fip {
7390 mb.spinUpFlushLoopLocked()
7391 }
7392
7393 return nil
7394 }
7395
7396 // Helper function to place a delete tombstone.
7397 func (mb *msgBlock) writeTombstone(seq uint64, ts int64) error {
7398 return mb.writeMsgRecord(emptyRecordLen, seq|tbit, _EMPTY_, nil, nil, ts, true)
7399 }
7400
7401 // Helper function to place a delete tombstone without flush.
7402 // Lock should not be held.
7403 func (mb *msgBlock) writeTombstoneNoFlush(seq uint64, ts int64) error {
7404 mb.mu.Lock()
7405 defer mb.mu.Unlock()
7406 return mb.writeMsgRecordLocked(emptyRecordLen, seq|tbit, _EMPTY_, nil, nil, ts, false, false)
7407 }
7408
7409 // Will write the message record to the underlying message block.
7410 // filestore lock will be held.
7411 func (mb *msgBlock) writeMsgRecord(rl, seq uint64, subj string, mhdr, msg []byte, ts int64, flush bool) error {
7412 mb.mu.Lock()
7413 defer mb.mu.Unlock()
7414 return mb.writeMsgRecordLocked(rl, seq, subj, mhdr, msg, ts, flush, true)
7415 }
7416
7417 // Will write the message record to the underlying message block.
7418 // filestore lock will be held.
7419 // mb lock should be held.
7420 func (mb *msgBlock) writeMsgRecordLocked(rl, seq uint64, subj string, mhdr, msg []byte, ts int64, flush, kick bool) (rerr error) {
7421 // Return previous write errors immediately.
7422 if mb.werr != nil {
7423 return mb.werr
7424 }
7425 // Persist any returned errors to be used in the future.
7426 defer func() {
7427 if rerr != nil && mb.werr == nil {
7428 // Read/decode errors surfaced from existing on-disk data are not write failures.
7429 // Log and continue instead of disabling writes.
7430 if isReadErr(rerr) {
7431 mb.fs.rateLimitWarn("Ignoring non-write error: %v", rerr)
7432 assert.Unreachable("Filestore msg block encountered read error", map[string]any{
7433 "name": mb.fs.cfg.Name,
7434 "mb.index": mb.index,
7435 "err": rerr,
7436 "stack": string(debug.Stack()),
7437 })
7438 return
7439 }
7440 mb.werr = rerr
7441 assert.Unreachable("Filestore msg block encountered write error", map[string]any{
7442 "name": mb.fs.cfg.Name,
7443 "mb.index": mb.index,
7444 "err": rerr,
7445 "stack": string(debug.Stack()),
7446 })
7447 }
7448 }()
7449
7450 // Enable for writing if our mfd is not open.
7451 if mb.mfd == nil {
7452 if err := mb.enableForWriting(flush && kick); err != nil {
7453 return err
7454 }
7455 }
7456
7457 // Check if we are tracking per subject for our simple state.
7458 // Do this before changing the cache that would trigger a flush pending msgs call
7459 // if we needed to regenerate the per subject info.
7460 // Note that tombstones have no subject so will not trigger here.
7461 if len(subj) > 0 && !mb.noTrack {
7462 if err := mb.ensurePerSubjectInfoLoaded(); err != nil {
7463 return err
7464 }
7465 // Mark fss activity.
7466 mb.lsts = ats.AccessTime()
7467 if ss, ok := mb.fss.Find(stringToBytes(subj)); ok && ss != nil {
7468 ss.Msgs++
7469 ss.Last = seq
7470 ss.lastNeedsUpdate = false
7471 } else {
7472 mb.fss.Insert(stringToBytes(subj), SimpleState{Msgs: 1, First: seq, Last: seq})
7473 }
7474 }
7475
7476 // Make sure we have a cache setup. Do so after ensurePerSubjectInfoLoaded as it may
7477 // have already brought in a cache for us.
7478 if err := mb.setupWriteCache(nil); err != nil {
7479 return err
7480 }
7481
7482 // Make sure that the GC can't take away our writes by strengthening the elastic
7483 // reference. It will now stay strong until the flusher decides it is time to weaken.
7484 mb.ecache.Strengthen()
7485
7486 // Make sure we have enough space to write into. If we don't then we can pull a buffer
7487 // from the next pool size up to save us from reallocating in append() below.
7488 if nsz := len(mb.cache.buf) + int(rl); cap(mb.cache.buf) < nsz {
7489 prev := mb.cache.buf
7490 mb.cache.stopRecycle()
7491 mb.cache.buf = getMsgBlockBuf(nsz)
7492 if prev != nil {
7493 mb.cache.buf = mb.cache.buf[:copy(mb.cache.buf[:nsz], prev)]
7494 recycleMsgBlockBuf(prev)
7495 }
7496 mb.cache.registerRecycle()
7497 }
7498
7499 // Indexing
7500 index := len(mb.cache.buf)
7501
7502 // Formats
7503 // Format with no header
7504 // total_len(4) sequence(8) timestamp(8) subj_len(2) subj msg hash(8)
7505 // With headers, high bit on total length will be set.
7506 // total_len(4) sequence(8) timestamp(8) subj_len(2) subj hdr_len(4) hdr msg hash(8)
7507
7508 var le = binary.LittleEndian
7509
7510 l := uint32(rl)
7511 hasHeaders := len(mhdr) > 0
7512 if hasHeaders {
7513 l |= hbit
7514 }
7515
7516 // Reserve space for the header on the underlying buffer.
7517 mb.cache.buf = append(mb.cache.buf, make([]byte, msgHdrSize)...)
7518 hdr := mb.cache.buf[len(mb.cache.buf)-msgHdrSize : len(mb.cache.buf)]
7519 le.PutUint32(hdr[0:], l)
7520 le.PutUint64(hdr[4:], seq)
7521 le.PutUint64(hdr[12:], uint64(ts))
7522 le.PutUint16(hdr[20:], uint16(len(subj)))
7523
7524 // Now write to underlying buffer.
7525 mb.cache.buf = append(mb.cache.buf, subj...)
7526
7527 if hasHeaders {
7528 var hlen [4]byte
7529 le.PutUint32(hlen[0:], uint32(len(mhdr)))
7530 mb.cache.buf = append(mb.cache.buf, hlen[:]...)
7531 mb.cache.buf = append(mb.cache.buf, mhdr...)
7532 }
7533 mb.cache.buf = append(mb.cache.buf, msg...)
7534
7535 // Calculate hash.
7536 mb.hh.Reset()
7537 mb.hh.Write(hdr[4:20])
7538 mb.hh.Write(stringToBytes(subj))
7539 if hasHeaders {
7540 mb.hh.Write(mhdr)
7541 }
7542 mb.hh.Write(msg)
7543 checksum := mb.hh.Sum(mb.lchk[:0:highwayhash.Size64])
7544 copy(mb.lchk[0:], checksum)
7545
7546 // Update write through cache.
7547 // Write to msg record.
7548 mb.cache.buf = append(mb.cache.buf, checksum...)
7549
7550 // Set cache timestamp for last store.
7551 mb.lwts = ts
7552
7553 // Only update index and do accounting if not a delete tombstone.
7554 if seq&tbit == 0 {
7555 last := atomic.LoadUint64(&mb.last.seq)
7556 // Accounting, do this before stripping ebit, it is ebit aware.
7557 mb.updateAccounting(seq, ts, rl)
7558 // Strip ebit if set.
7559 seq = seq &^ ebit
7560 // If we have a hole due to skipping many messages, fill it.
7561 if len(mb.cache.idx) > 0 && last+1 < seq {
7562 for dseq := last + 1; dseq < seq; dseq++ {
7563 mb.cache.idx = append(mb.cache.idx, dbit)
7564 }
7565 }
7566 // Write index
7567 if mb.cache.idx = append(mb.cache.idx, uint32(index)|cbit); len(mb.cache.idx) == 1 {
7568 mb.cache.fseq = seq
7569 }
7570 } else {
7571 // If the block is empty, still adjust the accounting accordingly.
7572 tseq := seq &^ tbit
7573 if mb.msgs == 0 && tseq > atomic.LoadUint64(&mb.last.seq) {
7574 atomic.StoreUint64(&mb.last.seq, tseq)
7575 mb.last.ts = ts
7576 atomic.StoreUint64(&mb.first.seq, tseq+1)
7577 mb.first.ts = 0
7578 }
7579 // Make sure to account for tombstones in rbytes.
7580 mb.rbytes += rl
7581 }
7582
7583 fch, werr := mb.fch, mb.werr
7584 if werr != nil {
7585 return werr
7586 }
7587
7588 // If we should be flushing, or had a write error, do so here.
7589 if flush && mb.fs.fip {
7590 ld, err := mb.flushPendingMsgsLocked()
7591 if ld != nil {
7592 // We have the mb lock here, this needs the mb locks so do in its own go routine.
7593 go mb.fs.rebuildState(ld)
7594 }
7595 if err != nil {
7596 return err
7597 }
7598 } else if kick {
7599 // Kick the flusher here.
7600 kickFlusher(fch)
7601 }
7602 return nil
7603 }
7604
7605 // How many bytes pending to be written for this message block.
7606 func (mb *msgBlock) pendingWriteSize() int {
7607 if mb == nil {
7608 return 0
7609 }
7610 mb.mu.RLock()
7611 defer mb.mu.RUnlock()
7612 return mb.pendingWriteSizeLocked()
7613 }
7614
7615 // How many bytes pending to be written for this message block.
7616 func (mb *msgBlock) pendingWriteSizeLocked() int {
7617 if mb == nil {
7618 return 0
7619 }
7620 var pending int
7621 if !mb.closed && mb.mfd != nil && mb.cache != nil {
7622 pending = len(mb.cache.buf) - int(mb.cache.wp)
7623 }
7624 return pending
7625 }
7626
7627 // Try to close our FDs if we can.
7628 func (mb *msgBlock) closeFDs() error {
7629 mb.mu.Lock()
7630 defer mb.mu.Unlock()
7631 return mb.closeFDsLocked()
7632 }
7633
7634 func (mb *msgBlock) closeFDsLocked() error {
7635 if buf, _ := mb.bytesPending(); len(buf) > 0 {
7636 return errPendingData
7637 }
7638 mb.closeFDsLockedNoCheck()
7639 return nil
7640 }
7641
7642 func (mb *msgBlock) closeFDsLockedNoCheck() {
7643 if mb.mfd != nil {
7644 _ = mb.mfd.Close()
7645 mb.mfd = nil
7646 }
7647 }
7648
7649 // bytesPending returns the buffer to be used for writing to the underlying file.
7650 // This marks we are in flush and will return nil if asked again until cleared.
7651 // Lock should be held.
7652 func (mb *msgBlock) bytesPending() ([]byte, error) {
7653 if mb == nil || mb.mfd == nil {
7654 return nil, errNoPending
7655 }
7656 if mb.cache == nil {
7657 return nil, errNoCache
7658 }
7659 if len(mb.cache.buf) <= mb.cache.wp {
7660 return nil, errNoPending
7661 }
7662 buf := mb.cache.buf[mb.cache.wp:]
7663 if len(buf) == 0 {
7664 return nil, errNoPending
7665 }
7666 return buf, nil
7667 }
7668
7669 // Returns the current blkSize including deleted msgs etc.
7670 func (mb *msgBlock) blkSize() uint64 {
7671 if mb == nil {
7672 return 0
7673 }
7674 mb.mu.RLock()
7675 nb := mb.rbytes
7676 mb.mu.RUnlock()
7677 return nb
7678 }
7679
7680 // Update accounting on a write msg.
7681 // Lock should be held.
7682 func (mb *msgBlock) updateAccounting(seq uint64, ts int64, rl uint64) {
7683 isDeleted := seq&ebit != 0
7684 if isDeleted {
7685 seq = seq &^ ebit
7686 }
7687
7688 fseq := atomic.LoadUint64(&mb.first.seq)
7689 if (fseq == 0 || mb.first.ts == 0) && seq >= fseq {
7690 atomic.StoreUint64(&mb.first.seq, seq)
7691 mb.first.ts = ts
7692 }
7693 // Need atomics here for selectMsgBlock speed.
7694 atomic.StoreUint64(&mb.last.seq, seq)
7695 mb.last.ts = ts
7696 mb.rbytes += rl
7697 if !isDeleted {
7698 mb.bytes += rl
7699 mb.msgs++
7700 }
7701 }
7702
7703 // Helper to check last msg block and create new one if too big.
7704 // Lock should be held.
7705 func (fs *fileStore) checkLastBlock(rl uint64) (lmb *msgBlock, err error) {
7706 // Grab our current last message block.
7707 lmb = fs.lmb
7708 rbytes := lmb.blkSize()
7709 if lmb == nil || (rbytes > 0 && rbytes+rl > fs.fcfg.BlockSize) {
7710 if lmb, err = fs.newMsgBlockForWrite(); err != nil {
7711 return nil, err
7712 }
7713 }
7714 return lmb, nil
7715 }
7716
7717 // Lock should be held.
7718 func (fs *fileStore) writeMsgRecord(seq uint64, ts int64, subj string, hdr, msg []byte) (uint64, error) {
7719 // Get size for this message.
7720 rl := fileStoreMsgSize(subj, hdr, msg)
7721 if isFileStoreMsgTooLarge(rl) {
7722 return 0, ErrMsgTooLarge
7723 }
7724 // Grab our current last message block.
7725 mb, err := fs.checkLastBlock(rl)
7726 if err != nil {
7727 return 0, err
7728 }
7729
7730 // Mark as dirty for stream state.
7731 fs.dirty++
7732
7733 // Ask msg block to store in write through cache.
7734 err = mb.writeMsgRecord(rl, seq, subj, hdr, msg, ts, fs.fip)
7735
7736 return rl, err
7737 }
7738
7739 // For writing tombstones to our lmb. This version will enforce maximum block sizes.
7740 // Lock should be held.
7741 func (fs *fileStore) writeTombstone(seq uint64, ts int64) error {
7742 // Grab our current last message block.
7743 lmb, err := fs.checkLastBlock(emptyRecordLen)
7744 if err != nil {
7745 return err
7746 }
7747 return lmb.writeTombstone(seq, ts)
7748 }
7749
7750 // For writing tombstones to our lmb. This version will enforce maximum block sizes.
7751 // This version does not flush contents.
7752 // Lock should be held.
7753 func (fs *fileStore) writeTombstoneNoFlush(seq uint64, ts int64) error {
7754 lmb, err := fs.checkLastBlock(emptyRecordLen)
7755 if err != nil {
7756 return err
7757 }
7758 // Write tombstone without flush or kick.
7759 return lmb.writeTombstoneNoFlush(seq, ts)
7760 }
7761
7762 // Lock should be held.
7763 func (mb *msgBlock) recompressOnDiskIfNeeded() error {
7764 // If the block has been closed in the meantime, skip.
7765 if mb.closed {
7766 return nil
7767 }
7768
7769 alg := mb.fs.fcfg.Compression
7770
7771 // Open up the file block and read in the entire contents into memory.
7772 // One of two things will happen:
7773 // 1. The block will be compressed already and have a valid metadata
7774 // header, in which case we do nothing.
7775 // 2. The block will be uncompressed, in which case we will compress it
7776 // and then write it back out to disk, re-encrypting if necessary.
7777 mb.fs.dios.acquire()
7778 origBuf, err := os.ReadFile(mb.mfn)
7779 mb.fs.dios.release()
7780
7781 if err != nil {
7782 return fmt.Errorf("failed to read original block from disk: %w", err)
7783 }
7784
7785 // If the block is encrypted then we will need to decrypt it before
7786 // doing anything. We always encrypt after compressing because then the
7787 // compression can be as efficient as possible on the raw data, whereas
7788 // the encrypted ciphertext will not compress anywhere near as well.
7789 // The block encryption also covers the optional compression metadata.
7790 if err = mb.encryptOrDecryptIfNeeded(origBuf); err != nil {
7791 return err
7792 }
7793
7794 meta := &CompressionInfo{}
7795 if _, err := meta.UnmarshalMetadata(origBuf); err != nil {
7796 // An error is only returned here if there's a problem with parsing
7797 // the metadata. If the file has no metadata at all, no error is
7798 // returned and the algorithm defaults to no compression.
7799 return fmt.Errorf("failed to read existing metadata header: %w", err)
7800 }
7801 if meta.Algorithm == alg {
7802 // The block is already compressed with the chosen algorithm so there
7803 // is nothing else to do. This is not a common case, it is here only
7804 // to ensure we don't do unnecessary work in case something asked us
7805 // to recompress an already compressed block with the same algorithm.
7806 return nil
7807 } else if alg != NoCompression {
7808 // The block is already compressed using some algorithm, so we need
7809 // to decompress the block using the existing algorithm before we can
7810 // recompress it with the new one.
7811 if origBuf, err = meta.Algorithm.Decompress(origBuf); err != nil {
7812 return fmt.Errorf("failed to decompress original block: %w", err)
7813 }
7814 }
7815
7816 return mb.atomicOverwriteFile(origBuf, true)
7817 }
7818
7819 // Lock should be held.
7820 func (mb *msgBlock) atomicOverwriteFile(buf []byte, allowCompress bool) error {
7821 if mb.mfd != nil {
7822 mb.closeFDsLockedNoCheck()
7823 defer mb.enableForWriting(mb.fs.fip)
7824 }
7825
7826 origFN := mb.mfn // The original message block on disk.
7827 tmpFN := mb.mfn + blkTmpSuffix // The new block will be written here.
7828
7829 // Rather than modifying the existing block on disk (which is a dangerous
7830 // operation if something goes wrong), create a new temporary file. We will
7831 // write out the new block here and then swap the files around afterwards
7832 // once everything else has succeeded correctly.
7833 mb.fs.dios.acquire()
7834 tmpFD, err := os.OpenFile(tmpFN, os.O_CREATE|os.O_TRUNC|os.O_WRONLY, defaultFilePerms)
7835 mb.fs.dios.release()
7836
7837 if err != nil {
7838 return fmt.Errorf("failed to create temporary file: %w", err)
7839 }
7840
7841 errorCleanup := func(err error) error {
7842 _ = tmpFD.Close()
7843 _ = os.Remove(tmpFN)
7844 return err
7845 }
7846
7847 alg := NoCompression
7848 if calg := mb.fs.fcfg.Compression; calg != NoCompression && allowCompress {
7849 alg = calg
7850 // The original buffer at this point is uncompressed, so we will now compress
7851 // it if needed. Note that if the selected algorithm is NoCompression, the
7852 // Compress function will just return the input buffer unmodified.
7853 originalSize := len(buf)
7854 if buf, err = alg.Compress(buf); err != nil {
7855 return errorCleanup(fmt.Errorf("failed to compress block: %w", err))
7856 }
7857
7858 // We only need to write out the metadata header if compression is enabled.
7859 // If we're trying to uncompress the file on disk at this point, don't bother
7860 // writing metadata.
7861 meta := &CompressionInfo{
7862 Algorithm: alg,
7863 OriginalSize: uint64(originalSize),
7864 }
7865 buf = append(meta.MarshalMetadata(), buf...)
7866 }
7867
7868 // Re-encrypt the block if necessary.
7869 if err = mb.encryptOrDecryptIfNeeded(buf); err != nil {
7870 return errorCleanup(err)
7871 }
7872
7873 // Write the new block data (which might be compressed or encrypted) to the
7874 // temporary file.
7875 if n, err := tmpFD.Write(buf); err != nil {
7876 return errorCleanup(fmt.Errorf("failed to write to temporary file: %w", err))
7877 } else if n != len(buf) {
7878 return errorCleanup(fmt.Errorf("short write to temporary file (%d != %d)", n, len(buf)))
7879 }
7880 if err := tmpFD.Sync(); err != nil {
7881 return errorCleanup(fmt.Errorf("failed to sync temporary file: %w", err))
7882 }
7883 if err := tmpFD.Close(); err != nil {
7884 return errorCleanup(fmt.Errorf("failed to close temporary file: %w", err))
7885 }
7886
7887 // Now replace the original file with the newly updated temp file.
7888 if err := os.Rename(tmpFN, origFN); err != nil {
7889 return fmt.Errorf("failed to move temporary file into place: %w", err)
7890 }
7891
7892 // Since the message block might be retained in memory, make sure the
7893 // compression algorithm is up-to-date, since this will be needed when
7894 // compacting or truncating.
7895 mb.cmp = alg
7896
7897 // Also update rbytes
7898 mb.rbytes = uint64(len(buf))
7899
7900 return nil
7901 }
7902
7903 // Lock should be held.
7904 func (mb *msgBlock) decompressIfNeeded(buf []byte) ([]byte, error) {
7905 var meta CompressionInfo
7906 if n, err := meta.UnmarshalMetadata(buf); err != nil {
7907 // There was a problem parsing the metadata header of the block.
7908 // If there's no metadata header, an error isn't returned here,
7909 // we will instead just use default values of no compression.
7910 return nil, err
7911 } else if n == 0 {
7912 // There were no metadata bytes, so we assume the block is not
7913 // compressed and return it as-is.
7914 return buf, nil
7915 } else {
7916 // Metadata was present so it's quite likely the block contents
7917 // are compressed. If by any chance the metadata claims that the
7918 // block is uncompressed, then the input slice is just returned
7919 // unmodified.
7920 return meta.Algorithm.Decompress(buf[n:])
7921 }
7922 }
7923
7924 // Lock should be held.
7925 func (mb *msgBlock) encryptOrDecryptIfNeeded(buf []byte) error {
7926 if mb.bek != nil && len(buf) > 0 {
7927 bek, err := genBlockEncryptionKey(mb.fs.fcfg.Cipher, mb.seed, mb.nonce)
7928 if err != nil {
7929 return err
7930 }
7931 mb.bek = bek
7932 mb.bek.XORKeyStream(buf, buf)
7933 }
7934 return nil
7935 }
7936
7937 // Lock should be held.
7938 func (mb *msgBlock) ensureRawBytesLoaded() error {
7939 if mb.rbytes > 0 {
7940 return nil
7941 }
7942 f, err := mb.openBlock()
7943 if err != nil {
7944 return err
7945 }
7946 defer f.Close()
7947 if fi, err := f.Stat(); fi != nil && err == nil {
7948 mb.rbytes = uint64(fi.Size())
7949 } else {
7950 return err
7951 }
7952 return nil
7953 }
7954
7955 // Lock should be held.
7956 func (mb *msgBlock) syncFile() error {
7957 mb.fs.dios.acquire()
7958 defer mb.fs.dios.release()
7959 fd, didOpen := mb.mfd, false
7960 if fd == nil {
7961 var err error
7962 fd, err = os.OpenFile(mb.mfn, os.O_RDWR, defaultFilePerms)
7963 if err != nil {
7964 if os.IsNotExist(err) {
7965 return nil
7966 }
7967 return err
7968 }
7969 didOpen = true
7970 }
7971 if err := fd.Sync(); err != nil {
7972 // Close fd if we opened it, but ignore its error since sync takes precedence.
7973 if didOpen {
7974 _ = fd.Close()
7975 }
7976 return err
7977 }
7978 if didOpen {
7979 return fd.Close()
7980 }
7981 return nil
7982 }
7983
7984 // Sync msg and index files as needed. This is called from a timer.
7985 func (fs *fileStore) syncBlocks() {
7986 if fs.isClosed() {
7987 return
7988 }
7989 fs.mu.Lock()
7990 if err := fs.werr; err != nil {
7991 fs.mu.Unlock()
7992 return
7993 }
7994 blks := append([]*msgBlock(nil), fs.blks...)
7995 lmb, firstMoved, firstSeq := fs.lmb, fs.firstMoved, fs.state.FirstSeq
7996 // Clear first moved.
7997 fs.firstMoved = false
7998 fs.mu.Unlock()
7999
8000 storeFsWerr := func(err error) {
8001 fs.mu.Lock()
8002 defer fs.mu.Unlock()
8003 fs.setWriteErr(err)
8004 }
8005
8006 var fsDmap *interiorDeletes
8007
8008 var markDirty bool
8009 var needDirSync bool
8010 for _, mb := range blks {
8011 // Do actual sync. Hold lock for consistency.
8012 mb.mu.Lock()
8013 if mb.closed {
8014 mb.mu.Unlock()
8015 continue
8016 }
8017 // Bubble up an individual block error into the broader filestore.
8018 if err := mb.werr; err != nil {
8019 mb.mu.Unlock()
8020 storeFsWerr(err)
8021 continue
8022 }
8023 // See if we can close FDs due to being idle.
8024 if mb.mfd != nil && mb.sinceLastWriteActivity() > closeFDsIdle && mb.pendingWriteSizeLocked() == 0 {
8025 if err := mb.dirtyCloseWithRemove(false); err != nil {
8026 mb.mu.Unlock()
8027 storeFsWerr(err)
8028 continue
8029 }
8030 }
8031 // If our first has moved and we are set to noCompact (which is from tombstones),
8032 // clear so that we might cleanup tombstones.
8033 if firstMoved && mb.noCompact {
8034 mb.noCompact = false
8035 }
8036 // Check if we should compact here as well.
8037 // Do not compact last mb.
8038 var needsCompact bool
8039 if mb != lmb && mb.ensureRawBytesLoaded() == nil && mb.shouldCompactSync() {
8040 needsCompact = true
8041 markDirty = true
8042 }
8043
8044 // Flush anything that may be pending.
8045 if _, err := mb.flushPendingMsgsLocked(); err != nil {
8046 mb.mu.Unlock()
8047 storeFsWerr(err)
8048 continue
8049 }
8050 // Check if we need to sync. We will not hold lock during actual sync.
8051 needSync := mb.needSync
8052 needKeySync, kfn := mb.needKeySync, mb.kfn
8053
8054 // Reset. Because we let go of the lock, we could write new data to this mb which might or
8055 // might not be synced later if we would've reset after letting go of the lock.
8056 mb.needSync = false
8057 mb.needKeySync = false
8058 mb.mu.Unlock()
8059
8060 // Check if we should compact here.
8061 // Need to hold fs lock in case we reference psim when loading in the mb and we may remove this block if truly empty.
8062 if needsCompact {
8063 // Load a delete map containing only interior deletes.
8064 // This is used when compacting to know if tombstones are still relevant,
8065 // and if not they can be compacted.
8066 if fsDmap == nil {
8067 fsDmap = deleteMap(blks)
8068 }
8069 fs.mu.RLock()
8070 mb.mu.Lock()
8071 // If the block has already been removed in the meantime, we can simply skip.
8072 if _, ok := fs.bim[mb.index]; !ok {
8073 mb.mu.Unlock()
8074 fs.mu.RUnlock()
8075 continue
8076 }
8077 err := mb.compactWithFloor(firstSeq, fsDmap)
8078 // If this compact removed all raw bytes due to tombstone cleanup, schedule to remove.
8079 shouldRemove := mb.rbytes == 0
8080 needSync = mb.needSync
8081 mb.mu.Unlock()
8082 fs.mu.RUnlock()
8083 if err != nil {
8084 storeFsWerr(err)
8085 continue
8086 }
8087 needDirSync = needDirSync || needSync || shouldRemove
8088
8089 // Check if we should remove. This will not be common, so we will re-take fs write lock here vs changing
8090 // it above which we would prefer to be a readlock such that other lookups can occur while compacting this block.
8091 if shouldRemove {
8092 fs.mu.Lock()
8093 mb.mu.Lock()
8094 err = fs.removeMsgBlock(mb)
8095 mb.mu.Unlock()
8096 fs.mu.Unlock()
8097 needSync = false
8098 if err != nil {
8099 storeFsWerr(err)
8100 continue
8101 }
8102 }
8103 }
8104
8105 // Check if we need to sync this block's key file.
8106 if needKeySync && kfn != _EMPTY_ {
8107 if err := fs.syncFileAndDir(kfn); err != nil {
8108 storeFsWerr(err)
8109 continue
8110 }
8111 }
8112
8113 // Check if we need to sync this block.
8114 if needSync {
8115 mb.mu.Lock()
8116 err := mb.syncFile()
8117 if err == nil {
8118 mb.needSync = false
8119 }
8120 mb.mu.Unlock()
8121 if err != nil {
8122 storeFsWerr(err)
8123 continue
8124 }
8125 }
8126 }
8127 if needDirSync && canFsyncDirectories {
8128 fs.dios.acquire()
8129 err := syncDir(filepath.Join(fs.fcfg.StoreDir, msgDir))
8130 fs.dios.release()
8131 if err != nil {
8132 storeFsWerr(err)
8133 }
8134 }
8135
8136 if fs.isClosed() {
8137 return
8138 }
8139 fs.mu.Lock()
8140 defer fs.mu.Unlock()
8141 fs.setSyncTimer()
8142 if markDirty {
8143 fs.dirty++
8144 }
8145
8146 // Sync state file if we are not running with sync always.
8147 if !fs.fcfg.SyncAlways {
8148 fn := filepath.Join(fs.fcfg.StoreDir, msgDir, streamStreamStateFile)
8149 var fd *os.File
8150 var err error
8151 fs.dios.acquire()
8152 fd, err = os.OpenFile(fn, os.O_RDWR, defaultFilePerms)
8153 fs.dios.release()
8154 if err != nil && !os.IsNotExist(err) {
8155 fs.setWriteErr(err)
8156 return
8157 }
8158 if fd != nil {
8159 if err = fd.Sync(); err != nil {
8160 // Close fd, but ignore its error since sync takes precedence.
8161 _ = fd.Close()
8162 fs.setWriteErr(err)
8163 return
8164 }
8165 if err = fd.Close(); err != nil {
8166 fs.setWriteErr(err)
8167 return
8168 }
8169 }
8170 }
8171 }
8172
8173 // Select the message block where this message should be found.
8174 // Return nil if not in the set.
8175 // Read lock should be held.
8176 func (fs *fileStore) selectMsgBlock(seq uint64) *msgBlock {
8177 _, mb := fs.selectMsgBlockWithIndex(seq)
8178 return mb
8179 }
8180
8181 // Lock should be held.
8182 func (fs *fileStore) selectMsgBlockWithIndex(seq uint64) (int, *msgBlock) {
8183 // Check for out of range.
8184 if seq < fs.state.FirstSeq || seq > fs.state.LastSeq || fs.state.Msgs == 0 {
8185 return -1, nil
8186 }
8187
8188 const linearThresh = 32
8189 nb := len(fs.blks) - 1
8190
8191 if nb < linearThresh {
8192 for i, mb := range fs.blks {
8193 if seq <= atomic.LoadUint64(&mb.last.seq) {
8194 return i, mb
8195 }
8196 }
8197 return -1, nil
8198 }
8199
8200 // Do traditional binary search here since we know the blocks are sorted by sequence first and last.
8201 for low, high, mid := 0, nb, nb/2; low <= high; mid = (low + high) / 2 {
8202 mb := fs.blks[mid]
8203 // Right now these atomic loads do not factor in, so fine to leave. Was considering
8204 // uplifting these to fs scope to avoid atomic load but not needed.
8205 first, last := atomic.LoadUint64(&mb.first.seq), atomic.LoadUint64(&mb.last.seq)
8206 if seq > last {
8207 low = mid + 1
8208 } else if seq < first {
8209 // A message block's first sequence can change here meaning we could find a gap.
8210 // We want to behave like above, which if inclusive (we check at start) should
8211 // always return an index and a valid mb.
8212 // If we have a gap then our seq would be > fs.blks[mid-1].last.seq
8213 if mid == 0 || seq > atomic.LoadUint64(&fs.blks[mid-1].last.seq) {
8214 return mid, mb
8215 }
8216 high = mid - 1
8217 } else {
8218 return mid, mb
8219 }
8220 }
8221
8222 return -1, nil
8223 }
8224
8225 // Select the message block where this message should be found.
8226 // Return nil if not in the set.
8227 func (fs *fileStore) selectMsgBlockForStart(minTime time.Time) *msgBlock {
8228 fs.mu.RLock()
8229 defer fs.mu.RUnlock()
8230
8231 // Binary search for first block where last.ts >= t.
8232 i, _ := slices.BinarySearchFunc(fs.blks, minTime.UnixNano(), func(mb *msgBlock, target int64) int {
8233 mb.mu.RLock()
8234 last := mb.last.ts
8235 mb.mu.RUnlock()
8236 switch {
8237 case last < target:
8238 return -1
8239 case last > target:
8240 return 1
8241 default:
8242 return 0
8243 }
8244 })
8245
8246 // BinarySearchFunc returns an insertion point if not found.
8247 // Either way, i is the index of the first mb where mb.last.ts >= t.
8248 if i < len(fs.blks) {
8249 return fs.blks[i]
8250 }
8251 return nil
8252 }
8253
8254 // Index a raw msg buffer.
8255 // Lock should be held.
8256 func (mb *msgBlock) indexCacheBuf(buf []byte) error {
8257 var le = binary.LittleEndian
8258
8259 var alloc bool
8260 var idx []uint32
8261 var index uint32
8262
8263 mbFirstSeq := atomic.LoadUint64(&mb.first.seq)
8264 mbLastSeq := atomic.LoadUint64(&mb.last.seq)
8265
8266 // Sanity check here since we calculate size to allocate based on this.
8267 if mbFirstSeq > (mbLastSeq + 1) { // Purged state first == last + 1
8268 mb.fs.warn("indexCacheBuf corrupt state in %s: mb.first %d mb.last %d", mb.mfn, mbFirstSeq, mbLastSeq)
8269 // This would cause idxSz to wrap.
8270 return errCorruptState
8271 }
8272
8273 idxSz := mbLastSeq - mbFirstSeq + 1
8274
8275 if mb.cache == nil {
8276 mb.cache = mb.ecache.Value()
8277 }
8278 if mb.cache == nil {
8279 mb.cache = &cache{}
8280 alloc = true
8281 } else {
8282 // The buf arg already came from the pool probably, so there's
8283 // no point in reusing mb.cache.buf's underlying capacity here.
8284 // Just recycle it for the next block load.
8285 mb.cache.stopRecycle()
8286 recycleMsgBlockBuf(mb.cache.buf)
8287 }
8288 if idx = mb.cache.idx; uint64(cap(idx)) >= idxSz {
8289 idx = idx[:0]
8290 } else {
8291 idx = make([]uint32, 0, idxSz)
8292 }
8293 if !alloc {
8294 // We didn't allocate a new *cache so instead wipe the current
8295 // one, we already have reused idx if possible.
8296 *mb.cache = cache{}
8297 }
8298
8299 // Create FSS if we should track.
8300 var popFss bool
8301 if mb.fssNotLoaded() {
8302 mb.fss = stree.NewSubjectTree[SimpleState]()
8303 popFss = true
8304 }
8305 // Mark fss activity.
8306 mb.lsts = ats.AccessTime()
8307 mb.ttls = 0
8308 mb.schedules = 0
8309
8310 lbuf := uint32(len(buf))
8311 var seq, ttls, schedules uint64
8312 var sm StoreMsg // Used for finding headers
8313
8314 // To ensure the sequence keeps moving up. As well as confirming our index
8315 // is aligned with the mb's first and last sequence.
8316 var first uint64
8317 var last uint64
8318
8319 for index < lbuf {
8320 if index+msgHdrSize > lbuf {
8321 return errCorruptState
8322 }
8323 hdr := buf[index : index+msgHdrSize]
8324 rl, slen := le.Uint32(hdr[0:]), int(le.Uint16(hdr[20:]))
8325 seq = le.Uint64(hdr[4:])
8326
8327 hasHeaders := rl&hbit != 0
8328 // Clear any headers bit that could be set.
8329 rl &^= hbit
8330 shlen := slen
8331 if hasHeaders {
8332 shlen += 4
8333 }
8334 dlen := int(rl) - msgHdrSize
8335 // Do some quick sanity checks here.
8336 if dlen < 0 || shlen > (dlen-recordHashSize) || dlen > int(rl) || index+rl > lbuf || rl > rlBadThresh {
8337 mb.fs.warn("indexCacheBuf corrupt record state in %s: dlen %d slen %d index %d rl %d lbuf %d", mb.mfn, dlen, slen, index, rl, lbuf)
8338 // This means something is off.
8339 // TODO(dlc) - Add into bad list?
8340 return errCorruptState
8341 }
8342
8343 // Check for tombstones which we can skip in terms of indexing.
8344 if seq&tbit != 0 {
8345 index += rl
8346 continue
8347 }
8348
8349 // Clear any erase bits.
8350 erased := seq&ebit != 0
8351 seq = seq &^ ebit
8352
8353 // The sequence needs to only ever move up.
8354 if seq <= last {
8355 // Advance to next record.
8356 // We've already accounted for this sequence and marked it as deleted.
8357 index += rl
8358 continue
8359 }
8360 // We defer checksum checks to individual msg cache lookups to amortorize costs and
8361 // not introduce latency for first message from a newly loaded block.
8362 if seq >= mbFirstSeq {
8363 last = seq
8364
8365 // If the first sequence doesn't align with what we had in-memory, we need to rebuild.
8366 if first == 0 {
8367 first = seq
8368 if mbFirstSeq != first {
8369 return errCorruptState
8370 }
8371 }
8372
8373 // Track that we do not have holes.
8374 if slot := int(seq - mbFirstSeq); slot != len(idx) {
8375 // If we have a hole fill it.
8376 for dseq := mbFirstSeq + uint64(len(idx)); dseq < seq; dseq++ {
8377 idx = append(idx, dbit)
8378 if dseq != 0 {
8379 mb.dmap.Insert(dseq)
8380 }
8381 }
8382 }
8383 // Add to our index.
8384 idx = append(idx, index)
8385
8386 // Make sure our dmap has this entry if it was erased.
8387 // If not, that means this erased message was not accounted for in our in-memory state.
8388 if erased && seq != 0 && !mb.dmap.Exists(seq) {
8389 return errCorruptState
8390 }
8391
8392 // Handle FSS inline here.
8393 if popFss && slen > 0 && !mb.noTrack && !erased && !mb.dmap.Exists(seq) {
8394 bsubj := buf[index+msgHdrSize : index+msgHdrSize+uint32(slen)]
8395 if ss, ok := mb.fss.Find(bsubj); ok && ss != nil {
8396 ss.Msgs++
8397 ss.Last = seq
8398 ss.lastNeedsUpdate = false
8399 } else {
8400 mb.fss.Insert(bsubj, SimpleState{
8401 Msgs: 1,
8402 First: seq,
8403 Last: seq,
8404 })
8405 }
8406 }
8407
8408 // Count how many TTLs/schedules we think are in this message block.
8409 // TODO(nat): Not terribly optimal...
8410 if hasHeaders {
8411 if fsm, err := mb.msgFromBufNoCopy(buf[index:], &sm, nil); err == nil && fsm != nil {
8412 if ttl := sliceHeader(JSMessageTTL, fsm.hdr); len(ttl) > 0 {
8413 ttls++
8414 }
8415 if sched := sliceHeader(JSSchedulePattern, fsm.hdr); len(sched) > 0 {
8416 schedules++
8417 }
8418 }
8419 }
8420 }
8421 index += rl
8422 }
8423
8424 // If we ended up with a smaller or larger index, or the first/last sequence
8425 // doesn't align with what we had in-memory, we need to rebuild.
8426 if len(idx) != int(idxSz) || (first > 0 && mbFirstSeq != first) || (last > 0 && mbLastSeq != last) {
8427 return errCorruptState
8428 }
8429
8430 mb.cache.buf = buf
8431 mb.cache.idx = idx
8432 mb.cache.fseq = mbFirstSeq
8433 mb.cache.wp = int(lbuf)
8434 mb.ttls = ttls
8435 mb.schedules = schedules
8436 mb.cache.registerRecycle()
8437
8438 return nil
8439 }
8440
8441 // flushPendingMsgs writes out any messages for this message block.
8442 func (mb *msgBlock) flushPendingMsgs() error {
8443 mb.mu.Lock()
8444 fsLostData, err := mb.flushPendingMsgsLocked()
8445 fs := mb.fs
8446 mb.mu.Unlock()
8447
8448 // Signals us that we need to rebuild filestore state.
8449 if fsLostData != nil && fs != nil {
8450 // Rebuild fs state too.
8451 fs.rebuildState(fsLostData)
8452 }
8453 return err
8454 }
8455
8456 // Write function for actual data.
8457 // mb.mfd should not be nil.
8458 // Lock should held.
8459 func (mb *msgBlock) writeAt(buf []byte, woff int64) (int, error) {
8460 // Used to mock write failures.
8461 if mb.mockWriteErr {
8462 // Reset on trip.
8463 mb.mockWriteErr = false
8464 return 0, errors.New("mock write error")
8465 }
8466 mb.fs.dios.acquire()
8467 n, err := mb.mfd.WriteAt(buf, woff)
8468 mb.fs.dios.release()
8469 return n, err
8470 }
8471
8472 // flushPendingMsgsLocked writes out any messages for this message block.
8473 // Lock should be held.
8474 func (mb *msgBlock) flushPendingMsgsLocked() (*LostStreamData, error) {
8475 var weakenCache bool
8476 if mb.cache == nil {
8477 mb.cache = mb.ecache.Value()
8478 weakenCache = mb.cache != nil
8479 }
8480 if mb.cache == nil || mb.mfd == nil || mb.werr != nil {
8481 return nil, mb.werr
8482 }
8483
8484 buf, err := mb.bytesPending()
8485 // If we got an error back return here.
8486 if err != nil {
8487 // No pending data to be written is not an error.
8488 if err == errNoPending || err == errNoCache {
8489 err = nil
8490 }
8491 return nil, err
8492 }
8493
8494 wp := int64(mb.cache.wp)
8495 lob := len(buf)
8496
8497 // TODO(dlc) - Normally we would not hold the lock across I/O so we can improve performance.
8498 // We will hold to stabilize the code base, as we have had a few anomalies with partial cache errors
8499 // under heavy load.
8500
8501 // Check if we need to encrypt.
8502 if err := mb.checkAndLoadEncryption(); err != nil {
8503 return nil, err
8504 }
8505 if mb.bek != nil && lob > 0 {
8506 // Need to leave original alone.
8507 var dst []byte
8508 if lob <= defaultLargeBlockSize {
8509 dst = getMsgBlockBuf(lob)[:lob]
8510 defer recycleMsgBlockBuf(dst)
8511 } else {
8512 dst = make([]byte, lob)
8513 }
8514 mb.bek.XORKeyStream(dst, buf)
8515 buf = dst
8516 }
8517
8518 // Append new data to the message block file.
8519 for lbb := lob; lbb > 0; lbb = len(buf) {
8520 n, err := mb.writeAt(buf, wp)
8521 if err != nil {
8522 // Ignore the errors here, we'll try reloading just to figure out and return the lost data if we can.
8523 _ = mb.dirtyCloseWithRemove(false)
8524 ld, _, _ := mb.rebuildStateLocked()
8525 mb.werr = err
8526 assert.Unreachable("Filestore msg block encountered flush error", map[string]any{
8527 "name": mb.fs.cfg.Name,
8528 "mb.index": mb.index,
8529 "err": err,
8530 "stack": string(debug.Stack()),
8531 })
8532 return ld, err
8533 }
8534 // Update our write offset.
8535 wp += int64(n)
8536 buf = buf[n:]
8537 }
8538
8539 // Cache may be gone.
8540 if mb.cache == nil || mb.mfd == nil {
8541 return nil, mb.werr
8542 }
8543
8544 // Update write pointer.
8545 mb.cache.wp = int(wp)
8546
8547 // Check if we are in sync always mode.
8548 if mb.syncAlways {
8549 if err = mb.mfd.Sync(); err != nil {
8550 mb.werr = err
8551 assert.Unreachable("Filestore msg block encountered sync error", map[string]any{
8552 "name": mb.fs.cfg.Name,
8553 "mb.index": mb.index,
8554 "err": err,
8555 "stack": string(debug.Stack()),
8556 })
8557 return nil, err
8558 }
8559 } else {
8560 mb.needSync = true
8561 }
8562
8563 // Check for additional writes while we were writing to the disk.
8564 // TODO(nat): This should not be possible at present since, as above, we are
8565 // not releasing the lock during I/O operation. Therefore this will always
8566 // return zero.
8567 if mb.pendingWriteSizeLocked() > 0 {
8568 return nil, mb.werr
8569 }
8570
8571 // Check last access time. If we think the block still has read interest
8572 // then we will weaken the pointer but otherwise try to hold onto it.
8573 if ts := ats.AccessTime(); ts < mb.llts || (ts-mb.llts) <= int64(mb.cexp) {
8574 if weakenCache {
8575 mb.cache = nil
8576 mb.ecache.Weaken()
8577 }
8578 mb.resetCacheExpireTimer(0)
8579 return nil, mb.werr
8580 }
8581
8582 // If not, we'll just drop the cache altogether & recycle the buffer.
8583 mb.cache.nra = false
8584 mb.tryExpireCacheLocked()
8585 return nil, mb.werr
8586 }
8587
8588 // Lock should be held.
8589 func (mb *msgBlock) clearLoading() {
8590 mb.loading = false
8591 }
8592
8593 // Will load msgs from disk.
8594 func (mb *msgBlock) loadMsgs() error {
8595 // We hold the lock here the whole time by design.
8596 mb.mu.Lock()
8597 defer mb.mu.Unlock()
8598 return mb.loadMsgsWithLock()
8599 }
8600
8601 // Lock should be held.
8602 func (mb *msgBlock) cacheAlreadyLoaded() bool {
8603 if mb.cache == nil {
8604 mb.cache = mb.ecache.Value()
8605 }
8606 if mb.cache == nil || mb.cache.fseq == 0 || len(mb.cache.buf) == 0 {
8607 return false
8608 }
8609 numEntries := mb.msgs + uint64(mb.dmap.Size()) + (atomic.LoadUint64(&mb.first.seq) - mb.cache.fseq)
8610 return numEntries == uint64(len(mb.cache.idx))
8611 }
8612
8613 // Lock should be held.
8614 func (mb *msgBlock) cacheNotLoaded() bool {
8615 return !mb.cacheAlreadyLoaded()
8616 }
8617
8618 // Report if our fss is not loaded.
8619 // Lock should be held.
8620 func (mb *msgBlock) fssNotLoaded() bool {
8621 return mb.fss == nil && !mb.noTrack
8622 }
8623
8624 // Wrap openBlock for the gated semaphore processing.
8625 // Lock should be held
8626 func (mb *msgBlock) openBlock() (*os.File, error) {
8627 // Gate with concurrent IO semaphore.
8628 mb.fs.dios.acquire()
8629 f, err := os.Open(mb.mfn)
8630 mb.fs.dios.release()
8631 return f, err
8632 }
8633
8634 // Used to load in the block contents.
8635 // Lock should be held and all conditionals satisfied prior.
8636 func (mb *msgBlock) loadBlock(buf []byte) ([]byte, error) {
8637 var f *os.File
8638 // Re-use if we have mfd open.
8639 if mb.mfd != nil {
8640 f = mb.mfd
8641 if n, err := f.Seek(0, 0); n != 0 || err != nil {
8642 f = nil
8643 mb.closeFDsLockedNoCheck()
8644 }
8645 }
8646 if f == nil {
8647 var err error
8648 f, err = mb.openBlock()
8649 if err != nil {
8650 if os.IsNotExist(err) {
8651 err = errNoBlkData
8652 }
8653 return nil, err
8654 }
8655 defer f.Close()
8656 }
8657
8658 var sz int
8659 if info, err := f.Stat(); err == nil {
8660 sz64 := info.Size()
8661 if int64(int(sz64)) == sz64 {
8662 sz = int(sz64)
8663 } else {
8664 return nil, errMsgBlkTooBig
8665 }
8666 }
8667
8668 if buf == nil || cap(buf) < sz {
8669 // getMsgBlockBuf will try to return a slice that fits from the
8670 // buffer pool, but if by chance `sz` is greater than the maximum
8671 // large block size, it'll return a new slice to fit regardless.
8672 buf = getMsgBlockBuf(sz)
8673 }
8674
8675 mb.fs.dios.acquire()
8676 n, err := io.ReadFull(f, buf[:sz])
8677 mb.fs.dios.release()
8678 // On success capture raw bytes size.
8679 if err == nil {
8680 mb.rbytes = uint64(n)
8681 }
8682 return buf[:n], err
8683 }
8684
8685 // Lock should be held.
8686 func (mb *msgBlock) loadMsgsWithLock() error {
8687 if err := mb.checkAndLoadEncryption(); err != nil {
8688 return err
8689 }
8690
8691 // Check to see if we are loading already.
8692 if mb.loading {
8693 return nil
8694 }
8695
8696 // Set loading status.
8697 mb.loading = true
8698 defer mb.clearLoading()
8699
8700 var nchecks int
8701
8702 checkCache:
8703 nchecks++
8704 if nchecks > 8 {
8705 return errNoCache
8706 }
8707
8708 // Check to see if we have a full cache.
8709 if mb.cacheAlreadyLoaded() {
8710 return nil
8711 }
8712
8713 mb.llts = ats.AccessTime()
8714
8715 // FIXME(dlc) - We could be smarter here.
8716 if buf, _ := mb.bytesPending(); len(buf) > 0 {
8717 ld, err := mb.flushPendingMsgsLocked()
8718 if ld != nil && mb.fs != nil {
8719 // We do not know if fs is locked or not at this point.
8720 // This should be an exceptional condition so do so in Go routine.
8721 go mb.fs.rebuildState(ld)
8722 }
8723 if err != nil {
8724 return err
8725 }
8726 goto checkCache
8727 }
8728
8729 // Load in the whole block.
8730 // We want to hold the mb lock here to avoid any changes to state.
8731 buf, err := mb.loadBlock(nil)
8732 if err != nil {
8733 mb.fs.warn("loadBlock error: %v", err)
8734 if err == errNoBlkData {
8735 if ld, _, _ := mb.rebuildStateLocked(); ld != nil {
8736 // Rebuild fs state too.
8737 go mb.fs.rebuildState(ld)
8738 }
8739 }
8740 return err
8741 }
8742
8743 // Check if we need to decrypt.
8744 if err = mb.encryptOrDecryptIfNeeded(buf); err != nil {
8745 return err
8746 }
8747 // Check for compression.
8748 if buf, err = mb.decompressIfNeeded(buf); err != nil {
8749 return err
8750 }
8751
8752 if err := mb.indexCacheBuf(buf); err != nil {
8753 if err == errCorruptState {
8754 var ld *LostStreamData
8755 ld, _, err = mb.rebuildStateLocked()
8756 // We do not know if fs is locked or not at this point.
8757 // This should be an exceptional condition so do so in Go routine.
8758 // Always rebuild the filestore's state if indexing fails, even if no data was lost,
8759 // our in-memory state was stale in that case.
8760 go mb.fs.rebuildState(ld)
8761 }
8762 if err != nil {
8763 return err
8764 }
8765 goto checkCache
8766 }
8767
8768 if len(buf) > 0 {
8769 mb.cloads++
8770 mb.startCacheExpireTimer()
8771 }
8772
8773 // Update the cache pointer since we cleared & rebuilt.
8774 mb.ecache.Set(mb.cache)
8775
8776 return nil
8777 }
8778
8779 // Fetch a message from this block, possibly reading in and caching the messages.
8780 // We assume the block was selected and is correct, so we do not do range checks.
8781 // Lock should not be held.
8782 func (mb *msgBlock) fetchMsg(seq uint64, sm *StoreMsg) (*StoreMsg, bool, error) {
8783 mb.mu.Lock()
8784 defer mb.mu.Unlock()
8785 defer mb.finishedWithCache()
8786 return mb.fetchMsgEx(seq, sm, true)
8787 }
8788
8789 // Fetch a message from this block, possibly reading in and caching the messages.
8790 // We assume the block was selected and is correct, so we do not do range checks.
8791 // We will not copy the msg data, the returned StoreMsg's subj/hdr/msg/buf are aliased
8792 // into mb.cache.buf and are only safe to read while mb.mu is held.
8793 func (mb *msgBlock) fetchMsgNoCopyLocked(seq uint64, sm *StoreMsg) (*StoreMsg, bool, error) {
8794 return mb.fetchMsgEx(seq, sm, false)
8795 }
8796
8797 // Fetch a message from this block, possibly reading in and caching the messages.
8798 // We assume the block was selected and is correct, so we do not do range checks.
8799 // We will copy the msg data based on doCopy boolean.
8800 // Lock should be held.
8801 func (mb *msgBlock) fetchMsgEx(seq uint64, sm *StoreMsg, doCopy bool) (*StoreMsg, bool, error) {
8802 fseq, lseq := atomic.LoadUint64(&mb.first.seq), atomic.LoadUint64(&mb.last.seq)
8803 if seq < fseq || seq > lseq {
8804 return nil, false, ErrStoreMsgNotFound
8805 }
8806
8807 // See if we can short circuit if we already know msg deleted.
8808 if mb.dmap.Exists(seq) {
8809 // Update for scanning like cacheLookup would have.
8810 llseq := mb.llseq
8811 if mb.llseq == 0 || seq < mb.llseq || seq == mb.llseq+1 || seq == mb.llseq-1 {
8812 mb.llseq = seq
8813 }
8814 expireOk := (seq == lseq && llseq == seq-1) || (seq == fseq && llseq == seq+1)
8815 return nil, expireOk, errDeletedMsg
8816 }
8817
8818 if mb.cacheNotLoaded() {
8819 if err := mb.loadMsgsWithLock(); err != nil {
8820 return nil, false, err
8821 }
8822 }
8823 llseq := mb.llseq
8824
8825 fsm, err := mb.cacheLookupEx(seq, sm, doCopy)
8826 if err != nil {
8827 return nil, false, err
8828 }
8829 expireOk := (seq == lseq && llseq == seq-1) || (seq == fseq && llseq == seq+1)
8830 return fsm, expireOk, nil
8831 }
8832
8833 var (
8834 errNoCache = errors.New("no message cache")
8835 errDeletedMsg = errors.New("deleted message")
8836 errPartialCache = errors.New("partial cache")
8837 errNoPending = errors.New("message block does not have pending data")
8838 errNotReadable = errors.New("storage directory not readable")
8839 errCorruptState = errors.New("corrupt state file")
8840 errPriorState = errors.New("prior state file")
8841 errPendingData = errors.New("pending data still present")
8842 errNoEncryption = errors.New("encryption not enabled")
8843 errBadKeySize = errors.New("encryption bad key size")
8844 errKeyInvalid = errors.New("unable to recover keys")
8845 errNoMsgBlk = errors.New("no message block")
8846 errMsgBlkTooBig = errors.New("message block size exceeded int capacity")
8847 errUnknownCipher = errors.New("unknown cipher")
8848 errNoMainKey = errors.New("encrypted store encountered with no main key")
8849 errNoBlkData = errors.New("message block data missing")
8850 errStateTooBig = errors.New("store state too big for optional write")
8851 )
8852
8853 type (
8854 errBadMsg struct{ fn, detail string }
8855 )
8856
8857 func (e errBadMsg) Error() string {
8858 if e.detail != _EMPTY_ {
8859 return fmt.Sprintf("malformed or corrupt message in %s: %s", filepath.Base(e.fn), e.detail)
8860 }
8861 return fmt.Sprintf("malformed or corrupt message in %s", filepath.Base(e.fn))
8862 }
8863
8864 const (
8865 // "Checksum bit" is used in "mb.cache.idx" for marking messages that have had their checksums checked.
8866 cbit = 1 << 31
8867 // "Delete bit" is used in "mb.cache.idx" to mark an index as deleted and non-existent.
8868 dbit = 1 << 30
8869 // "Header bit" is used in "rl" to signal a message record with headers.
8870 hbit = 1 << 31
8871 // "Erase bit" is used in "seq" for marking erased messages sequences.
8872 ebit = 1 << 63
8873 // "Tombstone bit" is used in "seq" for marking tombstone sequences.
8874 tbit = 1 << 62
8875 )
8876
8877 // Will do a lookup from cache.
8878 // This will copy the msg from the cache.
8879 // Lock should be held.
8880 func (mb *msgBlock) cacheLookup(seq uint64, sm *StoreMsg) (*StoreMsg, error) {
8881 return mb.cacheLookupEx(seq, sm, true)
8882 }
8883
8884 // Will do a lookup from cache.
8885 // This will NOT copy the msg from the cache.
8886 // Lock should be held.
8887 func (mb *msgBlock) cacheLookupNoCopy(seq uint64, sm *StoreMsg) (*StoreMsg, error) {
8888 return mb.cacheLookupEx(seq, sm, false)
8889 }
8890
8891 // Will do a lookup from cache.
8892 // Lock should be held.
8893 func (mb *msgBlock) cacheLookupEx(seq uint64, sm *StoreMsg, doCopy bool) (*StoreMsg, error) {
8894 fseq, lseq := atomic.LoadUint64(&mb.first.seq), atomic.LoadUint64(&mb.last.seq)
8895 switch {
8896 case lseq == fseq-1:
8897 // The block is empty, no messages have been written yet. This works because
8898 // newMsgBlockForWrite sets fseq=fs.State.LastSeq+1 and lseq=fs.State.LastSeq.
8899 return nil, ErrStoreMsgNotFound
8900 case seq < fseq || seq > lseq:
8901 // Sequence is out of range for this block.
8902 return nil, ErrStoreMsgNotFound
8903 }
8904
8905 // The llseq signals us when we can expire a cache at the end of a linear scan.
8906 // We want to only update when we know the last reads (multiple consumers) are sequential.
8907 // We want to account for forwards and backwards linear scans.
8908 if mb.llseq == 0 || seq < mb.llseq || seq == mb.llseq+1 || seq == mb.llseq-1 {
8909 mb.llseq = seq
8910 }
8911
8912 // If we have a delete map check it.
8913 if mb.dmap.Exists(seq) {
8914 mb.llts = ats.AccessTime()
8915 return nil, errDeletedMsg
8916 }
8917
8918 // Detect no cache loaded.
8919 if mb.cache == nil {
8920 mb.cache = mb.ecache.Value()
8921 }
8922 if mb.cache == nil || mb.cache.fseq == 0 || len(mb.cache.idx) == 0 || len(mb.cache.buf) == 0 {
8923 var reason string
8924 if mb.cache == nil {
8925 reason = "no cache"
8926 } else if mb.cache.fseq == 0 {
8927 reason = "fseq is 0"
8928 } else if len(mb.cache.idx) == 0 {
8929 reason = "no idx present"
8930 } else {
8931 reason = "cache buf empty"
8932 }
8933 mb.fs.warn("Cache lookup for sequence %d in block %d detected no cache: %s", seq, mb.index, reason)
8934 if mb.cache != nil {
8935 mb.tryForceExpireCacheLocked()
8936 }
8937 return nil, errNoCache
8938 }
8939 // Check partial cache status.
8940 if seq < mb.cache.fseq {
8941 mb.fs.warn("Partial cache: seq %d is less than cache fseq %d", seq, mb.cache.fseq)
8942 return nil, errPartialCache
8943 }
8944
8945 bi, _, hashChecked, err := mb.slotInfo(int(seq - mb.cache.fseq))
8946 if err != nil {
8947 return nil, err
8948 }
8949
8950 // Update cache activity.
8951 mb.llts = ats.AccessTime()
8952
8953 li := int(bi)
8954 if li >= len(mb.cache.buf) {
8955 mb.fs.warn("Partial cache: slot index %d is less than cache buffer len %d", li, len(mb.cache.buf))
8956 return nil, errPartialCache
8957 }
8958 buf := mb.cache.buf[li:]
8959
8960 // We use the high bit to denote we have already checked the checksum.
8961 var hh *highwayhash.Digest64
8962 if !hashChecked {
8963 hh = mb.hh // This will force the hash check in msgFromBuf.
8964 }
8965
8966 // Parse from the raw buffer.
8967 fsm, err := mb.msgFromBufEx(buf, sm, hh, doCopy)
8968 if err != nil || fsm == nil {
8969 return nil, err
8970 }
8971
8972 // Deleted messages that are decoded return a 0 for sequence.
8973 if fsm.seq == 0 {
8974 return nil, errDeletedMsg
8975 }
8976
8977 if seq != fsm.seq { // See TestFileStoreInvalidIndexesRebuilt.
8978 mb.clearCacheAndOffset()
8979 return nil, fmt.Errorf("sequence numbers for cache load did not match, %d vs %d", seq, fsm.seq)
8980 }
8981
8982 // Clear the check bit here after we know all is good.
8983 if !hashChecked {
8984 mb.cache.idx[seq-mb.cache.fseq] = (bi | cbit)
8985 }
8986
8987 return fsm, nil
8988 }
8989
8990 // Used when we are checking if discarding a message due to max msgs per subject will give us
8991 // enough room for a max bytes condition.
8992 // Lock should be already held.
8993 func (fs *fileStore) sizeForSeq(seq uint64) int {
8994 if seq == 0 {
8995 return 0
8996 }
8997 var smv StoreMsg
8998 if mb := fs.selectMsgBlock(seq); mb != nil {
8999 mb.mu.Lock()
9000 sm, _, _ := mb.fetchMsgNoCopyLocked(seq, &smv)
9001 var sz int
9002 if sm != nil {
9003 sz = int(fileStoreMsgSize(sm.subj, sm.hdr, sm.msg))
9004 }
9005 mb.finishedWithCache()
9006 mb.mu.Unlock()
9007 return sz
9008 }
9009 return 0
9010 }
9011
9012 // Will return message for the given sequence number.
9013 // This will be returned to external callers.
9014 func (fs *fileStore) msgForSeq(seq uint64, sm *StoreMsg) (*StoreMsg, error) {
9015 return fs.msgForSeqLocked(seq, sm, true)
9016 }
9017
9018 // Will return message for the given sequence number.
9019 func (fs *fileStore) msgForSeqLocked(seq uint64, sm *StoreMsg, needFSLock bool) (*StoreMsg, error) {
9020 if fs.isClosed() {
9021 return nil, ErrStoreClosed
9022 }
9023 // TODO(dlc) - Since Store, Remove, Skip all hold the write lock on fs this will
9024 // be stalled. Need another lock if want to happen in parallel.
9025 if needFSLock {
9026 fs.mu.RLock()
9027 }
9028 // Indicates we want first msg.
9029 if seq == 0 {
9030 seq = fs.state.FirstSeq
9031 }
9032 // Make sure to snapshot here.
9033 mb, lseq := fs.selectMsgBlock(seq), fs.state.LastSeq
9034 if needFSLock {
9035 fs.mu.RUnlock()
9036 }
9037
9038 if mb == nil {
9039 var err = ErrStoreEOF
9040 if seq <= lseq {
9041 err = ErrStoreMsgNotFound
9042 }
9043 return nil, err
9044 }
9045
9046 fsm, expireOk, err := mb.fetchMsg(seq, sm)
9047 if err != nil {
9048 return nil, err
9049 }
9050
9051 // We detected a linear scan and access to the last message.
9052 // If we are not the last message block we can try to expire the cache.
9053 if expireOk {
9054 mb.tryForceExpireCache()
9055 }
9056
9057 return fsm, nil
9058 }
9059
9060 // Internal function to return msg parts from a raw buffer.
9061 // Raw buffer will be copied into sm.
9062 // Lock should be held.
9063 func (mb *msgBlock) msgFromBuf(buf []byte, sm *StoreMsg, hh *highwayhash.Digest64) (*StoreMsg, error) {
9064 return mb.msgFromBufEx(buf, sm, hh, true)
9065 }
9066
9067 // Internal function to return msg parts from a raw buffer.
9068 // Raw buffer will NOT be copied into sm.
9069 // Only use for internal use, any message that is passed to upper layers should use mb.msgFromBuf.
9070 // Lock should be held.
9071 func (mb *msgBlock) msgFromBufNoCopy(buf []byte, sm *StoreMsg, hh *highwayhash.Digest64) (*StoreMsg, error) {
9072 return mb.msgFromBufEx(buf, sm, hh, false)
9073 }
9074
9075 // Internal function to return msg parts from a raw buffer.
9076 // copy boolean will determine if we make a copy or not.
9077 // Lock should be held.
9078 func (mb *msgBlock) msgFromBufEx(buf []byte, sm *StoreMsg, hh *highwayhash.Digest64, doCopy bool) (*StoreMsg, error) {
9079 if len(buf) < emptyRecordLen {
9080 return nil, errBadMsg{mb.mfn, "record too short"}
9081 }
9082 var le = binary.LittleEndian
9083
9084 hdr := buf[:msgHdrSize]
9085 rl := le.Uint32(hdr[0:])
9086 hasHeaders := rl&hbit != 0
9087 rl &^= hbit // clear header bit
9088 dlen := int(rl) - msgHdrSize
9089 slen := int(le.Uint16(hdr[20:]))
9090
9091 shlen := slen
9092 if hasHeaders {
9093 shlen += 4
9094 }
9095 // Simple sanity check.
9096 if dlen < 0 || shlen > (dlen-recordHashSize) || dlen > int(rl) || int(rl) > len(buf) || rl > rlBadThresh {
9097 return nil, errBadMsg{mb.mfn, fmt.Sprintf("sanity check failed (dlen %d slen %d rl %d buf %d)", dlen, slen, rl, buf)}
9098 }
9099 data := buf[msgHdrSize : msgHdrSize+dlen]
9100 // Do checksum tests here if requested.
9101 if hh != nil {
9102 hh.Reset()
9103 hh.Write(hdr[4:20])
9104 hh.Write(data[:slen])
9105 if hasHeaders {
9106 hh.Write(data[slen+4 : dlen-recordHashSize])
9107 } else {
9108 hh.Write(data[slen : dlen-recordHashSize])
9109 }
9110 var hb [highwayhash.Size64]byte
9111 if !bytes.Equal(hh.Sum(hb[:0]), data[len(data)-8:]) {
9112 return nil, errBadMsg{mb.mfn, "invalid checksum"}
9113 }
9114 }
9115 seq := le.Uint64(hdr[4:])
9116 if seq&ebit != 0 {
9117 seq = 0
9118 }
9119 ts := int64(le.Uint64(hdr[12:]))
9120
9121 // Create a StoreMsg if needed.
9122 if sm == nil {
9123 sm = new(StoreMsg)
9124 } else {
9125 sm.clear()
9126 }
9127 // To recycle the large blocks we can never pass back a reference, so need to copy for the upper
9128 // layers and for us to be safe to expire, and recycle, the large msgBlocks.
9129 end := dlen - 8
9130 if len(data) < end {
9131 return nil, errBadMsg{mb.mfn, "invalid data length"}
9132 }
9133
9134 if hasHeaders {
9135 if slen+4 > len(data) {
9136 return nil, errBadMsg{mb.mfn, "invalid subject length greataer than data length"}
9137 }
9138 hl := le.Uint32(data[slen:])
9139 bi := slen + 4
9140 li := bi + int(hl)
9141 if bi > end {
9142 return nil, errBadMsg{mb.mfn, "invalid buffer index"}
9143 }
9144 if doCopy {
9145 sm.buf = append(sm.buf, data[bi:end]...)
9146 } else {
9147 sm.buf = data[bi:end]
9148 }
9149 li, end = li-bi, end-bi
9150 if li > len(sm.buf) || end > len(sm.buf) {
9151 return nil, errBadMsg{mb.mfn, "invalid message length or end greater than buffer length"}
9152 }
9153 sm.hdr = sm.buf[0:li:li]
9154 sm.msg = sm.buf[li:end]
9155 } else {
9156 if slen > end {
9157 return nil, errBadMsg{mb.mfn, "invalid subject length greater than end"}
9158 }
9159 if doCopy {
9160 sm.buf = append(sm.buf, data[slen:end]...)
9161 } else {
9162 sm.buf = data[slen:end]
9163 }
9164 mlen := end - slen
9165 if mlen > len(sm.buf) {
9166 return nil, errBadMsg{mb.mfn, "invalid message length greater than buffer length"}
9167 }
9168 sm.msg = sm.buf[0:mlen]
9169 }
9170 sm.seq, sm.ts = seq, ts
9171 if slen > 0 {
9172 if slen > len(data) {
9173 return nil, errBadMsg{mb.mfn, "invalid subject length greater than data length"}
9174 }
9175 if doCopy {
9176 // Make a copy since sm.subj lifetime may last longer.
9177 sm.subj = string(data[:slen])
9178 } else {
9179 sm.subj = bytesToString(data[:slen])
9180 }
9181 }
9182
9183 return sm, nil
9184 }
9185
9186 // SubjectForSeq will return what the subject is for this sequence if found.
9187 func (fs *fileStore) SubjectForSeq(seq uint64) (string, error) {
9188 fs.mu.RLock()
9189 if seq < fs.state.FirstSeq {
9190 fs.mu.RUnlock()
9191 return _EMPTY_, ErrStoreMsgNotFound
9192 }
9193 var smv StoreMsg
9194 mb := fs.selectMsgBlock(seq)
9195 fs.mu.RUnlock()
9196 if mb != nil {
9197 mb.mu.Lock()
9198 sm, _, _ := mb.fetchMsgNoCopyLocked(seq, &smv)
9199 var subj string
9200 if sm != nil {
9201 // Copy the subject, as it's used elsewhere, and the backing cache could be reused in the meantime.
9202 subj = copyString(sm.subj)
9203 }
9204 mb.finishedWithCache()
9205 mb.mu.Unlock()
9206 if sm != nil {
9207 return subj, nil
9208 }
9209 }
9210 return _EMPTY_, ErrStoreMsgNotFound
9211 }
9212
9213 // LoadMsg will lookup the message by sequence number and return it if found.
9214 func (fs *fileStore) LoadMsg(seq uint64, sm *StoreMsg) (*StoreMsg, error) {
9215 return fs.msgForSeq(seq, sm)
9216 }
9217
9218 // loadLast will load the last message for a subject. Subject should be non empty and not ">".
9219 func (fs *fileStore) loadLast(subj string, sm *StoreMsg) (lsm *StoreMsg, err error) {
9220 if fs.isClosed() {
9221 return nil, ErrStoreClosed
9222 }
9223
9224 fs.mu.RLock()
9225 defer fs.mu.RUnlock()
9226 return fs.loadLastLocked(subj, sm)
9227 }
9228
9229 // Lock should be held.
9230 func (fs *fileStore) loadLastLocked(subj string, sm *StoreMsg) (lsm *StoreMsg, err error) {
9231 if fs.isClosed() || fs.lmb == nil {
9232 return nil, ErrStoreClosed
9233 }
9234
9235 if len(fs.blks) == 0 {
9236 return nil, ErrStoreMsgNotFound
9237 }
9238
9239 wc := subjectHasWildcard(subj)
9240 var start, stop uint32
9241
9242 // If literal subject check for presence.
9243 if wc {
9244 start = fs.lmb.index
9245 fs.psim.Match(stringToBytes(subj), func(_ []byte, psi *psi) {
9246 // Keep track of start and stop indexes for this subject.
9247 if psi.fblk < start {
9248 start = psi.fblk
9249 }
9250 if psi.lblk > stop {
9251 stop = psi.lblk
9252 }
9253 })
9254 // None matched.
9255 if stop == 0 {
9256 return nil, ErrStoreMsgNotFound
9257 }
9258 // These need to be swapped.
9259 start, stop = stop, start
9260 } else if info, ok := fs.psim.Find(stringToBytes(subj)); ok {
9261 start, stop = info.lblk, info.fblk
9262 } else {
9263 return nil, ErrStoreMsgNotFound
9264 }
9265
9266 // Walk blocks backwards.
9267 for i := start; i >= stop; i-- {
9268 mb := fs.bim[i]
9269 if mb == nil {
9270 continue
9271 }
9272 mb.mu.Lock()
9273 if err = mb.ensurePerSubjectInfoLoaded(); err != nil {
9274 mb.mu.Unlock()
9275 return nil, err
9276 }
9277 // Mark fss activity.
9278 mb.lsts = ats.AccessTime()
9279
9280 var l uint64
9281 // Optimize if subject is not a wildcard.
9282 if !wc {
9283 if ss, ok := mb.fss.Find(stringToBytes(subj)); ok && ss != nil {
9284 // Check if we need to recalculate. We only care about the last sequence.
9285 if ss.lastNeedsUpdate {
9286 // mb is already loaded into the cache so should be fast-ish.
9287 if err = mb.recalculateForSubj(subj, ss); err != nil {
9288 mb.mu.Unlock()
9289 return nil, err
9290 }
9291 }
9292 l = ss.Last
9293 }
9294 }
9295 if l == 0 {
9296 _, _, l, err = mb.filteredPendingLocked(subj, wc, atomic.LoadUint64(&mb.first.seq))
9297 if err != nil {
9298 mb.mu.Unlock()
9299 return nil, err
9300 }
9301 }
9302 needsCleanup := mb.cache == nil
9303 if l > 0 {
9304 if mb.cacheNotLoaded() {
9305 if err := mb.loadMsgsWithLock(); err != nil {
9306 if needsCleanup {
9307 mb.finishedWithCache()
9308 }
9309 mb.mu.Unlock()
9310 return nil, err
9311 }
9312 }
9313 lsm, err = mb.cacheLookup(l, sm)
9314 }
9315 if needsCleanup {
9316 mb.finishedWithCache()
9317 }
9318 mb.mu.Unlock()
9319 if l > 0 {
9320 break
9321 }
9322 }
9323 return lsm, err
9324 }
9325
9326 // LoadLastMsg will return the last message we have that matches a given subject.
9327 // The subject can be a wildcard.
9328 func (fs *fileStore) LoadLastMsg(subject string, smv *StoreMsg) (sm *StoreMsg, err error) {
9329 if subject == _EMPTY_ || subject == fwcs {
9330 sm, err = fs.msgForSeq(fs.lastSeq(), smv)
9331 } else {
9332 sm, err = fs.loadLast(subject, smv)
9333 }
9334 if sm == nil || (err != nil && err != ErrStoreClosed) {
9335 err = ErrStoreMsgNotFound
9336 }
9337 return sm, err
9338 }
9339
9340 // LoadNextMsgMulti will find the next message matching any entry in the sublist.
9341 func (fs *fileStore) LoadNextMsgMulti(sl *gsl.SimpleSublist, start uint64, smp *StoreMsg) (sm *StoreMsg, skip uint64, err error) {
9342 if fs.isClosed() {
9343 return nil, 0, ErrStoreClosed
9344 }
9345 if sl == nil || sl.MatchesFullWildcard() {
9346 return fs.LoadNextMsg(_EMPTY_, false, start, smp)
9347 }
9348 if filter, ok := sl.MatchesSingleFilter(); ok {
9349 return fs.LoadNextMsg(filter, subjectHasWildcard(filter), start, smp)
9350 }
9351 fs.mu.RLock()
9352 defer fs.mu.RUnlock()
9353
9354 if fs.state.Msgs == 0 || start > fs.state.LastSeq {
9355 return nil, fs.state.LastSeq, ErrStoreEOF
9356 }
9357 if start < fs.state.FirstSeq {
9358 start = fs.state.FirstSeq
9359 }
9360
9361 // If start is less than or equal to beginning of our stream, meaning our first call,
9362 // let's check the psim to see if we can skip ahead.
9363 if start <= fs.state.FirstSeq {
9364 var total uint64
9365 blkStart := uint32(math.MaxUint32)
9366 stree.IntersectGSL(fs.psim, sl, func(subj []byte, psi *psi) bool {
9367 total += psi.total
9368 // Keep track of start index for this subject.
9369 if psi.fblk < blkStart {
9370 blkStart = psi.fblk
9371 }
9372 return true
9373 })
9374 // Nothing available.
9375 if total == 0 {
9376 return nil, fs.state.LastSeq, ErrStoreEOF
9377 }
9378 // We can skip ahead.
9379 if mb := fs.bim[blkStart]; mb != nil {
9380 fseq := atomic.LoadUint64(&mb.first.seq)
9381 if fseq > start {
9382 start = fseq
9383 }
9384 }
9385 }
9386
9387 if bi, _ := fs.selectMsgBlockWithIndex(start); bi >= 0 {
9388 for i := bi; i < len(fs.blks); i++ {
9389 mb := fs.blks[i]
9390 if sm, expireOk, err := mb.firstMatchingMulti(sl, start, smp); err == nil {
9391 if expireOk {
9392 mb.tryForceExpireCache()
9393 }
9394 return sm, sm.seq, nil
9395 } else if err != ErrStoreMsgNotFound {
9396 return nil, 0, err
9397 } else {
9398 // Nothing found in this block. We missed, if first block (bi) check psim.
9399 // Similar to above if start <= first seq.
9400 // TODO(dlc) - For v2 track these by filter subject since they will represent filtered consumers.
9401 // We should not do this at all if we are already on the last block.
9402 if i == bi && i < len(fs.blks)-1 {
9403 nbi, err := fs.checkSkipFirstBlockMulti(sl, bi)
9404 // Nothing available.
9405 if err == ErrStoreEOF {
9406 return nil, fs.state.LastSeq, ErrStoreEOF
9407 }
9408 // See if we can jump ahead here.
9409 // Right now we can only spin on first, so if we have interior sparseness need to favor checking per block fss if loaded.
9410 // For v2 will track all blocks that have matches for psim.
9411 if nbi > i {
9412 i = nbi - 1 // For the iterator condition i++
9413 }
9414 }
9415 // Check if we can expire.
9416 if expireOk {
9417 mb.tryForceExpireCache()
9418 }
9419 }
9420 }
9421 }
9422
9423 return nil, fs.state.LastSeq, ErrStoreEOF
9424
9425 }
9426
9427 func (fs *fileStore) LoadNextMsg(filter string, wc bool, start uint64, sm *StoreMsg) (*StoreMsg, uint64, error) {
9428 if fs.isClosed() {
9429 return nil, 0, ErrStoreClosed
9430 }
9431
9432 fs.mu.RLock()
9433 defer fs.mu.RUnlock()
9434
9435 if fs.state.Msgs == 0 || start > fs.state.LastSeq {
9436 return nil, fs.state.LastSeq, ErrStoreEOF
9437 }
9438 if start < fs.state.FirstSeq {
9439 start = fs.state.FirstSeq
9440 }
9441
9442 // If start is less than or equal to beginning of our stream, meaning our first call,
9443 // let's check the psim to see if we can skip ahead.
9444 if start <= fs.state.FirstSeq {
9445 var ss SimpleState
9446 if err := fs.numFilteredPendingNoLast(filter, &ss); err != nil {
9447 return nil, 0, err
9448 }
9449 // Nothing available.
9450 if ss.Msgs == 0 {
9451 return nil, fs.state.LastSeq, ErrStoreEOF
9452 }
9453 // We can skip ahead.
9454 if ss.First > start {
9455 start = ss.First
9456 }
9457 }
9458
9459 if bi, _ := fs.selectMsgBlockWithIndex(start); bi >= 0 {
9460 for i := bi; i < len(fs.blks); i++ {
9461 mb := fs.blks[i]
9462 if sm, expireOk, err := mb.firstMatching(filter, wc, start, sm); err == nil {
9463 if expireOk {
9464 mb.tryForceExpireCache()
9465 }
9466 return sm, sm.seq, nil
9467 } else if err != ErrStoreMsgNotFound {
9468 return nil, 0, err
9469 } else {
9470 // Nothing found in this block. We missed, if first block (bi) check psim.
9471 // Similar to above if start <= first seq.
9472 // TODO(dlc) - For v2 track these by filter subject since they will represent filtered consumers.
9473 // We should not do this at all if we are already on the last block.
9474 // Also if we are a wildcard do not check if large subject space.
9475 const wcMaxSizeToCheck = 64 * 1024
9476 if i == bi && i < len(fs.blks)-1 && (!wc || fs.psim.Size() < wcMaxSizeToCheck) {
9477 nbi, err := fs.checkSkipFirstBlock(filter, wc, bi)
9478 // Nothing available.
9479 if err == ErrStoreEOF {
9480 return nil, fs.state.LastSeq, ErrStoreEOF
9481 }
9482 // See if we can jump ahead here.
9483 // Right now we can only spin on first, so if we have interior sparseness need to favor checking per block fss if loaded.
9484 // For v2 will track all blocks that have matches for psim.
9485 if nbi > i {
9486 i = nbi - 1 // For the iterator condition i++
9487 }
9488 }
9489 // Check if we can expire.
9490 if expireOk {
9491 mb.tryForceExpireCache()
9492 }
9493 }
9494 }
9495 }
9496
9497 return nil, fs.state.LastSeq, ErrStoreEOF
9498 }
9499
9500 // Find the previous matching message.
9501 // fs lock should be held.
9502 func (mb *msgBlock) prevMatching(filter string, wc bool, start uint64, sm *StoreMsg) (*StoreMsg, bool, error) {
9503 mb.mu.Lock()
9504 var updateLLTS bool
9505 defer func() {
9506 if updateLLTS {
9507 mb.llts = ats.AccessTime()
9508 }
9509 mb.finishedWithCache()
9510 mb.mu.Unlock()
9511 }()
9512
9513 end, isAll := start, filter == _EMPTY_ || filter == fwcs
9514
9515 var didLoad bool
9516 if mb.fssNotLoaded() {
9517 if err := mb.loadMsgsWithLock(); err != nil {
9518 return nil, false, err
9519 }
9520 didLoad = true
9521 }
9522 mb.lsts = ats.AccessTime()
9523
9524 if filter == _EMPTY_ {
9525 filter = fwcs
9526 wc = true
9527 }
9528
9529 if !isAll && mb.fss.Size() == 1 {
9530 if !wc {
9531 _, isAll = mb.fss.Find(stringToBytes(filter))
9532 } else {
9533 mb.fss.Match(stringToBytes(filter), func(subject []byte, _ *SimpleState) {
9534 isAll = true
9535 })
9536 }
9537 if !isAll {
9538 return nil, didLoad, ErrStoreMsgNotFound
9539 }
9540 }
9541
9542 lseq := atomic.LoadUint64(&mb.first.seq)
9543 end = min(end, atomic.LoadUint64(&mb.last.seq))
9544
9545 var isMatch func(subj string) bool
9546 if wc {
9547 _tsa, _fsa := [32]string{}, [32]string{}
9548 tsa, fsa := _tsa[:0], tokenizeSubjectIntoSlice(_fsa[:0], filter)
9549 isMatch = func(subj string) bool {
9550 tsa = tokenizeSubjectIntoSlice(tsa[:0], subj)
9551 return isSubsetMatchTokenized(tsa, fsa)
9552 }
9553 }
9554
9555 subjs := mb.fs.cfg.Subjects
9556 doLinearScan := isAll || (wc && len(subjs) == 1 && subjs[0] == filter)
9557 if !doLinearScan && wc && mb.cacheAlreadyLoaded() {
9558 doLinearScan = mb.fss.Size()*4 > int(end-lseq)
9559 }
9560
9561 if !doLinearScan {
9562 var found bool
9563 var first, last uint64
9564 if bfilter := stringToBytes(filter); wc {
9565 var ierr error
9566 mb.fss.Match(bfilter, func(bsubj []byte, ss *SimpleState) {
9567 if ierr != nil {
9568 return
9569 }
9570 if ss.firstNeedsUpdate || ss.lastNeedsUpdate {
9571 if ierr = mb.recalculateForSubj(bytesToString(bsubj), ss); ierr != nil {
9572 return
9573 }
9574 }
9575 if end < ss.First {
9576 return
9577 }
9578 if !found {
9579 found = true
9580 first, last = ss.First, min(end, ss.Last)
9581 return
9582 }
9583 first = min(first, ss.First)
9584 last = max(last, min(end, ss.Last))
9585 })
9586 if ierr != nil {
9587 return nil, false, ierr
9588 }
9589 } else if ss, _ := mb.fss.Find(bfilter); ss != nil {
9590 if ss.firstNeedsUpdate || ss.lastNeedsUpdate {
9591 if err := mb.recalculateForSubj(filter, ss); err != nil {
9592 return nil, false, err
9593 }
9594 }
9595 if end >= ss.First {
9596 found = true
9597 first, last = ss.First, min(end, ss.Last)
9598 }
9599 }
9600 if !found || first > last {
9601 return nil, didLoad, ErrStoreMsgNotFound
9602 }
9603 lseq, end = max(lseq, first), last
9604 }
9605
9606 if mb.cacheNotLoaded() {
9607 if err := mb.loadMsgsWithLock(); err != nil {
9608 return nil, false, err
9609 }
9610 didLoad = true
9611 }
9612
9613 if sm == nil {
9614 sm = new(StoreMsg)
9615 }
9616
9617 for seq := end; seq >= lseq; seq-- {
9618 if mb.dmap.Exists(seq) {
9619 updateLLTS = true
9620 continue
9621 }
9622 llseq := mb.llseq
9623 fsm, err := mb.cacheLookup(seq, sm)
9624 if err != nil {
9625 if err == errPartialCache || err == errNoCache {
9626 return nil, false, err
9627 }
9628 continue
9629 }
9630 updateLLTS = false
9631 expireOk := seq == lseq && mb.llseq != llseq && mb.llseq == seq
9632 if isAll {
9633 return fsm, expireOk, nil
9634 }
9635 if wc && isMatch(sm.subj) {
9636 return fsm, expireOk, nil
9637 } else if !wc && fsm.subj == filter {
9638 return fsm, expireOk, nil
9639 }
9640 mb.llseq = llseq
9641 }
9642
9643 return nil, didLoad, ErrStoreMsgNotFound
9644 }
9645
9646 // Will load the previous message matching the filter subject, starting at the start sequence and walking backwards.
9647 func (fs *fileStore) LoadPrevMsg(filter string, wc bool, start uint64, smp *StoreMsg) (sm *StoreMsg, skip uint64, err error) {
9648 if fs.isClosed() {
9649 return nil, 0, ErrStoreClosed
9650 }
9651
9652 fs.mu.RLock()
9653 defer fs.mu.RUnlock()
9654
9655 if fs.state.Msgs == 0 || start < fs.state.FirstSeq {
9656 return nil, fs.state.FirstSeq, ErrStoreEOF
9657 }
9658
9659 if start > fs.state.LastSeq {
9660 start = fs.state.LastSeq
9661 }
9662
9663 if bi, _ := fs.selectMsgBlockWithIndex(start); bi >= 0 {
9664 for i := bi; i >= 0; i-- {
9665 mb := fs.blks[i]
9666 if sm, expireOk, err := mb.prevMatching(filter, wc, start, smp); err == nil {
9667 if expireOk {
9668 mb.tryForceExpireCache()
9669 }
9670 return sm, sm.seq, nil
9671 } else if err != ErrStoreMsgNotFound {
9672 return nil, 0, err
9673 } else if expireOk {
9674 mb.tryForceExpireCache()
9675 }
9676 }
9677 }
9678
9679 return nil, fs.state.FirstSeq, ErrStoreEOF
9680 }
9681
9682 // LoadPrevMsgMulti will find the previous message matching any entry in the sublist.
9683 func (fs *fileStore) LoadPrevMsgMulti(sl *gsl.SimpleSublist, start uint64, smp *StoreMsg) (sm *StoreMsg, skip uint64, err error) {
9684 if fs.isClosed() {
9685 return nil, 0, ErrStoreClosed
9686 }
9687
9688 if sl == nil || sl.MatchesFullWildcard() {
9689 return fs.LoadPrevMsg(_EMPTY_, false, start, smp)
9690 }
9691 if filter, ok := sl.MatchesSingleFilter(); ok {
9692 return fs.LoadPrevMsg(filter, subjectHasWildcard(filter), start, smp)
9693 }
9694 fs.mu.RLock()
9695 defer fs.mu.RUnlock()
9696
9697 if fs.state.Msgs == 0 || start < fs.state.FirstSeq {
9698 return nil, fs.state.FirstSeq, ErrStoreEOF
9699 }
9700 if start > fs.state.LastSeq {
9701 start = fs.state.LastSeq
9702 }
9703
9704 if bi, _ := fs.selectMsgBlockWithIndex(start); bi >= 0 {
9705 for i := bi; i >= 0; i-- {
9706 mb := fs.blks[i]
9707 if sm, expireOk, err := mb.prevMatchingMulti(sl, start, smp); err == nil {
9708 if expireOk {
9709 mb.tryForceExpireCache()
9710 }
9711 return sm, sm.seq, nil
9712 } else if err != ErrStoreMsgNotFound {
9713 return nil, 0, err
9714 } else if expireOk {
9715 mb.tryForceExpireCache()
9716 }
9717 }
9718 }
9719
9720 return nil, fs.state.FirstSeq, ErrStoreEOF
9721 }
9722
9723 // Type returns the type of the underlying store.
9724 func (fs *fileStore) Type() StorageType {
9725 return FileStorage
9726 }
9727
9728 // Returns number of subjects in this store.
9729 // Lock should be held.
9730 func (fs *fileStore) numSubjects() int {
9731 return fs.psim.Size()
9732 }
9733
9734 // numConsumers uses new lock.
9735 func (fs *fileStore) numConsumers() int {
9736 fs.cmu.RLock()
9737 defer fs.cmu.RUnlock()
9738 return len(fs.cfs)
9739 }
9740
9741 // FastState will fill in state with only the following.
9742 // Msgs, Bytes, First and Last Sequence and Time and NumDeleted.
9743 func (fs *fileStore) FastState(state *StreamState) {
9744 fs.mu.RLock()
9745 state.Msgs = fs.state.Msgs
9746 state.Bytes = fs.state.Bytes
9747 state.FirstSeq = fs.state.FirstSeq
9748 state.FirstTime = fs.state.FirstTime
9749 state.LastSeq = fs.state.LastSeq
9750 state.LastTime = fs.state.LastTime
9751 // Make sure to reset if being re-used.
9752 state.Deleted, state.NumDeleted = nil, 0
9753 if state.LastSeq > state.FirstSeq {
9754 state.NumDeleted = int((state.LastSeq - state.FirstSeq + 1) - state.Msgs)
9755 if state.NumDeleted < 0 {
9756 state.NumDeleted = 0
9757 }
9758 }
9759 state.Consumers = fs.numConsumers()
9760 state.NumSubjects = fs.numSubjects()
9761 fs.mu.RUnlock()
9762 }
9763
9764 // State returns the current state of the stream.
9765 func (fs *fileStore) State() StreamState {
9766 fs.mu.RLock()
9767 state := fs.state
9768 state.Consumers = fs.numConsumers()
9769 state.NumSubjects = fs.numSubjects()
9770 state.Deleted = nil // make sure.
9771
9772 if numDeleted := int((state.LastSeq - state.FirstSeq + 1) - state.Msgs); numDeleted > 0 {
9773 state.Deleted = make([]uint64, 0, numDeleted)
9774 cur := fs.state.FirstSeq
9775
9776 for _, mb := range fs.blks {
9777 mb.mu.Lock()
9778 fseq := atomic.LoadUint64(&mb.first.seq)
9779 // Account for messages missing from the head.
9780 if fseq > cur {
9781 for seq := cur; seq < fseq; seq++ {
9782 state.Deleted = append(state.Deleted, seq)
9783 }
9784 }
9785 // Only advance cur if we are increasing. We could have marker blocks with just tombstones.
9786 if last := atomic.LoadUint64(&mb.last.seq); last >= cur {
9787 cur = last + 1 // Expected next first.
9788 }
9789 // Add in deleted.
9790 mb.dmap.Range(func(seq uint64) bool {
9791 state.Deleted = append(state.Deleted, seq)
9792 return true
9793 })
9794 mb.mu.Unlock()
9795 }
9796 }
9797 fs.mu.RUnlock()
9798
9799 state.Lost = fs.lostData()
9800
9801 // Can not be guaranteed to be sorted.
9802 if len(state.Deleted) > 0 {
9803 slices.Sort(state.Deleted)
9804 state.NumDeleted = len(state.Deleted)
9805 }
9806 return state
9807 }
9808
9809 func (fs *fileStore) Utilization() (total, reported uint64, err error) {
9810 fs.mu.RLock()
9811 defer fs.mu.RUnlock()
9812 for _, mb := range fs.blks {
9813 mb.mu.RLock()
9814 reported += mb.bytes
9815 total += mb.rbytes
9816 mb.mu.RUnlock()
9817 }
9818 return total, reported, nil
9819 }
9820
9821 func fileStoreMsgSizeRaw(slen, hlen, mlen int) uint64 {
9822 if hlen == 0 {
9823 // length of the message record (4bytes) + seq(8) + ts(8) + subj_len(2) + subj + msg + hash(8)
9824 return uint64(22 + slen + mlen + 8)
9825 }
9826 // length of the message record (4bytes) + seq(8) + ts(8) + subj_len(2) + subj + hdr_len(4) + hdr + msg + hash(8)
9827 return uint64(22 + slen + 4 + hlen + mlen + 8)
9828 }
9829
9830 func fileStoreMsgSize(subj string, hdr, msg []byte) uint64 {
9831 return fileStoreMsgSizeRaw(len(subj), len(hdr), len(msg))
9832 }
9833
9834 // isFileStoreMsgTooLarge reports whether a message record cannot be represented
9835 // safely by the file store.
9836 func isFileStoreMsgTooLarge(rl uint64) bool {
9837 return rl&hbit != 0 || rl > rlBadThresh
9838 }
9839
9840 func fileStoreMsgSizeEstimate(slen, maxPayload int) uint64 {
9841 return uint64(emptyRecordLen + slen + 4 + maxPayload)
9842 }
9843
9844 // ResetState resets any state that's temporary. For example when changing leaders.
9845 func (fs *fileStore) ResetState() {
9846 fs.mu.Lock()
9847 defer fs.mu.Unlock()
9848 if fs.scheduling != nil {
9849 fs.scheduling.clearInflight()
9850 }
9851 }
9852
9853 // Determine time since any last activity, read/load, write or remove.
9854 func (mb *msgBlock) sinceLastActivity() time.Duration {
9855 if mb.closed {
9856 return 0
9857 }
9858 last := mb.lwts
9859 if mb.lrts > last {
9860 last = mb.lrts
9861 }
9862 if mb.llts > last {
9863 last = mb.llts
9864 }
9865 if mb.lsts > last {
9866 last = mb.lsts
9867 }
9868 return time.Since(time.Unix(0, last).UTC())
9869 }
9870
9871 // Determine time since last write or remove of a message.
9872 // Read lock should be held.
9873 func (mb *msgBlock) sinceLastWriteActivity() time.Duration {
9874 if mb.closed {
9875 return 0
9876 }
9877 last := mb.lwts
9878 if mb.lrts > last {
9879 last = mb.lrts
9880 }
9881 return time.Since(time.Unix(0, last).UTC())
9882 }
9883
9884 func checkNewHeader(hdr []byte) error {
9885 if len(hdr) < 2 || hdr[0] != magic ||
9886 (hdr[1] != version && hdr[1] != newVersion) {
9887 return errCorruptState
9888 }
9889 return nil
9890 }
9891
9892 // readIndexInfo will read in the index information for the message block.
9893 func (mb *msgBlock) readIndexInfo() error {
9894 ifn := filepath.Join(mb.fs.fcfg.StoreDir, msgDir, fmt.Sprintf(indexScan, mb.index))
9895 buf, err := os.ReadFile(ifn)
9896 if err != nil {
9897 return err
9898 }
9899
9900 // Set if first time.
9901 if mb.liwsz == 0 {
9902 mb.liwsz = int64(len(buf))
9903 }
9904
9905 // Decrypt if needed.
9906 if mb.aek != nil {
9907 buf, err = mb.aek.Open(buf[:0], mb.nonce, buf, nil)
9908 if err != nil {
9909 return err
9910 }
9911 }
9912
9913 if err := checkNewHeader(buf); err != nil {
9914 defer os.Remove(ifn)
9915 return fmt.Errorf("bad index file")
9916 }
9917
9918 bi := hdrLen
9919
9920 // Helpers, will set i to -1 on error.
9921 readSeq := func() uint64 {
9922 if bi < 0 {
9923 return 0
9924 }
9925 seq, n := binary.Uvarint(buf[bi:])
9926 if n <= 0 {
9927 bi = -1
9928 return 0
9929 }
9930 bi += n
9931 return seq &^ ebit
9932 }
9933 readCount := readSeq
9934 readTimeStamp := func() int64 {
9935 if bi < 0 {
9936 return 0
9937 }
9938 ts, n := binary.Varint(buf[bi:])
9939 if n <= 0 {
9940 bi = -1
9941 return -1
9942 }
9943 bi += n
9944 return ts
9945 }
9946 mb.msgs = readCount()
9947 mb.bytes = readCount()
9948 atomic.StoreUint64(&mb.first.seq, readSeq())
9949 mb.first.ts = readTimeStamp()
9950 atomic.StoreUint64(&mb.last.seq, readSeq())
9951 mb.last.ts = readTimeStamp()
9952 dmapLen := readCount()
9953
9954 // Check if this is a short write index file.
9955 if bi < 0 || bi+checksumSize > len(buf) {
9956 os.Remove(ifn)
9957 return fmt.Errorf("short index file")
9958 }
9959
9960 // Check for consistency if accounting. If something is off bail and we will rebuild.
9961 if mb.msgs != (atomic.LoadUint64(&mb.last.seq)-atomic.LoadUint64(&mb.first.seq)+1)-dmapLen {
9962 os.Remove(ifn)
9963 return fmt.Errorf("accounting inconsistent")
9964 }
9965
9966 // Checksum
9967 copy(mb.lchk[0:], buf[bi:bi+checksumSize])
9968 bi += checksumSize
9969
9970 // Now check for presence of a delete map
9971 if dmapLen > 0 {
9972 // New version is encoded avl seqset.
9973 if buf[1] == newVersion {
9974 dmap, _, err := avl.Decode(buf[bi:])
9975 if err != nil {
9976 return fmt.Errorf("could not decode avl dmap: %v", err)
9977 }
9978 mb.dmap = *dmap
9979 } else {
9980 // This is the old version.
9981 for i, fseq := 0, atomic.LoadUint64(&mb.first.seq); i < int(dmapLen); i++ {
9982 seq := readSeq()
9983 if seq == 0 {
9984 break
9985 }
9986 mb.dmap.Insert(seq + fseq)
9987 }
9988 }
9989 }
9990
9991 return nil
9992 }
9993
9994 // Will return total number of cache loads.
9995 func (fs *fileStore) cacheLoads() uint64 {
9996 var tl uint64
9997 fs.mu.RLock()
9998 for _, mb := range fs.blks {
9999 mb.mu.RLock()
10000 tl += mb.cloads
10001 mb.mu.RUnlock()
10002 }
10003 fs.mu.RUnlock()
10004 return tl
10005 }
10006
10007 // Will return total number of cached bytes.
10008 func (fs *fileStore) cacheSize() uint64 {
10009 var sz uint64
10010 fs.mu.RLock()
10011 for _, mb := range fs.blks {
10012 mb.mu.Lock()
10013 var needsCleanup bool
10014 if mb.cache == nil {
10015 mb.cache = mb.ecache.Value()
10016 needsCleanup = mb.cache != nil
10017 }
10018 if mb.cache != nil {
10019 sz += uint64(len(mb.cache.buf))
10020 }
10021 if needsCleanup {
10022 mb.finishedWithCache()
10023 }
10024 mb.mu.Unlock()
10025 }
10026 fs.mu.RUnlock()
10027 return sz
10028 }
10029
10030 // Will return total number of dmapEntries for all msg blocks.
10031 func (fs *fileStore) dmapEntries() int {
10032 var total int
10033 fs.mu.RLock()
10034 for _, mb := range fs.blks {
10035 total += mb.dmap.Size()
10036 }
10037 fs.mu.RUnlock()
10038 return total
10039 }
10040
10041 // Fixed helper for iterating.
10042 func subjectsEqual(a, b string) bool {
10043 return a == b
10044 }
10045
10046 func subjectsAll(a, b string) bool {
10047 return true
10048 }
10049
10050 func compareFn(subject string) func(string, string) bool {
10051 if subject == _EMPTY_ || subject == fwcs {
10052 return subjectsAll
10053 }
10054 if subjectHasWildcard(subject) {
10055 return subjectIsSubsetMatch
10056 }
10057 return subjectsEqual
10058 }
10059
10060 // PurgeEx will remove messages based on subject filters, sequence and number of messages to keep.
10061 // Will return the number of purged messages.
10062 func (fs *fileStore) PurgeEx(subject string, sequence, keep uint64) (purged uint64, err error) {
10063 // sequence == 1 means "purge up to but not including 1", a no-op.
10064 if sequence == 1 {
10065 return 0, nil
10066 }
10067 if subject == _EMPTY_ || subject == fwcs {
10068 if keep == 0 && sequence == 0 {
10069 return fs.purge(0)
10070 }
10071 if sequence > 1 {
10072 return fs.compact(sequence)
10073 }
10074 // Make sure to not leave subject if empty.
10075 if subject == _EMPTY_ {
10076 subject = fwcs
10077 }
10078 }
10079
10080 // Persist any write errors.
10081 defer func() {
10082 if err != nil {
10083 fs.mu.Lock()
10084 fs.setWriteErr(err)
10085 fs.mu.Unlock()
10086 }
10087 }()
10088
10089 eq, wc := compareFn(subject), subjectHasWildcard(subject)
10090 var firstSeqNeedsUpdate bool
10091 var bytes uint64
10092
10093 // If we have a "keep" designation need to get full filtered state so we know how many to purge.
10094 var maxp uint64
10095 if keep > 0 {
10096 ss, err := fs.FilteredState(1, subject)
10097 if err != nil || keep >= ss.Msgs {
10098 return 0, err
10099 }
10100 maxp = ss.Msgs - keep
10101 }
10102
10103 var smv StoreMsg
10104 var tombs []msgId
10105 var lowSeq uint64
10106
10107 if fs.isClosed() {
10108 return purged, ErrStoreClosed
10109 }
10110 fs.mu.Lock()
10111 // Always return previous write errors.
10112 if err := fs.werr; err != nil {
10113 fs.mu.Unlock()
10114 return purged, err
10115 }
10116 if len(fs.blks) == 0 || fs.lmb == nil {
10117 fs.mu.Unlock()
10118 return purged, nil
10119 }
10120
10121 var start, stop uint32
10122
10123 // If literal subject check for presence.
10124 if wc {
10125 start = fs.lmb.index
10126 fs.psim.Match(stringToBytes(subject), func(_ []byte, psi *psi) {
10127 // Keep track of start and stop indexes for this subject.
10128 if psi.fblk < start {
10129 start = psi.fblk
10130 }
10131 if psi.lblk > stop {
10132 stop = psi.lblk
10133 }
10134 })
10135 // None matched.
10136 if stop == 0 {
10137 fs.mu.Unlock()
10138 return purged, nil
10139 }
10140 } else if info, ok := fs.psim.Find(stringToBytes(subject)); ok {
10141 start, stop = info.fblk, info.lblk
10142 } else {
10143 fs.mu.Unlock()
10144 return purged, nil
10145 }
10146
10147 // We may remove blocks as we purge, so don't range directly on fs.blks
10148 // otherwise we may jump over some (see https://github.com/nats-io/nats-server/issues/3528)
10149 for i := 0; i < len(fs.blks); i++ {
10150 mb := fs.blks[i]
10151 // Skip if not within our range for the purge subject.
10152 if mb.index < start || mb.index > stop {
10153 continue
10154 }
10155 mb.mu.Lock()
10156
10157 // If we do not have our fss, try to expire the cache if we have no items in this block.
10158 shouldExpire := mb.fssNotLoaded()
10159
10160 t, f, l, err := mb.filteredPendingLocked(subject, wc, atomic.LoadUint64(&mb.first.seq))
10161 if err != nil {
10162 mb.mu.Unlock()
10163 fs.mu.Unlock()
10164 return purged, err
10165 }
10166 if t == 0 {
10167 // Expire if we were responsible for loading.
10168 if shouldExpire {
10169 // Expire this cache before moving on.
10170 mb.tryForceExpireCacheLocked()
10171 }
10172 mb.mu.Unlock()
10173 continue
10174 }
10175
10176 // "Purge up to but not including sequence": sequence == 0 means no
10177 // sequence filter; sequence >= 1 clamps the per-block upper bound to
10178 // sequence-1 (so sequence == 1 leaves nothing to process).
10179 if sequence >= 1 && sequence <= l {
10180 l = sequence - 1
10181 }
10182
10183 if mb.cacheNotLoaded() {
10184 if err := mb.loadMsgsWithLock(); err != nil {
10185 mb.mu.Unlock()
10186 fs.mu.Unlock()
10187 return 0, err
10188 }
10189 shouldExpire = true
10190 }
10191
10192 var nrg uint64 // Number of remaining messages globally after removal from psim.
10193
10194 for seq, te := f, len(tombs); seq <= l; seq++ {
10195 if sm, _ := mb.cacheLookupNoCopy(seq, &smv); sm != nil && eq(sm.subj, subject) {
10196 rl := fileStoreMsgSize(sm.subj, sm.hdr, sm.msg)
10197 // Do fast in place remove.
10198 // Stats
10199 if mb.msgs > 0 {
10200 // Msgs
10201 fs.state.Msgs--
10202 mb.msgs--
10203 // Bytes, make sure to not go negative.
10204 if rl > fs.state.Bytes {
10205 rl = fs.state.Bytes
10206 }
10207 if rl > mb.bytes {
10208 rl = mb.bytes
10209 }
10210 fs.state.Bytes -= rl
10211 mb.bytes -= rl
10212 // Totals
10213 purged++
10214 bytes += rl
10215 }
10216 // PSIM and FSS updates.
10217 nr, err := mb.removeSeqPerSubject(sm.subj, seq)
10218 if err != nil {
10219 mb.mu.Unlock()
10220 fs.mu.Unlock()
10221 return purged, err
10222 }
10223 nrg = fs.removePerSubject(sm.subj)
10224
10225 // Track tombstones we need to write.
10226 tombs = append(tombs, msgId{sm.seq, sm.ts})
10227 if sm.seq < lowSeq || lowSeq == 0 {
10228 lowSeq = sm.seq
10229 }
10230
10231 // Check for first message.
10232 if seq == atomic.LoadUint64(&mb.first.seq) {
10233 mb.selectNextFirst()
10234 if mb.isEmpty() {
10235 // Since we are removing this block don't need to write tombstones.
10236 tombs = tombs[:te]
10237 if err = fs.removeMsgBlock(mb); err != nil {
10238 mb.mu.Unlock()
10239 fs.mu.Unlock()
10240 return 0, err
10241 }
10242 i--
10243 // keep flag set, if set previously
10244 firstSeqNeedsUpdate = firstSeqNeedsUpdate || seq == fs.state.FirstSeq
10245 } else if seq == fs.state.FirstSeq {
10246 fs.state.FirstSeq = atomic.LoadUint64(&mb.first.seq) // new one.
10247 if mb.first.ts == 0 {
10248 fs.state.FirstTime = time.Time{}
10249 } else {
10250 fs.state.FirstTime = time.Unix(0, mb.first.ts).UTC()
10251 }
10252 }
10253 } else {
10254 // Out of order delete.
10255 mb.dmap.Insert(seq)
10256 }
10257 // Break if we have emptied this block or if we set a maximum purge count.
10258 if mb.isEmpty() || (maxp > 0 && purged >= maxp) {
10259 break
10260 }
10261 // Also break if we know we have no more messages matching here.
10262 // This is only applicable for non-wildcarded filters.
10263 if !wc && nr == 0 {
10264 break
10265 }
10266 }
10267 }
10268 // Expire if we were responsible for loading and we do not seem to be doing successive purgeEx calls.
10269 // On successive calls - most likely from KV purge deletes, we want to keep the data loaded.
10270 if shouldExpire && time.Since(fs.lpex) > time.Second {
10271 // Expire this cache before moving on.
10272 mb.tryForceExpireCacheLocked()
10273 } else {
10274 mb.finishedWithCache()
10275 }
10276 mb.mu.Unlock()
10277
10278 // Check if we should break out of top level too.
10279 if maxp > 0 && purged >= maxp {
10280 break
10281 }
10282 // Also check if not wildcarded and we have no remaining matches.
10283 if !wc && nrg == 0 {
10284 break
10285 }
10286 }
10287 if firstSeqNeedsUpdate {
10288 if err = fs.selectNextFirst(); err != nil {
10289 fs.mu.Unlock()
10290 return purged, err
10291 }
10292 }
10293
10294 // Update the last purgeEx call time.
10295 defer func() { fs.lpex = time.Now() }()
10296
10297 // Write any tombstones as needed.
10298 // When writing multiple tombstones we will flush at the end.
10299 if len(tombs) > 0 {
10300 for _, tomb := range tombs {
10301 if err = fs.writeTombstoneNoFlush(tomb.seq, tomb.ts); err != nil {
10302 fs.mu.Unlock()
10303 return purged, err
10304 }
10305 }
10306 // Flush any pending. If we change blocks the newMsgBlockForWrite() will flush any pending for us.
10307 if lmb := fs.lmb; lmb != nil {
10308 if err = lmb.flushPendingMsgs(); err != nil {
10309 fs.mu.Unlock()
10310 return purged, err
10311 }
10312 }
10313 }
10314
10315 fs.dirty++
10316 cb := fs.scb
10317 fs.mu.Unlock()
10318
10319 if cb != nil {
10320 if purged == 1 {
10321 cb(-int64(purged), -int64(bytes), lowSeq, subject)
10322 } else {
10323 // FIXME(dlc) - Since we track lowSeq we could send to upper layer if they dealt with the condition properly.
10324 cb(-int64(purged), -int64(bytes), 0, _EMPTY_)
10325 }
10326 }
10327
10328 return purged, nil
10329 }
10330
10331 // Purge will remove all messages from this store.
10332 // Will return the number of purged messages.
10333 func (fs *fileStore) Purge() (uint64, error) {
10334 return fs.purge(0)
10335 }
10336
10337 func (fs *fileStore) purge(fseq uint64) (uint64, error) {
10338 if fs.isClosed() {
10339 return 0, ErrStoreClosed
10340 }
10341
10342 fs.mu.Lock()
10343 cb := fs.scb
10344 purged, bytes, err := fs.purgeLocked(fseq)
10345 if err != nil {
10346 fs.setWriteErr(err)
10347 fs.mu.Unlock()
10348 return purged, err
10349 }
10350 fs.mu.Unlock()
10351
10352 // Force a new index.db to be written.
10353 if purged > 0 {
10354 fs.forceWriteFullState()
10355 }
10356 if cb != nil {
10357 cb(-int64(purged), -int64(bytes), 0, _EMPTY_)
10358 }
10359 return purged, nil
10360 }
10361
10362 // Lock must be held.
10363 func (fs *fileStore) purgeLocked(fseq uint64) (purged, bytes uint64, err error) {
10364 // Always return previous write errors.
10365 if err := fs.werr; err != nil {
10366 return 0, 0, err
10367 }
10368
10369 purged, bytes = fs.state.Msgs, fs.state.Bytes
10370
10371 fs.state.FirstSeq = fs.state.LastSeq + 1
10372 fs.state.FirstTime = time.Time{}
10373
10374 fs.state.Bytes = 0
10375 fs.state.Msgs = 0
10376
10377 for _, mb := range fs.blks {
10378 // These blocks are being discarded by the purge, so mark them closed.
10379 mb.mu.Lock()
10380 mb.dirtyCloseWithRemove(false)
10381 mb.closed = true
10382 mb.mu.Unlock()
10383 }
10384
10385 // Check if we need to set the first seq to a new number.
10386 if fseq > fs.state.FirstSeq {
10387 fs.state.FirstSeq = fseq
10388 fs.state.LastSeq = fseq - 1
10389 }
10390
10391 // Make sure we have a lmb to write to.
10392 if _, err := fs.newMsgBlockForWrite(); err != nil {
10393 return purged, bytes, err
10394 }
10395
10396 lmb := fs.lmb
10397 atomic.StoreUint64(&lmb.first.seq, fs.state.FirstSeq)
10398 atomic.StoreUint64(&lmb.last.seq, fs.state.LastSeq)
10399 lmb.last.ts = fs.state.LastTime.UnixNano()
10400
10401 if lseq := atomic.LoadUint64(&lmb.last.seq); lseq > 0 {
10402 // Leave a tombstone so we can remember our starting sequence in case
10403 // full state becomes corrupted.
10404 if err := fs.writeTombstone(lseq, lmb.last.ts); err != nil {
10405 return purged, bytes, err
10406 }
10407 }
10408 // Close FDs since we'll move the file. We re-enable the FD after the purge is complete.
10409 if err := lmb.flushPendingMsgs(); err != nil {
10410 return purged, bytes, err
10411 }
10412 if err := lmb.closeFDs(); err != nil {
10413 return purged, bytes, err
10414 }
10415
10416 fs.blks = nil
10417 fs.lmb = nil
10418 fs.bim = make(map[uint32]*msgBlock)
10419 // Clear any per subject tracking.
10420 fs.psim, fs.tsl = fs.psim.Empty(), 0
10421 fs.sdm.empty()
10422 // Mark dirty.
10423 fs.dirty++
10424 fs.addMsgBlock(lmb)
10425
10426 // Move the msgs directory out of the way, will delete out of band.
10427 mdir := filepath.Join(fs.fcfg.StoreDir, msgDir)
10428 ndir := filepath.Join(fs.fcfg.StoreDir, newMsgDir)
10429 pdir := filepath.Join(fs.fcfg.StoreDir, purgeDir)
10430 fs.dios.acquire()
10431 // If purge directory still exists then we need to wait
10432 // in place and remove since rename would fail.
10433 if _, err := os.Stat(ndir); err == nil {
10434 if err = os.RemoveAll(ndir); err != nil {
10435 fs.dios.release()
10436 return purged, bytes, err
10437 }
10438 } else if !os.IsNotExist(err) {
10439 fs.dios.release()
10440 return purged, bytes, err
10441 }
10442 if _, err := os.Stat(pdir); err == nil {
10443 if err = os.RemoveAll(pdir); err != nil {
10444 fs.dios.release()
10445 return purged, bytes, err
10446 }
10447 } else if !os.IsNotExist(err) {
10448 fs.dios.release()
10449 return purged, bytes, err
10450 }
10451
10452 // Create directory to move the new tombstone to.
10453 if err := os.MkdirAll(ndir, defaultDirPerms); err != nil {
10454 fs.dios.release()
10455 return purged, bytes, err
10456 }
10457 // Move out the block containing the tombstone. Also move the key file if encrypted.
10458 // The block file itself MUST be moved last to ensure we can assume the prior renames
10459 // were successful during recovery.
10460 for _, mbf := range []string{fmt.Sprintf(keyScan, lmb.index), fmt.Sprintf(blkScan, lmb.index)} {
10461 b := filepath.Join(mdir, mbf)
10462 a := filepath.Join(ndir, mbf)
10463 if err := os.Rename(b, a); err != nil && !os.IsNotExist(err) {
10464 fs.dios.release()
10465 return purged, bytes, err
10466 }
10467 }
10468 // Purge all remaining messages.
10469 if err := os.Rename(mdir, pdir); err != nil {
10470 fs.dios.release()
10471 return purged, bytes, err
10472 }
10473 // Rename the directory back to be left only with the tombstone.
10474 if err := os.Rename(ndir, mdir); err != nil {
10475 fs.dios.release()
10476 return purged, bytes, err
10477 }
10478 fs.dios.release()
10479
10480 // Remove the purged messages directory asynchronously.
10481 go func() {
10482 fs.dios.acquire()
10483 _ = os.RemoveAll(pdir)
10484 fs.dios.release()
10485 }()
10486
10487 // Re-enable writing for the lmb.
10488 lmb.mu.Lock()
10489 err = lmb.enableForWriting(fs.fip)
10490 lmb.mu.Unlock()
10491 if err != nil {
10492 return purged, bytes, err
10493 }
10494
10495 return purged, bytes, nil
10496 }
10497
10498 // Lock and dios should be held.
10499 func (fs *fileStore) recoverPartialPurge() error {
10500 mdir := filepath.Join(fs.fcfg.StoreDir, msgDir)
10501 ndir := filepath.Join(fs.fcfg.StoreDir, newMsgDir)
10502 if entries, err := os.ReadDir(ndir); err != nil && !os.IsNotExist(err) {
10503 return err
10504 } else if err == nil {
10505 hasBlk := slices.ContainsFunc(entries, func(e os.DirEntry) bool {
10506 return strings.HasSuffix(e.Name(), blkSuffix)
10507 })
10508 if hasBlk {
10509 // We have a tombstone, we can purge the old messages.
10510 if err = os.RemoveAll(mdir); err != nil {
10511 return err
10512 }
10513 if err = os.Rename(ndir, mdir); err != nil {
10514 return err
10515 }
10516 } else {
10517 // No .blk means the purge did not complete, so clear
10518 // any progress made by the partial purge.
10519 for _, entry := range entries {
10520 var index uint32
10521 if n, err := fmt.Sscanf(entry.Name(), keyScan, &index); err != nil || n != 1 {
10522 continue
10523 }
10524 // Found a key file, remove the corresponding .blk, if any.
10525 // Recovery may otherwise wrongly conclude that the .blk is
10526 // is plaintext, and consider it corrupt when trying to open it.
10527 err := os.Remove(filepath.Join(mdir, fmt.Sprintf(blkScan, index)))
10528 if err != nil && !os.IsNotExist(err) {
10529 return err
10530 }
10531 }
10532 _ = os.RemoveAll(ndir)
10533 return nil
10534 }
10535 }
10536 pdir := filepath.Join(fs.fcfg.StoreDir, purgeDir)
10537 if _, err := os.Stat(pdir); err == nil {
10538 _ = os.RemoveAll(pdir)
10539 }
10540 return nil
10541 }
10542
10543 // Compact will remove all messages from this store up to
10544 // but not including the seq parameter.
10545 // Will return the number of purged messages.
10546 func (fs *fileStore) Compact(seq uint64) (uint64, error) {
10547 return fs.compact(seq)
10548 }
10549
10550 func (fs *fileStore) compact(seq uint64) (uint64, error) {
10551 if fs.isClosed() {
10552 return 0, ErrStoreClosed
10553 }
10554
10555 var err error
10556 var purged, bytes uint64
10557 fs.mu.Lock()
10558 if seq == 0 || seq > fs.state.LastSeq {
10559 purged, bytes, err = fs.purgeLocked(seq)
10560 } else {
10561 purged, bytes, err = fs.compactLocked(seq)
10562 }
10563 if err != nil {
10564 fs.setWriteErr(err)
10565 fs.mu.Unlock()
10566 return purged, err
10567 }
10568 cb := fs.scb
10569 fs.mu.Unlock()
10570
10571 // Force a new index.db to be written.
10572 if purged > 0 {
10573 fs.forceWriteFullState()
10574 }
10575
10576 if cb != nil && purged > 0 {
10577 cb(-int64(purged), -int64(bytes), 0, _EMPTY_)
10578 }
10579
10580 return purged, nil
10581 }
10582
10583 // Lock must be held.
10584 func (fs *fileStore) compactLocked(seq uint64) (purged, bytes uint64, err error) {
10585 // Always return previous write errors.
10586 if err := fs.werr; err != nil {
10587 return 0, 0, err
10588 }
10589
10590 // Short-circuit if the store was already compacted past this point.
10591 if fs.state.FirstSeq > seq {
10592 return 0, 0, nil
10593 }
10594 // We have to delete interior messages.
10595 smb := fs.selectMsgBlock(seq)
10596 if smb == nil {
10597 return 0, 0, nil
10598 }
10599
10600 // All msgblocks up to this one can be thrown away.
10601 var deleted int
10602 for _, mb := range fs.blks {
10603 if mb == smb {
10604 break
10605 }
10606 mb.mu.Lock()
10607 purged += mb.msgs
10608 bytes += mb.bytes
10609 // Make sure we do subject cleanup as well.
10610 if err := mb.ensurePerSubjectInfoLoaded(); err != nil {
10611 mb.mu.Unlock()
10612 return 0, 0, err
10613 }
10614 mb.fss.IterOrdered(func(bsubj []byte, ss *SimpleState) bool {
10615 subj := bytesToString(bsubj)
10616 for i := uint64(0); i < ss.Msgs; i++ {
10617 fs.removePerSubject(subj)
10618 }
10619 return true
10620 })
10621 // Now close.
10622 err := mb.dirtyCloseWithRemove(true)
10623 mb.mu.Unlock()
10624 if err != nil {
10625 return purged, bytes, err
10626 }
10627 deleted++
10628 }
10629
10630 var smv StoreMsg
10631 var tombs []msgId
10632
10633 smb.mu.Lock()
10634 if atomic.LoadUint64(&smb.first.seq) == seq {
10635 fs.state.FirstSeq = atomic.LoadUint64(&smb.first.seq)
10636 fs.state.FirstTime = time.Unix(0, smb.first.ts).UTC()
10637 goto SKIP
10638 }
10639
10640 // Make sure we have the messages loaded.
10641 if smb.cacheNotLoaded() {
10642 if err = smb.loadMsgsWithLock(); err != nil {
10643 smb.mu.Unlock()
10644 return purged, bytes, err
10645 }
10646 defer func() {
10647 // The block lock is released once we get here, so need to re-acquire.
10648 smb.mu.Lock()
10649 smb.finishedWithCache()
10650 smb.mu.Unlock()
10651 }()
10652 }
10653 for mseq := atomic.LoadUint64(&smb.first.seq); mseq < seq; mseq++ {
10654 sm, err := smb.cacheLookupNoCopy(mseq, &smv)
10655 if err == errDeletedMsg {
10656 // Update dmap.
10657 if !smb.dmap.IsEmpty() {
10658 smb.dmap.Delete(mseq)
10659 }
10660 } else if sm != nil {
10661 sz := fileStoreMsgSize(sm.subj, sm.hdr, sm.msg)
10662 if smb.msgs > 0 {
10663 smb.msgs--
10664 if sz > smb.bytes {
10665 sz = smb.bytes
10666 }
10667 smb.bytes -= sz
10668 bytes += sz
10669 purged++
10670 }
10671 // Update fss
10672 if _, err := smb.removeSeqPerSubject(sm.subj, mseq); err != nil {
10673 smb.mu.Unlock()
10674 return purged, bytes, err
10675 }
10676 fs.removePerSubject(sm.subj)
10677 tombs = append(tombs, msgId{sm.seq, sm.ts})
10678 }
10679 }
10680
10681 // Check if empty after processing, could happen if tail of messages are all deleted.
10682 if isEmpty := smb.msgs == 0; isEmpty {
10683 // Only remove if not the last block.
10684 if smb != fs.lmb {
10685 if err = smb.dirtyCloseWithRemove(true); err != nil {
10686 smb.mu.Unlock()
10687 return purged, bytes, err
10688 }
10689 deleted++
10690 } else {
10691 // Make sure to sync changes.
10692 smb.needSync = true
10693 }
10694 // Update fs first here as well.
10695 fs.state.FirstSeq = atomic.LoadUint64(&smb.last.seq) + 1
10696 fs.state.FirstTime = time.Time{}
10697
10698 } else {
10699 // Make sure to sync changes.
10700 smb.needSync = true
10701 // Just for start condition for selectNextFirst.
10702 if smb.first.seq < seq {
10703 atomic.StoreUint64(&smb.first.seq, seq-1)
10704 } else {
10705 // selectNextFirst always adds 1, so need to subtract 1 here.
10706 atomic.StoreUint64(&smb.first.seq, smb.first.seq-1)
10707 }
10708 smb.selectNextFirst()
10709
10710 fs.state.FirstSeq = atomic.LoadUint64(&smb.first.seq)
10711 fs.state.FirstTime = time.Unix(0, smb.first.ts).UTC()
10712
10713 // Check if we should reclaim the head space from this block.
10714 // This will be optimistic only, so don't continue if we encounter any errors here.
10715 if smb.rbytes > compactMinimum && smb.bytes*2 < smb.rbytes {
10716 var moff uint32
10717 moff, _, _, err = smb.slotInfo(int(atomic.LoadUint64(&smb.first.seq) - smb.cache.fseq))
10718 if err != nil {
10719 smb.mu.Unlock()
10720 return purged, bytes, err
10721 } else if moff >= uint32(len(smb.cache.buf)) {
10722 goto SKIP
10723 }
10724 buf := smb.cache.buf[moff:]
10725 // Don't reuse, copy to new recycled buf.
10726 nbuf := getMsgBlockBuf(len(buf))
10727 // Recycle our nbuf when we are done.
10728 defer recycleMsgBlockBuf(nbuf)
10729 nbuf = append(nbuf, buf...)
10730 smb.closeFDsLockedNoCheck()
10731 // Check for compression.
10732 if smb.cmp != NoCompression && len(nbuf) > 0 {
10733 originalSize := len(nbuf)
10734 if nbuf, err = smb.cmp.Compress(nbuf); err != nil {
10735 smb.mu.Unlock()
10736 return purged, bytes, err
10737 }
10738 meta := &CompressionInfo{
10739 Algorithm: smb.cmp,
10740 OriginalSize: uint64(originalSize),
10741 }
10742 nbuf = append(meta.MarshalMetadata(), nbuf...)
10743 }
10744 // Check for encryption.
10745 if smb.bek != nil && len(nbuf) > 0 {
10746 // Recreate to reset counter.
10747 bek, err := genBlockEncryptionKey(smb.fs.fcfg.Cipher, smb.seed, smb.nonce)
10748 if err != nil {
10749 smb.mu.Unlock()
10750 return purged, bytes, err
10751 }
10752 // For future writes make sure to set smb.bek to keep counter correct.
10753 smb.bek = bek
10754 smb.bek.XORKeyStream(nbuf, nbuf)
10755 }
10756
10757 // We will write to a new file and mv/rename it in case of failure.
10758 mfn := filepath.Join(smb.fs.fcfg.StoreDir, msgDir, fmt.Sprintf(newScan, smb.index))
10759 fs.dios.acquire()
10760 err = os.WriteFile(mfn, nbuf, defaultFilePerms)
10761 fs.dios.release()
10762 if err != nil {
10763 _ = os.Remove(mfn)
10764 smb.mu.Unlock()
10765 return purged, bytes, err
10766 }
10767 if err = os.Rename(mfn, smb.mfn); err != nil {
10768 _ = os.Remove(mfn)
10769 smb.mu.Unlock()
10770 return purged, bytes, err
10771 }
10772
10773 // Make sure to remove fss state.
10774 smb.fss = nil
10775 smb.clearCacheAndOffset()
10776 smb.rbytes = uint64(len(nbuf))
10777 // Make sure we don't write any additional tombstones.
10778 tombs = nil
10779 }
10780 }
10781
10782 SKIP:
10783 smb.mu.Unlock()
10784
10785 // Write any tombstones as needed.
10786 // When writing multiple tombstones we will flush at the end.
10787 if len(tombs) > 0 {
10788 for _, tomb := range tombs {
10789 if err = fs.writeTombstoneNoFlush(tomb.seq, tomb.ts); err != nil {
10790 return purged, bytes, err
10791 }
10792 }
10793 // Flush any pending. If we change blocks the newMsgBlockForWrite() will flush any pending for us.
10794 if lmb := fs.lmb; lmb != nil {
10795 if err = lmb.flushPendingMsgs(); err != nil {
10796 return purged, bytes, err
10797 }
10798 }
10799 }
10800
10801 if deleted > 0 {
10802 // Update block map.
10803 if fs.bim != nil {
10804 for _, mb := range fs.blks[:deleted] {
10805 delete(fs.bim, mb.index)
10806 }
10807 }
10808 // Update blks slice.
10809 fs.blks = copyMsgBlocks(fs.blks[deleted:])
10810 if lb := len(fs.blks); lb == 0 {
10811 fs.lmb = nil
10812 } else {
10813 fs.lmb = fs.blks[lb-1]
10814 }
10815 }
10816
10817 // Update top level accounting.
10818 if purged > fs.state.Msgs {
10819 purged = fs.state.Msgs
10820 }
10821 fs.state.Msgs -= purged
10822 if fs.state.Msgs == 0 {
10823 fs.state.FirstSeq = fs.state.LastSeq + 1
10824 fs.state.FirstTime = time.Time{}
10825 }
10826
10827 if bytes > fs.state.Bytes {
10828 bytes = fs.state.Bytes
10829 }
10830 fs.state.Bytes -= bytes
10831
10832 // Any existing state file no longer applicable. We will force write a new one
10833 // after we release the lock.
10834 os.Remove(filepath.Join(fs.fcfg.StoreDir, msgDir, streamStreamStateFile))
10835 fs.dirty++
10836
10837 return purged, bytes, nil
10838 }
10839
10840 // Will completely reset our store.
10841 func (fs *fileStore) reset() error {
10842 if fs.isClosed() {
10843 return ErrStoreClosed
10844 }
10845
10846 fs.mu.Lock()
10847
10848 var purged, bytes uint64
10849 cb := fs.scb
10850
10851 for _, mb := range fs.blks {
10852 mb.mu.Lock()
10853 purged += mb.msgs
10854 bytes += mb.bytes
10855 err := mb.dirtyCloseWithRemove(true)
10856 mb.mu.Unlock()
10857 if err != nil {
10858 fs.mu.Unlock()
10859 return err
10860 }
10861 }
10862
10863 // Reset
10864 fs.state.FirstSeq = 0
10865 fs.state.FirstTime = time.Time{}
10866 fs.state.LastSeq = 0
10867 fs.state.LastTime = time.Now().UTC()
10868 // Update msgs and bytes.
10869 fs.state.Msgs = 0
10870 fs.state.Bytes = 0
10871
10872 // Reset blocks.
10873 fs.blks, fs.lmb = nil, nil
10874
10875 // Reset subject mappings.
10876 fs.psim, fs.tsl = fs.psim.Empty(), 0
10877 fs.sdm.empty()
10878 fs.bim = make(map[uint32]*msgBlock)
10879
10880 // If we purged anything, make sure we kick flush state loop.
10881 if purged > 0 {
10882 fs.dirty++
10883 }
10884
10885 fs.mu.Unlock()
10886
10887 if cb != nil {
10888 cb(-int64(purged), -int64(bytes), 0, _EMPTY_)
10889 }
10890
10891 return nil
10892 }
10893
10894 // Return all active tombstones in this msgBlock.
10895 func (mb *msgBlock) tombs() []msgId {
10896 mb.mu.Lock()
10897 defer mb.mu.Unlock()
10898 return mb.tombsLocked()
10899 }
10900
10901 // Return all active tombstones in this msgBlock.
10902 // Write lock should be held.
10903 func (mb *msgBlock) tombsLocked() []msgId {
10904 if mb.cacheNotLoaded() {
10905 if err := mb.loadMsgsWithLock(); err != nil {
10906 return nil
10907 }
10908 }
10909 defer mb.finishedWithCache()
10910
10911 var tombs []msgId
10912 var le = binary.LittleEndian
10913 buf := mb.cache.buf
10914
10915 for index, lbuf := uint32(0), uint32(len(buf)); index < lbuf; {
10916 if index+msgHdrSize > lbuf {
10917 return tombs
10918 }
10919 hdr := buf[index : index+msgHdrSize]
10920 rl, seq := le.Uint32(hdr[0:]), le.Uint64(hdr[4:])
10921 // Clear any headers bit that could be set.
10922 rl &^= hbit
10923 // Check for tombstones.
10924 if seq&tbit != 0 {
10925 ts := int64(le.Uint64(hdr[12:]))
10926 tombs = append(tombs, msgId{seq &^ tbit, ts})
10927 }
10928 // Advance to next record.
10929 index += rl
10930 }
10931
10932 return tombs
10933 }
10934
10935 // fs lock should be held.
10936 func (mb *msgBlock) numPriorTombs() int {
10937 mb.mu.Lock()
10938 defer mb.mu.Unlock()
10939 return mb.numPriorTombsLocked()
10940 }
10941
10942 // Return number of tombstones for messages prior to this msgBlock.
10943 // Both locks should be held.
10944 // Write lock should be held for block.
10945 func (mb *msgBlock) numPriorTombsLocked() int {
10946 if mb.cacheNotLoaded() {
10947 if err := mb.loadMsgsWithLock(); err != nil {
10948 return 0
10949 }
10950 }
10951 defer mb.finishedWithCache()
10952
10953 var fseq uint64
10954 var tombs int
10955 var le = binary.LittleEndian
10956 buf := mb.cache.buf
10957
10958 for index, lbuf := uint32(0), uint32(len(buf)); index < lbuf; {
10959 if index+msgHdrSize > lbuf {
10960 return tombs
10961 }
10962 hdr := buf[index : index+msgHdrSize]
10963 rl, seq := le.Uint32(hdr[0:]), le.Uint64(hdr[4:])
10964 // Clear any headers bit that could be set.
10965 rl &^= hbit
10966 // Check for tombstones.
10967 if seq&tbit != 0 {
10968 seq = seq &^ tbit
10969 // Tombstones below the global first seq are irrelevant.
10970 // And we only count tombstones below this block's first seq.
10971 if seq >= mb.fs.state.FirstSeq && (fseq == 0 || seq < fseq) {
10972 tombs++
10973 }
10974 index += rl
10975 continue
10976 }
10977 if seq == 0 || seq&ebit != 0 {
10978 index += rl
10979 continue
10980 }
10981 // Advance to next record.
10982 index += rl
10983 if fseq == 0 {
10984 fseq = seq
10985 }
10986 }
10987
10988 return tombs
10989 }
10990
10991 // Truncate will truncate a stream store up to seq. Sequence needs to be valid.
10992 func (fs *fileStore) Truncate(seq uint64) (rerr error) {
10993 if fs.isClosed() {
10994 return ErrStoreClosed
10995 }
10996
10997 // Check for request to reset.
10998 if seq == 0 {
10999 return fs.reset()
11000 }
11001
11002 fs.mu.Lock()
11003 // Always return previous write errors.
11004 if err := fs.werr; err != nil {
11005 fs.mu.Unlock()
11006 return err
11007 }
11008
11009 // Persist any write errors.
11010 defer func() {
11011 if rerr != nil {
11012 fs.mu.Lock()
11013 fs.setWriteErr(rerr)
11014 fs.mu.Unlock()
11015 }
11016 }()
11017
11018 // Any existing state file will no longer be applicable. We will force write a new one
11019 // at the end, after we release the lock.
11020 os.Remove(filepath.Join(fs.fcfg.StoreDir, msgDir, streamStreamStateFile))
11021
11022 var hasLsm bool
11023 var lastTime int64
11024 smb := fs.selectMsgBlock(seq)
11025 if smb != nil {
11026 smb.mu.Lock()
11027 lsm, _, err := smb.fetchMsgNoCopyLocked(seq, nil)
11028 if lsm != nil {
11029 hasLsm = true
11030 lastTime = lsm.ts
11031 }
11032 smb.finishedWithCache()
11033 smb.mu.Unlock()
11034 if err != nil && err != ErrStoreMsgNotFound && err != errDeletedMsg {
11035 fs.mu.Unlock()
11036 return err
11037 }
11038 }
11039
11040 // Reset last so new block doesn't contain truncated sequences/timestamps.
11041 if !hasLsm {
11042 if smb != nil {
11043 lastTime = smb.last.ts
11044 } else {
11045 lastTime = fs.state.LastTime.UnixNano()
11046 }
11047 }
11048 fs.state.LastSeq = seq
11049 fs.state.LastTime = time.Unix(0, lastTime).UTC()
11050
11051 // Always create a new write block for any tombstones.
11052 // We'll truncate the selected message block as the last step, so can't write tombstones to it.
11053 // If we end up not needing to write tombstones, this block will be cleaned up at the end.
11054 tmb, err := fs.newMsgBlockForWrite()
11055 if err != nil {
11056 fs.mu.Unlock()
11057 return err
11058 }
11059
11060 // The selected message block needs to be removed if it needs to be fully truncated.
11061 var removeSmb bool
11062 if smb != nil {
11063 removeSmb = atomic.LoadUint64(&smb.first.seq) > seq
11064 }
11065
11066 // If the selected block is not found or the message was deleted, we'll need to write a tombstone
11067 // at the truncated sequence so we don't roll backward on our last sequence and timestamp.
11068 if !hasLsm || removeSmb {
11069 if err = fs.writeTombstone(seq, lastTime); err != nil {
11070 fs.mu.Unlock()
11071 return err
11072 }
11073 }
11074
11075 var purged, bytes uint64
11076
11077 // Remove any left over msg blocks.
11078 getLastMsgBlock := func() *msgBlock {
11079 // Start at one before last, tmb will be the last most of the time
11080 // unless a new block gets added for tombstones.
11081 for i := len(fs.blks) - 2; i >= 0; i-- {
11082 if mb := fs.blks[i]; mb.index < tmb.index {
11083 return mb
11084 }
11085 }
11086 return nil
11087 }
11088 for mb := getLastMsgBlock(); mb != nil && mb != smb; mb = getLastMsgBlock() {
11089 mb.mu.Lock()
11090 purged += mb.msgs
11091 bytes += mb.bytes
11092
11093 // We could have tombstones for messages before the truncated sequence.
11094 // Need to store those for blocks we're about to remove.
11095 if tombs := mb.tombsLocked(); len(tombs) > 0 {
11096 // Temporarily unlock while we write tombstones.
11097 mb.mu.Unlock()
11098 for _, tomb := range tombs {
11099 if tomb.seq < seq {
11100 if err = fs.writeTombstone(tomb.seq, tomb.ts); err != nil {
11101 fs.mu.Unlock()
11102 return err
11103 }
11104 }
11105 }
11106 mb.mu.Lock()
11107 }
11108 err = fs.forceRemoveMsgBlock(mb)
11109 mb.mu.Unlock()
11110 if err != nil {
11111 fs.mu.Unlock()
11112 return err
11113 }
11114 }
11115
11116 hasWrittenTombstones := len(tmb.tombs()) > 0
11117 if smb != nil {
11118 smb.mu.Lock()
11119 if removeSmb {
11120 purged += smb.msgs
11121 bytes += smb.bytes
11122
11123 // We could have tombstones for messages before the truncated sequence.
11124 if tombs := smb.tombsLocked(); len(tombs) > 0 {
11125 // Temporarily unlock while we write tombstones.
11126 smb.mu.Unlock()
11127 for _, tomb := range tombs {
11128 if tomb.seq < seq {
11129 if err = fs.writeTombstone(tomb.seq, tomb.ts); err != nil {
11130 fs.mu.Unlock()
11131 return err
11132 }
11133 }
11134 }
11135 smb.mu.Lock()
11136 }
11137 err = fs.forceRemoveMsgBlock(smb)
11138 smb.mu.Unlock()
11139 if err != nil {
11140 fs.mu.Unlock()
11141 return err
11142 }
11143 goto SKIP
11144 }
11145
11146 // Make sure writeable.
11147 if err := smb.enableForWriting(fs.fip); err != nil {
11148 smb.mu.Unlock()
11149 fs.mu.Unlock()
11150 return err
11151 }
11152
11153 // Truncate our selected message block.
11154 nmsgs, nbytes, err := smb.truncate(seq, lastTime)
11155 if err != nil {
11156 smb.mu.Unlock()
11157 fs.mu.Unlock()
11158 return fmt.Errorf("smb.truncate: %w", err)
11159 }
11160 // Account for the truncated msgs and bytes.
11161 purged += nmsgs
11162 bytes += nbytes
11163
11164 // The selected message block is not the last anymore, need to close down resources.
11165 if hasWrittenTombstones {
11166 // Quit our loops.
11167 if smb.qch != nil {
11168 close(smb.qch)
11169 smb.qch = nil
11170 }
11171 smb.closeFDsLockedNoCheck()
11172 smb.recompressOnDiskIfNeeded()
11173 }
11174 smb.mu.Unlock()
11175 }
11176
11177 SKIP:
11178 // If no tombstones were written, we can remove the block and
11179 // purely rely on the selected block as the last block.
11180 if !hasWrittenTombstones {
11181 fs.lmb = smb
11182 tmb.mu.Lock()
11183 err = fs.forceRemoveMsgBlock(tmb)
11184 tmb.mu.Unlock()
11185 if err != nil {
11186 fs.mu.Unlock()
11187 return err
11188 }
11189 }
11190
11191 // Reset last.
11192 fs.state.LastSeq = seq
11193 fs.state.LastTime = time.Unix(0, lastTime).UTC()
11194 // Update msgs and bytes.
11195 if purged > fs.state.Msgs {
11196 purged = fs.state.Msgs
11197 }
11198 fs.state.Msgs -= purged
11199 if bytes > fs.state.Bytes {
11200 bytes = fs.state.Bytes
11201 }
11202 fs.state.Bytes -= bytes
11203
11204 // Reset our subject lookup info.
11205 if err = fs.resetGlobalPerSubjectInfo(); err != nil {
11206 fs.mu.Unlock()
11207 return err
11208 }
11209
11210 fs.dirty++
11211
11212 cb := fs.scb
11213 fs.mu.Unlock()
11214
11215 // Force a new index.db to be written.
11216 if purged > 0 {
11217 fs.forceWriteFullState()
11218 }
11219
11220 if cb != nil {
11221 cb(-int64(purged), -int64(bytes), 0, _EMPTY_)
11222 }
11223
11224 return nil
11225 }
11226
11227 func (fs *fileStore) lastSeq() uint64 {
11228 fs.mu.RLock()
11229 seq := fs.state.LastSeq
11230 fs.mu.RUnlock()
11231 return seq
11232 }
11233
11234 // Returns number of msg blks.
11235 func (fs *fileStore) numMsgBlocks() int {
11236 fs.mu.RLock()
11237 defer fs.mu.RUnlock()
11238 return len(fs.blks)
11239 }
11240
11241 // Will add a new msgBlock.
11242 // Lock should be held.
11243 func (fs *fileStore) addMsgBlock(mb *msgBlock) {
11244 fs.blks = append(fs.blks, mb)
11245 fs.lmb = mb
11246 fs.bim[mb.index] = mb
11247 }
11248
11249 // Remove from our list of blks.
11250 // Both locks should be held.
11251 func (fs *fileStore) removeMsgBlockFromList(mb *msgBlock) {
11252 // Remove from list.
11253 for i, omb := range fs.blks {
11254 if mb == omb {
11255 fs.dirty++
11256 blks := append(fs.blks[:i], fs.blks[i+1:]...)
11257 fs.blks = copyMsgBlocks(blks)
11258 if fs.bim != nil {
11259 delete(fs.bim, mb.index)
11260 }
11261 break
11262 }
11263 }
11264 }
11265
11266 // Removes the msgBlock
11267 // Both locks should be held.
11268 func (fs *fileStore) removeMsgBlock(mb *msgBlock) error {
11269 // Check for us being last message block
11270 lseq, lts := atomic.LoadUint64(&mb.last.seq), mb.last.ts
11271 if mb == fs.lmb {
11272 // Creating a new message write block requires that the lmb lock is not held.
11273 mb.mu.Unlock()
11274 // Write the tombstone to remember since this was last block.
11275 if lmb, err := fs.newMsgBlockForWrite(); err != nil || lmb == nil {
11276 if err != nil {
11277 err = errors.New("lmb missing")
11278 }
11279 // Re-acquire mb lock
11280 mb.mu.Lock()
11281 return err
11282 } else if err = fs.writeTombstone(lseq, lts); err != nil {
11283 // Re-acquire mb lock
11284 mb.mu.Lock()
11285 return err
11286 }
11287 mb.mu.Lock()
11288 } else if lseq == fs.state.LastSeq {
11289 // Need to write a tombstone for the last sequence if we're removing the block containing it.
11290 if err := fs.writeTombstone(lseq, lts); err != nil {
11291 return err
11292 }
11293 }
11294 // Only delete message block after (potentially) writing a tombstone.
11295 // But only if it doesn't contain any tombstones for prior blocks.
11296 if mb.numPriorTombsLocked() > 0 {
11297 return nil
11298 }
11299 return fs.forceRemoveMsgBlock(mb)
11300 }
11301
11302 // Removes the msgBlock, without writing tombstones to ensure the last sequence is preserved.
11303 // Both locks should be held.
11304 func (fs *fileStore) forceRemoveMsgBlock(mb *msgBlock) error {
11305 if err := mb.dirtyCloseWithRemove(true); err != nil {
11306 return err
11307 }
11308 fs.removeMsgBlockFromList(mb)
11309 return nil
11310 }
11311
11312 // Purges and removes the msgBlock from the store.
11313 // Lock should be held.
11314 func (fs *fileStore) purgeMsgBlock(mb *msgBlock) error {
11315 mb.mu.Lock()
11316 // Adjust per-subject tracking if present.
11317 if err := mb.ensurePerSubjectInfoLoaded(); err != nil {
11318 mb.mu.Unlock()
11319 return err
11320 } else if mb.fss != nil {
11321 mb.fss.IterFast(func(bsubj []byte, ss *SimpleState) bool {
11322 subj := bytesToString(bsubj)
11323 for range ss.Msgs {
11324 fs.removePerSubject(subj)
11325 }
11326 return true
11327 })
11328 }
11329 // Clean up scheduled message metadata if we know this block contained any.
11330 if fs.scheduling != nil && mb.schedules > 0 {
11331 if mb.cacheNotLoaded() {
11332 if err := mb.loadMsgsWithLock(); err != nil {
11333 mb.mu.Unlock()
11334 return err
11335 }
11336 }
11337 var smv StoreMsg
11338 fseq, lseq := atomic.LoadUint64(&mb.first.seq), atomic.LoadUint64(&mb.last.seq)
11339 for seq := fseq; seq <= lseq; seq++ {
11340 sm, err := mb.cacheLookupNoCopy(seq, &smv)
11341 if err != nil && err != errDeletedMsg {
11342 mb.mu.Unlock()
11343 return err
11344 }
11345 if sm == nil {
11346 continue
11347 }
11348 if schedule, apiErr := getMessageSchedule(sm.hdr); apiErr == nil && !schedule.IsZero() {
11349 fs.scheduling.remove(seq)
11350 }
11351 }
11352 }
11353 // Update top level accounting.
11354 msgs, bytes := mb.msgs, mb.bytes
11355 if msgs > fs.state.Msgs {
11356 msgs = fs.state.Msgs
11357 }
11358 if bytes > fs.state.Bytes {
11359 bytes = fs.state.Bytes
11360 }
11361 fs.state.Msgs -= msgs
11362 fs.state.Bytes -= bytes
11363 if err := fs.removeMsgBlock(mb); err != nil {
11364 mb.mu.Unlock()
11365 return err
11366 }
11367 mb.tryForceExpireCacheLocked()
11368 mb.finishedWithCache()
11369 mb.mu.Unlock()
11370 if err := fs.selectNextFirst(); err != nil {
11371 return err
11372 }
11373
11374 if cb := fs.scb; cb != nil {
11375 // If we have a callback registered, we need to release lock regardless since consumers will recalculate pending.
11376 fs.mu.Unlock()
11377 // Storage updates.
11378 cb(-int64(msgs), -int64(bytes), 0, _EMPTY_)
11379 fs.mu.Lock()
11380 }
11381 return nil
11382 }
11383
11384 // Called by purge to simply get rid of the cache and close our fds.
11385 // Lock should not be held.
11386 func (mb *msgBlock) dirtyClose() {
11387 mb.mu.Lock()
11388 defer mb.mu.Unlock()
11389 mb.dirtyCloseWithRemove(false)
11390 }
11391
11392 // Should be called with lock held.
11393 func (mb *msgBlock) dirtyCloseWithRemove(remove bool) error {
11394 if mb == nil {
11395 return nil
11396 }
11397 // Stop cache expiration timer.
11398 if mb.ctmr != nil {
11399 mb.ctmr.Stop()
11400 mb.ctmr = nil
11401 }
11402 // Close cache
11403 mb.clearCacheAndOffset()
11404 // Quit our loops.
11405 if mb.qch != nil {
11406 close(mb.qch)
11407 mb.qch = nil
11408 }
11409 if fd := mb.mfd; fd != nil {
11410 mb.mfd = nil
11411 if err := fd.Close(); err != nil && !os.IsNotExist(err) {
11412 return err
11413 }
11414 }
11415 if remove {
11416 // The block is being destroyed, so mark it closed.
11417 mb.closed = true
11418 // Clear any tracking by subject if we are removing.
11419 mb.fss = nil
11420 if mb.mfn != _EMPTY_ {
11421 if err := os.Remove(mb.mfn); err != nil && !os.IsNotExist(err) {
11422 return err
11423 }
11424 mb.mfn = _EMPTY_
11425 }
11426 if mb.kfn != _EMPTY_ {
11427 if err := os.Remove(mb.kfn); err != nil && !os.IsNotExist(err) {
11428 return err
11429 }
11430 }
11431 }
11432 return nil
11433 }
11434
11435 // Remove a seq from the fss and select new first.
11436 // Lock should be held.
11437 func (mb *msgBlock) removeSeqPerSubject(subj string, seq uint64) (uint64, error) {
11438 if err := mb.ensurePerSubjectInfoLoaded(); err != nil {
11439 return 0, err
11440 }
11441 if mb.fss == nil {
11442 return 0, nil
11443 }
11444 bsubj := stringToBytes(subj)
11445 ss, ok := mb.fss.Find(bsubj)
11446 if !ok || ss == nil {
11447 return 0, nil
11448 }
11449
11450 mb.fs.sdm.removeSeqAndSubject(seq, subj)
11451 if ss.Msgs == 1 {
11452 mb.fss.Delete(bsubj)
11453 return 0, nil
11454 }
11455
11456 ss.Msgs--
11457
11458 // Only one left.
11459 if ss.Msgs == 1 {
11460 if !ss.lastNeedsUpdate && seq != ss.Last {
11461 ss.First = ss.Last
11462 ss.firstNeedsUpdate = false
11463 return 1, nil
11464 }
11465 if !ss.firstNeedsUpdate && seq != ss.First {
11466 ss.Last = ss.First
11467 ss.lastNeedsUpdate = false
11468 return 1, nil
11469 }
11470 }
11471
11472 // We can lazily calculate the first/last sequence when needed.
11473 ss.firstNeedsUpdate = seq == ss.First || ss.firstNeedsUpdate
11474 ss.lastNeedsUpdate = seq == ss.Last || ss.lastNeedsUpdate
11475
11476 return ss.Msgs, nil
11477 }
11478
11479 // Will recalculate the first and/or last sequence for this subject in this block.
11480 // Will avoid slower path message lookups and scan the cache directly instead.
11481 func (mb *msgBlock) recalculateForSubj(subj string, ss *SimpleState) error {
11482 // Need to make sure messages are loaded.
11483 needsCleanup := mb.cache == nil
11484 if mb.cacheNotLoaded() {
11485 if err := mb.loadMsgsWithLock(); err != nil {
11486 return err
11487 }
11488 }
11489 if needsCleanup {
11490 defer mb.finishedWithCache()
11491 }
11492
11493 startSlot := int(ss.First - mb.cache.fseq)
11494 if startSlot < 0 {
11495 startSlot = 0
11496 }
11497 if startSlot >= len(mb.cache.idx) {
11498 ss.First = ss.Last
11499 ss.firstNeedsUpdate = false
11500 ss.lastNeedsUpdate = false
11501 return nil
11502 }
11503
11504 endSlot := int(ss.Last - mb.cache.fseq)
11505 if endSlot < 0 {
11506 endSlot = 0
11507 }
11508 if endSlot >= len(mb.cache.idx) || startSlot > endSlot {
11509 return nil
11510 }
11511
11512 var le = binary.LittleEndian
11513 if ss.firstNeedsUpdate {
11514 // Mark first as updated.
11515 ss.firstNeedsUpdate = false
11516
11517 fseq := ss.First + 1
11518 if mbFseq := atomic.LoadUint64(&mb.first.seq); fseq < mbFseq {
11519 fseq = mbFseq
11520 }
11521 for slot := startSlot; slot < len(mb.cache.idx); slot++ {
11522 bi := mb.cache.idx[slot] &^ cbit
11523 if bi == dbit {
11524 // delete marker so skip.
11525 continue
11526 }
11527 li := int(bi)
11528 if li >= len(mb.cache.buf) {
11529 ss.First = ss.Last
11530 // Only need to reset ss.lastNeedsUpdate, ss.firstNeedsUpdate is already reset above.
11531 ss.lastNeedsUpdate = false
11532 return nil
11533 }
11534 buf := mb.cache.buf[li:]
11535 hdr := buf[:msgHdrSize]
11536 slen := int(le.Uint16(hdr[20:]))
11537 if subj == bytesToString(buf[msgHdrSize:msgHdrSize+slen]) {
11538 seq := le.Uint64(hdr[4:])
11539 if seq < fseq || seq&ebit != 0 || mb.dmap.Exists(seq) {
11540 continue
11541 }
11542 ss.First = seq
11543 if ss.Msgs == 1 {
11544 ss.Last = seq
11545 ss.lastNeedsUpdate = false
11546 return nil
11547 }
11548 // Skip the start slot ahead, if we need to recalculate last we can stop early.
11549 startSlot = slot
11550 break
11551 }
11552 }
11553 }
11554 if ss.lastNeedsUpdate {
11555 // Mark last as updated.
11556 ss.lastNeedsUpdate = false
11557
11558 lseq := ss.Last - 1
11559 if mbLseq := atomic.LoadUint64(&mb.last.seq); lseq > mbLseq {
11560 lseq = mbLseq
11561 }
11562 for slot := endSlot; slot >= startSlot; slot-- {
11563 bi := mb.cache.idx[slot] &^ cbit
11564 if bi == dbit {
11565 // delete marker so skip.
11566 continue
11567 }
11568 li := int(bi)
11569 if li >= len(mb.cache.buf) {
11570 // Can't overwrite ss.Last, just skip.
11571 return nil
11572 }
11573 buf := mb.cache.buf[li:]
11574 hdr := buf[:msgHdrSize]
11575 slen := int(le.Uint16(hdr[20:]))
11576 if subj == bytesToString(buf[msgHdrSize:msgHdrSize+slen]) {
11577 seq := le.Uint64(hdr[4:])
11578 if seq > lseq || seq&ebit != 0 || mb.dmap.Exists(seq) {
11579 continue
11580 }
11581 // Sequence should never be lower, but guard against it nonetheless.
11582 if seq < ss.First {
11583 seq = ss.First
11584 }
11585 ss.Last = seq
11586 if ss.Msgs == 1 {
11587 ss.First = seq
11588 ss.firstNeedsUpdate = false
11589 }
11590 return nil
11591 }
11592 }
11593 }
11594 return nil
11595 }
11596
11597 // Lock should be held.
11598 func (fs *fileStore) resetGlobalPerSubjectInfo() error {
11599 // Clear any global subject state.
11600 fs.psim, fs.tsl = fs.psim.Empty(), 0
11601 if fs.noTrackSubjects() {
11602 return nil
11603 }
11604 for _, mb := range fs.blks {
11605 if err := fs.populateGlobalPerSubjectInfo(mb); err != nil {
11606 return err
11607 }
11608 }
11609 return nil
11610 }
11611
11612 // Lock should be held.
11613 func (mb *msgBlock) resetPerSubjectInfo() error {
11614 mb.fss = nil
11615 return mb.generatePerSubjectInfo()
11616 }
11617
11618 // generatePerSubjectInfo will generate the per subject info via the raw msg block.
11619 // Lock should be held.
11620 func (mb *msgBlock) generatePerSubjectInfo() error {
11621 // Check if this mb is empty. This can happen when its the last one and we are holding onto it for seq and timestamp info.
11622 if mb.msgs == 0 {
11623 return nil
11624 }
11625
11626 needsCleanup := mb.cache == nil
11627 if mb.cacheNotLoaded() {
11628 if err := mb.loadMsgsWithLock(); err != nil {
11629 if needsCleanup {
11630 mb.finishedWithCache()
11631 }
11632 return err
11633 }
11634 }
11635 if needsCleanup {
11636 defer mb.finishedWithCache()
11637 }
11638 // indexCacheBuf can produce fss now, so if non-nil we are good.
11639 if mb.fss != nil {
11640 return nil
11641 }
11642
11643 // Create new one regardless.
11644 mb.fss = mb.fss.Empty()
11645
11646 var smv StoreMsg
11647 fseq, lseq := atomic.LoadUint64(&mb.first.seq), atomic.LoadUint64(&mb.last.seq)
11648 for seq := fseq; seq <= lseq; seq++ {
11649 if mb.dmap.Exists(seq) {
11650 // Optimisation to avoid calling cacheLookup which hits time.Now().
11651 // It gets set later on if the fss is non-empty anyway.
11652 continue
11653 }
11654 sm, err := mb.cacheLookupNoCopy(seq, &smv)
11655 if err != nil {
11656 // Since we are walking by sequence we can ignore some errors that are benign to rebuilding our state.
11657 if err == ErrStoreMsgNotFound || err == errDeletedMsg {
11658 continue
11659 }
11660 if err == errNoCache {
11661 return nil
11662 }
11663 // Clear partially built fss so callers don't operate on incomplete state.
11664 mb.fss = nil
11665 mb.clearCacheAndOffset()
11666 return err
11667 }
11668 if sm != nil && len(sm.subj) > 0 {
11669 if ss, ok := mb.fss.Find(stringToBytes(sm.subj)); ok && ss != nil {
11670 ss.Msgs++
11671 ss.Last = seq
11672 ss.lastNeedsUpdate = false
11673 } else {
11674 mb.fss.Insert(stringToBytes(sm.subj), SimpleState{Msgs: 1, First: seq, Last: seq})
11675 }
11676 }
11677 }
11678
11679 if mb.fss.Size() > 0 {
11680 // Make sure we run the cache expire timer.
11681 mb.llts = ats.AccessTime()
11682 // Mark fss activity same as load time.
11683 mb.lsts = mb.llts
11684 mb.startCacheExpireTimer()
11685 }
11686 return nil
11687 }
11688
11689 // Helper to make sure fss loaded if we are tracking.
11690 // Lock should be held
11691 func (mb *msgBlock) ensurePerSubjectInfoLoaded() error {
11692 if mb.fss != nil || mb.noTrack {
11693 if mb.fss != nil {
11694 // Mark fss activity.
11695 mb.lsts = ats.AccessTime()
11696 }
11697 return nil
11698 }
11699 if mb.msgs == 0 {
11700 mb.fss = stree.NewSubjectTree[SimpleState]()
11701 return nil
11702 }
11703 return mb.generatePerSubjectInfo()
11704 }
11705
11706 // Called on recovery to populate the global psim state.
11707 // Lock should be held.
11708 func (fs *fileStore) populateGlobalPerSubjectInfo(mb *msgBlock) error {
11709 mb.mu.Lock()
11710 defer mb.mu.Unlock()
11711
11712 if err := mb.ensurePerSubjectInfoLoaded(); err != nil {
11713 return err
11714 }
11715
11716 // Now populate psim.
11717 mb.fss.IterFast(func(bsubj []byte, ss *SimpleState) bool {
11718 if len(bsubj) > 0 {
11719 if info, ok := fs.psim.Find(bsubj); ok {
11720 info.total += ss.Msgs
11721 if mb.index > info.lblk {
11722 info.lblk = mb.index
11723 }
11724 } else {
11725 fs.psim.Insert(bsubj, psi{total: ss.Msgs, fblk: mb.index, lblk: mb.index})
11726 fs.tsl += len(bsubj)
11727 }
11728 }
11729 return true
11730 })
11731 return nil
11732 }
11733
11734 // Calls os.RemoveAll on the given `dir` directory, but if an error occurs,
11735 // retries up to one second. If that still fails, returns the last error
11736 // that os.RemoveAll returned.
11737 func removeAllWithRetry(dios *diskIOSemaphore, dir string) error {
11738 dios.acquire()
11739 err := os.RemoveAll(dir)
11740 dios.release()
11741 if err == nil {
11742 return nil
11743 }
11744 ttl := time.Now().Add(time.Second)
11745 for time.Now().Before(ttl) {
11746 time.Sleep(10 * time.Millisecond)
11747 dios.acquire()
11748 err = os.RemoveAll(dir)
11749 dios.release()
11750 if err == nil {
11751 return nil
11752 }
11753 }
11754 return err
11755 }
11756
11757 // Close the message block.
11758 func (mb *msgBlock) close(sync bool) {
11759 if mb == nil {
11760 return
11761 }
11762 mb.mu.Lock()
11763 defer mb.mu.Unlock()
11764
11765 if mb.closed {
11766 return
11767 }
11768
11769 // Stop cache expiration timer.
11770 if mb.ctmr != nil {
11771 mb.ctmr.Stop()
11772 mb.ctmr = nil
11773 }
11774
11775 // Clear fss.
11776 mb.fss = nil
11777
11778 // Flush pending writes.
11779 mb.flushPendingMsgsLocked()
11780 // Close cache
11781 mb.clearCacheAndOffset()
11782 // Quit our loops.
11783 if mb.qch != nil {
11784 close(mb.qch)
11785 mb.qch = nil
11786 }
11787 if mb.mfd != nil {
11788 if sync {
11789 mb.mfd.Sync()
11790 }
11791 mb.mfd.Close()
11792 }
11793 mb.mfd = nil
11794 // Mark as closed.
11795 mb.closed = true
11796 }
11797
11798 func (fs *fileStore) closeAllMsgBlocks(sync bool) {
11799 for _, mb := range fs.blks {
11800 mb.close(sync)
11801 }
11802 }
11803
11804 func (fs *fileStore) Delete(inline bool) error {
11805 if fs.isClosed() {
11806 // Always attempt to remove since we could have been closed beforehand.
11807 os.RemoveAll(fs.fcfg.StoreDir)
11808 // Since we did remove, if we did have anything remaining make sure to
11809 // call into any storage updates that had been registered.
11810 fs.mu.Lock()
11811 cb, msgs, bytes := fs.scb, int64(fs.state.Msgs), int64(fs.state.Bytes)
11812 // Guard against double accounting if called twice.
11813 fs.state.Msgs, fs.state.Bytes = 0, 0
11814 fs.mu.Unlock()
11815 if msgs > 0 && cb != nil {
11816 cb(-msgs, -bytes, 0, _EMPTY_)
11817 }
11818 return ErrStoreClosed
11819 }
11820
11821 pdir := filepath.Join(fs.fcfg.StoreDir, purgeDir)
11822 if _, err := os.Stat(pdir); err == nil {
11823 _ = os.RemoveAll(pdir)
11824 }
11825
11826 // Quickly close all blocks and simulate a purge w/o overhead an new write block.
11827 fs.mu.Lock()
11828 for _, mb := range fs.blks {
11829 mb.dirtyClose()
11830 }
11831 dmsgs := fs.state.Msgs
11832 dbytes := int64(fs.state.Bytes)
11833 fs.state.Msgs, fs.state.Bytes = 0, 0
11834 fs.blks = nil
11835 cb := fs.scb
11836 fs.mu.Unlock()
11837
11838 if cb != nil {
11839 cb(-int64(dmsgs), -dbytes, 0, _EMPTY_)
11840 }
11841
11842 if err := fs.stop(true, false); err != nil {
11843 return err
11844 }
11845
11846 // Make sure we will not try to recover if killed before removal below completes.
11847 if err := os.Remove(filepath.Join(fs.fcfg.StoreDir, JetStreamMetaFile)); err != nil {
11848 return err
11849 }
11850 // Now move into different directory with "." prefix.
11851 ndir := filepath.Join(filepath.Dir(fs.fcfg.StoreDir), tsep+filepath.Base(fs.fcfg.StoreDir))
11852 if err := os.Rename(fs.fcfg.StoreDir, ndir); err != nil {
11853 return err
11854 }
11855 // Do this in separate Go routine in case lots of blocks.
11856 // Purge above protects us as does the removal of meta artifacts above.
11857 if inline {
11858 if err := removeAllWithRetry(fs.dios, ndir); err != nil {
11859 return err
11860 }
11861 } else {
11862 go removeAllWithRetry(fs.dios, ndir)
11863 }
11864 return nil
11865 }
11866
11867 // Lock should be held.
11868 func (fs *fileStore) setSyncTimer() {
11869 if fs.syncTmr != nil {
11870 fs.syncTmr.Reset(fs.fcfg.SyncInterval)
11871 } else {
11872 // First time this fires will be between SyncInterval/2 and SyncInterval,
11873 // so that different stores are spread out, rather than having many of
11874 // them trying to all sync at once, causing blips and contending dios.
11875 start := (fs.fcfg.SyncInterval / 2) + (time.Duration(mrand.Int63n(int64(fs.fcfg.SyncInterval / 2))))
11876 fs.syncTmr = time.AfterFunc(start, fs.syncBlocks)
11877 }
11878 }
11879
11880 // Lock should be held.
11881 func (fs *fileStore) cancelSyncTimer() {
11882 if fs.syncTmr != nil {
11883 fs.syncTmr.Stop()
11884 fs.syncTmr = nil
11885 }
11886 }
11887
11888 // The full state file is versioned.
11889 // - 0x1: original binary index.db format
11890 // - 0x2: adds support for TTL count field after num deleted
11891 const (
11892 fullStateMagic = uint8(11)
11893 fullStateMinVersion = uint8(1) // What is the minimum version we know how to parse?
11894 fullStateVersion = uint8(4) // What is the current version written out to index.db?
11895 )
11896
11897 // This go routine periodically writes out our full stream state index.
11898 func (fs *fileStore) flushStreamStateLoop(qch, done chan struct{}) {
11899 // Signal we are done on exit.
11900 defer close(done)
11901
11902 // Make sure we do not try to write these out too fast.
11903 // Spread these out for large numbers on a server restart.
11904 const writeThreshold = 2 * time.Minute
11905 writeJitter := time.Duration(mrand.Int63n(int64(30 * time.Second)))
11906 t := time.NewTicker(writeThreshold + writeJitter)
11907 defer t.Stop()
11908
11909 for {
11910 select {
11911 case <-t.C:
11912 err := fs.writeFullState()
11913 if isPermissionError(err) && fs.srv != nil {
11914 fs.warn("File system permission denied when flushing stream state, disabling JetStream: %v", err)
11915 // messages in block cache could be lost in the worst case.
11916 // In the clustered mode it is very highly unlikely as a result of replication.
11917 fs.srv.ShutdownJetStream()
11918 return
11919 }
11920
11921 case <-qch:
11922 return
11923 }
11924 }
11925 }
11926
11927 // Helper since unixnano of zero time undefined.
11928 func timestampNormalized(t time.Time) int64 {
11929 if t.IsZero() {
11930 return 0
11931 }
11932 return t.UnixNano()
11933 }
11934
11935 // writeFullState will proceed to write the full meta state iff not complex and time consuming.
11936 // Since this is for quick recovery it is optional and should not block/stall normal operations.
11937 func (fs *fileStore) writeFullState() error {
11938 return fs._writeFullState(false)
11939 }
11940
11941 // forceWriteFullState will proceed to write the full meta state.
11942 func (fs *fileStore) forceWriteFullState() error {
11943 return fs._writeFullState(true)
11944 }
11945
11946 // This will write the full binary state for the stream.
11947 // This plus everything new since last hash will be the total recovered state.
11948 // This state dump will have the following.
11949 // 1. Stream summary - Msgs, Bytes, First and Last (Sequence and Timestamp)
11950 // 2. PSIM - Per Subject Index Map - Tracks first and last blocks with subjects present.
11951 // 3. MBs - Index, Bytes, First and Last Sequence and Timestamps, and the deleted map (avl.seqset).
11952 // 4. Last block index and hash of record inclusive to this stream state.
11953 func (fs *fileStore) _writeFullState(force bool) error {
11954 if fs.isClosed() {
11955 return nil
11956 }
11957
11958 // If we aren't forcing an update then only queue this up if we aren't already
11959 // running. This means we can keep waiting on shutdown if needed but not build up
11960 // lots of waiting goroutines in a bad timer case.
11961 if fs.wfsrun.Add(1) > 1 && !force {
11962 fs.wfsrun.Add(-1)
11963 return nil
11964 }
11965 defer fs.wfsrun.Add(-1)
11966
11967 // Only allow one _writeFullState to take place at a time, otherwise we can
11968 // have multiple goroutines trying to write the same file after we've released
11969 // the store lock.
11970 fs.wfsmu.Lock()
11971 defer fs.wfsmu.Unlock()
11972
11973 start := time.Now()
11974 fs.mu.RLock()
11975 if fs.dirty == 0 {
11976 fs.mu.RUnlock()
11977 return nil
11978 }
11979
11980 // Configure encryption if needed.
11981 if fs.prf != nil {
11982 // Re-acquire temporarily as write lock to set up AEK.
11983 fs.mu.RUnlock()
11984 fs.mu.Lock()
11985 err := fs.setupAEK()
11986 fs.mu.Unlock()
11987 if err != nil {
11988 return err
11989 }
11990 fs.mu.RLock()
11991 }
11992
11993 // For calculating size and checking time costs for non forced calls.
11994 numSubjects := fs.numSubjects()
11995
11996 // If we are not being forced to write out our state, check the complexity for time costs as to not
11997 // block or stall normal operations.
11998 // We will base off of number of subjects and interior deletes. A very large number of msg blocks could also
11999 // be used, but for next server version will redo all meta handling to be disk based. So this is temporary.
12000 if !force {
12001 // Calculate interior deletes.
12002 var numDeleted int
12003 if fs.state.LastSeq > fs.state.FirstSeq {
12004 numDeleted = int((fs.state.LastSeq - fs.state.FirstSeq + 1) - fs.state.Msgs)
12005 }
12006 if numSubjects > highCardinalityThreshold || numDeleted > highCardinalityThreshold {
12007 fs.mu.RUnlock()
12008 return errStateTooBig
12009 }
12010 }
12011
12012 // We track this through subsequent runs to get an avg per blk used for subsequent runs.
12013 avgDmapLen := fs.wfsadml
12014 // If first time through could be 0
12015 if avgDmapLen == 0 && ((fs.state.LastSeq-fs.state.FirstSeq+1)-fs.state.Msgs) > 0 {
12016 avgDmapLen = 1024
12017 }
12018
12019 // Calculate and estimate of the uper bound on the size to avoid multiple allocations.
12020 sz := hdrLen + // Magic and Version
12021 (binary.MaxVarintLen64 * 6) + // FS data
12022 binary.MaxVarintLen64 + fs.tsl + // NumSubjects + total subject length
12023 numSubjects*(binary.MaxVarintLen64*4) + // psi record
12024 binary.MaxVarintLen64 + // Num blocks.
12025 len(fs.blks)*((binary.MaxVarintLen64*8)+avgDmapLen) + // msg blocks, avgDmapLen is est for dmaps
12026 binary.MaxVarintLen64 + 8 + 8 // last index + record checksum + full state checksum
12027
12028 // Do 4k on stack if possible.
12029 const ssz = 4 * 1024
12030 var buf []byte
12031
12032 if sz <= ssz {
12033 var _buf [ssz]byte
12034 buf, sz = _buf[0:hdrLen:ssz], ssz
12035 } else {
12036 buf = make([]byte, hdrLen, sz)
12037 }
12038
12039 buf[0], buf[1] = fullStateMagic, fullStateVersion
12040 buf = binary.AppendUvarint(buf, fs.state.Msgs)
12041 buf = binary.AppendUvarint(buf, fs.state.Bytes)
12042 buf = binary.AppendUvarint(buf, fs.state.FirstSeq)
12043 buf = binary.AppendVarint(buf, timestampNormalized(fs.state.FirstTime))
12044 buf = binary.AppendUvarint(buf, fs.state.LastSeq)
12045 buf = binary.AppendVarint(buf, timestampNormalized(fs.state.LastTime))
12046
12047 // Do per subject information map if applicable.
12048 buf = binary.AppendUvarint(buf, uint64(numSubjects))
12049 if numSubjects > 0 {
12050 fs.psim.Match([]byte(fwcs), func(subj []byte, psi *psi) {
12051 buf = binary.AppendUvarint(buf, uint64(len(subj)))
12052 buf = append(buf, subj...)
12053 buf = binary.AppendUvarint(buf, psi.total)
12054 buf = binary.AppendUvarint(buf, uint64(psi.fblk))
12055 buf = binary.AppendUvarint(buf, uint64(psi.lblk))
12056 })
12057 }
12058
12059 // Now walk all blocks and write out first and last and optional dmap encoding.
12060 var lbi uint32
12061 var lchk [8]byte
12062
12063 nb := len(fs.blks)
12064 buf = binary.AppendUvarint(buf, uint64(nb))
12065
12066 // Use basetime to save some space.
12067 baseTime := timestampNormalized(fs.state.FirstTime)
12068 var scratch [8 * 1024]byte
12069
12070 // Track the state as represented by the mbs.
12071 var mstate StreamState
12072
12073 var dmapTotalLen int
12074 for _, mb := range fs.blks {
12075 mb.mu.RLock()
12076 buf = binary.AppendUvarint(buf, uint64(mb.index))
12077 buf = binary.AppendUvarint(buf, mb.bytes)
12078 buf = binary.AppendUvarint(buf, atomic.LoadUint64(&mb.first.seq))
12079 buf = binary.AppendVarint(buf, mb.first.ts-baseTime)
12080 buf = binary.AppendUvarint(buf, atomic.LoadUint64(&mb.last.seq))
12081 buf = binary.AppendVarint(buf, mb.last.ts-baseTime)
12082
12083 numDeleted := mb.dmap.Size()
12084 buf = binary.AppendUvarint(buf, uint64(numDeleted))
12085 buf = binary.AppendUvarint(buf, mb.ttls) // Field is new in version 2
12086 buf = binary.AppendUvarint(buf, mb.schedules) // Field is new in version 3
12087 if numDeleted > 0 {
12088 dmap := mb.dmap.Encode(scratch[:0])
12089 dmapTotalLen += len(dmap)
12090 buf = append(buf, dmap...)
12091 }
12092 // If this is the last one grab the last checksum and the block index, e.g. 22.blk, 22 is the block index.
12093 // We use this to quickly open this file on recovery.
12094 if mb == fs.lmb {
12095 lbi = mb.index
12096 mb.ensureLastChecksumLoaded()
12097 copy(lchk[0:], mb.lchk[:])
12098 }
12099 updateTrackingState(&mstate, mb)
12100 mb.mu.RUnlock()
12101 }
12102 if dmapTotalLen > 0 {
12103 fs.wfsadml = dmapTotalLen / len(fs.blks)
12104 }
12105
12106 // Place block index and hash onto the end.
12107 buf = binary.AppendUvarint(buf, uint64(lbi))
12108 buf = append(buf, lchk[:]...)
12109
12110 // Encrypt if needed.
12111 if fs.prf != nil {
12112 nonce := make([]byte, fs.aek.NonceSize(), fs.aek.NonceSize()+len(buf)+fs.aek.Overhead())
12113 if n, err := rand.Read(nonce); err != nil {
12114 fs.mu.RUnlock()
12115 return err
12116 } else if n != len(nonce) {
12117 fs.mu.RUnlock()
12118 return fmt.Errorf("not enough nonce bytes read (%d != %d)", n, len(nonce))
12119 }
12120 buf = fs.aek.Seal(nonce, nonce, buf, nil)
12121 }
12122
12123 fn := filepath.Join(fs.fcfg.StoreDir, msgDir, streamStreamStateFile)
12124
12125 // Need to have our own hasher here, as under a read lock we can't mutate the
12126 // fs.hh safely.
12127 key := sha256.Sum256([]byte(fs.cfg.Name))
12128 hh, _ := highwayhash.NewDigest64(key[:])
12129 hh.Write(buf)
12130 buf = hh.Sum(buf)
12131
12132 // Snapshot prior dirty count.
12133 priorDirty := fs.dirty
12134
12135 statesEqual := trackingStatesEqual(&fs.state, &mstate)
12136 // Release lock.
12137 fs.mu.RUnlock()
12138
12139 // Check consistency here.
12140 if !statesEqual {
12141 fs.warn("Stream state encountered internal inconsistency on write")
12142 // Rebuild our fs state from the mb state.
12143 fs.rebuildState(nil)
12144 return errCorruptState
12145 }
12146
12147 if cap(buf) > sz {
12148 fs.debug("WriteFullState reallocated from %d to %d", sz, cap(buf))
12149 }
12150
12151 // Only warn about construction time since file write not holding any locks.
12152 if took := time.Since(start); took > time.Minute {
12153 fs.warn("WriteFullState took %v (%d bytes)", took.Round(time.Millisecond), len(buf))
12154 }
12155
12156 // Write our update index.db
12157 // Protect with dios.
12158 fs.dios.acquire()
12159 err := os.WriteFile(fn, buf, defaultFilePerms)
12160 // if file system is not writable isPermissionError is set to true
12161 fs.dios.release()
12162 if err != nil {
12163 return err
12164 }
12165
12166 // Update dirty if successful.
12167 fs.mu.Lock()
12168 fs.dirty -= priorDirty
12169 fs.mu.Unlock()
12170
12171 // Attempt to write both files, an error in one should not prevent the other from being written.
12172 ttlErr := fs.writeTTLState()
12173 schedErr := fs.writeMsgSchedulingState()
12174 if ttlErr != nil {
12175 return ttlErr
12176 } else if schedErr != nil {
12177 return schedErr
12178 }
12179 return nil
12180 }
12181
12182 func (fs *fileStore) writeTTLState() error {
12183 fs.mu.RLock()
12184 if fs.ttls == nil {
12185 fs.mu.RUnlock()
12186 return nil
12187 }
12188 fn := filepath.Join(fs.fcfg.StoreDir, msgDir, ttlStreamStateFile)
12189 // Must be lseq+1 to identify up to which sequence the TTLs are valid.
12190 buf := fs.ttls.Encode(fs.state.LastSeq + 1)
12191 fs.mu.RUnlock()
12192
12193 return fs.writeFileWithOptionalSync(fn, buf, defaultFilePerms)
12194 }
12195
12196 func (fs *fileStore) writeMsgSchedulingState() error {
12197 fs.mu.RLock()
12198 if fs.scheduling == nil {
12199 fs.mu.RUnlock()
12200 return nil
12201 }
12202 fn := filepath.Join(fs.fcfg.StoreDir, msgDir, msgSchedulingStreamStateFile)
12203 // Must be lseq+1 to identify up to which sequence the schedules are valid.
12204 buf := fs.scheduling.encode(fs.state.LastSeq + 1)
12205 fs.mu.RUnlock()
12206
12207 return fs.writeFileWithOptionalSync(fn, buf, defaultFilePerms)
12208 }
12209
12210 // Stop the current filestore.
12211 func (fs *fileStore) Stop() error {
12212 return fs.stop(false, true)
12213 }
12214
12215 // Stop the current filestore.
12216 func (fs *fileStore) stop(delete, writeState bool) error {
12217 if fs.isClosed() {
12218 return ErrStoreClosed
12219 }
12220
12221 fs.mu.Lock()
12222 if fs.closing {
12223 fs.mu.Unlock()
12224 return ErrStoreClosed
12225 }
12226
12227 // Mark as closing. Do before releasing the lock to wait on the state flush loop
12228 // so we don't end up with this function running more than once.
12229 fs.closing = true
12230
12231 // Release the state flusher loop.
12232 if fs.qch != nil {
12233 close(fs.qch)
12234 fs.qch = nil
12235 }
12236
12237 if writeState {
12238 // Wait for the state flush loop to exit.
12239 fsld := fs.fsld
12240 fs.mu.Unlock()
12241 <-fsld
12242 fs.mu.Lock()
12243
12244 fs.checkAndFlushLastBlock()
12245 }
12246 fs.closeAllMsgBlocks(false)
12247
12248 fs.cancelSyncTimer()
12249 fs.cancelAgeChk()
12250
12251 if writeState {
12252 // Write full state if needed. If not dirty this is a no-op.
12253 fs.mu.Unlock()
12254 fs.forceWriteFullState()
12255 fs.mu.Lock()
12256 }
12257
12258 // Mark as closed. Last message block needs to be cleared after
12259 // writeFullState has completed.
12260 fs.closed.Store(true)
12261 fs.lmb = nil
12262
12263 // We should update the upper usage layer on a stop.
12264 cb, bytes := fs.scb, int64(fs.state.Bytes)
12265 fs.mu.Unlock()
12266
12267 fs.cmu.Lock()
12268 var _cfs [256]ConsumerStore
12269 cfs := append(_cfs[:0], fs.cfs...)
12270 fs.cfs = nil
12271 fs.cmu.Unlock()
12272
12273 for _, o := range cfs {
12274 if delete {
12275 o.StreamDelete()
12276 } else {
12277 o.Stop()
12278 }
12279 }
12280
12281 if bytes > 0 && cb != nil {
12282 cb(0, -bytes, 0, _EMPTY_)
12283 }
12284
12285 // Unregister from the access time service.
12286 ats.Unregister()
12287
12288 return nil
12289 }
12290
12291 const errFile = "errors.txt"
12292
12293 // Stream our snapshot through S2 compression and tar.
12294 func (fs *fileStore) streamSnapshot(w io.WriteCloser, includeConsumers bool, errCh chan string) {
12295 defer close(errCh)
12296 defer w.Close()
12297
12298 enc := s2.NewWriter(w)
12299 defer enc.Close()
12300
12301 tw := tar.NewWriter(enc)
12302 defer tw.Close()
12303
12304 defer func() {
12305 fs.mu.Lock()
12306 fs.sips--
12307 fs.mu.Unlock()
12308 }()
12309
12310 modTime := time.Now().UTC()
12311
12312 writeFile := func(name string, buf []byte) error {
12313 hdr := &tar.Header{
12314 Name: name,
12315 Mode: 0600,
12316 ModTime: modTime,
12317 Uname: "nats",
12318 Gname: "nats",
12319 Size: int64(len(buf)),
12320 Format: tar.FormatPAX,
12321 }
12322 if err := tw.WriteHeader(hdr); err != nil {
12323 return err
12324 }
12325 if _, err := tw.Write(buf); err != nil {
12326 return err
12327 }
12328 return nil
12329 }
12330
12331 writeErr := func(err string) {
12332 writeFile(errFile, []byte(err))
12333 errCh <- err
12334 }
12335
12336 fs.mu.Lock()
12337 blks := fs.blks
12338 // Grab our general meta data.
12339 // We do this now instead of pulling from files since they could be encrypted.
12340 meta, err := json.Marshal(fs.cfg)
12341 if err != nil {
12342 fs.mu.Unlock()
12343 writeErr(fmt.Sprintf("Could not gather stream meta file: %v", err))
12344 return
12345 }
12346 hh := fs.hh
12347 hh.Reset()
12348 hh.Write(meta)
12349 var hb [highwayhash.Size64]byte
12350 sum := []byte(hex.EncodeToString(fs.hh.Sum(hb[:0])))
12351 fs.mu.Unlock()
12352
12353 // Meta first.
12354 if writeFile(JetStreamMetaFile, meta) != nil {
12355 return
12356 }
12357 if writeFile(JetStreamMetaFileSum, sum) != nil {
12358 return
12359 }
12360
12361 // Can't use join path here, tar only recognizes relative paths with forward slashes.
12362 msgPre := msgDir + "/"
12363 var bbuf []byte
12364
12365 // Now do messages themselves.
12366 for _, mb := range blks {
12367 if mb.pendingWriteSize() > 0 {
12368 mb.flushPendingMsgs()
12369 }
12370 mb.mu.Lock()
12371 // We could stream but don't want to hold the lock and prevent changes, so just read in and
12372 // release the lock for now.
12373 bbuf, err = mb.loadBlock(bbuf)
12374 if err != nil {
12375 mb.mu.Unlock()
12376 writeErr(fmt.Sprintf("Could not read message block [%d]: %v", mb.index, err))
12377 return
12378 }
12379 // Check for encryption.
12380 if mb.bek != nil && len(bbuf) > 0 {
12381 rbek, err := genBlockEncryptionKey(fs.fcfg.Cipher, mb.seed, mb.nonce)
12382 if err != nil {
12383 mb.mu.Unlock()
12384 writeErr(fmt.Sprintf("Could not create encryption key for message block [%d]: %v", mb.index, err))
12385 return
12386 }
12387 rbek.XORKeyStream(bbuf, bbuf)
12388 }
12389 // Check for compression.
12390 if bbuf, err = mb.decompressIfNeeded(bbuf); err != nil {
12391 mb.mu.Unlock()
12392 writeErr(fmt.Sprintf("Could not decompress message block [%d]: %v", mb.index, err))
12393 return
12394 }
12395 mb.mu.Unlock()
12396
12397 // Do this one unlocked.
12398 if writeFile(msgPre+fmt.Sprintf(blkScan, mb.index), bbuf) != nil {
12399 return
12400 }
12401 }
12402
12403 // Do index.db last. We will force a write as well.
12404 // Write out full state as well before proceeding.
12405 if err := fs.forceWriteFullState(); err == nil {
12406 const minLen = 32
12407 sfn := filepath.Join(fs.fcfg.StoreDir, msgDir, streamStreamStateFile)
12408 if buf, err := os.ReadFile(sfn); err == nil && len(buf) >= minLen {
12409 fs.mu.Lock()
12410 if fs.aek != nil {
12411 ns := fs.aek.NonceSize()
12412 buf, err = fs.aek.Open(nil, buf[:ns], buf[ns:len(buf)-highwayhash.Size64], nil)
12413 if err == nil {
12414 // Redo hash checksum at end on plaintext.
12415 hh.Reset()
12416 hh.Write(buf)
12417 buf = fs.hh.Sum(buf)
12418 }
12419 }
12420 fs.mu.Unlock()
12421 if err == nil && writeFile(msgPre+streamStreamStateFile, buf) != nil {
12422 return
12423 }
12424 }
12425 }
12426
12427 // Bail if no consumers requested.
12428 if !includeConsumers {
12429 return
12430 }
12431
12432 // Do consumers' state last.
12433 fs.cmu.RLock()
12434 cfs := fs.cfs
12435 fs.cmu.RUnlock()
12436
12437 for _, cs := range cfs {
12438 o, ok := cs.(*consumerFileStore)
12439 if !ok {
12440 continue
12441 }
12442 o.mu.Lock()
12443 // Grab our general meta data.
12444 // We do this now instead of pulling from files since they could be encrypted.
12445 meta, err := json.Marshal(o.cfg)
12446 if err != nil {
12447 o.mu.Unlock()
12448 writeErr(fmt.Sprintf("Could not gather consumer meta file for %q: %v", o.name, err))
12449 return
12450 }
12451 o.hh.Reset()
12452 o.hh.Write(meta)
12453 var hb [highwayhash.Size64]byte
12454 sum := []byte(hex.EncodeToString(o.hh.Sum(hb[:0])))
12455
12456 // We can have the running state directly encoded now.
12457 state, err := o.encodeState()
12458 if err != nil {
12459 o.mu.Unlock()
12460 writeErr(fmt.Sprintf("Could not encode consumer state for %q: %v", o.name, err))
12461 return
12462 }
12463 odirPre := filepath.Join(consumerDir, o.name)
12464 o.mu.Unlock()
12465
12466 // Write all the consumer files.
12467 if writeFile(filepath.Join(odirPre, JetStreamMetaFile), meta) != nil {
12468 return
12469 }
12470 if writeFile(filepath.Join(odirPre, JetStreamMetaFileSum), sum) != nil {
12471 return
12472 }
12473 writeFile(filepath.Join(odirPre, consumerState), state)
12474 }
12475 }
12476
12477 // Create a snapshot of this stream and its consumer's state along with messages.
12478 func (fs *fileStore) Snapshot(deadline time.Duration, checkMsgs, includeConsumers bool) (*SnapshotResult, error) {
12479 if fs.isClosed() {
12480 return nil, ErrStoreClosed
12481 }
12482
12483 fs.mu.Lock()
12484
12485 // Only allow one at a time.
12486 if fs.sips > 0 {
12487 fs.mu.Unlock()
12488 return nil, ErrStoreSnapshotInProgress
12489 }
12490 // Mark us as snapshotting
12491 fs.sips += 1
12492 fs.mu.Unlock()
12493
12494 if checkMsgs {
12495 ld, err := fs.checkMsgs()
12496 clearSips := func() {
12497 fs.mu.Lock()
12498 fs.sips--
12499 fs.mu.Unlock()
12500 }
12501 if err != nil {
12502 clearSips()
12503 return nil, fmt.Errorf("snapshot check failed: %w", err)
12504 }
12505 if ld != nil && len(ld.Msgs) > 0 {
12506 clearSips()
12507 return nil, fmt.Errorf("snapshot check detected %d bad messages", len(ld.Msgs))
12508 }
12509 }
12510
12511 pr, pw := net.Pipe()
12512
12513 // Set a write deadline here to protect ourselves.
12514 if deadline > 0 {
12515 pw.SetWriteDeadline(time.Now().Add(deadline))
12516 }
12517
12518 // We can add to our stream while snapshotting but not "user" delete anything.
12519 var state StreamState
12520 fs.FastState(&state)
12521
12522 // Stream in separate Go routine.
12523 errCh := make(chan string, 1)
12524 go fs.streamSnapshot(pw, includeConsumers, errCh)
12525
12526 return &SnapshotResult{pr, state, errCh}, nil
12527 }
12528
12529 // Helper to return the config.
12530 func (fs *fileStore) fileStoreConfig() FileStoreConfig {
12531 fs.mu.RLock()
12532 defer fs.mu.RUnlock()
12533 return fs.fcfg
12534 }
12535
12536 // Read lock all existing message blocks.
12537 // Lock held on entry.
12538 func (fs *fileStore) readLockAllMsgBlocks() {
12539 for _, mb := range fs.blks {
12540 mb.mu.RLock()
12541 }
12542 }
12543
12544 // Read unlock all existing message blocks.
12545 // Lock held on entry.
12546 func (fs *fileStore) readUnlockAllMsgBlocks() {
12547 for _, mb := range fs.blks {
12548 mb.mu.RUnlock()
12549 }
12550 }
12551
12552 // Binary encoded state snapshot, >= v2.10 server.
12553 func (fs *fileStore) EncodedStreamState(failed uint64) ([]byte, error) {
12554 fs.mu.RLock()
12555 defer fs.mu.RUnlock()
12556
12557 // Calculate deleted.
12558 var numDeleted int64
12559 if fs.state.LastSeq > fs.state.FirstSeq {
12560 numDeleted = int64(fs.state.LastSeq-fs.state.FirstSeq+1) - int64(fs.state.Msgs)
12561 if numDeleted < 0 {
12562 numDeleted = 0
12563 }
12564 }
12565
12566 // Encoded is Msgs, Bytes, FirstSeq, LastSeq, Failed, NumDeleted and optional DeletedBlocks.
12567 // Calculate the exact encoded size up front so the buffer is allocated once.
12568 total := hdrLen + uvarintLen(fs.state.Msgs) + uvarintLen(fs.state.Bytes) +
12569 uvarintLen(fs.state.FirstSeq) + uvarintLen(fs.state.LastSeq) +
12570 uvarintLen(failed) + uvarintLen(uint64(numDeleted))
12571
12572 var dbs DeleteBlocks
12573 if numDeleted > 0 {
12574 fs.readLockAllMsgBlocks()
12575 defer fs.readUnlockAllMsgBlocks()
12576 var sz int
12577 dbs, sz = fs.deleteBlocks()
12578 total += sz
12579 }
12580
12581 b := make([]byte, 0, total)
12582 b = append(b, streamStateMagic, streamStateVersion)
12583 b = binary.AppendUvarint(b, fs.state.Msgs)
12584 b = binary.AppendUvarint(b, fs.state.Bytes)
12585 b = binary.AppendUvarint(b, fs.state.FirstSeq)
12586 b = binary.AppendUvarint(b, fs.state.LastSeq)
12587 b = binary.AppendUvarint(b, failed)
12588 b = binary.AppendUvarint(b, uint64(numDeleted))
12589
12590 for _, db := range dbs {
12591 switch db := db.(type) {
12592 case *DeleteRange:
12593 b = appendRunLength(b, db.First, db.Num)
12594 case *avl.SequenceSet:
12595 enc := db.Encode(b[len(b):])
12596 if n := len(b) + len(enc); n <= cap(b) {
12597 b = b[:n]
12598 } else {
12599 // Fallback if the buffer didn't have spare capacity.
12600 b = append(b, enc...)
12601 }
12602 default:
12603 return nil, errors.New("no impl")
12604 }
12605 }
12606
12607 if len(b) != total {
12608 assert.Unreachable("Filestore EncodedStreamState size accounting mismatch", map[string]any{
12609 "name": fs.cfg.Name,
12610 "total": total,
12611 "length": len(b),
12612 })
12613 }
12614 return b, nil
12615 }
12616
12617 // deleteBlocks returns DeleteBlocks representing interior deletes
12618 // and gaps between blocks, as well as their total binary encoded size.
12619 // All blocks should be at least read locked.
12620 func (fs *fileStore) deleteBlocks() (dbs DeleteBlocks, sz int) {
12621 var prevLast uint64
12622 var prevRange *DeleteRange
12623 var msgsSinceGap bool
12624
12625 for _, mb := range fs.blks {
12626 // Detect if we have a gap between these blocks.
12627 fseq := atomic.LoadUint64(&mb.first.seq)
12628 if prevLast > 0 && prevLast+1 != fseq {
12629 gapSize := fseq - prevLast - 1
12630 // The previous DeleteRange can be extended
12631 // to include this gap, if there are no
12632 // blocks containing messages between the
12633 // two gaps.
12634 if prevRange != nil && !msgsSinceGap {
12635 sz -= runLengthEncodeLen(prevRange.First, prevRange.Num)
12636 prevRange.Num += gapSize
12637 sz += runLengthEncodeLen(prevRange.First, prevRange.Num)
12638 } else {
12639 prevRange = &DeleteRange{
12640 First: prevLast + 1,
12641 Num: gapSize,
12642 }
12643 sz += runLengthEncodeLen(prevRange.First, prevRange.Num)
12644 msgsSinceGap = false
12645 dbs = append(dbs, prevRange)
12646 }
12647 }
12648 if mb.dmap.Size() > 0 {
12649 dbs = append(dbs, &mb.dmap)
12650 sz += mb.dmap.EncodeLen()
12651 prevRange = nil
12652 }
12653 prevLast = atomic.LoadUint64(&mb.last.seq)
12654 msgsSinceGap = msgsSinceGap || mb.msgs > 0
12655 }
12656 return dbs, sz
12657 }
12658
12659 // interiorDeletes is a point-in-time view of the interior deletes tracked by
12660 // the live message blocks, held as per-block clones of each mb.dmap. Blocks
12661 // own disjoint ascending sequence ranges, so a lookup binary searches for the
12662 // owning clone. Reads require no locks.
12663 type interiorDeletes struct {
12664 sets []*avl.SequenceSet // Per-block dmap clones, ascending disjoint ranges.
12665 maxs []uint64 // Last sequence of the block owning each clone.
12666 last int // Clone index of the previous lookup.
12667 }
12668
12669 // Exists returns whether the sequence was marked as an interior delete by a
12670 // live block at the time the view was built.
12671 // Not safe for concurrent use.
12672 func (v *interiorDeletes) Exists(seq uint64) bool {
12673 if v == nil {
12674 return false
12675 }
12676 // Check the clone that answered the previous lookup first, sequences are
12677 // mostly checked in ascending order and cluster per block.
12678 if i := v.last; i < len(v.maxs) && seq <= v.maxs[i] && (i == 0 || v.maxs[i-1] < seq) {
12679 return v.sets[i].Exists(seq)
12680 }
12681 // First clone whose max is >= seq is the only one that can contain it.
12682 i, _ := slices.BinarySearch(v.maxs, seq)
12683 if i == len(v.sets) {
12684 return false
12685 }
12686 v.last = i
12687 return v.sets[i].Exists(seq)
12688 }
12689
12690 // deleteMap returns a view of all interior deletes for each of the given blocks,
12691 // based on the mb.dmap. Specifically, this will not contain any deletes for blocks
12692 // that had already been removed. This is useful to know whether a tombstone is
12693 // still relevant and marked as deleted by an active block.
12694 // No locks should be held on entry.
12695 func deleteMap(blks []*msgBlock) *interiorDeletes {
12696 v := interiorDeletes{
12697 sets: make([]*avl.SequenceSet, 0, len(blks)),
12698 maxs: make([]uint64, 0, len(blks)),
12699 }
12700 for _, mb := range blks {
12701 mb.mu.RLock()
12702 if !mb.closed && mb.dmap.Size() > 0 {
12703 // The block's last sequence bounds all of its dmap entries and
12704 // preserves the ascending disjoint ordering across clones.
12705 v.sets = append(v.sets, mb.dmap.Clone())
12706 v.maxs = append(v.maxs, atomic.LoadUint64(&mb.last.seq))
12707 }
12708 mb.mu.RUnlock()
12709 }
12710 return &v
12711 }
12712
12713 // SyncDeleted will make sure this stream has same deleted state as dbs.
12714 // This will only process deleted state within our current state.
12715 func (fs *fileStore) SyncDeleted(dbs DeleteBlocks) error {
12716 if fs.isClosed() {
12717 return ErrStoreClosed
12718 }
12719
12720 if len(dbs) == 0 {
12721 return nil
12722 }
12723
12724 fs.mu.Lock()
12725 defer fs.mu.Unlock()
12726
12727 // Always return previous write errors.
12728 if err := fs.werr; err != nil {
12729 return err
12730 }
12731
12732 lseq := fs.state.LastSeq
12733 fs.readLockAllMsgBlocks()
12734 mdbs, _ := fs.deleteBlocks()
12735 // We'll release the locks below, so need to copy the ones that are references
12736 // which are only safe while the locks are still held.
12737 for i, db := range mdbs {
12738 if ss, ok := db.(*avl.SequenceSet); ok {
12739 mdbs[i] = ss.Clone()
12740 }
12741 }
12742 fs.readUnlockAllMsgBlocks()
12743
12744 for _, db := range dbs {
12745 first, last, _ := db.State()
12746 if first > lseq {
12747 break
12748 }
12749
12750 var prune bool
12751 if prune, mdbs = pruneDeleteBlock(db, mdbs); prune {
12752 continue
12753 }
12754
12755 var err error
12756 if _, ok := db.(*DeleteRange); ok {
12757 err = fs.removeMsgsInRange(first, last, true)
12758 } else {
12759 db.Range(func(dseq uint64) bool {
12760 _, err = fs.removeMsg(dseq, false, true, false)
12761 // Can continue safely if the message doesn't exist.
12762 if err == ErrStoreEOF || err == ErrStoreMsgNotFound {
12763 err = nil
12764 }
12765 return err == nil
12766 })
12767 }
12768 if err != nil {
12769 return err
12770 }
12771 }
12772 return nil
12773 }
12774
12775 // pruneDeleteBlock tries to find a delete block in the ordered blocks slice
12776 // that matches db. It skips blocks that are already behind db and returns
12777 // whether the next candidate matches exactly, along with the remaining
12778 // suffix to use for the next comparison.
12779 func pruneDeleteBlock(db DeleteBlock, blocks DeleteBlocks) (bool, DeleteBlocks) {
12780 if len(blocks) == 0 {
12781 return false, blocks
12782 }
12783
12784 aFirst, aLast, aNum := db.State()
12785 bFirst, bLast, bNum := blocks[0].State()
12786
12787 // Drop blocks that end before db starts.
12788 for bLast < aFirst {
12789 blocks = blocks[1:]
12790 if len(blocks) == 0 {
12791 return false, blocks
12792 }
12793 bFirst, bLast, bNum = blocks[0].State()
12794 }
12795
12796 if aFirst == bFirst && aLast == bLast && aNum == bNum {
12797 // Matching state is only conclusive for a dense block; two sparse
12798 // sequence sets can share the same state but differ in contents.
12799 if aNum == aLast-aFirst+1 || deleteBlockContentsEqual(db, blocks[0]) {
12800 return true, blocks[1:]
12801 }
12802 }
12803
12804 return false, blocks
12805 }
12806
12807 // deleteBlockContentsEqual reports whether two sparse delete blocks with
12808 // identical State() contain the same sequences. If neither block is a
12809 // sequence set we can't compare cheaply and safely report unequal.
12810 func deleteBlockContentsEqual(a, b DeleteBlock) bool {
12811 ssa, aIsSet := a.(*avl.SequenceSet)
12812 ssb, bIsSet := b.(*avl.SequenceSet)
12813 if aIsSet && bIsSet {
12814 return ssa.Equal(ssb)
12815 }
12816 // Use whichever side is a SequenceSet for fast Exists lookups.
12817 var ss *avl.SequenceSet
12818 var other DeleteBlock
12819 if bIsSet {
12820 ss, other = ssb, a
12821 } else if aIsSet {
12822 ss, other = ssa, b
12823 } else {
12824 return false
12825 }
12826 equal := true
12827 other.Range(func(seq uint64) bool {
12828 equal = ss.Exists(seq)
12829 return equal
12830 })
12831 return equal
12832 }
12833
12834 ////////////////////////////////////////////////////////////////////////////////
12835 // Consumers
12836 ////////////////////////////////////////////////////////////////////////////////
12837
12838 type consumerFileStore struct {
12839 mu sync.Mutex
12840 fs *fileStore
12841 cfg *FileConsumerInfo
12842 prf keyGen
12843 aek cipher.AEAD
12844 name string
12845 odir string
12846 ifn string
12847 hh *highwayhash.Digest64
12848 state ConsumerState
12849 fch chan struct{}
12850 qch chan struct{}
12851 flusher bool
12852 writing bool
12853 dirty bool
12854 closed bool
12855 }
12856
12857 func (fs *fileStore) ConsumerStore(name string, created time.Time, cfg *ConsumerConfig) (ConsumerStore, error) {
12858 if fs == nil {
12859 return nil, fmt.Errorf("filestore is nil")
12860 }
12861 if fs.isClosed() {
12862 return nil, ErrStoreClosed
12863 }
12864 if cfg == nil || name == _EMPTY_ {
12865 return nil, fmt.Errorf("bad consumer config")
12866 }
12867
12868 // We now allow overrides from a stream being a filestore type and forcing a consumer to be memory store.
12869 if cfg.MemoryStorage {
12870 // Create directly here.
12871 o := &consumerMemStore{ms: fs, cfg: *cfg}
12872 if err := fs.AddConsumer(o); err != nil {
12873 return nil, err
12874 }
12875 return o, nil
12876 }
12877
12878 odir := filepath.Join(fs.fcfg.StoreDir, consumerDir, name)
12879 if err := os.MkdirAll(odir, defaultDirPerms); err != nil {
12880 return nil, fmt.Errorf("could not create consumer directory - %v", err)
12881 }
12882 csi := &FileConsumerInfo{Name: name, Created: created, ConsumerConfig: *cfg}
12883 o := &consumerFileStore{
12884 fs: fs,
12885 cfg: csi,
12886 prf: fs.prf,
12887 name: name,
12888 odir: odir,
12889 ifn: filepath.Join(odir, consumerState),
12890 }
12891 key := sha256.Sum256([]byte(fs.cfg.Name + "/" + name))
12892 hh, err := highwayhash.NewDigest64(key[:])
12893 if err != nil {
12894 return nil, fmt.Errorf("could not create hash: %v", err)
12895 }
12896 o.hh = hh
12897
12898 // Check for encryption.
12899 if o.prf != nil {
12900 if ekey, err := os.ReadFile(filepath.Join(odir, JetStreamMetaFileKey)); err == nil {
12901 if len(ekey) < minBlkKeySize {
12902 return nil, errBadKeySize
12903 }
12904 // Recover key encryption key.
12905 rb, err := fs.prf([]byte(fs.cfg.Name + tsep + o.name))
12906 if err != nil {
12907 return nil, err
12908 }
12909
12910 sc := fs.fcfg.Cipher
12911 kek, err := genEncryptionKey(sc, rb)
12912 if err != nil {
12913 return nil, err
12914 }
12915 ns := kek.NonceSize()
12916 nonce := ekey[:ns]
12917 seed, err := kek.Open(nil, nonce, ekey[ns:], nil)
12918 if err != nil {
12919 // We may be here on a cipher conversion, so attempt to convert.
12920 if err = o.convertCipher(); err != nil {
12921 return nil, err
12922 }
12923 } else {
12924 o.aek, err = genEncryptionKey(sc, seed)
12925 }
12926 if err != nil {
12927 return nil, err
12928 }
12929 }
12930 }
12931
12932 // Track if we are creating the directory so that we can clean up if we encounter an error.
12933 var didCreate bool
12934
12935 // Write our meta data iff does not exist.
12936 meta := filepath.Join(odir, JetStreamMetaFile)
12937 if _, err := os.Stat(meta); err != nil && os.IsNotExist(err) {
12938 didCreate = true
12939 if err := o.writeConsumerMeta(); err != nil {
12940 _ = os.RemoveAll(odir)
12941 return nil, err
12942 }
12943 }
12944
12945 // If we expect to be encrypted check that what we are restoring is not plaintext.
12946 // This can happen on snapshot restores or conversions.
12947 if o.prf != nil {
12948 keyFile := filepath.Join(odir, JetStreamMetaFileKey)
12949 if _, err := os.Stat(keyFile); err != nil && os.IsNotExist(err) {
12950 if err := o.writeConsumerMeta(); err != nil {
12951 if didCreate {
12952 _ = os.RemoveAll(odir)
12953 }
12954 return nil, err
12955 }
12956 // Redo the state file as well here if we have one and we can tell it was plaintext.
12957 if buf, err := os.ReadFile(o.ifn); err == nil {
12958 if _, err := decodeConsumerState(buf); err == nil {
12959 state, err := o.encryptState(buf)
12960 if err != nil {
12961 return nil, err
12962 }
12963 err = fs.writeFileWithOptionalSync(o.ifn, state, defaultFilePerms)
12964 if err != nil {
12965 if didCreate {
12966 _ = os.RemoveAll(odir)
12967 }
12968 return nil, err
12969 }
12970 }
12971 }
12972 }
12973 }
12974
12975 // Create channels to control our flush go routine.
12976 o.fch = make(chan struct{}, 1)
12977 o.qch = make(chan struct{})
12978
12979 // Make sure to load in our state from disk if needed.
12980 if err = o.loadState(); err != nil {
12981 return nil, err
12982 }
12983
12984 // Assign to filestore.
12985 if err = fs.AddConsumer(o); err != nil {
12986 return nil, err
12987 }
12988
12989 go o.flushLoop(o.fch, o.qch)
12990 return o, nil
12991 }
12992
12993 func (o *consumerFileStore) convertCipher() error {
12994 fs := o.fs
12995 odir := filepath.Join(fs.fcfg.StoreDir, consumerDir, o.name)
12996
12997 ekey, err := os.ReadFile(filepath.Join(odir, JetStreamMetaFileKey))
12998 if err != nil {
12999 return err
13000 }
13001 if len(ekey) < minBlkKeySize {
13002 return errBadKeySize
13003 }
13004 // Recover key encryption key.
13005 rb, err := fs.prf([]byte(fs.cfg.Name + tsep + o.name))
13006 if err != nil {
13007 return err
13008 }
13009
13010 // Do these in reverse since converting.
13011 sc := fs.fcfg.Cipher
13012 osc := AES
13013 if sc == AES {
13014 osc = ChaCha
13015 }
13016 kek, err := genEncryptionKey(osc, rb)
13017 if err != nil {
13018 return err
13019 }
13020 ns := kek.NonceSize()
13021 nonce := ekey[:ns]
13022 seed, err := kek.Open(nil, nonce, ekey[ns:], nil)
13023 if err != nil {
13024 return err
13025 }
13026 aek, err := genEncryptionKey(osc, seed)
13027 if err != nil {
13028 return err
13029 }
13030 // Now read in and decode our state using the old cipher.
13031 buf, err := os.ReadFile(o.ifn)
13032 if err != nil {
13033 return err
13034 }
13035 buf, err = aek.Open(nil, buf[:ns], buf[ns:], nil)
13036 if err != nil {
13037 return err
13038 }
13039
13040 // Since we are here we recovered our old state.
13041 // Now write our meta, which will generate the new keys with the new cipher.
13042 if err := o.writeConsumerMeta(); err != nil {
13043 return err
13044 }
13045
13046 // Now write out or state with the new cipher.
13047 return o.writeState(buf)
13048 }
13049
13050 // Kick flusher for this consumer.
13051 // Lock should be held.
13052 func (o *consumerFileStore) kickFlusher() {
13053 if o.fch != nil {
13054 select {
13055 case o.fch <- struct{}{}:
13056 default:
13057 }
13058 }
13059 o.dirty = true
13060 }
13061
13062 // Set in flusher status
13063 func (o *consumerFileStore) setInFlusher() {
13064 o.mu.Lock()
13065 o.flusher = true
13066 o.mu.Unlock()
13067 }
13068
13069 // Clear in flusher status
13070 func (o *consumerFileStore) clearInFlusher() {
13071 o.mu.Lock()
13072 o.flusher = false
13073 o.mu.Unlock()
13074 }
13075
13076 // Report in flusher status
13077 func (o *consumerFileStore) inFlusher() bool {
13078 o.mu.Lock()
13079 defer o.mu.Unlock()
13080 return o.flusher
13081 }
13082
13083 // flushLoop watches for consumer updates and the quit channel.
13084 func (o *consumerFileStore) flushLoop(fch, qch chan struct{}) {
13085
13086 o.setInFlusher()
13087 defer o.clearInFlusher()
13088
13089 // Maintain approximately 10 updates per second per consumer under load.
13090 const minTime = 100 * time.Millisecond
13091 var lastWrite time.Time
13092 var dt *time.Timer
13093
13094 setDelayTimer := func(addWait time.Duration) {
13095 if dt == nil {
13096 dt = time.NewTimer(addWait)
13097 return
13098 }
13099 if !dt.Stop() {
13100 select {
13101 case <-dt.C:
13102 default:
13103 }
13104 }
13105 dt.Reset(addWait)
13106 }
13107
13108 for {
13109 select {
13110 case <-fch:
13111 if ts := time.Since(lastWrite); ts < minTime {
13112 setDelayTimer(minTime - ts)
13113 select {
13114 case <-dt.C:
13115 case <-qch:
13116 return
13117 }
13118 }
13119 o.mu.Lock()
13120 if o.closed {
13121 o.mu.Unlock()
13122 return
13123 }
13124 buf, err := o.encodeState()
13125 o.mu.Unlock()
13126 if err != nil {
13127 return
13128 }
13129 // TODO(dlc) - if we error should start failing upwards.
13130 if err := o.writeState(buf); err == nil {
13131 lastWrite = time.Now()
13132 }
13133 case <-qch:
13134 return
13135 }
13136 }
13137 }
13138
13139 // SetStarting sets our starting stream sequence.
13140 func (o *consumerFileStore) SetStarting(sseq uint64) error {
13141 o.mu.Lock()
13142 o.state.Delivered.Stream = sseq
13143 o.state.AckFloor.Stream = sseq
13144 buf := encodeConsumerState(&o.state)
13145 o.mu.Unlock()
13146 return o.writeState(buf)
13147 }
13148
13149 // UpdateStarting updates our starting stream sequence.
13150 func (o *consumerFileStore) UpdateStarting(sseq uint64) {
13151 o.mu.Lock()
13152 defer o.mu.Unlock()
13153
13154 if sseq > o.state.Delivered.Stream {
13155 o.state.Delivered.Stream = sseq
13156 // For AckNone just update delivered and ackfloor at the same time.
13157 if o.cfg.AckPolicy == AckNone {
13158 o.state.AckFloor.Stream = sseq
13159 }
13160 }
13161 // Make sure we flush to disk.
13162 o.kickFlusher()
13163 }
13164
13165 // Reset all values in the store, and reset the starting sequence.
13166 func (o *consumerFileStore) Reset(sseq uint64) error {
13167 o.mu.Lock()
13168 o.state = ConsumerState{}
13169 o.mu.Unlock()
13170 return o.SetStarting(sseq)
13171 }
13172
13173 // HasState returns if this store has a recorded state.
13174 func (o *consumerFileStore) HasState() bool {
13175 o.mu.Lock()
13176 // We have a running state, or stored on disk but not yet initialized.
13177 if o.state.Delivered.Consumer != 0 || o.state.Delivered.Stream != 0 {
13178 o.mu.Unlock()
13179 return true
13180 }
13181 _, err := os.Stat(o.ifn)
13182 o.mu.Unlock()
13183 return err == nil
13184 }
13185
13186 // UpdateDelivered is called whenever a new message has been delivered.
13187 func (o *consumerFileStore) UpdateDelivered(dseq, sseq, dc uint64, ts int64) error {
13188 o.mu.Lock()
13189 defer o.mu.Unlock()
13190
13191 if dc != 1 && o.cfg.AckPolicy == AckNone {
13192 return ErrNoAckPolicy
13193 }
13194
13195 // On restarts the old leader may get a replay from the raft logs that are old.
13196 if dseq <= o.state.AckFloor.Consumer {
13197 return nil
13198 }
13199
13200 // See if we expect an ack for this.
13201 if o.cfg.AckPolicy != AckNone {
13202 // Need to create pending records here.
13203 if o.state.Pending == nil {
13204 o.state.Pending = make(map[uint64]*Pending)
13205 }
13206 var p *Pending
13207 // Check for an update to a message already delivered.
13208 if sseq <= o.state.Delivered.Stream {
13209 if p = o.state.Pending[sseq]; p != nil {
13210 // Do not update p.Sequence, that should be the original delivery sequence.
13211 p.Timestamp = ts
13212 }
13213 } else {
13214 // Add to pending.
13215 o.state.Pending[sseq] = &Pending{dseq, ts}
13216 }
13217 // Update delivered as needed.
13218 if dseq > o.state.Delivered.Consumer {
13219 o.state.Delivered.Consumer = dseq
13220 }
13221 if sseq > o.state.Delivered.Stream {
13222 o.state.Delivered.Stream = sseq
13223 }
13224
13225 if dc > 1 {
13226 if maxdc := uint64(o.cfg.MaxDeliver); maxdc > 0 && dc > maxdc {
13227 // Make sure to remove from pending.
13228 delete(o.state.Pending, sseq)
13229 }
13230 if o.state.Redelivered == nil {
13231 o.state.Redelivered = make(map[uint64]uint64)
13232 }
13233 // Only update if greater than what we already have.
13234 if o.state.Redelivered[sseq] < dc-1 {
13235 o.state.Redelivered[sseq] = dc - 1
13236 }
13237 }
13238 } else {
13239 // For AckNone just update delivered and ackfloor at the same time.
13240 if dseq > o.state.Delivered.Consumer {
13241 o.state.Delivered.Consumer = dseq
13242 o.state.AckFloor.Consumer = dseq
13243 }
13244 if sseq > o.state.Delivered.Stream {
13245 o.state.Delivered.Stream = sseq
13246 o.state.AckFloor.Stream = sseq
13247 }
13248 }
13249 // Make sure we flush to disk.
13250 o.kickFlusher()
13251
13252 return nil
13253 }
13254
13255 // UpdateAcks is called whenever a consumer with explicit ack or ack all acks a message.
13256 func (o *consumerFileStore) UpdateAcks(dseq, sseq uint64) error {
13257 o.mu.Lock()
13258 defer o.mu.Unlock()
13259
13260 if o.cfg.AckPolicy == AckNone {
13261 return ErrNoAckPolicy
13262 }
13263
13264 var kick bool
13265 defer func() {
13266 if kick {
13267 o.kickFlusher()
13268 }
13269 }()
13270
13271 // We do this regardless.
13272 if _, ok := o.state.Redelivered[sseq]; ok {
13273 delete(o.state.Redelivered, sseq)
13274 kick = true
13275 }
13276
13277 // On restarts the old leader may get a replay from the raft logs that are old.
13278 if dseq <= o.state.AckFloor.Consumer {
13279 return nil
13280 }
13281
13282 if len(o.state.Pending) == 0 || o.state.Pending[sseq] == nil {
13283 return ErrStoreMsgNotFound
13284 }
13285
13286 // Done with the consistency checks, we'll always kick for below updates.
13287 kick = true
13288
13289 // Check for AckAll here (or AckFlowControl which functions like AckAll).
13290 if o.cfg.AckPolicy == AckAll || o.cfg.AckPolicy == AckFlowControl {
13291 sgap := sseq - o.state.AckFloor.Stream
13292 o.state.AckFloor.Consumer = dseq
13293 o.state.AckFloor.Stream = sseq
13294 if sgap > uint64(len(o.state.Pending)) {
13295 for seq := range o.state.Pending {
13296 if seq <= sseq {
13297 delete(o.state.Pending, seq)
13298 delete(o.state.Redelivered, seq)
13299 }
13300 }
13301 } else {
13302 for seq := sseq; seq > sseq-sgap && len(o.state.Pending) > 0; seq-- {
13303 delete(o.state.Pending, seq)
13304 delete(o.state.Redelivered, seq)
13305 }
13306 }
13307 return nil
13308 }
13309
13310 // AckExplicit
13311
13312 // First delete from our pending state.
13313 if p, ok := o.state.Pending[sseq]; ok {
13314 delete(o.state.Pending, sseq)
13315 if dseq > p.Sequence && p.Sequence > 0 {
13316 dseq = p.Sequence // Use the original.
13317 }
13318 }
13319 if len(o.state.Pending) == 0 {
13320 o.state.AckFloor.Consumer = o.state.Delivered.Consumer
13321 o.state.AckFloor.Stream = o.state.Delivered.Stream
13322 } else if dseq == o.state.AckFloor.Consumer+1 {
13323 o.state.AckFloor.Consumer = dseq
13324 o.state.AckFloor.Stream = sseq
13325
13326 if o.state.Delivered.Consumer > dseq {
13327 for ss := sseq + 1; ss <= o.state.Delivered.Stream; ss++ {
13328 if p, ok := o.state.Pending[ss]; ok {
13329 if p.Sequence > 0 {
13330 o.state.AckFloor.Consumer = p.Sequence - 1
13331 o.state.AckFloor.Stream = ss - 1
13332 }
13333 break
13334 }
13335 }
13336 }
13337 }
13338 return nil
13339 }
13340
13341 func (o *consumerFileStore) RemoveRedeliveredBelow(seq uint64) {
13342 if seq == 0 {
13343 return
13344 }
13345 o.mu.Lock()
13346 defer o.mu.Unlock()
13347 var removed bool
13348 for s := range o.state.Redelivered {
13349 if s < seq {
13350 delete(o.state.Redelivered, s)
13351 removed = true
13352 }
13353 }
13354 if removed {
13355 o.kickFlusher()
13356 }
13357 }
13358
13359 const seqsHdrSize = 6*binary.MaxVarintLen64 + hdrLen
13360
13361 // Encode our consumer state, version 2.
13362 // Lock should be held.
13363
13364 func (o *consumerFileStore) EncodedState() ([]byte, error) {
13365 o.mu.Lock()
13366 defer o.mu.Unlock()
13367 return o.encodeState()
13368 }
13369
13370 func (o *consumerFileStore) encodeState() ([]byte, error) {
13371 // Grab reference to state, but make sure we load in if needed, so do not reference o.state directly.
13372 state, err := o.stateWithCopyLocked(false)
13373 if err != nil {
13374 return nil, err
13375 }
13376 return encodeConsumerState(state), nil
13377 }
13378
13379 func (o *consumerFileStore) UpdateConfig(cfg *ConsumerConfig) error {
13380 o.mu.Lock()
13381 defer o.mu.Unlock()
13382
13383 // This is mostly unchecked here. We are assuming the upper layers have done sanity checking.
13384 csi := o.cfg
13385 csi.ConsumerConfig = *cfg
13386
13387 return o.writeConsumerMeta()
13388 }
13389
13390 func (o *consumerFileStore) Update(state *ConsumerState) error {
13391 // Sanity checks.
13392 if state.AckFloor.Consumer > state.Delivered.Consumer {
13393 return fmt.Errorf("bad ack floor for consumer")
13394 }
13395 if state.AckFloor.Stream > state.Delivered.Stream {
13396 return fmt.Errorf("bad ack floor for stream")
13397 }
13398
13399 // Copy to our state.
13400 var pending map[uint64]*Pending
13401 var redelivered map[uint64]uint64
13402 if len(state.Pending) > 0 {
13403 pending = make(map[uint64]*Pending, len(state.Pending))
13404 for seq, p := range state.Pending {
13405 pending[seq] = &Pending{p.Sequence, p.Timestamp}
13406 if seq <= state.AckFloor.Stream || seq > state.Delivered.Stream {
13407 return fmt.Errorf("bad pending entry, sequence [%d] out of range", seq)
13408 }
13409 }
13410 }
13411 if len(state.Redelivered) > 0 {
13412 redelivered = make(map[uint64]uint64, len(state.Redelivered))
13413 for seq, dc := range state.Redelivered {
13414 redelivered[seq] = dc
13415 }
13416 }
13417
13418 // Replace our state.
13419 o.mu.Lock()
13420 defer o.mu.Unlock()
13421
13422 // Check to see if this is an outdated update.
13423 if state.Delivered.Consumer < o.state.Delivered.Consumer || state.AckFloor.Stream < o.state.AckFloor.Stream {
13424 return ErrStoreOldUpdate
13425 }
13426
13427 o.state.Delivered = state.Delivered
13428 o.state.AckFloor = state.AckFloor
13429 o.state.Pending = pending
13430 o.state.Redelivered = redelivered
13431
13432 o.kickFlusher()
13433
13434 return nil
13435 }
13436
13437 // ForceUpdate updates the consumer state without the backwards check.
13438 // This is used during recovery when we need to reset the consumer to an earlier sequence.
13439 func (o *consumerFileStore) ForceUpdate(state *ConsumerState) error {
13440 // Sanity checks.
13441 if state.AckFloor.Consumer > state.Delivered.Consumer {
13442 return fmt.Errorf("bad ack floor for consumer")
13443 }
13444 if state.AckFloor.Stream > state.Delivered.Stream {
13445 return fmt.Errorf("bad ack floor for stream")
13446 }
13447
13448 // Copy to our state.
13449 var pending map[uint64]*Pending
13450 var redelivered map[uint64]uint64
13451 if len(state.Pending) > 0 {
13452 pending = make(map[uint64]*Pending, len(state.Pending))
13453 for seq, p := range state.Pending {
13454 pending[seq] = &Pending{p.Sequence, p.Timestamp}
13455 if seq <= state.AckFloor.Stream || seq > state.Delivered.Stream {
13456 return fmt.Errorf("bad pending entry, sequence [%d] out of range", seq)
13457 }
13458 }
13459 }
13460 if len(state.Redelivered) > 0 {
13461 redelivered = make(map[uint64]uint64, len(state.Redelivered))
13462 for seq, dc := range state.Redelivered {
13463 redelivered[seq] = dc
13464 }
13465 }
13466
13467 // Replace our state.
13468 o.mu.Lock()
13469 o.state.Delivered = state.Delivered
13470 o.state.AckFloor = state.AckFloor
13471 o.state.Pending = pending
13472 o.state.Redelivered = redelivered
13473 buf, err := o.encodeState()
13474 o.mu.Unlock()
13475 if err != nil {
13476 return err
13477 }
13478 return o.writeState(buf)
13479 }
13480
13481 // Will encrypt the state with our asset key. Will be a no-op if encryption not enabled.
13482 // Lock should be held.
13483 func (o *consumerFileStore) encryptState(buf []byte) ([]byte, error) {
13484 if o.aek == nil {
13485 return buf, nil
13486 }
13487 // TODO(dlc) - Optimize on space usage a bit?
13488 nonce := make([]byte, o.aek.NonceSize(), o.aek.NonceSize()+len(buf)+o.aek.Overhead())
13489 if n, err := rand.Read(nonce); err != nil {
13490 return nil, err
13491 } else if n != len(nonce) {
13492 return nil, fmt.Errorf("not enough nonce bytes read (%d != %d)", n, len(nonce))
13493 }
13494 return o.aek.Seal(nonce, nonce, buf, nil), nil
13495 }
13496
13497 func (o *consumerFileStore) writeState(buf []byte) error {
13498 // Check if we have the index file open.
13499 o.mu.Lock()
13500 if o.writing || len(buf) == 0 {
13501 o.mu.Unlock()
13502 return nil
13503 }
13504
13505 // Check on encryption.
13506 if o.aek != nil {
13507 var err error
13508 if buf, err = o.encryptState(buf); err != nil {
13509 o.mu.Unlock()
13510 return err
13511 }
13512 }
13513
13514 o.writing = true
13515 o.dirty = false
13516 ifn := o.ifn
13517 o.mu.Unlock()
13518
13519 // Lock not held here but we do limit number of outstanding calls that could block OS threads.
13520 err := o.fs.writeFileWithOptionalSync(ifn, buf, defaultFilePerms)
13521
13522 o.mu.Lock()
13523 if err != nil {
13524 o.dirty = true
13525 }
13526 o.writing = false
13527 o.mu.Unlock()
13528
13529 return err
13530 }
13531
13532 // Will upodate the config. Only used when recovering ephemerals.
13533 func (o *consumerFileStore) updateConfig(cfg ConsumerConfig) error {
13534 o.mu.Lock()
13535 defer o.mu.Unlock()
13536 o.cfg = &FileConsumerInfo{ConsumerConfig: cfg}
13537 return o.writeConsumerMeta()
13538 }
13539
13540 // Write out the consumer meta data, i.e. state.
13541 // Lock should be held.
13542 func (cfs *consumerFileStore) writeConsumerMeta() error {
13543 meta := filepath.Join(cfs.odir, JetStreamMetaFile)
13544 if _, err := os.Stat(meta); err != nil && !os.IsNotExist(err) {
13545 return err
13546 }
13547
13548 if cfs.prf != nil && cfs.aek == nil {
13549 fs := cfs.fs
13550 key, _, _, encrypted, err := fs.genEncryptionKeys(fs.cfg.Name + tsep + cfs.name)
13551 if err != nil {
13552 return err
13553 }
13554 cfs.aek = key
13555 keyFile := filepath.Join(cfs.odir, JetStreamMetaFileKey)
13556 if _, err := os.Stat(keyFile); err != nil && !os.IsNotExist(err) {
13557 return err
13558 }
13559 err = cfs.fs.writeFileWithOptionalSync(keyFile, encrypted, defaultFilePerms)
13560 if err != nil {
13561 return err
13562 }
13563 }
13564
13565 b, err := json.Marshal(cfs.cfg)
13566 if err != nil {
13567 return err
13568 }
13569 // Encrypt if needed.
13570 if cfs.aek != nil {
13571 nonce := make([]byte, cfs.aek.NonceSize(), cfs.aek.NonceSize()+len(b)+cfs.aek.Overhead())
13572 if n, err := rand.Read(nonce); err != nil {
13573 return err
13574 } else if n != len(nonce) {
13575 return fmt.Errorf("not enough nonce bytes read (%d != %d)", n, len(nonce))
13576 }
13577 b = cfs.aek.Seal(nonce, nonce, b, nil)
13578 }
13579
13580 err = cfs.fs.writeFileWithOptionalSync(meta, b, defaultFilePerms)
13581 if err != nil {
13582 return err
13583 }
13584 cfs.hh.Reset()
13585 cfs.hh.Write(b)
13586 var hb [highwayhash.Size64]byte
13587 checksum := hex.EncodeToString(cfs.hh.Sum(hb[:0]))
13588 sum := filepath.Join(cfs.odir, JetStreamMetaFileSum)
13589
13590 err = cfs.fs.writeFileWithOptionalSync(sum, []byte(checksum), defaultFilePerms)
13591 if err != nil {
13592 return err
13593 }
13594 return nil
13595 }
13596
13597 // Consumer version.
13598 func checkConsumerHeader(hdr []byte) (uint8, error) {
13599 if len(hdr) < 2 || hdr[0] != magic {
13600 return 0, errCorruptState
13601 }
13602 version := hdr[1]
13603 switch version {
13604 case 1, 2:
13605 return version, nil
13606 }
13607 return 0, fmt.Errorf("unsupported version: %d", version)
13608 }
13609
13610 func (o *consumerFileStore) copyPending() map[uint64]*Pending {
13611 pending := make(map[uint64]*Pending, len(o.state.Pending))
13612 for seq, p := range o.state.Pending {
13613 pending[seq] = &Pending{p.Sequence, p.Timestamp}
13614 }
13615 return pending
13616 }
13617
13618 func (o *consumerFileStore) copyRedelivered() map[uint64]uint64 {
13619 redelivered := make(map[uint64]uint64, len(o.state.Redelivered))
13620 for seq, dc := range o.state.Redelivered {
13621 redelivered[seq] = dc
13622 }
13623 return redelivered
13624 }
13625
13626 // Type returns the type of the underlying store.
13627 func (o *consumerFileStore) Type() StorageType { return FileStorage }
13628
13629 // State retrieves the state from the state file.
13630 // This is not expected to be called in high performance code, only on startup.
13631 func (o *consumerFileStore) State() (*ConsumerState, error) {
13632 return o.stateWithCopy(true)
13633 }
13634
13635 // This will not copy pending or redelivered, so should only be done under the
13636 // consumer owner's lock.
13637 func (o *consumerFileStore) BorrowState() (*ConsumerState, error) {
13638 return o.stateWithCopy(false)
13639 }
13640
13641 func (o *consumerFileStore) stateWithCopy(doCopy bool) (*ConsumerState, error) {
13642 o.mu.Lock()
13643 defer o.mu.Unlock()
13644 return o.stateWithCopyLocked(doCopy)
13645 }
13646
13647 // Lock should be held.
13648 func (o *consumerFileStore) stateWithCopyLocked(doCopy bool) (*ConsumerState, error) {
13649 if o.closed {
13650 return nil, ErrStoreClosed
13651 }
13652
13653 state := &ConsumerState{}
13654
13655 // See if we have a running state or if we need to read in from disk.
13656 if o.state.Delivered.Consumer != 0 || o.state.Delivered.Stream != 0 {
13657 state.Delivered = o.state.Delivered
13658 state.AckFloor = o.state.AckFloor
13659 if len(o.state.Pending) > 0 {
13660 if doCopy {
13661 state.Pending = o.copyPending()
13662 } else {
13663 state.Pending = o.state.Pending
13664 }
13665 }
13666 if len(o.state.Redelivered) > 0 {
13667 if doCopy {
13668 state.Redelivered = o.copyRedelivered()
13669 } else {
13670 state.Redelivered = o.state.Redelivered
13671 }
13672 }
13673 return state, nil
13674 }
13675
13676 // Read the state in here from disk..
13677 o.fs.dios.acquire()
13678 buf, err := os.ReadFile(o.ifn)
13679 o.fs.dios.release()
13680
13681 if err != nil && !os.IsNotExist(err) {
13682 return nil, err
13683 }
13684
13685 if len(buf) == 0 {
13686 return state, nil
13687 }
13688
13689 // Check on encryption.
13690 if o.aek != nil {
13691 ns := o.aek.NonceSize()
13692 buf, err = o.aek.Open(nil, buf[:ns], buf[ns:], nil)
13693 if err != nil {
13694 return nil, err
13695 }
13696 }
13697
13698 state, err = decodeConsumerState(buf)
13699 if err != nil {
13700 return nil, err
13701 }
13702
13703 // Copy this state into our own.
13704 o.state.Delivered = state.Delivered
13705 o.state.AckFloor = state.AckFloor
13706 if len(state.Pending) > 0 {
13707 if doCopy {
13708 o.state.Pending = make(map[uint64]*Pending, len(state.Pending))
13709 for seq, p := range state.Pending {
13710 o.state.Pending[seq] = &Pending{p.Sequence, p.Timestamp}
13711 }
13712 } else {
13713 o.state.Pending = state.Pending
13714 }
13715 }
13716 if len(state.Redelivered) > 0 {
13717 if doCopy {
13718 o.state.Redelivered = make(map[uint64]uint64, len(state.Redelivered))
13719 for seq, dc := range state.Redelivered {
13720 o.state.Redelivered[seq] = dc
13721 }
13722 } else {
13723 o.state.Redelivered = state.Redelivered
13724 }
13725 }
13726
13727 return state, nil
13728 }
13729
13730 // Lock should be held. Called at startup.
13731 func (o *consumerFileStore) loadState() error {
13732 if _, err := os.Stat(o.ifn); err == nil {
13733 // This will load our state in from disk.
13734 _, err = o.stateWithCopyLocked(false)
13735 return err
13736 } else if os.IsNotExist(err) {
13737 return nil
13738 } else {
13739 return err
13740 }
13741 }
13742
13743 // Decode consumer state.
13744 func decodeConsumerState(buf []byte) (*ConsumerState, error) {
13745 version, err := checkConsumerHeader(buf)
13746 if err != nil {
13747 return nil, err
13748 }
13749
13750 bi := hdrLen
13751 // Helpers, will set i to -1 on error.
13752 readSeq := func() uint64 {
13753 if bi < 0 {
13754 return 0
13755 }
13756 seq, n := binary.Uvarint(buf[bi:])
13757 if n <= 0 {
13758 bi = -1
13759 return 0
13760 }
13761 bi += n
13762 return seq
13763 }
13764 readTimeStamp := func() int64 {
13765 if bi < 0 {
13766 return 0
13767 }
13768 ts, n := binary.Varint(buf[bi:])
13769 if n <= 0 {
13770 bi = -1
13771 return -1
13772 }
13773 bi += n
13774 return ts
13775 }
13776 // Just for clarity below.
13777 readLen := readSeq
13778 readCount := readSeq
13779
13780 state := &ConsumerState{}
13781 state.AckFloor.Consumer = readSeq()
13782 state.AckFloor.Stream = readSeq()
13783 state.Delivered.Consumer = readSeq()
13784 state.Delivered.Stream = readSeq()
13785
13786 if bi == -1 {
13787 return nil, errCorruptState
13788 }
13789 if version == 1 {
13790 // Adjust back. Version 1 also stored delivered as next to be delivered,
13791 // so adjust that back down here.
13792 if state.AckFloor.Consumer > 1 {
13793 state.Delivered.Consumer += state.AckFloor.Consumer - 1
13794 }
13795 if state.AckFloor.Stream > 1 {
13796 state.Delivered.Stream += state.AckFloor.Stream - 1
13797 }
13798 }
13799
13800 // Protect ourselves against rolling backwards.
13801 const hbit = 1 << 63
13802 if state.AckFloor.Stream&hbit != 0 || state.Delivered.Stream&hbit != 0 {
13803 return nil, errCorruptState
13804 }
13805
13806 // We have additional stuff.
13807 if numPending := readLen(); numPending > 0 {
13808 mints := readTimeStamp()
13809 state.Pending = make(map[uint64]*Pending, numPending)
13810 for i := 0; i < int(numPending); i++ {
13811 sseq := readSeq()
13812 var dseq uint64
13813 if version == 2 {
13814 dseq = readSeq()
13815 }
13816 ts := readTimeStamp()
13817 // Check the state machine for corruption, not the value which could be -1.
13818 if bi == -1 {
13819 return nil, errCorruptState
13820 }
13821 // Adjust seq back.
13822 sseq += state.AckFloor.Stream
13823 if sseq == 0 {
13824 return nil, errCorruptState
13825 }
13826 if version == 2 {
13827 dseq += state.AckFloor.Consumer
13828 }
13829 // Adjust the timestamp back.
13830 if version == 1 {
13831 ts = (ts + mints) * int64(time.Second)
13832 } else {
13833 ts = (mints - ts) * int64(time.Second)
13834 }
13835 // Store in pending.
13836 state.Pending[sseq] = &Pending{dseq, ts}
13837 }
13838 }
13839
13840 // We have redelivered entries here.
13841 if numRedelivered := readLen(); numRedelivered > 0 {
13842 state.Redelivered = make(map[uint64]uint64, numRedelivered)
13843 for i := 0; i < int(numRedelivered); i++ {
13844 if seq, n := readSeq(), readCount(); seq > 0 && n > 0 {
13845 // Adjust seq back.
13846 seq += state.AckFloor.Stream
13847 state.Redelivered[seq] = n
13848 }
13849 }
13850 }
13851
13852 return state, nil
13853 }
13854
13855 // Stop the processing of the consumers's state.
13856 func (o *consumerFileStore) Stop() error {
13857 o.mu.Lock()
13858 if o.closed {
13859 o.mu.Unlock()
13860 return nil
13861 }
13862 if o.qch != nil {
13863 close(o.qch)
13864 o.qch = nil
13865 }
13866
13867 var err error
13868 var buf []byte
13869
13870 if o.dirty {
13871 // Make sure to write this out..
13872 if buf, err = o.encodeState(); err == nil && len(buf) > 0 {
13873 if o.aek != nil {
13874 if buf, err = o.encryptState(buf); err != nil {
13875 o.mu.Unlock()
13876 return err
13877 }
13878 }
13879 }
13880 }
13881
13882 o.odir = _EMPTY_
13883 o.closed = true
13884 ifn, fs := o.ifn, o.fs
13885 o.mu.Unlock()
13886
13887 if err = fs.RemoveConsumer(o); err != nil {
13888 return err
13889 }
13890
13891 if len(buf) > 0 {
13892 o.waitOnFlusher()
13893 err = o.fs.writeFileWithOptionalSync(ifn, buf, defaultFilePerms)
13894 }
13895 return err
13896 }
13897
13898 func (o *consumerFileStore) waitOnFlusher() {
13899 if !o.inFlusher() {
13900 return
13901 }
13902
13903 timeout := time.Now().Add(100 * time.Millisecond)
13904 for time.Now().Before(timeout) {
13905 if !o.inFlusher() {
13906 return
13907 }
13908 time.Sleep(10 * time.Millisecond)
13909 }
13910 }
13911
13912 // Delete the consumer.
13913 func (o *consumerFileStore) Delete() error {
13914 return o.delete(false)
13915 }
13916
13917 func (o *consumerFileStore) StreamDelete() error {
13918 return o.delete(true)
13919 }
13920
13921 func (o *consumerFileStore) delete(streamDeleted bool) error {
13922 o.mu.Lock()
13923 if o.closed {
13924 o.mu.Unlock()
13925 return nil
13926 }
13927 if o.qch != nil {
13928 close(o.qch)
13929 o.qch = nil
13930 }
13931
13932 odir := o.odir
13933 o.odir = _EMPTY_
13934 o.closed = true
13935 fs := o.fs
13936 o.mu.Unlock()
13937
13938 // If our stream was not deleted this will remove the directories.
13939 if odir != _EMPTY_ && !streamDeleted {
13940 if err := removeAllWithRetry(o.fs.dios, odir); err != nil {
13941 return err
13942 }
13943 }
13944
13945 if !streamDeleted {
13946 if err := fs.RemoveConsumer(o); err != nil {
13947 return err
13948 }
13949 }
13950
13951 return nil
13952 }
13953
13954 func (fs *fileStore) AddConsumer(o ConsumerStore) error {
13955 fs.cmu.Lock()
13956 defer fs.cmu.Unlock()
13957 fs.cfs = append(fs.cfs, o)
13958 return nil
13959 }
13960
13961 func (fs *fileStore) RemoveConsumer(o ConsumerStore) error {
13962 fs.cmu.Lock()
13963 defer fs.cmu.Unlock()
13964 for i, cfs := range fs.cfs {
13965 if o == cfs {
13966 fs.cfs = append(fs.cfs[:i], fs.cfs[i+1:]...)
13967 break
13968 }
13969 }
13970 return nil
13971 }
13972
13973 ////////////////////////////////////////////////////////////////////////////////
13974 // Compression
13975 ////////////////////////////////////////////////////////////////////////////////
13976
13977 type CompressionInfo struct {
13978 Algorithm StoreCompression
13979 OriginalSize uint64
13980 }
13981
13982 func (c *CompressionInfo) MarshalMetadata() []byte {
13983 b := make([]byte, 14) // 4 + potentially up to 10 for uint64
13984 b[0], b[1], b[2] = 'c', 'm', 'p'
13985 b[3] = byte(c.Algorithm)
13986 n := binary.PutUvarint(b[4:], c.OriginalSize)
13987 return b[:4+n]
13988 }
13989
13990 func (c *CompressionInfo) UnmarshalMetadata(b []byte) (int, error) {
13991 c.Algorithm = NoCompression
13992 c.OriginalSize = 0
13993 if len(b) < 5 { // 4 + min 1 for uvarint uint64
13994 return 0, nil
13995 }
13996 if b[0] != 'c' || b[1] != 'm' || b[2] != 'p' {
13997 return 0, nil
13998 }
13999 var n int
14000 c.Algorithm = StoreCompression(b[3])
14001 c.OriginalSize, n = binary.Uvarint(b[4:])
14002 if n <= 0 {
14003 return 0, fmt.Errorf("metadata incomplete")
14004 }
14005 return 4 + n, nil
14006 }
14007
14008 func (alg StoreCompression) Compress(buf []byte) ([]byte, error) {
14009 if len(buf) < checksumSize {
14010 return nil, fmt.Errorf("uncompressed buffer is too short")
14011 }
14012 bodyLen := int64(len(buf) - checksumSize)
14013 var output bytes.Buffer
14014 var writer io.WriteCloser
14015 switch alg {
14016 case NoCompression:
14017 return buf, nil
14018 case S2Compression:
14019 writer = s2.NewWriter(&output)
14020 default:
14021 return nil, fmt.Errorf("compression algorithm not known")
14022 }
14023
14024 input := bytes.NewReader(buf[:bodyLen])
14025 checksum := buf[bodyLen:]
14026
14027 // Compress the block content, but don't compress the checksum.
14028 // We will preserve it at the end of the block as-is.
14029 if n, err := io.CopyN(writer, input, bodyLen); err != nil {
14030 return nil, fmt.Errorf("error writing to compression writer: %w", err)
14031 } else if n != bodyLen {
14032 return nil, fmt.Errorf("short write on body (%d != %d)", n, bodyLen)
14033 }
14034 if err := writer.Close(); err != nil {
14035 return nil, fmt.Errorf("error closing compression writer: %w", err)
14036 }
14037
14038 // Now add the checksum back onto the end of the block.
14039 if n, err := output.Write(checksum); err != nil {
14040 return nil, fmt.Errorf("error writing checksum: %w", err)
14041 } else if n != checksumSize {
14042 return nil, fmt.Errorf("short write on checksum (%d != %d)", n, checksumSize)
14043 }
14044
14045 return output.Bytes(), nil
14046 }
14047
14048 func (alg StoreCompression) Decompress(buf []byte) ([]byte, error) {
14049 if len(buf) < checksumSize {
14050 return nil, fmt.Errorf("compressed buffer is too short")
14051 }
14052 bodyLen := int64(len(buf) - checksumSize)
14053 input := bytes.NewReader(buf[:bodyLen])
14054
14055 var reader io.ReadCloser
14056 switch alg {
14057 case NoCompression:
14058 return buf, nil
14059 case S2Compression:
14060 reader = io.NopCloser(s2.NewReader(input))
14061 default:
14062 return nil, fmt.Errorf("compression algorithm not known")
14063 }
14064
14065 // Decompress the block content. The checksum isn't compressed so
14066 // we can preserve it from the end of the block as-is.
14067 checksum := buf[bodyLen:]
14068 output, err := io.ReadAll(reader)
14069 if err != nil {
14070 return nil, fmt.Errorf("error reading compression reader: %w", err)
14071 }
14072 output = append(output, checksum...)
14073
14074 return output, reader.Close()
14075 }
14076
14077 // writeFileWithOptionalSync is equivalent to os.WriteFile() but optionally
14078 // sets O_SYNC on the open file if SyncAlways is set. The dios semaphore is
14079 // handled automatically by this function, so don't wrap calls to it in dios.
14080 func (fs *fileStore) writeFileWithOptionalSync(name string, data []byte, perm fs.FileMode) error {
14081 return writeAtomically(fs.dios, name, data, perm, fs.syncAlways.Load())
14082 }
14083
14084 func writeFileWithSync(dios *diskIOSemaphore, name string, data []byte, perm fs.FileMode) error {
14085 return writeAtomically(dios, name, data, perm, true)
14086 }
14087
14088 // Windows does not support fsyncing directory metadata, it results in a panic, so
14089 // we need to skip doing this there.
14090 const canFsyncDirectories = runtime.GOOS != "windows"
14091
14092 func writeAtomically(dios *diskIOSemaphore, name string, data []byte, perm fs.FileMode, sync bool) error {
14093 return writeAtomicallyWithTemp(dios, name+".tmp", name, data, perm, sync)
14094 }
14095
14096 func writeAtomicallyWithTemp(dios *diskIOSemaphore, tmp, name string, data []byte, perm fs.FileMode, sync bool) error {
14097 flags := os.O_CREATE | os.O_WRONLY | os.O_TRUNC
14098 if sync {
14099 flags = flags | os.O_SYNC
14100 }
14101 dios.acquire()
14102 defer dios.release()
14103 f, err := os.OpenFile(tmp, flags, perm)
14104 if err != nil {
14105 return err
14106 }
14107 if _, err := f.Write(data); err != nil {
14108 // Close fd, but ignore its error since write takes precedence.
14109 _ = f.Close()
14110 _ = os.Remove(tmp)
14111 return err
14112 }
14113 if err := f.Close(); err != nil {
14114 _ = os.Remove(tmp)
14115 return err
14116 }
14117 if err := os.Rename(tmp, name); err != nil {
14118 _ = os.Remove(tmp)
14119 return err
14120 }
14121 if sync && canFsyncDirectories {
14122 // To ensure that the file rename was persisted on all filesystems,
14123 // also try to flush the directory metadata.
14124 if err = syncDir(filepath.Dir(name)); err != nil {
14125 return err
14126 }
14127 }
14128 return nil
14129 }
14130
14131 func (fs *fileStore) syncFileAndDir(name string) error {
14132 fs.dios.acquire()
14133 defer fs.dios.release()
14134 f, err := os.OpenFile(name, os.O_RDWR, defaultFilePerms)
14135 if err != nil {
14136 if os.IsNotExist(err) {
14137 return nil
14138 }
14139 return err
14140 }
14141 if err = f.Sync(); err != nil {
14142 // Close fd, but ignore its error since sync takes precedence.
14143 _ = f.Close()
14144 return err
14145 }
14146 if err = f.Close(); err != nil {
14147 return err
14148 }
14149 if canFsyncDirectories {
14150 if err = syncDir(filepath.Dir(name)); err != nil {
14151 return err
14152 }
14153 }
14154 return nil
14155 }
14156
14157 // Dios should already be held.
14158 func syncDir(path string) error {
14159 var d *os.File
14160 var err error
14161 if d, err = os.Open(path); err != nil {
14162 return err
14163 }
14164 if err = d.Sync(); err != nil {
14165 // Close fd, but ignore its error since sync takes precedence.
14166 _ = d.Close()
14167 return err
14168 }
14169 if err = d.Close(); err != nil {
14170 return err
14171 }
14172 return nil
14173 }