Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
80 changes: 56 additions & 24 deletions packages/socket.io/lib/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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");
Expand Down Expand Up @@ -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<string, Promise<Buffer>>();

function compressClientFile(
filename: string,
encoding: ClientFileEncoding,
): Promise<Buffer> {
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 },
Expand Down Expand Up @@ -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);
}
});
}

/**
Expand Down
24 changes: 24 additions & 0 deletions packages/socket.io/test/server-attachment.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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", () => {
Expand Down Expand Up @@ -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, {
Expand Down
Loading