-
Notifications
You must be signed in to change notification settings - Fork 1.4k
/
queue.js
executable file
·1417 lines (1243 loc) · 37.5 KB
/
queue.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
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
'use strict';
const Redis = require('ioredis');
const EventEmitter = require('events');
const _ = require('lodash');
const fs = require('fs');
const path = require('path');
const util = require('util');
const url = require('url');
const Job = require('./job');
const scripts = require('./scripts');
const errors = require('./errors');
const utils = require('./utils');
const TimerManager = require('./timer-manager');
const { promisify } = require('util');
const { pTimeout } = require('./p-timeout');
const semver = require('semver');
const debuglog = require('util').debuglog('bull');
const uuid = require('uuid');
const commands = require('./scripts/');
/**
Gets or creates a new Queue with the given name.
The Queue keeps 6 data structures:
- wait (list)
- active (list)
- delayed (zset)
- priority (zset)
- completed (zset)
- failed (zset)
--> priorities -- > completed
/ | /
job -> wait -> active
\ ^ \
v | -- > failed
delayed
*/
/**
Delayed jobs are jobs that cannot be executed until a certain time in
ms has passed since they were added to the queue.
The mechanism is simple, a delayedTimestamp variable holds the next
known timestamp that is on the delayed set (or MAX_TIMEOUT_MS if none).
When the current job has finalized the variable is checked, if
no delayed job has to be executed yet a setTimeout is set so that a
delayed job is processed after timing out.
*/
const MINIMUM_REDIS_VERSION = '2.8.18';
/*
interface QueueOptions {
prefix?: string = 'bull',
limiter?: RateLimiter,
redis : RedisOpts, // ioredis defaults,
createClient?: (type: enum('client', 'subscriber'), redisOpts?: RedisOpts) => redisClient,
defaultJobOptions?: JobOptions,
// Advanced settings
settings?: QueueSettings {
lockDuration?: number = 30000,
lockRenewTime?: number = lockDuration / 2,
stalledInterval?: number = 30000,
maxStalledCount?: number = 1, // The maximum number of times a job can be recovered from the 'stalled' state
guardInterval?: number = 5000,
retryProcessDelay?: number = 5000,
drainDelay?: number = 5
isSharedChildPool?: boolean = false
}
}
interface RateLimiter {
max: number, // Number of jobs
duration: number, // per duration milliseconds
}
*/
// Queue(name: string, url?, opts?)
const Queue = function Queue(name, url, opts) {
if (!(this instanceof Queue)) {
return new Queue(name, url, opts);
}
if (_.isString(url)) {
const clonedOpts = _.cloneDeep(opts || {});
opts = {
...clonedOpts,
redis: {
...redisOptsFromUrl(url),
...clonedOpts.redis
}
};
} else {
opts = _.cloneDeep(url || {});
}
if (!_.isObject(opts)) {
throw TypeError('Options must be a valid object');
}
if (opts.limiter) {
if (opts.limiter.max && opts.limiter.duration) {
this.limiter = opts.limiter;
} else {
throw new TypeError('Limiter requires `max` and `duration` options');
}
}
if (opts.defaultJobOptions) {
this.defaultJobOptions = opts.defaultJobOptions;
}
this.name = name;
this.token = uuid.v4();
opts.redis = {
enableReadyCheck: false,
...(_.isString(opts.redis)
? { ...redisOptsFromUrl(opts.redis) }
: opts.redis)
};
_.defaults(opts.redis, {
port: 6379,
host: '127.0.0.1',
db: opts.redis.db || opts.redis.DB,
retryStrategy: function(times) {
return Math.min(Math.exp(times), 20000);
}
});
this.keyPrefix = opts.redis.keyPrefix || opts.prefix || 'bull';
//
// We cannot use ioredis keyPrefix feature since we
// create keys dynamically in lua scripts.
//
delete opts.redis.keyPrefix;
this.clients = [];
const loadCommands = (providedScripts, client) => {
const finalScripts = providedScripts || scripts;
for (const property in finalScripts) {
// Only define the command if not already defined
if (!client[finalScripts[property].name]) {
client.defineCommand(finalScripts[property].name, {
numberOfKeys: finalScripts[property].keys,
lua: finalScripts[property].content
});
}
}
};
const lazyClient = redisClientGetter(this, opts, (type, client) => {
// bubble up Redis error events
const handler = this.emit.bind(this, 'error');
client.on('error', handler);
this.once('close', () => client.removeListener('error', handler));
if (type === 'client') {
this._initializing = (async () => loadCommands(commands, client))().then(
() => {
debuglog(name + ' queue ready');
},
err => {
this.emit('error', new Error('Error initializing Lua scripts'));
throw err;
}
);
this._initializing.catch((/*err*/) => {});
}
});
Object.defineProperties(this, {
//
// Queue client (used to add jobs, pause queues, etc);
//
client: {
get: lazyClient('client')
},
//
// Event subscriber client (receive messages from other instance of the queue)
//
eclient: {
get: lazyClient('subscriber')
},
bclient: {
get: lazyClient('bclient')
}
});
if (opts.skipVersionCheck !== true) {
getRedisVersion(this.client)
.then(version => {
if (semver.lt(version, MINIMUM_REDIS_VERSION)) {
this.emit(
'error',
new Error(
'Redis version needs to be greater than ' +
MINIMUM_REDIS_VERSION +
'. Current: ' +
version
)
);
}
})
.catch((/*err*/) => {
// Ignore this error.
});
}
this.handlers = {};
this.delayTimer;
this.processing = [];
this.retrieving = 0;
this.drained = true;
this.settings = _.defaults(opts.settings, {
lockDuration: 30000,
stalledInterval: 30000,
maxStalledCount: 1,
guardInterval: 5000,
retryProcessDelay: 5000,
drainDelay: 5,
backoffStrategies: {},
isSharedChildPool: false
});
this.metrics = opts.metrics;
this.settings.lockRenewTime =
this.settings.lockRenewTime || this.settings.lockDuration / 2;
this.on('error', () => {
// Dummy handler to avoid process to exit with an unhandled exception.
});
// keeps track of active timers. used by close() to
// ensure that disconnect() is deferred until all
// scheduled redis commands have been executed
this.timers = new TimerManager();
// Bind these methods to avoid constant rebinding and/or creating closures
// in processJobs etc.
this.moveUnlockedJobsToWait = this.moveUnlockedJobsToWait.bind(this);
this.processJob = this.processJob.bind(this);
this.getJobFromId = Job.fromId.bind(null, this);
const keys = {};
_.each(
[
'',
'active',
'wait',
'waiting',
'paused',
'resumed',
'meta-paused',
'active',
'id',
'delayed',
'priority',
'stalled-check',
'completed',
'failed',
'stalled',
'repeat',
'limiter',
'drained',
'duplicated',
'progress',
'de' // debounce key
],
key => {
keys[key] = this.toKey(key);
}
);
this.keys = keys;
};
function redisClientGetter(queue, options, initCallback) {
const createClient = _.isFunction(options.createClient)
? options.createClient
: function(type, config) {
if (['bclient', 'subscriber'].includes(type)) {
return new Redis({ ...config, maxRetriesPerRequest: null });
} else {
return new Redis(config);
}
};
const connections = {};
return function(type) {
return function() {
// Memoized connection
if (connections[type] != null) {
return connections[type];
}
const clientOptions = _.assign({}, options.redis);
const client = (connections[type] = createClient(type, clientOptions));
const opts = client.options.redisOptions || client.options;
if (
['bclient', 'subscriber'].includes(type) &&
(opts.enableReadyCheck || opts.maxRetriesPerRequest)
) {
throw new Error(errors.Messages.MISSING_REDIS_OPTS);
}
// Since connections are lazily initialized, we can't check queue.client
// without initializing a connection. So expose a boolean we can safely
// query.
queue[type + 'Initialized'] = true;
if (!options.createClient) {
queue.clients.push(client);
}
return initCallback(type, client), client;
};
};
}
function redisOptsFromUrl(urlString) {
let redisOpts = {};
try {
const redisUrl = url.parse(urlString, true, true);
redisOpts.port = parseInt(redisUrl.port || '6379', 10);
redisOpts.host = redisUrl.hostname;
redisOpts.db = redisUrl.pathname ? redisUrl.pathname.split('/')[1] : 0;
if (redisUrl.auth) {
const columnIndex = redisUrl.auth.indexOf(':');
redisOpts.password = redisUrl.auth.slice(columnIndex + 1);
if (columnIndex > 0) {
redisOpts.username = redisUrl.auth.slice(0, columnIndex);
}
}
if (redisUrl.query) {
redisOpts = { ...redisOpts, ...redisUrl.query };
}
} catch (e) {
throw new Error(e.message);
}
return redisOpts;
}
util.inherits(Queue, EventEmitter);
//
// Extend Queue with "aspects"
//
require('./getters')(Queue);
require('./worker')(Queue);
require('./repeatable')(Queue);
// --
Queue.prototype.off = Queue.prototype.removeListener;
const _on = Queue.prototype.on;
Queue.prototype.on = function(eventName) {
this._registerEvent(eventName);
return _on.apply(this, arguments);
};
const _once = Queue.prototype.once;
Queue.prototype.once = function(eventName) {
this._registerEvent(eventName);
return _once.apply(this, arguments);
};
Queue.prototype._initProcess = function() {
if (!this._initializingProcess) {
//
// Only setup listeners if .on/.addEventListener called, or process function defined.
//
this.delayedTimestamp = Number.MAX_VALUE;
this._initializingProcess = this.isReady()
.then(() => {
return this._registerEvent('delayed');
})
.then(() => {
return this.updateDelayTimer();
});
this.errorRetryTimer = {};
}
return this._initializingProcess;
};
Queue.prototype._setupQueueEventListeners = function() {
/*
if(eventName !== 'cleaned' && eventName !== 'error'){
args[0] = Job.fromJSON(this, args[0]);
}
*/
const activeKey = this.keys.active;
const stalledKey = this.keys.stalled;
const progressKey = this.keys.progress;
const delayedKey = this.keys.delayed;
const pausedKey = this.keys.paused;
const resumedKey = this.keys.resumed;
const waitingKey = this.keys.waiting;
const completedKey = this.keys.completed;
const failedKey = this.keys.failed;
const drainedKey = this.keys.drained;
const duplicatedKey = this.keys.duplicated;
const debouncedKey = this.keys.de + 'bounced';
const pmessageHandler = (pattern, channel, message) => {
const keyAndToken = channel.split('@');
const key = keyAndToken[0];
const token = keyAndToken[1];
switch (key) {
case activeKey:
utils.emitSafe(this, 'global:active', message, 'waiting');
break;
case waitingKey:
if (this.token === token) {
utils.emitSafe(this, 'waiting', message, null);
}
token && utils.emitSafe(this, 'global:waiting', message, null);
break;
case stalledKey:
if (this.token === token) {
utils.emitSafe(this, 'stalled', message);
}
utils.emitSafe(this, 'global:stalled', message);
break;
case duplicatedKey:
if (this.token === token) {
utils.emitSafe(this, 'duplicated', message);
}
utils.emitSafe(this, 'global:duplicated', message);
break;
case debouncedKey:
if (this.token === token) {
utils.emitSafe(this, 'debounced', message);
}
utils.emitSafe(this, 'global:debounced', message);
break;
}
};
const messageHandler = (channel, message) => {
const key = channel.split('@')[0];
switch (key) {
case progressKey: {
// New way to send progress message data
try {
const { progress, jobId } = JSON.parse(message);
utils.emitSafe(this, 'global:progress', jobId, progress);
} catch (err) {
// If we fail we should try to parse the data using the deprecated method
const commaPos = message.indexOf(',');
const jobId = message.substring(0, commaPos);
const progress = message.substring(commaPos + 1);
utils.emitSafe(this, 'global:progress', jobId, JSON.parse(progress));
}
break;
}
case delayedKey: {
const newDelayedTimestamp = _.ceil(message);
if (newDelayedTimestamp < this.delayedTimestamp) {
// The new delayed timestamp is before the currently newest known delayed timestamp
// Assume this is the new delayed timestamp and call `updateDelayTimer()` to process any delayed jobs
// This will also update the `delayedTimestamp`
this.delayedTimestamp = newDelayedTimestamp;
this.updateDelayTimer();
}
break;
}
case pausedKey:
case resumedKey:
utils.emitSafe(this, 'global:' + message);
break;
case completedKey: {
const data = JSON.parse(message);
utils.emitSafe(
this,
'global:completed',
data.jobId,
data.val,
'active'
);
break;
}
case failedKey: {
const data = JSON.parse(message);
utils.emitSafe(this, 'global:failed', data.jobId, data.val, 'active');
break;
}
case drainedKey:
utils.emitSafe(this, 'global:drained');
break;
}
};
this.eclient.on('pmessage', pmessageHandler);
this.eclient.on('message', messageHandler);
this.once('close', () => {
this.eclient.removeListener('pmessage', pmessageHandler);
this.eclient.removeListener('message', messageHandler);
});
};
Queue.prototype._registerEvent = function(eventName) {
const internalEvents = ['waiting', 'delayed', 'duplicated', 'debounced'];
if (
eventName.startsWith('global:') ||
internalEvents.indexOf(eventName) !== -1
) {
if (!this.registeredEvents) {
this._setupQueueEventListeners();
this.registeredEvents = this.registeredEvents || {};
}
const _eventName = eventName.replace('global:', '');
if (!this.registeredEvents[_eventName]) {
return utils
.isRedisReady(this.eclient)
.then(() => {
const channel = this.toKey(_eventName);
if (['active', 'waiting', 'stalled', 'duplicated', 'debounced'].indexOf(_eventName) !== -1) {
return (this.registeredEvents[_eventName] = this.eclient.psubscribe(
channel + '*'
));
} else {
return (this.registeredEvents[_eventName] = this.eclient.subscribe(
channel
));
}
})
.then(() => {
utils.emitSafe(this, 'registered:' + eventName);
});
} else {
return this.registeredEvents[_eventName];
}
}
return Promise.resolve();
};
Queue.ErrorMessages = errors.Messages;
Queue.prototype.isReady = async function() {
await this._initializing;
return this;
};
async function redisClientDisconnect(client) {
if (client.status !== 'end') {
let _resolve, _reject;
return new Promise((resolve, reject) => {
_resolve = resolve;
_reject = reject;
client.once('end', _resolve);
pTimeout(
client.quit().catch(err => {
if (err.message !== 'Connection is closed.') {
throw err;
}
}),
500
)
.catch(() => {
// Ignore timeout error
})
.finally(() => {
client.once('error', _reject);
client.disconnect();
if (['connecting', 'reconnecting'].includes(client.status)) {
resolve();
}
});
}).finally(() => {
client.removeListener('end', _resolve);
client.removeListener('error', _reject);
});
}
}
Queue.prototype.disconnect = async function() {
await Promise.all(
this.clients.map(client =>
client.blocked ? client.disconnect() : redisClientDisconnect(client)
)
);
};
Queue.prototype.removeJobs = function(pattern) {
return Job.remove(this, pattern);
};
Queue.prototype.close = function(doNotWaitJobs) {
let isReady = true;
if (this.closing) {
return this.closing;
}
return (this.closing = this.isReady()
.then(this._initializingProcess)
.catch(() => {
isReady = false;
})
.then(() => isReady && this.pause(true, doNotWaitJobs))
.catch(() => void 0) // Ignore possible error from pause
.finally(() => this._clearTimers())
.then(() => {
if (!this.childPool) {
return;
}
const cleanPromise = this.childPool.clean().catch(() => {
// Ignore this error and try to close anyway.
});
if (doNotWaitJobs) {
return;
}
return cleanPromise;
})
.then(
async () => this.disconnect(),
err => console.error(err)
)
.finally(() => {
this.closed = true;
utils.emitSafe(this, 'close');
}));
};
Queue.prototype._clearTimers = function() {
_.each(this.errorRetryTimer, timer => {
clearTimeout(timer);
});
clearTimeout(this.delayTimer);
clearInterval(this.guardianTimer);
clearInterval(this.moveUnlockedJobsToWaitInterval);
this.timers.clearAll();
return this.timers.whenIdle();
};
/**
Processes a job from the queue. The callback is called for every job that
is dequeued.
@method process
*/
Queue.prototype.process = function(name, concurrency, handler) {
switch (arguments.length) {
case 1:
handler = name;
concurrency = 1;
name = Job.DEFAULT_JOB_NAME;
break;
case 2: // (string, function) or (string, string) or (number, function) or (number, string)
handler = concurrency;
if (typeof name === 'string') {
concurrency = 1;
} else {
concurrency = name;
name = Job.DEFAULT_JOB_NAME;
}
break;
}
this.setHandler(name, handler);
return this._initProcess().then(() => {
return this.start(concurrency, name);
});
};
Queue.prototype.start = function(concurrency, name) {
return this.run(concurrency, name).catch(err => {
utils.emitSafe(this, 'error', err, 'error running queue');
throw err;
});
};
Queue.prototype.setHandler = function(name, handler) {
if (!handler) {
throw new Error('Cannot set an undefined handler');
}
if (this.handlers[name]) {
throw new Error('Cannot define the same handler twice ' + name);
}
this.setWorkerName();
if (typeof handler === 'string') {
const supportedFileTypes = ['.js', '.ts', '.flow', '.cjs'];
const processorFile =
handler +
(supportedFileTypes.includes(path.extname(handler)) ? '' : '.js');
if (!fs.existsSync(processorFile)) {
throw new Error('File ' + processorFile + ' does not exist');
}
const isSharedChildPool = this.settings.isSharedChildPool;
this.childPool =
this.childPool || require('./process/child-pool')(isSharedChildPool);
const sandbox = require('./process/sandbox');
this.handlers[name] = sandbox(handler, this.childPool).bind(this);
} else {
handler = handler.bind(this);
if (handler.length > 1) {
this.handlers[name] = promisify(handler);
} else {
this.handlers[name] = function() {
try {
return Promise.resolve(handler.apply(null, arguments));
} catch (err) {
return Promise.reject(err);
}
};
}
}
};
/**
interface JobOptions
{
attempts: number;
repeat: {
tz?: string,
endDate?: Date | string | number
},
preventParsingData: boolean;
}
*/
/**
Adds a job to the queue.
@method add
@param data: {} Custom data to store for this job. Should be JSON serializable.
@param opts: JobOptions Options for this job.
*/
Queue.prototype.add = function(name, data, opts) {
if (typeof name !== 'string') {
opts = data;
data = name;
name = Job.DEFAULT_JOB_NAME;
}
opts = _.cloneDeep({ ...this.defaultJobOptions, ...opts });
opts.jobId = jobIdForGroup(this.limiter, opts, data);
if (opts.repeat) {
return this.isReady().then(() => {
return this.nextRepeatableJob(name, data, opts, true);
});
} else {
return Job.create(this, name, data, opts);
}
};
/**
* Retry all the failed jobs.
*
* @param opts.count - number to limit how many jobs will be moved to wait status per iteration
* @returns
*/
Queue.prototype.retryJobs = async function(opts = {}) {
let cursor = 0;
do {
cursor = await scripts.retryJobs(this, opts.count);
} while (cursor);
};
/**
* Removes a debounce key.
*
* @param id - identifier
*/
Queue.prototype.removeDebounceKey = (id) => {
return this.client.del(`${this.keys.de}:${id}`);
}
/**
Adds an array of jobs to the queue.
@method add
@param jobs: [] The array of jobs to add to the queue. Each job is defined by 3 properties, 'name', 'data' and 'opts'. They follow the same signature as 'Queue.add'.
*/
Queue.prototype.addBulk = function(jobs) {
const decoratedJobs = jobs.map(job => {
const jobId = jobIdForGroup(this.limiter, job.opts, job.data);
return {
...job,
name: typeof job.name !== 'string' ? Job.DEFAULT_JOB_NAME : job.name,
opts: {
...this.defaultJobOptions,
...job.opts,
jobId
}
};
});
return Job.createBulk(this, decoratedJobs);
};
/**
Empties the queue.
Returns a promise that is resolved after the operation has been completed.
Note that if some other process is adding jobs at the same time as emptying,
the queues may not be really empty after this method has executed completely.
Also, if the method does error between emptying the lists and removing all the
jobs, there will be zombie jobs left in redis.
TODO: Use EVAL to make this operation fully atomic.
*/
Queue.prototype.empty = function() {
const queueKeys = this.keys;
let multi = this.multi();
multi.lrange(queueKeys.wait, 0, -1);
multi.lrange(queueKeys.paused, 0, -1);
multi.keys(this.toKey('*:limited'));
multi.del(
queueKeys.wait,
queueKeys.paused,
queueKeys['meta-paused'],
queueKeys.delayed,
queueKeys.priority,
queueKeys.limiter,
`${queueKeys.limiter}:index`
);
return multi.exec().then(res => {
let [waiting, paused, limited] = res;
waiting = waiting[1];
paused = paused[1];
limited = limited[1];
const jobKeys = paused.concat(waiting).map(this.toKey, this);
if (jobKeys.length || limited.length) {
multi = this.multi();
for (let i = 0; i < jobKeys.length; i += 10000) {
multi.del.apply(multi, jobKeys.slice(i, i + 10000));
}
for (let i = 0; i < limited.length; i += 10000) {
multi.del.apply(multi, limited.slice(i, i + 10000));
}
return multi.exec();
}
});
};
/**
Pauses the processing of this queue, locally if true passed, otherwise globally.
For global pause, we use an atomic RENAME operation on the wait queue. Since
we have blocking calls with BRPOPLPUSH on the wait queue, as long as the queue
is renamed to 'paused', no new jobs will be processed (the current ones
will run until finalized).
Adding jobs requires a LUA script to check first if the paused list exist
and in that case it will add it there instead of the wait list.
*/
Queue.prototype.pause = function(isLocal, doNotWaitActive) {
return this.isReady()
.then(() => {
if (isLocal) {
if (!this.paused) {
this.paused = new Promise(resolve => {
this.resumeLocal = function() {
this.paused = null; // Allow pause to be checked externally for paused state.
resolve();
};
});
}
if (!this.bclientInitialized) {
// bclient not yet initialized, so no jobs to wait for
return;
}
if (doNotWaitActive) {
// Force reconnection of blocking connection to abort blocking redis call immediately.
return redisClientDisconnect(this.bclient).then(() =>
this.bclient.connect()
);
}
return this.whenCurrentJobsFinished();
} else {
return scripts.pause(this, true);
}
})
.then(() => {
return utils.emitSafe(this, 'paused');
});
};
Queue.prototype.resume = function(isLocal /* Optional */) {
return this.isReady()
.then(() => {
if (isLocal) {
if (this.resumeLocal) {
this.resumeLocal();
}
} else {
return scripts.pause(this, false);
}
})
.then(() => {
utils.emitSafe(this, 'resumed');
});
};
Queue.prototype.isPaused = async function(isLocal) {
if (isLocal) {
return !!this.paused;
} else {
await this.isReady();
const multi = this.multi();
multi.exists(this.keys['meta-paused']);
// For forward compatibility with BullMQ.
multi.hexists(this.toKey('meta'), 'paused');
const [[, isPaused], [, isPausedNew]] = await multi.exec();
return !!(isPaused || isPausedNew);
}
};
Queue.prototype.run = function(concurrency, handlerName) {
if (!Number.isInteger(concurrency)) {
throw new Error('Cannot set Float as concurrency');
}
const promises = [];
return this.isReady()
.then(() => {
return this.moveUnlockedJobsToWait();
})
.then(() => {
return utils.isRedisReady(this.bclient);
})
.then(() => {
while (concurrency--) {
promises.push(
new Promise(resolve => {
this.processJobs(`${handlerName}:${concurrency}`, resolve);
})
);
}
this.startMoveUnlockedJobsToWait();
return Promise.all(promises);
});
};
// ---------------------------------------------------------------------
// Private methods
// ---------------------------------------------------------------------
/**
This function updates the delay timer, which is a timer that timeouts
at the next known delayed job.
*/
Queue.prototype.updateDelayTimer = function() {
if (this.closing) {
return Promise.resolve();
}
return scripts
.updateDelaySet(this, Date.now())
.then(nextTimestamp => {
this.delayedTimestamp = nextTimestamp
? nextTimestamp / 4096