-
Notifications
You must be signed in to change notification settings - Fork 1
/
server.js
81 lines (74 loc) · 2.62 KB
/
server.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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
const port = process.argv[2] ? Number(process.argv[2]) : process.env.PORT ? Number(process.env.PORT) : 8080;
const healthcheckPath = process.env.HEALTHCHECK_PATH || '/retry-proxy/healthcheck';
const healthcheckReplies = (process.env.HEALTHCHECK_REPLIES ? Number(process.env.HEALTHCHECK_REPLIES) : 5) * 2; // 2 because both the REQ and RES are counted as a single reply
const statusCode = process.env.RESPONSE_HTTP_CODE ? Number(process.env.RESPONSE_HTTP_CODE) : 504;
const headers = process.env.RESPONSE_HTTP_HEADERS
? Object.fromEntries(process.env.RESPONSE_HTTP_HEADERS
.split(',')
.map(header => header
.trim()
.split(/:(.+)/) // split on the first colon
.filter(a => a) // remove empty strings
.map(a =>
a.trim()
.replace(/(?:^"|')|(?:"|'$)/g, '') // remove quotes at the beginning or end
.trim()
)
)
)
: {};
const responseType = process.env.RESPONSE_TYPE || 'text/html';
const responseString = process.env.RESPONSE_STRING || 'The server you requested is down. Retrying...<script>setTimeout(() => window.location.reload(), 5000);</script>';
const stream = require('stream');
const pino = require('pino');
let healthcheckRequestCount = 0;
const fastify = require('fastify')({
logger: {
serializers: {
res: (reply) => {
return {
statusCode: reply.statusCode,
headers: reply.headers,
url: reply.request.raw.url
};
},
req: (req) => {
return {
method: req.method,
url: req.url,
version: req.headers && req.headers['accept-version'],
hostname: req.hostname,
remoteAddress: req.ip,
remotePort: req.socket ? req.socket.remotePort : undefined
};
},
err: pino.stdSerializers.err
},
stream: new stream.Writable({
write: function (chunk, encoding, callback, isHealthcheck = false) {
const line = chunk.toString().trim();
if (healthcheckReplies === 0 || !(isHealthcheck = line.includes(healthcheckPath)) || (healthcheckRequestCount < healthcheckReplies && isHealthcheck && ++healthcheckRequestCount)) {
console.log(line);
}
callback();
}
})
}
});
fastify.all(healthcheckPath, async (request, reply) => {
reply.type('text/plain').send('OK');
});
fastify.all('/*', async (request, reply) => {
console.log(headers);
reply.type(responseType).code(statusCode).headers(headers)
.send(responseString);
});
const start = async () => {
try {
await fastify.listen(port, '0.0.0.0');
} catch (err) {
console.log(err);
process.exit(1);
}
};
module.exports = start;