Skip to content

Commit

Permalink
fix(proxy): close proxy when server closes
Browse files Browse the repository at this point in the history
  • Loading branch information
chimurai committed Mar 28, 2021
1 parent 7c3fd07 commit 32687ee
Show file tree
Hide file tree
Showing 4 changed files with 41 additions and 10 deletions.
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

0 comments on commit 32687ee

Please sign in to comment.