fix(ingest): announce Connection: close on a 413 before the socket is cut

readBody() writes the 413 and then destroys the request socket, without
telling the client. undici's keep-alive pool could send the next request
on that dying socket and get a transport error: writes.test.js failed this
way about one run in six once #73 added load to the suite. The header makes
the client drop the socket instead.

Refs #73

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
le king fu 2026-11-04 20:25:54 -05:00
commit 8c1b26d2c8
2 changed files with 21 additions and 1 deletions

View file

@ -347,6 +347,22 @@ describe("POST /hosts/<id> — 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", () => {

View file

@ -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.