@waffle-os/runtime 0.0.154 → 0.0.156

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 (42) hide show
  1. package/core/filesystem.ts +22 -0
  2. package/core/wasi.ts +78 -5
  3. package/dist/core/filesystem.js +1 -0
  4. package/dist/core/wasi.js +71 -6
  5. package/dist/fs/backend.js +22 -1
  6. package/dist/fs/client.js +11 -3
  7. package/dist/fs/cold-read-cache.js +23 -0
  8. package/dist/fs/guest-watch.js +267 -94
  9. package/dist/fs/indexeddb-chunks.js +88 -11
  10. package/dist/fs/indexeddb.js +78 -14
  11. package/dist/fs/memory.js +17 -1
  12. package/dist/fs/multitab-backend.js +198 -64
  13. package/dist/fs/multitab-protocol.js +1 -0
  14. package/dist/fs/persistent.js +19 -1
  15. package/dist/fs/service.js +30 -1
  16. package/dist/fs/shared.js +4 -0
  17. package/dist/fs/storage.js +107 -8
  18. package/dist/fs/watch-service.js +97 -2
  19. package/dist/fs/watch-subscriptions.js +121 -8
  20. package/dist/proc/intrinsics/core.js +5 -0
  21. package/dist/proc/intrinsics.js +1 -0
  22. package/dist/tooling/program/program-transformer.json +1 -1
  23. package/fs/backend.ts +27 -1
  24. package/fs/client.ts +11 -0
  25. package/fs/cold-read-cache.ts +38 -0
  26. package/fs/guest-watch.ts +298 -102
  27. package/fs/indexeddb-chunks.ts +103 -9
  28. package/fs/indexeddb.ts +98 -11
  29. package/fs/memory.ts +18 -0
  30. package/fs/multitab-backend.ts +273 -72
  31. package/fs/multitab-protocol.ts +1 -0
  32. package/fs/persistent.ts +38 -1
  33. package/fs/service.ts +28 -0
  34. package/fs/shared.ts +4 -0
  35. package/fs/storage.ts +128 -10
  36. package/fs/watch-service.ts +110 -3
  37. package/fs/watch-subscriptions.ts +115 -7
  38. package/package.json +1 -1
  39. package/proc/intrinsics/core.ts +7 -0
  40. package/proc/intrinsics.ts +1 -0
  41. package/testing/indexeddb-storage-browser.ts +129 -0
  42. package/tooling/program/program-transformer.json +1 -1
@@ -23,6 +23,7 @@ import {
23
23
  parseManifest,
24
24
  preparePayload,
25
25
  preparePayloads,
26
+ putPayload,
26
27
  copyLegacyChunks,
27
28
  validateRange
28
29
  } from "./indexeddb-chunks.js";
@@ -347,6 +348,9 @@ class PayloadSizes {
347
348
  size(key) {
348
349
  return this.entries.get(key)?.size;
349
350
  }
351
+ has(key) {
352
+ return this.entries.has(key);
353
+ }
350
354
  }
351
355
  function validateDatabaseLayout(committed, format, keys, journalKeys, dataKeys) {
352
356
  const empty = committed && !keys.includes("format") && keys.every((key) => key === "epoch" || key === "lastExclusiveEpoch") && !journalKeys.length && !dataKeys.length;
@@ -454,6 +458,16 @@ function placeManifestReads(data, format, resolve, reject) {
454
458
  }
455
459
  };
456
460
  }
461
+ function raceAbort(promise, signal) {
462
+ if (!signal)
463
+ return promise;
464
+ signal.throwIfAborted();
465
+ return new Promise((resolve, reject) => {
466
+ const onAbort = () => reject(signal.reason);
467
+ signal.addEventListener("abort", onAbort, { once: true });
468
+ promise.then(resolve, reject).finally(() => signal.removeEventListener("abort", onAbort));
469
+ });
470
+ }
457
471
  function completed(tx) {
458
472
  return new Promise((resolve, reject) => {
459
473
  tx.oncomplete = () => resolve();
@@ -829,6 +843,7 @@ export class IndexedDBStorage {
829
843
  ownershipError;
830
844
  ownershipRetirement;
831
845
  transactions = new Set;
846
+ epochWitnesses = new Set;
832
847
  committedEnvelope;
833
848
  committedRecord;
834
849
  committedPending = false;
@@ -859,6 +874,32 @@ export class IndexedDBStorage {
859
874
  if (this.closed || this.ownershipError)
860
875
  return false;
861
876
  signal?.throwIfAborted();
877
+ const witnessed = await this.witnessedEpoch(signal);
878
+ if (witnessed !== undefined)
879
+ return witnessed && !this.closed && !this.ownershipError;
880
+ return this.readEpoch(signal);
881
+ }
882
+ async witnessedEpoch(signal) {
883
+ for (const witness of Array.from(this.epochWitnesses)) {
884
+ const result = await raceAbort(witness, signal);
885
+ if (result !== undefined)
886
+ return result;
887
+ }
888
+ return;
889
+ }
890
+ witnessEpoch(tx, read) {
891
+ const { promise: witness, resolve } = Promise.withResolvers();
892
+ const end = () => {
893
+ this.epochWitnesses.delete(witness);
894
+ resolve(undefined);
895
+ };
896
+ read.addEventListener("success", () => resolve(read.result === this.epoch));
897
+ read.addEventListener("error", () => resolve(undefined));
898
+ tx.addEventListener("complete", end);
899
+ tx.addEventListener("abort", end);
900
+ this.epochWitnesses.add(witness);
901
+ }
902
+ async readEpoch(signal) {
862
903
  let tx;
863
904
  const onAbort = () => {
864
905
  try {
@@ -1582,14 +1623,14 @@ export class IndexedDBStorage {
1582
1623
  this.committedRecord = await encodeCommit(envelope);
1583
1624
  }
1584
1625
  recordRecovery(state, extra) {
1585
- const retained = new Set(extra);
1586
- payloads(state.nodes.values(), retained);
1587
- for (const base of state.bases)
1588
- if (base)
1589
- payloads(base.nodes, retained);
1590
- for (const journal of state.journals.values())
1591
- payloads(journal.upserts, retained);
1592
- this.readers.recovery(retained);
1626
+ if (!extra?.length) {
1627
+ this.readers.recovery(state.payloadSizes);
1628
+ return;
1629
+ }
1630
+ const extraRoots = new Set(extra);
1631
+ this.readers.recovery({
1632
+ has: (key) => extraRoots.has(key) || state.payloadSizes.has(key)
1633
+ });
1593
1634
  }
1594
1635
  matchSizes(nodes, manifests) {
1595
1636
  return !manifests || nodes.every((node) => node.data === undefined || manifests.get(node.data)?.size === node.size);
@@ -1609,6 +1650,7 @@ export class IndexedDBStorage {
1609
1650
  const done = completed(tx);
1610
1651
  const metadata = tx.objectStore("metadata");
1611
1652
  const epoch = metadata.get("epoch");
1653
+ this.witnessEpoch(tx, epoch);
1612
1654
  epoch.onsuccess = () => {
1613
1655
  try {
1614
1656
  if (epoch.result !== this.epoch)
@@ -1669,7 +1711,12 @@ export class IndexedDBStorage {
1669
1711
  async commit(batch, committed) {
1670
1712
  if (this.committedMode !== !!committed)
1671
1713
  throw new Error("Committed storage requires a complete durable group");
1672
- const prepared = await preparePayloads(batch.data);
1714
+ const checkActive = () => {
1715
+ committed?.control.checkAbort();
1716
+ this.assertOwner();
1717
+ };
1718
+ const prepared = await preparePayloads(batch.data, true, checkActive);
1719
+ checkActive();
1673
1720
  const staged = stageChanges(this.state, batch), old = this.state;
1674
1721
  const discarded = new Set(old?.journalKeys.filter((key) => typeof key !== "number" || key > old.generation));
1675
1722
  const compact = !old || old.sinceCompaction + 1 >= this.compactEvery;
@@ -1782,26 +1829,43 @@ export class IndexedDBStorage {
1782
1829
  abort(error);
1783
1830
  }
1784
1831
  };
1785
- let remaining = checking.size + pinChecks.size + (committed ? 2 : 0);
1832
+ const newKeys = [];
1833
+ const verifyKeys = [];
1834
+ for (const key of checking) {
1835
+ if (prepared.has(key) && !old?.payloadKeys.has(key))
1836
+ newKeys.push(key);
1837
+ else
1838
+ verifyKeys.push(key);
1839
+ }
1840
+ let remaining = 1 + verifyKeys.length + pinChecks.size + (committed ? 1 : 0);
1786
1841
  const checked = () => {
1787
1842
  if (--remaining === 0)
1788
1843
  finish();
1789
1844
  };
1790
1845
  const checkEpoch = tx.objectStore("metadata").get("epoch");
1846
+ this.witnessEpoch(tx, checkEpoch);
1791
1847
  checkEpoch.onsuccess = () => {
1792
1848
  if (checkEpoch.result !== this.epoch) {
1793
1849
  abort(this.loseOwnership());
1794
1850
  return;
1795
1851
  }
1796
- if (committed)
1852
+ try {
1853
+ for (const key of newKeys) {
1854
+ const supplied = prepared.get(key);
1855
+ const size = expected.get(key);
1856
+ if (size !== undefined && supplied.manifest.size !== size)
1857
+ throw new Error(`Invalid filesystem payload size: ${key}`);
1858
+ putPayload(data, key, supplied);
1859
+ }
1797
1860
  checked();
1861
+ } catch (error) {
1862
+ abort(error);
1863
+ }
1798
1864
  };
1799
1865
  if (committed)
1800
1866
  checkCommitHead(tx, committed, checked, abort);
1801
1867
  try {
1802
- if (!remaining)
1803
- finish();
1804
- for (const key of checking) {
1868
+ for (const key of verifyKeys) {
1805
1869
  const get = data.get(key);
1806
1870
  get.onsuccess = () => {
1807
1871
  try {
package/dist/fs/memory.js CHANGED
@@ -3,7 +3,8 @@ import { utf8ByteLength } from "./utf8-size.js";
3
3
  import {
4
4
  permissionsFor,
5
5
  FilesystemError,
6
- fileTimeNow
6
+ fileTimeNow,
7
+ PROBE_PATH_LIMIT
7
8
  } from "../core/filesystem.js";
8
9
  import {
9
10
  dirname,
@@ -476,6 +477,21 @@ export class MemFS {
476
477
  return this.pathOf(resolved.node);
477
478
  return joinBelow(this.pathOf(resolved.parent), "/" + resolved.name);
478
479
  }
480
+ probe(directory, paths, kind, rooted = false) {
481
+ if (paths.length > PROBE_PATH_LIMIT)
482
+ throw new FilesystemError(28);
483
+ const start = this.directory(directory);
484
+ const wanted = kind === "directory" ? "dir" : "file";
485
+ for (let index = 0;index < paths.length; index++) {
486
+ const path = paths[index];
487
+ if (path.startsWith("/"))
488
+ continue;
489
+ const resolved = this.walkNodes(start, path, false, true, undefined, rooted);
490
+ if (typeof resolved !== "number" && resolved.node?.kind === wanted)
491
+ return index;
492
+ }
493
+ return -1;
494
+ }
479
495
  pathOf(dir) {
480
496
  const names = [];
481
497
  for (let at = dir;at !== this.root; ) {
@@ -9,7 +9,12 @@ import {
9
9
  pack,
10
10
  unpack
11
11
  } from "./protocol.js";
12
- import { CLIENT_MODE, CLIENT_MODE_NO_CLIENT_CACHE, CLIENT_MODE_NO_DIRECT_IO } from "./shared.js";
12
+ import {
13
+ CLIENT_MODE,
14
+ CLIENT_MODE_NO_CLIENT_CACHE,
15
+ CLIENT_MODE_NO_DIRECT_IO,
16
+ CLIENT_MODE_NO_WATCH_DRAIN
17
+ } from "./shared.js";
13
18
  import { HEADER_WORDS, WATCH_OFFSET } from "./storage-geometry.js";
14
19
  import { WatchRing } from "./watch-ring.js";
15
20
  import { WatchService } from "./watch-service.js";
@@ -323,7 +328,14 @@ export class MultiTabBackend {
323
328
  sharedMaxBytes;
324
329
  retainedSegments = [];
325
330
  watchCells;
326
- role = "init";
331
+ roleState = "init";
332
+ get role() {
333
+ return this.roleState;
334
+ }
335
+ set role(next) {
336
+ this.roleState = next;
337
+ this.syncClientMode();
338
+ }
327
339
  phase = "opening";
328
340
  steppingDown = false;
329
341
  disposing = false;
@@ -409,6 +421,7 @@ export class MultiTabBackend {
409
421
  byFileId = new Map;
410
422
  nextLocalWatchId = 1;
411
423
  localWatches = new Map;
424
+ hostWatchToLocal = new Map;
412
425
  constructor(options) {
413
426
  this.options = options;
414
427
  this.scope = multitabScope(options.implementation, options.name);
@@ -509,14 +522,22 @@ export class MultiTabBackend {
509
522
  this.configureSharedBuffer(buffer);
510
523
  if (this.persistent) {
511
524
  this.persistent.attachShared(buffer, this.sharedMaxBytes, this.retainedSegments);
512
- this.persistent.shared.setClientMode(CLIENT_MODE_NO_DIRECT_IO | CLIENT_MODE_NO_CLIENT_CACHE);
513
525
  }
526
+ this.syncClientMode();
514
527
  }
515
528
  configureSharedBuffer(buffer) {
516
- const header = new Int32Array(buffer, 0, HEADER_WORDS);
517
- Atomics.store(header, CLIENT_MODE, CLIENT_MODE_NO_DIRECT_IO | CLIENT_MODE_NO_CLIENT_CACHE);
518
529
  const ring = new WatchRing(buffer, WATCH_OFFSET);
519
530
  this.watchCells = ring.cells;
531
+ this.syncClientMode();
532
+ }
533
+ syncClientMode() {
534
+ const mode = CLIENT_MODE_NO_DIRECT_IO | CLIENT_MODE_NO_CLIENT_CACHE | (this.roleState === "host" ? 0 : CLIENT_MODE_NO_WATCH_DRAIN);
535
+ if (this.persistent) {
536
+ this.persistent.shared.setClientMode(mode);
537
+ } else if (this.sharedBuffer) {
538
+ const header = new Int32Array(this.sharedBuffer, 0, HEADER_WORDS);
539
+ Atomics.store(header, CLIENT_MODE, mode);
540
+ }
520
541
  }
521
542
  wakeWatchWord() {
522
543
  if (!this.watchCells)
@@ -777,16 +798,15 @@ export class MultiTabBackend {
777
798
  throw new FilesystemError(8);
778
799
  if (this.role === "host") {
779
800
  const admittedTerm = this.hostTerm;
780
- if (this.leaseOnlyLapsed(admittedTerm)) {
801
+ if (!this.hostReadyForLocal(admittedTerm)) {
781
802
  return this.watchOpenAfterRenewal(owner, handle, recursive, cancelled, admittedTerm);
782
803
  }
783
- this.assertHostReadyForLocal(admittedTerm);
784
804
  if (entry.remoteHandle === undefined)
785
805
  throw new FilesystemError(8);
786
806
  this.watchService ??= new WatchService(this.persistent);
787
807
  const hostWatchId = this.watchService.open(owner, entry.remoteHandle, recursive, cancelled);
788
808
  const localWatchId = this.nextLocalWatchId++;
789
- this.localWatches.set(localWatchId, {
809
+ const localEntry = {
790
810
  localWatchId,
791
811
  localOwner: owner,
792
812
  fileId: entry.fileId,
@@ -795,7 +815,9 @@ export class MultiTabBackend {
795
815
  hostWatchId,
796
816
  overflowed: false,
797
817
  closed: false
798
- });
818
+ };
819
+ this.localWatches.set(localWatchId, localEntry);
820
+ this.hostWatchToLocal.set(hostWatchId, localEntry);
799
821
  return localWatchId;
800
822
  }
801
823
  if (this.needsFailoverWait()) {
@@ -858,28 +880,119 @@ export class MultiTabBackend {
858
880
  return this.watchOpen(owner, handle, recursive, cancelled);
859
881
  }
860
882
  async watchReadHostAfterRenew(owner, watch, cancelled) {
861
- if (this.disposing || cancelled())
862
- throw new FilesystemError(11);
863
- if (this.leaseOnlyLapsed(watch.hostTerm)) {
864
- await this.renewLapsedLease(watch.hostTerm, cancelled).catch(() => {});
865
- } else {
866
- await raceWithAbort(this.renewLeaseNow(), this.disposeAbort.signal, cancelled);
867
- }
868
- if (this.disposing || cancelled())
869
- throw new FilesystemError(11);
870
883
  const overflow = {
871
884
  batch: { kind: "overflow", events: [] },
872
885
  release() {},
873
886
  rollback() {}
874
887
  };
875
- const termEnded = watch.hostTerm !== this.hostTerm || this.role !== "host" || this.ownershipLost || this.leaseClosed;
876
- if (watch.overflowed || termEnded || !this.watchService) {
877
- watch.overflowed = true;
878
- return overflow;
888
+ const budget = {};
889
+ await this.renewWatchLeaseOnce(watch.hostTerm, cancelled);
890
+ for (;; ) {
891
+ if (this.disposing || cancelled())
892
+ throw new FilesystemError(11);
893
+ const termEnded = watch.hostTerm !== this.hostTerm || this.role !== "host" || this.ownershipLost || this.leaseClosed;
894
+ if (watch.overflowed || termEnded || !this.watchService) {
895
+ watch.overflowed = true;
896
+ return overflow;
897
+ }
898
+ if (this.isLeaseValid())
899
+ return this.watchService.readHeld(owner, watch.hostWatchId);
900
+ if (!await this.renewWatchLease(watch.hostTerm, cancelled, budget))
901
+ return overflow;
902
+ }
903
+ }
904
+ async renewWatchLeaseOnce(admittedTerm, cancelled) {
905
+ if (this.disposing || cancelled())
906
+ throw new FilesystemError(11);
907
+ if (this.leaseOnlyLapsed(admittedTerm))
908
+ return;
909
+ await raceWithAbort(this.renewLeaseNow(), this.disposeAbort.signal, cancelled);
910
+ }
911
+ async renewWatchLease(admittedTerm, cancelled, budget) {
912
+ if (!this.leaseOnlyLapsed(admittedTerm))
913
+ return false;
914
+ try {
915
+ await this.renewLapsedLease(admittedTerm, cancelled, budget);
916
+ return true;
917
+ } catch {
918
+ if (this.disposing || cancelled())
919
+ throw new FilesystemError(11);
920
+ return false;
921
+ }
922
+ }
923
+ watchDrain(owner, cancelled) {
924
+ if (this.role === "host") {
925
+ const admittedTerm = this.hostTerm;
926
+ if (!this.isLeaseValid()) {
927
+ return this.watchDrainHostAfterRenew(owner, admittedTerm, cancelled);
928
+ }
929
+ return this.drainHostWatches(owner);
930
+ }
931
+ throw new FilesystemError(58);
932
+ }
933
+ overflowOwnerWatches(owner, permanent) {
934
+ const entries = [];
935
+ for (const watch of this.localWatches.values()) {
936
+ if (watch.closed || watch.localOwner !== owner)
937
+ continue;
938
+ if (permanent || watch.hostTerm !== this.hostTerm)
939
+ watch.overflowed = true;
940
+ entries.push({ id: watch.localWatchId, batch: { kind: "overflow", events: [] } });
941
+ }
942
+ return { entries, more: false, hasEvents: false, release() {}, rollback() {} };
943
+ }
944
+ async watchDrainHostAfterRenew(owner, admittedTerm, cancelled) {
945
+ const budget = {};
946
+ await this.renewWatchLeaseOnce(admittedTerm, cancelled);
947
+ for (;; ) {
948
+ if (this.disposing || cancelled())
949
+ throw new FilesystemError(11);
950
+ const termEnded = admittedTerm !== this.hostTerm || this.role !== "host" || this.ownershipLost || this.leaseClosed || !!this.terminalFailure || !this.watchService;
951
+ if (termEnded)
952
+ return this.overflowOwnerWatches(owner, true);
953
+ if (this.isLeaseValid())
954
+ return this.drainHostWatches(owner);
955
+ if (!await this.renewWatchLease(admittedTerm, cancelled, budget))
956
+ return this.overflowOwnerWatches(owner, false);
957
+ }
958
+ }
959
+ drainHostWatches(owner) {
960
+ if (this.terminalFailure || !this.watchService) {
961
+ return this.overflowOwnerWatches(owner, true);
962
+ }
963
+ const entries = [];
964
+ const seen = new Set;
965
+ const held = this.watchService.drainHeld(owner);
966
+ for (const entry of held.entries) {
967
+ const local = this.hostWatchToLocal.get(entry.id);
968
+ if (!local || local.closed || local.localOwner !== owner)
969
+ continue;
970
+ if (local.overflowed || local.hostTerm !== this.hostTerm) {
971
+ local.overflowed = true;
972
+ seen.add(local.localWatchId);
973
+ entries.push({ id: local.localWatchId, batch: { kind: "overflow", events: [] } });
974
+ continue;
975
+ }
976
+ seen.add(local.localWatchId);
977
+ entries.push("batch" in entry ? { id: local.localWatchId, batch: entry.batch } : { id: local.localWatchId, errno: entry.errno });
879
978
  }
880
- if (!this.isLeaseValid())
881
- return overflow;
882
- return this.watchService.readHeld(owner, watch.hostWatchId);
979
+ if (this.hostWatchToLocal.size !== this.localWatches.size) {
980
+ for (const watch of this.localWatches.values()) {
981
+ if (watch.closed || watch.localOwner !== owner || seen.has(watch.localWatchId))
982
+ continue;
983
+ if (watch.overflowed || watch.hostTerm !== this.hostTerm || watch.hostWatchId === undefined) {
984
+ watch.overflowed = true;
985
+ entries.push({ id: watch.localWatchId, batch: { kind: "overflow", events: [] } });
986
+ }
987
+ }
988
+ }
989
+ return {
990
+ entries,
991
+ more: held.more,
992
+ hasEvents: held.hasEvents,
993
+ release: held.release,
994
+ rollback: held.rollback
995
+ };
883
996
  }
884
997
  watchClose(owner, localWatchId) {
885
998
  const watch = this.localWatches.get(localWatchId);
@@ -887,6 +1000,9 @@ export class MultiTabBackend {
887
1000
  return;
888
1001
  watch.closed = true;
889
1002
  this.localWatches.delete(localWatchId);
1003
+ if (watch.hostWatchId !== undefined && this.hostWatchToLocal.get(watch.hostWatchId) === watch) {
1004
+ this.hostWatchToLocal.delete(watch.hostWatchId);
1005
+ }
890
1006
  if (this.role === "host" && watch.hostTerm === this.hostTerm && watch.hostWatchId !== undefined) {
891
1007
  this.watchService?.close(owner, watch.hostWatchId);
892
1008
  } else if (this.role === "peer" && watch.hostTerm === this.peerHostTerm && watch.hostWatchId !== undefined && this.peerSessionId) {
@@ -1188,7 +1304,7 @@ export class MultiTabBackend {
1188
1304
  }
1189
1305
  });
1190
1306
  if (this.sharedBuffer) {
1191
- backend.shared.setClientMode(CLIENT_MODE_NO_DIRECT_IO | CLIENT_MODE_NO_CLIENT_CACHE);
1307
+ backend.shared.setClientMode(CLIENT_MODE_NO_DIRECT_IO | CLIENT_MODE_NO_CLIENT_CACHE | CLIENT_MODE_NO_WATCH_DRAIN);
1192
1308
  }
1193
1309
  if (!backend.hasLoadedIndex) {
1194
1310
  await backend.flush();
@@ -4027,7 +4143,7 @@ export class MultiTabBackend {
4027
4143
  this.hostAdmittedZeroWaiters.push(resolve);
4028
4144
  });
4029
4145
  }
4030
- assertHostReadyForLocal(admittedTerm) {
4146
+ hostReadyForLocal(admittedTerm) {
4031
4147
  if (this.terminalFailure || this.persistent?.isTerminallyFailed()) {
4032
4148
  throw new FilesystemError(29, describeReason(this.terminalFailure?.reason));
4033
4149
  }
@@ -4037,19 +4153,23 @@ export class MultiTabBackend {
4037
4153
  if (this.steppingDown && (!this.disposing || this.disposeHostTerm !== admittedTerm)) {
4038
4154
  throw new FilesystemError(11, "host is stepping down");
4039
4155
  }
4040
- if (!this.isLeaseValid()) {
4041
- throw new FilesystemError(11, "host lease expired");
4042
- }
4156
+ if (this.isLeaseValid())
4157
+ return true;
4158
+ if (this.lapseIsRenewable(admittedTerm))
4159
+ return false;
4160
+ throw new FilesystemError(11, "host lease expired");
4043
4161
  }
4044
4162
  leaseOnlyLapsed(admittedTerm) {
4045
- return !this.isLeaseValid() && !this.leaseClosed && !this.ownershipLost && !this.terminalFailure && !this.persistent?.isTerminallyFailed() && !!this.persistent && this.role === "host" && this.hostTerm === admittedTerm && !this.steppingDown && !this.disposing;
4163
+ return !this.isLeaseValid() && this.lapseIsRenewable(admittedTerm);
4164
+ }
4165
+ lapseIsRenewable(admittedTerm) {
4166
+ return !this.leaseClosed && !this.ownershipLost && !this.terminalFailure && !this.persistent?.isTerminallyFailed() && !!this.persistent && this.role === "host" && this.hostTerm === admittedTerm && !this.steppingDown && !this.disposing;
4046
4167
  }
4047
4168
  assertLocalAttempt(admittedTerm, cancelled) {
4048
4169
  if (cancelled?.())
4049
4170
  throw new FilesystemError(11, "operation cancelled");
4050
- if (this.leaseOnlyLapsed(admittedTerm))
4171
+ if (!this.hostReadyForLocal(admittedTerm))
4051
4172
  throw LEASE_LAPSED;
4052
- this.assertHostReadyForLocal(admittedTerm);
4053
4173
  }
4054
4174
  localAttemptStale(admittedTerm, cancelled) {
4055
4175
  if (cancelled?.() || this.hostTerm !== admittedTerm)
@@ -4068,9 +4188,9 @@ export class MultiTabBackend {
4068
4188
  }
4069
4189
  }
4070
4190
  async assertHostAfterRenewal(admittedTerm, cancelled, budget) {
4071
- if (this.leaseOnlyLapsed(admittedTerm))
4191
+ while (!this.hostReadyForLocal(admittedTerm)) {
4072
4192
  await this.renewLapsedLease(admittedTerm, cancelled, budget);
4073
- this.assertHostReadyForLocal(admittedTerm);
4193
+ }
4074
4194
  }
4075
4195
  async renewLapsedLease(admittedTerm, cancelled, budget = {}) {
4076
4196
  const fresh = budget.deadline === undefined;
@@ -4091,44 +4211,56 @@ export class MultiTabBackend {
4091
4211
  if (cancelled?.())
4092
4212
  throw new FilesystemError(11, "operation cancelled");
4093
4213
  }
4094
- async executeLocalOnHost(operation, args, data, responseCookieTag, cancelled) {
4214
+ async renewBeforeLocalHostCall(admittedTerm, budget, operation, args, data, responseCookieTag, cancelled) {
4215
+ if (this.disposing)
4216
+ throw new FilesystemError(11, "host lease expired during dispose");
4217
+ if (this.leaseOnlyLapsed(admittedTerm)) {
4218
+ await this.renewLapsedLease(admittedTerm, cancelled, budget);
4219
+ } else {
4220
+ await raceWithAbort(this.renewLeaseNow(this.currentAttemptId), this.disposeAbort.signal, cancelled);
4221
+ }
4095
4222
  if (cancelled?.())
4096
4223
  throw new FilesystemError(11, "operation cancelled");
4097
- const admittedTerm = this.hostTerm;
4098
- const budget = {};
4099
- if (!this.isLeaseValid()) {
4100
- if (this.disposing)
4101
- throw new FilesystemError(11, "host lease expired during dispose");
4102
- if (this.leaseOnlyLapsed(admittedTerm)) {
4103
- await this.renewLapsedLease(admittedTerm, cancelled, budget);
4104
- } else {
4105
- await raceWithAbort(this.renewLeaseNow(this.currentAttemptId), this.disposeAbort.signal, cancelled);
4106
- }
4224
+ if (this.disposing)
4225
+ throw new FilesystemError(11, "filesystem is disposing");
4226
+ if (!this.isLeaseValid() && !this.leaseOnlyLapsed(admittedTerm)) {
4227
+ await this.awaitPendingFenceLoss(cancelled);
4107
4228
  if (cancelled?.())
4108
4229
  throw new FilesystemError(11, "operation cancelled");
4109
4230
  if (this.disposing)
4110
4231
  throw new FilesystemError(11, "filesystem is disposing");
4111
- if (!this.isLeaseValid()) {
4112
- await this.awaitPendingFenceLoss(cancelled);
4113
- if (cancelled?.())
4114
- throw new FilesystemError(11, "operation cancelled");
4115
- if (this.disposing)
4116
- throw new FilesystemError(11, "filesystem is disposing");
4117
- if (this.terminalFailure) {
4118
- throw new FilesystemError(29, describeReason(this.terminalFailure.reason));
4119
- }
4120
- if (this.ownershipLost)
4121
- throw new FilesystemError(11, "filesystem ownership lost");
4122
- if (this.role === "peer" || this.role === "failover" || this.role === "waiting") {
4123
- const nextCookieTag = this.revalidateCookieForPeerForward(operation, args, responseCookieTag);
4124
- return this.executeOnPeer(operation, args, data, nextCookieTag, cancelled);
4125
- }
4126
- throw new FilesystemError(11, "host lease expired");
4232
+ if (this.terminalFailure) {
4233
+ throw new FilesystemError(29, describeReason(this.terminalFailure.reason));
4234
+ }
4235
+ if (this.ownershipLost)
4236
+ throw new FilesystemError(11, "filesystem ownership lost");
4237
+ if (this.role === "peer" || this.role === "failover" || this.role === "waiting") {
4238
+ const nextCookieTag = this.revalidateCookieForPeerForward(operation, args, responseCookieTag);
4239
+ return {
4240
+ result: await this.executeOnPeer(operation, args, data, nextCookieTag, cancelled)
4241
+ };
4127
4242
  }
4243
+ throw new FilesystemError(11, "host lease expired");
4128
4244
  }
4245
+ return;
4246
+ }
4247
+ async executeLocalOnHost(operation, args, data, responseCookieTag, cancelled) {
4129
4248
  if (cancelled?.())
4130
4249
  throw new FilesystemError(11, "operation cancelled");
4131
- this.assertHostReadyForLocal(admittedTerm);
4250
+ const admittedTerm = this.hostTerm;
4251
+ const budget = {};
4252
+ if (!this.isLeaseValid()) {
4253
+ const forwarded = await this.renewBeforeLocalHostCall(admittedTerm, budget, operation, args, data, responseCookieTag, cancelled);
4254
+ if (forwarded)
4255
+ return forwarded.result;
4256
+ }
4257
+ if (cancelled?.())
4258
+ throw new FilesystemError(11, "operation cancelled");
4259
+ if (!this.hostReadyForLocal(admittedTerm)) {
4260
+ await this.assertHostAfterRenewal(admittedTerm, cancelled, budget);
4261
+ if (cancelled?.())
4262
+ throw new FilesystemError(11, "operation cancelled");
4263
+ }
4132
4264
  const persistent = this.persistent;
4133
4265
  const translated = this.translateArgsToHost(operation, args);
4134
4266
  if (!translated)
@@ -5210,7 +5342,8 @@ export class MultiTabBackend {
5210
5342
  case "readdir":
5211
5343
  case "readdirPage":
5212
5344
  case "resolve":
5213
- case "realpath": {
5345
+ case "realpath":
5346
+ case "probe": {
5214
5347
  const remote = mapHandle(args[0]);
5215
5348
  if (remote === undefined)
5216
5349
  return;
@@ -5241,6 +5374,7 @@ export class MultiTabBackend {
5241
5374
  this.dirEpoch++;
5242
5375
  }
5243
5376
  markLocalWatchesOverflow() {
5377
+ this.hostWatchToLocal.clear();
5244
5378
  for (const watch of this.localWatches.values()) {
5245
5379
  watch.overflowed = true;
5246
5380
  }
@@ -144,6 +144,7 @@ const PURE_STATELESS_READ_OPS = new Set([
144
144
  "readlink",
145
145
  "resolve",
146
146
  "realpath",
147
+ "probe",
147
148
  "readdirPage"
148
149
  ]);
149
150
  export function isReplayableRead(operation, args) {
@@ -322,17 +322,35 @@ export class PersistentBackend extends MemoryBackend {
322
322
  const cached = this.coldReads.read(key, offset, count);
323
323
  if (cached) {
324
324
  this.storage.checkPayload(key, size);
325
+ this.coldReads.noteRead(key, offset + count);
325
326
  return this.cachedDescriptorRange(cached, cancelled);
326
327
  }
328
+ const window = this.coldReads.readWindow(key, offset, count, size);
327
329
  const backing = this.coldBacking(node, key, undefined, cancelled);
330
+ this.coldReads.noteRead(key, offset + count);
328
331
  const drained = Promise.withResolvers();
329
332
  this.ownWork(drained.promise);
330
- return this.readDescriptorRange(backing, offset, count, cancelled).finally(() => {
333
+ const reply = this.readDescriptorWindow(backing, offset, count, window, cancelled);
334
+ return reply.finally(() => {
331
335
  const release = Promise.resolve().then(() => backing.retention.release());
332
336
  release.then(drained.resolve, drained.reject);
333
337
  return release;
334
338
  });
335
339
  }
340
+ async readDescriptorWindow(backing, offset, count, window, cancelled) {
341
+ if (window.offset === offset && window.length === count)
342
+ return this.readDescriptorRange(backing, offset, count, cancelled);
343
+ try {
344
+ const bytes = await this.readDescriptorRange(backing, window.offset, window.length, cancelled);
345
+ return bytes.slice(offset - window.offset, offset - window.offset + count);
346
+ } catch (error) {
347
+ if (cancelled() || this.stopped)
348
+ throw new FilesystemError(11);
349
+ if (error instanceof FilesystemError && error.errno === 11)
350
+ throw error;
351
+ return this.readDescriptorRange(backing, offset, count, cancelled);
352
+ }
353
+ }
336
354
  async readDescriptorRange(backing, offset, length, cancelled) {
337
355
  if (cancelled() || this.stopped)
338
356
  throw new FilesystemError(11);