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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (112) 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/indexeddb/array.js +18 -6
  5. package/dest/indexeddb/index.d.ts +2 -2
  6. package/dest/indexeddb/index.d.ts.map +1 -1
  7. package/dest/indexeddb/index.js +3 -6
  8. package/dest/indexeddb/map.d.ts +8 -2
  9. package/dest/indexeddb/map.d.ts.map +1 -1
  10. package/dest/indexeddb/map.js +23 -13
  11. package/dest/indexeddb/multi_map.d.ts +2 -1
  12. package/dest/indexeddb/multi_map.d.ts.map +1 -1
  13. package/dest/indexeddb/multi_map.js +16 -1
  14. package/dest/indexeddb/singleton.js +3 -1
  15. package/dest/indexeddb/store.d.ts +3 -3
  16. package/dest/indexeddb/store.d.ts.map +1 -1
  17. package/dest/indexeddb/store.js +6 -4
  18. package/dest/interfaces/array_test_suite.d.ts +1 -1
  19. package/dest/interfaces/array_test_suite.d.ts.map +1 -1
  20. package/dest/interfaces/array_test_suite.js +33 -34
  21. package/dest/interfaces/index.d.ts +2 -2
  22. package/dest/interfaces/index.d.ts.map +1 -1
  23. package/dest/interfaces/map_test_suite.d.ts +1 -1
  24. package/dest/interfaces/map_test_suite.d.ts.map +1 -1
  25. package/dest/interfaces/map_test_suite.js +74 -29
  26. package/dest/interfaces/multi_map_test_suite.d.ts +1 -1
  27. package/dest/interfaces/multi_map_test_suite.d.ts.map +1 -1
  28. package/dest/interfaces/multi_map_test_suite.js +84 -60
  29. package/dest/interfaces/set_test_suite.d.ts +1 -1
  30. package/dest/interfaces/set_test_suite.d.ts.map +1 -1
  31. package/dest/interfaces/set_test_suite.js +13 -14
  32. package/dest/interfaces/singleton_test_suite.d.ts +1 -1
  33. package/dest/interfaces/singleton_test_suite.d.ts.map +1 -1
  34. package/dest/interfaces/singleton_test_suite.js +6 -7
  35. package/dest/interfaces/utils.d.ts +2 -1
  36. package/dest/interfaces/utils.d.ts.map +1 -1
  37. package/dest/interfaces/utils.js +2 -1
  38. package/dest/lmdb/index.d.ts +2 -2
  39. package/dest/lmdb/index.d.ts.map +1 -1
  40. package/dest/lmdb/index.js +3 -3
  41. package/dest/lmdb-v2/factory.d.ts +6 -6
  42. package/dest/lmdb-v2/factory.d.ts.map +1 -1
  43. package/dest/lmdb-v2/factory.js +14 -10
  44. package/dest/lmdb-v2/store.d.ts +3 -3
  45. package/dest/lmdb-v2/store.d.ts.map +1 -1
  46. package/dest/lmdb-v2/store.js +2 -1
  47. package/dest/sqlite-opfs/array.d.ts +21 -0
  48. package/dest/sqlite-opfs/array.d.ts.map +1 -0
  49. package/dest/sqlite-opfs/array.js +128 -0
  50. package/dest/sqlite-opfs/errors.d.ts +27 -0
  51. package/dest/sqlite-opfs/errors.d.ts.map +1 -0
  52. package/dest/sqlite-opfs/errors.js +34 -0
  53. package/dest/sqlite-opfs/index.d.ts +16 -0
  54. package/dest/sqlite-opfs/index.d.ts.map +1 -0
  55. package/dest/sqlite-opfs/index.js +22 -0
  56. package/dest/sqlite-opfs/internal/ordered-binary-browser.d.ts +32 -0
  57. package/dest/sqlite-opfs/internal/ordered-binary-browser.d.ts.map +1 -0
  58. package/dest/sqlite-opfs/internal/ordered-binary-browser.js +448 -0
  59. package/dest/sqlite-opfs/map.d.ts +35 -0
  60. package/dest/sqlite-opfs/map.d.ts.map +1 -0
  61. package/dest/sqlite-opfs/map.js +163 -0
  62. package/dest/sqlite-opfs/messages.d.ts +66 -0
  63. package/dest/sqlite-opfs/messages.d.ts.map +1 -0
  64. package/dest/sqlite-opfs/messages.js +5 -0
  65. package/dest/sqlite-opfs/multi_map.d.ts +16 -0
  66. package/dest/sqlite-opfs/multi_map.d.ts.map +1 -0
  67. package/dest/sqlite-opfs/multi_map.js +67 -0
  68. package/dest/sqlite-opfs/set.d.ts +13 -0
  69. package/dest/sqlite-opfs/set.d.ts.map +1 -0
  70. package/dest/sqlite-opfs/set.js +19 -0
  71. package/dest/sqlite-opfs/singleton.d.ts +13 -0
  72. package/dest/sqlite-opfs/singleton.d.ts.map +1 -0
  73. package/dest/sqlite-opfs/singleton.js +48 -0
  74. package/dest/sqlite-opfs/store.d.ts +79 -0
  75. package/dest/sqlite-opfs/store.d.ts.map +1 -0
  76. package/dest/sqlite-opfs/store.js +281 -0
  77. package/dest/sqlite-opfs/worker.d.ts +2 -0
  78. package/dest/sqlite-opfs/worker.d.ts.map +1 -0
  79. package/dest/sqlite-opfs/worker.js +244 -0
  80. package/dest/utils.d.ts +9 -6
  81. package/dest/utils.d.ts.map +1 -1
  82. package/dest/utils.js +51 -16
  83. package/package.json +28 -23
  84. package/src/bench/shared_map_bench.ts +111 -0
  85. package/src/indexeddb/array.ts +4 -4
  86. package/src/indexeddb/index.ts +8 -6
  87. package/src/indexeddb/map.ts +24 -11
  88. package/src/indexeddb/multi_map.ts +15 -1
  89. package/src/indexeddb/singleton.ts +1 -1
  90. package/src/indexeddb/store.ts +13 -6
  91. package/src/interfaces/array_test_suite.ts +33 -35
  92. package/src/interfaces/index.ts +1 -1
  93. package/src/interfaces/map_test_suite.ts +56 -30
  94. package/src/interfaces/multi_map_test_suite.ts +88 -58
  95. package/src/interfaces/set_test_suite.ts +13 -15
  96. package/src/interfaces/singleton_test_suite.ts +6 -8
  97. package/src/interfaces/utils.ts +1 -0
  98. package/src/lmdb/index.ts +8 -3
  99. package/src/lmdb-v2/factory.ts +15 -11
  100. package/src/lmdb-v2/store.ts +3 -2
  101. package/src/sqlite-opfs/array.ts +124 -0
  102. package/src/sqlite-opfs/errors.ts +44 -0
  103. package/src/sqlite-opfs/index.ts +39 -0
  104. package/src/sqlite-opfs/internal/ordered-binary-browser.js +465 -0
  105. package/src/sqlite-opfs/map.ts +163 -0
  106. package/src/sqlite-opfs/messages.ts +39 -0
  107. package/src/sqlite-opfs/multi_map.ts +74 -0
  108. package/src/sqlite-opfs/set.ts +29 -0
  109. package/src/sqlite-opfs/singleton.ts +48 -0
  110. package/src/sqlite-opfs/store.ts +296 -0
  111. package/src/sqlite-opfs/worker.ts +226 -0
  112. package/src/utils.ts +79 -21
@@ -1,6 +1,6 @@
1
1
  import { EthAddress } from '@aztec/foundation/eth-address';
2
- import { type Logger, createLogger } from '@aztec/foundation/log';
3
- import { DatabaseVersionManager } from '@aztec/stdlib/database-version';
2
+ import { type LoggerBindings, createLogger } from '@aztec/foundation/log';
3
+ import { DatabaseVersionManager } from '@aztec/stdlib/database-version/manager';
4
4
 
5
5
  import { mkdir, mkdtemp, rm } from 'fs/promises';
6
6
  import { tmpdir } from 'os';
@@ -15,8 +15,9 @@ export async function createStore(
15
15
  name: string,
16
16
  schemaVersion: number,
17
17
  config: DataStoreConfig,
18
- log: Logger = createLogger('kv-store:lmdb-v2:' + name),
18
+ bindings?: LoggerBindings,
19
19
  ): Promise<AztecLMDBStoreV2> {
20
+ const log = createLogger('kv-store:lmdb-v2:' + name, bindings);
20
21
  const { dataDirectory, l1Contracts } = config;
21
22
 
22
23
  let store: AztecLMDBStoreV2;
@@ -33,7 +34,7 @@ export async function createStore(
33
34
  rollupAddress,
34
35
  dataDirectory: subDir,
35
36
  onOpen: dbDirectory =>
36
- AztecLMDBStoreV2.new(dbDirectory, config.dataStoreMapSizeKb, MAX_READERS, () => Promise.resolve(), log),
37
+ AztecLMDBStoreV2.new(dbDirectory, config.dataStoreMapSizeKb, MAX_READERS, () => Promise.resolve(), bindings),
37
38
  });
38
39
 
39
40
  log.info(
@@ -41,7 +42,7 @@ export async function createStore(
41
42
  );
42
43
  [store] = await versionManager.open();
43
44
  } else {
44
- store = await openTmpStore(name, true, config.dataStoreMapSizeKb, MAX_READERS, log);
45
+ store = await openTmpStore(name, true, config.dataStoreMapSizeKb, MAX_READERS, bindings);
45
46
  }
46
47
 
47
48
  return store;
@@ -52,8 +53,9 @@ export async function openTmpStore(
52
53
  ephemeral: boolean = true,
53
54
  dbMapSizeKb = 10 * 1_024 * 1_024, // 10GB
54
55
  maxReaders = MAX_READERS,
55
- log: Logger = createLogger('kv-store:lmdb-v2:' + name),
56
+ bindings?: LoggerBindings,
56
57
  ): Promise<AztecLMDBStoreV2> {
58
+ const log = createLogger('kv-store:lmdb-v2:' + name, bindings);
57
59
  const dataDir = await mkdtemp(join(tmpdir(), name + '-'));
58
60
  log.debug(`Created temporary data store at: ${dataDir} with size: ${dbMapSizeKb} KB (LMDB v2)`);
59
61
 
@@ -73,17 +75,18 @@ export async function openTmpStore(
73
75
 
74
76
  // For temporary stores, we don't need to worry about versioning
75
77
  // as they are ephemeral and get cleaned up after use
76
- return AztecLMDBStoreV2.new(dataDir, dbMapSizeKb, maxReaders, cleanup, log);
78
+ return AztecLMDBStoreV2.new(dataDir, dbMapSizeKb, maxReaders, cleanup, bindings);
77
79
  }
78
80
 
79
81
  export async function openStoreAt(
80
82
  dataDir: string,
81
83
  dbMapSizeKb = 10 * 1_024 * 1_024, // 10GB
82
84
  maxReaders = MAX_READERS,
83
- log: Logger = createLogger('kv-store:lmdb-v2'),
85
+ bindings?: LoggerBindings,
84
86
  ): Promise<AztecLMDBStoreV2> {
87
+ const log = createLogger('kv-store:lmdb-v2', bindings);
85
88
  log.debug(`Opening data store at: ${dataDir} with size: ${dbMapSizeKb} KB (LMDB v2)`);
86
- return await AztecLMDBStoreV2.new(dataDir, dbMapSizeKb, maxReaders, undefined, log);
89
+ return await AztecLMDBStoreV2.new(dataDir, dbMapSizeKb, maxReaders, undefined, bindings);
87
90
  }
88
91
 
89
92
  export async function openVersionedStoreAt(
@@ -92,14 +95,15 @@ export async function openVersionedStoreAt(
92
95
  rollupAddress: EthAddress,
93
96
  dbMapSizeKb = 10 * 1_024 * 1_024, // 10GB
94
97
  maxReaders = MAX_READERS,
95
- log: Logger = createLogger('kv-store:lmdb-v2'),
98
+ bindings?: LoggerBindings,
96
99
  ): Promise<AztecLMDBStoreV2> {
100
+ const log = createLogger('kv-store:lmdb-v2', bindings);
97
101
  log.debug(`Opening data store at: ${dataDirectory} with size: ${dbMapSizeKb} KB (LMDB v2)`);
98
102
  const [store] = await new DatabaseVersionManager({
99
103
  schemaVersion,
100
104
  rollupAddress,
101
105
  dataDirectory,
102
- onOpen: dataDir => AztecLMDBStoreV2.new(dataDir, dbMapSizeKb, maxReaders, undefined, log),
106
+ onOpen: dataDir => AztecLMDBStoreV2.new(dataDir, dbMapSizeKb, maxReaders, undefined, bindings),
103
107
  }).open();
104
108
  return store;
105
109
  }
@@ -1,4 +1,4 @@
1
- import { type Logger, createLogger } from '@aztec/foundation/log';
1
+ import { type Logger, type LoggerBindings, createLogger } from '@aztec/foundation/log';
2
2
  import { Semaphore, SerialQueue } from '@aztec/foundation/queue';
3
3
  import { MsgpackChannel, NativeLMDBStore } from '@aztec/native';
4
4
 
@@ -75,8 +75,9 @@ export class AztecLMDBStoreV2 implements AztecAsyncKVStore, LMDBMessageChannel {
75
75
  dbMapSizeKb: number = 10 * 1024 * 1024,
76
76
  maxReaders: number = 16,
77
77
  cleanup?: () => Promise<void>,
78
- log = createLogger('kv-store:lmdb-v2'),
78
+ bindings?: LoggerBindings,
79
79
  ) {
80
+ const log = createLogger('kv-store:lmdb-v2', bindings);
80
81
  const db = new AztecLMDBStoreV2(dataDir, dbMapSizeKb, maxReaders, log, cleanup);
81
82
  await db.start();
82
83
  return db;
@@ -0,0 +1,124 @@
1
+ import { Encoder } from '#msgpackr';
2
+ import { toBufferKey } from '#ordered-binary';
3
+ import { hash } from 'ohash';
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,44 @@
1
+ /**
2
+ * Typed error surface for sqlite3mc-backed page-level encryption failures.
3
+ *
4
+ * Three concrete failure modes are surfaced:
5
+ *
6
+ * - `invalid_key_length`: caller-side pre-flight (key not 32 bytes).
7
+ * - `encryption_not_supported_for_ephemeral`: caller-side pre-flight (encryption was requested on an ephemeral
8
+ * `:memory:` store, which sqlite3mc does not support).
9
+ * - `decrypt_failed`: runtime failure raised when sqlite3mc cannot decode page 1 of an existing database. Covers
10
+ * both "wrong key supplied" and "no key supplied to an encrypted DB".
11
+ */
12
+ export type SqliteEncryptionErrorCode =
13
+ | 'invalid_key_length'
14
+ | 'encryption_not_supported_for_ephemeral'
15
+ | 'decrypt_failed';
16
+
17
+ /**
18
+ * Error thrown by sqlite-opfs when an encryption operation fails.
19
+ **/
20
+ export class SqliteEncryptionError extends Error {
21
+ readonly code: SqliteEncryptionErrorCode;
22
+
23
+ constructor(code: SqliteEncryptionErrorCode, message: string, opts?: { cause?: unknown }) {
24
+ super(message, opts?.cause !== undefined ? { cause: opts.cause } : undefined);
25
+ this.name = 'SqliteEncryptionError';
26
+ this.code = code;
27
+ }
28
+ }
29
+
30
+ /**
31
+ * Strings raised by sqlite3mc when page 1 cannot be decoded.
32
+ **/
33
+ const SQLITE3MC_DECRYPT_ERROR_PATTERNS: readonly RegExp[] = [
34
+ /file is not a database/i,
35
+ /file is encrypted or is not a database/i,
36
+ ];
37
+
38
+ /**
39
+ * Returns `true` if `message` matches one of the known sqlite3mc decrypt-failure
40
+ * strings.
41
+ **/
42
+ export function isDecryptFailureMessage(message: string): boolean {
43
+ return SQLITE3MC_DECRYPT_ERROR_PATTERNS.some(p => p.test(message));
44
+ }
@@ -0,0 +1,39 @@
1
+ import { type Logger, createLogger } from '@aztec/foundation/log';
2
+
3
+ import type { DataStoreConfig } from '../config.js';
4
+ import { initStoreForRollupAndSchemaVersion } from '../utils.js';
5
+ import { AztecSQLiteOPFSStore } from './store.js';
6
+
7
+ export { AztecSQLiteOPFSStore } from './store.js';
8
+ export { SqliteEncryptionError } from './errors.js';
9
+ export type { SqliteEncryptionErrorCode } from './errors.js';
10
+
11
+ export async function createStore(
12
+ name: string,
13
+ config: DataStoreConfig,
14
+ schemaVersion: number | undefined = undefined,
15
+ log: Logger = createLogger('kv-store'),
16
+ ) {
17
+ const { dataDirectory } = config;
18
+ log.info(
19
+ dataDirectory
20
+ ? `Creating ${name} SQLite-OPFS data store with map size ${config.dataStoreMapSizeKb} KB`
21
+ : `Creating ${name} ephemeral SQLite-OPFS data store with map size ${config.dataStoreMapSizeKb} KB`,
22
+ );
23
+ const store = await AztecSQLiteOPFSStore.open(createLogger('kv-store:sqlite-opfs'), name, false);
24
+ return initStoreForRollupAndSchemaVersion(store, schemaVersion, config.l1Contracts?.rollupAddress, log);
25
+ }
26
+
27
+ export function openTmpStore(ephemeral: boolean = false): Promise<AztecSQLiteOPFSStore> {
28
+ return AztecSQLiteOPFSStore.open(createLogger('kv-store:sqlite-opfs'), undefined, ephemeral);
29
+ }
30
+
31
+ /**
32
+ * Convenience helper for tests and consumers that want an encrypted sqlite-opfs
33
+ * store without dealing with the full `open()` parameter order. Key must be 32
34
+ * bytes. Creates a fresh persistent store (sqlite3mc does not support encryption
35
+ * on ephemeral `:memory:` databases) in an auto-generated OPFS directory.
36
+ */
37
+ export function openEncryptedStore(encryptionKey: Uint8Array, name?: string, poolDirectory?: string) {
38
+ return AztecSQLiteOPFSStore.open(createLogger('kv-store:sqlite-opfs'), name, false, poolDirectory, encryptionKey);
39
+ }