Skip to content

Commit 5cb62ec

Browse files
committed
fix(sdk): honor caller abort signals in retry.fetch
Stop treating caller AbortErrors as timeouts, listen to Request signals, and reject immediately when the signal is already aborted.
1 parent 2fbd5c7 commit 5cb62ec

2 files changed

Lines changed: 179 additions & 63 deletions

File tree

‎packages/trigger-sdk/src/v3/retry.test.ts‎

Lines changed: 82 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,18 @@
11
import { SEMATTRS_HTTP_URL } from "@opentelemetry/semantic-conventions";
2-
import { describe, expect, it } from "vitest";
2+
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
33
import {
44
createAttributesFromHeaders,
55
createFetchAttributes,
66
createFetchResponseAttributes,
7+
retry,
78
} from "./retry.js";
89

10+
vi.mock("./wait.js", () => ({
11+
wait: {
12+
until: vi.fn(async () => undefined),
13+
},
14+
}));
15+
916
describe("retry fetch telemetry", () => {
1017
it("omits URL credentials, query parameters, and fragments", () => {
1118
const attributes = createFetchAttributes(
@@ -54,3 +61,77 @@ describe("retry fetch telemetry", () => {
5461
expect(attributes).not.toHaveProperty("http.response.header.set-cookie");
5562
});
5663
});
64+
65+
describe("retry.fetch abort signal", () => {
66+
const originalFetch = globalThis.fetch;
67+
let fetchCount = 0;
68+
69+
beforeEach(() => {
70+
fetchCount = 0;
71+
});
72+
73+
afterEach(() => {
74+
globalThis.fetch = originalFetch;
75+
});
76+
77+
it("rejects immediately when init.signal is already aborted", async () => {
78+
globalThis.fetch = (async () => {
79+
fetchCount += 1;
80+
return new Response("ok");
81+
}) as typeof fetch;
82+
83+
await expect(retry.fetch("https://example.com", { signal: AbortSignal.abort() })).rejects.toMatchObject({
84+
name: "AbortError",
85+
});
86+
expect(fetchCount).toBe(0);
87+
});
88+
89+
it("rejects when a Request input carries an already-aborted signal", async () => {
90+
globalThis.fetch = (async () => {
91+
fetchCount += 1;
92+
return new Response("ok");
93+
}) as typeof fetch;
94+
95+
await expect(
96+
retry.fetch(new Request("https://example.com", { signal: AbortSignal.abort() }))
97+
).rejects.toMatchObject({ name: "AbortError" });
98+
expect(fetchCount).toBe(0);
99+
});
100+
101+
it("does not retry when the caller aborts mid-request", async () => {
102+
globalThis.fetch = (async (_input, init) => {
103+
fetchCount += 1;
104+
return await new Promise<Response>((_resolve, reject) => {
105+
const signal = init?.signal;
106+
if (!signal) {
107+
reject(new Error("missing signal"));
108+
return;
109+
}
110+
111+
if (signal.aborted) {
112+
const error = new Error("This operation was aborted.");
113+
error.name = "AbortError";
114+
reject(error);
115+
return;
116+
}
117+
118+
signal.addEventListener(
119+
"abort",
120+
() => {
121+
const error = new Error("This operation was aborted.");
122+
error.name = "AbortError";
123+
reject(error);
124+
},
125+
{ once: true }
126+
);
127+
});
128+
}) as typeof fetch;
129+
130+
const controller = new AbortController();
131+
const pending = retry.fetch("https://example.com/slow", { signal: controller.signal });
132+
controller.abort();
133+
134+
await expect(pending).rejects.toMatchObject({ name: "AbortError" });
135+
expect(fetchCount).toBe(1);
136+
});
137+
});

‎packages/trigger-sdk/src/v3/retry.ts‎

Lines changed: 97 additions & 62 deletions
Original file line numberDiff line numberDiff line change
@@ -152,6 +152,31 @@ class FetchErrorWithSpan extends Error {
152152

153153
const MAX_ATTEMPTS = 10;
154154

155+
function resolveCallerAbortSignal(
156+
input: RequestInfo | URL,
157+
init?: RequestInit
158+
): AbortSignal | undefined {
159+
if (init?.signal) {
160+
return init.signal;
161+
}
162+
163+
if (typeof Request !== "undefined" && input instanceof Request) {
164+
return input.signal;
165+
}
166+
167+
return undefined;
168+
}
169+
170+
function createCallerAbortError(signal?: AbortSignal): Error {
171+
if (signal?.reason instanceof Error) {
172+
return signal.reason;
173+
}
174+
175+
const error = new Error("This operation was aborted.");
176+
error.name = "AbortError";
177+
return error;
178+
}
179+
155180
async function retryFetch(
156181
input: RequestInfo | URL,
157182
init?: RetryFetchRequestInit | undefined
@@ -160,36 +185,59 @@ async function retryFetch(
160185
"retry.fetch()",
161186
async (span) => {
162187
let attempt = 1;
188+
const callerSignal = resolveCallerAbortSignal(input, init);
189+
190+
if (callerSignal?.aborted) {
191+
throw createCallerAbortError(callerSignal);
192+
}
163193

164194
while (true) {
165195
try {
166-
const abortController = new AbortController();
196+
if (callerSignal?.aborted) {
197+
throw createCallerAbortError(callerSignal);
198+
}
167199

200+
const abortController = new AbortController();
168201
const timeoutId = init?.timeoutInMs
169202
? setTimeout(() => {
170203
abortController.abort();
171-
}, init?.timeoutInMs)
204+
}, init.timeoutInMs)
172205
: undefined;
173206

174-
init?.signal?.addEventListener("abort", () => {
175-
abortController.abort();
176-
});
177-
178-
const [response, span] = await doFetchRequest(
179-
input,
180-
{ ...(init ?? {}), signal: abortController.signal },
181-
attempt
182-
);
207+
const onCallerAbort = () => {
208+
abortController.abort(callerSignal?.reason);
209+
};
183210

184-
if (timeoutId) {
185-
clearTimeout(timeoutId);
211+
if (callerSignal) {
212+
if (callerSignal.aborted) {
213+
abortController.abort(callerSignal.reason);
214+
} else {
215+
callerSignal.addEventListener("abort", onCallerAbort, { once: true });
216+
}
186217
}
187218

188-
if (response.ok) {
189-
span.setAttributes(createFetchResponseAttributes(response));
219+
let response: Response;
220+
let requestSpan: Span;
190221

191-
span.end();
222+
try {
223+
[response, requestSpan] = await doFetchRequest(
224+
input,
225+
{ ...(init ?? {}), signal: abortController.signal },
226+
attempt
227+
);
228+
} finally {
229+
if (timeoutId) {
230+
clearTimeout(timeoutId);
231+
}
192232

233+
if (callerSignal) {
234+
callerSignal.removeEventListener("abort", onCallerAbort);
235+
}
236+
}
237+
238+
if (response.ok) {
239+
requestSpan.setAttributes(createFetchResponseAttributes(response));
240+
requestSpan.end();
193241
return response;
194242
}
195243

@@ -199,67 +247,65 @@ async function retryFetch(
199247
attempt
200248
);
201249

202-
if (!nextRetry) {
203-
span.setAttributes(createFetchResponseAttributes(response));
204-
205-
span.end();
206-
207-
return response;
208-
}
209-
210-
if (attempt >= MAX_ATTEMPTS) {
211-
span.setAttributes(createFetchResponseAttributes(response));
212-
213-
span.end();
214-
250+
if (!nextRetry || attempt >= MAX_ATTEMPTS) {
251+
requestSpan.setAttributes(createFetchResponseAttributes(response));
252+
requestSpan.end();
215253
return response;
216254
}
217255

218256
if (nextRetry.type === "delay") {
219257
const continueDate = new Date(Date.now() + nextRetry.value);
220-
span.setAttribute(SemanticInternalAttributes.RETRY_AT, continueDate.toISOString());
221-
span.setAttribute(SemanticInternalAttributes.RETRY_COUNT, attempt);
222-
span.setAttribute(SemanticInternalAttributes.RETRY_DELAY, `${nextRetry.value}ms`);
223-
224-
span.end();
225-
258+
requestSpan.setAttribute(
259+
SemanticInternalAttributes.RETRY_AT,
260+
continueDate.toISOString()
261+
);
262+
requestSpan.setAttribute(SemanticInternalAttributes.RETRY_COUNT, attempt);
263+
requestSpan.setAttribute(
264+
SemanticInternalAttributes.RETRY_DELAY,
265+
`${nextRetry.value}ms`
266+
);
267+
requestSpan.end();
226268
await wait.until({ date: continueDate });
227269
} else {
228270
const now = Date.now();
229271
const nextRetryDate = new Date(nextRetry.value);
230272
const isInFuture = nextRetryDate.getTime() > now;
231273

232-
span.setAttribute(
274+
requestSpan.setAttribute(
233275
SemanticInternalAttributes.RETRY_AT,
234-
new Date(nextRetry.value).toISOString()
276+
nextRetryDate.toISOString()
235277
);
236-
span.setAttribute(SemanticInternalAttributes.RETRY_COUNT, attempt);
278+
requestSpan.setAttribute(SemanticInternalAttributes.RETRY_COUNT, attempt);
237279

238280
if (isInFuture) {
239-
span.setAttribute(
281+
requestSpan.setAttribute(
240282
SemanticInternalAttributes.RETRY_DELAY,
241283
`${nextRetry.value - now}ms`
242284
);
243285
}
244286

245-
span.end();
246-
247-
await wait.until({ date: new Date(nextRetry.value) });
287+
requestSpan.end();
288+
await wait.until({ date: nextRetryDate });
248289
}
249290
} catch (e) {
291+
if (e instanceof Error && e.name === "AbortError" && callerSignal?.aborted) {
292+
throw e;
293+
}
294+
250295
if (e instanceof FetchErrorWithSpan && e.originalError instanceof Error) {
251296
if (e.originalError.name === "AbortError") {
297+
// Caller-initiated aborts must not be retried as timeouts.
298+
if (callerSignal?.aborted) {
299+
e.span.end();
300+
throw e.originalError;
301+
}
302+
252303
const nextRetryDelay = calculateNextRetryDelay(
253304
resolveDefaults(init?.retry, "timeout", defaultFetchRetryOptions.timeout),
254305
attempt
255306
);
256307

257-
if (!nextRetryDelay) {
258-
e.span.end();
259-
throw e;
260-
}
261-
262-
if (attempt >= MAX_ATTEMPTS) {
308+
if (!nextRetryDelay || attempt >= MAX_ATTEMPTS) {
263309
e.span.end();
264310
throw e;
265311
}
@@ -268,12 +314,9 @@ async function retryFetch(
268314
e.span.setAttribute(SemanticInternalAttributes.RETRY_AT, continueDate.toISOString());
269315
e.span.setAttribute(SemanticInternalAttributes.RETRY_COUNT, attempt);
270316
e.span.setAttribute(SemanticInternalAttributes.RETRY_DELAY, `${nextRetryDelay}ms`);
271-
272317
e.span.end();
273-
274318
await wait.until({ date: continueDate });
275-
276-
continue; // Move to the next attempt
319+
continue;
277320
} else if (
278321
e.originalError.name === "TypeError" &&
279322
"cause" in e.originalError &&
@@ -288,12 +331,7 @@ async function retryFetch(
288331
attempt
289332
);
290333

291-
if (!nextRetryDelay) {
292-
e.span.end();
293-
throw e;
294-
}
295-
296-
if (attempt >= MAX_ATTEMPTS) {
334+
if (!nextRetryDelay || attempt >= MAX_ATTEMPTS) {
297335
e.span.end();
298336
throw e;
299337
}
@@ -304,12 +342,9 @@ async function retryFetch(
304342
);
305343
e.span.setAttribute(SemanticInternalAttributes.RETRY_COUNT, attempt);
306344
e.span.setAttribute(SemanticInternalAttributes.RETRY_DELAY, `${nextRetryDelay}ms`);
307-
308345
e.span.end();
309-
310346
await wait.until({ date: new Date(Date.now() + nextRetryDelay) });
311-
312-
continue; // Move to the next attempt
347+
continue;
313348
}
314349
}
315350

0 commit comments

Comments
 (0)