Skip to content

Commit e3d7a8e

Browse files
committed
Graceful startup and shutdown of HTTP server.
1 parent 8618af7 commit e3d7a8e

File tree

1 file changed

+32
-5
lines changed

1 file changed

+32
-5
lines changed

scripts/update-server.js

+32-5
Original file line numberDiff line numberDiff line change
@@ -2,31 +2,58 @@ var http = require( "http" ),
22
hook = require( "../lib/hook" ),
33
logger = require( "../lib/logger" );
44

5+
var port = (function() {
6+
var index = process.argv.indexOf( "-p" );
7+
return index === -1 ? 8001 : +process.argv[ index + 1 ];
8+
})();
9+
510
process.on( "uncaughtException", function( error ) {
611
logger.error( "Uncaught exception: " + error.stack );
712
});
813

9-
http.createServer(function( request, response ) {
14+
var server = http.createServer(function( request, response ) {
1015
var json = "";
1116
request.setEncoding( "utf8" );
1217
request.on( "data", function( chunk ) {
1318
json += chunk;
1419
});
15-
request.on( "end", function() {
16-
response.writeHead( 200 );
17-
response.end();
1820

21+
request.on( "end", function() {
1922
try {
2023
json = JSON.parse( json );
2124
} catch( e ) {
25+
// Invalid JSON, stop processing
2226
logger.error( "Invalid request: " + json );
27+
response.writeHead( 400 );
28+
response.end();
2329
return;
2430
}
2531

32+
// Accept the request and close the connection
33+
response.writeHead( 202 );
34+
response.end();
35+
36+
// Process the request
2637
hook.processHook( json, function( error ) {
2738
if ( error ) {
2839
logger.error( "Error processing hook: " + error.stack );
2940
}
3041
});
3142
});
32-
}).listen( 8001 );
43+
});
44+
45+
// If another process is using this port, keep retrying
46+
server.on( "error", function( error ) {
47+
if ( error.code === "EADDRINUSE" ) {
48+
return setTimeout(function() {
49+
// server.close();
50+
server.listen( port );
51+
}, 100 );
52+
}
53+
});
54+
55+
server.listen( port );
56+
57+
process.on( "SIGINT", function() {
58+
server.close();
59+
});

0 commit comments

Comments
 (0)