@aztec/kv-store 0.0.1-commit.e588bc7e5 → 0.0.1-commit.e5a3663dd

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 (43) 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/lmdb-v2/read_transaction.js +21 -19
  5. package/dest/sqlite-opfs/array.d.ts +21 -0
  6. package/dest/sqlite-opfs/array.d.ts.map +1 -0
  7. package/dest/sqlite-opfs/array.js +128 -0
  8. package/dest/sqlite-opfs/index.d.ts +14 -0
  9. package/dest/sqlite-opfs/index.d.ts.map +1 -0
  10. package/dest/sqlite-opfs/index.js +21 -0
  11. package/dest/sqlite-opfs/map.d.ts +35 -0
  12. package/dest/sqlite-opfs/map.d.ts.map +1 -0
  13. package/dest/sqlite-opfs/map.js +163 -0
  14. package/dest/sqlite-opfs/messages.d.ts +59 -0
  15. package/dest/sqlite-opfs/messages.d.ts.map +1 -0
  16. package/dest/sqlite-opfs/messages.js +5 -0
  17. package/dest/sqlite-opfs/multi_map.d.ts +16 -0
  18. package/dest/sqlite-opfs/multi_map.d.ts.map +1 -0
  19. package/dest/sqlite-opfs/multi_map.js +67 -0
  20. package/dest/sqlite-opfs/set.d.ts +13 -0
  21. package/dest/sqlite-opfs/set.d.ts.map +1 -0
  22. package/dest/sqlite-opfs/set.js +19 -0
  23. package/dest/sqlite-opfs/singleton.d.ts +13 -0
  24. package/dest/sqlite-opfs/singleton.d.ts.map +1 -0
  25. package/dest/sqlite-opfs/singleton.js +48 -0
  26. package/dest/sqlite-opfs/store.d.ts +79 -0
  27. package/dest/sqlite-opfs/store.d.ts.map +1 -0
  28. package/dest/sqlite-opfs/store.js +273 -0
  29. package/dest/sqlite-opfs/worker.d.ts +2 -0
  30. package/dest/sqlite-opfs/worker.d.ts.map +1 -0
  31. package/dest/sqlite-opfs/worker.js +225 -0
  32. package/package.json +10 -7
  33. package/src/bench/shared_map_bench.ts +111 -0
  34. package/src/lmdb-v2/read_transaction.ts +23 -23
  35. package/src/sqlite-opfs/array.ts +124 -0
  36. package/src/sqlite-opfs/index.ts +37 -0
  37. package/src/sqlite-opfs/map.ts +163 -0
  38. package/src/sqlite-opfs/messages.ts +28 -0
  39. package/src/sqlite-opfs/multi_map.ts +74 -0
  40. package/src/sqlite-opfs/set.ts +29 -0
  41. package/src/sqlite-opfs/singleton.ts +48 -0
  42. package/src/sqlite-opfs/store.ts +282 -0
  43. package/src/sqlite-opfs/worker.ts +199 -0
@@ -0,0 +1,225 @@
1
+ /// <reference lib="webworker" />
2
+ import sqlite3InitModule from '@aztec/sqlite3mc-wasm';
3
+ const SCHEMA_SQL = `
4
+ CREATE TABLE IF NOT EXISTS data (
5
+ slot TEXT NOT NULL PRIMARY KEY,
6
+ container TEXT NOT NULL,
7
+ key BLOB NOT NULL,
8
+ key_count INTEGER NOT NULL,
9
+ hash TEXT NOT NULL,
10
+ value BLOB
11
+ ) WITHOUT ROWID;
12
+
13
+ CREATE INDEX IF NOT EXISTS idx_container_key ON data(container, key);
14
+ CREATE UNIQUE INDEX IF NOT EXISTS idx_container_key_count ON data(container, key, key_count);
15
+ CREATE UNIQUE INDEX IF NOT EXISTS idx_container_key_hash ON data(container, key, hash);
16
+ `;
17
+ const DEFAULT_SAH_POOL_DIRECTORY = '.aztec-kv';
18
+ const SAH_POOL_VFS_NAME = 'aztec-kv-opfs';
19
+ const MC_SAH_POOL_VFS_NAME = `multipleciphers-${SAH_POOL_VFS_NAME}`;
20
+ let sqlite3;
21
+ let pool;
22
+ let db;
23
+ let dbPath;
24
+ async function ensurePool(directory) {
25
+ sqlite3 ??= await sqlite3InitModule();
26
+ const s = sqlite3;
27
+ if (!pool) {
28
+ pool = await s.installOpfsSAHPoolVfs({
29
+ name: SAH_POOL_VFS_NAME,
30
+ directory,
31
+ initialCapacity: 8
32
+ });
33
+ // Register a sqlite3mc-wrapped VFS pointing at our SAH Pool VFS.
34
+ // Encrypted DBs must be opened through this wrapper so sqlite3mc can
35
+ // intercept file I/O; plain DBs continue using the SAH Pool VFS directly.
36
+ // The wrapper name is `multipleciphers-<underlying>`.
37
+ s.capi.sqlite3mc_vfs_create(SAH_POOL_VFS_NAME, 0);
38
+ }
39
+ return pool;
40
+ }
41
+ /**
42
+ * Applies sqlite3mc's ChaCha20 page cipher using a pre-derived 32-byte key.
43
+ * The PRAGMAs must run before any schema DDL so sqlite3mc can decrypt existing
44
+ * pages and encrypt new ones. Zeroes the caller-held key array after the PRAGMA
45
+ * completes to minimize residency of the raw key bytes outside sqlite3mc's heap.
46
+ */ function applyEncryptionKey(conn, key) {
47
+ const hex = Array.from(key, (b)=>b.toString(16).padStart(2, '0')).join('');
48
+ conn.exec(`PRAGMA cipher = 'chacha20'`);
49
+ conn.exec(`PRAGMA key = "x'${hex}'"`);
50
+ key.fill(0);
51
+ }
52
+ async function handleInit(dbName, ephemeral, directory, encryptionKey) {
53
+ sqlite3 ??= await sqlite3InitModule();
54
+ const s = sqlite3;
55
+ if (encryptionKey !== undefined && ephemeral) {
56
+ throw new Error('encryptionKey is not supported for ephemeral (:memory:) stores');
57
+ }
58
+ if (ephemeral) {
59
+ db = new s.oo1.DB(':memory:', 'c');
60
+ } else {
61
+ await ensurePool(directory ?? DEFAULT_SAH_POOL_DIRECTORY);
62
+ dbPath = normalizeDbPath(dbName);
63
+ if (encryptionKey !== undefined) {
64
+ db = new s.oo1.DB({
65
+ filename: dbPath,
66
+ flags: 'c',
67
+ vfs: MC_SAH_POOL_VFS_NAME
68
+ });
69
+ applyEncryptionKey(db, encryptionKey);
70
+ } else {
71
+ db = new pool.OpfsSAHPoolDb(dbPath);
72
+ }
73
+ }
74
+ runSql(SCHEMA_SQL);
75
+ }
76
+ function handleClose() {
77
+ db?.close();
78
+ db = undefined;
79
+ dbPath = undefined;
80
+ }
81
+ async function handleExport() {
82
+ if (!db || !dbPath) {
83
+ throw new Error('SQLite worker: no database open to export');
84
+ }
85
+ if (!pool) {
86
+ throw new Error('SQLite worker: no SAH Pool available (ephemeral DBs cannot be exported)');
87
+ }
88
+ return await pool.exportFile(dbPath);
89
+ }
90
+ function handleDeleteDb(dbName) {
91
+ const path = normalizeDbPath(dbName);
92
+ if (db && dbPath === path) {
93
+ db.close();
94
+ db = undefined;
95
+ dbPath = undefined;
96
+ }
97
+ // Ephemeral :memory: DBs never back a file — skip installing a pool just to unlink
98
+ // nothing. installOpfsSAHPoolVfs acquires an exclusive lock on the OPFS SAH
99
+ // directory, and under heavy test churn that can contend with workers from
100
+ // previous tests whose OPFS handles Chromium hasn't yet released, hanging the RPC
101
+ // and then the whole test run.
102
+ if (!pool) {
103
+ return;
104
+ }
105
+ try {
106
+ pool.unlink(path);
107
+ } catch {
108
+ // File may not exist; ignore.
109
+ }
110
+ }
111
+ function requireDb() {
112
+ if (!db) {
113
+ throw new Error('SQLite worker: no database open');
114
+ }
115
+ return db;
116
+ }
117
+ function runSql(sql, bind) {
118
+ const conn = requireDb();
119
+ conn.exec({
120
+ sql,
121
+ bind
122
+ });
123
+ return {
124
+ changes: conn.changes()
125
+ };
126
+ }
127
+ function selectAll(sql, bind) {
128
+ const conn = requireDb();
129
+ const rows = [];
130
+ conn.exec({
131
+ sql,
132
+ bind,
133
+ rowMode: 'array',
134
+ resultRows: rows
135
+ });
136
+ return rows;
137
+ }
138
+ function normalizeDbPath(dbName) {
139
+ return dbName.startsWith('/') ? dbName : `/${dbName}`;
140
+ }
141
+ function respond(msg) {
142
+ self.postMessage(msg);
143
+ }
144
+ self.onmessage = async (ev)=>{
145
+ const req = ev.data;
146
+ try {
147
+ switch(req.type){
148
+ case 'init':
149
+ await handleInit(req.dbName, req.ephemeral, req.poolDirectory, req.encryptionKey);
150
+ return respond({
151
+ type: 'ok',
152
+ id: req.id
153
+ });
154
+ case 'close':
155
+ handleClose();
156
+ return respond({
157
+ type: 'ok',
158
+ id: req.id
159
+ });
160
+ case 'deleteDb':
161
+ handleDeleteDb(req.dbName);
162
+ return respond({
163
+ type: 'ok',
164
+ id: req.id
165
+ });
166
+ case 'run':
167
+ {
168
+ const { changes } = runSql(req.sql, req.bind);
169
+ return respond({
170
+ type: 'ok',
171
+ id: req.id,
172
+ changes
173
+ });
174
+ }
175
+ case 'all':
176
+ {
177
+ const rows = selectAll(req.sql, req.bind);
178
+ return respond({
179
+ type: 'ok',
180
+ id: req.id,
181
+ rows
182
+ });
183
+ }
184
+ case 'export':
185
+ {
186
+ const bytes = await handleExport();
187
+ return respond({
188
+ type: 'ok',
189
+ id: req.id,
190
+ bytes
191
+ });
192
+ }
193
+ case 'begin':
194
+ runSql('BEGIN');
195
+ return respond({
196
+ type: 'ok',
197
+ id: req.id
198
+ });
199
+ case 'commit':
200
+ runSql('COMMIT');
201
+ return respond({
202
+ type: 'ok',
203
+ id: req.id
204
+ });
205
+ case 'rollback':
206
+ runSql('ROLLBACK');
207
+ return respond({
208
+ type: 'ok',
209
+ id: req.id
210
+ });
211
+ default:
212
+ {
213
+ const _exhaustive = req;
214
+ throw new Error(`Unknown request: ${JSON.stringify(_exhaustive)}`);
215
+ }
216
+ }
217
+ } catch (err) {
218
+ const message = err instanceof Error ? err.message : String(err);
219
+ respond({
220
+ type: 'err',
221
+ id: req.id,
222
+ message
223
+ });
224
+ }
225
+ };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@aztec/kv-store",
3
- "version": "0.0.1-commit.e588bc7e5",
3
+ "version": "0.0.1-commit.e5a3663dd",
4
4
  "type": "module",
5
5
  "exports": {
6
6
  ".": "./dest/interfaces/index.js",
@@ -8,6 +8,7 @@
8
8
  "./lmdb": "./dest/lmdb/index.js",
9
9
  "./lmdb-v2": "./dest/lmdb-v2/index.js",
10
10
  "./indexeddb": "./dest/indexeddb/index.js",
11
+ "./sqlite-opfs": "./dest/sqlite-opfs/index.js",
11
12
  "./stores": "./dest/stores/index.js"
12
13
  },
13
14
  "scripts": {
@@ -15,7 +16,8 @@
15
16
  "build:dev": "../scripts/tsc.sh --watch",
16
17
  "clean": "rm -rf ./dest .tsbuildinfo",
17
18
  "test:node": "NODE_NO_WARNINGS=1 mocha --config ./.mocharc.json",
18
- "test:browser": "vitest run --config ./vitest.config.ts",
19
+ "test:browser": "bash scripts/run-browser-tests.sh",
20
+ "bench:browser": "VITE_BENCH=1 vitest run --config ./vitest.config.ts src/bench",
19
21
  "test": "yarn test:node && yarn test:browser",
20
22
  "test:jest": "NODE_NO_WARNINGS=1 node --experimental-vm-modules ../node_modules/.bin/jest --passWithNoTests --maxWorkers=${JEST_MAX_WORKERS:-8}"
21
23
  },
@@ -24,11 +26,12 @@
24
26
  "./package.local.json"
25
27
  ],
26
28
  "dependencies": {
27
- "@aztec/constants": "0.0.1-commit.e588bc7e5",
28
- "@aztec/ethereum": "0.0.1-commit.e588bc7e5",
29
- "@aztec/foundation": "0.0.1-commit.e588bc7e5",
30
- "@aztec/native": "0.0.1-commit.e588bc7e5",
31
- "@aztec/stdlib": "0.0.1-commit.e588bc7e5",
29
+ "@aztec/constants": "0.0.1-commit.e5a3663dd",
30
+ "@aztec/ethereum": "0.0.1-commit.e5a3663dd",
31
+ "@aztec/foundation": "0.0.1-commit.e5a3663dd",
32
+ "@aztec/native": "0.0.1-commit.e5a3663dd",
33
+ "@aztec/sqlite3mc-wasm": "0.0.1-commit.e5a3663dd",
34
+ "@aztec/stdlib": "0.0.1-commit.e5a3663dd",
32
35
  "idb": "^8.0.0",
33
36
  "lmdb": "^3.2.0",
34
37
  "msgpackr": "^1.11.2",
@@ -0,0 +1,111 @@
1
+ import type { Logger } from '@aztec/foundation/log';
2
+ import { Timer } from '@aztec/foundation/timer';
3
+
4
+ import type { Key } from '../interfaces/common.js';
5
+ import type { AztecAsyncMap } from '../interfaces/map.js';
6
+ import type { AztecAsyncKVStore } from '../interfaces/store.js';
7
+
8
+ /** One benchmark measurement. */
9
+ export type BenchResult = {
10
+ /** Benchmark name (includes the backend prefix for disambiguation). */
11
+ name: string;
12
+ value: number;
13
+ unit: 'ms' | 'us';
14
+ };
15
+
16
+ export type BenchReporter = (results: BenchResult[]) => void | Promise<void>;
17
+
18
+ /**
19
+ * Runs the standard Map benchmark suite against any `AztecAsyncKVStore` backend,
20
+ * populates `results`, and calls `reporter` in `afterAll`.
21
+ *
22
+ * Kept free of Node-only deps (`fs`, `path`) so the same runner works under
23
+ * vitest-browser for IndexedDB and SQLite-OPFS.
24
+ */
25
+ export function describeAztecMapBench(
26
+ backendPrefix: string,
27
+ getStore: () => Promise<AztecAsyncKVStore>,
28
+ logger: Logger,
29
+ reporter: BenchReporter,
30
+ ) {
31
+ describe(`${backendPrefix} Map benchmarks`, () => {
32
+ let store: AztecAsyncKVStore;
33
+ let map: AztecAsyncMap<Key, string>;
34
+
35
+ const results: BenchResult[] = [];
36
+
37
+ const generateKeyValuePairs = (count: number, offset = 0) => {
38
+ const keys = Array.from({ length: count }, (_, i) => `key-${i + offset}`);
39
+ const values = Array.from({ length: count }, (_, i) => `value-${i + offset}`);
40
+ return keys.map((key, i) => ({ key, value: values[i] }));
41
+ };
42
+
43
+ const record = (name: string, value: number, unit: BenchResult['unit']) => {
44
+ results.push({ name: `${backendPrefix}/Map/${name}`, value, unit });
45
+ };
46
+
47
+ beforeEach(async () => {
48
+ store = await getStore();
49
+ map = store.openMap<Key, string>('test');
50
+ });
51
+
52
+ afterEach(async () => {
53
+ await store.delete();
54
+ });
55
+
56
+ afterAll(async () => {
57
+ const pretty = results.map(r => `${r.name}: ${r.value.toFixed(2)} ${r.unit}`).join('\n');
58
+ logger.info(`\n${pretty}\n`);
59
+ await reporter(results);
60
+ });
61
+
62
+ it('adds individual values', async () => {
63
+ const pairs = generateKeyValuePairs(1000);
64
+ const timer = new Timer();
65
+ for (const pair of pairs) {
66
+ await map.set(pair.key, pair.value);
67
+ }
68
+ record('Individual insertion', timer.ms() / pairs.length, 'ms');
69
+ });
70
+
71
+ it('adds batched values', async () => {
72
+ const batches = Array.from({ length: 100 }, (_, i) => generateKeyValuePairs(1000, i * 1000));
73
+ const timer = new Timer();
74
+ for (const batch of batches) {
75
+ await map.setMany(batch);
76
+ }
77
+ record(`Batch insertion of ${batches[0].length} items`, timer.ms() / batches.length, 'ms');
78
+ });
79
+
80
+ it('reads individual values', async () => {
81
+ const pairs = generateKeyValuePairs(10000);
82
+ await map.setMany(pairs);
83
+ const timer = new Timer();
84
+ for (const pair of pairs) {
85
+ await map.getAsync(pair.key);
86
+ }
87
+ record('Individual read', (timer.ms() * 1000) / pairs.length, 'us');
88
+ });
89
+
90
+ it('reads via a cursor', async () => {
91
+ const pairs = generateKeyValuePairs(10000);
92
+ await map.setMany(pairs);
93
+ const timer = new Timer();
94
+ for await (const _ of map.entriesAsync()) {
95
+ // consume
96
+ }
97
+ record(`Iterator per item read of ${pairs.length} items`, (timer.ms() * 1000) / pairs.length, 'us');
98
+ });
99
+
100
+ it('reads the size of the map', async () => {
101
+ const numIterations = 1000;
102
+ const pairs = generateKeyValuePairs(10000);
103
+ await map.setMany(pairs);
104
+ const timer = new Timer();
105
+ for (let i = 0; i < numIterations; i++) {
106
+ await map.sizeAsync();
107
+ }
108
+ record(`Read size of ${pairs.length} items`, (timer.ms() * 1000) / numIterations, 'us');
109
+ });
110
+ });
111
+ }
@@ -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
  }
@@ -0,0 +1,124 @@
1
+ import { Encoder } from 'msgpackr';
2
+ import { hash } from 'ohash';
3
+ import { toBufferKey } from 'ordered-binary';
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,37 @@
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
+
9
+ export async function createStore(
10
+ name: string,
11
+ config: DataStoreConfig,
12
+ schemaVersion: number | undefined = undefined,
13
+ log: Logger = createLogger('kv-store'),
14
+ ) {
15
+ const { dataDirectory } = config;
16
+ log.info(
17
+ dataDirectory
18
+ ? `Creating ${name} SQLite-OPFS data store with map size ${config.dataStoreMapSizeKb} KB`
19
+ : `Creating ${name} ephemeral SQLite-OPFS data store with map size ${config.dataStoreMapSizeKb} KB`,
20
+ );
21
+ const store = await AztecSQLiteOPFSStore.open(createLogger('kv-store:sqlite-opfs'), name, false);
22
+ return initStoreForRollupAndSchemaVersion(store, schemaVersion, config.l1Contracts?.rollupAddress, log);
23
+ }
24
+
25
+ export function openTmpStore(ephemeral: boolean = false): Promise<AztecSQLiteOPFSStore> {
26
+ return AztecSQLiteOPFSStore.open(createLogger('kv-store:sqlite-opfs'), undefined, ephemeral);
27
+ }
28
+
29
+ /**
30
+ * Convenience helper for tests and consumers that want an encrypted sqlite-opfs
31
+ * store without dealing with the full `open()` parameter order. Key must be 32
32
+ * bytes. Creates a fresh persistent store (sqlite3mc does not support encryption
33
+ * on ephemeral `:memory:` databases) in an auto-generated OPFS directory.
34
+ */
35
+ export function openEncryptedStore(encryptionKey: Uint8Array, name?: string, poolDirectory?: string) {
36
+ return AztecSQLiteOPFSStore.open(createLogger('kv-store:sqlite-opfs'), name, false, poolDirectory, encryptionKey);
37
+ }