-
Notifications
You must be signed in to change notification settings - Fork 15
/
Copy pathdb.go
820 lines (684 loc) · 21.8 KB
/
db.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
package pebbledb
import (
"bytes"
"encoding/binary"
"errors"
"fmt"
"math"
"strings"
"sync"
"time"
"github.com/armon/go-metrics"
"github.com/cockroachdb/pebble"
"github.com/cockroachdb/pebble/bloom"
errorutils "github.com/sei-protocol/sei-db/common/errors"
"github.com/sei-protocol/sei-db/common/logger"
"github.com/sei-protocol/sei-db/common/utils"
"github.com/sei-protocol/sei-db/config"
"github.com/sei-protocol/sei-db/proto"
"github.com/sei-protocol/sei-db/ss/types"
"github.com/sei-protocol/sei-db/stream/changelog"
"golang.org/x/exp/slices"
)
const (
VersionSize = 8
PrefixStore = "s/k:"
LenPrefixStore = 4
StorePrefixTpl = "s/k:%s/" // s/k:<storeKey>
HashTpl = "s/_hash:%s:%d-%d" // "s/_hash:<storeKey>:%d-%d"
latestVersionKey = "s/_latest" // NB: latestVersionKey key must be lexically smaller than StorePrefixTpl
earliestVersionKey = "s/_earliest"
latestMigratedKeyMetadata = "s/_latestMigratedKey"
latestMigratedModuleMetadata = "s/_latestMigratedModule"
tombstoneVal = "TOMBSTONE"
// TODO: Make configurable
ImportCommitBatchSize = 10000
PruneCommitBatchSize = 50
)
var (
_ types.StateStore = (*Database)(nil)
defaultWriteOpts = pebble.NoSync
)
type Database struct {
storage *pebble.DB
asyncWriteWG sync.WaitGroup
config config.StateStoreConfig
// Earliest version for db after pruning
earliestVersion int64
// Map of module to when each was last updated
// Used in pruning to skip over stores that have not been updated recently
storeKeyDirty sync.Map
// Changelog used to support async write
streamHandler *changelog.Stream
// Pending changes to be written to the DB
pendingChanges chan VersionedChangesets
}
type VersionedChangesets struct {
Version int64
Changesets []*proto.NamedChangeSet
}
func New(dataDir string, config config.StateStoreConfig) (*Database, error) {
cache := pebble.NewCache(1024 * 1024 * 32)
defer cache.Unref()
opts := &pebble.Options{
Cache: cache,
Comparer: MVCCComparer,
FormatMajorVersion: pebble.FormatNewest,
L0CompactionThreshold: 2,
L0StopWritesThreshold: 1000,
LBaseMaxBytes: 64 << 20, // 64 MB
Levels: make([]pebble.LevelOptions, 7),
MaxConcurrentCompactions: func() int { return 3 }, // TODO: Make Configurable
MemTableSize: 64 << 20,
MemTableStopWritesThreshold: 4,
}
for i := 0; i < len(opts.Levels); i++ {
l := &opts.Levels[i]
l.BlockSize = 32 << 10 // 32 KB
l.IndexBlockSize = 256 << 10 // 256 KB
l.FilterPolicy = bloom.FilterPolicy(10)
l.FilterType = pebble.TableFilter
// TODO: Consider compression only for specific layers like bottommost
l.Compression = pebble.ZstdCompression
if i > 0 {
l.TargetFileSize = opts.Levels[i-1].TargetFileSize * 2
}
l.EnsureDefaults()
}
opts.Levels[6].FilterPolicy = nil
opts.FlushSplitBytes = opts.Levels[0].TargetFileSize
opts = opts.EnsureDefaults()
db, err := pebble.Open(dataDir, opts)
if err != nil {
return nil, fmt.Errorf("failed to open PebbleDB: %w", err)
}
earliestVersion, err := retrieveEarliestVersion(db)
if err != nil {
return nil, fmt.Errorf("failed to open PebbleDB: %w", err)
}
database := &Database{
storage: db,
asyncWriteWG: sync.WaitGroup{},
config: config,
earliestVersion: earliestVersion,
pendingChanges: make(chan VersionedChangesets, config.AsyncWriteBuffer),
}
if config.DedicatedChangelog {
streamHandler, _ := changelog.NewStream(
logger.NewNopLogger(),
utils.GetChangelogPath(dataDir),
changelog.Config{
DisableFsync: true,
ZeroCopy: true,
KeepRecent: uint64(config.KeepRecent),
PruneInterval: 300 * time.Second,
},
)
database.streamHandler = streamHandler
go database.writeAsyncInBackground()
}
return database, nil
}
func NewWithDB(storage *pebble.DB) *Database {
return &Database{
storage: storage,
}
}
func (db *Database) Close() error {
if db.streamHandler != nil {
db.streamHandler.Close()
db.streamHandler = nil
close(db.pendingChanges)
}
// Wait for the async writes to finish
db.asyncWriteWG.Wait()
err := db.storage.Close()
db.storage = nil
return err
}
func (db *Database) SetLatestVersion(version int64) error {
var ts [VersionSize]byte
binary.LittleEndian.PutUint64(ts[:], uint64(version))
err := db.storage.Set([]byte(latestVersionKey), ts[:], defaultWriteOpts)
return err
}
func (db *Database) GetLatestVersion() (int64, error) {
bz, closer, err := db.storage.Get([]byte(latestVersionKey))
if err != nil {
if errors.Is(err, pebble.ErrNotFound) {
// in case of a fresh database
return 0, nil
}
return 0, err
}
if len(bz) == 0 {
return 0, closer.Close()
}
return int64(binary.LittleEndian.Uint64(bz)), closer.Close()
}
func (db *Database) SetEarliestVersion(version int64, ignoreVersion bool) error {
if version > db.earliestVersion || ignoreVersion {
db.earliestVersion = version
var ts [VersionSize]byte
binary.LittleEndian.PutUint64(ts[:], uint64(version))
return db.storage.Set([]byte(earliestVersionKey), ts[:], defaultWriteOpts)
}
return nil
}
func (db *Database) GetEarliestVersion() (int64, error) {
return db.earliestVersion, nil
}
// Retrieves earliest version from db
func retrieveEarliestVersion(db *pebble.DB) (int64, error) {
bz, closer, err := db.Get([]byte(earliestVersionKey))
if err != nil {
if errors.Is(err, pebble.ErrNotFound) {
// in case of a fresh database
return 0, nil
}
return 0, err
}
if len(bz) == 0 {
return 0, closer.Close()
}
return int64(binary.LittleEndian.Uint64(bz)), closer.Close()
}
// SetLatestKey sets the latest key processed during migration.
func (db *Database) SetLatestMigratedKey(key []byte) error {
return db.storage.Set([]byte(latestMigratedKeyMetadata), key, defaultWriteOpts)
}
// GetLatestKey retrieves the latest key processed during migration.
func (db *Database) GetLatestMigratedKey() ([]byte, error) {
bz, closer, err := db.storage.Get([]byte(latestMigratedKeyMetadata))
if err != nil {
if errors.Is(err, pebble.ErrNotFound) {
return nil, nil
}
return nil, err
}
defer closer.Close()
return bz, nil
}
// SetLatestModule sets the latest module processed during migration.
func (db *Database) SetLatestMigratedModule(module string) error {
return db.storage.Set([]byte(latestMigratedModuleMetadata), []byte(module), defaultWriteOpts)
}
// GetLatestModule retrieves the latest module processed during migration.
func (db *Database) GetLatestMigratedModule() (string, error) {
bz, closer, err := db.storage.Get([]byte(latestMigratedModuleMetadata))
if err != nil {
if errors.Is(err, pebble.ErrNotFound) {
return "", nil
}
return "", err
}
defer closer.Close()
return string(bz), nil
}
func (db *Database) Has(storeKey string, version int64, key []byte) (bool, error) {
if version < db.earliestVersion {
return false, nil
}
val, err := db.Get(storeKey, version, key)
if err != nil {
return false, err
}
return val != nil, nil
}
func (db *Database) Get(storeKey string, targetVersion int64, key []byte) ([]byte, error) {
if targetVersion < db.earliestVersion {
return nil, nil
}
prefixedVal, err := getMVCCSlice(db.storage, storeKey, key, targetVersion)
if err != nil {
if errors.Is(err, errorutils.ErrRecordNotFound) {
return nil, nil
}
return nil, fmt.Errorf("failed to perform PebbleDB read: %w", err)
}
valBz, tombBz, ok := SplitMVCCKey(prefixedVal)
if !ok {
return nil, fmt.Errorf("invalid PebbleDB MVCC value: %s", prefixedVal)
}
// A tombstone of zero or a target version that is less than the tombstone
// version means the key is not deleted at the target version.
if len(tombBz) == 0 {
return valBz, nil
}
tombstone, err := decodeUint64Ascending(tombBz)
if err != nil {
return nil, fmt.Errorf("failed to decode value tombstone: %w", err)
}
// A tombstone of zero or a target version that is less than the tombstone
// version means the key is not deleted at the target version.
if targetVersion < tombstone {
return valBz, nil
}
// the value is considered deleted
return nil, nil
}
func (db *Database) ApplyChangeset(version int64, cs *proto.NamedChangeSet) error {
// Check if version is 0 and change it to 1
// We do this specifically since keys written as part of genesis state come in as version 0
// But pebbledb treats version 0 as special, so apply the changeset at version 1 instead
if version == 0 {
version = 1
}
b, err := NewBatch(db.storage, version)
if err != nil {
return err
}
for _, kvPair := range cs.Changeset.Pairs {
if kvPair.Value == nil {
if err := b.Delete(cs.Name, kvPair.Key); err != nil {
return err
}
} else {
if err := b.Set(cs.Name, kvPair.Key, kvPair.Value); err != nil {
return err
}
}
}
// Mark the store as updated
db.storeKeyDirty.Store(cs.Name, version)
return b.Write()
}
func (db *Database) ApplyChangesetAsync(version int64, changesets []*proto.NamedChangeSet) error {
// Write to WAL first
if db.streamHandler != nil {
entry := proto.ChangelogEntry{
Version: version,
}
entry.Changesets = changesets
entry.Upgrades = nil
err := db.streamHandler.WriteNextEntry(entry)
if err != nil {
return err
}
}
// Then write to pending changes
db.pendingChanges <- VersionedChangesets{
Version: version,
Changesets: changesets,
}
return nil
}
func (db *Database) writeAsyncInBackground() {
db.asyncWriteWG.Add(1)
defer db.asyncWriteWG.Done()
for nextChange := range db.pendingChanges {
if db.streamHandler != nil {
version := nextChange.Version
for _, cs := range nextChange.Changesets {
err := db.ApplyChangeset(version, cs)
if err != nil {
panic(err)
}
}
err := db.SetLatestVersion(version)
if err != nil {
panic(err)
}
}
}
}
// Prune attempts to prune all versions up to and including the current version
// Get the range of keys, manually iterate over them and delete them
// We add a heuristic to skip over a module's keys during pruning if it hasn't been updated
// since the last time pruning occurred.
// NOTE: There is a rare case when a module's keys are skipped during pruning even though
// it has been updated. This occurs when that module's keys are updated in between pruning runs, the node after is restarted.
// This is not a large issue given the next time that module is updated, it will be properly pruned thereafter.
func (db *Database) Prune(version int64) error {
earliestVersion := version + 1 // we increment by 1 to include the provided version
itr, err := db.storage.NewIter(nil)
if err != nil {
return err
}
defer itr.Close()
batch := db.storage.NewBatch()
defer batch.Close()
var (
counter int
prevKey, prevKeyEncoded, prevValEncoded []byte
prevVersionDecoded int64
prevStore string
)
for itr.First(); itr.Valid(); {
currKeyEncoded := slices.Clone(itr.Key())
// Ignore metadata entry for version during pruning
if bytes.Equal(currKeyEncoded, []byte(latestVersionKey)) || bytes.Equal(currKeyEncoded, []byte(earliestVersionKey)) {
itr.Next()
continue
}
// Store current key and version
currKey, currVersion, currOK := SplitMVCCKey(currKeyEncoded)
if !currOK {
return fmt.Errorf("invalid MVCC key")
}
storeKey, err := parseStoreKey(currKey)
if err != nil {
// XXX: This should never happen given we skip the metadata keys.
return err
}
// For every new module visited, check to see last time it was updated
if storeKey != prevStore {
prevStore = storeKey
updated, ok := db.storeKeyDirty.Load(storeKey)
versionUpdated, typeOk := updated.(int64)
// Skip a store's keys if version it was last updated is less than last prune height
if !ok || (typeOk && versionUpdated < db.earliestVersion) {
itr.SeekGE(storePrefix(storeKey + "0"))
continue
}
}
currVersionDecoded, err := decodeUint64Ascending(currVersion)
if err != nil {
return err
}
// Seek to next key if we are at a version which is higher than prune height
// Do not seek to next key if KeepLastVersion is false and we need to delete the previous key in pruning
if currVersionDecoded > version && (db.config.KeepLastVersion || prevVersionDecoded > version) {
itr.NextPrefix()
continue
}
// Delete a key if another entry for that key exists at a larger version than original but leq to the prune height
// Also delete a key if it has been tombstoned and its version is leq to the prune height
// Also delete a key if KeepLastVersion is false and version is leq to the prune height
if prevVersionDecoded <= version && (bytes.Equal(prevKey, currKey) || valTombstoned(prevValEncoded) || !db.config.KeepLastVersion) {
err = batch.Delete(prevKeyEncoded, nil)
if err != nil {
return err
}
counter++
if counter >= PruneCommitBatchSize {
err = batch.Commit(defaultWriteOpts)
if err != nil {
return err
}
counter = 0
batch.Reset()
}
}
// Update prevKey and prevVersion for next iteration
prevKey = currKey
prevVersionDecoded = currVersionDecoded
prevKeyEncoded = currKeyEncoded
prevValEncoded = slices.Clone(itr.Value())
itr.Next()
}
// Commit any leftover delete ops in batch
if counter > 0 {
err = batch.Commit(defaultWriteOpts)
if err != nil {
return err
}
}
return db.SetEarliestVersion(earliestVersion, false)
}
func (db *Database) Iterator(storeKey string, version int64, start, end []byte) (types.DBIterator, error) {
if (start != nil && len(start) == 0) || (end != nil && len(end) == 0) {
return nil, errorutils.ErrKeyEmpty
}
if start != nil && end != nil && bytes.Compare(start, end) > 0 {
return nil, errorutils.ErrStartAfterEnd
}
lowerBound := MVCCEncode(prependStoreKey(storeKey, start), 0)
var upperBound []byte
if end != nil {
upperBound = MVCCEncode(prependStoreKey(storeKey, end), 0)
}
itr, err := db.storage.NewIter(&pebble.IterOptions{LowerBound: lowerBound, UpperBound: upperBound})
if err != nil {
return nil, fmt.Errorf("failed to create PebbleDB iterator: %w", err)
}
return newPebbleDBIterator(itr, storePrefix(storeKey), start, end, version, db.earliestVersion, false), nil
}
func (db *Database) ReverseIterator(storeKey string, version int64, start, end []byte) (types.DBIterator, error) {
if (start != nil && len(start) == 0) || (end != nil && len(end) == 0) {
return nil, errorutils.ErrKeyEmpty
}
if start != nil && end != nil && bytes.Compare(start, end) > 0 {
return nil, errorutils.ErrStartAfterEnd
}
lowerBound := MVCCEncode(prependStoreKey(storeKey, start), 0)
var upperBound []byte
if end != nil {
upperBound = MVCCEncode(prependStoreKey(storeKey, end), 0)
}
itr, err := db.storage.NewIter(&pebble.IterOptions{LowerBound: lowerBound, UpperBound: upperBound})
if err != nil {
return nil, fmt.Errorf("failed to create PebbleDB iterator: %w", err)
}
return newPebbleDBIterator(itr, storePrefix(storeKey), start, end, version, db.earliestVersion, true), nil
}
// Import loads the initial version of the state in parallel with numWorkers goroutines
// TODO: Potentially add retries instead of panics
func (db *Database) Import(version int64, ch <-chan types.SnapshotNode) error {
var wg sync.WaitGroup
worker := func() {
defer wg.Done()
batch, err := NewBatch(db.storage, version)
if err != nil {
panic(err)
}
var counter int
for entry := range ch {
err := batch.Set(entry.StoreKey, entry.Key, entry.Value)
if err != nil {
panic(err)
}
counter++
if counter%ImportCommitBatchSize == 0 {
if err := batch.Write(); err != nil {
panic(err)
}
batch, err = NewBatch(db.storage, version)
if err != nil {
panic(err)
}
}
}
if batch.Size() > 0 {
if err := batch.Write(); err != nil {
panic(err)
}
}
}
wg.Add(db.config.ImportNumWorkers)
for i := 0; i < db.config.ImportNumWorkers; i++ {
go worker()
}
wg.Wait()
return nil
}
func (db *Database) RawImport(ch <-chan types.RawSnapshotNode) error {
var wg sync.WaitGroup
worker := func() {
defer wg.Done()
batch, err := NewRawBatch(db.storage)
if err != nil {
panic(err)
}
var counter int
var latestKey []byte // store the latest key from the batch
var latestModule string
for entry := range ch {
err := batch.Set(entry.StoreKey, entry.Key, entry.Value, entry.Version)
if err != nil {
panic(err)
}
latestKey = entry.Key // track the latest key
latestModule = entry.StoreKey
counter++
if counter%ImportCommitBatchSize == 0 {
startTime := time.Now()
// Commit the batch and record the latest key as metadata
if err := batch.Write(); err != nil {
panic(err)
}
// Persist the latest key in the metadata
if err := db.SetLatestMigratedKey(latestKey); err != nil {
panic(err)
}
if err := db.SetLatestMigratedModule(latestModule); err != nil {
panic(err)
}
if counter%1000000 == 0 {
fmt.Printf("Time taken to write batch counter %d: %v\n", counter, time.Since(startTime))
metrics.IncrCounterWithLabels([]string{"sei", "migration", "nodes_imported"}, float32(1000000), []metrics.Label{
{Name: "module", Value: latestModule},
})
}
batch, err = NewRawBatch(db.storage)
if err != nil {
panic(err)
}
}
}
// Final batch write
if batch.Size() > 0 {
if err := batch.Write(); err != nil {
panic(err)
}
// Persist the final latest key
if err := db.SetLatestMigratedKey(latestKey); err != nil {
panic(err)
}
if err := db.SetLatestMigratedModule(latestModule); err != nil {
panic(err)
}
}
}
wg.Add(db.config.ImportNumWorkers)
for i := 0; i < db.config.ImportNumWorkers; i++ {
go worker()
}
wg.Wait()
return nil
}
// RawIterate iterates over all keys and values for a store
func (db *Database) RawIterate(storeKey string, fn func(key []byte, value []byte, version int64) bool) (bool, error) {
// Iterate through all keys and values for a store
lowerBound := MVCCEncode(prependStoreKey(storeKey, nil), 0)
itr, err := db.storage.NewIter(&pebble.IterOptions{LowerBound: lowerBound})
if err != nil {
return false, fmt.Errorf("failed to create PebbleDB iterator: %w", err)
}
defer itr.Close()
for itr.First(); itr.Valid(); itr.Next() {
currKeyEncoded := itr.Key()
// Ignore metadata entry for version
if bytes.Equal(currKeyEncoded, []byte(latestVersionKey)) || bytes.Equal(currKeyEncoded, []byte(earliestVersionKey)) {
continue
}
// Store current key and version
currKey, currVersion, currOK := SplitMVCCKey(currKeyEncoded)
if !currOK {
return false, fmt.Errorf("invalid MVCC key")
}
// Only iterate through module
if storeKey != "" && !bytes.HasPrefix(currKey, storePrefix(storeKey)) {
break
}
currVersionDecoded, err := decodeUint64Ascending(currVersion)
if err != nil {
return false, err
}
// Decode the value
currValEncoded := itr.Value()
if valTombstoned(currValEncoded) {
continue
}
valBz, _, ok := SplitMVCCKey(currValEncoded)
if !ok {
return false, fmt.Errorf("invalid PebbleDB MVCC value: %s", currKey)
}
// Call callback fn
if fn(currKey, valBz, currVersionDecoded) {
return true, nil
}
}
return false, nil
}
func storePrefix(storeKey string) []byte {
return []byte(fmt.Sprintf(StorePrefixTpl, storeKey))
}
func prependStoreKey(storeKey string, key []byte) []byte {
if storeKey == "" {
return key
}
return append(storePrefix(storeKey), key...)
}
// Parses store from key with format "s/k:{store}/..."
func parseStoreKey(key []byte) (string, error) {
// Convert byte slice to string only once
keyStr := string(key)
if !strings.HasPrefix(keyStr, PrefixStore) {
return "", fmt.Errorf("not a valid store key")
}
// Find the first occurrence of "/" after the prefix
slashIndex := strings.Index(keyStr[LenPrefixStore:], "/")
if slashIndex == -1 {
return "", fmt.Errorf("not a valid store key")
}
// Return the substring between the prefix and the first "/"
return keyStr[LenPrefixStore : LenPrefixStore+slashIndex], nil
}
func getMVCCSlice(db *pebble.DB, storeKey string, key []byte, version int64) ([]byte, error) {
// end domain is exclusive, so we need to increment the version by 1
if version < math.MaxInt64 {
version++
}
itr, err := db.NewIter(&pebble.IterOptions{
LowerBound: MVCCEncode(prependStoreKey(storeKey, key), 0),
UpperBound: MVCCEncode(prependStoreKey(storeKey, key), version),
})
if err != nil {
return nil, fmt.Errorf("failed to create PebbleDB iterator: %w", err)
}
defer func() {
err = errorutils.Join(err, itr.Close())
}()
if !itr.Last() {
return nil, errorutils.ErrRecordNotFound
}
_, vBz, ok := SplitMVCCKey(itr.Key())
if !ok {
return nil, fmt.Errorf("invalid PebbleDB MVCC key: %s", itr.Key())
}
keyVersion, err := decodeUint64Ascending(vBz)
if err != nil {
return nil, fmt.Errorf("failed to decode key version: %w", err)
}
if keyVersion > version {
return nil, fmt.Errorf("key version too large: %d", keyVersion)
}
return slices.Clone(itr.Value()), nil
}
func valTombstoned(value []byte) bool {
if value == nil {
return false
}
_, tombBz, ok := SplitMVCCKey(value)
if !ok {
// XXX: This should not happen as that would indicate we have a malformed
// MVCC value.
panic(fmt.Sprintf("invalid PebbleDB MVCC value: %s", value))
}
// If the tombstone suffix is empty, we consider this a zero value and thus it
// is not tombstoned.
if len(tombBz) == 0 {
return false
}
return true
}
// WriteBlockRangeHash writes a hash for a range of blocks to the database
func (db *Database) WriteBlockRangeHash(storeKey string, beginBlockRange, endBlockRange int64, hash []byte) error {
key := []byte(fmt.Sprintf(HashTpl, storeKey, beginBlockRange, endBlockRange))
err := db.storage.Set(key, hash, defaultWriteOpts)
if err != nil {
return fmt.Errorf("failed to write block range hash: %w", err)
}
return nil
}