-
Notifications
You must be signed in to change notification settings - Fork 86
/
Copy pathindex.js
598 lines (530 loc) · 18.1 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
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
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
const EventEmitter = require('events');
const fs = require('fs');
const { resolve } = require('path');
const pWaitFor = require('p-wait-for');
const combineErrors = require('combine-errors');
const debug = require('debug')('bree');
const isSANB = require('is-string-and-not-blank');
const isValidPath = require('is-valid-path');
const later = require('@breejs/later');
const threads = require('bthreads');
const { setTimeout, setInterval } = require('safe-timers');
const {
isSchedule,
getName,
getHumanToMs,
parseValue,
getJobNames
} = require('./job-utils');
const buildJob = require('./job-builder');
const validateJob = require('./job-validator');
// Bthreads requires us to do this for web workers (see bthreads docs for insight)
threads.Buffer = Buffer;
// Instead of `threads.browser` checks below, we previously used this boolean
// const hasFsStatSync = typeof fs === 'object' && typeof fs.statSync === 'function';
class Bree extends EventEmitter {
constructor(config) {
super();
this.config = {
// We recommend using Cabin for logging
// <https://cabinjs.com>
logger: console,
// Set this to `false` to prevent requiring a root directory of jobs
// (e.g. if your jobs are not all in one directory)
root: threads.browser /* istanbul ignore next */
? threads.resolve('jobs')
: resolve('jobs'),
// Default timeout for jobs
// (set this to `false` if you do not wish for a default timeout to be set)
timeout: 0,
// Default interval for jobs
// (set this to `0` for no interval, and > 0 for a default interval to be set)
interval: 0,
// This is an Array of your job definitions (see README for examples)
jobs: [],
// <https://breejs.github.io/later/parsers.html#cron>
// (can be overridden on a job basis with same prop name)
hasSeconds: false,
// <https://github.com/Airfooox/cron-validate>
cronValidate: {},
// If you set a value > 0 here, then it will terminate workers after this time (ms)
closeWorkerAfterMs: 0,
// Could also be mjs if desired
// (this is the default extension if you just specify a job's name without ".js" or ".mjs")
defaultExtension: 'js',
// Default worker options to pass to ~`new Worker`~ `new threads.Worker`
// (can be overridden on a per job basis)
// <https://nodejs.org/api/worker_threads.html#worker_threads_new_worker_filename_options>
worker: {},
// Custom handler to execute when error events are emitted by the workers or when they exit
// with non-zero code
// pass in a callback function with following signature: `(error, workerMetadata) => { // custom handling here }`
errorHandler: null,
// Custom handler executed when a `message` event is received from a worker.
// A special 'done' even is also broadcasted while leaving worker shutdown logic in place.
workerMessageHandler: null,
//
// if you set this to `true`, then a second arg is passed to log output
// and it will be an Object with `{ worker: Object }` set, for example:
// (see the documentation at <https://nodejs.org/api/worker_threads.html> for more insight)
//
// logger.info('...', {
// worker: {
// isMainThread: Boolean
// resourceLimits: Object,
// threadId: String
// }
// });
//
outputWorkerMetadata: false,
...config
};
//
// if `hasSeconds` is `true` then ensure that
// `cronValidate` object has `override` object with `useSeconds` set to `true`
// <https://github.com/breejs/bree/issues/7>
//
if (this.config.hasSeconds) {
this.config.cronValidate = {
...this.config.cronValidate,
preset:
this.config.cronValidate && this.config.cronValidate.preset
? this.config.cronValidate.preset
: 'default',
override: {
...(this.config.cronValidate && this.config.cronValidate.override
? this.config.cronValidate.override
: {}),
useSeconds: true
}
};
}
debug('config', this.config);
this.closeWorkerAfterMs = {};
this.workers = {};
this.timeouts = {};
this.intervals = {};
this.isSchedule = isSchedule;
this.getWorkerMetadata = this.getWorkerMetadata.bind(this);
this.run = this.run.bind(this);
this.start = this.start.bind(this);
this.stop = this.stop.bind(this);
this.add = this.add.bind(this);
this.remove = this.remove.bind(this);
this.validateJob = validateJob;
this.getName = getName;
this.getHumanToMs = getHumanToMs;
this.parseValue = parseValue;
// Validate root (sync check)
if (isSANB(this.config.root)) {
/* istanbul ignore next */
if (!threads.browser && isValidPath(this.config.root)) {
const stats = fs.statSync(this.config.root);
if (!stats.isDirectory()) {
throw new Error(
`Root directory of ${this.config.root} does not exist`
);
}
}
}
// Validate timeout
this.config.timeout = this.parseValue(this.config.timeout);
debug('timeout', this.config.timeout);
// Validate interval
this.config.interval = this.parseValue(this.config.interval);
debug('interval', this.config.interval);
//
// if `this.config.jobs` is an empty array
// then we should try to load `jobs/index.js`
//
if (
this.config.root &&
(!Array.isArray(this.config.jobs) || this.config.jobs.length === 0)
) {
try {
this.config.jobs = threads.require(this.config.root);
} catch (err) {
this.config.logger.error(err);
}
}
//
// validate jobs
//
if (!Array.isArray(this.config.jobs)) {
throw new TypeError('Jobs must be an Array');
}
// Provide human-friendly errors for complex configurations
const errors = [];
/*
Jobs = [
'name',
{ name: 'boot' },
{ name: 'timeout', timeout: ms('3s') },
{ name: 'cron', cron: '* * * * *' },
{ name: 'cron with timeout', timeout: '3s', cron: '* * * * *' },
{ name: 'interval', interval: ms('4s') }
{ name: 'interval', path: '/some/path/to/script.js', interval: ms('4s') },
{ name: 'timeout', timeout: 'three minutes' },
{ name: 'interval', interval: 'one minute' },
{ name: 'timeout', timeout: '3s' },
{ name: 'interval', interval: '30d' },
{ name: 'schedule object', interval: { schedules: [] } }
]
*/
for (let i = 0; i < this.config.jobs.length; i++) {
try {
const names = getJobNames(this.config.jobs, i);
validateJob(this.config.jobs[i], i, names, this.config);
this.config.jobs[i] = buildJob(this.config.jobs[i], this.config);
} catch (err) {
errors.push(err);
}
}
// If there were any errors then throw them
if (errors.length > 0) {
throw combineErrors(errors);
}
debug('this.config.jobs', this.config.jobs);
}
getWorkerMetadata(name, meta = {}) {
const job = this.config.jobs.find((j) => j.name === name);
if (!job) {
throw new Error(`Job "${name}" does not exist`);
}
if (!this.config.outputWorkerMetadata && !job.outputWorkerMetadata) {
return meta &&
(typeof meta.err !== 'undefined' || typeof meta.message !== 'undefined')
? meta
: undefined;
}
return this.workers[name]
? {
...meta,
worker: {
isMainThread: this.workers[name].isMainThread,
resourceLimits: this.workers[name].resourceLimits,
threadId: this.workers[name].threadId
}
}
: meta;
}
run(name) {
debug('run', name);
if (name) {
const job = this.config.jobs.find((j) => j.name === name);
if (!job) {
throw new Error(`Job "${name}" does not exist`);
}
if (this.workers[name]) {
return this.config.logger.warn(
new Error(`Job "${name}" is already running`),
this.getWorkerMetadata(name)
);
}
debug('starting worker', name);
const object = {
...(this.config.worker ? this.config.worker : {}),
...(job.worker ? job.worker : {}),
workerData: {
job,
...(this.config.worker && this.config.worker.workerData
? this.config.worker.workerData
: {}),
...(job.worker && job.worker.workerData ? job.worker.workerData : {})
}
};
this.workers[name] = new threads.Worker(job.path, object);
this.emit('worker created', name);
debug('worker started', name);
const prefix = `Worker for job "${name}"`;
this.workers[name].on('online', () => {
// If we specified a value for `closeWorkerAfterMs`
// then we need to terminate it after that execution time
const closeWorkerAfterMs = Number.isFinite(job.closeWorkerAfterMs)
? job.closeWorkerAfterMs
: this.config.closeWorkerAfterMs;
if (Number.isFinite(closeWorkerAfterMs) && closeWorkerAfterMs > 0) {
debug('worker has close set', name, closeWorkerAfterMs);
this.closeWorkerAfterMs[name] = setTimeout(() => {
/* istanbul ignore else */
if (this.workers[name]) {
debug('worker has been terminated', name);
this.workers[name].terminate();
}
}, closeWorkerAfterMs);
}
this.config.logger.info(
`${prefix} online`,
this.getWorkerMetadata(name)
);
});
this.workers[name].on('message', (message) => {
const metadata = this.getWorkerMetadata(name, { message });
if (this.config.workerMessageHandler) {
this.config.workerMessageHandler({
name,
...metadata
});
} else if (message === 'done') {
this.config.logger.info(`${prefix} signaled completion`, metadata);
} else {
this.config.logger.info(`${prefix} sent a message`, metadata);
}
if (message === 'done') {
this.workers[name].removeAllListeners('message');
this.workers[name].removeAllListeners('exit');
this.workers[name].terminate();
delete this.workers[name];
}
});
// NOTE: you cannot catch messageerror since it is a Node internal
// (if anyone has any idea how to catch this in tests let us know)
/* istanbul ignore next */
this.workers[name].on('messageerror', (err) => {
if (this.config.errorHandler) {
this.config.errorHandler(err, {
name,
...this.getWorkerMetadata(name, { err })
});
} else {
this.config.logger.error(
`${prefix} had a message error`,
this.getWorkerMetadata(name, { err })
);
}
});
this.workers[name].on('error', (err) => {
if (this.config.errorHandler) {
this.config.errorHandler(err, {
name,
...this.getWorkerMetadata(name, { err })
});
} else {
this.config.logger.error(
`${prefix} had an error`,
this.getWorkerMetadata(name, { err })
);
}
});
this.workers[name].on('exit', (code) => {
const level = code === 0 ? 'info' : 'error';
if (level === 'error' && this.config.errorHandler) {
this.config.errorHandler(
new Error(`${prefix} exited with code ${code}`),
{
name,
...this.getWorkerMetadata(name)
}
);
} else {
this.config.logger[level](
`${prefix} exited with code ${code}`,
this.getWorkerMetadata(name)
);
}
delete this.workers[name];
this.emit('worker deleted', name);
});
return;
}
for (const job of this.config.jobs) {
this.run(job.name);
}
}
start(name) {
debug('start', name);
if (name) {
const job = this.config.jobs.find((j) => j.name === name);
if (!job) {
throw new Error(`Job ${name} does not exist`);
}
if (this.timeouts[name] || this.intervals[name] || this.workers[name]) {
return this.config.logger.warn(
new Error(`Job "${name}" is already started`)
);
}
debug('job', job);
// Check for date and if it is in the past then don't run it
if (job.date instanceof Date) {
debug('job date', job);
if (job.date.getTime() < Date.now()) {
debug('job date was in the past');
return;
}
this.timeouts[name] = setTimeout(() => {
this.run(name);
if (this.isSchedule(job.interval)) {
debug('job.interval is schedule', job);
this.intervals[name] = later.setInterval(
() => this.run(name),
job.interval
);
} else if (Number.isFinite(job.interval) && job.interval > 0) {
debug('job.interval is finite', job);
this.intervals[name] = setInterval(
() => this.run(name),
job.interval
);
} else {
debug('job.date was scheduled to run only once', job);
}
delete this.timeouts[name];
}, job.date.getTime() - Date.now());
return;
}
// This is only complex because both timeout and interval can be a schedule
if (this.isSchedule(job.timeout)) {
debug('job timeout is schedule', job);
this.timeouts[name] = later.setTimeout(() => {
this.run(name);
if (this.isSchedule(job.interval)) {
debug('job.interval is schedule', job);
this.intervals[name] = later.setInterval(
() => this.run(name),
job.interval
);
} else if (Number.isFinite(job.interval) && job.interval > 0) {
debug('job.interval is finite', job);
this.intervals[name] = setInterval(
() => this.run(name),
job.interval
);
}
delete this.timeouts[name];
}, job.timeout);
return;
}
if (Number.isFinite(job.timeout)) {
debug('job timeout is finite', job);
this.timeouts[name] = setTimeout(() => {
this.run(name);
if (this.isSchedule(job.interval)) {
debug('job.interval is schedule', job);
this.intervals[name] = later.setInterval(
() => this.run(name),
job.interval
);
} else if (Number.isFinite(job.interval) && job.interval > 0) {
debug('job.interval is finite', job.interval);
this.intervals[name] = setInterval(
() => this.run(name),
job.interval
);
}
delete this.timeouts[name];
}, job.timeout);
} else if (this.isSchedule(job.interval)) {
debug('job.interval is schedule', job);
this.intervals[name] = later.setInterval(
() => this.run(name),
job.interval
);
} else if (Number.isFinite(job.interval) && job.interval > 0) {
debug('job.interval is finite', job);
this.intervals[name] = setInterval(() => this.run(name), job.interval);
}
return;
}
for (const job of this.config.jobs) {
this.start(job.name);
}
}
async stop(name) {
if (name) {
if (this.timeouts[name]) {
if (
typeof this.timeouts[name] === 'object' &&
typeof this.timeouts[name].clear === 'function'
) {
this.timeouts[name].clear();
}
delete this.timeouts[name];
}
if (this.intervals[name]) {
if (
typeof this.intervals[name] === 'object' &&
typeof this.intervals[name].clear === 'function'
) {
this.intervals[name].clear();
}
delete this.intervals[name];
}
if (this.workers[name]) {
this.workers[name].once('message', (message) => {
if (message === 'cancelled') {
this.config.logger.info(
`Gracefully cancelled worker for job "${name}"`,
this.getWorkerMetadata(name)
);
this.workers[name].terminate();
}
});
this.workers[name].postMessage('cancel');
}
if (this.closeWorkerAfterMs[name]) {
if (
typeof this.closeWorkerAfterMs[name] === 'object' &&
typeof this.closeWorkerAfterMs[name].clear === 'function'
) {
this.closeWorkerAfterMs[name].clear();
}
delete this.closeWorkerAfterMs[name];
}
return pWaitFor(() => this.workers[name] === undefined);
}
for (const job of this.config.jobs) {
this.stop(job.name);
}
return pWaitFor(() => Object.keys(this.workers).length === 0);
}
add(jobs) {
//
// make sure jobs is an array
//
if (!Array.isArray(jobs)) {
jobs = [jobs];
}
const errors = [];
for (const [i, job_] of jobs.entries()) {
try {
const names = [
...getJobNames(jobs, i),
...getJobNames(this.config.jobs)
];
validateJob(job_, i, names, this.config);
const job = buildJob(job_, this.config);
this.config.jobs.push(job);
} catch (err) {
errors.push(err);
}
}
debug('jobs added', this.config.jobs);
// If there were any errors then throw them
if (errors.length > 0) {
throw combineErrors(errors);
}
}
async remove(name) {
const job = this.config.jobs.find((j) => j.name === name);
if (!job) {
throw new Error(`Job "${name}" does not exist`);
}
// make sure it also closes any open workers
await this.stop(name);
this.config.jobs = this.config.jobs.filter((j) => j.name !== name);
}
}
// Expose bthreads (useful for tests)
// https://github.com/chjj/bthreads#api
Bree.threads = {
backend: threads.backend,
browser: threads.browser,
location: threads.location,
filename: threads.filename,
dirname: threads.dirname,
require: threads.require,
resolve: threads.resolve,
exit: threads.exit,
cores: threads.cores
};
module.exports = Bree;