@@ -2,31 +2,58 @@ var http = require( "http" ),
2
2
hook = require ( "../lib/hook" ) ,
3
3
logger = require ( "../lib/logger" ) ;
4
4
5
+ var port = ( function ( ) {
6
+ var index = process . argv . indexOf ( "-p" ) ;
7
+ return index === - 1 ? 8001 : + process . argv [ index + 1 ] ;
8
+ } ) ( ) ;
9
+
5
10
process . on ( "uncaughtException" , function ( error ) {
6
11
logger . error ( "Uncaught exception: " + error . stack ) ;
7
12
} ) ;
8
13
9
- http . createServer ( function ( request , response ) {
14
+ var server = http . createServer ( function ( request , response ) {
10
15
var json = "" ;
11
16
request . setEncoding ( "utf8" ) ;
12
17
request . on ( "data" , function ( chunk ) {
13
18
json += chunk ;
14
19
} ) ;
15
- request . on ( "end" , function ( ) {
16
- response . writeHead ( 200 ) ;
17
- response . end ( ) ;
18
20
21
+ request . on ( "end" , function ( ) {
19
22
try {
20
23
json = JSON . parse ( json ) ;
21
24
} catch ( e ) {
25
+ // Invalid JSON, stop processing
22
26
logger . error ( "Invalid request: " + json ) ;
27
+ response . writeHead ( 400 ) ;
28
+ response . end ( ) ;
23
29
return ;
24
30
}
25
31
32
+ // Accept the request and close the connection
33
+ response . writeHead ( 202 ) ;
34
+ response . end ( ) ;
35
+
36
+ // Process the request
26
37
hook . processHook ( json , function ( error ) {
27
38
if ( error ) {
28
39
logger . error ( "Error processing hook: " + error . stack ) ;
29
40
}
30
41
} ) ;
31
42
} ) ;
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