Skip to content
This repository has been archived by the owner on Apr 20, 2019. It is now read-only.

Commit

Permalink
Merge pull request #41 from jaulz/patch-1
Browse files Browse the repository at this point in the history
fix: closes all connections when stopped
  • Loading branch information
geek committed Nov 12, 2018
2 parents 79d64ee + 48f2ee0 commit 5154e76
Show file tree
Hide file tree
Showing 2 changed files with 72 additions and 0 deletions.
30 changes: 30 additions & 0 deletions lib/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
// Load modules

const Net = require('net');
const Util = require('util');
const Repl = require('repl');
const Barrier = require('cb-barrier');
const Hoek = require('hoek');
Expand Down Expand Up @@ -56,6 +57,35 @@ exports.register = async function (server, options) {
barrier.pass();
});

// Keep track of all connections
const sockets = [];
tcp.on('connection', (socket) => {

sockets.push(socket);
socket.once('close', () => {

sockets.splice(sockets.indexOf(socket), 1);
});
});

// Close all connections when Hapi server is stopped
server.ext({
type: 'onPostStop',
method: async () => {

// Close server (which keeps existing connections)
Util.promisify(tcp.close.bind(tcp))();

// Close all sockets
await Promise.all(sockets.map((socket) => {

return Util.promisify(socket.end.bind(socket))('\n', 'utf8');
}));

return null;
}
});

tcp.listen(settings.port);
await barrier;
};
Expand Down
42 changes: 42 additions & 0 deletions test/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -443,3 +443,45 @@ it('allows the use of extra repl start options', async () => {

return barrier;
});

it('closes all connections when the server is stopped', async () => {

const barrier = new Barrier();
const server = Hapi.server();
const port = await internals.availablePort();

await server.register({ plugin: Reptile, options: { port } });

const address = Net.Socket.prototype.address;
Net.Socket.prototype.address = function () {

Net.Socket.prototype.address = address;
return {
family: 'IPv4',
address: '127.0.0.1'
};
};
const sock = Net.connect(port);
let state = 0;

sock.once('close', () => {

barrier.pass();
});

sock.on('readable', () => {

const buffer = sock.read();
if (!buffer) {
return;
}

if (state === 0) {
server.stop();
}

state++;
});

return barrier;
});

0 comments on commit 5154e76

Please sign in to comment.