-
Notifications
You must be signed in to change notification settings - Fork 33
/
index.js
99 lines (79 loc) · 2.28 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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
const express = require('express');
const process = require('process');
const { poolHall, startPoolHall } = require('pool-hall');
const app = express();
function timeToMs(tuple) {
return (tuple[0] * 1000) + (tuple[1] / 1000000);
}
function spinWait(ms) {
const start = process.hrtime();
while(timeToMs(process.hrtime(start)) < ms) {
}
}
startPoolHall(
{
workerCount: 4,
// never go unhealthy because of dead processes
minWorkerCount: 0,
workerEnv: id => ({ PORT: 9001 + (+id) })
},
// supervisor
() => {
process.title = 'node example_app supervisor';
process.on('SIGTERM', () => {
console.log('Got SIGTERM. Going down.');
poolHall.stop().then(() => process.exit(0), () => process.exit(1));
});
process.on('SIGINT', () => {
console.log('Got SIGINT. Going down.');
poolHall.stop().then(() => process.exit(0), () => process.exit(1));
});
poolHall.on('workerUp', (id) => {
console.log(`Worker ${id} is up`);
});
poolHall.on('workerDown', (id, info) => {
console.log(`Worker ${id} is down with code ${info.signalCode || info.exitCode}`);
});
},
// worker
(ready) => {
const workerId = poolHall.worker.id;
process.title = `node example_app worker[${workerId}]`;
// simulate server boot for 20s
spinWait(20000);
const app = express();
let healthy = false;
let booted = false;
poolHall.worker.on('healthy', () => {
if (!healthy) {
console.log(`Worker ${workerId} is healthy`);
}
healthy = true;
booted = true;
});
poolHall.worker.on('unhealthy', () => {
if (healthy && booted) {
console.log(`Worker ${workerId} is unhealthy`);
}
healthy = false;
});
app.get('/health', (req, res) => {
if (healthy) {
res.type('text').send('OK\n');
} else {
res.status(503).send('NOPE\n');
}
});
app.get("/infinite", (req, res) => {
while(true) {
}
res.type('text').send('This is awkward\n');
});
app.get('/render', (req, res) => {
spinWait(200);
res.type('text').send('DONE\n');
});
const server = app.listen(process.env.PORT, "localhost", ready);
poolHall.worker.onShutdown = () => server.close(() => process.exit(0));
}
);