Skip to content

Commit 4a2f7ff

Browse files
kulshekharflovilmart
authored andcommitted
Close client connections on SIGINT/SIGTERM (#2964)
* Close all alive connections on SIGINT/SIGTERM * Add a comment referencing the node issue.
1 parent 22c790f commit 4a2f7ff

File tree

1 file changed

+27
-0
lines changed

1 file changed

+27
-0
lines changed

src/cli/parse-server.js

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -31,9 +31,13 @@ const help = function(){
3131
function startServer(options, callback) {
3232
const app = express();
3333
const api = new ParseServer(options);
34+
const sockets = {};
35+
3436
app.use(options.mountPath, api);
3537

3638
var server = app.listen(options.port, callback);
39+
server.on('connection', initializeConnections);
40+
3741
if (options.startLiveQueryServer || options.liveQueryServerOptions) {
3842
let liveQueryServer = server;
3943
if (options.liveQueryPort) {
@@ -43,8 +47,31 @@ function startServer(options, callback) {
4347
}
4448
ParseServer.createLiveQueryServer(liveQueryServer, options.liveQueryServerOptions);
4549
}
50+
51+
function initializeConnections(socket) {
52+
/* Currently, express doesn't shut down immediately after receiving SIGINT/SIGTERM if it has client connections that haven't timed out. (This is a known issue with node - https://github.com/nodejs/node/issues/2642)
53+
54+
This function, along with `destroyAliveConnections()`, intend to fix this behavior such that parse server will close all open connections and initiate the shutdown process as soon as it receives a SIGINT/SIGTERM signal. */
55+
56+
const socketId = socket.remoteAddress + ':' + socket.remotePort;
57+
sockets[socketId] = socket;
58+
59+
socket.on('close', () => {
60+
delete sockets[socketId];
61+
});
62+
}
63+
64+
function destroyAliveConnections() {
65+
for (const socketId in sockets) {
66+
try {
67+
sockets[socketId].destroy();
68+
} catch (e) { }
69+
}
70+
}
71+
4672
var handleShutdown = function() {
4773
console.log('Termination signal received. Shutting down.');
74+
destroyAliveConnections();
4875
server.close(function () {
4976
process.exit(0);
5077
});

0 commit comments

Comments
 (0)