@opendatalabs/personal-server-ts-lite 0.0.1-canary.052d47e → 0.0.1-canary.0620a9a

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 (124) hide show
  1. package/dist/additions-crypto.d.ts +3 -0
  2. package/dist/additions-crypto.d.ts.map +1 -0
  3. package/dist/additions-crypto.js +42 -0
  4. package/dist/additions-crypto.js.map +1 -0
  5. package/dist/additions-protocol.d.ts +56 -0
  6. package/dist/additions-protocol.d.ts.map +1 -0
  7. package/dist/additions-protocol.js +17 -0
  8. package/dist/additions-protocol.js.map +1 -0
  9. package/dist/additions-session.d.ts +20 -0
  10. package/dist/additions-session.d.ts.map +1 -0
  11. package/dist/additions-session.js +215 -0
  12. package/dist/additions-session.js.map +1 -0
  13. package/dist/additions-transport.d.ts +72 -0
  14. package/dist/additions-transport.d.ts.map +1 -0
  15. package/dist/additions-transport.js +428 -0
  16. package/dist/additions-transport.js.map +1 -0
  17. package/dist/additions-worker.bundle.js +31161 -0
  18. package/dist/additions-worker.d.ts +2 -0
  19. package/dist/additions-worker.d.ts.map +1 -0
  20. package/dist/additions-worker.js +308 -0
  21. package/dist/additions-worker.js.map +1 -0
  22. package/dist/browser-runtime.d.ts +54 -0
  23. package/dist/browser-runtime.d.ts.map +1 -1
  24. package/dist/browser-runtime.js +69 -3
  25. package/dist/browser-runtime.js.map +1 -1
  26. package/dist/canonical-persistence.d.ts +53 -0
  27. package/dist/canonical-persistence.d.ts.map +1 -0
  28. package/dist/canonical-persistence.js +13 -0
  29. package/dist/canonical-persistence.js.map +1 -0
  30. package/dist/canonical-store.d.ts +395 -0
  31. package/dist/canonical-store.d.ts.map +1 -0
  32. package/dist/canonical-store.js +1807 -0
  33. package/dist/canonical-store.js.map +1 -0
  34. package/dist/client.d.ts +7 -1
  35. package/dist/client.d.ts.map +1 -1
  36. package/dist/client.js +155 -1
  37. package/dist/client.js.map +1 -1
  38. package/dist/derivatives.d.ts.map +1 -1
  39. package/dist/derivatives.js +4 -2
  40. package/dist/derivatives.js.map +1 -1
  41. package/dist/diagnostics.d.ts +3 -0
  42. package/dist/diagnostics.d.ts.map +1 -1
  43. package/dist/diagnostics.js +9 -1
  44. package/dist/diagnostics.js.map +1 -1
  45. package/dist/history-probe-worker.bundle.js +31241 -0
  46. package/dist/history-probe.worker.d.ts +35 -0
  47. package/dist/history-probe.worker.d.ts.map +1 -0
  48. package/dist/history-probe.worker.js +160 -0
  49. package/dist/history-probe.worker.js.map +1 -0
  50. package/dist/index.d.ts +13 -2
  51. package/dist/index.d.ts.map +1 -1
  52. package/dist/index.js +11 -0
  53. package/dist/index.js.map +1 -1
  54. package/dist/mcp-store.d.ts +1 -1
  55. package/dist/mcp-store.d.ts.map +1 -1
  56. package/dist/mcp-store.js +140 -15
  57. package/dist/mcp-store.js.map +1 -1
  58. package/dist/oura-import.d.ts +2 -0
  59. package/dist/oura-import.d.ts.map +1 -0
  60. package/dist/oura-import.js +3 -0
  61. package/dist/oura-import.js.map +1 -0
  62. package/dist/relay-tls.d.ts.map +1 -1
  63. package/dist/relay-tls.js +10 -0
  64. package/dist/relay-tls.js.map +1 -1
  65. package/dist/relay.d.ts +2 -2
  66. package/dist/relay.d.ts.map +1 -1
  67. package/dist/relay.js +118 -55
  68. package/dist/relay.js.map +1 -1
  69. package/dist/replication-coordinator-state.d.ts +19 -0
  70. package/dist/replication-coordinator-state.d.ts.map +1 -0
  71. package/dist/replication-coordinator-state.js +20 -0
  72. package/dist/replication-coordinator-state.js.map +1 -0
  73. package/dist/replication-door.d.ts +17 -0
  74. package/dist/replication-door.d.ts.map +1 -0
  75. package/dist/replication-door.js +23 -0
  76. package/dist/replication-door.js.map +1 -0
  77. package/dist/replication-engine.d.ts +49 -0
  78. package/dist/replication-engine.d.ts.map +1 -0
  79. package/dist/replication-engine.js +589 -0
  80. package/dist/replication-engine.js.map +1 -0
  81. package/dist/replication-host.d.ts +92 -0
  82. package/dist/replication-host.d.ts.map +1 -0
  83. package/dist/replication-host.js +135 -0
  84. package/dist/replication-host.js.map +1 -0
  85. package/dist/replication-ports.d.ts +194 -0
  86. package/dist/replication-ports.d.ts.map +1 -0
  87. package/dist/replication-ports.js +58 -0
  88. package/dist/replication-ports.js.map +1 -0
  89. package/dist/replication-runtime.d.ts +64 -0
  90. package/dist/replication-runtime.d.ts.map +1 -0
  91. package/dist/replication-runtime.js +79 -0
  92. package/dist/replication-runtime.js.map +1 -0
  93. package/dist/replication-storage.d.ts +42 -0
  94. package/dist/replication-storage.d.ts.map +1 -0
  95. package/dist/replication-storage.js +173 -0
  96. package/dist/replication-storage.js.map +1 -0
  97. package/dist/runtime.d.ts +57 -5
  98. package/dist/runtime.d.ts.map +1 -1
  99. package/dist/runtime.js +287 -36
  100. package/dist/runtime.js.map +1 -1
  101. package/dist/state.d.ts +8 -1
  102. package/dist/state.d.ts.map +1 -1
  103. package/dist/state.js +84 -20
  104. package/dist/state.js.map +1 -1
  105. package/dist/storage-utils.d.ts.map +1 -1
  106. package/dist/storage-utils.js +10 -2
  107. package/dist/storage-utils.js.map +1 -1
  108. package/dist/storage.d.ts +33 -0
  109. package/dist/storage.d.ts.map +1 -1
  110. package/dist/storage.js +465 -131
  111. package/dist/storage.js.map +1 -1
  112. package/dist/stream-sync-files.d.ts +54 -0
  113. package/dist/stream-sync-files.d.ts.map +1 -0
  114. package/dist/stream-sync-files.js +316 -0
  115. package/dist/stream-sync-files.js.map +1 -0
  116. package/dist/stream-sync-read-cache-files.d.ts +5 -0
  117. package/dist/stream-sync-read-cache-files.d.ts.map +1 -0
  118. package/dist/stream-sync-read-cache-files.js +19 -0
  119. package/dist/stream-sync-read-cache-files.js.map +1 -0
  120. package/dist/sync.d.ts +62 -1
  121. package/dist/sync.d.ts.map +1 -1
  122. package/dist/sync.js +261 -61
  123. package/dist/sync.js.map +1 -1
  124. package/package.json +12 -5
package/dist/storage.js CHANGED
@@ -1,5 +1,7 @@
1
1
  import { buildDataBlocksAsync } from "@opendatalabs/personal-server-ts-core/storage/blocks";
2
2
  import { DataBlockStorageError, encodeDataBlockCursor, selectScopeBlocksByIds, validateDataBlockCursor, } from "@opendatalabs/personal-server-ts-core/storage/blocks";
3
+ import { withScopeLock } from "@opendatalabs/personal-server-ts-core/additions";
4
+ import { IngestPersistedError, VersionSupersededError, } from "@opendatalabs/personal-server-ts-core/contracts";
3
5
  import { createStorageReadMethods, sortEntries } from "./storage-utils.js";
4
6
  import { previewEnvelopeValue, previewJsonEnvelopePrefix, } from "@opendatalabs/personal-server-ts-core/storage/preview";
5
7
  const DEFAULT_INDEXED_DB_NAME = "personal-server-lite-storage";
@@ -44,8 +46,12 @@ function normalizeState(state) {
44
46
  schemaId: entry.schemaId ?? null,
45
47
  })),
46
48
  envelopes: state.envelopes,
49
+ readyBlockManifests: state.readyBlockManifests ?? [],
47
50
  blockManifests: state.blockManifests ?? [],
48
51
  blockPayloads: state.blockPayloads ?? [],
52
+ ...(state.pendingLedgerDeletes?.length
53
+ ? { pendingLedgerDeletes: state.pendingLedgerDeletes }
54
+ : {}),
49
55
  };
50
56
  }
51
57
  export function createIndexedDbFallbackDataFileStore(envelopes, blockManifests = new Map(), blockPayloads = new Map()) {
@@ -162,6 +168,39 @@ export async function createOpfsPsLiteDataFileStore() {
162
168
  await writable.close();
163
169
  return new TextEncoder().encode(encoded).length;
164
170
  },
171
+ async openEnvelopeWriter(path) {
172
+ const parts = path.split("/").filter(Boolean);
173
+ const fileName = parts.pop();
174
+ if (!fileName)
175
+ throw new Error("OPFS path must include a file name");
176
+ const dir = await getOrCreateOpfsDirectory(root, parts);
177
+ const handle = await dir.getFileHandle(fileName, { create: true });
178
+ // A writable stream writes to a swap file; `close` replaces the file in
179
+ // one step and `abort` drops the swap file.
180
+ const writable = await handle.createWritable();
181
+ let sizeBytes = 0;
182
+ let open = true;
183
+ return {
184
+ async write(text) {
185
+ const bytes = textEncoder.encode(text);
186
+ await writable.write(bytes);
187
+ sizeBytes += bytes.byteLength;
188
+ },
189
+ async commit() {
190
+ open = false;
191
+ await writable.close();
192
+ return sizeBytes;
193
+ },
194
+ async abort() {
195
+ if (!open)
196
+ return;
197
+ open = false;
198
+ await writable.abort();
199
+ // `create: true` left an empty, unindexed file at the path.
200
+ await dir.removeEntry(fileName).catch(() => undefined);
201
+ },
202
+ };
203
+ },
165
204
  async deleteEnvelope(path) {
166
205
  const parts = path.split("/").filter(Boolean);
167
206
  const fileName = parts.pop();
@@ -278,6 +317,18 @@ export function createIndexedDbPsLitePersistence(options = {}) {
278
317
  async write(state) {
279
318
  await runIndexedDbTransaction(resolved, "readwrite", (store) => store.put(state, resolved.key));
280
319
  },
320
+ // Side records live in the same object store under their own keys, which
321
+ // a build that only knows `resolved.key` never reads.
322
+ async readAux(name) {
323
+ const value = await runIndexedDbTransaction(resolved, "readonly", (store) => store.get(`${resolved.key}:${name}`));
324
+ return value ?? null;
325
+ },
326
+ async writeAux(name, value) {
327
+ await runIndexedDbTransaction(resolved, "readwrite", (store) => store.put(value, `${resolved.key}:${name}`));
328
+ },
329
+ async deleteAux(name) {
330
+ await runIndexedDbTransaction(resolved, "readwrite", (store) => store.delete(`${resolved.key}:${name}`));
331
+ },
281
332
  };
282
333
  }
283
334
  export async function createPersistentPsLiteStorage(adapter, persistence = createIndexedDbPsLitePersistence(), dataFileStore) {
@@ -287,7 +338,17 @@ export async function createPersistentPsLiteStorage(adapter, persistence = creat
287
338
  envelope,
288
339
  ]));
289
340
  const fallbackBlockManifests = new Map((state.blockManifests ?? []).map(({ path, manifest }) => [path, manifest]));
341
+ const readyBlockManifests = new Set([
342
+ ...(state.readyBlockManifests ?? []),
343
+ ...fallbackBlockManifests.keys(),
344
+ ]);
290
345
  const fallbackBlockPayloads = new Map((state.blockPayloads ?? []).map(({ path, block }) => [path, block]));
346
+ // First-seen ledgers: each persisted on its own (`persistence.*Aux`), read
347
+ // lazily, never part of the main state. A ledger the previous build kept
348
+ // inside the main state is ignored: it is a cache, rebuilt on demand.
349
+ const ledgerAux = (scope) => `first-seen:${scope}`;
350
+ const firstSeenLedgers = new Map();
351
+ const pendingLedgerDeletes = new Set(state.pendingLedgerDeletes ?? []);
291
352
  const fallbackStore = createIndexedDbFallbackDataFileStore(fallbackEnvelopes, fallbackBlockManifests, fallbackBlockPayloads);
292
353
  const fileStore = dataFileStore ??
293
354
  (adapter.kind !== "custom" && (await isOpfsAvailable())
@@ -298,19 +359,114 @@ export async function createPersistentPsLiteStorage(adapter, persistence = creat
298
359
  files: fileStore.kind,
299
360
  opfsAvailable: await isOpfsAvailable(),
300
361
  };
362
+ // Every write of the persisted state runs in this queue, one at a time, in
363
+ // call order. A snapshot is taken when its turn comes, so each write carries
364
+ // the latest index, and index changes never interleave.
301
365
  let persistQueue = Promise.resolve();
302
- async function persist() {
303
- const snapshot = {
304
- ...state,
366
+ function enqueue(step) {
367
+ const run = persistQueue.then(step);
368
+ persistQueue = run.then(() => undefined, () => undefined);
369
+ return run;
370
+ }
371
+ function snapshotOf(source) {
372
+ return {
373
+ ...source,
374
+ readyBlockManifests: Array.from(readyBlockManifests),
305
375
  envelopes: fileStore.kind === "indexeddb"
306
376
  ? Array.from(fallbackEnvelopes.values())
307
377
  : [],
308
378
  blockManifests: Array.from(fallbackBlockManifests.entries()).map(([path, manifest]) => ({ path, manifest })),
309
379
  blockPayloads: Array.from(fallbackBlockPayloads.entries()).map(([path, block]) => ({ path, block })),
380
+ pendingLedgerDeletes: pendingLedgerDeletes.size > 0
381
+ ? Array.from(pendingLedgerDeletes)
382
+ : undefined,
310
383
  };
311
- const write = persistQueue.then(() => persistence.write(snapshot));
312
- persistQueue = write.catch(() => undefined);
313
- await write;
384
+ }
385
+ async function persist() {
386
+ await enqueue(() => persistence.write(snapshotOf(state)));
387
+ }
388
+ /**
389
+ * Make `next` the live index, once it is durable. Call only inside
390
+ * `enqueue`. A failed write leaves the live index as it was, so a reader
391
+ * never sees a change that could be lost on restart.
392
+ */
393
+ async function publish(next) {
394
+ await persistence.write(snapshotOf(next));
395
+ state = next;
396
+ }
397
+ /**
398
+ * Replace the live index with `change(index)`. `change` returns null to
399
+ * leave the index alone. Resolves to whether the index was written.
400
+ */
401
+ function updateIndex(change) {
402
+ return enqueue(async () => {
403
+ const next = change(state);
404
+ if (!next)
405
+ return false;
406
+ await publish(next);
407
+ return true;
408
+ });
409
+ }
410
+ function updateEntryField(path, patch) {
411
+ return updateIndex((current) => {
412
+ if (!current.entries.some((entry) => entry.path === path))
413
+ return null;
414
+ return {
415
+ ...current,
416
+ entries: current.entries.map((entry) => entry.path === path ? { ...entry, ...patch } : entry),
417
+ };
418
+ });
419
+ }
420
+ /**
421
+ * Remove a blob that no index entry names, after its index write failed. A
422
+ * blob that an entry does name is kept. Best effort: the commit's own error
423
+ * is what the caller sees.
424
+ */
425
+ function dropUnindexedEnvelope(path) {
426
+ return enqueue(async () => {
427
+ if (state.entries.some((entry) => entry.path === path))
428
+ return;
429
+ await Promise.all([
430
+ fileStore.deleteEnvelope(path),
431
+ fallbackStore.deleteEnvelope(path),
432
+ ]);
433
+ }).catch(() => undefined);
434
+ }
435
+ /**
436
+ * Install a row at its path, replacing any row there. Caller holds the path
437
+ * lock. With `onlyIfNewest`, the row is refused when the scope already has a
438
+ * later `collectedAt`; that check runs in the index queue, so it is atomic
439
+ * with the publication.
440
+ */
441
+ async function installEntry(entry, options = {}) {
442
+ let indexed;
443
+ await updateIndex((current) => {
444
+ if (options.onlyIfNewest &&
445
+ current.entries.some((e) => e.scope === entry.scope &&
446
+ Date.parse(e.collectedAt) > Date.parse(entry.collectedAt))) {
447
+ throw new VersionSupersededError(entry.scope);
448
+ }
449
+ const version = entry.version ??
450
+ current.entries.reduce((max, e) => e.scope === entry.scope && e.version > max ? e.version : max, 0) + 1;
451
+ indexed = {
452
+ ...entry,
453
+ schemaId: entry.schemaId ?? null,
454
+ version,
455
+ dataPointId: entry.dataPointId ?? null,
456
+ afterTombstoneVersion: entry.afterTombstoneVersion ?? null,
457
+ id: current.nextId,
458
+ createdAt: new Date().toISOString(),
459
+ };
460
+ return {
461
+ ...current,
462
+ nextId: current.nextId + 1,
463
+ entries: [
464
+ ...current.entries.filter((item) => item.path !== entry.path),
465
+ indexed,
466
+ ],
467
+ };
468
+ });
469
+ return indexed;
314
470
  }
315
471
  function entriesForScope(scope) {
316
472
  return sortEntries(state.entries.filter((entry) => entry.scope === scope));
@@ -323,7 +479,14 @@ export async function createPersistentPsLiteStorage(adapter, persistence = creat
323
479
  return state.entries.find((entry) => entry.fileId === fileId);
324
480
  },
325
481
  findByDataPointId(dataPointId) {
326
- return state.entries.find((entry) => entry.dataPointId === dataPointId);
482
+ let newest;
483
+ for (const entry of state.entries) {
484
+ if (entry.dataPointId !== dataPointId)
485
+ continue;
486
+ if (!newest || entry.version >= newest.version)
487
+ newest = entry;
488
+ }
489
+ return newest;
327
490
  },
328
491
  findUnsynced(options) {
329
492
  const entries = state.entries
@@ -344,10 +507,13 @@ export async function createPersistentPsLiteStorage(adapter, persistence = creat
344
507
  },
345
508
  async writeEnvelope(envelope) {
346
509
  const path = envelopePath(envelope.scope, envelope.collectedAt);
347
- const sizeBytes = await fileStore.writeEnvelope(path, envelope);
348
- if (fileStore.kind !== "indexeddb") {
349
- await fallbackStore.deleteEnvelope(path);
350
- }
510
+ const sizeBytes = await withPathLock(path, async () => {
511
+ const size = await fileStore.writeEnvelope(path, envelope);
512
+ if (fileStore.kind !== "indexeddb") {
513
+ await fallbackStore.deleteEnvelope(path);
514
+ }
515
+ return size;
516
+ });
351
517
  await persist();
352
518
  return {
353
519
  path,
@@ -355,6 +521,67 @@ export async function createPersistentPsLiteStorage(adapter, persistence = creat
355
521
  sizeBytes,
356
522
  };
357
523
  },
524
+ async writeEnvelopeAndIndex(envelope, entry) {
525
+ const path = envelopePath(envelope.scope, envelope.collectedAt);
526
+ // The blob and its row are one step under the path lock, so no erase or
527
+ // replacement of this path runs between them.
528
+ return withPathLock(path, async () => {
529
+ const size = await fileStore.writeEnvelope(path, envelope);
530
+ if (fileStore.kind !== "indexeddb") {
531
+ await fallbackStore.deleteEnvelope(path);
532
+ }
533
+ try {
534
+ return await installEntry({
535
+ ...entry,
536
+ scope: envelope.scope,
537
+ collectedAt: envelope.collectedAt,
538
+ path,
539
+ sizeBytes: entry.sizeBytes ?? size,
540
+ });
541
+ }
542
+ catch (error) {
543
+ // The bytes are durable here; the caller's recovery depends on that.
544
+ throw new IngestPersistedError(path, error);
545
+ }
546
+ });
547
+ },
548
+ ...(fileStore.openEnvelopeWriter
549
+ ? {
550
+ async openVersionWriter(scope, collectedAt) {
551
+ const path = envelopePath(scope, collectedAt);
552
+ const file = await fileStore.openEnvelopeWriter(path);
553
+ return {
554
+ write: (text) => file.write(text),
555
+ abort: () => file.abort(),
556
+ async commit(entry, options) {
557
+ // The rename and the index install are one step under the path
558
+ // lock, so no erase of this path runs between them.
559
+ return withPathLock(path, async () => {
560
+ const sizeBytes = await file.commit();
561
+ try {
562
+ // The index entry is what makes the version visible.
563
+ await installEntry({
564
+ ...entry,
565
+ scope,
566
+ collectedAt,
567
+ path,
568
+ sizeBytes,
569
+ }, options);
570
+ }
571
+ catch (error) {
572
+ await dropUnindexedEnvelope(path);
573
+ throw error;
574
+ }
575
+ if (fileStore.kind !== "indexeddb") {
576
+ await fallbackStore.deleteEnvelope(path);
577
+ }
578
+ return { path, relativePath: path, sizeBytes };
579
+ });
580
+ },
581
+ };
582
+ },
583
+ }
584
+ : {}),
358
585
  async readScopeBlocks(scope, collectedAt, options) {
359
586
  const manifestPath = blockManifestPath(scope, collectedAt);
360
587
  let manifest = (await fileStore.readBlockManifest?.(manifestPath)) ??
@@ -482,7 +709,7 @@ export async function createPersistentPsLiteStorage(adapter, persistence = creat
482
709
  null);
483
710
  },
484
711
  async hasScopeBlocks(scope, collectedAt) {
485
- return Boolean(await storagePort.readBlockManifest?.(scope, collectedAt));
712
+ return readyBlockManifests.has(blockManifestPath(scope, collectedAt));
486
713
  },
487
714
  async canReadScopeBlocks(scope, collectedAt) {
488
715
  if (await storagePort.hasScopeBlocks?.(scope, collectedAt)) {
@@ -502,6 +729,9 @@ export async function createPersistentPsLiteStorage(adapter, persistence = creat
502
729
  return Boolean(envelope);
503
730
  },
504
731
  async writeBlockManifest(scope, collectedAt, manifest, blocks) {
732
+ // Invalidate before replacing a tree; a failed build is not ready.
733
+ readyBlockManifests.delete(blockManifestPath(scope, collectedAt));
734
+ await persist();
505
735
  const writeTree = async (store) => {
506
736
  if (!store.writeBlockManifest || !store.writeBlockPayload) {
507
737
  throw new Error("Block sidecar storage is not available");
@@ -533,140 +763,227 @@ export async function createPersistentPsLiteStorage(adapter, persistence = creat
533
763
  if (wrotePrimary && fileStore.kind !== "indexeddb") {
534
764
  await fallbackStore.deleteBlockTree?.(blockTreePath(scope, collectedAt));
535
765
  }
766
+ readyBlockManifests.add(blockManifestPath(scope, collectedAt));
536
767
  await persist();
537
768
  },
538
- async insertEntry(entry) {
539
- const version = entry.version ??
540
- state.entries.reduce((max, e) => e.scope === entry.scope && e.version > max ? e.version : max, 0) + 1;
541
- const indexed = {
542
- ...entry,
543
- schemaId: entry.schemaId ?? null,
544
- version,
545
- dataPointId: entry.dataPointId ?? null,
546
- afterTombstoneVersion: entry.afterTombstoneVersion ?? null,
547
- id: state.nextId,
548
- createdAt: new Date().toISOString(),
549
- };
550
- state = {
551
- ...state,
552
- nextId: state.nextId + 1,
553
- entries: [
554
- ...state.entries.filter((item) => item.path !== entry.path),
555
- indexed,
556
- ],
557
- };
558
- await persist();
559
- return indexed;
560
- },
561
- async updateFileId(path, fileId) {
562
- let updated = false;
563
- state = {
564
- ...state,
565
- entries: state.entries.map((entry) => {
566
- if (entry.path !== path)
567
- return entry;
568
- updated = true;
569
- return { ...entry, fileId };
570
- }),
571
- };
572
- if (updated) {
573
- await persist();
574
- }
575
- return updated;
769
+ insertEntry(entry) {
770
+ return withPathLock(entry.path, () => installEntry(entry));
771
+ },
772
+ updateFileId(path, fileId) {
773
+ return updateEntryField(path, { fileId });
576
774
  },
577
775
  findLatestVersionByScope(scope) {
578
776
  return state.entries.reduce((max, e) => (e.scope === scope && e.version > max ? e.version : max), 0);
579
777
  },
580
- async updateDataPointId(path, dataPointId) {
581
- let updated = false;
582
- state = {
583
- ...state,
584
- entries: state.entries.map((entry) => {
585
- if (entry.path !== path)
586
- return entry;
587
- updated = true;
588
- return { ...entry, dataPointId };
589
- }),
590
- };
591
- if (updated) {
592
- await persist();
593
- }
594
- return updated;
595
- },
596
- async updateEntryVersion(path, version) {
597
- let updated = false;
598
- state = {
599
- ...state,
600
- entries: state.entries.map((entry) => {
601
- if (entry.path !== path)
602
- return entry;
603
- updated = true;
604
- return { ...entry, version };
605
- }),
606
- };
607
- if (updated) {
608
- await persist();
778
+ updateDataPointId(path, dataPointId) {
779
+ return updateEntryField(path, { dataPointId });
780
+ },
781
+ updateEntryVersion(path, version) {
782
+ return updateEntryField(path, { version });
783
+ },
784
+ async readFirstSeenLedger(scope) {
785
+ if (!firstSeenLedgers.has(scope)) {
786
+ const stored = (await persistence.readAux?.(ledgerAux(scope))) ?? null;
787
+ if (stored !== null)
788
+ firstSeenLedgers.set(scope, stored);
609
789
  }
610
- return updated;
790
+ return structuredClone(firstSeenLedgers.get(scope) ?? null);
791
+ },
792
+ async writeFirstSeenLedger(scope, ledger) {
793
+ firstSeenLedgers.set(scope, structuredClone(ledger));
794
+ await persistence.writeAux?.(ledgerAux(scope), ledger);
611
795
  },
796
+ async deleteFirstSeenLedger(scope) {
797
+ firstSeenLedgers.delete(scope);
798
+ await persistence.deleteAux?.(ledgerAux(scope));
799
+ },
800
+ // The ledger barrier runs under the scope lock (a rebuild in flight cannot
801
+ // write it back). Each row is then erased under its own path lock, the
802
+ // same owner an ordinary write takes, so no write to a path interleaves
803
+ // with the erase of that path. The scope lock is never held across those
804
+ // path locks: lock order is path, scope, queue.
612
805
  async deleteScope(scope) {
613
- let deleted = 0;
614
- const deletedPaths = [];
615
- const deletedBlockTrees = [];
616
- state = {
617
- ...state,
618
- entries: state.entries.filter((entry) => {
619
- if (entry.scope !== scope)
620
- return true;
621
- deleted += 1;
622
- deletedPaths.push(envelopePath(entry.scope, entry.collectedAt));
623
- deletedBlockTrees.push(blockTreePath(entry.scope, entry.collectedAt));
624
- return false;
625
- }),
626
- };
627
- await Promise.all([
628
- ...deletedPaths.flatMap((path) => [
629
- fileStore.deleteEnvelope(path),
630
- fallbackStore.deleteEnvelope(path),
631
- ]),
632
- ...deletedBlockTrees.flatMap((path) => [
633
- fileStore.deleteBlockTree?.(path),
634
- fallbackStore.deleteBlockTree?.(path),
635
- ]),
636
- ].filter((promise) => promise !== undefined));
637
- await persist();
638
- return deleted;
806
+ await withScopeLock(scope, async () => {
807
+ await dropLedger(scope);
808
+ for (const entry of entriesForScope(scope)) {
809
+ readyBlockManifests.delete(blockManifestPath(scope, entry.collectedAt));
810
+ }
811
+ // Repeat the barrier on retry, even if a failed write cleared the set.
812
+ await persist();
813
+ });
814
+ // A row a later write adds is not in this snapshot; it is not deleted.
815
+ const paths = await enqueue(async () => Array.from(new Set(state.entries
816
+ .filter((entry) => entry.scope === scope)
817
+ .map((entry) => entry.path))));
818
+ // Each path settles on its own, so one failed blob delete does not stop
819
+ // the others. Rows whose delete failed stay, for the next retry.
820
+ const outcomes = await Promise.allSettled(paths.map((path) => withPathLock(path, () => eraseUnderPathLock(path, (e) => e.scope === scope && e.path === path))));
821
+ const failed = outcomes.find((outcome) => outcome.status === "rejected");
822
+ if (failed)
823
+ throw failed.reason;
824
+ return outcomes.filter((outcome) => outcome.status === "fulfilled" && outcome.value === true).length;
639
825
  },
640
- async deleteVersion(scope, collectedAt) {
641
- const entry = state.entries.find((e) => e.scope === scope && e.collectedAt === collectedAt);
642
- if (!entry)
643
- return false;
644
- return removeEntry(entry);
826
+ // Unfenced: by (scope, collectedAt) alone. Fenced: only the row the caller
827
+ // decided on, by its id and path.
828
+ deleteVersion(scope, collectedAt, fence) {
829
+ // The path is fixed by (scope, collectedAt), so the lock is known now.
830
+ const path = envelopePath(scope, collectedAt);
831
+ return withPathLock(path, () => eraseUnderPathLock(path, (e) => e.scope === scope &&
832
+ e.collectedAt === collectedAt &&
833
+ e.path === path &&
834
+ (fence === undefined || e.id === fence.id))).then((outcome) => outcome === true);
835
+ },
836
+ // Only while the envelope is absent: the check and the erase both run
837
+ // under the path lock that every write of this path takes. A store that
838
+ // throws on read is a fault, not absence, and the row stays.
839
+ deleteVersionIfEnvelopeMissing(scope, collectedAt, fence) {
840
+ const path = envelopePath(scope, collectedAt);
841
+ if (fence.path !== path)
842
+ return Promise.resolve(false);
843
+ return withPathLock(path, async () => {
844
+ const present = (await fileStore.readEnvelope(path)) ??
845
+ (await fallbackStore.readEnvelope(path));
846
+ if (present)
847
+ return false;
848
+ const outcome = await eraseUnderPathLock(path, (e) => e.scope === scope &&
849
+ e.collectedAt === collectedAt &&
850
+ e.path === path &&
851
+ e.id === fence.id);
852
+ return outcome === true;
853
+ });
645
854
  },
646
855
  async deleteByFileId(fileId) {
647
- const entry = state.entries.find((e) => e.fileId === fileId);
648
- if (!entry)
649
- return false;
650
- return removeEntry(entry);
856
+ // The fileId only names the path whose lock to take. The row is
857
+ // re-resolved under that lock, and looked again if it moved.
858
+ for (;;) {
859
+ const path = await enqueue(async () => state.entries.find((e) => e.fileId === fileId)?.path ?? null);
860
+ if (path === null)
861
+ return false;
862
+ const outcome = await withPathLock(path, () => eraseUnderPathLock(path, (e) => e.fileId === fileId));
863
+ if (outcome !== "moved")
864
+ return outcome;
865
+ }
651
866
  },
652
867
  };
653
- async function removeEntry(entry) {
654
- const blobPath = envelopePath(entry.scope, entry.collectedAt);
655
- // Delete the blob FIRST (both stores tolerate a missing blob); only drop the index row once
656
- // the blob is gone. If blob deletion throws for a real reason, the row is preserved so the
657
- // next sync retry re-attempts instead of orphaning the local blob.
658
- await Promise.all([
659
- fileStore.deleteEnvelope(blobPath),
660
- fallbackStore.deleteEnvelope(blobPath),
661
- fileStore.deleteBlockTree?.(blockTreePath(entry.scope, entry.collectedAt)) ?? Promise.resolve(),
662
- fallbackStore.deleteBlockTree?.(blockTreePath(entry.scope, entry.collectedAt)) ?? Promise.resolve(),
663
- ]);
664
- state = {
665
- ...state,
666
- entries: state.entries.filter((e) => e !== entry),
868
+ /**
869
+ * Delete a scope's ledger side record without ever blocking the data
870
+ * delete that asked for it: a failure leaves the scope on the pending list,
871
+ * which is retried on load and on the next call.
872
+ */
873
+ async function dropLedger(scope) {
874
+ const attempt = async (name) => {
875
+ try {
876
+ await storagePort.deleteFirstSeenLedger(name);
877
+ return true;
878
+ }
879
+ catch {
880
+ return false;
881
+ }
667
882
  };
668
- await persist();
669
- return true;
883
+ const before = pendingLedgerDeletes.size;
884
+ if (await attempt(scope))
885
+ pendingLedgerDeletes.delete(scope);
886
+ else
887
+ pendingLedgerDeletes.add(scope);
888
+ for (const other of [...pendingLedgerDeletes]) {
889
+ if (other === scope)
890
+ continue;
891
+ const stillStored = state.entries.some((e) => e.scope === other);
892
+ if (stillStored || (await attempt(other)))
893
+ pendingLedgerDeletes.delete(other);
894
+ }
895
+ if (pendingLedgerDeletes.size !== before) {
896
+ await persist().catch(() => undefined);
897
+ }
898
+ }
899
+ /**
900
+ * The per-path FIFO lock: the one owner of a path's blob and row. An
901
+ * operation holds it for its whole duration, so operations on one path never
902
+ * interleave. The slot is taken synchronously at call time, so calls run in
903
+ * call order.
904
+ *
905
+ * Lock order, never reversed: path lock, then scope lock, then the index
906
+ * queue. Never take a path lock while holding the scope lock or inside the
907
+ * queue (`enqueue`), or two operations can wait on each other.
908
+ */
909
+ const pathTails = new Map();
910
+ function withPathLock(path, fn) {
911
+ const previous = pathTails.get(path);
912
+ let release;
913
+ const mine = new Promise((resolve) => {
914
+ release = resolve;
915
+ });
916
+ const tail = previous ? previous.then(() => mine) : mine;
917
+ pathTails.set(path, tail);
918
+ // A free path starts `fn` now, not a microtask later, so the caller's
919
+ // index-queue slot is taken in call order.
920
+ const run = previous
921
+ ? previous.then(fn)
922
+ : new Promise((resolve) => resolve(fn()));
923
+ return run.finally(() => {
924
+ release();
925
+ if (pathTails.get(path) === tail)
926
+ pathTails.delete(path);
927
+ });
928
+ }
929
+ /**
930
+ * Erase the row `match` picks, and its blob. The caller holds the path lock
931
+ * for `path`. The row is resolved inside the queue at the moment the lock is
932
+ * held, so an earlier update or replacement is seen. Resolves "moved" when
933
+ * the row found sits at another path, and the caller must look again.
934
+ *
935
+ * The blob parts run together, and all of them settle before this returns.
936
+ * If any part fails, the row stays and the first error is rethrown.
937
+ */
938
+ async function eraseUnderPathLock(path, match) {
939
+ const found = await enqueue(async () => {
940
+ const entry = state.entries.find(match);
941
+ if (!entry)
942
+ return null;
943
+ if (entry.path !== path)
944
+ return "moved";
945
+ // Persist the conservative hint before any destructive file operation.
946
+ // A partial delete can remove the tree while leaving the row.
947
+ readyBlockManifests.delete(blockManifestPath(entry.scope, entry.collectedAt));
948
+ await persistence.write(snapshotOf(state));
949
+ return {
950
+ id: entry.id,
951
+ scope: entry.scope,
952
+ collectedAt: entry.collectedAt,
953
+ path: entry.path,
954
+ };
955
+ });
956
+ if (found === null)
957
+ return false;
958
+ if (found === "moved")
959
+ return "moved";
960
+ return withScopeLock(found.scope, async () => {
961
+ const blob = envelopePath(found.scope, found.collectedAt);
962
+ const tree = blockTreePath(found.scope, found.collectedAt);
963
+ const parts = await Promise.allSettled([
964
+ fileStore.deleteEnvelope(blob),
965
+ fallbackStore.deleteEnvelope(blob),
966
+ fileStore.deleteBlockTree?.(tree) ?? Promise.resolve(),
967
+ fallbackStore.deleteBlockTree?.(tree) ?? Promise.resolve(),
968
+ ]);
969
+ const failed = parts.find((part) => part.status === "rejected");
970
+ if (failed)
971
+ throw failed.reason;
972
+ await enqueue(async () => {
973
+ if (!state.entries.some((e) => e.id === found.id))
974
+ return;
975
+ await publish({
976
+ ...state,
977
+ entries: state.entries.filter((e) => e.id !== found.id),
978
+ });
979
+ });
980
+ // The sidecar goes with the scope's last version.
981
+ await persist();
982
+ if (!state.entries.some((e) => e.scope === found.scope)) {
983
+ await dropLedger(found.scope);
984
+ }
985
+ return true;
986
+ });
670
987
  }
671
988
  if (fileStore.readEnvelopePreview) {
672
989
  storagePort.readEnvelopePreview = async (scope, collectedAt, { maxBytes }) => {
@@ -682,6 +999,23 @@ export async function createPersistentPsLiteStorage(adapter, persistence = creat
682
999
  return preview;
683
1000
  };
684
1001
  }
1002
+ // Collect leftovers from an earlier failed ledger delete.
1003
+ if (pendingLedgerDeletes.size > 0) {
1004
+ for (const scope of [...pendingLedgerDeletes]) {
1005
+ if (state.entries.some((e) => e.scope === scope)) {
1006
+ pendingLedgerDeletes.delete(scope);
1007
+ continue;
1008
+ }
1009
+ try {
1010
+ await storagePort.deleteFirstSeenLedger(scope);
1011
+ pendingLedgerDeletes.delete(scope);
1012
+ }
1013
+ catch {
1014
+ // Still pending; retried on the next ledger delete.
1015
+ }
1016
+ }
1017
+ await persist().catch(() => undefined);
1018
+ }
685
1019
  return storagePort;
686
1020
  }
687
1021
  async function readPreviewFromFileStore(store, path, maxBytes) {