@opendatalabs/personal-server-ts-lite 0.0.1-canary.052d47e → 0.0.1-canary.05cdd81

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 (148) hide show
  1. package/dist/account-mode-store.d.ts +11 -0
  2. package/dist/account-mode-store.d.ts.map +1 -0
  3. package/dist/account-mode-store.js +68 -0
  4. package/dist/account-mode-store.js.map +1 -0
  5. package/dist/additions-crypto.d.ts +3 -0
  6. package/dist/additions-crypto.d.ts.map +1 -0
  7. package/dist/additions-crypto.js +42 -0
  8. package/dist/additions-crypto.js.map +1 -0
  9. package/dist/additions-protocol.d.ts +56 -0
  10. package/dist/additions-protocol.d.ts.map +1 -0
  11. package/dist/additions-protocol.js +17 -0
  12. package/dist/additions-protocol.js.map +1 -0
  13. package/dist/additions-session.d.ts +20 -0
  14. package/dist/additions-session.d.ts.map +1 -0
  15. package/dist/additions-session.js +215 -0
  16. package/dist/additions-session.js.map +1 -0
  17. package/dist/additions-transport.d.ts +72 -0
  18. package/dist/additions-transport.d.ts.map +1 -0
  19. package/dist/additions-transport.js +428 -0
  20. package/dist/additions-transport.js.map +1 -0
  21. package/dist/additions-worker.bundle.js +31252 -0
  22. package/dist/additions-worker.d.ts +2 -0
  23. package/dist/additions-worker.d.ts.map +1 -0
  24. package/dist/additions-worker.js +308 -0
  25. package/dist/additions-worker.js.map +1 -0
  26. package/dist/bridge.d.ts +3 -0
  27. package/dist/bridge.d.ts.map +1 -1
  28. package/dist/bridge.js +4 -0
  29. package/dist/bridge.js.map +1 -1
  30. package/dist/browser-runtime.d.ts +111 -1
  31. package/dist/browser-runtime.d.ts.map +1 -1
  32. package/dist/browser-runtime.js +176 -11
  33. package/dist/browser-runtime.js.map +1 -1
  34. package/dist/canonical-persistence.d.ts +53 -0
  35. package/dist/canonical-persistence.d.ts.map +1 -0
  36. package/dist/canonical-persistence.js +13 -0
  37. package/dist/canonical-persistence.js.map +1 -0
  38. package/dist/canonical-store.d.ts +395 -0
  39. package/dist/canonical-store.d.ts.map +1 -0
  40. package/dist/canonical-store.js +1807 -0
  41. package/dist/canonical-store.js.map +1 -0
  42. package/dist/client.d.ts +24 -1
  43. package/dist/client.d.ts.map +1 -1
  44. package/dist/client.js +214 -1
  45. package/dist/client.js.map +1 -1
  46. package/dist/derivatives.d.ts.map +1 -1
  47. package/dist/derivatives.js +4 -2
  48. package/dist/derivatives.js.map +1 -1
  49. package/dist/diagnostics.d.ts +3 -0
  50. package/dist/diagnostics.d.ts.map +1 -1
  51. package/dist/diagnostics.js +9 -1
  52. package/dist/diagnostics.js.map +1 -1
  53. package/dist/history-probe-worker.bundle.js +31274 -0
  54. package/dist/history-probe.worker.d.ts +35 -0
  55. package/dist/history-probe.worker.d.ts.map +1 -0
  56. package/dist/history-probe.worker.js +161 -0
  57. package/dist/history-probe.worker.js.map +1 -0
  58. package/dist/index.d.ts +17 -4
  59. package/dist/index.d.ts.map +1 -1
  60. package/dist/index.js +12 -1
  61. package/dist/index.js.map +1 -1
  62. package/dist/localdb-port.d.ts +28 -0
  63. package/dist/localdb-port.d.ts.map +1 -0
  64. package/dist/localdb-port.js +30 -0
  65. package/dist/localdb-port.js.map +1 -0
  66. package/dist/mcp-store.d.ts +1 -1
  67. package/dist/mcp-store.d.ts.map +1 -1
  68. package/dist/mcp-store.js +144 -15
  69. package/dist/mcp-store.js.map +1 -1
  70. package/dist/oura-import.d.ts +2 -0
  71. package/dist/oura-import.d.ts.map +1 -0
  72. package/dist/oura-import.js +3 -0
  73. package/dist/oura-import.js.map +1 -0
  74. package/dist/owner-binding.d.ts +5 -0
  75. package/dist/owner-binding.d.ts.map +1 -1
  76. package/dist/owner-binding.js +4 -8
  77. package/dist/owner-binding.js.map +1 -1
  78. package/dist/persistence.d.ts +1 -1
  79. package/dist/persistence.d.ts.map +1 -1
  80. package/dist/persistence.js +2 -2
  81. package/dist/persistence.js.map +1 -1
  82. package/dist/pull-signals.d.ts +38 -0
  83. package/dist/pull-signals.d.ts.map +1 -0
  84. package/dist/pull-signals.js +73 -0
  85. package/dist/pull-signals.js.map +1 -0
  86. package/dist/relay-tls.d.ts.map +1 -1
  87. package/dist/relay-tls.js +10 -0
  88. package/dist/relay-tls.js.map +1 -1
  89. package/dist/relay.d.ts +91 -3
  90. package/dist/relay.d.ts.map +1 -1
  91. package/dist/relay.js +522 -75
  92. package/dist/relay.js.map +1 -1
  93. package/dist/replication-coordinator-state.d.ts +19 -0
  94. package/dist/replication-coordinator-state.d.ts.map +1 -0
  95. package/dist/replication-coordinator-state.js +20 -0
  96. package/dist/replication-coordinator-state.js.map +1 -0
  97. package/dist/replication-door.d.ts +17 -0
  98. package/dist/replication-door.d.ts.map +1 -0
  99. package/dist/replication-door.js +23 -0
  100. package/dist/replication-door.js.map +1 -0
  101. package/dist/replication-engine.d.ts +49 -0
  102. package/dist/replication-engine.d.ts.map +1 -0
  103. package/dist/replication-engine.js +589 -0
  104. package/dist/replication-engine.js.map +1 -0
  105. package/dist/replication-host.d.ts +92 -0
  106. package/dist/replication-host.d.ts.map +1 -0
  107. package/dist/replication-host.js +135 -0
  108. package/dist/replication-host.js.map +1 -0
  109. package/dist/replication-ports.d.ts +194 -0
  110. package/dist/replication-ports.d.ts.map +1 -0
  111. package/dist/replication-ports.js +58 -0
  112. package/dist/replication-ports.js.map +1 -0
  113. package/dist/replication-runtime.d.ts +64 -0
  114. package/dist/replication-runtime.d.ts.map +1 -0
  115. package/dist/replication-runtime.js +79 -0
  116. package/dist/replication-runtime.js.map +1 -0
  117. package/dist/replication-storage.d.ts +42 -0
  118. package/dist/replication-storage.d.ts.map +1 -0
  119. package/dist/replication-storage.js +173 -0
  120. package/dist/replication-storage.js.map +1 -0
  121. package/dist/runtime.d.ts +85 -6
  122. package/dist/runtime.d.ts.map +1 -1
  123. package/dist/runtime.js +561 -37
  124. package/dist/runtime.js.map +1 -1
  125. package/dist/seed-staging.d.ts +8 -0
  126. package/dist/seed-staging.d.ts.map +1 -0
  127. package/dist/seed-staging.js +106 -0
  128. package/dist/seed-staging.js.map +1 -0
  129. package/dist/state.d.ts +16 -1
  130. package/dist/state.d.ts.map +1 -1
  131. package/dist/state.js +93 -23
  132. package/dist/state.js.map +1 -1
  133. package/dist/storage-utils.d.ts.map +1 -1
  134. package/dist/storage-utils.js +11 -3
  135. package/dist/storage-utils.js.map +1 -1
  136. package/dist/storage.d.ts +59 -1
  137. package/dist/storage.d.ts.map +1 -1
  138. package/dist/storage.js +601 -150
  139. package/dist/storage.js.map +1 -1
  140. package/dist/stream-sync-budget.d.ts +3 -0
  141. package/dist/stream-sync-budget.d.ts.map +1 -0
  142. package/dist/stream-sync-budget.js +3 -0
  143. package/dist/stream-sync-budget.js.map +1 -0
  144. package/dist/sync.d.ts +104 -3
  145. package/dist/sync.d.ts.map +1 -1
  146. package/dist/sync.js +377 -62
  147. package/dist/sync.js.map +1 -1
  148. package/package.json +12 -5
package/dist/storage.js CHANGED
@@ -1,5 +1,8 @@
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 { LegacyWriteRefusedError, } from "@opendatalabs/personal-server-ts-core/storage/legacy-write-seal";
5
+ import { IngestPersistedError, VersionSupersededError, } from "@opendatalabs/personal-server-ts-core/contracts";
3
6
  import { createStorageReadMethods, sortEntries } from "./storage-utils.js";
4
7
  import { previewEnvelopeValue, previewJsonEnvelopePrefix, } from "@opendatalabs/personal-server-ts-core/storage/preview";
5
8
  const DEFAULT_INDEXED_DB_NAME = "personal-server-lite-storage";
@@ -44,8 +47,12 @@ function normalizeState(state) {
44
47
  schemaId: entry.schemaId ?? null,
45
48
  })),
46
49
  envelopes: state.envelopes,
50
+ readyBlockManifests: state.readyBlockManifests ?? [],
47
51
  blockManifests: state.blockManifests ?? [],
48
52
  blockPayloads: state.blockPayloads ?? [],
53
+ ...(state.pendingLedgerDeletes?.length
54
+ ? { pendingLedgerDeletes: state.pendingLedgerDeletes }
55
+ : {}),
49
56
  };
50
57
  }
51
58
  export function createIndexedDbFallbackDataFileStore(envelopes, blockManifests = new Map(), blockPayloads = new Map()) {
@@ -162,6 +169,39 @@ export async function createOpfsPsLiteDataFileStore() {
162
169
  await writable.close();
163
170
  return new TextEncoder().encode(encoded).length;
164
171
  },
172
+ async openEnvelopeWriter(path) {
173
+ const parts = path.split("/").filter(Boolean);
174
+ const fileName = parts.pop();
175
+ if (!fileName)
176
+ throw new Error("OPFS path must include a file name");
177
+ const dir = await getOrCreateOpfsDirectory(root, parts);
178
+ const handle = await dir.getFileHandle(fileName, { create: true });
179
+ // A writable stream writes to a swap file; `close` replaces the file in
180
+ // one step and `abort` drops the swap file.
181
+ const writable = await handle.createWritable();
182
+ let sizeBytes = 0;
183
+ let open = true;
184
+ return {
185
+ async write(text) {
186
+ const bytes = textEncoder.encode(text);
187
+ await writable.write(bytes);
188
+ sizeBytes += bytes.byteLength;
189
+ },
190
+ async commit() {
191
+ open = false;
192
+ await writable.close();
193
+ return sizeBytes;
194
+ },
195
+ async abort() {
196
+ if (!open)
197
+ return;
198
+ open = false;
199
+ await writable.abort();
200
+ // `create: true` left an empty, unindexed file at the path.
201
+ await dir.removeEntry(fileName).catch(() => undefined);
202
+ },
203
+ };
204
+ },
165
205
  async deleteEnvelope(path) {
166
206
  const parts = path.split("/").filter(Boolean);
167
207
  const fileName = parts.pop();
@@ -250,17 +290,37 @@ function openIndexedDb(dbName, storeName) {
250
290
  request.onerror = () => reject(request.error);
251
291
  });
252
292
  }
293
+ /**
294
+ * Run one request in its own transaction. Resolves with the request's result
295
+ * only when the transaction has committed: a request's `success` event comes
296
+ * before the commit, and the transaction can still abort after it (quota, a
297
+ * closed tab, an explicit `abort()`). Rejects on a request error and on abort.
298
+ */
253
299
  function runIndexedDbTransaction(options, mode, callback) {
254
300
  return openIndexedDb(options.dbName, options.storeName).then((db) => new Promise((resolve, reject) => {
255
- const transaction = db.transaction(options.storeName, mode);
256
- const store = transaction.objectStore(options.storeName);
257
- const request = callback(store);
258
- request.onsuccess = () => resolve(request.result);
259
- request.onerror = () => reject(request.error);
260
- transaction.oncomplete = () => db.close();
301
+ let transaction;
302
+ let request;
303
+ try {
304
+ transaction = db.transaction(options.storeName, mode);
305
+ request = callback(transaction.objectStore(options.storeName));
306
+ }
307
+ catch (err) {
308
+ db.close();
309
+ reject(err);
310
+ return;
311
+ }
312
+ transaction.oncomplete = () => {
313
+ db.close();
314
+ resolve(request.result);
315
+ };
261
316
  transaction.onerror = () => {
262
317
  db.close();
263
- reject(transaction.error);
318
+ reject(transaction.error ?? request.error);
319
+ };
320
+ transaction.onabort = () => {
321
+ db.close();
322
+ reject(transaction.error ??
323
+ new DOMException("The transaction was aborted", "AbortError"));
264
324
  };
265
325
  }));
266
326
  }
@@ -278,16 +338,57 @@ export function createIndexedDbPsLitePersistence(options = {}) {
278
338
  async write(state) {
279
339
  await runIndexedDbTransaction(resolved, "readwrite", (store) => store.put(state, resolved.key));
280
340
  },
341
+ // Side records live in the same object store under their own keys, which
342
+ // a build that only knows `resolved.key` never reads.
343
+ async readAux(name) {
344
+ const value = await runIndexedDbTransaction(resolved, "readonly", (store) => store.get(`${resolved.key}:${name}`));
345
+ return value ?? null;
346
+ },
347
+ async writeAux(name, value) {
348
+ await runIndexedDbTransaction(resolved, "readwrite", (store) => store.put(value, `${resolved.key}:${name}`));
349
+ },
350
+ async deleteAux(name) {
351
+ await runIndexedDbTransaction(resolved, "readwrite", (store) => store.delete(`${resolved.key}:${name}`));
352
+ },
281
353
  };
282
354
  }
283
- export async function createPersistentPsLiteStorage(adapter, persistence = createIndexedDbPsLitePersistence(), dataFileStore) {
355
+ /**
356
+ * Persistent Lite storage. `legacyWriteSeal` is required: the storage makes a
357
+ * legacy version durable only inside `legacyWriteSeal.commit`, and removes
358
+ * data only inside `legacyWriteSeal.remove` (or under the `hold` of a caller
359
+ * that is already inside `commit`).
360
+ *
361
+ * Lock order, for every sealed method: the seal first, then the path lock,
362
+ * then the scope lock, then the index queue. A method takes the seal once, at
363
+ * its outermost call, and hands the hold to the helpers it calls; the seal is
364
+ * never taken from inside a path lock, the queue or a scope lock, so a write
365
+ * that waits behind a queued On cannot be waited on by a call that holds the
366
+ * lock the On is waiting for.
367
+ *
368
+ * Not sealed, because they add no visible version: `updateFileId`,
369
+ * `updateDataPointId`, `updateEntryVersion` (they rewrite a row that is
370
+ * already visible), and the sidecars (block manifests and payloads, first-seen
371
+ * ledgers).
372
+ */
373
+ export async function createPersistentPsLiteStorage(adapter, persistenceAdapter, dataFileStore, legacyWriteSeal) {
374
+ const persistence = persistenceAdapter ?? createIndexedDbPsLitePersistence();
284
375
  let state = normalizeState(await persistence.read());
285
376
  const fallbackEnvelopes = new Map(state.envelopes.map((envelope) => [
286
377
  envelopePath(envelope.scope, envelope.collectedAt),
287
378
  envelope,
288
379
  ]));
289
380
  const fallbackBlockManifests = new Map((state.blockManifests ?? []).map(({ path, manifest }) => [path, manifest]));
381
+ const readyBlockManifests = new Set([
382
+ ...(state.readyBlockManifests ?? []),
383
+ ...fallbackBlockManifests.keys(),
384
+ ]);
290
385
  const fallbackBlockPayloads = new Map((state.blockPayloads ?? []).map(({ path, block }) => [path, block]));
386
+ // First-seen ledgers: each persisted on its own (`persistence.*Aux`), read
387
+ // lazily, never part of the main state. A ledger the previous build kept
388
+ // inside the main state is ignored: it is a cache, rebuilt on demand.
389
+ const ledgerAux = (scope) => `first-seen:${scope}`;
390
+ const firstSeenLedgers = new Map();
391
+ const pendingLedgerDeletes = new Set(state.pendingLedgerDeletes ?? []);
291
392
  const fallbackStore = createIndexedDbFallbackDataFileStore(fallbackEnvelopes, fallbackBlockManifests, fallbackBlockPayloads);
292
393
  const fileStore = dataFileStore ??
293
394
  (adapter.kind !== "custom" && (await isOpfsAvailable())
@@ -298,32 +399,171 @@ export async function createPersistentPsLiteStorage(adapter, persistence = creat
298
399
  files: fileStore.kind,
299
400
  opfsAvailable: await isOpfsAvailable(),
300
401
  };
402
+ // Every write of the persisted state runs in this queue, one at a time, in
403
+ // call order. A snapshot is taken when its turn comes, so each write carries
404
+ // the latest index, and index changes never interleave.
301
405
  let persistQueue = Promise.resolve();
302
- async function persist() {
303
- const snapshot = {
304
- ...state,
406
+ function enqueue(step) {
407
+ const run = persistQueue.then(step);
408
+ persistQueue = run.then(() => undefined, () => undefined);
409
+ return run;
410
+ }
411
+ /**
412
+ * Write a version's blob. Caller holds the path lock and is inside
413
+ * `legacyWriteSeal.commit`. Returns the size in bytes.
414
+ */
415
+ async function storeEnvelopeBlob(_hold, path, envelope) {
416
+ const size = await fileStore.writeEnvelope(path, envelope);
417
+ if (fileStore.kind !== "indexeddb") {
418
+ await fallbackStore.deleteEnvelope(path);
419
+ }
420
+ return size;
421
+ }
422
+ /**
423
+ * Run a pure removal. Inside a `commit` (the caller passes its `hold`) it
424
+ * runs as is, because the lock is already held and is not re-entrant;
425
+ * otherwise it takes the seal's shared lock, which is open in every mode.
426
+ */
427
+ function removal(hold, work) {
428
+ return hold ? work() : legacyWriteSeal.remove(work);
429
+ }
430
+ function snapshotOf(source) {
431
+ return {
432
+ ...source,
433
+ readyBlockManifests: Array.from(readyBlockManifests),
305
434
  envelopes: fileStore.kind === "indexeddb"
306
435
  ? Array.from(fallbackEnvelopes.values())
307
436
  : [],
308
437
  blockManifests: Array.from(fallbackBlockManifests.entries()).map(([path, manifest]) => ({ path, manifest })),
309
438
  blockPayloads: Array.from(fallbackBlockPayloads.entries()).map(([path, block]) => ({ path, block })),
439
+ pendingLedgerDeletes: pendingLedgerDeletes.size > 0
440
+ ? Array.from(pendingLedgerDeletes)
441
+ : undefined,
310
442
  };
311
- const write = persistQueue.then(() => persistence.write(snapshot));
312
- persistQueue = write.catch(() => undefined);
313
- await write;
314
443
  }
444
+ async function persist() {
445
+ await enqueue(() => persistence.write(snapshotOf(state)));
446
+ }
447
+ /**
448
+ * Make `next` the live index, once it is durable. Call only inside
449
+ * `enqueue`. A failed write leaves the live index as it was, so a reader
450
+ * never sees a change that could be lost on restart.
451
+ */
452
+ async function publish(next) {
453
+ await persistence.write(snapshotOf(next));
454
+ state = next;
455
+ }
456
+ /**
457
+ * Replace the live index with `change(index)`. `change` returns null to
458
+ * leave the index alone. Resolves to whether the index was written.
459
+ */
460
+ function updateIndex(change) {
461
+ return enqueue(async () => {
462
+ const next = change(state);
463
+ if (!next)
464
+ return false;
465
+ await publish(next);
466
+ return true;
467
+ });
468
+ }
469
+ function updateEntryField(path, patch, expectedId) {
470
+ return updateIndex((current) => {
471
+ const row = current.entries.find((entry) => entry.path === path);
472
+ if (!row || (expectedId !== undefined && row.id !== expectedId))
473
+ return null;
474
+ return {
475
+ ...current,
476
+ entries: current.entries.map((entry) => entry.path === path ? { ...entry, ...patch } : entry),
477
+ };
478
+ });
479
+ }
480
+ /**
481
+ * Remove a blob that no index entry names, after its index write failed. A
482
+ * blob that an entry does name is kept. Best effort: the commit's own error
483
+ * is what the caller sees.
484
+ */
485
+ function dropUnindexedEnvelope(path) {
486
+ return enqueue(async () => {
487
+ if (state.entries.some((entry) => entry.path === path))
488
+ return;
489
+ await Promise.all([
490
+ fileStore.deleteEnvelope(path),
491
+ fallbackStore.deleteEnvelope(path),
492
+ ]);
493
+ }).catch(() => undefined);
494
+ }
495
+ /**
496
+ * Install a row at its path, replacing any row there. A row is a visible
497
+ * legacy version, so the caller must be inside `legacyWriteSeal.commit` (it
498
+ * holds the proof) and holds the path lock. With `onlyIfNewest`, the row is
499
+ * refused when the scope already has a later `collectedAt`; that check runs
500
+ * in the index queue, so it is atomic with the publication.
501
+ */
502
+ async function installEntry(_hold, entry, options = {}) {
503
+ let indexed;
504
+ await updateIndex((current) => {
505
+ if (options.onlyIfNewest &&
506
+ current.entries.some((e) => e.scope === entry.scope &&
507
+ Date.parse(e.collectedAt) > Date.parse(entry.collectedAt))) {
508
+ throw new VersionSupersededError(entry.scope);
509
+ }
510
+ const version = entry.version ??
511
+ current.entries.reduce((max, e) => e.scope === entry.scope && e.version > max ? e.version : max, 0) + 1;
512
+ indexed = {
513
+ ...entry,
514
+ schemaId: entry.schemaId ?? null,
515
+ version,
516
+ dataPointId: entry.dataPointId ?? null,
517
+ afterTombstoneVersion: entry.afterTombstoneVersion ?? null,
518
+ id: current.nextId,
519
+ createdAt: new Date().toISOString(),
520
+ };
521
+ return {
522
+ ...current,
523
+ nextId: current.nextId + 1,
524
+ entries: [
525
+ ...current.entries.filter((item) => item.path !== entry.path),
526
+ indexed,
527
+ ],
528
+ };
529
+ });
530
+ return indexed;
531
+ }
532
+ // Rows grouped by scope, rebuilt once per index state (state is replaced,
533
+ // never edited in place), so a lookup is O(scope rows) instead of O(all
534
+ // rows): the upload worker looks up every coalesced scope it plans.
535
+ let scopeGroups;
315
536
  function entriesForScope(scope) {
316
- return sortEntries(state.entries.filter((entry) => entry.scope === scope));
537
+ if (scopeGroups?.source !== state.entries) {
538
+ const groups = new Map();
539
+ for (const entry of state.entries) {
540
+ const group = groups.get(entry.scope);
541
+ if (group)
542
+ group.push(entry);
543
+ else
544
+ groups.set(entry.scope, [entry]);
545
+ }
546
+ scopeGroups = { source: state.entries, groups };
547
+ }
548
+ return sortEntries(scopeGroups.groups.get(scope) ?? []);
317
549
  }
318
550
  const storagePort = {
319
551
  kind: adapter.kind === "custom" ? "custom" : "browser-indexeddb-opfs",
320
552
  capabilities,
553
+ legacyWriteSeal,
321
554
  ...createStorageReadMethods(() => state.entries, entriesForScope),
322
555
  findByFileId(fileId) {
323
556
  return state.entries.find((entry) => entry.fileId === fileId);
324
557
  },
325
558
  findByDataPointId(dataPointId) {
326
- return state.entries.find((entry) => entry.dataPointId === dataPointId);
559
+ let newest;
560
+ for (const entry of state.entries) {
561
+ if (entry.dataPointId !== dataPointId)
562
+ continue;
563
+ if (!newest || entry.version >= newest.version)
564
+ newest = entry;
565
+ }
566
+ return newest;
327
567
  },
328
568
  findUnsynced(options) {
329
569
  const entries = state.entries
@@ -333,6 +573,30 @@ export async function createPersistentPsLiteStorage(adapter, persistence = creat
333
573
  ? entries
334
574
  : entries.slice(0, options.limit);
335
575
  },
576
+ findUnsyncedPage({ afterId, limit }) {
577
+ const page = [];
578
+ for (const entry of state.entries) {
579
+ if (entry.dataPointId === null && entry.id > afterId)
580
+ page.push(entry);
581
+ }
582
+ return page.sort((a, b) => a.id - b.id).slice(0, limit);
583
+ },
584
+ countUnsynced() {
585
+ let count = 0;
586
+ for (const entry of state.entries) {
587
+ if (entry.dataPointId === null)
588
+ count += 1;
589
+ }
590
+ return count;
591
+ },
592
+ maxUnsyncedId() {
593
+ let max = 0;
594
+ for (const entry of state.entries) {
595
+ if (entry.dataPointId === null && entry.id > max)
596
+ max = entry.id;
597
+ }
598
+ return max;
599
+ },
336
600
  async readEnvelope(scope, collectedAt) {
337
601
  const path = envelopePath(scope, collectedAt);
338
602
  const envelope = (await fileStore.readEnvelope(path)) ??
@@ -342,19 +606,93 @@ export async function createPersistentPsLiteStorage(adapter, persistence = creat
342
606
  }
343
607
  return envelope;
344
608
  },
345
- async writeEnvelope(envelope) {
609
+ // A blob with no row is invisible, but it is the bytes of a legacy
610
+ // version: a refused write must not write them. The whole write is sealed,
611
+ // so a refusal happens before any file is touched and there is nothing to
612
+ // clean up.
613
+ writeEnvelope(envelope) {
346
614
  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
- }
351
- await persist();
352
- return {
353
- path,
354
- relativePath: path,
355
- sizeBytes,
356
- };
615
+ return legacyWriteSeal.commit(async (blobHold) => {
616
+ const sizeBytes = await withPathLock(path, () => storeEnvelopeBlob(blobHold, path, envelope));
617
+ await persist();
618
+ return {
619
+ path,
620
+ relativePath: path,
621
+ sizeBytes,
622
+ };
623
+ });
357
624
  },
625
+ writeEnvelopeAndIndex(envelope, entry) {
626
+ const path = envelopePath(envelope.scope, envelope.collectedAt);
627
+ // Sealed as one step, blob and row: a refusal comes before the blob is
628
+ // written, so a refused write leaves neither. Under the seal, the blob
629
+ // and its row are one step under the path lock, so no erase or
630
+ // replacement of this path runs between them.
631
+ return legacyWriteSeal.commit((blobAndRowHold) => withPathLock(path, async () => {
632
+ const size = await storeEnvelopeBlob(blobAndRowHold, path, envelope);
633
+ try {
634
+ return await installEntry(blobAndRowHold, {
635
+ ...entry,
636
+ scope: envelope.scope,
637
+ collectedAt: envelope.collectedAt,
638
+ path,
639
+ sizeBytes: entry.sizeBytes ?? size,
640
+ });
641
+ }
642
+ catch (error) {
643
+ // The bytes are durable here; the caller's recovery depends on that.
644
+ throw new IngestPersistedError(path, error);
645
+ }
646
+ }));
647
+ },
648
+ ...(fileStore.openEnvelopeWriter
649
+ ? {
650
+ async openVersionWriter(scope, collectedAt) {
651
+ const path = envelopePath(scope, collectedAt);
652
+ const file = await fileStore.openEnvelopeWriter(path);
653
+ return {
654
+ write: (text) => file.write(text),
655
+ abort: () => file.abort(),
656
+ async commit(entry, options) {
657
+ // The bytes were streamed to a staged file before this call
658
+ // and are invisible there. The seal covers the rename and the
659
+ // index install, which are one step under the path lock, so
660
+ // no erase of this path runs between them. A refused commit
661
+ // discards the staged file.
662
+ try {
663
+ return await legacyWriteSeal.commit((renameHold) => withPathLock(path, async () => {
664
+ const sizeBytes = await file.commit();
665
+ try {
666
+ // The index entry is what makes the version visible.
667
+ await installEntry(renameHold, {
668
+ ...entry,
669
+ scope,
670
+ collectedAt,
671
+ path,
672
+ sizeBytes,
673
+ }, options);
674
+ }
675
+ catch (error) {
676
+ await dropUnindexedEnvelope(path);
677
+ throw error;
678
+ }
679
+ if (fileStore.kind !== "indexeddb") {
680
+ await fallbackStore.deleteEnvelope(path);
681
+ }
682
+ return { path, relativePath: path, sizeBytes };
683
+ }));
684
+ }
685
+ catch (error) {
686
+ if (error instanceof LegacyWriteRefusedError) {
687
+ await file.abort();
688
+ }
689
+ throw error;
690
+ }
691
+ },
692
+ };
693
+ },
694
+ }
695
+ : {}),
358
696
  async readScopeBlocks(scope, collectedAt, options) {
359
697
  const manifestPath = blockManifestPath(scope, collectedAt);
360
698
  let manifest = (await fileStore.readBlockManifest?.(manifestPath)) ??
@@ -482,7 +820,7 @@ export async function createPersistentPsLiteStorage(adapter, persistence = creat
482
820
  null);
483
821
  },
484
822
  async hasScopeBlocks(scope, collectedAt) {
485
- return Boolean(await storagePort.readBlockManifest?.(scope, collectedAt));
823
+ return readyBlockManifests.has(blockManifestPath(scope, collectedAt));
486
824
  },
487
825
  async canReadScopeBlocks(scope, collectedAt) {
488
826
  if (await storagePort.hasScopeBlocks?.(scope, collectedAt)) {
@@ -502,6 +840,9 @@ export async function createPersistentPsLiteStorage(adapter, persistence = creat
502
840
  return Boolean(envelope);
503
841
  },
504
842
  async writeBlockManifest(scope, collectedAt, manifest, blocks) {
843
+ // Invalidate before replacing a tree; a failed build is not ready.
844
+ readyBlockManifests.delete(blockManifestPath(scope, collectedAt));
845
+ await persist();
505
846
  const writeTree = async (store) => {
506
847
  if (!store.writeBlockManifest || !store.writeBlockPayload) {
507
848
  throw new Error("Block sidecar storage is not available");
@@ -533,140 +874,233 @@ export async function createPersistentPsLiteStorage(adapter, persistence = creat
533
874
  if (wrotePrimary && fileStore.kind !== "indexeddb") {
534
875
  await fallbackStore.deleteBlockTree?.(blockTreePath(scope, collectedAt));
535
876
  }
877
+ readyBlockManifests.add(blockManifestPath(scope, collectedAt));
536
878
  await persist();
537
879
  },
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;
880
+ insertEntry(entry) {
881
+ return legacyWriteSeal.commit((rowHold) => withPathLock(entry.path, () => installEntry(rowHold, entry)));
882
+ },
883
+ updateFileId(path, fileId) {
884
+ return updateEntryField(path, { fileId });
576
885
  },
577
886
  findLatestVersionByScope(scope) {
578
887
  return state.entries.reduce((max, e) => (e.scope === scope && e.version > max ? e.version : max), 0);
579
888
  },
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();
889
+ updateDataPointId(path, dataPointId, expectedId) {
890
+ return updateEntryField(path, { dataPointId }, expectedId);
891
+ },
892
+ updateEntryVersion(path, version, expectedId) {
893
+ return updateEntryField(path, { version }, expectedId);
894
+ },
895
+ async readFirstSeenLedger(scope) {
896
+ if (!firstSeenLedgers.has(scope)) {
897
+ const stored = (await persistence.readAux?.(ledgerAux(scope))) ?? null;
898
+ if (stored !== null)
899
+ firstSeenLedgers.set(scope, stored);
609
900
  }
610
- return updated;
611
- },
612
- 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;
901
+ return structuredClone(firstSeenLedgers.get(scope) ?? null);
639
902
  },
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);
903
+ async writeFirstSeenLedger(scope, ledger) {
904
+ firstSeenLedgers.set(scope, structuredClone(ledger));
905
+ await persistence.writeAux?.(ledgerAux(scope), ledger);
645
906
  },
646
- async deleteByFileId(fileId) {
647
- const entry = state.entries.find((e) => e.fileId === fileId);
648
- if (!entry)
649
- return false;
650
- return removeEntry(entry);
907
+ async deleteFirstSeenLedger(scope) {
908
+ firstSeenLedgers.delete(scope);
909
+ await persistence.deleteAux?.(ledgerAux(scope));
910
+ },
911
+ // The whole removal runs under the seal's shared lock (or the caller's
912
+ // hold). The ledger barrier runs under the scope lock (a rebuild in flight
913
+ // cannot write it back). Each row is then erased under its own path lock,
914
+ // the same owner an ordinary write takes, so no write to a path
915
+ // interleaves with the erase of that path. The scope lock is never held
916
+ // across those path locks: lock order is seal, path, scope, queue.
917
+ deleteScope(scope, hold) {
918
+ return removal(hold, async () => {
919
+ await withScopeLock(scope, async () => {
920
+ await dropLedger(scope);
921
+ for (const entry of entriesForScope(scope)) {
922
+ readyBlockManifests.delete(blockManifestPath(scope, entry.collectedAt));
923
+ }
924
+ // Repeat the barrier on retry, even if a failed write cleared the set.
925
+ await persist();
926
+ });
927
+ // A row a later write adds is not in this snapshot; it is not deleted.
928
+ const paths = await enqueue(async () => Array.from(new Set(state.entries
929
+ .filter((entry) => entry.scope === scope)
930
+ .map((entry) => entry.path))));
931
+ // Each path settles on its own, so one failed blob delete does not stop
932
+ // the others. Rows whose delete failed stay, for the next retry.
933
+ const outcomes = await Promise.allSettled(paths.map((path) => withPathLock(path, () => eraseUnderPathLock(path, (e) => e.scope === scope && e.path === path))));
934
+ const failed = outcomes.find((outcome) => outcome.status === "rejected");
935
+ if (failed)
936
+ throw failed.reason;
937
+ return outcomes.filter((outcome) => outcome.status === "fulfilled" && outcome.value === true).length;
938
+ });
939
+ },
940
+ // Unfenced: by (scope, collectedAt) alone. Fenced: only the row the caller
941
+ // decided on, by its id and path.
942
+ deleteVersion(scope, collectedAt, fence, hold) {
943
+ // The path is fixed by (scope, collectedAt), so the lock is known now.
944
+ const path = envelopePath(scope, collectedAt);
945
+ return removal(hold, () => withPathLock(path, () => eraseUnderPathLock(path, (e) => e.scope === scope &&
946
+ e.collectedAt === collectedAt &&
947
+ e.path === path &&
948
+ (fence === undefined || e.id === fence.id)))).then((outcome) => outcome === true);
949
+ },
950
+ // Only while the envelope is absent: the check and the erase both run
951
+ // under the path lock that every write of this path takes. A store that
952
+ // throws on read is a fault, not absence, and the row stays.
953
+ deleteVersionIfEnvelopeMissing(scope, collectedAt, fence, hold) {
954
+ const path = envelopePath(scope, collectedAt);
955
+ if (fence.path !== path)
956
+ return Promise.resolve(false);
957
+ return removal(hold, () => withPathLock(path, async () => {
958
+ const present = (await fileStore.readEnvelope(path)) ??
959
+ (await fallbackStore.readEnvelope(path));
960
+ if (present)
961
+ return false;
962
+ const outcome = await eraseUnderPathLock(path, (e) => e.scope === scope &&
963
+ e.collectedAt === collectedAt &&
964
+ e.path === path &&
965
+ e.id === fence.id);
966
+ return outcome === true;
967
+ }));
968
+ },
969
+ deleteByFileId(fileId, hold) {
970
+ return removal(hold, async () => {
971
+ // The fileId only names the path whose lock to take. The row is
972
+ // re-resolved under that lock, and looked again if it moved.
973
+ for (;;) {
974
+ const path = await enqueue(async () => state.entries.find((e) => e.fileId === fileId)?.path ?? null);
975
+ if (path === null)
976
+ return false;
977
+ const outcome = await withPathLock(path, () => eraseUnderPathLock(path, (e) => e.fileId === fileId));
978
+ if (outcome !== "moved")
979
+ return outcome;
980
+ }
981
+ });
651
982
  },
652
983
  };
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),
984
+ /**
985
+ * Delete a scope's ledger side record without ever blocking the data
986
+ * delete that asked for it: a failure leaves the scope on the pending list,
987
+ * which is retried on load and on the next call.
988
+ */
989
+ async function dropLedger(scope) {
990
+ const attempt = async (name) => {
991
+ try {
992
+ await storagePort.deleteFirstSeenLedger(name);
993
+ return true;
994
+ }
995
+ catch {
996
+ return false;
997
+ }
667
998
  };
668
- await persist();
669
- return true;
999
+ const before = pendingLedgerDeletes.size;
1000
+ if (await attempt(scope))
1001
+ pendingLedgerDeletes.delete(scope);
1002
+ else
1003
+ pendingLedgerDeletes.add(scope);
1004
+ for (const other of [...pendingLedgerDeletes]) {
1005
+ if (other === scope)
1006
+ continue;
1007
+ const stillStored = state.entries.some((e) => e.scope === other);
1008
+ if (stillStored || (await attempt(other)))
1009
+ pendingLedgerDeletes.delete(other);
1010
+ }
1011
+ if (pendingLedgerDeletes.size !== before) {
1012
+ await persist().catch(() => undefined);
1013
+ }
1014
+ }
1015
+ /**
1016
+ * The per-path FIFO lock: the one owner of a path's blob and row. An
1017
+ * operation holds it for its whole duration, so operations on one path never
1018
+ * interleave. The slot is taken synchronously at call time, so calls run in
1019
+ * call order.
1020
+ *
1021
+ * Lock order, never reversed: the legacy-write seal, then the path lock,
1022
+ * then the scope lock, then the index queue. Never take a path lock while
1023
+ * holding the scope lock or inside the queue (`enqueue`), and never take the
1024
+ * seal inside any of them, or two operations can wait on each other.
1025
+ */
1026
+ const pathTails = new Map();
1027
+ function withPathLock(path, fn) {
1028
+ const previous = pathTails.get(path);
1029
+ let release;
1030
+ const mine = new Promise((resolve) => {
1031
+ release = resolve;
1032
+ });
1033
+ const tail = previous ? previous.then(() => mine) : mine;
1034
+ pathTails.set(path, tail);
1035
+ // A free path starts `fn` now, not a microtask later, so the caller's
1036
+ // index-queue slot is taken in call order.
1037
+ const run = previous
1038
+ ? previous.then(fn)
1039
+ : new Promise((resolve) => resolve(fn()));
1040
+ return run.finally(() => {
1041
+ release();
1042
+ if (pathTails.get(path) === tail)
1043
+ pathTails.delete(path);
1044
+ });
1045
+ }
1046
+ /**
1047
+ * Erase the row `match` picks, and its blob. The caller holds the path lock
1048
+ * for `path`. The row is resolved inside the queue at the moment the lock is
1049
+ * held, so an earlier update or replacement is seen. Resolves "moved" when
1050
+ * the row found sits at another path, and the caller must look again.
1051
+ *
1052
+ * The blob parts run together, and all of them settle before this returns.
1053
+ * If any part fails, the row stays and the first error is rethrown.
1054
+ */
1055
+ async function eraseUnderPathLock(path, match) {
1056
+ const found = await enqueue(async () => {
1057
+ const entry = state.entries.find(match);
1058
+ if (!entry)
1059
+ return null;
1060
+ if (entry.path !== path)
1061
+ return "moved";
1062
+ // Persist the conservative hint before any destructive file operation.
1063
+ // A partial delete can remove the tree while leaving the row.
1064
+ readyBlockManifests.delete(blockManifestPath(entry.scope, entry.collectedAt));
1065
+ await persistence.write(snapshotOf(state));
1066
+ return {
1067
+ id: entry.id,
1068
+ scope: entry.scope,
1069
+ collectedAt: entry.collectedAt,
1070
+ path: entry.path,
1071
+ };
1072
+ });
1073
+ if (found === null)
1074
+ return false;
1075
+ if (found === "moved")
1076
+ return "moved";
1077
+ return withScopeLock(found.scope, async () => {
1078
+ const blob = envelopePath(found.scope, found.collectedAt);
1079
+ const tree = blockTreePath(found.scope, found.collectedAt);
1080
+ const parts = await Promise.allSettled([
1081
+ fileStore.deleteEnvelope(blob),
1082
+ fallbackStore.deleteEnvelope(blob),
1083
+ fileStore.deleteBlockTree?.(tree) ?? Promise.resolve(),
1084
+ fallbackStore.deleteBlockTree?.(tree) ?? Promise.resolve(),
1085
+ ]);
1086
+ const failed = parts.find((part) => part.status === "rejected");
1087
+ if (failed)
1088
+ throw failed.reason;
1089
+ await enqueue(async () => {
1090
+ if (!state.entries.some((e) => e.id === found.id))
1091
+ return;
1092
+ await publish({
1093
+ ...state,
1094
+ entries: state.entries.filter((e) => e.id !== found.id),
1095
+ });
1096
+ });
1097
+ // The sidecar goes with the scope's last version.
1098
+ await persist();
1099
+ if (!state.entries.some((e) => e.scope === found.scope)) {
1100
+ await dropLedger(found.scope);
1101
+ }
1102
+ return true;
1103
+ });
670
1104
  }
671
1105
  if (fileStore.readEnvelopePreview) {
672
1106
  storagePort.readEnvelopePreview = async (scope, collectedAt, { maxBytes }) => {
@@ -682,6 +1116,23 @@ export async function createPersistentPsLiteStorage(adapter, persistence = creat
682
1116
  return preview;
683
1117
  };
684
1118
  }
1119
+ // Collect leftovers from an earlier failed ledger delete.
1120
+ if (pendingLedgerDeletes.size > 0) {
1121
+ for (const scope of [...pendingLedgerDeletes]) {
1122
+ if (state.entries.some((e) => e.scope === scope)) {
1123
+ pendingLedgerDeletes.delete(scope);
1124
+ continue;
1125
+ }
1126
+ try {
1127
+ await storagePort.deleteFirstSeenLedger(scope);
1128
+ pendingLedgerDeletes.delete(scope);
1129
+ }
1130
+ catch {
1131
+ // Still pending; retried on the next ledger delete.
1132
+ }
1133
+ }
1134
+ await persist().catch(() => undefined);
1135
+ }
685
1136
  return storagePort;
686
1137
  }
687
1138
  async function readPreviewFromFileStore(store, path, maxBytes) {