-
Notifications
You must be signed in to change notification settings - Fork 86
/
Copy pathindex.js
706 lines (625 loc) · 21 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
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
const fs = require('fs');
const EventEmitter = require('events');
const { Worker } = require('worker_threads');
const { resolve } = require('path');
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 pWaitFor = require('p-wait-for');
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');
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: resolve('jobs'),
// Set this to `true` to silence root check error log
silenceRootCheckError: false,
// Set this to `false` to prevent requiring a root directory of jobs
doRootCheck: true,
// Remove jobs upon completion
// (set this to `true` if you want jobs to removed from array upon completion)
// this will not remove jobs when `stop` is called
removeCompleted: false,
// 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,
// Default timezone for jobs
// Must be a IANA string (ie. 'America/New_York', 'EST', 'UTC', etc).
// To use the system specified timezone, set this to 'local' or 'system'.
timezone: 'local',
// 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',
// an array of accepted extensions
// NOTE: if you add to this array you must extend `createWorker`
// to deal with the conversion to acceptable files for
// Node Workers
acceptedExtensions: ['.js', '.mjs'],
// Default worker options to pass to ~`new 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' event 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
};
// Validate timezone string
// `.toLocaleString()` will throw a `RangeError` if `timeZone` string
// is bogus or not supported by the environment.
if (
isSANB(this.config.timezone) &&
!['local', 'system'].includes(this.config.timezone)
) {
new Date().toLocaleString('ia', { timeZone: this.config.timezone });
}
//
// 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
}
};
}
// validate acceptedExtensions
if (
!this.config.acceptedExtensions ||
!Array.isArray(this.config.acceptedExtensions)
) {
throw new TypeError('`acceptedExtensions` must be defined and an Array');
}
// convert `false` logger option into noop
// <https://github.com/breejs/bree/issues/147>
if (this.config.logger === false)
this.config.logger = {
/* istanbul ignore next */
info() {},
/* istanbul ignore next */
warn() {},
/* istanbul ignore next */
error() {}
};
debug('config', this.config);
this.closeWorkerAfterMs = new Map();
this.workers = new Map();
this.timeouts = new Map();
this.intervals = new Map();
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.removeSafeTimer = this.removeSafeTimer.bind(this);
this.handleJobCompletion = this.handleJobCompletion.bind(this);
this.validateJob = validateJob;
this.getName = getName;
this.getHumanToMs = getHumanToMs;
this.parseValue = parseValue;
// so plugins can extend constructor
this.init = this.init.bind(this);
this.init();
debug('this.config.jobs', this.config.jobs);
}
init() {
// Validate root (sync check)
if (
isSANB(this.config.root) /* istanbul ignore next */ &&
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 &&
this.config.doRootCheck &&
(!Array.isArray(this.config.jobs) || this.config.jobs.length === 0)
) {
try {
this.config.jobs = require(this.config.root);
} catch (err) {
if (!this.config.silenceRootCheckError) {
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);
}
}
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;
}
if (this.workers.has(name)) {
const worker = this.workers.get(name);
return {
...meta,
worker: {
isMainThread: worker.isMainThread,
resourceLimits: worker.resourceLimits,
threadId: worker.threadId
}
};
}
return 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.has(name)) {
this.config.logger.warn(
new Error(`Job "${name}" is already running`),
this.getWorkerMetadata(name)
);
return;
}
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.set(name, this.createWorker(job.path, object));
this.emit('worker created', name);
debug('worker started', name);
const prefix = `Worker for job "${name}"`;
this.workers.get(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.set(
name,
setTimeout(() => {
/* istanbul ignore else */
if (this.workers.has(name)) {
debug('worker has been terminated', name);
this.workers.get(name).terminate();
}
}, closeWorkerAfterMs)
);
}
this.config.logger.info(
`${prefix} online`,
this.getWorkerMetadata(name)
);
});
this.workers.get(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') {
const worker = this.workers.get(name);
worker.removeAllListeners('message');
worker.removeAllListeners('exit');
worker.terminate();
this.workers.delete(name);
this.handleJobCompletion(name);
this.emit('worker deleted', 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.get(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.get(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.get(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)
);
}
this.workers.delete(name);
this.handleJobCompletion(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.has(name) ||
this.intervals.has(name) ||
this.workers.has(name)
) {
throw 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');
// not throwing an error so that jobs can be set with a specifc date
// and only run on that date then never run again without changing config
this.config.logger.warn(
`Job "${name}" was skipped because it was in the past.`
);
this.emit('job past', name);
return;
}
this.timeouts.set(
name,
setTimeout(() => {
this.run(name);
if (this.isSchedule(job.interval)) {
debug('job.interval is schedule', job);
this.intervals.set(
name,
later.setInterval(
() => this.run(name),
job.interval,
job.timezone
)
);
} else if (Number.isFinite(job.interval) && job.interval > 0) {
debug('job.interval is finite', job);
this.intervals.set(
name,
setInterval(() => this.run(name), job.interval)
);
} else {
debug('job.date was scheduled to run only once', job);
}
this.timeouts.delete(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.set(
name,
later.setTimeout(
() => {
this.run(name);
if (this.isSchedule(job.interval)) {
debug('job.interval is schedule', job);
this.intervals.set(
name,
later.setInterval(
() => this.run(name),
job.interval,
job.timezone
)
);
} else if (Number.isFinite(job.interval) && job.interval > 0) {
debug('job.interval is finite', job);
this.intervals.set(
name,
setInterval(() => this.run(name), job.interval)
);
}
this.timeouts.delete(name);
},
job.timeout,
job.timezone
)
);
return;
}
if (Number.isFinite(job.timeout)) {
debug('job timeout is finite', job);
this.timeouts.set(
name,
setTimeout(() => {
this.run(name);
if (this.isSchedule(job.interval)) {
debug('job.interval is schedule', job);
this.intervals.set(
name,
later.setInterval(
() => this.run(name),
job.interval,
job.timezone
)
);
} else if (Number.isFinite(job.interval) && job.interval > 0) {
debug('job.interval is finite', job.interval);
this.intervals.set(
name,
setInterval(() => this.run(name), job.interval)
);
}
this.timeouts.delete(name);
}, job.timeout)
);
} else if (this.isSchedule(job.interval)) {
debug('job.interval is schedule', job);
this.intervals.set(
name,
later.setInterval(() => this.run(name), job.interval, job.timezone)
);
} else if (Number.isFinite(job.interval) && job.interval > 0) {
debug('job.interval is finite', job);
this.intervals.set(
name,
setInterval(() => this.run(name), job.interval)
);
}
return;
}
for (const job of this.config.jobs) {
this.start(job.name);
}
}
async stop(name) {
if (name) {
this.removeSafeTimer('timeouts', name);
this.removeSafeTimer('intervals', name);
if (this.workers.has(name)) {
this.workers.get(name).once('message', (message) => {
if (message === 'cancelled') {
this.config.logger.info(
`Gracefully cancelled worker for job "${name}"`,
this.getWorkerMetadata(name)
);
this.workers.get(name).terminate();
}
});
this.workers.get(name).postMessage('cancel');
}
this.removeSafeTimer('closeWorkerAfterMs', name);
return pWaitFor(() => !this.workers.has(name));
}
for (const job of this.config.jobs) {
this.stop(job.name);
}
return pWaitFor(() => this.workers.size === 0);
}
add(jobs) {
//
// make sure jobs is an array
//
if (!Array.isArray(jobs)) {
jobs = [jobs];
}
const errors = [];
const addedJobs = [];
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);
addedJobs.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);
}
this.config.jobs.push(...addedJobs);
return addedJobs;
}
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);
}
/**
* A friendly helper to clear safe-timers timeout and interval
* @param {string} type
* @param {string} name
*/
removeSafeTimer(type, name) {
if (this[type].has(name)) {
const timer = this[type].get(name);
if (typeof timer === 'object' && typeof timer.clear === 'function') {
timer.clear();
}
this[type].delete(name);
}
}
createWorker(filename, options) {
return new Worker(filename, options);
}
handleJobCompletion(name) {
// remove closeWorkerAfterMs if exist
this.removeSafeTimer('closeWorkerAfterMs', name);
if (
this.config.removeCompleted &&
!this.timeouts.has(name) &&
!this.intervals.has(name)
) {
this.config.jobs = this.config.jobs.filter((j) => j.name !== name);
}
}
}
// plugins inspired by Dayjs
Bree.extend = (plugin, options) => {
if (!plugin.$i) {
// install plugin only once
plugin(options, Bree);
plugin.$i = true;
}
return Bree;
};
module.exports = Bree;