diff --git a/lib/middleware/proxy.js b/lib/middleware/proxy.js index 444effd31..6b0fcf730 100644 --- a/lib/middleware/proxy.js +++ b/lib/middleware/proxy.js @@ -1,4 +1,6 @@ const url = require('url') +const { Agent: httpAgent } = require('http') +const { Agent: httpsAgent } = require('https') const httpProxy = require('http-proxy') const _ = require('lodash') @@ -38,11 +40,14 @@ function parseProxyConfig (proxies, config) { } const port = proxyDetails.port || defaultPorts[proxyDetails.protocol] || config.port const changeOrigin = proxyConfiguration.changeOrigin || false + const Agent = protocol === 'https:' ? httpsAgent : httpAgent + const agent = new Agent({ keepAlive: true }) const proxy = httpProxy.createProxyServer({ target: { host: hostname, port, protocol }, xfwd: true, changeOrigin: changeOrigin, - secure: config.proxyValidateSSL + secure: config.proxyValidateSSL, + agent }) ;['proxyReq', 'proxyRes'].forEach(function (name) { @@ -62,7 +67,7 @@ function parseProxyConfig (proxies, config) { res.destroy() }) - return { path: proxyPath, baseUrl: pathname, host: hostname, port, proxy } + return { path: proxyPath, baseUrl: pathname, host: hostname, port, proxy, agent } }), 'path').reverse() } @@ -108,7 +113,14 @@ function createProxyHandler (proxies, urlRoot) { return createProxy } -exports.create = function (/* config */config, /* config.proxies */proxies) { +exports.create = function (/* config */config, /* config.proxies */proxies, /* emitter */emitter) { const proxyRecords = parseProxyConfig(proxies, config) + emitter.on('exit', (done) => { + log.debug('Destroying proxy agents') + proxyRecords.forEach((proxyRecord) => { + proxyRecord.agent.destroy() + }) + done() + }) return createProxyHandler(proxyRecords, config.urlRoot) } diff --git a/test/unit/middleware/proxy.spec.js b/test/unit/middleware/proxy.spec.js index d12f255ed..bdc83e50b 100644 --- a/test/unit/middleware/proxy.spec.js +++ b/test/unit/middleware/proxy.spec.js @@ -360,4 +360,24 @@ describe('middleware.proxy', () => { it('should handle empty proxy config', () => { expect(m.parseProxyConfig({})).to.deep.equal([]) }) + + it('should use http agent with keepAlive=true', () => { + const proxy = { '/base': 'http://localhost:8000/proxy' } + const parsedProxyConfig = m.parseProxyConfig(proxy, {}) + expect(parsedProxyConfig).to.have.length(1) + expect(parsedProxyConfig[0].proxy.options.agent).to.containSubset({ + keepAlive: true, + protocol: 'http:' + }) + }) + + it('should use https agent with keepAlive=true', () => { + const proxy = { '/base': 'https://localhost:8000/proxy' } + const parsedProxyConfig = m.parseProxyConfig(proxy, {}) + expect(parsedProxyConfig).to.have.length(1) + expect(parsedProxyConfig[0].proxy.options.agent).to.containSubset({ + keepAlive: true, + protocol: 'https:' + }) + }) })