@aztec/kv-store 0.0.1-commit.9372f48 → 0.0.1-commit.949a33fd8
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.
- package/dest/bench/shared_map_bench.d.ts +19 -0
- package/dest/bench/shared_map_bench.d.ts.map +1 -0
- package/dest/bench/shared_map_bench.js +91 -0
- package/dest/indexeddb/array.js +18 -6
- package/dest/indexeddb/index.d.ts +2 -2
- package/dest/indexeddb/index.d.ts.map +1 -1
- package/dest/indexeddb/map.d.ts +8 -2
- package/dest/indexeddb/map.d.ts.map +1 -1
- package/dest/indexeddb/map.js +23 -13
- package/dest/indexeddb/multi_map.d.ts +2 -1
- package/dest/indexeddb/multi_map.d.ts.map +1 -1
- package/dest/indexeddb/multi_map.js +16 -1
- package/dest/indexeddb/singleton.js +3 -1
- package/dest/indexeddb/store.d.ts +3 -3
- package/dest/indexeddb/store.d.ts.map +1 -1
- package/dest/indexeddb/store.js +6 -4
- package/dest/interfaces/map_test_suite.d.ts +1 -1
- package/dest/interfaces/map_test_suite.d.ts.map +1 -1
- package/dest/interfaces/map_test_suite.js +48 -2
- package/dest/interfaces/multi_map_test_suite.d.ts +1 -1
- package/dest/interfaces/multi_map_test_suite.d.ts.map +1 -1
- package/dest/interfaces/multi_map_test_suite.js +25 -0
- package/dest/lmdb/index.d.ts +2 -2
- package/dest/lmdb/index.d.ts.map +1 -1
- package/dest/lmdb/store.d.ts +3 -3
- package/dest/lmdb/store.d.ts.map +1 -1
- package/dest/lmdb/store.js +12 -8
- package/dest/lmdb-v2/factory.d.ts +2 -2
- package/dest/lmdb-v2/factory.d.ts.map +1 -1
- package/dest/lmdb-v2/read_transaction.js +21 -19
- package/dest/sqlite-opfs/array.d.ts +21 -0
- package/dest/sqlite-opfs/array.d.ts.map +1 -0
- package/dest/sqlite-opfs/array.js +128 -0
- package/dest/sqlite-opfs/index.d.ts +7 -0
- package/dest/sqlite-opfs/index.d.ts.map +1 -0
- package/dest/sqlite-opfs/index.js +13 -0
- package/dest/sqlite-opfs/map.d.ts +35 -0
- package/dest/sqlite-opfs/map.d.ts.map +1 -0
- package/dest/sqlite-opfs/map.js +163 -0
- package/dest/sqlite-opfs/messages.d.ts +58 -0
- package/dest/sqlite-opfs/messages.d.ts.map +1 -0
- package/dest/sqlite-opfs/messages.js +5 -0
- package/dest/sqlite-opfs/multi_map.d.ts +16 -0
- package/dest/sqlite-opfs/multi_map.d.ts.map +1 -0
- package/dest/sqlite-opfs/multi_map.js +67 -0
- package/dest/sqlite-opfs/set.d.ts +13 -0
- package/dest/sqlite-opfs/set.d.ts.map +1 -0
- package/dest/sqlite-opfs/set.js +19 -0
- package/dest/sqlite-opfs/singleton.d.ts +13 -0
- package/dest/sqlite-opfs/singleton.d.ts.map +1 -0
- package/dest/sqlite-opfs/singleton.js +48 -0
- package/dest/sqlite-opfs/store.d.ts +70 -0
- package/dest/sqlite-opfs/store.d.ts.map +1 -0
- package/dest/sqlite-opfs/store.js +242 -0
- package/dest/sqlite-opfs/worker.d.ts +2 -0
- package/dest/sqlite-opfs/worker.d.ts.map +1 -0
- package/dest/sqlite-opfs/worker.js +194 -0
- package/dest/utils.d.ts +1 -1
- package/dest/utils.d.ts.map +1 -1
- package/dest/utils.js +7 -1
- package/package.json +17 -13
- package/src/bench/shared_map_bench.ts +111 -0
- package/src/indexeddb/array.ts +4 -4
- package/src/indexeddb/index.ts +1 -1
- package/src/indexeddb/map.ts +24 -11
- package/src/indexeddb/multi_map.ts +15 -1
- package/src/indexeddb/singleton.ts +1 -1
- package/src/indexeddb/store.ts +13 -6
- package/src/interfaces/map_test_suite.ts +30 -2
- package/src/interfaces/multi_map_test_suite.ts +32 -0
- package/src/lmdb/index.ts +1 -1
- package/src/lmdb/store.ts +12 -8
- package/src/lmdb-v2/factory.ts +1 -1
- package/src/lmdb-v2/read_transaction.ts +23 -23
- package/src/sqlite-opfs/array.ts +124 -0
- package/src/sqlite-opfs/index.ts +27 -0
- package/src/sqlite-opfs/map.ts +163 -0
- package/src/sqlite-opfs/messages.ts +28 -0
- package/src/sqlite-opfs/multi_map.ts +74 -0
- package/src/sqlite-opfs/set.ts +29 -0
- package/src/sqlite-opfs/singleton.ts +48 -0
- package/src/sqlite-opfs/store.ts +248 -0
- package/src/sqlite-opfs/worker.ts +162 -0
- package/src/utils.ts +10 -0
- package/dest/config.d.ts +0 -17
- package/dest/config.d.ts.map +0 -1
- package/dest/config.js +0 -26
- package/src/config.ts +0 -36
|
@@ -0,0 +1,248 @@
|
|
|
1
|
+
import type { Logger } from '@aztec/foundation/log';
|
|
2
|
+
import { SerialQueue } from '@aztec/foundation/queue';
|
|
3
|
+
|
|
4
|
+
import type { AztecAsyncArray } from '../interfaces/array.js';
|
|
5
|
+
import type { Key, StoreSize, Value } from '../interfaces/common.js';
|
|
6
|
+
import type { AztecAsyncCounter } from '../interfaces/counter.js';
|
|
7
|
+
import type { AztecAsyncMap } from '../interfaces/map.js';
|
|
8
|
+
import type { AztecAsyncMultiMap } from '../interfaces/multi_map.js';
|
|
9
|
+
import type { AztecAsyncSet } from '../interfaces/set.js';
|
|
10
|
+
import type { AztecAsyncSingleton } from '../interfaces/singleton.js';
|
|
11
|
+
import type { AztecAsyncKVStore } from '../interfaces/store.js';
|
|
12
|
+
import { SQLiteOPFSAztecArray } from './array.js';
|
|
13
|
+
import { SQLiteOPFSAztecMap } from './map.js';
|
|
14
|
+
import type { ResultRow, SqlValue, WorkerRequest, WorkerResponse } from './messages.js';
|
|
15
|
+
import { SQLiteOPFSAztecMultiMap } from './multi_map.js';
|
|
16
|
+
import { SQLiteOPFSAztecSet } from './set.js';
|
|
17
|
+
import { SQLiteOPFSAztecSingleton } from './singleton.js';
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* Main-thread handle for a SQLite database persisted to OPFS via the `opfs-sahpool`
|
|
21
|
+
* VFS. Owns a dedicated Web Worker (the SAH Pool VFS requires Worker context) and
|
|
22
|
+
* routes every SQL op through it via typed postMessage RPC.
|
|
23
|
+
*
|
|
24
|
+
* Transaction ordering is guaranteed by a `SerialQueue` on the main thread combined
|
|
25
|
+
* with an `#inTx` flag: outside a `transactionAsync` block, each op acquires the
|
|
26
|
+
* queue for its own auto-commit; inside a block, the outer call holds the queue and
|
|
27
|
+
* nested ops bypass it to avoid deadlock.
|
|
28
|
+
*/
|
|
29
|
+
export class AztecSQLiteOPFSStore implements AztecAsyncKVStore {
|
|
30
|
+
readonly #worker: Worker;
|
|
31
|
+
readonly #pending = new Map<number, { resolve: (r: WorkerResponse) => void; reject: (err: Error) => void }>();
|
|
32
|
+
readonly #txQueue = new SerialQueue();
|
|
33
|
+
readonly #name: string;
|
|
34
|
+
readonly #log: Logger;
|
|
35
|
+
#nextId = 0;
|
|
36
|
+
#inTx = false;
|
|
37
|
+
#closed = false;
|
|
38
|
+
|
|
39
|
+
private constructor(
|
|
40
|
+
worker: Worker,
|
|
41
|
+
name: string,
|
|
42
|
+
log: Logger,
|
|
43
|
+
public readonly isEphemeral: boolean,
|
|
44
|
+
) {
|
|
45
|
+
this.#worker = worker;
|
|
46
|
+
this.#name = name;
|
|
47
|
+
this.#log = log;
|
|
48
|
+
this.#worker.onmessage = (ev: MessageEvent<WorkerResponse>) => {
|
|
49
|
+
const { id } = ev.data;
|
|
50
|
+
const handler = this.#pending.get(id);
|
|
51
|
+
if (!handler) {
|
|
52
|
+
this.#log.warn(`SQLite worker: no pending handler for id ${id}`);
|
|
53
|
+
return;
|
|
54
|
+
}
|
|
55
|
+
this.#pending.delete(id);
|
|
56
|
+
handler.resolve(ev.data);
|
|
57
|
+
};
|
|
58
|
+
this.#worker.onerror = ev => {
|
|
59
|
+
this.#log.error(`SQLite worker crashed: ${ev.message}`);
|
|
60
|
+
this.#rejectPending(`SQLite worker crashed: ${ev.message}`);
|
|
61
|
+
};
|
|
62
|
+
this.#txQueue.start();
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/**
|
|
66
|
+
* Opens (or creates) a SQLite database stored in the OPFS SAH Pool. When `ephemeral`
|
|
67
|
+
* is true the database lives only in memory and is lost when the worker terminates.
|
|
68
|
+
* Pass `poolDirectory` to place the SAH Pool in a non-default OPFS subdirectory —
|
|
69
|
+
* required when multiple stores coexist in the same tab, because the SAH Pool holds
|
|
70
|
+
* an exclusive lock on its directory.
|
|
71
|
+
*/
|
|
72
|
+
static async open(
|
|
73
|
+
log: Logger,
|
|
74
|
+
name?: string,
|
|
75
|
+
ephemeral: boolean = false,
|
|
76
|
+
poolDirectory?: string,
|
|
77
|
+
): Promise<AztecSQLiteOPFSStore> {
|
|
78
|
+
const dbName = name && !ephemeral ? name : `tmp-${globalThis.crypto.getRandomValues(new Uint8Array(8)).join('')}`;
|
|
79
|
+
log.debug(`Opening SQLite-OPFS ${ephemeral ? 'ephemeral ' : ''}database ${dbName}`);
|
|
80
|
+
const worker = new Worker(new URL('./worker.js', import.meta.url), { type: 'module' });
|
|
81
|
+
const store = new AztecSQLiteOPFSStore(worker, dbName, log, ephemeral);
|
|
82
|
+
await store.#sendRequest({ type: 'init', id: store.#allocId(), dbName, ephemeral, poolDirectory });
|
|
83
|
+
return store;
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
openMap<K extends Key, V extends Value>(name: string): AztecAsyncMap<K, V> {
|
|
87
|
+
return new SQLiteOPFSAztecMap<K, V>(this, name);
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
openSet<K extends Key>(name: string): AztecAsyncSet<K> {
|
|
91
|
+
return new SQLiteOPFSAztecSet<K>(this, name);
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
openMultiMap<K extends Key, V extends Value>(name: string): AztecAsyncMultiMap<K, V> {
|
|
95
|
+
return new SQLiteOPFSAztecMultiMap<K, V>(this, name);
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
openCounter<K extends Key>(_name: string): AztecAsyncCounter<K> {
|
|
99
|
+
throw new Error('Method not implemented.');
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
openArray<T extends Value>(name: string): AztecAsyncArray<T> {
|
|
103
|
+
return new SQLiteOPFSAztecArray<T>(this, name);
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
openSingleton<T extends Value>(name: string): AztecAsyncSingleton<T> {
|
|
107
|
+
return new SQLiteOPFSAztecSingleton<T>(this, name);
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
transactionAsync<T>(callback: () => Promise<T>): Promise<T> {
|
|
111
|
+
// Nested calls join the outer transaction — SQLite does not support nested BEGIN,
|
|
112
|
+
// and re-acquiring the SerialQueue while the outer call holds it would deadlock.
|
|
113
|
+
// Errors in the nested callback propagate to the outer catch, which rolls back the
|
|
114
|
+
// whole thing (the standard "nested tx = savepoint-free join" semantic).
|
|
115
|
+
if (this.#inTx) {
|
|
116
|
+
return callback();
|
|
117
|
+
}
|
|
118
|
+
return this.#txQueue.put(async () => {
|
|
119
|
+
this.#inTx = true;
|
|
120
|
+
await this.#sendRequest({ type: 'begin', id: this.#allocId() });
|
|
121
|
+
try {
|
|
122
|
+
const result = await callback();
|
|
123
|
+
await this.#sendRequest({ type: 'commit', id: this.#allocId() });
|
|
124
|
+
return result;
|
|
125
|
+
} catch (err) {
|
|
126
|
+
await this.#sendRequest({ type: 'rollback', id: this.#allocId() }).catch(rollbackErr =>
|
|
127
|
+
this.#log.warn(`SQLite ROLLBACK failed: ${rollbackErr instanceof Error ? rollbackErr.message : rollbackErr}`),
|
|
128
|
+
);
|
|
129
|
+
throw err;
|
|
130
|
+
} finally {
|
|
131
|
+
this.#inTx = false;
|
|
132
|
+
}
|
|
133
|
+
});
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
async clear(): Promise<void> {
|
|
137
|
+
await this.runAsync('DELETE FROM data');
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
async delete(): Promise<void> {
|
|
141
|
+
if (this.#closed) {
|
|
142
|
+
return;
|
|
143
|
+
}
|
|
144
|
+
this.#closed = true;
|
|
145
|
+
await this.#txQueue.end();
|
|
146
|
+
await this.#sendRequest({ type: 'deleteDb', id: this.#allocId(), dbName: this.#name }).catch(err =>
|
|
147
|
+
this.#log.warn(`SQLite deleteDb failed: ${err instanceof Error ? err.message : err}`),
|
|
148
|
+
);
|
|
149
|
+
this.#worker.terminate();
|
|
150
|
+
this.#rejectPending('SQLite store deleted');
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
/**
|
|
154
|
+
* Placeholder — returns zeros to mirror the IndexedDB backend. SQLite exposes real
|
|
155
|
+
* numbers cheaply via `PRAGMA page_count` / `page_size` / `freelist_count` and
|
|
156
|
+
* `SELECT COUNT(*) FROM data`, which would populate `physicalFileSize`, `actualSize`,
|
|
157
|
+
* and `numItems` meaningfully (`mappingSize` stays 0 — it's an LMDB mmap concept).
|
|
158
|
+
* Upgrade when any caller actually consumes these values; all current consumers
|
|
159
|
+
* tolerate zeros.
|
|
160
|
+
*/
|
|
161
|
+
estimateSize(): Promise<StoreSize> {
|
|
162
|
+
return Promise.resolve({ mappingSize: 0, physicalFileSize: 0, actualSize: 0, numItems: 0 });
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
async close(): Promise<void> {
|
|
166
|
+
if (this.#closed) {
|
|
167
|
+
return;
|
|
168
|
+
}
|
|
169
|
+
this.#closed = true;
|
|
170
|
+
await this.#txQueue.end();
|
|
171
|
+
await this.#sendRequest({ type: 'close', id: this.#allocId() }).catch(() => {});
|
|
172
|
+
this.#worker.terminate();
|
|
173
|
+
this.#rejectPending('SQLite store closed');
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
backupTo(_dstPath: string, _compact?: boolean): Promise<void> {
|
|
177
|
+
throw new Error('Method not implemented.');
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
/**
|
|
181
|
+
* Returns a raw SQLite image (bytes suitable for writing as a `.sqlite` file and
|
|
182
|
+
* opening in any SQLite tool). Works only for non-ephemeral DBs because the OPFS
|
|
183
|
+
* SAH Pool has to be initialized. Useful for inspection/debugging.
|
|
184
|
+
*/
|
|
185
|
+
async exportDb(): Promise<Uint8Array> {
|
|
186
|
+
const resp = await this.#sendRequest({ type: 'export', id: this.#allocId() });
|
|
187
|
+
if (!('bytes' in resp) || !resp.bytes) {
|
|
188
|
+
throw new Error('exportDb: worker returned no bytes');
|
|
189
|
+
}
|
|
190
|
+
return resp.bytes;
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
/**
|
|
194
|
+
* Runs a write statement (INSERT/UPDATE/DELETE/DDL). If called inside a
|
|
195
|
+
* `transactionAsync` block, bypasses the queue; otherwise acquires it so the
|
|
196
|
+
* op runs in its own auto-commit.
|
|
197
|
+
*/
|
|
198
|
+
runAsync(sql: string, bind?: SqlValue[]): Promise<{ changes: number }> {
|
|
199
|
+
const send = () =>
|
|
200
|
+
this.#sendRequest({ type: 'run', id: this.#allocId(), sql, bind }).then(r => ({
|
|
201
|
+
changes: 'changes' in r ? (r.changes ?? 0) : 0,
|
|
202
|
+
}));
|
|
203
|
+
return this.#inTx ? send() : this.#txQueue.put(send);
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
/** Runs a SELECT statement and returns rows in array row-mode. */
|
|
207
|
+
allAsync(sql: string, bind?: SqlValue[]): Promise<ResultRow[]> {
|
|
208
|
+
const send = () =>
|
|
209
|
+
this.#sendRequest({ type: 'all', id: this.#allocId(), sql, bind }).then(r => ('rows' in r ? (r.rows ?? []) : []));
|
|
210
|
+
return this.#inTx ? send() : this.#txQueue.put(send);
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
#allocId(): number {
|
|
214
|
+
return ++this.#nextId;
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
/**
|
|
218
|
+
* Reject any in-flight requests with `reason`, so callers awaiting a response to a
|
|
219
|
+
* request sent to a now-terminated worker don't hang forever. Called from
|
|
220
|
+
* close()/delete() and from the worker.onerror handler.
|
|
221
|
+
*/
|
|
222
|
+
#rejectPending(reason: string): void {
|
|
223
|
+
if (this.#pending.size === 0) {
|
|
224
|
+
return;
|
|
225
|
+
}
|
|
226
|
+
const err = new Error(reason);
|
|
227
|
+
for (const { reject } of this.#pending.values()) {
|
|
228
|
+
reject(err);
|
|
229
|
+
}
|
|
230
|
+
this.#pending.clear();
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
#sendRequest(req: WorkerRequest): Promise<WorkerResponse> {
|
|
234
|
+
return new Promise<WorkerResponse>((resolve, reject) => {
|
|
235
|
+
this.#pending.set(req.id, {
|
|
236
|
+
resolve: resp => {
|
|
237
|
+
if (resp.type === 'err') {
|
|
238
|
+
reject(new Error(resp.message));
|
|
239
|
+
} else {
|
|
240
|
+
resolve(resp);
|
|
241
|
+
}
|
|
242
|
+
},
|
|
243
|
+
reject,
|
|
244
|
+
});
|
|
245
|
+
this.#worker.postMessage(req);
|
|
246
|
+
});
|
|
247
|
+
}
|
|
248
|
+
}
|
|
@@ -0,0 +1,162 @@
|
|
|
1
|
+
/// <reference lib="webworker" />
|
|
2
|
+
import sqlite3InitModule, { type Database, type SAHPoolUtil, type Sqlite3Static } from '@sqlite.org/sqlite-wasm';
|
|
3
|
+
|
|
4
|
+
import type { ResultRow, SqlValue, WorkerRequest, WorkerResponse } from './messages.js';
|
|
5
|
+
|
|
6
|
+
const SCHEMA_SQL = `
|
|
7
|
+
CREATE TABLE IF NOT EXISTS data (
|
|
8
|
+
slot TEXT NOT NULL PRIMARY KEY,
|
|
9
|
+
container TEXT NOT NULL,
|
|
10
|
+
key BLOB NOT NULL,
|
|
11
|
+
key_count INTEGER NOT NULL,
|
|
12
|
+
hash TEXT NOT NULL,
|
|
13
|
+
value BLOB
|
|
14
|
+
) WITHOUT ROWID;
|
|
15
|
+
|
|
16
|
+
CREATE INDEX IF NOT EXISTS idx_container_key ON data(container, key);
|
|
17
|
+
CREATE UNIQUE INDEX IF NOT EXISTS idx_container_key_count ON data(container, key, key_count);
|
|
18
|
+
CREATE UNIQUE INDEX IF NOT EXISTS idx_container_key_hash ON data(container, key, hash);
|
|
19
|
+
`;
|
|
20
|
+
|
|
21
|
+
const DEFAULT_SAH_POOL_DIRECTORY = '.aztec-kv';
|
|
22
|
+
const SAH_POOL_VFS_NAME = 'aztec-kv-opfs';
|
|
23
|
+
|
|
24
|
+
let sqlite3: Sqlite3Static | undefined;
|
|
25
|
+
let pool: SAHPoolUtil | undefined;
|
|
26
|
+
let db: Database | undefined;
|
|
27
|
+
let dbPath: string | undefined;
|
|
28
|
+
|
|
29
|
+
async function ensurePool(directory: string): Promise<SAHPoolUtil> {
|
|
30
|
+
sqlite3 ??= await sqlite3InitModule();
|
|
31
|
+
if (!pool) {
|
|
32
|
+
pool = await sqlite3.installOpfsSAHPoolVfs({
|
|
33
|
+
name: SAH_POOL_VFS_NAME,
|
|
34
|
+
directory,
|
|
35
|
+
initialCapacity: 8,
|
|
36
|
+
});
|
|
37
|
+
}
|
|
38
|
+
return pool;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
async function handleInit(dbName: string, ephemeral: boolean, directory?: string): Promise<void> {
|
|
42
|
+
sqlite3 ??= await sqlite3InitModule();
|
|
43
|
+
if (ephemeral) {
|
|
44
|
+
db = new sqlite3.oo1.DB(':memory:', 'c');
|
|
45
|
+
} else {
|
|
46
|
+
const p = await ensurePool(directory ?? DEFAULT_SAH_POOL_DIRECTORY);
|
|
47
|
+
dbPath = normalizeDbPath(dbName);
|
|
48
|
+
db = new p.OpfsSAHPoolDb(dbPath);
|
|
49
|
+
}
|
|
50
|
+
runSql(SCHEMA_SQL);
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
function handleClose(): void {
|
|
54
|
+
db?.close();
|
|
55
|
+
db = undefined;
|
|
56
|
+
dbPath = undefined;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
async function handleExport(): Promise<Uint8Array> {
|
|
60
|
+
if (!db || !dbPath) {
|
|
61
|
+
throw new Error('SQLite worker: no database open to export');
|
|
62
|
+
}
|
|
63
|
+
if (!pool) {
|
|
64
|
+
throw new Error('SQLite worker: no SAH Pool available (ephemeral DBs cannot be exported)');
|
|
65
|
+
}
|
|
66
|
+
return await pool.exportFile(dbPath);
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
function handleDeleteDb(dbName: string): void {
|
|
70
|
+
const path = normalizeDbPath(dbName);
|
|
71
|
+
if (db && dbPath === path) {
|
|
72
|
+
db.close();
|
|
73
|
+
db = undefined;
|
|
74
|
+
dbPath = undefined;
|
|
75
|
+
}
|
|
76
|
+
// Ephemeral :memory: DBs never back a file — skip installing a pool just to unlink
|
|
77
|
+
// nothing. installOpfsSAHPoolVfs acquires an exclusive lock on the OPFS SAH
|
|
78
|
+
// directory, and under heavy test churn that can contend with workers from
|
|
79
|
+
// previous tests whose OPFS handles Chromium hasn't yet released, hanging the RPC
|
|
80
|
+
// and then the whole test run.
|
|
81
|
+
if (!pool) {
|
|
82
|
+
return;
|
|
83
|
+
}
|
|
84
|
+
try {
|
|
85
|
+
pool.unlink(path);
|
|
86
|
+
} catch {
|
|
87
|
+
// File may not exist; ignore.
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
function requireDb(): Database {
|
|
92
|
+
if (!db) {
|
|
93
|
+
throw new Error('SQLite worker: no database open');
|
|
94
|
+
}
|
|
95
|
+
return db;
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
function runSql(sql: string, bind?: SqlValue[]): { changes: number } {
|
|
99
|
+
const conn = requireDb();
|
|
100
|
+
conn.exec({ sql, bind });
|
|
101
|
+
return { changes: conn.changes() };
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
function selectAll(sql: string, bind?: SqlValue[]): ResultRow[] {
|
|
105
|
+
const conn = requireDb();
|
|
106
|
+
const rows: ResultRow[] = [];
|
|
107
|
+
conn.exec({ sql, bind, rowMode: 'array', resultRows: rows });
|
|
108
|
+
return rows;
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
function normalizeDbPath(dbName: string): string {
|
|
112
|
+
return dbName.startsWith('/') ? dbName : `/${dbName}`;
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
function respond(msg: WorkerResponse): void {
|
|
116
|
+
(self as DedicatedWorkerGlobalScope).postMessage(msg);
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
(self as DedicatedWorkerGlobalScope).onmessage = async (ev: MessageEvent<WorkerRequest>) => {
|
|
120
|
+
const req = ev.data;
|
|
121
|
+
try {
|
|
122
|
+
switch (req.type) {
|
|
123
|
+
case 'init':
|
|
124
|
+
await handleInit(req.dbName, req.ephemeral, req.poolDirectory);
|
|
125
|
+
return respond({ type: 'ok', id: req.id });
|
|
126
|
+
case 'close':
|
|
127
|
+
handleClose();
|
|
128
|
+
return respond({ type: 'ok', id: req.id });
|
|
129
|
+
case 'deleteDb':
|
|
130
|
+
handleDeleteDb(req.dbName);
|
|
131
|
+
return respond({ type: 'ok', id: req.id });
|
|
132
|
+
case 'run': {
|
|
133
|
+
const { changes } = runSql(req.sql, req.bind);
|
|
134
|
+
return respond({ type: 'ok', id: req.id, changes });
|
|
135
|
+
}
|
|
136
|
+
case 'all': {
|
|
137
|
+
const rows = selectAll(req.sql, req.bind);
|
|
138
|
+
return respond({ type: 'ok', id: req.id, rows });
|
|
139
|
+
}
|
|
140
|
+
case 'export': {
|
|
141
|
+
const bytes = await handleExport();
|
|
142
|
+
return respond({ type: 'ok', id: req.id, bytes });
|
|
143
|
+
}
|
|
144
|
+
case 'begin':
|
|
145
|
+
runSql('BEGIN');
|
|
146
|
+
return respond({ type: 'ok', id: req.id });
|
|
147
|
+
case 'commit':
|
|
148
|
+
runSql('COMMIT');
|
|
149
|
+
return respond({ type: 'ok', id: req.id });
|
|
150
|
+
case 'rollback':
|
|
151
|
+
runSql('ROLLBACK');
|
|
152
|
+
return respond({ type: 'ok', id: req.id });
|
|
153
|
+
default: {
|
|
154
|
+
const _exhaustive: never = req;
|
|
155
|
+
throw new Error(`Unknown request: ${JSON.stringify(_exhaustive)}`);
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
} catch (err) {
|
|
159
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
160
|
+
respond({ type: 'err', id: req.id, message });
|
|
161
|
+
}
|
|
162
|
+
};
|
package/src/utils.ts
CHANGED
|
@@ -33,7 +33,14 @@ export async function initStoreForRollupAndSchemaVersion<T extends AztecKVStore
|
|
|
33
33
|
? (dbVersion as AztecSingleton<string>).get()
|
|
34
34
|
: await (dbVersion as AztecAsyncSingleton<string>).getAsync();
|
|
35
35
|
|
|
36
|
+
// Check if this is an old format store (has rollupAddress singleton but no dbVersion)
|
|
37
|
+
const oldRollupSingleton = store.openSingleton<string>('rollupAddress');
|
|
38
|
+
const hasOldFormat = isSyncStore(store)
|
|
39
|
+
? !storedDatabaseVersion && !!(oldRollupSingleton as AztecSingleton<string>).get()
|
|
40
|
+
: !storedDatabaseVersion && !!(await (oldRollupSingleton as AztecAsyncSingleton<string>).getAsync());
|
|
41
|
+
|
|
36
42
|
if (
|
|
43
|
+
hasOldFormat ||
|
|
37
44
|
doesStoreNeedToBeCleared(
|
|
38
45
|
targetDatabaseVersion,
|
|
39
46
|
storedDatabaseVersion,
|
|
@@ -42,6 +49,9 @@ export async function initStoreForRollupAndSchemaVersion<T extends AztecKVStore
|
|
|
42
49
|
log,
|
|
43
50
|
)
|
|
44
51
|
) {
|
|
52
|
+
if (hasOldFormat) {
|
|
53
|
+
log?.warn('Detected old store format without dbVersion, clearing database');
|
|
54
|
+
}
|
|
45
55
|
await store.clear();
|
|
46
56
|
}
|
|
47
57
|
|
package/dest/config.d.ts
DELETED
|
@@ -1,17 +0,0 @@
|
|
|
1
|
-
import { type ConfigMappingsType } from '@aztec/foundation/config';
|
|
2
|
-
import type { EthAddress } from '@aztec/foundation/eth-address';
|
|
3
|
-
export type DataStoreConfig = {
|
|
4
|
-
dataDirectory: string | undefined;
|
|
5
|
-
dataStoreMapSizeKb: number;
|
|
6
|
-
l1Contracts?: {
|
|
7
|
-
rollupAddress: EthAddress;
|
|
8
|
-
};
|
|
9
|
-
};
|
|
10
|
-
export declare const dataConfigMappings: ConfigMappingsType<DataStoreConfig>;
|
|
11
|
-
/**
|
|
12
|
-
* Returns the archiver configuration from the environment variables.
|
|
13
|
-
* Note: If an environment variable is not set, the default value is used.
|
|
14
|
-
* @returns The archiver configuration.
|
|
15
|
-
*/
|
|
16
|
-
export declare function getDataConfigFromEnv(): DataStoreConfig;
|
|
17
|
-
//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiY29uZmlnLmQudHMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyIuLi9zcmMvY29uZmlnLnRzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiJBQUNBLE9BQU8sRUFBRSxLQUFLLGtCQUFrQixFQUE2QyxNQUFNLDBCQUEwQixDQUFDO0FBQzlHLE9BQU8sS0FBSyxFQUFFLFVBQVUsRUFBRSxNQUFNLCtCQUErQixDQUFDO0FBRWhFLE1BQU0sTUFBTSxlQUFlLEdBQUc7SUFDNUIsYUFBYSxFQUFFLE1BQU0sR0FBRyxTQUFTLENBQUM7SUFDbEMsa0JBQWtCLEVBQUUsTUFBTSxDQUFDO0lBQzNCLFdBQVcsQ0FBQyxFQUFFO1FBQUUsYUFBYSxFQUFFLFVBQVUsQ0FBQTtLQUFFLENBQUM7Q0FDN0MsQ0FBQztBQUVGLGVBQU8sTUFBTSxrQkFBa0IsRUFBRSxrQkFBa0IsQ0FBQyxlQUFlLENBZ0JsRSxDQUFDO0FBRUY7Ozs7R0FJRztBQUNILHdCQUFnQixvQkFBb0IsSUFBSSxlQUFlLENBRXREIn0=
|
package/dest/config.d.ts.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"config.d.ts","sourceRoot":"","sources":["../src/config.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,KAAK,kBAAkB,EAA6C,MAAM,0BAA0B,CAAC;AAC9G,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,+BAA+B,CAAC;AAEhE,MAAM,MAAM,eAAe,GAAG;IAC5B,aAAa,EAAE,MAAM,GAAG,SAAS,CAAC;IAClC,kBAAkB,EAAE,MAAM,CAAC;IAC3B,WAAW,CAAC,EAAE;QAAE,aAAa,EAAE,UAAU,CAAA;KAAE,CAAC;CAC7C,CAAC;AAEF,eAAO,MAAM,kBAAkB,EAAE,kBAAkB,CAAC,eAAe,CAgBlE,CAAC;AAEF;;;;GAIG;AACH,wBAAgB,oBAAoB,IAAI,eAAe,CAEtD"}
|
package/dest/config.js
DELETED
|
@@ -1,26 +0,0 @@
|
|
|
1
|
-
import { l1ContractAddressesMapping } from '@aztec/ethereum/l1-contract-addresses';
|
|
2
|
-
import { getConfigFromMappings, numberConfigHelper } from '@aztec/foundation/config';
|
|
3
|
-
export const dataConfigMappings = {
|
|
4
|
-
dataDirectory: {
|
|
5
|
-
env: 'DATA_DIRECTORY',
|
|
6
|
-
description: 'Optional dir to store data. If omitted will store in memory.'
|
|
7
|
-
},
|
|
8
|
-
dataStoreMapSizeKb: {
|
|
9
|
-
env: 'DATA_STORE_MAP_SIZE_KB',
|
|
10
|
-
description: 'The maximum possible size of a data store DB in KB. Can be overridden by component-specific options.',
|
|
11
|
-
...numberConfigHelper(128 * 1_024 * 1_024)
|
|
12
|
-
},
|
|
13
|
-
l1Contracts: {
|
|
14
|
-
description: 'The deployed L1 contract addresses',
|
|
15
|
-
nested: {
|
|
16
|
-
rollupAddress: l1ContractAddressesMapping.rollupAddress
|
|
17
|
-
}
|
|
18
|
-
}
|
|
19
|
-
};
|
|
20
|
-
/**
|
|
21
|
-
* Returns the archiver configuration from the environment variables.
|
|
22
|
-
* Note: If an environment variable is not set, the default value is used.
|
|
23
|
-
* @returns The archiver configuration.
|
|
24
|
-
*/ export function getDataConfigFromEnv() {
|
|
25
|
-
return getConfigFromMappings(dataConfigMappings);
|
|
26
|
-
}
|
package/src/config.ts
DELETED
|
@@ -1,36 +0,0 @@
|
|
|
1
|
-
import { l1ContractAddressesMapping } from '@aztec/ethereum/l1-contract-addresses';
|
|
2
|
-
import { type ConfigMappingsType, getConfigFromMappings, numberConfigHelper } from '@aztec/foundation/config';
|
|
3
|
-
import type { EthAddress } from '@aztec/foundation/eth-address';
|
|
4
|
-
|
|
5
|
-
export type DataStoreConfig = {
|
|
6
|
-
dataDirectory: string | undefined;
|
|
7
|
-
dataStoreMapSizeKb: number;
|
|
8
|
-
l1Contracts?: { rollupAddress: EthAddress };
|
|
9
|
-
};
|
|
10
|
-
|
|
11
|
-
export const dataConfigMappings: ConfigMappingsType<DataStoreConfig> = {
|
|
12
|
-
dataDirectory: {
|
|
13
|
-
env: 'DATA_DIRECTORY',
|
|
14
|
-
description: 'Optional dir to store data. If omitted will store in memory.',
|
|
15
|
-
},
|
|
16
|
-
dataStoreMapSizeKb: {
|
|
17
|
-
env: 'DATA_STORE_MAP_SIZE_KB',
|
|
18
|
-
description: 'The maximum possible size of a data store DB in KB. Can be overridden by component-specific options.',
|
|
19
|
-
...numberConfigHelper(128 * 1_024 * 1_024), // Defaulted to 128 GB
|
|
20
|
-
},
|
|
21
|
-
l1Contracts: {
|
|
22
|
-
description: 'The deployed L1 contract addresses',
|
|
23
|
-
nested: {
|
|
24
|
-
rollupAddress: l1ContractAddressesMapping.rollupAddress,
|
|
25
|
-
},
|
|
26
|
-
},
|
|
27
|
-
};
|
|
28
|
-
|
|
29
|
-
/**
|
|
30
|
-
* Returns the archiver configuration from the environment variables.
|
|
31
|
-
* Note: If an environment variable is not set, the default value is used.
|
|
32
|
-
* @returns The archiver configuration.
|
|
33
|
-
*/
|
|
34
|
-
export function getDataConfigFromEnv(): DataStoreConfig {
|
|
35
|
-
return getConfigFromMappings<DataStoreConfig>(dataConfigMappings);
|
|
36
|
-
}
|