[
  {
    "path": ".gitignore",
    "content": "node_modules/*\n*.log\n*~\n"
  },
  {
    "path": ".travis.yml",
    "content": "language: node_js\nnode_js:\n  - \"8\"\n  - \"10\"\n  - \"11\"\nservices: mongodb\n"
  },
  {
    "path": "README.md",
    "content": "# mongodb-queue #\n\n[![Build Status](https://travis-ci.org/chilts/mongodb-queue.png)](https://travis-ci.org/chilts/mongodb-queue) [![NPM](https://nodei.co/npm/mongodb-queue.png?mini=true)](https://nodei.co/npm/mongodb-queue/)\n\nA really light-weight way to create queues with a nice API if you're already\nusing MongoDB.\n\nNow compatible with the MongoDB v3 driver.\n\nFor MongoDB v2 driver use mongodb-queue@3.\n\n**NOTE**: This package is considered feature complete and **STABLE** hence there is not a whole lot of development on\nit though it is being used extensively. Use it with all your might and let us know of any problems - it should be\nbullet-proof.\n\n## Synopsis ##\n\nCreate a connection to your MongoDB database, and use it to create a queue object:\n\n```js\nvar mongodb = require('mongodb')\nvar mongoDbQueue = require('mongodb-queue')\n\nconst url = 'mongodb://localhost:27017/'\nconst client = new mongodb.MongoClient(url, { useNewUrlParser: true })\n\nclient.connect(err => {\n  const db = client.db('test')\n  const queue = mongoDbQueue(db, 'my-queue')\n\n  // ...\n\n})\n```\n\nAdd a message to a queue:\n\n```js\nqueue.add('Hello, World!', (err, id) => {\n    // Message with payload 'Hello, World!' added.\n    // 'id' is returned, useful for logging.\n})\n```\n\nGet a message from the queue:\n\n```js\nqueue.get((err, msg) => {\n    console.log('msg.id=' + msg.id)\n    console.log('msg.ack=' + msg.ack)\n    console.log('msg.payload=' + msg.payload) // 'Hello, World!'\n    console.log('msg.tries=' + msg.tries)\n})\n```\n\nPing a message to keep it's visibility open for long-running tasks\n\n```js\nqueue.ping(msg.ack, (err, id) => {\n    // Visibility window now increased for this message id.\n    // 'id' is returned, useful for logging.\n})\n```\n\nAck a message (and remove it from the queue):\n\n```js\nqueue.ack(msg.ack, (err, id) => {\n    // This msg removed from queue for this ack.\n    // The 'id' of the message is returned, useful for logging.\n})\n```\n\nBy default, all old messages - even processed ones - are left in MongoDB. This is so that\nyou can go and analyse them if you want. However, you can call the following function\nto remove processed messages:\n\n```js\nqueue.clean((err) => {\n    // All processed (ie. acked) messages have been deleted\n})\n```\n\nAnd if you haven't already, you should call this to make sure indexes have\nbeen added in MongoDB. Of course, if you've called this once (in some kind\none-off script) you don't need to call it in your program. Of course, check\nthe changelock to see if you need to update them with new releases:\n\n```js\nqueue.createIndexes((err, indexName) => {\n    // The indexes needed have been added to MongoDB.\n})\n```\n\n## Creating a Queue ##\n\nTo create a queue, call the exported function with the `MongoClient`, the name\nand a set of opts. The MongoDB collection used is the same name as the name\npassed in:\n\n```\nvar mongoDbQueue = require('mongodb-queue')\n\n// an instance of a queue\nvar queue1 = mongoDbQueue(db, 'a-queue')\n// another queue which uses the same collection as above\nvar queue2 = mongoDbQueue(db, 'a-queue')\n```\n\nUsing `queue1` and `queue2` here won't interfere with each other and will play along nicely, but that's not\na good idea code-wise - just use the same object. This example is for illustrative purposes only.\n\nNote: Don't use the same queue name twice with different options, otherwise behaviour is undefined and again\nit's not something you should do.\n\nTo pass in options for the queue:\n\n```\nvar resizeQueue = mongoDbQueue(db, 'resize-queue', { visibility : 30, delay : 15 })\n```\n\nThis example shows a queue with a message visibility of 30s and a delay to each message of 15s.\n\n## Options ##\n\n### name ###\n\nThis is the name of the MongoDB Collection you wish to use to store the messages.\nEach queue you create will be it's own collection.\n\ne.g.\n\n```\nvar resizeImageQueue = mongoDbQueue(db, 'resize-image-queue')\nvar notifyOwnerQueue = mongoDbQueue(db, 'notify-owner-queue')\n```\n\nThis will create two collections in MongoDB called `resize-image-queue` and `notify-owner-queue`.\n\n### visibility - Message Visibility Window ###\n\nDefault: `30`\n\nBy default, if you don't ack a message within the first 30s after receiving it,\nit is placed back in the queue so it can be fetched again. This is called the\nvisibility window.\n\nYou may set this visibility window on a per queue basis. For example, to set the\nvisibility to 15 seconds:\n\n```\nvar queue = mongoDbQueue(db, 'queue', { visibility : 15 })\n```\n\nAll messages in this queue now have a visibility window of 15s, instead of the\ndefault 30s.\n\n### delay - Delay Messages on Queue ###\n\nDefault: `0`\n\nWhen a message is added to a queue, it is immediately available for retrieval.\nHowever, there are times when you might like to delay messages coming off a queue.\nie. if you set delay to be `10`, then every message will only be available for\nretrieval 10s after being added.\n\nTo delay all messages by 10 seconds, try this:\n\n```\nvar queue = mongoDbQueue(db, 'queue', { delay : 10 })\n```\n\nThis is now the default for every message added to the queue.\n\n### deadQueue - Dead Message Queue ###\n\nDefault: none\n\nMessages that have been retried over `maxRetries` will be pushed to this queue so you can\nautomatically see problem messages.\n\nPass in a queue (that you created) onto which these messages will be pushed:\n\n```js\nvar deadQueue = mongoDbQueue(db, 'dead-queue')\nvar queue = mongoDbQueue(db, 'queue', { deadQueue : deadQueue })\n```\n\nIf you pop a message off the `queue` over `maxRetries` times and still have not acked it,\nit will be pushed onto the `deadQueue` for you. This happens when you `.get()` (not when\nyou miss acking a message in it's visibility window). By doing it when you call `.get()`,\nthe unprocessed message will be received, pushed to the `deadQueue`, acked off the normal\nqueue and `.get()` will check for new messages prior to returning you one (or none).\n\n### maxRetries - Maximum Retries per Message ###\n\nDefault: 5\n\nThis option only comes into effect if you pass in a `deadQueue` as shown above. What this\nmeans is that if an item is popped off the queue `maxRetries` times (e.g. 5) and not acked,\nit will be moved to this `deadQueue` the next time it is tried to pop off. You can poll your\n`deadQueue` for dead messages much like you can poll your regular queues.\n\nThe payload of the messages in the dead queue are the entire messages returned when `.get()`ing\nthem from the original queue.\n\ne.g.\n\nGiven this message:\n\n```\nmsg = {\n  id: '533b1eb64ee78a57664cc76c',\n  ack: 'c8a3cc585cbaaacf549d746d7db72f69',\n  payload: 'Hello, World!',\n  tries: 1\n}\n```\n\nIf it is not acked within the `maxRetries` times, then when you receive this same message\nfrom the `deadQueue`, it may look like this:\n\n```\nmsg = {\n  id: '533b1ecf3ca3a76b667671ef',\n  ack: '73872b204e3f7be84050a1ce82c5c9c0',\n  payload: {\n    id: '533b1eb64ee78a57664cc76c',\n    ack: 'c8a3cc585cbaaacf549d746d7db72f69',\n    payload: 'Hello, World!',\n    tries: 5\n  },\n  tries: 1\n}\n```\n\nNotice that the payload from the `deadQueue` is exactly the same as the original message\nwhen it was on the original queue (except with the number of tries set to 5).\n\n## Operations ##\n\n### .add() ###\n\nYou can add a string to the queue:\n\n```js\nqueue.add('Hello, World!', (err, id) => {\n    // Message with payload 'Hello, World!' added.\n    // 'id' is returned, useful for logging.\n})\n```\n\nOr add an object of your choosing:\n\n```js\nqueue.add({ err: 'E_BORKED', msg: 'Broken' }, (err, id) => {\n    // Message with payload { err: 'E_BORKED', msg: 'Broken' } added.\n    // 'id' is returned, useful for logging.\n})\n```\n\nOr add multiple messages:\n\n```js\nqueue.add(['msg1', 'msg2', 'msg3'], (err, ids) => {\n    // Messages with payloads 'msg1', 'msg2' & 'msg3' added.\n    // All 'id's are returned as an array, useful for logging.\n})\n```\n\nYou can delay individual messages from being visible by passing the `delay` option:\n\n```js\nqueue.add('Later', { delay: 120 }, (err, id) => {\n    // Message with payload 'Later' added.\n    // 'id' is returned, useful for logging.\n    // This message won't be available for getting for 2 mins.\n})\n```\n\n### .get() ###\n\nRetrieve a message from the queue:\n\n```js\nqueue.get((err, msg) => {\n    // You can now process the message\n    // IMPORTANT: The callback will not wait for an message if the queue is empty.  The message will be undefined if the queue is empty.\n})\n```\n\nYou can choose the visibility of an individual retrieved message by passing the `visibility` option:\n\n```js\nqueue.get({ visibility: 10 }, (err, msg) => {\n    // You can now process the message for 10s before it goes back into the queue if not ack'd instead of the duration that is set on the queue in general\n})\n```\n\nMessage will have the following structure:\n\n```js\n{\n  id: '533b1eb64ee78a57664cc76c', // ID of the message\n  ack: 'c8a3cc585cbaaacf549d746d7db72f69', // ID for ack and ping operations\n  payload: 'Hello, World!', // Payload passed when the message was addded\n  tries: 1 // Number of times this message has been retrieved from queue without being ack'd\n}\n```\n\n### .ack() ###\n\nAfter you have received an item from a queue and processed it, you can delete it\nby calling `.ack()` with the unique `ackId` returned:\n\n```js\nqueue.get((err, msg) => {\n    queue.ack(msg.ack, (err, id) => {\n        // this message has now been removed from the queue\n    })\n})\n```\n\n### .ping() ###\n\nAfter you have received an item from a queue and you are taking a while\nto process it, you can `.ping()` the message to tell the queue that you are\nstill alive and continuing to process the message:\n\n```js\nqueue.get((err, msg) => {\n    queue.ping(msg.ack, (err, id) => {\n        // this message has had it's visibility window extended\n    })\n})\n```\n\nYou can also choose the visibility time that gets added by the ping operation by passing the `visibility` option:\n\n```js\nqueue.get((err, msg) => {\n    queue.ping(msg.ack, { visibility: 10 }, (err, id) => {\n        // this message has had it's visibility window extended by 10s instead of the visibilty set on the queue in general\n    })\n})\n```\n\n### .total() ###\n\nReturns the total number of messages that has ever been in the queue, including\nall current messages:\n\n```js\nqueue.total((err, count) => {\n    console.log('This queue has seen %d messages', count)\n})\n```\n\n### .size() ###\n\nReturns the total number of messages that are waiting in the queue.\n\n```js\nqueue.size((err, count) => {\n    console.log('This queue has %d current messages', count)\n})\n```\n\n### .inFlight() ###\n\nReturns the total number of messages that are currently in flight. ie. that\nhave been received but not yet acked:\n\n```js\nqueue.inFlight((err, count) => {\n    console.log('A total of %d messages are currently being processed', count)\n})\n```\n\n### .done() ###\n\nReturns the total number of messages that have been processed correctly in the\nqueue:\n\n```js\nqueue.done((err, count) => {\n    console.log('This queue has processed %d messages', count)\n})\n```\n\n### .clean() ###\n\nDeletes all processed mesages from the queue. Of course, you can leave these hanging around\nif you wish, but delete them if you no longer need them. Perhaps do this using `setInterval`\nfor a regular cleaning:\n\n```js\nqueue.clean((err) => {\n    console.log('The processed messages have been deleted from the queue')\n})\n```\n\n### Notes about Numbers ###\n\nIf you add up `.size() + .inFlight() + .done()` then you should get `.total()`\nbut this will only be approximate since these are different operations hitting the database\nat slightly different times. Hence, a message or two might be counted twice or not at all\ndepending on message turnover at any one time. You should not rely on these numbers for\nanything but are included as approximations at any point in time.\n\n## Use of MongoDB ##\n\nWhilst using MongoDB recently and having a need for lightweight queues, I realised\nthat the atomic operations that MongoDB provides are ideal for this kind of job.\n\nSince everything it atomic, it is impossible to lose messages in or around your\napplication. I guess MongoDB could lose them but it's a safer bet it won't compared\nto your own application.\n\nAs an example of the atomic nature being used, messages stay in the same collection\nand are never moved around or deleted, just a couple of fields are set, incremented\nor deleted. We always use MongoDB's excellent `collection.findAndModify()` so that\neach message is updated atomically inside MongoDB and we never have to fetch something,\nchange it and store it back.\n\n## Roadmap ##\n\nWe may add the ability for each function to return a promise in the future so it can be used as such, or with\nasync/await.\n\n## Releases ##\n\n### 4.0.0 (2019-02-20) ###\n\n* [NEW] Updated entire codebase to be compatible with the mongodb driver v3\n\n### 2.1.0 (2016-04-21) ###\n\n* [FIX] Fix to indexes (thanks https://github.com/ifightcrime) when lots of messages\n\n### 2.0.0 (2014-11-12) ###\n\n* [NEW] Update MongoDB API from v1 to v2 (thanks https://github.com/hanwencheng)\n\n### 1.0.1 (2015-05-25) ###\n\n* [NEW] Test changes only\n\n### 1.0.0 (2014-10-30) ###\n\n* [NEW] Ability to specify a visibility window when getting a message (thanks https://github.com/Gertt)\n\n### 0.9.1 (2014-08-28) ###\n\n* [NEW] Added .clean() method to remove old (processed) messages\n* [NEW] Add 'delay' option to queue.add() so individual messages can be delayed separately\n* [TEST] Test individual 'delay' option for each message\n\n### 0.7.0 (2014-03-24) ###\n\n* [FIX] Fix .ping() so only visible/non-deleted messages can be pinged\n* [FIX] Fix .ack() so only visible/non-deleted messages can be pinged\n* [TEST] Add test to make sure messages can't be acked twice\n* [TEST] Add test to make sure an acked message can't be pinged\n* [INTERNAL] Slight function name changes, nicer date routines\n\n### 0.6.0 (2014-03-22) ###\n\n* [NEW] The msg.id is now returned on successful Queue.ping() and Queue.ack() calls\n* [NEW] Call quueue.ensureIndexes(callback) to create them\n* [CHANGE] When a message is acked, 'deleted' is now set to the current time (not true)\n* [CHANGE] The queue is now created synchronously\n\n### 0.5.0 (2014-03-21) ###\n\n* [NEW] Now adds two indexes onto the MongoDB collection used for the message\n* [CHANGE] The queue is now created by calling the async exported function\n* [DOC] Update to show how the queues are now created\n\n### 0.4.0 (2014-03-20) ###\n\n* [NEW] Ability to ping retrieved messages a. la. 'still alive' and 'extend visibility'\n* [CHANGE] Removed ability to have different queues in the same collection\n* [CHANGE] All queues are now stored in their own collection\n* [CHANGE] When acking a message, only need ack (no longer need id)\n* [TEST] Added test for pinged messages\n* [DOC] Update to specify each queue will create it's own MongoDB collection\n* [DOC] Added docs for option `delay`\n* [DOC] Added synopsis for Queue.ping()\n* [DOC] Removed use of msg.id when calling Queue.ack()\n\n### 0.3.1 (2014-03-19) ###\n\n* [DOC] Added documentation for the `delay` option\n\n### 0.3.0 (2014-03-19) ###\n\n* [NEW] Return the message id when added to a queue\n* [NEW] Ability to set a default delay on all messages in a queue\n* [FIX] Make sure old messages (outside of visibility window) aren't deleted when acked\n* [FIX] Internal: Fix `queueName`\n* [TEST] Added test for multiple messages\n* [TEST] Added test for delayed messages\n\n### 0.2.1 (2014-03-19) ###\n\n* [FIX] Fix when getting messages off an empty queue\n* [NEW] More Tests\n\n### 0.2.0 (2014-03-18) ###\n\n* [NEW] messages now return number of tries (times they have been fetched)\n\n### 0.1.0 (2014-03-18) ###\n\n* [NEW] add messages to queues\n* [NEW] fetch messages from queues\n* [NEW] ack messages on queues\n* [NEW] set up multiple queues\n* [NEW] set your own MongoDB Collection name\n* [NEW] set a visibility timeout on a queue\n\n## Author ##\n\n```\n$ npx chilts\n\n   ╒════════════════════════════════════════════════════╕\n   │                                                    │\n   │   Andrew Chilton (Personal)                        │\n   │   -------------------------                        │\n   │                                                    │\n   │          Email : andychilton@gmail.com             │\n   │            Web : https://chilts.org                │\n   │        Twitter : https://twitter.com/andychilton   │\n   │         GitHub : https://github.com/chilts         │\n   │         GitLab : https://gitlab.org/chilts         │\n   │                                                    │\n   │   Apps Attic Ltd (My Company)                      │\n   │   ---------------------------                      │\n   │                                                    │\n   │          Email : chilts@appsattic.com              │\n   │            Web : https://appsattic.com             │\n   │        Twitter : https://twitter.com/AppsAttic     │\n   │         GitLab : https://gitlab.com/appsattic      │\n   │                                                    │\n   │   Node.js / npm                                    │\n   │   -------------                                    │\n   │                                                    │\n   │        Profile : https://www.npmjs.com/~chilts     │\n   │           Card : $ npx chilts                      │\n   │                                                    │\n   ╘════════════════════════════════════════════════════╛\n```\n\n## License ##\n\nMIT - http://chilts.mit-license.org/2014/\n\n(Ends)\n"
  },
  {
    "path": "mongodb-queue.js",
    "content": "/**\n *\n * mongodb-queue.js - Use your existing MongoDB as a local queue.\n *\n * Copyright (c) 2014 Andrew Chilton\n * - http://chilts.org/\n * - andychilton@gmail.com\n *\n * License: http://chilts.mit-license.org/2014/\n *\n **/\n\nvar crypto = require('crypto')\n\n// some helper functions\nfunction id() {\n    return crypto.randomBytes(16).toString('hex')\n}\n\nfunction now() {\n    return (new Date()).toISOString()\n}\n\nfunction nowPlusSecs(secs) {\n    return (new Date(Date.now() + secs * 1000)).toISOString()\n}\n\nmodule.exports = function(db, name, opts) {\n    return new Queue(db, name, opts)\n}\n\n// the Queue object itself\nfunction Queue(db, name, opts) {\n    if ( !db ) {\n        throw new Error(\"mongodb-queue: provide a mongodb.MongoClient.db\")\n    }\n    if ( !name ) {\n        throw new Error(\"mongodb-queue: provide a queue name\")\n    }\n    opts = opts || {}\n\n    this.db = db\n    this.name = name\n    this.col = db.collection(name)\n    this.visibility = opts.visibility || 30\n    this.delay = opts.delay || 0\n\n    if ( opts.deadQueue ) {\n        this.deadQueue = opts.deadQueue\n        this.maxRetries = opts.maxRetries || 5\n    }\n}\n\nQueue.prototype.createIndexes = function(callback) {\n    var self = this\n\n    self.col.createIndex({ deleted : 1, visible : 1 }, function(err, indexname) {\n        if (err) return callback(err)\n        self.col.createIndex({ ack : 1 }, { unique : true, sparse : true }, function(err) {\n            if (err) return callback(err)\n            callback(null, indexname)\n        })\n    })\n}\n\nQueue.prototype.add = function(payload, opts, callback) {\n    var self = this\n    if ( !callback ) {\n        callback = opts\n        opts = {}\n    }\n    var delay = opts.delay || self.delay\n    var visible = delay ? (delay instanceof Date ? delay.toISOString() : nowPlusSecs(delay)) : now()\n\n    var msgs = []\n    if (payload instanceof Array) {\n        if (payload.length === 0) {\n            var errMsg = 'Queue.add(): Array payload length must be greater than 0'\n            return callback(new Error(errMsg))\n        }\n        payload.forEach(function(payload) {\n            msgs.push({\n                visible  : visible,\n                payload  : payload,\n            })\n        })\n    } else {\n        msgs.push({\n            visible  : visible,\n            payload  : payload,\n        })\n    }\n\n    self.col.insertMany(msgs, function(err, results) {\n        if (err) return callback(err);\n        if (payload instanceof Array) return callback(null, '' + results.insertedIds);\n        callback(null, '' + results.insertedIds[\"0\"]);\n    })\n}\n\nQueue.prototype.get = function(opts, callback) {\n    var self = this\n    if ( !callback ) {\n        callback = opts\n        opts = {}\n    }\n\n    var visibility = opts.visibility || self.visibility\n    var query = {\n        deleted : null,\n        visible : { $lte : now() },\n    }\n    var sort = {\n        _id : 1\n    }\n    var update = {\n        $inc : { tries : 1 },\n        $set : {\n            ack     : id(),\n            visible : nowPlusSecs(visibility),\n        }\n    }\n\n    self.col.findOneAndUpdate(query, update, { sort: sort, returnDocument : 'after' }, function(err, result) {\n        if (err){\n            return callback(err);\n        }\n\n        var msg = result.value\n        if (!msg) return callback()\n\n        // convert to an external representation\n        msg = {\n            // convert '_id' to an 'id' string\n            id      : '' + msg._id,\n            ack     : msg.ack,\n            payload : msg.payload,\n            tries   : msg.tries,\n        }\n        // if we have a deadQueue, then check the tries, else don't\n        if ( self.deadQueue ) {\n            // check the tries\n            if ( msg.tries > self.maxRetries ) {\n                // So:\n                // 1) add this message to the deadQueue\n                // 2) ack this message from the regular queue\n                // 3) call ourself to return a new message (if exists)\n                self.deadQueue.add(msg, function(err) {\n                    if (err) return callback(err)\n                    self.ack(msg.ack, function(err) {\n                        if (err) return callback(err)\n                        self.get(callback)\n                    })\n                })\n                return\n            }\n        }\n        callback(null, msg)\n    })\n}\n\nQueue.prototype.ping = function(ack, opts, callback) {\n    var self = this\n    if ( !callback ) {\n        callback = opts\n        opts = {}\n    }\n\n    var visibility = opts.visibility || self.visibility\n    var query = {\n        ack     : ack,\n        visible : { $gt : now() },\n        deleted : null,\n    }\n    var update = {\n        $set : {\n            visible : nowPlusSecs(visibility)\n        }\n    }\n    self.col.findOneAndUpdate(query, update, { returnDocument : 'after' }, function(err, msg, blah) {\n        if (err) return callback(err)\n        if ( !msg.value ) {\n            return callback(new Error(\"Queue.ping(): Unidentified ack  : \" + ack))\n        }\n        callback(null, '' + msg.value._id)\n    })\n}\n\nQueue.prototype.ack = function(ack, callback) {\n    var self = this\n\n    var query = {\n        ack     : ack,\n        visible : { $gt : now() },\n        deleted : null,\n    }\n    var update = {\n        $set : {\n            deleted : now(),\n        }\n    }\n\n    self.col.findOneAndUpdate(query, update, { returnDocument : 'after' }, function(err, msg, blah) {\n        if (err) return callback(err)\n        if ( !msg.value ) {\n            return callback(new Error(\"Queue.ack(): Unidentified ack : \" + ack))\n        }\n        callback(null, '' + msg.value._id)\n    })\n}\n\nQueue.prototype.clean = function(callback) {\n    var self = this\n\n    var query = {\n        deleted : { $exists : true },\n    }\n\n    self.col.deleteMany(query, callback)\n}\n\nQueue.prototype.total = function(callback) {\n    var self = this\n\n    self.col.countDocuments(function(err, count) {\n        if (err) return callback(err)\n        callback(null, count)\n    })\n}\n\nQueue.prototype.size = function(callback) {\n    var self = this\n\n    var query = {\n        deleted : null,\n        visible : { $lte : now() },\n    }\n\n    self.col.countDocuments(query, function(err, count) {\n        if (err) return callback(err)\n        callback(null, count)\n    })\n}\n\nQueue.prototype.inFlight = function(callback) {\n    var self = this\n\n    var query = {\n        ack     : { $exists : true },\n        visible : { $gt : now() },\n        deleted : null,\n    }\n\n    self.col.countDocuments(query, function(err, count) {\n        if (err) return callback(err)\n        callback(null, count)\n    })\n}\n\nQueue.prototype.done = function(callback) {\n    var self = this\n\n    var query = {\n        deleted : { $exists : true },\n    }\n\n    self.col.countDocuments(query, function(err, count) {\n        if (err) return callback(err)\n        callback(null, count)\n    })\n}\n"
  },
  {
    "path": "package.json",
    "content": "{\n  \"name\": \"mongodb-queue\",\n  \"version\": \"5.0.0\",\n  \"description\": \"Message queues which uses MongoDB.\",\n  \"main\": \"mongodb-queue.js\",\n  \"scripts\": {\n    \"test\": \"set -e; for FILE in test/*.js; do echo --- $FILE ---; node $FILE; done\"\n  },\n  \"dependencies\": {},\n  \"devDependencies\": {\n    \"async\": \"^2.6.2\",\n    \"mongodb\": \"^4.0.0\",\n    \"tape\": \"^4.10.1\"\n  },\n  \"homepage\": \"https://github.com/chilts/mongodb-queue\",\n  \"repository\": {\n    \"type\": \"git\",\n    \"url\": \"git://github.com/chilts/mongodb-queue.git\"\n  },\n  \"bugs\": {\n    \"url\": \"http://github.com/chilts/mongodb-queue/issues\",\n    \"mail\": \"andychilton@gmail.com\"\n  },\n  \"author\": {\n    \"name\": \"Andrew Chilton\",\n    \"email\": \"andychilton@gmail.com\",\n    \"url\": \"http://chilts.org/\"\n  },\n  \"license\": \"MIT\",\n  \"keywords\": [\n    \"mongodb\",\n    \"queue\"\n  ]\n}\n"
  },
  {
    "path": "test/clean.js",
    "content": "var async = require('async')\nvar test = require('tape')\n\nvar setup = require('./setup.js')\nvar mongoDbQueue = require('../')\n\nsetup(function(client, db) {\n\n    test('clean: check deleted messages are deleted', function(t) {\n        var queue = mongoDbQueue(db, 'clean', { visibility : 3 })\n        var msg\n\n        async.series(\n            [\n                function(next) {\n                    queue.size(function(err, size) {\n                        t.ok(!err, 'There is no error.')\n                        t.equal(size, 0, 'There is currently nothing on the queue')\n                        next()\n                    })\n                },\n                function(next) {\n                    queue.total(function(err, size) {\n                        t.ok(!err, 'There is no error.')\n                        t.equal(size, 0, 'There is currently nothing in the queue at all')\n                        next()\n                    })\n                },\n                function(next) {\n                    queue.clean(function(err) {\n                        t.ok(!err, 'There is no error.')\n                        next()\n                    })\n                },\n                function(next) {\n                    queue.size(function(err, size) {\n                        t.ok(!err, 'There is no error.')\n                        t.equal(size, 0, 'There is currently nothing on the queue')\n                        next()\n                    })\n                },\n                function(next) {\n                    queue.total(function(err, size) {\n                        t.ok(!err, 'There is no error.')\n                        t.equal(size, 0, 'There is currently nothing in the queue at all')\n                        next()\n                    })\n                },\n                function(next) {\n                    queue.add('Hello, World!', function(err) {\n                        t.ok(!err, 'There is no error when adding a message.')\n                        next()\n                    })\n                },\n                function(next) {\n                    queue.clean(function(err) {\n                        t.ok(!err, 'There is no error.')\n                        next()\n                    })\n                },\n                function(next) {\n                    queue.size(function(err, size) {\n                        t.ok(!err, 'There is no error.')\n                        t.equal(size, 1, 'Queue size is correct')\n                        next()\n                    })\n                },\n                function(next) {\n                    queue.total(function(err, size) {\n                        t.ok(!err, 'There is no error.')\n                        t.equal(size, 1, 'Queue total is correct')\n                        next()\n                    })\n                },\n                function(next) {\n                    queue.get(function(err, newMsg) {\n                        msg = newMsg\n                        t.ok(msg.id, 'Got a msg.id (sanity check)')\n                        next()\n                    })\n                },\n                function(next) {\n                    queue.size(function(err, size) {\n                        t.ok(!err, 'There is no error.')\n                        t.equal(size, 0, 'Queue size is correct')\n                        next()\n                    })\n                },\n                function(next) {\n                    queue.total(function(err, size) {\n                        t.ok(!err, 'There is no error.')\n                        t.equal(size, 1, 'Queue total is correct')\n                        next()\n                    })\n                },\n                function(next) {\n                    queue.clean(function(err) {\n                        t.ok(!err, 'There is no error.')\n                        next()\n                    })\n                },\n                function(next) {\n                    queue.size(function(err, size) {\n                        t.ok(!err, 'There is no error.')\n                        t.equal(size, 0, 'Queue size is correct')\n                        next()\n                    })\n                },\n                function(next) {\n                    queue.total(function(err, size) {\n                        t.ok(!err, 'There is no error.')\n                        t.equal(size, 1, 'Queue total is correct')\n                        next()\n                    })\n                },\n                function(next) {\n                    queue.ack(msg.ack, function(err, id) {\n                        t.ok(!err, 'No error when acking the message')\n                        t.ok(id, 'Received an id when acking this message')\n                        next()\n                    })\n                },\n                function(next) {\n                    queue.size(function(err, size) {\n                        t.ok(!err, 'There is no error.')\n                        t.equal(size, 0, 'Queue size is correct')\n                        next()\n                    })\n                },\n                function(next) {\n                    queue.total(function(err, size) {\n                        t.ok(!err, 'There is no error.')\n                        t.equal(size, 1, 'Queue total is correct')\n                        next()\n                    })\n                },\n                function(next) {\n                    queue.clean(function(err) {\n                        t.ok(!err, 'There is no error.')\n                        next()\n                    })\n                },\n                function(next) {\n                    queue.size(function(err, size) {\n                        t.ok(!err, 'There is no error.')\n                        t.equal(size, 0, 'Queue size is correct')\n                        next()\n                    })\n                },\n                function(next) {\n                  queue.total(function(err, size) {\n                    t.ok(!err, 'There is no error.')\n                    t.equal(size, 0, 'Queue total is correct')\n                    next()\n                  })\n                },\n            ],\n            function(err) {\n                if (err) t.fail(err)\n                t.pass('Finished test ok')\n                t.end()\n            }\n        )\n    })\n\n    test('client.close()', function(t) {\n        t.pass('client.close()')\n        client.close()\n        t.end()\n    })\n\n})\n"
  },
  {
    "path": "test/dead-queue.js",
    "content": "var async = require('async')\nvar test = require('tape')\n\nvar setup = require('./setup.js')\nvar mongoDbQueue = require('../')\n\nsetup(function(client, db) {\n\n    test('first test', function(t) {\n        var queue = mongoDbQueue(db, 'queue', { visibility : 3, deadQueue : 'dead-queue' })\n        t.ok(queue, 'Queue created ok')\n        t.end()\n    });\n\n    test('single message going over 5 tries, should appear on dead-queue', function(t) {\n        var deadQueue = mongoDbQueue(db, 'dead-queue')\n        var queue = mongoDbQueue(db, 'queue', { visibility : 1, deadQueue : deadQueue })\n        var msg\n        var origId\n\n        async.series(\n            [\n                function(next) {\n                    queue.add('Hello, World!', function(err, id) {\n                        t.ok(!err, 'There is no error when adding a message.')\n                        t.ok(id, 'Received an id for this message')\n                        origId = id\n                        next()\n                    })\n                },\n                function(next) {\n                    queue.get(function(err, thisMsg) {\n                        setTimeout(function() {\n                            t.pass('First expiration')\n                            next()\n                        }, 2 * 1000)\n                    })\n                },\n                function(next) {\n                    queue.get(function(err, thisMsg) {\n                        setTimeout(function() {\n                            t.pass('Second expiration')\n                            next()\n                        }, 2 * 1000)\n                    })\n                },\n                function(next) {\n                    queue.get(function(err, thisMsg) {\n                        setTimeout(function() {\n                            t.pass('Third expiration')\n                            next()\n                        }, 2 * 1000)\n                    })\n                },\n                function(next) {\n                    queue.get(function(err, thisMsg) {\n                        setTimeout(function() {\n                            t.pass('Fourth expiration')\n                            next()\n                        }, 2 * 1000)\n                    })\n                },\n                function(next) {\n                    queue.get(function(err, thisMsg) {\n                        setTimeout(function() {\n                            t.pass('Fifth expiration')\n                            next()\n                        }, 2 * 1000)\n                    })\n                },\n                function(next) {\n                    queue.get(function(err, id) {\n                        t.ok(!err, 'No error when getting no messages')\n                        t.ok(!msg, 'No msg received')\n                        next()\n                    })\n                },\n                function(next) {\n                    deadQueue.get(function(err, msg) {\n                        t.ok(!err, 'No error when getting from the deadQueue')\n                        t.ok(msg.id, 'Got a message id from the deadQueue')\n                        t.equal(msg.payload.id, origId, 'Got the same message id as the original message')\n                        t.equal(msg.payload.payload, 'Hello, World!', 'Got the same as the original message')\n                        t.equal(msg.payload.tries, 6, 'Got the tries as 6')\n                        next()\n                    })\n                },\n            ],\n            function(err) {\n                t.ok(!err, 'No error during single round-trip test')\n                t.end()\n            }\n        )\n    })\n\n    test('two messages, with first going over 3 tries', function(t) {\n        var deadQueue = mongoDbQueue(db, 'dead-queue-2')\n        var queue = mongoDbQueue(db, 'queue-2', { visibility : 1, deadQueue : deadQueue, maxRetries : 3 })\n        var msg\n        var origId, origId2\n\n        async.series(\n            [\n                function(next) {\n                    queue.add('Hello, World!', function(err, id) {\n                        t.ok(!err, 'There is no error when adding a message.')\n                        t.ok(id, 'Received an id for this message')\n                        origId = id\n                        next()\n                    })\n                },\n                function(next) {\n                    queue.add('Part II', function(err, id) {\n                        t.ok(!err, 'There is no error when adding another message.')\n                        t.ok(id, 'Received an id for this message')\n                        origId2 = id\n                        next()\n                    })\n                },\n                function(next) {\n                    queue.get(function(err, thisMsg) {\n                        t.equal(thisMsg.id, origId, 'We return the first message on first go')\n                        setTimeout(function() {\n                            t.pass('First expiration')\n                            next()\n                        }, 2 * 1000)\n                    })\n                },\n                function(next) {\n                    queue.get(function(err, thisMsg) {\n                        t.equal(thisMsg.id, origId, 'We return the first message on second go')\n                        setTimeout(function() {\n                            t.pass('Second expiration')\n                            next()\n                        }, 2 * 1000)\n                    })\n                },\n                function(next) {\n                    queue.get(function(err, thisMsg) {\n                        t.equal(thisMsg.id, origId, 'We return the first message on third go')\n                        setTimeout(function() {\n                            t.pass('Third expiration')\n                            next()\n                        }, 2 * 1000)\n                    })\n                },\n                function(next) {\n                    // This is the 4th time, so we SHOULD have moved it to the dead queue\n                    // pior to it being returned.\n                    queue.get(function(err, msg) {\n                        t.ok(!err, 'No error when getting the 2nd message')\n                        t.equal(msg.id, origId2, 'Got the ID of the 2nd message')\n                        t.equal(msg.payload, 'Part II', 'Got the same payload as the 2nd message')\n                        next()\n                    })\n                },\n                function(next) {\n                    deadQueue.get(function(err, msg) {\n                        t.ok(!err, 'No error when getting from the deadQueue')\n                        t.ok(msg.id, 'Got a message id from the deadQueue')\n                        t.equal(msg.payload.id, origId, 'Got the same message id as the original message')\n                        t.equal(msg.payload.payload, 'Hello, World!', 'Got the same as the original message')\n                        t.equal(msg.payload.tries, 4, 'Got the tries as 4')\n                        next()\n                    })\n                },\n            ],\n            function(err) {\n                t.ok(!err, 'No error during single round-trip test')\n                t.end()\n            }\n        )\n    })\n\n    test('client.close()', function(t) {\n        t.pass('client.close()')\n        client.close()\n        t.end()\n    })\n\n})\n"
  },
  {
    "path": "test/default.js",
    "content": "var async = require('async')\nvar test = require('tape')\n\nvar setup = require('./setup.js')\nvar mongoDbQueue = require('../')\n\nsetup(function(client, db) {\n\n    test('first test', function(t) {\n        var queue = mongoDbQueue(db, 'default')\n        t.ok(queue, 'Queue created ok')\n        t.end()\n    });\n\n    test('single round trip', function(t) {\n        var queue = mongoDbQueue(db, 'default')\n        var msg\n\n        async.series(\n            [\n                function(next) {\n                    queue.add('Hello, World!', function(err, id) {\n                        t.ok(!err, 'There is no error when adding a message.')\n                        t.ok(id, 'Received an id for this message')\n                        next()\n                    })\n                },\n                function(next) {\n                    queue.get(function(err, thisMsg) {\n                        console.log(thisMsg)\n                        msg = thisMsg\n                        t.ok(msg.id, 'Got a msg.id')\n                        t.equal(typeof msg.id, 'string', 'msg.id is a string')\n                        t.ok(msg.ack, 'Got a msg.ack')\n                        t.equal(typeof msg.ack, 'string', 'msg.ack is a string')\n                        t.ok(msg.tries, 'Got a msg.tries')\n                        t.equal(typeof msg.tries, 'number', 'msg.tries is a number')\n                        t.equal(msg.tries, 1, 'msg.tries is currently one')\n                        t.equal(msg.payload, 'Hello, World!', 'Payload is correct')\n                        next()\n                    })\n                },\n                function(next) {\n                    queue.ack(msg.ack, function(err, id) {\n                        t.ok(!err, 'No error when acking the message')\n                        t.ok(id, 'Received an id when acking this message')\n                        next()\n                    })\n                },\n            ],\n            function(err) {\n                t.ok(!err, 'No error during single round-trip test')\n                t.end()\n            }\n        )\n    })\n\n    test(\"single round trip, can't be acked again\", function(t) {\n        var queue = mongoDbQueue(db, 'default')\n        var msg\n\n        async.series(\n            [\n                function(next) {\n                    queue.add('Hello, World!', function(err, id) {\n                        t.ok(!err, 'There is no error when adding a message.')\n                        t.ok(id, 'Received an id for this message')\n                        next()\n                    })\n                },\n                function(next) {\n                    queue.get(function(err, thisMsg) {\n                        msg = thisMsg\n                        t.ok(msg.id, 'Got a msg.id')\n                        t.equal(typeof msg.id, 'string', 'msg.id is a string')\n                        t.ok(msg.ack, 'Got a msg.ack')\n                        t.equal(typeof msg.ack, 'string', 'msg.ack is a string')\n                        t.ok(msg.tries, 'Got a msg.tries')\n                        t.equal(typeof msg.tries, 'number', 'msg.tries is a number')\n                        t.equal(msg.tries, 1, 'msg.tries is currently one')\n                        t.equal(msg.payload, 'Hello, World!', 'Payload is correct')\n                        next()\n                    })\n                },\n                function(next) {\n                    queue.ack(msg.ack, function(err, id) {\n                        t.ok(!err, 'No error when acking the message')\n                        t.ok(id, 'Received an id when acking this message')\n                        next()\n                    })\n                },\n                function(next) {\n                    queue.ack(msg.ack, function(err, id) {\n                        t.ok(err, 'There is an error when acking the message again')\n                        t.ok(!id, 'No id received when trying to ack an already deleted message')\n                        next()\n                    })\n                },\n            ],\n            function(err) {\n                t.ok(!err, 'No error during single round-trip when trying to double ack')\n                t.end()\n            }\n        )\n    })\n\n    test('client.close()', function(t) {\n        t.pass('client.close()')\n        client.close()\n        t.end()\n    })\n\n})\n"
  },
  {
    "path": "test/delay.js",
    "content": "var async = require('async')\nvar test = require('tape')\n\nvar setup = require('./setup.js')\nvar mongoDbQueue = require('../')\n\nsetup(function(client, db) {\n\n    test('delay: check messages on this queue are returned after the delay', function(t) {\n        var queue = mongoDbQueue(db, 'delay', { delay : 3 })\n\n        async.series(\n            [\n                function(next) {\n                    queue.add('Hello, World!', function(err, id) {\n                        t.ok(!err, 'There is no error when adding a message.')\n                        t.ok(id, 'There is an id returned when adding a message.')\n                        next()\n                    })\n                },\n                function(next) {\n                    // get something now and it shouldn't be there\n                    queue.get(function(err, msg) {\n                        t.ok(!err, 'No error when getting no messages')\n                        t.ok(!msg, 'No msg received')\n                        // now wait 4s\n                        setTimeout(next, 4 * 1000)\n                    })\n                },\n                function(next) {\n                    // get something now and it SHOULD be there\n                    queue.get(function(err, msg) {\n                        t.ok(!err, 'No error when getting a message')\n                        t.ok(msg.id, 'Got a message id now that the message delay has passed')\n                        queue.ack(msg.ack, next)\n                    })\n                },\n                function(next) {\n                    queue.get(function(err, msg) {\n                        // no more messages\n                        t.ok(!err, 'No error when getting no messages')\n                        t.ok(!msg, 'No more messages')\n                        next()\n                    })\n                },\n            ],\n            function(err) {\n                if (err) t.fail(err)\n                t.pass('Finished test ok')\n                t.end()\n            }\n        )\n    })\n\n    test('delay: check an individual message delay overrides the queue delay', function(t) {\n        var queue = mongoDbQueue(db, 'delay')\n\n        async.series(\n            [\n                function(next) {\n                  queue.add('I am delayed by 3 seconds', { delay : 3 }, function(err, id) {\n                        t.ok(!err, 'There is no error when adding a message.')\n                        t.ok(id, 'There is an id returned when adding a message.')\n                        next()\n                    })\n                },\n                function(next) {\n                    // get something now and it shouldn't be there\n                    queue.get(function(err, msg) {\n                        t.ok(!err, 'No error when getting no messages')\n                        t.ok(!msg, 'No msg received')\n                        // now wait 4s\n                        setTimeout(next, 4 * 1000)\n                    })\n                },\n                function(next) {\n                    // get something now and it SHOULD be there\n                    queue.get(function(err, msg) {\n                        t.ok(!err, 'No error when getting a message')\n                        t.ok(msg.id, 'Got a message id now that the message delay has passed')\n                        queue.ack(msg.ack, next)\n                    })\n                },\n                function(next) {\n                    queue.get(function(err, msg) {\n                        // no more messages\n                        t.ok(!err, 'No error when getting no messages')\n                        t.ok(!msg, 'No more messages')\n                        next()\n                    })\n                },\n            ],\n            function(err) {\n                if (err) t.fail(err)\n                t.pass('Finished test ok')\n                t.end()\n            }\n        )\n    })\n\n    test('client.close()', function(t) {\n        t.pass('client.close()')\n        client.close()\n        t.end()\n    })\n\n})\n"
  },
  {
    "path": "test/indexes.js",
    "content": "var async = require('async')\nvar test = require('tape')\n\nvar setup = require('./setup.js')\nvar mongoDbQueue = require('../')\n\nsetup(function(client, db) {\n\n    test('visibility: check message is back in queue after 3s', function(t) {\n        t.plan(2)\n\n        var queue = mongoDbQueue(db, 'visibility', { visibility : 3 })\n\n        queue.createIndexes(function(err, indexName) {\n            t.ok(!err, 'There was no error when running .ensureIndexes()')\n            t.ok(indexName, 'receive indexName we created')\n            t.end()\n        })\n    })\n\n    test('client.close()', function(t) {\n        t.pass('client.close()')\n        client.close()\n        t.end()\n    })\n\n})\n"
  },
  {
    "path": "test/many.js",
    "content": "var async = require('async')\nvar test = require('tape')\n\nvar setup = require('./setup.js')\nvar mongoDbQueue = require('../')\n\nvar total = 250\n\nsetup(function(client, db) {\n\n    test('many: add ' + total + ' messages, get ' + total + ' back', function(t) {\n        var queue = mongoDbQueue(db, 'many')\n        var msgs = []\n        var msgsToQueue = []\n\n        async.series(\n            [\n                function(next) {\n                    var i\n                    for(i=0; i<total; i++) {\n                        msgsToQueue.push('no=' + i)\n                    }\n                    queue.add(msgsToQueue, function(err) {\n                        if (err) return t.fail('Failed adding a message')\n                        t.pass('All ' + total + ' messages sent to MongoDB')\n                        next()\n                    })\n                },\n                function(next) {\n                    function getOne() {\n                        queue.get(function(err, msg) {\n                            if (err || !msg) return t.fail('Failed getting a message')\n                            msgs.push(msg)\n                            if (msgs.length === total) {\n                                t.pass('Received all ' + total + ' messages')\n                                next()\n                            }\n                            else {\n                                getOne()\n                            }\n                        })\n                    }\n                    getOne()\n                },\n                function(next) {\n                    var acked = 0\n                    msgs.forEach(function(msg) {\n                        queue.ack(msg.ack, function(err) {\n                            if (err) return t.fail('Failed acking a message')\n                            acked++\n                            if (acked === total) {\n                                t.pass('Acked all ' + total + ' messages')\n                                next()\n                            }\n                        })\n                    })\n                },\n            ],\n            function(err) {\n                if (err) t.fail(err)\n                t.pass('Finished test ok')\n                t.end()\n            }\n        )\n    })\n\n    test('many: add no messages, receive err in callback', function(t) {\n        var queue = mongoDbQueue(db, 'many')\n        var messages = []\n        queue.add([], function(err) {\n            if (!err) t.fail('Error was not received')\n            t.pass('Finished test ok')\n            t.end()\n        });\n    })\n\n    test('client.close()', function(t) {\n        t.pass('client.close()')\n        client.close()\n        t.end()\n    })\n\n})\n"
  },
  {
    "path": "test/multi.js",
    "content": "var async = require('async')\nvar test = require('tape')\n\nvar setup = require('./setup.js')\nvar mongoDbQueue = require('../')\n\nvar total = 250\n\nsetup(function(client, db) {\n\n    test('multi: add ' + total + ' messages, get ' + total + ' back', function(t) {\n        var queue = mongoDbQueue(db, 'multi')\n        var msgs = []\n\n        async.series(\n            [\n                function(next) {\n                    var i, done = 0\n                    for(i=0; i<total; i++) {\n                        queue.add('no=' + i, function(err) {\n                            if (err) return t.fail('Failed adding a message')\n                            done++\n                            if (done === total) {\n                                t.pass('All ' + total + ' messages sent to MongoDB')\n                                next()\n                            }\n                        })\n                    }\n                },\n                function(next) {\n                    function getOne() {\n                        queue.get(function(err, msg) {\n                            if (err) return t.fail('Failed getting a message')\n                            msgs.push(msg)\n                            if (msgs.length === total) {\n                                t.pass('Received all ' + total + ' messages')\n                                next()\n                            }\n                            else {\n                                getOne()\n                            }\n                        })\n                    }\n                    getOne()\n                },\n                function(next) {\n                    var acked = 0\n                    msgs.forEach(function(msg) {\n                        queue.ack(msg.ack, function(err) {\n                            if (err) return t.fail('Failed acking a message')\n                            acked++\n                            if (acked === total) {\n                                t.pass('Acked all ' + total + ' messages')\n                                next()\n                            }\n                        })\n                    })\n                },\n            ],\n            function(err) {\n                if (err) t.fail(err)\n                t.pass('Finished test ok')\n                t.end()\n            }\n        )\n    })\n\n    test('client.close()', function(t) {\n        t.pass('client.close()')\n        client.close()\n        t.end()\n    })\n\n})\n"
  },
  {
    "path": "test/ping.js",
    "content": "var async = require('async')\nvar test = require('tape')\n\nvar setup = require('./setup.js')\nvar mongoDbQueue = require('../')\n\nsetup(function(client, db) {\n\n    test('ping: check a retrieved message with a ping can still be acked', function(t) {\n        var queue = mongoDbQueue(db, 'ping', { visibility : 5 })\n        var msg\n\n        async.series(\n            [\n                function(next) {\n                    queue.add('Hello, World!', function(err, id) {\n                        t.ok(!err, 'There is no error when adding a message.')\n                        t.ok(id, 'There is an id returned when adding a message.')\n                        next()\n                    })\n                },\n                function(next) {\n                    // get something now and it shouldn't be there\n                    queue.get(function(err, thisMsg) {\n                        msg = thisMsg\n                        t.ok(!err, 'No error when getting this message')\n                        t.ok(msg.id, 'Got this message id')\n                        // now wait 4s\n                        setTimeout(next, 4 * 1000)\n                    })\n                },\n                function(next) {\n                    // ping this message so it will be kept alive longer, another 5s\n                    queue.ping(msg.ack, function(err, id) {\n                        t.ok(!err, 'No error when pinging a message')\n                        t.ok(id, 'Received an id when acking this message')\n                        // now wait 4s\n                        setTimeout(next, 4 * 1000)\n                    })\n                },\n                function(next) {\n                    queue.ack(msg.ack, function(err, id) {\n                        t.ok(!err, 'No error when acking this message')\n                        t.ok(id, 'Received an id when acking this message')\n                        next()\n                    })\n                },\n                function(next) {\n                    queue.get(function(err, msg) {\n                        t.ok(!err, 'No error when getting no messages')\n                        t.ok(!msg, 'No message when getting from an empty queue')\n                        next()\n                    })\n                },\n            ],\n            function(err) {\n                if (err) t.fail(err)\n                t.pass('Finished test ok')\n                t.end()\n            }\n        )\n    })\n\n    test(\"ping: check that an acked message can't be pinged\", function(t) {\n        var queue = mongoDbQueue(db, 'ping', { visibility : 5 })\n        var msg\n\n        async.series(\n            [\n                function(next) {\n                    queue.add('Hello, World!', function(err, id) {\n                        t.ok(!err, 'There is no error when adding a message.')\n                        t.ok(id, 'There is an id returned when adding a message.')\n                        next()\n                    })\n                },\n                function(next) {\n                    // get something now and it shouldn't be there\n                    queue.get(function(err, thisMsg) {\n                        msg = thisMsg\n                        t.ok(!err, 'No error when getting this message')\n                        t.ok(msg.id, 'Got this message id')\n                        next()\n                    })\n                },\n                function(next) {\n                    // ack the message\n                    queue.ack(msg.ack, function(err, id) {\n                        t.ok(!err, 'No error when acking this message')\n                        t.ok(id, 'Received an id when acking this message')\n                        next()\n                    })\n                },\n                function(next) {\n                    // ping this message, even though it has been acked\n                    queue.ping(msg.ack, function(err, id) {\n                        t.ok(err, 'Error when pinging an acked message')\n                        t.ok(!id, 'Received no id when pinging an acked message')\n                        next()\n                    })\n                },\n            ],\n            function(err) {\n                if (err) t.fail(err)\n                t.pass('Finished test ok')\n                t.end()\n            }\n        )\n    })\n\ntest(\"ping: check visibility option overrides the queue visibility\", function(t) {\n        var queue = mongoDbQueue(db, 'ping', { visibility : 3 })\n        var msg\n\n        async.series(\n            [\n                function(next) {\n                    queue.add('Hello, World!', function(err, id) {\n                        t.ok(!err, 'There is no error when adding a message.')\n                        t.ok(id, 'There is an id returned when adding a message.')\n                        next()\n                    })\n                },\n                function(next) {\n                    queue.get(function(err, thisMsg) {\n                        msg = thisMsg\n                        // message should reset in three seconds\n                        t.ok(msg.id, 'Got a msg.id (sanity check)')\n                        setTimeout(next, 2 * 1000)\n                    })\n                },\n                function(next) {\n                    // ping this message so it will be kept alive longer, another 5s instead of 3s\n                    queue.ping(msg.ack, { visibility: 5 }, function(err, id) {\n                        t.ok(!err, 'No error when pinging a message')\n                        t.ok(id, 'Received an id when acking this message')\n                        // wait 4s so the msg would normally have returns to the queue\n                        setTimeout(next, 4 * 1000)\n                    })\n                },\n                function(next) {\n                    queue.get(function(err, msg) {\n                        // messages should not be back yet\n                        t.ok(!err, 'No error when getting no messages')\n                        t.ok(!msg, 'No msg received')\n                        // wait 2s so the msg should have returns to the queue\n                        setTimeout(next, 2 * 1000)\n                    })\n                },\n                function(next) {\n                    queue.get(function(err, msg) {\n                        // yes, there should be a message on the queue again\n                        t.ok(msg.id, 'Got a msg.id (sanity check)')\n                        queue.ack(msg.ack, function(err) {\n                            t.ok(!err, 'No error when acking the message')\n                            next()\n                        })\n                    })\n                },\n                function(next) {\n                    queue.get(function(err, msg) {\n                        // no more messages\n                        t.ok(!err, 'No error when getting no messages')\n                        t.ok(!msg, 'No msg received')\n                        next()\n                    })\n                }\n            ],\n            function(err) {\n                if (err) t.fail(err)\n                t.pass('Finished test ok')\n                t.end()\n            }\n        )\n    })\n\n    test('client.close()', function(t) {\n        t.pass('client.close()')\n        client.close()\n        t.end()\n    })\n\n})\n"
  },
  {
    "path": "test/setup.js",
    "content": "const mongodb = require('mongodb')\n\nconst url = 'mongodb://localhost:27017/'\nconst dbName = 'mongodb-queue'\n\nconst collections = [\n  'default',\n  'delay',\n  'multi',\n  'visibility',\n  'clean',\n  'ping',\n  'stats1',\n  'stats2',\n  'queue',\n  'dead-queue',\n  'queue-2',\n  'dead-queue-2',\n]\n\nmodule.exports = function(callback) {\n  const client = new mongodb.MongoClient(url, { useNewUrlParser: true })\n\n  client.connect(err => {\n    // we can throw since this is test-only\n    if (err) throw err\n\n    const db = client.db(dbName)\n\n    // empty out some collections to make sure there are no messages\n    let done = 0\n    collections.forEach((col) => {\n      db.collection(col).deleteMany(() => {\n        done += 1\n        if ( done === collections.length ) {\n          callback(client, db)\n        }\n      })\n    })\n  })\n\n}\n"
  },
  {
    "path": "test/stats.js",
    "content": "var async = require('async')\nvar test = require('tape')\n\nvar setup = require('./setup.js')\nvar mongoDbQueue = require('../')\n\nsetup(function(client, db) {\n\n    test('first test', function(t) {\n        var queue = mongoDbQueue(db, 'stats')\n        t.ok(queue, 'Queue created ok')\n        t.end()\n    });\n\n    test('stats for a single message added, received and acked', function(t) {\n        var queue = mongoDbQueue(db, 'stats1')\n        var msg\n\n        async.series(\n            [\n                function(next) {\n                    queue.add('Hello, World!', function(err, id) {\n                        t.ok(!err, 'There is no error when adding a message.')\n                        t.ok(id, 'Received an id for this message')\n                        next()\n                    })\n                },\n                function(next) {\n                    queue.total(function(err, count) {\n                        t.equal(count, 1, 'Total number of messages is one')\n                        next()\n                    })\n                },\n                function(next) {\n                    queue.size(function(err, count) {\n                        t.equal(count, 1, 'Size of queue is one')\n                        next()\n                    })\n                },\n                function(next) {\n                    queue.inFlight(function(err, count) {\n                        t.equal(count, 0, 'There are no inFlight messages')\n                        next()\n                    })\n                },\n                function(next) {\n                    queue.done(function(err, count) {\n                        t.equal(count, 0, 'There are no done messages')\n                        next()\n                    })\n                },\n                function(next) {\n                    // let's set one to be inFlight\n                    queue.get(function(err, newMsg) {\n                        msg = newMsg\n                        next()\n                    })\n                },\n                function(next) {\n                    queue.total(function(err, count) {\n                        t.equal(count, 1, 'Total number of messages is still one')\n                        next()\n                    })\n                },\n                function(next) {\n                    queue.size(function(err, count) {\n                        t.equal(count, 0, 'Size of queue is now zero (ie. none to come)')\n                        next()\n                    })\n                },\n                function(next) {\n                    queue.inFlight(function(err, count) {\n                        t.equal(count, 1, 'There is one inflight message')\n                        next()\n                    })\n                },\n                function(next) {\n                    queue.done(function(err, count) {\n                        t.equal(count, 0, 'There are still no done messages')\n                        next()\n                    })\n                },\n                function(next) {\n                    // now ack that message\n                    queue.ack(msg.ack, function(err, newMsg) {\n                        msg = newMsg\n                        next()\n                    })\n                },\n                function(next) {\n                    queue.total(function(err, count) {\n                        t.equal(count, 1, 'Total number of messages is again one')\n                        next()\n                    })\n                },\n                function(next) {\n                    queue.size(function(err, count) {\n                        t.equal(count, 0, 'Size of queue is still zero (ie. none to come)')\n                        next()\n                    })\n                },\n                function(next) {\n                    queue.inFlight(function(err, count) {\n                        t.equal(count, 0, 'There are no inflight messages anymore')\n                        next()\n                    })\n                },\n                function(next) {\n                    queue.done(function(err, count) {\n                        t.equal(count, 1, 'There is now one processed message')\n                        next()\n                    })\n                },\n            ],\n            function(err) {\n                t.ok(!err, 'No error when doing stats on one message')\n                t.end()\n            }\n        )\n    })\n\n\n    // ToDo: add more tests for adding a message, getting it and letting it lapse\n    // then re-checking all stats.\n\n    test('stats for a single message added, received, timed-out and back on queue', function(t) {\n        var queue = mongoDbQueue(db, 'stats2', { visibility : 3 })\n\n        async.series(\n            [\n                function(next) {\n                    queue.add('Hello, World!', function(err, id) {\n                        t.ok(!err, 'There is no error when adding a message.')\n                        t.ok(id, 'Received an id for this message')\n                        next()\n                    })\n                },\n                function(next) {\n                    queue.total(function(err, count) {\n                        t.equal(count, 1, 'Total number of messages is one')\n                        next()\n                    })\n                },\n                function(next) {\n                    queue.size(function(err, count) {\n                        t.equal(count, 1, 'Size of queue is one')\n                        next()\n                    })\n                },\n                function(next) {\n                    queue.inFlight(function(err, count) {\n                        t.equal(count, 0, 'There are no inFlight messages')\n                        next()\n                    })\n                },\n                function(next) {\n                    queue.done(function(err, count) {\n                        t.equal(count, 0, 'There are no done messages')\n                        next()\n                    })\n                },\n                function(next) {\n                    // let's set one to be inFlight\n                    queue.get(function(err, msg) {\n                        // msg is ignored, we don't care about the message here\n                        setTimeout(next, 4 * 1000)\n                    })\n                },\n                function(next) {\n                    queue.total(function(err, count) {\n                        t.equal(count, 1, 'Total number of messages is still one')\n                        next()\n                    })\n                },\n                function(next) {\n                    queue.size(function(err, count) {\n                        t.equal(count, 1, 'Size of queue is still at one')\n                        next()\n                    })\n                },\n                function(next) {\n                    queue.inFlight(function(err, count) {\n                        t.equal(count, 0, 'There are no inflight messages again')\n                        next()\n                    })\n                },\n                function(next) {\n                    queue.done(function(err, count) {\n                        t.equal(count, 0, 'There are still no done messages')\n                        next()\n                    })\n                },\n            ],\n            function(err) {\n                t.ok(!err, 'No error when doing stats on one message')\n                t.end()\n            }\n        )\n    })\n\n    test('client.close()', function(t) {\n        t.pass('client.close()')\n        client.close()\n        t.end()\n    })\n\n})\n\n"
  },
  {
    "path": "test/visibility.js",
    "content": "var async = require('async')\nvar test = require('tape')\n\nvar setup = require('./setup.js')\nvar mongoDbQueue = require('../')\n\nsetup(function(client, db) {\n\n    test('visibility: check message is back in queue after 3s', function(t) {\n        var queue = mongoDbQueue(db, 'visibility', { visibility : 3 })\n\n        async.series(\n            [\n                function(next) {\n                    queue.add('Hello, World!', function(err) {\n                        t.ok(!err, 'There is no error when adding a message.')\n                        next()\n                    })\n                },\n                function(next) {\n                    queue.get(function(err, msg) {\n                        // wait over 3s so the msg returns to the queue\n                        t.ok(msg.id, 'Got a msg.id (sanity check)')\n                        setTimeout(next, 4 * 1000)\n                    })\n                },\n                function(next) {\n                    queue.get(function(err, msg) {\n                        // yes, there should be a message on the queue again\n                        t.ok(msg.id, 'Got a msg.id (sanity check)')\n                        queue.ack(msg.ack, function(err) {\n                            t.ok(!err, 'No error when acking the message')\n                            next()\n                        })\n                    })\n                },\n                function(next) {\n                    queue.get(function(err, msg) {\n                        // no more messages\n                        t.ok(!err, 'No error when getting no messages')\n                        t.ok(!msg, 'No msg received')\n                        next()\n                    })\n                },\n            ],\n            function(err) {\n                if (err) t.fail(err)\n                t.pass('Finished test ok')\n                t.end()\n            }\n        )\n    })\n\n    test(\"visibility: check that a late ack doesn't remove the msg\", function(t) {\n        var queue = mongoDbQueue(db, 'visibility', { visibility : 3 })\n        var originalAck\n\n        async.series(\n            [\n                function(next) {\n                    queue.add('Hello, World!', function(err) {\n                        t.ok(!err, 'There is no error when adding a message.')\n                        next()\n                    })\n                },\n                function(next) {\n                    queue.get(function(err, msg) {\n                        t.ok(msg.id, 'Got a msg.id (sanity check)')\n\n                        // remember this original ack\n                        originalAck = msg.ack\n\n                        // wait over 3s so the msg returns to the queue\n                        setTimeout(function() {\n                            t.pass('Back from timeout, now acking the message')\n\n                            // now ack the message but too late - it shouldn't be deleted\n                            queue.ack(msg.ack, function(err, msg) {\n                                t.ok(err, 'Got an error when acking the message late')\n                                t.ok(!msg, 'No message was updated')\n                                next()\n                            })\n                        }, 4 * 1000)\n                    })\n                },\n                function(next) {\n                    queue.get(function(err, msg) {\n                        // the message should now be able to be retrieved, with a new 'ack' id\n                        t.ok(msg.id, 'Got a msg.id (sanity check)')\n                        t.notEqual(msg.ack, originalAck, 'Original ack and new ack are different')\n\n                        // now ack this new retrieval\n                        queue.ack(msg.ack, next)\n                    })\n                },\n                function(next) {\n                    queue.get(function(err, msg) {\n                        // no more messages\n                        t.ok(!err, 'No error when getting no messages')\n                        t.ok(!msg, 'No msg received')\n                        next()\n                    })\n                },\n            ],\n            function(err) {\n                if (err) t.fail(err)\n                t.pass('Finished test ok')\n                t.end()\n            }\n        )\n    })\n\n    test(\"visibility: check visibility option overrides the queue visibility\", function(t) {\n        var queue = mongoDbQueue(db, 'visibility', { visibility : 2 })\n        var originalAck\n\n        async.series(\n            [\n                function(next) {\n                    queue.add('Hello, World!', function(err) {\n                        t.ok(!err, 'There is no error when adding a message.')\n                        next()\n                    })\n                },\n                function(next) {\n                    queue.get({ visibility: 4 }, function(err, msg) {\n                        // wait over 2s so the msg would normally have returns to the queue\n                        t.ok(msg.id, 'Got a msg.id (sanity check)')\n                        setTimeout(next, 3 * 1000)\n                    })\n                },\n                function(next) {\n                    queue.get(function(err, msg) {\n                        // messages should not be back yet\n                        t.ok(!err, 'No error when getting no messages')\n                        t.ok(!msg, 'No msg received')\n                        // wait 2s so the msg should have returns to the queue\n                        setTimeout(next, 2 * 1000)\n                    })\n                },\n                function(next) {\n                    queue.get(function(err, msg) {\n                        // yes, there should be a message on the queue again\n                        t.ok(msg.id, 'Got a msg.id (sanity check)')\n                        queue.ack(msg.ack, function(err) {\n                            t.ok(!err, 'No error when acking the message')\n                            next()\n                        })\n                    })\n                },\n                function(next) {\n                    queue.get(function(err, msg) {\n                        // no more messages\n                        t.ok(!err, 'No error when getting no messages')\n                        t.ok(!msg, 'No msg received')\n                        next()\n                    })\n                }\n            ],\n            function(err) {\n                if (err) t.fail(err)\n                t.pass('Finished test ok')\n                t.end()\n            }\n        )\n    })\n\n    test('client.close()', function(t) {\n        t.pass('client.close()')\n        client.close()\n        t.end()\n    })\n\n})\n"
  }
]