-
Notifications
You must be signed in to change notification settings - Fork 47
/
index.js
1503 lines (1235 loc) · 37.9 KB
/
index.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';
/**
* @module
* @name kue-scheduler
* @description A job scheduling utility for kue
* @return {kue} a patched kue with job scheduling capabilities
* @public
*/
//dependencies
var kue = require('kue-unique');
var Job = kue.Job;
var Queue = kue;
//
//make use of kue redis factories
//for establishing redis connections
//
var redis = kue.redis;
var _ = require('lodash');
var async = require('async');
var datejs = require('date.js');
var { v1: uuidv1 } = require('uuid');
var humanInterval = require('human-interval');
var warlock = require('node-redis-warlock');
var CronTime = require('cron').CronTime;
//------------------------------------------------------------------------------
// constants
//------------------------------------------------------------------------------
var lockKey = 'locks';
//------------------------------------------------------------------------------
// utility helpers
//------------------------------------------------------------------------------
/**
* @function
* @description ensure only a single job instance
*
* This is a case when working on reccur job(s) and only one instance
* of a job is supposed to exists and only current run history is
* of importance than previous running
*
* @param {Job} job valid job instance
* @param {Function} done a callback to invoke on success or failure
* @return {Job} valid job instance
* @private
*/
function ensureUniqueJob(job, done) {
if (job && job.alreadyExist) {
//check if job is complete or failed
var isCompletedOrFailedJob =
(job.state() === 'complete' ||
job.state() === 'failed');
var now = new Date();
//assuming updated_at is in the past or now
// updated_at is a built-in from kue.
var timeSinceLastUpdate = now.getTime() - job.updated_at; // jshint ignore:line
var arbitraryThreshold = job.data.ttl + (job.data.ttl / 2);
var isStaleJob =
(job.state() === 'active' &&
timeSinceLastUpdate > arbitraryThreshold
);
if (isCompletedOrFailedJob || isStaleJob) {
//resave job for next run
//
//NOTE!: We inactivate job to allow kue to queue the same job for next run.
//This will ensure only a single job instance will be used for the next run.
//This is the case for unique job behaviour.
job.inactive();
job.save(done);
} else {
done(null, job);
}
} else {
done(null, job);
}
}
/**
* @function
* @name scheduleEveryJob
* @param {Object} jobDefinition valid job definition
* @param {String} jobUUID valid job uuid
* @param {Function} done a callback to invoke on success or failure
* @private
*/
function scheduleEveryJob(jobDefinition, jobUUID, done) {
/*jshint validthis:true*/
async.waterfall([
function obtainLock(next) {
//TODO expose lock duration as configurations
this._warlock.lock(this._getJobLockKey(jobUUID), 1000, function (err,
unlock) {
if (!unlock) {
next(new Error('Job already locked, skipping...'));
} else {
next(err, unlock);
}
});
}.bind(this),
function prepareNextRun(unlock, next) {
async.parallel({
//compute job expiry key
jobExpiryKey: function (then) {
then(null, this._getJobExpiryKey(jobUUID));
}.bind(this),
//compute job data key
jobDataKey: function (then) {
then(null, this._getJobDataKey(jobUUID));
}.bind(this),
//compute next run time of the job
nextRunTime: function (then) {
this._computeNextRunTime(jobDefinition, then);
}.bind(this)
}, function (error, results) {
next(error, unlock, results);
});
}.bind(this),
function saveJobData(unlock, results, next) {
//compute job shedule key expiry time
var now = new Date();
var delay = results.nextRunTime.getTime() - now.getTime();
//ensure job data
jobDefinition.data = jobDefinition.data || {};
//extend job definition with expiry key
jobDefinition.data.expiryKey = results.jobExpiryKey;
//extend job definition with data key
jobDefinition.data.dataKey = results.jobDataKey;
//save job data
this._saveJobData(results.jobDataKey, jobDefinition, function (error) {
next(error, unlock, delay, results.jobExpiryKey, jobDefinition);
});
}.bind(this),
//schedule job for next run
function setJobKeyExpiry(unlock, delay, jobExpiryKey, jobDefinition,
next) {
//save key if not exists and wait for it to expiry
this._scheduler.set(jobExpiryKey, jobExpiryKey, 'PX', delay, 'NX',
function (error) {
next(error, unlock, jobDefinition);
});
}.bind(this),
function releaseLock(unlock, jobDefinition, next) {
unlock(function (error) {
next(error, jobDefinition);
});
}
], function (error, results) {
done(error, results);
});
/*jshint validthis:false*/
}
//------------------------------------------------------------------------------
//patch and implementations
//------------------------------------------------------------------------------
/**
* @function
* @description generate an expiration key that is used to track job scheduling
* @return {String} a job expiry key
* @private
*/
Queue.prototype._getJobExpiryKey = function (uuid) {
//this refer to kue Queue instance context
var key = this.options.prefix + ':scheduler:' + uuid;
return key;
};
/**
* @function
* @description test a give key if is valid job expiry key
* @param {String} jobExpiryKey a key to test
* @return {Boolean} true if is valid job expiry key else false
* @private
*/
Queue.prototype._isJobExpiryKey = function (jobExpiryKey) {
//this refer to kue Queue instance context
var isJobExpiryKey = this._jobExpiryKeyValidator.test(jobExpiryKey);
return isJobExpiryKey;
};
/**
* @function
* @description check if job exists and its ttl has not timeout
* @param {String} jobExpiryKey valid job expiry key
* @param {Function} done a function to invoke on success or error
* @return {Boolean} whether job already scheduled or not
* @private
*/
Queue.prototype._isJobAlreadyScheduled = function (jobExpiryKey, done) {
//this refer to kue Queue instance context
async.parallel({
exists: function isKeyExists(next) {
this._scheduler.exists(jobExpiryKey, next);
}.bind(this),
ttl: function isKeyExpired(next) {
this._scheduler.pttl(jobExpiryKey, next);
}.bind(this)
}, function (error, results) {
if (error) {
done(error);
} else {
var exists =
(results.exists && results.exists === 1) ? true : false;
var active =
(results.ttl && results.ttl > 0) ? true : false;
var alreadyScheduled = exists && active;
done(null, alreadyScheduled);
}
});
};
/**
* @function
* @description generate job uuid from job definition
* @param {Object} jobDefinition valid job definition
* @return {String} job uuid
* @private
*/
Queue.prototype._generateJobUUID = function (jobDefinition) {
//this refer to kue Queue instance context
var unique = jobDefinition.data ? jobDefinition.data.unique : undefined;
//deduce job uuid from unique key
if (unique) {
return _.snakeCase(unique);
}
//otherwise generate uuid
else {
return uuidv1();
}
};
/**
* @function
* @description generate job uuid from job expiry key or job data key
* @return {String} a scheduled job uuid
* @private
*/
Queue.prototype._getJobUUID = function (key) {
//this refer to kue Queue instance context
var uuid;
var splits = key.split(':');
splits = _.filter(splits, function (o) { return o !== ''; });
if (splits.length > 0) {
uuid = splits[splits.length - 1];
}
return uuid;
};
/**
* @function
* @description generate a storage key for the scheduled job data
* @return {String} a key to retrieve a scheduled job data
* @private
*/
Queue.prototype._getJobDataKey = function (uuid) {
//this refer to kue Queue instance context
var key = this.options.prefix + ':scheduler:data:' + uuid;
return key;
};
/**
* @function
* @description generate a lock for the scheduling of a job
* @return {String} a key to lock on based on the UUID
* @private
*/
Queue.prototype._getJobLockKey = function (uuid) {
//this refer to kue Queue instance context
var key = this.options.prefix + ':scheduler:' + lockKey + ':' + uuid;
return key;
};
/**
* @function
* @description save scheduled job data into redis backend
* @param {String} jobDataKey valid job data key
* @param {Object} jobData valid job data
* @param {Function} done a callback to invoke on success or failure
* @private
*/
Queue.prototype._saveJobData = function (jobDataKey, jobData, done) {
//this refer to kue Queue instance context
//TODO make use of redis hash i.e redis.hmset(<key>, <data>);
this
._scheduler
.set(jobDataKey, JSON.stringify(jobData), function (error /*, response*/ ) {
done(error, jobData);
});
};
/**
* @function
* @description retrieved saved scheduled job data from redis backend
* @param {String} jobDataKey valid job data key
* @param {Function} done a callback to invoke on success or failure
* @return {Object} job data if found else error
* @private
*/
Queue.prototype._readJobData = function (jobDataKey, done) {
//this refer to kue Queue instance context
//TODO make use of redis hash i.e redis.hgetall(<key>);
this
._scheduler
.get(jobDataKey, function (error, data) {
done(error, JSON.parse(data));
});
};
/**
* @function
* @description Enable redis expiry keys notifications
* @public
*/
Queue.prototype.enableExpiryNotifications = function () {
//this refer to Queue instance context
//enable expired events (events generated every time a key expires)
this._cli.config('SET', 'notify-keyspace-events', 'Ex');
};
/**
* @function
* @description parse date.js valid string and return a date object
* @param {String} str a valid date.js date string
* @param {Function} done a callback to invoke on error or success
* @private
*/
Queue.prototype._parse = function (str, done) {
//this refer to kue Queue instance context
try {
var date = datejs(str);
return done(null, date);
} catch (error) {
return done(error);
}
};
/**
* @function
* @description instantiate a kue job from a job definition hash
* @param {Object} jobDefinition valid kue job attributes
* @param {Function} done a callback to invoke on error or success
* @private
*/
Queue.prototype._buildJob = function (jobDefinition, done) {
//this refer to kue Queue instance context
async.parallel({
isDefined: function (next) {
//is job definition provided
var isObject = _.isPlainObject(jobDefinition);
if (!isObject) {
next(new Error('Invalid job definition'));
} else {
next(null, true);
}
},
isValid: function (next) {
//check job for required attributes
//
//a valid job must have a type and
//associated data
var isValidJob = _.has(jobDefinition, 'type') &&
(
_.has(jobDefinition, 'data') &&
_.isPlainObject(jobDefinition.data)
);
if (!isValidJob) {
next(new Error('Missing job type or data'));
} else {
next(null, true);
}
}
},
function finish(error, validations) {
//is not well formatted job
//back-off
if (error) {
done(error);
}
//otherwise create a job
//from job definition
else {
//extend default job options with
//custom job definition
var jobDefaults = {
data: {
schedule: 'NOW'
}
};
jobDefinition = _.merge({}, jobDefaults, jobDefinition);
//instantiate kue job
var job =
this.createJob(jobDefinition.type, jobDefinition.data);
//apply all job attributes into kue job instance
// except for `progress` and `error`
_.without(_.keys(jobDefinition), 'progress', 'error')
.forEach(function (attribute) {
//if given job definition attribute
//is one of job instance method
//apply it
var fn = job[attribute];
var isFunction = !_.isUndefined(fn) && _.isFunction(fn);
if (isFunction) {
fn.call(job, jobDefinition[attribute]);
}
});
//re attach max attempts
//if we failed in above
//re attach max attempts from attempts hash
if (jobDefinition.attempts) {
job.attempts(jobDefinition.attempts.max);
}
//re attach max attempts from _max_attempts
/*jshint camelcase:false*/
if (jobDefinition._max_attempts) {
job.attempts(jobDefinition._max_attempts);
}
/*jshint camelcase:true*/
//we are done
done(null, job, validations);
}
}.bind(this));
};
/**
* @function
* @description compute next run time of the given job data
* @param {Object} jobData valid job data
* @param {Function} done a callback to invoke on success or failure
* @private
*/
Queue.prototype._computeNextRunTime = function (jobData, done) {
//this refer to kue Queue instance context
if (!jobData) {
return done(new Error('Invalid job data'));
}
//grab job reccur interval
var interval = jobData.reccurInterval;
var timezone = jobData.data ? jobData.data.timezone : undefined;
async.parallel({
//compute next run from cron interval
cron: function (after) {
try {
//compute next date from the cron interval
var cronTime = new CronTime(interval, timezone);
var nextRun = cronTime.sendAt();
//return computed time
after(null, nextRun.toDate());
} catch (ex) {
//to allow parallel run with other interval parser
after(null, null);
}
},
//compute next run from human interval
human: function (after) {
try {
//last run of the job is now if not exist
var lastRun =
jobData.lastRun ? new Date(jobData.lastRun) : new Date();
var nextRun =
new Date(lastRun.valueOf() + humanInterval(interval));
//return computed time
if (isNaN(nextRun.getTime())) {
nextRun = null;
}
after(null, nextRun);
} catch (ex) {
//to allow parallel run with other interval parser
after(null, null);
}
}
}, function finish(error, results) {
//was parsed as cron interval?
if (!_.isNull(results.cron)) {
return done(null, results.cron);
}
//was parsed as human interval?
else if (!_.isNull(results.human)) {
return done(null, results.human);
}
//all parser failed
else {
return done(new Error('Invalid reccur interval'));
}
});
};
/**
* @function
* @description respond to job key expiry events
* @param {String} jobExpiryKey valid job expiry key
* @private
*/
Queue.prototype._onJobKeyExpiry = function (jobExpiryKey) {
//this refer to kue Queue instance context
//TODO refactor
//generate lock key for specific job
var jobLockKey = this._getJobLockKey(this._getJobUUID(jobExpiryKey));
//obtain lock to ensure only one worker process expiry event
//TODO add specs to test for lock lifetime
this._warlock.lock(jobLockKey, 1000, function (err, unlock) {
//handle lock error
if (err) {
//notity error to queue instance
this.emit('lock error', err);
}
//continue to process event
else if (unlock) {
async.waterfall(
[
//get job data
function getJobData(next) {
//get job uuid
var jobUUID = this._getJobUUID(jobExpiryKey);
//get saved job data
this._readJobData(this._getJobDataKey(jobUUID), next);
}.bind(this),
//compute next run time
function computeNextRun(jobData, next) {
this
._computeNextRunTime(jobData, function (error,
nextRunTime) {
if (error) {
next(error);
} else {
next(null, jobData, nextRunTime);
}
});
}.bind(this),
//resave the key to rerun this job again
function resaveJobKey(jobData, nextRunTime, next) {
//compute delay
var now = new Date();
var delay = nextRunTime.getTime() - now.getTime();
this
._scheduler
.set(jobExpiryKey, '', 'PX', delay, function (error) {
if (error) {
next(error);
} else {
next(null, jobData);
}
});
}.bind(this),
function buildJob(jobDefinition, next) {
this._buildJob(jobDefinition, next);
}.bind(this),
function runJob(job, validations, next) {
job.save(function (error, existJob) {
next(error, existJob || job);
});
},
function ensureSingleUniqueJob(job, next) {
ensureUniqueJob(job, next);
}
],
function (error, job) {
if (unlock) {
unlock(function (err) {
if (err) {
// couldn't talk to redis to unlock the lock,
// which will release at the 1s ttl.
//
//notity error to queue instance
this.emit('unlock error', error);
}
});
}
if (error) {
this.emit('schedule error', error);
} else if (job.alreadyExist) {
this.emit('already scheduled', job);
} else {
this.emit('schedule success', job);
}
}.bind(this));
}
}.bind(this)); // end warlock
};
/**
* @function
* @description subscribe to key expiry events
* @private
*/
Queue.prototype._subscribe = function () {
//this refer to kue Queue instance context
//listen for job key expiry
this
._listener
.on('message', function (channel, jobExpiryKey) {
//test if the event key is job expiry key
//and emit `scheduler unknown job expiry key` if not
if (!this._isJobExpiryKey(jobExpiryKey)) {
this.emit('scheduler unknown job expiry key', jobExpiryKey);
return;
}
this._onJobKeyExpiry(jobExpiryKey);
}.bind(this));
//subscribe to key expiration events
this._listener.subscribe(this._getExpiredSubscribeKey());
};
/**
* @function
* @description get a key to subscribe on for expired events
* @return {String} key for expired events
* @private
*/
Queue.prototype._getExpiredSubscribeKey = function () {
// default redis db
var redisDb = 0;
if (Queue.prototype.options.redis.db) {
//works for node-redis
redisDb = Queue.prototype.options.redis.db;
} else if (this._listener.options.db) {
//works for ioredis
redisDb = this._listener.options.db;
}
// key to subscribe on
return '__keyevent@' + redisDb + '__:expired';
};
/**
* @function
* @description schedule a job to run every after a specified interval
*
* If an error occur, it will be emitted using `schedule error` key
* with error passed as first parameter on event.
*
* If job schedule successfully, it will be emitted using
* `schedule success` key with job instance passed as a first parameter
* on event.
*
* @param {String} interval scheduled interval in either human interval or
* cron format
* @param {Job} job valid kue job instance which has not been saved
* @param {Function} [done] a callback to invoke on success or failure
* @example
* 1. create non-unique job
* var job = Queue
* .createJob('every', data)
* .attempts(3)
* .priority('normal');
*
* Queue.every('2 seconds', job, done);
*
* 2. create unique job
* var job = Queue
* .create('every', data)
* .attempts(3)
* .priority('normal')
* .unique(<unique_key>);
*
* Queue.every('2 seconds', job, done);
* @public
*/
Queue.prototype.every = function (interval, job, done) {
//this refer to kue Queue instance context
async.waterfall([
function ensureInterval(next) {
if (!interval && _.isEmpty(interval) && !_.isString(interval)) {
next(new Error('Missing Schedule Interval'));
} else {
next(null, interval, job);
}
},
function ensureJobInstance(interval, job, next) {
if (!job && !(job instanceof Job)) {
next(new Error('Invalid Job Instance'));
} else {
next(null, interval, job);
}
},
function prepareJobDefinition(interval, job, next) {
//extend job definition with
//scheduling data
var jobDefinition = _.merge({}, job.toJSON(), {
reccurInterval: interval,
data: {
schedule: 'RECCUR'
},
backoff: job._backoff
});
//generate job uuid
var jobUUID = this._generateJobUUID(jobDefinition);
//continue
next(null, jobDefinition, jobUUID);
}.bind(this),
function checkIfJobAlreadyScheduled(jobDefinition, jobUUID, next) {
this._isJobAlreadyScheduled(
this._getJobExpiryKey(jobUUID),
function (error, isAlreadyScheduled) {
next(error, jobDefinition, jobUUID, isAlreadyScheduled);
});
}.bind(this),
function scheduleJob(jobDefinition, jobUUID, isAlreadyScheduled, next) {
if (!isAlreadyScheduled) {
scheduleEveryJob.call(this, jobDefinition, jobUUID, function (
error) {
next(error, job);
});
} else {
next(null, job);
}
}.bind(this)
], function (error, job) {
//fire schedule error event
if (error) {
this.emit('schedule error', error);
}
//fire already schedule event
else if (job.alreadyExist) {
this.emit('already scheduled', job);
}
//fire schedule success event
else {
this.emit('schedule success', job);
}
//invoke callback if provided
if (done && _.isFunction(done)) {
done(error, job);
}
}.bind(this));
};
/**
* @function
* @description schedules a job to run once at a given time.
* `when` can be a `Date` or a valid `date.js string`
* such as `tomorrow at 5pm`.
*
* If an error occur, it will be emitted using `schedule error` key
* with error passed as first parameter on event.
*
* If job schedule successfully, it will be emitted using
* `schedule success` key with job instance passed as a first parameter
* on event.
*
* @param {Date|String} when when should this job run
* @param {Job} jobDefinition valid kue job instance which has not been saved
* @param {Fuction} [done] a callback to invoke on success or error
* @example
* 1. create non-unique job
* var job = Queue
* .createJob('schedule', data)
* .attempts(3)
* .priority('normal');
*
* Queue.schedule('2 seconds from now', job, done);
*
* 2. create unique job
* var job = Queue
* .create('schedule', data)
* .attempts(3)
* .priority('normal')
* .unique(<unique_key>);
*
* Queue.schedule('2 seconds from now', job, done);
* @public
*/
Queue.prototype.schedule = function (when, job, done) {
//this refer to kue Queue instance context
async.waterfall([
function ensureInterval(next) {
if (!when && !(_.isString(when) || _.isDate(when))) {
next(new Error('Missing Schedule Interval'));
} else {
next(null, when, job);
}
},
function ensureJobInstance(when, job, next) {
if (!job && !(job instanceof Job)) {
next(new Error('Invalid Job Instance'));
} else {
next(null, when, job);
}
},
function prepareJobDefinition(when, job, next) {
var jobDefinition = _.extend(job.toJSON(), {
backoff: job._backoff,
removeOnComplete: job._removeOnComplete
});
next(null, when, job, jobDefinition);
},
function computeDelay(when, job, jobDefinition, next) {
//when is date instance
if (when instanceof Date) {
next(null, jobDefinition, when);
}
//otherwise parse as date.js string
else {
this._parse(when, function (error, scheduledDate) {
next(error, jobDefinition, scheduledDate);
});
}
}.bind(this),
//set job delay
function setDelay(jobDefinition, scheduledDate, next) {
next(
null,
_.merge({}, jobDefinition, {
delay: scheduledDate,
data: {
schedule: 'ONCE'
}
})
);
},
function buildJob(delayedJobDefinition, next) {
this._buildJob(delayedJobDefinition, next);
}.bind(this),
function saveJob(job, validations, next) {
job.save(function (error, existJob) {
next(error, existJob || job);
});
},
function ensureSingleUniqueJob(job, next) {
ensureUniqueJob(job, next);
},
function saveUniqueJob(job, next) {
// if a unique name is specified, save it with the job details
if (job.data && job.data.unique) {
var jobDataKey = this._getJobDataKey(job.data.unique);
this._saveJobData(jobDataKey, job, function (error) {
next(error, job);
});
} else {
next(null, job);
}
}.bind(this)
], function (error, job) {
//fire schedule error event
if (error) {
this.emit('schedule error', error);
}
//fire already schedule event
else if (job.alreadyExist) {
this.emit('already scheduled', job);
}
//fire schedule success event
else {
this.emit('schedule success', job);
}
//invoke callback if provided
if (done && _.isFunction(done)) {
done(error, job);
}
}.bind(this));
};
/**
* @function