-
Notifications
You must be signed in to change notification settings - Fork 421
/
Copy pathjob.ts
1023 lines (883 loc) · 25.7 KB
/
job.ts
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
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { ChainableCommander } from 'ioredis';
import { fromPairs } from 'lodash';
import { debuglog } from 'util';
import {
BackoffOptions,
JobJson,
JobJsonRaw,
JobsOptions,
ParentKeys,
RedisClient,
WorkerOptions,
} from '../interfaces';
import { FinishedStatus, JobState, JobJsonSandbox } from '../types';
import {
errorObject,
isEmpty,
getParentKey,
lengthInUtf8Bytes,
tryCatch,
} from '../utils';
import { QueueEvents } from './queue-events';
import { Backoffs } from './backoffs';
import { MinimalQueue, ParentOpts, Scripts, JobData } from './scripts';
import { UnrecoverableError } from './unrecoverable-error';
const logger = debuglog('bull');
export type BulkJobOptions = Omit<JobsOptions, 'repeat'>;
export interface MoveToWaitingChildrenOpts {
child?: {
id: string;
queue: string;
};
}
export interface DependenciesOpts {
processed?: {
cursor?: number;
count?: number;
};
unprocessed?: {
cursor?: number;
count?: number;
};
}
/**
* Job
*
* This class represents a Job in the queue. Normally job are implicitly created when
* you add a job to the queue with methods such as Queue.addJob( ... )
*
* A Job instance is also passed to the Worker's process function.
*
* @class Job
*/
export class Job<
DataType = any,
ReturnType = any,
NameType extends string = string,
> {
/**
* The progress a job has performed so far.
* @defaultValue 0
*/
progress: number | object = 0;
/**
* The value returned by the processor when processing this job.
* @defaultValue null
*/
returnvalue: ReturnType = null;
/**
* Stacktrace for the error (for failed jobs).
* @defaultValue null
*/
stacktrace: string[] = null;
/**
* An amount of milliseconds to wait until this job can be processed.
* @defaultValue 0
*/
delay: number;
/**
* Timestamp when the job was created (unless overridden with job options).
*/
timestamp: number;
/**
* Number of attempts after the job has failed.
* @defaultValue 0
*/
attemptsMade = 0;
/**
* Reason for failing.
*/
failedReason: string;
/**
* Timestamp for when the job finished (completed or failed).
*/
finishedOn?: number;
/**
* Timestamp for when the job was processed.
*/
processedOn?: number;
/**
* Fully qualified key (including the queue prefix) pointing to the parent of this job.
*/
parentKey?: string;
/**
* Object that contains parentId (id) and parent queueKey.
*/
parent?: ParentKeys;
/**
* Base repeat job key.
*/
repeatJobKey?: string;
protected toKey: (type: string) => string;
protected discarded: boolean;
protected scripts: Scripts;
constructor(
protected queue: MinimalQueue,
/**
* The name of the Job
*/
public name: NameType,
/**
* The payload for this job.
*/
public data: DataType,
/**
* The options object for this job.
*/
public opts: JobsOptions = {},
public id?: string,
) {
const { repeatJobKey, ...restOpts } = this.opts;
this.opts = Object.assign(
{
attempts: 0,
delay: 0,
},
restOpts,
);
this.delay = this.opts.delay;
this.repeatJobKey = repeatJobKey;
this.timestamp = opts.timestamp ? opts.timestamp : Date.now();
this.opts.backoff = Backoffs.normalize(opts.backoff);
this.parentKey = getParentKey(opts.parent);
this.parent = opts.parent
? { id: opts.parent.id, queueKey: opts.parent.queue }
: undefined;
this.toKey = queue.toKey.bind(queue);
this.scripts = new Scripts(queue);
}
/**
* Creates a new job and adds it to the queue.
*
* @param queue - the queue where to add the job.
* @param name - the name of the job.
* @param data - the payload of the job.
* @param opts - the options bag for this job.
* @returns
*/
static async create<T = any, R = any, N extends string = string>(
queue: MinimalQueue,
name: N,
data: T,
opts?: JobsOptions,
): Promise<Job<T, R, N>> {
const client = await queue.client;
const job = new this<T, R, N>(queue, name, data, opts, opts && opts.jobId);
job.id = await job.addJob(client, {
parentKey: job.parentKey,
parentDependenciesKey: job.parentKey
? `${job.parentKey}:dependencies`
: '',
});
return job;
}
/**
* Creates a bulk of jobs and adds them atomically to the given queue.
*
* @param queue -the queue were to add the jobs.
* @param jobs - an array of jobs to be added to the queue.
* @returns
*/
static async createBulk<T = any, R = any, N extends string = string>(
queue: MinimalQueue,
jobs: {
name: N;
data: T;
opts?: BulkJobOptions;
}[],
): Promise<Job<T, R, N>[]> {
const client = await queue.client;
const jobInstances = jobs.map(
job =>
new this<T, R, N>(queue, job.name, job.data, job.opts, job.opts?.jobId),
);
const multi = client.multi();
for (const job of jobInstances) {
job.addJob(<RedisClient>(multi as unknown), {
parentKey: job.parentKey,
parentDependenciesKey: job.parentKey
? `${job.parentKey}:dependencies`
: '',
});
}
const results = (await multi.exec()) as [null | Error, string][];
for (let index = 0; index < results.length; ++index) {
const [err, id] = results[index];
if (err) {
throw err;
}
jobInstances[index].id = id;
}
return jobInstances;
}
/**
* Instantiates a Job from a JobJsonRaw object (coming from a deserialized JSON object)
*
* @param queue - the queue where the job belongs to.
* @param json - the plain object containing the job.
* @param jobId - an optional job id (overrides the id coming from the JSON object)
* @returns
*/
static fromJSON<T = any, R = any, N extends string = string>(
queue: MinimalQueue,
json: JobJsonRaw,
jobId?: string,
): Job<T, R, N> {
const data = JSON.parse(json.data || '{}');
const opts = JSON.parse(json.opts || '{}');
const job = new this<T, R, N>(
queue,
json.name as N,
data,
opts,
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);
}
if (json.rjk) {
job.repeatJobKey = json.rjk;
}
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);
}
if (json.parentKey) {
job.parentKey = json.parentKey;
}
if (json.parent) {
job.parent = JSON.parse(json.parent);
}
return job;
}
/**
* Fetches a Job from the queue given the passed job id.
*
* @param queue - the queue where the job belongs to.
* @param jobId - the job id.
* @returns
*/
static async fromId<T = any, R = any, N extends string = string>(
queue: MinimalQueue,
jobId: string,
): Promise<Job<T, R, N> | undefined> {
// jobId can be undefined if moveJob returns undefined
if (jobId) {
const client = await queue.client;
const jobData = await client.hgetall(queue.toKey(jobId));
return isEmpty(jobData)
? undefined
: this.fromJSON<T, R, N>(
queue,
(<unknown>jobData) as JobJsonRaw,
jobId,
);
}
}
toJSON() {
const { queue, scripts, ...withoutQueueAndScripts } = this;
return withoutQueueAndScripts;
}
/**
* Prepares a job to be serialized for storage in Redis.
* @returns
*/
asJSON(): JobJson {
return {
id: this.id,
name: this.name,
data: JSON.stringify(typeof this.data === 'undefined' ? {} : this.data),
opts: this.opts,
parent: this.parent ? { ...this.parent } : undefined,
parentKey: this.parentKey,
progress: this.progress,
attemptsMade: this.attemptsMade,
finishedOn: this.finishedOn,
processedOn: this.processedOn,
timestamp: this.timestamp,
failedReason: JSON.stringify(this.failedReason),
stacktrace: JSON.stringify(this.stacktrace),
repeatJobKey: this.repeatJobKey,
returnvalue: JSON.stringify(this.returnvalue),
};
}
/**
* Prepares a job to be passed to Sandbox.
* @returns
*/
asJSONSandbox(): JobJsonSandbox {
return {
...this.asJSON(),
queueName: this.queueName,
prefix: this.prefix,
};
}
/**
* Updates a job's data
*
* @param data - the data that will replace the current jobs data.
*/
update(data: DataType): Promise<void> {
this.data = data;
return this.scripts.updateData<DataType, ReturnType, NameType>(this, data);
}
/**
* Updates a job's progress
*
* @param progress - number or object to be saved as progress.
*/
updateProgress(progress: number | object): Promise<void> {
this.progress = progress;
return this.scripts.updateProgress(this, progress);
}
/**
* Logs one row of log data.
*
* @param logRow - string with log data to be logged.
*/
async log(logRow: string): Promise<number> {
const client = await this.queue.client;
const logsKey = this.toKey(this.id) + ':logs';
return client.rpush(logsKey, logRow);
}
/**
* Completely remove the job from the queue.
* Note, this call will throw an exception if the job
* is being processed when the call is performed.
*/
async remove(): Promise<void> {
await this.queue.waitUntilReady();
const queue = this.queue;
const job = this;
const removed = await this.scripts.remove(job.id);
if (removed) {
queue.emit('removed', job);
} else {
throw new Error('Could not remove job ' + job.id);
}
}
/**
* Extend the lock for this job.
*
* @param token - unique token for the lock
* @param duration - lock duration in milliseconds
*/
extendLock(token: string, duration: number): Promise<number> {
return this.scripts.extendLock(this.id, token, duration);
}
/**
* Moves a job to the completed queue.
* Returned job to be used with Queue.prototype.nextJobFromJobData.
*
* @param returnValue - The jobs success message.
* @param token - Worker token used to acquire completed job.
* @param fetchNext - True when wanting to fetch the next job.
* @returns Returns the jobData of the next job in the waiting queue.
*/
async moveToCompleted(
returnValue: ReturnType,
token: string,
fetchNext = true,
): Promise<JobData | []> {
await this.queue.waitUntilReady();
this.returnvalue = returnValue || void 0;
const stringifiedReturnValue = tryCatch(JSON.stringify, JSON, [
returnValue,
]);
if (stringifiedReturnValue === errorObject) {
throw errorObject.value;
}
return this.scripts.moveToCompleted(
this,
stringifiedReturnValue,
this.opts.removeOnComplete,
token,
fetchNext,
);
}
/**
* Moves a job to the failed queue.
*
* @param err - the jobs error message.
* @param token - token to check job is locked by current worker
* @param fetchNext - true when wanting to fetch the next job
* @returns void
*/
async moveToFailed<E extends Error>(
err: E,
token: string,
fetchNext = false,
): Promise<void> {
const client = await this.queue.client;
const message = err?.message;
const queue = this.queue;
this.failedReason = message;
let command: string;
const multi = client.multi();
this.saveStacktrace(multi, err);
//
// Check if an automatic retry should be performed
//
let moveToFailed = false;
let finishedOn;
if (
this.attemptsMade < this.opts.attempts &&
!this.discarded &&
!(err instanceof UnrecoverableError || err.name == 'UnrecoverableError')
) {
const opts = queue.opts as WorkerOptions;
// Check if backoff is needed
const delay = await Backoffs.calculate(
<BackoffOptions>this.opts.backoff,
this.attemptsMade,
opts.settings && opts.settings.backoffStrategies,
err,
this,
);
if (delay === -1) {
moveToFailed = true;
} else if (delay) {
const args = this.scripts.moveToDelayedArgs(
this.id,
Date.now() + delay,
token,
);
(<any>multi).moveToDelayed(args);
command = 'delayed';
} else {
// Retry immediately
(<any>multi).retryJob(
this.scripts.retryJobArgs(this.id, this.opts.lifo, token),
);
command = 'retry';
}
} else {
// If not, move to failed
moveToFailed = true;
}
if (moveToFailed) {
const args = this.scripts.moveToFailedArgs(
this,
message,
this.opts.removeOnFail,
token,
fetchNext,
);
(<any>multi).moveToFinished(args);
finishedOn = args[13];
command = 'failed';
}
const results = await multi.exec();
const code = results[results.length - 1][1] as number;
if (code < 0) {
throw this.scripts.finishedErrors(code, this.id, command, 'active');
}
if (finishedOn && typeof finishedOn === 'number') {
this.finishedOn = finishedOn;
}
}
/**
* @returns true if the job has completed.
*/
isCompleted(): Promise<boolean> {
return this.isInZSet('completed');
}
/**
* @returns true if the job has failed.
*/
isFailed(): Promise<boolean> {
return this.isInZSet('failed');
}
/**
* @returns true if the job is delayed.
*/
isDelayed(): Promise<boolean> {
return this.isInZSet('delayed');
}
/**
* @returns true if the job is waiting for children.
*/
isWaitingChildren(): Promise<boolean> {
return this.isInZSet('waiting-children');
}
/**
* @returns true of the job is active.
*/
isActive(): Promise<boolean> {
return this.isInList('active');
}
/**
* @returns true if the job is waiting.
*/
async isWaiting(): Promise<boolean> {
return (await this.isInList('wait')) || (await this.isInList('paused'));
}
/**
* @returns the queue name this job belongs to.
*/
get queueName(): string {
return this.queue.name;
}
get prefix(): string {
return this.queue.opts.prefix;
}
/**
* Get current state.
*
* @returns Returns one of these values:
* 'completed', 'failed', 'delayed', 'active', 'waiting', 'waiting-children', 'unknown'.
*/
getState(): Promise<JobState | 'unknown'> {
return this.scripts.getState(this.id);
}
/**
* Change delay of a delayed job.
*
* @param delay - milliseconds to be added to current time.
* @returns void
*/
async changeDelay(delay: number): Promise<void> {
await this.scripts.changeDelay(this.id, delay);
this.delay = delay;
}
/**
* Get this jobs children result values if any.
*
* @returns Object mapping children job keys with their values.
*/
async getChildrenValues<CT = any>(): Promise<{ [jobKey: string]: CT }> {
const client = await this.queue.client;
const result = (await client.hgetall(
this.toKey(`${this.id}:processed`),
)) as Object;
if (result) {
return fromPairs(
Object.entries(result).map(([k, v]) => [k, JSON.parse(v)]),
);
}
}
/**
* Get children job keys if this job is a parent and has children.
*
* @returns dependencies separated by processed and unprocessed.
*/
async getDependencies(opts: DependenciesOpts = {}): Promise<{
nextProcessedCursor?: number;
processed?: Record<string, any>;
nextUnprocessedCursor?: number;
unprocessed?: string[];
}> {
const client = await this.queue.client;
const multi = client.multi();
if (!opts.processed && !opts.unprocessed) {
multi.hgetall(this.toKey(`${this.id}:processed`));
multi.smembers(this.toKey(`${this.id}:dependencies`));
const [[err1, processed], [err2, unprocessed]] = (await multi.exec()) as [
[null | Error, { [jobKey: string]: string }],
[null | Error, string[]],
];
const transformedProcessed = Object.entries(processed).reduce(
(accumulator: Record<string, any>, [key, value]) => {
accumulator[key] = JSON.parse(value);
return accumulator;
},
{},
);
return { processed: transformedProcessed, unprocessed };
} else {
const defaultOpts = {
cursor: 0,
count: 20,
};
if (opts.processed) {
const processedOpts = Object.assign({ ...defaultOpts }, opts.processed);
multi.hscan(
this.toKey(`${this.id}:processed`),
processedOpts.cursor,
'COUNT',
processedOpts.count,
);
}
if (opts.unprocessed) {
const unprocessedOpts = Object.assign(
{ ...defaultOpts },
opts.unprocessed,
);
multi.sscan(
this.toKey(`${this.id}:dependencies`),
unprocessedOpts.cursor,
'COUNT',
unprocessedOpts.count,
);
}
const [result1, result2] = (await multi.exec()) as [
Error,
[number[], string[] | undefined],
][];
const [processedCursor, processed = []] = opts.processed
? result1[1]
: [];
const [unprocessedCursor, unprocessed = []] = opts.unprocessed
? opts.processed
? result2[1]
: result1[1]
: [];
const transformedProcessed = processed.reduce(
(
accumulator: Record<string, any>,
currentValue: string,
index: number,
) => {
if (index % 2) {
return {
...accumulator,
[processed[index - 1]]: JSON.parse(currentValue),
};
}
return accumulator;
},
{},
);
return {
...(processedCursor
? {
processed: transformedProcessed,
nextProcessedCursor: Number(processedCursor),
}
: {}),
...(unprocessedCursor
? { unprocessed, nextUnprocessedCursor: Number(unprocessedCursor) }
: {}),
};
}
}
/**
* Get children job counts if this job is a parent and has children.
*
* @returns dependencies count separated by processed and unprocessed.
*/
async getDependenciesCount(
opts: {
processed?: boolean;
unprocessed?: boolean;
} = {},
): Promise<{
processed?: number;
unprocessed?: number;
}> {
const client = await this.queue.client;
const multi = client.multi();
const updatedOpts =
!opts.processed && !opts.unprocessed
? { processed: true, unprocessed: true }
: opts;
if (updatedOpts.processed) {
multi.hlen(this.toKey(`${this.id}:processed`));
}
if (updatedOpts.unprocessed) {
multi.scard(this.toKey(`${this.id}:dependencies`));
}
const [[err1, result1] = [], [err2, result2] = []] =
(await multi.exec()) as [[null | Error, number], [null | Error, number]];
const processed = updatedOpts.processed ? result1 : undefined;
const unprocessed = updatedOpts.unprocessed
? updatedOpts.processed
? result2
: result1
: undefined;
return {
...(updatedOpts.processed
? {
processed,
}
: {}),
...(updatedOpts.unprocessed ? { unprocessed } : {}),
};
}
/**
* Returns a promise the resolves when the job has completed (containing the return value of the job),
* or rejects when the job has failed (containing the failedReason).
*
* @param queueEvents - Instance of QueueEvents.
* @param ttl - Time in milliseconds to wait for job to finish before timing out.
*/
async waitUntilFinished(
queueEvents: QueueEvents,
ttl?: number,
): Promise<ReturnType> {
await this.queue.waitUntilReady();
const jobId = this.id;
return new Promise<any>(async (resolve, reject) => {
let timeout: NodeJS.Timeout;
if (ttl) {
timeout = setTimeout(
() =>
onFailed(
/* eslint-disable max-len */
`Job wait ${this.name} timed out before finishing, no finish notification arrived after ${ttl}ms (id=${jobId})`,
/* eslint-enable max-len */
),
ttl,
);
}
function onCompleted(args: any) {
removeListeners();
resolve(args.returnvalue);
}
function onFailed(args: any) {
removeListeners();
reject(new Error(args.failedReason || args));
}
const completedEvent = `completed:${jobId}`;
const failedEvent = `failed:${jobId}`;
queueEvents.on(completedEvent as any, onCompleted);
queueEvents.on(failedEvent as any, onFailed);
this.queue.on('closing', onFailed);
const removeListeners = () => {
clearInterval(timeout);
queueEvents.removeListener(completedEvent, onCompleted);
queueEvents.removeListener(failedEvent, onFailed);
this.queue.removeListener('closing', onFailed);
};
// Poll once right now to see if the job has already finished. The job may have been completed before we were able
// to register the event handlers on the QueueEvents, so we check here to make sure we're not waiting for an event
// that has already happened. We block checking the job until the queue events object is actually listening to
// Redis so there's no chance that it will miss events.
await queueEvents.waitUntilReady();
const [status, result] = (await this.scripts.isFinished(jobId, true)) as [
number,
string,
];
const finished = status != 0;
if (finished) {
if (status == -5 || status == 2) {
onFailed({ failedReason: result });
} else {
onCompleted({ returnvalue: getReturnValue(result) });
}
}
});
}
/**
* Moves the job to the delay set.
*
* @param timestamp - timestamp where the job should be moved back to "wait"
* @param token - token to check job is locked by current worker
* @returns
*/
moveToDelayed(timestamp: number, token?: string): Promise<void> {
return this.scripts.moveToDelayed(this.id, timestamp, token);
}
/**
* Moves the job to the waiting-children set.
*
* @param token - Token to check job is locked by current worker
* @param opts - The options bag for moving a job to waiting-children.
* @returns true if the job was moved
*/
moveToWaitingChildren(
token: string,
opts: MoveToWaitingChildrenOpts = {},
): Promise<boolean> {
return this.scripts.moveToWaitingChildren(this.id, token, opts);
}
/**
* Promotes a delayed job so that it starts to be processed as soon as possible.
*/
async promote(): Promise<void> {
const jobId = this.id;
const code = await this.scripts.promote(jobId);
if (code < 0) {
throw this.scripts.finishedErrors(code, this.id, 'promote', 'delayed');
}
}
/**
* Attempts to retry the job. Only a job that has failed or completed can be retried.
*
* @param state - completed / failed
* @returns 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
*/
async retry(state: FinishedStatus = 'failed'): Promise<void> {
this.failedReason = null;
this.finishedOn = null;
this.processedOn = null;
this.returnvalue = null;
return this.scripts.reprocessJob(this, state);
}
/**
* Marks a job to not be retried if it fails (even if attempts has been configured)
*/
discard(): void {
this.discarded = true;
}
private async isInZSet(set: string): Promise<boolean> {
const client = await this.queue.client;
const score = await client.zscore(this.queue.toKey(set), this.id);
return score !== null;
}
private async isInList(list: string): Promise<boolean> {
return this.scripts.isJobInList(this.queue.toKey(list), this.id);
}
/**
* Adds the job to Redis.
*
* @param client -
* @param parentOpts -
* @returns
*/
addJob(client: RedisClient, parentOpts?: ParentOpts): Promise<string> {
const jobData = this.asJSON();
const exceedLimit =
this.opts.sizeLimit &&
lengthInUtf8Bytes(jobData.data) > this.opts.sizeLimit;
if (exceedLimit) {
throw new Error(
`The size of job ${this.name} exceeds the limit ${this.opts.sizeLimit} bytes`,
);
}
if (this.opts.delay && this.opts.repeat && !this.opts.repeat?.count) {
throw new Error(`Delay and repeat options could not be used together`);
}
return this.scripts.addJob(client, jobData, this.opts, this.id, parentOpts);
}
protected saveStacktrace(multi: ChainableCommander, err: Error): void {
this.stacktrace = this.stacktrace || [];
if (err?.stack) {
this.stacktrace.push(err.stack);
if (this.opts.stackTraceLimit) {
this.stacktrace = this.stacktrace.slice(0, this.opts.stackTraceLimit);
}
}
const params = {
stacktrace: JSON.stringify(this.stacktrace),
failedReason: err?.message,
};