1 module.exports = ForeverAgent
2 ForeverAgent.SSL = ForeverAgentSSL
4 var util = require('util')
5 , Agent = require('http').Agent
8 , AgentSSL = require('https').Agent
10 function ForeverAgent(options) {
12 self.options = options || {}
16 self.maxSockets = self.options.maxSockets || Agent.defaultMaxSockets
17 self.minSockets = self.options.minSockets || ForeverAgent.defaultMinSockets
18 self.on('free', function(socket, host, port) {
19 var name = host + ':' + port
20 if (self.requests[name] && self.requests[name].length) {
21 self.requests[name].shift().onSocket(socket)
22 } else if (self.sockets[name].length < self.minSockets) {
23 if (!self.freeSockets[name]) self.freeSockets[name] = []
24 self.freeSockets[name].push(socket)
26 // if an error happens while we don't use the socket anyway, meh, throw the socket away
27 function onIdleError() {
30 socket._onIdleError = onIdleError
31 socket.on('error', onIdleError)
33 // If there are no pending requests just destroy the
34 // socket and it will get removed from the pool. This
35 // gets us out of timeout issues and allows us to
36 // default to Connection:keep-alive.
42 util.inherits(ForeverAgent, Agent)
44 ForeverAgent.defaultMinSockets = 5
47 ForeverAgent.prototype.createConnection = net.createConnection
48 ForeverAgent.prototype.addRequestNoreuse = Agent.prototype.addRequest
49 ForeverAgent.prototype.addRequest = function(req, host, port) {
50 var name = host + ':' + port
51 if (this.freeSockets[name] && this.freeSockets[name].length > 0 && !req.useChunkedEncodingByDefault) {
52 var idleSocket = this.freeSockets[name].pop()
53 idleSocket.removeListener('error', idleSocket._onIdleError)
54 delete idleSocket._onIdleError
55 req._reusedSocket = true
56 req.onSocket(idleSocket)
58 this.addRequestNoreuse(req, host, port)
62 ForeverAgent.prototype.removeSocket = function(s, name, host, port) {
63 if (this.sockets[name]) {
64 var index = this.sockets[name].indexOf(s)
66 this.sockets[name].splice(index, 1)
68 } else if (this.sockets[name] && this.sockets[name].length === 0) {
70 delete this.sockets[name]
71 delete this.requests[name]
74 if (this.freeSockets[name]) {
75 var index = this.freeSockets[name].indexOf(s)
77 this.freeSockets[name].splice(index, 1)
78 if (this.freeSockets[name].length === 0) {
79 delete this.freeSockets[name]
84 if (this.requests[name] && this.requests[name].length) {
85 // If we have pending requests and a socket gets closed a new one
86 // needs to be created to take over in the pool for the one that closed.
87 this.createSocket(name, host, port).emit('free')
91 function ForeverAgentSSL (options) {
92 ForeverAgent.call(this, options)
94 util.inherits(ForeverAgentSSL, ForeverAgent)
96 ForeverAgentSSL.prototype.createConnection = createConnectionSSL
97 ForeverAgentSSL.prototype.addRequestNoreuse = AgentSSL.prototype.addRequest
99 function createConnectionSSL (port, host, options) {
102 return tls.connect(options)