@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.
@@ -233,6 +233,7 @@ interface HostPeerSession {
233
233
  readonly pendingSettledUnpins: number[];
234
234
  readonly pendingSettledWatchAcks: number[];
235
235
  readonly pendingSettledWatchCloses: number[];
236
+ readonly pendingSettledUploadAborts: string[];
236
237
  settledFlushTimer?: ReturnType<typeof setTimeout>;
237
238
  latestWakeSeq: number;
238
239
  wakeInFlightSeq?: number;
@@ -278,6 +279,7 @@ interface QueuedPeerOp {
278
279
  readonly isWatchRead?: boolean;
279
280
  readonly localWatchId?: number;
280
281
  readonly replayOnSessionBreak?: boolean;
282
+ readonly cancelled?: () => boolean;
281
283
  readonly resolve: (value: any) => void;
282
284
  readonly reject: (error: unknown) => void;
283
285
  }
@@ -285,7 +287,8 @@ interface QueuedPeerOp {
285
287
  type SettlementItem =
286
288
  | { readonly kind: "unpin"; readonly pinToken: number }
287
289
  | { readonly kind: "watch-ack"; readonly ackId: number; readonly accepted: boolean }
288
- | { readonly kind: "watch-close"; readonly hostWatchId: number };
290
+ | { readonly kind: "watch-close"; readonly hostWatchId: number }
291
+ | { readonly kind: "chunk-abort"; readonly uploadId: string };
289
292
 
290
293
  function abortError(): FilesystemError {
291
294
  return new FilesystemError(11, "operation cancelled");
@@ -348,6 +351,25 @@ async function raceWithAbort(
348
351
  }
349
352
  }
350
353
 
354
+ async function awaitUnlessCancelled<T>(promise: Promise<T>, cancelled?: () => boolean): Promise<T> {
355
+ if (!cancelled) return promise;
356
+ if (cancelled()) {
357
+ void promise.catch(() => {});
358
+ throw abortError();
359
+ }
360
+ let poll: ReturnType<typeof setInterval> | undefined;
361
+ try {
362
+ return await new Promise<T>((resolve, reject) => {
363
+ promise.then(resolve, reject);
364
+ poll = setInterval(() => {
365
+ if (cancelled()) reject(abortError());
366
+ }, 20);
367
+ });
368
+ } finally {
369
+ if (poll) clearInterval(poll);
370
+ }
371
+ }
372
+
351
373
  function linkAbortSignals(...signals: (AbortSignal | undefined)[]): {
352
374
  signal: AbortSignal;
353
375
  cleanup: () => void;
@@ -476,6 +498,42 @@ function defaultOpenStorage(
476
498
  });
477
499
  }
478
500
 
501
+ /** Orders flush/sync barriers behind prior in-flight mutations and holds later mutations until
502
+ * an active barrier settles, while allowing concurrent non-barrier mutations between barriers. */
503
+ class BarrierGate {
504
+ private readonly mutations = new Set<Promise<void>>();
505
+ private activeBarrier: Promise<void> | undefined;
506
+
507
+ runMutation<T>(fn: () => Promise<T>): Promise<T> {
508
+ const barrier = this.activeBarrier;
509
+ const result = barrier ? barrier.then(fn) : fn();
510
+ const settled = result.then(
511
+ () => {},
512
+ () => {},
513
+ );
514
+ this.mutations.add(settled);
515
+ void settled.finally(() => {
516
+ this.mutations.delete(settled);
517
+ });
518
+ return result;
519
+ }
520
+
521
+ runBarrier<T>(fn: () => Promise<T>): Promise<T> {
522
+ const prior = Array.from(this.mutations);
523
+ if (this.activeBarrier) prior.push(this.activeBarrier);
524
+ const result = prior.length ? Promise.allSettled(prior).then(fn) : fn();
525
+ const settled = result.then(
526
+ () => {},
527
+ () => {},
528
+ );
529
+ this.activeBarrier = settled;
530
+ void settled.finally(() => {
531
+ if (this.activeBarrier === settled) this.activeBarrier = undefined;
532
+ });
533
+ return result;
534
+ }
535
+ }
536
+
479
537
  /**
480
538
  * Multi-tab shared persistent filesystem backend (`whenBusy: "attach"`).
481
539
  * Implements Rev 24 of the Waffle multi-tab persistent FS design:
@@ -545,6 +603,7 @@ export class MultiTabBackend implements FilesystemBackend {
545
603
  private persistent?: PersistentBackend;
546
604
  private watchService?: WatchService;
547
605
  private hostQueue: Promise<void> = Promise.resolve();
606
+ private readonly barrier = new BarrierGate();
548
607
  private hostAdmittedCount = 0;
549
608
  private hostAdmittedZeroWaiters: (() => void)[] = [];
550
609
  private hostPeers = new Map<string, HostPeerSession>();
@@ -585,6 +644,7 @@ export class MultiTabBackend implements FilesystemBackend {
585
644
  private peerPendingUnpins = new Set<number>();
586
645
  private peerPendingWatchAcks = new Map<number, boolean>();
587
646
  private peerPendingWatchCloses = new Set<number>();
647
+ private peerPendingUploadAborts = new Set<string>();
588
648
  readonly supportsSockets = false;
589
649
  readonly asyncErrorsAreClientResults = true;
590
650
  private peerFailoverInFlight?: Promise<void>;
@@ -818,21 +878,42 @@ export class MultiTabBackend implements FilesystemBackend {
818
878
  prepare(operation: string, args: any[], _data: Uint8Array): void | Promise<void> {
819
879
  if (this.role !== "host" || !this.persistent || !this.isLeaseValid()) return;
820
880
  if (UNSUPPORTED_ATTACH_OPS.has(operation)) return;
821
- if (operation === "flush" || operation === "sync") return;
881
+ // Mutations hydrate inside execute() under the barrier gate so flush/sync cannot bypass them.
882
+ if (operation === "flush" || operation === "sync" || MUTATION_OPS.has(operation)) return;
822
883
  const translated = this.translateArgsToHost(operation, args);
823
884
  if (!translated) return;
824
885
  return this.persistent.prepare(operation, translated);
825
886
  }
826
887
 
827
- execute(operation: string, args: any[], data: Uint8Array): unknown | Promise<unknown> {
888
+ execute(
889
+ operation: string,
890
+ args: any[],
891
+ data: Uint8Array,
892
+ cancelled?: () => boolean,
893
+ ): unknown | Promise<unknown> {
828
894
  if (UNSUPPORTED_ATTACH_OPS.has(operation)) {
829
895
  throw new FilesystemError(58, `${operation} is not supported in whenBusy: "attach"`);
830
896
  }
831
897
  if (this.terminalFailure)
832
898
  throw new FilesystemError(29, describeReason(this.terminalFailure.reason));
833
- if (this.fenceLossInFlight && !this.disposing && !this.externalOwnershipLostNotified) {
834
- return this.executeAfterFenceLoss(operation, args, data);
899
+ const awaitingFenceLoss =
900
+ !!this.fenceLossInFlight && !this.disposing && !this.externalOwnershipLostNotified;
901
+ if (!awaitingFenceLoss) {
902
+ this.assertLocalExecuteAdmissible();
903
+ }
904
+ if (operation === "flush" || operation === "sync") {
905
+ return this.barrier.runBarrier(() => this.runLocalExecute(operation, args, data, cancelled));
906
+ }
907
+ if (MUTATION_OPS.has(operation)) {
908
+ return this.barrier.runMutation(() => this.runLocalExecute(operation, args, data, cancelled));
835
909
  }
910
+ if (awaitingFenceLoss) {
911
+ return this.runLocalExecute(operation, args, data, cancelled);
912
+ }
913
+ return this.dispatchLocalRead(operation, args, data, cancelled);
914
+ }
915
+
916
+ private assertLocalExecuteAdmissible(): void {
836
917
  if (this.ownershipLost) throw new FilesystemError(11, "filesystem ownership lost");
837
918
  if (this.disposing) {
838
919
  // Allow queued local Host work on disposeHostTerm ONLY while lease is valid.
@@ -846,7 +927,22 @@ export class MultiTabBackend implements FilesystemBackend {
846
927
  throw new FilesystemError(11, "filesystem is disposing");
847
928
  }
848
929
  }
930
+ if (
931
+ this.role !== "host" &&
932
+ this.role !== "peer" &&
933
+ this.role !== "failover" &&
934
+ this.role !== "waiting"
935
+ ) {
936
+ throw new FilesystemError(11, "filesystem backend is closed");
937
+ }
938
+ }
849
939
 
940
+ private dispatchLocalRead(
941
+ operation: string,
942
+ args: any[],
943
+ data: Uint8Array,
944
+ cancelled?: () => boolean,
945
+ ): unknown | Promise<unknown> {
850
946
  // Validate & strip directory cookies at the receiving boundary BEFORE dispatch!
851
947
  let effectiveArgs = args;
852
948
  let responseCookieTag: bigint | undefined;
@@ -860,12 +956,26 @@ export class MultiTabBackend implements FilesystemBackend {
860
956
  }
861
957
 
862
958
  if (this.role === "host") {
863
- return this.executeLocalOnHost(operation, effectiveArgs, data, responseCookieTag);
959
+ return this.executeLocalOnHost(operation, effectiveArgs, data, responseCookieTag, cancelled);
864
960
  }
865
- if (this.role === "peer" || this.role === "failover" || this.role === "waiting") {
866
- return this.executeOnPeer(operation, effectiveArgs, data, responseCookieTag);
961
+ return this.executeOnPeer(operation, effectiveArgs, data, responseCookieTag, cancelled);
962
+ }
963
+
964
+ private async runLocalExecute(
965
+ operation: string,
966
+ args: any[],
967
+ data: Uint8Array,
968
+ cancelled?: () => boolean,
969
+ ): Promise<unknown> {
970
+ if (cancelled?.()) throw new FilesystemError(11, "operation cancelled");
971
+ if (this.fenceLossInFlight && !this.disposing && !this.externalOwnershipLostNotified) {
972
+ await this.awaitPendingFenceLoss(cancelled);
867
973
  }
868
- throw new FilesystemError(11, "filesystem backend is closed");
974
+ if (cancelled?.()) throw new FilesystemError(11, "operation cancelled");
975
+ if (this.terminalFailure)
976
+ throw new FilesystemError(29, describeReason(this.terminalFailure.reason));
977
+ this.assertLocalExecuteAdmissible();
978
+ return this.dispatchLocalRead(operation, args, data, cancelled);
869
979
  }
870
980
 
871
981
  private async awaitPendingFenceLoss(cancelled?: () => boolean): Promise<void> {
@@ -928,16 +1038,11 @@ export class MultiTabBackend implements FilesystemBackend {
928
1038
  }
929
1039
  }
930
1040
 
931
- private async executeAfterFenceLoss(
932
- operation: string,
933
- args: any[],
934
- data: Uint8Array,
935
- ): Promise<unknown> {
936
- await this.awaitPendingFenceLoss();
937
- return this.execute(operation, args, data);
1041
+ flush(target?: FileHandle | string): Promise<void> {
1042
+ return this.barrier.runBarrier(() => this.runLocalFlush(target));
938
1043
  }
939
1044
 
940
- async flush(target?: FileHandle | string): Promise<void> {
1045
+ private async runLocalFlush(target?: FileHandle | string): Promise<void> {
941
1046
  if (this.fenceLossInFlight && !this.disposing && !this.externalOwnershipLostNotified) {
942
1047
  await this.awaitPendingFenceLoss();
943
1048
  }
@@ -964,6 +1069,8 @@ export class MultiTabBackend implements FilesystemBackend {
964
1069
  }
965
1070
  this.enterHostAdmitted();
966
1071
  try {
1072
+ await this.hostQueue;
1073
+ this.assertHostReadyForLocal(admittedTerm);
967
1074
  await this.persistent!.flush(resolvedTarget);
968
1075
  } finally {
969
1076
  this.leaveHostAdmitted();
@@ -2541,6 +2648,7 @@ export class MultiTabBackend implements FilesystemBackend {
2541
2648
  this.peerPendingUnpins.clear();
2542
2649
  this.peerPendingWatchAcks.clear();
2543
2650
  this.peerPendingWatchCloses.clear();
2651
+ this.peerPendingUploadAborts.clear();
2544
2652
 
2545
2653
  const attachedGate = Promise.withResolvers<PeerCreditLimit | "failed" | "rejected">();
2546
2654
  let newerHostReady = false;
@@ -2646,8 +2754,7 @@ export class MultiTabBackend implements FilesystemBackend {
2646
2754
  return false;
2647
2755
  }
2648
2756
  if (this.peerSessionId !== sessionId || !this.peerAttached) return false;
2649
- this.drainPeerRetryQueue();
2650
- this.drainPeerFailoverQueue();
2757
+ this.drainPeerRetryAndFailoverQueues();
2651
2758
  return true;
2652
2759
  } finally {
2653
2760
  if (retryTimer) clearInterval(retryTimer);
@@ -3568,6 +3675,7 @@ export class MultiTabBackend implements FilesystemBackend {
3568
3675
  pendingSettledUnpins: [],
3569
3676
  pendingSettledWatchAcks: [],
3570
3677
  pendingSettledWatchCloses: [],
3678
+ pendingSettledUploadAborts: [],
3571
3679
  latestWakeSeq: 0,
3572
3680
  wakeDirty: false,
3573
3681
  lastActivityAt: Date.now(),
@@ -3795,6 +3903,7 @@ export class MultiTabBackend implements FilesystemBackend {
3795
3903
  const settledUnpins: number[] = [];
3796
3904
  const settledWatchAcks: number[] = [];
3797
3905
  const settledWatchCloses: number[] = [];
3906
+ const settledUploadAborts: string[] = [];
3798
3907
  for (const token of msg.pendingUnpins ?? []) {
3799
3908
  this.hostProcessUnpin(session, token, false);
3800
3909
  settledUnpins.push(token);
@@ -3807,6 +3916,10 @@ export class MultiTabBackend implements FilesystemBackend {
3807
3916
  this.hostProcessWatchClose(session, watchId, false);
3808
3917
  settledWatchCloses.push(watchId);
3809
3918
  }
3919
+ for (const uploadId of msg.pendingUploadAborts ?? []) {
3920
+ this.hostProcessUploadAbort(session, uploadId, false);
3921
+ settledUploadAborts.push(uploadId);
3922
+ }
3810
3923
  const slot = this.hostCreditSlots.get(session.peerId);
3811
3924
  const creditLimit = slot
3812
3925
  ? this.slotCreditLimit(slot)
@@ -3821,6 +3934,7 @@ export class MultiTabBackend implements FilesystemBackend {
3821
3934
  ...(settledUnpins.length ? { settledUnpins } : {}),
3822
3935
  ...(settledWatchAcks.length ? { settledWatchAcks } : {}),
3823
3936
  ...(settledWatchCloses.length ? { settledWatchCloses } : {}),
3937
+ ...(settledUploadAborts.length ? { settledUploadAborts } : {}),
3824
3938
  creditLimit,
3825
3939
  hostState: this.hostHealthState(),
3826
3940
  });
@@ -3832,6 +3946,11 @@ export class MultiTabBackend implements FilesystemBackend {
3832
3946
  return;
3833
3947
  }
3834
3948
 
3949
+ case "chunk-abort": {
3950
+ this.hostProcessUploadAbort(session, msg.uploadId, true);
3951
+ return;
3952
+ }
3953
+
3835
3954
  case "chunk-get": {
3836
3955
  void this.handleHostChunkGet(session, msg);
3837
3956
  return;
@@ -3889,11 +4008,20 @@ export class MultiTabBackend implements FilesystemBackend {
3889
4008
  }
3890
4009
  }
3891
4010
 
4011
+ private hostProcessUploadAbort(session: HostPeerSession, uploadId: string, batch = true): void {
4012
+ this.discardHostStagedUpload(session, uploadId);
4013
+ if (batch) {
4014
+ session.pendingSettledUploadAborts.push(uploadId);
4015
+ this.maybeScheduleHostSettledFlush(session);
4016
+ }
4017
+ }
4018
+
3892
4019
  private maybeScheduleHostSettledFlush(session: HostPeerSession): void {
3893
4020
  const total =
3894
4021
  session.pendingSettledUnpins.length +
3895
4022
  session.pendingSettledWatchAcks.length +
3896
- session.pendingSettledWatchCloses.length;
4023
+ session.pendingSettledWatchCloses.length +
4024
+ session.pendingSettledUploadAborts.length;
3897
4025
  if (total >= SETTLEMENT_BATCH_SIZE) {
3898
4026
  this.flushHostSettled(session);
3899
4027
  return;
@@ -3915,12 +4043,14 @@ export class MultiTabBackend implements FilesystemBackend {
3915
4043
  if (
3916
4044
  !session.pendingSettledUnpins.length &&
3917
4045
  !session.pendingSettledWatchAcks.length &&
3918
- !session.pendingSettledWatchCloses.length
4046
+ !session.pendingSettledWatchCloses.length &&
4047
+ !session.pendingSettledUploadAborts.length
3919
4048
  )
3920
4049
  return;
3921
4050
  const unpins = session.pendingSettledUnpins.splice(0);
3922
4051
  const watchAcks = session.pendingSettledWatchAcks.splice(0);
3923
4052
  const watchCloses = session.pendingSettledWatchCloses.splice(0);
4053
+ const uploadAborts = session.pendingSettledUploadAborts.splice(0);
3924
4054
  this.sendPeerFrame(session.peerId, session.channel, {
3925
4055
  kind: "settled",
3926
4056
  hostTerm: formatTerm(session.hostTerm),
@@ -3928,6 +4058,7 @@ export class MultiTabBackend implements FilesystemBackend {
3928
4058
  ...(unpins.length ? { unpins } : {}),
3929
4059
  ...(watchAcks.length ? { watchAcks } : {}),
3930
4060
  ...(watchCloses.length ? { watchCloses } : {}),
4061
+ ...(uploadAborts.length ? { uploadAborts } : {}),
3931
4062
  });
3932
4063
  }
3933
4064
 
@@ -4310,7 +4441,11 @@ export class MultiTabBackend implements FilesystemBackend {
4310
4441
  if (msg.op === "flush" || msg.op === "sync") {
4311
4442
  const target =
4312
4443
  msg.op === "sync" ? (msg.args[0] as number) : (msg.args[0] as string | undefined);
4313
- await this.persistent!.flush(target);
4444
+ await this.barrier.runBarrier(async () => {
4445
+ await this.hostQueue;
4446
+ this.assertHostOpStillValid(session, admittedTerm);
4447
+ await this.persistent!.flush(target);
4448
+ });
4314
4449
  await this.hooks.beforeHostReplyPublish?.(msg.op, msg.reqId);
4315
4450
  this.assertHostOpStillValid(session, admittedTerm);
4316
4451
  reply({ ok: true, value: msg.op === "sync" ? 0 : undefined });
@@ -4655,19 +4790,13 @@ export class MultiTabBackend implements FilesystemBackend {
4655
4790
  }
4656
4791
  }
4657
4792
 
4658
- private async handleHostPeerGeneral(
4793
+ private async executeHostPeerGeneralLoop(
4659
4794
  session: HostPeerSession,
4660
4795
  admittedTerm: bigint,
4796
+ persistent: PersistentBackend,
4661
4797
  msg: Extract<PeerMessage, { kind: "req" }>,
4662
4798
  data: Uint8Array,
4663
- reply: (
4664
- partial: Omit<
4665
- Extract<PeerMessage, { kind: "res" }>,
4666
- "kind" | "hostTerm" | "sessionId" | "reqId" | "creditFrames" | "creditBytes"
4667
- >,
4668
- ) => void,
4669
- ): Promise<void> {
4670
- const persistent = this.persistent!;
4799
+ ): Promise<unknown> {
4671
4800
  for (;;) {
4672
4801
  this.assertHostOpStillValid(session, admittedTerm);
4673
4802
  const preparing = persistent.prepare(msg.op, msg.args);
@@ -4693,32 +4822,52 @@ export class MultiTabBackend implements FilesystemBackend {
4693
4822
  );
4694
4823
  continue;
4695
4824
  }
4825
+ return result;
4826
+ }
4827
+ }
4696
4828
 
4697
- const { wireValue, mintedTokens } = this.wrapHostPeerResult(
4698
- session,
4699
- persistent,
4700
- msg.op,
4701
- result,
4702
- );
4829
+ private async handleHostPeerGeneral(
4830
+ session: HostPeerSession,
4831
+ admittedTerm: bigint,
4832
+ msg: Extract<PeerMessage, { kind: "req" }>,
4833
+ data: Uint8Array,
4834
+ reply: (
4835
+ partial: Omit<
4836
+ Extract<PeerMessage, { kind: "res" }>,
4837
+ "kind" | "hostTerm" | "sessionId" | "reqId" | "creditFrames" | "creditBytes"
4838
+ >,
4839
+ ) => void,
4840
+ ): Promise<void> {
4841
+ const persistent = this.persistent!;
4842
+ const result = MUTATION_OPS.has(msg.op)
4843
+ ? await this.barrier.runMutation(() =>
4844
+ this.executeHostPeerGeneralLoop(session, admittedTerm, persistent, msg, data),
4845
+ )
4846
+ : await this.executeHostPeerGeneralLoop(session, admittedTerm, persistent, msg, data);
4847
+
4848
+ const { wireValue, mintedTokens } = this.wrapHostPeerResult(
4849
+ session,
4850
+ persistent,
4851
+ msg.op,
4852
+ result,
4853
+ );
4703
4854
 
4704
- await this.hooks.beforeHostReplyPublish?.(msg.op, msg.reqId);
4705
- if (
4706
- session.revoked ||
4707
- this.terminalFailure ||
4708
- !this.isLeaseValid() ||
4709
- this.hostTerm !== admittedTerm ||
4710
- persistent.isTerminallyFailed()
4711
- ) {
4712
- this.rollbackMintedPeerTokens(session, persistent, mintedTokens);
4713
- this.assertHostOpStillValid(session, admittedTerm);
4714
- }
4855
+ await this.hooks.beforeHostReplyPublish?.(msg.op, msg.reqId);
4856
+ if (
4857
+ session.revoked ||
4858
+ this.terminalFailure ||
4859
+ !this.isLeaseValid() ||
4860
+ this.hostTerm !== admittedTerm ||
4861
+ persistent.isTerminallyFailed()
4862
+ ) {
4863
+ this.rollbackMintedPeerTokens(session, persistent, mintedTokens);
4864
+ this.assertHostOpStillValid(session, admittedTerm);
4865
+ }
4715
4866
 
4716
- if (wireValue instanceof Uint8Array) {
4717
- reply({ ok: true, data: unsharedBytes(wireValue), binary: true });
4718
- } else {
4719
- reply({ ok: true, value: wireValue });
4720
- }
4721
- return;
4867
+ if (wireValue instanceof Uint8Array) {
4868
+ reply({ ok: true, data: unsharedBytes(wireValue), binary: true });
4869
+ } else {
4870
+ reply({ ok: true, value: wireValue });
4722
4871
  }
4723
4872
  }
4724
4873
 
@@ -5265,7 +5414,9 @@ export class MultiTabBackend implements FilesystemBackend {
5265
5414
  args: any[],
5266
5415
  data: Uint8Array,
5267
5416
  responseCookieTag?: bigint,
5417
+ cancelled?: () => boolean,
5268
5418
  ): Promise<unknown> {
5419
+ if (cancelled?.()) throw new FilesystemError(11, "operation cancelled");
5269
5420
  const admittedTerm = this.hostTerm;
5270
5421
 
5271
5422
  // If lease expired before execution: renew first (or fail ECANCELED if disposing!)
@@ -5277,10 +5428,13 @@ export class MultiTabBackend implements FilesystemBackend {
5277
5428
  ok = renewed;
5278
5429
  }),
5279
5430
  this.disposeAbort.signal,
5431
+ cancelled,
5280
5432
  );
5433
+ if (cancelled?.()) throw new FilesystemError(11, "operation cancelled");
5281
5434
  if (this.disposing) throw new FilesystemError(11, "filesystem is disposing");
5282
5435
  if (!ok || !this.isLeaseValid()) {
5283
- await this.awaitPendingFenceLoss();
5436
+ await this.awaitPendingFenceLoss(cancelled);
5437
+ if (cancelled?.()) throw new FilesystemError(11, "operation cancelled");
5284
5438
  if (this.disposing) throw new FilesystemError(11, "filesystem is disposing");
5285
5439
  if (this.terminalFailure) {
5286
5440
  throw new FilesystemError(29, describeReason(this.terminalFailure.reason));
@@ -5292,12 +5446,13 @@ export class MultiTabBackend implements FilesystemBackend {
5292
5446
  args,
5293
5447
  responseCookieTag,
5294
5448
  );
5295
- return this.executeOnPeer(operation, args, data, nextCookieTag);
5449
+ return this.executeOnPeer(operation, args, data, nextCookieTag, cancelled);
5296
5450
  }
5297
5451
  throw new FilesystemError(11, "host lease expired");
5298
5452
  }
5299
5453
  }
5300
5454
 
5455
+ if (cancelled?.()) throw new FilesystemError(11, "operation cancelled");
5301
5456
  this.assertHostReadyForLocal(admittedTerm);
5302
5457
  const persistent = this.persistent!;
5303
5458
  const translated = this.translateArgsToHost(operation, args);
@@ -5308,11 +5463,14 @@ export class MultiTabBackend implements FilesystemBackend {
5308
5463
  if (operation === "flush" || operation === "sync") {
5309
5464
  const target =
5310
5465
  operation === "sync" ? (translated[0] as number) : (translated[0] as string | undefined);
5466
+ await this.hostQueue;
5467
+ if (cancelled?.()) throw new FilesystemError(11, "operation cancelled");
5468
+ this.assertHostReadyForLocal(admittedTerm);
5311
5469
  await persistent.flush(target);
5312
5470
  return operation === "sync" ? 0 : undefined;
5313
5471
  }
5314
5472
  if (operation === "read") {
5315
- return await this.executeLocalHostRead(persistent, admittedTerm, translated);
5473
+ return await this.executeLocalHostRead(persistent, admittedTerm, translated, cancelled);
5316
5474
  }
5317
5475
  const result = await this.executeLocalHostGeneral(
5318
5476
  persistent,
@@ -5321,6 +5479,7 @@ export class MultiTabBackend implements FilesystemBackend {
5321
5479
  translated,
5322
5480
  data,
5323
5481
  responseCookieTag,
5482
+ cancelled,
5324
5483
  );
5325
5484
  return this.mapLocalHostHandles(persistent, admittedTerm, operation, result);
5326
5485
  } finally {
@@ -5332,27 +5491,30 @@ export class MultiTabBackend implements FilesystemBackend {
5332
5491
  persistent: PersistentBackend,
5333
5492
  admittedTerm: bigint,
5334
5493
  translated: any[],
5494
+ cancelled?: () => boolean,
5335
5495
  ): Promise<Uint8Array> {
5336
5496
  const [remoteHandle, length, offset] = translated as [number, number, number];
5337
- for (;;) {
5497
+ const assertValid = () => {
5498
+ if (cancelled?.()) throw new FilesystemError(11, "operation cancelled");
5338
5499
  this.assertHostReadyForLocal(admittedTerm);
5500
+ };
5501
+ for (;;) {
5502
+ assertValid();
5339
5503
  const startVer = this.readVersion();
5340
5504
  const prep = persistent.prepareDescriptorRead(
5341
5505
  remoteHandle,
5342
5506
  offset,
5343
5507
  length,
5344
- () => this.hostTerm !== admittedTerm || !this.isLeaseValid(),
5508
+ () => !!cancelled?.() || this.hostTerm !== admittedTerm || !this.isLeaseValid(),
5345
5509
  );
5346
5510
  if (prep) {
5347
- const accepted = await this.revalidateColdReadBytes(prep, startVer, () =>
5348
- this.assertHostReadyForLocal(admittedTerm),
5349
- );
5511
+ const accepted = await this.revalidateColdReadBytes(prep, startVer, assertValid);
5350
5512
  if (accepted !== undefined) return accepted;
5351
5513
  continue;
5352
5514
  }
5353
5515
  let readBytes!: Uint8Array;
5354
5516
  await this.enqueueHostSerial(() => {
5355
- this.assertHostReadyForLocal(admittedTerm);
5517
+ assertValid();
5356
5518
  readBytes = persistent.execute(
5357
5519
  "read",
5358
5520
  [remoteHandle, length, offset],
@@ -5370,17 +5532,22 @@ export class MultiTabBackend implements FilesystemBackend {
5370
5532
  translated: any[],
5371
5533
  data: Uint8Array,
5372
5534
  responseCookieTag?: bigint,
5535
+ cancelled?: () => boolean,
5373
5536
  ): Promise<unknown> {
5374
- for (;;) {
5537
+ const assertValid = () => {
5538
+ if (cancelled?.()) throw new FilesystemError(11, "operation cancelled");
5375
5539
  this.assertHostReadyForLocal(admittedTerm);
5540
+ };
5541
+ for (;;) {
5542
+ assertValid();
5376
5543
  const preparing = persistent.prepare(operation, translated);
5377
- if (preparing) await preparing;
5378
- this.assertHostReadyForLocal(admittedTerm);
5544
+ if (preparing) await awaitUnlessCancelled(preparing, cancelled);
5545
+ assertValid();
5379
5546
 
5380
5547
  let result: unknown;
5381
5548
  let dirtyRetryChange: number | undefined;
5382
5549
  await this.enqueueHostSerial(() => {
5383
- this.assertHostReadyForLocal(admittedTerm);
5550
+ assertValid();
5384
5551
  const step = this.executePersistentOrDirtyRetry(
5385
5552
  persistent,
5386
5553
  operation,
@@ -5397,7 +5564,7 @@ export class MultiTabBackend implements FilesystemBackend {
5397
5564
  if (dirtyRetryChange !== undefined) {
5398
5565
  await persistent.waitForDirtyCapacity(
5399
5566
  dirtyRetryChange,
5400
- () => this.hostTerm !== admittedTerm || !this.isLeaseValid(),
5567
+ () => !!cancelled?.() || this.hostTerm !== admittedTerm || !this.isLeaseValid(),
5401
5568
  );
5402
5569
  continue;
5403
5570
  }
@@ -5471,7 +5638,8 @@ export class MultiTabBackend implements FilesystemBackend {
5471
5638
  return (
5472
5639
  this.peerPendingUnpins.size +
5473
5640
  this.peerPendingWatchAcks.size +
5474
- this.peerPendingWatchCloses.size
5641
+ this.peerPendingWatchCloses.size +
5642
+ this.peerPendingUploadAborts.size
5475
5643
  );
5476
5644
  }
5477
5645
 
@@ -5484,7 +5652,8 @@ export class MultiTabBackend implements FilesystemBackend {
5484
5652
  const alreadyPresent =
5485
5653
  (item.kind === "unpin" && this.peerPendingUnpins.has(item.pinToken)) ||
5486
5654
  (item.kind === "watch-ack" && this.peerPendingWatchAcks.has(item.ackId)) ||
5487
- (item.kind === "watch-close" && this.peerPendingWatchCloses.has(item.hostWatchId));
5655
+ (item.kind === "watch-close" && this.peerPendingWatchCloses.has(item.hostWatchId)) ||
5656
+ (item.kind === "chunk-abort" && this.peerPendingUploadAborts.has(item.uploadId));
5488
5657
 
5489
5658
  if (!alreadyPresent && this.totalPendingSettlements() >= MAX_PENDING_SETTLEMENTS) {
5490
5659
  // Pre-insertion cap: trigger session reset instead of exceeding 1024!
@@ -5510,7 +5679,7 @@ export class MultiTabBackend implements FilesystemBackend {
5510
5679
  ackId: item.ackId,
5511
5680
  accepted: item.accepted,
5512
5681
  });
5513
- } else {
5682
+ } else if (item.kind === "watch-close") {
5514
5683
  this.peerPendingWatchCloses.add(item.hostWatchId);
5515
5684
  this.postToPeerChannel({
5516
5685
  kind: "watch-close",
@@ -5518,6 +5687,14 @@ export class MultiTabBackend implements FilesystemBackend {
5518
5687
  sessionId,
5519
5688
  hostWatchId: item.hostWatchId,
5520
5689
  });
5690
+ } else {
5691
+ this.peerPendingUploadAborts.add(item.uploadId);
5692
+ this.postToPeerChannel({
5693
+ kind: "chunk-abort",
5694
+ hostTerm: termStr,
5695
+ sessionId,
5696
+ uploadId: item.uploadId,
5697
+ });
5521
5698
  }
5522
5699
  }
5523
5700
 
@@ -5559,11 +5736,24 @@ export class MultiTabBackend implements FilesystemBackend {
5559
5736
  for (const wake of waiters) wake();
5560
5737
  }
5561
5738
 
5739
+ private refundPeerCredits(sessionId: string, frames: number, bytes: number): void {
5740
+ if (this.peerSessionId !== sessionId) return;
5741
+ this.peerAvailableFrames += frames;
5742
+ this.peerAvailableBytes += bytes;
5743
+ this.wakePeerCreditWaiters();
5744
+ }
5745
+
5746
+ private abortPeerUpload(sessionId: string, _term: bigint, uploadId: string): void {
5747
+ this.enqueueSettlement(sessionId, { kind: "chunk-abort", uploadId });
5748
+ }
5749
+
5562
5750
  private async reservePeerCredits(
5563
5751
  sessionId: string,
5564
5752
  frames: number,
5565
5753
  bytes: number,
5754
+ cancelled?: () => boolean,
5566
5755
  ): Promise<void> {
5756
+ if (cancelled?.()) throw abortError();
5567
5757
  while (
5568
5758
  this.peerSessionId === sessionId &&
5569
5759
  this.peerAttached &&
@@ -5571,12 +5761,22 @@ export class MultiTabBackend implements FilesystemBackend {
5571
5761
  !this.ownershipLost &&
5572
5762
  !this.terminalFailure &&
5573
5763
  !this.peerObservedHostFailed &&
5764
+ !cancelled?.() &&
5574
5765
  (this.peerAvailableFrames < frames || this.peerAvailableBytes < bytes)
5575
5766
  ) {
5576
- await new Promise<void>((resolve) => {
5767
+ let waiter!: () => void;
5768
+ const ready = new Promise<void>((resolve) => {
5769
+ waiter = resolve;
5577
5770
  this.peerCreditWaiters.push(resolve);
5578
5771
  });
5772
+ try {
5773
+ await awaitUnlessCancelled(ready, cancelled);
5774
+ } finally {
5775
+ const idx = this.peerCreditWaiters.indexOf(waiter);
5776
+ if (idx >= 0) this.peerCreditWaiters.splice(idx, 1);
5777
+ }
5579
5778
  }
5779
+ if (cancelled?.()) throw abortError();
5580
5780
  if (this.disposing || this.ownershipLost) {
5581
5781
  throw new FilesystemError(11, "filesystem is closing");
5582
5782
  }
@@ -5613,6 +5813,10 @@ export class MultiTabBackend implements FilesystemBackend {
5613
5813
  0,
5614
5814
  PONG_SETTLEMENT_LIMIT,
5615
5815
  );
5816
+ const pendingUploadAborts = Array.from(this.peerPendingUploadAborts).slice(
5817
+ 0,
5818
+ PONG_SETTLEMENT_LIMIT,
5819
+ );
5616
5820
  this.postToPeerChannel({
5617
5821
  kind: "ping",
5618
5822
  hostTerm: formatTerm(this.peerHostTerm),
@@ -5622,6 +5826,7 @@ export class MultiTabBackend implements FilesystemBackend {
5622
5826
  ...(pendingUnpins.length ? { pendingUnpins } : {}),
5623
5827
  ...(pendingWatchAcks.length ? { pendingWatchAcks } : {}),
5624
5828
  ...(pendingWatchCloses.length ? { pendingWatchCloses } : {}),
5829
+ ...(pendingUploadAborts.length ? { pendingUploadAborts } : {}),
5625
5830
  });
5626
5831
  }
5627
5832
 
@@ -5654,7 +5859,7 @@ export class MultiTabBackend implements FilesystemBackend {
5654
5859
  });
5655
5860
  return;
5656
5861
  case "settled":
5657
- this.applyPeerSettledLists(msg.unpins, msg.watchAcks, msg.watchCloses);
5862
+ this.applyPeerSettledLists(msg.unpins, msg.watchAcks, msg.watchCloses, msg.uploadAborts);
5658
5863
  return;
5659
5864
  case "pong":
5660
5865
  this.onPeerPong(msg);
@@ -5669,15 +5874,22 @@ export class MultiTabBackend implements FilesystemBackend {
5669
5874
  unpins?: readonly number[],
5670
5875
  watchAcks?: readonly number[],
5671
5876
  watchCloses?: readonly number[],
5877
+ uploadAborts?: readonly string[],
5672
5878
  ): void {
5673
5879
  for (const token of unpins ?? []) this.peerPendingUnpins.delete(token);
5674
5880
  for (const ackId of watchAcks ?? []) this.peerPendingWatchAcks.delete(ackId);
5675
5881
  for (const watchId of watchCloses ?? []) this.peerPendingWatchCloses.delete(watchId);
5882
+ for (const uploadId of uploadAborts ?? []) this.peerPendingUploadAborts.delete(uploadId);
5676
5883
  }
5677
5884
 
5678
5885
  private onPeerPong(msg: Extract<PeerMessage, { kind: "pong" }>): void {
5679
5886
  this.applyPeerCreditLimit(msg.creditLimit);
5680
- this.applyPeerSettledLists(msg.settledUnpins, msg.settledWatchAcks, msg.settledWatchCloses);
5887
+ this.applyPeerSettledLists(
5888
+ msg.settledUnpins,
5889
+ msg.settledWatchAcks,
5890
+ msg.settledWatchCloses,
5891
+ msg.settledUploadAborts,
5892
+ );
5681
5893
 
5682
5894
  if (msg.latestWakeSeq > this.peerLatestSeenWakeSeq) {
5683
5895
  this.peerLatestSeenWakeSeq = msg.latestWakeSeq;
@@ -5766,7 +5978,9 @@ export class MultiTabBackend implements FilesystemBackend {
5766
5978
  args: any[],
5767
5979
  data: Uint8Array,
5768
5980
  responseCookieTag?: bigint,
5981
+ cancelled?: () => boolean,
5769
5982
  ): Promise<unknown> {
5983
+ if (cancelled?.()) return Promise.reject(new FilesystemError(11, "operation cancelled"));
5770
5984
  if (this.disposing || this.ownershipLost) return Promise.reject(new FilesystemError(11));
5771
5985
  if (this.terminalFailure || this.peerObservedHostFailed) {
5772
5986
  return Promise.reject(
@@ -5783,7 +5997,14 @@ export class MultiTabBackend implements FilesystemBackend {
5783
5997
  !this.peerAttached ||
5784
5998
  this.peerRebinding
5785
5999
  ) {
5786
- return this.enqueuePeerOp(this.peerFailoverQueue, operation, args, data, responseCookieTag);
6000
+ return this.enqueuePeerOp(
6001
+ this.peerFailoverQueue,
6002
+ operation,
6003
+ args,
6004
+ data,
6005
+ responseCookieTag,
6006
+ cancelled,
6007
+ );
5787
6008
  }
5788
6009
 
5789
6010
  let effectiveCookieTag = responseCookieTag;
@@ -5792,7 +6013,7 @@ export class MultiTabBackend implements FilesystemBackend {
5792
6013
  } catch (error) {
5793
6014
  return Promise.reject(error);
5794
6015
  }
5795
- return this.dispatchPeerOperation(operation, args, data, effectiveCookieTag);
6016
+ return this.dispatchPeerOperation(operation, args, data, effectiveCookieTag, cancelled);
5796
6017
  }
5797
6018
 
5798
6019
  private revalidateCookieForPeerForward(
@@ -5817,30 +6038,38 @@ export class MultiTabBackend implements FilesystemBackend {
5817
6038
  args: any[],
5818
6039
  data: Uint8Array,
5819
6040
  responseCookieTag?: bigint,
6041
+ cancelled?: () => boolean,
5820
6042
  ): Promise<unknown> {
6043
+ if (cancelled?.()) throw new FilesystemError(11, "operation cancelled");
5821
6044
  const sessionId = this.peerSessionId;
5822
6045
  const term = this.peerHostTerm;
5823
6046
  if (!sessionId || term === undefined || !this.peerAttached) {
5824
- return this.executeOnPeer(operation, args, data, responseCookieTag);
6047
+ return this.executeOnPeer(operation, args, data, responseCookieTag, cancelled);
5825
6048
  }
5826
6049
 
5827
6050
  const remoteArgs = this.translateArgsToPeer(operation, args, term, sessionId);
5828
6051
  if (!remoteArgs) throw new FilesystemError(8);
5829
6052
 
6053
+ let uploadId: string | undefined;
5830
6054
  let finalValue: unknown;
5831
6055
  try {
5832
- const { uploadId, inlineData } = await this.uploadPeerDataIfChunked(sessionId, term, data);
6056
+ const uploaded = await this.uploadPeerDataIfChunked(sessionId, term, data, cancelled);
6057
+ uploadId = uploaded.uploadId;
5833
6058
  const res = await this.sendPeerReq(
5834
6059
  sessionId,
5835
6060
  term,
5836
6061
  operation,
5837
6062
  remoteArgs,
5838
6063
  args,
5839
- inlineData,
6064
+ uploaded.inlineData,
5840
6065
  uploadId,
5841
6066
  data.byteLength > MAX_FRAME_BYTES ? data.byteLength : undefined,
5842
6067
  responseCookieTag,
6068
+ false,
6069
+ undefined,
6070
+ cancelled,
5843
6071
  );
6072
+ uploadId = undefined;
5844
6073
  finalValue = await this.decodePeerResponseValue(
5845
6074
  sessionId,
5846
6075
  term,
@@ -5848,10 +6077,11 @@ export class MultiTabBackend implements FilesystemBackend {
5848
6077
  isReplayableRead(operation, args),
5849
6078
  );
5850
6079
  } catch (error) {
6080
+ if (uploadId) this.abortPeerUpload(sessionId, term, uploadId);
5851
6081
  if (error instanceof RetryOnHostReadyError || error instanceof FailoverReplayError) {
5852
6082
  const queue =
5853
6083
  error instanceof RetryOnHostReadyError ? this.peerRetryQueue : this.peerFailoverQueue;
5854
- return this.enqueuePeerOp(queue, operation, args, data, responseCookieTag);
6084
+ return this.enqueuePeerOp(queue, operation, args, data, responseCookieTag, cancelled);
5855
6085
  }
5856
6086
  throw error;
5857
6087
  }
@@ -5865,7 +6095,9 @@ export class MultiTabBackend implements FilesystemBackend {
5865
6095
  args: any[],
5866
6096
  data: Uint8Array,
5867
6097
  responseCookieTag?: bigint,
6098
+ cancelled?: () => boolean,
5868
6099
  ): Promise<unknown> {
6100
+ if (cancelled?.()) return Promise.reject(new FilesystemError(11, "operation cancelled"));
5869
6101
  if (this.disposing || this.ownershipLost) {
5870
6102
  return Promise.reject(new FilesystemError(11, "filesystem is closing"));
5871
6103
  }
@@ -5883,6 +6115,7 @@ export class MultiTabBackend implements FilesystemBackend {
5883
6115
  args,
5884
6116
  data: data.byteLength ? unsharedBytes(data) : undefined,
5885
6117
  responseCookieTag,
6118
+ cancelled,
5886
6119
  resolve,
5887
6120
  reject,
5888
6121
  });
@@ -5893,15 +6126,23 @@ export class MultiTabBackend implements FilesystemBackend {
5893
6126
  sessionId: string,
5894
6127
  term: bigint,
5895
6128
  data: Uint8Array,
6129
+ cancelled?: () => boolean,
5896
6130
  ): Promise<{ uploadId?: string; inlineData?: Uint8Array<ArrayBuffer> }> {
5897
- if (data.byteLength > MAX_FRAME_BYTES) {
5898
- if (data.byteLength > MAX_STAGED_UPLOAD_BYTES) {
5899
- throw new FilesystemError(22, "payload exceeds 32 MiB upload cap");
5900
- }
5901
- const uploadId = `up-${this.peerNextUploadId++}`;
5902
- const totalBytes = data.byteLength;
6131
+ if (cancelled?.()) throw abortError();
6132
+ if (data.byteLength <= MAX_FRAME_BYTES) {
6133
+ return data.byteLength > 0 ? { inlineData: unsharedBytes(data) } : {};
6134
+ }
6135
+ if (data.byteLength > MAX_STAGED_UPLOAD_BYTES) {
6136
+ throw new FilesystemError(22, "payload exceeds 32 MiB upload cap");
6137
+ }
6138
+ const uploadId = `up-${this.peerNextUploadId++}`;
6139
+ const totalBytes = data.byteLength;
6140
+ let staged = false;
6141
+ try {
5903
6142
  for (let offset = 0; offset < totalBytes; offset += MAX_FRAME_BYTES) {
6143
+ if (cancelled?.()) throw abortError();
5904
6144
  const end = Math.min(totalBytes, offset + MAX_FRAME_BYTES);
6145
+ staged = true;
5905
6146
  await this.sendPeerChunkPut(
5906
6147
  sessionId,
5907
6148
  term,
@@ -5909,11 +6150,15 @@ export class MultiTabBackend implements FilesystemBackend {
5909
6150
  offset,
5910
6151
  totalBytes,
5911
6152
  unsharedBytes(data.subarray(offset, end)),
6153
+ cancelled,
5912
6154
  );
5913
6155
  }
6156
+ if (cancelled?.()) throw abortError();
5914
6157
  return { uploadId };
6158
+ } catch (error) {
6159
+ if (staged) this.abortPeerUpload(sessionId, term, uploadId);
6160
+ throw error;
5915
6161
  }
5916
- return data.byteLength > 0 ? { inlineData: unsharedBytes(data) } : {};
5917
6162
  }
5918
6163
 
5919
6164
  private async decodePeerResponseValue(
@@ -6011,10 +6256,15 @@ export class MultiTabBackend implements FilesystemBackend {
6011
6256
  offset: number,
6012
6257
  totalBytes: number,
6013
6258
  chunk: Uint8Array<ArrayBuffer>,
6259
+ cancelled?: () => boolean,
6014
6260
  ): Promise<void> {
6015
- await this.reservePeerCredits(sessionId, 1, chunk.byteLength);
6261
+ await this.reservePeerCredits(sessionId, 1, chunk.byteLength, cancelled);
6262
+ if (cancelled?.()) {
6263
+ this.refundPeerCredits(sessionId, 1, chunk.byteLength);
6264
+ throw abortError();
6265
+ }
6016
6266
  const reqId = this.peerNextReqId++;
6017
- await new Promise<void>((resolve, reject) => {
6267
+ const ack = new Promise<void>((resolve, reject) => {
6018
6268
  this.peerInFlightRpcs.set(reqId, {
6019
6269
  reqId,
6020
6270
  op: "chunk-put",
@@ -6035,6 +6285,8 @@ export class MultiTabBackend implements FilesystemBackend {
6035
6285
  chunk,
6036
6286
  });
6037
6287
  });
6288
+ void ack.catch(() => {});
6289
+ await awaitUnlessCancelled(ack, cancelled);
6038
6290
  }
6039
6291
 
6040
6292
  private async fetchPeerChunkedDownload(
@@ -6091,9 +6343,14 @@ export class MultiTabBackend implements FilesystemBackend {
6091
6343
  responseCookieTag?: bigint,
6092
6344
  isWatchRead = false,
6093
6345
  localWatchId?: number,
6346
+ cancelled?: () => boolean,
6094
6347
  ): Promise<Extract<PeerMessage, { kind: "res" }>> {
6095
6348
  const payloadBytes = data?.byteLength ?? 0;
6096
- await this.reservePeerCredits(sessionId, 1, payloadBytes);
6349
+ await this.reservePeerCredits(sessionId, 1, payloadBytes, cancelled);
6350
+ if (cancelled?.()) {
6351
+ this.refundPeerCredits(sessionId, 1, payloadBytes);
6352
+ throw abortError();
6353
+ }
6097
6354
  const reqId = this.peerNextReqId++;
6098
6355
  return new Promise<Extract<PeerMessage, { kind: "res" }>>((resolve, reject) => {
6099
6356
  this.peerInFlightRpcs.set(reqId, {
@@ -6290,6 +6547,7 @@ export class MultiTabBackend implements FilesystemBackend {
6290
6547
  this.peerPendingUnpins.clear();
6291
6548
  this.peerPendingWatchAcks.clear();
6292
6549
  this.peerPendingWatchCloses.clear();
6550
+ this.peerPendingUploadAborts.clear();
6293
6551
  this.settleInFlightOnSessionBreak();
6294
6552
  this.markLocalWatchesOverflow();
6295
6553
  this.detachHandlesForRemount();
@@ -6479,46 +6737,68 @@ export class MultiTabBackend implements FilesystemBackend {
6479
6737
  return typeof cookie === "bigint" && cookie >= 3n && op.responseCookieTag !== this.dirEpoch;
6480
6738
  }
6481
6739
 
6482
- private drainPeerQueue(queue: QueuedPeerOp[]): void {
6483
- if (!queue.length || !this.peerAttached || this.peerRebinding) return;
6484
- const queued = queue.splice(0);
6485
- for (const op of queued) {
6740
+ private dispatchQueuedOps(
6741
+ ops: readonly QueuedPeerOp[],
6742
+ dispatchImmediate: (op: QueuedPeerOp) => Promise<unknown>,
6743
+ ): void {
6744
+ for (const op of ops) {
6745
+ if (op.cancelled?.()) {
6746
+ op.reject(new FilesystemError(11, "operation cancelled"));
6747
+ continue;
6748
+ }
6486
6749
  if (this.isStaleQueuedCookie(op)) {
6487
6750
  op.reject(new FilesystemError(8, "stale directory cookie"));
6488
6751
  continue;
6489
6752
  }
6753
+ dispatchImmediate(op).then(op.resolve, op.reject);
6754
+ }
6755
+ }
6756
+
6757
+ private drainPeerQueue(queue: QueuedPeerOp[]): void {
6758
+ if (!queue.length || !this.peerAttached || this.peerRebinding) return;
6759
+ this.dispatchQueuedOps(queue.splice(0), (op) =>
6490
6760
  this.dispatchPeerOperation(
6491
6761
  op.op,
6492
6762
  op.args,
6493
6763
  op.data ?? new Uint8Array(),
6494
6764
  op.op === "readdirPage" ? this.dirEpoch : op.responseCookieTag,
6495
- ).then(op.resolve, op.reject);
6496
- }
6765
+ op.cancelled,
6766
+ ),
6767
+ );
6497
6768
  }
6498
6769
 
6499
6770
  private drainPeerRetryQueue(): void {
6500
6771
  this.drainPeerQueue(this.peerRetryQueue);
6501
6772
  }
6502
6773
 
6503
- private drainPeerFailoverQueue(): void {
6504
- this.drainPeerQueue(this.peerFailoverQueue);
6774
+ private drainPeerRetryAndFailoverQueues(): void {
6775
+ if (!this.peerAttached || this.peerRebinding) return;
6776
+ const all = this.peerRetryQueue.splice(0).concat(this.peerFailoverQueue.splice(0));
6777
+ if (all.length) {
6778
+ this.dispatchQueuedOps(all, (op) =>
6779
+ this.dispatchPeerOperation(
6780
+ op.op,
6781
+ op.args,
6782
+ op.data ?? new Uint8Array(),
6783
+ op.op === "readdirPage" ? this.dirEpoch : op.responseCookieTag,
6784
+ op.cancelled,
6785
+ ),
6786
+ );
6787
+ }
6505
6788
  this.notifyFailoverReadyWaiters();
6506
6789
  }
6507
6790
 
6508
6791
  private drainQueuedPeerOpsOnNewHost(): void {
6509
6792
  const all = this.peerRetryQueue.splice(0).concat(this.peerFailoverQueue.splice(0));
6510
- for (const op of all) {
6511
- if (this.isStaleQueuedCookie(op)) {
6512
- op.reject(new FilesystemError(8, "stale directory cookie"));
6513
- continue;
6514
- }
6793
+ this.dispatchQueuedOps(all, (op) =>
6515
6794
  this.executeLocalOnHost(
6516
6795
  op.op,
6517
6796
  op.args,
6518
6797
  op.data ?? new Uint8Array(),
6519
6798
  op.op === "readdirPage" ? this.dirEpoch : undefined,
6520
- ).then(op.resolve, op.reject);
6521
- }
6799
+ op.cancelled,
6800
+ ),
6801
+ );
6522
6802
  this.notifyFailoverReadyWaiters();
6523
6803
  }
6524
6804