Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

fix(http): release a read body when its request closes again

Yudhi Armyndharisd68f4802e864
diff --git a/src/config/inflight-body-budget.spec.ts b/src/config/inflight-body-budget.spec.ts
index f1441f3de..934bbc798 100644
--- a/src/config/inflight-body-budget.spec.ts
+++ b/src/config/inflight-body-budget.spec.ts
@@ -1087,92 +1087,3 @@ describe('body-parser inflate backstop', () => {
expect(read('../modules/mcp/mcp.server.ts')).toContain('express.json({ limit: bodyLimit, inflate: false })');
});
});
-
-/**
- * A request holds its reservation until its response is done, not until its body is read. Over a real
- * server, Node closes the request stream as soon as the body has been consumed, long before a slow handler
- * answers, while the handler still holds the raw bytes and the parsed copy. The doubles above never emit
- * that early close, so only a real socket shows whether the budget keeps bounding what the handlers hold.
- */
-describe('a body whose handler is still running', () => {
- const BUDGET = 1000;
- let server: Server | undefined;
- let budget: InflightBodyBudget;
- let port = 0;
- let open: () => void = () => undefined;
- let handlerReached: () => void = () => undefined;
- let reached: Promise<void>;
- let gate: Promise<void>;
-
- beforeEach(async () => {
- jest.useRealTimers();
- gate = new Promise<void>(resolve => (open = resolve));
- reached = new Promise<void>(resolve => (handlerReached = resolve));
- budget = createInflightBodyBudget(BUDGET, { perClientShare: 1 });
- const app = express();
- app.use(budget.middleware);
- app.use(json({ limit: '25mb' }));
- app.post('/slow', async (_req, res) => {
- handlerReached();
- await gate;
- res.status(200).json({ ok: true });
- });
- server = createServer(app);
- await new Promise<void>(resolve => server!.listen(0, '127.0.0.1', resolve));
- port = (server.address() as AddressInfo).port;
- });
-
- afterEach(async () => {
- open();
- if (server) await new Promise<void>(resolve => server!.close(() => resolve()));
- server = undefined;
- });
-
- const post = (length: number): { done: Promise<number>; abort: () => void } => {
- const body = Buffer.from(JSON.stringify({ pad: 'x'.repeat(length - 10) }));
- let abort: () => void = () => undefined;
- const done = new Promise<number>(resolve => {
- const req = httpRequest(
- {
- host: '127.0.0.1',
- port,
- path: '/slow',
- method: 'POST',
- headers: { 'Content-Type': 'application/json', 'Content-Length': String(body.length) },
- },
- res => {
- res.resume();
- res.on('end', () => resolve(res.statusCode ?? 0));
- },
- );
- abort = () => req.destroy();
- req.on('error', () => resolve(0));
- req.end(body);
- });
- return { done, abort };
- };
-
- it('stays charged until the response is sent, so a second large body is refused meanwhile', async () => {
- const first = post(400);
- await reached;
- expect(budget.currentBytes()).toBe(400);
-
- const second = await post(700).done;
- expect(second).toBe(503);
-
- open();
- expect(await first.done).toBe(200);
- expect(budget.currentBytes()).toBe(0);
- });
-
- it('is released when the client gives up while the handler is still running', async () => {
- const first = post(400);
- await reached;
- expect(budget.currentBytes()).toBe(400);
-
- first.abort();
- await first.done;
- await new Promise<void>(resolve => setTimeout(resolve, 50));
- expect(budget.currentBytes()).toBe(0);
- });
-});
diff --git a/src/config/inflight-body-budget.ts b/src/config/inflight-body-budget.ts
index 29952def7..69d5a709b 100644
--- a/src/config/inflight-body-budget.ts
+++ b/src/config/inflight-body-budget.ts
@@ -329,9 +329,8 @@ export function createInflightBodyBudget(budgetBytes: number, options?: Inflight
};
// Exactly-once release: the first terminal event wins: normal completion (res 'finish'),
- // client/socket abort (res 'close', or req 'close' before the body is complete), stream failure
- // (req/res 'error'). An aborted upload typically fires several of these; the flag guarantees the
- // aggregate is decremented once.
+ // client/socket abort (req/res 'close'), stream failure (req/res 'error'). An aborted upload
+ // typically fires several of these; the flag guarantees the aggregate is decremented once.
const release = (): void => {
if (released) return;
released = true;
@@ -345,11 +344,7 @@ export function createInflightBodyBudget(budgetBytes: number, options?: Inflight
res.on('finish', release);
res.on('close', release);
res.on('error', release);
- // Node also closes the request stream right after a body has been read in full, while the handler
- // still holds the raw bytes and the parsed copy. That body stays charged until the response is done.
- req.on('close', () => {
- if (!req.complete) release();
- });
+ req.on('close', release);
req.on('error', release);
// Stall reaper (see STALL_TIMEOUT_MS above). Progress is measured on the SOCKET byte counter,