1'use strict'; 2 3const common = require('../common'); 4const assert = require('assert'); 5const http = require('http'); 6const Countdown = require('../common/countdown'); 7 8assert.throws(() => new http.Agent({ 9 maxTotalSockets: 'test', 10}), { 11 code: 'ERR_INVALID_ARG_TYPE', 12 name: 'TypeError', 13 message: 'The "maxTotalSockets" argument must be of type number. ' + 14 "Received type string ('test')", 15}); 16 17[-1, 0, NaN].forEach((item) => { 18 assert.throws(() => new http.Agent({ 19 maxTotalSockets: item, 20 }), { 21 code: 'ERR_OUT_OF_RANGE', 22 name: 'RangeError', 23 message: 'The value of "maxTotalSockets" is out of range. ' + 24 `It must be > 0. Received ${item}`, 25 }); 26}); 27 28assert.ok(new http.Agent({ 29 maxTotalSockets: Infinity, 30})); 31 32function start(param = {}) { 33 const { maxTotalSockets, maxSockets } = param; 34 35 const agent = new http.Agent({ 36 keepAlive: true, 37 keepAliveMsecs: 1000, 38 maxTotalSockets, 39 maxSockets, 40 maxFreeSockets: 3 41 }); 42 43 const server = http.createServer(common.mustCall((req, res) => { 44 res.end('hello world'); 45 }, 6)); 46 const server2 = http.createServer(common.mustCall((req, res) => { 47 res.end('hello world'); 48 }, 6)); 49 50 server.keepAliveTimeout = 0; 51 server2.keepAliveTimeout = 0; 52 53 const countdown = new Countdown(12, () => { 54 assert.strictEqual(getRequestCount(), 0); 55 agent.destroy(); 56 server.close(); 57 server2.close(); 58 }); 59 60 function handler(s) { 61 for (let i = 0; i < 6; i++) { 62 http.get({ 63 host: 'localhost', 64 port: s.address().port, 65 agent, 66 path: `/${i}`, 67 }, common.mustCall((res) => { 68 assert.strictEqual(res.statusCode, 200); 69 res.resume(); 70 res.on('end', common.mustCall(() => { 71 for (const key of Object.keys(agent.sockets)) { 72 assert(agent.sockets[key].length <= maxSockets); 73 } 74 assert(getTotalSocketsCount() <= maxTotalSockets); 75 countdown.dec(); 76 })); 77 })); 78 } 79 } 80 81 function getTotalSocketsCount() { 82 let num = 0; 83 for (const key of Object.keys(agent.sockets)) { 84 num += agent.sockets[key].length; 85 } 86 return num; 87 } 88 89 function getRequestCount() { 90 let num = 0; 91 for (const key of Object.keys(agent.requests)) { 92 num += agent.requests[key].length; 93 } 94 return num; 95 } 96 97 server.listen(0, common.mustCall(() => handler(server))); 98 server2.listen(0, common.mustCall(() => handler(server2))); 99} 100 101// If maxTotalSockets is larger than maxSockets, 102// then the origin check will be skipped 103// when the socket is removed. 104[{ 105 maxTotalSockets: 2, 106 maxSockets: 3, 107}, { 108 maxTotalSockets: 3, 109 maxSockets: 2, 110}, { 111 maxTotalSockets: 2, 112 maxSockets: 2, 113}].forEach(start); 114