@aztec/kv-store 0.0.1-commit.936cb2cae → 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/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/package.json +10 -7
- package/src/bench/shared_map_bench.ts +111 -0
- 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
|
@@ -0,0 +1,194 @@
|
|
|
1
|
+
/// <reference lib="webworker" />
|
|
2
|
+
import sqlite3InitModule from '@sqlite.org/sqlite-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
|
+
let sqlite3;
|
|
20
|
+
let pool;
|
|
21
|
+
let db;
|
|
22
|
+
let dbPath;
|
|
23
|
+
async function ensurePool(directory) {
|
|
24
|
+
sqlite3 ??= await sqlite3InitModule();
|
|
25
|
+
if (!pool) {
|
|
26
|
+
pool = await sqlite3.installOpfsSAHPoolVfs({
|
|
27
|
+
name: SAH_POOL_VFS_NAME,
|
|
28
|
+
directory,
|
|
29
|
+
initialCapacity: 8
|
|
30
|
+
});
|
|
31
|
+
}
|
|
32
|
+
return pool;
|
|
33
|
+
}
|
|
34
|
+
async function handleInit(dbName, ephemeral, directory) {
|
|
35
|
+
sqlite3 ??= await sqlite3InitModule();
|
|
36
|
+
if (ephemeral) {
|
|
37
|
+
db = new sqlite3.oo1.DB(':memory:', 'c');
|
|
38
|
+
} else {
|
|
39
|
+
const p = await ensurePool(directory ?? DEFAULT_SAH_POOL_DIRECTORY);
|
|
40
|
+
dbPath = normalizeDbPath(dbName);
|
|
41
|
+
db = new p.OpfsSAHPoolDb(dbPath);
|
|
42
|
+
}
|
|
43
|
+
runSql(SCHEMA_SQL);
|
|
44
|
+
}
|
|
45
|
+
function handleClose() {
|
|
46
|
+
db?.close();
|
|
47
|
+
db = undefined;
|
|
48
|
+
dbPath = undefined;
|
|
49
|
+
}
|
|
50
|
+
async function handleExport() {
|
|
51
|
+
if (!db || !dbPath) {
|
|
52
|
+
throw new Error('SQLite worker: no database open to export');
|
|
53
|
+
}
|
|
54
|
+
if (!pool) {
|
|
55
|
+
throw new Error('SQLite worker: no SAH Pool available (ephemeral DBs cannot be exported)');
|
|
56
|
+
}
|
|
57
|
+
return await pool.exportFile(dbPath);
|
|
58
|
+
}
|
|
59
|
+
function handleDeleteDb(dbName) {
|
|
60
|
+
const path = normalizeDbPath(dbName);
|
|
61
|
+
if (db && dbPath === path) {
|
|
62
|
+
db.close();
|
|
63
|
+
db = undefined;
|
|
64
|
+
dbPath = undefined;
|
|
65
|
+
}
|
|
66
|
+
// Ephemeral :memory: DBs never back a file — skip installing a pool just to unlink
|
|
67
|
+
// nothing. installOpfsSAHPoolVfs acquires an exclusive lock on the OPFS SAH
|
|
68
|
+
// directory, and under heavy test churn that can contend with workers from
|
|
69
|
+
// previous tests whose OPFS handles Chromium hasn't yet released, hanging the RPC
|
|
70
|
+
// and then the whole test run.
|
|
71
|
+
if (!pool) {
|
|
72
|
+
return;
|
|
73
|
+
}
|
|
74
|
+
try {
|
|
75
|
+
pool.unlink(path);
|
|
76
|
+
} catch {
|
|
77
|
+
// File may not exist; ignore.
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
function requireDb() {
|
|
81
|
+
if (!db) {
|
|
82
|
+
throw new Error('SQLite worker: no database open');
|
|
83
|
+
}
|
|
84
|
+
return db;
|
|
85
|
+
}
|
|
86
|
+
function runSql(sql, bind) {
|
|
87
|
+
const conn = requireDb();
|
|
88
|
+
conn.exec({
|
|
89
|
+
sql,
|
|
90
|
+
bind
|
|
91
|
+
});
|
|
92
|
+
return {
|
|
93
|
+
changes: conn.changes()
|
|
94
|
+
};
|
|
95
|
+
}
|
|
96
|
+
function selectAll(sql, bind) {
|
|
97
|
+
const conn = requireDb();
|
|
98
|
+
const rows = [];
|
|
99
|
+
conn.exec({
|
|
100
|
+
sql,
|
|
101
|
+
bind,
|
|
102
|
+
rowMode: 'array',
|
|
103
|
+
resultRows: rows
|
|
104
|
+
});
|
|
105
|
+
return rows;
|
|
106
|
+
}
|
|
107
|
+
function normalizeDbPath(dbName) {
|
|
108
|
+
return dbName.startsWith('/') ? dbName : `/${dbName}`;
|
|
109
|
+
}
|
|
110
|
+
function respond(msg) {
|
|
111
|
+
self.postMessage(msg);
|
|
112
|
+
}
|
|
113
|
+
self.onmessage = async (ev)=>{
|
|
114
|
+
const req = ev.data;
|
|
115
|
+
try {
|
|
116
|
+
switch(req.type){
|
|
117
|
+
case 'init':
|
|
118
|
+
await handleInit(req.dbName, req.ephemeral, req.poolDirectory);
|
|
119
|
+
return respond({
|
|
120
|
+
type: 'ok',
|
|
121
|
+
id: req.id
|
|
122
|
+
});
|
|
123
|
+
case 'close':
|
|
124
|
+
handleClose();
|
|
125
|
+
return respond({
|
|
126
|
+
type: 'ok',
|
|
127
|
+
id: req.id
|
|
128
|
+
});
|
|
129
|
+
case 'deleteDb':
|
|
130
|
+
handleDeleteDb(req.dbName);
|
|
131
|
+
return respond({
|
|
132
|
+
type: 'ok',
|
|
133
|
+
id: req.id
|
|
134
|
+
});
|
|
135
|
+
case 'run':
|
|
136
|
+
{
|
|
137
|
+
const { changes } = runSql(req.sql, req.bind);
|
|
138
|
+
return respond({
|
|
139
|
+
type: 'ok',
|
|
140
|
+
id: req.id,
|
|
141
|
+
changes
|
|
142
|
+
});
|
|
143
|
+
}
|
|
144
|
+
case 'all':
|
|
145
|
+
{
|
|
146
|
+
const rows = selectAll(req.sql, req.bind);
|
|
147
|
+
return respond({
|
|
148
|
+
type: 'ok',
|
|
149
|
+
id: req.id,
|
|
150
|
+
rows
|
|
151
|
+
});
|
|
152
|
+
}
|
|
153
|
+
case 'export':
|
|
154
|
+
{
|
|
155
|
+
const bytes = await handleExport();
|
|
156
|
+
return respond({
|
|
157
|
+
type: 'ok',
|
|
158
|
+
id: req.id,
|
|
159
|
+
bytes
|
|
160
|
+
});
|
|
161
|
+
}
|
|
162
|
+
case 'begin':
|
|
163
|
+
runSql('BEGIN');
|
|
164
|
+
return respond({
|
|
165
|
+
type: 'ok',
|
|
166
|
+
id: req.id
|
|
167
|
+
});
|
|
168
|
+
case 'commit':
|
|
169
|
+
runSql('COMMIT');
|
|
170
|
+
return respond({
|
|
171
|
+
type: 'ok',
|
|
172
|
+
id: req.id
|
|
173
|
+
});
|
|
174
|
+
case 'rollback':
|
|
175
|
+
runSql('ROLLBACK');
|
|
176
|
+
return respond({
|
|
177
|
+
type: 'ok',
|
|
178
|
+
id: req.id
|
|
179
|
+
});
|
|
180
|
+
default:
|
|
181
|
+
{
|
|
182
|
+
const _exhaustive = req;
|
|
183
|
+
throw new Error(`Unknown request: ${JSON.stringify(_exhaustive)}`);
|
|
184
|
+
}
|
|
185
|
+
}
|
|
186
|
+
} catch (err) {
|
|
187
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
188
|
+
respond({
|
|
189
|
+
type: 'err',
|
|
190
|
+
id: req.id,
|
|
191
|
+
message
|
|
192
|
+
});
|
|
193
|
+
}
|
|
194
|
+
};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@aztec/kv-store",
|
|
3
|
-
"version": "0.0.1-commit.
|
|
3
|
+
"version": "0.0.1-commit.949a33fd8",
|
|
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": {
|
|
@@ -16,7 +17,8 @@
|
|
|
16
17
|
"clean": "rm -rf ./dest .tsbuildinfo",
|
|
17
18
|
"test:node": "NODE_NO_WARNINGS=1 mocha --config ./.mocharc.json",
|
|
18
19
|
"test:browser": "vitest run --config ./vitest.config.ts",
|
|
19
|
-
"
|
|
20
|
+
"bench:browser": "VITE_BENCH=1 vitest run --config ./vitest.config.ts src/bench",
|
|
21
|
+
"test": "yarn test:node",
|
|
20
22
|
"test:jest": "NODE_NO_WARNINGS=1 node --experimental-vm-modules ../node_modules/.bin/jest --passWithNoTests --maxWorkers=${JEST_MAX_WORKERS:-8}"
|
|
21
23
|
},
|
|
22
24
|
"inherits": [
|
|
@@ -24,11 +26,12 @@
|
|
|
24
26
|
"./package.local.json"
|
|
25
27
|
],
|
|
26
28
|
"dependencies": {
|
|
27
|
-
"@aztec/constants": "0.0.1-commit.
|
|
28
|
-
"@aztec/ethereum": "0.0.1-commit.
|
|
29
|
-
"@aztec/foundation": "0.0.1-commit.
|
|
30
|
-
"@aztec/native": "0.0.1-commit.
|
|
31
|
-
"@aztec/stdlib": "0.0.1-commit.
|
|
29
|
+
"@aztec/constants": "0.0.1-commit.949a33fd8",
|
|
30
|
+
"@aztec/ethereum": "0.0.1-commit.949a33fd8",
|
|
31
|
+
"@aztec/foundation": "0.0.1-commit.949a33fd8",
|
|
32
|
+
"@aztec/native": "0.0.1-commit.949a33fd8",
|
|
33
|
+
"@aztec/stdlib": "0.0.1-commit.949a33fd8",
|
|
34
|
+
"@sqlite.org/sqlite-wasm": "3.50.4-build1",
|
|
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
|
-
|
|
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
|
-
|
|
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,27 @@
|
|
|
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
|
+
}
|