Skip to content

Commit

Permalink
better connection draining for shutdown handler
Browse files Browse the repository at this point in the history
  • Loading branch information
esatterwhite committed May 28, 2017
1 parent b401edd commit 177488a
Show file tree
Hide file tree
Showing 3 changed files with 26 additions and 17 deletions.
18 changes: 13 additions & 5 deletions lib/tcp.js
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,8 @@ module.exports = function tcp( method, url, payload, id, cache ){
})
}

module.exports.shutdown = shutdown

function getPool(addr, opts) {
if (connections.has(addr)) return connections.get(addr)
const pool = Pool.createPool({
Expand Down Expand Up @@ -57,14 +59,20 @@ function getPool(addr, opts) {
return pool
}

function onSignal() {
debug('open connections', connections.size)
for (var [key, value] of connections.entries()) {
function shutdown(cb = ()=>{}) {
const entries = connections.entries()
const run = () => {
const next = entries.next()
if (next.done) return cb()
const [key, value] = next.value
debug('disconnecting %s', key)
value.drain().then(() => {
value.clear()
debug(`removing tcp connection to ${key}`)
connections.delete(key)
run()
})
}

run()
}
process.once('SIGINT', onSignal)
process.once('SIGTERM', onSignal)
6 changes: 3 additions & 3 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "skyring-tcp-transport",
"version": "1.0.0",
"name": "@skyring/tcp-trasport",
"version": "0.1.0",
"description": "A TCP transport for skyring service",
"main": "index.js",
"scripts": {
Expand Down Expand Up @@ -28,7 +28,7 @@
"generic-pool": "^3.1.7"
},
"devDependencies": {
"skyring": "^4.0.4",
"skyring": "^4.2.0",
"supertest": "^3.0.0",
"tap": "^10.3.2"
}
Expand Down
19 changes: 10 additions & 9 deletions test/transport.tcp.spec.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
'use strict'

const net = require('net')
, os = require('os')
, path = require('path')
, tap = require('tap')
, supertest = require('supertest')
Expand Down Expand Up @@ -90,8 +91,9 @@ test('pool', (t) => {
})
}
t.on('end', (done) => {
console.log("shutting down")
handler.close()
server.close()
server.shutdown()
})
t.test('set up skyring server', (tt) => {
server = new Skyring({
Expand All @@ -112,19 +114,18 @@ test('pool', (t) => {
}, 2000)
})
t.test('success - should deliver payload', (tt) => {
tt.plan(150)
tt.plan(151)
handler = net.createServer((socket) => {
console.log('connection')
socket.setEncoding('utf8')
socket.once('data', (data) => {
tt.match(data, /fake/)
tt.pass('timeout executed')
})
}).listen(5555).unref()

for (var x = 0; x < 150; x++ ) {
doRequest({error: () => {}})
}
}).listen(5555, (err) => {
tt.error(err)
for (var x = 0; x < 150; x++ ) {
doRequest({error: () => {}})
}
})
})
t.end()
})
Expand Down

0 comments on commit 177488a

Please sign in to comment.