From 123ebad682450fe8253e91d8fec713e9f2fa5f58 Mon Sep 17 00:00:00 2001 From: b84330808 Date: Fri, 13 Nov 2026 16:01:39 +0900 Subject: [PATCH] perf(sio): compress each client file only once The client bundle served by the Node.js HTTP server was compressed on every request. With brotli at its default quality (11), that costs about 60 ms of CPU for socket.io.min.js and 200 ms for socket.io.js per request, in the libuv threadpool. The compressed content is now computed on the first request and kept in memory, keyed by file and encoding. The response bytes are unchanged. --- packages/socket.io/lib/index.ts | 80 ++++++++++++++------ packages/socket.io/test/server-attachment.ts | 24 ++++++ 2 files changed, 80 insertions(+), 24 deletions(-) diff --git a/packages/socket.io/lib/index.ts b/packages/socket.io/lib/index.ts index a047c7446c..5afad9e86f 100644 --- a/packages/socket.io/lib/index.ts +++ b/packages/socket.io/lib/index.ts @@ -6,8 +6,8 @@ import type { } from "http"; import type { Server as HTTPSServer } from "https"; import type { Http2SecureServer, Http2Server } from "http2"; -import { createReadStream } from "fs"; -import { createDeflate, createGzip, createBrotliCompress } from "zlib"; +import { createReadStream, readFile } from "fs"; +import { brotliCompress, deflate, gzip } from "zlib"; import accepts = require("accepts"); import { pipeline } from "stream"; import path = require("path"); @@ -64,6 +64,41 @@ const CLIENT_FILES = new Set([ "socket.io.msgpack.min.js.map", ]); +const COMPRESSORS = { + br: brotliCompress, + gzip, + deflate, +}; + +type ClientFileEncoding = keyof typeof COMPRESSORS; + +// the client files are static, so each one is only compressed once per encoding +const compressedClientFiles = new Map>(); + +function compressClientFile( + filename: string, + encoding: ClientFileEncoding, +): Promise { + const key = encoding + ":" + filename; + let content = compressedClientFiles.get(key); + if (!content) { + content = new Promise((resolve, reject) => { + readFile( + path.join(__dirname, "../client-dist/", filename), + (err, data) => { + if (err) return reject(err); + COMPRESSORS[encoding](data, (err, result) => + err ? reject(err) : resolve(result), + ); + }, + ); + }); + content.catch(() => compressedClientFiles.delete(key)); + compressedClientFiles.set(key, content); + } + return content; +} + type ParentNspNameMatchFn = ( name: string, auth: { [key: string]: any }, @@ -696,34 +731,31 @@ export class Server< req: IncomingMessage, res: ServerResponse, ): void { + const encoding = accepts(req).encodings(["br", "gzip", "deflate"]); + + if (encoding === "br" || encoding === "gzip" || encoding === "deflate") { + compressClientFile(filename, encoding).then( + (content) => { + res.writeHead(200, { "content-encoding": encoding }); + res.end(content); + }, + () => { + res.writeHead(200, { "content-encoding": encoding }); + res.end(); + }, + ); + return; + } + const readStream = createReadStream( path.join(__dirname, "../client-dist/", filename), ); - const encoding = accepts(req).encodings(["br", "gzip", "deflate"]); - - const onError = (err: NodeJS.ErrnoException | null) => { + res.writeHead(200); + pipeline(readStream, res, (err) => { if (err) { res.end(); } - }; - - switch (encoding) { - case "br": - res.writeHead(200, { "content-encoding": "br" }); - pipeline(readStream, createBrotliCompress(), res, onError); - break; - case "gzip": - res.writeHead(200, { "content-encoding": "gzip" }); - pipeline(readStream, createGzip(), res, onError); - break; - case "deflate": - res.writeHead(200, { "content-encoding": "deflate" }); - pipeline(readStream, createDeflate(), res, onError); - break; - default: - res.writeHead(200); - pipeline(readStream, res, onError); - } + }); } /** diff --git a/packages/socket.io/test/server-attachment.ts b/packages/socket.io/test/server-attachment.ts index 9bbcbb7112..10ddf2c021 100644 --- a/packages/socket.io/test/server-attachment.ts +++ b/packages/socket.io/test/server-attachment.ts @@ -3,6 +3,9 @@ import { createServer } from "http"; import request from "supertest"; import expect from "expect.js"; import { getPort, successFn } from "./support/util"; +import { readFileSync } from "fs"; +import { join } from "path"; +import { brotliDecompressSync } from "zlib"; describe("server attachment", () => { describe("http.Server", () => { @@ -85,6 +88,27 @@ describe("server attachment", () => { }); }); + it("should serve the same compressed client to each request", async () => { + const srv = createServer(); + new Server(srv); + const expected = readFileSync( + join(__dirname, "../client-dist/socket.io.js"), + ); + for (let i = 0; i < 2; i++) { + const res = await request(srv) + .get("/socket.io/socket.io.js") + .set("accept-encoding", "br") + .buffer(true) + .parse((res, callback) => { + const chunks: Buffer[] = []; + res.on("data", (chunk) => chunks.push(chunk)); + res.on("end", () => callback(null, Buffer.concat(chunks))); + }); + expect(res.headers["content-encoding"]).to.be("br"); + expect(brotliDecompressSync(res.body).equals(expected)).to.be(true); + } + }); + it("should serve client with necessary CORS headers", (done) => { const srv = createServer(); new Server(srv, {