/
worker.ts
965 lines (851 loc) · 25.4 KB
/
worker.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
import * as fs from 'fs';
import { Redis } from 'ioredis';
import * as path from 'path';
import { v4 } from 'uuid';
// Note: this Polyfill is only needed for Node versions < 15.4.0
import { AbortController } from 'node-abort-controller';
import {
GetNextJobOptions,
IoredisListener,
JobJsonRaw,
Processor,
RedisClient,
WorkerOptions,
} from '../interfaces';
import { MinimalQueue } from '../types';
import {
delay,
DELAY_TIME_1,
isNotConnectionError,
isRedisInstance,
isRedisVersionLowerThan,
WORKER_SUFFIX,
} from '../utils';
import { QueueBase } from './queue-base';
import { Repeat } from './repeat';
import { ChildPool } from './child-pool';
import { Job } from './job';
import { RedisConnection } from './redis-connection';
import sandbox from './sandbox';
import { AsyncFifoQueue } from './async-fifo-queue';
import { DelayedError } from './delayed-error';
import { WaitingChildrenError } from './waiting-children-error';
// 10 seconds is the maximum time a BRPOPLPUSH can block.
const maximumBlockTimeout = 10;
// note: sandboxed processors would also like to define concurrency per process
// for better resource utilization.
export interface WorkerListener<
DataType = any,
ResultType = any,
NameType extends string = string,
> extends IoredisListener {
/**
* Listen to 'active' event.
*
* This event is triggered when a job enters the 'active' state.
*/
active: (job: Job<DataType, ResultType, NameType>, prev: string) => void;
/**
* Listen to 'closing' event.
*
* This event is triggered when the worker is closed.
*/
closed: () => void;
/**
* Listen to 'closing' event.
*
* This event is triggered when the worker is closing.
*/
closing: (msg: string) => void;
/**
* Listen to 'completed' event.
*
* This event is triggered when a job has successfully completed.
*/
completed: (
job: Job<DataType, ResultType, NameType>,
result: ResultType,
prev: string,
) => void;
/**
* Listen to 'drained' event.
*
* This event is triggered when the queue has drained the waiting list.
* Note that there could still be delayed jobs waiting their timers to expire
* and this event will still be triggered as long as the waiting list has emptied.
*/
drained: () => void;
/**
* Listen to 'error' event.
*
* This event is triggered when an error is throw.
*/
error: (failedReason: Error) => void;
/**
* Listen to 'failed' event.
*
* This event is triggered when a job has thrown an exception.
* Note: job parameter could be received as undefined when an stalled job
* reaches the stalled limit and it is deleted by the removeOnFail option.
*/
failed: (
job: Job<DataType, ResultType, NameType> | undefined,
error: Error,
prev: string,
) => void;
/**
* Listen to 'paused' event.
*
* This event is triggered when the queue is paused.
*/
paused: () => void;
/**
* Listen to 'progress' event.
*
* This event is triggered when a job updates it progress, i.e. the
* Job##updateProgress() method is called. This is useful to notify
* progress or any other data from within a processor to the rest of the
* world.
*/
progress: (
job: Job<DataType, ResultType, NameType>,
progress: number | object,
) => void;
/**
* Listen to 'ready' event.
*
* This event is triggered when blockingConnection is ready.
*/
ready: () => void;
/**
* Listen to 'resumed' event.
*
* This event is triggered when the queue is resumed.
*/
resumed: () => void;
/**
* Listen to 'stalled' event.
*
* This event is triggered when a job has stalled and
* has been moved back to the wait list.
*/
stalled: (jobId: string, prev: string) => void;
}
const RATE_LIMIT_ERROR = 'bullmq:rateLimitExceeded';
/**
*
* This class represents a worker that is able to process jobs from the queue.
* As soon as the class is instantiated and a connection to Redis is established
* it will start processing jobs.
*
*/
export class Worker<
DataType = any,
ResultType = any,
NameType extends string = string,
> extends QueueBase {
readonly opts: WorkerOptions;
readonly id: string;
private drained: boolean = false;
private waiting: Promise<string> | null = null;
private running = false;
private blockUntil = 0;
private limitUntil = 0;
private abortDelayController: AbortController | null = null;
protected processFn: Processor<DataType, ResultType, NameType>;
private resumeWorker: () => void;
protected paused: Promise<void>;
private _repeat: Repeat;
private childPool: ChildPool;
private extendLocksTimer: NodeJS.Timeout | null = null;
private blockingConnection: RedisConnection;
private stalledCheckTimer: NodeJS.Timeout;
private asyncFifoQueue: AsyncFifoQueue<void | Job<
DataType,
ResultType,
NameType
>>;
static RateLimitError(): Error {
return new Error(RATE_LIMIT_ERROR);
}
constructor(
name: string,
processor?: string | null | Processor<DataType, ResultType, NameType>,
opts: WorkerOptions = {},
Connection?: typeof RedisConnection,
) {
super(
name,
{
...opts,
sharedConnection: isRedisInstance(opts.connection),
blockingConnection: true,
},
Connection,
);
this.opts = {
drainDelay: 5,
concurrency: 1,
lockDuration: 30000,
maxStalledCount: 1,
stalledInterval: 30000,
autorun: true,
runRetryDelay: 15000,
...this.opts,
};
if (this.opts.stalledInterval <= 0) {
throw new Error('stalledInterval must be greater than 0');
}
this.concurrency = this.opts.concurrency;
this.opts.lockRenewTime =
this.opts.lockRenewTime || this.opts.lockDuration / 2;
this.id = v4();
if (processor) {
if (typeof processor === 'function') {
this.processFn = processor;
} else {
// SANDBOXED
const supportedFileTypes = ['.js', '.ts', '.flow', '.cjs'];
const processorFile =
processor +
(supportedFileTypes.includes(path.extname(processor)) ? '' : '.js');
if (!fs.existsSync(processorFile)) {
throw new Error(`File ${processorFile} does not exist`);
}
const mainFile = this.opts.useWorkerThreads
? 'main-worker.js'
: 'main.js';
let mainFilePath = path.join(__dirname, `${mainFile}`);
try {
fs.statSync(mainFilePath); // would throw if file not exists
} catch (_) {
mainFilePath = path.join(
process.cwd(),
`dist/cjs/classes/${mainFile}`,
);
fs.statSync(mainFilePath);
}
this.childPool = new ChildPool({
mainFile: mainFilePath,
useWorkerThreads: this.opts.useWorkerThreads,
});
this.processFn = sandbox<DataType, ResultType, NameType>(
processor,
this.childPool,
).bind(this);
}
if (this.opts.autorun) {
this.run().catch(error => this.emit('error', error));
}
}
const connectionName = this.clientName(WORKER_SUFFIX);
this.blockingConnection = new RedisConnection(
isRedisInstance(opts.connection)
? (<Redis>opts.connection).duplicate({ connectionName })
: { ...opts.connection, connectionName },
);
this.blockingConnection.on('error', error => this.emit('error', error));
this.blockingConnection.on('ready', () =>
setTimeout(() => this.emit('ready'), 0),
);
}
emit<U extends keyof WorkerListener<DataType, ResultType, NameType>>(
event: U,
...args: Parameters<WorkerListener<DataType, ResultType, NameType>[U]>
): boolean {
return super.emit(event, ...args);
}
off<U extends keyof WorkerListener<DataType, ResultType, NameType>>(
eventName: U,
listener: WorkerListener<DataType, ResultType, NameType>[U],
): this {
super.off(eventName, listener);
return this;
}
on<U extends keyof WorkerListener<DataType, ResultType, NameType>>(
event: U,
listener: WorkerListener<DataType, ResultType, NameType>[U],
): this {
super.on(event, listener);
return this;
}
once<U extends keyof WorkerListener<DataType, ResultType, NameType>>(
event: U,
listener: WorkerListener<DataType, ResultType, NameType>[U],
): this {
super.once(event, listener);
return this;
}
protected callProcessJob(
job: Job<DataType, ResultType, NameType>,
token: string,
): Promise<ResultType> {
return this.processFn(job, token);
}
protected createJob(
data: JobJsonRaw,
jobId: string,
): Job<DataType, ResultType, NameType> {
return this.Job.fromJSON(this as MinimalQueue, data, jobId) as Job<
DataType,
ResultType,
NameType
>;
}
/**
*
* Waits until the worker is ready to start processing jobs.
* In general only useful when writing tests.
*
*/
async waitUntilReady(): Promise<RedisClient> {
await super.waitUntilReady();
return this.blockingConnection.client;
}
set concurrency(concurrency: number) {
if (
typeof concurrency !== 'number' ||
concurrency < 1 ||
!isFinite(concurrency)
) {
throw new Error('concurrency must be a finite number greater than 0');
}
this.opts.concurrency = concurrency;
}
get repeat(): Promise<Repeat> {
return new Promise<Repeat>(async resolve => {
if (!this._repeat) {
const connection = await this.client;
this._repeat = new Repeat(this.name, {
...this.opts,
connection,
});
this._repeat.on('error', e => this.emit.bind(this, e));
}
resolve(this._repeat);
});
}
async run() {
if (!this.processFn) {
throw new Error('No process function is defined.');
}
if (this.running) {
throw new Error('Worker is already running.');
}
try {
this.running = true;
if (this.closing) {
return;
}
await this.startStalledCheckTimer();
const jobsInProgress = new Set<{ job: Job; ts: number }>();
this.startLockExtenderTimer(jobsInProgress);
const asyncFifoQueue = (this.asyncFifoQueue =
new AsyncFifoQueue<void | Job<DataType, ResultType, NameType>>());
let tokenPostfix = 0;
while (!this.closing) {
while (
!this.waiting &&
asyncFifoQueue.numTotal() < this.opts.concurrency &&
(!this.limitUntil || asyncFifoQueue.numTotal() == 0)
) {
const token = `${this.id}:${tokenPostfix++}`;
asyncFifoQueue.add(
this.retryIfFailed<void | Job<DataType, ResultType, NameType>>(
() => this.getNextJob(token),
this.opts.runRetryDelay,
),
);
}
const job = await asyncFifoQueue.fetch();
if (job) {
const token = job.token;
asyncFifoQueue.add(
this.retryIfFailed<void | Job<DataType, ResultType, NameType>>(
() =>
this.processJob(
job,
token,
() => asyncFifoQueue.numTotal() <= this.opts.concurrency,
jobsInProgress,
),
this.opts.runRetryDelay,
),
);
}
}
this.running = false;
return asyncFifoQueue.waitAll();
} catch (error) {
this.running = false;
throw error;
}
}
/**
* Returns a promise that resolves to the next job in queue.
* @param token - worker token to be assigned to retrieved job
* @returns a Job or undefined if no job was available in the queue.
*/
async getNextJob(
token: string,
{ block = true }: GetNextJobOptions = {},
): Promise<Job<DataType, ResultType, NameType> | undefined> {
if (this.paused) {
if (block) {
await this.paused;
} else {
return;
}
}
if (this.closing) {
return;
}
if (this.drained && block && !this.limitUntil && !this.waiting) {
try {
this.waiting = this.waitForJob();
try {
const jobId = await this.waiting;
return this.moveToActive(token, jobId);
} finally {
this.waiting = null;
}
} catch (err) {
// Swallow error if locally paused or closing since we did force a disconnection
if (
!(this.paused || this.closing) &&
isNotConnectionError(<Error>err)
) {
throw err;
}
}
} else {
if (this.limitUntil) {
this.abortDelayController?.abort();
this.abortDelayController = new AbortController();
await this.delay(this.limitUntil, this.abortDelayController);
}
return this.moveToActive(token);
}
}
/**
* Overrides the rate limit to be active for the next jobs.
*
* @param expireTimeMs - expire time in ms of this rate limit.
*/
async rateLimit(expireTimeMs: number): Promise<void> {
await this.client.then(client =>
client.set(
this.keys.limiter,
Number.MAX_SAFE_INTEGER,
'PX',
expireTimeMs,
),
);
}
protected async moveToActive(
token: string,
jobId?: string,
): Promise<Job<DataType, ResultType, NameType>> {
// If we get the special delayed job ID, we pick the delay as the next
// block timeout.
if (jobId && jobId.startsWith('0:')) {
this.blockUntil = parseInt(jobId.split(':')[1]) || 0;
}
const [jobData, id, limitUntil, delayUntil] =
await this.scripts.moveToActive(token, jobId);
return this.nextJobFromJobData(jobData, id, limitUntil, delayUntil, token);
}
private async waitForJob() {
// I am not sure returning here this quick is a good idea, the main
// loop could stay looping at a very high speed and consume all CPU time.
if (this.paused) {
return;
}
try {
const opts: WorkerOptions = <WorkerOptions>this.opts;
if (!this.closing) {
const client = await this.blockingConnection.client;
let blockTimeout = Math.max(
this.blockUntil
? (this.blockUntil - Date.now()) / 1000
: opts.drainDelay,
0.01,
);
// Only Redis v6.0.0 and above supports doubles as block time
blockTimeout = isRedisVersionLowerThan(
this.blockingConnection.redisVersion,
'6.0.0',
)
? Math.ceil(blockTimeout)
: blockTimeout;
// We restrict the maximum block timeout to 10 second to avoid
// blocking the connection for too long in the case of reconnections
// reference: https://github.com/taskforcesh/bullmq/issues/1658
blockTimeout = Math.min(blockTimeout, maximumBlockTimeout);
const jobId = await client.brpoplpush(
this.keys.wait,
this.keys.active,
blockTimeout,
);
return jobId;
}
} catch (error) {
if (isNotConnectionError(<Error>error)) {
this.emit('error', <Error>error);
}
if (!this.closing) {
await this.delay();
}
} finally {
this.waiting = null;
}
}
/**
*
* This function is exposed only for testing purposes.
*/
async delay(
milliseconds?: number,
abortController?: AbortController,
): Promise<void> {
await delay(milliseconds || DELAY_TIME_1, abortController);
}
protected async nextJobFromJobData(
jobData?: JobJsonRaw,
jobId?: string,
limitUntil?: number,
delayUntil?: number,
token?: string,
): Promise<Job<DataType, ResultType, NameType>> {
if (!jobData) {
if (!this.drained) {
this.emit('drained');
this.drained = true;
this.blockUntil = 0;
}
}
// Update limitUntil and delayUntil
// TODO: Refactor out of this function
this.limitUntil = Math.max(limitUntil, 0) || 0;
if (delayUntil) {
this.blockUntil = Math.max(delayUntil, 0) || 0;
}
if (jobData) {
this.drained = false;
const job = this.createJob(jobData, jobId);
job.token = token;
if (job.opts.repeat) {
const repeat = await this.repeat;
await repeat.addNextRepeatableJob(job.name, job.data, job.opts);
}
return job;
}
}
async processJob(
job: Job<DataType, ResultType, NameType>,
token: string,
fetchNextCallback = () => true,
jobsInProgress: Set<{ job: Job; ts: number }>,
): Promise<void | Job<DataType, ResultType, NameType>> {
if (!job || this.closing || this.paused) {
return;
}
const handleCompleted = async (result: ResultType) => {
if (!this.connection.closing) {
const completed = await job.moveToCompleted(
result,
token,
fetchNextCallback() && !(this.closing || this.paused),
);
this.emit('completed', job, result, 'active');
const [jobData, jobId, limitUntil, delayUntil] = completed || [];
return this.nextJobFromJobData(
jobData,
jobId,
limitUntil,
delayUntil,
token,
);
}
};
const handleFailed = async (err: Error) => {
if (!this.connection.closing) {
try {
if (err.message == RATE_LIMIT_ERROR) {
this.limitUntil = await this.moveLimitedBackToWait(job, token);
return;
}
if (
err instanceof DelayedError ||
err.message == 'DelayedError' ||
err instanceof WaitingChildrenError ||
err.name == 'WaitingChildrenError'
) {
return;
}
await job.moveToFailed(err, token);
this.emit('failed', job, err, 'active');
} catch (err) {
this.emit('error', <Error>err);
// It probably means that the job has lost the lock before completion
// A worker will (or already has) moved the job back
// to the waiting list (as stalled)
}
}
};
this.emit('active', job, 'waiting');
const inProgressItem = { job, ts: Date.now() };
try {
jobsInProgress.add(inProgressItem);
const result = await this.callProcessJob(job, token);
return await handleCompleted(result);
} catch (err) {
return handleFailed(<Error>err);
} finally {
jobsInProgress.delete(inProgressItem);
}
}
/**
*
* Pauses the processing of this queue only for this worker.
*/
async pause(doNotWaitActive?: boolean): Promise<void> {
if (!this.paused) {
this.paused = new Promise(resolve => {
this.resumeWorker = function () {
resolve();
this.paused = null; // Allow pause to be checked externally for paused state.
this.resumeWorker = null;
};
});
await (!doNotWaitActive && this.whenCurrentJobsFinished());
this.emit('paused');
}
}
/**
*
* Resumes processing of this worker (if paused).
*/
resume(): void {
if (this.resumeWorker) {
this.resumeWorker();
this.emit('resumed');
}
}
/**
*
* Checks if worker is paused.
*
* @returns true if worker is paused, false otherwise.
*/
isPaused(): boolean {
return !!this.paused;
}
/**
*
* Checks if worker is currently running.
*
* @returns true if worker is running, false otherwise.
*/
isRunning(): boolean {
return this.running;
}
/**
*
* Closes the worker and related redis connections.
*
* This method waits for current jobs to finalize before returning.
*
* @param force - Use force boolean parameter if you do not want to wait for
* current jobs to be processed.
*
* @returns Promise that resolves when the worker has been closed.
*/
close(force = false): Promise<void> {
if (this.closing) {
return this.closing;
}
this.closing = (async () => {
this.emit('closing', 'closing queue');
this.abortDelayController?.abort();
const client = await this.blockingConnection.client;
this.resume();
await Promise.resolve()
.finally(() => {
return force || this.whenCurrentJobsFinished(false);
})
.finally(() => {
const closePoolPromise = this.childPool?.clean();
if (force) {
// since we're not waiting for the job to end attach
// an error handler to avoid crashing the whole process
closePoolPromise?.catch(err => {
console.error(err); // TODO: emit error in next breaking change version
});
return;
}
return closePoolPromise;
})
.finally(() => clearTimeout(this.extendLocksTimer))
.finally(() => clearTimeout(this.stalledCheckTimer))
.finally(() => client.disconnect())
.finally(() => this.connection.close())
.finally(() => this.emit('closed'));
})();
return this.closing;
}
/**
*
* Manually starts the stalled checker.
* The check will run once as soon as this method is called, and
* then every opts.stalledInterval milliseconds until the worker is closed.
* Note: Normally you do not need to call this method, since the stalled checker
* is automatically started when the worker starts processing jobs after
* calling run. However if you want to process the jobs manually you need
* to call this method to start the stalled checker.
*
* @see {@link https://docs.bullmq.io/patterns/manually-fetching-jobs}
*/
async startStalledCheckTimer(): Promise<void> {
if (!this.opts.skipStalledCheck) {
clearTimeout(this.stalledCheckTimer);
if (!this.closing) {
try {
await this.checkConnectionError(() => this.moveStalledJobsToWait());
this.stalledCheckTimer = setTimeout(async () => {
await this.startStalledCheckTimer();
}, this.opts.stalledInterval);
} catch (err) {
this.emit('error', <Error>err);
}
}
}
}
private startLockExtenderTimer(
jobsInProgress: Set<{ job: Job; ts: number }>,
): void {
if (!this.opts.skipLockRenewal) {
clearTimeout(this.extendLocksTimer);
if (!this.closing) {
this.extendLocksTimer = setTimeout(async () => {
// Get all the jobs whose locks expire in less than 1/2 of the lockRenewTime
const now = Date.now();
const jobsToExtend = [];
for (const item of jobsInProgress) {
const { job, ts } = item;
if (!ts) {
item.ts = now;
continue;
}
if (ts + this.opts.lockRenewTime / 2 < now) {
item.ts = now;
jobsToExtend.push(job);
}
}
try {
if (jobsToExtend.length) {
await this.extendLocks(jobsToExtend);
}
} catch (err) {
this.emit('error', <Error>err);
}
this.startLockExtenderTimer(jobsInProgress);
}, this.opts.lockRenewTime / 2);
}
}
}
/**
* Returns a promise that resolves when active jobs are cleared
*
* @returns
*/
private async whenCurrentJobsFinished(reconnect = true) {
//
// Force reconnection of blocking connection to abort blocking redis call immediately.
//
if (this.waiting) {
await this.blockingConnection.disconnect();
} else {
reconnect = false;
}
if (this.asyncFifoQueue) {
await this.asyncFifoQueue.waitAll();
}
reconnect && (await this.blockingConnection.reconnect());
}
private async retryIfFailed<T>(fn: () => Promise<T>, delayInMs: number) {
const retry = 1;
do {
try {
return await fn();
} catch (err) {
this.emit('error', <Error>err);
if (delayInMs) {
await this.delay(delayInMs);
} else {
return;
}
}
} while (retry);
}
protected async extendLocks(jobs: Job[]) {
try {
const multi = (await this.client).multi();
for (const job of jobs) {
await this.scripts.extendLock(
job.id,
job.token,
this.opts.lockDuration,
multi,
);
}
const result = (await multi.exec()) as [Error, string][];
for (const [err, jobId] of result) {
if (err) {
// TODO: signal process function that the job has been lost.
this.emit(
'error',
new Error(`could not renew lock for job ${jobId}`),
);
}
}
} catch (err) {
this.emit('error', <Error>err);
}
}
private async moveStalledJobsToWait() {
const chunkSize = 50;
const [failed, stalled] = await this.scripts.moveStalledJobsToWait();
stalled.forEach((jobId: string) => this.emit('stalled', jobId, 'active'));
const jobPromises: Promise<Job<DataType, ResultType, NameType>>[] = [];
for (let i = 0; i < failed.length; i++) {
jobPromises.push(
Job.fromId<DataType, ResultType, NameType>(
this as MinimalQueue,
failed[i],
),
);
if ((i + 1) % chunkSize === 0) {
this.notifyFailedJobs(await Promise.all(jobPromises));
jobPromises.length = 0;
}
}
this.notifyFailedJobs(await Promise.all(jobPromises));
}
private notifyFailedJobs(failedJobs: Job<DataType, ResultType, NameType>[]) {
failedJobs.forEach((job: Job<DataType, ResultType, NameType>) =>
this.emit(
'failed',
job,
new Error('job stalled more than allowable limit'),
'active',
),
);
}
private moveLimitedBackToWait(
job: Job<DataType, ResultType, NameType>,
token: string,
) {
return this.scripts.moveJobFromActiveToWait(job.id, token);
}
}