diff --git a/__tests__/hosts.test.js b/__tests__/hosts.test.js index a0bf8c8..67f9d7d 100644 --- a/__tests__/hosts.test.js +++ b/__tests__/hosts.test.js @@ -347,6 +347,22 @@ describe("POST /hosts/ — body handling", () => { expect(status).toBe(413); expect(fs.existsSync(path.join(hostsDir, "thinkpad.json"))).toBe(false); }); + + // The 413 is followed by req.destroy(). Without Connection: close, fetch's + // keep-alive pool could send the next request on the dying socket and get a + // transport error (seen as a flaky writes.test.js run while #73 was built). + test("the 413 announces Connection: close, and the next request still gets through", async () => { + const payload = { ...validSnapshot(), padding: "x".repeat(5000) }; + const res = await fetch(`${baseUrl}/hosts/thinkpad`, { + method: "POST", + headers: { Authorization: `Bearer ${INGEST_TOKEN}`, "Content-Type": "application/json" }, + body: JSON.stringify(payload), + }); + expect(res.status).toBe(413); + expect(res.headers.get("connection")).toBe("close"); + const next = await fetch(`${baseUrl}/hosts`, { headers: { Authorization: `Bearer ${TOKEN}` } }); + expect(next.status).toBe(200); + }); }); describe("GET /hosts", () => { diff --git a/index.js b/index.js index 9f0f8f6..9ad3e4f 100644 --- a/index.js +++ b/index.js @@ -332,7 +332,11 @@ function readBody(req, res, maxBytes) { if (size > maxBytes) { settled = true; req.pause(); - res.writeHead(413); + // Connection: close tells the client this socket is about to die, so + // a keep-alive pool (undici's fetch) never sends its next request on + // it: without it, a request right after a 413 could hit the dead + // socket and fail with a transport error. + res.writeHead(413, { Connection: "close" }); // Destroy only once the 413 has been flushed: req.destroy() tears down // the socket, so cutting first would leave the client with a network // error instead of a status code.