-
Notifications
You must be signed in to change notification settings - Fork 268
/
mutable_tree.go
1014 lines (874 loc) · 28.6 KB
/
mutable_tree.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
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package iavl
import (
"bytes"
"crypto/sha256"
"errors"
"fmt"
"sort"
"sync"
dbm "github.com/cosmos/cosmos-db"
"github.com/cosmos/iavl/fastnode"
ibytes "github.com/cosmos/iavl/internal/bytes"
"github.com/cosmos/iavl/internal/logger"
)
// commitGap after upgrade/delete commitGap FastNodes when commit the batch
var commitGap uint64 = 5000000
// ErrVersionDoesNotExist is returned if a requested version does not exist.
var ErrVersionDoesNotExist = errors.New("version does not exist")
// ErrKeyDoesNotExist is returned if a key does not exist.
var ErrKeyDoesNotExist = errors.New("key does not exist")
// MutableTree is a persistent tree which keeps track of versions. It is not safe for concurrent
// use, and should be guarded by a Mutex or RWLock as appropriate. An immutable tree at a given
// version can be returned via GetImmutable, which is safe for concurrent access.
//
// Given and returned key/value byte slices must not be modified, since they may point to data
// located inside IAVL which would also be modified.
//
// The inner ImmutableTree should not be used directly by callers.
type MutableTree struct {
*ImmutableTree // The current, working tree.
lastSaved *ImmutableTree // The most recently saved tree.
unsavedFastNodeAdditions map[string]*fastnode.Node // FastNodes that have not yet been saved to disk
unsavedFastNodeRemovals map[string]interface{} // FastNodes that have not yet been removed from disk
ndb *nodeDB
skipFastStorageUpgrade bool // If true, the tree will work like no fast storage and always not upgrade fast storage
mtx sync.Mutex
}
// NewMutableTree returns a new tree with the specified cache size and datastore.
func NewMutableTree(db dbm.DB, cacheSize int, skipFastStorageUpgrade bool) (*MutableTree, error) {
return NewMutableTreeWithOpts(db, cacheSize, nil, skipFastStorageUpgrade)
}
// NewMutableTreeWithOpts returns a new tree with the specified options.
func NewMutableTreeWithOpts(db dbm.DB, cacheSize int, opts *Options, skipFastStorageUpgrade bool) (*MutableTree, error) {
ndb := newNodeDB(db, cacheSize, opts)
head := &ImmutableTree{ndb: ndb, skipFastStorageUpgrade: skipFastStorageUpgrade}
return &MutableTree{
ImmutableTree: head,
lastSaved: head.clone(),
unsavedFastNodeAdditions: make(map[string]*fastnode.Node),
unsavedFastNodeRemovals: make(map[string]interface{}),
ndb: ndb,
skipFastStorageUpgrade: skipFastStorageUpgrade,
}, nil
}
// IsEmpty returns whether or not the tree has any keys. Only trees that are
// not empty can be saved.
func (tree *MutableTree) IsEmpty() bool {
return tree.ImmutableTree.Size() == 0
}
// VersionExists returns whether or not a version exists.
func (tree *MutableTree) VersionExists(version int64) bool {
firstVersion, err := tree.ndb.getFirstVersion()
if err != nil {
return false
}
latestVersion, err := tree.ndb.getLatestVersion()
if err != nil {
return false
}
return firstVersion <= version && version <= latestVersion
}
// AvailableVersions returns all available versions in ascending order
func (tree *MutableTree) AvailableVersions() []int {
firstVersion, err := tree.ndb.getFirstVersion()
if err != nil {
return nil
}
latestVersion, err := tree.ndb.getLatestVersion()
if err != nil {
return nil
}
res := make([]int, 0)
for version := firstVersion; version <= latestVersion; version++ {
res = append(res, int(version))
}
return res
}
// Hash returns the hash of the latest saved version of the tree, as returned
// by SaveVersion. If no versions have been saved, Hash returns nil.
func (tree *MutableTree) Hash() ([]byte, error) {
return tree.lastSaved.Hash()
}
// WorkingHash returns the hash of the current working tree.
func (tree *MutableTree) WorkingHash() ([]byte, error) {
return tree.ImmutableTree.Hash()
}
// String returns a string representation of the tree.
func (tree *MutableTree) String() (string, error) {
return tree.ndb.String()
}
// Set sets a key in the working tree. Nil values are invalid. The given
// key/value byte slices must not be modified after this call, since they point
// to slices stored within IAVL. It returns true when an existing value was
// updated, while false means it was a new key.
func (tree *MutableTree) Set(key, value []byte) (updated bool, err error) {
updated, err = tree.set(key, value)
if err != nil {
return false, err
}
return updated, nil
}
// Get returns the value of the specified key if it exists, or nil otherwise.
// The returned value must not be modified, since it may point to data stored within IAVL.
func (tree *MutableTree) Get(key []byte) ([]byte, error) {
if tree.root == nil {
return nil, nil
}
if !tree.skipFastStorageUpgrade {
if fastNode, ok := tree.unsavedFastNodeAdditions[ibytes.UnsafeBytesToStr(key)]; ok {
return fastNode.GetValue(), nil
}
// check if node was deleted
if _, ok := tree.unsavedFastNodeRemovals[string(key)]; ok {
return nil, nil
}
}
return tree.ImmutableTree.Get(key)
}
// Import returns an importer for tree nodes previously exported by ImmutableTree.Export(),
// producing an identical IAVL tree. The caller must call Close() on the importer when done.
//
// version should correspond to the version that was initially exported. It must be greater than
// or equal to the highest ExportNode version number given.
//
// Import can only be called on an empty tree. It is the callers responsibility that no other
// modifications are made to the tree while importing.
func (tree *MutableTree) Import(version int64) (*Importer, error) {
return newImporter(tree, version)
}
// Iterate iterates over all keys of the tree. The keys and values must not be modified,
// since they may point to data stored within IAVL. Returns true if stopped by callnack, false otherwise
func (tree *MutableTree) Iterate(fn func(key []byte, value []byte) bool) (stopped bool, err error) {
if tree.root == nil {
return false, nil
}
if tree.skipFastStorageUpgrade {
return tree.ImmutableTree.Iterate(fn)
}
isFastCacheEnabled, err := tree.IsFastCacheEnabled()
if err != nil {
return false, err
}
if !isFastCacheEnabled {
return tree.ImmutableTree.Iterate(fn)
}
itr := NewUnsavedFastIterator(nil, nil, true, tree.ndb, tree.unsavedFastNodeAdditions, tree.unsavedFastNodeRemovals)
defer itr.Close()
for ; itr.Valid(); itr.Next() {
if fn(itr.Key(), itr.Value()) {
return true, nil
}
}
return false, nil
}
// Iterator returns an iterator over the mutable tree.
// CONTRACT: no updates are made to the tree while an iterator is active.
func (tree *MutableTree) Iterator(start, end []byte, ascending bool) (dbm.Iterator, error) {
if !tree.skipFastStorageUpgrade {
isFastCacheEnabled, err := tree.IsFastCacheEnabled()
if err != nil {
return nil, err
}
if isFastCacheEnabled {
return NewUnsavedFastIterator(start, end, ascending, tree.ndb, tree.unsavedFastNodeAdditions, tree.unsavedFastNodeRemovals), nil
}
}
return tree.ImmutableTree.Iterator(start, end, ascending)
}
func (tree *MutableTree) set(key []byte, value []byte) (updated bool, err error) {
if value == nil {
return updated, fmt.Errorf("attempt to store nil value at key '%s'", key)
}
if tree.ImmutableTree.root == nil {
if !tree.skipFastStorageUpgrade {
tree.addUnsavedAddition(key, fastnode.NewNode(key, value, tree.version+1))
}
tree.ImmutableTree.root = NewNode(key, value, tree.version+1)
return updated, nil
}
tree.ImmutableTree.root, updated, err = tree.recursiveSet(tree.ImmutableTree.root, key, value)
return updated, err
}
func (tree *MutableTree) recursiveSet(node *Node, key []byte, value []byte) (
newSelf *Node, updated bool, err error,
) {
version := tree.version + 1
if node.isLeaf() {
if !tree.skipFastStorageUpgrade {
tree.addUnsavedAddition(key, fastnode.NewNode(key, value, version))
}
switch bytes.Compare(key, node.key) {
case -1:
return &Node{
key: node.key,
subtreeHeight: 1,
size: 2,
leftNode: NewNode(key, value, version),
rightNode: node,
version: version,
}, false, nil
case 1:
return &Node{
key: key,
subtreeHeight: 1,
size: 2,
leftNode: node,
rightNode: NewNode(key, value, version),
version: version,
}, false, nil
default:
return NewNode(key, value, version), true, nil
}
} else {
node, err = node.clone(version)
if err != nil {
return nil, false, err
}
if bytes.Compare(key, node.key) < 0 {
leftNode, err := node.getLeftNode(tree.ImmutableTree)
if err != nil {
return nil, false, err
}
node.leftNode, updated, err = tree.recursiveSet(leftNode, key, value)
if err != nil {
return nil, updated, err
}
node.leftHash = nil // leftHash is yet unknown
} else {
rightNode, err := node.getRightNode(tree.ImmutableTree)
if err != nil {
return nil, false, err
}
node.rightNode, updated, err = tree.recursiveSet(rightNode, key, value)
if err != nil {
return nil, updated, err
}
node.rightHash = nil // rightHash is yet unknown
}
if updated {
return node, updated, nil
}
err = node.calcHeightAndSize(tree.ImmutableTree)
if err != nil {
return nil, false, err
}
newNode, err := tree.balance(node)
if err != nil {
return nil, false, err
}
return newNode, updated, err
}
}
// Remove removes a key from the working tree. The given key byte slice should not be modified
// after this call, since it may point to data stored inside IAVL.
func (tree *MutableTree) Remove(key []byte) ([]byte, bool, error) {
val, removed, err := tree.remove(key)
if err != nil {
return nil, false, err
}
return val, removed, nil
}
// remove tries to remove a key from the tree and if removed, returns its
// value, nodes orphaned and 'true'.
func (tree *MutableTree) remove(key []byte) (value []byte, removed bool, err error) {
if tree.root == nil {
return nil, false, nil
}
newRootHash, newRoot, _, value, err := tree.recursiveRemove(tree.root, key)
if err != nil && err != ErrKeyDoesNotExist {
return nil, false, err
}
if !tree.skipFastStorageUpgrade {
tree.addUnsavedRemoval(key)
}
if newRoot == nil && newRootHash != nil {
tree.root, err = tree.ndb.GetNode(newRootHash)
if err != nil {
return nil, false, err
}
} else {
tree.root = newRoot
}
return value, true, nil
}
// removes the node corresponding to the passed key and balances the tree.
// It returns:
// - the hash of the new node (or nil if the node is the one removed)
// - the node that replaces the orig. node after remove
// - new leftmost leaf key for tree after successfully removing 'key' if changed.
// - the removed value
// - the orphaned nodes.
func (tree *MutableTree) recursiveRemove(node *Node, key []byte) (newHash []byte, newSelf *Node, newKey []byte, newValue []byte, err error) {
version := tree.version + 1
if node.isLeaf() {
if bytes.Equal(key, node.key) {
return nil, nil, nil, node.value, nil
}
return node.hash, node, nil, nil, ErrKeyDoesNotExist
}
// node.key < key; we go to the left to find the key:
if bytes.Compare(key, node.key) < 0 {
leftNode, err := node.getLeftNode(tree.ImmutableTree)
if err != nil {
return nil, nil, nil, nil, err
}
newLeftHash, newLeftNode, newKey, value, err := tree.recursiveRemove(leftNode, key)
if err != nil {
if err == ErrKeyDoesNotExist {
return node.hash, node, nil, value, err
}
return nil, nil, nil, nil, err
}
if newLeftHash == nil && newLeftNode == nil { // left node held value, was removed
return node.rightHash, node.rightNode, node.key, value, nil
}
newNode, err := node.clone(version)
if err != nil {
return nil, nil, nil, nil, err
}
newNode.leftHash, newNode.leftNode = newLeftHash, newLeftNode
err = newNode.calcHeightAndSize(tree.ImmutableTree)
if err != nil {
return nil, nil, nil, nil, err
}
newNode, err = tree.balance(newNode)
if err != nil {
return nil, nil, nil, nil, err
}
return newNode.hash, newNode, newKey, value, nil
}
// node.key >= key; either found or look to the right:
rightNode, err := node.getRightNode(tree.ImmutableTree)
if err != nil {
return nil, nil, nil, nil, err
}
newRightHash, newRightNode, newKey, value, err := tree.recursiveRemove(rightNode, key)
if err != nil {
if err == ErrKeyDoesNotExist {
return node.hash, node, nil, value, err
}
return nil, nil, nil, nil, err
}
if newRightHash == nil && newRightNode == nil { // right node held value, was removed
return node.leftHash, node.leftNode, nil, value, nil
}
newNode, err := node.clone(version)
if err != nil {
return nil, nil, nil, nil, err
}
newNode.rightHash, newNode.rightNode = newRightHash, newRightNode
if newKey != nil {
newNode.key = newKey
}
err = newNode.calcHeightAndSize(tree.ImmutableTree)
if err != nil {
return nil, nil, nil, nil, err
}
newNode, err = tree.balance(newNode)
if err != nil {
return nil, nil, nil, nil, err
}
return newNode.hash, newNode, nil, value, nil
}
// Load the latest versioned tree from disk.
func (tree *MutableTree) Load() (int64, error) {
return tree.LoadVersion(int64(0))
}
// Returns the version number of the specific version found
func (tree *MutableTree) LoadVersion(targetVersion int64) (int64, error) {
firstVersion, err := tree.ndb.getFirstVersion()
if err != nil {
return 0, err
}
latestVersion, err := tree.ndb.getLatestVersion()
if err != nil {
return 0, err
}
if firstVersion > 0 && firstVersion < int64(tree.ndb.opts.InitialVersion) {
return latestVersion, fmt.Errorf("initial version set to %v, but found earlier version %v",
tree.ndb.opts.InitialVersion, firstVersion)
}
if latestVersion < targetVersion {
return latestVersion, fmt.Errorf("wanted to load target %d but only found up to %d", targetVersion, latestVersion)
}
if firstVersion == 0 {
if targetVersion <= 0 {
if !tree.skipFastStorageUpgrade {
tree.mtx.Lock()
defer tree.mtx.Unlock()
_, err := tree.enableFastStorageAndCommitIfNotEnabled()
return 0, err
}
return 0, nil
}
return 0, fmt.Errorf("no versions found while trying to load %v", targetVersion)
}
if targetVersion <= 0 {
targetVersion = latestVersion
}
if firstVersion > targetVersion {
return latestVersion, fmt.Errorf("wanted to load target %v but only found from %v",
targetVersion, firstVersion)
}
if latestVersion < targetVersion {
return latestVersion, fmt.Errorf("wanted to load target %v but only found up to %v",
targetVersion, latestVersion)
}
targetRoot, err := tree.ndb.getRoot(targetVersion)
if err != nil {
return 0, err
}
if firstVersion < int64(tree.ndb.opts.InitialVersion) {
return latestVersion, fmt.Errorf("initial version set to %v, but found earlier version %v",
tree.ndb.opts.InitialVersion, firstVersion)
}
t := &ImmutableTree{
ndb: tree.ndb,
version: targetVersion,
skipFastStorageUpgrade: tree.skipFastStorageUpgrade,
}
if len(targetRoot) != 0 {
t.root, err = tree.ndb.GetNode(targetRoot)
if err != nil {
return 0, err
}
}
tree.ImmutableTree = t
tree.lastSaved = t.clone()
if !tree.skipFastStorageUpgrade {
// Attempt to upgrade
if _, err := tree.enableFastStorageAndCommitIfNotEnabled(); err != nil {
return 0, err
}
}
return latestVersion, nil
}
// loadVersionForOverwriting attempts to load a tree at a previously committed
// version, or the latest version below it. Any versions greater than targetVersion will be deleted.
func (tree *MutableTree) LoadVersionForOverwriting(targetVersion int64) error {
if _, err := tree.LoadVersion(targetVersion); err != nil {
return err
}
if err := tree.ndb.DeleteVersionsFrom(targetVersion + 1); err != nil {
return err
}
// Commit the tree rollback first
// The fast storage rebuild don't have to be atomic with this,
// because it's idempotent and will do again when `LoadVersion`.
if err := tree.ndb.Commit(); err != nil {
return err
}
if !tree.skipFastStorageUpgrade {
// it'll repopulates the fast node index because of version mismatch.
if _, err := tree.enableFastStorageAndCommitIfNotEnabled(); err != nil {
return err
}
}
return nil
}
// Returns true if the tree may be auto-upgraded, false otherwise
// An example of when an upgrade may be performed is when we are enaling fast storage for the first time or
// need to overwrite fast nodes due to mismatch with live state.
func (tree *MutableTree) IsUpgradeable() (bool, error) {
shouldForce, err := tree.ndb.shouldForceFastStorageUpgrade()
if err != nil {
return false, err
}
return !tree.skipFastStorageUpgrade && (!tree.ndb.hasUpgradedToFastStorage() || shouldForce), nil
}
// enableFastStorageAndCommitIfNotEnabled if nodeDB doesn't mark fast storage as enabled, enable it, and commit the update.
// Checks whether the fast cache on disk matches latest live state. If not, deletes all existing fast nodes and repopulates them
// from latest tree.
func (tree *MutableTree) enableFastStorageAndCommitIfNotEnabled() (bool, error) {
isUpgradeable, err := tree.IsUpgradeable()
if err != nil {
return false, err
}
if !isUpgradeable {
return false, nil
}
// If there is a mismatch between which fast nodes are on disk and the live state due to temporary
// downgrade and subsequent re-upgrade, we cannot know for sure which fast nodes have been removed while downgraded,
// Therefore, there might exist stale fast nodes on disk. As a result, to avoid persisting the stale state, it might
// be worth to delete the fast nodes from disk.
fastItr := NewFastIterator(nil, nil, true, tree.ndb)
defer fastItr.Close()
var deletedFastNodes uint64
for ; fastItr.Valid(); fastItr.Next() {
deletedFastNodes++
if err := tree.ndb.DeleteFastNode(fastItr.Key()); err != nil {
return false, err
}
if deletedFastNodes%commitGap == 0 {
if err := tree.ndb.Commit(); err != nil {
return false, err
}
}
}
if deletedFastNodes%commitGap != 0 {
if err := tree.ndb.Commit(); err != nil {
return false, err
}
}
if err := tree.enableFastStorageAndCommit(); err != nil {
tree.ndb.storageVersion = defaultStorageVersionValue
return false, err
}
return true, nil
}
func (tree *MutableTree) enableFastStorageAndCommit() error {
var err error
itr := NewIterator(nil, nil, true, tree.ImmutableTree)
defer itr.Close()
var upgradedFastNodes uint64
for ; itr.Valid(); itr.Next() {
upgradedFastNodes++
if err = tree.ndb.SaveFastNodeNoCache(fastnode.NewNode(itr.Key(), itr.Value(), tree.version)); err != nil {
return err
}
if upgradedFastNodes%commitGap == 0 {
err := tree.ndb.Commit()
if err != nil {
return err
}
}
}
if err = itr.Error(); err != nil {
return err
}
if err = tree.ndb.setFastStorageVersionToBatch(); err != nil {
return err
}
return tree.ndb.Commit()
}
// GetImmutable loads an ImmutableTree at a given version for querying. The returned tree is
// safe for concurrent access, provided the version is not deleted, e.g. via `DeleteVersion()`.
func (tree *MutableTree) GetImmutable(version int64) (*ImmutableTree, error) {
firstVersion, err := tree.ndb.getFirstVersion()
if err != nil {
return nil, err
}
latestVersion, err := tree.ndb.getLatestVersion()
if err != nil {
return nil, err
}
if firstVersion > version || version > latestVersion {
return nil, ErrVersionDoesNotExist
}
rootHash, err := tree.ndb.getRoot(version)
if err != nil {
return nil, err
}
root, err := tree.ndb.GetNode(rootHash)
if err != nil {
return nil, err
}
return &ImmutableTree{
root: root,
ndb: tree.ndb,
version: version,
skipFastStorageUpgrade: tree.skipFastStorageUpgrade,
}, nil
}
// Rollback resets the working tree to the latest saved version, discarding
// any unsaved modifications.
func (tree *MutableTree) Rollback() {
if tree.version > 0 {
tree.ImmutableTree = tree.lastSaved.clone()
} else {
tree.ImmutableTree = &ImmutableTree{
ndb: tree.ndb,
version: 0,
skipFastStorageUpgrade: tree.skipFastStorageUpgrade,
}
}
if !tree.skipFastStorageUpgrade {
tree.unsavedFastNodeAdditions = map[string]*fastnode.Node{}
tree.unsavedFastNodeRemovals = map[string]interface{}{}
}
}
// GetVersioned gets the value at the specified key and version. The returned value must not be
// modified, since it may point to data stored within IAVL.
func (tree *MutableTree) GetVersioned(key []byte, version int64) ([]byte, error) {
if tree.VersionExists(version) {
if !tree.skipFastStorageUpgrade {
isFastCacheEnabled, err := tree.IsFastCacheEnabled()
if err != nil {
return nil, err
}
if isFastCacheEnabled {
fastNode, _ := tree.ndb.GetFastNode(key)
if fastNode == nil && version == tree.ndb.latestVersion {
return nil, nil
}
if fastNode != nil && fastNode.GetVersionLastUpdatedAt() <= version {
return fastNode.GetValue(), nil
}
}
}
t, err := tree.GetImmutable(version)
if err != nil {
return nil, nil
}
value, err := t.Get(key)
if err != nil {
return nil, err
}
return value, nil
}
return nil, nil
}
// SaveVersion saves a new tree version to disk, based on the current state of
// the tree. Returns the hash and new version number.
func (tree *MutableTree) SaveVersion() ([]byte, int64, error) {
version := tree.version + 1
if version == 1 && tree.ndb.opts.InitialVersion > 0 {
version = int64(tree.ndb.opts.InitialVersion)
}
if tree.VersionExists(version) {
// If the version already exists, return an error as we're attempting to overwrite.
// However, the same hash means idempotent (i.e. no-op).
existingHash, err := tree.ndb.getRoot(version)
if err != nil {
return nil, version, err
}
// If the existing root hash is empty (because the tree is empty), then we need to
// compare with the hash of an empty input which is what `WorkingHash()` returns.
if len(existingHash) == 0 {
existingHash = sha256.New().Sum(nil)
}
newHash, err := tree.WorkingHash()
if err != nil {
return nil, version, err
}
if bytes.Equal(existingHash, newHash) {
tree.version = version
tree.ImmutableTree = tree.ImmutableTree.clone()
tree.lastSaved = tree.ImmutableTree.clone()
return existingHash, version, nil
}
return nil, version, fmt.Errorf("version %d was already saved to different hash %X (existing hash %X)", version, newHash, existingHash)
}
if tree.root == nil {
// There can still be orphans, for example if the root is the node being
// removed.
logger.Debug("SAVE EMPTY TREE %v\n", version)
if err := tree.ndb.SaveEmptyRoot(version); err != nil {
return nil, 0, err
}
} else {
logger.Debug("SAVE TREE %v\n", version)
if _, err := tree.ndb.SaveBranch(tree.root); err != nil {
return nil, 0, err
}
if err := tree.ndb.SaveRoot(tree.root, version); err != nil {
return nil, 0, err
}
}
if !tree.skipFastStorageUpgrade {
if err := tree.saveFastNodeVersion(); err != nil {
return nil, version, err
}
}
if err := tree.ndb.Commit(); err != nil {
return nil, version, err
}
tree.version = version
// set new working tree
tree.ImmutableTree = tree.ImmutableTree.clone()
tree.lastSaved = tree.ImmutableTree.clone()
if !tree.skipFastStorageUpgrade {
tree.unsavedFastNodeAdditions = make(map[string]*fastnode.Node)
tree.unsavedFastNodeRemovals = make(map[string]interface{})
}
hash, err := tree.Hash()
if err != nil {
return nil, version, err
}
return hash, version, nil
}
func (tree *MutableTree) saveFastNodeVersion() error {
if err := tree.saveFastNodeAdditions(); err != nil {
return err
}
if err := tree.saveFastNodeRemovals(); err != nil {
return err
}
return tree.ndb.setFastStorageVersionToBatch()
}
func (tree *MutableTree) getUnsavedFastNodeAdditions() map[string]*fastnode.Node {
return tree.unsavedFastNodeAdditions
}
// getUnsavedFastNodeRemovals returns unsaved FastNodes to remove
func (tree *MutableTree) getUnsavedFastNodeRemovals() map[string]interface{} {
return tree.unsavedFastNodeRemovals
}
func (tree *MutableTree) addUnsavedAddition(key []byte, node *fastnode.Node) {
skey := ibytes.UnsafeBytesToStr(key)
delete(tree.unsavedFastNodeRemovals, skey)
tree.unsavedFastNodeAdditions[skey] = node
}
func (tree *MutableTree) saveFastNodeAdditions() error {
keysToSort := make([]string, 0, len(tree.unsavedFastNodeAdditions))
for key := range tree.unsavedFastNodeAdditions {
keysToSort = append(keysToSort, key)
}
sort.Strings(keysToSort)
for _, key := range keysToSort {
if err := tree.ndb.SaveFastNode(tree.unsavedFastNodeAdditions[key]); err != nil {
return err
}
}
return nil
}
func (tree *MutableTree) addUnsavedRemoval(key []byte) {
skey := ibytes.UnsafeBytesToStr(key)
delete(tree.unsavedFastNodeAdditions, skey)
tree.unsavedFastNodeRemovals[skey] = true
}
func (tree *MutableTree) saveFastNodeRemovals() error {
keysToSort := make([]string, 0, len(tree.unsavedFastNodeRemovals))
for key := range tree.unsavedFastNodeRemovals {
keysToSort = append(keysToSort, key)
}
sort.Strings(keysToSort)
for _, key := range keysToSort {
if err := tree.ndb.DeleteFastNode(ibytes.UnsafeStrToBytes(key)); err != nil {
return err
}
}
return nil
}
// SetInitialVersion sets the initial version of the tree, replacing Options.InitialVersion.
// It is only used during the initial SaveVersion() call for a tree with no other versions,
// and is otherwise ignored.
func (tree *MutableTree) SetInitialVersion(version uint64) {
tree.ndb.opts.InitialVersion = version
}
// DeleteVersionsTo removes versions upto the given version from the MutableTree.
// An error is returned if any single version has active readers.
// All writes happen in a single batch with a single commit.
func (tree *MutableTree) DeleteVersionsTo(toVersion int64) error {
if err := tree.ndb.DeleteVersionsTo(toVersion); err != nil {
return err
}
if err := tree.ndb.Commit(); err != nil {
return err
}
return nil
}
// Rotate right and return the new node and orphan.
func (tree *MutableTree) rotateRight(node *Node) (*Node, error) {
version := tree.version + 1
var err error
// TODO: optimize balance & rotate.
node, err = node.clone(version)
if err != nil {
return nil, err
}
leftNode, err := node.getLeftNode(tree.ImmutableTree)
if err != nil {
return nil, err
}
newNode, err := leftNode.clone(version)
if err != nil {
return nil, err
}
newNoderHash, newNoderCached := newNode.rightHash, newNode.rightNode
newNode.rightHash, newNode.rightNode = node.hash, node
node.leftHash, node.leftNode = newNoderHash, newNoderCached
err = node.calcHeightAndSize(tree.ImmutableTree)
if err != nil {
return nil, err
}
err = newNode.calcHeightAndSize(tree.ImmutableTree)
if err != nil {
return nil, err
}
return newNode, nil
}
// Rotate left and return the new node and orphan.
func (tree *MutableTree) rotateLeft(node *Node) (*Node, error) {
version := tree.version + 1
var err error
// TODO: optimize balance & rotate.
node, err = node.clone(version)
if err != nil {
return nil, err
}
rightNode, err := node.getRightNode(tree.ImmutableTree)
if err != nil {
return nil, err
}
newNode, err := rightNode.clone(version)
if err != nil {
return nil, err
}
newNodelHash, newNodelCached := newNode.leftHash, newNode.leftNode
newNode.leftHash, newNode.leftNode = node.hash, node
node.rightHash, node.rightNode = newNodelHash, newNodelCached
err = node.calcHeightAndSize(tree.ImmutableTree)
if err != nil {
return nil, err
}
err = newNode.calcHeightAndSize(tree.ImmutableTree)
if err != nil {
return nil, err
}
return newNode, nil
}
// NOTE: assumes that node can be modified
// TODO: optimize balance & rotate
func (tree *MutableTree) balance(node *Node) (newSelf *Node, err error) {
if node.persisted {
return nil, fmt.Errorf("unexpected balance() call on persisted node")
}
balance, err := node.calcBalance(tree.ImmutableTree)
if err != nil {
return nil, err
}
if balance > 1 {
leftNode, err := node.getLeftNode(tree.ImmutableTree)
if err != nil {
return nil, err
}
lftBalance, err := leftNode.calcBalance(tree.ImmutableTree)
if err != nil {
return nil, err
}
if lftBalance >= 0 {
// Left Left Case
return tree.rotateRight(node)
}
// Left Right Case
node.leftHash = nil
node.leftNode, err = tree.rotateLeft(leftNode)
if err != nil {
return nil, err
}
return tree.rotateRight(node)
}
if balance < -1 {
rightNode, err := node.getRightNode(tree.ImmutableTree)
if err != nil {
return nil, err
}
rightBalance, err := rightNode.calcBalance(tree.ImmutableTree)
if err != nil {
return nil, err
}
if rightBalance <= 0 {