-
-
Notifications
You must be signed in to change notification settings - Fork 31
/
worker.js
272 lines (250 loc) · 7.56 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
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
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
const debug = require('debug')('faktory-worker:worker');
const uuid = require('uuid');
const compose = require('koa-compose');
const Client = require('./client');
const wrapNonErrors = require('./wrap-non-errors');
const START_DELAY = process.env.NODE_ENV === 'test' ? 0 : 50;
const sleep = (ms, value = true) => new Promise(resolve => (
setTimeout(() => resolve(value), ms)
));
/**
* Representation of a worker process with many concurrent job processors. Works at the
* concurrency set in options during construction. Will hold at most `concurrency` jobs
* in-memory while processing at any one time. Listens for signals to quiet or shutdown.
* Should not be started more than once per-process, nor should more than one worker be
* started per-process.
*
* @example
* const worker = new Worker({
* queues: ['critical', 'default', 'low'],
* });
*
* worker.work();
*/
class Worker {
/**
* @param {object} [options]
* @param {String} [options.wid=uuid().slice(0, 8)]: the wid the worker will use
* @param {Number} [options.concurrency=20]: how many jobs this worker can process at once
* @param {Number} [options.shutdownTimeout=8]: the amount of time in seconds that the worker
* may take to finish a job before exiting
* ungracefully
* @param {Number} [options.beatInterval=15]: the amount of time in seconds between each
* heartbeat
* @param {string[]} [options.queues=['default']]: the queues this worker will fetch jobs from
* @param {function[]} [options.middleware=[]]: a set of middleware to run before performing
* each job
* in koa.js-style middleware execution signature
* @param {Registry} [options.registry=Registry]: the job registry to use when working
*/
constructor(options = {}) {
this.wid = options.wid || uuid().slice(0, 8);
this.concurrency = options.concurrency || 20;
this.shutdownTimeout = (options.timeout || 8) * 1000;
this.beatInterval = (options.beatInterval || 15) * 1000;
this.queues = [].concat(options.queues || 'default');
this.middleware = [].concat(options.middleware || []);
this.registry = options.registry || {};
this.processors = {};
this.client = new Client({
wid: this.wid,
url: options.url,
host: options.host,
port: options.port,
password: options.password,
poolSize: this.concurrency + 2,
labels: options.labels || [],
});
}
/**
* @private
* @param {string} pid
* @return {undefined}
*/
async tick(pid) {
if (this.quieted) return;
try {
const job = await this.fetch();
if (job) await this.handle(job);
} catch (e) {
console.error(e);
await sleep(2000);
} finally {
setImmediate(() => this.setTick(pid));
}
}
/**
* starts the worker fetch loop and job processing
*
* @return {Worker} self, when working has been stopped by a signal or concurrent
* call to stop or quiet
* @see Worker.quiet
* @see Worker.stop
*/
async work() {
debug('work concurrency=%i', this.concurrency);
this.execute = this.createExecutor();
this.heartbeat = setInterval(() => this.beat(), this.beatInterval);
this.trapSignals();
const starts = Array(this.concurrency)
.fill(0)
.map(async (_, i) => {
await sleep(i * START_DELAY);
this.setTick(`p${i + 1}`);
});
await Promise.all(starts);
return this;
}
setTick(pid) {
this.processors[pid] = this.tick(pid);
}
/**
* Signals to the worker to discontinue fetching new jobs and allows the worker
* to continue processing any currently-running jobs
*
* @return {undefined}
*/
quiet() {
debug('quiet');
this.quieted = true;
}
/**
* stops the worker
*
* @return {promise} resolved when worker stops
*/
async stop() {
Worker.removeSignalHandlers();
debug('stop');
this.quiet();
this.stopped = true;
clearInterval(this.heartbeat);
return new Promise(async (resolve) => {
const timeout = setTimeout(async () => {
debug('shutdown timeout exceeded');
// @TODO fail in progress jobs so they retry faster
this.client.close();
resolve();
process.exit(1);
}, this.shutdownTimeout);
try {
debug('awaiting in progress');
await Promise.all(this.inProgress);
debug('all clear');
await this.client.close();
clearTimeout(timeout);
resolve();
} catch (e) {
console.warn('error during forced shutdown:', e);
}
});
}
/**
* Returns an array of ids of processors with a job currently in progress
*
* @return {array} array of processor ids
*/
get inProgress() {
return Object.values(this.processors);
}
/**
* Sends a heartbeat for this server and interprets the response state (if present)
* to quiet or terminate the worker
*
* @private
* @return {undefined}
*/
async beat() {
const response = await this.client.beat();
switch (response) {
case 'quiet':
this.quiet();
break;
case 'terminate':
this.stop();
break;
default:
break;
}
}
/**
* Fetches a job from the defined queues.
*
* @private
* @return {JobPayload|null} a job payload from the server or null when there are
* no jobs
*/
fetch() {
return this.client.fetch(...this.queues);
}
/**
* Builds a koa-compose stack of the middleware functions in addition to
* two worker-added middleware functions for pulling the job function from the
* registry and calling the job function and/or thunk
*
* @private
* @return {function} entrypoint function to the middleware stack
*/
createExecutor() {
const { registry } = this;
return compose([
...this.middleware,
function getJobFnFromRegistry(ctx, next) {
const { job: { jobtype } } = ctx;
ctx.fn = registry[jobtype];
if (!ctx.fn) throw new Error(`No jobtype registered: ${jobtype}`);
return next();
},
async function callJobFn(ctx, next) {
const { fn, job: { args } } = ctx;
const thunkOrPromise = await fn(...args);
if (typeof thunkOrPromise === 'function') {
await thunkOrPromise(ctx);
} else {
await thunkOrPromise;
}
return next();
}
]);
}
/**
* Handles a job from the server by executing it and either acknowledging
* or failing the job when done
*
* @private
* @param {JobPayload} job the job payload from the server
* @return {string} 'ack' or 'fail' depending on job handling result
*/
async handle(job) {
const { jid } = job;
try {
debug(`executing ${jid}`);
await this.execute({ job });
await this.client.ack(jid);
debug(`ACK ${jid}`);
return 'ack';
} catch (e) {
const error = wrapNonErrors(e);
await this.client.fail(jid, error);
debug(`FAIL ${jid}`);
return 'fail';
}
}
/**
* @private
*/
trapSignals() {
// istanbul ignore next
process
.once('SIGTERM', () => this.stop())
.once('SIGTSTP', () => this.quiet())
.once('SIGINT', () => this.stop());
}
static removeSignalHandlers() {
process
.removeAllListeners('SIGTERM')
.removeAllListeners('SIGTSTP')
.removeAllListeners('SIGINT');
}
}
module.exports = Worker;