@aztec/kv-store 0.0.0-test.1 → 0.0.1-commit.017a351

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 (221) hide show
  1. package/README.md +8 -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/indexeddb/array.d.ts +3 -2
  6. package/dest/indexeddb/array.d.ts.map +1 -1
  7. package/dest/indexeddb/array.js +24 -7
  8. package/dest/indexeddb/index.d.ts +3 -3
  9. package/dest/indexeddb/index.d.ts.map +1 -1
  10. package/dest/indexeddb/index.js +4 -7
  11. package/dest/indexeddb/map.d.ts +18 -6
  12. package/dest/indexeddb/map.d.ts.map +1 -1
  13. package/dest/indexeddb/map.js +51 -63
  14. package/dest/indexeddb/multi_map.d.ts +14 -0
  15. package/dest/indexeddb/multi_map.d.ts.map +1 -0
  16. package/dest/indexeddb/multi_map.js +107 -0
  17. package/dest/indexeddb/set.d.ts +1 -1
  18. package/dest/indexeddb/set.d.ts.map +1 -1
  19. package/dest/indexeddb/singleton.d.ts +3 -2
  20. package/dest/indexeddb/singleton.d.ts.map +1 -1
  21. package/dest/indexeddb/singleton.js +6 -2
  22. package/dest/indexeddb/store.d.ts +15 -16
  23. package/dest/indexeddb/store.d.ts.map +1 -1
  24. package/dest/indexeddb/store.js +51 -46
  25. package/dest/interfaces/array.d.ts +5 -4
  26. package/dest/interfaces/array.d.ts.map +1 -1
  27. package/dest/interfaces/array.js +1 -3
  28. package/dest/interfaces/array_test_suite.d.ts +1 -1
  29. package/dest/interfaces/array_test_suite.d.ts.map +1 -1
  30. package/dest/interfaces/array_test_suite.js +33 -34
  31. package/dest/interfaces/common.d.ts +11 -9
  32. package/dest/interfaces/common.d.ts.map +1 -1
  33. package/dest/interfaces/common.js +8 -3
  34. package/dest/interfaces/counter.d.ts +1 -1
  35. package/dest/interfaces/index.d.ts +4 -2
  36. package/dest/interfaces/index.d.ts.map +1 -1
  37. package/dest/interfaces/index.js +2 -0
  38. package/dest/interfaces/map.d.ts +21 -49
  39. package/dest/interfaces/map.d.ts.map +1 -1
  40. package/dest/interfaces/map.js +1 -1
  41. package/dest/interfaces/map_test_suite.d.ts +1 -1
  42. package/dest/interfaces/map_test_suite.d.ts.map +1 -1
  43. package/dest/interfaces/map_test_suite.js +193 -83
  44. package/dest/interfaces/multi_map.d.ts +41 -0
  45. package/dest/interfaces/multi_map.d.ts.map +1 -0
  46. package/dest/interfaces/multi_map.js +3 -0
  47. package/dest/interfaces/multi_map_test_suite.d.ts +3 -0
  48. package/dest/interfaces/multi_map_test_suite.d.ts.map +1 -0
  49. package/dest/interfaces/multi_map_test_suite.js +363 -0
  50. package/dest/interfaces/set.d.ts +1 -1
  51. package/dest/interfaces/set_test_suite.d.ts +1 -1
  52. package/dest/interfaces/set_test_suite.d.ts.map +1 -1
  53. package/dest/interfaces/set_test_suite.js +13 -14
  54. package/dest/interfaces/singleton.d.ts +1 -1
  55. package/dest/interfaces/singleton_test_suite.d.ts +1 -1
  56. package/dest/interfaces/singleton_test_suite.d.ts.map +1 -1
  57. package/dest/interfaces/singleton_test_suite.js +6 -7
  58. package/dest/interfaces/store.d.ts +18 -43
  59. package/dest/interfaces/store.d.ts.map +1 -1
  60. package/dest/interfaces/utils.d.ts +3 -1
  61. package/dest/interfaces/utils.d.ts.map +1 -1
  62. package/dest/interfaces/utils.js +3 -1
  63. package/dest/lmdb/array.d.ts +3 -2
  64. package/dest/lmdb/array.d.ts.map +1 -1
  65. package/dest/lmdb/array.js +4 -2
  66. package/dest/lmdb/counter.d.ts +1 -1
  67. package/dest/lmdb/counter.d.ts.map +1 -1
  68. package/dest/lmdb/index.d.ts +3 -3
  69. package/dest/lmdb/index.d.ts.map +1 -1
  70. package/dest/lmdb/index.js +6 -6
  71. package/dest/lmdb/map.d.ts +11 -23
  72. package/dest/lmdb/map.d.ts.map +1 -1
  73. package/dest/lmdb/map.js +15 -81
  74. package/dest/lmdb/multi_map.d.ts +13 -0
  75. package/dest/lmdb/multi_map.d.ts.map +1 -0
  76. package/dest/lmdb/multi_map.js +44 -0
  77. package/dest/lmdb/set.d.ts +1 -1
  78. package/dest/lmdb/set.d.ts.map +1 -1
  79. package/dest/lmdb/singleton.d.ts +1 -1
  80. package/dest/lmdb/singleton.d.ts.map +1 -1
  81. package/dest/lmdb/store.d.ts +11 -27
  82. package/dest/lmdb/store.d.ts.map +1 -1
  83. package/dest/lmdb/store.js +24 -40
  84. package/dest/lmdb-v2/array.d.ts +4 -3
  85. package/dest/lmdb-v2/array.d.ts.map +1 -1
  86. package/dest/lmdb-v2/array.js +4 -2
  87. package/dest/lmdb-v2/factory.d.ts +32 -10
  88. package/dest/lmdb-v2/factory.d.ts.map +1 -1
  89. package/dest/lmdb-v2/factory.js +83 -18
  90. package/dest/lmdb-v2/index.d.ts +1 -1
  91. package/dest/lmdb-v2/map.d.ts +12 -45
  92. package/dest/lmdb-v2/map.d.ts.map +1 -1
  93. package/dest/lmdb-v2/map.js +17 -104
  94. package/dest/lmdb-v2/message.d.ts +24 -5
  95. package/dest/lmdb-v2/message.d.ts.map +1 -1
  96. package/dest/lmdb-v2/message.js +6 -4
  97. package/dest/lmdb-v2/multi_map.d.ts +52 -0
  98. package/dest/lmdb-v2/multi_map.d.ts.map +1 -0
  99. package/dest/lmdb-v2/multi_map.js +123 -0
  100. package/dest/lmdb-v2/read_transaction.d.ts +3 -1
  101. package/dest/lmdb-v2/read_transaction.d.ts.map +1 -1
  102. package/dest/lmdb-v2/read_transaction.js +47 -11
  103. package/dest/lmdb-v2/set.d.ts +15 -0
  104. package/dest/lmdb-v2/set.d.ts.map +1 -0
  105. package/dest/lmdb-v2/set.js +23 -0
  106. package/dest/lmdb-v2/singleton.d.ts +2 -2
  107. package/dest/lmdb-v2/singleton.d.ts.map +1 -1
  108. package/dest/lmdb-v2/singleton.js +1 -1
  109. package/dest/lmdb-v2/store.d.ts +13 -13
  110. package/dest/lmdb-v2/store.d.ts.map +1 -1
  111. package/dest/lmdb-v2/store.js +22 -32
  112. package/dest/lmdb-v2/tx-helpers.d.ts +6 -0
  113. package/dest/lmdb-v2/tx-helpers.d.ts.map +1 -0
  114. package/dest/lmdb-v2/tx-helpers.js +21 -0
  115. package/dest/lmdb-v2/utils.d.ts +3 -14
  116. package/dest/lmdb-v2/utils.d.ts.map +1 -1
  117. package/dest/lmdb-v2/utils.js +0 -94
  118. package/dest/lmdb-v2/write_transaction.d.ts +3 -5
  119. package/dest/lmdb-v2/write_transaction.d.ts.map +1 -1
  120. package/dest/lmdb-v2/write_transaction.js +9 -5
  121. package/dest/sqlite-opfs/array.d.ts +21 -0
  122. package/dest/sqlite-opfs/array.d.ts.map +1 -0
  123. package/dest/sqlite-opfs/array.js +128 -0
  124. package/dest/sqlite-opfs/errors.d.ts +27 -0
  125. package/dest/sqlite-opfs/errors.d.ts.map +1 -0
  126. package/dest/sqlite-opfs/errors.js +34 -0
  127. package/dest/sqlite-opfs/index.d.ts +16 -0
  128. package/dest/sqlite-opfs/index.d.ts.map +1 -0
  129. package/dest/sqlite-opfs/index.js +22 -0
  130. package/dest/sqlite-opfs/internal/ordered-binary-browser.d.ts +32 -0
  131. package/dest/sqlite-opfs/internal/ordered-binary-browser.d.ts.map +1 -0
  132. package/dest/sqlite-opfs/internal/ordered-binary-browser.js +448 -0
  133. package/dest/sqlite-opfs/map.d.ts +35 -0
  134. package/dest/sqlite-opfs/map.d.ts.map +1 -0
  135. package/dest/sqlite-opfs/map.js +163 -0
  136. package/dest/sqlite-opfs/messages.d.ts +66 -0
  137. package/dest/sqlite-opfs/messages.d.ts.map +1 -0
  138. package/dest/sqlite-opfs/messages.js +5 -0
  139. package/dest/sqlite-opfs/multi_map.d.ts +16 -0
  140. package/dest/sqlite-opfs/multi_map.d.ts.map +1 -0
  141. package/dest/sqlite-opfs/multi_map.js +67 -0
  142. package/dest/sqlite-opfs/set.d.ts +13 -0
  143. package/dest/sqlite-opfs/set.d.ts.map +1 -0
  144. package/dest/sqlite-opfs/set.js +19 -0
  145. package/dest/sqlite-opfs/singleton.d.ts +13 -0
  146. package/dest/sqlite-opfs/singleton.d.ts.map +1 -0
  147. package/dest/sqlite-opfs/singleton.js +48 -0
  148. package/dest/sqlite-opfs/store.d.ts +79 -0
  149. package/dest/sqlite-opfs/store.d.ts.map +1 -0
  150. package/dest/sqlite-opfs/store.js +281 -0
  151. package/dest/sqlite-opfs/worker.d.ts +2 -0
  152. package/dest/sqlite-opfs/worker.d.ts.map +1 -0
  153. package/dest/sqlite-opfs/worker.js +249 -0
  154. package/dest/stores/index.d.ts +2 -1
  155. package/dest/stores/index.d.ts.map +1 -1
  156. package/dest/stores/index.js +1 -0
  157. package/dest/stores/l2_tips_store.d.ts +25 -9
  158. package/dest/stores/l2_tips_store.d.ts.map +1 -1
  159. package/dest/stores/l2_tips_store.js +64 -46
  160. package/dest/utils.d.ts +9 -6
  161. package/dest/utils.d.ts.map +1 -1
  162. package/dest/utils.js +51 -16
  163. package/package.json +44 -33
  164. package/src/bench/shared_map_bench.ts +111 -0
  165. package/src/indexeddb/array.ts +9 -5
  166. package/src/indexeddb/index.ts +11 -9
  167. package/src/indexeddb/map.ts +51 -56
  168. package/src/indexeddb/multi_map.ts +105 -0
  169. package/src/indexeddb/singleton.ts +5 -2
  170. package/src/indexeddb/store.ts +77 -60
  171. package/src/interfaces/array.ts +5 -3
  172. package/src/interfaces/array_test_suite.ts +33 -35
  173. package/src/interfaces/common.ts +20 -9
  174. package/src/interfaces/index.ts +3 -1
  175. package/src/interfaces/map.ts +19 -53
  176. package/src/interfaces/map_test_suite.ts +113 -58
  177. package/src/interfaces/multi_map.ts +45 -0
  178. package/src/interfaces/multi_map_test_suite.ts +372 -0
  179. package/src/interfaces/set_test_suite.ts +13 -15
  180. package/src/interfaces/singleton_test_suite.ts +6 -8
  181. package/src/interfaces/store.ts +18 -53
  182. package/src/interfaces/utils.ts +2 -0
  183. package/src/lmdb/array.ts +2 -1
  184. package/src/lmdb/index.ts +13 -8
  185. package/src/lmdb/map.ts +23 -94
  186. package/src/lmdb/multi_map.ts +51 -0
  187. package/src/lmdb/store.ts +36 -56
  188. package/src/lmdb-v2/array.ts +8 -3
  189. package/src/lmdb-v2/factory.ts +107 -26
  190. package/src/lmdb-v2/map.ts +30 -127
  191. package/src/lmdb-v2/message.ts +23 -0
  192. package/src/lmdb-v2/multi_map.ts +150 -0
  193. package/src/lmdb-v2/read_transaction.ts +53 -13
  194. package/src/lmdb-v2/set.ts +33 -0
  195. package/src/lmdb-v2/singleton.ts +6 -2
  196. package/src/lmdb-v2/store.ts +28 -44
  197. package/src/lmdb-v2/tx-helpers.ts +29 -0
  198. package/src/lmdb-v2/utils.ts +0 -118
  199. package/src/lmdb-v2/write_transaction.ts +11 -10
  200. package/src/sqlite-opfs/array.ts +124 -0
  201. package/src/sqlite-opfs/errors.ts +44 -0
  202. package/src/sqlite-opfs/index.ts +39 -0
  203. package/src/sqlite-opfs/internal/ordered-binary-browser.js +465 -0
  204. package/src/sqlite-opfs/map.ts +163 -0
  205. package/src/sqlite-opfs/messages.ts +39 -0
  206. package/src/sqlite-opfs/multi_map.ts +74 -0
  207. package/src/sqlite-opfs/set.ts +29 -0
  208. package/src/sqlite-opfs/singleton.ts +48 -0
  209. package/src/sqlite-opfs/store.ts +296 -0
  210. package/src/sqlite-opfs/worker.ts +231 -0
  211. package/src/stores/index.ts +2 -0
  212. package/src/stores/l2_tips_store.ts +68 -49
  213. package/src/utils.ts +79 -21
  214. package/dest/config.d.ts +0 -17
  215. package/dest/config.d.ts.map +0 -1
  216. package/dest/config.js +0 -24
  217. package/dest/interfaces/store_test_suite.d.ts +0 -3
  218. package/dest/interfaces/store_test_suite.d.ts.map +0 -1
  219. package/dest/interfaces/store_test_suite.js +0 -37
  220. package/src/config.ts +0 -34
  221. package/src/interfaces/store_test_suite.ts +0 -56
@@ -1,19 +1,20 @@
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
 
5
5
  import { AsyncLocalStorage } from 'async_hooks';
6
- import { rm } from 'fs/promises';
6
+ import { mkdir, rm } from 'fs/promises';
7
7
 
8
8
  import type { AztecAsyncArray } from '../interfaces/array.js';
9
- import type { Key, StoreSize } from '../interfaces/common.js';
9
+ import type { Key, StoreSize, Value } from '../interfaces/common.js';
10
10
  import type { AztecAsyncCounter } from '../interfaces/counter.js';
11
- import type { AztecAsyncMap, AztecAsyncMultiMap } from '../interfaces/map.js';
11
+ import type { AztecAsyncMap } from '../interfaces/map.js';
12
+ import type { AztecAsyncMultiMap } from '../interfaces/multi_map.js';
12
13
  import type { AztecAsyncSet } from '../interfaces/set.js';
13
14
  import type { AztecAsyncSingleton } from '../interfaces/singleton.js';
14
15
  import type { AztecAsyncKVStore } from '../interfaces/store.js';
15
16
  import { LMDBArray } from './array.js';
16
- import { LMDBMap, LMDBMultiMap } from './map.js';
17
+ import { LMDBMap } from './map.js';
17
18
  import {
18
19
  Database,
19
20
  type LMDBMessageChannel,
@@ -21,10 +22,14 @@ import {
21
22
  type LMDBRequestBody,
22
23
  type LMDBResponseBody,
23
24
  } from './message.js';
25
+ import { LMDBMultiMap } from './multi_map.js';
24
26
  import { ReadTransaction } from './read_transaction.js';
27
+ import { LMDBSet } from './set.js';
25
28
  import { LMDBSingleValue } from './singleton.js';
26
29
  import { WriteTransaction } from './write_transaction.js';
27
30
 
31
+ export { execInReadTx, execInWriteTx } from './tx-helpers.js';
32
+
28
33
  export class AztecLMDBStoreV2 implements AztecAsyncKVStore, LMDBMessageChannel {
29
34
  private open = false;
30
35
  private channel: MsgpackChannel<LMDBMessageType, LMDBRequestBody, LMDBResponseBody>;
@@ -38,9 +43,10 @@ export class AztecLMDBStoreV2 implements AztecAsyncKVStore, LMDBMessageChannel {
38
43
  maxReaders: number,
39
44
  private log: Logger,
40
45
  private cleanup?: () => Promise<void>,
46
+ ephemeral: boolean = false,
41
47
  ) {
42
48
  this.log.info(`Starting data store with maxReaders ${maxReaders}`);
43
- this.channel = new MsgpackChannel(new NativeLMDBStore(dataDir, mapSize, maxReaders));
49
+ this.channel = new MsgpackChannel(new NativeLMDBStore(dataDir, mapSize, maxReaders, ephemeral));
44
50
  // leave one reader to always be available for regular, atomic, reads
45
51
  this.availableCursors = new Semaphore(maxReaders - 1);
46
52
  }
@@ -70,13 +76,20 @@ export class AztecLMDBStoreV2 implements AztecAsyncKVStore, LMDBMessageChannel {
70
76
  dbMapSizeKb: number = 10 * 1024 * 1024,
71
77
  maxReaders: number = 16,
72
78
  cleanup?: () => Promise<void>,
73
- log = createLogger('kv-store:lmdb-v2'),
79
+ bindings?: LoggerBindings,
80
+ ephemeral: boolean = false,
74
81
  ) {
75
- 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);
76
84
  await db.start();
77
85
  return db;
78
86
  }
79
87
 
88
+ public async backupTo(dstPath: string, compact = true) {
89
+ await mkdir(dstPath, { recursive: true });
90
+ await this.channel.sendMessage(LMDBMessageType.COPY_STORE, { dstPath, compact });
91
+ }
92
+
80
93
  public getReadTx(): ReadTransaction {
81
94
  if (!this.open) {
82
95
  throw new Error('Store is closed');
@@ -92,24 +105,24 @@ export class AztecLMDBStoreV2 implements AztecAsyncKVStore, LMDBMessageChannel {
92
105
  return currentWrite;
93
106
  }
94
107
 
95
- openMap<K extends Key, V>(name: string): AztecAsyncMap<K, V> {
108
+ openMap<K extends Key, V extends Value>(name: string): AztecAsyncMap<K, V> {
96
109
  return new LMDBMap(this, name);
97
110
  }
98
111
 
99
- openMultiMap<K extends Key, V>(name: string): AztecAsyncMultiMap<K, V> {
112
+ openMultiMap<K extends Key, V extends Value>(name: string): AztecAsyncMultiMap<K, V> {
100
113
  return new LMDBMultiMap(this, name);
101
114
  }
102
115
 
103
- openSingleton<T>(name: string): AztecAsyncSingleton<T> {
116
+ openSingleton<T extends Value>(name: string): AztecAsyncSingleton<T> {
104
117
  return new LMDBSingleValue(this, name);
105
118
  }
106
119
 
107
- openArray<T>(name: string): AztecAsyncArray<T> {
120
+ openArray<T extends Value>(name: string): AztecAsyncArray<T> {
108
121
  return new LMDBArray(this, name);
109
122
  }
110
123
 
111
- openSet<K extends Key>(_name: string): AztecAsyncSet<K> {
112
- throw new Error('Not implemented');
124
+ openSet<K extends Key>(name: string): AztecAsyncSet<K> {
125
+ return new LMDBSet(this, name);
113
126
  }
114
127
 
115
128
  openCounter<K extends Key>(_name: string): AztecAsyncCounter<K> {
@@ -150,10 +163,6 @@ export class AztecLMDBStoreV2 implements AztecAsyncKVStore, LMDBMessageChannel {
150
163
  return Promise.resolve();
151
164
  }
152
165
 
153
- fork(): Promise<AztecAsyncKVStore> {
154
- throw new Error('Not implemented');
155
- }
156
-
157
166
  async delete(): Promise<void> {
158
167
  await this.close();
159
168
  await rm(this.dataDir, { recursive: true, force: true, maxRetries: 3 });
@@ -204,34 +213,9 @@ export class AztecLMDBStoreV2 implements AztecAsyncKVStore, LMDBMessageChannel {
204
213
  const resp = await this.sendMessage(LMDBMessageType.STATS, undefined);
205
214
  return {
206
215
  mappingSize: Number(resp.dbMapSizeBytes),
216
+ physicalFileSize: Number(resp.dbPhysicalFileSizeBytes),
207
217
  actualSize: resp.stats.reduce((s, db) => Number(db.totalUsedSize) + s, 0),
208
218
  numItems: resp.stats.reduce((s, db) => Number(db.numDataItems) + s, 0),
209
219
  };
210
220
  }
211
221
  }
212
-
213
- export function execInWriteTx<T>(store: AztecLMDBStoreV2, fn: (tx: WriteTransaction) => Promise<T>): Promise<T> {
214
- const currentWrite = store.getCurrentWriteTx();
215
- if (currentWrite) {
216
- return fn(currentWrite);
217
- } else {
218
- return store.transactionAsync(fn);
219
- }
220
- }
221
-
222
- export async function execInReadTx<T>(
223
- store: AztecLMDBStoreV2,
224
- fn: (tx: ReadTransaction) => T | Promise<T>,
225
- ): Promise<T> {
226
- const currentWrite = store.getCurrentWriteTx();
227
- if (currentWrite) {
228
- return await fn(currentWrite);
229
- } else {
230
- const tx = store.getReadTx();
231
- try {
232
- return await fn(tx);
233
- } finally {
234
- tx.close();
235
- }
236
- }
237
- }
@@ -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);
@@ -163,7 +163,7 @@ export class WriteTransaction extends ReadTransaction {
163
163
 
164
164
  public override async *iterate(
165
165
  startKey: Uint8Array,
166
- endKey?: Uint8Array | undefined,
166
+ endKey?: Uint8Array,
167
167
  reverse?: boolean,
168
168
  limit?: number,
169
169
  ): AsyncIterable<[Uint8Array, Uint8Array]> {
@@ -181,7 +181,7 @@ export class WriteTransaction extends ReadTransaction {
181
181
 
182
182
  public override async *iterateIndex(
183
183
  startKey: Uint8Array,
184
- endKey?: Uint8Array | undefined,
184
+ endKey?: Uint8Array,
185
185
  reverse?: boolean,
186
186
  limit?: number,
187
187
  ): AsyncIterable<[Uint8Array, Uint8Array[]]> {
@@ -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`
@@ -0,0 +1,124 @@
1
+ import { Encoder } from '#msgpackr';
2
+ import { toBufferKey } from '#ordered-binary';
3
+ import { hash } from 'ohash';
4
+
5
+ import type { AztecAsyncArray } from '../interfaces/array.js';
6
+ import type { Value } from '../interfaces/common.js';
7
+ import type { AztecSQLiteOPFSStore } from './store.js';
8
+
9
+ /**
10
+ * Persistent array backed by SQLite. Entries share a common `key` (the array name)
11
+ * and are ordered by `key_count`, which doubles as the 1-indexed slot number.
12
+ */
13
+ export class SQLiteOPFSAztecArray<T extends Value> implements AztecAsyncArray<T> {
14
+ readonly #name: string;
15
+ readonly #container: string;
16
+ readonly #encoder = new Encoder();
17
+
18
+ constructor(
19
+ private readonly store: AztecSQLiteOPFSStore,
20
+ name: string,
21
+ ) {
22
+ this.#name = name;
23
+ this.#container = `array:${name}`;
24
+ }
25
+
26
+ async lengthAsync(): Promise<number> {
27
+ const rows = await this.store.allAsync('SELECT COUNT(*) FROM data WHERE container = ? AND key = ?', [
28
+ this.#container,
29
+ this.#encodedKey(),
30
+ ]);
31
+ return Number(rows[0]?.[0] ?? 0);
32
+ }
33
+
34
+ async push(...vals: T[]): Promise<number> {
35
+ if (vals.length === 0) {
36
+ return this.lengthAsync();
37
+ }
38
+ return await this.store.transactionAsync(async () => {
39
+ let length = await this.lengthAsync();
40
+ for (const val of vals) {
41
+ await this.store.runAsync(
42
+ `INSERT INTO data (slot, container, key, key_count, hash, value)
43
+ VALUES (?, ?, ?, ?, ?, ?)`,
44
+ [this.#slot(length), this.#container, this.#encodedKey(), length + 1, hash(val), this.#encoder.pack(val)],
45
+ );
46
+ length += 1;
47
+ }
48
+ return length;
49
+ });
50
+ }
51
+
52
+ async pop(): Promise<T | undefined> {
53
+ return await this.store.transactionAsync(async () => {
54
+ const length = await this.lengthAsync();
55
+ if (length === 0) {
56
+ return undefined;
57
+ }
58
+ const slot = this.#slot(length - 1);
59
+ const rows = await this.store.allAsync('SELECT value FROM data WHERE slot = ? LIMIT 1', [slot]);
60
+ await this.store.runAsync('DELETE FROM data WHERE slot = ?', [slot]);
61
+ const raw = rows[0]?.[0];
62
+ return raw instanceof Uint8Array ? (this.#encoder.unpack(raw) as T) : undefined;
63
+ });
64
+ }
65
+
66
+ async atAsync(index: number): Promise<T | undefined> {
67
+ const length = await this.lengthAsync();
68
+ const resolved = index < 0 ? length + index : index;
69
+ if (resolved < 0 || resolved >= length) {
70
+ return undefined;
71
+ }
72
+ const rows = await this.store.allAsync('SELECT value FROM data WHERE slot = ? LIMIT 1', [this.#slot(resolved)]);
73
+ const raw = rows[0]?.[0];
74
+ return raw instanceof Uint8Array ? (this.#encoder.unpack(raw) as T) : undefined;
75
+ }
76
+
77
+ async setAt(index: number, val: T): Promise<boolean> {
78
+ return await this.store.transactionAsync(async () => {
79
+ const length = await this.lengthAsync();
80
+ const resolved = index < 0 ? length + index : index;
81
+ if (resolved < 0 || resolved >= length) {
82
+ return false;
83
+ }
84
+ await this.store.runAsync(
85
+ `INSERT OR REPLACE INTO data (slot, container, key, key_count, hash, value)
86
+ VALUES (?, ?, ?, ?, ?, ?)`,
87
+ [this.#slot(resolved), this.#container, this.#encodedKey(), resolved + 1, hash(val), this.#encoder.pack(val)],
88
+ );
89
+ return true;
90
+ });
91
+ }
92
+
93
+ async *entriesAsync(): AsyncIterableIterator<[number, T]> {
94
+ const rows = await this.store.allAsync(
95
+ 'SELECT key_count, value FROM data WHERE container = ? AND key = ? ORDER BY key_count ASC',
96
+ [this.#container, this.#encodedKey()],
97
+ );
98
+ for (const row of rows) {
99
+ const keyCount = Number(row[0]);
100
+ const raw = row[1];
101
+ if (raw instanceof Uint8Array) {
102
+ yield [keyCount - 1, this.#encoder.unpack(raw) as T];
103
+ }
104
+ }
105
+ }
106
+
107
+ async *valuesAsync(): AsyncIterableIterator<T> {
108
+ for await (const [, val] of this.entriesAsync()) {
109
+ yield val;
110
+ }
111
+ }
112
+
113
+ [Symbol.asyncIterator](): AsyncIterableIterator<T> {
114
+ return this.valuesAsync();
115
+ }
116
+
117
+ #encodedKey(): Buffer {
118
+ return toBufferKey([this.#name]);
119
+ }
120
+
121
+ #slot(index: number): string {
122
+ return `array:${this.#name}:slot:${index}`;
123
+ }
124
+ }
@@ -0,0 +1,44 @@
1
+ /**
2
+ * Typed error surface for sqlite3mc-backed page-level encryption failures.
3
+ *
4
+ * Three concrete failure modes are surfaced:
5
+ *
6
+ * - `invalid_key_length`: caller-side pre-flight (key not 32 bytes).
7
+ * - `encryption_not_supported_for_ephemeral`: caller-side pre-flight (encryption was requested on an ephemeral
8
+ * `:memory:` store, which sqlite3mc does not support).
9
+ * - `decrypt_failed`: runtime failure raised when sqlite3mc cannot decode page 1 of an existing database. Covers
10
+ * both "wrong key supplied" and "no key supplied to an encrypted DB".
11
+ */
12
+ export type SqliteEncryptionErrorCode =
13
+ | 'invalid_key_length'
14
+ | 'encryption_not_supported_for_ephemeral'
15
+ | 'decrypt_failed';
16
+
17
+ /**
18
+ * Error thrown by sqlite-opfs when an encryption operation fails.
19
+ **/
20
+ export class SqliteEncryptionError extends Error {
21
+ readonly code: SqliteEncryptionErrorCode;
22
+
23
+ constructor(code: SqliteEncryptionErrorCode, message: string, opts?: { cause?: unknown }) {
24
+ super(message, opts?.cause !== undefined ? { cause: opts.cause } : undefined);
25
+ this.name = 'SqliteEncryptionError';
26
+ this.code = code;
27
+ }
28
+ }
29
+
30
+ /**
31
+ * Strings raised by sqlite3mc when page 1 cannot be decoded.
32
+ **/
33
+ const SQLITE3MC_DECRYPT_ERROR_PATTERNS: readonly RegExp[] = [
34
+ /file is not a database/i,
35
+ /file is encrypted or is not a database/i,
36
+ ];
37
+
38
+ /**
39
+ * Returns `true` if `message` matches one of the known sqlite3mc decrypt-failure
40
+ * strings.
41
+ **/
42
+ export function isDecryptFailureMessage(message: string): boolean {
43
+ return SQLITE3MC_DECRYPT_ERROR_PATTERNS.some(p => p.test(message));
44
+ }
@@ -0,0 +1,39 @@
1
+ import { type Logger, createLogger } from '@aztec/foundation/log';
2
+ import type { DataStoreConfig } from '@aztec/stdlib/kv-store';
3
+
4
+ import { initStoreForRollupAndSchemaVersion } from '../utils.js';
5
+ import { AztecSQLiteOPFSStore } from './store.js';
6
+
7
+ export { AztecSQLiteOPFSStore } from './store.js';
8
+ export { SqliteEncryptionError } from './errors.js';
9
+ export type { SqliteEncryptionErrorCode } from './errors.js';
10
+
11
+ export async function createStore(
12
+ name: string,
13
+ config: DataStoreConfig,
14
+ schemaVersion: number | undefined = undefined,
15
+ log: Logger = createLogger('kv-store'),
16
+ ) {
17
+ const { dataDirectory } = config;
18
+ log.info(
19
+ dataDirectory
20
+ ? `Creating ${name} SQLite-OPFS data store with map size ${config.dataStoreMapSizeKb} KB`
21
+ : `Creating ${name} ephemeral SQLite-OPFS data store with map size ${config.dataStoreMapSizeKb} KB`,
22
+ );
23
+ const store = await AztecSQLiteOPFSStore.open(createLogger('kv-store:sqlite-opfs'), name, false);
24
+ return initStoreForRollupAndSchemaVersion(store, schemaVersion, config.rollupAddress, log);
25
+ }
26
+
27
+ export function openTmpStore(ephemeral: boolean = false): Promise<AztecSQLiteOPFSStore> {
28
+ return AztecSQLiteOPFSStore.open(createLogger('kv-store:sqlite-opfs'), undefined, ephemeral);
29
+ }
30
+
31
+ /**
32
+ * Convenience helper for tests and consumers that want an encrypted sqlite-opfs
33
+ * store without dealing with the full `open()` parameter order. Key must be 32
34
+ * bytes. Creates a fresh persistent store (sqlite3mc does not support encryption
35
+ * on ephemeral `:memory:` databases) in an auto-generated OPFS directory.
36
+ */
37
+ export function openEncryptedStore(encryptionKey: Uint8Array, name?: string, poolDirectory?: string) {
38
+ return AztecSQLiteOPFSStore.open(createLogger('kv-store:sqlite-opfs'), name, false, poolDirectory, encryptionKey);
39
+ }