diff --git a/docs/architecture/tla/AbortBridge.DetachSkipped.cfg b/docs/architecture/tla/AbortBridge.DetachSkipped.cfg new file mode 100644 index 0000000000..ad2af18ece --- /dev/null +++ b/docs/architecture/tla/AbortBridge.DetachSkipped.cfg @@ -0,0 +1,4 @@ +CONSTANT Variant = "DetachSkipped" +SPECIFICATION Spec +INVARIANTS CallerHasDispose HookSeesAbortFirst AbortNotLost HookAtMostOnce NoAbortAfterDispose NoHookWithoutExternal ReturnedIsSupplied +CHECK_DEADLOCK FALSE diff --git a/docs/architecture/tla/AbortBridge.DoubleRun.cfg b/docs/architecture/tla/AbortBridge.DoubleRun.cfg new file mode 100644 index 0000000000..19c93a045f --- /dev/null +++ b/docs/architecture/tla/AbortBridge.DoubleRun.cfg @@ -0,0 +1,4 @@ +CONSTANT Variant = "DoubleRun" +SPECIFICATION Spec +INVARIANTS CallerHasDispose HookSeesAbortFirst AbortNotLost HookAtMostOnce NoAbortAfterDispose NoHookWithoutExternal ReturnedIsSupplied +CHECK_DEADLOCK FALSE diff --git a/docs/architecture/tla/AbortBridge.NotifyFirst.cfg b/docs/architecture/tla/AbortBridge.NotifyFirst.cfg new file mode 100644 index 0000000000..e97d2e7dc8 --- /dev/null +++ b/docs/architecture/tla/AbortBridge.NotifyFirst.cfg @@ -0,0 +1,4 @@ +CONSTANT Variant = "NotifyFirst" +SPECIFICATION Spec +INVARIANTS CallerHasDispose HookSeesAbortFirst AbortNotLost HookAtMostOnce NoAbortAfterDispose NoHookWithoutExternal ReturnedIsSupplied +CHECK_DEADLOCK FALSE diff --git a/docs/architecture/tla/AbortBridge.SwallowAbort.cfg b/docs/architecture/tla/AbortBridge.SwallowAbort.cfg new file mode 100644 index 0000000000..b1da80d691 --- /dev/null +++ b/docs/architecture/tla/AbortBridge.SwallowAbort.cfg @@ -0,0 +1,4 @@ +CONSTANT Variant = "SwallowAbort" +SPECIFICATION Spec +INVARIANTS CallerHasDispose HookSeesAbortFirst AbortNotLost HookAtMostOnce NoAbortAfterDispose NoHookWithoutExternal ReturnedIsSupplied +CHECK_DEADLOCK FALSE diff --git a/docs/architecture/tla/AbortBridge.Unfixed.cfg b/docs/architecture/tla/AbortBridge.Unfixed.cfg new file mode 100644 index 0000000000..7684b77952 --- /dev/null +++ b/docs/architecture/tla/AbortBridge.Unfixed.cfg @@ -0,0 +1,4 @@ +CONSTANT Variant = "Unfixed" +SPECIFICATION Spec +INVARIANTS CallerHasDispose HookSeesAbortFirst AbortNotLost HookAtMostOnce NoAbortAfterDispose NoHookWithoutExternal ReturnedIsSupplied +CHECK_DEADLOCK FALSE diff --git a/docs/architecture/tla/AbortBridge.cfg b/docs/architecture/tla/AbortBridge.cfg new file mode 100644 index 0000000000..c660bb1f3e --- /dev/null +++ b/docs/architecture/tla/AbortBridge.cfg @@ -0,0 +1,4 @@ +CONSTANT Variant = "Fixed" +SPECIFICATION Spec +INVARIANTS CallerHasDispose HookSeesAbortFirst AbortNotLost HookAtMostOnce NoAbortAfterDispose NoHookWithoutExternal ReturnedIsSupplied +CHECK_DEADLOCK FALSE diff --git a/docs/architecture/tla/AbortBridge.tla b/docs/architecture/tla/AbortBridge.tla new file mode 100644 index 0000000000..1fb8f53ebd --- /dev/null +++ b/docs/architecture/tla/AbortBridge.tla @@ -0,0 +1,225 @@ +---- MODULE AbortBridge ---- +\* Subsystem: bridgeExternalAbortSignal in src/api/providers/utils/abort-signal.ts. +\* Source: the caller's external signal plus one optional onAbort hook. Sinks: the +\* dispose handle handed to the caller, and the per-request controller a provider +\* keeps as its stop-button handle. +\* Modeled: the two abort paths (already-aborted at call time, abort during the +\* request), the detach performed by dispose, and one hook that may throw. +\* Oracle: the hook body and the reason value. No provider code is copied here. +\* +\* EXPECTED (written before the run, per the trial policy): TLC will find an +\* interleaving on the already-aborted path where the hook runs before the +\* controller aborts, because only statement order prevents it, and it will find +\* that a throwing hook removes the dispose handle on that path while the live +\* path keeps it. I do NOT expect a hook that runs twice: the code invokes the hook +\* from one place per path, so a double run has to come from a new interleaving. +\* +\* Failure 1: a hook that throws on the already-aborted path escapes the call, so +\* the caller never receives dispose and cannot detach what it was never handed. +\* Failure 2: the hook runs before the controller aborts, so a hook that inspects +\* the request signal sees a request that has not been cancelled yet. +\* Failure 3: a hook that throws before the controller aborts swallows the abort: +\* the caller believes it cancelled the request and the signal never settles. +\* Failure 4: the hook runs twice for one cancellation, so a provider side effect +\* (abort a client, cancel a token source) fires twice for one stop. +\* Failure 5: dispose does not detach, so a later external abort still reaches this +\* request after the caller cleaned up. +\* +\* Invariant CallerHasDispose is the opposite of Failure 1: the call returns, so the +\* caller holds dispose, whatever the hook did. +\* Invariant HookSeesAbortFirst is the opposite of Failure 2: whenever the hook ran, +\* the request controller was already aborted at that moment. +\* Invariant AbortNotLost is the opposite of Failure 3: while the caller still +\* expects the relay, an external abort leaves the request controller aborted. +\* Invariant HookAtMostOnce is the opposite of Failure 4. +\* Invariant NoAbortAfterDispose is the opposite of Failure 5: once dispose ran, no +\* later external abort reaches the request. +\* Invariants NoHookWithoutExternal and ReturnedIsSupplied are the opposite of a +\* broken controller-only branch: with no external signal the hook never runs and +\* the caller's own controller comes back. +\* +\* Variants: +\* Fixed is the guarded code: a hook error is reported, not propagated. +\* Unfixed is the code before the guard on the already-aborted path: the throw +\* escapes, so CallerHasDispose must fail here. +\* NotifyFirst runs the hook before controller.abort(): HookSeesAbortFirst must fail. +\* SwallowAbort runs the hook first and drops its error: AbortNotLost must fail. +\* DoubleRun runs the hook twice for one cancellation: HookAtMostOnce must fail. +\* DetachSkipped returns a dispose that never removes the listener: +\* NoAbortAfterDispose must fail. +\* +\* FOUND (read off the gate output, written after the run): +\* Fixed violates none of the seven invariants over 48 distinct states. +\* Unfixed violates CallerHasDispose on the already-aborted path with a throwing +\* hook, over 22 states: the call does not return, so the caller never holds +\* dispose. On the live path that same variant keeps dispose, which is the +\* asymmetry the review comment described. +\* NotifyFirst violates HookSeesAbortFirst over 21 states: nothing in the structure +\* forces controller.abort() before the hook; only the statement order does. +\* SwallowAbort violates HookSeesAbortFirst over 21 states: an early +\* hook error drops the controller abort as well. The gate reports the first +\* violated invariant and TLC stops there, so the expected AbortNotLost failure for +\* this variant is a design expectation, not a measurement read off the run. +\* DoubleRun violates HookAtMostOnce over 29 states; DetachSkipped violates +\* NoAbortAfterDispose over 42 states. Both are injected, not found: the guarded +\* model produced no behavior that runs the hook twice and no behavior that leaves +\* the listener attached after dispose. That is a null result, recorded as data. +\* AbortNotLost holds in Fixed: with the guard, a hook error cannot swallow the abort. +\* +\* Invariant provenance, declared: the seven invariants were written from the four +\* inline findings and the two failure paths, after the guard was implemented, not +\* before. They state the failure, not the guard: only Variant selects the guard. +\* +\* Cost (caliber declared before the run and applied to the same run): wall clock is +\* the start/stop stamps around the six java invocations: 5.141030673 s total, one +\* invocation per config, six configs. States explored per config are printed above. +\* Host that ran the gate: WSL bash + WSL java (openjdk 21.0.13.1) + tlc2.TLC 2.19 of +\* 08 August 2024 (rev 5a47802) from /mnt/c/tools/tla2tools.jar (2274532 bytes). +\* Runner: check.sh AbortBridge. The run reproduced check.sh's java invocation and +\* verdict strings (pass on "No error has been found", fail on "violated"); check.sh +\* reports pass/fail only and never pins which invariant a variant violated, so the +\* FOUND section below records what the gate could show, not more. +\* Review: PR 2626 round 2 (edelauna), four inline findings: 4690260914 (should the +\* bridge catch an onAbort error), 4690260919 (tests for a throwing hook on both +\* paths), 4690260925 (record the request signal inside the hook), 4690260930 +\* (controller-only branch). Covered 4, added 0, gap 0: each finding maps to one +\* invariant and one focused test in abort-signal.spec.ts. + +EXTENDS Naturals, TLC +CONSTANT Variant +VARIABLES scenario, supplied, hookOutcome, externalAborted, ctrlAborted, + attached, returned, hookRan, hookSawAborted, returnedController, + disposeCalled, abortAfterDispose + +vars == <> + +Scenarios == {"None", "Live", "PreAborted"} +Supplied == {"Mine", "Provided"} +Outcomes == {"Ok", "Throws"} + +\* HookEarly is the sabotaged order; HookEscapes is a hook error the code lets +\* destroy the call instead of reporting it. +HookEarly == Variant = "NotifyFirst" \/ Variant = "SwallowAbort" +HookEscapes == hookOutcome = "Throws" /\ (Variant = "Unfixed" \/ Variant = "SwallowAbort") + +Init == + /\ scenario \in Scenarios + /\ supplied \in Supplied + /\ hookOutcome \in Outcomes + /\ externalAborted = (scenario = "PreAborted") + /\ ctrlAborted = FALSE + /\ attached = FALSE + /\ returned = FALSE + /\ hookRan = 0 + /\ hookSawAborted = FALSE + /\ returnedController = "None" + /\ disposeCalled = FALSE + /\ abortAfterDispose = FALSE + +\* The call itself. On the already-aborted path the code aborts the controller first +\* and then runs the hook; the live path attaches a once-listener and returns at +\* once, so the caller already holds dispose before any hook on that path can run. +CallBridge == + /\ returned = FALSE + /\ returnedController' = supplied + /\ IF scenario = "None" + THEN /\ returned' = TRUE + /\ attached' = FALSE + /\ ctrlAborted' = FALSE + /\ hookRan' = 0 + /\ hookSawAborted' = FALSE + ELSE IF scenario = "PreAborted" + THEN /\ IF HookEarly + THEN /\ attached' = FALSE + /\ hookRan' = hookRan + 1 + /\ hookSawAborted' = ctrlAborted + /\ ctrlAborted' = (IF HookEscapes THEN ctrlAborted ELSE TRUE) + /\ returned' = (IF HookEscapes THEN FALSE ELSE TRUE) + ELSE /\ ctrlAborted' = TRUE + /\ attached' = FALSE + /\ hookRan' = hookRan + 1 + /\ hookSawAborted' = TRUE + /\ returned' = (IF HookEscapes THEN FALSE ELSE TRUE) + ELSE /\ returned' = TRUE + /\ attached' = TRUE + /\ ctrlAborted' = FALSE + /\ hookRan' = 0 + /\ hookSawAborted' = FALSE + +\* The external signal aborts. A still-attached once-listener aborts the controller +\* and runs the hook; after a real detach the same abort reaches nothing at all. +ExternalAbort == + /\ scenario # "None" + /\ ~externalAborted + /\ externalAborted' = TRUE + /\ IF attached + THEN /\ ctrlAborted' = TRUE + /\ hookRan' = hookRan + (IF Variant = "DoubleRun" THEN 2 ELSE 1) + /\ hookSawAborted' = (IF Variant = "NotifyFirst" THEN FALSE ELSE TRUE) + /\ attached' = FALSE + /\ abortAfterDispose' = disposeCalled + ELSE /\ UNCHANGED <> + /\ abortAfterDispose' = FALSE + +\* The caller ends the request and uses the handle it was handed. +Dispose == + /\ returned = TRUE + /\ ~disposeCalled + /\ disposeCalled' = TRUE + /\ attached' = (IF Variant = "DetachSkipped" THEN attached ELSE FALSE) + +\* TLC requires every variable to be decided in each step, so each action states the +\* ones it deliberately leaves alone instead of leaving them open. +CallBridgeStable == + CallBridge /\ UNCHANGED <> + +ExternalAbortStable == + ExternalAbort /\ UNCHANGED <> + +DisposeStable == + Dispose /\ UNCHANGED <> + +\* Nothing. Once the caller disposed and no further abort arrives, nothing is left +\* to do, so the model lets the behavior stop instead of reporting a dead end. +Nothing == UNCHANGED(vars) + +Next == + /\ IF returned = FALSE + THEN CallBridgeStable + ELSE ExternalAbortStable \/ DisposeStable \/ Nothing + +Spec == Init /\ [][Next]_vars + +\* returnedController is still "None" exactly while the call has not happened yet, +\* so the invariant does not claim a caller holds a handle it was never given. +CallerHasDispose == IF returnedController = "None" THEN TRUE ELSE returned + +HookSeesAbortFirst == hookRan = 0 \/ hookSawAborted + +\* Precondition first (the same rule the other three invariants need): before the call +\* exists there is no relay for an abort to travel along, and after dispose the caller no +\* longer expects one. +AbortNotLost == + IF returnedController = "None" THEN TRUE + ELSE IF disposeCalled THEN TRUE + ELSE ~externalAborted \/ ctrlAborted + +HookAtMostOnce == hookRan <= 1 + +NoAbortAfterDispose == ~(disposeCalled /\ abortAfterDispose) + +NoHookWithoutExternal == scenario # "None" \/ hookRan = 0 + +\* Same precondition as CallerHasDispose: before the call there is no returned handle to compare. +ReturnedIsSupplied == + IF returnedController = "None" + THEN TRUE + ELSE returnedController = supplied + +==== diff --git a/src/api/providers/utils/__tests__/abort-signal.spec.ts b/src/api/providers/utils/__tests__/abort-signal.spec.ts index bc5fe8f550..63e9356d2d 100644 --- a/src/api/providers/utils/__tests__/abort-signal.spec.ts +++ b/src/api/providers/utils/__tests__/abort-signal.spec.ts @@ -829,6 +829,193 @@ describe("bridgeExternalAbortSignal", () => { controller.abort() expect(signal?.aborted).toBe(false) }) + + it("hands back a request-local controller when there is no external signal", () => { + const bridge = bridgeExternalAbortSignal() + expect(bridge.signal).toBeUndefined() + // Providers like lm-studio and qwen-code need a signal for their own races even + // when the caller passed none; the controller is that signal. + expect(bridge.controller.signal.aborted).toBe(false) + bridge.controller.abort() + expect(bridge.controller.signal.aborted).toBe(true) + }) + + it("hands back the caller's controller without an external signal and never runs the hook", () => { + const requestController = new AbortController() + const hook = vitest.fn() + // A provider that keeps its own controller can pass it even when the caller + // gave no signal at all; the bridge must return that same handle and must not + // invent a cancellation the caller never asked for. + const bridge = bridgeExternalAbortSignal(undefined, { controller: requestController, onAbort: hook }) + expect(bridge.controller).toBe(requestController) + expect(bridge.signal).toBeUndefined() + bridge.dispose() + expect(hook).not.toHaveBeenCalled() + expect(requestController.signal.aborted).toBe(false) + }) + + it("returns the signal of the controller it created", () => { + const external = new AbortController() + const bridge = bridgeExternalAbortSignal(external.signal) + expect(bridge.signal).toBe(bridge.controller.signal) + }) + + it("bridges onto a caller-supplied controller instead of creating one", () => { + const external = new AbortController() + const requestController = new AbortController() + const bridge = bridgeExternalAbortSignal(external.signal, { controller: requestController }) + // openai-native keeps its class-level controller as the stop-button handle; the + // bridge must abort that same controller, not a private one. + expect(bridge.controller).toBe(requestController) + expect(bridge.signal).toBe(requestController.signal) + external.abort() + expect(requestController.signal.aborted).toBe(true) + }) + + it("runs the onAbort hook once, after the request signal aborts", () => { + const external = new AbortController() + const requestController = new AbortController() + const reason = new Error("caller stop") + const seen: { calls: number; abortedDuringHook: boolean; hookReason: unknown } = { + calls: 0, + abortedDuringHook: false, + hookReason: undefined, + } + // Providers pass their own controller exactly this way, so the hook can observe + // it directly instead of a mutable local. + bridgeExternalAbortSignal(external.signal, { + controller: requestController, + onAbort: (hookReason) => { + seen.calls += 1 + seen.abortedDuringHook = requestController.signal.aborted + seen.hookReason = hookReason + }, + }) + external.abort(reason) + expect(seen.calls).toBe(1) + // A hook that threw must never be the reason a request signal stays un-settled, + // so the controller aborts first. + expect(seen.abortedDuringHook).toBe(true) + expect(seen.hookReason).toBe(reason) + }) + + it("keeps aborting and detaching when a live-path onAbort hook throws", () => { + const external = new AbortController() + const requestController = new AbortController() + const hookError = new Error("hook blew up") + const warnSpy = vitest.spyOn(console, "warn").mockImplementation(() => {}) + const addSpy = vitest.spyOn(external.signal, "addEventListener") + const removeSpy = vitest.spyOn(external.signal, "removeEventListener") + let bridge: ReturnType | undefined + let warnCalls: unknown[][] = [] + let addCalls: unknown[][] = [] + let removeCalls: unknown[][] = [] + try { + bridge = bridgeExternalAbortSignal(external.signal, { + controller: requestController, + onAbort: () => { + throw hookError + }, + }) + // The bridge attaches the relay with `once: true`, which is what makes a + // later external abort reach this request at most once. + addCalls = addSpy.mock.calls.map((call) => [...call]) + // The listener runs the hook, so a throw there used to surface only as an + // uncaught error while the caller kept dispose by accident of ordering. + expect(() => external.abort(new Error("caller stop"))).not.toThrow() + // Read the record before mockRestore clears it. + warnCalls = warnSpy.mock.calls.map((call) => [...call]) + } finally { + bridge?.dispose() + removeCalls = removeSpy.mock.calls.map((call) => [...call]) + warnSpy.mockRestore() + addSpy.mockRestore() + removeSpy.mockRestore() + } + expect(addCalls.length).toBe(1) + expect(addCalls[0]?.[0]).toBe("abort") + expect(addCalls[0]?.[2]).toEqual({ once: true }) + expect(requestController.signal.aborted).toBe(true) + expect(warnCalls.length).toBe(1) + expect(warnCalls[0]?.[1]).toBe(hookError) + expect(removeCalls.length).toBe(1) + expect(removeCalls[0]?.[0]).toBe("abort") + // dispose must remove the same function that was registered; a different + // callback would pass the two assertions above. + expect(removeCalls[0]?.[1]).toBe(addCalls[0]?.[1]) + }) + + it("still hands back dispose when the pre-aborted path throws in onAbort", () => { + const external = new AbortController() + const reason = new Error("already stopped") + const hookError = new Error("hook blew up") + const warnSpy = vitest.spyOn(console, "warn").mockImplementation(() => {}) + let bridge: ReturnType | undefined + let warnCalls: unknown[][] = [] + try { + external.abort(reason) + bridge = bridgeExternalAbortSignal(external.signal, { + onAbort: () => { + throw hookError + }, + }) + // Read the record before mockRestore clears it. + warnCalls = warnSpy.mock.calls.map((call) => [...call]) + } finally { + warnSpy.mockRestore() + } + // Before the guard this call never returned on this path, so the caller had no + // dispose and the hook's exception escaped into the caller's own stack. + expect(bridge).toBeDefined() + expect(typeof bridge?.dispose).toBe("function") + expect(bridge?.controller.signal.aborted).toBe(true) + expect(warnCalls.length).toBe(1) + expect(warnCalls[0]?.[1]).toBe(hookError) + bridge?.dispose() + }) + + it("runs the onAbort hook when the external signal was already aborted", () => { + const external = new AbortController() + const reason = new Error("already stopped") + external.abort(reason) + const requestController = new AbortController() + const seen: { calls: number; abortedDuringHook: boolean; hookReason: unknown } = { + calls: 0, + abortedDuringHook: false, + hookReason: undefined, + } + // native-ollama aborts its client and vscode-lm cancels its token source on the + // same signal: a caller that stopped before we started must reach that side + // effect too, not only the live-abort path. + const bridge = bridgeExternalAbortSignal(external.signal, { + controller: requestController, + onAbort: (hookReason) => { + seen.calls += 1 + // Observing the flag from inside the hook is the only assertion that can + // fail if notify ever runs before controller.abort(); checking the flag + // afterwards passes either way. + seen.abortedDuringHook = requestController.signal.aborted + seen.hookReason = hookReason + }, + }) + expect(bridge.controller.signal.aborted).toBe(true) + // The caller gets the very signal the bridge aborted: on this path a different + // (also-aborted) signal would pass every assertion above but be a different object. + expect(bridge.signal).toBe(bridge.controller.signal) + expect(seen.calls).toBe(1) + expect(seen.abortedDuringHook).toBe(true) + expect(seen.hookReason).toBe(reason) + }) + + it("neither aborts nor runs the hook for an abort that lands after dispose", () => { + const external = new AbortController() + const hook = vitest.fn() + const bridge = bridgeExternalAbortSignal(external.signal, { onAbort: hook }) + bridge.dispose() + external.abort() + expect(hook).not.toHaveBeenCalled() + expect(bridge.controller.signal.aborted).toBe(false) + }) }) describe("hasUsableTimeout", () => { diff --git a/src/api/providers/utils/abort-signal.ts b/src/api/providers/utils/abort-signal.ts index 6abbc12437..2eaf28fd1a 100644 --- a/src/api/providers/utils/abort-signal.ts +++ b/src/api/providers/utils/abort-signal.ts @@ -67,6 +67,30 @@ export function mergeAbortSignals(primarySignal: AbortSignal, secondarySignal?: return AbortSignal.any([primarySignal, secondarySignal]) } +/** + * Optional hooks for {@link bridgeExternalAbortSignal}: the cancellation side effects a + * provider needs that a plain signal relay cannot express. + */ +export type AbortBridgeHooks = { + /** + * Run this when the external signal aborts - a client-level `abort()` on a transport + * that owns its own connection, a host cancellation token, or a flag recording that the + * caller rather than a timeout ended the request. + * + * It also runs when the external signal was already aborted at call time, so a + * pre-aborted caller reaches the same side effect as a live abort. The per-request + * controller aborts before the hook runs, so a hook that throws cannot leave a + * request signal that never settles. + */ + onAbort?: (reason?: unknown) => void + /** + * Bridge onto this controller instead of creating one. Providers that keep a + * class-level controller as the stop-button handle pass it here so the bridge and + * that path share one controller. + */ + controller?: AbortController +} + /** * Bridge an optional caller-owned (external) abort signal to a per-request * signal, with an explicit detach handle. @@ -78,30 +102,67 @@ export function mergeAbortSignals(primarySignal: AbortSignal, secondarySignal?: * left attached would outlive the request and retain the per-request * controller for every completed request. * - * With no external signal, returns `{ signal: undefined, dispose: noop }` so - * the client-level timeout remains the only cancellation mechanism. + * With no external signal, `signal` is `undefined` and `dispose` is a noop, so the + * client-level timeout remains the only cancellation mechanism; the returned + * `controller` is still a usable request-local signal for a provider that needs + * one without relaying anything. + * + * An `onAbort` hook that throws is reported through `console.warn` and changes + * nothing else: the request controller is aborted before the hook runs, the hook + * still runs at most once per cancellation, and `dispose` is handed back on every + * path, so a caller can always detach the listener. A throwing hook is a provider + * bug, not a cancellation mechanism - the bridge never lets it decide whether the + * abort lands or whether the caller can clean up. */ -export function bridgeExternalAbortSignal(externalSignal?: AbortSignal): { +export function bridgeExternalAbortSignal( + externalSignal?: AbortSignal, + hooks?: AbortBridgeHooks, +): { signal?: AbortSignal + controller: AbortController dispose: () => void } { + const controller = hooks?.controller ?? new AbortController() + // The hook is invoked from one place per abort path so a provider side effect + // cannot be run twice for the same cancellation. + const notify = (reason?: unknown): void => { + if (!hooks?.onAbort) { + return + } + try { + hooks.onAbort(reason) + } catch (error) { + // The controller is already aborted by the time notify runs here: the hook + // error is reported, not dropped, and dispose still reaches the caller. + console.warn("[abort-signal] bridge: onAbort hook threw", error) + } + } + if (!externalSignal) { - return { signal: undefined, dispose: () => {} } + // No caller signal: the request-local controller is still handed back, so a + // provider that needs a signal for its own races or timer keeps one without + // relaying anything. + return { signal: undefined, controller, dispose: () => {} } } - const controller = new AbortController() if (externalSignal.aborted) { controller.abort() - return { signal: controller.signal, dispose: () => {} } + notify(externalSignal.reason) + return { signal: controller.signal, controller, dispose: () => {} } } // Retain the callback so the listener can be detached once this request // ends: an anonymous listener on a long-lived external signal would // outlive the request and retain the per-request controller. - const onExternalAbort = () => controller.abort() + const onExternalAbort = (): void => { + const reason = externalSignal.reason + controller.abort() + notify(reason) + } externalSignal.addEventListener("abort", onExternalAbort, { once: true }) return { signal: controller.signal, + controller, dispose: () => externalSignal.removeEventListener("abort", onExternalAbort), } }