forked from OptimalBits/bull
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathjob.js
623 lines (539 loc) · 15.8 KB
/
job.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
'use strict';
const _ = require('lodash');
const utils = require('./utils');
const scripts = require('./scripts');
const debuglog = require('debuglog')('bull');
const errors = require('./errors');
const backoffs = require('./backoffs');
const FINISHED_WATCHDOG = 5000;
/**
interface JobOptions
{
priority: Priority;
attempts: number;
delay: number;
}
*/
// queue: Queue, data: {}, opts: JobOptions
const Job = function(queue, name, data, opts) {
if (typeof name !== 'string') {
opts = data;
data = name;
name = '__default__';
}
// defaults
this.opts = setDefaultOpts(opts);
this.name = name;
this.queue = queue;
this.data = data;
this._progress = 0;
this.delay = this.opts.delay;
this.timestamp = this.opts.timestamp;
this.stacktrace = [];
this.returnvalue = null;
this.attemptsMade = 0;
this.toKey = _.bind(queue.toKey, queue);
};
function setDefaultOpts(opts) {
const _opts = Object.assign({}, opts);
_opts.attempts = typeof _opts.attempts == 'undefined' ? 1 : _opts.attempts;
_opts.delay = typeof _opts.delay == 'undefined' ? 0 : Number(_opts.delay);
_opts.timestamp =
typeof _opts.timestamp == 'undefined' ? Date.now() : _opts.timestamp;
_opts.attempts = parseInt(_opts.attempts);
_opts.backoff = backoffs.normalize(_opts.backoff);
return _opts;
}
Job.DEFAULT_JOB_NAME = '__default__';
function addJob(queue, client, job) {
const opts = job.opts;
const jobData = job.toData();
return scripts.addJob(client, queue, jobData, {
lifo: opts.lifo,
customJobId: opts.jobId,
priority: opts.priority
});
}
Job.create = function(queue, name, data, opts) {
const job = new Job(queue, name, data, opts);
return queue
.isReady()
.then(() => {
return addJob(queue, queue.client, job);
})
.then(jobId => {
job.id = jobId;
debuglog('Job added', jobId);
return job;
});
};
Job.createBulk = function(queue, jobs) {
jobs = jobs.map(job => new Job(queue, job.name, job.data, job.opts));
return queue
.isReady()
.then(() => {
const multi = queue.client.multi();
for (const job of jobs) {
addJob(queue, multi, job);
}
return multi.exec();
})
.then(res => {
res.forEach((res, index) => {
jobs[index].id = res[1];
debuglog('Job added', res[1]);
});
return jobs;
});
};
Job.fromId = function(queue, jobId) {
// jobId can be undefined if moveJob returns undefined
if (!jobId) {
return Promise.resolve();
}
return queue.client.hgetall(queue.toKey(jobId)).then(jobData => {
return utils.isEmpty(jobData) ? null : Job.fromJSON(queue, jobData, jobId);
});
};
Job.prototype.progress = function(progress, data) {
if (_.isUndefined(progress) && _.isUndefined(data)) {
return this._progress;
}
if (!_.isUndefined(progress)) this._progress = progress;
return scripts.updateProgress(this, progress, data);
};
Job.prototype.update = function(data) {
this.data = data;
return this.queue.client.hset(
this.queue.toKey(this.id),
'data',
JSON.stringify(data)
);
};
Job.prototype.toJSON = function() {
const opts = Object.assign({}, this.opts);
return {
id: this.id,
name: this.name,
data: this.data || {},
opts: opts,
progress: this._progress,
delay: this.delay, // Move to opts
timestamp: this.timestamp,
attemptsMade: this.attemptsMade,
failedReason: this.failedReason,
stacktrace: this.stacktrace || null,
returnvalue: this.returnvalue || null,
finishedOn: this.finishedOn || null,
processedOn: this.processedOn || null
};
};
Job.prototype.toData = function() {
const json = this.toJSON();
json.data = JSON.stringify(json.data);
json.opts = JSON.stringify(json.opts);
json.stacktrace = JSON.stringify(json.stacktrace);
json.failedReason = JSON.stringify(json.failedReason);
json.returnvalue = JSON.stringify(json.returnvalue);
return json;
};
/**
Return a unique key representing a lock for this Job
*/
Job.prototype.lockKey = function() {
return this.toKey(this.id) + ':lock';
};
/**
Takes a lock for this job so that no other queue worker can process it at the
same time.
*/
Job.prototype.takeLock = function() {
return scripts.takeLock(this.queue, this).then(lock => {
return lock || false;
});
};
/**
Releases the lock. Only locks owned by the queue instance can be released.
*/
Job.prototype.releaseLock = function() {
return scripts.releaseLock(this.queue, this.id).then(unlocked => {
if (unlocked != 1) {
throw new Error('Could not release lock for job ' + this.id);
}
});
};
/**
* Moves a job to the completed queue.
* Returned job to be used with Queue.prototype.nextJobFromJobData.
* @param returnValue {string} The jobs success message.
* @param ignoreLock {boolean} True when wanting to ignore the redis lock on this job.
* @param notFetch {boolean} True when should not fetch next job from queue.
* @returns {Promise} Returns the jobData of the next job in the waiting queue.
*/
Job.prototype.moveToCompleted = function(
returnValue,
ignoreLock,
notFetch = false
) {
this.returnvalue = returnValue || 0;
returnValue = utils.tryCatch(JSON.stringify, JSON, [returnValue]);
if (returnValue === utils.errorObject) {
const err = utils.errorObject.value;
return Promise.reject(err);
}
this.finishedOn = Date.now();
return scripts.moveToCompleted(
this,
returnValue,
this.opts.removeOnComplete,
ignoreLock,
notFetch
);
};
Job.prototype.discard = function() {
this._discarded = true;
};
/**
* Moves a job to the failed queue.
* @param err {string} The jobs error message.
* @param ignoreLock {boolean} True when wanting to ignore the redis lock on this job.
* @returns void
*/
Job.prototype.moveToFailed = function(err, ignoreLock) {
this.failedReason = err.message;
return new Promise(async (resolve, reject) => {
let command;
const multi = this.queue.client.multi();
this._saveAttempt(multi, err);
// Check if an automatic retry should be performed
let moveToFailed = false;
if (this.attemptsMade < this.opts.attempts && !this._discarded) {
// Check if backoff is needed
const delay = await backoffs.calculate(
this.opts.backoff,
this.attemptsMade,
this.queue.settings.backoffStrategies,
err
);
if (delay === -1) {
// If delay is -1, we should no continue retrying
moveToFailed = true;
} else if (delay) {
// If so, move to delayed (need to unlock job in this case!)
const args = scripts.moveToDelayedArgs(
this.queue,
this.id,
Date.now() + delay,
ignoreLock
);
multi.moveToDelayed(args);
command = 'delayed';
} else {
// If not, retry immediately
multi.retryJob(scripts.retryJobArgs(this, ignoreLock));
command = 'retry';
}
} else {
// If not, move to failed
moveToFailed = true;
}
if (moveToFailed) {
this.finishedOn = Date.now();
const args = scripts.moveToFailedArgs(
this,
err.message,
this.opts.removeOnFail,
ignoreLock
);
multi.moveToFinished(args);
command = 'failed';
}
return multi.exec().then(results => {
const code = _.last(results)[1];
if (code < 0) {
return reject(scripts.finishedErrors(code, this.id, command));
}
resolve();
}, reject);
});
};
Job.prototype.moveToDelayed = function(timestamp, ignoreLock) {
return scripts.moveToDelayed(this.queue, this.id, timestamp, ignoreLock);
};
Job.prototype.promote = function() {
const queue = this.queue;
const jobId = this.id;
return scripts.promote(queue, jobId).then(result => {
if (result === -1) {
throw new Error('Job ' + jobId + ' is not in a delayed state');
}
});
};
/**
* Attempts to retry the job. Only a job that has failed can be retried.
*
* @return {Promise} If resolved and return code is 1, then the queue emits a waiting event
* otherwise the operation was not a success and throw the corresponding error. If the promise
* rejects, it indicates that the script failed to execute
*/
Job.prototype.retry = function() {
return this.queue.isReady().then(() => {
this.failedReason = null;
this.finishedOn = null;
this.processedOn = null;
return this.queue.client
.hdel(
this.queue.toKey(this.id),
'finishedOn',
'processedOn',
'failedReason'
)
.then((/*redisResult*/) => {
return scripts.reprocessJob(this, { state: 'failed' }).then(result => {
if (result === 1) {
return;
} else if (result === 0) {
throw new Error(errors.Messages.RETRY_JOB_NOT_EXIST);
} else if (result === -1) {
throw new Error(errors.Messages.RETRY_JOB_IS_LOCKED);
} else if (result === -2) {
throw new Error(errors.Messages.RETRY_JOB_NOT_FAILED);
}
});
});
});
};
/**
* Logs one row of log data.
*
* @params logRow: string String with log data to be logged.
*
*/
Job.prototype.log = function(logRow) {
const logsKey = this.toKey(this.id) + ':logs';
return this.queue.client.rpush(logsKey, logRow);
};
Job.prototype.isCompleted = function() {
return this._isDone('completed');
};
Job.prototype.isFailed = function() {
return this._isDone('failed');
};
Job.prototype.isDelayed = function() {
return this._isDone('delayed');
};
Job.prototype.isActive = function() {
return this._isInList('active');
};
Job.prototype.isWaiting = function() {
return this._isInList('wait');
};
Job.prototype.isPaused = function() {
return this._isInList('paused');
};
Job.prototype.isStuck = function() {
return this.getState().then(state => {
return state === 'stuck';
});
};
Job.prototype.getState = function() {
const fns = [
{ fn: 'isCompleted', state: 'completed' },
{ fn: 'isFailed', state: 'failed' },
{ fn: 'isDelayed', state: 'delayed' },
{ fn: 'isActive', state: 'active' },
{ fn: 'isWaiting', state: 'waiting' },
{ fn: 'isPaused', state: 'paused' }
];
return fns
.reduce((result, fn) => {
return result.then(state => {
if (state) {
return state;
}
return this[fn.fn]().then(result => {
return result ? fn.state : null;
});
});
}, Promise.resolve())
.then(result => {
return result ? result : 'stuck';
});
};
Job.prototype.remove = function() {
const queue = this.queue;
const job = this;
return queue.isReady().then(() => {
return scripts.remove(queue, job.id).then(removed => {
if (removed) {
queue.emit('removed', job);
} else {
throw new Error('Could not remove job ' + job.id);
}
});
});
};
/**
* When there is progress from the job.
*/
Job.prototype.onProgress = function(callback) {
var _this = this;
function processProgress(data) {
var s = data.split('|');
var id = s.shift();
if (id == _this.id) callback(...s);
}
this.queue.on('global:progress', processProgress);
this.finished().then(() => {
this.queue.removeListener('global:progress', processProgress);
});
};
/**
* Returns a promise the resolves when the job has finished. (completed or failed).
*/
Job.prototype.finished = async function() {
await Promise.all([
this.queue._registerEvent('global:completed'),
this.queue._registerEvent('global:failed')
]);
await this.queue.isReady();
const status = await scripts.isFinished(this);
const finished = status > 0;
if (finished) {
const job = await Job.fromId(this.queue, this.id);
if (status == 2) {
throw new Error(job.failedReason);
} else {
return job.returnvalue;
}
} else {
return new Promise((resolve, reject) => {
const onCompleted = (jobId, resultValue) => {
if (String(jobId) === String(this.id)) {
let result = void 0;
try {
if (typeof resultValue === 'string') {
result = JSON.parse(resultValue);
}
} catch (err) {
//swallow exception because the resultValue got corrupted somehow.
debuglog('corrupted resultValue: ' + resultValue, err);
}
resolve(result);
removeListeners();
}
};
const onFailed = (jobId, failedReason) => {
if (String(jobId) === String(this.id)) {
reject(new Error(failedReason));
removeListeners();
}
};
this.queue.on('global:completed', onCompleted);
this.queue.on('global:failed', onFailed);
const removeListeners = () => {
clearInterval(interval);
this.queue.removeListener('global:completed', onCompleted);
this.queue.removeListener('global:failed', onFailed);
};
//
// Watchdog
//
const interval = setInterval(() => {
if (this._isQueueClosing()) {
removeListeners();
// TODO(manast) maybe we would need a more graceful way to get out of this interval.
reject(
new Error('cannot check if job is finished in a closing queue.')
);
} else {
scripts.isFinished(this).then(status => {
const finished = status > 0;
if (finished) {
Job.fromId(this.queue, this.id).then(job => {
removeListeners();
if (status == 2) {
reject(new Error(job.failedReason));
} else {
resolve(job.returnvalue);
}
});
}
});
}
}, FINISHED_WATCHDOG);
});
}
};
// -----------------------------------------------------------------------------
// Private methods
// -----------------------------------------------------------------------------
Job.prototype._isQueueClosing = function() {
return this.queue.closing;
};
Job.prototype._isDone = function(list) {
return this.queue.client
.zscore(this.queue.toKey(list), this.id)
.then(score => {
return score !== null;
});
};
Job.prototype._isInList = function(list) {
return scripts.isJobInList(
this.queue.client,
this.queue.toKey(list),
this.id
);
};
Job.prototype._saveAttempt = function(multi, err) {
this.attemptsMade++;
const params = {
attemptsMade: this.attemptsMade
};
if (this.opts.stackTraceLimit) {
this.stacktrace = this.stacktrace.slice(0, this.opts.stackTraceLimit - 1);
}
this.stacktrace.push(err.stack);
params.stacktrace = JSON.stringify(this.stacktrace);
params.failedReason = err.message;
multi.hmset(this.queue.toKey(this.id), params);
};
Job.fromJSON = function(queue, json, jobId) {
const data = JSON.parse(json.data || '{}');
const opts = JSON.parse(json.opts || '{}');
const job = new Job(queue, json.name || Job.DEFAULT_JOB_NAME, data, opts);
job.id = json.id || jobId;
job._progress = JSON.parse(json.progress || 0);
job.delay = parseInt(json.delay);
job.timestamp = parseInt(json.timestamp);
if (json.finishedOn) {
job.finishedOn = parseInt(json.finishedOn);
}
if (json.processedOn) {
job.processedOn = parseInt(json.processedOn);
}
job.failedReason = json.failedReason;
job.attemptsMade = parseInt(json.attemptsMade || 0);
job.stacktrace = getTraces(json.stacktrace);
if (typeof json.returnvalue === 'string') {
job.returnvalue = getReturnValue(json.returnvalue);
}
return job;
};
function getTraces(stacktrace) {
const _traces = utils.tryCatch(JSON.parse, JSON, [stacktrace]);
if (_traces === utils.errorObject || !(_traces instanceof Array)) {
return [];
} else {
return _traces;
}
}
function getReturnValue(_value) {
const value = utils.tryCatch(JSON.parse, JSON, [_value]);
if (value !== utils.errorObject) {
return value;
} else {
debuglog('corrupted returnvalue: ' + _value, value);
}
}
module.exports = Job;