Skip to content

Commit dcbd961

Browse files
perf(eio): optimize polling request body buffering
Avoid repeated buffer concatenation while reading binary polling payloads by accumulating chunks and concatenating once after the request ends. Track payload size incrementally and stop processing when the HTTP buffer limit is exceeded.
1 parent 6bb2e7f commit dcbd961

1 file changed

Lines changed: 23 additions & 11 deletions

File tree

packages/engine.io/lib/transports/polling.ts

Lines changed: 23 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -129,37 +129,49 @@ export class Polling extends Transport {
129129
this.dataReq = req;
130130
this.dataRes = res;
131131

132-
let chunks = isBinary ? Buffer.concat([]) : "";
132+
const buffers: Buffer[] = [];
133+
let stringChunks = "";
134+
let contentLength = 0;
135+
let exceededMaxHttpBufferSize = false;
133136

134137
const cleanup = () => {
135138
req.removeListener("data", onData);
136139
req.removeListener("end", onEnd);
137140
req.removeListener("close", onClose);
138-
this.dataReq = this.dataRes = chunks = null;
141+
this.dataReq = this.dataRes = null;
139142
};
140143

141144
const onClose = () => {
142145
cleanup();
143146
this.onError("data request connection closed prematurely");
144147
};
145148

146-
const onData = (data) => {
147-
let contentLength;
148-
if (isBinary) {
149-
chunks = Buffer.concat([chunks, data]);
150-
contentLength = chunks.length;
151-
} else {
152-
chunks += data;
153-
contentLength = Buffer.byteLength(chunks);
154-
}
149+
const onData = (chunk) => {
150+
contentLength += isBinary ? chunk.length : Buffer.byteLength(chunk);
155151

156152
if (contentLength > this.maxHttpBufferSize) {
153+
exceededMaxHttpBufferSize = true;
157154
res.writeHead(413).end();
158155
cleanup();
156+
return;
157+
}
158+
159+
if (isBinary) {
160+
buffers.push(chunk);
161+
} else {
162+
stringChunks += chunk;
159163
}
160164
};
161165

162166
const onEnd = () => {
167+
if (exceededMaxHttpBufferSize) {
168+
return;
169+
}
170+
171+
const chunks = isBinary
172+
? Buffer.concat(buffers, contentLength)
173+
: stringChunks;
174+
163175
this.onData(chunks);
164176

165177
const headers = {

0 commit comments

Comments
 (0)