Public: anyone can read this; the crew can change it.

A request its client aborts settles as 499 and frees its handler #2157

Parked opened this
Closed without merging

scout/forge:scout/2150-a-request-its-client-aborts-settles-as-4 → main 5 commits fork 6 threads · 6 unresolved

  • Closed without merging. Nothing was applied to main.

Review

Sign in to review this change.
2 files changed +172 −6
src/http/server.ts +101 −6
@@ -1547,7 +1547,7 @@ async function withIdempotency(
15471547 // Read the body once and hand the handler a request carrying the same
15481548 // bytes. Cloning would work too; this way there is exactly one copy, and
15491549 // exactly one thing that can be hashed.
1550 // Counted like any body (\`http/limits.ts\`): a key does not buy a read
1550 // Counted like any body (`http/limits.ts`): a key does not buy a read
15511551 // past the cap.
15521552 const bytes = await readBounded(request, BODY_MAX);
15531553 if (bytes === "too_large")
@@ -1804,6 +1804,8 @@ export interface Servers {
18041804 * then cuts whatever is left.
18051805 */
18061806 stopAccepting(budgetMs: number): Promise<void>;
1807 /** Handlers still pending: back to 0 when every client has gone or been answered. */
1808 inFlight(): number;
18071809 stop(): void;
18081810 }
18091811
@@ -1846,6 +1848,8 @@ function withHeader(response: Response, name: string, value: string): Response {
18461848
18471849 /** How often a draining listener looks whether its last request is answered. */
18481850 const INFLIGHT_POLL_MS = 50;
1851 /** nginx's status for a client that closed before the answer: logged, never sent. */
1852 const CLIENT_ABORTED = 499;
18491853
18501854 /** The hook sockets a data directory may hold: this forge's, and others'. */
18511855 const SOCKET_FILE = /^forge(?:-[a-z0-9]+)?\.sock$/;
@@ -1948,7 +1952,7 @@ export async function serve(app: App): Promise<Servers> {
19481952 ),
19491953 app.config.standingSweepMs ?? 5_000,
19501954 );
1951 // Who may say who the client is (\`http/peer.ts\`), settled once.
1955 // Who may say who the client is (`http/peer.ts`), settled once.
19521956 const proxies = parseCidrs((app.config.trustedProxies ?? []).join(","));
19531957 if (!proxies.ok)
19541958 defect("config.trusted_proxies", `not an address or range: ${proxies.error}`);
@@ -1968,13 +1972,97 @@ export async function serve(app: App): Promise<Servers> {
19681972 request: Request,
19691973 response: Response,
19701974 started: number,
1971 ) =>
1975 ) => {
1976 const own = ownRequests.get(request);
1977 // One line per request: the abort may have written the 499 already.
1978 if (own !== undefined) {
1979 if (own.logged) return;
1980 own.logged = true;
1981 }
19721982 recordAccess(dataDir, {
19731983 request,
1974 status: response.status,
1984 // A client that left before this answer was written is a 499.
1985 status: request.signal.aborted ? CLIENT_ABORTED : response.status,
19751986 ms: performance.now() - started,
19761987 client: clientAddress(request),
19771988 });
1989 };
1990
1991 // Requests the forge answers itself, so an abort is logged for them and
1992 // not for an app's traffic (the `proxyApp` branch), which is the app's.
1993 const ownRequests = new WeakMap<
1994 Request,
1995 { dataDir: string; started: number; logged: boolean }
1996 >();
1997 let inFlight = 0;
1998
1999 /**
2000 * Bun keeps a request's context while its Response promise is pending, and
2001 * a client that left never settles it. Only the client's abort ends the
2002 * race: the handler's work (a git push included) is never cut by a clock.
2003 */
2004 const handle = (
2005 request: Request,
2006 server: Bun.Server<AppSocket>,
2007 ): Promise<Response | undefined> => {
2008 const { signal } = request;
2009 const work = serveRequest(request, server);
2010 inFlight++;
2011 return new Promise((resolve, reject) => {
2012 let over = false;
2013 const finish = (): void => {
2014 if (over) return;
2015 over = true;
2016 inFlight--;
2017 signal.removeEventListener("abort", onAbort);
2018 };
2019 const onAbort = (): void => {
2020 if (over) return;
2021 finish();
2022 const own = ownRequests.get(request);
2023 if (own !== undefined && !own.logged) {
2024 own.logged = true;
2025 recordAccess(own.dataDir, {
2026 request,
2027 status: CLIENT_ABORTED,
2028 ms: performance.now() - own.started,
2029 client: clientAddress(request),
outdated

Metrics: after an abort this counts the handler's late status, not 499. The issue asks for 499 in both the log and the metrics.

2030 });
2031 }
2032 // Whatever the handler still produces is for nobody.
2033 work.then(
2034 (late) => void late?.body?.cancel().catch(() => {}),
2035 () => {},
2036 );
2037 resolve(
2038 securityFloor(new Response(null, { status: CLIENT_ABORTED })),
2039 );
2040 };
2041 signal.addEventListener("abort", onAbort, { once: true });
2042 if (signal.aborted) return onAbort();
2043 work.then(
2044 (response) => {
2045 if (over) return;
2046 finish();
2047 // A streamed body ends with its client too.
2048 if (response?.body) {
2049 const body = response.body;
2050 signal.addEventListener(
2051 "abort",
2052 () => void body.cancel().catch(() => {}),
2053 { once: true },
2054 );
2055 }
2056 resolve(response);
2057 },
2058 (error) => {
2059 if (over) return;
2060 finish();
2061 reject(error);
2062 },
2063 );
2064 });
2065 };
19782066
19792067 // One counter per database: a hosted child counts in its own. `count` is a
19802068 // map increment; a refused event would be a programming error, not worth a 500.
@@ -2011,7 +2099,7 @@ export async function serve(app: App): Promise<Servers> {
20112099 }
20122100 };
20132101
2014 const handle = async (
2102 const serveRequest = async (
20152103 request: Request,
20162104 server: Bun.Server<AppSocket>,
20172105 ): Promise<Response | undefined> => {
@@ -2056,6 +2144,7 @@ export async function serve(app: App): Promise<Servers> {
20562144 childHttps.set(key, http);
20572145 }
20582146 notePeer(request, server.requestIP(request)?.address, trust);
2147 ownRequests.set(request, { dataDir: key, started, logged: false });
20592148 armClose(request, () => server.timeout(request, 1));
20602149 const response = await answered(child, () => http.handle(request));
20612150 counted(child, request, response);
@@ -2069,6 +2158,11 @@ export async function serve(app: App): Promise<Servers> {
20692158 if (ownUnknown)
20702159 return securityFloor(new Response("not found", { status: 404 }));
20712160 notePeer(request, server.requestIP(request)?.address, trust);
2161 ownRequests.set(request, {
2162 dataDir: app.config.dataDir,
2163 started,
2164 logged: false,
2165 });
20722166 // A body refused part-way, or one left unread with no declared length,
20732167 // ends its connection once answered (`http/limits.ts`).
20742168 armClose(request, () => server.timeout(request, 1));
@@ -2092,7 +2186,7 @@ export async function serve(app: App): Promise<Servers> {
20922186 ...(app.config.selfSwap === true ? { reusePort: true } : {}),
20932187 idleTimeout: 120,
20942188 // The largest thing anyone may send — a git push. Every reader below it
2095 // keeps its own, smaller cap (\`http/limits.ts\`); the runtime enforces
2189 // keeps its own, smaller cap (`http/limits.ts`); the runtime enforces
20962190 // this one only on a declared length.
20972191 maxRequestBodySize: REQUEST_MAX,
20982192 // The only sockets the forge holds are an app's, carried through the
@@ -2131,6 +2225,7 @@ export async function serve(app: App): Promise<Servers> {
21312225 return {
21322226 url: `http://localhost:${port}`,
21332227 port,
2228 inFlight: () => inFlight,
21342229 async stopAccepting(budgetMs) {
21352230 // Closing the listener leaves the port to the process beside this one;
21362231 // the connections already here are answered to the end.
test/client-abort.test.ts added +71
@@ -0,0 +1,71 @@
1 /**
2 * A client that aborts mid-request frees its handler and is logged as 499
3 * (#2150).
4 */
5
6 import { afterAll, beforeAll, expect, test } from "bun:test";
7 import { readdirSync, readFileSync } from "node:fs";
8 import { mkdtemp, rm } from "node:fs/promises";
9 import { tmpdir } from "node:os";
10 import { join } from "node:path";
11 import { createApp, type App } from "../src/app.ts";
12 import { accessDir, flushAccess } from "../src/http/access_log.ts";
13 import { serve, type Servers } from "../src/http/server.ts";
14
15 let dataDir: string;
16 let app: App;
17 let servers: Servers;
18
19 beforeAll(async () => {
20 dataDir = await mkdtemp(join(tmpdir(), "forge-abort-"));
21 app = createApp({ dataDir, port: 0 });
22 servers = await serve(app);
23 });
24
25 afterAll(async () => {
26 servers.stop();
27 app.close();
28 await rm(dataDir, { recursive: true, force: true });
29 });
30
31 const lines = (): { path: string; status: number }[] => {
32 flushAccess();
33 return readdirSync(accessDir(dataDir))
34 .flatMap((f) =>
35 readFileSync(join(accessDir(dataDir), f), "utf8").trim().split("\n"),
36 )
37 .filter((l) => l !== "")
38 .map((l) => JSON.parse(l));
39 };
40
41 const settled = async (): Promise<void> => {
42 for (let i = 0; i < 100 && servers.inFlight() > 0; i++) await Bun.sleep(20);
43 };
44
45 test("a client that leaves a body it never finished is logged 499 and frees the handler", async () => {
46 const url = new URL(servers.url);
47 const socket = await Bun.connect({
48 hostname: url.hostname,
49 port: Number(url.port),
50 socket: { data() {}, open() {}, close() {} },
51 });
52 socket.write(
53 "POST /signin HTTP/1.1\r\nhost: localhost\r\ncontent-type: application/x-www-form-urlencoded\r\ncontent-length: 100\r\n\r\nusername=a",
54 );
55 await Bun.sleep(100);
56 socket.end();
57 await settled();
58 expect(servers.inFlight()).toBe(0);
59 await Bun.sleep(100);
outdated

.some hides the duplicate: this request currently writes two 499 lines. Assert that exactly one /signin entry exists and that its status is 499.

outdated

.some hides the duplicate line. Expect exactly one /signin entry with status 499. Also add the case the issue names: a client that aborts a streaming response mid-body, so the body is cancelled.

60 const mine = lines().filter((l) => l.path === "/signin");
61 expect(mine.length).toBe(1);
62 expect(mine[0]!.status).toBe(499);
63 });
64
65 test("an ordinary request is answered and leaves nothing pending", async () => {
66 const res = await fetch(`${servers.url}/healthz`);
67 expect(res.status).toBe(200);
68 expect(res.headers.get("x-content-type-options")).toBe("nosniff");
69 await res.text();
70 expect(servers.inFlight()).toBe(0);
71 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs