@aztec/kv-store 0.0.1-commit.f504929 → 0.0.1-commit.f5a9928
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/README.md +10 -1
- 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/deprecated/indexeddb/array.d.ts +22 -0
- package/dest/deprecated/indexeddb/array.d.ts.map +1 -0
- package/dest/deprecated/indexeddb/index.d.ts +7 -0
- package/dest/deprecated/indexeddb/index.d.ts.map +1 -0
- package/dest/deprecated/indexeddb/index.js +8 -0
- package/dest/deprecated/indexeddb/map.d.ts +38 -0
- package/dest/deprecated/indexeddb/map.d.ts.map +1 -0
- package/dest/deprecated/indexeddb/multi_map.d.ts +14 -0
- package/dest/deprecated/indexeddb/multi_map.d.ts.map +1 -0
- package/dest/{indexeddb → deprecated/indexeddb}/multi_map.js +2 -1
- package/dest/deprecated/indexeddb/set.d.ts +17 -0
- package/dest/deprecated/indexeddb/set.d.ts.map +1 -0
- package/dest/deprecated/indexeddb/singleton.d.ts +17 -0
- package/dest/deprecated/indexeddb/singleton.d.ts.map +1 -0
- package/dest/deprecated/indexeddb/store.d.ts +98 -0
- package/dest/deprecated/indexeddb/store.d.ts.map +1 -0
- package/dest/{indexeddb → deprecated/indexeddb}/store.js +2 -0
- package/dest/interfaces/array_test_suite.d.ts +1 -1
- package/dest/interfaces/array_test_suite.d.ts.map +1 -1
- package/dest/interfaces/array_test_suite.js +33 -34
- package/dest/interfaces/index.d.ts +2 -2
- package/dest/interfaces/index.d.ts.map +1 -1
- 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 +32 -33
- 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 +68 -69
- package/dest/interfaces/set_test_suite.d.ts +1 -1
- package/dest/interfaces/set_test_suite.d.ts.map +1 -1
- package/dest/interfaces/set_test_suite.js +13 -14
- package/dest/interfaces/singleton_test_suite.d.ts +1 -1
- package/dest/interfaces/singleton_test_suite.d.ts.map +1 -1
- package/dest/interfaces/singleton_test_suite.js +6 -7
- package/dest/lmdb/index.d.ts +2 -2
- package/dest/lmdb/index.d.ts.map +1 -1
- package/dest/lmdb/index.js +2 -2
- 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 +30 -4
- package/dest/lmdb-v2/factory.d.ts.map +1 -1
- package/dest/lmdb-v2/factory.js +62 -10
- package/dest/lmdb-v2/read_transaction.js +21 -19
- package/dest/lmdb-v2/store.d.ts +2 -2
- package/dest/lmdb-v2/store.d.ts.map +1 -1
- package/dest/lmdb-v2/store.js +4 -4
- 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/errors.d.ts +54 -0
- package/dest/sqlite-opfs/errors.d.ts.map +1 -0
- package/dest/sqlite-opfs/errors.js +77 -0
- package/dest/sqlite-opfs/index.d.ts +14 -0
- package/dest/sqlite-opfs/index.d.ts.map +1 -0
- package/dest/sqlite-opfs/index.js +16 -0
- package/dest/sqlite-opfs/internal/ordered-binary-browser.d.ts +32 -0
- package/dest/sqlite-opfs/internal/ordered-binary-browser.d.ts.map +1 -0
- package/dest/sqlite-opfs/internal/ordered-binary-browser.js +448 -0
- package/dest/sqlite-opfs/manage.d.ts +22 -0
- package/dest/sqlite-opfs/manage.d.ts.map +1 -0
- package/dest/sqlite-opfs/manage.js +38 -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 +66 -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/pool_integrity.d.ts +20 -0
- package/dest/sqlite-opfs/pool_integrity.d.ts.map +1 -0
- package/dest/sqlite-opfs/pool_integrity.js +282 -0
- package/dest/sqlite-opfs/pool_lock.d.ts +8 -0
- package/dest/sqlite-opfs/pool_lock.d.ts.map +1 -0
- package/dest/sqlite-opfs/pool_lock.js +47 -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 +84 -0
- package/dest/sqlite-opfs/store.d.ts.map +1 -0
- package/dest/sqlite-opfs/store.js +317 -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 +275 -0
- package/dest/stores/l2_tips_store.d.ts +7 -13
- package/dest/stores/l2_tips_store.d.ts.map +1 -1
- package/dest/stores/l2_tips_store.js +24 -43
- package/package.json +24 -22
- package/src/bench/shared_map_bench.ts +111 -0
- package/src/{indexeddb → deprecated/indexeddb}/array.ts +2 -2
- package/src/deprecated/indexeddb/index.ts +12 -0
- package/src/{indexeddb → deprecated/indexeddb}/map.ts +2 -2
- package/src/{indexeddb → deprecated/indexeddb}/multi_map.ts +5 -3
- package/src/{indexeddb → deprecated/indexeddb}/set.ts +2 -2
- package/src/{indexeddb → deprecated/indexeddb}/singleton.ts +2 -2
- package/src/{indexeddb → deprecated/indexeddb}/store.ts +10 -9
- package/src/interfaces/array_test_suite.ts +33 -35
- package/src/interfaces/index.ts +1 -1
- package/src/interfaces/map_test_suite.ts +32 -34
- package/src/interfaces/multi_map_test_suite.ts +65 -67
- package/src/interfaces/set_test_suite.ts +13 -15
- package/src/interfaces/singleton_test_suite.ts +6 -8
- package/src/lmdb/index.ts +3 -3
- package/src/lmdb/store.ts +12 -8
- package/src/lmdb-v2/factory.ts +86 -10
- package/src/lmdb-v2/read_transaction.ts +23 -23
- package/src/lmdb-v2/store.ts +4 -2
- package/src/sqlite-opfs/array.ts +124 -0
- package/src/sqlite-opfs/errors.ts +94 -0
- package/src/sqlite-opfs/index.ts +27 -0
- package/src/sqlite-opfs/internal/ordered-binary-browser.js +465 -0
- package/src/sqlite-opfs/manage.ts +46 -0
- package/src/sqlite-opfs/map.ts +163 -0
- package/src/sqlite-opfs/messages.ts +39 -0
- package/src/sqlite-opfs/multi_map.ts +74 -0
- package/src/sqlite-opfs/pool_integrity.ts +327 -0
- package/src/sqlite-opfs/pool_lock.ts +62 -0
- package/src/sqlite-opfs/set.ts +29 -0
- package/src/sqlite-opfs/singleton.ts +48 -0
- package/src/sqlite-opfs/store.ts +330 -0
- package/src/sqlite-opfs/worker.ts +259 -0
- package/src/stores/l2_tips_store.ts +20 -41
- package/dest/config.d.ts +0 -17
- package/dest/config.d.ts.map +0 -1
- package/dest/config.js +0 -26
- package/dest/indexeddb/array.d.ts +0 -22
- package/dest/indexeddb/array.d.ts.map +0 -1
- package/dest/indexeddb/index.d.ts +0 -7
- package/dest/indexeddb/index.d.ts.map +0 -1
- package/dest/indexeddb/index.js +0 -16
- package/dest/indexeddb/map.d.ts +0 -38
- package/dest/indexeddb/map.d.ts.map +0 -1
- package/dest/indexeddb/multi_map.d.ts +0 -14
- package/dest/indexeddb/multi_map.d.ts.map +0 -1
- package/dest/indexeddb/set.d.ts +0 -17
- package/dest/indexeddb/set.d.ts.map +0 -1
- package/dest/indexeddb/singleton.d.ts +0 -17
- package/dest/indexeddb/singleton.d.ts.map +0 -1
- package/dest/indexeddb/store.d.ts +0 -96
- package/dest/indexeddb/store.d.ts.map +0 -1
- package/src/config.ts +0 -36
- package/src/indexeddb/index.ts +0 -31
- /package/dest/{indexeddb → deprecated/indexeddb}/array.js +0 -0
- /package/dest/{indexeddb → deprecated/indexeddb}/map.js +0 -0
- /package/dest/{indexeddb → deprecated/indexeddb}/set.js +0 -0
- /package/dest/{indexeddb → deprecated/indexeddb}/singleton.js +0 -0
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* RPC protocol between the main thread and the SQLite worker.
|
|
3
|
+
* All requests carry a unique `id`; responses echo the same id so the main thread
|
|
4
|
+
* can resolve the right pending promise.
|
|
5
|
+
*/
|
|
6
|
+
import type { SqliteEncryptionErrorCode } from './errors.js';
|
|
7
|
+
|
|
8
|
+
/** Matches `@sqlite.org/sqlite-wasm`'s internal SqlValue type. Boolean is not a native SQLite type. */
|
|
9
|
+
export type SqlValue = string | number | bigint | null | Uint8Array;
|
|
10
|
+
|
|
11
|
+
/** A row returned in 'array' rowMode — one value per column, in select order. */
|
|
12
|
+
export type ResultRow = SqlValue[];
|
|
13
|
+
|
|
14
|
+
export type WorkerRequest =
|
|
15
|
+
| { type: 'init'; id: number; dbName: string; ephemeral: boolean; poolDirectory?: string; encryptionKey?: Uint8Array }
|
|
16
|
+
| { type: 'close'; id: number }
|
|
17
|
+
| { type: 'deleteDb'; id: number; dbName: string }
|
|
18
|
+
| { type: 'run'; id: number; sql: string; bind?: SqlValue[] }
|
|
19
|
+
| { type: 'all'; id: number; sql: string; bind?: SqlValue[] }
|
|
20
|
+
| { type: 'export'; id: number }
|
|
21
|
+
| { type: 'begin'; id: number }
|
|
22
|
+
| { type: 'commit'; id: number }
|
|
23
|
+
| { type: 'rollback'; id: number };
|
|
24
|
+
|
|
25
|
+
export type WorkerResponse =
|
|
26
|
+
| { type: 'ok'; id: number; rows?: ResultRow[]; changes?: number; bytes?: Uint8Array }
|
|
27
|
+
| {
|
|
28
|
+
type: 'err';
|
|
29
|
+
id: number;
|
|
30
|
+
message: string;
|
|
31
|
+
/**
|
|
32
|
+
* Set when the worker detected an encryption-shaped failure. The main thread
|
|
33
|
+
* uses this to re-throw the error as a {@link SqliteEncryptionError} with the
|
|
34
|
+
* matching code. Absent on non-encryption failures (untyped paths preserved).
|
|
35
|
+
*/
|
|
36
|
+
encryptionCode?: SqliteEncryptionErrorCode;
|
|
37
|
+
};
|
|
38
|
+
|
|
39
|
+
export type WorkerRequestType = WorkerRequest['type'];
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
import { hash } from 'ohash';
|
|
2
|
+
|
|
3
|
+
import type { Key, Value } from '../interfaces/common.js';
|
|
4
|
+
import type { AztecAsyncMultiMap } from '../interfaces/multi_map.js';
|
|
5
|
+
import { SQLiteOPFSAztecMap } from './map.js';
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* Multi-map backed by SQLite. Extends the base map with always-incrementing
|
|
9
|
+
* `key_count` per-key so the same slot is never reused across deletions — this
|
|
10
|
+
* matches the IndexedDB backend's sparse-multi-map semantics.
|
|
11
|
+
*/
|
|
12
|
+
export class SQLiteOPFSAztecMultiMap<K extends Key, V extends Value>
|
|
13
|
+
extends SQLiteOPFSAztecMap<K, V>
|
|
14
|
+
implements AztecAsyncMultiMap<K, V>
|
|
15
|
+
{
|
|
16
|
+
override async set(key: K, val: V): Promise<void> {
|
|
17
|
+
const valueHash = hash(val);
|
|
18
|
+
await this.store.transactionAsync(async () => {
|
|
19
|
+
const exists = await this.store.allAsync(
|
|
20
|
+
'SELECT 1 FROM data WHERE container = ? AND key = ? AND hash = ? LIMIT 1',
|
|
21
|
+
[this.container, this.encodedKey(key), valueHash],
|
|
22
|
+
);
|
|
23
|
+
if (exists.length > 0) {
|
|
24
|
+
return;
|
|
25
|
+
}
|
|
26
|
+
const maxRow = await this.store.allAsync('SELECT MAX(key_count) FROM data WHERE container = ? AND key = ?', [
|
|
27
|
+
this.container,
|
|
28
|
+
this.encodedKey(key),
|
|
29
|
+
]);
|
|
30
|
+
const count = Number(maxRow[0]?.[0] ?? 0);
|
|
31
|
+
await this.store.runAsync(
|
|
32
|
+
`INSERT INTO data (slot, container, key, key_count, hash, value)
|
|
33
|
+
VALUES (?, ?, ?, ?, ?, ?)`,
|
|
34
|
+
[this.slot(key, count), this.container, this.encodedKey(key), count + 1, valueHash, this.encoder.pack(val)],
|
|
35
|
+
);
|
|
36
|
+
});
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
async *getValuesAsync(key: K): AsyncIterableIterator<V> {
|
|
40
|
+
const rows = await this.store.allAsync(
|
|
41
|
+
'SELECT value FROM data WHERE container = ? AND key = ? ORDER BY key_count ASC',
|
|
42
|
+
[this.container, this.encodedKey(key)],
|
|
43
|
+
);
|
|
44
|
+
for (const row of rows) {
|
|
45
|
+
const raw = row[0];
|
|
46
|
+
if (raw instanceof Uint8Array) {
|
|
47
|
+
yield this.decodeValue(raw);
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
async getValueCountAsync(key: K): Promise<number> {
|
|
53
|
+
const rows = await this.store.allAsync('SELECT COUNT(*) FROM data WHERE container = ? AND key = ?', [
|
|
54
|
+
this.container,
|
|
55
|
+
this.encodedKey(key),
|
|
56
|
+
]);
|
|
57
|
+
return Number(rows[0]?.[0] ?? 0);
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
async deleteValue(key: K, val: V): Promise<void> {
|
|
61
|
+
await this.store.runAsync('DELETE FROM data WHERE container = ? AND key = ? AND hash = ?', [
|
|
62
|
+
this.container,
|
|
63
|
+
this.encodedKey(key),
|
|
64
|
+
hash(val),
|
|
65
|
+
]);
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
override async delete(key: K): Promise<void> {
|
|
69
|
+
await this.store.runAsync('DELETE FROM data WHERE container = ? AND key = ?', [
|
|
70
|
+
this.container,
|
|
71
|
+
this.encodedKey(key),
|
|
72
|
+
]);
|
|
73
|
+
}
|
|
74
|
+
}
|
|
@@ -0,0 +1,327 @@
|
|
|
1
|
+
import { normalizePoolDirectory } from './pool_lock.js';
|
|
2
|
+
|
|
3
|
+
// The constants below mirror the opaque-file header format of the pinned opfs-sahpool VFS
|
|
4
|
+
// (`yarn-project/sqlite3mc-wasm/vendor/jswasm/sqlite3.mjs`, class `OpfsSAHPool`). The pool names its files randomly
|
|
5
|
+
// under `.opaque/` and prepends a header that maps each one back to its logical SQLite path:
|
|
6
|
+
//
|
|
7
|
+
// bytes [0, 512) logical path, NUL-terminated UTF-8 (HEADER_MAX_PATH_SIZE)
|
|
8
|
+
// bytes [512, 516) SQLite open-flags of the file, big-endian uint32 (HEADER_FLAGS_SIZE)
|
|
9
|
+
// bytes [516, 524) digest over the preceding 516 bytes, two uint32 words (HEADER_DIGEST_SIZE)
|
|
10
|
+
//
|
|
11
|
+
// Database content starts at byte 4096 (the pool's SECTOR_SIZE). We re-read the header ourselves rather than asking
|
|
12
|
+
// the VFS because the upstream pool "repairs" anything it cannot validate by disassociating the file — destroying
|
|
13
|
+
// exactly the evidence this module exists to quarantine. The browser regression test writes a real pool through the
|
|
14
|
+
// pinned VFS before duplicating an opaque file, so a vendor upgrade that changes the layout breaks detection loudly
|
|
15
|
+
// rather than silently.
|
|
16
|
+
const OPAQUE_DIRECTORY = '.opaque';
|
|
17
|
+
const HEADER_MAX_PATH_SIZE = 512;
|
|
18
|
+
const HEADER_FLAGS_SIZE = 4;
|
|
19
|
+
const HEADER_DIGEST_SIZE = 8;
|
|
20
|
+
const HEADER_CORPUS_SIZE = HEADER_MAX_PATH_SIZE + HEADER_FLAGS_SIZE;
|
|
21
|
+
const HEADER_SIZE = HEADER_CORPUS_SIZE + HEADER_DIGEST_SIZE;
|
|
22
|
+
|
|
23
|
+
// Standard SQLite open-flag bit values (sqlite3.h). Restated as literals because the header stores them numerically
|
|
24
|
+
// and this module runs on the main thread, without the sqlite3 WASM bundle that defines `capi.SQLITE_OPEN_*`.
|
|
25
|
+
const SQLITE_OPEN_DELETEONCLOSE = 0x00000008;
|
|
26
|
+
const SQLITE_OPEN_MEMORY = 0x00000080;
|
|
27
|
+
const SQLITE_OPEN_MAIN_DB = 0x00000100;
|
|
28
|
+
const SQLITE_OPEN_MAIN_JOURNAL = 0x00000800;
|
|
29
|
+
const SQLITE_OPEN_SUPER_JOURNAL = 0x00004000;
|
|
30
|
+
const SQLITE_OPEN_WAL = 0x00080000;
|
|
31
|
+
|
|
32
|
+
// A live association must name one of the file types the pool persists; transient types (temp DBs, statement
|
|
33
|
+
// journals) never survive in a valid header.
|
|
34
|
+
const PERSISTENT_FILE_TYPES =
|
|
35
|
+
SQLITE_OPEN_MAIN_DB | SQLITE_OPEN_MAIN_JOURNAL | SQLITE_OPEN_SUPER_JOURNAL | SQLITE_OPEN_WAL;
|
|
36
|
+
|
|
37
|
+
// The upstream VFS repurposes SQLITE_OPEN_MEMORY — meaningless for a file that exists on disk — as a header version
|
|
38
|
+
// marker: headers written with it set carry a real digest, while legacy headers leave it unset and store all-zero
|
|
39
|
+
// digest words.
|
|
40
|
+
const FLAG_COMPUTE_DIGEST_V2 = SQLITE_OPEN_MEMORY;
|
|
41
|
+
|
|
42
|
+
export const OPFS_QUARANTINE_ROOT_DIRECTORY = '.aztec-sqlite-quarantine';
|
|
43
|
+
|
|
44
|
+
export interface DuplicatePoolAssociation {
|
|
45
|
+
logicalPath: string;
|
|
46
|
+
opaqueFileNames: string[];
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
export interface PoolQuarantineMetadata {
|
|
50
|
+
formatVersion: 1;
|
|
51
|
+
originalPoolDirectory: string;
|
|
52
|
+
quarantinedAt: string;
|
|
53
|
+
duplicateAssociations: DuplicatePoolAssociation[];
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
export interface PoolQuarantineResult extends PoolQuarantineMetadata {
|
|
57
|
+
quarantineDirectory: string;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/**
|
|
61
|
+
* Detects duplicate SAH logical-file associations and, if found, copies the complete pool into quarantine before
|
|
62
|
+
* removing the original. The caller must hold the pool's exclusive Web Lock for the whole operation.
|
|
63
|
+
*/
|
|
64
|
+
export async function quarantineDuplicatePool(poolDirectory: string): Promise<PoolQuarantineResult | undefined> {
|
|
65
|
+
poolDirectory = normalizePoolDirectory(poolDirectory);
|
|
66
|
+
const root = await navigator.storage.getDirectory();
|
|
67
|
+
const source = await getDirectory(root, poolDirectory);
|
|
68
|
+
if (!source) {
|
|
69
|
+
return undefined;
|
|
70
|
+
}
|
|
71
|
+
const opaque = await getChildDirectory(source, OPAQUE_DIRECTORY);
|
|
72
|
+
if (!opaque) {
|
|
73
|
+
return undefined;
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
const duplicateAssociations = await findDuplicateAssociations(opaque);
|
|
77
|
+
if (duplicateAssociations.length === 0) {
|
|
78
|
+
return undefined;
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
const quarantineRoot = await root.getDirectoryHandle(OPFS_QUARANTINE_ROOT_DIRECTORY, { create: true });
|
|
82
|
+
const quarantineName = createQuarantineName();
|
|
83
|
+
const destination = await quarantineRoot.getDirectoryHandle(quarantineName, { create: true });
|
|
84
|
+
const metadata: PoolQuarantineMetadata = {
|
|
85
|
+
formatVersion: 1,
|
|
86
|
+
originalPoolDirectory: poolDirectory,
|
|
87
|
+
quarantinedAt: new Date().toISOString(),
|
|
88
|
+
duplicateAssociations,
|
|
89
|
+
};
|
|
90
|
+
|
|
91
|
+
let quarantineComplete = false;
|
|
92
|
+
try {
|
|
93
|
+
await copyDirectory(source, destination);
|
|
94
|
+
await verifyDirectoryCopy(source, destination);
|
|
95
|
+
await writeJson(destination, 'quarantine.json', metadata);
|
|
96
|
+
quarantineComplete = true;
|
|
97
|
+
await removeDirectory(root, poolDirectory);
|
|
98
|
+
} catch (err) {
|
|
99
|
+
if (!quarantineComplete) {
|
|
100
|
+
await quarantineRoot.removeEntry(quarantineName, { recursive: true }).catch(() => {});
|
|
101
|
+
}
|
|
102
|
+
throw err;
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
return {
|
|
106
|
+
...metadata,
|
|
107
|
+
quarantineDirectory: `${OPFS_QUARANTINE_ROOT_DIRECTORY}/${quarantineName}`,
|
|
108
|
+
};
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
async function findDuplicateAssociations(opaque: FileSystemDirectoryHandle): Promise<DuplicatePoolAssociation[]> {
|
|
112
|
+
const associations = new Map<string, string[]>();
|
|
113
|
+
for await (const [opaqueName, handle] of opaque.entries()) {
|
|
114
|
+
if (handle.kind !== 'file') {
|
|
115
|
+
continue;
|
|
116
|
+
}
|
|
117
|
+
const logicalPath = await readAssociatedPath(handle as FileSystemFileHandle);
|
|
118
|
+
if (logicalPath) {
|
|
119
|
+
const names = associations.get(logicalPath) ?? [];
|
|
120
|
+
names.push(opaqueName);
|
|
121
|
+
associations.set(logicalPath, names);
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
return [...associations.entries()]
|
|
125
|
+
.filter(([, names]) => names.length > 1)
|
|
126
|
+
.map(([logicalPath, opaqueFileNames]) => ({ logicalPath, opaqueFileNames: opaqueFileNames.sort() }))
|
|
127
|
+
.sort((a, b) => a.logicalPath.localeCompare(b.logicalPath));
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
/**
|
|
131
|
+
* Returns the logical SQLite path an opaque SAH file is associated with, or undefined if the file is not a live,
|
|
132
|
+
* valid association. Applies the same checks as the vendored pool's `getAssociatedPath`: a non-empty NUL-terminated
|
|
133
|
+
* path, open-flags naming a persistent file type without DELETEONCLOSE, and a matching header digest. Files failing
|
|
134
|
+
* any check are the pool's free-list or garbage entries — the VFS itself would disassociate them on open — so they
|
|
135
|
+
* cannot participate in a duplicate mapping.
|
|
136
|
+
*/
|
|
137
|
+
async function readAssociatedPath(handle: FileSystemFileHandle): Promise<string | undefined> {
|
|
138
|
+
const file = await handle.getFile();
|
|
139
|
+
if (file.size < HEADER_SIZE) {
|
|
140
|
+
return undefined;
|
|
141
|
+
}
|
|
142
|
+
const header = new Uint8Array(await file.slice(0, HEADER_SIZE).arrayBuffer());
|
|
143
|
+
const pathEnd = header.subarray(0, HEADER_MAX_PATH_SIZE).indexOf(0);
|
|
144
|
+
if (pathEnd <= 0) {
|
|
145
|
+
return undefined;
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
const dataView = new DataView(header.buffer, header.byteOffset, header.byteLength);
|
|
149
|
+
const flags = dataView.getUint32(HEADER_MAX_PATH_SIZE);
|
|
150
|
+
if ((flags & SQLITE_OPEN_DELETEONCLOSE) !== 0 || (flags & PERSISTENT_FILE_TYPES) === 0) {
|
|
151
|
+
return undefined;
|
|
152
|
+
}
|
|
153
|
+
if (!hasValidDigest(header, flags)) {
|
|
154
|
+
return undefined;
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
try {
|
|
158
|
+
return new TextDecoder('utf-8', { fatal: true }).decode(header.subarray(0, pathEnd));
|
|
159
|
+
} catch {
|
|
160
|
+
return undefined;
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
/**
|
|
165
|
+
* Byte-for-byte port of the vendored pool's `computeDigest`, checked against the digest words stored in the header.
|
|
166
|
+
*/
|
|
167
|
+
function hasValidDigest(header: Uint8Array, flags: number): boolean {
|
|
168
|
+
let expected0 = 0;
|
|
169
|
+
let expected1 = 0;
|
|
170
|
+
if ((flags & FLAG_COMPUTE_DIGEST_V2) !== 0) {
|
|
171
|
+
// These seeds (0xdeadbeef, 0x41c6ce57) and odd multipliers (2654435761, 104729) are the upstream author's choices
|
|
172
|
+
// (a cyrb53-hash variant) and carry no meaning here beyond having to match the vendored implementation bit for
|
|
173
|
+
// bit.
|
|
174
|
+
expected0 = 0xdeadbeef;
|
|
175
|
+
expected1 = 0x41c6ce57;
|
|
176
|
+
for (const value of header.subarray(0, HEADER_CORPUS_SIZE)) {
|
|
177
|
+
expected0 = Math.imul(expected0 ^ value, 2654435761);
|
|
178
|
+
expected1 = Math.imul(expected1 ^ value, 104729);
|
|
179
|
+
}
|
|
180
|
+
expected0 >>>= 0;
|
|
181
|
+
expected1 >>>= 0;
|
|
182
|
+
}
|
|
183
|
+
const dataView = new DataView(header.buffer, header.byteOffset, header.byteLength);
|
|
184
|
+
return (
|
|
185
|
+
dataView.getUint32(HEADER_CORPUS_SIZE, true) === expected0 &&
|
|
186
|
+
dataView.getUint32(HEADER_CORPUS_SIZE + 4, true) === expected1
|
|
187
|
+
);
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
async function getDirectory(
|
|
191
|
+
root: FileSystemDirectoryHandle,
|
|
192
|
+
path: string,
|
|
193
|
+
): Promise<FileSystemDirectoryHandle | undefined> {
|
|
194
|
+
let current = root;
|
|
195
|
+
try {
|
|
196
|
+
for (const segment of path.split('/')) {
|
|
197
|
+
current = await current.getDirectoryHandle(segment);
|
|
198
|
+
}
|
|
199
|
+
return current;
|
|
200
|
+
} catch (err) {
|
|
201
|
+
if (err instanceof DOMException && err.name === 'NotFoundError') {
|
|
202
|
+
return undefined;
|
|
203
|
+
}
|
|
204
|
+
throw err;
|
|
205
|
+
}
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
async function getChildDirectory(
|
|
209
|
+
parent: FileSystemDirectoryHandle,
|
|
210
|
+
name: string,
|
|
211
|
+
): Promise<FileSystemDirectoryHandle | undefined> {
|
|
212
|
+
try {
|
|
213
|
+
return await parent.getDirectoryHandle(name);
|
|
214
|
+
} catch (err) {
|
|
215
|
+
if (err instanceof DOMException && err.name === 'NotFoundError') {
|
|
216
|
+
return undefined;
|
|
217
|
+
}
|
|
218
|
+
throw err;
|
|
219
|
+
}
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
async function removeDirectory(root: FileSystemDirectoryHandle, path: string): Promise<void> {
|
|
223
|
+
const segments = path.split('/');
|
|
224
|
+
const name = segments.pop()!;
|
|
225
|
+
let parent = root;
|
|
226
|
+
for (const segment of segments) {
|
|
227
|
+
parent = await parent.getDirectoryHandle(segment);
|
|
228
|
+
}
|
|
229
|
+
await parent.removeEntry(name, { recursive: true });
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
async function copyDirectory(source: FileSystemDirectoryHandle, destination: FileSystemDirectoryHandle): Promise<void> {
|
|
233
|
+
for await (const [name, handle] of source.entries()) {
|
|
234
|
+
if (handle.kind === 'directory') {
|
|
235
|
+
const childDestination = await destination.getDirectoryHandle(name, { create: true });
|
|
236
|
+
await copyDirectory(handle as FileSystemDirectoryHandle, childDestination);
|
|
237
|
+
continue;
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
const sourceFile = await (handle as FileSystemFileHandle).getFile();
|
|
241
|
+
const destinationHandle = await destination.getFileHandle(name, { create: true });
|
|
242
|
+
const writable = await destinationHandle.createWritable();
|
|
243
|
+
try {
|
|
244
|
+
await writable.write(sourceFile);
|
|
245
|
+
await writable.close();
|
|
246
|
+
} catch (err) {
|
|
247
|
+
await writable.abort().catch(() => {});
|
|
248
|
+
throw err;
|
|
249
|
+
}
|
|
250
|
+
}
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
async function verifyDirectoryCopy(
|
|
254
|
+
source: FileSystemDirectoryHandle,
|
|
255
|
+
destination: FileSystemDirectoryHandle,
|
|
256
|
+
): Promise<void> {
|
|
257
|
+
const sourceEntries = await getSortedEntries(source);
|
|
258
|
+
const destinationEntries = await getSortedEntries(destination);
|
|
259
|
+
if (
|
|
260
|
+
sourceEntries.length !== destinationEntries.length ||
|
|
261
|
+
sourceEntries.some(([name, handle], index) => {
|
|
262
|
+
const destinationEntry = destinationEntries[index];
|
|
263
|
+
return name !== destinationEntry[0] || handle.kind !== destinationEntry[1].kind;
|
|
264
|
+
})
|
|
265
|
+
) {
|
|
266
|
+
throw new Error('Failed to verify quarantined OPFS directory structure');
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
for (let i = 0; i < sourceEntries.length; i++) {
|
|
270
|
+
const [, sourceHandle] = sourceEntries[i];
|
|
271
|
+
const [, destinationHandle] = destinationEntries[i];
|
|
272
|
+
if (sourceHandle.kind === 'directory') {
|
|
273
|
+
await verifyDirectoryCopy(
|
|
274
|
+
sourceHandle as FileSystemDirectoryHandle,
|
|
275
|
+
destinationHandle as FileSystemDirectoryHandle,
|
|
276
|
+
);
|
|
277
|
+
} else {
|
|
278
|
+
await verifyFilesEqual(sourceHandle as FileSystemFileHandle, destinationHandle as FileSystemFileHandle);
|
|
279
|
+
}
|
|
280
|
+
}
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
async function getSortedEntries(directory: FileSystemDirectoryHandle): Promise<[string, FileSystemHandle][]> {
|
|
284
|
+
const entries: [string, FileSystemHandle][] = [];
|
|
285
|
+
for await (const entry of directory.entries()) {
|
|
286
|
+
entries.push(entry);
|
|
287
|
+
}
|
|
288
|
+
return entries.sort(([a], [b]) => a.localeCompare(b));
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
async function verifyFilesEqual(sourceHandle: FileSystemFileHandle, destinationHandle: FileSystemFileHandle) {
|
|
292
|
+
const source = await sourceHandle.getFile();
|
|
293
|
+
const destination = await destinationHandle.getFile();
|
|
294
|
+
if (source.size !== destination.size) {
|
|
295
|
+
throw new Error(`Failed to verify quarantined OPFS file "${source.name}"`);
|
|
296
|
+
}
|
|
297
|
+
|
|
298
|
+
const chunkSize = 1024 * 1024;
|
|
299
|
+
for (let offset = 0; offset < source.size; offset += chunkSize) {
|
|
300
|
+
const [sourceChunk, destinationChunk] = await Promise.all([
|
|
301
|
+
source.slice(offset, offset + chunkSize).arrayBuffer(),
|
|
302
|
+
destination.slice(offset, offset + chunkSize).arrayBuffer(),
|
|
303
|
+
]);
|
|
304
|
+
const sourceBytes = new Uint8Array(sourceChunk);
|
|
305
|
+
const destinationBytes = new Uint8Array(destinationChunk);
|
|
306
|
+
if (sourceBytes.some((value, index) => value !== destinationBytes[index])) {
|
|
307
|
+
throw new Error(`Failed to verify quarantined OPFS file "${source.name}"`);
|
|
308
|
+
}
|
|
309
|
+
}
|
|
310
|
+
}
|
|
311
|
+
|
|
312
|
+
async function writeJson(directory: FileSystemDirectoryHandle, name: string, value: unknown): Promise<void> {
|
|
313
|
+
const handle = await directory.getFileHandle(name, { create: true });
|
|
314
|
+
const writable = await handle.createWritable();
|
|
315
|
+
try {
|
|
316
|
+
await writable.write(JSON.stringify(value, undefined, 2));
|
|
317
|
+
await writable.close();
|
|
318
|
+
} catch (err) {
|
|
319
|
+
await writable.abort().catch(() => {});
|
|
320
|
+
throw err;
|
|
321
|
+
}
|
|
322
|
+
}
|
|
323
|
+
|
|
324
|
+
function createQuarantineName(): string {
|
|
325
|
+
const random = globalThis.crypto.getRandomValues(new Uint8Array(8));
|
|
326
|
+
return `${Date.now()}-${[...random].map(byte => byte.toString(16).padStart(2, '0')).join('')}`;
|
|
327
|
+
}
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
import { SqlitePoolBusyError, SqliteWebLocksUnavailableError } from './errors.js';
|
|
2
|
+
|
|
3
|
+
export const DEFAULT_SAH_POOL_DIRECTORY = '.aztec-kv';
|
|
4
|
+
|
|
5
|
+
const WEB_LOCK_PREFIX = 'aztec.sqlite-opfs.pool:';
|
|
6
|
+
|
|
7
|
+
export interface PoolLockLease {
|
|
8
|
+
release(): Promise<void>;
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
export function normalizePoolDirectory(poolDirectory?: string): string {
|
|
12
|
+
const path = poolDirectory
|
|
13
|
+
?.split('/')
|
|
14
|
+
.filter(segment => segment.length > 0)
|
|
15
|
+
.join('/');
|
|
16
|
+
return path || DEFAULT_SAH_POOL_DIRECTORY;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
export async function acquirePoolLock(poolDirectory?: string): Promise<PoolLockLease> {
|
|
20
|
+
if (!navigator.locks) {
|
|
21
|
+
throw new SqliteWebLocksUnavailableError();
|
|
22
|
+
}
|
|
23
|
+
const normalizedDirectory = normalizePoolDirectory(poolDirectory);
|
|
24
|
+
const acquired = Promise.withResolvers<Lock | null>();
|
|
25
|
+
const hold = Promise.withResolvers<void>();
|
|
26
|
+
const request = navigator.locks.request(
|
|
27
|
+
`${WEB_LOCK_PREFIX}${normalizedDirectory}`,
|
|
28
|
+
{ mode: 'exclusive', ifAvailable: true },
|
|
29
|
+
async lock => {
|
|
30
|
+
acquired.resolve(lock);
|
|
31
|
+
if (lock) {
|
|
32
|
+
await hold.promise;
|
|
33
|
+
}
|
|
34
|
+
},
|
|
35
|
+
);
|
|
36
|
+
request.catch(acquired.reject);
|
|
37
|
+
|
|
38
|
+
if (!(await acquired.promise)) {
|
|
39
|
+
await request;
|
|
40
|
+
throw new SqlitePoolBusyError(normalizedDirectory);
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
let released = false;
|
|
44
|
+
return {
|
|
45
|
+
release: async () => {
|
|
46
|
+
if (!released) {
|
|
47
|
+
released = true;
|
|
48
|
+
hold.resolve();
|
|
49
|
+
}
|
|
50
|
+
await request;
|
|
51
|
+
},
|
|
52
|
+
};
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
export async function withPoolLock<T>(poolDirectory: string, callback: () => Promise<T>): Promise<T> {
|
|
56
|
+
const lease = await acquirePoolLock(poolDirectory);
|
|
57
|
+
try {
|
|
58
|
+
return await callback();
|
|
59
|
+
} finally {
|
|
60
|
+
await lease.release();
|
|
61
|
+
}
|
|
62
|
+
}
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import type { Key, Range } from '../interfaces/common.js';
|
|
2
|
+
import type { AztecAsyncSet } from '../interfaces/set.js';
|
|
3
|
+
import { SQLiteOPFSAztecMap } from './map.js';
|
|
4
|
+
import type { AztecSQLiteOPFSStore } from './store.js';
|
|
5
|
+
|
|
6
|
+
/** Set backed by SQLite. Composes a Map<K, true>. */
|
|
7
|
+
export class SQLiteOPFSAztecSet<K extends Key> implements AztecAsyncSet<K> {
|
|
8
|
+
readonly #map: SQLiteOPFSAztecMap<K, boolean>;
|
|
9
|
+
|
|
10
|
+
constructor(store: AztecSQLiteOPFSStore, name: string) {
|
|
11
|
+
this.#map = new SQLiteOPFSAztecMap<K, boolean>(store, name);
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
hasAsync(key: K): Promise<boolean> {
|
|
15
|
+
return this.#map.hasAsync(key);
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
add(key: K): Promise<void> {
|
|
19
|
+
return this.#map.set(key, true);
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
delete(key: K): Promise<void> {
|
|
23
|
+
return this.#map.delete(key);
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
async *entriesAsync(range: Range<K> = {}): AsyncIterableIterator<K> {
|
|
27
|
+
yield* this.#map.keysAsync(range);
|
|
28
|
+
}
|
|
29
|
+
}
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
import { Encoder } from '#msgpackr';
|
|
2
|
+
import { toBufferKey } from '#ordered-binary';
|
|
3
|
+
import { hash } from 'ohash';
|
|
4
|
+
|
|
5
|
+
import type { Value } from '../interfaces/common.js';
|
|
6
|
+
import type { AztecAsyncSingleton } from '../interfaces/singleton.js';
|
|
7
|
+
import type { AztecSQLiteOPFSStore } from './store.js';
|
|
8
|
+
|
|
9
|
+
/** Stores a single value identified by `name`. */
|
|
10
|
+
export class SQLiteOPFSAztecSingleton<T extends Value> implements AztecAsyncSingleton<T> {
|
|
11
|
+
readonly #container: string;
|
|
12
|
+
readonly #slot: string;
|
|
13
|
+
readonly #encoder = new Encoder();
|
|
14
|
+
|
|
15
|
+
constructor(
|
|
16
|
+
private readonly store: AztecSQLiteOPFSStore,
|
|
17
|
+
name: string,
|
|
18
|
+
) {
|
|
19
|
+
this.#container = `singleton:${name}`;
|
|
20
|
+
this.#slot = `singleton:${name}:value`;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
async getAsync(): Promise<T | undefined> {
|
|
24
|
+
const rows = await this.store.allAsync('SELECT value FROM data WHERE slot = ? LIMIT 1', [this.#slot]);
|
|
25
|
+
if (rows.length === 0) {
|
|
26
|
+
return undefined;
|
|
27
|
+
}
|
|
28
|
+
const raw = rows[0][0];
|
|
29
|
+
if (raw instanceof Uint8Array) {
|
|
30
|
+
return this.#encoder.unpack(raw) as T;
|
|
31
|
+
}
|
|
32
|
+
return undefined;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
async set(val: T): Promise<boolean> {
|
|
36
|
+
const { changes } = await this.store.runAsync(
|
|
37
|
+
`INSERT OR REPLACE INTO data (slot, container, key, key_count, hash, value)
|
|
38
|
+
VALUES (?, ?, ?, ?, ?, ?)`,
|
|
39
|
+
[this.#slot, this.#container, toBufferKey([this.#slot]), 1, hash(val), this.#encoder.pack(val)],
|
|
40
|
+
);
|
|
41
|
+
return changes > 0;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
async delete(): Promise<boolean> {
|
|
45
|
+
await this.store.runAsync('DELETE FROM data WHERE slot = ?', [this.#slot]);
|
|
46
|
+
return true;
|
|
47
|
+
}
|
|
48
|
+
}
|