Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(server): use ServerResponse's close event to catch request cancellation #1220

Merged
merged 3 commits into from
Mar 22, 2024
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/young-trees-call.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@whatwg-node/server": patch
---

Use ServerResponse's close event to catch request cancellation
2 changes: 2 additions & 0 deletions packages/server/src/createServerAdapter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ import {
isServerResponse,
iterateAsyncVoid,
NodeRequest,
nodeRequestResponseMap,
NodeResponse,
normalizeNodeRequest,
sendNodeResponse,
Expand Down Expand Up @@ -198,6 +199,7 @@ function createServerAdapter<
waitUntilPromises.push(cb.catch(err => console.error(err)));
},
};
nodeRequestResponseMap.set(nodeRequest, serverResponse);
let response$: Response | Promise<Response> | undefined;
try {
response$ = handleNodeRequest(nodeRequest, defaultServerContext as any, ...ctx);
Expand Down
48 changes: 27 additions & 21 deletions packages/server/src/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -116,6 +116,8 @@ export class ServerAdapterRequestAbortSignal extends EventTarget implements Abor

let bunNodeCompatModeWarned = false;

export const nodeRequestResponseMap = new WeakMap<NodeRequest, NodeResponse>();

export function normalizeNodeRequest(
nodeRequest: NodeRequest,
RequestCtor: typeof Request,
Expand All @@ -130,30 +132,34 @@ export function normalizeNodeRequest(
fullUrl = url.toString();
}

let signal: AbortSignal;
let signal: AbortSignal | undefined;

// If ponyfilled
if (RequestCtor !== globalThis.Request) {
signal = new ServerAdapterRequestAbortSignal();
const nodeResponse = nodeRequestResponseMap.get(nodeRequest);
nodeRequestResponseMap.delete(nodeRequest);
if (nodeResponse?.once) {
let sendAbortSignal: VoidFunction;

if (rawRequest?.once) {
rawRequest.once('close', () => {
if (rawRequest.aborted) {
(signal as ServerAdapterRequestAbortSignal).sendAbort();
}
});
}
} else {
const controller = new AbortController();
signal = controller.signal;

if (rawRequest.once) {
rawRequest.once('close', () => {
if (rawRequest.aborted) {
controller.abort();
}
});
// If ponyfilled
if (RequestCtor !== globalThis.Request) {
signal = new ServerAdapterRequestAbortSignal();
sendAbortSignal = () => (signal as ServerAdapterRequestAbortSignal).sendAbort();
} else {
const controller = new AbortController();
signal = controller.signal;
sendAbortSignal = () => controller.abort();
}

let responseFinished = false;

nodeResponse.once('finish', () => {
responseFinished = true;
});

nodeResponse.once('close', () => {
if (!responseFinished && signal && !signal.aborted) {
sendAbortSignal();
}
});
n1ru4l marked this conversation as resolved.
Show resolved Hide resolved
}

if (nodeRequest.method === 'GET' || nodeRequest.method === 'HEAD') {
Expand Down
14 changes: 9 additions & 5 deletions packages/server/test/node.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -162,18 +162,22 @@ describe('Node Specific Cases', () => {
const serverAdapter = createServerAdapter(
req =>
new Promise(resolve => {
req.signal.onabort = () => {
req.signal.addEventListener('abort', () => {
abortListener();
resolve(new Response('Hello World', { status: 200 }));
};
});
}),
);
testServer.addOnceHandler(serverAdapter);
const controller = new AbortController();
setTimeout(() => controller.abort(), 1000);
const error = await fetch(testServer.url, { signal: controller.signal }).catch(e => e);
const error$ = fetch(testServer.url, { signal: controller.signal }).catch(e => e);
await sleep(100);
expect(abortListener).toHaveBeenCalledTimes(0);
controller.abort();
await sleep(100);
const error = await error$;
expect(error.toString().toLowerCase()).toContain('abort');
await new Promise(resolve => setTimeout(resolve, 300));
await sleep(100);
expect(abortListener).toHaveBeenCalledTimes(1);
});

Expand Down
Loading