@aztec/kv-store 0.0.1-commit.9ef841308 → 0.0.1-commit.a5db02d

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 (137) 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/deprecated/indexeddb/index.d.ts +7 -0
  8. package/dest/deprecated/indexeddb/index.d.ts.map +1 -0
  9. package/dest/deprecated/indexeddb/index.js +8 -0
  10. package/dest/deprecated/indexeddb/map.d.ts +38 -0
  11. package/dest/deprecated/indexeddb/map.d.ts.map +1 -0
  12. package/dest/deprecated/indexeddb/multi_map.d.ts +14 -0
  13. package/dest/deprecated/indexeddb/multi_map.d.ts.map +1 -0
  14. package/dest/deprecated/indexeddb/set.d.ts +17 -0
  15. package/dest/deprecated/indexeddb/set.d.ts.map +1 -0
  16. package/dest/deprecated/indexeddb/singleton.d.ts +17 -0
  17. package/dest/deprecated/indexeddb/singleton.d.ts.map +1 -0
  18. package/dest/deprecated/indexeddb/store.d.ts +98 -0
  19. package/dest/deprecated/indexeddb/store.d.ts.map +1 -0
  20. package/dest/{indexeddb → deprecated/indexeddb}/store.js +2 -0
  21. package/dest/interfaces/array_test_suite.d.ts +1 -1
  22. package/dest/interfaces/array_test_suite.d.ts.map +1 -1
  23. package/dest/interfaces/array_test_suite.js +33 -34
  24. package/dest/interfaces/index.d.ts +2 -2
  25. package/dest/interfaces/index.d.ts.map +1 -1
  26. package/dest/interfaces/map_test_suite.d.ts +1 -1
  27. package/dest/interfaces/map_test_suite.d.ts.map +1 -1
  28. package/dest/interfaces/map_test_suite.js +32 -33
  29. package/dest/interfaces/multi_map_test_suite.d.ts +1 -1
  30. package/dest/interfaces/multi_map_test_suite.d.ts.map +1 -1
  31. package/dest/interfaces/multi_map_test_suite.js +68 -69
  32. package/dest/interfaces/set_test_suite.d.ts +1 -1
  33. package/dest/interfaces/set_test_suite.d.ts.map +1 -1
  34. package/dest/interfaces/set_test_suite.js +13 -14
  35. package/dest/interfaces/singleton_test_suite.d.ts +1 -1
  36. package/dest/interfaces/singleton_test_suite.d.ts.map +1 -1
  37. package/dest/interfaces/singleton_test_suite.js +6 -7
  38. package/dest/lmdb/index.js +2 -2
  39. package/dest/lmdb-v2/factory.d.ts +29 -3
  40. package/dest/lmdb-v2/factory.d.ts.map +1 -1
  41. package/dest/lmdb-v2/factory.js +62 -10
  42. package/dest/lmdb-v2/read_transaction.js +21 -19
  43. package/dest/lmdb-v2/store.d.ts +2 -2
  44. package/dest/lmdb-v2/store.d.ts.map +1 -1
  45. package/dest/lmdb-v2/store.js +4 -4
  46. package/dest/sqlite-opfs/array.d.ts +21 -0
  47. package/dest/sqlite-opfs/array.d.ts.map +1 -0
  48. package/dest/sqlite-opfs/array.js +128 -0
  49. package/dest/sqlite-opfs/errors.d.ts +27 -0
  50. package/dest/sqlite-opfs/errors.d.ts.map +1 -0
  51. package/dest/sqlite-opfs/errors.js +34 -0
  52. package/dest/sqlite-opfs/index.d.ts +14 -0
  53. package/dest/sqlite-opfs/index.d.ts.map +1 -0
  54. package/dest/sqlite-opfs/index.js +16 -0
  55. package/dest/sqlite-opfs/internal/ordered-binary-browser.d.ts +32 -0
  56. package/dest/sqlite-opfs/internal/ordered-binary-browser.d.ts.map +1 -0
  57. package/dest/sqlite-opfs/internal/ordered-binary-browser.js +448 -0
  58. package/dest/sqlite-opfs/manage.d.ts +20 -0
  59. package/dest/sqlite-opfs/manage.d.ts.map +1 -0
  60. package/dest/sqlite-opfs/manage.js +31 -0
  61. package/dest/sqlite-opfs/map.d.ts +35 -0
  62. package/dest/sqlite-opfs/map.d.ts.map +1 -0
  63. package/dest/sqlite-opfs/map.js +163 -0
  64. package/dest/sqlite-opfs/messages.d.ts +66 -0
  65. package/dest/sqlite-opfs/messages.d.ts.map +1 -0
  66. package/dest/sqlite-opfs/messages.js +5 -0
  67. package/dest/sqlite-opfs/multi_map.d.ts +16 -0
  68. package/dest/sqlite-opfs/multi_map.d.ts.map +1 -0
  69. package/dest/sqlite-opfs/multi_map.js +67 -0
  70. package/dest/sqlite-opfs/set.d.ts +13 -0
  71. package/dest/sqlite-opfs/set.d.ts.map +1 -0
  72. package/dest/sqlite-opfs/set.js +19 -0
  73. package/dest/sqlite-opfs/singleton.d.ts +13 -0
  74. package/dest/sqlite-opfs/singleton.d.ts.map +1 -0
  75. package/dest/sqlite-opfs/singleton.js +48 -0
  76. package/dest/sqlite-opfs/store.d.ts +79 -0
  77. package/dest/sqlite-opfs/store.d.ts.map +1 -0
  78. package/dest/sqlite-opfs/store.js +281 -0
  79. package/dest/sqlite-opfs/worker.d.ts +2 -0
  80. package/dest/sqlite-opfs/worker.d.ts.map +1 -0
  81. package/dest/sqlite-opfs/worker.js +264 -0
  82. package/dest/stores/l2_tips_store.d.ts +7 -13
  83. package/dest/stores/l2_tips_store.d.ts.map +1 -1
  84. package/dest/stores/l2_tips_store.js +24 -43
  85. package/package.json +23 -20
  86. package/src/bench/shared_map_bench.ts +111 -0
  87. package/src/{indexeddb → deprecated/indexeddb}/array.ts +2 -2
  88. package/src/deprecated/indexeddb/index.ts +12 -0
  89. package/src/{indexeddb → deprecated/indexeddb}/map.ts +2 -2
  90. package/src/{indexeddb → deprecated/indexeddb}/multi_map.ts +2 -2
  91. package/src/{indexeddb → deprecated/indexeddb}/set.ts +2 -2
  92. package/src/{indexeddb → deprecated/indexeddb}/singleton.ts +2 -2
  93. package/src/{indexeddb → deprecated/indexeddb}/store.ts +10 -9
  94. package/src/interfaces/array_test_suite.ts +33 -35
  95. package/src/interfaces/index.ts +1 -1
  96. package/src/interfaces/map_test_suite.ts +32 -34
  97. package/src/interfaces/multi_map_test_suite.ts +65 -67
  98. package/src/interfaces/set_test_suite.ts +13 -15
  99. package/src/interfaces/singleton_test_suite.ts +6 -8
  100. package/src/lmdb/index.ts +2 -2
  101. package/src/lmdb-v2/factory.ts +85 -9
  102. package/src/lmdb-v2/read_transaction.ts +23 -23
  103. package/src/lmdb-v2/store.ts +4 -2
  104. package/src/sqlite-opfs/array.ts +124 -0
  105. package/src/sqlite-opfs/errors.ts +44 -0
  106. package/src/sqlite-opfs/index.ts +22 -0
  107. package/src/sqlite-opfs/internal/ordered-binary-browser.js +465 -0
  108. package/src/sqlite-opfs/manage.ts +36 -0
  109. package/src/sqlite-opfs/map.ts +163 -0
  110. package/src/sqlite-opfs/messages.ts +39 -0
  111. package/src/sqlite-opfs/multi_map.ts +74 -0
  112. package/src/sqlite-opfs/set.ts +29 -0
  113. package/src/sqlite-opfs/singleton.ts +48 -0
  114. package/src/sqlite-opfs/store.ts +296 -0
  115. package/src/sqlite-opfs/worker.ts +248 -0
  116. package/src/stores/l2_tips_store.ts +20 -41
  117. package/dest/indexeddb/array.d.ts +0 -22
  118. package/dest/indexeddb/array.d.ts.map +0 -1
  119. package/dest/indexeddb/index.d.ts +0 -7
  120. package/dest/indexeddb/index.d.ts.map +0 -1
  121. package/dest/indexeddb/index.js +0 -16
  122. package/dest/indexeddb/map.d.ts +0 -38
  123. package/dest/indexeddb/map.d.ts.map +0 -1
  124. package/dest/indexeddb/multi_map.d.ts +0 -14
  125. package/dest/indexeddb/multi_map.d.ts.map +0 -1
  126. package/dest/indexeddb/set.d.ts +0 -17
  127. package/dest/indexeddb/set.d.ts.map +0 -1
  128. package/dest/indexeddb/singleton.d.ts +0 -17
  129. package/dest/indexeddb/singleton.d.ts.map +0 -1
  130. package/dest/indexeddb/store.d.ts +0 -96
  131. package/dest/indexeddb/store.d.ts.map +0 -1
  132. package/src/indexeddb/index.ts +0 -31
  133. /package/dest/{indexeddb → deprecated/indexeddb}/array.js +0 -0
  134. /package/dest/{indexeddb → deprecated/indexeddb}/map.js +0 -0
  135. /package/dest/{indexeddb → deprecated/indexeddb}/multi_map.js +0 -0
  136. /package/dest/{indexeddb → deprecated/indexeddb}/set.js +0 -0
  137. /package/dest/{indexeddb → deprecated/indexeddb}/singleton.js +0 -0
@@ -1,9 +1,13 @@
1
1
  import { EthAddress } from '@aztec/foundation/eth-address';
2
2
  import { type LoggerBindings, createLogger } from '@aztec/foundation/log';
3
- import { DatabaseVersionManager } from '@aztec/stdlib/database-version/manager';
3
+ import {
4
+ DatabaseVersionManager,
5
+ type SchemaVersionMismatchPolicy,
6
+ type VersionFileReadFailurePolicy,
7
+ } from '@aztec/stdlib/database-version/manager';
4
8
  import type { DataStoreConfig } from '@aztec/stdlib/kv-store';
5
9
 
6
- import { mkdir, mkdtemp, rm } from 'fs/promises';
10
+ import { copyFile, mkdir, mkdtemp, rm } from 'fs/promises';
7
11
  import { tmpdir } from 'os';
8
12
  import { join } from 'path';
9
13
 
@@ -11,14 +15,22 @@ 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
29
  bindings?: LoggerBindings,
30
+ options: CreateStoreOptions = {},
19
31
  ): Promise<AztecLMDBStoreV2> {
20
32
  const log = createLogger('kv-store:lmdb-v2:' + name, bindings);
21
- const { dataDirectory, l1Contracts } = config;
33
+ const { dataDirectory, rollupAddress: rollupFromConfig } = config;
22
34
 
23
35
  let store: AztecLMDBStoreV2;
24
36
  if (typeof dataDirectory !== 'undefined') {
@@ -26,7 +38,7 @@ export async function createStore(
26
38
  const subDir = join(dataDirectory, name);
27
39
  await mkdir(subDir, { recursive: true });
28
40
 
29
- const rollupAddress = l1Contracts ? l1Contracts.rollupAddress : EthAddress.ZERO;
41
+ const rollupAddress = rollupFromConfig ?? EthAddress.ZERO;
30
42
 
31
43
  // Create a version manager
32
44
  const versionManager = new DatabaseVersionManager({
@@ -35,6 +47,9 @@ export async function createStore(
35
47
  dataDirectory: subDir,
36
48
  onOpen: dbDirectory =>
37
49
  AztecLMDBStoreV2.new(dbDirectory, config.dataStoreMapSizeKb, MAX_READERS, () => Promise.resolve(), bindings),
50
+ onUpgrade: options.onUpgrade,
51
+ schemaVersionMismatchPolicy: options.schemaVersionMismatchPolicy,
52
+ versionFileReadFailurePolicy: options.versionFileReadFailurePolicy,
38
53
  });
39
54
 
40
55
  log.info(
@@ -48,9 +63,14 @@ export async function createStore(
48
63
  return store;
49
64
  }
50
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
+ */
51
71
  export async function openTmpStore(
52
72
  name: string,
53
- ephemeral: boolean = true,
73
+ cleanupTmpDir: boolean = true,
54
74
  dbMapSizeKb = 10 * 1_024 * 1_024, // 10GB
55
75
  maxReaders = MAX_READERS,
56
76
  bindings?: LoggerBindings,
@@ -61,7 +81,7 @@ export async function openTmpStore(
61
81
 
62
82
  // pass a cleanup callback because process.on('beforeExit', cleanup) does not work under Jest
63
83
  const cleanup = async () => {
64
- if (ephemeral) {
84
+ if (cleanupTmpDir) {
65
85
  try {
66
86
  await rm(dataDir, { recursive: true, force: true, maxRetries: 3 });
67
87
  log.debug(`Deleted temporary data store: ${dataDir}`);
@@ -73,9 +93,35 @@ export async function openTmpStore(
73
93
  }
74
94
  };
75
95
 
76
- // For temporary stores, we don't need to worry about versioning
77
- // as they are ephemeral and get cleaned up after use
78
- return AztecLMDBStoreV2.new(dataDir, dbMapSizeKb, maxReaders, cleanup, bindings);
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);
79
125
  }
80
126
 
81
127
  export async function openStoreAt(
@@ -89,6 +135,36 @@ export async function openStoreAt(
89
135
  return await AztecLMDBStoreV2.new(dataDir, dbMapSizeKb, maxReaders, undefined, bindings);
90
136
  }
91
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);
166
+ }
167
+
92
168
  export async function openVersionedStoreAt(
93
169
  dataDirectory: string,
94
170
  schemaVersion: number,
@@ -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
  }
@@ -43,9 +43,10 @@ export class AztecLMDBStoreV2 implements AztecAsyncKVStore, LMDBMessageChannel {
43
43
  maxReaders: number,
44
44
  private log: Logger,
45
45
  private cleanup?: () => Promise<void>,
46
+ ephemeral: boolean = false,
46
47
  ) {
47
48
  this.log.info(`Starting data store with maxReaders ${maxReaders}`);
48
- this.channel = new MsgpackChannel(new NativeLMDBStore(dataDir, mapSize, maxReaders));
49
+ this.channel = new MsgpackChannel(new NativeLMDBStore(dataDir, mapSize, maxReaders, ephemeral));
49
50
  // leave one reader to always be available for regular, atomic, reads
50
51
  this.availableCursors = new Semaphore(maxReaders - 1);
51
52
  }
@@ -76,9 +77,10 @@ export class AztecLMDBStoreV2 implements AztecAsyncKVStore, LMDBMessageChannel {
76
77
  maxReaders: number = 16,
77
78
  cleanup?: () => Promise<void>,
78
79
  bindings?: LoggerBindings,
80
+ ephemeral: boolean = false,
79
81
  ) {
80
82
  const log = createLogger('kv-store:lmdb-v2', bindings);
81
- const db = new AztecLMDBStoreV2(dataDir, dbMapSizeKb, maxReaders, log, cleanup);
83
+ const db = new AztecLMDBStoreV2(dataDir, dbMapSizeKb, maxReaders, log, cleanup, ephemeral);
82
84
  await db.start();
83
85
  return db;
84
86
  }
@@ -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,22 @@
1
+ import { createLogger } from '@aztec/foundation/log';
2
+
3
+ import { AztecSQLiteOPFSStore } from './store.js';
4
+
5
+ export { AztecSQLiteOPFSStore } from './store.js';
6
+ export { SqliteEncryptionError } from './errors.js';
7
+ export type { SqliteEncryptionErrorCode } from './errors.js';
8
+ export { OPFS_POOL_DIR_PREFIX, deleteStore, listStores, storePoolDirectory } from './manage.js';
9
+
10
+ export function openTmpStore(ephemeral: boolean = false): Promise<AztecSQLiteOPFSStore> {
11
+ return AztecSQLiteOPFSStore.open(createLogger('kv-store:sqlite-opfs'), undefined, ephemeral);
12
+ }
13
+
14
+ /**
15
+ * Convenience helper for tests and consumers that want an encrypted sqlite-opfs
16
+ * store without dealing with the full `open()` parameter order. Key must be 32
17
+ * bytes. Creates a fresh persistent store (sqlite3mc does not support encryption
18
+ * on ephemeral `:memory:` databases) in an auto-generated OPFS directory.
19
+ */
20
+ export function openEncryptedStore(encryptionKey: Uint8Array, name?: string, poolDirectory?: string) {
21
+ return AztecSQLiteOPFSStore.open(createLogger('kv-store:sqlite-opfs'), name, false, poolDirectory, encryptionKey);
22
+ }