-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
63 lines (47 loc) · 1.62 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
'use strict';
const proxy = require('./proxy');
function socketPath(suffix) {
return `/tmp/server.${suffix}.sock`;
}
function newHandler(initServer) {
console.log('initializing new handler');
let socketSuffix = 0;
let listening = false;
const handler = function(event, context, callback) {
context.callbackWaitsForEmptyEventLoop = false;
if(!listening) {
console.log('initializing new server')
initServer(socketPath(socketSuffix), function(error) {
if (error) {
if (error.code === "EADDRINUSE") {
console.log('recieved EADDRINUSE, trying again');
++socketSuffix;
} else {
console.log(error);
callback(null, { statusCode: 500, headers: {}, body: JSON.stringify({ error: "Internal Server Error" }) });
}
} else {
listening = true;
}
handler(event, context, callback);
});
return undefined;
}
console.log('sending http request to server')
proxy.forwardRequestToSocket(socketPath(socketSuffix), event, context).then(function(data) {
console.log('received http response from server')
callback(null, data);
}).catch(function(error) {
if (error.code === 'ECONNREFUSED' || error.code === 'ENOENT') {
console.log('could not connect, rebooting server');
listening = false;
handler(event, context, callback);
} else {
console.log(error);
callback(null, { statusCode: 502, headers: {}, body: JSON.stringify({ error: '502 Bad Gateway' }) });
}
});
}
return handler
}
exports.newHandler = newHandler