Skip to content

Commit

Permalink
VersionedTree.SaveVersion() succeeds on idempontent
Browse files Browse the repository at this point in the history
  • Loading branch information
jaekwon committed Jan 22, 2018
1 parent 02885cf commit ae2ea4a
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 4 deletions.
7 changes: 4 additions & 3 deletions nodedb.go
Expand Up @@ -129,9 +129,10 @@ func (ndb *nodeDB) Has(hash []byte) bool {
return ndb.db.Get(key) != nil
}

// SaveBranch saves the given node and all of its descendants. NOTE: This
// function clears leftNode/rigthNode recursively and calls hashWithCount on
// the given node.
// SaveBranch saves the given node and all of its descendants.
// NOTE: This function clears leftNode/rigthNode recursively and
// calls _hash() on the given node.
// TODO refactor, maybe use hashWithCount() but provide a callback.
func (ndb *nodeDB) SaveBranch(node *Node) []byte {
if node.persisted {
return node.hash
Expand Down
11 changes: 10 additions & 1 deletion versioned_tree.go
@@ -1,6 +1,7 @@
package iavl

import (
"bytes"
"fmt"

"github.com/pkg/errors"
Expand Down Expand Up @@ -149,7 +150,15 @@ func (tree *VersionedTree) SaveVersion() ([]byte, int64, error) {
version := tree.version + 1

if _, ok := tree.versions[version]; ok {
return nil, version, errors.Errorf("version %d was already saved", version)
// Same hash means idempotent. Return success.
var existingHash = tree.versions[version].Hash()
var newHash = tree.orphaningTree.Hash()
if bytes.Equal(existingHash, newHash) {
tree.orphaningTree = newOrphaningTree(tree.versions[version].clone())
return existingHash, version, nil
}
return nil, version, errors.Errorf("version %d was already saved to different hash %X (existing hash %X)",
version, newHash, existingHash)
}

// Persist version and stash to .versions.
Expand Down

0 comments on commit ae2ea4a

Please sign in to comment.