Skip to content

Commit 521f329

Browse files
1220moritzclaude
andcommitted
feat(api): abort signal support for Zoo Gateway completePrompt
Follow the shared abort-signal contract (as in requesty.ts): bridge the caller's signal to a per-request signal, merge the optional timeout, race model lookup and the SDK call against the signal, normalize aborts to AbortError without surfacing a gateway error, drop a late result, and detach the bridge listener on every exit path. Tests cover a pre-aborted signal, a caller abort and a timeout-only abort during model lookup, an abort mid-flight while the SDK ignores the signal, an SDK abort error after the caller aborts, a completion that resolves just before the abort, and removal of the same abort listener. Split out of #2306. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1 parent 53cb5b5 commit 521f329

2 files changed

Lines changed: 199 additions & 14 deletions

File tree

‎src/api/providers/__tests__/zoo-gateway.spec.ts‎

Lines changed: 128 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -520,6 +520,7 @@ describe("ZooGatewayHandler", () => {
520520
temperature: ZOO_GATEWAY_DEFAULT_TEMPERATURE,
521521
max_completion_tokens: 64000,
522522
}),
523+
{},
523524
)
524525
})
525526

@@ -534,6 +535,133 @@ describe("ZooGatewayHandler", () => {
534535
)
535536
})
536537

538+
it("forwards a per-request signal and the timeout to the SDK", async () => {
539+
const handler = new ZooGatewayHandler(mockOptions)
540+
const caller = new AbortController()
541+
542+
await handler.completePrompt("Test", { abortSignal: caller.signal, timeoutMs: 5_000 })
543+
544+
const requestOptions = mockCreate.mock.calls[0][1] as { signal?: AbortSignal; timeout?: number }
545+
expect(requestOptions.signal).toBeInstanceOf(AbortSignal)
546+
expect(requestOptions.signal).not.toBe(caller.signal)
547+
expect(requestOptions.timeout).toBe(5_000)
548+
})
549+
550+
it("sends no signal when the caller gives none", async () => {
551+
const handler = new ZooGatewayHandler(mockOptions)
552+
553+
await handler.completePrompt("Test")
554+
555+
expect(mockCreate.mock.calls[0][1]).toEqual({})
556+
})
557+
558+
it("rejects with an AbortError and sends no request when the signal is pre-aborted", async () => {
559+
const handler = new ZooGatewayHandler(mockOptions)
560+
const caller = new AbortController()
561+
caller.abort()
562+
563+
await expect(handler.completePrompt("Test", { abortSignal: caller.signal })).rejects.toMatchObject({
564+
name: "AbortError",
565+
})
566+
expect(mockCreate).not.toHaveBeenCalled()
567+
})
568+
569+
it("rejects with an AbortError when the timeout alone expires during model lookup", async () => {
570+
const { getModels } = await import("../fetchers/modelCache")
571+
vitest.mocked(getModels).mockImplementation(() => new Promise(() => {}))
572+
const handler = new ZooGatewayHandler(mockOptions)
573+
574+
await expect(handler.completePrompt("Test", { timeoutMs: 20 })).rejects.toMatchObject({
575+
name: "AbortError",
576+
message: "The Zoo Gateway request was aborted",
577+
})
578+
expect(mockCreate).not.toHaveBeenCalled()
579+
})
580+
581+
it("rejects with an AbortError when the signal aborts during model lookup", async () => {
582+
const { getModels } = await import("../fetchers/modelCache")
583+
vitest.mocked(getModels).mockImplementation(() => new Promise(() => {}))
584+
const handler = new ZooGatewayHandler(mockOptions)
585+
const caller = new AbortController()
586+
587+
const pending = handler.completePrompt("Test", { abortSignal: caller.signal })
588+
caller.abort()
589+
590+
await expect(pending).rejects.toMatchObject({
591+
name: "AbortError",
592+
message: "The Zoo Gateway request was aborted",
593+
})
594+
expect(mockCreate).not.toHaveBeenCalled()
595+
})
596+
597+
it("rejects with an AbortError at once when aborted mid-flight, without a gateway error", async () => {
598+
const handler = new ZooGatewayHandler(mockOptions)
599+
const caller = new AbortController()
600+
let sdkSignal: AbortSignal | undefined
601+
// The SDK call never settles, as when the SDK sleeps between retries.
602+
mockCreate.mockImplementation((_params: unknown, requestOptions: { signal?: AbortSignal }) => {
603+
sdkSignal = requestOptions.signal
604+
return new Promise(() => {})
605+
})
606+
607+
const pending = handler.completePrompt("Test", { abortSignal: caller.signal })
608+
await vitest.waitFor(() => expect(mockCreate).toHaveBeenCalled())
609+
caller.abort()
610+
611+
await expect(pending).rejects.toMatchObject({
612+
name: "AbortError",
613+
message: "The Zoo Gateway request was aborted",
614+
})
615+
expect(sdkSignal?.aborted).toBe(true)
616+
expect(showErrorMessage).not.toHaveBeenCalled()
617+
})
618+
619+
it("reports an SDK abort error after the caller aborts as an AbortError, not a gateway error", async () => {
620+
const handler = new ZooGatewayHandler(mockOptions)
621+
const caller = new AbortController()
622+
mockCreate.mockImplementation(async () => {
623+
caller.abort()
624+
throw new Error("Request was aborted.")
625+
})
626+
627+
await expect(handler.completePrompt("Test", { abortSignal: caller.signal })).rejects.toMatchObject({
628+
name: "AbortError",
629+
})
630+
expect(showErrorMessage).not.toHaveBeenCalled()
631+
})
632+
633+
it("does not return a completion that resolves just before the caller aborts", async () => {
634+
const handler = new ZooGatewayHandler(mockOptions)
635+
const caller = new AbortController()
636+
let resolveCompletion: (value: unknown) => void = () => {}
637+
const completion = new Promise((resolve) => {
638+
resolveCompletion = resolve
639+
})
640+
mockCreate.mockImplementation(() => completion)
641+
642+
const pending = handler.completePrompt("Test", { abortSignal: caller.signal })
643+
await vitest.waitFor(() => expect(mockCreate).toHaveBeenCalled())
644+
// This callback runs after the handler's own race settles but before completePrompt resumes,
645+
// so only the check after the await can drop the late result.
646+
void completion.then(() => caller.abort())
647+
resolveCompletion({ choices: [{ message: { role: "assistant", content: "late" } }] })
648+
649+
await expect(pending).rejects.toMatchObject({ name: "AbortError" })
650+
})
651+
652+
it("removes the same abort listener from the caller's signal that it added", async () => {
653+
const handler = new ZooGatewayHandler(mockOptions)
654+
const caller = new AbortController()
655+
const addListener = vitest.spyOn(caller.signal, "addEventListener")
656+
const removeListener = vitest.spyOn(caller.signal, "removeEventListener")
657+
658+
await handler.completePrompt("Test", { abortSignal: caller.signal })
659+
660+
const abortListeners = addListener.mock.calls.filter(([type]) => type === "abort")
661+
expect(abortListeners).toHaveLength(1)
662+
expect(removeListener).toHaveBeenCalledWith("abort", abortListeners[0][1])
663+
})
664+
537665
it("returns an empty string when the model returns no content", async () => {
538666
const handler = new ZooGatewayHandler(mockOptions)
539667
mockCreate.mockImplementation(async () => ({

‎src/api/providers/zoo-gateway.ts‎

Lines changed: 71 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,18 @@ import type {
3030
import { NOT_PROVIDED } from "./constants"
3131
import { RouterProvider } from "./router-provider"
3232
import { getZooGatewayModels } from "./fetchers/zoo-gateway"
33+
import {
34+
bridgeExternalAbortSignal,
35+
createAbortError,
36+
hasUsableTimeout,
37+
isRequestAborted,
38+
mergeAbortSignalAndTimeout,
39+
rejectOnAbort,
40+
throwIfAborted,
41+
toSdkTimeoutMs,
42+
} from "./utils/abort-signal"
43+
44+
const ZOO_GATEWAY_PROVIDER_NAME = "Zoo Gateway"
3345

3446
function getApiErrorStatus(error: unknown): number | undefined {
3547
if (typeof error === "object" && error !== null && "status" in error) {
@@ -294,12 +306,33 @@ export class ZooGatewayHandler extends RouterProvider implements SingleCompletio
294306
}
295307
}
296308

297-
async completePrompt(prompt: string, _options?: CompletePromptOptions): Promise<string> {
309+
async completePrompt(prompt: string, options?: CompletePromptOptions): Promise<string> {
298310
this.ensureAuthenticated()
299311

300-
const { id: modelId, info } = await this.fetchModel()
312+
// Same abort-signal contract as the other providers (see requesty.ts): the SDK gets a
313+
// per-request signal bridged from the caller's signal, so its abort listener does not stay on
314+
// the caller's long-lived signal. The `finally` below detaches the bridge on every exit path.
315+
const { signal: bridgedCallerSignal, dispose: removeExternalAbortListener } = bridgeExternalAbortSignal(
316+
options?.abortSignal,
317+
)
318+
const requestAbortSignal = mergeAbortSignalAndTimeout(bridgedCallerSignal, options?.timeoutMs)
301319

302320
try {
321+
throwIfAborted(requestAbortSignal)
322+
323+
let model: Awaited<ReturnType<ZooGatewayHandler["fetchModel"]>>
324+
try {
325+
model = requestAbortSignal
326+
? await rejectOnAbort(this.fetchModel(), requestAbortSignal, ZOO_GATEWAY_PROVIDER_NAME)
327+
: await this.fetchModel()
328+
} catch (error) {
329+
if (isRequestAborted(error, requestAbortSignal)) {
330+
throw createAbortError(ZOO_GATEWAY_PROVIDER_NAME)
331+
}
332+
throw error
333+
}
334+
const { id: modelId, info } = model
335+
303336
const requestOptions: OpenAI.Chat.ChatCompletionCreateParams = {
304337
model: modelId,
305338
messages: [{ role: "user", content: prompt }],
@@ -312,21 +345,45 @@ export class ZooGatewayHandler extends RouterProvider implements SingleCompletio
312345

313346
requestOptions.max_completion_tokens = info.maxTokens
314347

315-
const response = await this.client.chat.completions.create(requestOptions)
316-
return response.choices[0]?.message.content || ""
317-
} catch (error) {
348+
const createOptions: OpenAI.RequestOptions = {
349+
...(requestAbortSignal && { signal: requestAbortSignal }),
350+
...(hasUsableTimeout(options?.timeoutMs) && { timeout: toSdkTimeoutMs(options.timeoutMs) }),
351+
}
352+
353+
let response: OpenAI.Chat.ChatCompletion
318354
try {
319-
await surfaceGatewayApiError(error)
320-
} catch (surfaceError) {
321-
console.error(
322-
"Failed to surface Zoo Gateway error:",
323-
surfaceError instanceof Error ? surfaceError.message : surfaceError,
324-
)
355+
const pendingCompletion = this.client.chat.completions.create(requestOptions, createOptions)
356+
// Race the completion against the signal: the SDK does not observe the signal while it
357+
// sleeps between retries, so awaiting the SDK call alone can outlive the cancel.
358+
response = requestAbortSignal
359+
? await rejectOnAbort(pendingCompletion, requestAbortSignal, ZOO_GATEWAY_PROVIDER_NAME)
360+
: await pendingCompletion
361+
} catch (error) {
362+
// A cancel or timeout is not a gateway failure: do not show a gateway error for it.
363+
if (requestAbortSignal?.aborted) {
364+
throw createAbortError(ZOO_GATEWAY_PROVIDER_NAME)
365+
}
366+
try {
367+
await surfaceGatewayApiError(error)
368+
} catch (surfaceError) {
369+
console.error(
370+
"Failed to surface Zoo Gateway error:",
371+
surfaceError instanceof Error ? surfaceError.message : surfaceError,
372+
)
373+
}
374+
if (error instanceof Error) {
375+
throw new Error(`Zoo Gateway completion error: ${error.message}`)
376+
}
377+
throw error
325378
}
326-
if (error instanceof Error) {
327-
throw new Error(`Zoo Gateway completion error: ${error.message}`)
379+
380+
if (requestAbortSignal?.aborted) {
381+
// The response resolved after the request was aborted: do not return the late result.
382+
throw createAbortError(ZOO_GATEWAY_PROVIDER_NAME)
328383
}
329-
throw error
384+
return response.choices[0]?.message.content || ""
385+
} finally {
386+
removeExternalAbortListener()
330387
}
331388
}
332389
}

0 commit comments

Comments
 (0)