UNPKG

33.4 kBMarkdownView Raw
1# Kue
2
3[![Build Status](https://travis-ci.org/Automattic/kue.svg?branch=master&style=flat)](https://travis-ci.org/Automattic/kue)
4[![npm version](https://badge.fury.io/js/kue.svg?style=flat)](http://badge.fury.io/js/kue)
5[![Dependency Status](https://img.shields.io/david/Automattic/kue.svg?style=flat)](https://david-dm.org/Automattic/kue)
6[![Join the chat at https://gitter.im/Automattic/kue](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/Automattic/kue?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)
7
8
9Kue is a priority job queue backed by [redis](http://redis.io), built for [node.js](http://nodejs.org).
10
11**PROTIP** This is the latest Kue documentation, make sure to also read the [changelist](History.md).
12
13
14
15## Upgrade Notes (Please Read)
16 - [0.9 -> 0.10](https://github.com/Automattic/kue/wiki/Upgrading-to-0.10.x)
17 - [0.8 -> 0.9](https://github.com/Automattic/kue/wiki/Upgrading-to-0.9.x)
18
19
20
21## Installation
22
23 - Latest release:
24
25 $ npm install kue
26
27 - Master branch:
28
29 $ npm install http://github.com/Automattic/kue/tarball/master
30
31[![NPM](https://nodei.co/npm/kue.png?downloads=true&stars=true)](https://nodei.co/npm/kue/)
32
33## Features
34
35 - Delayed jobs
36 - Distribution of parallel work load
37 - Job event and progress pubsub
38 - Job TTL
39 - Optional retries with backoff
40 - Graceful workers shutdown
41 - Full-text search capabilities
42 - RESTful JSON API
43 - Rich integrated UI
44 - Infinite scrolling
45 - UI progress indication
46 - Job specific logging
47 - Powered by Redis
48
49## Overview
50
51 - [Creating Jobs](#creating-jobs)
52 - [Jobs Priority](#job-priority)
53 - [Failure Attempts](#failure-attempts)
54 - [Failure Backoff](#failure-backoff)
55 - [Job TTL](#job-ttl)
56 - [Job Logs](#job-logs)
57 - [Job Progress](#job-progress)
58 - [Job Events](#job-events)
59 - [Queue Events](#queue-events)
60 - [Delayed Jobs](#delayed-jobs)
61 - [Processing Jobs](#processing-jobs)
62 - [Processing Concurrency](#processing-concurrency)
63 - [Pause Processing](#pause-processing)
64 - [Updating Progress](#updating-progress)
65 - [Graceful Shutdown](#graceful-shutdown)
66 - [Error Handling](#error-handling)
67 - [Queue Maintenance](#queue-maintenance)
68 - [Redis Connection Settings](#redis-connection-settings)
69 - [User-Interface](#user-interface)
70 - [JSON API](#json-api)
71 - [Parallel Processing With Cluster](#parallel-processing-with-cluster)
72 - [Securing Kue](#securing-kue)
73 - [Testing](#testing)
74 - [Screencasts](#screencasts)
75 - [License](#license)
76
77
78
79## Creating Jobs
80
81First create a job `Queue` with `kue.createQueue()`:
82
83```js
84var kue = require('kue')
85 , queue = kue.createQueue();
86```
87
88Calling `queue.create()` with the type of job ("email"), and arbitrary job data will return a `Job`, which can then be `save()`ed, adding it to redis, with a default priority level of "normal". The `save()` method optionally accepts a callback, responding with an `error` if something goes wrong. The `title` key is special-cased, and will display in the job listings within the UI, making it easier to find a specific job.
89
90```js
91var job = queue.create('email', {
92 title: 'welcome email for tj'
93 , to: 'tj@learnboost.com'
94 , template: 'welcome-email'
95}).save( function(err){
96 if( !err ) console.log( job.id );
97});
98```
99
100### Job Priority
101
102To specify the priority of a job, simply invoke the `priority()` method with a number, or priority name, which is mapped to a number.
103
104```js
105queue.create('email', {
106 title: 'welcome email for tj'
107 , to: 'tj@learnboost.com'
108 , template: 'welcome-email'
109}).priority('high').save();
110```
111
112The default priority map is as follows:
113
114```js
115{
116 low: 10
117 , normal: 0
118 , medium: -5
119 , high: -10
120 , critical: -15
121};
122```
123
124### Failure Attempts
125
126By default jobs only have _one_ attempt, that is when they fail, they are marked as a failure, and remain that way until you intervene. However, Kue allows you to specify this, which is important for jobs such as transferring an email, which upon failure, may usually retry without issue. To do this invoke the `.attempts()` method with a number.
127
128```js
129 queue.create('email', {
130 title: 'welcome email for tj'
131 , to: 'tj@learnboost.com'
132 , template: 'welcome-email'
133 }).priority('high').attempts(5).save();
134```
135
136### Failure Backoff
137Job retry attempts are done as soon as they fail, with no delay, even if your job had a delay set via `Job#delay`. If you want to delay job re-attempts upon failures (known as backoff) you can use `Job#backoff` method in different ways:
138
139```js
140 // Honor job's original delay (if set) at each attempt, defaults to fixed backoff
141 job.attempts(3).backoff( true )
142
143 // Override delay value, fixed backoff
144 job.attempts(3).backoff( {delay: 60*1000, type:'fixed'} )
145
146 // Enable exponential backoff using original delay (if set)
147 job.attempts(3).backoff( {type:'exponential'} )
148
149 // Use a function to get a customized next attempt delay value
150 job.attempts(3).backoff( function( attempts, delay ){
151 //attempts will correspond to the nth attempt failure so it will start with 0
152 //delay will be the amount of the last delay, not the initial delay unless attempts === 0
153 return my_customized_calculated_delay;
154 })
155```
156
157In the last scenario, provided function will be executed (via eval) on each re-attempt to get next attempt delay value, meaning that you can't reference external/context variables within it.
158
159### Job TTL
160
161Job producers can set an expiry value for the time their job can live in active state, so that if workers didn't reply in timely fashion, Kue will fail it with `TTL exceeded` error message preventing that job from being stuck in active state and spoiling concurrency.
162
163```js
164queue.create('email', {title: 'email job with TTL'}).ttl(milliseconds).save();
165```
166
167### Job Logs
168
169Job-specific logs enable you to expose information to the UI at any point in the job's life-time. To do so simply invoke `job.log()`, which accepts a message string as well as variable-arguments for sprintf-like support:
170
171```js
172job.log('$%d sent to %s', amount, user.name);
173```
174
175or anything else (uses [util.inspect()](https://nodejs.org/api/util.html#util_util_inspect_object_options) internally):
176
177```js
178job.log({key: 'some key', value: 10});
179job.log([1,2,3,5,8]);
180job.log(10.1);
181```
182
183### Job Progress
184
185Job progress is extremely useful for long-running jobs such as video conversion. To update the job's progress simply invoke `job.progress(completed, total [, data])`:
186
187```js
188job.progress(frames, totalFrames);
189```
190
191data can be used to pass extra information about the job. For example a message or an object with some extra contextual data to the current status.
192
193### Job Events
194
195Job-specific events are fired on the `Job` instances via Redis pubsub. The following events are currently supported:
196
197- `enqueue` the job is now queued
198- `start` the job is now running
199- `promotion` the job is promoted from delayed state to queued
200- `progress` the job's progress ranging from 0-100
201- `failed attempt` the job has failed, but has remaining attempts yet
202- `failed` the job has failed and has no remaining attempts
203- `complete` the job has completed
204- `remove` the job has been removed
205
206
207For example this may look something like the following:
208
209```js
210var job = queue.create('video conversion', {
211 title: 'converting loki\'s to avi'
212 , user: 1
213 , frames: 200
214});
215
216job.on('complete', function(result){
217 console.log('Job completed with data ', result);
218
219}).on('failed attempt', function(errorMessage, doneAttempts){
220 console.log('Job failed');
221
222}).on('failed', function(errorMessage){
223 console.log('Job failed');
224
225}).on('progress', function(progress, data){
226 console.log('\r job #' + job.id + ' ' + progress + '% complete with data ', data );
227
228});
229```
230
231**Note** that Job level events are not guaranteed to be received upon process restarts, since restarted node.js process will lose the reference to the specific Job object. If you want a more reliable event handler look for [Queue Events](#queue-events).
232
233**Note** Kue stores job objects in memory until they are complete/failed to be able to emit events on them. If you have a huge concurrency in uncompleted jobs, turn this feature off and use queue level events for better memory scaling.
234
235 ```js
236 kue.createQueue({jobEvents: false})
237 ```
238
239 Alternatively, you can use the job level function `events` to control whether events are fired for a job at the job level.
240
241 ```js
242var job = queue.create('test').events(false).save();
243 ```
244
245### Queue Events
246
247Queue-level events provide access to the job-level events previously mentioned, however scoped to the `Queue` instance to apply logic at a "global" level. An example of this is removing completed jobs:
248
249```js
250queue.on('job enqueue', function(id, type){
251 console.log( 'Job %s got queued of type %s', id, type );
252
253}).on('job complete', function(id, result){
254 kue.Job.get(id, function(err, job){
255 if (err) return;
256 job.remove(function(err){
257 if (err) throw err;
258 console.log('removed completed job #%d', job.id);
259 });
260 });
261});
262```
263
264The events available are the same as mentioned in "Job Events", however prefixed with "job ".
265
266### Delayed Jobs
267
268Delayed jobs may be scheduled to be queued for an arbitrary distance in time by invoking the `.delay(ms)` method, passing the number of milliseconds relative to _now_. Alternatively, you can pass a JavaScript `Date` object with a specific time in the future.
269This automatically flags the `Job` as "delayed".
270
271```js
272var email = queue.create('email', {
273 title: 'Account renewal required'
274 , to: 'tj@learnboost.com'
275 , template: 'renewal-email'
276}).delay(milliseconds)
277 .priority('high')
278 .save();
279```
280
281Kue will check the delayed jobs with a timer, promoting them if the scheduled delay has been exceeded, defaulting to a check of top 1000 jobs every second.
282
283## Processing Jobs
284
285Processing jobs is simple with Kue. First create a `Queue` instance much like we do for creating jobs, providing us access to redis etc, then invoke `queue.process()` with the associated type.
286Note that unlike what the name `createQueue` suggests, it currently returns a singleton `Queue` instance. So you can configure and use only a single `Queue` object within your node.js process.
287
288In the following example we pass the callback `done` to `email`, When an error occurs we invoke `done(err)` to tell Kue something happened, otherwise we invoke `done()` only when the job is complete. If this function responds with an error it will be displayed in the UI and the job will be marked as a failure. The error object passed to done, should be of standard type `Error`.
289
290```js
291var kue = require('kue')
292 , queue = kue.createQueue();
293
294queue.process('email', function(job, done){
295 email(job.data.to, done);
296});
297
298function email(address, done) {
299 if(!isValidEmail(address)) {
300 //done('invalid to address') is possible but discouraged
301 return done(new Error('invalid to address'));
302 }
303 // email send stuff...
304 done();
305}
306```
307
308Workers can also pass job result as the second parameter to done `done(null,result)` to store that in `Job.result` key. `result` is also passed through `complete` event handlers so that job producers can receive it if they like to.
309
310### Processing Concurrency
311
312By default a call to `queue.process()` will only accept one job at a time for processing. For small tasks like sending emails this is not ideal, so we may specify the maximum active jobs for this type by passing a number:
313
314```js
315queue.process('email', 20, function(job, done){
316 // ...
317});
318```
319
320### Pause Processing
321
322Workers can temporary pause and resume their activity. It is, after calling `pause` they will receive no jobs in their process callback until `resume` is called. `pause` function gracefully shutdowns this worker, and uses the same internal functionality as `shutdown` method in [Graceful Shutdown](#graceful-shutdown).
323
324```js
325queue.process('email', function(job, ctx, done){
326 ctx.pause( 5000, function(err){
327 console.log("Worker is paused... ");
328 setTimeout( function(){ ctx.resume(); }, 10000 );
329 });
330});
331```
332
333**Note** *that the `ctx` parameter from Kue `>=0.9.0` is the second argument of the process callback function and `done` is idiomatically always the last*
334
335**Note** *that `pause` method signature is changed from Kue `>=0.9.0` to move the callback function to the last.*
336
337### Updating Progress
338
339For a "real" example, let's say we need to compile a PDF from numerous slides with [node-canvas](https://github.com/Automattic/node-canvas). Our job may consist of the following data, note that in general you should _not_ store large data in the job it-self, it's better to store references like ids, pulling them in while processing.
340
341```js
342queue.create('slideshow pdf', {
343 title: user.name + "'s slideshow"
344 , slides: [...] // keys to data stored in redis, mongodb, or some other store
345});
346```
347
348We can access this same arbitrary data within a separate process while processing, via the `job.data` property. In the example we render each slide one-by-one, updating the job's log and progress.
349
350```js
351queue.process('slideshow pdf', 5, function(job, done){
352 var slides = job.data.slides
353 , len = slides.length;
354
355 function next(i) {
356 var slide = slides[i]; // pretend we did a query on this slide id ;)
357 job.log('rendering %dx%d slide', slide.width, slide.height);
358 renderSlide(slide, function(err){
359 if (err) return done(err);
360 job.progress(i, len, {nextSlide : i == len ? 'itsdone' : i + 1});
361 if (i == len) done()
362 else next(i + 1);
363 });
364 }
365
366 next(0);
367});
368```
369
370### Graceful Shutdown
371
372`Queue#shutdown([timeout,] fn)` signals all workers to stop processing after their current active job is done. Workers will wait `timeout` milliseconds for their active job's done to be called or mark the active job `failed` with shutdown error reason. When all workers tell Kue they are stopped `fn` is called.
373
374```javascript
375var queue = require('kue').createQueue();
376
377process.once( 'SIGTERM', function ( sig ) {
378 queue.shutdown( 5000, function(err) {
379 console.log( 'Kue shutdown: ', err||'' );
380 process.exit( 0 );
381 });
382});
383```
384
385**Note** *that `shutdown` method signature is changed from Kue `>=0.9.0` to move the callback function to the last.*
386
387## Error Handling
388
389All errors either in Redis client library or Queue are emitted to the `Queue` object. You should bind to `error` events to prevent uncaught exceptions or debug kue errors.
390
391```javascript
392var queue = require('kue').createQueue();
393
394queue.on( 'error', function( err ) {
395 console.log( 'Oops... ', err );
396});
397```
398
399### Prevent from Stuck Active Jobs
400
401Kue marks a job complete/failed when `done` is called by your worker, so you should use proper error handling to prevent uncaught exceptions in your worker's code and node.js process exiting before in handle jobs get done.
402This can be achieved in two ways:
403
4041. Wrapping your worker's process function in [Domains](https://nodejs.org/api/domain.html)
405
406 ```js
407 queue.process('my-error-prone-task', function(job, done){
408 var domain = require('domain').create();
409 domain.on('error', function(err){
410 done(err);
411 });
412 domain.run(function(){ // your process function
413 throw new Error( 'bad things happen' );
414 done();
415 });
416 });
417 ```
418 **Notice -** Domains are [deprecated](https://nodejs.org/api/documentation.html#documentation_stability_index) from Nodejs with **stability 0** and it's not recommended to use.
419
420 This is the softest and best solution, however is not built-in with Kue. Please refer to [this discussion](https://github.com/kriskowal/q/issues/120). You can comment on this feature in the related open Kue [issue](https://github.com/Automattic/kue/pull/403).
421
422 You can also use promises to do something like
423
424 ```js
425 queue.process('my-error-prone-task', function(job, done){
426 Promise.method( function(){ // your process function
427 throw new Error( 'bad things happen' );
428 })().nodeify(done)
429 });
430 ```
431
432 but this won't catch exceptions in your async call stack as domains do.
433
434
435
4362. Binding to `uncaughtException` and gracefully shutting down the Kue, however this is not a recommended error handling idiom in javascript since you are losing the error context.
437
438 ```js
439 process.once( 'uncaughtException', function(err){
440 console.error( 'Something bad happened: ', err );
441 queue.shutdown( 1000, function(err2){
442 console.error( 'Kue shutdown result: ', err2 || 'OK' );
443 process.exit( 0 );
444 });
445 });
446 ```
447
448### Unstable Redis connections
449
450Kue currently uses client side job state management and when redis crashes in the middle of that operations, some stuck jobs or index inconsistencies will happen. The consequence is that certain number of jobs will be stuck, and be pulled out by worker only when new jobs are created, if no more new jobs are created, they stuck forever. So we **strongly** suggest that you run watchdog to fix this issue by calling:
451
452```js
453queue.watchStuckJobs(interval)
454```
455
456`interval` is in milliseconds and defaults to 1000ms
457
458Kue will be refactored to fully atomic job state management from version 1.0 and this will happen by lua scripts and/or BRPOPLPUSH combination. You can read more [here](https://github.com/Automattic/kue/issues/130) and [here](https://github.com/Automattic/kue/issues/38).
459
460## Queue Maintenance
461
462Queue object has two type of methods to tell you about the number of jobs in each state
463
464```js
465queue.inactiveCount( function( err, total ) { // others are activeCount, completeCount, failedCount, delayedCount
466 if( total > 100000 ) {
467 console.log( 'We need some back pressure here' );
468 }
469});
470```
471
472you can also query on an specific job type:
473
474```js
475queue.failedCount( 'my-critical-job', function( err, total ) {
476 if( total > 10000 ) {
477 console.log( 'This is tOoOo bad' );
478 }
479});
480```
481
482and iterating over job ids
483
484```js
485queue.inactive( function( err, ids ) { // others are active, complete, failed, delayed
486 // you may want to fetch each id to get the Job object out of it...
487});
488```
489
490however the second one doesn't scale to large deployments, there you can use more specific `Job` static methods:
491
492```js
493kue.Job.rangeByState( 'failed', 0, n, 'asc', function( err, jobs ) {
494 // you have an array of maximum n Job objects here
495});
496```
497or
498
499```js
500kue.Job.rangeByType( 'my-job-type', 'failed', 0, n, 'asc', function( err, jobs ) {
501 // you have an array of maximum n Job objects here
502});
503```
504
505**Note** *that the last two methods are subject to change in later Kue versions.*
506
507
508### Programmatic Job Management
509
510If you did none of above in [Error Handling](#error-handling) section or your process lost active jobs in any way, you can recover from them when your process is restarted. A blind logic would be to re-queue all stuck jobs:
511
512```js
513queue.active( function( err, ids ) {
514 ids.forEach( function( id ) {
515 kue.Job.get( id, function( err, job ) {
516 // Your application should check if job is a stuck one
517 job.inactive();
518 });
519 });
520});
521```
522
523**Note** *in a clustered deployment your application should be aware not to involve a job that is valid, currently inprocess by other workers.*
524
525### Job Cleanup
526
527Jobs data and search indexes eat up redis memory space, so you will need some job-keeping process in real world deployments. Your first chance is using automatic job removal on completion.
528
529```javascript
530queue.create( ... ).removeOnComplete( true ).save()
531```
532
533But if you eventually/temporally need completed job data, you can setup an on-demand job removal script like below to remove top `n` completed jobs:
534
535```js
536kue.Job.rangeByState( 'complete', 0, n, 'asc', function( err, jobs ) {
537 jobs.forEach( function( job ) {
538 job.remove( function(){
539 console.log( 'removed ', job.id );
540 });
541 });
542});
543```
544
545**Note** *that you should provide enough time for `.remove` calls on each job object to complete before your process exits, or job indexes will leak*
546
547
548## Redis Connection Settings
549
550By default, Kue will connect to Redis using the client default settings (port defaults to `6379`, host defaults to `127.0.0.1`, prefix defaults to `q`). `Queue#createQueue(options)` accepts redis connection options in `options.redis` key.
551
552```javascript
553var kue = require('kue');
554var q = kue.createQueue({
555 prefix: 'q',
556 redis: {
557 port: 1234,
558 host: '10.0.50.20',
559 auth: 'password',
560 db: 3, // if provided select a non-default redis db
561 options: {
562 // see https://github.com/mranney/node_redis#rediscreateclient
563 }
564 }
565});
566```
567
568`prefix` controls the key names used in Redis. By default, this is simply `q`. Prefix generally shouldn't be changed unless you need to use one Redis instance for multiple apps. It can also be useful for providing an isolated testbed across your main application.
569
570You can also specify the connection information as a URL string.
571
572```js
573var q = kue.createQueue({
574 redis: 'redis://example.com:1234?redis_option=value&redis_option=value'
575});
576```
577
578#### Connecting using Unix Domain Sockets
579
580Since [node_redis](https://github.com/mranney/node_redis) supports Unix Domain Sockets, you can also tell Kue to do so. See [unix-domain-socket](https://github.com/mranney/node_redis#unix-domain-socket) for your redis server configuration.
581
582```javascript
583var kue = require('kue');
584var q = kue.createQueue({
585 prefix: 'q',
586 redis: {
587 socket: '/data/sockets/redis.sock',
588 auth: 'password',
589 options: {
590 // see https://github.com/mranney/node_redis#rediscreateclient
591 }
592 }
593});
594```
595
596#### Replacing Redis Client Module
597
598Any node.js redis client library that conforms (or when adapted) to [node_redis](https://github.com/mranney/node_redis) API can be injected into Kue. You should only provide a `createClientFactory` function as a redis connection factory instead of providing node_redis connection options.
599
600Below is a sample code to enable [redis-sentinel](https://github.com/ortoo/node-redis-sentinel) to connect to [Redis Sentinel](http://redis.io/topics/sentinel) for automatic master/slave failover.
601
602```javascript
603var kue = require('kue');
604var Sentinel = require('redis-sentinel');
605var endpoints = [
606 {host: '192.168.1.10', port: 6379},
607 {host: '192.168.1.11', port: 6379}
608];
609var opts = options || {}; // Standard node_redis client options
610var masterName = 'mymaster';
611var sentinel = Sentinel.Sentinel(endpoints);
612
613var q = kue.createQueue({
614 redis: {
615 createClientFactory: function(){
616 return sentinel.createClient(masterName, opts);
617 }
618 }
619});
620```
621
622**Note** *that all `<0.8.x` client codes should be refactored to pass redis options to `Queue#createQueue` instead of monkey patched style overriding of `redis#createClient` or they will be broken from Kue `0.8.x`.*
623
624#### Using ioredis client with cluster support
625
626```javascript
627
628var Redis = require('ioredis');
629var kue = require('kue');
630
631// using https://github.com/72squared/vagrant-redis-cluster
632
633var queue = kue.createQueue({
634 redis: {
635 createClientFactory: function () {
636 return new Redis.Cluster([{
637 port: 7000
638 }, {
639 port: 7001
640 }]);
641 }
642 }
643 });
644```
645
646## User-Interface
647
648The UI is a small [Express](https://github.com/strongloop/express) application.
649A script is provided in `bin/` for running the interface as a standalone application
650with default settings. You may pass in options for the port, redis-url, and prefix. For example:
651
652```
653node_modules/kue/bin/kue-dashboard -p 3050 -r redis://127.0.0.1:3000 -q prefix
654```
655
656You can fire it up from within another application too:
657
658
659```js
660var kue = require('kue');
661kue.createQueue(...);
662kue.app.listen(3000);
663```
664
665The title defaults to "Kue", to alter this invoke:
666
667```js
668kue.app.set('title', 'My Application');
669```
670
671**Note** *that if you are using non-default Kue options, `kue.createQueue(...)` must be called before accessing `kue.app`.*
672
673### Third-party interfaces
674
675You can also use [Kue-UI](https://github.com/StreetHub/kue-ui) web interface contributed by [Arnaud Bénard](https://github.com/arnaudbenard)
676
677
678## JSON API
679
680Along with the UI Kue also exposes a JSON API, which is utilized by the UI.
681
682### GET /job/search?q=
683
684Query jobs, for example "GET /job/search?q=avi video":
685
686```js
687["5", "7", "10"]
688```
689
690By default kue indexes the whole Job data object for searching, but this can be customized via calling `Job#searchKeys` to tell kue which keys on Job data to create index for:
691
692```javascript
693var kue = require('kue');
694queue = kue.createQueue();
695queue.create('email', {
696 title: 'welcome email for tj'
697 , to: 'tj@learnboost.com'
698 , template: 'welcome-email'
699}).searchKeys( ['to', 'title'] ).save();
700```
701
702Search feature is turned off by default from Kue `>=0.9.0`. Read more about this [here](https://github.com/Automattic/kue/issues/412). You should enable search indexes and add [reds](https://www.npmjs.com/package/reds) in your dependencies if you need to:
703
704```javascript
705var kue = require('kue');
706q = kue.createQueue({
707 disableSearch: false
708});
709```
710
711```
712npm install reds --save
713```
714
715### GET /stats
716
717Currently responds with state counts, and worker activity time in milliseconds:
718
719```js
720{"inactiveCount":4,"completeCount":69,"activeCount":2,"failedCount":0,"workTime":20892}
721```
722
723### GET /job/:id
724
725Get a job by `:id`:
726
727```js
728{"id":"3","type":"email","data":{"title":"welcome email for tj","to":"tj@learnboost.com","template":"welcome-email"},"priority":-10,"progress":"100","state":"complete","attempts":null,"created_at":"1309973155248","updated_at":"1309973155248","duration":"15002"}
729```
730
731### GET /job/:id/log
732
733Get job `:id`'s log:
734
735```js
736['foo', 'bar', 'baz']
737```
738
739### GET /jobs/:from..:to/:order?
740
741Get jobs with the specified range `:from` to `:to`, for example "/jobs/0..2", where `:order` may be "asc" or "desc":
742
743```js
744[{"id":"12","type":"email","data":{"title":"welcome email for tj","to":"tj@learnboost.com","template":"welcome-email"},"priority":-10,"progress":0,"state":"active","attempts":null,"created_at":"1309973299293","updated_at":"1309973299293"},{"id":"130","type":"email","data":{"title":"welcome email for tj","to":"tj@learnboost.com","template":"welcome-email"},"priority":-10,"progress":0,"state":"active","attempts":null,"created_at":"1309975157291","updated_at":"1309975157291"}]
745```
746
747### GET /jobs/:state/:from..:to/:order?
748
749Same as above, restricting by `:state` which is one of:
750
751 - active
752 - inactive
753 - failed
754 - complete
755
756### GET /jobs/:type/:state/:from..:to/:order?
757
758Same as above, however restricted to `:type` and `:state`.
759
760### DELETE /job/:id
761
762Delete job `:id`:
763
764 $ curl -X DELETE http://local:3000/job/2
765 {"message":"job 2 removed"}
766
767### POST /job
768
769Create a job:
770
771 $ curl -H "Content-Type: application/json" -X POST -d \
772 '{
773 "type": "email",
774 "data": {
775 "title": "welcome email for tj",
776 "to": "tj@learnboost.com",
777 "template": "welcome-email"
778 },
779 "options" : {
780 "attempts": 5,
781 "priority": "high"
782 }
783 }' http://localhost:3000/job
784 {"message": "job created", "id": 3}
785
786You can create multiple jobs at once by passing an array. In this case, the response will be an array too, preserving the order:
787
788 $ curl -H "Content-Type: application/json" -X POST -d \
789 '[{
790 "type": "email",
791 "data": {
792 "title": "welcome email for tj",
793 "to": "tj@learnboost.com",
794 "template": "welcome-email"
795 },
796 "options" : {
797 "attempts": 5,
798 "priority": "high"
799 }
800 },
801 {
802 "type": "email",
803 "data": {
804 "title": "followup email for tj",
805 "to": "tj@learnboost.com",
806 "template": "followup-email"
807 },
808 "options" : {
809 "delay": 86400,
810 "attempts": 5,
811 "priority": "high"
812 }
813 }]' http://localhost:3000/job
814 [
815 {"message": "job created", "id": 4},
816 {"message": "job created", "id": 5}
817 ]
818
819Note: when inserting multiple jobs in bulk, if one insertion fails Kue will keep processing the remaining jobs in order. The response array will contain the ids of the jobs added successfully, and any failed element will be an object describing the error: `{"error": "error reason"}`.
820
821
822## Parallel Processing With Cluster
823
824The example below shows how you may use [Cluster](http://nodejs.org/api/cluster.html) to spread the job processing load across CPUs. Please see [Cluster module's documentation](http://nodejs.org/api/cluster.html) for more detailed examples on using it.
825
826When cluster `.isMaster` the file is being executed in context of the master process, in which case you may perform tasks that you only want once, such as starting the web app bundled with Kue. The logic in the `else` block is executed _per worker_.
827
828```js
829var kue = require('kue')
830 , cluster = require('cluster')
831 , queue = kue.createQueue();
832
833var clusterWorkerSize = require('os').cpus().length;
834
835if (cluster.isMaster) {
836 kue.app.listen(3000);
837 for (var i = 0; i < clusterWorkerSize; i++) {
838 cluster.fork();
839 }
840} else {
841 queue.process('email', 10, function(job, done){
842 var pending = 5
843 , total = pending;
844
845 var interval = setInterval(function(){
846 job.log('sending!');
847 job.progress(total - pending, total);
848 --pending || done();
849 pending || clearInterval(interval);
850 }, 1000);
851 });
852}
853```
854
855This will create an `email` job processor (worker) per each of your machine CPU cores, with each you can handle 10 concurrent email jobs, leading to total `10 * N` concurrent email jobs processed in your `N` core machine.
856
857Now when you visit Kue's UI in the browser you'll see that jobs are being processed roughly `N` times faster! (if you have `N` cores).
858
859## Securing Kue
860
861Through the use of app mounting you may customize the web application, enabling TLS, or adding additional middleware like `basic-auth-connect`.
862
863```bash
864$ npm install --save basic-auth-connect
865```
866
867```js
868var basicAuth = require('basic-auth-connect');
869var app = express.createServer({ ... tls options ... });
870app.use(basicAuth('foo', 'bar'));
871app.use(kue.app);
872app.listen(3000);
873```
874
875## Testing
876
877Enable test mode to push all jobs into a `jobs` array. Make assertions against
878the jobs in that array to ensure code under test is correctly enqueuing jobs.
879
880```js
881queue = require('kue').createQueue();
882
883before(function() {
884 queue.testMode.enter();
885});
886
887afterEach(function() {
888 queue.testMode.clear();
889});
890
891after(function() {
892 queue.testMode.exit()
893});
894
895it('does something cool', function() {
896 queue.createJob('myJob', { foo: 'bar' }).save();
897 queue.createJob('anotherJob', { baz: 'bip' }).save();
898 expect(queue.testMode.jobs.length).to.equal(2);
899 expect(queue.testMode.jobs[0].type).to.equal('myJob');
900 expect(queue.testMode.jobs[0].data).to.eql({ foo: 'bar' });
901});
902```
903
904**IMPORTANT:** By default jobs aren't processed when created during test mode. You can enable job processing by passing true to testMode.enter
905
906```js
907before(function() {
908 queue.testMode.enter(true);
909});
910```
911
912
913## Screencasts
914
915 - [Introduction](http://www.screenr.com/oyNs) to Kue
916 - API [walkthrough](https://vimeo.com/26963384) to Kue
917
918## Contributing
919
920**We love contributions!**
921
922When contributing, follow the simple rules:
923
924* Don't violate [DRY](http://programmer.97things.oreilly.com/wiki/index.php/Don%27t_Repeat_Yourself) principles.
925* [Boy Scout Rule](http://programmer.97things.oreilly.com/wiki/index.php/The_Boy_Scout_Rule) needs to have been applied.
926* Your code should look like all the other code – this project should look like it was written by one person, always.
927* If you want to propose something – just create an issue and describe your question with as much description as you can.
928* If you think you have some general improvement, consider creating a pull request with it.
929* If you add new code, it should be covered by tests. No tests – no code.
930* If you add a new feature, don't forget to update the documentation for it.
931* If you find a bug (or at least you think it is a bug), create an issue with the library version and test case that we can run and see what are you talking about, or at least full steps by which we can reproduce it.
932
933## License
934
935(The MIT License)
936
937Copyright (c) 2011 LearnBoost &lt;tj@learnboost.com&gt;
938
939Permission is hereby granted, free of charge, to any person obtaining
940a copy of this software and associated documentation files (the
941'Software'), to deal in the Software without restriction, including
942without limitation the rights to use, copy, modify, merge, publish,
943distribute, sublicense, and/or sell copies of the Software, and to
944permit persons to whom the Software is furnished to do so, subject to
945the following conditions:
946
947The above copyright notice and this permission notice shall be
948included in all copies or substantial portions of the Software.
949
950THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,
951EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
952MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
953IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
954CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
955TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
956SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.