UNPKG

2.33 kBJavaScriptView Raw
1"use strict";
2Object.defineProperty(exports, "__esModule", { value: true });
3exports.CheckpointTrie = void 0;
4const baseTrie_1 = require("./baseTrie");
5const checkpointDb_1 = require("./checkpointDb");
6/**
7 * Adds checkpointing to the {@link BaseTrie}
8 */
9class CheckpointTrie extends baseTrie_1.Trie {
10 constructor(...args) {
11 super(...args);
12 this.db = new checkpointDb_1.CheckpointDB(...args);
13 }
14 /**
15 * Is the trie during a checkpoint phase?
16 */
17 get isCheckpoint() {
18 return this.db.isCheckpoint;
19 }
20 /**
21 * Creates a checkpoint that can later be reverted to or committed.
22 * After this is called, all changes can be reverted until `commit` is called.
23 */
24 checkpoint() {
25 this.db.checkpoint(this.root);
26 }
27 /**
28 * Commits a checkpoint to disk, if current checkpoint is not nested.
29 * If nested, only sets the parent checkpoint as current checkpoint.
30 * @throws If not during a checkpoint phase
31 */
32 async commit() {
33 if (!this.isCheckpoint) {
34 throw new Error('trying to commit when not checkpointed');
35 }
36 await this.lock.wait();
37 await this.db.commit();
38 this.lock.signal();
39 }
40 /**
41 * Reverts the trie to the state it was at when `checkpoint` was first called.
42 * If during a nested checkpoint, sets root to most recent checkpoint, and sets
43 * parent checkpoint as current.
44 */
45 async revert() {
46 if (!this.isCheckpoint) {
47 throw new Error('trying to revert when not checkpointed');
48 }
49 await this.lock.wait();
50 this.root = await this.db.revert();
51 this.lock.signal();
52 }
53 /**
54 * Returns a copy of the underlying trie with the interface of CheckpointTrie.
55 * @param includeCheckpoints - If true and during a checkpoint, the copy will contain the checkpointing metadata and will use the same scratch as underlying db.
56 */
57 copy(includeCheckpoints = true) {
58 const db = this.db.copy();
59 const trie = new CheckpointTrie(db._leveldb, this.root);
60 if (includeCheckpoints && this.isCheckpoint) {
61 trie.db.checkpoints = [...this.db.checkpoints];
62 }
63 return trie;
64 }
65}
66exports.CheckpointTrie = CheckpointTrie;
67//# sourceMappingURL=checkpointTrie.js.map
\No newline at end of file