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 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 | 1× 1× 1× 1× 1× 1× 1× 1× 1× 1× 1× 1× 1× 1× 1× 1× 1× 1× 112× 112× 112× 5× 107× 112× 112× 112× 112× 3× 112× 112× 112× 112× 12× 112× 112× 112× 112× 289× 289× 112× 108× 1× 1× 112× 112× 112× 108× 112× 112× 112× 112× 112× 112× 112× 112× 112× 112× 112× 112× 112× 2128× 112× 1× 112× 280× 112× 112× 336× 1667× 1378× 289× 289× 280× 289× 1× 5× 5× 5× 5× 5× 5× 5× 1× 5× 1× 55× 1× 1× 1× 1× 1× 1× 1× 242× 242× 1× 1× 16× 16× 1× 55× 55× 55× 55× 55× 55× 55× 55× 55× 55× 55× 1× 61× 61× 61× 61× 61× 61× 61× 61× 61× 61× 61× 61× 8× 8× 8× 8× 1× 1× 6× 5× 6× 6× 1× 1× 1× 61× 6× 6× 4× 4× 4× 1× 1× 1× 1× 1× 1× 329× 329× 94× 61× 61× 94× 94× 86× 86× 86× 86× 11× 75× 86× 8× 235× 1× 1× 659× 659× 653× 1× 380× 380× 380× 380× 380× 380× 380× 380× 20× 380× 380× 1× 105× 271× 105× 105× 1× 159× 159× 50× 109× 105× 106× 106× 105× 106× 106× 1× 106× 106× 106× 106× 106× 106× 106× 1× 55× 55× 55× 55× 55× 55× 55× 55× 55× 1× 55× 55× 1× 55× 55× 55× 55× 55× 55× 31× 24× 1× 252× 252× 252× 252× 252× 252× 252× 252× 1× 1× 1× 1× 1× 1× 1× 1× 1× 1× 1× 1× 1× 1× 1× 1× 1× 1× 117× 117× 116× 111× 106× 106× 1× 1× 111× 5× 116× 1× 5× 5× 5× 1× 1× 4× 4× 1× 55× 55× 55× 55× 55× 55× 55× 55× 55× 55× 1× 1× 59× 59× 2× 57× 57× 57× 2× 2× 2× 57× 1× 57× 57× 55× 1× 234× 234× 234× 234× 186× 181× 181× 2× 2× 2× 2× 2× 48× 1× 179× 179× 179× 179× 53× 126× 126× 126× 1× 126× 126× 1× 111× 111× 111× 1× 15× 15× 13× 13× 126× 126× 126× 126× 126× 1× 126× 126× 126× 1× 30× 1× 114× 114× 3× 111× 23× 1× 1× 20× 88× 1× 89× 89× 89× 1× 157× 127× 127× 127× 127× 30× 30× 30× 1× 1× 3182× 1× 13× 13× 13× 13× 13× 13× 13× 13× 1× 109× 109× 109× 109× 109× 109× 1× 112× 108× 108× 108× 216× 108× 1× | /*eslint-env node */ 'use strict'; var redis = require('ioredis'); var EventEmitter = require('events'); var _ = require('lodash'); var util = require('util'); var url = require('url'); var Job = require('./job'); var scripts = require('./scripts'); var errors = require('./errors'); var utils = require('./utils'); var TimerManager = require('./timer-manager'); var Promise = require('bluebird'); var semver = require('semver'); var debuglog = require('debuglog')('bull'); var uuid = require('uuid'); var commands = require('./commands/'); /** 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. */ var MINIMUM_REDIS_VERSION = '2.8.18'; var MAX_TIMEOUT_MS = Math.pow(2, 31) - 1; // 32 bit signed /* 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 } } interface RateLimiter { max: number, // Number of jobs duration: number, // per duration milliseconds } */ // Queue(name: string, url?, opts?) var Queue = function Queue(name, url, opts) { var _this = this; Iif (!(this instanceof Queue)) { return new Queue(name, url, opts); } if (_.isString(url)) { opts = _.extend( {}, { redis: redisOptsFromUrl(url) }, opts ); } else { opts = url; } opts = _.cloneDeep(opts || {}); Iif (opts && !_.isObject(opts)) { throw Error('Options must be a valid object'); } Iif (opts.limiter) { this.limiter = opts.limiter; } if (opts.defaultJobOptions) { this.defaultJobOptions = opts.defaultJobOptions; } this.name = name; this.token = uuid(); 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 = []; var lazyClient = redisClientGetter(this, opts, function(type, client) { // bubble up Redis error events client.on('error', _this.emit.bind(_this, 'error')); if (type === 'client') { _this._initializing = commands(client).then( function() { debuglog(name + ' queue ready'); }, function(err) { _this.emit('error', new Error('Error initializing Lua scripts')); throw 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') } }); Eif (opts.skipVersionCheck !== true) { getRedisVersion(this.client) .then(function(version) { Iif (semver.lt(version, MINIMUM_REDIS_VERSION)) { _this.emit( 'error', new Error( 'Redis version needs to be greater than ' + MINIMUM_REDIS_VERSION + '. Current: ' + version ) ); } }) .catch(function(/*err*/) { // Ignore this error. }); } this.handlers = {}; this.delayTimer; this.processing = []; this.retrieving = 0; this.settings = _.defaults(opts.settings, { lockDuration: 30000, stalledInterval: 30000, maxStalledCount: 1, guardInterval: 5000, retryProcessDelay: 5000, drainDelay: 5, backoffStrategies: {} }); this.settings.lockRenewTime = this.settings.lockRenewTime || this.settings.lockDuration / 2; this.on('error', function() { // 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); var keys = {}; _.each( [ '', 'active', 'wait', 'waiting', 'paused', 'resumed', 'meta-paused', 'active', 'id', 'delayed', 'priority', 'stalled-check', 'completed', 'failed', 'stalled', 'repeat', 'limiter', 'drained', 'progress' ], function(key) { keys[key] = _this.toKey(key); } ); this.keys = keys; }; function redisClientGetter(queue, options, initCallback) { var createClient = _.isFunction(options.createClient) ? options.createClient : function(type, config) { return new redis(config); }; var connections = {}; return function(type) { return function() { // getter function if (connections[type] != null) { return connections[type]; } var client = (connections[type] = createClient(type, options.redis)); if (!options.createClient) { queue.clients.push(client); } return initCallback(type, client), client; }; }; } function redisOptsFromUrl(urlString) { var redisOpts = {}; try { var redisUrl = url.parse(urlString); redisOpts.port = redisUrl.port || 6379; redisOpts.host = redisUrl.hostname; redisOpts.db = redisUrl.pathname ? redisUrl.pathname.split('/')[1] : 0; if (redisUrl.auth) { redisOpts.password = redisUrl.auth.split(':')[1]; } } catch (e) { throw new Error(e.message); } return redisOpts; } function setGuardianTimer(queue) { return setInterval(function() { var now = Date.now(); if ( queue.delayedTimestamp < now || queue.delayedTimestamp - now > queue.settings.guardInterval ) { scripts .updateDelaySet(queue, now) .then(function(timestamp) { if (timestamp) { queue.updateDelayTimer(timestamp); } return null; }) .catch(function(err) { queue.emit('error', err); }) .return(null); } }, queue.settings.guardInterval); } util.inherits(Queue, EventEmitter); // // Extend Queue with "aspects" // require('./getters')(Queue); require('./worker')(Queue); require('./repeatable')(Queue); // -- Queue.prototype.off = Queue.prototype.removeListener; var _on = Queue.prototype.on; Queue.prototype.on = function(eventName) { this._registerEvent(eventName); return _on.apply(this, arguments); }; var _once = Queue.prototype.once; Queue.prototype.once = function(eventName) { this._registerEvent(eventName); return _once.apply(this, arguments); }; Queue.prototype._initProcess = function() { var _this = this; Eif (!this._initializingProcess) { // // Only setup listeners if .on/.addEventListener called, or process function defined. // this.delayedTimestamp = Number.MAX_VALUE; this._initializingProcess = this.isReady() .then(function() { return _this._registerEvent('delayed'); }) .then(function() { // // Init delay timestamp. // return scripts .updateDelaySet(_this, Date.now()) .then(function(timestamp) { Iif (timestamp) { _this.updateDelayTimer(timestamp); } return null; }) .return(null); }) .then(function() { // // Create a guardian timer to revive delayTimer if necessary // This is necessary when redis connection is unstable, which can cause the pub/sub to fail // _this.guardianTimer = setGuardianTimer(_this); }); this.errorRetryTimer = {}; } return this._initializingProcess; }; Queue.prototype._setupQueueEventListeners = function() { /* if(eventName !== 'cleaned' && eventName !== 'error'){ args[0] = Job.fromJSON(_this, args[0]); } */ var _this = this; var activeKey = _this.keys.active; var stalledKey = _this.keys.stalled; var progressKey = _this.keys.progress; var delayedKey = _this.keys.delayed; var pausedKey = _this.keys.paused; var resumedKey = _this.keys.resumed; var waitingKey = _this.keys.waiting; var completedKey = _this.keys.completed; var failedKey = _this.keys.failed; var drainedKey = _this.keys.drained; this.eclient.on('pmessage', function(pattern, channel, message) { var keyAndToken = channel.split('@'); var key = keyAndToken[0]; var token = keyAndToken[1]; switch (key) { case activeKey: _this.emit('global:active', message, 'waiting'); break; case waitingKey: if (_this.token === token) { _this.emit('waiting', message, null); } token && _this.emit('global:waiting', message, null); break; case stalledKey: Iif (_this.token === token) { _this.emit('stalled', message); } _this.emit('global:stalled', message); break; } }); this.eclient.on('message', function(channel, message) { var key = channel.split('@')[0]; switch (key) { case progressKey: var jobAndProgress = message.split(','); _this.emit('global:progress', jobAndProgress[0], jobAndProgress[1]); break; case delayedKey: _this.updateDelayTimer(message); break; case pausedKey: case resumedKey: _this.emit('global:' + message); break; case completedKey: var data = JSON.parse(message); _this.emit('global:completed', data.jobId, data.val, 'active'); break; case failedKey: var data = JSON.parse(message); _this.emit('global:failed', data.jobId, data.val, 'active'); break; case drainedKey: _this.emit('global:drained'); break; } }); }; Queue.prototype._registerEvent = function(eventName) { var internalEvents = ['waiting', 'delayed']; if ( eventName.startsWith('global:') || internalEvents.indexOf(eventName) !== -1 ) { if (!this.registeredEvents) { this._setupQueueEventListeners(); this.registeredEvents = this.registeredEvents || {}; } var _eventName = eventName.replace('global:', ''); if (!this.registeredEvents[_eventName]) { var _this = this; return utils .isRedisReady(this.eclient) .then(function() { var channel = _this.toKey(_eventName); if (['active', 'waiting', 'stalled'].indexOf(_eventName) !== -1) { return (_this.registeredEvents[ _eventName ] = _this.eclient.psubscribe(channel + '*')); } else { return (_this.registeredEvents[ _eventName ] = _this.eclient.subscribe(channel)); } }) .then(function() { _this.emit('registered:' + eventName); }); } else { return this.registeredEvents[_eventName]; } } return Promise.resolve(); }; Queue.ErrorMessages = errors.Messages; Queue.prototype.isReady = function() { var _this = this; return this._initializing.then(function() { return _this; }); }; function redisClientDisconnect(client) { Iif (client.status === 'end') { return Promise.resolve(); } var _resolve, _reject; return new Promise(function(resolve, reject) { _resolve = resolve; _reject = reject; client.once('end', resolve); client.once('error', reject); client .quit() .catch(function(err) { if (err.message !== 'Connection is closed.') { throw err; } }) .timeout(500) .catch(function() { client.disconnect(); }); }).finally(function() { client.removeListener('end', _resolve); client.removeListener('error', _reject); }); } Queue.prototype.disconnect = function() { // // TODO: Only quit clients that we "own". // var clients = this.clients.filter(function(client) { return client.status !== 'end'; }); return Promise.all(clients.map(redisClientDisconnect)) .catch(function(err) { return console.error(err); }) .then(function() { return null; }); }; Queue.prototype.close = function(doNotWaitJobs) { var _this = this; if (this.closing) { return this.closing; } return (this.closing = this.isReady() .then( function() { return _this._initializingProcess; }, function(/*err*/) { // Ignore this error and try to close anyway. } ) .finally(function() { return _this._clearTimers(); }) .then(function() { return _this.pause(true, doNotWaitJobs); }) .then( function() { return _this.disconnect(); }, function(/*err*/) { // Ignore this error and try to close anyway. } ) .finally(function() { _this.childPool && _this.childPool.clean(); _this.closed = true; })); }; Queue.prototype._clearTimers = function() { var _this = this; _.each(_this.errorRetryTimer, function(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. Deprecate in favor of: /* queue.work('export', opts, function(job, input){ return output; }, 'adrapid-export-results'); @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); var _this = this; return this._initProcess().then(function() { return _this.start(concurrency); }); }; Queue.prototype.start = function(concurrency) { var _this = this; return this.run(concurrency).catch(function(err) { _this.emit('error', err, 'error running queue'); throw err; }); }; Queue.prototype.setHandler = function(name, handler) { Iif (!handler) { throw new Error('Cannot set an undefined handler'); } Iif (this.handlers[name]) { throw new Error('Cannot define the same handler twice ' + name); } this.setWorkerName(); Iif (typeof handler === 'string') { this.childPool = this.childPool || require('./process/child-pool')(); var 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] = Promise.promisify(handler); } else { this.handlers[name] = Promise.method(handler); } } }; /** interface JobOptions { attempts: number; repeat: { tz?: string, endDate?: Date | string | number } } */ /** 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) { Eif (typeof name !== 'string') { opts = data; data = name; name = Job.DEFAULT_JOB_NAME; } opts = _.cloneDeep(opts || {}); _.defaults(opts, this.defaultJobOptions); Iif (opts.repeat) { var _this = this; return this.isReady().then(function() { return _this.nextRepeatableJob(name, data, opts, true); }); } else { return Job.create(this, name, data, opts); } }; /** 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() { var _this = this; // Get all jobids and empty all lists atomically. var multi = this.multi(); multi.lrange(this.toKey('wait'), 0, -1); multi.lrange(this.toKey('paused'), 0, -1); multi.del(this.toKey('wait')); multi.del(this.toKey('paused')); multi.del(this.toKey('meta-paused')); multi.del(this.toKey('delayed')); return multi.exec().spread(function(waiting, paused) { waiting = waiting[1]; paused = paused[1]; var jobKeys = paused.concat(waiting).map(_this.toKey, _this); Eif (jobKeys.length) { multi = _this.multi(); multi.del.apply(multi, jobKeys); 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) { var _this = this; return _this .isReady() .then(function() { if (isLocal) { if (!_this.paused) { _this.paused = new Promise(function(resolve) { _this.resumeLocal = function() { resolve(); _this.paused = null; // Allow pause to be checked externally for paused state. }; }); } return !doNotWaitActive && _this.whenCurrentJobsFinished(); } else { return scripts.pause(_this, true); } }) .then(function() { return _this.emit('paused'); }); }; Queue.prototype.resume = function(isLocal /* Optional */) { var _this = this; return this.isReady() .then(function() { if (isLocal) { Eif (_this.resumeLocal) { _this.resumeLocal(); } } else { return scripts.pause(_this, false); } }) .then(function() { _this.emit('resumed'); }); }; Queue.prototype.run = function(concurrency) { var promises = []; var _this = this; return this.isReady() .then(function() { return _this.moveUnlockedJobsToWait(); }) .then(function() { return utils.isRedisReady(_this.bclient); }) .then(function() { while (concurrency--) { promises.push( new Promise(function(resolve) { _this.processJobs(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(newDelayedTimestamp) { var _this = this; var now = Date.now(); newDelayedTimestamp = Math.round(newDelayedTimestamp); if ( newDelayedTimestamp < _this.delayedTimestamp && newDelayedTimestamp < MAX_TIMEOUT_MS + now ) { clearTimeout(this.delayTimer); this.delayedTimestamp = newDelayedTimestamp; var nextDelayedJob = newDelayedTimestamp - now; var delay = nextDelayedJob <= 0 ? 0 : nextDelayedJob; var delayUpdate = function() { scripts .updateDelaySet(_this, _this.delayedTimestamp) .then(function(nextTimestamp) { if (nextTimestamp) { nextTimestamp = nextTimestamp < now ? now : nextTimestamp; } else { nextTimestamp = Number.MAX_VALUE; } return _this.updateDelayTimer(nextTimestamp); }) .catch(function(err) { _this.emit('error', err, 'Error updating the delay timer'); }) .return(null); _this.delayedTimestamp = Number.MAX_VALUE; }; if (delay) { this.delayTimer = setTimeout(delayUpdate, delay); } else { delayUpdate(); } } return null; }; /** * Process jobs that have been added to the active list but are not being * processed properly. This can happen due to a process crash in the middle * of processing a job, leaving it in 'active' but without a job lock. */ Queue.prototype.moveUnlockedJobsToWait = function() { var _this = this; if (this.closing) { return Promise.resolve(); } return scripts .moveUnlockedJobsToWait(this) .spread(function(failed, stalled) { var handleFailedJobs = failed.map(function(jobId) { return _this.getJobFromId(jobId).then(function(job) { _this.emit( 'failed', job, new Error('job stalled more than allowable limit'), 'active' ); return null; }); }); var handleStalledJobs = stalled.map(function(jobId) { return _this.getJobFromId(jobId).then(function(job) { _this.emit('stalled', job); return null; }); }); return Promise.all(handleFailedJobs.concat(handleStalledJobs)); }) .catch(function(err) { _this.emit('error', err, 'Failed to handle unlocked job in active'); }); }; Queue.prototype.startMoveUnlockedJobsToWait = function() { clearInterval(this.moveUnlockedJobsToWaitInterval); if (this.settings.stalledInterval > 0 && !this.closing) { this.moveUnlockedJobsToWaitInterval = setInterval( this.moveUnlockedJobsToWait, this.settings.stalledInterval ); } }; /* Process jobs. Note last argument 'job' is optional. */ Queue.prototype.processJobs = function(index, resolve, job) { var _this = this; var processJobs = this.processJobs.bind(this, index, resolve); process.nextTick(function() { if (!_this.closing) { (_this.paused || Promise.resolve()) .then(function() { var gettingNextJob = job ? Promise.resolve(job) : _this.getNextJob(); return (_this.processing[index] = gettingNextJob .then(_this.processJob) .then(processJobs, function(err) { _this.emit('error', err, 'Error processing job'); // // Wait before trying to process again. // clearTimeout(_this.errorRetryTimer[index]); _this.errorRetryTimer[index] = setTimeout(function() { processJobs(); }, _this.settings.retryProcessDelay); return null; })); }) .catch(function(err) { _this.emit('error', err, 'Error processing job'); }); } else { resolve(_this.closing); } }); }; Queue.prototype.processJob = function(job) { var _this = this; var lockRenewId; var timerStopped = false; if (!job) { return Promise.resolve(); } // // There are two cases to take into consideration regarding locks. // 1) The lock renewer fails to renew a lock, this should make this job // unable to complete, since some other worker is also working on it. // 2) The lock renewer is called more seldom than the check for stalled // jobs, so we can assume the job has been stalled and is already being processed // by another worker. See #308 // var lockExtender = function() { lockRenewId = _this.timers.set( 'lockExtender', _this.settings.lockRenewTime, function() { scripts .extendLock(_this, job.id) .then(function(lock) { if (lock && !timerStopped) { lockExtender(); } }) .catch(function(/*err*/) { // Somehow tell the worker this job should stop processing... }); } ); }; var timeoutMs = job.opts.timeout; function stopTimer() { timerStopped = true; _this.timers.clear(lockRenewId); } function handleCompleted(result) { return job.moveToCompleted(result).then(function(jobData) { _this.emit('completed', job, result, 'active'); return jobData ? _this.nextJobFromJobData(jobData[0], jobData[1]) : null; }); } function handleFailed(err) { var error = err.cause || err; //Handle explicit rejection return job.moveToFailed(err).then(function(jobData) { _this.emit('failed', job, error, 'active'); return jobData ? _this.nextJobFromJobData(jobData[0], jobData[1]) : null; }); } lockExtender(); var handler = _this.handlers[job.name] || _this.handlers['*']; Iif (!handler) { return handleFailed( Error('Missing process handler for job type ' + job.name) ); } else { var jobPromise = handler(job); if (timeoutMs) { jobPromise = jobPromise.timeout(timeoutMs); } // Local event with jobPromise so that we can cancel job. _this.emit('active', job, jobPromise, 'waiting'); return jobPromise .then(handleCompleted) .catch(handleFailed) .finally(function() { stopTimer(); }); } }; Queue.prototype.multi = function() { return this.client.multi(); }; /** Returns a promise that resolves to the next job in queue. */ Queue.prototype.getNextJob = function() { var _this = this; if (this.closing) { return Promise.resolve(); } if (this.drained) { // // Waiting for new jobs to arrive // return this.bclient .brpoplpush(this.keys.wait, this.keys.active, _this.settings.drainDelay) .then( function(jobId) { Eif (jobId) { return _this.moveToActive(jobId); } }, function(err) { // Swallow error Iif (err.message !== 'Connection is closed.') { console.error('BRPOPLPUSH', err); } } ); } else { return this.moveToActive(); } }; Queue.prototype.moveToActive = function(jobId) { var _this = this; return scripts.moveToActive(_this, jobId).spread(function(jobData, jobId) { return _this.nextJobFromJobData(jobData, jobId); }); }; Queue.prototype.nextJobFromJobData = function(jobData, jobId) { if (jobData) { this.drained = false; var job = Job.fromJSON(this, jobData, jobId); Iif (job.opts.repeat) { return this.nextRepeatableJob(job.name, job.data, job.opts).then( function() { return job; } ); } return job; } else { this.drained = true; this.emit('drained'); return null; } }; Queue.prototype.retryJob = function(job) { return job.retry(); }; Queue.prototype.toKey = function(queueType) { return [this.keyPrefix, this.name, queueType].join(':'); }; /*@function clean * * Cleans jobs from a queue. Similar to remove but keeps jobs within a certain * grace period. * * @param {int} grace - The grace period * @param {string} [type=completed] - The type of job to clean. Possible values are completed, wait, active, paused, delayed, failed. Defaults to completed. * @param {int} The max number of jobs to clean */ Queue.prototype.clean = function(grace, type, limit) { var _this = this; Iif (grace === undefined || grace === null) { return Promise.reject(new Error('You must define a grace period.')); } Eif (!type) { type = 'completed'; } Iif ( _.indexOf( ['completed', 'wait', 'active', 'paused', 'delayed', 'failed'], type ) === -1 ) { return Promise.reject(new Error('Cannot clean unknown queue type ' + type)); } return scripts .cleanJobsInSet(_this, type, Date.now() - grace, limit) .then(function(jobs) { _this.emit('cleaned', jobs, type); return jobs; }) .catch(function(err) { _this.emit('error', err); throw err; }); }; /** * Returns a promise that resolves when active jobs are cleared * * @returns {Promise} */ Queue.prototype.whenCurrentJobsFinished = function() { var _this = this; return new Promise(function(resolve, reject) { // // Force reconnection of blocking connection to abort blocking redis call immediately. // var forcedReconnetion = redisClientDisconnect(_this.bclient).then( function() { return _this.bclient.connect(); } ); Promise.all(_this.processing) .then(function() { return forcedReconnetion; }) .then(resolve, reject); /* _this.bclient.disconnect(); _this.bclient.once('end', function(){ console.error('ENDED!'); setTimeout(function(){ _this.bclient.connect(); }, 0); }); /* var stream = _this.bclient.connector.stream; if(stream){ stream.on('finish', function(){ console.error('FINISHED!'); _this.bclient.connect(); }); stream.on('error', function(err){ console.error('errir', err); _this.bclient.connect(); }); _this.bclient.connect(); } */ //_this.bclient.connect(); }); }; // // Private local functions // function getRedisVersion(client) { return client.info().then(function(doc) { var prefix = 'redis_version:'; var lines = doc.split('\r\n'); for (var i = 0; i < lines.length; i++) { if (lines[i].indexOf(prefix) === 0) { return lines[i].substr(prefix.length); } } }); } module.exports = Queue; |