-
Notifications
You must be signed in to change notification settings - Fork 420
/
scripts.ts
983 lines (840 loc) · 24.5 KB
/
scripts.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
/**
* Includes all the scripts needed by the queue and jobs.
*/
/*eslint-env node */
'use strict';
import { Packr } from 'msgpackr';
const packer = new Packr({
useRecords: false,
encodeUndefinedAsNil: true,
});
const pack = packer.pack;
import {
JobJson,
JobJsonRaw,
MinimalJob,
MoveToWaitingChildrenOpts,
ParentOpts,
RedisClient,
WorkerOptions,
KeepJobs,
} from '../interfaces';
import {
JobState,
JobType,
FinishedStatus,
FinishedPropValAttribute,
MinimalQueue,
RedisJobOptions,
} from '../types';
import { ErrorCode } from '../enums';
import { array2obj, getParentKey, isRedisVersionLowerThan } from '../utils';
import { ChainableCommander } from 'ioredis';
export type JobData = [JobJsonRaw | number, string?];
export class Scripts {
moveToFinishedKeys: string[];
constructor(protected queue: MinimalQueue) {
const queueKeys = this.queue.keys;
this.moveToFinishedKeys = [
queueKeys.wait,
queueKeys.active,
queueKeys.priority,
queueKeys.events,
queueKeys.stalled,
queueKeys.limiter,
queueKeys.delayed,
queueKeys.paused,
undefined,
undefined,
queueKeys.meta,
undefined,
];
}
async isJobInList(listKey: string, jobId: string): Promise<boolean> {
const client = await this.queue.client;
let result;
if (isRedisVersionLowerThan(this.queue.redisVersion, '6.0.6')) {
result = await (<any>client).isJobInList([listKey, jobId]);
} else {
result = await (<any>client).lpos(listKey, jobId);
}
return Number.isInteger(result);
}
async addJob(
client: RedisClient,
job: JobJson,
opts: RedisJobOptions,
jobId: string,
parentOpts: ParentOpts = {
parentKey: null,
waitChildrenKey: null,
parentDependenciesKey: null,
},
): Promise<string> {
const queueKeys = this.queue.keys;
const keys: (string | Buffer)[] = [
queueKeys.wait,
queueKeys.paused,
queueKeys.meta,
queueKeys.id,
queueKeys.delayed,
queueKeys.priority,
queueKeys.completed,
queueKeys.events,
];
const fpof = opts.fpof ? { fpof: true } : {};
const parent = job.parent ? { ...job.parent, ...fpof } : null;
const args = [
queueKeys[''],
typeof jobId !== 'undefined' ? jobId : '',
job.name,
job.timestamp,
job.parentKey || null,
parentOpts.waitChildrenKey || null,
parentOpts.parentDependenciesKey || null,
parent,
job.repeatJobKey,
];
let encodedOpts;
if (opts.repeat) {
const repeat = {
...opts.repeat,
};
if (repeat.startDate) {
repeat.startDate = +new Date(repeat.startDate);
}
if (repeat.endDate) {
repeat.endDate = +new Date(repeat.endDate);
}
encodedOpts = pack({
...opts,
repeat,
});
} else {
encodedOpts = pack(opts);
}
keys.push(pack(args), job.data, encodedOpts);
const result = await (<any>client).addJob(keys);
if (result < 0) {
throw this.finishedErrors(result, parentOpts.parentKey, 'addJob');
}
return result;
}
async pause(pause: boolean): Promise<void> {
const client = await this.queue.client;
let src = 'wait',
dst = 'paused';
if (!pause) {
src = 'paused';
dst = 'wait';
}
const keys = [src, dst, 'meta'].map((name: string) =>
this.queue.toKey(name),
);
keys.push(this.queue.keys.events);
return (<any>client).pause(keys.concat([pause ? 'paused' : 'resumed']));
}
private removeRepeatableArgs(
repeatJobId: string,
repeatJobKey: string,
): string[] {
const queueKeys = this.queue.keys;
const keys = [queueKeys.repeat, queueKeys.delayed];
const args = [repeatJobId, repeatJobKey, queueKeys['']];
return keys.concat(args);
}
async removeRepeatable(
repeatJobId: string,
repeatJobKey: string,
): Promise<number> {
const client = await this.queue.client;
const args = this.removeRepeatableArgs(repeatJobId, repeatJobKey);
return (<any>client).removeRepeatable(args);
}
async remove(jobId: string): Promise<number> {
const client = await this.queue.client;
const keys = [''].map(name => this.queue.toKey(name));
return (<any>client).removeJob(keys.concat([jobId]));
}
async extendLock(
jobId: string,
token: string,
duration: number,
client?: RedisClient | ChainableCommander,
): Promise<number> {
client = client || (await this.queue.client);
const args = [
this.queue.toKey(jobId) + ':lock',
this.queue.keys.stalled,
token,
duration,
jobId,
];
return (<any>client).extendLock(args);
}
async updateData<T = any, R = any, N extends string = string>(
job: MinimalJob<T, R, N>,
data: T,
): Promise<void> {
const client = await this.queue.client;
const keys = [this.queue.toKey(job.id)];
const dataJson = JSON.stringify(data);
const result = await (<any>client).updateData(keys.concat([dataJson]));
if (result < 0) {
throw this.finishedErrors(result, job.id, 'updateData');
}
}
async updateProgress<T = any, R = any, N extends string = string>(
job: MinimalJob<T, R, N>,
progress: number | object,
): Promise<void> {
const client = await this.queue.client;
const keys = [this.queue.toKey(job.id), this.queue.keys.events];
const progressJson = JSON.stringify(progress);
const result = await (<any>client).updateProgress(
keys.concat([job.id, progressJson]),
);
if (result < 0) {
throw this.finishedErrors(result, job.id, 'updateProgress');
}
this.queue.emit('progress', job, progress);
}
protected moveToFinishedArgs<T = any, R = any, N extends string = string>(
job: MinimalJob<T, R, N>,
val: any,
propVal: FinishedPropValAttribute,
shouldRemove: undefined | boolean | number | KeepJobs,
target: FinishedStatus,
token: string,
timestamp: number,
fetchNext = true,
): (string | number | boolean | Buffer)[] {
const queueKeys = this.queue.keys;
const opts: WorkerOptions = <WorkerOptions>this.queue.opts;
const workerKeepJobs =
target === 'completed' ? opts.removeOnComplete : opts.removeOnFail;
const metricsKey = this.queue.toKey(`metrics:${target}`);
const keys = this.moveToFinishedKeys;
keys[8] = queueKeys[target];
keys[9] = this.queue.toKey(job.id ?? '');
keys[11] = metricsKey;
const keepJobs = this.getKeepJobs(shouldRemove, workerKeepJobs);
const args = [
job.id,
timestamp,
propVal,
typeof val === 'undefined' ? 'null' : val,
target,
JSON.stringify({ jobId: job.id, val: val }),
!fetchNext || this.queue.closing ? 0 : 1,
queueKeys[''],
pack({
token,
keepJobs,
limiter: opts.limiter,
lockDuration: opts.lockDuration,
attempts: job.opts.attempts,
attemptsMade: job.attemptsMade,
maxMetricsSize: opts.metrics?.maxDataPoints
? opts.metrics?.maxDataPoints
: '',
fpof: !!job.opts?.failParentOnFailure,
}),
];
return keys.concat(args);
}
protected getKeepJobs(
shouldRemove: undefined | boolean | number | KeepJobs,
workerKeepJobs: undefined | KeepJobs,
) {
if (typeof shouldRemove === 'undefined') {
return workerKeepJobs || { count: shouldRemove ? 0 : -1 };
}
return typeof shouldRemove === 'object'
? shouldRemove
: typeof shouldRemove === 'number'
? { count: shouldRemove }
: { count: shouldRemove ? 0 : -1 };
}
protected async moveToFinished<
DataType = any,
ReturnType = any,
NameType extends string = string,
>(
job: MinimalJob<DataType, ReturnType, NameType>,
val: any,
propVal: FinishedPropValAttribute,
shouldRemove: boolean | number | KeepJobs,
target: FinishedStatus,
token: string,
fetchNext: boolean,
) {
const client = await this.queue.client;
const timestamp = Date.now();
const args = this.moveToFinishedArgs<DataType, ReturnType, NameType>(
job,
val,
propVal,
shouldRemove,
target,
token,
timestamp,
fetchNext,
);
const result = await (<any>client).moveToFinished(args);
if (result < 0) {
throw this.finishedErrors(result, job.id, 'finished', 'active');
} else {
job.finishedOn = timestamp;
if (typeof result !== 'undefined') {
return raw2NextJobData(result);
}
}
}
finishedErrors(
code: number,
jobId: string,
command: string,
state?: string,
): Error {
switch (code) {
case ErrorCode.JobNotExist:
return new Error(`Missing key for job ${jobId}. ${command}`);
case ErrorCode.JobLockNotExist:
return new Error(`Missing lock for job ${jobId}. ${command}`);
case ErrorCode.JobNotInState:
return new Error(
`Job ${jobId} is not in the ${state} state. ${command}`,
);
case ErrorCode.JobPendingDependencies:
return new Error(`Job ${jobId} has pending dependencies. ${command}`);
case ErrorCode.ParentJobNotExist:
return new Error(`Missing key for parent job ${jobId}. ${command}`);
case ErrorCode.JobLockMismatch:
return new Error(
`Lock mismatch for job ${jobId}. Cmd ${command} from ${state}`,
);
default:
return new Error(`Unknown code ${code} error for ${jobId}. ${command}`);
}
}
private drainArgs(delayed: boolean): (string | number)[] {
const queueKeys = this.queue.keys;
const keys: (string | number)[] = [
queueKeys.wait,
queueKeys.paused,
delayed ? queueKeys.delayed : '',
queueKeys.priority,
];
const args = [queueKeys['']];
return keys.concat(args);
}
async drain(delayed: boolean): Promise<void> {
const client = await this.queue.client;
const args = this.drainArgs(delayed);
return (<any>client).drain(args);
}
private getRangesArgs(
types: JobType[],
start: number,
end: number,
asc: boolean,
): (string | number)[] {
const queueKeys = this.queue.keys;
const transformedTypes = types.map(type => {
return type === 'waiting' ? 'wait' : type;
});
const keys: (string | number)[] = [queueKeys['']];
const args = [start, end, asc ? '1' : '0', ...transformedTypes];
return keys.concat(args);
}
async getRanges(
types: JobType[],
start = 0,
end = 1,
asc = false,
): Promise<[string][]> {
const client = await this.queue.client;
const args = this.getRangesArgs(types, start, end, asc);
return (<any>client).getRanges(args);
}
private getCountsArgs(types: JobType[]): (string | number)[] {
const queueKeys = this.queue.keys;
const transformedTypes = types.map(type => {
return type === 'waiting' ? 'wait' : type;
});
const keys: (string | number)[] = [queueKeys['']];
const args = [...transformedTypes];
return keys.concat(args);
}
async getCounts(types: JobType[]): Promise<number[]> {
const client = await this.queue.client;
const args = this.getCountsArgs(types);
return (<any>client).getCounts(args);
}
moveToCompleted<T = any, R = any, N extends string = string>(
job: MinimalJob<T, R, N>,
returnvalue: R,
removeOnComplete: boolean | number | KeepJobs,
token: string,
fetchNext: boolean,
) {
return this.moveToFinished<T, R, N>(
job,
returnvalue,
'returnvalue',
removeOnComplete,
'completed',
token,
fetchNext,
);
}
moveToFailedArgs<T = any, R = any, N extends string = string>(
job: MinimalJob<T, R, N>,
failedReason: string,
removeOnFailed: boolean | number | KeepJobs,
token: string,
fetchNext = false,
): (string | number | boolean | Buffer)[] {
const timestamp = Date.now();
return this.moveToFinishedArgs(
job,
failedReason,
'failedReason',
removeOnFailed,
'failed',
token,
timestamp,
fetchNext,
);
}
async isFinished(
jobId: string,
returnValue = false,
): Promise<number | [number, string]> {
const client = await this.queue.client;
const keys = ['completed', 'failed', jobId].map((key: string) => {
return this.queue.toKey(key);
});
return (<any>client).isFinished(
keys.concat([jobId, returnValue ? '1' : '']),
);
}
async getState(jobId: string): Promise<JobState | 'unknown'> {
const client = await this.queue.client;
const keys = [
'completed',
'failed',
'delayed',
'active',
'wait',
'paused',
'waiting-children',
].map((key: string) => {
return this.queue.toKey(key);
});
if (isRedisVersionLowerThan(this.queue.redisVersion, '6.0.6')) {
return (<any>client).getState(keys.concat([jobId]));
}
return (<any>client).getStateV2(keys.concat([jobId]));
}
async changeDelay(jobId: string, delay: number): Promise<void> {
const client = await this.queue.client;
const args = this.changeDelayArgs(jobId, delay);
const result = await (<any>client).changeDelay(args);
if (result < 0) {
throw this.finishedErrors(result, jobId, 'changeDelay', 'delayed');
}
}
private changeDelayArgs(jobId: string, delay: number): (string | number)[] {
//
// Bake in the job id first 12 bits into the timestamp
// to guarantee correct execution order of delayed jobs
// (up to 4096 jobs per given timestamp or 4096 jobs apart per timestamp)
//
// WARNING: Jobs that are so far apart that they wrap around will cause FIFO to fail
//
let timestamp = Date.now() + delay;
if (timestamp > 0) {
timestamp = timestamp * 0x1000 + (+jobId & 0xfff);
}
const keys: (string | number)[] = ['delayed', jobId].map(name => {
return this.queue.toKey(name);
});
keys.push.apply(keys, [this.queue.keys.events]);
return keys.concat([delay, JSON.stringify(timestamp), jobId]);
}
// Note: We have an issue here with jobs using custom job ids
moveToDelayedArgs(
jobId: string,
timestamp: number,
token: string,
): (string | number)[] {
//
// Bake in the job id first 12 bits into the timestamp
// to guarantee correct execution order of delayed jobs
// (up to 4096 jobs per given timestamp or 4096 jobs apart per timestamp)
//
// WARNING: Jobs that are so far apart that they wrap around will cause FIFO to fail
//
timestamp = Math.max(0, timestamp ?? 0);
if (timestamp > 0) {
timestamp = timestamp * 0x1000 + (+jobId & 0xfff);
}
const keys: (string | number)[] = [
'wait',
'active',
'priority',
'delayed',
jobId,
].map(name => {
return this.queue.toKey(name);
});
keys.push.apply(keys, [
this.queue.keys.events,
this.queue.keys.paused,
this.queue.keys.meta,
]);
return keys.concat([
this.queue.keys[''],
Date.now(),
JSON.stringify(timestamp),
jobId,
token,
]);
}
saveStacktraceArgs(
jobId: string,
stacktrace: string,
failedReason: string,
): string[] {
const keys: string[] = [this.queue.toKey(jobId)];
return keys.concat([stacktrace, failedReason]);
}
moveToWaitingChildrenArgs(
jobId: string,
token: string,
opts?: MoveToWaitingChildrenOpts,
): string[] {
const timestamp = Date.now();
const childKey = getParentKey(opts.child);
const keys = [`${jobId}:lock`, 'active', 'waiting-children', jobId].map(
name => {
return this.queue.toKey(name);
},
);
return keys.concat([
token,
childKey ?? '',
JSON.stringify(timestamp),
jobId,
]);
}
async moveToDelayed(
jobId: string,
timestamp: number,
token = '0',
): Promise<void> {
const client = await this.queue.client;
const args = this.moveToDelayedArgs(jobId, timestamp, token);
const result = await (<any>client).moveToDelayed(args);
if (result < 0) {
throw this.finishedErrors(result, jobId, 'moveToDelayed', 'active');
}
}
/**
* Move parent job to waiting-children state.
*
* @returns true if job is successfully moved, false if there are pending dependencies.
* @throws JobNotExist
* This exception is thrown if jobId is missing.
* @throws JobLockNotExist
* This exception is thrown if job lock is missing.
* @throws JobNotInState
* This exception is thrown if job is not in active state.
*/
async moveToWaitingChildren(
jobId: string,
token: string,
opts: MoveToWaitingChildrenOpts = {},
): Promise<boolean> {
const client = await this.queue.client;
const args = this.moveToWaitingChildrenArgs(jobId, token, opts);
const result = await (<any>client).moveToWaitingChildren(args);
switch (result) {
case 0:
return true;
case 1:
return false;
default:
throw this.finishedErrors(
result,
jobId,
'moveToWaitingChildren',
'active',
);
}
}
/**
* Remove jobs in a specific state.
*
* @returns Id jobs from the deleted records.
*/
async cleanJobsInSet(
set: string,
timestamp: number,
limit = 0,
): Promise<string[]> {
const client = await this.queue.client;
return (<any>client).cleanJobsInSet([
this.queue.toKey(set),
this.queue.toKey('events'),
this.queue.toKey(''),
timestamp,
limit,
set,
]);
}
retryJobArgs(
jobId: string,
lifo: boolean,
token: string,
): (string | number)[] {
const keys: (string | number)[] = [
'active',
'wait',
'paused',
jobId,
'meta',
].map(name => {
return this.queue.toKey(name);
});
keys.push(
this.queue.keys.events,
this.queue.keys.delayed,
this.queue.keys.priority,
);
const pushCmd = (lifo ? 'R' : 'L') + 'PUSH';
return keys.concat([
this.queue.toKey(''),
Date.now(),
pushCmd,
jobId,
token,
]);
}
protected retryJobsArgs(
state: FinishedStatus,
count: number,
timestamp: number,
): (string | number)[] {
const keys: (string | number)[] = [
this.queue.toKey(''),
this.queue.keys.events,
this.queue.toKey(state),
this.queue.toKey('wait'),
this.queue.toKey('paused'),
this.queue.toKey('meta'),
];
const args = [count, timestamp, state];
return keys.concat(args);
}
async retryJobs(
state: FinishedStatus = 'failed',
count = 1000,
timestamp = new Date().getTime(),
): Promise<number> {
const client = await this.queue.client;
const args = this.retryJobsArgs(state, count, timestamp);
return (<any>client).retryJobs(args);
}
/**
* Attempts to reprocess a job
*
* @param job -
* @param state - The expected job state. If the job is not found
* on the provided state, then it's not reprocessed. Supported states: 'failed', 'completed'
*
* @returns Returns a promise that evaluates to a return code:
* 1 means the operation was a success
* 0 means the job does not exist
* -1 means the job is currently locked and can't be retried.
* -2 means the job was not found in the expected set
*/
async reprocessJob<T = any, R = any, N extends string = string>(
job: MinimalJob<T, R, N>,
state: 'failed' | 'completed',
): Promise<void> {
const client = await this.queue.client;
const keys = [
this.queue.toKey(job.id),
this.queue.keys.events,
this.queue.toKey(state),
this.queue.toKey('wait'),
];
const args = [
job.id,
(job.opts.lifo ? 'R' : 'L') + 'PUSH',
state === 'failed' ? 'failedReason' : 'returnvalue',
state,
];
const result = await (<any>client).reprocessJob(keys.concat(args));
switch (result) {
case 1:
return;
default:
throw this.finishedErrors(result, job.id, 'reprocessJob', state);
}
}
async moveToActive(token: string, jobId?: string) {
const client = await this.queue.client;
const opts = this.queue.opts as WorkerOptions;
const queueKeys = this.queue.keys;
const keys = [
queueKeys.wait,
queueKeys.active,
queueKeys.priority,
queueKeys.events,
queueKeys.stalled,
queueKeys.limiter,
queueKeys.delayed,
queueKeys.paused,
queueKeys.meta,
];
const args: (string | number | boolean | Buffer)[] = [
queueKeys[''],
Date.now(),
jobId,
pack({
token,
lockDuration: opts.lockDuration,
limiter: opts.limiter,
}),
];
const result = await (<any>client).moveToActive(
(<(string | number | boolean | Buffer)[]>keys).concat(args),
);
return raw2NextJobData(result);
}
async promote(jobId: string): Promise<number> {
const client = await this.queue.client;
const keys = [
this.queue.keys.delayed,
this.queue.keys.wait,
this.queue.keys.paused,
this.queue.keys.meta,
this.queue.keys.priority,
this.queue.keys.events,
];
const args = [this.queue.toKey(''), jobId];
return (<any>client).promote(keys.concat(args));
}
/**
* Looks for unlocked jobs in the active queue.
*
* The job was being worked on, but the worker process died and it failed to renew the lock.
* We call these jobs 'stalled'. This is the most common case. We resolve these by moving them
* back to wait to be re-processed. To prevent jobs from cycling endlessly between active and wait,
* (e.g. if the job handler keeps crashing),
* we limit the number stalled job recoveries to settings.maxStalledCount.
*/
async moveStalledJobsToWait(): Promise<[string[], string[]]> {
const client = await this.queue.client;
const opts = this.queue.opts as WorkerOptions;
const keys: (string | number)[] = [
this.queue.keys.stalled,
this.queue.keys.wait,
this.queue.keys.active,
this.queue.keys.failed,
this.queue.keys['stalled-check'],
this.queue.keys.meta,
this.queue.keys.paused,
this.queue.keys.events,
];
const args = [
opts.maxStalledCount,
this.queue.toKey(''),
Date.now(),
opts.stalledInterval,
];
return (<any>client).moveStalledJobsToWait(keys.concat(args));
}
/**
* Moves a job back from Active to Wait.
* This script is used when a job has been manually rate limited and needs
* to be moved back to wait from active status.
*
* @param client - Redis client
* @param jobId - Job id
* @returns
*/
moveJobFromActiveToWait(
client: ChainableCommander,
jobId: string,
token: string,
) {
const lockKey = `${this.queue.toKey(jobId)}:lock`;
const keys = [
this.queue.keys.active,
this.queue.keys.wait,
this.queue.keys.stalled,
lockKey,
];
const args = [jobId, token];
return (<any>client).moveJobFromActiveToWait(keys.concat(args));
}
async obliterate(opts: { force: boolean; count: number }): Promise<number> {
const client = await this.queue.client;
const keys: (string | number)[] = [
this.queue.keys.meta,
this.queue.toKey(''),
];
const args = [opts.count, opts.force ? 'force' : null];
const result = await (<any>client).obliterate(keys.concat(args));
if (result < 0) {
switch (result) {
case -1:
throw new Error('Cannot obliterate non-paused queue');
case -2:
throw new Error('Cannot obliterate queue with active jobs');
}
}
return result;
}
/*
// *
// * Attempts to reprocess a job
// *
// * @param {Job} job
// * @param {Object} options
// * @param {String} options.state The expected job state. If the job is not found
// * on the provided state, then it's not reprocessed. Supported states: 'failed', 'completed'
// *
// * @return {Promise<Number>} Returns a promise that evaluates to a return code:
// * 1 means the operation was a success
// * 0 means the job does not exist
// * -1 means the job is currently locked and can't be retried.
// * -2 means the job was not found in the expected set
static reprocessJob(job: Jov, state: string) {
var queue = job.queue;
var keys = [
queue.toKey(job.id),
queue.toKey(job.id) + ':lock',
queue.toKey(state),
queue.toKey('wait'),
];
var args = [job.id, (job.opts.lifo ? 'R' : 'L') + 'PUSH', queue.token];
return queue.client.reprocessJob(keys.concat(args));
}
*/
}
export function raw2NextJobData(raw: any[]) {
if (raw) {
const result = [null, raw[1], raw[2], raw[3]];
if (raw[0]) {
result[0] = array2obj(raw[0]);
}
return result;
}
return [];
}