Skip to content

Commit 2cbd4c4

Browse files
committed
fix issue where externalSignal event listener is cleared during stream
1 parent 2988c61 commit 2cbd4c4

File tree

1 file changed

+13
-21
lines changed

1 file changed

+13
-21
lines changed

packages/ai/src/requests/request.ts

Lines changed: 13 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -187,6 +187,7 @@ export async function makeRequest(
187187
requestUrlParams.singleRequestOptions.timeout >= 0
188188
? requestUrlParams.singleRequestOptions.timeout
189189
: DEFAULT_FETCH_TIMEOUT_MS;
190+
190191
const internalAbortController = new AbortController();
191192
const fetchTimeoutId = setTimeout(() => {
192193
internalAbortController.abort(
@@ -197,31 +198,25 @@ export async function makeRequest(
197198
);
198199
}, timeoutMillis);
199200

200-
const externalAbortListener = (): void => {
201-
logger.debug(`Aborting request to ${url} due to external abort signal.`);
202-
// If this listener was invoked, an external signal was aborted, so externalSignal must be defined.
203-
internalAbortController.abort(
204-
new DOMException(externalSignal!.reason, ABORT_ERROR_NAME)
205-
);
206-
};
201+
const combinedSignal = AbortSignal.any(
202+
externalSignal
203+
? [externalSignal, internalAbortController.signal]
204+
: [internalAbortController.signal]
205+
);
207206

208-
if (externalSignal) {
209-
if (externalSignal.aborted) {
210-
clearTimeout(fetchTimeoutId);
211-
throw new DOMException(
212-
externalSignal.reason ?? 'Aborted externally before fetch',
213-
ABORT_ERROR_NAME
214-
);
215-
}
216-
217-
externalSignal.addEventListener('abort', externalAbortListener);
207+
if (externalSignal && externalSignal.aborted) {
208+
clearTimeout(fetchTimeoutId);
209+
throw new DOMException(
210+
externalSignal.reason ?? 'Aborted externally before fetch',
211+
ABORT_ERROR_NAME
212+
);
218213
}
219214

220215
try {
221216
const fetchOptions: RequestInit = {
222217
method: 'POST',
223218
headers: await getHeaders(url),
224-
signal: internalAbortController.signal,
219+
signal: combinedSignal,
225220
body
226221
};
227222

@@ -297,9 +292,6 @@ export async function makeRequest(
297292
throw err;
298293
} finally {
299294
clearTimeout(fetchTimeoutId);
300-
if (externalSignal) {
301-
externalSignal.removeEventListener('abort', externalAbortListener);
302-
}
303295
}
304296
return response;
305297
}

0 commit comments

Comments
 (0)