@aztec/kv-store 0.0.1-commit.d3ec352c → 0.0.1-commit.d58ff9d0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (192) hide show
  1. package/README.md +10 -1
  2. package/dest/bench/shared_map_bench.d.ts +19 -0
  3. package/dest/bench/shared_map_bench.d.ts.map +1 -0
  4. package/dest/bench/shared_map_bench.js +91 -0
  5. package/dest/deprecated/indexeddb/array.d.ts +22 -0
  6. package/dest/deprecated/indexeddb/array.d.ts.map +1 -0
  7. package/dest/{indexeddb → deprecated/indexeddb}/array.js +21 -7
  8. package/dest/deprecated/indexeddb/index.d.ts +7 -0
  9. package/dest/deprecated/indexeddb/index.d.ts.map +1 -0
  10. package/dest/deprecated/indexeddb/index.js +8 -0
  11. package/dest/deprecated/indexeddb/map.d.ts +38 -0
  12. package/dest/deprecated/indexeddb/map.d.ts.map +1 -0
  13. package/dest/{indexeddb → deprecated/indexeddb}/map.js +23 -13
  14. package/dest/deprecated/indexeddb/multi_map.d.ts +14 -0
  15. package/dest/deprecated/indexeddb/multi_map.d.ts.map +1 -0
  16. package/dest/{indexeddb → deprecated/indexeddb}/multi_map.js +16 -1
  17. package/dest/deprecated/indexeddb/set.d.ts +17 -0
  18. package/dest/deprecated/indexeddb/set.d.ts.map +1 -0
  19. package/dest/deprecated/indexeddb/singleton.d.ts +17 -0
  20. package/dest/deprecated/indexeddb/singleton.d.ts.map +1 -0
  21. package/dest/{indexeddb → deprecated/indexeddb}/singleton.js +3 -1
  22. package/dest/deprecated/indexeddb/store.d.ts +98 -0
  23. package/dest/deprecated/indexeddb/store.d.ts.map +1 -0
  24. package/dest/{indexeddb → deprecated/indexeddb}/store.js +8 -4
  25. package/dest/interfaces/array_test_suite.d.ts +1 -1
  26. package/dest/interfaces/array_test_suite.d.ts.map +1 -1
  27. package/dest/interfaces/array_test_suite.js +33 -34
  28. package/dest/interfaces/index.d.ts +2 -2
  29. package/dest/interfaces/index.d.ts.map +1 -1
  30. package/dest/interfaces/map_test_suite.d.ts +1 -1
  31. package/dest/interfaces/map_test_suite.d.ts.map +1 -1
  32. package/dest/interfaces/map_test_suite.js +74 -29
  33. package/dest/interfaces/multi_map_test_suite.d.ts +1 -1
  34. package/dest/interfaces/multi_map_test_suite.d.ts.map +1 -1
  35. package/dest/interfaces/multi_map_test_suite.js +84 -60
  36. package/dest/interfaces/set_test_suite.d.ts +1 -1
  37. package/dest/interfaces/set_test_suite.d.ts.map +1 -1
  38. package/dest/interfaces/set_test_suite.js +13 -14
  39. package/dest/interfaces/singleton_test_suite.d.ts +1 -1
  40. package/dest/interfaces/singleton_test_suite.d.ts.map +1 -1
  41. package/dest/interfaces/singleton_test_suite.js +6 -7
  42. package/dest/interfaces/utils.d.ts +2 -1
  43. package/dest/interfaces/utils.d.ts.map +1 -1
  44. package/dest/interfaces/utils.js +2 -1
  45. package/dest/lmdb/array.js +4 -2
  46. package/dest/lmdb/index.d.ts +3 -3
  47. package/dest/lmdb/index.d.ts.map +1 -1
  48. package/dest/lmdb/index.js +4 -4
  49. package/dest/lmdb/store.d.ts +3 -3
  50. package/dest/lmdb/store.d.ts.map +1 -1
  51. package/dest/lmdb/store.js +13 -9
  52. package/dest/lmdb-v2/array.d.ts +2 -2
  53. package/dest/lmdb-v2/array.d.ts.map +1 -1
  54. package/dest/lmdb-v2/array.js +4 -3
  55. package/dest/lmdb-v2/factory.d.ts +33 -7
  56. package/dest/lmdb-v2/factory.d.ts.map +1 -1
  57. package/dest/lmdb-v2/factory.js +72 -16
  58. package/dest/lmdb-v2/map.d.ts +2 -2
  59. package/dest/lmdb-v2/map.d.ts.map +1 -1
  60. package/dest/lmdb-v2/map.js +1 -2
  61. package/dest/lmdb-v2/multi_map.d.ts +2 -2
  62. package/dest/lmdb-v2/multi_map.d.ts.map +1 -1
  63. package/dest/lmdb-v2/multi_map.js +1 -2
  64. package/dest/lmdb-v2/read_transaction.js +21 -19
  65. package/dest/lmdb-v2/singleton.d.ts +2 -2
  66. package/dest/lmdb-v2/singleton.d.ts.map +1 -1
  67. package/dest/lmdb-v2/singleton.js +1 -2
  68. package/dest/lmdb-v2/store.d.ts +4 -5
  69. package/dest/lmdb-v2/store.d.ts.map +1 -1
  70. package/dest/lmdb-v2/store.js +6 -28
  71. package/dest/lmdb-v2/tx-helpers.d.ts +6 -0
  72. package/dest/lmdb-v2/tx-helpers.d.ts.map +1 -0
  73. package/dest/lmdb-v2/tx-helpers.js +21 -0
  74. package/dest/lmdb-v2/utils.d.ts +1 -10
  75. package/dest/lmdb-v2/utils.d.ts.map +1 -1
  76. package/dest/lmdb-v2/utils.js +0 -94
  77. package/dest/lmdb-v2/write_transaction.d.ts +1 -1
  78. package/dest/lmdb-v2/write_transaction.d.ts.map +1 -1
  79. package/dest/lmdb-v2/write_transaction.js +9 -5
  80. package/dest/sqlite-opfs/array.d.ts +21 -0
  81. package/dest/sqlite-opfs/array.d.ts.map +1 -0
  82. package/dest/sqlite-opfs/array.js +128 -0
  83. package/dest/sqlite-opfs/errors.d.ts +54 -0
  84. package/dest/sqlite-opfs/errors.d.ts.map +1 -0
  85. package/dest/sqlite-opfs/errors.js +77 -0
  86. package/dest/sqlite-opfs/index.d.ts +14 -0
  87. package/dest/sqlite-opfs/index.d.ts.map +1 -0
  88. package/dest/sqlite-opfs/index.js +16 -0
  89. package/dest/sqlite-opfs/internal/ordered-binary-browser.d.ts +32 -0
  90. package/dest/sqlite-opfs/internal/ordered-binary-browser.d.ts.map +1 -0
  91. package/dest/sqlite-opfs/internal/ordered-binary-browser.js +448 -0
  92. package/dest/sqlite-opfs/manage.d.ts +22 -0
  93. package/dest/sqlite-opfs/manage.d.ts.map +1 -0
  94. package/dest/sqlite-opfs/manage.js +38 -0
  95. package/dest/sqlite-opfs/map.d.ts +35 -0
  96. package/dest/sqlite-opfs/map.d.ts.map +1 -0
  97. package/dest/sqlite-opfs/map.js +163 -0
  98. package/dest/sqlite-opfs/messages.d.ts +66 -0
  99. package/dest/sqlite-opfs/messages.d.ts.map +1 -0
  100. package/dest/sqlite-opfs/messages.js +5 -0
  101. package/dest/sqlite-opfs/multi_map.d.ts +16 -0
  102. package/dest/sqlite-opfs/multi_map.d.ts.map +1 -0
  103. package/dest/sqlite-opfs/multi_map.js +67 -0
  104. package/dest/sqlite-opfs/pool_integrity.d.ts +20 -0
  105. package/dest/sqlite-opfs/pool_integrity.d.ts.map +1 -0
  106. package/dest/sqlite-opfs/pool_integrity.js +282 -0
  107. package/dest/sqlite-opfs/pool_lock.d.ts +8 -0
  108. package/dest/sqlite-opfs/pool_lock.d.ts.map +1 -0
  109. package/dest/sqlite-opfs/pool_lock.js +47 -0
  110. package/dest/sqlite-opfs/set.d.ts +13 -0
  111. package/dest/sqlite-opfs/set.d.ts.map +1 -0
  112. package/dest/sqlite-opfs/set.js +19 -0
  113. package/dest/sqlite-opfs/singleton.d.ts +13 -0
  114. package/dest/sqlite-opfs/singleton.d.ts.map +1 -0
  115. package/dest/sqlite-opfs/singleton.js +48 -0
  116. package/dest/sqlite-opfs/store.d.ts +84 -0
  117. package/dest/sqlite-opfs/store.d.ts.map +1 -0
  118. package/dest/sqlite-opfs/store.js +317 -0
  119. package/dest/sqlite-opfs/worker.d.ts +2 -0
  120. package/dest/sqlite-opfs/worker.d.ts.map +1 -0
  121. package/dest/sqlite-opfs/worker.js +275 -0
  122. package/dest/stores/l2_tips_store.d.ts +18 -10
  123. package/dest/stores/l2_tips_store.d.ts.map +1 -1
  124. package/dest/stores/l2_tips_store.js +43 -55
  125. package/dest/utils.d.ts +9 -6
  126. package/dest/utils.d.ts.map +1 -1
  127. package/dest/utils.js +51 -16
  128. package/package.json +32 -27
  129. package/src/bench/shared_map_bench.ts +111 -0
  130. package/src/{indexeddb → deprecated/indexeddb}/array.ts +6 -6
  131. package/src/deprecated/indexeddb/index.ts +12 -0
  132. package/src/{indexeddb → deprecated/indexeddb}/map.ts +26 -13
  133. package/src/{indexeddb → deprecated/indexeddb}/multi_map.ts +17 -3
  134. package/src/{indexeddb → deprecated/indexeddb}/set.ts +2 -2
  135. package/src/{indexeddb → deprecated/indexeddb}/singleton.ts +3 -3
  136. package/src/{indexeddb → deprecated/indexeddb}/store.ts +23 -15
  137. package/src/interfaces/array_test_suite.ts +33 -35
  138. package/src/interfaces/index.ts +1 -1
  139. package/src/interfaces/map_test_suite.ts +56 -30
  140. package/src/interfaces/multi_map_test_suite.ts +88 -58
  141. package/src/interfaces/set_test_suite.ts +13 -15
  142. package/src/interfaces/singleton_test_suite.ts +6 -8
  143. package/src/interfaces/utils.ts +1 -0
  144. package/src/lmdb/index.ts +10 -5
  145. package/src/lmdb/store.ts +13 -9
  146. package/src/lmdb-v2/array.ts +2 -2
  147. package/src/lmdb-v2/factory.ts +99 -19
  148. package/src/lmdb-v2/map.ts +2 -2
  149. package/src/lmdb-v2/multi_map.ts +2 -2
  150. package/src/lmdb-v2/read_transaction.ts +23 -23
  151. package/src/lmdb-v2/singleton.ts +2 -2
  152. package/src/lmdb-v2/store.ts +9 -33
  153. package/src/lmdb-v2/tx-helpers.ts +29 -0
  154. package/src/lmdb-v2/utils.ts +0 -118
  155. package/src/lmdb-v2/write_transaction.ts +9 -8
  156. package/src/sqlite-opfs/array.ts +124 -0
  157. package/src/sqlite-opfs/errors.ts +94 -0
  158. package/src/sqlite-opfs/index.ts +27 -0
  159. package/src/sqlite-opfs/internal/ordered-binary-browser.js +465 -0
  160. package/src/sqlite-opfs/manage.ts +46 -0
  161. package/src/sqlite-opfs/map.ts +163 -0
  162. package/src/sqlite-opfs/messages.ts +39 -0
  163. package/src/sqlite-opfs/multi_map.ts +74 -0
  164. package/src/sqlite-opfs/pool_integrity.ts +327 -0
  165. package/src/sqlite-opfs/pool_lock.ts +62 -0
  166. package/src/sqlite-opfs/set.ts +29 -0
  167. package/src/sqlite-opfs/singleton.ts +48 -0
  168. package/src/sqlite-opfs/store.ts +330 -0
  169. package/src/sqlite-opfs/worker.ts +259 -0
  170. package/src/stores/l2_tips_store.ts +43 -57
  171. package/src/utils.ts +79 -21
  172. package/dest/config.d.ts +0 -17
  173. package/dest/config.d.ts.map +0 -1
  174. package/dest/config.js +0 -26
  175. package/dest/indexeddb/array.d.ts +0 -22
  176. package/dest/indexeddb/array.d.ts.map +0 -1
  177. package/dest/indexeddb/index.d.ts +0 -7
  178. package/dest/indexeddb/index.d.ts.map +0 -1
  179. package/dest/indexeddb/index.js +0 -19
  180. package/dest/indexeddb/map.d.ts +0 -32
  181. package/dest/indexeddb/map.d.ts.map +0 -1
  182. package/dest/indexeddb/multi_map.d.ts +0 -13
  183. package/dest/indexeddb/multi_map.d.ts.map +0 -1
  184. package/dest/indexeddb/set.d.ts +0 -17
  185. package/dest/indexeddb/set.d.ts.map +0 -1
  186. package/dest/indexeddb/singleton.d.ts +0 -17
  187. package/dest/indexeddb/singleton.d.ts.map +0 -1
  188. package/dest/indexeddb/store.d.ts +0 -96
  189. package/dest/indexeddb/store.d.ts.map +0 -1
  190. package/src/config.ts +0 -36
  191. package/src/indexeddb/index.ts +0 -29
  192. /package/dest/{indexeddb → deprecated/indexeddb}/set.js +0 -0
package/src/lmdb/store.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { randomBytes } from '@aztec/foundation/crypto';
1
+ import { randomBytes } from '@aztec/foundation/crypto/random';
2
2
  import { createLogger } from '@aztec/foundation/log';
3
3
 
4
4
  import { promises as fs, mkdirSync } from 'fs';
@@ -147,21 +147,25 @@ export class AztecLmdbStore implements AztecKVStore, AztecAsyncKVStore {
147
147
  }
148
148
 
149
149
  /**
150
- * Clears all entries in the store & sub DBs.
150
+ * Clears all entries in the store & sub DBs atomically within a single transaction.
151
151
  */
152
152
  async clear() {
153
- await this.#data.clearAsync();
154
- await this.#multiMapData.clearAsync();
155
- await this.#rootDb.clearAsync();
153
+ await this.#rootDb.transaction(async () => {
154
+ await this.#data.clearAsync();
155
+ await this.#multiMapData.clearAsync();
156
+ await this.#rootDb.clearAsync();
157
+ });
156
158
  }
157
159
 
158
160
  /**
159
- * Drops the database & sub DBs.
161
+ * Drops the database & sub DBs atomically within a single transaction.
160
162
  */
161
163
  async drop() {
162
- await this.#data.drop();
163
- await this.#multiMapData.drop();
164
- await this.#rootDb.drop();
164
+ await this.#rootDb.transaction(async () => {
165
+ await this.#data.drop();
166
+ await this.#multiMapData.drop();
167
+ await this.#rootDb.drop();
168
+ });
165
169
  }
166
170
 
167
171
  /**
@@ -4,8 +4,8 @@ import type { AztecAsyncArray } from '../interfaces/array.js';
4
4
  import type { Value } from '../interfaces/common.js';
5
5
  import type { AztecAsyncSingleton } from '../interfaces/singleton.js';
6
6
  import type { ReadTransaction } from './read_transaction.js';
7
- // eslint-disable-next-line import/no-cycle
8
- import { AztecLMDBStoreV2, execInReadTx, execInWriteTx } from './store.js';
7
+ import type { AztecLMDBStoreV2 } from './store.js';
8
+ import { execInReadTx, execInWriteTx } from './tx-helpers.js';
9
9
  import { deserializeKey, serializeKey } from './utils.js';
10
10
 
11
11
  export class LMDBArray<T extends Value> implements AztecAsyncArray<T> {
@@ -1,23 +1,36 @@
1
1
  import { EthAddress } from '@aztec/foundation/eth-address';
2
- import { type Logger, createLogger } from '@aztec/foundation/log';
3
- import { DatabaseVersionManager } from '@aztec/stdlib/database-version';
2
+ import { type LoggerBindings, createLogger } from '@aztec/foundation/log';
3
+ import {
4
+ DatabaseVersionManager,
5
+ type SchemaVersionMismatchPolicy,
6
+ type VersionFileReadFailurePolicy,
7
+ } from '@aztec/stdlib/database-version/manager';
8
+ import type { DataStoreConfig } from '@aztec/stdlib/kv-store';
4
9
 
5
- import { mkdir, mkdtemp, rm } from 'fs/promises';
10
+ import { copyFile, mkdir, mkdtemp, rm } from 'fs/promises';
6
11
  import { tmpdir } from 'os';
7
12
  import { join } from 'path';
8
13
 
9
- import type { DataStoreConfig } from '../config.js';
10
14
  import { AztecLMDBStoreV2 } from './store.js';
11
15
 
12
16
  const MAX_READERS = 16;
13
17
 
18
+ /** Optional versioning hooks for persistent LMDB stores. */
19
+ export type CreateStoreOptions = {
20
+ onUpgrade?: (dataDir: string, currentVersion: number, latestVersion: number) => Promise<void>;
21
+ schemaVersionMismatchPolicy?: SchemaVersionMismatchPolicy;
22
+ versionFileReadFailurePolicy?: VersionFileReadFailurePolicy;
23
+ };
24
+
14
25
  export async function createStore(
15
26
  name: string,
16
27
  schemaVersion: number,
17
28
  config: DataStoreConfig,
18
- log: Logger = createLogger('kv-store:lmdb-v2:' + name),
29
+ bindings?: LoggerBindings,
30
+ options: CreateStoreOptions = {},
19
31
  ): Promise<AztecLMDBStoreV2> {
20
- const { dataDirectory, l1Contracts } = config;
32
+ const log = createLogger('kv-store:lmdb-v2:' + name, bindings);
33
+ const { dataDirectory, rollupAddress: rollupFromConfig } = config;
21
34
 
22
35
  let store: AztecLMDBStoreV2;
23
36
  if (typeof dataDirectory !== 'undefined') {
@@ -25,7 +38,7 @@ export async function createStore(
25
38
  const subDir = join(dataDirectory, name);
26
39
  await mkdir(subDir, { recursive: true });
27
40
 
28
- const rollupAddress = l1Contracts ? l1Contracts.rollupAddress : EthAddress.ZERO;
41
+ const rollupAddress = rollupFromConfig ?? EthAddress.ZERO;
29
42
 
30
43
  // Create a version manager
31
44
  const versionManager = new DatabaseVersionManager({
@@ -33,7 +46,10 @@ export async function createStore(
33
46
  rollupAddress,
34
47
  dataDirectory: subDir,
35
48
  onOpen: dbDirectory =>
36
- AztecLMDBStoreV2.new(dbDirectory, config.dataStoreMapSizeKb, MAX_READERS, () => Promise.resolve(), log),
49
+ AztecLMDBStoreV2.new(dbDirectory, config.dataStoreMapSizeKb, MAX_READERS, () => Promise.resolve(), bindings),
50
+ onUpgrade: options.onUpgrade,
51
+ schemaVersionMismatchPolicy: options.schemaVersionMismatchPolicy,
52
+ versionFileReadFailurePolicy: options.versionFileReadFailurePolicy,
37
53
  });
38
54
 
39
55
  log.info(
@@ -41,25 +57,31 @@ export async function createStore(
41
57
  );
42
58
  [store] = await versionManager.open();
43
59
  } else {
44
- store = await openTmpStore(name, true, config.dataStoreMapSizeKb, MAX_READERS, log);
60
+ store = await openTmpStore(name, true, config.dataStoreMapSizeKb, MAX_READERS, bindings);
45
61
  }
46
62
 
47
63
  return store;
48
64
  }
49
65
 
66
+ /**
67
+ * Open a persistent on-disk store rooted in OS tmpdir. Caller chooses whether to
68
+ * auto-remove the directory on close. Uses standard durable LMDB flags (fsync on
69
+ * every commit) — for full in-memory / NOSYNC semantics use `openEphemeralStore`.
70
+ */
50
71
  export async function openTmpStore(
51
72
  name: string,
52
- ephemeral: boolean = true,
73
+ cleanupTmpDir: boolean = true,
53
74
  dbMapSizeKb = 10 * 1_024 * 1_024, // 10GB
54
75
  maxReaders = MAX_READERS,
55
- log: Logger = createLogger('kv-store:lmdb-v2:' + name),
76
+ bindings?: LoggerBindings,
56
77
  ): Promise<AztecLMDBStoreV2> {
78
+ const log = createLogger('kv-store:lmdb-v2:' + name, bindings);
57
79
  const dataDir = await mkdtemp(join(tmpdir(), name + '-'));
58
80
  log.debug(`Created temporary data store at: ${dataDir} with size: ${dbMapSizeKb} KB (LMDB v2)`);
59
81
 
60
82
  // pass a cleanup callback because process.on('beforeExit', cleanup) does not work under Jest
61
83
  const cleanup = async () => {
62
- if (ephemeral) {
84
+ if (cleanupTmpDir) {
63
85
  try {
64
86
  await rm(dataDir, { recursive: true, force: true, maxRetries: 3 });
65
87
  log.debug(`Deleted temporary data store: ${dataDir}`);
@@ -71,19 +93,76 @@ export async function openTmpStore(
71
93
  }
72
94
  };
73
95
 
74
- // For temporary stores, we don't need to worry about versioning
75
- // as they are ephemeral and get cleaned up after use
76
- return AztecLMDBStoreV2.new(dataDir, dbMapSizeKb, maxReaders, cleanup, log);
96
+ return AztecLMDBStoreV2.new(dataDir, dbMapSizeKb, maxReaders, cleanup, bindings, false);
97
+ }
98
+
99
+ /**
100
+ * Open a fully-ephemeral store: a fresh tmpdir backing file, LMDB opened with
101
+ * MDB_NOSYNC | MDB_NOMETASYNC (no fsync, kernel-only writeback), and the directory
102
+ * unconditionally removed on close. Intended for tests and worker-local scratch
103
+ * stores where durability is explicitly not desired.
104
+ */
105
+ export async function openEphemeralStore(
106
+ name: string,
107
+ dbMapSizeKb = 10 * 1_024 * 1_024, // 10GB
108
+ maxReaders = MAX_READERS,
109
+ bindings?: LoggerBindings,
110
+ ): Promise<AztecLMDBStoreV2> {
111
+ const log = createLogger('kv-store:lmdb-v2:' + name, bindings);
112
+ const dataDir = await mkdtemp(join(tmpdir(), name + '-'));
113
+ log.debug(`Created ephemeral data store at: ${dataDir} with size: ${dbMapSizeKb} KB (LMDB v2)`);
114
+
115
+ const cleanup = async () => {
116
+ try {
117
+ await rm(dataDir, { recursive: true, force: true, maxRetries: 3 });
118
+ log.debug(`Deleted ephemeral data store: ${dataDir}`);
119
+ } catch (err) {
120
+ log.warn(`Failed to delete ephemeral data directory (LMDB v2) ${dataDir}: ${err}`);
121
+ }
122
+ };
123
+
124
+ return AztecLMDBStoreV2.new(dataDir, dbMapSizeKb, maxReaders, cleanup, bindings, true);
77
125
  }
78
126
 
79
127
  export async function openStoreAt(
80
128
  dataDir: string,
81
129
  dbMapSizeKb = 10 * 1_024 * 1_024, // 10GB
82
130
  maxReaders = MAX_READERS,
83
- log: Logger = createLogger('kv-store:lmdb-v2'),
131
+ bindings?: LoggerBindings,
84
132
  ): Promise<AztecLMDBStoreV2> {
133
+ const log = createLogger('kv-store:lmdb-v2', bindings);
85
134
  log.debug(`Opening data store at: ${dataDir} with size: ${dbMapSizeKb} KB (LMDB v2)`);
86
- return await AztecLMDBStoreV2.new(dataDir, dbMapSizeKb, maxReaders, undefined, log);
135
+ return await AztecLMDBStoreV2.new(dataDir, dbMapSizeKb, maxReaders, undefined, bindings);
136
+ }
137
+
138
+ /**
139
+ * Open a fully-ephemeral store seeded from an existing `data.mdb` file. Creates a fresh tmpdir,
140
+ * copies `srcDataMdbPath` into it as `data.mdb`, opens with MDB_NOSYNC | MDB_NOMETASYNC, and
141
+ * removes the tmpdir on close. Intended for worker clones of a main-thread-built store — the
142
+ * source file is never written to.
143
+ */
144
+ export async function cloneEphemeralStoreFrom(
145
+ srcDataMdbPath: string,
146
+ name: string,
147
+ dbMapSizeKb = 10 * 1_024 * 1_024, // 10GB
148
+ maxReaders = MAX_READERS,
149
+ bindings?: LoggerBindings,
150
+ ): Promise<AztecLMDBStoreV2> {
151
+ const log = createLogger('kv-store:lmdb-v2:' + name, bindings);
152
+ const dataDir = await mkdtemp(join(tmpdir(), name + '-'));
153
+ await copyFile(srcDataMdbPath, join(dataDir, 'data.mdb'));
154
+ log.debug(`Cloned ephemeral data store at: ${dataDir} from ${srcDataMdbPath} (LMDB v2)`);
155
+
156
+ const cleanup = async () => {
157
+ try {
158
+ await rm(dataDir, { recursive: true, force: true, maxRetries: 3 });
159
+ log.debug(`Deleted ephemeral data store: ${dataDir}`);
160
+ } catch (err) {
161
+ log.warn(`Failed to delete ephemeral data directory (LMDB v2) ${dataDir}: ${err}`);
162
+ }
163
+ };
164
+
165
+ return AztecLMDBStoreV2.new(dataDir, dbMapSizeKb, maxReaders, cleanup, bindings, true);
87
166
  }
88
167
 
89
168
  export async function openVersionedStoreAt(
@@ -92,14 +171,15 @@ export async function openVersionedStoreAt(
92
171
  rollupAddress: EthAddress,
93
172
  dbMapSizeKb = 10 * 1_024 * 1_024, // 10GB
94
173
  maxReaders = MAX_READERS,
95
- log: Logger = createLogger('kv-store:lmdb-v2'),
174
+ bindings?: LoggerBindings,
96
175
  ): Promise<AztecLMDBStoreV2> {
176
+ const log = createLogger('kv-store:lmdb-v2', bindings);
97
177
  log.debug(`Opening data store at: ${dataDirectory} with size: ${dbMapSizeKb} KB (LMDB v2)`);
98
178
  const [store] = await new DatabaseVersionManager({
99
179
  schemaVersion,
100
180
  rollupAddress,
101
181
  dataDirectory,
102
- onOpen: dataDir => AztecLMDBStoreV2.new(dataDir, dbMapSizeKb, maxReaders, undefined, log),
182
+ onOpen: dataDir => AztecLMDBStoreV2.new(dataDir, dbMapSizeKb, maxReaders, undefined, bindings),
103
183
  }).open();
104
184
  return store;
105
185
  }
@@ -3,8 +3,8 @@ import { Encoder } from 'msgpackr';
3
3
  import type { Key, Range, Value } from '../interfaces/common.js';
4
4
  import type { AztecAsyncMap } from '../interfaces/map.js';
5
5
  import type { ReadTransaction } from './read_transaction.js';
6
- // eslint-disable-next-line import/no-cycle
7
- import { type AztecLMDBStoreV2, execInReadTx, execInWriteTx } from './store.js';
6
+ import type { AztecLMDBStoreV2 } from './store.js';
7
+ import { execInReadTx, execInWriteTx } from './tx-helpers.js';
8
8
  import { deserializeKey, maxKey, minKey, serializeKey } from './utils.js';
9
9
 
10
10
  export class LMDBMap<K extends Key, V extends Value> implements AztecAsyncMap<K, V> {
@@ -4,8 +4,8 @@ import { MAXIMUM_KEY, toBufferKey } from 'ordered-binary';
4
4
  import type { Key, Range, Value } from '../interfaces/common.js';
5
5
  import type { AztecAsyncMultiMap } from '../interfaces/multi_map.js';
6
6
  import type { ReadTransaction } from './read_transaction.js';
7
- // eslint-disable-next-line import/no-cycle
8
- import { type AztecLMDBStoreV2, execInReadTx, execInWriteTx } from './store.js';
7
+ import type { AztecLMDBStoreV2 } from './store.js';
8
+ import { execInReadTx, execInWriteTx } from './tx-helpers.js';
9
9
  import { deserializeKey, maxKey, minKey, serializeKey } from './utils.js';
10
10
 
11
11
  export class LMDBMultiMap<K extends Key, V extends Value> implements AztecAsyncMultiMap<K, V> {
@@ -66,20 +66,20 @@ export class ReadTransaction {
66
66
  ): AsyncIterable<[Uint8Array, T]> {
67
67
  this.assertIsOpen();
68
68
 
69
- const response = await this.channel.sendMessage(LMDBMessageType.START_CURSOR, {
70
- key: startKey,
71
- reverse,
72
- count: typeof limit === 'number' ? Math.min(limit, CURSOR_PAGE_SIZE) : CURSOR_PAGE_SIZE,
73
- onePage: typeof limit === 'number' && limit < CURSOR_PAGE_SIZE,
74
- db,
75
- });
76
-
77
- const cursor = response.cursor;
78
- let entries = response.entries;
79
- let done = typeof cursor !== 'number';
80
- let count = 0;
81
-
69
+ let cursor: number | undefined;
82
70
  try {
71
+ const response = await this.channel.sendMessage(LMDBMessageType.START_CURSOR, {
72
+ key: startKey,
73
+ reverse,
74
+ count: typeof limit === 'number' ? Math.min(limit, CURSOR_PAGE_SIZE) : CURSOR_PAGE_SIZE,
75
+ onePage: typeof limit === 'number' && limit < CURSOR_PAGE_SIZE,
76
+ db,
77
+ });
78
+
79
+ cursor = response.cursor ?? undefined;
80
+ let entries = response.entries;
81
+ let done = typeof cursor !== 'number';
82
+ let count = 0;
83
83
  // emit the first page and any subsequent pages in a while loop
84
84
  // NB: end contition is in the middle of the while loop
85
85
  while (entries.length > 0) {
@@ -125,17 +125,17 @@ export class ReadTransaction {
125
125
  async #countEntries(db: string, startKey: Uint8Array, endKey: Uint8Array, reverse: boolean): Promise<number> {
126
126
  this.assertIsOpen();
127
127
 
128
- const response = await this.channel.sendMessage(LMDBMessageType.START_CURSOR, {
129
- key: startKey,
130
- reverse,
131
- count: 0,
132
- onePage: false,
133
- db,
134
- });
135
-
136
- const cursor = response.cursor;
137
-
128
+ let cursor: number | undefined;
138
129
  try {
130
+ const response = await this.channel.sendMessage(LMDBMessageType.START_CURSOR, {
131
+ key: startKey,
132
+ reverse,
133
+ count: 0,
134
+ onePage: false,
135
+ db,
136
+ });
137
+
138
+ cursor = response.cursor ?? undefined;
139
139
  if (!cursor) {
140
140
  return 0;
141
141
  }
@@ -1,8 +1,8 @@
1
1
  import { Encoder } from 'msgpackr';
2
2
 
3
3
  import type { AztecAsyncSingleton } from '../interfaces/singleton.js';
4
- // eslint-disable-next-line import/no-cycle
5
- import { type AztecLMDBStoreV2, execInReadTx, execInWriteTx } from './store.js';
4
+ import type { AztecLMDBStoreV2 } from './store.js';
5
+ import { execInReadTx, execInWriteTx } from './tx-helpers.js';
6
6
  import { serializeKey } from './utils.js';
7
7
 
8
8
  export class LMDBSingleValue<T> implements AztecAsyncSingleton<T> {
@@ -1,4 +1,4 @@
1
- import { type Logger, createLogger } from '@aztec/foundation/log';
1
+ import { type Logger, type LoggerBindings, createLogger } from '@aztec/foundation/log';
2
2
  import { Semaphore, SerialQueue } from '@aztec/foundation/queue';
3
3
  import { MsgpackChannel, NativeLMDBStore } from '@aztec/native';
4
4
 
@@ -13,9 +13,7 @@ import type { AztecAsyncMultiMap } from '../interfaces/multi_map.js';
13
13
  import type { AztecAsyncSet } from '../interfaces/set.js';
14
14
  import type { AztecAsyncSingleton } from '../interfaces/singleton.js';
15
15
  import type { AztecAsyncKVStore } from '../interfaces/store.js';
16
- // eslint-disable-next-line import/no-cycle
17
16
  import { LMDBArray } from './array.js';
18
- // eslint-disable-next-line import/no-cycle
19
17
  import { LMDBMap } from './map.js';
20
18
  import {
21
19
  Database,
@@ -27,10 +25,11 @@ import {
27
25
  import { LMDBMultiMap } from './multi_map.js';
28
26
  import { ReadTransaction } from './read_transaction.js';
29
27
  import { LMDBSet } from './set.js';
30
- // eslint-disable-next-line import/no-cycle
31
28
  import { LMDBSingleValue } from './singleton.js';
32
29
  import { WriteTransaction } from './write_transaction.js';
33
30
 
31
+ export { execInReadTx, execInWriteTx } from './tx-helpers.js';
32
+
34
33
  export class AztecLMDBStoreV2 implements AztecAsyncKVStore, LMDBMessageChannel {
35
34
  private open = false;
36
35
  private channel: MsgpackChannel<LMDBMessageType, LMDBRequestBody, LMDBResponseBody>;
@@ -44,9 +43,10 @@ export class AztecLMDBStoreV2 implements AztecAsyncKVStore, LMDBMessageChannel {
44
43
  maxReaders: number,
45
44
  private log: Logger,
46
45
  private cleanup?: () => Promise<void>,
46
+ ephemeral: boolean = false,
47
47
  ) {
48
48
  this.log.info(`Starting data store with maxReaders ${maxReaders}`);
49
- this.channel = new MsgpackChannel(new NativeLMDBStore(dataDir, mapSize, maxReaders));
49
+ this.channel = new MsgpackChannel(new NativeLMDBStore(dataDir, mapSize, maxReaders, ephemeral));
50
50
  // leave one reader to always be available for regular, atomic, reads
51
51
  this.availableCursors = new Semaphore(maxReaders - 1);
52
52
  }
@@ -76,9 +76,11 @@ export class AztecLMDBStoreV2 implements AztecAsyncKVStore, LMDBMessageChannel {
76
76
  dbMapSizeKb: number = 10 * 1024 * 1024,
77
77
  maxReaders: number = 16,
78
78
  cleanup?: () => Promise<void>,
79
- log = createLogger('kv-store:lmdb-v2'),
79
+ bindings?: LoggerBindings,
80
+ ephemeral: boolean = false,
80
81
  ) {
81
- const db = new AztecLMDBStoreV2(dataDir, dbMapSizeKb, maxReaders, log, cleanup);
82
+ const log = createLogger('kv-store:lmdb-v2', bindings);
83
+ const db = new AztecLMDBStoreV2(dataDir, dbMapSizeKb, maxReaders, log, cleanup, ephemeral);
82
84
  await db.start();
83
85
  return db;
84
86
  }
@@ -217,29 +219,3 @@ export class AztecLMDBStoreV2 implements AztecAsyncKVStore, LMDBMessageChannel {
217
219
  };
218
220
  }
219
221
  }
220
-
221
- export function execInWriteTx<T>(store: AztecLMDBStoreV2, fn: (tx: WriteTransaction) => Promise<T>): Promise<T> {
222
- const currentWrite = store.getCurrentWriteTx();
223
- if (currentWrite) {
224
- return fn(currentWrite);
225
- } else {
226
- return store.transactionAsync(fn);
227
- }
228
- }
229
-
230
- export async function execInReadTx<T>(
231
- store: AztecLMDBStoreV2,
232
- fn: (tx: ReadTransaction) => T | Promise<T>,
233
- ): Promise<T> {
234
- const currentWrite = store.getCurrentWriteTx();
235
- if (currentWrite) {
236
- return await fn(currentWrite);
237
- } else {
238
- const tx = store.getReadTx();
239
- try {
240
- return await fn(tx);
241
- } finally {
242
- tx.close();
243
- }
244
- }
245
- }
@@ -0,0 +1,29 @@
1
+ import type { ReadTransaction } from './read_transaction.js';
2
+ import type { AztecLMDBStoreV2 } from './store.js';
3
+ import type { WriteTransaction } from './write_transaction.js';
4
+
5
+ export function execInWriteTx<T>(store: AztecLMDBStoreV2, fn: (tx: WriteTransaction) => Promise<T>): Promise<T> {
6
+ const currentWrite = store.getCurrentWriteTx();
7
+ if (currentWrite) {
8
+ return fn(currentWrite);
9
+ } else {
10
+ return store.transactionAsync(fn);
11
+ }
12
+ }
13
+
14
+ export async function execInReadTx<T>(
15
+ store: AztecLMDBStoreV2,
16
+ fn: (tx: ReadTransaction) => T | Promise<T>,
17
+ ): Promise<T> {
18
+ const currentWrite = store.getCurrentWriteTx();
19
+ if (currentWrite) {
20
+ return await fn(currentWrite);
21
+ } else {
22
+ const tx = store.getReadTx();
23
+ try {
24
+ return await fn(tx);
25
+ } finally {
26
+ tx.close();
27
+ }
28
+ }
29
+ }
@@ -2,124 +2,6 @@ import { MAXIMUM_KEY, fromBufferKey, toBufferKey } from 'ordered-binary';
2
2
 
3
3
  import type { Key } from '../interfaces/common.js';
4
4
 
5
- type Cmp<T> = (a: T, b: T) => -1 | 0 | 1;
6
-
7
- export function dedupeSortedArray<T>(arr: T[], cmp: Cmp<T>): void {
8
- for (let i = 0; i < arr.length; i++) {
9
- let j = i + 1;
10
- for (; j < arr.length; j++) {
11
- const res = cmp(arr[i], arr[j]);
12
- if (res === 0) {
13
- continue;
14
- } else if (res < 0) {
15
- break;
16
- } else {
17
- throw new Error('Array not sorted');
18
- }
19
- }
20
-
21
- if (j - i > 1) {
22
- arr.splice(i + 1, j - i - 1);
23
- }
24
- }
25
- }
26
-
27
- export function insertIntoSortedArray<T>(arr: T[], item: T, cmp: (a: T, b: T) => number): void {
28
- let left = 0;
29
- let right = arr.length;
30
-
31
- while (left < right) {
32
- const mid = (left + right) >> 1;
33
- const comparison = cmp(arr[mid], item);
34
-
35
- if (comparison < 0) {
36
- left = mid + 1;
37
- } else {
38
- right = mid;
39
- }
40
- }
41
-
42
- arr.splice(left, 0, item);
43
- }
44
-
45
- export function findIndexInSortedArray<T, N>(values: T[], needle: N, cmp: (a: T, b: N) => number): number {
46
- let start = 0;
47
- let end = values.length - 1;
48
-
49
- while (start <= end) {
50
- const mid = start + (((end - start) / 2) | 0);
51
- const res = cmp(values[mid], needle);
52
- if (res === 0) {
53
- return mid;
54
- } else if (res > 0) {
55
- end = mid - 1;
56
- } else {
57
- start = mid + 1;
58
- }
59
- }
60
-
61
- return -1;
62
- }
63
-
64
- export function findInSortedArray<T, N>(values: T[], needle: N, cmp: (a: T, b: N) => number): T | undefined {
65
- const idx = findIndexInSortedArray(values, needle, cmp);
66
- return idx > -1 ? values[idx] : undefined;
67
- }
68
-
69
- export function removeAnyOf<T, N>(arr: T[], vals: N[], cmp: (a: T, b: N) => -1 | 0 | 1): void {
70
- let writeIdx = 0;
71
- let readIdx = 0;
72
- let valIdx = 0;
73
-
74
- while (readIdx < arr.length && valIdx < vals.length) {
75
- const comparison = cmp(arr[readIdx], vals[valIdx]);
76
-
77
- if (comparison < 0) {
78
- arr[writeIdx++] = arr[readIdx++];
79
- } else if (comparison > 0) {
80
- valIdx++;
81
- } else {
82
- readIdx++;
83
- }
84
- }
85
-
86
- while (readIdx < arr.length) {
87
- arr[writeIdx++] = arr[readIdx++];
88
- }
89
-
90
- arr.length = writeIdx;
91
- }
92
-
93
- export function removeFromSortedArray<T, N>(arr: T[], val: N, cmp: (a: T, b: N) => -1 | 0 | 1) {
94
- const idx = findIndexInSortedArray(arr, val, cmp);
95
- if (idx > -1) {
96
- arr.splice(idx, 1);
97
- }
98
- }
99
-
100
- export function merge<T>(arr: T[], toInsert: T[], cmp: (a: T, b: T) => -1 | 0 | 1): void {
101
- const result = new Array<T>(arr.length + toInsert.length);
102
- let i = 0,
103
- j = 0,
104
- k = 0;
105
-
106
- while (i < arr.length && j < toInsert.length) {
107
- result[k++] = cmp(arr[i], toInsert[j]) <= 0 ? arr[i++] : toInsert[j++];
108
- }
109
-
110
- while (i < arr.length) {
111
- result[k++] = arr[i++];
112
- }
113
- while (j < toInsert.length) {
114
- result[k++] = toInsert[j++];
115
- }
116
-
117
- for (i = 0; i < result.length; i++) {
118
- arr[i] = result[i];
119
- }
120
- arr.length = result.length;
121
- }
122
-
123
5
  export function keyCmp(a: [Uint8Array, Uint8Array[] | null], b: [Uint8Array, Uint8Array[] | null]): -1 | 0 | 1 {
124
6
  return Buffer.compare(a[0], b[0]);
125
7
  }
@@ -1,16 +1,16 @@
1
- import { type Batch, Database, LMDBMessageType } from './message.js';
2
- import { ReadTransaction } from './read_transaction.js';
3
1
  import {
4
2
  dedupeSortedArray,
5
3
  findInSortedArray,
6
4
  findIndexInSortedArray,
7
5
  insertIntoSortedArray,
8
- keyCmp,
9
6
  merge,
10
7
  removeAnyOf,
11
8
  removeFromSortedArray,
12
- singleKeyCmp,
13
- } from './utils.js';
9
+ } from '@aztec/foundation/array';
10
+
11
+ import { type Batch, Database, LMDBMessageType } from './message.js';
12
+ import { ReadTransaction } from './read_transaction.js';
13
+ import { keyCmp, singleKeyCmp } from './utils.js';
14
14
 
15
15
  export class WriteTransaction extends ReadTransaction {
16
16
  // exposed for tests
@@ -44,7 +44,7 @@ export class WriteTransaction extends ReadTransaction {
44
44
  remove(key: Uint8Array): Promise<void> {
45
45
  const removeEntryIndex = findIndexInSortedArray(this.dataBatch.removeEntries, key, singleKeyCmp);
46
46
  if (removeEntryIndex === -1) {
47
- this.dataBatch.removeEntries.push([key, null]);
47
+ insertIntoSortedArray(this.dataBatch.removeEntries, [key, null], keyCmp);
48
48
  }
49
49
 
50
50
  const addEntryIndex = findIndexInSortedArray(this.dataBatch.addEntries, key, singleKeyCmp);
@@ -218,8 +218,9 @@ export class WriteTransaction extends ReadTransaction {
218
218
  ): AsyncIterable<[Uint8Array, T]> {
219
219
  this.assertIsOpen();
220
220
 
221
- // make a copy of this in case we're running in reverse
221
+ // Snapshot both add and remove entries at the start of iteration to ensure consistency
222
222
  const uncommittedEntries = [...batch.addEntries];
223
+ const removeEntries = [...batch.removeEntries];
223
224
  // used to check we're in the right order when comparing between a key and uncommittedEntries
224
225
  let cmpDirection = -1;
225
226
  if (reverse) {
@@ -262,7 +263,7 @@ export class WriteTransaction extends ReadTransaction {
262
263
  break;
263
264
  }
264
265
 
265
- const toRemove = findInSortedArray(batch.removeEntries, key, singleKeyCmp);
266
+ const toRemove = findInSortedArray(removeEntries, key, singleKeyCmp);
266
267
 
267
268
  // at this point we've either exhausted all uncommitted entries,
268
269
  // we reached a key strictly greater/smaller than `key`