@optimystic/db-p2p-storage-fs 1.0.0-beta.2 → 1.0.0

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