@waffle-os/runtime 0.0.155 → 0.0.157

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 (77) hide show
  1. package/browser/filesystem-backend.ts +11 -1
  2. package/browser/preview-protocol.ts +2 -0
  3. package/browser/preview.ts +128 -18
  4. package/browser/runtime-terminals.ts +65 -24
  5. package/browser/shared-fs.ts +141 -14
  6. package/browser/worker.ts +73 -6
  7. package/core/descriptors.ts +19 -2
  8. package/core/devices.ts +237 -2
  9. package/core/fd-reopen.ts +105 -20
  10. package/core/filesystem.ts +79 -0
  11. package/core/index.ts +4 -0
  12. package/core/open-file.ts +212 -18
  13. package/core/wasi.ts +449 -47
  14. package/dist/browser/filesystem-backend.js +4 -2
  15. package/dist/browser/preview.js +120 -17
  16. package/dist/browser/runtime-terminals.js +53 -10
  17. package/dist/browser/shared-fs.js +124 -11
  18. package/dist/browser/worker.js +59 -6
  19. package/dist/core/descriptors.js +9 -1
  20. package/dist/core/devices.js +211 -1
  21. package/dist/core/fd-reopen.js +79 -18
  22. package/dist/core/filesystem.js +14 -0
  23. package/dist/core/open-file.js +166 -13
  24. package/dist/core/wasi.js +402 -29
  25. package/dist/fs/backend.js +51 -3
  26. package/dist/fs/client.js +204 -7
  27. package/dist/fs/cold-read-cache.js +23 -0
  28. package/dist/fs/index.js +21 -1
  29. package/dist/fs/indexeddb.js +30 -2
  30. package/dist/fs/locks.js +1112 -0
  31. package/dist/fs/memory.js +126 -2
  32. package/dist/fs/multitab-backend.js +317 -196
  33. package/dist/fs/multitab-protocol.js +2 -0
  34. package/dist/fs/persistent.js +32 -7
  35. package/dist/fs/protocol.js +9 -3
  36. package/dist/fs/service.js +387 -22
  37. package/dist/fs/shared.js +54 -1
  38. package/dist/fs/storage-geometry.js +2 -0
  39. package/dist/interrupt/rewriter-internal.js +4 -1
  40. package/dist/proc/abi.js +80 -6
  41. package/dist/proc/errors.js +1 -0
  42. package/dist/proc/filesystem-codec.js +40 -9
  43. package/dist/proc/index.js +10 -1
  44. package/dist/proc/pty.js +193 -0
  45. package/dist/proc/worker-client.js +11 -2
  46. package/dist/proc/worker-pipes.js +51 -0
  47. package/dist/runtime.js +11 -2
  48. package/dist/search/engine.js +53 -0
  49. package/dist/tooling/program/program-transformer.json +1 -1
  50. package/fs/backend.ts +54 -2
  51. package/fs/client.ts +230 -6
  52. package/fs/cold-read-cache.ts +38 -0
  53. package/fs/index.ts +22 -1
  54. package/fs/indexeddb.ts +36 -2
  55. package/fs/locks.ts +1406 -0
  56. package/fs/memory.ts +132 -1
  57. package/fs/multitab-backend.ts +563 -304
  58. package/fs/multitab-protocol.ts +2 -0
  59. package/fs/persistent.ts +46 -4
  60. package/fs/protocol.ts +17 -5
  61. package/fs/service.ts +469 -23
  62. package/fs/shared.ts +60 -2
  63. package/fs/storage-geometry.ts +3 -0
  64. package/index.ts +2 -0
  65. package/interrupt/rewriter-internal.ts +4 -1
  66. package/package.json +2 -2
  67. package/proc/abi.ts +79 -6
  68. package/proc/errors.ts +1 -0
  69. package/proc/filesystem-codec.ts +39 -9
  70. package/proc/index.ts +11 -0
  71. package/proc/pty.ts +227 -0
  72. package/proc/worker-client.ts +28 -6
  73. package/proc/worker-pipes.ts +57 -0
  74. package/runtime.ts +12 -2
  75. package/search/engine.ts +49 -0
  76. package/testing/indexeddb-storage-browser.ts +173 -2
  77. package/tooling/program/program-transformer.json +1 -1
@@ -18,7 +18,10 @@ import {
18
18
  CLIENT_MODE_NO_CLIENT_CACHE,
19
19
  CLIENT_MODE_NO_DIRECT_IO,
20
20
  CLIENT_MODE_NO_WATCH_DRAIN,
21
+ machineIdFromWorkspace,
22
+ writeSharedMachineId,
21
23
  } from "./shared.js";
24
+ import { validateMachineId } from "../core/devices.js";
22
25
  import type { RuntimeStartupObserver } from "./startup.js";
23
26
  import type { StorageBackend } from "./storage.js";
24
27
  import { HEADER_WORDS, WATCH_OFFSET } from "./storage-geometry.js";
@@ -143,6 +146,7 @@ export interface MultiTabBackendOptions {
143
146
  readonly name: string;
144
147
  readonly startupRoot?: MemoryBudget;
145
148
  readonly sharedRoot?: MemoryBackendSharedRoot;
149
+ readonly machineId?: string;
146
150
  readonly onStartupStage?: RuntimeStartupObserver;
147
151
  readonly signal?: AbortSignal;
148
152
  readonly onWaiting?: () => void;
@@ -672,6 +676,7 @@ export class MultiTabBackend implements FilesystemBackend {
672
676
  private peerPendingWatchCloses = new Set<number>();
673
677
  private peerPendingUploadAborts = new Set<string>();
674
678
  readonly supportsSockets = false;
679
+ readonly supportsLocks = false;
675
680
  readonly asyncErrorsAreClientResults = true;
676
681
  private peerFailoverInFlight?: Promise<void>;
677
682
  private pendingDirectHostReady?: Extract<ControlMessage, { kind: "host-ready" }>;
@@ -814,6 +819,26 @@ export class MultiTabBackend implements FilesystemBackend {
814
819
  const ring = new WatchRing(buffer, WATCH_OFFSET);
815
820
  this.watchCells = ring.cells;
816
821
  this.syncClientMode();
822
+ this.syncMachineId();
823
+ }
824
+
825
+ private resolveMachineId(): string | undefined {
826
+ if (this.options.machineId !== undefined) return validateMachineId(this.options.machineId);
827
+ if (this.cohortWorkspaceId !== undefined) return machineIdFromWorkspace(this.cohortWorkspaceId);
828
+ return undefined;
829
+ }
830
+
831
+ private syncMachineId(): void {
832
+ const id = this.resolveMachineId();
833
+ if (!id) return;
834
+ if (this.persistent) {
835
+ this.persistent.shared.setMachineId(id);
836
+ return;
837
+ }
838
+ if (this.sharedBuffer) {
839
+ const header = new Int32Array(this.sharedBuffer, 0, HEADER_WORDS);
840
+ writeSharedMachineId(header, id);
841
+ }
817
842
  }
818
843
 
819
844
  private syncClientMode(): void {
@@ -1526,6 +1551,7 @@ export class MultiTabBackend implements FilesystemBackend {
1526
1551
  // Terminal failure already latched (including from a joined promotion rollback):
1527
1552
  // retain attach-claim + aliveLock + controlChannel and reject with released:false!
1528
1553
  if (this.terminalFailure) {
1554
+ this.persistent?.dispose();
1529
1555
  throw wrapReleaseError(this.terminalFailure.reason, false);
1530
1556
  }
1531
1557
 
@@ -1825,6 +1851,7 @@ export class MultiTabBackend implements FilesystemBackend {
1825
1851
  segments: this.retainedSegments,
1826
1852
  }
1827
1853
  : undefined,
1854
+ machineId: this.options.machineId,
1828
1855
  signal,
1829
1856
  });
1830
1857
 
@@ -1970,7 +1997,10 @@ export class MultiTabBackend implements FilesystemBackend {
1970
1997
  backend: PersistentBackend | undefined,
1971
1998
  storage: StorageBackend,
1972
1999
  ): Promise<void> {
1973
- if (this.terminalFailure) throw wrapReleaseError(this.terminalFailure.reason, false);
2000
+ if (this.terminalFailure) {
2001
+ backend?.dispose();
2002
+ throw wrapReleaseError(this.terminalFailure.reason, false);
2003
+ }
1974
2004
  if (backend) {
1975
2005
  this.setPersistent(undefined);
1976
2006
  this.watchService = undefined;
@@ -2158,6 +2188,7 @@ export class MultiTabBackend implements FilesystemBackend {
2158
2188
  this.leaseMonoDeadline = 0;
2159
2189
  this.leaseWallDeadline = 0;
2160
2190
  this.stopHostTimers();
2191
+ this.persistent?.dispose();
2161
2192
 
2162
2193
  const msg = describeReason(reason);
2163
2194
  // Broadcast host-failed to all tabs (AND keep answering discover/attach with host-failed!)
@@ -3494,6 +3525,7 @@ export class MultiTabBackend implements FilesystemBackend {
3494
3525
  private commitCohortEpoch(workspaceId: string, storageEpoch: number): void {
3495
3526
  this.cohortWorkspaceId = workspaceId;
3496
3527
  this.cohortLastAcceptedEpoch = Math.max(this.cohortLastAcceptedEpoch ?? 0, storageEpoch);
3528
+ this.syncMachineId();
3497
3529
  }
3498
3530
 
3499
3531
  // ---------------------------------------------------------------------------
@@ -4386,26 +4418,20 @@ export class MultiTabBackend implements FilesystemBackend {
4386
4418
  return { ok: true };
4387
4419
  }
4388
4420
 
4389
- private validateChunkGetState(
4421
+ private async ensureChunkGetLease(
4390
4422
  session: HostPeerSession,
4391
4423
  admittedTerm: bigint,
4424
+ budget: LeaseRenewalBudget,
4392
4425
  replyErr: (errno: number, message?: string) => void,
4393
- requireLease: boolean,
4394
- ): boolean {
4395
- if (session.revoked) return false;
4396
- if (this.terminalFailure || this.persistent?.isTerminallyFailed()) {
4397
- replyErr(29, "host storage terminally failed");
4398
- return false;
4399
- }
4400
- if (this.ownershipLost || this.role !== "host" || this.hostTerm !== admittedTerm) {
4401
- replyErr(11, "host term ended");
4402
- return false;
4403
- }
4404
- if (requireLease && !this.isLeaseValid()) {
4405
- replyErr(11, "host lease expired");
4426
+ publish?: () => void,
4427
+ ): Promise<boolean> {
4428
+ try {
4429
+ await this.ensurePeerLeaseAndPublish(session, admittedTerm, budget, publish ?? (() => {}));
4430
+ return true;
4431
+ } catch (error) {
4432
+ if (!session.revoked) replyErr(errorToErrno(error), describeReason(error));
4406
4433
  return false;
4407
4434
  }
4408
- return true;
4409
4435
  }
4410
4436
 
4411
4437
  private async handleHostChunkGet(
@@ -4418,6 +4444,7 @@ export class MultiTabBackend implements FilesystemBackend {
4418
4444
  }
4419
4445
  session.activeReqs.add(msg.reqId);
4420
4446
  const admittedTerm = session.hostTerm;
4447
+ const budget: LeaseRenewalBudget = {};
4421
4448
  const reclaimDownload = () => {
4422
4449
  const existing = session.downloads.get(msg.downloadId);
4423
4450
  if (existing && session.downloads.delete(msg.downloadId)) {
@@ -4443,45 +4470,11 @@ export class MultiTabBackend implements FilesystemBackend {
4443
4470
  });
4444
4471
  };
4445
4472
  try {
4446
- if (!this.validateChunkGetState(session, admittedTerm, replyErr, false)) return;
4447
- if (!this.isLeaseValid()) {
4448
- await this.renewLeaseNow(this.currentAttemptId);
4449
- if (!this.validateChunkGetState(session, admittedTerm, replyErr, true)) return;
4450
- }
4473
+ if (!(await this.ensureChunkGetLease(session, admittedTerm, budget, replyErr))) return;
4451
4474
 
4452
4475
  this.enterHostAdmitted();
4453
4476
  try {
4454
- const dl = session.downloads.get(msg.downloadId);
4455
- if (!dl) {
4456
- replyErr(11);
4457
- return;
4458
- }
4459
- if (msg.offset < 0 || msg.offset >= dl.bytes.byteLength || msg.length <= 0) {
4460
- replyErr(28);
4461
- return;
4462
- }
4463
- const end = Math.min(
4464
- dl.bytes.byteLength,
4465
- msg.offset + Math.min(msg.length, MAX_FRAME_BYTES),
4466
- );
4467
- const slice = unsharedBytes(dl.bytes.subarray(msg.offset, end));
4468
- await this.hooks.beforeHostReplyPublish?.("chunk-get", msg.reqId);
4469
- // Revalidate lease, term, and terminal state immediately before settling & publishing!
4470
- if (!this.validateChunkGetState(session, admittedTerm, replyErr, true)) return;
4471
- if (end >= dl.bytes.byteLength) {
4472
- reclaimDownload();
4473
- }
4474
- this.sendPeerFrame(session.peerId, session.channel, {
4475
- kind: "res",
4476
- hostTerm: formatTerm(admittedTerm),
4477
- sessionId: session.sessionId,
4478
- reqId: msg.reqId,
4479
- ok: true,
4480
- data: slice,
4481
- binary: true,
4482
- creditFrames: 1,
4483
- creditBytes: 0,
4484
- });
4477
+ await this.serveHostChunkGet(session, msg, admittedTerm, budget, reclaimDownload, replyErr);
4485
4478
  } finally {
4486
4479
  this.leaveHostAdmitted();
4487
4480
  }
@@ -4491,6 +4484,62 @@ export class MultiTabBackend implements FilesystemBackend {
4491
4484
  }
4492
4485
  }
4493
4486
 
4487
+ private async serveHostChunkGet(
4488
+ session: HostPeerSession,
4489
+ msg: Extract<PeerMessage, { kind: "chunk-get" }>,
4490
+ admittedTerm: bigint,
4491
+ budget: LeaseRenewalBudget,
4492
+ reclaimDownload: () => void,
4493
+ replyErr: (errno: number, message?: string) => void,
4494
+ ): Promise<void> {
4495
+ const dl = session.downloads.get(msg.downloadId);
4496
+ if (!dl) {
4497
+ replyErr(11);
4498
+ return;
4499
+ }
4500
+ if (msg.offset < 0 || msg.offset >= dl.bytes.byteLength || msg.length <= 0) {
4501
+ replyErr(28);
4502
+ return;
4503
+ }
4504
+ const end = Math.min(dl.bytes.byteLength, msg.offset + Math.min(msg.length, MAX_FRAME_BYTES));
4505
+ const slice = unsharedBytes(dl.bytes.subarray(msg.offset, end));
4506
+ const isFinalChunk = end >= dl.bytes.byteLength;
4507
+ await this.hooks.beforeHostReplyPublish?.("chunk-get", msg.reqId);
4508
+ // Revalidate lease, term, and terminal state synchronously in the same turn as publication!
4509
+ await this.ensureChunkGetLease(session, admittedTerm, budget, replyErr, () => {
4510
+ this.publishChunkGetFrame(
4511
+ session,
4512
+ msg.reqId,
4513
+ admittedTerm,
4514
+ slice,
4515
+ isFinalChunk,
4516
+ reclaimDownload,
4517
+ );
4518
+ });
4519
+ }
4520
+
4521
+ private publishChunkGetFrame(
4522
+ session: HostPeerSession,
4523
+ reqId: number,
4524
+ admittedTerm: bigint,
4525
+ slice: Uint8Array,
4526
+ isFinalChunk: boolean,
4527
+ reclaimDownload: () => void,
4528
+ ): void {
4529
+ if (isFinalChunk) reclaimDownload();
4530
+ this.sendPeerFrame(session.peerId, session.channel, {
4531
+ kind: "res",
4532
+ hostTerm: formatTerm(admittedTerm),
4533
+ sessionId: session.sessionId,
4534
+ reqId,
4535
+ ok: true,
4536
+ data: slice,
4537
+ binary: true,
4538
+ creditFrames: 1,
4539
+ creditBytes: 0,
4540
+ });
4541
+ }
4542
+
4494
4543
  private async handleHostPeerReq(
4495
4544
  session: HostPeerSession,
4496
4545
  msg: Extract<PeerMessage, { kind: "req" }>,
@@ -4539,9 +4588,10 @@ export class MultiTabBackend implements FilesystemBackend {
4539
4588
  return;
4540
4589
  }
4541
4590
 
4542
- // Lease check at admission!
4543
- if (!this.isLeaseValid()) {
4544
- const renewed = await this.renewLeaseNow(this.currentAttemptId);
4591
+ const budget: LeaseRenewalBudget = {};
4592
+ // Lease check at admission: renew a lapsed lease within the call's budget instead of failing.
4593
+ while (!this.hostReadyForPeer(session, admittedTerm)) {
4594
+ await this.renewLapsedLease(admittedTerm, () => session.revoked, budget);
4545
4595
  if (session.revoked) return;
4546
4596
  if (this.terminalFailure || this.persistent?.isTerminallyFailed()) {
4547
4597
  reply({ ok: false, errno: 29, message: "host storage terminally failed" });
@@ -4551,15 +4601,11 @@ export class MultiTabBackend implements FilesystemBackend {
4551
4601
  reply({ ok: false, retry: true });
4552
4602
  return;
4553
4603
  }
4554
- if (!renewed || !this.isLeaseValid() || this.hostTerm !== admittedTerm) {
4555
- reply({ ok: false, errno: 11, message: "host lease expired" });
4556
- return;
4557
- }
4558
4604
  }
4559
4605
 
4560
4606
  this.enterHostAdmitted();
4561
4607
  try {
4562
- await this.executePeerRpcOnHost(session, admittedTerm, msg, reply);
4608
+ await this.executePeerRpcOnHost(session, admittedTerm, msg, reply, budget);
4563
4609
  } finally {
4564
4610
  this.leaveHostAdmitted();
4565
4611
  }
@@ -4578,18 +4624,74 @@ export class MultiTabBackend implements FilesystemBackend {
4578
4624
  }
4579
4625
  }
4580
4626
 
4581
- private assertHostOpStillValid(session: HostPeerSession, admittedTerm: bigint): void {
4627
+ /**
4628
+ * Checks Host authority for a Peer request, sampling the lease once so a lapse is renewed
4629
+ * within the call's budget instead of failing with ECANCELED.
4630
+ */
4631
+ private hostReadyForPeer(session: HostPeerSession, admittedTerm: bigint): boolean {
4582
4632
  if (session.revoked) throw new FilesystemError(11, "peer session revoked");
4583
- if (this.terminalFailure || this.persistent?.isTerminallyFailed())
4633
+ if (this.terminalFailure || this.persistent?.isTerminallyFailed()) {
4584
4634
  throw new FilesystemError(29, "host storage terminally failed");
4635
+ }
4585
4636
  if (
4586
4637
  this.ownershipLost ||
4587
4638
  this.role !== "host" ||
4588
4639
  this.hostTerm !== admittedTerm ||
4589
- !this.isLeaseValid() ||
4590
4640
  !this.persistent
4591
- )
4592
- throw new FilesystemError(11, "host lease invalid");
4641
+ ) {
4642
+ throw new FilesystemError(11, "host term ended");
4643
+ }
4644
+ if (this.isLeaseValid()) return true;
4645
+ if (this.lapseIsRenewable(admittedTerm)) return false;
4646
+ throw new FilesystemError(11, "host lease invalid");
4647
+ }
4648
+
4649
+ private assertPeerAttempt(session: HostPeerSession, admittedTerm: bigint): void {
4650
+ if (!this.hostReadyForPeer(session, admittedTerm)) throw LEASE_LAPSED;
4651
+ }
4652
+
4653
+ private peerAttemptStale(session: HostPeerSession, admittedTerm: bigint): boolean {
4654
+ if (session.revoked || this.hostTerm !== admittedTerm) return true;
4655
+ return !this.isLeaseValid() && !this.leaseOnlyLapsed(admittedTerm);
4656
+ }
4657
+
4658
+ private async ensurePeerLease(
4659
+ session: HostPeerSession,
4660
+ admittedTerm: bigint,
4661
+ budget: LeaseRenewalBudget,
4662
+ ): Promise<void> {
4663
+ await this.ensurePeerLeaseAndPublish(session, admittedTerm, budget, () => {});
4664
+ }
4665
+
4666
+ /** Verify lease/term authority and invoke `publish` synchronously in the same turn. */
4667
+ private async ensurePeerLeaseAndPublish(
4668
+ session: HostPeerSession,
4669
+ admittedTerm: bigint,
4670
+ budget: LeaseRenewalBudget,
4671
+ publish: () => void,
4672
+ ): Promise<void> {
4673
+ const cancelled = () => session.revoked;
4674
+ while (!this.hostReadyForPeer(session, admittedTerm)) {
4675
+ await this.renewLapsedLease(admittedTerm, cancelled, budget);
4676
+ }
4677
+ publish();
4678
+ }
4679
+
4680
+ private async retryPeerAfterLeaseRenewal<T>(
4681
+ session: HostPeerSession,
4682
+ admittedTerm: bigint,
4683
+ budget: LeaseRenewalBudget,
4684
+ attempt: () => Promise<T>,
4685
+ ): Promise<T> {
4686
+ const cancelled = () => session.revoked;
4687
+ for (;;) {
4688
+ try {
4689
+ return await attempt();
4690
+ } catch (error) {
4691
+ if (error !== LEASE_LAPSED) throw error;
4692
+ }
4693
+ await this.renewLapsedLease(admittedTerm, cancelled, budget);
4694
+ }
4593
4695
  }
4594
4696
 
4595
4697
  private async executePeerRpcOnHost(
@@ -4602,17 +4704,18 @@ export class MultiTabBackend implements FilesystemBackend {
4602
4704
  "kind" | "hostTerm" | "sessionId" | "reqId" | "creditFrames" | "creditBytes"
4603
4705
  >,
4604
4706
  ) => void,
4707
+ budget: LeaseRenewalBudget,
4605
4708
  ): Promise<void> {
4606
4709
  if (msg.op === "__rebind") {
4607
- await this.handleHostPeerRebind(session, admittedTerm, msg, reply);
4710
+ await this.handleHostPeerRebind(session, admittedTerm, msg, reply, budget);
4608
4711
  return;
4609
4712
  }
4610
4713
  if (msg.op === "watchOpen") {
4611
- await this.handleHostPeerWatchOpen(session, admittedTerm, msg, reply);
4714
+ await this.handleHostPeerWatchOpen(session, admittedTerm, msg, reply, budget);
4612
4715
  return;
4613
4716
  }
4614
4717
  if (msg.op === "watchRead") {
4615
- await this.handleHostPeerWatchRead(session, admittedTerm, msg, reply);
4718
+ await this.handleHostPeerWatchRead(session, admittedTerm, msg, reply, budget);
4616
4719
  return;
4617
4720
  }
4618
4721
 
@@ -4625,6 +4728,7 @@ export class MultiTabBackend implements FilesystemBackend {
4625
4728
  msg.args[0] as string,
4626
4729
  msg.reqId,
4627
4730
  reply,
4731
+ budget,
4628
4732
  );
4629
4733
  return;
4630
4734
  }
@@ -4636,32 +4740,24 @@ export class MultiTabBackend implements FilesystemBackend {
4636
4740
  msg.args,
4637
4741
  msg.reqId,
4638
4742
  reply,
4743
+ budget,
4639
4744
  );
4640
4745
  return;
4641
4746
  }
4642
4747
  if (msg.op === "readdirPage") {
4643
- await this.handleHostPeerReaddirPage(session, admittedTerm, msg, reply);
4748
+ await this.handleHostPeerReaddirPage(session, admittedTerm, msg, reply, budget);
4644
4749
  return;
4645
4750
  }
4646
4751
  if (msg.op === "flush" || msg.op === "sync") {
4647
- const target =
4648
- msg.op === "sync" ? (msg.args[0] as number) : (msg.args[0] as string | undefined);
4649
- await this.barrier.runBarrier(async () => {
4650
- await this.hostQueue;
4651
- this.assertHostOpStillValid(session, admittedTerm);
4652
- await this.persistent!.flush(target);
4653
- });
4654
- await this.hooks.beforeHostReplyPublish?.(msg.op, msg.reqId);
4655
- this.assertHostOpStillValid(session, admittedTerm);
4656
- reply({ ok: true, value: msg.op === "sync" ? 0 : undefined });
4752
+ await this.handleHostPeerFlush(session, admittedTerm, msg, reply, budget);
4657
4753
  return;
4658
4754
  }
4659
4755
  if (msg.op === "read") {
4660
- await this.handleHostPeerRead(session, admittedTerm, msg, reply);
4756
+ await this.handleHostPeerRead(session, admittedTerm, msg, reply, budget);
4661
4757
  return;
4662
4758
  }
4663
4759
 
4664
- await this.handleHostPeerGeneral(session, admittedTerm, msg, data, reply);
4760
+ await this.handleHostPeerGeneral(session, admittedTerm, msg, data, reply, budget);
4665
4761
  } finally {
4666
4762
  if (reservedUploadBytes > 0) {
4667
4763
  this.hostUsedUploadBytes = Math.max(0, this.hostUsedUploadBytes - reservedUploadBytes);
@@ -4669,6 +4765,33 @@ export class MultiTabBackend implements FilesystemBackend {
4669
4765
  }
4670
4766
  }
4671
4767
 
4768
+ private async handleHostPeerFlush(
4769
+ session: HostPeerSession,
4770
+ admittedTerm: bigint,
4771
+ msg: Extract<PeerMessage, { kind: "req" }>,
4772
+ reply: (
4773
+ partial: Omit<
4774
+ Extract<PeerMessage, { kind: "res" }>,
4775
+ "kind" | "hostTerm" | "sessionId" | "reqId" | "creditFrames" | "creditBytes"
4776
+ >,
4777
+ ) => void,
4778
+ budget: LeaseRenewalBudget,
4779
+ ): Promise<void> {
4780
+ const target =
4781
+ msg.op === "sync" ? (msg.args[0] as number) : (msg.args[0] as string | undefined);
4782
+ await this.barrier.runBarrier(async () => {
4783
+ await this.retryPeerAfterLeaseRenewal(session, admittedTerm, budget, async () => {
4784
+ await this.hostQueue;
4785
+ this.assertPeerAttempt(session, admittedTerm);
4786
+ });
4787
+ await this.persistent!.flush(target);
4788
+ });
4789
+ await this.hooks.beforeHostReplyPublish?.(msg.op, msg.reqId);
4790
+ await this.ensurePeerLeaseAndPublish(session, admittedTerm, budget, () => {
4791
+ reply({ ok: true, value: msg.op === "sync" ? 0 : undefined });
4792
+ });
4793
+ }
4794
+
4672
4795
  private consumeHostStagedUpload(
4673
4796
  session: HostPeerSession,
4674
4797
  msg: Extract<PeerMessage, { kind: "req" }>,
@@ -4683,6 +4806,23 @@ export class MultiTabBackend implements FilesystemBackend {
4683
4806
  return { data: upload.buffer, reservedUploadBytes: upload.totalBytes };
4684
4807
  }
4685
4808
 
4809
+ private rebindPeerFiles(
4810
+ session: HostPeerSession,
4811
+ persistent: PersistentBackend,
4812
+ fileIds: readonly bigint[],
4813
+ bound: (WirePinnedHandle | null)[],
4814
+ ): void {
4815
+ for (const fileId of fileIds) {
4816
+ const node = persistent.nodeByFileId(fileId);
4817
+ if (!node) {
4818
+ bound.push(null);
4819
+ continue;
4820
+ }
4821
+ const remoteHandle = persistent.fs.handleForNode(node);
4822
+ bound.push(this.mintHostPeerPin(session, remoteHandle, fileId));
4823
+ }
4824
+ }
4825
+
4686
4826
  private async handleHostPeerRebind(
4687
4827
  session: HostPeerSession,
4688
4828
  admittedTerm: bigint,
@@ -4693,25 +4833,27 @@ export class MultiTabBackend implements FilesystemBackend {
4693
4833
  "kind" | "hostTerm" | "sessionId" | "reqId" | "creditFrames" | "creditBytes"
4694
4834
  >,
4695
4835
  ) => void,
4836
+ budget: LeaseRenewalBudget,
4696
4837
  ): Promise<void> {
4697
4838
  const persistent = this.persistent!;
4698
4839
  const fileIds = msg.args[0] as bigint[];
4699
4840
  const bound: (WirePinnedHandle | null)[] = [];
4700
- await this.enqueueHostSerial(() => {
4701
- this.assertHostOpStillValid(session, admittedTerm);
4702
- for (const fileId of fileIds) {
4703
- const node = persistent.nodeByFileId(fileId);
4704
- if (!node) {
4705
- bound.push(null);
4706
- continue;
4707
- }
4708
- const remoteHandle = persistent.fs.handleForNode(node);
4709
- bound.push(this.mintHostPeerPin(session, remoteHandle, fileId));
4710
- }
4711
- });
4841
+ await this.retryPeerAfterLeaseRenewal(session, admittedTerm, budget, () =>
4842
+ this.enqueueHostSerial(() => {
4843
+ this.assertPeerAttempt(session, admittedTerm);
4844
+ this.rebindPeerFiles(session, persistent, fileIds, bound);
4845
+ }),
4846
+ );
4712
4847
  await this.hooks.beforeHostReplyPublish?.(msg.op, msg.reqId);
4713
- this.assertHostOpStillValid(session, admittedTerm);
4714
- reply({ ok: true, value: bound });
4848
+ try {
4849
+ await this.ensurePeerLeaseAndPublish(session, admittedTerm, budget, () => {
4850
+ reply({ ok: true, value: bound });
4851
+ });
4852
+ } catch (error) {
4853
+ const mintedTokens = bound.flatMap((item) => (item ? [item.pinToken] : []));
4854
+ this.rollbackMintedPeerTokens(session, persistent, mintedTokens);
4855
+ throw error;
4856
+ }
4715
4857
  }
4716
4858
 
4717
4859
  private async handleHostPeerWatchOpen(
@@ -4724,34 +4866,32 @@ export class MultiTabBackend implements FilesystemBackend {
4724
4866
  "kind" | "hostTerm" | "sessionId" | "reqId" | "creditFrames" | "creditBytes"
4725
4867
  >,
4726
4868
  ) => void,
4869
+ budget: LeaseRenewalBudget,
4727
4870
  ): Promise<void> {
4728
4871
  const persistent = this.persistent!;
4729
4872
  const [remoteHandle, recursive] = msg.args as [number, boolean];
4730
4873
  let hostWatchId = 0;
4731
- await this.enqueueHostSerial(() => {
4732
- this.assertHostOpStillValid(session, admittedTerm);
4733
- this.watchService ??= new WatchService(persistent);
4734
- hostWatchId = this.watchService.open(
4735
- session.ownerId,
4736
- remoteHandle,
4737
- recursive,
4738
- () => session.revoked || this.hostTerm !== admittedTerm || !this.isLeaseValid(),
4739
- );
4740
- session.watchIds.add(hostWatchId);
4741
- });
4874
+ await this.retryPeerAfterLeaseRenewal(session, admittedTerm, budget, () =>
4875
+ this.enqueueHostSerial(() => {
4876
+ this.assertPeerAttempt(session, admittedTerm);
4877
+ this.watchService ??= new WatchService(persistent);
4878
+ hostWatchId = this.watchService.open(session.ownerId, remoteHandle, recursive, () =>
4879
+ this.peerAttemptStale(session, admittedTerm),
4880
+ );
4881
+ session.watchIds.add(hostWatchId);
4882
+ }),
4883
+ );
4742
4884
  await this.hooks.beforeHostReplyPublish?.(msg.op, msg.reqId);
4743
- if (
4744
- session.revoked ||
4745
- this.terminalFailure ||
4746
- !this.isLeaseValid() ||
4747
- this.hostTerm !== admittedTerm
4748
- ) {
4885
+ try {
4886
+ await this.ensurePeerLeaseAndPublish(session, admittedTerm, budget, () => {
4887
+ reply({ ok: true, value: hostWatchId });
4888
+ });
4889
+ } catch (error) {
4749
4890
  if (session.watchIds.delete(hostWatchId)) {
4750
4891
  this.watchService?.close(session.ownerId, hostWatchId);
4751
4892
  }
4752
- this.assertHostOpStillValid(session, admittedTerm);
4893
+ throw error;
4753
4894
  }
4754
- reply({ ok: true, value: hostWatchId });
4755
4895
  }
4756
4896
 
4757
4897
  private rollbackHeldWatchAck(session: HostPeerSession, ackId: number | undefined): void {
@@ -4773,26 +4913,40 @@ export class MultiTabBackend implements FilesystemBackend {
4773
4913
  "kind" | "hostTerm" | "sessionId" | "reqId" | "creditFrames" | "creditBytes"
4774
4914
  >,
4775
4915
  ) => void,
4916
+ budget: LeaseRenewalBudget,
4776
4917
  ): Promise<void> {
4777
4918
  const [hostWatchId] = msg.args as [number];
4778
4919
  let held: HeldWatchBatch | undefined;
4779
- await this.enqueueHostSerial(() => {
4780
- this.assertHostOpStillValid(session, admittedTerm);
4781
- if (!this.watchService || !session.watchIds.has(hostWatchId)) throw new FilesystemError(8);
4782
- held = this.watchService.readHeld(session.ownerId, hostWatchId);
4783
- });
4920
+ await this.retryPeerAfterLeaseRenewal(session, admittedTerm, budget, () =>
4921
+ this.enqueueHostSerial(() => {
4922
+ this.assertPeerAttempt(session, admittedTerm);
4923
+ if (!this.watchService || !session.watchIds.has(hostWatchId)) throw new FilesystemError(8);
4924
+ held = this.watchService.readHeld(session.ownerId, hostWatchId);
4925
+ }),
4926
+ );
4784
4927
  await this.hooks.beforeHostReplyPublish?.(msg.op, msg.reqId);
4785
- if (
4786
- !held ||
4787
- session.revoked ||
4788
- this.terminalFailure ||
4789
- !this.isLeaseValid() ||
4790
- this.hostTerm !== admittedTerm
4791
- ) {
4928
+ try {
4929
+ await this.ensurePeerLeaseAndPublish(session, admittedTerm, budget, () => {
4930
+ if (!held) return;
4931
+ this.publishHeldWatchBatch(session, held, hostWatchId, reply);
4932
+ });
4933
+ } catch (error) {
4792
4934
  held?.rollback();
4793
- this.assertHostOpStillValid(session, admittedTerm);
4794
- return;
4935
+ throw error;
4795
4936
  }
4937
+ }
4938
+
4939
+ private publishHeldWatchBatch(
4940
+ session: HostPeerSession,
4941
+ held: HeldWatchBatch,
4942
+ hostWatchId: number,
4943
+ reply: (
4944
+ partial: Omit<
4945
+ Extract<PeerMessage, { kind: "res" }>,
4946
+ "kind" | "hostTerm" | "sessionId" | "reqId" | "creditFrames" | "creditBytes"
4947
+ >,
4948
+ ) => void,
4949
+ ): void {
4796
4950
  const batch = held.batch;
4797
4951
  const encoded = pack(batch);
4798
4952
  let ackId: number | undefined;
@@ -4821,6 +4975,18 @@ export class MultiTabBackend implements FilesystemBackend {
4821
4975
  });
4822
4976
  }
4823
4977
 
4978
+ private reserveStagedDownload(session: HostPeerSession, byteLength: number): number {
4979
+ if (byteLength <= MAX_FRAME_BYTES) return 0;
4980
+ if (
4981
+ session.downloads.size >= MAX_CONCURRENT_DOWNLOADS_PER_PEER ||
4982
+ this.hostUsedDownloadBytes + byteLength > MAX_STAGED_DOWNLOAD_BYTES
4983
+ ) {
4984
+ throw new FilesystemError(6, "staged download pool exhausted");
4985
+ }
4986
+ this.hostUsedDownloadBytes += byteLength;
4987
+ return byteLength;
4988
+ }
4989
+
4824
4990
  private async handleHostPeerReaddirPage(
4825
4991
  session: HostPeerSession,
4826
4992
  admittedTerm: bigint,
@@ -4831,40 +4997,35 @@ export class MultiTabBackend implements FilesystemBackend {
4831
4997
  "kind" | "hostTerm" | "sessionId" | "reqId" | "creditFrames" | "creditBytes"
4832
4998
  >,
4833
4999
  ) => void,
5000
+ budget: LeaseRenewalBudget,
4834
5001
  ): Promise<void> {
4835
5002
  const persistent = this.persistent!;
4836
5003
  const [remoteHandle, rawCookie, byteLength] = msg.args as [number, bigint, number];
4837
5004
  const tag = msg.responseCookieTag ? parseTerm(msg.responseCookieTag) : undefined;
4838
5005
  let bytes!: Uint8Array;
4839
5006
  let reserved = 0;
4840
- await this.enqueueHostSerial(() => {
4841
- this.assertHostOpStillValid(session, admittedTerm);
4842
- const remaining = Math.max(0, MAX_STAGED_DOWNLOAD_BYTES - this.hostUsedDownloadBytes);
4843
- bytes = persistent.fs.readdirPage(
4844
- remoteHandle,
4845
- rawCookie,
4846
- byteLength,
4847
- tag,
4848
- remaining,
4849
- MAX_STAGED_DOWNLOAD_BYTES,
4850
- );
4851
- if (bytes.byteLength > MAX_FRAME_BYTES) {
4852
- if (
4853
- session.downloads.size >= MAX_CONCURRENT_DOWNLOADS_PER_PEER ||
4854
- this.hostUsedDownloadBytes + bytes.byteLength > MAX_STAGED_DOWNLOAD_BYTES
4855
- ) {
4856
- throw new FilesystemError(6, "staged download pool exhausted");
4857
- }
4858
- reserved = bytes.byteLength;
4859
- this.hostUsedDownloadBytes += reserved;
4860
- }
4861
- });
5007
+ await this.retryPeerAfterLeaseRenewal(session, admittedTerm, budget, () =>
5008
+ this.enqueueHostSerial(() => {
5009
+ this.assertPeerAttempt(session, admittedTerm);
5010
+ const remaining = Math.max(0, MAX_STAGED_DOWNLOAD_BYTES - this.hostUsedDownloadBytes);
5011
+ bytes = persistent.fs.readdirPage(
5012
+ remoteHandle,
5013
+ rawCookie,
5014
+ byteLength,
5015
+ tag,
5016
+ remaining,
5017
+ MAX_STAGED_DOWNLOAD_BYTES,
5018
+ );
5019
+ reserved = this.reserveStagedDownload(session, bytes.byteLength);
5020
+ }),
5021
+ );
4862
5022
  try {
4863
5023
  await this.hooks.beforeHostReplyPublish?.(msg.op, msg.reqId);
4864
- this.assertHostOpStillValid(session, admittedTerm);
4865
- const transferReserved = reserved;
4866
- reserved = 0;
4867
- this.replyWithBytes(session, bytes, transferReserved, true, false, reply);
5024
+ await this.ensurePeerLeaseAndPublish(session, admittedTerm, budget, () => {
5025
+ const transferReserved = reserved;
5026
+ reserved = 0;
5027
+ this.replyWithBytes(session, bytes, transferReserved, true, false, reply);
5028
+ });
4868
5029
  } catch (error) {
4869
5030
  if (reserved > 0) {
4870
5031
  this.hostUsedDownloadBytes = Math.max(0, this.hostUsedDownloadBytes - reserved);
@@ -4883,44 +5044,75 @@ export class MultiTabBackend implements FilesystemBackend {
4883
5044
  "kind" | "hostTerm" | "sessionId" | "reqId" | "creditFrames" | "creditBytes"
4884
5045
  >,
4885
5046
  ) => void,
5047
+ budget: LeaseRenewalBudget,
4886
5048
  ): Promise<void> {
4887
5049
  const persistent = this.persistent!;
4888
5050
  const [remoteHandle, length, offset] = msg.args as [number, number, number];
4889
5051
  for (;;) {
4890
- this.assertHostOpStillValid(session, admittedTerm);
5052
+ await this.ensurePeerLease(session, admittedTerm, budget);
4891
5053
  const startVer = this.readVersion();
4892
- const prep = persistent.prepareDescriptorRead(
4893
- remoteHandle,
4894
- offset,
4895
- length,
4896
- () => session.revoked || this.hostTerm !== admittedTerm || !this.isLeaseValid(),
5054
+ const prep = persistent.prepareDescriptorRead(remoteHandle, offset, length, () =>
5055
+ this.peerAttemptStale(session, admittedTerm),
4897
5056
  );
4898
5057
  if (prep) {
4899
- const accepted = await this.revalidateColdReadBytes(prep, startVer, () =>
4900
- this.assertHostOpStillValid(session, admittedTerm),
4901
- );
5058
+ const accepted = await this.tryColdPeerRead(session, admittedTerm, budget, prep, startVer);
4902
5059
  if (accepted === undefined) continue;
4903
5060
  await this.hooks.beforeHostReplyPublish?.(msg.op, msg.reqId);
4904
- this.assertHostOpStillValid(session, admittedTerm);
4905
- reply({ ok: true, data: unsharedBytes(accepted), binary: true });
5061
+ await this.publishHostPeerReadBytes(session, admittedTerm, budget, accepted, reply);
4906
5062
  return;
4907
5063
  }
4908
5064
  let readBytes!: Uint8Array;
4909
- await this.enqueueHostSerial(() => {
4910
- this.assertHostOpStillValid(session, admittedTerm);
4911
- readBytes = persistent.execute(
4912
- "read",
4913
- [remoteHandle, length, offset],
4914
- new Uint8Array(),
4915
- ) as Uint8Array;
4916
- });
5065
+ await this.retryPeerAfterLeaseRenewal(session, admittedTerm, budget, () =>
5066
+ this.enqueueHostSerial(() => {
5067
+ this.assertPeerAttempt(session, admittedTerm);
5068
+ readBytes = persistent.execute(
5069
+ "read",
5070
+ [remoteHandle, length, offset],
5071
+ new Uint8Array(),
5072
+ ) as Uint8Array;
5073
+ }),
5074
+ );
4917
5075
  await this.hooks.beforeHostReplyPublish?.(msg.op, msg.reqId);
4918
- this.assertHostOpStillValid(session, admittedTerm);
4919
- reply({ ok: true, data: unsharedBytes(readBytes), binary: true });
5076
+ await this.publishHostPeerReadBytes(session, admittedTerm, budget, readBytes, reply);
4920
5077
  return;
4921
5078
  }
4922
5079
  }
4923
5080
 
5081
+ private async tryColdPeerRead(
5082
+ session: HostPeerSession,
5083
+ admittedTerm: bigint,
5084
+ budget: LeaseRenewalBudget,
5085
+ prep: Promise<Uint8Array>,
5086
+ startVer: string,
5087
+ ): Promise<Uint8Array | undefined> {
5088
+ try {
5089
+ return await this.revalidateColdReadBytes(prep, startVer, () =>
5090
+ this.assertPeerAttempt(session, admittedTerm),
5091
+ );
5092
+ } catch (error) {
5093
+ if (error !== LEASE_LAPSED) throw error;
5094
+ await this.ensurePeerLease(session, admittedTerm, budget);
5095
+ return undefined;
5096
+ }
5097
+ }
5098
+
5099
+ private publishHostPeerReadBytes(
5100
+ session: HostPeerSession,
5101
+ admittedTerm: bigint,
5102
+ budget: LeaseRenewalBudget,
5103
+ bytes: Uint8Array,
5104
+ reply: (
5105
+ partial: Omit<
5106
+ Extract<PeerMessage, { kind: "res" }>,
5107
+ "kind" | "hostTerm" | "sessionId" | "reqId" | "creditFrames" | "creditBytes"
5108
+ >,
5109
+ ) => void,
5110
+ ): Promise<void> {
5111
+ return this.ensurePeerLeaseAndPublish(session, admittedTerm, budget, () => {
5112
+ reply({ ok: true, data: unsharedBytes(bytes), binary: true });
5113
+ });
5114
+ }
5115
+
4924
5116
  private async revalidateColdReadBytes(
4925
5117
  prep: Promise<Uint8Array>,
4926
5118
  startVer: string,
@@ -5001,29 +5193,31 @@ export class MultiTabBackend implements FilesystemBackend {
5001
5193
  persistent: PersistentBackend,
5002
5194
  msg: Extract<PeerMessage, { kind: "req" }>,
5003
5195
  data: Uint8Array,
5196
+ budget: LeaseRenewalBudget,
5004
5197
  ): Promise<unknown> {
5005
5198
  for (;;) {
5006
- this.assertHostOpStillValid(session, admittedTerm);
5199
+ await this.ensurePeerLease(session, admittedTerm, budget);
5007
5200
  const preparing = persistent.prepare(msg.op, msg.args);
5008
5201
  if (preparing) await preparing;
5009
- this.assertHostOpStillValid(session, admittedTerm);
5202
+ await this.ensurePeerLease(session, admittedTerm, budget);
5010
5203
 
5011
5204
  let result: unknown;
5012
5205
  let dirtyRetryChange: number | undefined;
5013
- await this.enqueueHostSerial(() => {
5014
- this.assertHostOpStillValid(session, admittedTerm);
5015
- const step = this.executePersistentOrDirtyRetry(persistent, msg.op, msg.args, data);
5016
- if (step.retryChange !== undefined) {
5017
- dirtyRetryChange = step.retryChange;
5018
- return;
5019
- }
5020
- result = step.result;
5021
- });
5206
+ await this.retryPeerAfterLeaseRenewal(session, admittedTerm, budget, () =>
5207
+ this.enqueueHostSerial(() => {
5208
+ this.assertPeerAttempt(session, admittedTerm);
5209
+ const step = this.executePersistentOrDirtyRetry(persistent, msg.op, msg.args, data);
5210
+ if (step.retryChange !== undefined) {
5211
+ dirtyRetryChange = step.retryChange;
5212
+ return;
5213
+ }
5214
+ result = step.result;
5215
+ }),
5216
+ );
5022
5217
 
5023
5218
  if (dirtyRetryChange !== undefined) {
5024
- await persistent.waitForDirtyCapacity(
5025
- dirtyRetryChange,
5026
- () => session.revoked || this.hostTerm !== admittedTerm || !this.isLeaseValid(),
5219
+ await persistent.waitForDirtyCapacity(dirtyRetryChange, () =>
5220
+ this.peerAttemptStale(session, admittedTerm),
5027
5221
  );
5028
5222
  continue;
5029
5223
  }
@@ -5042,13 +5236,14 @@ export class MultiTabBackend implements FilesystemBackend {
5042
5236
  "kind" | "hostTerm" | "sessionId" | "reqId" | "creditFrames" | "creditBytes"
5043
5237
  >,
5044
5238
  ) => void,
5239
+ budget: LeaseRenewalBudget,
5045
5240
  ): Promise<void> {
5046
5241
  const persistent = this.persistent!;
5047
5242
  const result = MUTATION_OPS.has(msg.op)
5048
5243
  ? await this.barrier.runMutation(() =>
5049
- this.executeHostPeerGeneralLoop(session, admittedTerm, persistent, msg, data),
5244
+ this.executeHostPeerGeneralLoop(session, admittedTerm, persistent, msg, data, budget),
5050
5245
  )
5051
- : await this.executeHostPeerGeneralLoop(session, admittedTerm, persistent, msg, data);
5246
+ : await this.executeHostPeerGeneralLoop(session, admittedTerm, persistent, msg, data, budget);
5052
5247
 
5053
5248
  const { wireValue, mintedTokens } = this.wrapHostPeerResult(
5054
5249
  session,
@@ -5058,21 +5253,17 @@ export class MultiTabBackend implements FilesystemBackend {
5058
5253
  );
5059
5254
 
5060
5255
  await this.hooks.beforeHostReplyPublish?.(msg.op, msg.reqId);
5061
- if (
5062
- session.revoked ||
5063
- this.terminalFailure ||
5064
- !this.isLeaseValid() ||
5065
- this.hostTerm !== admittedTerm ||
5066
- persistent.isTerminallyFailed()
5067
- ) {
5256
+ try {
5257
+ await this.ensurePeerLeaseAndPublish(session, admittedTerm, budget, () => {
5258
+ if (wireValue instanceof Uint8Array) {
5259
+ reply({ ok: true, data: unsharedBytes(wireValue), binary: true });
5260
+ } else {
5261
+ reply({ ok: true, value: wireValue });
5262
+ }
5263
+ });
5264
+ } catch (error) {
5068
5265
  this.rollbackMintedPeerTokens(session, persistent, mintedTokens);
5069
- this.assertHostOpStillValid(session, admittedTerm);
5070
- }
5071
-
5072
- if (wireValue instanceof Uint8Array) {
5073
- reply({ ok: true, data: unsharedBytes(wireValue), binary: true });
5074
- } else {
5075
- reply({ ok: true, value: wireValue });
5266
+ throw error;
5076
5267
  }
5077
5268
  }
5078
5269
 
@@ -5151,10 +5342,11 @@ export class MultiTabBackend implements FilesystemBackend {
5151
5342
  "kind" | "hostTerm" | "sessionId" | "reqId" | "creditFrames" | "creditBytes"
5152
5343
  >,
5153
5344
  ) => void,
5345
+ budget: LeaseRenewalBudget,
5154
5346
  ): Promise<void> {
5155
5347
  const persistent = this.persistent!;
5156
5348
  for (;;) {
5157
- this.assertHostOpStillValid(session, admittedTerm);
5349
+ await this.ensurePeerLease(session, admittedTerm, budget);
5158
5350
  const attempt = { handle: undefined as number | undefined, reservedBytes: 0, fileId: 0n };
5159
5351
  const releaseAttempt = () => {
5160
5352
  if (attempt.reservedBytes > 0) {
@@ -5177,11 +5369,11 @@ export class MultiTabBackend implements FilesystemBackend {
5177
5369
  admittedTerm,
5178
5370
  path,
5179
5371
  attempt,
5372
+ budget,
5180
5373
  );
5181
5374
  if (!admitted) {
5182
5375
  await this.hooks.beforeHostReplyPublish?.("readFile", reqId);
5183
- this.assertHostOpStillValid(session, admittedTerm);
5184
- reply({ ok: true, value: undefined });
5376
+ await this.publishHostPeerMissingFile(session, admittedTerm, budget, reply);
5185
5377
  return;
5186
5378
  }
5187
5379
 
@@ -5192,6 +5384,7 @@ export class MultiTabBackend implements FilesystemBackend {
5192
5384
  admittedTerm,
5193
5385
  path,
5194
5386
  attempt,
5387
+ budget,
5195
5388
  );
5196
5389
  if (!stillSame) {
5197
5390
  releaseAttempt();
@@ -5207,6 +5400,7 @@ export class MultiTabBackend implements FilesystemBackend {
5207
5400
  admittedTerm,
5208
5401
  path,
5209
5402
  attempt,
5403
+ budget,
5210
5404
  );
5211
5405
  if (outcome.kind === "restart") {
5212
5406
  releaseAttempt();
@@ -5215,19 +5409,21 @@ export class MultiTabBackend implements FilesystemBackend {
5215
5409
  if (outcome.kind === "missing") {
5216
5410
  releaseAttempt();
5217
5411
  await this.hooks.beforeHostReplyPublish?.("readFile", reqId);
5218
- this.assertHostOpStillValid(session, admittedTerm);
5219
- reply({ ok: true, value: undefined });
5412
+ await this.publishHostPeerMissingFile(session, admittedTerm, budget, reply);
5220
5413
  return;
5221
5414
  }
5222
5415
 
5223
5416
  persistent.release(attempt.handle!);
5224
5417
  attempt.handle = undefined;
5225
5418
  await this.hooks.beforeHostReplyPublish?.("readFile", reqId);
5226
- this.assertHostOpStillValid(session, admittedTerm);
5227
-
5228
- const transferReserved = attempt.reservedBytes;
5229
- attempt.reservedBytes = 0;
5230
- this.replyWithBytes(session, outcome.bytes, transferReserved, true, false, reply);
5419
+ await this.publishHostPeerStagedBytes(
5420
+ session,
5421
+ admittedTerm,
5422
+ budget,
5423
+ attempt,
5424
+ outcome.bytes,
5425
+ reply,
5426
+ );
5231
5427
  return;
5232
5428
  } catch (error) {
5233
5429
  releaseAttempt();
@@ -5236,26 +5432,65 @@ export class MultiTabBackend implements FilesystemBackend {
5236
5432
  }
5237
5433
  }
5238
5434
 
5435
+ private publishHostPeerMissingFile(
5436
+ session: HostPeerSession,
5437
+ admittedTerm: bigint,
5438
+ budget: LeaseRenewalBudget,
5439
+ reply: (
5440
+ partial: Omit<
5441
+ Extract<PeerMessage, { kind: "res" }>,
5442
+ "kind" | "hostTerm" | "sessionId" | "reqId" | "creditFrames" | "creditBytes"
5443
+ >,
5444
+ ) => void,
5445
+ ): Promise<void> {
5446
+ return this.ensurePeerLeaseAndPublish(session, admittedTerm, budget, () => {
5447
+ reply({ ok: true, value: undefined });
5448
+ });
5449
+ }
5450
+
5451
+ private publishHostPeerStagedBytes(
5452
+ session: HostPeerSession,
5453
+ admittedTerm: bigint,
5454
+ budget: LeaseRenewalBudget,
5455
+ attempt: { reservedBytes: number },
5456
+ bytes: Uint8Array,
5457
+ reply: (
5458
+ partial: Omit<
5459
+ Extract<PeerMessage, { kind: "res" }>,
5460
+ "kind" | "hostTerm" | "sessionId" | "reqId" | "creditFrames" | "creditBytes"
5461
+ >,
5462
+ ) => void,
5463
+ ): Promise<void> {
5464
+ return this.ensurePeerLeaseAndPublish(session, admittedTerm, budget, () => {
5465
+ const transferReserved = attempt.reservedBytes;
5466
+ attempt.reservedBytes = 0;
5467
+ this.replyWithBytes(session, bytes, transferReserved, true, false, reply);
5468
+ });
5469
+ }
5470
+
5239
5471
  private async admitPeerReadFile(
5240
5472
  persistent: PersistentBackend,
5241
5473
  session: HostPeerSession,
5242
5474
  admittedTerm: bigint,
5243
5475
  path: string,
5244
5476
  attempt: { handle: number | undefined; reservedBytes: number; fileId: bigint },
5477
+ budget: LeaseRenewalBudget,
5245
5478
  ): Promise<boolean> {
5246
5479
  let found = false;
5247
- await this.enqueueHostSerial(() => {
5248
- this.assertHostOpStillValid(session, admittedTerm);
5249
- const node = persistent.resolveNodePublic(path);
5250
- if (!node || node.kind !== "file") return;
5251
- const h = persistent.fs.handleForNode(node);
5252
- persistent.retain(h);
5253
- attempt.handle = h;
5254
- attempt.fileId = persistent.ensureIdentity(node).id;
5255
- const estimatedSize = persistent.shared.info(h)?.size ?? node.size ?? node.data.byteLength;
5256
- attempt.reservedBytes = this.adjustPeerDownloadBudget(session, 0, estimatedSize, false);
5257
- found = true;
5258
- });
5480
+ await this.retryPeerAfterLeaseRenewal(session, admittedTerm, budget, () =>
5481
+ this.enqueueHostSerial(() => {
5482
+ this.assertPeerAttempt(session, admittedTerm);
5483
+ const node = persistent.resolveNodePublic(path);
5484
+ if (!node || node.kind !== "file") return;
5485
+ const h = persistent.fs.handleForNode(node);
5486
+ persistent.retain(h);
5487
+ attempt.handle = h;
5488
+ attempt.fileId = persistent.ensureIdentity(node).id;
5489
+ const estimatedSize = persistent.shared.info(h)?.size ?? node.size ?? node.data.byteLength;
5490
+ attempt.reservedBytes = this.adjustPeerDownloadBudget(session, 0, estimatedSize, false);
5491
+ found = true;
5492
+ }),
5493
+ );
5259
5494
  return found;
5260
5495
  }
5261
5496
 
@@ -5265,23 +5500,26 @@ export class MultiTabBackend implements FilesystemBackend {
5265
5500
  admittedTerm: bigint,
5266
5501
  path: string,
5267
5502
  attempt: { handle: number | undefined; reservedBytes: number; fileId: bigint },
5503
+ budget: LeaseRenewalBudget,
5268
5504
  ): Promise<boolean> {
5269
5505
  let valid = false;
5270
- await this.enqueueHostSerial(() => {
5271
- this.assertHostOpStillValid(session, admittedTerm);
5272
- const current = persistent.resolveNodePublic(path);
5273
- if (!current || current.kind !== "file") return;
5274
- if (persistent.ensureIdentity(current).id !== attempt.fileId) return;
5275
- const currentSize =
5276
- persistent.shared.info(attempt.handle!)?.size ?? current.size ?? current.data.byteLength;
5277
- attempt.reservedBytes = this.adjustPeerDownloadBudget(
5278
- session,
5279
- attempt.reservedBytes,
5280
- currentSize,
5281
- false,
5282
- );
5283
- valid = true;
5284
- });
5506
+ await this.retryPeerAfterLeaseRenewal(session, admittedTerm, budget, () =>
5507
+ this.enqueueHostSerial(() => {
5508
+ this.assertPeerAttempt(session, admittedTerm);
5509
+ const current = persistent.resolveNodePublic(path);
5510
+ if (!current || current.kind !== "file") return;
5511
+ if (persistent.ensureIdentity(current).id !== attempt.fileId) return;
5512
+ const currentSize =
5513
+ persistent.shared.info(attempt.handle!)?.size ?? current.size ?? current.data.byteLength;
5514
+ attempt.reservedBytes = this.adjustPeerDownloadBudget(
5515
+ session,
5516
+ attempt.reservedBytes,
5517
+ currentSize,
5518
+ false,
5519
+ );
5520
+ valid = true;
5521
+ }),
5522
+ );
5285
5523
  return valid;
5286
5524
  }
5287
5525
 
@@ -5291,33 +5529,36 @@ export class MultiTabBackend implements FilesystemBackend {
5291
5529
  admittedTerm: bigint,
5292
5530
  path: string,
5293
5531
  attempt: { handle: number | undefined; reservedBytes: number; fileId: bigint },
5532
+ budget: LeaseRenewalBudget,
5294
5533
  ): Promise<{ kind: "restart" } | { kind: "missing" } | { kind: "bytes"; bytes: Uint8Array }> {
5295
5534
  let outcome: { kind: "restart" } | { kind: "missing" } | { kind: "bytes"; bytes: Uint8Array } =
5296
5535
  {
5297
5536
  kind: "missing",
5298
5537
  };
5299
- await this.enqueueHostSerial(() => {
5300
- this.assertHostOpStillValid(session, admittedTerm);
5301
- const current = persistent.resolveNodePublic(path);
5302
- if (!current || current.kind !== "file") {
5303
- outcome = { kind: "missing" };
5304
- return;
5305
- }
5306
- if (persistent.ensureIdentity(current).id !== attempt.fileId) {
5307
- outcome = { kind: "restart" };
5308
- return;
5309
- }
5310
- const actualSize = persistent.shared.info(attempt.handle!)!.size;
5311
- attempt.reservedBytes = this.adjustPeerDownloadBudget(
5312
- session,
5313
- attempt.reservedBytes,
5314
- actualSize,
5315
- true,
5316
- );
5317
- const out = new Uint8Array(actualSize);
5318
- const bytes = out.subarray(0, persistent.shared.read(attempt.handle!, [out], 0));
5319
- outcome = { kind: "bytes", bytes };
5320
- });
5538
+ await this.retryPeerAfterLeaseRenewal(session, admittedTerm, budget, () =>
5539
+ this.enqueueHostSerial(() => {
5540
+ this.assertPeerAttempt(session, admittedTerm);
5541
+ const current = persistent.resolveNodePublic(path);
5542
+ if (!current || current.kind !== "file") {
5543
+ outcome = { kind: "missing" };
5544
+ return;
5545
+ }
5546
+ if (persistent.ensureIdentity(current).id !== attempt.fileId) {
5547
+ outcome = { kind: "restart" };
5548
+ return;
5549
+ }
5550
+ const actualSize = persistent.shared.info(attempt.handle!)!.size;
5551
+ attempt.reservedBytes = this.adjustPeerDownloadBudget(
5552
+ session,
5553
+ attempt.reservedBytes,
5554
+ actualSize,
5555
+ true,
5556
+ );
5557
+ const out = new Uint8Array(actualSize);
5558
+ const bytes = out.subarray(0, persistent.shared.read(attempt.handle!, [out], 0));
5559
+ outcome = { kind: "bytes", bytes };
5560
+ }),
5561
+ );
5321
5562
  return outcome;
5322
5563
  }
5323
5564
 
@@ -5334,53 +5575,43 @@ export class MultiTabBackend implements FilesystemBackend {
5334
5575
  "kind" | "hostTerm" | "sessionId" | "reqId" | "creditFrames" | "creditBytes"
5335
5576
  >,
5336
5577
  ) => void,
5578
+ budget: LeaseRenewalBudget,
5337
5579
  ): Promise<void> {
5338
5580
  const persistent = this.persistent!;
5339
5581
  let built!: { bytes: Uint8Array<ArrayBuffer>; reservedBytes: number };
5340
5582
 
5341
- await this.enqueueHostSerial(() => {
5342
- this.assertHostOpStillValid(session, admittedTerm);
5343
- const builder = new BoundedWireBuilder(
5344
- MAX_STAGED_DOWNLOAD_BYTES,
5345
- (delta) => {
5346
- if (this.hostUsedDownloadBytes + delta > MAX_STAGED_DOWNLOAD_BYTES) return false;
5347
- this.hostUsedDownloadBytes += delta;
5348
- return true;
5349
- },
5350
- (all) => {
5351
- this.hostUsedDownloadBytes = Math.max(0, this.hostUsedDownloadBytes - all);
5352
- },
5353
- );
5354
- try {
5355
- this.encodeBoundedWireOp(persistent, builder, op, args);
5356
- built = builder.finish();
5357
- } catch (error) {
5358
- builder.abort();
5359
- throw error;
5360
- }
5361
- });
5583
+ await this.retryPeerAfterLeaseRenewal(session, admittedTerm, budget, () =>
5584
+ this.enqueueHostSerial(() => {
5585
+ this.assertPeerAttempt(session, admittedTerm);
5586
+ const builder = new BoundedWireBuilder(
5587
+ MAX_STAGED_DOWNLOAD_BYTES,
5588
+ (delta) => {
5589
+ if (this.hostUsedDownloadBytes + delta > MAX_STAGED_DOWNLOAD_BYTES) return false;
5590
+ this.hostUsedDownloadBytes += delta;
5591
+ return true;
5592
+ },
5593
+ (all) => {
5594
+ this.hostUsedDownloadBytes = Math.max(0, this.hostUsedDownloadBytes - all);
5595
+ },
5596
+ );
5597
+ try {
5598
+ this.encodeBoundedWireOp(persistent, builder, op, args);
5599
+ built = builder.finish();
5600
+ } catch (error) {
5601
+ builder.abort();
5602
+ throw error;
5603
+ }
5604
+ }),
5605
+ );
5362
5606
 
5363
5607
  let remainingReserved = built.reservedBytes;
5364
5608
  try {
5365
5609
  await this.hooks.beforeHostReplyPublish?.(op, reqId);
5366
- this.assertHostOpStillValid(session, admittedTerm);
5367
-
5368
- if (built.bytes.byteLength <= MAX_FRAME_BYTES) {
5369
- if (remainingReserved > 0) {
5370
- this.hostUsedDownloadBytes = Math.max(0, this.hostUsedDownloadBytes - remainingReserved);
5371
- remainingReserved = 0;
5372
- }
5373
- reply({ ok: true, data: unsharedBytes(built.bytes), packed: true });
5374
- return;
5375
- }
5376
-
5377
- if (session.downloads.size >= MAX_CONCURRENT_DOWNLOADS_PER_PEER) {
5378
- throw new FilesystemError(6, "staged download pool exhausted");
5379
- }
5380
-
5381
- const transferReserved = remainingReserved;
5382
- remainingReserved = 0;
5383
- this.replyWithBytes(session, built.bytes, transferReserved, false, true, reply);
5610
+ await this.ensurePeerLeaseAndPublish(session, admittedTerm, budget, () => {
5611
+ const reserved = remainingReserved;
5612
+ remainingReserved = 0;
5613
+ this.publishBoundedWireRead(session, built.bytes, reserved, reply);
5614
+ });
5384
5615
  } catch (error) {
5385
5616
  if (remainingReserved > 0) {
5386
5617
  this.hostUsedDownloadBytes = Math.max(0, this.hostUsedDownloadBytes - remainingReserved);
@@ -5389,6 +5620,33 @@ export class MultiTabBackend implements FilesystemBackend {
5389
5620
  }
5390
5621
  }
5391
5622
 
5623
+ private publishBoundedWireRead(
5624
+ session: HostPeerSession,
5625
+ bytes: Uint8Array<ArrayBuffer>,
5626
+ reserved: number,
5627
+ reply: (
5628
+ partial: Omit<
5629
+ Extract<PeerMessage, { kind: "res" }>,
5630
+ "kind" | "hostTerm" | "sessionId" | "reqId" | "creditFrames" | "creditBytes"
5631
+ >,
5632
+ ) => void,
5633
+ ): void {
5634
+ if (bytes.byteLength <= MAX_FRAME_BYTES) {
5635
+ if (reserved > 0) {
5636
+ this.hostUsedDownloadBytes = Math.max(0, this.hostUsedDownloadBytes - reserved);
5637
+ }
5638
+ reply({ ok: true, data: unsharedBytes(bytes), packed: true });
5639
+ return;
5640
+ }
5641
+ if (session.downloads.size >= MAX_CONCURRENT_DOWNLOADS_PER_PEER) {
5642
+ if (reserved > 0) {
5643
+ this.hostUsedDownloadBytes = Math.max(0, this.hostUsedDownloadBytes - reserved);
5644
+ }
5645
+ throw new FilesystemError(6, "staged download pool exhausted");
5646
+ }
5647
+ this.replyWithBytes(session, bytes, reserved, false, true, reply);
5648
+ }
5649
+
5392
5650
  private encodeBoundedWireOp(
5393
5651
  persistent: PersistentBackend,
5394
5652
  builder: BoundedWireBuilder,
@@ -7325,7 +7583,8 @@ export class MultiTabBackend implements FilesystemBackend {
7325
7583
  case "readdir":
7326
7584
  case "readdirPage":
7327
7585
  case "resolve":
7328
- case "realpath": {
7586
+ case "realpath":
7587
+ case "probe": {
7329
7588
  const remote = mapHandle(args[0]);
7330
7589
  if (remote === undefined) return undefined;
7331
7590
  return [remote, ...args.slice(1)];