Handle abort signal in SocketManager

This commit is contained in:
Fedor Indutny 2024-11-14 12:38:43 -08:00 committed by GitHub
parent c123218e7f
commit b7d67b453a
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
3 changed files with 64 additions and 29 deletions

View file

@ -15,6 +15,7 @@ import EventListener from 'events';
import { AbortableProcess } from '../util/AbortableProcess';
import { strictAssert } from '../util/assert';
import { explodePromise } from '../util/explodePromise';
import {
BackOff,
EXTENDED_FIBONACCI_TIMEOUTS,
@ -421,7 +422,7 @@ export class SocketManager extends EventListener {
const { path } = URL.parse(url);
strictAssert(path, "Fetch can't have empty path");
const { method = 'GET', body, timeout } = init;
const { method = 'GET', body, timeout, signal } = init;
let bodyBytes: Uint8Array | undefined;
if (body === undefined) {
@ -436,13 +437,26 @@ export class SocketManager extends EventListener {
throw new Error(`Unsupported body type: ${typeof body}`);
}
return resource.sendRequest({
const { promise: abortPromise, reject } = explodePromise<Response>();
const onAbort = () => reject(new Error('Aborted'));
const cleanup = () => signal?.removeEventListener('abort', onAbort);
signal?.addEventListener('abort', onAbort, { once: true });
const responsePromise = resource.sendRequest({
verb: method,
path,
body: bodyBytes,
headers: Array.from(headers.entries()),
timeout,
});
try {
return await Promise.race([responsePromise, abortPromise]);
} finally {
cleanup();
}
}
public registerRequestHandler(handler: IRequestHandler): void {