-
Notifications
You must be signed in to change notification settings - Fork 17
/
worker.js
70 lines (57 loc) · 1.72 KB
/
worker.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
var config = JSON.parse(process.env.WORKER_CONFIG || "{}");
// Workers can share any TCP connection
// In this case its a HTTP server
var server = require('http').createServer();
if (config.setNoDelay)
server.on('connection', function(socket) {
socket.setNoDelay(); // Disable Nagle's alg.
});
var connections = 0;
var packets = 0;
server.on('request', function(req, res) {
connections++;
var pingInterval = setInterval(function() {
res.write('ping');
packets++;
}, config.pingInterval);
res.writeHead(200);
res.write("Welcome!");
res.on('close', function() {
connections--;
clearInterval(pingInterval);
pingInterval = undefined;
});
// TODO: res.on('error') ?
});
server.listen(config.port);
// Gather statistics.
function hrtime() { var hr = process.hrtime(); return hr[0]*1e3 + hr[1]*1e-6; }
var lastTimes = {};
function timeFromLast(name) {
var curt = hrtime();
var res = 0;
if (lastTimes[name])
res = curt - lastTimes[name];
lastTimes[name] = curt;
return res;
}
// Make high-frequency sampling of event loop.
var ticks = [];
setInterval(function() {
ticks.push(timeFromLast('tick'));
}, config.samplingInterval);
// Respond on data request.
process.on('message', function(param) {
process.send({
id: param.id, // Identify this is an answer to particular request.
timeFromLast: timeFromLast('message'),
ticks: ticks,
mem: process.memoryUsage(),
conns: connections,
packets: packets,
});
ticks.length = 0;
});
// ==== GC =====================================================================
if (typeof gc === 'function')
setInterval(gc, config.gcInterval);