Skip to content

fix(proxy): close proxy when server closes #508

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Mar 28, 2021
Merged
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
6 changes: 6 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,11 @@
# Changelog

## next

- fix(proxy): close proxy when server closes ([#508](https://github.com/chimurai/http-proxy-middleware/pull/508))
- refactor(lodash): remove lodash ([#459](https://github.com/chimurai/http-proxy-middleware/pull/459)) ([#507](https://github.com/chimurai/http-proxy-middleware/pull/507)) ([TrySound](https://github.com/TrySound))
- fix(ETIMEDOUT): return 504 on ETIMEDOUT ([#480](https://github.com/chimurai/http-proxy-middleware/pull/480)) ([aremishevsky](https://github.com/aremishevsky))

## [v1.0.6](https://github.com/chimurai/http-proxy-middleware/releases/tag/v1.0.6)

- chore(deps): lodash 4.17.20 ([#475](https://github.com/chimurai/http-proxy-middleware/pull/475))
Expand Down
24 changes: 22 additions & 2 deletions src/http-proxy-middleware.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import * as https from 'https';
import * as express from 'express';
import * as httpProxy from 'http-proxy';
import { createConfig } from './config-factory';
Expand All @@ -12,6 +13,7 @@ export class HttpProxyMiddleware {
private logger = getInstance();
private config;
private wsInternalSubscribed = false;
private serverOnCloseSubscribed = false;
private proxyOptions: Options;
private proxy: httpProxy;
private pathRewriter;
Expand Down Expand Up @@ -58,13 +60,31 @@ export class HttpProxyMiddleware {
next();
}

/**
* Get the server object to subscribe to server events;
* 'upgrade' for websocket and 'close' for graceful shutdown
*
* NOTE:
* req.socket: node >= 13
* req.connection: node < 13 (Remove this when node 12/13 support is dropped)
*/
const server: https.Server = ((req.socket ?? req.connection) as any)?.server;

if (server && !this.serverOnCloseSubscribed) {
server.on('close', () => {
this.logger.info('[HPM] server close signal received: closing proxy server');
this.proxy.close();
});
this.serverOnCloseSubscribed = true;
}

if (this.proxyOptions.ws === true) {
// use initial request to access the server object to subscribe to http upgrade event
this.catchUpgradeRequest((req.connection as any).server);
this.catchUpgradeRequest(server);
}
};

private catchUpgradeRequest = (server) => {
private catchUpgradeRequest = (server: https.Server) => {
if (!this.wsInternalSubscribed) {
server.on('upgrade', this.handleUpgrade);
// prevent duplicate upgrade handling;
Expand Down
5 changes: 3 additions & 2 deletions test/e2e/express-router.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,8 @@ import { createProxyMiddleware } from './_utils';
import { Options } from '../../src/index';

describe('Usage in Express', () => {
let app;
let server;
let app: express.Express;
let server: http.Server;

beforeEach(() => {
app = express();
Expand Down Expand Up @@ -46,6 +46,7 @@ describe('Usage in Express', () => {
server = app.listen(3000);
});

// FIXME: flaky e2e test; caused by fixed port:3000
it('should still return a response when route does not match proxyConfig', (done) => {
let responseBody;
http.get('http://localhost:3000/sub/hello', (res) => {
Expand Down
16 changes: 10 additions & 6 deletions test/e2e/http-proxy-middleware.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -382,11 +382,12 @@ describe('E2E http-proxy-middleware', () => {
});

describe('option.logLevel & option.logProvider', () => {
let logMessage;
let logMessages: string[];

beforeEach(() => {
const customLogger = (message) => {
logMessage = message;
logMessages = [];
const customLogger = (message: string) => {
logMessages.push(message);
};

agent = request(
Expand All @@ -406,9 +407,12 @@ describe('E2E http-proxy-middleware', () => {
await mockTargetServer.get('/api/foo/bar').thenReply(200);
await agent.get(`/api/foo/bar`).expect(200);

expect(logMessage).toMatchInlineSnapshot(
`"[HPM] Proxy created: /api -> http://localhost:8000"`
);
expect(logMessages).toMatchInlineSnapshot(`
Array [
"[HPM] Proxy created: /api -> http://localhost:8000",
"[HPM] server close signal received: closing proxy server",
]
`);
});
});
});
Expand Down