@optimystic/db-p2p-storage-fs 0.22.0 → 0.24.1

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.
@@ -1,418 +1,422 @@
1
- import { promises as fs } from 'fs';
2
- import * as path from 'path';
3
- import type { BlockId, ActionId } from "@optimystic/db-core";
4
- import { KvRawStorage, type RawStoreDriver } from "@optimystic/db-p2p";
5
- import { createLogger } from './logger.js';
6
- import { atomicWriteFile } from './atomic-write.js';
7
-
8
- const log = createLogger('storage:file');
9
-
10
- const decoder = new TextDecoder();
11
-
12
- // Colons are illegal in Windows filenames; encode them so action ids like
13
- // `tx:<hash>` and `stamp:<hash>` round-trip safely on all platforms.
14
- function encodeActionIdForFilename(actionId: ActionId): string {
15
- return actionId.replace(/:/g, '%3A');
16
- }
17
-
18
- function decodeFilenameToActionId(filename: string): ActionId {
19
- return filename.replace(/%3A/g, ':') as ActionId;
20
- }
21
-
22
- // A torn write leaves valid-prefix JSON cut off mid-token — JSON.parse throws
23
- // SyntaxError. Used as the "corrupt content → treat as missing" guard so a
24
- // crash-truncated file reads as absent (letting recover() make progress) instead
25
- // of surfacing a parse error forever. Only the JSON-valued stores use this; the
26
- // revisions store holds a bare ActionId string (not JSON) and is never guarded.
27
- // NOTE: every guarded read parses the JSON here (validate, discard) and the kernel's
28
- // decodeJson parses the same bytes AGAIN to build the value — 2× parse per get. The
29
- // guard is intrinsic to the driver's "corrupt→missing" contract (the kernel can't
30
- // express it), so it can't simply be dropped. Fine at current read volumes; if a read
31
- // path ever shows up hot, parse once and thread the parsed value through the driver.
32
- function isParseableJson(bytes: Uint8Array): boolean {
33
- try {
34
- JSON.parse(decoder.decode(bytes));
35
- return true;
36
- } catch (err) {
37
- if (err instanceof SyntaxError) return false;
38
- throw err;
39
- }
40
- }
41
-
42
- /**
43
- * Filesystem {@link RawStoreDriver}: the five logical block-storage stores mapped
44
- * to five subdirectories under `basePath/<blockId>/`
45
- * (`{meta.json,revs/,pend/,actions/,blocks/}`). The directory tree is a
46
- * deliberate, human-inspectable/debuggable layout — it is NOT flattened into
47
- * encoded-filename KV keys.
48
- *
49
- * `KvRawStorage` now owns all JSON serialization, so this driver reads/writes raw
50
- * `Uint8Array` bytes and never does `JSON.stringify/parse` on values. Everything
51
- * else fs-specific lives here: atomic (temp-file + rename) writes, the
52
- * corrupt-content-as-missing read guard, colon-encoded action-id filenames with
53
- * the legacy raw-colon read fallback + win32 guards, and rename-based promote.
54
- */
55
- export class FileStoreDriver implements RawStoreDriver {
56
- constructor(private readonly basePath: string) {
57
- // TODO: use https://www.npmjs.com/package/proper-lockfile to take a lock on the basePath, also introduce explicit dispose pattern
58
- }
59
-
60
- // --- metadata ---
61
-
62
- async getMetadata(blockId: BlockId): Promise<Uint8Array | undefined> {
63
- return this.readBytesIfExists(this.getMetadataPath(blockId), true);
64
- }
65
-
66
- async putMetadata(blockId: BlockId, value: Uint8Array): Promise<void> {
67
- await atomicWriteFile(this.getMetadataPath(blockId), value);
68
- }
69
-
70
- // --- revisions ---
71
-
72
- // The revisions store value is a bare ActionId string (kernel `encodeActionId`,
73
- // NOT JSON), so it is read WITHOUT the JSON guard — any bytes are a valid string
74
- // and `decodeActionId` never throws.
75
- // NOTE: because there is no guard here, a *torn* revision file reads back as a wrong
76
- // (truncated) ActionId rather than as missing — unlike the JSON stores, which torn-read
77
- // as undefined. Atomic writes (temp+rename) make a new torn revision impossible; only a
78
- // legacy pre-atomic-write torn rev could hit this, and recover() re-derives revisions
79
- // from the actions store anyway. If revisions ever move to a non-atomic writer, add a
80
- // checksum/length guard here.
81
- async getRevision(blockId: BlockId, rev: number): Promise<Uint8Array | undefined> {
82
- return this.readBytesIfExists(this.getRevisionPath(blockId, rev), false);
83
- }
84
-
85
- async putRevision(blockId: BlockId, rev: number, value: Uint8Array): Promise<void> {
86
- await atomicWriteFile(this.getRevisionPath(blockId, rev), value);
87
- }
88
-
89
- async *rangeRevisions(blockId: BlockId, lo: number, hi: number, reverse: boolean): AsyncIterable<[number, Uint8Array]> {
90
- // The fs backend has no cursor: walk the bounded [lo, hi] range rev-by-rev,
91
- // reading each present rev. The range is caller-bounded, so this avoids
92
- // listing an unbounded revs/ directory. Drain into an array BEFORE yielding
93
- // (drain-before-yield contract) — matches the memory/native drivers and keeps
94
- // the consumer's interleaved awaits from straddling any in-flight read.
95
- const results: [number, Uint8Array][] = [];
96
- for (let rev = lo; rev <= hi; rev++) {
97
- const value = await this.readBytesIfExists(this.getRevisionPath(blockId, rev), false);
98
- if (value !== undefined) {
99
- results.push([rev, value]);
100
- }
101
- }
102
- if (reverse) {
103
- results.reverse();
104
- }
105
- for (const result of results) {
106
- yield result;
107
- }
108
- }
109
-
110
- // --- pending ---
111
-
112
- async getPending(blockId: BlockId, actionId: ActionId): Promise<Uint8Array | undefined> {
113
- return this.readActionScopedBytes(
114
- this.getPendingActionPath(blockId, actionId),
115
- this.getPendingActionPath(blockId, actionId, false)
116
- );
117
- }
118
-
119
- async putPending(blockId: BlockId, actionId: ActionId, value: Uint8Array): Promise<void> {
120
- await atomicWriteFile(this.getPendingActionPath(blockId, actionId), value);
121
- }
122
-
123
- async deletePending(blockId: BlockId, actionId: ActionId): Promise<void> {
124
- const pendingPath = this.getPendingActionPath(blockId, actionId);
125
- await fs.unlink(pendingPath)
126
- .catch((err) => {
127
- if ((err as NodeJS.ErrnoException)?.code !== 'ENOENT') log('deletePending unlink failed for %s/%s - %o', blockId, actionId, err);
128
- });
129
- await this.unlinkRawColon(pendingPath, this.getPendingActionPath(blockId, actionId, false));
130
- }
131
-
132
- async *listPendingActionIds(blockId: BlockId): AsyncIterable<ActionId> {
133
- const pendingPath = path.join(this.getBlockPath(blockId), 'pend');
134
-
135
- // Only a genuinely-absent directory (ENOENT) maps to "no pendings". Any other error
136
- // (EACCES, EIO, ENOTDIR, ...) must surface — swallowing it here would make
137
- // listPendingActionIds silently report an empty directory, so pend's conflict
138
- // detection would be skipped. Mirrors directoryByteSize's ENOENT-vs-other discrimination.
139
- const files = await fs.readdir(pendingPath).catch((err) => {
140
- if ((err as NodeJS.ErrnoException)?.code === 'ENOENT') return [] as string[];
141
- log('listPendingActionIds readdir failed for %s - %o', blockId, err);
142
- throw err;
143
- });
144
- // Drain into an array before yielding (drain-before-yield): readdir has already
145
- // resolved the full listing, so this just decodes/filters up front.
146
- const ids: ActionId[] = [];
147
- for (const file of files) {
148
- if (!file.endsWith('.json')) continue;
149
- const actionId = decodeFilenameToActionId(file.slice(0, -5));
150
- // Accept every realistic action id: legacy UUIDs (`[0-9a-f-]`), consensus
151
- // tx:/stamp: ids (base64url-encoded SHA-256, alphabet `[A-Za-z0-9_-]` — see
152
- // db-core hashString, NOT lowercase hex), AND the bare-alphanumeric ids the
153
- // cross-backend conformance suite uses (`a1`, `b1`, ...). This is deliberately
154
- // broad-but-not-total: an id is any `[A-Za-z0-9_-]` string, optionally prefixed
155
- // with `tx:`/`stamp:`. It is NOT a total accept — a file whose decoded name
156
- // carries other punctuation (a dot, a space) is genuine junk in pend/ and is
157
- // logged-and-skipped rather than surfaced as a phantom pending. The memory/db
158
- // reference drivers key on the raw id and never see a filesystem name, so this
159
- // filter is fs-only; it must not drop an id those backends would list, hence the
160
- // widened class (an earlier hex-only class silently dropped real consensus ids —
161
- // see `optimystic-filestorage-colon-actionid-windows`).
162
- if (!/^(?:tx:|stamp:)?[A-Za-z0-9_-]+$/.test(actionId)) {
163
- // Leave a breadcrumb rather than silently dropping: the .json + decode guard
164
- // already excludes *.tmp orphans, so anything reaching here is an unexpected
165
- // filename a maintainer should see.
166
- log('listPendingActionIds skipping unrecognized action-id file %s for %s', file, blockId);
167
- continue;
168
- }
169
- ids.push(actionId);
170
- }
171
- for (const id of ids) {
172
- yield id;
173
- }
174
- }
175
-
176
- // --- transactions ---
177
-
178
- async getTransaction(blockId: BlockId, actionId: ActionId): Promise<Uint8Array | undefined> {
179
- return this.readActionScopedBytes(
180
- this.getActionPath(blockId, actionId),
181
- this.getActionPath(blockId, actionId, false)
182
- );
183
- }
184
-
185
- async putTransaction(blockId: BlockId, actionId: ActionId, value: Uint8Array): Promise<void> {
186
- await atomicWriteFile(this.getActionPath(blockId, actionId), value);
187
- }
188
-
189
- // --- materialized ---
190
-
191
- async getMaterialized(blockId: BlockId, actionId: ActionId): Promise<Uint8Array | undefined> {
192
- return this.readActionScopedBytes(
193
- this.getMaterializedPath(blockId, actionId),
194
- this.getMaterializedPath(blockId, actionId, false)
195
- );
196
- }
197
-
198
- async putMaterialized(blockId: BlockId, actionId: ActionId, value: Uint8Array): Promise<void> {
199
- await atomicWriteFile(this.getMaterializedPath(blockId, actionId), value);
200
- }
201
-
202
- // The kernel owns the put-or-delete branch of `saveMaterializedBlock`, so the
203
- // driver exposes delete as a separate op.
204
- async deleteMaterialized(blockId: BlockId, actionId: ActionId): Promise<void> {
205
- const matPath = this.getMaterializedPath(blockId, actionId);
206
- await fs.unlink(matPath)
207
- .catch((err) => {
208
- if ((err as NodeJS.ErrnoException)?.code !== 'ENOENT') log('deleteMaterialized unlink failed for %s/%s - %o', blockId, actionId, err);
209
- });
210
- await this.unlinkRawColon(matPath, this.getMaterializedPath(blockId, actionId, false));
211
- }
212
-
213
- // --- promote (the only cross-key atomic op) ---
214
-
215
- async promote(blockId: BlockId, actionId: ActionId): Promise<void> {
216
- const pendingPath = this.getPendingActionPath(blockId, actionId);
217
- const actionPath = this.getActionPath(blockId, actionId);
218
-
219
- await fs.mkdir(path.dirname(actionPath), { recursive: true });
220
-
221
- // This single rename IS the atomic move — it is why fs honors the kernel's
222
- // promote contract without a WAL. A crash leaves either the pending or the
223
- // committed file, never both/neither. Do NOT replace with read-write-delete.
224
- return fs.rename(pendingPath, actionPath)
225
- .catch(err => {
226
- if (err.code === 'ENOENT') {
227
- throw new Error(`Pending action ${actionId} not found for block ${blockId}`);
228
- }
229
- log('promote rename failed for %s/%s - %o', blockId, actionId, err);
230
- throw err;
231
- });
232
- }
233
-
234
- // --- optional passthroughs ---
235
-
236
- async *listBlockIds(): AsyncIterable<BlockId> {
237
- // The block layout is `basePath/<blockId>/{meta.json,revs/,pend/,actions/,blocks/}`
238
- // (see getBlockPath), so the direct children of basePath are the per-block directories
239
- // and each directory NAME is the blockId (used raw, no encoding). Filter to directories
240
- // so a stray file can't be mistaken for a block; `*.tmp` atomic-write orphans live inside
241
- // block subdirs, never at basePath root, so the root is clean.
242
- //
243
- // A directory alone is NOT sufficient to call a block "durable owned": a block that was
244
- // only PENDED (never committed) still creates `<blockId>/pend/` — hence a root directory
245
- // entry — via atomicWriteFile's recursive mkdir, but has no meta.json. So we gate on
246
- // meta.json existence: `meta.json` IS this backend's metadata store, and enumerating it
247
- // yields exactly the blocks with a committed revision / persisted replica (the same
248
- // "owned" population the live change feed tracks, and the same one the metadata-keyed
249
- // backends — sqlite/leveldb/indexeddb — enumerate for free). Existence (fs.access), not
250
- // parse, matches key-existence semantics: a torn/corrupt meta.json still counts as a key,
251
- // exactly as a corrupt value would in the other backends.
252
- //
253
- // ENOENT (basePath not created yet, or a dir without meta.json) maps to "not owned" —
254
- // same discrimination as directoryByteSize. Any OTHER readdir/access error must surface:
255
- // swallowing it would make the seed falsely report an empty store and under-protect data
256
- // already on disk.
257
- // NOTE: reads the whole root listing up front + one meta.json stat per block dir; if a
258
- // store ever grows to millions of block subdirs and this becomes a startup-latency
259
- // problem, page it (e.g. opendir cursor) — fine at current scale.
260
- const entries = await fs.readdir(this.basePath, { withFileTypes: true })
261
- .catch((err) => {
262
- if ((err as NodeJS.ErrnoException)?.code === 'ENOENT') return [];
263
- log('listBlockIds readdir failed for %s - %o', this.basePath, err);
264
- throw err;
265
- });
266
- for (const entry of entries) {
267
- if (!entry.isDirectory()) continue;
268
- const blockId = entry.name as BlockId;
269
- const hasMeta = await fs.access(this.getMetadataPath(blockId))
270
- .then(() => true)
271
- .catch((err) => {
272
- if ((err as NodeJS.ErrnoException)?.code === 'ENOENT') return false;
273
- log('listBlockIds access failed for %s - %o', blockId, err);
274
- throw err;
275
- });
276
- if (hasMeta) yield blockId;
277
- }
278
- }
279
-
280
- async approximateBytesUsed(): Promise<number> {
281
- return this.directoryByteSize(this.basePath);
282
- }
283
-
284
- private async directoryByteSize(dir: string): Promise<number> {
285
- const entries = await fs.readdir(dir, { withFileTypes: true })
286
- .catch((err) => {
287
- if ((err as NodeJS.ErrnoException)?.code === 'ENOENT') return [];
288
- log('directoryByteSize readdir failed for %s - %o', dir, err);
289
- return [];
290
- });
291
-
292
- let total = 0;
293
- for (const entry of entries) {
294
- const entryPath = path.join(dir, entry.name);
295
- if (entry.isDirectory()) {
296
- total += await this.directoryByteSize(entryPath);
297
- } else if (entry.isFile()) {
298
- const size = await fs.stat(entryPath)
299
- .then(st => st.size)
300
- .catch((err) => {
301
- if ((err as NodeJS.ErrnoException)?.code === 'ENOENT') return 0;
302
- log('directoryByteSize stat failed for %s - %o', entryPath, err);
303
- return 0;
304
- });
305
- total += size;
306
- }
307
- }
308
- return total;
309
- }
310
-
311
- // --- paths ---
312
-
313
- private getBlockPath(blockId: BlockId): string {
314
- return path.join(this.basePath, blockId);
315
- }
316
-
317
- private getMetadataPath(blockId: BlockId): string {
318
- return path.join(this.getBlockPath(blockId), 'meta.json');
319
- }
320
-
321
- private getRevisionPath(blockId: BlockId, rev: number): string {
322
- return path.join(this.getBlockPath(blockId), 'revs', `${rev}.json`);
323
- }
324
-
325
- // `encoded` controls colon handling: writes and canonical reads use the
326
- // percent-encoded filename (encoded = true); the legacy raw-colon fallback
327
- // (see readActionScopedBytes) passes encoded = false to reach pre-encode
328
- // POSIX files like `actions/tx:<hash>.json`.
329
- private getPendingActionPath(blockId: BlockId, actionId: ActionId, encoded = true): string {
330
- const filename = encoded ? encodeActionIdForFilename(actionId) : actionId;
331
- return path.join(this.getBlockPath(blockId), 'pend', `${filename}.json`);
332
- }
333
-
334
- private getActionPath(blockId: BlockId, actionId: ActionId, encoded = true): string {
335
- const filename = encoded ? encodeActionIdForFilename(actionId) : actionId;
336
- return path.join(this.getBlockPath(blockId), 'actions', `${filename}.json`);
337
- }
338
-
339
- private getMaterializedPath(blockId: BlockId, actionId: ActionId, encoded = true): string {
340
- const filename = encoded ? encodeActionIdForFilename(actionId) : actionId;
341
- return path.join(this.getBlockPath(blockId), 'blocks', `${filename}.json`);
342
- }
343
-
344
- // Best-effort removal of a pre-encode raw-colon file after the encoded delete,
345
- // so a deleted item cannot resurface via the read fallback in readActionScopedBytes.
346
- // Skipped on win32 (raw-colon files cannot exist there) and when paths are identical
347
- // (action id contains no colon — only one syscall needed). ENOENT is silently ignored.
348
- private async unlinkRawColon(encodedPath: string, rawPath: string): Promise<void> {
349
- if (process.platform === 'win32' || rawPath === encodedPath) return;
350
- await fs.unlink(rawPath).catch((err) => {
351
- if ((err as NodeJS.ErrnoException)?.code !== 'ENOENT') log('unlinkRawColon failed for %s - %o', rawPath, err);
352
- });
353
- }
354
-
355
- // Reads an action-id-keyed file (JSON-valued) by its canonical (percent-encoded)
356
- // path, falling back on a miss to the legacy raw-colon path written by pre-encode
357
- // nodes (e.g. POSIX files literally named `actions/tx:<hash>.json`).
358
- //
359
- // Tradeoff: this reads legacy files in place and never renames them, so a
360
- // store upgraded from a pre-encode node keeps mixed naming on disk. That is
361
- // acceptable pre-1.0; a future migration sweep can normalize if desired. We
362
- // deliberately do NOT migrate-on-read here — reads stay side-effect-free.
363
- //
364
- // win32 guard: a raw-colon path is not a benign miss on Windows — the colon
365
- // is parsed as an NTFS alternate-data-stream separator and a read there can
366
- // throw a non-ENOENT error rather than cleanly missing. Raw-colon files
367
- // cannot have been written on win32 anyway, so we skip the fallback there
368
- // (losing nothing) and swallow ALL fallback errors elsewhere, guaranteeing
369
- // the fallback never surfaces a new throw to callers.
370
- private async readActionScopedBytes(encodedPath: string, rawPath: string): Promise<Uint8Array | undefined> {
371
- const hit = await this.readBytesIfExists(encodedPath, true);
372
- if (hit !== undefined) return hit;
373
- if (process.platform === 'win32' || rawPath === encodedPath) return undefined;
374
- return fs.readFile(rawPath)
375
- .then(bytes => (isParseableJson(bytes) ? bytes : undefined))
376
- .catch(() => undefined);
377
- }
378
-
379
- // Reads a file's raw bytes. ENOENT → undefined. When `jsonGuard` is set, a
380
- // present-but-corrupt file (JSON.parse fails — most likely a torn write from a
381
- // crash before atomic writes existed) is treated as "missing" so recover() and
382
- // normal reads make progress instead of rethrowing forever. A real I/O error
383
- // (permissions, EIO, EISDIR, ...) still throws — it must not be masked.
384
- private async readBytesIfExists(filePath: string, jsonGuard: boolean): Promise<Uint8Array | undefined> {
385
- let bytes: Uint8Array;
386
- try {
387
- bytes = await fs.readFile(filePath);
388
- } catch (err) {
389
- if ((err as NodeJS.ErrnoException)?.code === 'ENOENT') return undefined;
390
- throw err;
391
- }
392
- if (jsonGuard && !isParseableJson(bytes)) {
393
- log('readBytesIfExists: corrupt JSON at %s, treating as missing', filePath);
394
- return undefined;
395
- }
396
- return bytes;
397
- }
398
- }
399
-
400
- /**
401
- * Filesystem-backed {@link IRawStorage}, now a thin shell over the shared
402
- * {@link KvRawStorage} kernel driven by a {@link FileStoreDriver}. The public
403
- * name/constructor (`new FileRawStorage(basePath)`) is unchanged so existing
404
- * imports keep resolving; the kernel supplies the `IRawStorage` surface and the
405
- * driver supplies fs behavior.
406
- *
407
- * `listBlockIds`/`getApproximateBytesUsed` are re-declared here as always-present
408
- * (the fs driver always implements them, so the kernel constructor always wires
409
- * them) — the base declares them optional, but every fs consumer relies on them.
410
- */
411
- export class FileRawStorage extends KvRawStorage {
412
- declare listBlockIds: () => AsyncIterable<BlockId>;
413
- declare getApproximateBytesUsed: () => Promise<number>;
414
-
415
- constructor(basePath: string) {
416
- super(new FileStoreDriver(basePath));
417
- }
418
- }
1
+ import { promises as fs } from 'fs';
2
+ import * as path from 'path';
3
+ import type { BlockId, ActionId } from "@optimystic/db-core";
4
+ import { KvRawStorage, type RawStoreDriver } from "@optimystic/db-p2p";
5
+ import { createLogger } from './logger.js';
6
+ import { atomicWriteFile } from './atomic-write.js';
7
+
8
+ const log = createLogger('storage:file');
9
+
10
+ const decoder = new TextDecoder();
11
+
12
+ // Colons are illegal in Windows filenames; encode them so action ids like
13
+ // `tx:<hash>` and `stamp:<hash>` round-trip safely on all platforms.
14
+ function encodeActionIdForFilename(actionId: ActionId): string {
15
+ return actionId.replace(/:/g, '%3A');
16
+ }
17
+
18
+ function decodeFilenameToActionId(filename: string): ActionId {
19
+ return filename.replace(/%3A/g, ':') as ActionId;
20
+ }
21
+
22
+ // A torn write leaves valid-prefix JSON cut off mid-token — JSON.parse throws
23
+ // SyntaxError. Used as the "corrupt content → treat as missing" guard so a
24
+ // crash-truncated file reads as absent (letting recover() make progress) instead
25
+ // of surfacing a parse error forever. Only the JSON-valued stores use this; the
26
+ // revisions store holds a bare ActionId string (not JSON) and is never guarded.
27
+ // NOTE: every guarded read parses the JSON here (validate, discard) and the kernel's
28
+ // decodeJson parses the same bytes AGAIN to build the value — 2× parse per get. The
29
+ // guard is intrinsic to the driver's "corrupt→missing" contract (the kernel can't
30
+ // express it), so it can't simply be dropped. Fine at current read volumes; if a read
31
+ // path ever shows up hot, parse once and thread the parsed value through the driver.
32
+ function isParseableJson(bytes: Uint8Array): boolean {
33
+ try {
34
+ JSON.parse(decoder.decode(bytes));
35
+ return true;
36
+ } catch (err) {
37
+ if (err instanceof SyntaxError) return false;
38
+ throw err;
39
+ }
40
+ }
41
+
42
+ /**
43
+ * Filesystem {@link RawStoreDriver}: the five logical block-storage stores mapped
44
+ * to five subdirectories under `basePath/<blockId>/`
45
+ * (`{meta.json,revs/,pend/,actions/,blocks/}`). The directory tree is a
46
+ * deliberate, human-inspectable/debuggable layout — it is NOT flattened into
47
+ * encoded-filename KV keys.
48
+ *
49
+ * `KvRawStorage` now owns all JSON serialization, so this driver reads/writes raw
50
+ * `Uint8Array` bytes and never does `JSON.stringify/parse` on values. Everything
51
+ * else fs-specific lives here: atomic (temp-file + rename) writes, the
52
+ * corrupt-content-as-missing read guard, colon-encoded action-id filenames with
53
+ * the legacy raw-colon read fallback + win32 guards, and rename-based promote.
54
+ */
55
+ export class FileStoreDriver implements RawStoreDriver {
56
+ constructor(private readonly basePath: string) {
57
+ // TODO: use https://www.npmjs.com/package/proper-lockfile to take a lock on the basePath, also introduce explicit dispose pattern
58
+ }
59
+
60
+ // --- metadata ---
61
+
62
+ async getMetadata(blockId: BlockId): Promise<Uint8Array | undefined> {
63
+ return this.readBytesIfExists(this.getMetadataPath(blockId), true);
64
+ }
65
+
66
+ async putMetadata(blockId: BlockId, value: Uint8Array): Promise<void> {
67
+ await atomicWriteFile(this.getMetadataPath(blockId), value);
68
+ }
69
+
70
+ // --- revisions ---
71
+
72
+ // The revisions store value is a bare ActionId string (kernel `encodeActionId`,
73
+ // NOT JSON), so it is read WITHOUT the JSON guard — any bytes are a valid string
74
+ // and `decodeActionId` never throws.
75
+ // NOTE: because there is no guard here, a *torn* revision file reads back as a wrong
76
+ // (truncated) ActionId rather than as missing — unlike the JSON stores, which torn-read
77
+ // as undefined. Atomic writes (temp+rename) make a new torn revision impossible; only a
78
+ // legacy pre-atomic-write torn rev could hit this, and recover() re-derives revisions
79
+ // from the actions store anyway. If revisions ever move to a non-atomic writer, add a
80
+ // checksum/length guard here.
81
+ async getRevision(blockId: BlockId, rev: number): Promise<Uint8Array | undefined> {
82
+ return this.readBytesIfExists(this.getRevisionPath(blockId, rev), false);
83
+ }
84
+
85
+ async putRevision(blockId: BlockId, rev: number, value: Uint8Array): Promise<void> {
86
+ await atomicWriteFile(this.getRevisionPath(blockId, rev), value);
87
+ }
88
+
89
+ async *rangeRevisions(blockId: BlockId, lo: number, hi: number, reverse: boolean): AsyncIterable<[number, Uint8Array]> {
90
+ // The fs backend has no cursor: walk the bounded [lo, hi] range rev-by-rev,
91
+ // reading each present rev. The range is caller-bounded, so this avoids
92
+ // listing an unbounded revs/ directory. Drain into an array BEFORE yielding
93
+ // (drain-before-yield contract) — matches the memory/native drivers and keeps
94
+ // the consumer's interleaved awaits from straddling any in-flight read.
95
+ const results: [number, Uint8Array][] = [];
96
+ for (let rev = lo; rev <= hi; rev++) {
97
+ const value = await this.readBytesIfExists(this.getRevisionPath(blockId, rev), false);
98
+ if (value !== undefined) {
99
+ results.push([rev, value]);
100
+ }
101
+ }
102
+ if (reverse) {
103
+ results.reverse();
104
+ }
105
+ for (const result of results) {
106
+ yield result;
107
+ }
108
+ }
109
+
110
+ // --- pending ---
111
+
112
+ async getPending(blockId: BlockId, actionId: ActionId): Promise<Uint8Array | undefined> {
113
+ return this.readActionScopedBytes(
114
+ this.getPendingActionPath(blockId, actionId),
115
+ this.getPendingActionPath(blockId, actionId, false)
116
+ );
117
+ }
118
+
119
+ async putPending(blockId: BlockId, actionId: ActionId, value: Uint8Array): Promise<void> {
120
+ await atomicWriteFile(this.getPendingActionPath(blockId, actionId), value);
121
+ }
122
+
123
+ async deletePending(blockId: BlockId, actionId: ActionId): Promise<void> {
124
+ const pendingPath = this.getPendingActionPath(blockId, actionId);
125
+ await fs.unlink(pendingPath)
126
+ .catch((err) => {
127
+ if ((err as NodeJS.ErrnoException)?.code !== 'ENOENT') log('deletePending unlink failed for %s/%s - %o', blockId, actionId, err);
128
+ });
129
+ await this.unlinkRawColon(pendingPath, this.getPendingActionPath(blockId, actionId, false));
130
+ }
131
+
132
+ async *listPendingActionIds(blockId: BlockId): AsyncIterable<ActionId> {
133
+ const pendingPath = path.join(this.getBlockPath(blockId), 'pend');
134
+
135
+ // Only a genuinely-absent directory (ENOENT) maps to "no pendings". Any other error
136
+ // (EACCES, EIO, ENOTDIR, ...) must surface — swallowing it here would make
137
+ // listPendingActionIds silently report an empty directory, so pend's conflict
138
+ // detection would be skipped. Mirrors directoryByteSize's ENOENT-vs-other discrimination.
139
+ const files = await fs.readdir(pendingPath).catch((err) => {
140
+ if ((err as NodeJS.ErrnoException)?.code === 'ENOENT') return [] as string[];
141
+ log('listPendingActionIds readdir failed for %s - %o', blockId, err);
142
+ throw err;
143
+ });
144
+ // Drain into an array before yielding (drain-before-yield): readdir has already
145
+ // resolved the full listing, so this just decodes/filters up front.
146
+ const ids: ActionId[] = [];
147
+ for (const file of files) {
148
+ if (!file.endsWith('.json')) continue;
149
+ const actionId = decodeFilenameToActionId(file.slice(0, -5));
150
+ // Accept every realistic action id: legacy UUIDs (`[0-9a-f-]`), consensus
151
+ // tx:/stamp: ids (base64url-encoded SHA-256, alphabet `[A-Za-z0-9_-]` — see
152
+ // db-core hashString, NOT lowercase hex), AND the bare-alphanumeric ids the
153
+ // cross-backend conformance suite uses (`a1`, `b1`, ...). This is deliberately
154
+ // broad-but-not-total: an id is any `[A-Za-z0-9_-]` string, optionally prefixed
155
+ // with `tx:`/`stamp:`. It is NOT a total accept — a file whose decoded name
156
+ // carries other punctuation (a dot, a space) is genuine junk in pend/ and is
157
+ // logged-and-skipped rather than surfaced as a phantom pending. The memory/db
158
+ // reference drivers key on the raw id and never see a filesystem name, so this
159
+ // filter is fs-only; it must not drop an id those backends would list, hence the
160
+ // widened class (an earlier hex-only class silently dropped real consensus ids —
161
+ // see `optimystic-filestorage-colon-actionid-windows`).
162
+ if (!/^(?:tx:|stamp:)?[A-Za-z0-9_-]+$/.test(actionId)) {
163
+ // Leave a breadcrumb rather than silently dropping: the .json + decode guard
164
+ // already excludes *.tmp orphans, so anything reaching here is an unexpected
165
+ // filename a maintainer should see.
166
+ log('listPendingActionIds skipping unrecognized action-id file %s for %s', file, blockId);
167
+ continue;
168
+ }
169
+ ids.push(actionId);
170
+ }
171
+ for (const id of ids) {
172
+ yield id;
173
+ }
174
+ }
175
+
176
+ // --- transactions ---
177
+
178
+ async getTransaction(blockId: BlockId, actionId: ActionId): Promise<Uint8Array | undefined> {
179
+ return this.readActionScopedBytes(
180
+ this.getActionPath(blockId, actionId),
181
+ this.getActionPath(blockId, actionId, false)
182
+ );
183
+ }
184
+
185
+ async putTransaction(blockId: BlockId, actionId: ActionId, value: Uint8Array): Promise<void> {
186
+ await atomicWriteFile(this.getActionPath(blockId, actionId), value);
187
+ }
188
+
189
+ // --- materialized ---
190
+
191
+ async getMaterialized(blockId: BlockId, actionId: ActionId): Promise<Uint8Array | undefined> {
192
+ return this.readActionScopedBytes(
193
+ this.getMaterializedPath(blockId, actionId),
194
+ this.getMaterializedPath(blockId, actionId, false)
195
+ );
196
+ }
197
+
198
+ async putMaterialized(blockId: BlockId, actionId: ActionId, value: Uint8Array): Promise<void> {
199
+ await atomicWriteFile(this.getMaterializedPath(blockId, actionId), value);
200
+ }
201
+
202
+ // The kernel owns the put-or-delete branch of `saveMaterializedBlock`, so the
203
+ // driver exposes delete as a separate op.
204
+ async deleteMaterialized(blockId: BlockId, actionId: ActionId): Promise<void> {
205
+ const matPath = this.getMaterializedPath(blockId, actionId);
206
+ await fs.unlink(matPath)
207
+ .catch((err) => {
208
+ if ((err as NodeJS.ErrnoException)?.code !== 'ENOENT') log('deleteMaterialized unlink failed for %s/%s - %o', blockId, actionId, err);
209
+ });
210
+ await this.unlinkRawColon(matPath, this.getMaterializedPath(blockId, actionId, false));
211
+ }
212
+
213
+ // --- promote (the only cross-key atomic op) ---
214
+
215
+ async promote(blockId: BlockId, actionId: ActionId): Promise<void> {
216
+ const pendingPath = this.getPendingActionPath(blockId, actionId);
217
+ const actionPath = this.getActionPath(blockId, actionId);
218
+
219
+ await fs.mkdir(path.dirname(actionPath), { recursive: true });
220
+
221
+ // This single rename IS the atomic move — it is why fs honors the kernel's
222
+ // promote contract without a WAL. A crash leaves either the pending or the
223
+ // committed file, never both/neither. Do NOT replace with read-write-delete.
224
+ return fs.rename(pendingPath, actionPath)
225
+ .catch(err => {
226
+ if (err.code === 'ENOENT') {
227
+ throw new Error(`Pending action ${actionId} not found for block ${blockId}`);
228
+ }
229
+ log('promote rename failed for %s/%s - %o', blockId, actionId, err);
230
+ throw err;
231
+ });
232
+ }
233
+
234
+ // --- optional passthroughs ---
235
+
236
+ async *listBlockIds(): AsyncIterable<BlockId> {
237
+ // The block layout is `basePath/<blockId>/{meta.json,revs/,pend/,actions/,blocks/}`
238
+ // (see getBlockPath), so the direct children of basePath are the per-block directories
239
+ // and each directory NAME is the blockId (used raw, no encoding). Filter to directories
240
+ // so a stray file can't be mistaken for a block; `*.tmp` atomic-write orphans live inside
241
+ // block subdirs, never at basePath root, so the root is clean.
242
+ //
243
+ // A directory alone is NOT sufficient: pending a transform straight through this driver
244
+ // creates `<blockId>/pend/` — hence a root directory entry — via atomicWriteFile's
245
+ // recursive mkdir, without writing meta.json. So we gate on meta.json existence:
246
+ // `meta.json` IS this backend's metadata store, so gating on it enumerates exactly the
247
+ // same population the metadata-keyed backends (sqlite/leveldb/indexeddb) get for free.
248
+ // That population is every block with ANY durable metadata — which on the node path
249
+ // INCLUDES a pend-only block, because `BlockStorage.savePendingTransaction` seeds
250
+ // metadata for a block that has none before storing the transform. Do not "improve" this
251
+ // into a committed-revision filter: reading and parsing every meta.json would turn a
252
+ // cheap access() sweep into a per-block read at startup (see the `listBlockIds` contract
253
+ // in i-raw-storage.ts). Existence (fs.access), not parse, matches key-existence
254
+ // semantics: a torn/corrupt meta.json still counts as a key, exactly as a corrupt value
255
+ // would in the other backends.
256
+ //
257
+ // ENOENT (basePath not created yet, or a dir without meta.json) maps to "not owned" —
258
+ // same discrimination as directoryByteSize. Any OTHER readdir/access error must surface:
259
+ // swallowing it would make the seed falsely report an empty store and under-protect data
260
+ // already on disk.
261
+ // NOTE: reads the whole root listing up front + one meta.json stat per block dir; if a
262
+ // store ever grows to millions of block subdirs and this becomes a startup-latency
263
+ // problem, page it (e.g. opendir cursor) — fine at current scale.
264
+ const entries = await fs.readdir(this.basePath, { withFileTypes: true })
265
+ .catch((err) => {
266
+ if ((err as NodeJS.ErrnoException)?.code === 'ENOENT') return [];
267
+ log('listBlockIds readdir failed for %s - %o', this.basePath, err);
268
+ throw err;
269
+ });
270
+ for (const entry of entries) {
271
+ if (!entry.isDirectory()) continue;
272
+ const blockId = entry.name as BlockId;
273
+ const hasMeta = await fs.access(this.getMetadataPath(blockId))
274
+ .then(() => true)
275
+ .catch((err) => {
276
+ if ((err as NodeJS.ErrnoException)?.code === 'ENOENT') return false;
277
+ log('listBlockIds access failed for %s - %o', blockId, err);
278
+ throw err;
279
+ });
280
+ if (hasMeta) yield blockId;
281
+ }
282
+ }
283
+
284
+ async approximateBytesUsed(): Promise<number> {
285
+ return this.directoryByteSize(this.basePath);
286
+ }
287
+
288
+ private async directoryByteSize(dir: string): Promise<number> {
289
+ const entries = await fs.readdir(dir, { withFileTypes: true })
290
+ .catch((err) => {
291
+ if ((err as NodeJS.ErrnoException)?.code === 'ENOENT') return [];
292
+ log('directoryByteSize readdir failed for %s - %o', dir, err);
293
+ return [];
294
+ });
295
+
296
+ let total = 0;
297
+ for (const entry of entries) {
298
+ const entryPath = path.join(dir, entry.name);
299
+ if (entry.isDirectory()) {
300
+ total += await this.directoryByteSize(entryPath);
301
+ } else if (entry.isFile()) {
302
+ const size = await fs.stat(entryPath)
303
+ .then(st => st.size)
304
+ .catch((err) => {
305
+ if ((err as NodeJS.ErrnoException)?.code === 'ENOENT') return 0;
306
+ log('directoryByteSize stat failed for %s - %o', entryPath, err);
307
+ return 0;
308
+ });
309
+ total += size;
310
+ }
311
+ }
312
+ return total;
313
+ }
314
+
315
+ // --- paths ---
316
+
317
+ private getBlockPath(blockId: BlockId): string {
318
+ return path.join(this.basePath, blockId);
319
+ }
320
+
321
+ private getMetadataPath(blockId: BlockId): string {
322
+ return path.join(this.getBlockPath(blockId), 'meta.json');
323
+ }
324
+
325
+ private getRevisionPath(blockId: BlockId, rev: number): string {
326
+ return path.join(this.getBlockPath(blockId), 'revs', `${rev}.json`);
327
+ }
328
+
329
+ // `encoded` controls colon handling: writes and canonical reads use the
330
+ // percent-encoded filename (encoded = true); the legacy raw-colon fallback
331
+ // (see readActionScopedBytes) passes encoded = false to reach pre-encode
332
+ // POSIX files like `actions/tx:<hash>.json`.
333
+ private getPendingActionPath(blockId: BlockId, actionId: ActionId, encoded = true): string {
334
+ const filename = encoded ? encodeActionIdForFilename(actionId) : actionId;
335
+ return path.join(this.getBlockPath(blockId), 'pend', `${filename}.json`);
336
+ }
337
+
338
+ private getActionPath(blockId: BlockId, actionId: ActionId, encoded = true): string {
339
+ const filename = encoded ? encodeActionIdForFilename(actionId) : actionId;
340
+ return path.join(this.getBlockPath(blockId), 'actions', `${filename}.json`);
341
+ }
342
+
343
+ private getMaterializedPath(blockId: BlockId, actionId: ActionId, encoded = true): string {
344
+ const filename = encoded ? encodeActionIdForFilename(actionId) : actionId;
345
+ return path.join(this.getBlockPath(blockId), 'blocks', `${filename}.json`);
346
+ }
347
+
348
+ // Best-effort removal of a pre-encode raw-colon file after the encoded delete,
349
+ // so a deleted item cannot resurface via the read fallback in readActionScopedBytes.
350
+ // Skipped on win32 (raw-colon files cannot exist there) and when paths are identical
351
+ // (action id contains no colon — only one syscall needed). ENOENT is silently ignored.
352
+ private async unlinkRawColon(encodedPath: string, rawPath: string): Promise<void> {
353
+ if (process.platform === 'win32' || rawPath === encodedPath) return;
354
+ await fs.unlink(rawPath).catch((err) => {
355
+ if ((err as NodeJS.ErrnoException)?.code !== 'ENOENT') log('unlinkRawColon failed for %s - %o', rawPath, err);
356
+ });
357
+ }
358
+
359
+ // Reads an action-id-keyed file (JSON-valued) by its canonical (percent-encoded)
360
+ // path, falling back on a miss to the legacy raw-colon path written by pre-encode
361
+ // nodes (e.g. POSIX files literally named `actions/tx:<hash>.json`).
362
+ //
363
+ // Tradeoff: this reads legacy files in place and never renames them, so a
364
+ // store upgraded from a pre-encode node keeps mixed naming on disk. That is
365
+ // acceptable pre-1.0; a future migration sweep can normalize if desired. We
366
+ // deliberately do NOT migrate-on-read here — reads stay side-effect-free.
367
+ //
368
+ // win32 guard: a raw-colon path is not a benign miss on Windows — the colon
369
+ // is parsed as an NTFS alternate-data-stream separator and a read there can
370
+ // throw a non-ENOENT error rather than cleanly missing. Raw-colon files
371
+ // cannot have been written on win32 anyway, so we skip the fallback there
372
+ // (losing nothing) and swallow ALL fallback errors elsewhere, guaranteeing
373
+ // the fallback never surfaces a new throw to callers.
374
+ private async readActionScopedBytes(encodedPath: string, rawPath: string): Promise<Uint8Array | undefined> {
375
+ const hit = await this.readBytesIfExists(encodedPath, true);
376
+ if (hit !== undefined) return hit;
377
+ if (process.platform === 'win32' || rawPath === encodedPath) return undefined;
378
+ return fs.readFile(rawPath)
379
+ .then(bytes => (isParseableJson(bytes) ? bytes : undefined))
380
+ .catch(() => undefined);
381
+ }
382
+
383
+ // Reads a file's raw bytes. ENOENT → undefined. When `jsonGuard` is set, a
384
+ // present-but-corrupt file (JSON.parse fails — most likely a torn write from a
385
+ // crash before atomic writes existed) is treated as "missing" so recover() and
386
+ // normal reads make progress instead of rethrowing forever. A real I/O error
387
+ // (permissions, EIO, EISDIR, ...) still throws — it must not be masked.
388
+ private async readBytesIfExists(filePath: string, jsonGuard: boolean): Promise<Uint8Array | undefined> {
389
+ let bytes: Uint8Array;
390
+ try {
391
+ bytes = await fs.readFile(filePath);
392
+ } catch (err) {
393
+ if ((err as NodeJS.ErrnoException)?.code === 'ENOENT') return undefined;
394
+ throw err;
395
+ }
396
+ if (jsonGuard && !isParseableJson(bytes)) {
397
+ log('readBytesIfExists: corrupt JSON at %s, treating as missing', filePath);
398
+ return undefined;
399
+ }
400
+ return bytes;
401
+ }
402
+ }
403
+
404
+ /**
405
+ * Filesystem-backed {@link IRawStorage}, now a thin shell over the shared
406
+ * {@link KvRawStorage} kernel driven by a {@link FileStoreDriver}. The public
407
+ * name/constructor (`new FileRawStorage(basePath)`) is unchanged so existing
408
+ * imports keep resolving; the kernel supplies the `IRawStorage` surface and the
409
+ * driver supplies fs behavior.
410
+ *
411
+ * `listBlockIds`/`getApproximateBytesUsed` are re-declared here as always-present
412
+ * (the fs driver always implements them, so the kernel constructor always wires
413
+ * them) — the base declares them optional, but every fs consumer relies on them.
414
+ */
415
+ export class FileRawStorage extends KvRawStorage {
416
+ declare listBlockIds: () => AsyncIterable<BlockId>;
417
+ declare getApproximateBytesUsed: () => Promise<number>;
418
+
419
+ constructor(basePath: string) {
420
+ super(new FileStoreDriver(basePath));
421
+ }
422
+ }