@unieai/rabi-storage-json 0.2.1-rc.3 → 0.2.2-rc.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/index.js CHANGED
@@ -39,7 +39,11 @@ async function writeAtomic(path, data) {
39
39
  throw error;
40
40
  }
41
41
  }
42
- /** fsync a POSIX directory so a just-renamed entry is crash-durable. */
42
+ /**
43
+ * Persist directory-entry changes on POSIX; skip this unsupported operation on Windows.
44
+ * @param path - Absolute directory path.
45
+ * @returns resolution after the directory is synced, or immediately on Windows.
46
+ */
43
47
  /* v8 ignore start -- Windows rejects O_RDONLY directory opens; POSIX coverage exercises this. */
44
48
  async function fsyncDirectory(path) {
45
49
  if (process.platform === "win32") return;
@@ -85,7 +89,7 @@ function serialize(name, state) {
85
89
  /**
86
90
  * Parse file content into unit state, validating shape and version.
87
91
  * @param text - Raw file content.
88
- * @param descriptor - Expected identity; version mismatch rejects.
92
+ * @param descriptor - Expected identity and accepted current or compatible versions.
89
93
  * @returns the parsed state.
90
94
  */
91
95
  function parse(text, descriptor) {
@@ -99,7 +103,7 @@ function parse(text, descriptor) {
99
103
  const { unit, global: globalValue, tables } = document;
100
104
  if (typeof unit !== "object" || unit === null || unit["name"] !== descriptor.name || typeof unit["version"] !== "number") throw new StorageError("malformed-medium", `unit '${descriptor.name}': missing or foreign unit header`);
101
105
  const version = unit["version"];
102
- if (version !== descriptor.version) throw new StorageError("version-mismatch", `unit '${descriptor.name}': stored version ${version} != expected ${descriptor.version}`);
106
+ if (version !== descriptor.version && !descriptor.compatibleVersions?.includes(version)) throw new StorageError("version-mismatch", `unit '${descriptor.name}': stored version ${version} is not accepted by version ${descriptor.version}`);
103
107
  if (typeof tables !== "object" || tables === null || Array.isArray(tables)) throw new StorageError("malformed-medium", `unit '${descriptor.name}': tables is not an object`);
104
108
  const state = {
105
109
  version,
@@ -160,7 +164,8 @@ function parseRecord(text, versions) {
160
164
  /**
161
165
  * One opened JSON unit in `single` layout: the whole unit is one document at
162
166
  * `<root>/<name>.json`. The in-memory state is authoritative; every write
163
- * primitive mutates it and republishes the whole file atomically. Writes are
167
+ * primitive mutates it and republishes the whole file atomically, including a
168
+ * batch delete, which changes several records but publishes once. Writes are
164
169
  * NOT queued here — per the backend contract, write ordering belongs to the
165
170
  * caller (the domain layer's write chain); this unit only guarantees that
166
171
  * each single call publishes a complete, durable file. The `per-record`
@@ -183,11 +188,13 @@ async function openSingleUnit(descriptor, root, onClose) {
183
188
  } catch (error) {
184
189
  if (error.code !== "ENOENT") throw error;
185
190
  }
186
- return new SingleJsonUnit(descriptor, path, text === void 0 ? {
191
+ const state = text === void 0 ? {
187
192
  version: descriptor.version,
188
193
  global: null,
189
194
  tables: new Map(descriptor.tables.map((table) => [table, /* @__PURE__ */ new Map()]))
190
- } : parse(text, descriptor), onClose);
195
+ } : parse(text, descriptor);
196
+ state.version = descriptor.version;
197
+ return new SingleJsonUnit(descriptor, path, state, onClose);
191
198
  }
192
199
  var SingleJsonUnit = class {
193
200
  descriptor;
@@ -224,14 +231,21 @@ var SingleJsonUnit = class {
224
231
  throw error;
225
232
  });
226
233
  }
227
- async deleteRecord(table, key) {
234
+ deleteRecord(table, key) {
235
+ return this.deleteRecords(table, [key]);
236
+ }
237
+ async deleteRecords(table, keys) {
228
238
  this.assertOpen();
229
239
  const records = this.records(table);
230
- if (!records.has(key)) return;
231
- const previous = records.get(key);
232
- records.delete(key);
240
+ const removed = /* @__PURE__ */ new Map();
241
+ for (const key of new Set(keys)) {
242
+ if (!records.has(key)) continue;
243
+ removed.set(key, records.get(key));
244
+ records.delete(key);
245
+ }
246
+ if (removed.size === 0) return;
233
247
  await this.publish().catch((error) => {
234
- records.set(key, previous);
248
+ for (const [key, value] of removed) records.set(key, value);
235
249
  throw error;
236
250
  });
237
251
  }
@@ -262,7 +276,7 @@ var SingleJsonUnit = class {
262
276
  if (!records) throw new Error(`unit '${this.descriptor.name}' does not declare table '${table}'`);
263
277
  return records;
264
278
  }
265
- publish() {
279
+ async publish() {
266
280
  const write = writeAtomic(this.path, serialize(this.descriptor.name, this.state));
267
281
  this.inFlight.add(write);
268
282
  write.catch(() => {}).finally(() => this.inFlight.delete(write));
@@ -275,12 +289,13 @@ var SingleJsonUnit = class {
275
289
  * One opened JSON unit in `per-record` layout: the unit is a directory at
276
290
  * `dir`, holding one document per record under `<dir>/<table>/<key>.json`
277
291
  * plus `global.json` for the global slot. The directory is the state — this
278
- * unit holds NO in-memory state of its own: `loadAll` re-reads the tree and
279
- * every write is one durable file operation. The domain layer owns the live
292
+ * unit holds NO in-memory state of its own: `loadAll` re-reads the tree, each
293
+ * put or delete touches one durable document, and a batch delete renames its
294
+ * documents out of the readable set before unlinking them. The domain layer owns the live
280
295
  * in-memory tables (seeded by the open-time `loadAll`) and serializes writes
281
- * through its write chain, so this unit never mutates memory and needs no
282
- * rollback — a failed write simply leaves both the file and the domain's
283
- * memory unchanged.
296
+ * through its write chain. A rejected write leaves domain memory unchanged;
297
+ * a failed deletion restores its staged documents or quarantines the unit
298
+ * with `unknown-state` when restoration cannot be established.
284
299
  *
285
300
  * Per-record contract: a record document that is malformed or stamped with a
286
301
  * version outside the accepted set (the descriptor's current version plus
@@ -289,13 +304,13 @@ var SingleJsonUnit = class {
289
304
  * the record instead of migrating it. Record keys become path segments, so
290
305
  * they must be path-safe (`[a-zA-Z0-9_-]+`); an unsafe key rejects at write.
291
306
  *
292
- * Legacy bootstrap: when the new tree has no document path, a legacy
293
- * whole-unit file `<root>/<name>.json` (the pre-per-record layout) seeds
307
+ * Legacy bootstrap: when the new tree has no declared table directory or
308
+ * global document, a whole-unit file `<root>/<name>.json` seeds
294
309
  * per-record documents, provided its stored unit version is in the accepted
295
310
  * set — a legacy file stamped with any other version is left alone and reads
296
- * as the empty unit. Any new document path, including one whose contents are
297
- * unreadable or stale, suppresses the bootstrap for the whole unit. The
298
- * legacy file is never changed or deleted.
311
+ * as the empty unit. An existing declared table directory, even when empty,
312
+ * or a declared global document suppresses the bootstrap for the whole unit.
313
+ * The legacy file is never changed or deleted.
299
314
  * @module @unieai/rabi-storage-json/src/per-record-unit
300
315
  */
301
316
  /** Keys become path segments in this layout; this set is path-safe on every OS. */
@@ -338,7 +353,10 @@ async function loadPerRecordState(descriptor, dir) {
338
353
  if (!(entries === void 0 ? false : (await Promise.all(entries.map(async (entry) => {
339
354
  if (entry.isDirectory()) {
340
355
  const records = state.tables.get(entry.name);
341
- if (records !== void 0) return loadTableRecords(records, versions, join(dir, entry.name));
356
+ if (records !== void 0) {
357
+ await loadTableRecords(records, versions, join(dir, entry.name));
358
+ return true;
359
+ }
342
360
  }
343
361
  if (entry.name === "global.json" && descriptor.hasGlobal) {
344
362
  const global = await readRecord(join(dir, entry.name), versions);
@@ -354,7 +372,7 @@ function acceptedStamps(descriptor) {
354
372
  return [descriptor.version, ...descriptor.compatibleVersions ?? []];
355
373
  }
356
374
  /**
357
- * Bootstrap an empty per-record tree from a legacy whole-unit file
375
+ * Bootstrap an unmaterialized per-record tree from a legacy whole-unit file
358
376
  * (`<root>/<name>.json`, the pre-per-record layout). Every declared-table
359
377
  * record is copied into a current-version document, while the legacy file is
360
378
  * retained unchanged. A missing, foreign (another unit's name), malformed,
@@ -404,12 +422,9 @@ async function bootstrapLegacyUnit(descriptor, dir, state) {
404
422
  }
405
423
  /**
406
424
  * Read one declared table's record documents into `records`.
407
- * @returns whether the directory contains any `.json` document path,
408
- * independently of key safety, readability, or stored version.
409
425
  */
410
426
  async function loadTableRecords(records, versions, dir) {
411
427
  const files = await readdir(dir, { withFileTypes: true });
412
- const hasDocuments = files.some((file) => file.name.endsWith(".json"));
413
428
  const loaded = await Promise.all(files.map(async (file) => {
414
429
  if (!file.name.endsWith(".json")) return;
415
430
  const key = file.name.slice(0, -5);
@@ -418,7 +433,6 @@ async function loadTableRecords(records, versions, dir) {
418
433
  if (record !== void 0) return [key, record];
419
434
  }));
420
435
  for (const record of loaded) if (record !== void 0) records.set(...record);
421
- return hasDocuments;
422
436
  }
423
437
  /** Read one record document; a foreign (unreadable or stale) one reads as absent. */
424
438
  async function readRecord(path, versions) {
@@ -430,15 +444,17 @@ async function readRecord(path, versions) {
430
444
  }
431
445
  /**
432
446
  * One opened `per-record`-layout unit. Stateless by design: the directory is
433
- * the medium, the domain layer owns the live memory, and each method here is
434
- * a single durable file operation. Write ordering belongs to the caller (the
435
- * domain layer's write chain), exactly like the `single`-layout unit.
447
+ * the medium and the domain layer owns the live memory. Replacements publish
448
+ * one document; deletions stage and sync their documents before cleanup.
449
+ * Write ordering belongs to the caller (the domain layer's write chain).
436
450
  */
437
451
  var PerRecordJsonUnit = class {
438
452
  descriptor;
439
453
  dir;
440
454
  onClose;
441
455
  closed = false;
456
+ /** Set when a failed batch could not restore its staged documents. */
457
+ unusable;
442
458
  /** In-flight durable writes; close() drains them before releasing the unit. */
443
459
  inFlight = /* @__PURE__ */ new Set();
444
460
  constructor(descriptor, dir, onClose) {
@@ -464,10 +480,67 @@ var PerRecordJsonUnit = class {
464
480
  await this.tracked(this.writeDocument(join(this.tableDir(table), `${key}.json`), value));
465
481
  }
466
482
  /** Durably delete one record. Idempotent: a missing key is a no-op. */
467
- async deleteRecord(table, key) {
483
+ deleteRecord(table, key) {
484
+ return this.deleteRecords(table, [key]);
485
+ }
486
+ /**
487
+ * Durably delete many records as one batch. Documents are renamed out of the
488
+ * readable set first; only after the whole batch is staged are the staged
489
+ * copies unlinked. A failure while staging restores the documents it moved,
490
+ * so a rejection normally leaves the batch unapplied. If that restoration
491
+ * itself fails, the readable or durable state is unknown: the unit rejects with
492
+ * `unknown-state` and every later operation on it rejects, while `close`
493
+ * still releases it. Staged directory changes are synced before cleanup on
494
+ * POSIX, so a resolved deletion remains absent after a crash. Cleanup residue
495
+ * is not readable (`open` reads `*.json` documents only).
496
+ */
497
+ async deleteRecords(table, keys) {
468
498
  this.assertOpen();
469
- assertSafeKey(this.descriptor.name, key);
470
- await this.tracked(rm(join(this.tableDir(table), `${key}.json`), { force: true }));
499
+ const dir = this.tableDir(table);
500
+ const unique = [...new Set(keys)];
501
+ for (const key of unique) assertSafeKey(this.descriptor.name, key);
502
+ await this.tracked(this.removeDocuments(dir, unique));
503
+ }
504
+ /**
505
+ * Remove one batch's documents under a single tracked promise.
506
+ * @param dir - Declared table directory.
507
+ * @param keys - Validated, de-duplicated record keys.
508
+ */
509
+ async removeDocuments(dir, keys) {
510
+ const staged = [];
511
+ try {
512
+ for (const key of keys) {
513
+ const from = join(dir, `${key}.json`);
514
+ const to = `${from}.deleting`;
515
+ try {
516
+ await rename(from, to);
517
+ } catch (error) {
518
+ if (error.code === "ENOENT") continue;
519
+ throw error;
520
+ }
521
+ staged.push({
522
+ from,
523
+ to
524
+ });
525
+ }
526
+ if (staged.length > 0) await fsyncDirectory(dir);
527
+ } catch (error) {
528
+ const restoreFailures = [];
529
+ for (const { from, to } of staged) try {
530
+ await rename(to, from);
531
+ } catch (restoreError) {
532
+ restoreFailures.push(restoreError);
533
+ }
534
+ if (staged.length > 0) try {
535
+ await fsyncDirectory(dir);
536
+ } catch (restoreError) {
537
+ restoreFailures.push(restoreError);
538
+ }
539
+ if (restoreFailures.length === 0) throw error;
540
+ this.unusable = new StorageError("unknown-state", `unit '${this.descriptor.name}' could not restore a failed batch delete; its state is unknown`, { cause: new AggregateError([error, ...restoreFailures], "batch delete failed and restoration failed") });
541
+ throw this.unusable;
542
+ }
543
+ await Promise.allSettled(staged.map(({ to }) => rm(to, { force: true })));
471
544
  }
472
545
  /**
473
546
  * Move one record's document aside as `<key>.json.bak.<YYYYMMDDHHmm>`. The
@@ -502,6 +575,7 @@ var PerRecordJsonUnit = class {
502
575
  }
503
576
  assertOpen() {
504
577
  if (this.closed) throw new StorageError("closed", `unit '${this.descriptor.name}' is closed`);
578
+ if (this.unusable !== void 0) throw this.unusable;
505
579
  }
506
580
  /** Resolve a declared table's directory; an undeclared table is a caller bug and throws. */
507
581
  tableDir(table) {
@@ -509,14 +583,13 @@ var PerRecordJsonUnit = class {
509
583
  return join(this.dir, table);
510
584
  }
511
585
  /** Durably replace one document, creating its parent directory. */
512
- writeDocument(path, value) {
513
- return (async () => {
514
- await mkdir(dirname(path), {
515
- recursive: true,
516
- mode: 448
517
- });
518
- await writeAtomic(path, serializeRecord(this.descriptor.version, value));
519
- })();
586
+ async writeDocument(path, value) {
587
+ const text = serializeRecord(this.descriptor.version, value);
588
+ await mkdir(dirname(path), {
589
+ recursive: true,
590
+ mode: 448
591
+ });
592
+ await writeAtomic(path, text);
520
593
  }
521
594
  /** Track one durable write so close() drains it. */
522
595
  tracked(write) {
@@ -17,4 +17,10 @@
17
17
  * @returns resolution after the replacement is crash-durable.
18
18
  */
19
19
  export declare function writeAtomic(path: string, data: string): Promise<void>;
20
+ /**
21
+ * Persist directory-entry changes on POSIX; skip this unsupported operation on Windows.
22
+ * @param path - Absolute directory path.
23
+ * @returns resolution after the directory is synced, or immediately on Windows.
24
+ */
25
+ export declare function fsyncDirectory(path: string): Promise<void>;
20
26
  //# sourceMappingURL=atomic.d.ts.map
@@ -25,7 +25,7 @@ export declare function serialize(name: string, state: UnitState): string;
25
25
  /**
26
26
  * Parse file content into unit state, validating shape and version.
27
27
  * @param text - Raw file content.
28
- * @param descriptor - Expected identity; version mismatch rejects.
28
+ * @param descriptor - Expected identity and accepted current or compatible versions.
29
29
  * @returns the parsed state.
30
30
  */
31
31
  export declare function parse(text: string, descriptor: KvUnitDescriptor): UnitState;
@@ -2,12 +2,13 @@
2
2
  * One opened JSON unit in `per-record` layout: the unit is a directory at
3
3
  * `dir`, holding one document per record under `<dir>/<table>/<key>.json`
4
4
  * plus `global.json` for the global slot. The directory is the state — this
5
- * unit holds NO in-memory state of its own: `loadAll` re-reads the tree and
6
- * every write is one durable file operation. The domain layer owns the live
5
+ * unit holds NO in-memory state of its own: `loadAll` re-reads the tree, each
6
+ * put or delete touches one durable document, and a batch delete renames its
7
+ * documents out of the readable set before unlinking them. The domain layer owns the live
7
8
  * in-memory tables (seeded by the open-time `loadAll`) and serializes writes
8
- * through its write chain, so this unit never mutates memory and needs no
9
- * rollback — a failed write simply leaves both the file and the domain's
10
- * memory unchanged.
9
+ * through its write chain. A rejected write leaves domain memory unchanged;
10
+ * a failed deletion restores its staged documents or quarantines the unit
11
+ * with `unknown-state` when restoration cannot be established.
11
12
  *
12
13
  * Per-record contract: a record document that is malformed or stamped with a
13
14
  * version outside the accepted set (the descriptor's current version plus
@@ -16,13 +17,13 @@
16
17
  * the record instead of migrating it. Record keys become path segments, so
17
18
  * they must be path-safe (`[a-zA-Z0-9_-]+`); an unsafe key rejects at write.
18
19
  *
19
- * Legacy bootstrap: when the new tree has no document path, a legacy
20
- * whole-unit file `<root>/<name>.json` (the pre-per-record layout) seeds
20
+ * Legacy bootstrap: when the new tree has no declared table directory or
21
+ * global document, a whole-unit file `<root>/<name>.json` seeds
21
22
  * per-record documents, provided its stored unit version is in the accepted
22
23
  * set — a legacy file stamped with any other version is left alone and reads
23
- * as the empty unit. Any new document path, including one whose contents are
24
- * unreadable or stale, suppresses the bootstrap for the whole unit. The
25
- * legacy file is never changed or deleted.
24
+ * as the empty unit. An existing declared table directory, even when empty,
25
+ * or a declared global document suppresses the bootstrap for the whole unit.
26
+ * The legacy file is never changed or deleted.
26
27
  * @module @unieai/rabi-storage-json/src/per-record-unit
27
28
  */
28
29
  import type { KvUnit, KvUnitDescriptor } from '@unieai/rabi-storage';
@@ -38,15 +39,17 @@ import type { KvUnit, KvUnitDescriptor } from '@unieai/rabi-storage';
38
39
  export declare function openPerRecordUnit(descriptor: KvUnitDescriptor, root: string, onClose: () => void): Promise<KvUnit>;
39
40
  /**
40
41
  * One opened `per-record`-layout unit. Stateless by design: the directory is
41
- * the medium, the domain layer owns the live memory, and each method here is
42
- * a single durable file operation. Write ordering belongs to the caller (the
43
- * domain layer's write chain), exactly like the `single`-layout unit.
42
+ * the medium and the domain layer owns the live memory. Replacements publish
43
+ * one document; deletions stage and sync their documents before cleanup.
44
+ * Write ordering belongs to the caller (the domain layer's write chain).
44
45
  */
45
46
  export declare class PerRecordJsonUnit implements KvUnit {
46
47
  private readonly descriptor;
47
48
  private readonly dir;
48
49
  private readonly onClose;
49
50
  private closed;
51
+ /** Set when a failed batch could not restore its staged documents. */
52
+ private unusable;
50
53
  /** In-flight durable writes; close() drains them before releasing the unit. */
51
54
  private readonly inFlight;
52
55
  constructor(descriptor: KvUnitDescriptor, dir: string, onClose: () => void);
@@ -59,6 +62,24 @@ export declare class PerRecordJsonUnit implements KvUnit {
59
62
  putRecord(table: string, key: string, value: unknown): Promise<void>;
60
63
  /** Durably delete one record. Idempotent: a missing key is a no-op. */
61
64
  deleteRecord(table: string, key: string): Promise<void>;
65
+ /**
66
+ * Durably delete many records as one batch. Documents are renamed out of the
67
+ * readable set first; only after the whole batch is staged are the staged
68
+ * copies unlinked. A failure while staging restores the documents it moved,
69
+ * so a rejection normally leaves the batch unapplied. If that restoration
70
+ * itself fails, the readable or durable state is unknown: the unit rejects with
71
+ * `unknown-state` and every later operation on it rejects, while `close`
72
+ * still releases it. Staged directory changes are synced before cleanup on
73
+ * POSIX, so a resolved deletion remains absent after a crash. Cleanup residue
74
+ * is not readable (`open` reads `*.json` documents only).
75
+ */
76
+ deleteRecords(table: string, keys: readonly string[]): Promise<void>;
77
+ /**
78
+ * Remove one batch's documents under a single tracked promise.
79
+ * @param dir - Declared table directory.
80
+ * @param keys - Validated, de-duplicated record keys.
81
+ */
82
+ private removeDocuments;
62
83
  /**
63
84
  * Move one record's document aside as `<key>.json.bak.<YYYYMMDDHHmm>`. The
64
85
  * moved file no longer ends in `.json`, so every later read ignores it; the
@@ -1,7 +1,8 @@
1
1
  /**
2
2
  * One opened JSON unit in `single` layout: the whole unit is one document at
3
3
  * `<root>/<name>.json`. The in-memory state is authoritative; every write
4
- * primitive mutates it and republishes the whole file atomically. Writes are
4
+ * primitive mutates it and republishes the whole file atomically, including a
5
+ * batch delete, which changes several records but publishes once. Writes are
5
6
  * NOT queued here — per the backend contract, write ordering belongs to the
6
7
  * caller (the domain layer's write chain); this unit only guarantees that
7
8
  * each single call publishes a complete, durable file. The `per-record`
package/locale/de.json ADDED
@@ -0,0 +1,6 @@
1
+ {
2
+ "meta": {
3
+ "title": "JSON Dateispeicher",
4
+ "description": "Speichern Sie Schlüsselwertdaten in einer lokalen JSON-Datei."
5
+ }
6
+ }
package/locale/es.json ADDED
@@ -0,0 +1,6 @@
1
+ {
2
+ "meta": {
3
+ "title": "JSON almacenamiento de archivos",
4
+ "description": "Guarde los datos clave-valor en un archivo JSON local."
5
+ }
6
+ }
package/locale/fr.json ADDED
@@ -0,0 +1,6 @@
1
+ {
2
+ "meta": {
3
+ "title": "JSON stockage de fichiers",
4
+ "description": "Enregistrez les données clé-valeur dans un fichier JSON local."
5
+ }
6
+ }
package/locale/ja.json ADDED
@@ -0,0 +1,6 @@
1
+ {
2
+ "meta": {
3
+ "title": "JSON ファイル保存",
4
+ "description": "キーと値のデータをローカルの JSON ファイルに保存します。"
5
+ }
6
+ }
package/locale/pt.json ADDED
@@ -0,0 +1,6 @@
1
+ {
2
+ "meta": {
3
+ "title": "JSON armazenamento de arquivos",
4
+ "description": "Salve dados de valores-chave em um arquivo JSON local."
5
+ }
6
+ }
package/locale/ru.json ADDED
@@ -0,0 +1,6 @@
1
+ {
2
+ "meta": {
3
+ "title": "JSON файловое хранилище",
4
+ "description": "Сохраните данные «ключ-значение» в локальном файле JSON."
5
+ }
6
+ }
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@unieai/rabi-storage-json",
3
3
  "description": "JSON file KV storage backend for the Rabi Harness storage hub",
4
- "version": "0.2.1-rc.3",
4
+ "version": "0.2.2-rc.5",
5
5
  "publishConfig": {
6
6
  "access": "public"
7
7
  },
@@ -21,14 +21,17 @@
21
21
  "locale/*.json",
22
22
  "lib/index.js",
23
23
  "lib/types/**/*.d.ts",
24
+ "lib/types/**/*.d.ts.map",
25
+ "lib/**/*.js.map",
26
+ "src",
24
27
  "README.md"
25
28
  ],
26
29
  "license": "MIT",
27
30
  "peerDependencies": {
28
- "@unieai/rabi-storage": "0.2.1-rc.3",
29
- "@unieai/cordis": "4.0.5"
31
+ "@unieai/rabi-storage": "0.2.2-rc.5",
32
+ "@unieai/cordis": "4.1.0"
30
33
  },
31
34
  "dependencies": {
32
- "@unieai/schemastery": "3.18.5"
35
+ "@unieai/schemastery": "3.19.0"
33
36
  }
34
37
  }
package/src/atomic.ts ADDED
@@ -0,0 +1,57 @@
1
+ /**
2
+ * Atomic whole-file replacement for the JSON backend.
3
+ *
4
+ * Publish protocol: write a same-directory temp file, fsync it, then
5
+ * `rename()` over the target. Rename is an atomic replace on POSIX and on
6
+ * Windows (libuv maps it to `MoveFileExW(..., MOVEFILE_REPLACE_EXISTING)`),
7
+ * and replacement is the intended semantic here — unlike the session-log
8
+ * backend's link()+unlink() no-clobber protocol, a unit file has exactly one
9
+ * writer per process and last-write-wins is correct. After the rename the
10
+ * parent directory is fsynced on POSIX so the new entry is crash-durable.
11
+ * @module @unieai/rabi-storage-json/src/atomic
12
+ */
13
+
14
+ import { open, rename, rm } from 'node:fs/promises'
15
+ import { dirname, join } from 'node:path'
16
+ import { randomUUID } from 'node:crypto'
17
+
18
+ /**
19
+ * Durably replace `path` with `data`.
20
+ * @param path - Absolute target file path.
21
+ * @param data - Full new file content.
22
+ * @returns resolution after the replacement is crash-durable.
23
+ */
24
+ export async function writeAtomic(path: string, data: string): Promise<void> {
25
+ const tmp = join(dirname(path), `.${randomUUID()}.tmp`)
26
+ try {
27
+ const handle = await open(tmp, 'wx', 0o600)
28
+ try {
29
+ await handle.writeFile(data, 'utf8')
30
+ await handle.sync()
31
+ } finally {
32
+ await handle.close()
33
+ }
34
+ await rename(tmp, path)
35
+ await fsyncDirectory(dirname(path))
36
+ } catch (error) {
37
+ await rm(tmp, { force: true })
38
+ throw error
39
+ }
40
+ }
41
+
42
+ /**
43
+ * Persist directory-entry changes on POSIX; skip this unsupported operation on Windows.
44
+ * @param path - Absolute directory path.
45
+ * @returns resolution after the directory is synced, or immediately on Windows.
46
+ */
47
+ /* v8 ignore start -- Windows rejects O_RDONLY directory opens; POSIX coverage exercises this. */
48
+ export async function fsyncDirectory(path: string): Promise<void> {
49
+ if (process.platform === 'win32') return
50
+ const handle = await open(path, 'r')
51
+ try {
52
+ await handle.sync()
53
+ } finally {
54
+ await handle.close()
55
+ }
56
+ }
57
+ /* v8 ignore stop */