-
Notifications
You must be signed in to change notification settings - Fork 1
/
balancing.worker.js
184 lines (154 loc) · 6.02 KB
/
balancing.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
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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
const zmq = require('zmq');
const config = require('./config.js');
const procSignals = ['SIGHUP', 'SIGINT', 'SIGQUIT', 'SIGILL', 'SIGTRAP', 'SIGABRT', 'SIGBUS', 'SIGFPE', 'SIGUSR1', 'SIGSEGV', 'SIGTERM'/*, 'SIGUSR2'*/];
// STATE
var brokerURI;
var responder;
var initialized = false;
var terminating = false;
var doWorkerJob;
var lastActivity = Date.now();
function init(){
if(initialized) return;
initialized = true;
// Internal health checks
setInterval(checkHealth, config.PING_BASE_INTERVAL + 100);
// Termination handlers
procSignals.forEach(sig => process.on(sig, onTerminate) );
}
function checkHealth() {
if(terminating) return;
else if(!responder) return lastActivity = Date.now();
else if((Date.now() - lastActivity) >= config.INACTIVITY_TIMEOUT) {
// Reset clock
lastActivity = Date.now();
console.error(`[TinyZMQ] WARNING: No heartbeat from clients for ${config.INACTIVITY_TIMEOUT / 1000} seconds`);
reconnect();
}
}
// MESSAGE HANDLER
function onRequest(requestBuffer) {
let requestPayload;
lastActivity = Date.now();
if(requestBuffer.length == 4 && requestBuffer.toString() == 'ping') return responder.send('pong'); // done
else if(!doWorkerJob) return console.error('ERROR: No worker callback is registered. Ignoring request.');
try {
requestPayload = JSON.parse(requestBuffer.toString());
}
catch(err) {
console.error("[TinyZMQ] Got an invalid request: ", requestBuffer.toString());
responder.send(JSON.stringify({error: true, message: "Unable to parse the payload"}));
return;
}
// DO WORK
doWorkerJob(requestPayload.parameters, function(response){
let responsePayload = {
id: requestPayload.id,
response
};
responder.send(JSON.stringify(responsePayload));
});
}
// Lifecycle
function connect(uri, workerCallback){
if(terminating) return;
else if(!initialized) {
if(!uri || typeof uri != "string" || !uri.length)
throw new Error('[TinyZMQ] ERROR: expected the broker URI to connect the worker to');
else if(!workerCallback || typeof workerCallback != 'function')
throw new Error('[TinyZMQ] ERROR: expected a callback function to notify the worker');
brokerURI = uri;
doWorkerJob = workerCallback;
}
else { // already on
if(uri == brokerURI) { // no need to connect
if(typeof workerCallback == 'function')
doWorkerJob = workerCallback;
else
console.log('[TinyZMQ] WARNING: Connection already established to the broker');
return;
}
else if(!uri || typeof uri != "string" || !uri.length)
throw new Error('[TinyZMQ] ERROR: expected the broker URI to connect the worker to');
else if(responder) {
console.log('[TinyZMQ] WARNING: Connecting to another broker URI. Closing the previous connection.');
responder.close(brokerURI);
brokerURI = uri;
}
if(typeof workerCallback == 'function')
doWorkerJob = workerCallback;
}
// INITIALIZE
init();
// CONNECT TO THE BROKER
responder = zmq.socket('rep');
responder.on('message', onRequest);
if(config.DEBUG) {
// Register to monitoring events
responder.on('connect', function(fd, ep) {console.log('[TinyZMQ] Connect');});
responder.on('connect_delay', function(fd, ep) {console.log('[TinyZMQ] Connect delay');});
responder.on('connect_retry', function(fd, ep) {console.log('[TinyZMQ] Connect retry');});
responder.on('listen', function(fd, ep) {console.log('[TinyZMQ] Listen');});
responder.on('bind_error', function(fd, ep) {console.log('[TinyZMQ] Bind error');});
responder.on('accept', function(fd, ep) {console.log('[TinyZMQ] Accept');});
responder.on('accept_error', function(fd, ep) {console.log('[TinyZMQ] Accept_error');});
responder.on('close', function(fd, ep) {console.log('[TinyZMQ] Close');});
responder.on('close_error', function(fd, ep) {console.log('[TinyZMQ] Close_error');});
responder.on('disconnect', function(fd, ep) {console.log('[TinyZMQ] WARNING: Disconnected');});
// Handle monitor error
responder.on('monitor_error', function(err) {
console.log('[TinyZMQ] WARNING: Error in monitoring: %s, will restart monitoring in .5 seconds', err);
setTimeout(function() { responder.monitor(500, 0); }, 500);
});
responder.monitor(500, 0);
}
// READY
responder.connect(brokerURI);
}
function reconnect(){
if(terminating) return;
console.error("[TinyZMQ] Trying to reconnect...");
responder.disconnect(brokerURI);
responder.close(brokerURI);
setTimeout(function(){
// CONNECT TO THE BROKER
responder = zmq.socket('rep');
responder.on('message', onRequest);
if(config.DEBUG) {
// Register to monitoring events
responder.on('connect', function(fd, ep) {console.log('[TinyZMQ] Connect');});
responder.on('connect_delay', function(fd, ep) {console.log('[TinyZMQ] Connect delay');});
responder.on('connect_retry', function(fd, ep) {console.log('[TinyZMQ] Connect retry');});
responder.on('listen', function(fd, ep) {console.log('[TinyZMQ] Listen');});
responder.on('bind_error', function(fd, ep) {console.log('[TinyZMQ] Bind error');});
responder.on('accept', function(fd, ep) {console.log('[TinyZMQ] Accept');});
responder.on('accept_error', function(fd, ep) {console.log('[TinyZMQ] Accept_error');});
responder.on('close', function(fd, ep) {console.log('[TinyZMQ] Close');});
responder.on('close_error', function(fd, ep) {console.log('[TinyZMQ] Close_error');});
responder.on('disconnect', function(fd, ep) {console.log('[TinyZMQ] WARNING: Disconnected');});
// Handle monitor error
responder.on('monitor_error', function(err) {
console.log('[TinyZMQ] WARNING: Error in monitoring: %s, will restart monitoring in .5 seconds', err);
setTimeout(function() { responder.monitor(500, 0); }, 500);
});
responder.monitor(500, 0);
}
// READY
responder.connect(brokerURI);
}, 50);
}
function onTerminate(code){
console.log("\n[TinyZMQ] The process is terminating", code || '');
terminating = true;
if(responder) {
try {
responder.disconnect(brokerURI);
responder.close(brokerURI);
}
catch(e){ ; }
}
process.exit(0);
}
module.exports = {
connect // this function gets the callback to execute when a matching request is received
};