@optimystic/db-p2p-storage-fs 1.14.0 → 1.16.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.
Files changed (37) hide show
  1. package/README.md +142 -33
  2. package/dist/src/file-batch-backend.d.ts +69 -0
  3. package/dist/src/file-batch-backend.d.ts.map +1 -0
  4. package/dist/src/file-batch-backend.js +400 -0
  5. package/dist/src/file-batch-backend.js.map +1 -0
  6. package/dist/src/file-kv-store.d.ts +37 -3
  7. package/dist/src/file-kv-store.d.ts.map +1 -1
  8. package/dist/src/file-kv-store.js +100 -34
  9. package/dist/src/file-kv-store.js.map +1 -1
  10. package/dist/src/file-storage.d.ts +20 -58
  11. package/dist/src/file-storage.d.ts.map +1 -1
  12. package/dist/src/file-storage.js +16 -430
  13. package/dist/src/file-storage.js.map +1 -1
  14. package/dist/src/file-write-log.d.ts +361 -0
  15. package/dist/src/file-write-log.d.ts.map +1 -0
  16. package/dist/src/file-write-log.js +848 -0
  17. package/dist/src/file-write-log.js.map +1 -0
  18. package/dist/src/index.d.ts +3 -0
  19. package/dist/src/index.d.ts.map +1 -1
  20. package/dist/src/index.js +3 -0
  21. package/dist/src/index.js.map +1 -1
  22. package/dist/src/store-lock.d.ts +42 -0
  23. package/dist/src/store-lock.d.ts.map +1 -0
  24. package/dist/src/store-lock.js +116 -0
  25. package/dist/src/store-lock.js.map +1 -0
  26. package/package.json +3 -3
  27. package/src/file-batch-backend.ts +430 -0
  28. package/src/file-kv-store.ts +112 -32
  29. package/src/file-storage.ts +22 -468
  30. package/src/file-write-log.ts +906 -0
  31. package/src/index.ts +3 -0
  32. package/src/store-lock.ts +123 -0
  33. package/dist/src/atomic-write.d.ts +0 -22
  34. package/dist/src/atomic-write.d.ts.map +0 -1
  35. package/dist/src/atomic-write.js +0 -90
  36. package/dist/src/atomic-write.js.map +0 -1
  37. package/src/atomic-write.ts +0 -89
@@ -1,482 +1,36 @@
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
- }
1
+ import type { BlockId } from "@optimystic/db-core";
2
+ import { KvRawStorage, WriteGroupDriver, type StoreIdentity, type WriteGroupOptions } from "@optimystic/db-p2p";
3
+ import { FileBatchBackend } from './file-batch-backend.js';
4
+ import type { FileWriteLogOptions } from './file-write-log.js';
45
5
 
46
6
  /**
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.
7
+ * The write group's `idleFlushMs` and the directory log's `checkpointBytes` and `checkpointIdleMs`
8
+ * (see `WriteGroupOptions` and `FileWriteLogOptions`); the test-only `setTimer` arms both.
58
9
  */
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
- }
10
+ export type FileRawStorageOptions = WriteGroupOptions & FileWriteLogOptions;
462
11
 
463
12
  /**
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.
13
+ * Filesystem-backed {@link IRawStorage}: the shared {@link KvRawStorage} kernel over a
14
+ * {@link WriteGroupDriver} over a {@link FileBatchBackend}. Every write resolves into the driver's
15
+ * in-memory overlay; `flush()` hands the group to the backend as one batch, which appends it to
16
+ * `<basePath>/write-ahead.log` with one sync and then writes the tree. The public constructor
17
+ * (`new FileRawStorage(basePath, options?)`) is synchronous: the lock is taken and the log replayed
18
+ * on the first operation.
469
19
  *
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.
20
+ * `listBlockIds`/`getApproximateBytesUsed`/`getStoreIdentity`/`close` are re-declared here as
21
+ * always-present (the fs backend always implements the first three, so the driver and kernel always
22
+ * wire them, and the driver always has a `close`) — the base declares them optional, but every fs
23
+ * consumer relies on them. `close()` flushes what is still held, releases this store's reference to
24
+ * the directory's shared log, and — for the last store over the directory — checkpoints the log,
25
+ * closes it and removes the lock.
473
26
  */
474
27
  export class FileRawStorage extends KvRawStorage {
475
28
  declare listBlockIds: () => AsyncIterable<BlockId>;
476
29
  declare getApproximateBytesUsed: () => Promise<number>;
477
30
  declare getStoreIdentity: () => StoreIdentity;
31
+ declare close: () => Promise<void>;
478
32
 
479
- constructor(basePath: string) {
480
- super(new FileStoreDriver(basePath));
33
+ constructor(basePath: string, options: FileRawStorageOptions = {}) {
34
+ super(new WriteGroupDriver(new FileBatchBackend(basePath, options), options));
481
35
  }
482
36
  }