@waffle-os/runtime 0.0.153 → 0.0.155

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 (61) hide show
  1. package/browser/net/helper.ts +114 -19
  2. package/browser/net/ring.ts +18 -6
  3. package/browser/net/runtime.ts +2 -2
  4. package/browser/notification-relay.ts +105 -18
  5. package/browser/notification-wait.ts +45 -4
  6. package/browser/notification-worker.ts +169 -76
  7. package/browser/preview.ts +15 -2
  8. package/core/filesystem.ts +18 -0
  9. package/core/wasi.ts +75 -4
  10. package/dist/browser/net/helper.js +83 -18
  11. package/dist/browser/net/ring.js +6 -5
  12. package/dist/browser/net/runtime.js +2 -2
  13. package/dist/browser/notification-relay.js +78 -15
  14. package/dist/browser/notification-wait.js +37 -5
  15. package/dist/browser/notification-worker.js +146 -67
  16. package/dist/core/wasi.js +62 -4
  17. package/dist/fs/backend.js +7 -0
  18. package/dist/fs/client.js +75 -17
  19. package/dist/fs/dirty-admission.js +15 -8
  20. package/dist/fs/guest-watch.js +267 -94
  21. package/dist/fs/indexeddb-chunks.js +88 -11
  22. package/dist/fs/indexeddb.js +366 -110
  23. package/dist/fs/memory.js +106 -20
  24. package/dist/fs/multitab-backend.js +291 -74
  25. package/dist/fs/multitab-protocol.js +1 -0
  26. package/dist/fs/persistent.js +70 -16
  27. package/dist/fs/protocol.js +15 -7
  28. package/dist/fs/publication-attachment.js +9 -7
  29. package/dist/fs/service.js +62 -9
  30. package/dist/fs/shared.js +100 -6
  31. package/dist/fs/storage.js +107 -8
  32. package/dist/fs/watch-service.js +97 -2
  33. package/dist/fs/watch-subscriptions.js +121 -8
  34. package/dist/proc/command-stdio.js +1 -1
  35. package/dist/proc/intrinsics/core.js +5 -0
  36. package/dist/proc/intrinsics.js +1 -0
  37. package/dist/tooling/program/program-transformer.json +1 -1
  38. package/fs/backend.ts +17 -0
  39. package/fs/client.ts +99 -16
  40. package/fs/dirty-admission.ts +22 -7
  41. package/fs/guest-watch.ts +299 -103
  42. package/fs/indexeddb-chunks.ts +103 -9
  43. package/fs/indexeddb.ts +477 -121
  44. package/fs/memory.ts +120 -19
  45. package/fs/multitab-backend.ts +440 -95
  46. package/fs/multitab-protocol.ts +1 -0
  47. package/fs/persistent.ts +88 -16
  48. package/fs/protocol.ts +26 -7
  49. package/fs/publication-attachment.ts +9 -7
  50. package/fs/service.ts +62 -7
  51. package/fs/shared.ts +110 -8
  52. package/fs/storage.ts +128 -10
  53. package/fs/watch-service.ts +110 -3
  54. package/fs/watch-subscriptions.ts +115 -7
  55. package/package.json +1 -1
  56. package/proc/command-stdio.ts +1 -1
  57. package/proc/intrinsics/core.ts +7 -0
  58. package/proc/intrinsics.ts +1 -0
  59. package/testing/idle-workspace-cancellation-browser.ts +22 -13
  60. package/testing/indexeddb-storage-browser.ts +564 -1
  61. package/tooling/program/program-transformer.json +1 -1
package/fs/indexeddb.ts CHANGED
@@ -28,6 +28,7 @@ import {
28
28
  parseManifest,
29
29
  preparePayload,
30
30
  preparePayloads,
31
+ putPayload,
31
32
  copyLegacyChunks,
32
33
  validateRange,
33
34
  type ChunkManifest,
@@ -422,8 +423,37 @@ interface State extends TreeState {
422
423
  journals: Map<number, Journal>;
423
424
  journalKeys: IDBValidKey[];
424
425
  payloadKeys: Set<string>;
426
+ /** Payload sizes named by `nodes`, `bases` and `journals`, kept with every change to them. */
427
+ payloadSizes: PayloadSizes;
425
428
  sinceCompaction: number;
426
429
  }
430
+ /** The size of each payload that a node of the current tree, a recovery base or a kept journal
431
+ * names, counted per naming node so a lookup never scans the tree. Validation keeps every node
432
+ * naming one key at the size of its stored manifest. */
433
+ class PayloadSizes {
434
+ private readonly entries = new Map<string, { size: number; count: number }>();
435
+ add(nodes: Iterable<PersistedNode>): void {
436
+ for (const node of nodes) {
437
+ if (node.data === undefined) continue;
438
+ const entry = this.entries.get(node.data);
439
+ if (entry) entry.count++;
440
+ else this.entries.set(node.data, { size: node.size, count: 1 });
441
+ }
442
+ }
443
+ remove(nodes: Iterable<PersistedNode>): void {
444
+ for (const node of nodes) {
445
+ if (node.data === undefined) continue;
446
+ const entry = this.entries.get(node.data);
447
+ if (entry && --entry.count === 0) this.entries.delete(node.data);
448
+ }
449
+ }
450
+ size(key: string): number | undefined {
451
+ return this.entries.get(key)?.size;
452
+ }
453
+ has(key: string): boolean {
454
+ return this.entries.has(key);
455
+ }
456
+ }
427
457
  interface CommittedTransaction {
428
458
  group: PreparedDurableGroup;
429
459
  envelope: CommitEnvelope;
@@ -527,12 +557,205 @@ function request<T>(value: IDBRequest<T>): Promise<T> {
527
557
  void result.catch(() => {});
528
558
  return result;
529
559
  }
560
+ /** Every string key in the data store, which in chunked formats names a payload manifest. Keys
561
+ * order numbers, dates, strings, binary, arrays: the empty binary key is the least binary key, so
562
+ * values under invalid number, date or binary keys are never loaded. Layout validation still
563
+ * rejects those keys from the key listing. */
564
+ function manifestKeyRange(): IDBKeyRange {
565
+ return IDBKeyRange.bound("", new ArrayBuffer(0), false, true);
566
+ }
567
+ /** Pairs a bulk manifest read; each result is read once (see formatAndManifests). */
568
+ function pairManifests(
569
+ names: readonly IDBValidKey[],
570
+ records: readonly unknown[],
571
+ ): Map<IDBValidKey, unknown> {
572
+ if (names.length !== records.length)
573
+ throw new VfsError("INVALID_VFS_FORMAT", "indexeddb", "Invalid payload manifests");
574
+ const manifests = new Map<IDBValidKey, unknown>();
575
+ for (const [index, key] of names.entries()) manifests.set(key, records[index]);
576
+ return manifests;
577
+ }
578
+ interface FormatRecords {
579
+ readonly format: unknown;
580
+ /** Manifest records by payload key, read only for chunked formats. */
581
+ readonly manifests?: ReadonlyMap<IDBValidKey, unknown>;
582
+ }
583
+ /** Reads the format and, for chunked formats, every manifest in the same snapshot. Legacy
584
+ * formats keep whole payloads at string keys, so those are never read here. */
585
+ function formatAndManifests(
586
+ metadata: IDBObjectStore,
587
+ data: IDBObjectStore,
588
+ ): Promise<FormatRecords> {
589
+ return new Promise<FormatRecords>((resolve, reject) => {
590
+ const format = metadata.get("format");
591
+ format.onerror = requestFailed(format, reject);
592
+ format.onsuccess = () => {
593
+ if (format.result !== INDEXEDDB_FORMAT && format.result !== STAGED_FORMAT) {
594
+ resolve({ format: format.result });
595
+ return;
596
+ }
597
+ // Placed from the format's success callback, so they read the same snapshot.
598
+ placeManifestReads(data, format.result, resolve, reject);
599
+ };
600
+ });
601
+ }
602
+ function requestFailed(failure: IDBRequest, reject: (error: unknown) => void): () => void {
603
+ return () => reject(failure.error ?? new Error("IndexedDB request failed"));
604
+ }
605
+ /** Requests complete in order, so the keys are ready when the values arrive. */
606
+ function placeManifestReads(
607
+ data: IDBObjectStore,
608
+ format: unknown,
609
+ resolve: (records: FormatRecords) => void,
610
+ reject: (error: unknown) => void,
611
+ ): void {
612
+ const range = manifestKeyRange();
613
+ const keys = data.getAllKeys(range);
614
+ const values = data.getAll(range);
615
+ keys.onerror = requestFailed(keys, reject);
616
+ values.onerror = requestFailed(values, reject);
617
+ values.onsuccess = () => {
618
+ // Read each result once: WebKit builds a new array on every `result` access, which made an
619
+ // indexed loop over 17,000 manifests take 6.5 s.
620
+ try {
621
+ resolve({ format, manifests: pairManifests(keys.result, values.result) });
622
+ } catch (error) {
623
+ reject(error);
624
+ }
625
+ };
626
+ }
627
+ /**
628
+ * The epoch read of a readwrite transaction whose scope holds "metadata": whether the epoch
629
+ * matched, or `undefined` when the transaction ended before reading it. No connection can change
630
+ * the epoch while that transaction holds "metadata", so a match stays current until it ends.
631
+ */
632
+ type EpochWitness = Promise<boolean | undefined>;
633
+
634
+ /** Settles with `promise`, or rejects with the signal's reason once it aborts. */
635
+ function raceAbort<T>(promise: Promise<T>, signal?: AbortSignal): Promise<T> {
636
+ if (!signal) return promise;
637
+ signal.throwIfAborted();
638
+ return new Promise<T>((resolve, reject) => {
639
+ const onAbort = () => reject(signal.reason);
640
+ signal.addEventListener("abort", onAbort, { once: true });
641
+ promise.then(resolve, reject).finally(() => signal.removeEventListener("abort", onAbort));
642
+ });
643
+ }
644
+
530
645
  function completed(tx: IDBTransaction): Promise<void> {
531
646
  return new Promise((resolve, reject) => {
532
647
  tx.oncomplete = () => resolve();
533
648
  tx.onabort = () => reject(tx.error ?? new Error("IndexedDB transaction aborted"));
534
649
  });
535
650
  }
651
+ interface ChunkCheck {
652
+ readonly bytes: Uint8Array<ArrayBuffer>;
653
+ readonly checksum: string;
654
+ }
655
+ /** One range read in progress: bytes copied as chunks arrive and the checksums still owed. */
656
+ interface PayloadRead {
657
+ readonly key: string;
658
+ readonly range: IndexedDBRange;
659
+ /** The payload size the read expects, when the caller or the index knows it. */
660
+ readonly expectedSize: number | undefined;
661
+ manifest?: ChunkManifest;
662
+ result?: Uint8Array<ArrayBuffer>;
663
+ /** End of the clamped range, and the next chunk index to request. */
664
+ end: number;
665
+ next: number;
666
+ readonly checks: ChunkCheck[];
667
+ /** Chunk requests placed and not yet answered. */
668
+ pending: number;
669
+ failure?: { cause: unknown };
670
+ /** Called once the manifest and every chunk have arrived. */
671
+ arrived: () => void;
672
+ fail: (error: unknown) => void;
673
+ }
674
+ function corruption<T>(parse: () => T, fallback: string): T {
675
+ try {
676
+ return parse();
677
+ } catch (error) {
678
+ throw new PayloadCorruption(error instanceof Error ? error.message : fallback);
679
+ }
680
+ }
681
+ /** Chunk gets one read keeps in flight. Each answer places the next from its success callback,
682
+ * so a large read stays one transaction without queueing every chunk at once. */
683
+ const CHUNK_READ_WINDOW = 16;
684
+ /** Starts the gets for every chunk the range touches in a payload of `size` bytes. */
685
+ function placeChunkReads(store: IDBObjectStore, size: number, read: PayloadRead): void {
686
+ const range = read.range;
687
+ const length = Math.max(0, Math.min(range.length, size - range.offset));
688
+ read.result = new Uint8Array(length);
689
+ read.end = range.offset + length;
690
+ read.next = Math.floor(range.offset / CHUNK_SIZE);
691
+ // An empty range, or one past the end, takes no byte from any chunk.
692
+ if (length) placeMoreChunks(store, read);
693
+ }
694
+ function placeMoreChunks(store: IDBObjectStore, read: PayloadRead): void {
695
+ while (read.pending < CHUNK_READ_WINDOW && read.next * CHUNK_SIZE < read.end)
696
+ placeChunk(store, read, read.next++);
697
+ }
698
+ function placeChunk(store: IDBObjectStore, read: PayloadRead, index: number): void {
699
+ read.pending++;
700
+ const get = store.get([read.key, index]);
701
+ get.onsuccess = () => {
702
+ try {
703
+ copyChunk(get.result, index, read);
704
+ read.pending--;
705
+ placeMoreChunks(store, read);
706
+ if (read.pending === 0 && read.manifest) read.arrived();
707
+ } catch (error) {
708
+ read.fail(error);
709
+ }
710
+ };
711
+ }
712
+ /** Runs first among the read's requests, which complete in the order they were placed. */
713
+ function acceptManifest(store: IDBObjectStore, value: unknown, read: PayloadRead): void {
714
+ const key = read.key;
715
+ if (value === undefined) throw new Error(`Missing filesystem payload: ${key}`);
716
+ const manifest = corruption(() => parseManifest(value, key), "Invalid payload manifest");
717
+ if (read.expectedSize !== undefined && manifest.size !== read.expectedSize)
718
+ throw new PayloadCorruption("Retained payload size mismatch");
719
+ read.manifest = manifest;
720
+ // Without a known size, the chunk requests wait for the manifest, still in this transaction.
721
+ if (read.expectedSize === undefined) placeChunkReads(store, manifest.size, read);
722
+ if (read.pending === 0) read.arrived();
723
+ }
724
+ /** Copies the chunk's part of the range now and keeps what its checksum covers. A chunk the
725
+ * range covers whole is checked from the copy, so only the two edge chunks stay alive. */
726
+ function copyChunk(record: unknown, index: number, read: PayloadRead): void {
727
+ const offset = read.range.offset;
728
+ const length = chunkLength(read.manifest!, index);
729
+ const chunk = corruption(() => parseChunk(record, length, read.key), "Invalid payload chunk");
730
+ const base = index * CHUNK_SIZE;
731
+ const start = Math.max(offset, base);
732
+ const stop = Math.min(read.end, base + length);
733
+ const result = read.result!;
734
+ result.set(chunk.bytes.subarray(start - base, stop - base), start - offset);
735
+ const whole = start === base && stop === base + length;
736
+ read.checks.push({
737
+ checksum: chunk.checksum,
738
+ bytes: whole ? result.subarray(start - offset, stop - offset) : chunk.bytes,
739
+ });
740
+ }
741
+ /** Digests run concurrently in small batches: digest() copies its input, so a batch bounds the
742
+ * extra memory while the browser overlaps the work. `admit` runs before each batch, so a read
743
+ * that lost its owner or its caller starts no further checksum work. */
744
+ const CHECKSUM_BATCH = 16;
745
+ async function verifyChecksums(
746
+ key: string,
747
+ checks: readonly ChunkCheck[],
748
+ admit: () => void,
749
+ ): Promise<void> {
750
+ for (let start = 0; start < checks.length; start += CHECKSUM_BATCH) {
751
+ admit();
752
+ const batch = checks.slice(start, start + CHECKSUM_BATCH);
753
+ const digests = await Promise.all(batch.map((check) => chunkChecksum(check.bytes)));
754
+ if (digests.some((digest, index) => digest !== batch[index]!.checksum))
755
+ throw new PayloadCorruption(`Invalid filesystem payload chunks: ${key}`);
756
+ }
757
+ admit();
758
+ }
536
759
  function payloads(nodes: Iterable<PersistedNode>, keys: Set<string>): void {
537
760
  for (const node of nodes) if (node.data !== undefined) keys.add(node.data);
538
761
  }
@@ -546,6 +769,42 @@ function recoveryManifest(value: unknown, key: string): ChunkManifest | undefine
546
769
  return undefined;
547
770
  }
548
771
  }
772
+ /** Manifests whose chunk keys are exactly 0 to count - 1. `records` holds every manifest record
773
+ * read in the same snapshot as `keys`. */
774
+ function validateChunks(
775
+ keys: readonly IDBValidKey[],
776
+ records: ReadonlyMap<IDBValidKey, unknown>,
777
+ ): Map<string, ChunkManifest> {
778
+ const manifests = new Map<string, ChunkManifest>();
779
+ const chunks = new Map<string, Set<number>>();
780
+ for (const key of keys) {
781
+ if (typeof key === "string") {
782
+ const manifest = recoveryManifest(records.get(key), key);
783
+ if (manifest) manifests.set(key, manifest);
784
+ continue;
785
+ }
786
+ if (
787
+ !Array.isArray(key) ||
788
+ key.length !== 2 ||
789
+ typeof key[0] !== "string" ||
790
+ !validInteger(key[1])
791
+ )
792
+ chunkError(String(key));
793
+ const indices = chunks.get(key[0]) ?? new Set<number>();
794
+ indices.add(key[1]);
795
+ chunks.set(key[0], indices);
796
+ }
797
+ for (const [key, manifest] of manifests) {
798
+ const indices = chunks.get(key);
799
+ if ((indices?.size ?? 0) !== manifest.count) {
800
+ manifests.delete(key);
801
+ continue;
802
+ }
803
+ if (indices && Array.from(indices).some((index) => index >= manifest.count))
804
+ manifests.delete(key);
805
+ }
806
+ return manifests;
807
+ }
549
808
  function referenceIndex(nodes: Iterable<PersistedNode>): Pick<State, "references" | "parents"> {
550
809
  const references = new Map<number, number>(),
551
810
  parents = new Map<number, number>();
@@ -729,6 +988,29 @@ function applyChanges(
729
988
  state.publication = selection.publication;
730
989
  }
731
990
 
991
+ /** Moves payload sizes from the nodes a commit replaces or removes to the ones it writes. */
992
+ function replaceNodes(state: State, staged: StagedChanges): void {
993
+ for (const ino of Array.from(staged.removes).concat(Array.from(staged.upserts.keys()))) {
994
+ const previous = state.nodes.get(ino);
995
+ if (previous) state.payloadSizes.remove([previous]);
996
+ }
997
+ state.payloadSizes.add(staged.upserts.values());
998
+ }
999
+ function installBases(state: State, bases: State["bases"]): void {
1000
+ for (const slot of [0, 1] as const) {
1001
+ if (state.bases[slot] === bases[slot]) continue;
1002
+ state.payloadSizes.remove(state.bases[slot]?.nodes ?? []);
1003
+ state.payloadSizes.add(bases[slot]?.nodes ?? []);
1004
+ }
1005
+ state.bases = bases;
1006
+ }
1007
+ function dropJournal(state: State, generation: number): void {
1008
+ const journal = state.journals.get(generation);
1009
+ if (!journal) return;
1010
+ state.journals.delete(generation);
1011
+ state.payloadSizes.remove(journal.upserts);
1012
+ }
1013
+
732
1014
  /** Recover newest-first, copying the full tree only for a candidate with a complete chain. */
733
1015
  export function recoverIndex(
734
1016
  bases: readonly (PersistedIndex | undefined)[],
@@ -785,6 +1067,8 @@ export class IndexedDBStorage implements StorageBackend {
785
1067
  private tail: Promise<void> = Promise.resolve();
786
1068
  private readonly readers = new PayloadRetentions();
787
1069
  private readonly readerWork = new Set<Promise<unknown>>();
1070
+ /** Read transactions whose bytes may already be returned but which have not settled. */
1071
+ private readonly nativeReads = new Set<Promise<void>>();
788
1072
  private readonly deletingPayloads = new Set<string>();
789
1073
  private persistenceError: unknown;
790
1074
  private initialized = false;
@@ -794,6 +1078,8 @@ export class IndexedDBStorage implements StorageBackend {
794
1078
  private ownershipError?: Error;
795
1079
  private ownershipRetirement?: Promise<void>;
796
1080
  private transactions = new Set<IDBTransaction>();
1081
+ /** Epoch reads of this connection's open readwrite transactions; see verifyEpoch. */
1082
+ private readonly epochWitnesses = new Set<EpochWitness>();
797
1083
  private committedEnvelope: CommitEnvelope | undefined;
798
1084
  private committedRecord: ChecksummedRecord | undefined;
799
1085
  private committedPending = false;
@@ -824,10 +1110,47 @@ export class IndexedDBStorage implements StorageBackend {
824
1110
  return this.initialLastExclusiveEpoch;
825
1111
  }
826
1112
 
827
- /** Readonly IndexedDB check verifying this connection still owns the latest epoch. */
1113
+ /**
1114
+ * Verifies this connection still owns the latest epoch. While one of its own readwrite
1115
+ * transactions holds "metadata", that transaction's epoch read answers: a readonly transaction
1116
+ * would only queue behind it, and a large checkpoint commit can hold it for seconds.
1117
+ *
1118
+ * A witness leaves the set in its transaction's complete or abort event, a task after the
1119
+ * transaction released "metadata". That gap does not weaken the answer for the multitab lease:
1120
+ * only a connection that took the storage Web Lock writes a new epoch, and the lease renewal
1121
+ * confirms this connection still holds that lock before it asks here.
1122
+ */
828
1123
  async verifyEpoch(signal?: AbortSignal): Promise<boolean> {
829
1124
  if (this.closed || this.ownershipError) return false;
830
1125
  signal?.throwIfAborted();
1126
+ const witnessed = await this.witnessedEpoch(signal);
1127
+ if (witnessed !== undefined) return witnessed && !this.closed && !this.ownershipError;
1128
+ return this.readEpoch(signal);
1129
+ }
1130
+
1131
+ private async witnessedEpoch(signal?: AbortSignal): Promise<boolean | undefined> {
1132
+ for (const witness of Array.from(this.epochWitnesses)) {
1133
+ const result = await raceAbort(witness, signal);
1134
+ if (result !== undefined) return result;
1135
+ }
1136
+ return undefined;
1137
+ }
1138
+
1139
+ /** Records the epoch read of a readwrite transaction holding "metadata" until it ends. */
1140
+ private witnessEpoch(tx: IDBTransaction, read: IDBRequest): void {
1141
+ const { promise: witness, resolve } = Promise.withResolvers<boolean | undefined>();
1142
+ const end = () => {
1143
+ this.epochWitnesses.delete(witness);
1144
+ resolve(undefined);
1145
+ };
1146
+ read.addEventListener("success", () => resolve(read.result === this.epoch));
1147
+ read.addEventListener("error", () => resolve(undefined));
1148
+ tx.addEventListener("complete", end);
1149
+ tx.addEventListener("abort", end);
1150
+ this.epochWitnesses.add(witness);
1151
+ }
1152
+
1153
+ private async readEpoch(signal?: AbortSignal): Promise<boolean> {
831
1154
  let tx: IDBTransaction | undefined;
832
1155
  const onAbort = () => {
833
1156
  try {
@@ -1149,9 +1472,9 @@ export class IndexedDBStorage implements StorageBackend {
1149
1472
  } catch {}
1150
1473
  }
1151
1474
  this.db.close();
1152
- this.ownershipRetirement = Promise.allSettled(
1153
- Array.from(this.readerWork).concat([this.tail]),
1154
- ).then(() => this.retireMaintenance());
1475
+ this.ownershipRetirement = Promise.allSettled(Array.from(this.readerWork).concat([this.tail]))
1476
+ .then(() => this.joinNativeReads())
1477
+ .then(() => this.retireMaintenance());
1155
1478
  void this.ownershipRetirement.catch(() => {});
1156
1479
  this.onOwnershipLost?.();
1157
1480
  return error;
@@ -1225,10 +1548,16 @@ export class IndexedDBStorage implements StorageBackend {
1225
1548
  const value = await this.readRecord(key, signal);
1226
1549
  if (!(value instanceof Uint8Array)) chunkError(key);
1227
1550
  if (value.length !== this.payloadSize(key)) chunkError(key);
1551
+ // readRecord awaits its transaction again after its own check.
1552
+ signal?.throwIfAborted();
1553
+ this.assertOwner();
1228
1554
  return value;
1229
1555
  }
1230
- const manifest = await this.manifest(key, signal);
1231
- return this.readChunks(key, manifest, { offset: 0, length: manifest.size, signal });
1556
+ return this.readPayload(
1557
+ key,
1558
+ { offset: 0, length: Number.MAX_SAFE_INTEGER, signal },
1559
+ this.knownSize(key),
1560
+ );
1232
1561
  });
1233
1562
  }
1234
1563
 
@@ -1251,27 +1580,22 @@ export class IndexedDBStorage implements StorageBackend {
1251
1580
  throw new Error("Missing retained filesystem payload");
1252
1581
  }
1253
1582
  private payloadSize(key: string): number | undefined {
1254
- const retained = this.readers.size(key);
1255
- if (retained !== undefined) return retained;
1256
- for (const node of this.state!.nodes.values()) if (node.data === key) return node.size;
1257
- for (const base of this.state!.bases) {
1258
- for (const node of base?.nodes ?? []) if (node.data === key) return node.size;
1259
- }
1260
- for (const journal of this.state!.journals.values()) {
1261
- for (const node of journal.upserts) if (node.data === key) return node.size;
1262
- }
1263
- return undefined;
1583
+ return this.readers.size(key) ?? this.state!.payloadSizes.size(key);
1584
+ }
1585
+ /** The size a read can expect before its manifest arrives, when anything names the payload. */
1586
+ private knownSize(key: string): number | undefined {
1587
+ return this.readers.size(key) ?? this.state?.payloadSizes.size(key);
1264
1588
  }
1265
1589
  resources(): Record<string, number> {
1266
1590
  return { ...this.readers.resources(), indexeddbReaderWork: this.readerWork.size };
1267
1591
  }
1268
1592
  private retainedRange(key: string, range: IndexedDBRange): Promise<Uint8Array> {
1269
1593
  if (this.closed) return Promise.reject(new Error("Filesystem storage is closed"));
1270
- const work = this.manifest(key, range.signal).then((manifest) => {
1271
- if (manifest.size !== this.readers.size(key))
1272
- throw new PayloadCorruption("Retained payload size mismatch");
1273
- return this.readChunks(key, manifest, range);
1274
- });
1594
+ const size = this.readers.size(key);
1595
+ const work =
1596
+ size === undefined
1597
+ ? Promise.reject(new PayloadCorruption("Retained payload size mismatch"))
1598
+ : this.readPayload(key, range, size);
1275
1599
  this.readerWork.add(work);
1276
1600
  void work.then(
1277
1601
  () => this.readerWork.delete(work),
@@ -1290,8 +1614,7 @@ export class IndexedDBStorage implements StorageBackend {
1290
1614
  return this.enqueue(async () => {
1291
1615
  range.signal?.throwIfAborted();
1292
1616
  await this.initialize(range.signal);
1293
- const manifest = await this.manifest(key, range.signal);
1294
- return this.readChunks(key, manifest, range);
1617
+ return this.readPayload(key, range, this.knownSize(key));
1295
1618
  }).catch((error: unknown) => {
1296
1619
  range.signal?.throwIfAborted();
1297
1620
  throw error;
@@ -1326,52 +1649,87 @@ export class IndexedDBStorage implements StorageBackend {
1326
1649
  }
1327
1650
  }
1328
1651
 
1329
- private async manifest(key: string, signal?: AbortSignal): Promise<ChunkManifest> {
1330
- const value = await this.readRecord(key, signal);
1331
- if (value === undefined) throw new Error(`Missing filesystem payload: ${key}`);
1332
- try {
1333
- return parseManifest(value, key);
1334
- } catch (error) {
1335
- throw new PayloadCorruption(
1336
- error instanceof Error ? error.message : "Invalid payload manifest",
1337
- );
1338
- }
1339
- }
1340
-
1341
- private async readChunks(
1652
+ /** One readonly transaction for the manifest and every chunk the range touches. With a known
1653
+ * size (`expectedSize`) all requests go out together, so the read costs one round trip; the
1654
+ * manifest must then match that size. The bytes are returned once every request has answered,
1655
+ * without waiting for the transaction's commit, and only after every checksum is verified. */
1656
+ private async readPayload(
1342
1657
  key: string,
1343
- manifest: ChunkManifest,
1344
1658
  range: IndexedDBRange,
1659
+ expectedSize: number | undefined,
1345
1660
  ): Promise<Uint8Array> {
1346
- const length = Math.max(0, Math.min(range.length, manifest.size - range.offset));
1347
- const result = new Uint8Array(length);
1348
- range.signal?.throwIfAborted();
1349
- if (!length) return result;
1350
- const end = range.offset + length;
1351
- for (let index = Math.floor(range.offset / CHUNK_SIZE); index * CHUNK_SIZE < end; index++) {
1352
- const record = await this.readRecord([key, index], range.signal);
1353
- const chunk = this.validChunk(record, chunkLength(manifest, index), key);
1354
- if ((await chunkChecksum(chunk.bytes)) !== chunk.checksum)
1355
- throw new PayloadCorruption(`Invalid filesystem payload chunks: ${key}`);
1356
- range.signal?.throwIfAborted();
1357
- this.assertOwner();
1358
- const start = Math.max(range.offset, index * CHUNK_SIZE);
1359
- const stop = Math.min(end, (index + 1) * CHUNK_SIZE);
1360
- result.set(
1361
- chunk.bytes.subarray(start - index * CHUNK_SIZE, stop - index * CHUNK_SIZE),
1362
- start - range.offset,
1363
- );
1364
- }
1365
- range.signal?.throwIfAborted();
1366
- return result;
1367
- }
1368
-
1369
- private validChunk(record: unknown, length: number, key: string) {
1661
+ const signal = range.signal;
1662
+ signal?.throwIfAborted();
1663
+ this.assertOwner();
1664
+ const tx = this.db.transaction("data", "readonly");
1665
+ this.transactions.add(tx);
1666
+ const abort = () => {
1667
+ try {
1668
+ tx.abort();
1669
+ } catch {}
1670
+ };
1671
+ signal?.addEventListener("abort", abort, { once: true });
1672
+ const settled = completed(tx);
1673
+ // The bytes may be returned before the native transaction settles. Ownership loss aborts it
1674
+ // and close and ownership retirement join it until then.
1675
+ const native: Promise<void> = settled.then(
1676
+ (): void => this.nativeSettled(tx, native),
1677
+ (): void => this.nativeSettled(tx, native),
1678
+ );
1679
+ this.nativeReads.add(native);
1680
+ const arrival = Promise.withResolvers<void>();
1681
+ const read: PayloadRead = {
1682
+ key,
1683
+ range,
1684
+ expectedSize,
1685
+ end: 0,
1686
+ next: 0,
1687
+ checks: [],
1688
+ pending: 0,
1689
+ arrived: arrival.resolve,
1690
+ fail: (error) => {
1691
+ read.failure ??= { cause: error };
1692
+ abort();
1693
+ },
1694
+ };
1370
1695
  try {
1371
- return parseChunk(record, length, key);
1696
+ // Setup can throw synchronously; the catch then aborts the transaction it opened.
1697
+ this.placePayloadReads(tx, read);
1698
+ await Promise.race([arrival.promise, settled.then(() => arrival.promise)]);
1372
1699
  } catch (error) {
1373
- throw new PayloadCorruption(error instanceof Error ? error.message : "Invalid payload chunk");
1700
+ abort();
1701
+ throw signal?.aborted ? signal.reason : (this.ownershipError ?? read.failure?.cause ?? error);
1702
+ } finally {
1703
+ signal?.removeEventListener("abort", abort);
1374
1704
  }
1705
+ const admit = () => {
1706
+ signal?.throwIfAborted();
1707
+ this.assertOwner();
1708
+ };
1709
+ await verifyChecksums(key, read.checks, admit);
1710
+ // Revocation can land while the verifier's result is delivered: check once more with no
1711
+ // await between this check and handing out the bytes.
1712
+ admit();
1713
+ return read.result!;
1714
+ }
1715
+ private placePayloadReads(tx: IDBTransaction, read: PayloadRead): void {
1716
+ const store = tx.objectStore("data");
1717
+ const manifest = store.get(read.key);
1718
+ manifest.onsuccess = () => {
1719
+ try {
1720
+ acceptManifest(store, manifest.result, read);
1721
+ } catch (error) {
1722
+ read.fail(error);
1723
+ }
1724
+ };
1725
+ if (read.expectedSize !== undefined) placeChunkReads(store, read.expectedSize, read);
1726
+ }
1727
+ private joinNativeReads(): Promise<unknown> {
1728
+ return Promise.all(Array.from(this.nativeReads));
1729
+ }
1730
+ private nativeSettled(tx: IDBTransaction, native: Promise<void>): void {
1731
+ this.transactions.delete(tx);
1732
+ this.nativeReads.delete(native);
1375
1733
  }
1376
1734
 
1377
1735
  recoverCommitted(): Promise<CommittedRecovery> {
@@ -1486,6 +1844,8 @@ export class IndexedDBStorage implements StorageBackend {
1486
1844
  if (!this.closing) {
1487
1845
  this.closed = true;
1488
1846
  this.closing = Promise.all(Array.from(this.readerWork).concat([this.tail])).then(async () => {
1847
+ // Admitted work has finished; reads it started may still be settling natively.
1848
+ await this.joinNativeReads();
1489
1849
  this.db.close();
1490
1850
  if (this.readOnly) {
1491
1851
  this.state = undefined;
@@ -1522,7 +1882,8 @@ export class IndexedDBStorage implements StorageBackend {
1522
1882
  void settled.catch(() => {});
1523
1883
  signal?.addEventListener("abort", abort, { once: true });
1524
1884
  const metadata = tx.objectStore("metadata"),
1525
- journal = tx.objectStore("journal");
1885
+ journal = tx.objectStore("journal"),
1886
+ data = tx.objectStore("data");
1526
1887
  try {
1527
1888
  const records = await Promise.all([
1528
1889
  request(metadata.get(0)),
@@ -1530,8 +1891,8 @@ export class IndexedDBStorage implements StorageBackend {
1530
1891
  request(metadata.getAllKeys()),
1531
1892
  request(journal.getAll()),
1532
1893
  request(journal.getAllKeys()),
1533
- request(tx.objectStore("data").getAllKeys()),
1534
- request(metadata.get("format")),
1894
+ request(data.getAllKeys()),
1895
+ formatAndManifests(metadata, data),
1535
1896
  request(metadata.get("commit")),
1536
1897
  request(metadata.get("active")),
1537
1898
  settled,
@@ -1558,7 +1919,7 @@ export class IndexedDBStorage implements StorageBackend {
1558
1919
  journalValues,
1559
1920
  journalKeys,
1560
1921
  dataKeys,
1561
- format,
1922
+ { format, manifests },
1562
1923
  storedCommit,
1563
1924
  active,
1564
1925
  ] = await this.indexRecords(signal);
@@ -1574,10 +1935,7 @@ export class IndexedDBStorage implements StorageBackend {
1574
1935
  if (typeof key === "string") payloadKeys.add(key);
1575
1936
  else if (Array.isArray(key) && typeof key[0] === "string") payloadKeys.add(key[0]);
1576
1937
  }
1577
- const physical =
1578
- format === INDEXEDDB_FORMAT || format === STAGED_FORMAT
1579
- ? await this.validateChunks(dataKeys, signal)
1580
- : undefined;
1938
+ const physical = manifests && validateChunks(dataKeys, manifests);
1581
1939
  const available = physical ? new Set(physical.keys()) : payloadKeys;
1582
1940
  const decoded = await Promise.all([decodeIndex(first), decodeIndex(second)]);
1583
1941
  signal?.throwIfAborted();
@@ -1626,6 +1984,10 @@ export class IndexedDBStorage implements StorageBackend {
1626
1984
  }
1627
1985
  if (newest) {
1628
1986
  const nodes = new Map(newest.nodes.map((node) => [node.ino, node]));
1987
+ const payloadSizes = new PayloadSizes();
1988
+ payloadSizes.add(nodes.values());
1989
+ for (const base of bases) if (base) payloadSizes.add(base.nodes);
1990
+ for (const journal of journals.values()) payloadSizes.add(journal.upserts);
1629
1991
  const lastBase = Math.max(
1630
1992
  ...bases.filter((base): base is PersistedIndex => !!base).map((base) => base.generation),
1631
1993
  );
@@ -1639,6 +2001,7 @@ export class IndexedDBStorage implements StorageBackend {
1639
2001
  journals,
1640
2002
  journalKeys,
1641
2003
  payloadKeys,
2004
+ payloadSizes,
1642
2005
  sinceCompaction: Array.from(journals.values()).filter(
1643
2006
  (entry) => entry.generation > lastBase,
1644
2007
  ).length,
@@ -1695,11 +2058,14 @@ export class IndexedDBStorage implements StorageBackend {
1695
2058
  }
1696
2059
 
1697
2060
  private recordRecovery(state: State, extra?: readonly string[]): void {
1698
- const retained = new Set<string>(extra);
1699
- payloads(state.nodes.values(), retained);
1700
- for (const base of state.bases) if (base) payloads(base.nodes, retained);
1701
- for (const journal of state.journals.values()) payloads(journal.upserts, retained);
1702
- this.readers.recovery(retained);
2061
+ if (!extra?.length) {
2062
+ this.readers.recovery(state.payloadSizes);
2063
+ return;
2064
+ }
2065
+ const extraRoots = new Set(extra);
2066
+ this.readers.recovery({
2067
+ has: (key) => extraRoots.has(key) || state.payloadSizes.has(key),
2068
+ });
1703
2069
  }
1704
2070
 
1705
2071
  private matchSizes(
@@ -1712,42 +2078,6 @@ export class IndexedDBStorage implements StorageBackend {
1712
2078
  );
1713
2079
  }
1714
2080
 
1715
- private async validateChunks(
1716
- keys: IDBValidKey[],
1717
- signal?: AbortSignal,
1718
- ): Promise<Map<string, ChunkManifest>> {
1719
- const manifests = new Map<string, ChunkManifest>();
1720
- const chunks = new Map<string, Set<number>>();
1721
- for (const key of keys) {
1722
- signal?.throwIfAborted();
1723
- if (typeof key === "string") {
1724
- const manifest = recoveryManifest(await this.readRecord(key, signal), key);
1725
- if (manifest) manifests.set(key, manifest);
1726
- continue;
1727
- }
1728
- if (
1729
- !Array.isArray(key) ||
1730
- key.length !== 2 ||
1731
- typeof key[0] !== "string" ||
1732
- !validInteger(key[1])
1733
- )
1734
- chunkError(String(key));
1735
- const indices = chunks.get(key[0]) ?? new Set<number>();
1736
- indices.add(key[1]);
1737
- chunks.set(key[0], indices);
1738
- }
1739
- for (const [key, manifest] of manifests) {
1740
- const indices = chunks.get(key);
1741
- if ((indices?.size ?? 0) !== manifest.count) {
1742
- manifests.delete(key);
1743
- continue;
1744
- }
1745
- if (indices && Array.from(indices).some((index) => index >= manifest.count))
1746
- manifests.delete(key);
1747
- }
1748
- return manifests;
1749
- }
1750
-
1751
2081
  private async fencedWrite(
1752
2082
  work: (data: IDBObjectStore, metadata: IDBObjectStore) => void,
1753
2083
  signal?: AbortSignal,
@@ -1766,6 +2096,7 @@ export class IndexedDBStorage implements StorageBackend {
1766
2096
  const done = completed(tx);
1767
2097
  const metadata = tx.objectStore("metadata");
1768
2098
  const epoch = metadata.get("epoch");
2099
+ this.witnessEpoch(tx, epoch);
1769
2100
  epoch.onsuccess = () => {
1770
2101
  try {
1771
2102
  if (epoch.result !== this.epoch) throw this.loseOwnership();
@@ -1827,7 +2158,12 @@ export class IndexedDBStorage implements StorageBackend {
1827
2158
  private async commit(batch: PersistenceBatch, committed?: CommittedTransaction): Promise<void> {
1828
2159
  if (this.committedMode !== !!committed)
1829
2160
  throw new Error("Committed storage requires a complete durable group");
1830
- const prepared = await preparePayloads(batch.data);
2161
+ const checkActive = () => {
2162
+ committed?.control.checkAbort();
2163
+ this.assertOwner();
2164
+ };
2165
+ const prepared = await preparePayloads(batch.data, true, checkActive);
2166
+ checkActive();
1831
2167
  const staged = stageChanges(this.state, batch),
1832
2168
  old = this.state;
1833
2169
  // A recovered generation may be reused. Its abandoned successors must not reconnect
@@ -1937,22 +2273,39 @@ export class IndexedDBStorage implements StorageBackend {
1937
2273
  abort(error);
1938
2274
  }
1939
2275
  };
1940
- let remaining = checking.size + pinChecks.size + (committed ? 2 : 0);
2276
+ const newKeys: string[] = [];
2277
+ const verifyKeys: string[] = [];
2278
+ for (const key of checking) {
2279
+ if (prepared.has(key) && !old?.payloadKeys.has(key)) newKeys.push(key);
2280
+ else verifyKeys.push(key);
2281
+ }
2282
+ let remaining = 1 + verifyKeys.length + pinChecks.size + (committed ? 1 : 0);
1941
2283
  const checked = () => {
1942
2284
  if (--remaining === 0) finish();
1943
2285
  };
1944
2286
  const checkEpoch = tx.objectStore("metadata").get("epoch");
2287
+ this.witnessEpoch(tx, checkEpoch);
1945
2288
  checkEpoch.onsuccess = () => {
1946
2289
  if (checkEpoch.result !== this.epoch) {
1947
2290
  abort(this.loseOwnership());
1948
2291
  return;
1949
2292
  }
1950
- if (committed) checked();
2293
+ try {
2294
+ for (const key of newKeys) {
2295
+ const supplied = prepared.get(key)!;
2296
+ const size = expected.get(key);
2297
+ if (size !== undefined && supplied.manifest.size !== size)
2298
+ throw new Error(`Invalid filesystem payload size: ${key}`);
2299
+ putPayload(data, key, supplied);
2300
+ }
2301
+ checked();
2302
+ } catch (error) {
2303
+ abort(error);
2304
+ }
1951
2305
  };
1952
2306
  if (committed) checkCommitHead(tx, committed, checked, abort);
1953
2307
  try {
1954
- if (!remaining) finish();
1955
- for (const key of checking) {
2308
+ for (const key of verifyKeys) {
1956
2309
  const get = data.get(key);
1957
2310
  get.onsuccess = () => {
1958
2311
  try {
@@ -1988,23 +2341,26 @@ export class IndexedDBStorage implements StorageBackend {
1988
2341
  nodes: new Map(),
1989
2342
  references: new Map(),
1990
2343
  parents: new Map(),
1991
- bases,
2344
+ bases: [undefined, undefined],
1992
2345
  journals: new Map(),
1993
2346
  journalKeys: [],
1994
2347
  payloadKeys: new Set(),
2348
+ payloadSizes: new PayloadSizes(),
1995
2349
  sinceCompaction: 0,
1996
2350
  };
1997
- for (const key of discarded) if (typeof key === "number") state.journals.delete(key);
2351
+ for (const key of discarded) if (typeof key === "number") dropJournal(state, key);
1998
2352
  state.journalKeys = state.journalKeys.filter((key) => !discarded.has(key));
2353
+ replaceNodes(state, staged);
1999
2354
  applyChanges(state, staged, batch);
2000
- state.bases = bases;
2355
+ installBases(state, bases);
2001
2356
  if (entry) {
2002
2357
  state.journals.set(entry.generation, entry);
2003
2358
  state.journalKeys.push(entry.generation);
2359
+ state.payloadSizes.add(entry.upserts);
2004
2360
  }
2005
2361
  for (const key of batch.data.keys()) state.payloadKeys.add(key);
2006
2362
  if (compact) {
2007
- for (const key of state.journals.keys()) if (key <= cutoff) state.journals.delete(key);
2363
+ for (const key of state.journals.keys()) if (key <= cutoff) dropJournal(state, key);
2008
2364
  state.journalKeys = state.journalKeys.filter(
2009
2365
  (key) => typeof key !== "number" || key > cutoff,
2010
2366
  );