Public: anyone can read this; the crew can change it.
A request its client aborts settles as 499 and frees its handler #2157
scout/forge:scout/2150-a-request-its-client-aborts-settles-as-4 → main 5 commits fork 6 threads · 6 unresolved
2 files
changed +172
−6
src/http/server.ts +101 −6
| @@ -1547,7 +1547,7 @@ async function withIdempotency( | ||
| 1547 | 1547 | // Read the body once and hand the handler a request carrying the same |
| 1548 | 1548 | // bytes. Cloning would work too; this way there is exactly one copy, and |
| 1549 | 1549 | // 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 | |
| 1551 | 1551 | // past the cap. |
| 1552 | 1552 | const bytes = await readBounded(request, BODY_MAX); |
| 1553 | 1553 | if (bytes === "too_large") |
| @@ -1804,6 +1804,8 @@ export interface Servers { | ||
| 1804 | 1804 | * then cuts whatever is left. |
| 1805 | 1805 | */ |
| 1806 | 1806 | stopAccepting(budgetMs: number): Promise<void>; |
| 1807 | /** Handlers still pending: back to 0 when every client has gone or been answered. */ | |
| 1808 | inFlight(): number; | |
| 1807 | 1809 | stop(): void; |
| 1808 | 1810 | } |
| 1809 | 1811 | |
| @@ -1846,6 +1848,8 @@ function withHeader(response: Response, name: string, value: string): Response { | ||
| 1846 | 1848 | |
| 1847 | 1849 | /** How often a draining listener looks whether its last request is answered. */ |
| 1848 | 1850 | 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; | |
| 1849 | 1853 | |
| 1850 | 1854 | /** The hook sockets a data directory may hold: this forge's, and others'. */ |
| 1851 | 1855 | const SOCKET_FILE = /^forge(?:-[a-z0-9]+)?\.sock$/; |
| @@ -1948,7 +1952,7 @@ export async function serve(app: App): Promise<Servers> { | ||
| 1948 | 1952 | ), |
| 1949 | 1953 | app.config.standingSweepMs ?? 5_000, |
| 1950 | 1954 | ); |
| 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. | |
| 1952 | 1956 | const proxies = parseCidrs((app.config.trustedProxies ?? []).join(",")); |
| 1953 | 1957 | if (!proxies.ok) |
| 1954 | 1958 | defect("config.trusted_proxies", `not an address or range: ${proxies.error}`); |
| @@ -1968,13 +1972,97 @@ export async function serve(app: App): Promise<Servers> { | ||
| 1968 | 1972 | request: Request, |
| 1969 | 1973 | response: Response, |
| 1970 | 1974 | 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 | } | |
| 1972 | 1982 | recordAccess(dataDir, { |
| 1973 | 1983 | 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, | |
| 1975 | 1986 | ms: performance.now() - started, |
| 1976 | 1987 | client: clientAddress(request), |
| 1977 | 1988 | }); |
| 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), | |
| 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 | }; | |
| 1978 | 2066 | |
| 1979 | 2067 | // One counter per database: a hosted child counts in its own. `count` is a |
| 1980 | 2068 | // 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> { | ||
| 2011 | 2099 | } |
| 2012 | 2100 | }; |
| 2013 | 2101 | |
| 2014 | const handle = async ( | |
| 2102 | const serveRequest = async ( | |
| 2015 | 2103 | request: Request, |
| 2016 | 2104 | server: Bun.Server<AppSocket>, |
| 2017 | 2105 | ): Promise<Response | undefined> => { |
| @@ -2056,6 +2144,7 @@ export async function serve(app: App): Promise<Servers> { | ||
| 2056 | 2144 | childHttps.set(key, http); |
| 2057 | 2145 | } |
| 2058 | 2146 | notePeer(request, server.requestIP(request)?.address, trust); |
| 2147 | ownRequests.set(request, { dataDir: key, started, logged: false }); | |
| 2059 | 2148 | armClose(request, () => server.timeout(request, 1)); |
| 2060 | 2149 | const response = await answered(child, () => http.handle(request)); |
| 2061 | 2150 | counted(child, request, response); |
| @@ -2069,6 +2158,11 @@ export async function serve(app: App): Promise<Servers> { | ||
| 2069 | 2158 | if (ownUnknown) |
| 2070 | 2159 | return securityFloor(new Response("not found", { status: 404 })); |
| 2071 | 2160 | notePeer(request, server.requestIP(request)?.address, trust); |
| 2161 | ownRequests.set(request, { | |
| 2162 | dataDir: app.config.dataDir, | |
| 2163 | started, | |
| 2164 | logged: false, | |
| 2165 | }); | |
| 2072 | 2166 | // A body refused part-way, or one left unread with no declared length, |
| 2073 | 2167 | // ends its connection once answered (`http/limits.ts`). |
| 2074 | 2168 | armClose(request, () => server.timeout(request, 1)); |
| @@ -2092,7 +2186,7 @@ export async function serve(app: App): Promise<Servers> { | ||
| 2092 | 2186 | ...(app.config.selfSwap === true ? { reusePort: true } : {}), |
| 2093 | 2187 | idleTimeout: 120, |
| 2094 | 2188 | // 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 | |
| 2096 | 2190 | // this one only on a declared length. |
| 2097 | 2191 | maxRequestBodySize: REQUEST_MAX, |
| 2098 | 2192 | // 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> { | ||
| 2131 | 2225 | return { |
| 2132 | 2226 | url: `http://localhost:${port}`, |
| 2133 | 2227 | port, |
| 2228 | inFlight: () => inFlight, | |
| 2134 | 2229 | async stopAccepting(budgetMs) { |
| 2135 | 2230 | // Closing the listener leaves the port to the process beside this one; |
| 2136 | 2231 | // 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
outdated
|
||
| 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 | }); |
new above
offline
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.