Code coverage report for lib/queue.js

Statements: 99.47% (187 / 188)      Branches: 99.02% (101 / 102)      Functions: 100% (30 / 30)      Lines: 100% (184 / 184)      Ignored: 9 statements, 1 function, 7 branches     

All files » lib/ » 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 3571 1 1   1 1 1 1 1   1 139 69     70 70 70   70 70               70 70 350       70 1   70 70 70       70     70         70 207 207 207     70   70 68     70 69 69 69 69     70 70     1   1 594 594 36     594   594 108 1 107 3     108   108 104         1 68 68     68 1     68 68 66     68 67     68 67 67     68 201 201       1 2 2   2     1 4             4 4                 1 146     1 2 2 1   1 1 1 1         1 185 185   149 149       1 149 149 149   149 158 144 54       149   149   139 3     136 136   136     149 3 3     149 1 1   1     148       1 136   136       136           136 9 3 3 3     6     127 1   126       136 135     136   132 1   132       1 49 1     48 1     47 44 44     47 47 47 47 47   47 195 10 10         185   149 1 1     149 149 149 12 12     149 132 132     132 1   132     132         47   5   47 47   47     1 55 55   55       53   53 3     53         1 2051     1  
var redis = require('redis');
var events = require('events');
var util = require('util');
 
var Job = require('./job');
var defaults = require('./defaults');
var lua = require('./lua');
var helpers = require('./helpers');
var barrier = helpers.barrier;
 
function Queue(name, settings) {
  if (!(this instanceof Queue)) {
    return new Queue(name, settings);
  }
 
  this.name = name;
  this.paused = false;
  this.jobs = {};
 
  settings = settings || {};
  this.settings = {
    redis: settings.redis || {},
    stallInterval: typeof settings.stallInterval === 'number' ?
      settings.stallInterval :
      defaults.stallInterval,
    keyPrefix: (settings.prefix || defaults.prefix) + ':' + this.name + ':'
  };
 
  var boolProps = ['isWorker', 'getEvents', 'sendEvents', 'removeOnSuccess', 'catchExceptions'];
  boolProps.forEach(function (prop) {
    this.settings[prop] = typeof settings[prop] === 'boolean' ? settings[prop] : defaults[prop];
  }.bind(this));
 
  /* istanbul ignore if */
  Iif (this.settings.redis.socket) {
    this.settings.redis.params = [this.settings.redis.socket, this.settings.redis.options];
  } else {
    this.settings.redis.port = this.settings.redis.port || 6379;
    this.settings.redis.host = this.settings.redis.host || '127.0.0.1';
    this.settings.redis.params = [
      this.settings.redis.port, this.settings.redis.host, this.settings.redis.options
    ];
  }
  this.settings.redis.db = this.settings.redis.db || 0;
 
  // Wait for Lua loading and client connection; bclient and eclient/subscribe if needed
  var reportReady = barrier(
    2 + this.settings.isWorker + this.settings.getEvents * 2,
    this.emit.bind(this, 'ready')
  );
 
  var makeClient = function (clientName) {
    this[clientName] = redis.createClient.apply(redis, this.settings.redis.params);
    this[clientName].on('error', this.emit.bind(this, 'error'));
    this[clientName].select(this.settings.redis.db, reportReady);
  }.bind(this);
 
  makeClient('client');
 
  if (this.settings.isWorker) {
    makeClient('bclient');
  }
 
  if (this.settings.getEvents) {
    makeClient('eclient');
    this.eclient.subscribe(this.toKey('events'));
    this.eclient.on('message', this.onMessage.bind(this));
    this.eclient.on('subscribe', reportReady);
  }
 
  this.settings.serverKey = this.settings.redis.socket || this.settings.redis.host + ':' + this.settings.redis.port;
  lua.buildCache(this.settings.serverKey, this.client, reportReady);
}
 
util.inherits(Queue, events.EventEmitter);
 
Queue.prototype.onMessage = function (channel, message) {
  message = JSON.parse(message);
  if (message.event === 'failed' || message.event === 'retrying') {
    message.data = Error(message.data);
  }
 
  this.emit('job ' + message.event, message.id, message.data);
 
  if (this.jobs[message.id]) {
    if (message.event === 'progress') {
      this.jobs[message.id].progress = message.data;
    } else if (message.event === 'retrying') {
      this.jobs[message.id].options.retries -= 1;
    }
 
    this.jobs[message.id].emit(message.event, message.data);
 
    if (message.event === 'succeeded' || message.event === 'failed') {
      delete this.jobs[message.id];
    }
  }
};
 
Queue.prototype.close = function (cb) {
  cb = cb || helpers.defaultCb;
  this.paused = true;
 
  /* istanbul ignore next */
  var closeTimeout = setTimeout(function () {
    return cb(Error('Timed out closing redis connections'));
  }, 5000);
 
  var clients = [this.client];
  if (this.settings.isWorker) {
    clients.push(this.bclient);
  }
 
  if (this.settings.getEvents) {
    clients.push(this.eclient);
  }
 
  var handleEnd = barrier(clients.length, function () {
    clearTimeout(closeTimeout);
    return cb(null);
  });
 
  clients.forEach(function (client) {
    client.end();
    client.stream.on('close', handleEnd);
  });
};
 
Queue.prototype.destroy = function (cb) {
  cb = cb || helpers.defaultCb;
  var keys = ['id', 'jobs', 'stallTime', 'stalling', 'waiting', 'active', 'succeeded', 'failed']
    .map(this.toKey.bind(this));
  this.client.del.apply(this.client, keys.concat(cb));
};
 
Queue.prototype.checkHealth = function (cb) {
  this.client.multi()
    .llen(this.toKey('waiting'))
    .llen(this.toKey('active'))
    .scard(this.toKey('succeeded'))
    .scard(this.toKey('failed'))
    .exec(function (err, results) {
      /* istanbul ignore if */
      Iif (err) return cb(err);
      return cb(null, {
        waiting: results[0],
        active: results[1],
        succeeded: results[2],
        failed: results[3]
      });
    });
};
 
Queue.prototype.createJob = function (data) {
  return new Job(this, null, data);
};
 
Queue.prototype.getJob = function (jobId, cb) {
  var self = this;
  if (jobId in this.jobs) {
    return process.nextTick(cb.bind(null, null, this.jobs[jobId]));
  } else {
    Job.fromId(this, jobId, function (err, job) {
      Iif (err) return cb(err);
      self.jobs[jobId] = job;
      return cb(err, job);
    });
  }
};
 
Queue.prototype.getNextJob = function (cb) {
  var self = this;
  this.bclient.brpoplpush(this.toKey('waiting'), this.toKey('active'), 0, function (err, jobId) {
    /* istanbul ignore if */
    Iif (err) return cb(err);
    return Job.fromId(self, Number(jobId), cb);
  });
};
 
Queue.prototype.runJob = function (job, cb) {
  var self = this;
  var psTimeout;
  var handled = false;
 
  var preventStalling = function () {
    self.client.srem(self.toKey('stalling'), job.id, function () {
      if (!handled) {
        psTimeout = setTimeout(preventStalling, self.settings.stallInterval / 2);
      }
    });
  };
  preventStalling();
 
  var handleOutcome = function (err, data) {
    // silently ignore any multiple calls
    if (handled) {
      return;
    }
 
    handled = true;
    clearTimeout(psTimeout);
 
    self.finishJob(err, data, job, cb);
  };
 
  if (job.options.timeout) {
    var msg = 'Job ' + job.id + ' timed out (' + job.options.timeout + ' ms)';
    setTimeout(handleOutcome.bind(null, Error(msg)), job.options.timeout);
  }
 
  if (this.settings.catchExceptions) {
    try {
      this.handler(job, handleOutcome);
    } catch (err) {
      handleOutcome(err);
    }
  } else {
    this.handler(job, handleOutcome);
  }
};
 
Queue.prototype.finishJob = function (err, data, job, cb) {
  var status = err ? 'failed' : 'succeeded';
 
  var multi = this.client.multi()
    .lrem(this.toKey('active'), 0, job.id)
    .srem(this.toKey('stalling'), job.id);
 
  var jobEvent = {
    id: job.id,
    event: status,
    data: err ? err.message : data
  };
 
  if (status === 'failed') {
    if (job.options.retries > 0) {
      job.options.retries -= 1;
      jobEvent.event = 'retrying';
      multi.hset(this.toKey('jobs'), job.id, job.toData())
           .lpush(this.toKey('waiting'), job.id);
    } else {
      multi.sadd(this.toKey('failed'), job.id);
    }
  } else {
    if (this.settings.removeOnSuccess) {
      multi.hdel(this.toKey('jobs'), job.id);
    } else {
      multi.sadd(this.toKey('succeeded'), job.id);
    }
  }
 
  if (this.settings.sendEvents) {
    multi.publish(this.toKey('events'), JSON.stringify(jobEvent));
  }
 
  multi.exec(function (errMulti) {
    /* istanbul ignore if */
    Iif (errMulti) {
      return cb(errMulti);
    }
    return cb(null, status, err ? err : data);
  });
};
 
Queue.prototype.process = function (concurrency, handler) {
  if (!this.settings.isWorker) {
    throw Error('Cannot call Queue.prototype.process on a non-worker');
  }
 
  if (this.handler) {
    throw Error('Cannot call Queue.prototype.process twice');
  }
 
  if (typeof concurrency === 'function') {
    handler = concurrency;
    concurrency = 1;
  }
 
  var self = this;
  this.handler = handler;
  this.running = 0;
  this.queued = 1;
  this.concurrency = concurrency;
 
  var jobTick = function () {
    if (self.paused) {
      self.queued -= 1;
      return;
    }
 
    // invariant: in this code path, self.running < self.concurrency, always
    // after spoolup, self.running + self.queued === self.concurrency
    self.getNextJob(function (getErr, job) {
      /* istanbul ignore if */
      Iif (getErr) {
        self.emit('error', getErr);
        return setImmediate(jobTick);
      }
 
      self.running += 1;
      self.queued -= 1;
      if (self.running + self.queued < self.concurrency) {
        self.queued += 1;
        setImmediate(jobTick);
      }
 
      self.runJob(job, function (err, status, result) {
        self.running -= 1;
        self.queued += 1;
 
        /* istanbul ignore if */
        Iif (err) {
          self.emit('error', err);
        } else {
          self.emit(status, job, result);
        }
 
        setImmediate(jobTick);
      });
    });
  };
 
  var restartProcessing = function () {
    // maybe need to increment queued here?
    self.bclient.once('ready', jobTick);
  };
  this.bclient.on('error', restartProcessing);
  this.bclient.on('end', restartProcessing);
 
  this.checkStalledJobs(setImmediate.bind(null, jobTick));
};
 
Queue.prototype.checkStalledJobs = function (interval, cb) {
  var self = this;
  cb = typeof interval === 'function' ? interval : cb || helpers.defaultCb;
 
  this.client.evalsha(lua.shas.checkStalledJobs, 4,
    this.toKey('stallTime'), this.toKey('stalling'), this.toKey('waiting'), this.toKey('active'),
    Date.now(), this.settings.stallInterval, function (err) {
      /* istanbul ignore if */
      Iif (err) return cb(err);
 
      if (typeof interval === 'number') {
        setTimeout(self.checkStalledJobs.bind(self, interval, cb), interval);
      }
 
      return cb();
    }
  );
};
 
Queue.prototype.toKey = function (str) {
  return this.settings.keyPrefix + str;
};
 
module.exports = Queue;