@aztec/kv-store 0.0.1-commit.fff30aa → 0.0.1-dev

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 (72) hide show
  1. package/dest/bench/shared_map_bench.d.ts +19 -0
  2. package/dest/bench/shared_map_bench.d.ts.map +1 -0
  3. package/dest/bench/shared_map_bench.js +91 -0
  4. package/dest/interfaces/array_test_suite.d.ts +1 -1
  5. package/dest/interfaces/array_test_suite.d.ts.map +1 -1
  6. package/dest/interfaces/array_test_suite.js +33 -34
  7. package/dest/interfaces/index.d.ts +2 -2
  8. package/dest/interfaces/index.d.ts.map +1 -1
  9. package/dest/interfaces/map_test_suite.d.ts +1 -1
  10. package/dest/interfaces/map_test_suite.d.ts.map +1 -1
  11. package/dest/interfaces/map_test_suite.js +32 -33
  12. package/dest/interfaces/multi_map_test_suite.d.ts +1 -1
  13. package/dest/interfaces/multi_map_test_suite.d.ts.map +1 -1
  14. package/dest/interfaces/multi_map_test_suite.js +68 -69
  15. package/dest/interfaces/set_test_suite.d.ts +1 -1
  16. package/dest/interfaces/set_test_suite.d.ts.map +1 -1
  17. package/dest/interfaces/set_test_suite.js +13 -14
  18. package/dest/interfaces/singleton_test_suite.d.ts +1 -1
  19. package/dest/interfaces/singleton_test_suite.d.ts.map +1 -1
  20. package/dest/interfaces/singleton_test_suite.js +6 -7
  21. package/dest/sqlite-opfs/array.d.ts +21 -0
  22. package/dest/sqlite-opfs/array.d.ts.map +1 -0
  23. package/dest/sqlite-opfs/array.js +128 -0
  24. package/dest/sqlite-opfs/errors.d.ts +27 -0
  25. package/dest/sqlite-opfs/errors.d.ts.map +1 -0
  26. package/dest/sqlite-opfs/errors.js +34 -0
  27. package/dest/sqlite-opfs/index.d.ts +16 -0
  28. package/dest/sqlite-opfs/index.d.ts.map +1 -0
  29. package/dest/sqlite-opfs/index.js +22 -0
  30. package/dest/sqlite-opfs/internal/ordered-binary-browser.d.ts +32 -0
  31. package/dest/sqlite-opfs/internal/ordered-binary-browser.d.ts.map +1 -0
  32. package/dest/sqlite-opfs/internal/ordered-binary-browser.js +448 -0
  33. package/dest/sqlite-opfs/map.d.ts +35 -0
  34. package/dest/sqlite-opfs/map.d.ts.map +1 -0
  35. package/dest/sqlite-opfs/map.js +163 -0
  36. package/dest/sqlite-opfs/messages.d.ts +66 -0
  37. package/dest/sqlite-opfs/messages.d.ts.map +1 -0
  38. package/dest/sqlite-opfs/messages.js +5 -0
  39. package/dest/sqlite-opfs/multi_map.d.ts +16 -0
  40. package/dest/sqlite-opfs/multi_map.d.ts.map +1 -0
  41. package/dest/sqlite-opfs/multi_map.js +67 -0
  42. package/dest/sqlite-opfs/set.d.ts +13 -0
  43. package/dest/sqlite-opfs/set.d.ts.map +1 -0
  44. package/dest/sqlite-opfs/set.js +19 -0
  45. package/dest/sqlite-opfs/singleton.d.ts +13 -0
  46. package/dest/sqlite-opfs/singleton.d.ts.map +1 -0
  47. package/dest/sqlite-opfs/singleton.js +48 -0
  48. package/dest/sqlite-opfs/store.d.ts +79 -0
  49. package/dest/sqlite-opfs/store.d.ts.map +1 -0
  50. package/dest/sqlite-opfs/store.js +281 -0
  51. package/dest/sqlite-opfs/worker.d.ts +2 -0
  52. package/dest/sqlite-opfs/worker.d.ts.map +1 -0
  53. package/dest/sqlite-opfs/worker.js +244 -0
  54. package/package.json +22 -19
  55. package/src/bench/shared_map_bench.ts +111 -0
  56. package/src/interfaces/array_test_suite.ts +33 -35
  57. package/src/interfaces/index.ts +1 -1
  58. package/src/interfaces/map_test_suite.ts +32 -34
  59. package/src/interfaces/multi_map_test_suite.ts +65 -67
  60. package/src/interfaces/set_test_suite.ts +13 -15
  61. package/src/interfaces/singleton_test_suite.ts +6 -8
  62. package/src/sqlite-opfs/array.ts +124 -0
  63. package/src/sqlite-opfs/errors.ts +44 -0
  64. package/src/sqlite-opfs/index.ts +39 -0
  65. package/src/sqlite-opfs/internal/ordered-binary-browser.js +465 -0
  66. package/src/sqlite-opfs/map.ts +163 -0
  67. package/src/sqlite-opfs/messages.ts +39 -0
  68. package/src/sqlite-opfs/multi_map.ts +74 -0
  69. package/src/sqlite-opfs/set.ts +29 -0
  70. package/src/sqlite-opfs/singleton.ts +48 -0
  71. package/src/sqlite-opfs/store.ts +296 -0
  72. package/src/sqlite-opfs/worker.ts +226 -0
@@ -0,0 +1,226 @@
1
+ /// <reference lib="webworker" />
2
+ import sqlite3InitModule, { type Database, type SAHPoolUtil, type Sqlite3Static } from '@aztec/sqlite3mc-wasm';
3
+
4
+ import { SqliteEncryptionError, type SqliteEncryptionErrorCode, isDecryptFailureMessage } from './errors.js';
5
+ import type { ResultRow, SqlValue, WorkerRequest, WorkerResponse } from './messages.js';
6
+
7
+ const SCHEMA_SQL = `
8
+ CREATE TABLE IF NOT EXISTS data (
9
+ slot TEXT NOT NULL PRIMARY KEY,
10
+ container TEXT NOT NULL,
11
+ key BLOB NOT NULL,
12
+ key_count INTEGER NOT NULL,
13
+ hash TEXT NOT NULL,
14
+ value BLOB
15
+ ) WITHOUT ROWID;
16
+
17
+ CREATE INDEX IF NOT EXISTS idx_container_key ON data(container, key);
18
+ CREATE UNIQUE INDEX IF NOT EXISTS idx_container_key_count ON data(container, key, key_count);
19
+ CREATE UNIQUE INDEX IF NOT EXISTS idx_container_key_hash ON data(container, key, hash);
20
+ `;
21
+
22
+ const DEFAULT_SAH_POOL_DIRECTORY = '.aztec-kv';
23
+ const SAH_POOL_VFS_NAME = 'aztec-kv-opfs';
24
+ const MC_SAH_POOL_VFS_NAME = `multipleciphers-${SAH_POOL_VFS_NAME}`;
25
+
26
+ let sqlite3: Sqlite3Static | undefined;
27
+ let pool: SAHPoolUtil | undefined;
28
+ let poolDirectory: string | undefined;
29
+ let db: Database | undefined;
30
+ let dbPath: string | undefined;
31
+
32
+ async function ensurePool(directory: string): Promise<SAHPoolUtil> {
33
+ sqlite3 ??= await sqlite3InitModule();
34
+ const s = sqlite3;
35
+ if (!pool) {
36
+ poolDirectory = directory;
37
+ pool = await s.installOpfsSAHPoolVfs({
38
+ name: SAH_POOL_VFS_NAME,
39
+ directory,
40
+ initialCapacity: 8,
41
+ });
42
+ // Register a sqlite3mc-wrapped VFS pointing at our SAH Pool VFS.
43
+ // Encrypted DBs must be opened through this wrapper so sqlite3mc can
44
+ // intercept file I/O; plain DBs continue using the SAH Pool VFS directly.
45
+ // The wrapper name is `multipleciphers-<underlying>`.
46
+ (s.capi as unknown as { sqlite3mc_vfs_create(name: string, makeDefault: number): number }).sqlite3mc_vfs_create(
47
+ SAH_POOL_VFS_NAME,
48
+ 0,
49
+ );
50
+ }
51
+ return pool!;
52
+ }
53
+
54
+ /**
55
+ * Applies sqlite3mc's ChaCha20 page cipher using a pre-derived 32-byte key.
56
+ * The PRAGMAs must run before any schema DDL so sqlite3mc can decrypt existing
57
+ * pages and encrypt new ones. Zeroes the caller-held key array after the PRAGMA
58
+ * completes to minimize residency of the raw key bytes outside sqlite3mc's heap.
59
+ */
60
+ function applyEncryptionKey(conn: Database, key: Uint8Array): void {
61
+ const hex = Array.from(key, b => b.toString(16).padStart(2, '0')).join('');
62
+ conn.exec(`PRAGMA cipher = 'chacha20'`);
63
+ conn.exec(`PRAGMA key = "x'${hex}'"`);
64
+ key.fill(0);
65
+ }
66
+
67
+ async function handleInit(
68
+ dbName: string,
69
+ ephemeral: boolean,
70
+ directory?: string,
71
+ encryptionKey?: Uint8Array,
72
+ ): Promise<void> {
73
+ sqlite3 ??= await sqlite3InitModule();
74
+ const s = sqlite3;
75
+ if (encryptionKey !== undefined && ephemeral) {
76
+ throw new SqliteEncryptionError(
77
+ 'encryption_not_supported_for_ephemeral',
78
+ 'encryptionKey is not supported for ephemeral (:memory:) stores',
79
+ );
80
+ }
81
+ if (ephemeral) {
82
+ db = new s.oo1.DB(':memory:', 'c');
83
+ } else {
84
+ await ensurePool(directory ?? DEFAULT_SAH_POOL_DIRECTORY);
85
+ dbPath = normalizeDbPath(dbName);
86
+ if (encryptionKey !== undefined) {
87
+ db = new s.oo1.DB({ filename: dbPath, flags: 'c', vfs: MC_SAH_POOL_VFS_NAME });
88
+ applyEncryptionKey(db, encryptionKey);
89
+ } else {
90
+ db = new pool!.OpfsSAHPoolDb(dbPath);
91
+ }
92
+ }
93
+ runSql(SCHEMA_SQL);
94
+ }
95
+
96
+ function handleClose(): void {
97
+ db?.close();
98
+ db = undefined;
99
+ dbPath = undefined;
100
+ }
101
+
102
+ async function handleExport(): Promise<Uint8Array> {
103
+ if (!db || !dbPath) {
104
+ throw new Error('SQLite worker: no database open to export');
105
+ }
106
+ if (!pool) {
107
+ throw new Error('SQLite worker: no SAH Pool available (ephemeral DBs cannot be exported)');
108
+ }
109
+ return await pool.exportFile(dbPath);
110
+ }
111
+
112
+ async function handleDeleteDb(dbName: string): Promise<void> {
113
+ const path = normalizeDbPath(dbName);
114
+ if (db && dbPath === path) {
115
+ db.close();
116
+ db = undefined;
117
+ dbPath = undefined;
118
+ }
119
+ const p = await ensurePool(poolDirectory ?? DEFAULT_SAH_POOL_DIRECTORY);
120
+ try {
121
+ p.unlink(path);
122
+ } catch {
123
+ // File may not exist; ignore.
124
+ }
125
+ }
126
+
127
+ function requireDb(): Database {
128
+ if (!db) {
129
+ throw new Error('SQLite worker: no database open');
130
+ }
131
+ return db;
132
+ }
133
+
134
+ function runSql(sql: string, bind?: SqlValue[]): { changes: number } {
135
+ const conn = requireDb();
136
+ conn.exec({ sql, bind });
137
+ return { changes: conn.changes() };
138
+ }
139
+
140
+ function selectAll(sql: string, bind?: SqlValue[]): ResultRow[] {
141
+ const conn = requireDb();
142
+ const rows: ResultRow[] = [];
143
+ conn.exec({ sql, bind, rowMode: 'array', resultRows: rows });
144
+ return rows;
145
+ }
146
+
147
+ function normalizeDbPath(dbName: string): string {
148
+ return dbName.startsWith('/') ? dbName : `/${dbName}`;
149
+ }
150
+
151
+ function respond(msg: WorkerResponse): void {
152
+ (self as DedicatedWorkerGlobalScope).postMessage(msg);
153
+ }
154
+
155
+ (self as DedicatedWorkerGlobalScope).onmessage = async (ev: MessageEvent<WorkerRequest>) => {
156
+ const req = ev.data;
157
+ try {
158
+ switch (req.type) {
159
+ case 'init':
160
+ await handleInit(req.dbName, req.ephemeral, req.poolDirectory, req.encryptionKey);
161
+ return respond({ type: 'ok', id: req.id });
162
+ case 'close':
163
+ handleClose();
164
+ return respond({ type: 'ok', id: req.id });
165
+ case 'deleteDb':
166
+ await handleDeleteDb(req.dbName);
167
+ return respond({ type: 'ok', id: req.id });
168
+ case 'run': {
169
+ const { changes } = runSql(req.sql, req.bind);
170
+ return respond({ type: 'ok', id: req.id, changes });
171
+ }
172
+ case 'all': {
173
+ const rows = selectAll(req.sql, req.bind);
174
+ return respond({ type: 'ok', id: req.id, rows });
175
+ }
176
+ case 'export': {
177
+ const bytes = await handleExport();
178
+ return respond({ type: 'ok', id: req.id, bytes });
179
+ }
180
+ case 'begin':
181
+ runSql('BEGIN');
182
+ return respond({ type: 'ok', id: req.id });
183
+ case 'commit':
184
+ runSql('COMMIT');
185
+ return respond({ type: 'ok', id: req.id });
186
+ case 'rollback':
187
+ runSql('ROLLBACK');
188
+ return respond({ type: 'ok', id: req.id });
189
+ default: {
190
+ const _exhaustive: never = req;
191
+ throw new Error(`Unknown request: ${JSON.stringify(_exhaustive)}`);
192
+ }
193
+ }
194
+ } catch (err) {
195
+ const message = err instanceof Error ? err.message : String(err);
196
+ respond({ type: 'err', id: req.id, message, encryptionCode: detectEncryptionCode(req, err, message) });
197
+ }
198
+ };
199
+
200
+ /**
201
+ * Maps a thrown error during request handling to a typed encryption code, so the
202
+ * main thread can re-hydrate it as a {@link SqliteEncryptionError}. Returns
203
+ * `undefined` for non-encryption errors (preserves the existing untyped path).
204
+ *
205
+ * Two sources:
206
+ * - The error was already a `SqliteEncryptionError` (pre-flight throws inside
207
+ * this worker — e.g. ephemeral + encryptionKey). Forward its code as-is.
208
+ * - The error came from SQLite/sqlite3mc with a known decrypt-failure message
209
+ * during an `init` request. Both "wrong key supplied" and "no key supplied
210
+ * to an encrypted DB" surface as SQLITE_NOTADB ("file is not a database") —
211
+ * we don't constrain on `req.encryptionKey` because the no-key-on-encrypted-DB
212
+ * case is exactly when the caller most needs the typed signal.
213
+ */
214
+ function detectEncryptionCode(
215
+ req: WorkerRequest,
216
+ err: unknown,
217
+ message: string,
218
+ ): SqliteEncryptionErrorCode | undefined {
219
+ if (err instanceof SqliteEncryptionError) {
220
+ return err.code;
221
+ }
222
+ if (req.type === 'init' && isDecryptFailureMessage(message)) {
223
+ return 'decrypt_failed';
224
+ }
225
+ return undefined;
226
+ }