-
Notifications
You must be signed in to change notification settings - Fork 15
/
index.js
96 lines (90 loc) · 2.81 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
// Generated by CoffeeScript 1.10.0
(function() {
var cluster, master, os, worker;
cluster = require("cluster");
os = require("os");
master = function(config) {
var count, i, j, outputStream, ref, respawn, worker, workerCount, workers;
count = parseInt(config.count || process.env.WORKER_COUNT);
workerCount = count > 0 ? count : os.cpus().length;
respawn = typeof config.respawn === "undefined" ? true : Boolean(config.respawn);
outputStream = config.outputStream && typeof config.outputStream.write === "function" ? config.outputStream.write : console.log;
workers = [];
if (config.verbose) {
outputStream("Master started on pid " + process.pid + ", forking " + workerCount + " processes");
}
for (i = j = 0, ref = workerCount; 0 <= ref ? j < ref : j > ref; i = 0 <= ref ? ++j : --j) {
worker = cluster.fork();
if (typeof config.workerListener === "function") {
worker.on("message", config.workerListener);
}
workers.push(worker);
}
cluster.on("exit", function(worker, code, signal) {
var idx;
if (config.verbose) {
outputStream((worker.process.pid + " died with " + (signal || ("exit code " + code))) + (respawn ? ", restarting" : ""));
}
idx = workers.indexOf(worker);
if (idx > -1) {
workers.splice(idx, 1);
}
if (respawn) {
worker = cluster.fork();
if (typeof config.workerListener === "function") {
worker.on("message", config.workerListener);
}
return workers.push(worker);
}
});
return process.on("SIGQUIT", function() {
var k, len, results;
respawn = false;
if (config.verbose) {
outputStream("QUIT received, will exit once all workers have finished current requests");
}
results = [];
for (k = 0, len = workers.length; k < len; k++) {
worker = workers[k];
results.push(worker.send("quit"));
}
return results;
});
};
worker = function(fn, worker) {
var server;
server = fn(worker);
if (!server) {
return;
}
if (typeof server.on === "function") {
server.on("close", function() {
return process.exit();
});
}
if (typeof server.close === "function") {
return process.on("message", function(msg) {
if (msg === "quit") {
return server.close();
}
});
}
};
module.exports = function(arg0, arg1) {
var config, fn;
fn = function() {};
config = {};
if (typeof arg0 === 'function') {
fn = arg0;
config = arg1 || config;
} else if (typeof arg1 === 'function') {
fn = arg1;
config = arg0 || config;
}
if (cluster.isMaster) {
return master(config);
} else {
return worker(fn, cluster.worker);
}
};
}).call(this);