@waffle-os/runtime 0.0.151 → 0.0.152

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.
@@ -151,6 +151,27 @@ async function raceWithAbort(promise, signal, cancelled) {
151
151
  waiter.cleanup();
152
152
  }
153
153
  }
154
+ async function awaitUnlessCancelled(promise, cancelled) {
155
+ if (!cancelled)
156
+ return promise;
157
+ if (cancelled()) {
158
+ promise.catch(() => {});
159
+ throw abortError();
160
+ }
161
+ let poll;
162
+ try {
163
+ return await new Promise((resolve, reject) => {
164
+ promise.then(resolve, reject);
165
+ poll = setInterval(() => {
166
+ if (cancelled())
167
+ reject(abortError());
168
+ }, 20);
169
+ });
170
+ } finally {
171
+ if (poll)
172
+ clearInterval(poll);
173
+ }
174
+ }
154
175
  function linkAbortSignals(...signals) {
155
176
  const controller = new AbortController;
156
177
  const listeners = [];
@@ -247,6 +268,34 @@ function defaultOpenStorage(implementation, name, options) {
247
268
  });
248
269
  }
249
270
 
271
+ class BarrierGate {
272
+ mutations = new Set;
273
+ activeBarrier;
274
+ runMutation(fn) {
275
+ const barrier = this.activeBarrier;
276
+ const result = barrier ? barrier.then(fn) : fn();
277
+ const settled = result.then(() => {}, () => {});
278
+ this.mutations.add(settled);
279
+ settled.finally(() => {
280
+ this.mutations.delete(settled);
281
+ });
282
+ return result;
283
+ }
284
+ runBarrier(fn) {
285
+ const prior = Array.from(this.mutations);
286
+ if (this.activeBarrier)
287
+ prior.push(this.activeBarrier);
288
+ const result = prior.length ? Promise.allSettled(prior).then(fn) : fn();
289
+ const settled = result.then(() => {}, () => {});
290
+ this.activeBarrier = settled;
291
+ settled.finally(() => {
292
+ if (this.activeBarrier === settled)
293
+ this.activeBarrier = undefined;
294
+ });
295
+ return result;
296
+ }
297
+ }
298
+
250
299
  export class MultiTabBackend {
251
300
  options;
252
301
  scope;
@@ -298,6 +347,7 @@ export class MultiTabBackend {
298
347
  persistent;
299
348
  watchService;
300
349
  hostQueue = Promise.resolve();
350
+ barrier = new BarrierGate;
301
351
  hostAdmittedCount = 0;
302
352
  hostAdmittedZeroWaiters = [];
303
353
  hostPeers = new Map;
@@ -336,6 +386,7 @@ export class MultiTabBackend {
336
386
  peerPendingUnpins = new Set;
337
387
  peerPendingWatchAcks = new Map;
338
388
  peerPendingWatchCloses = new Set;
389
+ peerPendingUploadAborts = new Set;
339
390
  supportsSockets = false;
340
391
  asyncErrorsAreClientResults = true;
341
392
  peerFailoverInFlight;
@@ -541,22 +592,35 @@ export class MultiTabBackend {
541
592
  return;
542
593
  if (UNSUPPORTED_ATTACH_OPS.has(operation))
543
594
  return;
544
- if (operation === "flush" || operation === "sync")
595
+ if (operation === "flush" || operation === "sync" || MUTATION_OPS.has(operation))
545
596
  return;
546
597
  const translated = this.translateArgsToHost(operation, args);
547
598
  if (!translated)
548
599
  return;
549
600
  return this.persistent.prepare(operation, translated);
550
601
  }
551
- execute(operation, args, data) {
602
+ execute(operation, args, data, cancelled) {
552
603
  if (UNSUPPORTED_ATTACH_OPS.has(operation)) {
553
604
  throw new FilesystemError(58, `${operation} is not supported in whenBusy: "attach"`);
554
605
  }
555
606
  if (this.terminalFailure)
556
607
  throw new FilesystemError(29, describeReason(this.terminalFailure.reason));
557
- if (this.fenceLossInFlight && !this.disposing && !this.externalOwnershipLostNotified) {
558
- return this.executeAfterFenceLoss(operation, args, data);
608
+ const awaitingFenceLoss = !!this.fenceLossInFlight && !this.disposing && !this.externalOwnershipLostNotified;
609
+ if (!awaitingFenceLoss) {
610
+ this.assertLocalExecuteAdmissible();
611
+ }
612
+ if (operation === "flush" || operation === "sync") {
613
+ return this.barrier.runBarrier(() => this.runLocalExecute(operation, args, data, cancelled));
614
+ }
615
+ if (MUTATION_OPS.has(operation)) {
616
+ return this.barrier.runMutation(() => this.runLocalExecute(operation, args, data, cancelled));
559
617
  }
618
+ if (awaitingFenceLoss) {
619
+ return this.runLocalExecute(operation, args, data, cancelled);
620
+ }
621
+ return this.dispatchLocalRead(operation, args, data, cancelled);
622
+ }
623
+ assertLocalExecuteAdmissible() {
560
624
  if (this.ownershipLost)
561
625
  throw new FilesystemError(11, "filesystem ownership lost");
562
626
  if (this.disposing) {
@@ -564,6 +628,11 @@ export class MultiTabBackend {
564
628
  throw new FilesystemError(11, "filesystem is disposing");
565
629
  }
566
630
  }
631
+ if (this.role !== "host" && this.role !== "peer" && this.role !== "failover" && this.role !== "waiting") {
632
+ throw new FilesystemError(11, "filesystem backend is closed");
633
+ }
634
+ }
635
+ dispatchLocalRead(operation, args, data, cancelled) {
567
636
  let effectiveArgs = args;
568
637
  let responseCookieTag;
569
638
  if (operation === "readdirPage") {
@@ -575,12 +644,22 @@ export class MultiTabBackend {
575
644
  responseCookieTag = this.dirEpoch;
576
645
  }
577
646
  if (this.role === "host") {
578
- return this.executeLocalOnHost(operation, effectiveArgs, data, responseCookieTag);
647
+ return this.executeLocalOnHost(operation, effectiveArgs, data, responseCookieTag, cancelled);
579
648
  }
580
- if (this.role === "peer" || this.role === "failover" || this.role === "waiting") {
581
- return this.executeOnPeer(operation, effectiveArgs, data, responseCookieTag);
649
+ return this.executeOnPeer(operation, effectiveArgs, data, responseCookieTag, cancelled);
650
+ }
651
+ async runLocalExecute(operation, args, data, cancelled) {
652
+ if (cancelled?.())
653
+ throw new FilesystemError(11, "operation cancelled");
654
+ if (this.fenceLossInFlight && !this.disposing && !this.externalOwnershipLostNotified) {
655
+ await this.awaitPendingFenceLoss(cancelled);
582
656
  }
583
- throw new FilesystemError(11, "filesystem backend is closed");
657
+ if (cancelled?.())
658
+ throw new FilesystemError(11, "operation cancelled");
659
+ if (this.terminalFailure)
660
+ throw new FilesystemError(29, describeReason(this.terminalFailure.reason));
661
+ this.assertLocalExecuteAdmissible();
662
+ return this.dispatchLocalRead(operation, args, data, cancelled);
584
663
  }
585
664
  async awaitPendingFenceLoss(cancelled) {
586
665
  const signal = this.disposeAbort.signal;
@@ -621,11 +700,10 @@ export class MultiTabBackend {
621
700
  await this.awaitNextFailoverWake(signal, cancelled);
622
701
  }
623
702
  }
624
- async executeAfterFenceLoss(operation, args, data) {
625
- await this.awaitPendingFenceLoss();
626
- return this.execute(operation, args, data);
703
+ flush(target) {
704
+ return this.barrier.runBarrier(() => this.runLocalFlush(target));
627
705
  }
628
- async flush(target) {
706
+ async runLocalFlush(target) {
629
707
  if (this.fenceLossInFlight && !this.disposing && !this.externalOwnershipLostNotified) {
630
708
  await this.awaitPendingFenceLoss();
631
709
  }
@@ -649,6 +727,8 @@ export class MultiTabBackend {
649
727
  }
650
728
  this.enterHostAdmitted();
651
729
  try {
730
+ await this.hostQueue;
731
+ this.assertHostReadyForLocal(admittedTerm);
652
732
  await this.persistent.flush(resolvedTarget);
653
733
  } finally {
654
734
  this.leaveHostAdmitted();
@@ -1879,6 +1959,7 @@ export class MultiTabBackend {
1879
1959
  this.peerPendingUnpins.clear();
1880
1960
  this.peerPendingWatchAcks.clear();
1881
1961
  this.peerPendingWatchCloses.clear();
1962
+ this.peerPendingUploadAborts.clear();
1882
1963
  const attachedGate = Promise.withResolvers();
1883
1964
  let newerHostReady = false;
1884
1965
  const onControl = (msg) => {
@@ -1980,8 +2061,7 @@ export class MultiTabBackend {
1980
2061
  }
1981
2062
  if (this.peerSessionId !== sessionId || !this.peerAttached)
1982
2063
  return false;
1983
- this.drainPeerRetryQueue();
1984
- this.drainPeerFailoverQueue();
2064
+ this.drainPeerRetryAndFailoverQueues();
1985
2065
  return true;
1986
2066
  } finally {
1987
2067
  if (retryTimer)
@@ -2661,6 +2741,7 @@ export class MultiTabBackend {
2661
2741
  pendingSettledUnpins: [],
2662
2742
  pendingSettledWatchAcks: [],
2663
2743
  pendingSettledWatchCloses: [],
2744
+ pendingSettledUploadAborts: [],
2664
2745
  latestWakeSeq: 0,
2665
2746
  wakeDirty: false,
2666
2747
  lastActivityAt: Date.now(),
@@ -2853,6 +2934,7 @@ export class MultiTabBackend {
2853
2934
  const settledUnpins = [];
2854
2935
  const settledWatchAcks = [];
2855
2936
  const settledWatchCloses = [];
2937
+ const settledUploadAborts = [];
2856
2938
  for (const token of msg.pendingUnpins ?? []) {
2857
2939
  this.hostProcessUnpin(session, token, false);
2858
2940
  settledUnpins.push(token);
@@ -2865,6 +2947,10 @@ export class MultiTabBackend {
2865
2947
  this.hostProcessWatchClose(session, watchId, false);
2866
2948
  settledWatchCloses.push(watchId);
2867
2949
  }
2950
+ for (const uploadId of msg.pendingUploadAborts ?? []) {
2951
+ this.hostProcessUploadAbort(session, uploadId, false);
2952
+ settledUploadAborts.push(uploadId);
2953
+ }
2868
2954
  const slot = this.hostCreditSlots.get(session.peerId);
2869
2955
  const creditLimit = slot ? this.slotCreditLimit(slot) : { frames: MIN_PEER_FRAMES, bytes: MIN_PEER_BYTES };
2870
2956
  this.sendPeerFrame(session.peerId, session.channel, {
@@ -2877,6 +2963,7 @@ export class MultiTabBackend {
2877
2963
  ...settledUnpins.length ? { settledUnpins } : {},
2878
2964
  ...settledWatchAcks.length ? { settledWatchAcks } : {},
2879
2965
  ...settledWatchCloses.length ? { settledWatchCloses } : {},
2966
+ ...settledUploadAborts.length ? { settledUploadAborts } : {},
2880
2967
  creditLimit,
2881
2968
  hostState: this.hostHealthState()
2882
2969
  });
@@ -2886,6 +2973,10 @@ export class MultiTabBackend {
2886
2973
  this.handleHostChunkPut(session, msg);
2887
2974
  return;
2888
2975
  }
2976
+ case "chunk-abort": {
2977
+ this.hostProcessUploadAbort(session, msg.uploadId, true);
2978
+ return;
2979
+ }
2889
2980
  case "chunk-get": {
2890
2981
  this.handleHostChunkGet(session, msg);
2891
2982
  return;
@@ -2932,8 +3023,15 @@ export class MultiTabBackend {
2932
3023
  this.maybeScheduleHostSettledFlush(session);
2933
3024
  }
2934
3025
  }
3026
+ hostProcessUploadAbort(session, uploadId, batch = true) {
3027
+ this.discardHostStagedUpload(session, uploadId);
3028
+ if (batch) {
3029
+ session.pendingSettledUploadAborts.push(uploadId);
3030
+ this.maybeScheduleHostSettledFlush(session);
3031
+ }
3032
+ }
2935
3033
  maybeScheduleHostSettledFlush(session) {
2936
- const total = session.pendingSettledUnpins.length + session.pendingSettledWatchAcks.length + session.pendingSettledWatchCloses.length;
3034
+ const total = session.pendingSettledUnpins.length + session.pendingSettledWatchAcks.length + session.pendingSettledWatchCloses.length + session.pendingSettledUploadAborts.length;
2937
3035
  if (total >= SETTLEMENT_BATCH_SIZE) {
2938
3036
  this.flushHostSettled(session);
2939
3037
  return;
@@ -2952,18 +3050,20 @@ export class MultiTabBackend {
2952
3050
  }
2953
3051
  if (session.revoked)
2954
3052
  return;
2955
- if (!session.pendingSettledUnpins.length && !session.pendingSettledWatchAcks.length && !session.pendingSettledWatchCloses.length)
3053
+ if (!session.pendingSettledUnpins.length && !session.pendingSettledWatchAcks.length && !session.pendingSettledWatchCloses.length && !session.pendingSettledUploadAborts.length)
2956
3054
  return;
2957
3055
  const unpins = session.pendingSettledUnpins.splice(0);
2958
3056
  const watchAcks = session.pendingSettledWatchAcks.splice(0);
2959
3057
  const watchCloses = session.pendingSettledWatchCloses.splice(0);
3058
+ const uploadAborts = session.pendingSettledUploadAborts.splice(0);
2960
3059
  this.sendPeerFrame(session.peerId, session.channel, {
2961
3060
  kind: "settled",
2962
3061
  hostTerm: formatTerm(session.hostTerm),
2963
3062
  sessionId: session.sessionId,
2964
3063
  ...unpins.length ? { unpins } : {},
2965
3064
  ...watchAcks.length ? { watchAcks } : {},
2966
- ...watchCloses.length ? { watchCloses } : {}
3065
+ ...watchCloses.length ? { watchCloses } : {},
3066
+ ...uploadAborts.length ? { uploadAborts } : {}
2967
3067
  });
2968
3068
  }
2969
3069
  scheduleHostWatchWake(session) {
@@ -3270,7 +3370,11 @@ export class MultiTabBackend {
3270
3370
  }
3271
3371
  if (msg.op === "flush" || msg.op === "sync") {
3272
3372
  const target = msg.op === "sync" ? msg.args[0] : msg.args[0];
3273
- await this.persistent.flush(target);
3373
+ await this.barrier.runBarrier(async () => {
3374
+ await this.hostQueue;
3375
+ this.assertHostOpStillValid(session, admittedTerm);
3376
+ await this.persistent.flush(target);
3377
+ });
3274
3378
  await this.hooks.beforeHostReplyPublish?.(msg.op, msg.reqId);
3275
3379
  this.assertHostOpStillValid(session, admittedTerm);
3276
3380
  reply({ ok: true, value: msg.op === "sync" ? 0 : undefined });
@@ -3500,8 +3604,7 @@ export class MultiTabBackend {
3500
3604
  persistent.release(h);
3501
3605
  }
3502
3606
  }
3503
- async handleHostPeerGeneral(session, admittedTerm, msg, data, reply) {
3504
- const persistent = this.persistent;
3607
+ async executeHostPeerGeneralLoop(session, admittedTerm, persistent, msg, data) {
3505
3608
  for (;; ) {
3506
3609
  this.assertHostOpStillValid(session, admittedTerm);
3507
3610
  const preparing = persistent.prepare(msg.op, msg.args);
@@ -3523,18 +3626,22 @@ export class MultiTabBackend {
3523
3626
  await persistent.waitForDirtyCapacity(dirtyRetryChange, () => session.revoked || this.hostTerm !== admittedTerm || !this.isLeaseValid());
3524
3627
  continue;
3525
3628
  }
3526
- const { wireValue, mintedTokens } = this.wrapHostPeerResult(session, persistent, msg.op, result);
3527
- await this.hooks.beforeHostReplyPublish?.(msg.op, msg.reqId);
3528
- if (session.revoked || this.terminalFailure || !this.isLeaseValid() || this.hostTerm !== admittedTerm || persistent.isTerminallyFailed()) {
3529
- this.rollbackMintedPeerTokens(session, persistent, mintedTokens);
3530
- this.assertHostOpStillValid(session, admittedTerm);
3531
- }
3532
- if (wireValue instanceof Uint8Array) {
3533
- reply({ ok: true, data: unsharedBytes(wireValue), binary: true });
3534
- } else {
3535
- reply({ ok: true, value: wireValue });
3536
- }
3537
- return;
3629
+ return result;
3630
+ }
3631
+ }
3632
+ async handleHostPeerGeneral(session, admittedTerm, msg, data, reply) {
3633
+ const persistent = this.persistent;
3634
+ const result = MUTATION_OPS.has(msg.op) ? await this.barrier.runMutation(() => this.executeHostPeerGeneralLoop(session, admittedTerm, persistent, msg, data)) : await this.executeHostPeerGeneralLoop(session, admittedTerm, persistent, msg, data);
3635
+ const { wireValue, mintedTokens } = this.wrapHostPeerResult(session, persistent, msg.op, result);
3636
+ await this.hooks.beforeHostReplyPublish?.(msg.op, msg.reqId);
3637
+ if (session.revoked || this.terminalFailure || !this.isLeaseValid() || this.hostTerm !== admittedTerm || persistent.isTerminallyFailed()) {
3638
+ this.rollbackMintedPeerTokens(session, persistent, mintedTokens);
3639
+ this.assertHostOpStillValid(session, admittedTerm);
3640
+ }
3641
+ if (wireValue instanceof Uint8Array) {
3642
+ reply({ ok: true, data: unsharedBytes(wireValue), binary: true });
3643
+ } else {
3644
+ reply({ ok: true, value: wireValue });
3538
3645
  }
3539
3646
  }
3540
3647
  executePersistentOrDirtyRetry(persistent, op, args, data, responseCookieTag) {
@@ -3900,7 +4007,9 @@ export class MultiTabBackend {
3900
4007
  throw new FilesystemError(11, "host lease expired");
3901
4008
  }
3902
4009
  }
3903
- async executeLocalOnHost(operation, args, data, responseCookieTag) {
4010
+ async executeLocalOnHost(operation, args, data, responseCookieTag, cancelled) {
4011
+ if (cancelled?.())
4012
+ throw new FilesystemError(11, "operation cancelled");
3904
4013
  const admittedTerm = this.hostTerm;
3905
4014
  if (!this.isLeaseValid()) {
3906
4015
  if (this.disposing)
@@ -3908,11 +4017,15 @@ export class MultiTabBackend {
3908
4017
  let ok = false;
3909
4018
  await raceWithAbort(this.renewLeaseNow(this.currentAttemptId).then((renewed) => {
3910
4019
  ok = renewed;
3911
- }), this.disposeAbort.signal);
4020
+ }), this.disposeAbort.signal, cancelled);
4021
+ if (cancelled?.())
4022
+ throw new FilesystemError(11, "operation cancelled");
3912
4023
  if (this.disposing)
3913
4024
  throw new FilesystemError(11, "filesystem is disposing");
3914
4025
  if (!ok || !this.isLeaseValid()) {
3915
- await this.awaitPendingFenceLoss();
4026
+ await this.awaitPendingFenceLoss(cancelled);
4027
+ if (cancelled?.())
4028
+ throw new FilesystemError(11, "operation cancelled");
3916
4029
  if (this.disposing)
3917
4030
  throw new FilesystemError(11, "filesystem is disposing");
3918
4031
  if (this.terminalFailure) {
@@ -3922,11 +4035,13 @@ export class MultiTabBackend {
3922
4035
  throw new FilesystemError(11, "filesystem ownership lost");
3923
4036
  if (this.role === "peer" || this.role === "failover" || this.role === "waiting") {
3924
4037
  const nextCookieTag = this.revalidateCookieForPeerForward(operation, args, responseCookieTag);
3925
- return this.executeOnPeer(operation, args, data, nextCookieTag);
4038
+ return this.executeOnPeer(operation, args, data, nextCookieTag, cancelled);
3926
4039
  }
3927
4040
  throw new FilesystemError(11, "host lease expired");
3928
4041
  }
3929
4042
  }
4043
+ if (cancelled?.())
4044
+ throw new FilesystemError(11, "operation cancelled");
3930
4045
  this.assertHostReadyForLocal(admittedTerm);
3931
4046
  const persistent = this.persistent;
3932
4047
  const translated = this.translateArgsToHost(operation, args);
@@ -3936,49 +4051,63 @@ export class MultiTabBackend {
3936
4051
  try {
3937
4052
  if (operation === "flush" || operation === "sync") {
3938
4053
  const target = operation === "sync" ? translated[0] : translated[0];
4054
+ await this.hostQueue;
4055
+ if (cancelled?.())
4056
+ throw new FilesystemError(11, "operation cancelled");
4057
+ this.assertHostReadyForLocal(admittedTerm);
3939
4058
  await persistent.flush(target);
3940
4059
  return operation === "sync" ? 0 : undefined;
3941
4060
  }
3942
4061
  if (operation === "read") {
3943
- return await this.executeLocalHostRead(persistent, admittedTerm, translated);
4062
+ return await this.executeLocalHostRead(persistent, admittedTerm, translated, cancelled);
3944
4063
  }
3945
- const result = await this.executeLocalHostGeneral(persistent, admittedTerm, operation, translated, data, responseCookieTag);
4064
+ const result = await this.executeLocalHostGeneral(persistent, admittedTerm, operation, translated, data, responseCookieTag, cancelled);
3946
4065
  return this.mapLocalHostHandles(persistent, admittedTerm, operation, result);
3947
4066
  } finally {
3948
4067
  this.leaveHostAdmitted();
3949
4068
  }
3950
4069
  }
3951
- async executeLocalHostRead(persistent, admittedTerm, translated) {
4070
+ async executeLocalHostRead(persistent, admittedTerm, translated, cancelled) {
3952
4071
  const [remoteHandle, length, offset] = translated;
3953
- for (;; ) {
4072
+ const assertValid = () => {
4073
+ if (cancelled?.())
4074
+ throw new FilesystemError(11, "operation cancelled");
3954
4075
  this.assertHostReadyForLocal(admittedTerm);
4076
+ };
4077
+ for (;; ) {
4078
+ assertValid();
3955
4079
  const startVer = this.readVersion();
3956
- const prep = persistent.prepareDescriptorRead(remoteHandle, offset, length, () => this.hostTerm !== admittedTerm || !this.isLeaseValid());
4080
+ const prep = persistent.prepareDescriptorRead(remoteHandle, offset, length, () => !!cancelled?.() || this.hostTerm !== admittedTerm || !this.isLeaseValid());
3957
4081
  if (prep) {
3958
- const accepted = await this.revalidateColdReadBytes(prep, startVer, () => this.assertHostReadyForLocal(admittedTerm));
4082
+ const accepted = await this.revalidateColdReadBytes(prep, startVer, assertValid);
3959
4083
  if (accepted !== undefined)
3960
4084
  return accepted;
3961
4085
  continue;
3962
4086
  }
3963
4087
  let readBytes;
3964
4088
  await this.enqueueHostSerial(() => {
3965
- this.assertHostReadyForLocal(admittedTerm);
4089
+ assertValid();
3966
4090
  readBytes = persistent.execute("read", [remoteHandle, length, offset], new Uint8Array);
3967
4091
  });
3968
4092
  return readBytes;
3969
4093
  }
3970
4094
  }
3971
- async executeLocalHostGeneral(persistent, admittedTerm, operation, translated, data, responseCookieTag) {
3972
- for (;; ) {
4095
+ async executeLocalHostGeneral(persistent, admittedTerm, operation, translated, data, responseCookieTag, cancelled) {
4096
+ const assertValid = () => {
4097
+ if (cancelled?.())
4098
+ throw new FilesystemError(11, "operation cancelled");
3973
4099
  this.assertHostReadyForLocal(admittedTerm);
4100
+ };
4101
+ for (;; ) {
4102
+ assertValid();
3974
4103
  const preparing = persistent.prepare(operation, translated);
3975
4104
  if (preparing)
3976
- await preparing;
3977
- this.assertHostReadyForLocal(admittedTerm);
4105
+ await awaitUnlessCancelled(preparing, cancelled);
4106
+ assertValid();
3978
4107
  let result;
3979
4108
  let dirtyRetryChange;
3980
4109
  await this.enqueueHostSerial(() => {
3981
- this.assertHostReadyForLocal(admittedTerm);
4110
+ assertValid();
3982
4111
  const step = this.executePersistentOrDirtyRetry(persistent, operation, translated, data, responseCookieTag);
3983
4112
  if (step.retryChange !== undefined) {
3984
4113
  dirtyRetryChange = step.retryChange;
@@ -3987,7 +4116,7 @@ export class MultiTabBackend {
3987
4116
  result = step.result;
3988
4117
  });
3989
4118
  if (dirtyRetryChange !== undefined) {
3990
- await persistent.waitForDirtyCapacity(dirtyRetryChange, () => this.hostTerm !== admittedTerm || !this.isLeaseValid());
4119
+ await persistent.waitForDirtyCapacity(dirtyRetryChange, () => !!cancelled?.() || this.hostTerm !== admittedTerm || !this.isLeaseValid());
3991
4120
  continue;
3992
4121
  }
3993
4122
  return result;
@@ -4024,12 +4153,12 @@ export class MultiTabBackend {
4024
4153
  return result;
4025
4154
  }
4026
4155
  totalPendingSettlements() {
4027
- return this.peerPendingUnpins.size + this.peerPendingWatchAcks.size + this.peerPendingWatchCloses.size;
4156
+ return this.peerPendingUnpins.size + this.peerPendingWatchAcks.size + this.peerPendingWatchCloses.size + this.peerPendingUploadAborts.size;
4028
4157
  }
4029
4158
  enqueueSettlement(sessionId, item) {
4030
4159
  if (sessionId !== this.peerSessionId || !this.peerAttached || !this.peerHostTerm)
4031
4160
  return;
4032
- const alreadyPresent = item.kind === "unpin" && this.peerPendingUnpins.has(item.pinToken) || item.kind === "watch-ack" && this.peerPendingWatchAcks.has(item.ackId) || item.kind === "watch-close" && this.peerPendingWatchCloses.has(item.hostWatchId);
4161
+ const alreadyPresent = item.kind === "unpin" && this.peerPendingUnpins.has(item.pinToken) || item.kind === "watch-ack" && this.peerPendingWatchAcks.has(item.ackId) || item.kind === "watch-close" && this.peerPendingWatchCloses.has(item.hostWatchId) || item.kind === "chunk-abort" && this.peerPendingUploadAborts.has(item.uploadId);
4033
4162
  if (!alreadyPresent && this.totalPendingSettlements() >= MAX_PENDING_SETTLEMENTS) {
4034
4163
  this.triggerPeerSessionReset("settlement-cap");
4035
4164
  return;
@@ -4052,7 +4181,7 @@ export class MultiTabBackend {
4052
4181
  ackId: item.ackId,
4053
4182
  accepted: item.accepted
4054
4183
  });
4055
- } else {
4184
+ } else if (item.kind === "watch-close") {
4056
4185
  this.peerPendingWatchCloses.add(item.hostWatchId);
4057
4186
  this.postToPeerChannel({
4058
4187
  kind: "watch-close",
@@ -4060,6 +4189,14 @@ export class MultiTabBackend {
4060
4189
  sessionId,
4061
4190
  hostWatchId: item.hostWatchId
4062
4191
  });
4192
+ } else {
4193
+ this.peerPendingUploadAborts.add(item.uploadId);
4194
+ this.postToPeerChannel({
4195
+ kind: "chunk-abort",
4196
+ hostTerm: termStr,
4197
+ sessionId,
4198
+ uploadId: item.uploadId
4199
+ });
4063
4200
  }
4064
4201
  }
4065
4202
  postToPeerChannel(message) {
@@ -4100,12 +4237,35 @@ export class MultiTabBackend {
4100
4237
  for (const wake of waiters)
4101
4238
  wake();
4102
4239
  }
4103
- async reservePeerCredits(sessionId, frames, bytes) {
4104
- while (this.peerSessionId === sessionId && this.peerAttached && !this.disposing && !this.ownershipLost && !this.terminalFailure && !this.peerObservedHostFailed && (this.peerAvailableFrames < frames || this.peerAvailableBytes < bytes)) {
4105
- await new Promise((resolve) => {
4240
+ refundPeerCredits(sessionId, frames, bytes) {
4241
+ if (this.peerSessionId !== sessionId)
4242
+ return;
4243
+ this.peerAvailableFrames += frames;
4244
+ this.peerAvailableBytes += bytes;
4245
+ this.wakePeerCreditWaiters();
4246
+ }
4247
+ abortPeerUpload(sessionId, _term, uploadId) {
4248
+ this.enqueueSettlement(sessionId, { kind: "chunk-abort", uploadId });
4249
+ }
4250
+ async reservePeerCredits(sessionId, frames, bytes, cancelled) {
4251
+ if (cancelled?.())
4252
+ throw abortError();
4253
+ while (this.peerSessionId === sessionId && this.peerAttached && !this.disposing && !this.ownershipLost && !this.terminalFailure && !this.peerObservedHostFailed && !cancelled?.() && (this.peerAvailableFrames < frames || this.peerAvailableBytes < bytes)) {
4254
+ let waiter;
4255
+ const ready = new Promise((resolve) => {
4256
+ waiter = resolve;
4106
4257
  this.peerCreditWaiters.push(resolve);
4107
4258
  });
4259
+ try {
4260
+ await awaitUnlessCancelled(ready, cancelled);
4261
+ } finally {
4262
+ const idx = this.peerCreditWaiters.indexOf(waiter);
4263
+ if (idx >= 0)
4264
+ this.peerCreditWaiters.splice(idx, 1);
4265
+ }
4108
4266
  }
4267
+ if (cancelled?.())
4268
+ throw abortError();
4109
4269
  if (this.disposing || this.ownershipLost) {
4110
4270
  throw new FilesystemError(11, "filesystem is closing");
4111
4271
  }
@@ -4130,6 +4290,7 @@ export class MultiTabBackend {
4130
4290
  const pendingUnpins = Array.from(this.peerPendingUnpins).slice(0, PONG_SETTLEMENT_LIMIT);
4131
4291
  const pendingWatchAcks = Array.from(this.peerPendingWatchAcks.entries()).slice(0, PONG_SETTLEMENT_LIMIT);
4132
4292
  const pendingWatchCloses = Array.from(this.peerPendingWatchCloses).slice(0, PONG_SETTLEMENT_LIMIT);
4293
+ const pendingUploadAborts = Array.from(this.peerPendingUploadAborts).slice(0, PONG_SETTLEMENT_LIMIT);
4133
4294
  this.postToPeerChannel({
4134
4295
  kind: "ping",
4135
4296
  hostTerm: formatTerm(this.peerHostTerm),
@@ -4138,7 +4299,8 @@ export class MultiTabBackend {
4138
4299
  latestAckedWakeSeq: this.peerLatestSeenWakeSeq,
4139
4300
  ...pendingUnpins.length ? { pendingUnpins } : {},
4140
4301
  ...pendingWatchAcks.length ? { pendingWatchAcks } : {},
4141
- ...pendingWatchCloses.length ? { pendingWatchCloses } : {}
4302
+ ...pendingWatchCloses.length ? { pendingWatchCloses } : {},
4303
+ ...pendingUploadAborts.length ? { pendingUploadAborts } : {}
4142
4304
  });
4143
4305
  }
4144
4306
  onPeerMessage(msg) {
@@ -4163,7 +4325,7 @@ export class MultiTabBackend {
4163
4325
  });
4164
4326
  return;
4165
4327
  case "settled":
4166
- this.applyPeerSettledLists(msg.unpins, msg.watchAcks, msg.watchCloses);
4328
+ this.applyPeerSettledLists(msg.unpins, msg.watchAcks, msg.watchCloses, msg.uploadAborts);
4167
4329
  return;
4168
4330
  case "pong":
4169
4331
  this.onPeerPong(msg);
@@ -4173,17 +4335,19 @@ export class MultiTabBackend {
4173
4335
  return;
4174
4336
  }
4175
4337
  }
4176
- applyPeerSettledLists(unpins, watchAcks, watchCloses) {
4338
+ applyPeerSettledLists(unpins, watchAcks, watchCloses, uploadAborts) {
4177
4339
  for (const token of unpins ?? [])
4178
4340
  this.peerPendingUnpins.delete(token);
4179
4341
  for (const ackId of watchAcks ?? [])
4180
4342
  this.peerPendingWatchAcks.delete(ackId);
4181
4343
  for (const watchId of watchCloses ?? [])
4182
4344
  this.peerPendingWatchCloses.delete(watchId);
4345
+ for (const uploadId of uploadAborts ?? [])
4346
+ this.peerPendingUploadAborts.delete(uploadId);
4183
4347
  }
4184
4348
  onPeerPong(msg) {
4185
4349
  this.applyPeerCreditLimit(msg.creditLimit);
4186
- this.applyPeerSettledLists(msg.settledUnpins, msg.settledWatchAcks, msg.settledWatchCloses);
4350
+ this.applyPeerSettledLists(msg.settledUnpins, msg.settledWatchAcks, msg.settledWatchCloses, msg.settledUploadAborts);
4187
4351
  if (msg.latestWakeSeq > this.peerLatestSeenWakeSeq) {
4188
4352
  this.peerLatestSeenWakeSeq = msg.latestWakeSeq;
4189
4353
  this.wakeWatchWord();
@@ -4258,14 +4422,16 @@ export class MultiTabBackend {
4258
4422
  }
4259
4423
  }
4260
4424
  }
4261
- executeOnPeer(operation, args, data, responseCookieTag) {
4425
+ executeOnPeer(operation, args, data, responseCookieTag, cancelled) {
4426
+ if (cancelled?.())
4427
+ return Promise.reject(new FilesystemError(11, "operation cancelled"));
4262
4428
  if (this.disposing || this.ownershipLost)
4263
4429
  return Promise.reject(new FilesystemError(11));
4264
4430
  if (this.terminalFailure || this.peerObservedHostFailed) {
4265
4431
  return Promise.reject(new FilesystemError(29, this.peerObservedHostFailed ?? describeReason(this.terminalFailure?.reason)));
4266
4432
  }
4267
4433
  if (this.role === "failover" || this.role === "waiting" || !this.peerAttached || this.peerRebinding) {
4268
- return this.enqueuePeerOp(this.peerFailoverQueue, operation, args, data, responseCookieTag);
4434
+ return this.enqueuePeerOp(this.peerFailoverQueue, operation, args, data, responseCookieTag, cancelled);
4269
4435
  }
4270
4436
  let effectiveCookieTag = responseCookieTag;
4271
4437
  try {
@@ -4273,7 +4439,7 @@ export class MultiTabBackend {
4273
4439
  } catch (error) {
4274
4440
  return Promise.reject(error);
4275
4441
  }
4276
- return this.dispatchPeerOperation(operation, args, data, effectiveCookieTag);
4442
+ return this.dispatchPeerOperation(operation, args, data, effectiveCookieTag, cancelled);
4277
4443
  }
4278
4444
  revalidateCookieForPeerForward(operation, args, responseCookieTag) {
4279
4445
  if (operation !== "readdirPage" || responseCookieTag === undefined)
@@ -4289,30 +4455,39 @@ export class MultiTabBackend {
4289
4455
  }
4290
4456
  return this.dirEpoch;
4291
4457
  }
4292
- async dispatchPeerOperation(operation, args, data, responseCookieTag) {
4458
+ async dispatchPeerOperation(operation, args, data, responseCookieTag, cancelled) {
4459
+ if (cancelled?.())
4460
+ throw new FilesystemError(11, "operation cancelled");
4293
4461
  const sessionId = this.peerSessionId;
4294
4462
  const term = this.peerHostTerm;
4295
4463
  if (!sessionId || term === undefined || !this.peerAttached) {
4296
- return this.executeOnPeer(operation, args, data, responseCookieTag);
4464
+ return this.executeOnPeer(operation, args, data, responseCookieTag, cancelled);
4297
4465
  }
4298
4466
  const remoteArgs = this.translateArgsToPeer(operation, args, term, sessionId);
4299
4467
  if (!remoteArgs)
4300
4468
  throw new FilesystemError(8);
4469
+ let uploadId;
4301
4470
  let finalValue;
4302
4471
  try {
4303
- const { uploadId, inlineData } = await this.uploadPeerDataIfChunked(sessionId, term, data);
4304
- const res = await this.sendPeerReq(sessionId, term, operation, remoteArgs, args, inlineData, uploadId, data.byteLength > MAX_FRAME_BYTES ? data.byteLength : undefined, responseCookieTag);
4472
+ const uploaded = await this.uploadPeerDataIfChunked(sessionId, term, data, cancelled);
4473
+ uploadId = uploaded.uploadId;
4474
+ const res = await this.sendPeerReq(sessionId, term, operation, remoteArgs, args, uploaded.inlineData, uploadId, data.byteLength > MAX_FRAME_BYTES ? data.byteLength : undefined, responseCookieTag, false, undefined, cancelled);
4475
+ uploadId = undefined;
4305
4476
  finalValue = await this.decodePeerResponseValue(sessionId, term, res, isReplayableRead(operation, args));
4306
4477
  } catch (error) {
4478
+ if (uploadId)
4479
+ this.abortPeerUpload(sessionId, term, uploadId);
4307
4480
  if (error instanceof RetryOnHostReadyError || error instanceof FailoverReplayError) {
4308
4481
  const queue = error instanceof RetryOnHostReadyError ? this.peerRetryQueue : this.peerFailoverQueue;
4309
- return this.enqueuePeerOp(queue, operation, args, data, responseCookieTag);
4482
+ return this.enqueuePeerOp(queue, operation, args, data, responseCookieTag, cancelled);
4310
4483
  }
4311
4484
  throw error;
4312
4485
  }
4313
4486
  return this.mapPeerReturnedHandles(operation, term, sessionId, finalValue);
4314
4487
  }
4315
- enqueuePeerOp(queue, op, args, data, responseCookieTag) {
4488
+ enqueuePeerOp(queue, op, args, data, responseCookieTag, cancelled) {
4489
+ if (cancelled?.())
4490
+ return Promise.reject(new FilesystemError(11, "operation cancelled"));
4316
4491
  if (this.disposing || this.ownershipLost) {
4317
4492
  return Promise.reject(new FilesystemError(11, "filesystem is closing"));
4318
4493
  }
@@ -4325,25 +4500,40 @@ export class MultiTabBackend {
4325
4500
  args,
4326
4501
  data: data.byteLength ? unsharedBytes(data) : undefined,
4327
4502
  responseCookieTag,
4503
+ cancelled,
4328
4504
  resolve,
4329
4505
  reject
4330
4506
  });
4331
4507
  });
4332
4508
  }
4333
- async uploadPeerDataIfChunked(sessionId, term, data) {
4334
- if (data.byteLength > MAX_FRAME_BYTES) {
4335
- if (data.byteLength > MAX_STAGED_UPLOAD_BYTES) {
4336
- throw new FilesystemError(22, "payload exceeds 32 MiB upload cap");
4337
- }
4338
- const uploadId = `up-${this.peerNextUploadId++}`;
4339
- const totalBytes = data.byteLength;
4509
+ async uploadPeerDataIfChunked(sessionId, term, data, cancelled) {
4510
+ if (cancelled?.())
4511
+ throw abortError();
4512
+ if (data.byteLength <= MAX_FRAME_BYTES) {
4513
+ return data.byteLength > 0 ? { inlineData: unsharedBytes(data) } : {};
4514
+ }
4515
+ if (data.byteLength > MAX_STAGED_UPLOAD_BYTES) {
4516
+ throw new FilesystemError(22, "payload exceeds 32 MiB upload cap");
4517
+ }
4518
+ const uploadId = `up-${this.peerNextUploadId++}`;
4519
+ const totalBytes = data.byteLength;
4520
+ let staged = false;
4521
+ try {
4340
4522
  for (let offset = 0;offset < totalBytes; offset += MAX_FRAME_BYTES) {
4523
+ if (cancelled?.())
4524
+ throw abortError();
4341
4525
  const end = Math.min(totalBytes, offset + MAX_FRAME_BYTES);
4342
- await this.sendPeerChunkPut(sessionId, term, uploadId, offset, totalBytes, unsharedBytes(data.subarray(offset, end)));
4526
+ staged = true;
4527
+ await this.sendPeerChunkPut(sessionId, term, uploadId, offset, totalBytes, unsharedBytes(data.subarray(offset, end)), cancelled);
4343
4528
  }
4529
+ if (cancelled?.())
4530
+ throw abortError();
4344
4531
  return { uploadId };
4532
+ } catch (error) {
4533
+ if (staged)
4534
+ this.abortPeerUpload(sessionId, term, uploadId);
4535
+ throw error;
4345
4536
  }
4346
- return data.byteLength > 0 ? { inlineData: unsharedBytes(data) } : {};
4347
4537
  }
4348
4538
  async decodePeerResponseValue(sessionId, term, res, replayOnSessionBreak = false) {
4349
4539
  if (res.chunkedId && res.totalBytes !== undefined && res.firstChunk) {
@@ -4389,10 +4579,14 @@ export class MultiTabBackend {
4389
4579
  }
4390
4580
  return finalValue;
4391
4581
  }
4392
- async sendPeerChunkPut(sessionId, term, uploadId, offset, totalBytes, chunk) {
4393
- await this.reservePeerCredits(sessionId, 1, chunk.byteLength);
4582
+ async sendPeerChunkPut(sessionId, term, uploadId, offset, totalBytes, chunk, cancelled) {
4583
+ await this.reservePeerCredits(sessionId, 1, chunk.byteLength, cancelled);
4584
+ if (cancelled?.()) {
4585
+ this.refundPeerCredits(sessionId, 1, chunk.byteLength);
4586
+ throw abortError();
4587
+ }
4394
4588
  const reqId = this.peerNextReqId++;
4395
- await new Promise((resolve, reject) => {
4589
+ const ack = new Promise((resolve, reject) => {
4396
4590
  this.peerInFlightRpcs.set(reqId, {
4397
4591
  reqId,
4398
4592
  op: "chunk-put",
@@ -4413,6 +4607,8 @@ export class MultiTabBackend {
4413
4607
  chunk
4414
4608
  });
4415
4609
  });
4610
+ ack.catch(() => {});
4611
+ await awaitUnlessCancelled(ack, cancelled);
4416
4612
  }
4417
4613
  async fetchPeerChunkedDownload(sessionId, term, downloadId, totalBytes, firstChunk, replayOnSessionBreak = false) {
4418
4614
  const out = new Uint8Array(totalBytes);
@@ -4449,9 +4645,13 @@ export class MultiTabBackend {
4449
4645
  }
4450
4646
  return out;
4451
4647
  }
4452
- async sendPeerReq(sessionId, term, op, args, localArgs = args, data, uploadId, totalBytes, responseCookieTag, isWatchRead = false, localWatchId) {
4648
+ async sendPeerReq(sessionId, term, op, args, localArgs = args, data, uploadId, totalBytes, responseCookieTag, isWatchRead = false, localWatchId, cancelled) {
4453
4649
  const payloadBytes = data?.byteLength ?? 0;
4454
- await this.reservePeerCredits(sessionId, 1, payloadBytes);
4650
+ await this.reservePeerCredits(sessionId, 1, payloadBytes, cancelled);
4651
+ if (cancelled?.()) {
4652
+ this.refundPeerCredits(sessionId, 1, payloadBytes);
4653
+ throw abortError();
4654
+ }
4455
4655
  const reqId = this.peerNextReqId++;
4456
4656
  return new Promise((resolve, reject) => {
4457
4657
  this.peerInFlightRpcs.set(reqId, {
@@ -4588,6 +4788,7 @@ export class MultiTabBackend {
4588
4788
  this.peerPendingUnpins.clear();
4589
4789
  this.peerPendingWatchAcks.clear();
4590
4790
  this.peerPendingWatchCloses.clear();
4791
+ this.peerPendingUploadAborts.clear();
4591
4792
  this.settleInFlightOnSessionBreak();
4592
4793
  this.markLocalWatchesOverflow();
4593
4794
  this.detachHandlesForRemount();
@@ -4747,34 +4948,39 @@ export class MultiTabBackend {
4747
4948
  const cookie = op.args[1];
4748
4949
  return typeof cookie === "bigint" && cookie >= 3n && op.responseCookieTag !== this.dirEpoch;
4749
4950
  }
4750
- drainPeerQueue(queue) {
4751
- if (!queue.length || !this.peerAttached || this.peerRebinding)
4752
- return;
4753
- const queued = queue.splice(0);
4754
- for (const op of queued) {
4951
+ dispatchQueuedOps(ops, dispatchImmediate) {
4952
+ for (const op of ops) {
4953
+ if (op.cancelled?.()) {
4954
+ op.reject(new FilesystemError(11, "operation cancelled"));
4955
+ continue;
4956
+ }
4755
4957
  if (this.isStaleQueuedCookie(op)) {
4756
4958
  op.reject(new FilesystemError(8, "stale directory cookie"));
4757
4959
  continue;
4758
4960
  }
4759
- this.dispatchPeerOperation(op.op, op.args, op.data ?? new Uint8Array, op.op === "readdirPage" ? this.dirEpoch : op.responseCookieTag).then(op.resolve, op.reject);
4961
+ dispatchImmediate(op).then(op.resolve, op.reject);
4760
4962
  }
4761
4963
  }
4964
+ drainPeerQueue(queue) {
4965
+ if (!queue.length || !this.peerAttached || this.peerRebinding)
4966
+ return;
4967
+ this.dispatchQueuedOps(queue.splice(0), (op) => this.dispatchPeerOperation(op.op, op.args, op.data ?? new Uint8Array, op.op === "readdirPage" ? this.dirEpoch : op.responseCookieTag, op.cancelled));
4968
+ }
4762
4969
  drainPeerRetryQueue() {
4763
4970
  this.drainPeerQueue(this.peerRetryQueue);
4764
4971
  }
4765
- drainPeerFailoverQueue() {
4766
- this.drainPeerQueue(this.peerFailoverQueue);
4972
+ drainPeerRetryAndFailoverQueues() {
4973
+ if (!this.peerAttached || this.peerRebinding)
4974
+ return;
4975
+ const all = this.peerRetryQueue.splice(0).concat(this.peerFailoverQueue.splice(0));
4976
+ if (all.length) {
4977
+ this.dispatchQueuedOps(all, (op) => this.dispatchPeerOperation(op.op, op.args, op.data ?? new Uint8Array, op.op === "readdirPage" ? this.dirEpoch : op.responseCookieTag, op.cancelled));
4978
+ }
4767
4979
  this.notifyFailoverReadyWaiters();
4768
4980
  }
4769
4981
  drainQueuedPeerOpsOnNewHost() {
4770
4982
  const all = this.peerRetryQueue.splice(0).concat(this.peerFailoverQueue.splice(0));
4771
- for (const op of all) {
4772
- if (this.isStaleQueuedCookie(op)) {
4773
- op.reject(new FilesystemError(8, "stale directory cookie"));
4774
- continue;
4775
- }
4776
- this.executeLocalOnHost(op.op, op.args, op.data ?? new Uint8Array, op.op === "readdirPage" ? this.dirEpoch : undefined).then(op.resolve, op.reject);
4777
- }
4983
+ this.dispatchQueuedOps(all, (op) => this.executeLocalOnHost(op.op, op.args, op.data ?? new Uint8Array, op.op === "readdirPage" ? this.dirEpoch : undefined, op.cancelled));
4778
4984
  this.notifyFailoverReadyWaiters();
4779
4985
  }
4780
4986
  failAllPeerWork(error) {