Updated closing logic

This commit is contained in:
delvedor
2018-12-19 19:49:29 +01:00
parent 7a181ff9ac
commit fc6d12ad3e
3 changed files with 16 additions and 10 deletions

View File

@ -1,6 +1,7 @@
'use strict'
const { EventEmitter } = require('events')
const debug = require('debug')('elasticsearch')
const Transport = require('./lib/Transport')
const Connection = require('./lib/Connection')
const ConnectionPool = require('./lib/ConnectionPool')
@ -92,8 +93,8 @@ class Client extends EventEmitter {
this.close(resolve)
})
}
this.connectionPool.empty()
callback()
debug('Closing the client')
this.connectionPool.empty(callback)
}
}

View File

@ -110,12 +110,13 @@ class Connection {
}
// TODO: write a better closing logic
close () {
close (callback = () => {}) {
debug('Closing connection', this.id)
if (this._openRequests > 0) {
setTimeout(() => this.close(), 1000)
setTimeout(() => this.close(callback), 1000)
} else {
this._agent.destroy()
callback()
}
}

View File

@ -220,7 +220,7 @@ class ConnectionPool {
*/
removeConnection (connection) {
debug('Removing connection', connection)
connection.close()
connection.close(noop)
const { id } = connection
this.connections.delete(id)
var index = this.dead.indexOf(id)
@ -233,14 +233,18 @@ class ConnectionPool {
*
* @returns {ConnectionPool}
*/
empty () {
empty (callback) {
debug('Emptying the connection pool')
var openConnections = this.connections.size
this.connections.forEach(connection => {
connection.close()
connection.close(() => {
if (--openConnections === 0) {
this.connections = new Map()
this.dead = []
callback()
}
})
})
this.connections = new Map()
this.dead = []
return this
}
/**