Skip to content

Commit

Permalink
fix: clean 'close' event listeners on socket server after generating …
Browse files Browse the repository at this point in the history
…new proxy config. (#5001)
  • Loading branch information
cwj0417 authored and alexander-akait committed Jan 22, 2024
1 parent 5ec6a39 commit 26aae7e
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 0 deletions.
6 changes: 6 additions & 0 deletions lib/Server.js
Original file line number Diff line number Diff line change
Expand Up @@ -2087,6 +2087,12 @@ class Server {

if (newProxyConfig !== proxyConfig) {
proxyConfig = newProxyConfig;
const socket = req.socket != null ? req.socket : req.connection;
// @ts-ignore
const server = socket != null ? socket.server : null;
if (server) {
server.removeAllListeners("close");
}
proxyMiddleware =
/** @type {RequestHandler} */
(getProxyMiddleware(proxyConfig));
Expand Down
16 changes: 16 additions & 0 deletions test/server/proxy-option.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -75,9 +75,21 @@ const proxyOption = [
},
];

let maxServerListeners = 0;
const proxyOptionOfArray = [
{ context: "/proxy1", target: `http://localhost:${port1}` },
function proxy(req, res, next) {
if (req != null) {
const socket = req.socket != null ? req.socket : req.connection;
// @ts-ignore
const server = socket != null ? socket.server : null;
if (server) {
maxServerListeners = Math.max(
maxServerListeners,
server.listeners("close").length
);
}
}
return {
context: "/api/proxy2",
target: `http://localhost:${port2}`,
Expand Down Expand Up @@ -463,6 +475,10 @@ describe("proxy option", () => {
expect(response.statusCode).toEqual(200);
expect(response.text).toEqual("foo+next+function");
});

it("should not exist multiple close events registered", async () => {
expect(maxServerListeners).toBeLessThanOrEqual(1);
});
});

describe("as an array without the `route` option", () => {
Expand Down

0 comments on commit 26aae7e

Please sign in to comment.