@waffle-os/runtime 0.0.153 → 0.0.154

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 (48) 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 +4 -0
  9. package/core/wasi.ts +49 -0
  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 +40 -0
  17. package/dist/fs/backend.js +7 -0
  18. package/dist/fs/client.js +69 -15
  19. package/dist/fs/dirty-admission.js +15 -8
  20. package/dist/fs/indexeddb.js +288 -96
  21. package/dist/fs/memory.js +106 -20
  22. package/dist/fs/multitab-backend.js +121 -37
  23. package/dist/fs/multitab-protocol.js +1 -0
  24. package/dist/fs/persistent.js +70 -16
  25. package/dist/fs/protocol.js +15 -7
  26. package/dist/fs/publication-attachment.js +9 -7
  27. package/dist/fs/service.js +34 -9
  28. package/dist/fs/shared.js +96 -6
  29. package/dist/proc/command-stdio.js +1 -1
  30. package/dist/tooling/program/program-transformer.json +1 -1
  31. package/fs/backend.ts +11 -0
  32. package/fs/client.ts +93 -16
  33. package/fs/dirty-admission.ts +22 -7
  34. package/fs/guest-watch.ts +1 -1
  35. package/fs/indexeddb.ts +379 -110
  36. package/fs/memory.ts +120 -19
  37. package/fs/multitab-backend.ts +206 -61
  38. package/fs/multitab-protocol.ts +1 -0
  39. package/fs/persistent.ts +82 -16
  40. package/fs/protocol.ts +26 -7
  41. package/fs/publication-attachment.ts +9 -7
  42. package/fs/service.ts +35 -7
  43. package/fs/shared.ts +106 -8
  44. package/package.json +1 -1
  45. package/proc/command-stdio.ts +1 -1
  46. package/testing/idle-workspace-cancellation-browser.ts +22 -13
  47. package/testing/indexeddb-storage-browser.ts +435 -1
  48. package/tooling/program/program-transformer.json +1 -1
@@ -127,15 +127,22 @@ export class DirtyAdmission {
127
127
  get revision() {
128
128
  return this.values[REVISION];
129
129
  }
130
- clean(revision, namespace) {
131
- if (!this.enabled || this.revision !== revision)
132
- return false;
133
- this.values[DIRTY_BYTES] = 0;
134
- this.values[DIRTY_METADATA] = 0;
130
+ releaseSlot(bytes, metadata) {
131
+ if (!this.enabled || !bytes && !metadata)
132
+ return;
133
+ this.values[DIRTY_BYTES] = Math.max(0, this.values[DIRTY_BYTES] - bytes);
134
+ this.values[DIRTY_METADATA] = Math.max(0, this.values[DIRTY_METADATA] - metadata);
135
+ this.values[REVISION]++;
136
+ this.notify();
137
+ }
138
+ reconcile(namespace, dirtyNamespace, dirtyBytes, dirtyMetadata) {
139
+ if (!this.enabled)
140
+ return;
141
+ this.values[DIRTY_BYTES] = dirtyBytes;
142
+ this.values[DIRTY_METADATA] = dirtyMetadata;
135
143
  this.values[NAMESPACE] = namespace;
136
- this.values[BASE_NAMESPACE] = namespace;
144
+ this.values[BASE_NAMESPACE] = namespace - dirtyNamespace;
137
145
  this.notify();
138
- return true;
139
146
  }
140
147
  notify() {
141
148
  Atomics.add(this.signals, 0, 1);
@@ -162,7 +169,7 @@ export class DirtyAdmission {
162
169
  }
163
170
  }
164
171
  get hasDebt() {
165
- return this.values[DIRTY_BYTES] > 0 || this.values[DIRTY_METADATA] > 0;
172
+ return this.values[DIRTY_BYTES] > 0 || this.values[DIRTY_METADATA] > 0 || this.values[NAMESPACE] > this.values[BASE_NAMESPACE];
166
173
  }
167
174
  capacityReleased() {
168
175
  if (this.enabled)
@@ -321,6 +321,33 @@ export async function readIndexedDBEpochMetadata(name, options = {}) {
321
321
  } catch {}
322
322
  }
323
323
  }
324
+
325
+ class PayloadSizes {
326
+ entries = new Map;
327
+ add(nodes) {
328
+ for (const node of nodes) {
329
+ if (node.data === undefined)
330
+ continue;
331
+ const entry = this.entries.get(node.data);
332
+ if (entry)
333
+ entry.count++;
334
+ else
335
+ this.entries.set(node.data, { size: node.size, count: 1 });
336
+ }
337
+ }
338
+ remove(nodes) {
339
+ for (const node of nodes) {
340
+ if (node.data === undefined)
341
+ continue;
342
+ const entry = this.entries.get(node.data);
343
+ if (entry && --entry.count === 0)
344
+ this.entries.delete(node.data);
345
+ }
346
+ }
347
+ size(key) {
348
+ return this.entries.get(key)?.size;
349
+ }
350
+ }
324
351
  function validateDatabaseLayout(committed, format, keys, journalKeys, dataKeys) {
325
352
  const empty = committed && !keys.includes("format") && keys.every((key) => key === "epoch" || key === "lastExclusiveEpoch") && !journalKeys.length && !dataKeys.length;
326
353
  if (committed && !empty && format !== STAGED_FORMAT)
@@ -386,12 +413,128 @@ function request(value) {
386
413
  result.catch(() => {});
387
414
  return result;
388
415
  }
416
+ function manifestKeyRange() {
417
+ return IDBKeyRange.bound("", new ArrayBuffer(0), false, true);
418
+ }
419
+ function pairManifests(names, records) {
420
+ if (names.length !== records.length)
421
+ throw new VfsError("INVALID_VFS_FORMAT", "indexeddb", "Invalid payload manifests");
422
+ const manifests = new Map;
423
+ for (const [index, key] of names.entries())
424
+ manifests.set(key, records[index]);
425
+ return manifests;
426
+ }
427
+ function formatAndManifests(metadata, data) {
428
+ return new Promise((resolve, reject) => {
429
+ const format = metadata.get("format");
430
+ format.onerror = requestFailed(format, reject);
431
+ format.onsuccess = () => {
432
+ if (format.result !== INDEXEDDB_FORMAT && format.result !== STAGED_FORMAT) {
433
+ resolve({ format: format.result });
434
+ return;
435
+ }
436
+ placeManifestReads(data, format.result, resolve, reject);
437
+ };
438
+ });
439
+ }
440
+ function requestFailed(failure, reject) {
441
+ return () => reject(failure.error ?? new Error("IndexedDB request failed"));
442
+ }
443
+ function placeManifestReads(data, format, resolve, reject) {
444
+ const range = manifestKeyRange();
445
+ const keys = data.getAllKeys(range);
446
+ const values = data.getAll(range);
447
+ keys.onerror = requestFailed(keys, reject);
448
+ values.onerror = requestFailed(values, reject);
449
+ values.onsuccess = () => {
450
+ try {
451
+ resolve({ format, manifests: pairManifests(keys.result, values.result) });
452
+ } catch (error) {
453
+ reject(error);
454
+ }
455
+ };
456
+ }
389
457
  function completed(tx) {
390
458
  return new Promise((resolve, reject) => {
391
459
  tx.oncomplete = () => resolve();
392
460
  tx.onabort = () => reject(tx.error ?? new Error("IndexedDB transaction aborted"));
393
461
  });
394
462
  }
463
+ function corruption(parse, fallback) {
464
+ try {
465
+ return parse();
466
+ } catch (error) {
467
+ throw new PayloadCorruption(error instanceof Error ? error.message : fallback);
468
+ }
469
+ }
470
+ const CHUNK_READ_WINDOW = 16;
471
+ function placeChunkReads(store, size, read) {
472
+ const range = read.range;
473
+ const length = Math.max(0, Math.min(range.length, size - range.offset));
474
+ read.result = new Uint8Array(length);
475
+ read.end = range.offset + length;
476
+ read.next = Math.floor(range.offset / CHUNK_SIZE);
477
+ if (length)
478
+ placeMoreChunks(store, read);
479
+ }
480
+ function placeMoreChunks(store, read) {
481
+ while (read.pending < CHUNK_READ_WINDOW && read.next * CHUNK_SIZE < read.end)
482
+ placeChunk(store, read, read.next++);
483
+ }
484
+ function placeChunk(store, read, index) {
485
+ read.pending++;
486
+ const get = store.get([read.key, index]);
487
+ get.onsuccess = () => {
488
+ try {
489
+ copyChunk(get.result, index, read);
490
+ read.pending--;
491
+ placeMoreChunks(store, read);
492
+ if (read.pending === 0 && read.manifest)
493
+ read.arrived();
494
+ } catch (error) {
495
+ read.fail(error);
496
+ }
497
+ };
498
+ }
499
+ function acceptManifest(store, value, read) {
500
+ const key = read.key;
501
+ if (value === undefined)
502
+ throw new Error(`Missing filesystem payload: ${key}`);
503
+ const manifest = corruption(() => parseManifest(value, key), "Invalid payload manifest");
504
+ if (read.expectedSize !== undefined && manifest.size !== read.expectedSize)
505
+ throw new PayloadCorruption("Retained payload size mismatch");
506
+ read.manifest = manifest;
507
+ if (read.expectedSize === undefined)
508
+ placeChunkReads(store, manifest.size, read);
509
+ if (read.pending === 0)
510
+ read.arrived();
511
+ }
512
+ function copyChunk(record, index, read) {
513
+ const offset = read.range.offset;
514
+ const length = chunkLength(read.manifest, index);
515
+ const chunk = corruption(() => parseChunk(record, length, read.key), "Invalid payload chunk");
516
+ const base = index * CHUNK_SIZE;
517
+ const start = Math.max(offset, base);
518
+ const stop = Math.min(read.end, base + length);
519
+ const result = read.result;
520
+ result.set(chunk.bytes.subarray(start - base, stop - base), start - offset);
521
+ const whole = start === base && stop === base + length;
522
+ read.checks.push({
523
+ checksum: chunk.checksum,
524
+ bytes: whole ? result.subarray(start - offset, stop - offset) : chunk.bytes
525
+ });
526
+ }
527
+ const CHECKSUM_BATCH = 16;
528
+ async function verifyChecksums(key, checks, admit) {
529
+ for (let start = 0;start < checks.length; start += CHECKSUM_BATCH) {
530
+ admit();
531
+ const batch = checks.slice(start, start + CHECKSUM_BATCH);
532
+ const digests = await Promise.all(batch.map((check) => chunkChecksum(check.bytes)));
533
+ if (digests.some((digest, index) => digest !== batch[index].checksum))
534
+ throw new PayloadCorruption(`Invalid filesystem payload chunks: ${key}`);
535
+ }
536
+ admit();
537
+ }
395
538
  function payloads(nodes, keys) {
396
539
  for (const node of nodes)
397
540
  if (node.data !== undefined)
@@ -407,6 +550,33 @@ function recoveryManifest(value, key) {
407
550
  return;
408
551
  }
409
552
  }
553
+ function validateChunks(keys, records) {
554
+ const manifests = new Map;
555
+ const chunks = new Map;
556
+ for (const key of keys) {
557
+ if (typeof key === "string") {
558
+ const manifest = recoveryManifest(records.get(key), key);
559
+ if (manifest)
560
+ manifests.set(key, manifest);
561
+ continue;
562
+ }
563
+ if (!Array.isArray(key) || key.length !== 2 || typeof key[0] !== "string" || !validInteger(key[1]))
564
+ chunkError(String(key));
565
+ const indices = chunks.get(key[0]) ?? new Set;
566
+ indices.add(key[1]);
567
+ chunks.set(key[0], indices);
568
+ }
569
+ for (const [key, manifest] of manifests) {
570
+ const indices = chunks.get(key);
571
+ if ((indices?.size ?? 0) !== manifest.count) {
572
+ manifests.delete(key);
573
+ continue;
574
+ }
575
+ if (indices && Array.from(indices).some((index) => index >= manifest.count))
576
+ manifests.delete(key);
577
+ }
578
+ return manifests;
579
+ }
410
580
  function referenceIndex(nodes) {
411
581
  const references = new Map, parents = new Map;
412
582
  for (const node of nodes)
@@ -569,6 +739,30 @@ function applyChanges(state, staged, selection) {
569
739
  state.root = selection.root;
570
740
  state.publication = selection.publication;
571
741
  }
742
+ function replaceNodes(state, staged) {
743
+ for (const ino of Array.from(staged.removes).concat(Array.from(staged.upserts.keys()))) {
744
+ const previous = state.nodes.get(ino);
745
+ if (previous)
746
+ state.payloadSizes.remove([previous]);
747
+ }
748
+ state.payloadSizes.add(staged.upserts.values());
749
+ }
750
+ function installBases(state, bases) {
751
+ for (const slot of [0, 1]) {
752
+ if (state.bases[slot] === bases[slot])
753
+ continue;
754
+ state.payloadSizes.remove(state.bases[slot]?.nodes ?? []);
755
+ state.payloadSizes.add(bases[slot]?.nodes ?? []);
756
+ }
757
+ state.bases = bases;
758
+ }
759
+ function dropJournal(state, generation) {
760
+ const journal = state.journals.get(generation);
761
+ if (!journal)
762
+ return;
763
+ state.journals.delete(generation);
764
+ state.payloadSizes.remove(journal.upserts);
765
+ }
572
766
  export function recoverIndex(bases, journals, payloadKeys) {
573
767
  const generations = Array.from(new Set(Array.from(journals.keys()).concat(bases.flatMap((base) => base ? [base.generation] : []))));
574
768
  generations.sort((a, b) => b - a);
@@ -625,6 +819,7 @@ export class IndexedDBStorage {
625
819
  tail = Promise.resolve();
626
820
  readers = new PayloadRetentions;
627
821
  readerWork = new Set;
822
+ nativeReads = new Set;
628
823
  deletingPayloads = new Set;
629
824
  persistenceError;
630
825
  initialized = false;
@@ -907,7 +1102,7 @@ export class IndexedDBStorage {
907
1102
  } catch {}
908
1103
  }
909
1104
  this.db.close();
910
- this.ownershipRetirement = Promise.allSettled(Array.from(this.readerWork).concat([this.tail])).then(() => this.retireMaintenance());
1105
+ this.ownershipRetirement = Promise.allSettled(Array.from(this.readerWork).concat([this.tail])).then(() => this.joinNativeReads()).then(() => this.retireMaintenance());
911
1106
  this.ownershipRetirement.catch(() => {});
912
1107
  this.onOwnershipLost?.();
913
1108
  return error;
@@ -976,10 +1171,11 @@ export class IndexedDBStorage {
976
1171
  chunkError(key);
977
1172
  if (value.length !== this.payloadSize(key))
978
1173
  chunkError(key);
1174
+ signal?.throwIfAborted();
1175
+ this.assertOwner();
979
1176
  return value;
980
1177
  }
981
- const manifest = await this.manifest(key, signal);
982
- return this.readChunks(key, manifest, { offset: 0, length: manifest.size, signal });
1178
+ return this.readPayload(key, { offset: 0, length: Number.MAX_SAFE_INTEGER, signal }, this.knownSize(key));
983
1179
  });
984
1180
  }
985
1181
  retainPayload(key, expectedSize, metadata) {
@@ -996,23 +1192,10 @@ export class IndexedDBStorage {
996
1192
  throw new Error("Missing retained filesystem payload");
997
1193
  }
998
1194
  payloadSize(key) {
999
- const retained = this.readers.size(key);
1000
- if (retained !== undefined)
1001
- return retained;
1002
- for (const node of this.state.nodes.values())
1003
- if (node.data === key)
1004
- return node.size;
1005
- for (const base of this.state.bases) {
1006
- for (const node of base?.nodes ?? [])
1007
- if (node.data === key)
1008
- return node.size;
1009
- }
1010
- for (const journal of this.state.journals.values()) {
1011
- for (const node of journal.upserts)
1012
- if (node.data === key)
1013
- return node.size;
1014
- }
1015
- return;
1195
+ return this.readers.size(key) ?? this.state.payloadSizes.size(key);
1196
+ }
1197
+ knownSize(key) {
1198
+ return this.readers.size(key) ?? this.state?.payloadSizes.size(key);
1016
1199
  }
1017
1200
  resources() {
1018
1201
  return { ...this.readers.resources(), indexeddbReaderWork: this.readerWork.size };
@@ -1020,11 +1203,8 @@ export class IndexedDBStorage {
1020
1203
  retainedRange(key, range) {
1021
1204
  if (this.closed)
1022
1205
  return Promise.reject(new Error("Filesystem storage is closed"));
1023
- const work = this.manifest(key, range.signal).then((manifest) => {
1024
- if (manifest.size !== this.readers.size(key))
1025
- throw new PayloadCorruption("Retained payload size mismatch");
1026
- return this.readChunks(key, manifest, range);
1027
- });
1206
+ const size = this.readers.size(key);
1207
+ const work = size === undefined ? Promise.reject(new PayloadCorruption("Retained payload size mismatch")) : this.readPayload(key, range, size);
1028
1208
  this.readerWork.add(work);
1029
1209
  work.then(() => this.readerWork.delete(work), () => this.readerWork.delete(work));
1030
1210
  return work;
@@ -1041,8 +1221,7 @@ export class IndexedDBStorage {
1041
1221
  return this.enqueue(async () => {
1042
1222
  range.signal?.throwIfAborted();
1043
1223
  await this.initialize(range.signal);
1044
- const manifest = await this.manifest(key, range.signal);
1045
- return this.readChunks(key, manifest, range);
1224
+ return this.readPayload(key, range, this.knownSize(key));
1046
1225
  }).catch((error) => {
1047
1226
  range.signal?.throwIfAborted();
1048
1227
  throw error;
@@ -1075,43 +1254,72 @@ export class IndexedDBStorage {
1075
1254
  this.transactions.delete(tx);
1076
1255
  }
1077
1256
  }
1078
- async manifest(key, signal) {
1079
- const value = await this.readRecord(key, signal);
1080
- if (value === undefined)
1081
- throw new Error(`Missing filesystem payload: ${key}`);
1257
+ async readPayload(key, range, expectedSize) {
1258
+ const signal = range.signal;
1259
+ signal?.throwIfAborted();
1260
+ this.assertOwner();
1261
+ const tx = this.db.transaction("data", "readonly");
1262
+ this.transactions.add(tx);
1263
+ const abort = () => {
1264
+ try {
1265
+ tx.abort();
1266
+ } catch {}
1267
+ };
1268
+ signal?.addEventListener("abort", abort, { once: true });
1269
+ const settled = completed(tx);
1270
+ const native = settled.then(() => this.nativeSettled(tx, native), () => this.nativeSettled(tx, native));
1271
+ this.nativeReads.add(native);
1272
+ const arrival = Promise.withResolvers();
1273
+ const read = {
1274
+ key,
1275
+ range,
1276
+ expectedSize,
1277
+ end: 0,
1278
+ next: 0,
1279
+ checks: [],
1280
+ pending: 0,
1281
+ arrived: arrival.resolve,
1282
+ fail: (error) => {
1283
+ read.failure ??= { cause: error };
1284
+ abort();
1285
+ }
1286
+ };
1082
1287
  try {
1083
- return parseManifest(value, key);
1288
+ this.placePayloadReads(tx, read);
1289
+ await Promise.race([arrival.promise, settled.then(() => arrival.promise)]);
1084
1290
  } catch (error) {
1085
- throw new PayloadCorruption(error instanceof Error ? error.message : "Invalid payload manifest");
1291
+ abort();
1292
+ throw signal?.aborted ? signal.reason : this.ownershipError ?? read.failure?.cause ?? error;
1293
+ } finally {
1294
+ signal?.removeEventListener("abort", abort);
1086
1295
  }
1087
- }
1088
- async readChunks(key, manifest, range) {
1089
- const length = Math.max(0, Math.min(range.length, manifest.size - range.offset));
1090
- const result = new Uint8Array(length);
1091
- range.signal?.throwIfAborted();
1092
- if (!length)
1093
- return result;
1094
- const end = range.offset + length;
1095
- for (let index = Math.floor(range.offset / CHUNK_SIZE);index * CHUNK_SIZE < end; index++) {
1096
- const record = await this.readRecord([key, index], range.signal);
1097
- const chunk = this.validChunk(record, chunkLength(manifest, index), key);
1098
- if (await chunkChecksum(chunk.bytes) !== chunk.checksum)
1099
- throw new PayloadCorruption(`Invalid filesystem payload chunks: ${key}`);
1100
- range.signal?.throwIfAborted();
1296
+ const admit = () => {
1297
+ signal?.throwIfAborted();
1101
1298
  this.assertOwner();
1102
- const start = Math.max(range.offset, index * CHUNK_SIZE);
1103
- const stop = Math.min(end, (index + 1) * CHUNK_SIZE);
1104
- result.set(chunk.bytes.subarray(start - index * CHUNK_SIZE, stop - index * CHUNK_SIZE), start - range.offset);
1105
- }
1106
- range.signal?.throwIfAborted();
1107
- return result;
1299
+ };
1300
+ await verifyChecksums(key, read.checks, admit);
1301
+ admit();
1302
+ return read.result;
1303
+ }
1304
+ placePayloadReads(tx, read) {
1305
+ const store = tx.objectStore("data");
1306
+ const manifest = store.get(read.key);
1307
+ manifest.onsuccess = () => {
1308
+ try {
1309
+ acceptManifest(store, manifest.result, read);
1310
+ } catch (error) {
1311
+ read.fail(error);
1312
+ }
1313
+ };
1314
+ if (read.expectedSize !== undefined)
1315
+ placeChunkReads(store, read.expectedSize, read);
1108
1316
  }
1109
- validChunk(record, length, key) {
1110
- try {
1111
- return parseChunk(record, length, key);
1112
- } catch (error) {
1113
- throw new PayloadCorruption(error instanceof Error ? error.message : "Invalid payload chunk");
1114
- }
1317
+ joinNativeReads() {
1318
+ return Promise.all(Array.from(this.nativeReads));
1319
+ }
1320
+ nativeSettled(tx, native) {
1321
+ this.transactions.delete(tx);
1322
+ this.nativeReads.delete(native);
1115
1323
  }
1116
1324
  recoverCommitted() {
1117
1325
  return this.enqueue(async () => {
@@ -1218,6 +1426,7 @@ export class IndexedDBStorage {
1218
1426
  if (!this.closing) {
1219
1427
  this.closed = true;
1220
1428
  this.closing = Promise.all(Array.from(this.readerWork).concat([this.tail])).then(async () => {
1429
+ await this.joinNativeReads();
1221
1430
  this.db.close();
1222
1431
  if (this.readOnly) {
1223
1432
  this.state = undefined;
@@ -1251,7 +1460,7 @@ export class IndexedDBStorage {
1251
1460
  const settled = completed(tx);
1252
1461
  settled.catch(() => {});
1253
1462
  signal?.addEventListener("abort", abort, { once: true });
1254
- const metadata = tx.objectStore("metadata"), journal = tx.objectStore("journal");
1463
+ const metadata = tx.objectStore("metadata"), journal = tx.objectStore("journal"), data = tx.objectStore("data");
1255
1464
  try {
1256
1465
  const records = await Promise.all([
1257
1466
  request(metadata.get(0)),
@@ -1259,8 +1468,8 @@ export class IndexedDBStorage {
1259
1468
  request(metadata.getAllKeys()),
1260
1469
  request(journal.getAll()),
1261
1470
  request(journal.getAllKeys()),
1262
- request(tx.objectStore("data").getAllKeys()),
1263
- request(metadata.get("format")),
1471
+ request(data.getAllKeys()),
1472
+ formatAndManifests(metadata, data),
1264
1473
  request(metadata.get("commit")),
1265
1474
  request(metadata.get("active")),
1266
1475
  settled
@@ -1287,7 +1496,7 @@ export class IndexedDBStorage {
1287
1496
  journalValues,
1288
1497
  journalKeys,
1289
1498
  dataKeys,
1290
- format,
1499
+ { format, manifests },
1291
1500
  storedCommit,
1292
1501
  active
1293
1502
  ] = await this.indexRecords(signal);
@@ -1299,7 +1508,7 @@ export class IndexedDBStorage {
1299
1508
  else if (Array.isArray(key) && typeof key[0] === "string")
1300
1509
  payloadKeys.add(key[0]);
1301
1510
  }
1302
- const physical = format === INDEXEDDB_FORMAT || format === STAGED_FORMAT ? await this.validateChunks(dataKeys, signal) : undefined;
1511
+ const physical = manifests && validateChunks(dataKeys, manifests);
1303
1512
  const available = physical ? new Set(physical.keys()) : payloadKeys;
1304
1513
  const decoded = await Promise.all([decodeIndex(first), decodeIndex(second)]);
1305
1514
  signal?.throwIfAborted();
@@ -1322,6 +1531,13 @@ export class IndexedDBStorage {
1322
1531
  }
1323
1532
  if (newest) {
1324
1533
  const nodes = new Map(newest.nodes.map((node) => [node.ino, node]));
1534
+ const payloadSizes = new PayloadSizes;
1535
+ payloadSizes.add(nodes.values());
1536
+ for (const base of bases)
1537
+ if (base)
1538
+ payloadSizes.add(base.nodes);
1539
+ for (const journal of journals.values())
1540
+ payloadSizes.add(journal.upserts);
1325
1541
  const lastBase = Math.max(...bases.filter((base) => !!base).map((base) => base.generation));
1326
1542
  this.state = {
1327
1543
  generation: newest.generation,
@@ -1333,6 +1549,7 @@ export class IndexedDBStorage {
1333
1549
  journals,
1334
1550
  journalKeys,
1335
1551
  payloadKeys,
1552
+ payloadSizes,
1336
1553
  sinceCompaction: Array.from(journals.values()).filter((entry) => entry.generation > lastBase).length
1337
1554
  };
1338
1555
  }
@@ -1377,34 +1594,6 @@ export class IndexedDBStorage {
1377
1594
  matchSizes(nodes, manifests) {
1378
1595
  return !manifests || nodes.every((node) => node.data === undefined || manifests.get(node.data)?.size === node.size);
1379
1596
  }
1380
- async validateChunks(keys, signal) {
1381
- const manifests = new Map;
1382
- const chunks = new Map;
1383
- for (const key of keys) {
1384
- signal?.throwIfAborted();
1385
- if (typeof key === "string") {
1386
- const manifest = recoveryManifest(await this.readRecord(key, signal), key);
1387
- if (manifest)
1388
- manifests.set(key, manifest);
1389
- continue;
1390
- }
1391
- if (!Array.isArray(key) || key.length !== 2 || typeof key[0] !== "string" || !validInteger(key[1]))
1392
- chunkError(String(key));
1393
- const indices = chunks.get(key[0]) ?? new Set;
1394
- indices.add(key[1]);
1395
- chunks.set(key[0], indices);
1396
- }
1397
- for (const [key, manifest] of manifests) {
1398
- const indices = chunks.get(key);
1399
- if ((indices?.size ?? 0) !== manifest.count) {
1400
- manifests.delete(key);
1401
- continue;
1402
- }
1403
- if (indices && Array.from(indices).some((index) => index >= manifest.count))
1404
- manifests.delete(key);
1405
- }
1406
- return manifests;
1407
- }
1408
1597
  async fencedWrite(work, signal) {
1409
1598
  signal?.throwIfAborted();
1410
1599
  this.assertOwner();
@@ -1641,28 +1830,31 @@ export class IndexedDBStorage {
1641
1830
  nodes: new Map,
1642
1831
  references: new Map,
1643
1832
  parents: new Map,
1644
- bases,
1833
+ bases: [undefined, undefined],
1645
1834
  journals: new Map,
1646
1835
  journalKeys: [],
1647
1836
  payloadKeys: new Set,
1837
+ payloadSizes: new PayloadSizes,
1648
1838
  sinceCompaction: 0
1649
1839
  };
1650
1840
  for (const key of discarded)
1651
1841
  if (typeof key === "number")
1652
- state.journals.delete(key);
1842
+ dropJournal(state, key);
1653
1843
  state.journalKeys = state.journalKeys.filter((key) => !discarded.has(key));
1844
+ replaceNodes(state, staged);
1654
1845
  applyChanges(state, staged, batch);
1655
- state.bases = bases;
1846
+ installBases(state, bases);
1656
1847
  if (entry) {
1657
1848
  state.journals.set(entry.generation, entry);
1658
1849
  state.journalKeys.push(entry.generation);
1850
+ state.payloadSizes.add(entry.upserts);
1659
1851
  }
1660
1852
  for (const key of batch.data.keys())
1661
1853
  state.payloadKeys.add(key);
1662
1854
  if (compact) {
1663
1855
  for (const key of state.journals.keys())
1664
1856
  if (key <= cutoff)
1665
- state.journals.delete(key);
1857
+ dropJournal(state, key);
1666
1858
  state.journalKeys = state.journalKeys.filter((key) => typeof key !== "number" || key > cutoff);
1667
1859
  for (const key of deletedReaders) {
1668
1860
  state.payloadKeys.delete(key);