Full Code of chilts/mongodb-queue for AI

master e12c1c8c20fb cached
16 files
73.2 KB
15.9k tokens
6 symbols
1 requests
Download .txt
Repository: chilts/mongodb-queue
Branch: master
Commit: e12c1c8c20fb
Files: 16
Total size: 73.2 KB

Directory structure:
gitextract_5_hou0nf/

├── .gitignore
├── .travis.yml
├── README.md
├── mongodb-queue.js
├── package.json
└── test/
    ├── clean.js
    ├── dead-queue.js
    ├── default.js
    ├── delay.js
    ├── indexes.js
    ├── many.js
    ├── multi.js
    ├── ping.js
    ├── setup.js
    ├── stats.js
    └── visibility.js

================================================
FILE CONTENTS
================================================

================================================
FILE: .gitignore
================================================
node_modules/*
*.log
*~


================================================
FILE: .travis.yml
================================================
language: node_js
node_js:
  - "8"
  - "10"
  - "11"
services: mongodb


================================================
FILE: README.md
================================================
# mongodb-queue #

[![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/)

A really light-weight way to create queues with a nice API if you're already
using MongoDB.

Now compatible with the MongoDB v3 driver.

For MongoDB v2 driver use mongodb-queue@3.

**NOTE**: This package is considered feature complete and **STABLE** hence there is not a whole lot of development on
it though it is being used extensively. Use it with all your might and let us know of any problems - it should be
bullet-proof.

## Synopsis ##

Create a connection to your MongoDB database, and use it to create a queue object:

```js
var mongodb = require('mongodb')
var mongoDbQueue = require('mongodb-queue')

const url = 'mongodb://localhost:27017/'
const client = new mongodb.MongoClient(url, { useNewUrlParser: true })

client.connect(err => {
  const db = client.db('test')
  const queue = mongoDbQueue(db, 'my-queue')

  // ...

})
```

Add a message to a queue:

```js
queue.add('Hello, World!', (err, id) => {
    // Message with payload 'Hello, World!' added.
    // 'id' is returned, useful for logging.
})
```

Get a message from the queue:

```js
queue.get((err, msg) => {
    console.log('msg.id=' + msg.id)
    console.log('msg.ack=' + msg.ack)
    console.log('msg.payload=' + msg.payload) // 'Hello, World!'
    console.log('msg.tries=' + msg.tries)
})
```

Ping a message to keep it's visibility open for long-running tasks

```js
queue.ping(msg.ack, (err, id) => {
    // Visibility window now increased for this message id.
    // 'id' is returned, useful for logging.
})
```

Ack a message (and remove it from the queue):

```js
queue.ack(msg.ack, (err, id) => {
    // This msg removed from queue for this ack.
    // The 'id' of the message is returned, useful for logging.
})
```

By default, all old messages - even processed ones - are left in MongoDB. This is so that
you can go and analyse them if you want. However, you can call the following function
to remove processed messages:

```js
queue.clean((err) => {
    // All processed (ie. acked) messages have been deleted
})
```

And if you haven't already, you should call this to make sure indexes have
been added in MongoDB. Of course, if you've called this once (in some kind
one-off script) you don't need to call it in your program. Of course, check
the changelock to see if you need to update them with new releases:

```js
queue.createIndexes((err, indexName) => {
    // The indexes needed have been added to MongoDB.
})
```

## Creating a Queue ##

To create a queue, call the exported function with the `MongoClient`, the name
and a set of opts. The MongoDB collection used is the same name as the name
passed in:

```
var mongoDbQueue = require('mongodb-queue')

// an instance of a queue
var queue1 = mongoDbQueue(db, 'a-queue')
// another queue which uses the same collection as above
var queue2 = mongoDbQueue(db, 'a-queue')
```

Using `queue1` and `queue2` here won't interfere with each other and will play along nicely, but that's not
a good idea code-wise - just use the same object. This example is for illustrative purposes only.

Note: Don't use the same queue name twice with different options, otherwise behaviour is undefined and again
it's not something you should do.

To pass in options for the queue:

```
var resizeQueue = mongoDbQueue(db, 'resize-queue', { visibility : 30, delay : 15 })
```

This example shows a queue with a message visibility of 30s and a delay to each message of 15s.

## Options ##

### name ###

This is the name of the MongoDB Collection you wish to use to store the messages.
Each queue you create will be it's own collection.

e.g.

```
var resizeImageQueue = mongoDbQueue(db, 'resize-image-queue')
var notifyOwnerQueue = mongoDbQueue(db, 'notify-owner-queue')
```

This will create two collections in MongoDB called `resize-image-queue` and `notify-owner-queue`.

### visibility - Message Visibility Window ###

Default: `30`

By default, if you don't ack a message within the first 30s after receiving it,
it is placed back in the queue so it can be fetched again. This is called the
visibility window.

You may set this visibility window on a per queue basis. For example, to set the
visibility to 15 seconds:

```
var queue = mongoDbQueue(db, 'queue', { visibility : 15 })
```

All messages in this queue now have a visibility window of 15s, instead of the
default 30s.

### delay - Delay Messages on Queue ###

Default: `0`

When a message is added to a queue, it is immediately available for retrieval.
However, there are times when you might like to delay messages coming off a queue.
ie. if you set delay to be `10`, then every message will only be available for
retrieval 10s after being added.

To delay all messages by 10 seconds, try this:

```
var queue = mongoDbQueue(db, 'queue', { delay : 10 })
```

This is now the default for every message added to the queue.

### deadQueue - Dead Message Queue ###

Default: none

Messages that have been retried over `maxRetries` will be pushed to this queue so you can
automatically see problem messages.

Pass in a queue (that you created) onto which these messages will be pushed:

```js
var deadQueue = mongoDbQueue(db, 'dead-queue')
var queue = mongoDbQueue(db, 'queue', { deadQueue : deadQueue })
```

If you pop a message off the `queue` over `maxRetries` times and still have not acked it,
it will be pushed onto the `deadQueue` for you. This happens when you `.get()` (not when
you miss acking a message in it's visibility window). By doing it when you call `.get()`,
the unprocessed message will be received, pushed to the `deadQueue`, acked off the normal
queue and `.get()` will check for new messages prior to returning you one (or none).

### maxRetries - Maximum Retries per Message ###

Default: 5

This option only comes into effect if you pass in a `deadQueue` as shown above. What this
means is that if an item is popped off the queue `maxRetries` times (e.g. 5) and not acked,
it will be moved to this `deadQueue` the next time it is tried to pop off. You can poll your
`deadQueue` for dead messages much like you can poll your regular queues.

The payload of the messages in the dead queue are the entire messages returned when `.get()`ing
them from the original queue.

e.g.

Given this message:

```
msg = {
  id: '533b1eb64ee78a57664cc76c',
  ack: 'c8a3cc585cbaaacf549d746d7db72f69',
  payload: 'Hello, World!',
  tries: 1
}
```

If it is not acked within the `maxRetries` times, then when you receive this same message
from the `deadQueue`, it may look like this:

```
msg = {
  id: '533b1ecf3ca3a76b667671ef',
  ack: '73872b204e3f7be84050a1ce82c5c9c0',
  payload: {
    id: '533b1eb64ee78a57664cc76c',
    ack: 'c8a3cc585cbaaacf549d746d7db72f69',
    payload: 'Hello, World!',
    tries: 5
  },
  tries: 1
}
```

Notice that the payload from the `deadQueue` is exactly the same as the original message
when it was on the original queue (except with the number of tries set to 5).

## Operations ##

### .add() ###

You can add a string to the queue:

```js
queue.add('Hello, World!', (err, id) => {
    // Message with payload 'Hello, World!' added.
    // 'id' is returned, useful for logging.
})
```

Or add an object of your choosing:

```js
queue.add({ err: 'E_BORKED', msg: 'Broken' }, (err, id) => {
    // Message with payload { err: 'E_BORKED', msg: 'Broken' } added.
    // 'id' is returned, useful for logging.
})
```

Or add multiple messages:

```js
queue.add(['msg1', 'msg2', 'msg3'], (err, ids) => {
    // Messages with payloads 'msg1', 'msg2' & 'msg3' added.
    // All 'id's are returned as an array, useful for logging.
})
```

You can delay individual messages from being visible by passing the `delay` option:

```js
queue.add('Later', { delay: 120 }, (err, id) => {
    // Message with payload 'Later' added.
    // 'id' is returned, useful for logging.
    // This message won't be available for getting for 2 mins.
})
```

### .get() ###

Retrieve a message from the queue:

```js
queue.get((err, msg) => {
    // You can now process the message
    // IMPORTANT: The callback will not wait for an message if the queue is empty.  The message will be undefined if the queue is empty.
})
```

You can choose the visibility of an individual retrieved message by passing the `visibility` option:

```js
queue.get({ visibility: 10 }, (err, msg) => {
    // 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
})
```

Message will have the following structure:

```js
{
  id: '533b1eb64ee78a57664cc76c', // ID of the message
  ack: 'c8a3cc585cbaaacf549d746d7db72f69', // ID for ack and ping operations
  payload: 'Hello, World!', // Payload passed when the message was addded
  tries: 1 // Number of times this message has been retrieved from queue without being ack'd
}
```

### .ack() ###

After you have received an item from a queue and processed it, you can delete it
by calling `.ack()` with the unique `ackId` returned:

```js
queue.get((err, msg) => {
    queue.ack(msg.ack, (err, id) => {
        // this message has now been removed from the queue
    })
})
```

### .ping() ###

After you have received an item from a queue and you are taking a while
to process it, you can `.ping()` the message to tell the queue that you are
still alive and continuing to process the message:

```js
queue.get((err, msg) => {
    queue.ping(msg.ack, (err, id) => {
        // this message has had it's visibility window extended
    })
})
```

You can also choose the visibility time that gets added by the ping operation by passing the `visibility` option:

```js
queue.get((err, msg) => {
    queue.ping(msg.ack, { visibility: 10 }, (err, id) => {
        // this message has had it's visibility window extended by 10s instead of the visibilty set on the queue in general
    })
})
```

### .total() ###

Returns the total number of messages that has ever been in the queue, including
all current messages:

```js
queue.total((err, count) => {
    console.log('This queue has seen %d messages', count)
})
```

### .size() ###

Returns the total number of messages that are waiting in the queue.

```js
queue.size((err, count) => {
    console.log('This queue has %d current messages', count)
})
```

### .inFlight() ###

Returns the total number of messages that are currently in flight. ie. that
have been received but not yet acked:

```js
queue.inFlight((err, count) => {
    console.log('A total of %d messages are currently being processed', count)
})
```

### .done() ###

Returns the total number of messages that have been processed correctly in the
queue:

```js
queue.done((err, count) => {
    console.log('This queue has processed %d messages', count)
})
```

### .clean() ###

Deletes all processed mesages from the queue. Of course, you can leave these hanging around
if you wish, but delete them if you no longer need them. Perhaps do this using `setInterval`
for a regular cleaning:

```js
queue.clean((err) => {
    console.log('The processed messages have been deleted from the queue')
})
```

### Notes about Numbers ###

If you add up `.size() + .inFlight() + .done()` then you should get `.total()`
but this will only be approximate since these are different operations hitting the database
at slightly different times. Hence, a message or two might be counted twice or not at all
depending on message turnover at any one time. You should not rely on these numbers for
anything but are included as approximations at any point in time.

## Use of MongoDB ##

Whilst using MongoDB recently and having a need for lightweight queues, I realised
that the atomic operations that MongoDB provides are ideal for this kind of job.

Since everything it atomic, it is impossible to lose messages in or around your
application. I guess MongoDB could lose them but it's a safer bet it won't compared
to your own application.

As an example of the atomic nature being used, messages stay in the same collection
and are never moved around or deleted, just a couple of fields are set, incremented
or deleted. We always use MongoDB's excellent `collection.findAndModify()` so that
each message is updated atomically inside MongoDB and we never have to fetch something,
change it and store it back.

## Roadmap ##

We may add the ability for each function to return a promise in the future so it can be used as such, or with
async/await.

## Releases ##

### 4.0.0 (2019-02-20) ###

* [NEW] Updated entire codebase to be compatible with the mongodb driver v3

### 2.1.0 (2016-04-21) ###

* [FIX] Fix to indexes (thanks https://github.com/ifightcrime) when lots of messages

### 2.0.0 (2014-11-12) ###

* [NEW] Update MongoDB API from v1 to v2 (thanks https://github.com/hanwencheng)

### 1.0.1 (2015-05-25) ###

* [NEW] Test changes only

### 1.0.0 (2014-10-30) ###

* [NEW] Ability to specify a visibility window when getting a message (thanks https://github.com/Gertt)

### 0.9.1 (2014-08-28) ###

* [NEW] Added .clean() method to remove old (processed) messages
* [NEW] Add 'delay' option to queue.add() so individual messages can be delayed separately
* [TEST] Test individual 'delay' option for each message

### 0.7.0 (2014-03-24) ###

* [FIX] Fix .ping() so only visible/non-deleted messages can be pinged
* [FIX] Fix .ack() so only visible/non-deleted messages can be pinged
* [TEST] Add test to make sure messages can't be acked twice
* [TEST] Add test to make sure an acked message can't be pinged
* [INTERNAL] Slight function name changes, nicer date routines

### 0.6.0 (2014-03-22) ###

* [NEW] The msg.id is now returned on successful Queue.ping() and Queue.ack() calls
* [NEW] Call quueue.ensureIndexes(callback) to create them
* [CHANGE] When a message is acked, 'deleted' is now set to the current time (not true)
* [CHANGE] The queue is now created synchronously

### 0.5.0 (2014-03-21) ###

* [NEW] Now adds two indexes onto the MongoDB collection used for the message
* [CHANGE] The queue is now created by calling the async exported function
* [DOC] Update to show how the queues are now created

### 0.4.0 (2014-03-20) ###

* [NEW] Ability to ping retrieved messages a. la. 'still alive' and 'extend visibility'
* [CHANGE] Removed ability to have different queues in the same collection
* [CHANGE] All queues are now stored in their own collection
* [CHANGE] When acking a message, only need ack (no longer need id)
* [TEST] Added test for pinged messages
* [DOC] Update to specify each queue will create it's own MongoDB collection
* [DOC] Added docs for option `delay`
* [DOC] Added synopsis for Queue.ping()
* [DOC] Removed use of msg.id when calling Queue.ack()

### 0.3.1 (2014-03-19) ###

* [DOC] Added documentation for the `delay` option

### 0.3.0 (2014-03-19) ###

* [NEW] Return the message id when added to a queue
* [NEW] Ability to set a default delay on all messages in a queue
* [FIX] Make sure old messages (outside of visibility window) aren't deleted when acked
* [FIX] Internal: Fix `queueName`
* [TEST] Added test for multiple messages
* [TEST] Added test for delayed messages

### 0.2.1 (2014-03-19) ###

* [FIX] Fix when getting messages off an empty queue
* [NEW] More Tests

### 0.2.0 (2014-03-18) ###

* [NEW] messages now return number of tries (times they have been fetched)

### 0.1.0 (2014-03-18) ###

* [NEW] add messages to queues
* [NEW] fetch messages from queues
* [NEW] ack messages on queues
* [NEW] set up multiple queues
* [NEW] set your own MongoDB Collection name
* [NEW] set a visibility timeout on a queue

## Author ##

```
$ npx chilts

   ╒════════════════════════════════════════════════════╕
   │                                                    │
   │   Andrew Chilton (Personal)                        │
   │   -------------------------                        │
   │                                                    │
   │          Email : andychilton@gmail.com             │
   │            Web : https://chilts.org                │
   │        Twitter : https://twitter.com/andychilton   │
   │         GitHub : https://github.com/chilts         │
   │         GitLab : https://gitlab.org/chilts         │
   │                                                    │
   │   Apps Attic Ltd (My Company)                      │
   │   ---------------------------                      │
   │                                                    │
   │          Email : chilts@appsattic.com              │
   │            Web : https://appsattic.com             │
   │        Twitter : https://twitter.com/AppsAttic     │
   │         GitLab : https://gitlab.com/appsattic      │
   │                                                    │
   │   Node.js / npm                                    │
   │   -------------                                    │
   │                                                    │
   │        Profile : https://www.npmjs.com/~chilts     │
   │           Card : $ npx chilts                      │
   │                                                    │
   ╘════════════════════════════════════════════════════╛
```

## License ##

MIT - http://chilts.mit-license.org/2014/

(Ends)


================================================
FILE: mongodb-queue.js
================================================
/**
 *
 * mongodb-queue.js - Use your existing MongoDB as a local queue.
 *
 * Copyright (c) 2014 Andrew Chilton
 * - http://chilts.org/
 * - andychilton@gmail.com
 *
 * License: http://chilts.mit-license.org/2014/
 *
 **/

var crypto = require('crypto')

// some helper functions
function id() {
    return crypto.randomBytes(16).toString('hex')
}

function now() {
    return (new Date()).toISOString()
}

function nowPlusSecs(secs) {
    return (new Date(Date.now() + secs * 1000)).toISOString()
}

module.exports = function(db, name, opts) {
    return new Queue(db, name, opts)
}

// the Queue object itself
function Queue(db, name, opts) {
    if ( !db ) {
        throw new Error("mongodb-queue: provide a mongodb.MongoClient.db")
    }
    if ( !name ) {
        throw new Error("mongodb-queue: provide a queue name")
    }
    opts = opts || {}

    this.db = db
    this.name = name
    this.col = db.collection(name)
    this.visibility = opts.visibility || 30
    this.delay = opts.delay || 0

    if ( opts.deadQueue ) {
        this.deadQueue = opts.deadQueue
        this.maxRetries = opts.maxRetries || 5
    }
}

Queue.prototype.createIndexes = function(callback) {
    var self = this

    self.col.createIndex({ deleted : 1, visible : 1 }, function(err, indexname) {
        if (err) return callback(err)
        self.col.createIndex({ ack : 1 }, { unique : true, sparse : true }, function(err) {
            if (err) return callback(err)
            callback(null, indexname)
        })
    })
}

Queue.prototype.add = function(payload, opts, callback) {
    var self = this
    if ( !callback ) {
        callback = opts
        opts = {}
    }
    var delay = opts.delay || self.delay
    var visible = delay ? (delay instanceof Date ? delay.toISOString() : nowPlusSecs(delay)) : now()

    var msgs = []
    if (payload instanceof Array) {
        if (payload.length === 0) {
            var errMsg = 'Queue.add(): Array payload length must be greater than 0'
            return callback(new Error(errMsg))
        }
        payload.forEach(function(payload) {
            msgs.push({
                visible  : visible,
                payload  : payload,
            })
        })
    } else {
        msgs.push({
            visible  : visible,
            payload  : payload,
        })
    }

    self.col.insertMany(msgs, function(err, results) {
        if (err) return callback(err);
        if (payload instanceof Array) return callback(null, '' + results.insertedIds);
        callback(null, '' + results.insertedIds["0"]);
    })
}

Queue.prototype.get = function(opts, callback) {
    var self = this
    if ( !callback ) {
        callback = opts
        opts = {}
    }

    var visibility = opts.visibility || self.visibility
    var query = {
        deleted : null,
        visible : { $lte : now() },
    }
    var sort = {
        _id : 1
    }
    var update = {
        $inc : { tries : 1 },
        $set : {
            ack     : id(),
            visible : nowPlusSecs(visibility),
        }
    }

    self.col.findOneAndUpdate(query, update, { sort: sort, returnDocument : 'after' }, function(err, result) {
        if (err){
            return callback(err);
        }

        var msg = result.value
        if (!msg) return callback()

        // convert to an external representation
        msg = {
            // convert '_id' to an 'id' string
            id      : '' + msg._id,
            ack     : msg.ack,
            payload : msg.payload,
            tries   : msg.tries,
        }
        // if we have a deadQueue, then check the tries, else don't
        if ( self.deadQueue ) {
            // check the tries
            if ( msg.tries > self.maxRetries ) {
                // So:
                // 1) add this message to the deadQueue
                // 2) ack this message from the regular queue
                // 3) call ourself to return a new message (if exists)
                self.deadQueue.add(msg, function(err) {
                    if (err) return callback(err)
                    self.ack(msg.ack, function(err) {
                        if (err) return callback(err)
                        self.get(callback)
                    })
                })
                return
            }
        }
        callback(null, msg)
    })
}

Queue.prototype.ping = function(ack, opts, callback) {
    var self = this
    if ( !callback ) {
        callback = opts
        opts = {}
    }

    var visibility = opts.visibility || self.visibility
    var query = {
        ack     : ack,
        visible : { $gt : now() },
        deleted : null,
    }
    var update = {
        $set : {
            visible : nowPlusSecs(visibility)
        }
    }
    self.col.findOneAndUpdate(query, update, { returnDocument : 'after' }, function(err, msg, blah) {
        if (err) return callback(err)
        if ( !msg.value ) {
            return callback(new Error("Queue.ping(): Unidentified ack  : " + ack))
        }
        callback(null, '' + msg.value._id)
    })
}

Queue.prototype.ack = function(ack, callback) {
    var self = this

    var query = {
        ack     : ack,
        visible : { $gt : now() },
        deleted : null,
    }
    var update = {
        $set : {
            deleted : now(),
        }
    }

    self.col.findOneAndUpdate(query, update, { returnDocument : 'after' }, function(err, msg, blah) {
        if (err) return callback(err)
        if ( !msg.value ) {
            return callback(new Error("Queue.ack(): Unidentified ack : " + ack))
        }
        callback(null, '' + msg.value._id)
    })
}

Queue.prototype.clean = function(callback) {
    var self = this

    var query = {
        deleted : { $exists : true },
    }

    self.col.deleteMany(query, callback)
}

Queue.prototype.total = function(callback) {
    var self = this

    self.col.countDocuments(function(err, count) {
        if (err) return callback(err)
        callback(null, count)
    })
}

Queue.prototype.size = function(callback) {
    var self = this

    var query = {
        deleted : null,
        visible : { $lte : now() },
    }

    self.col.countDocuments(query, function(err, count) {
        if (err) return callback(err)
        callback(null, count)
    })
}

Queue.prototype.inFlight = function(callback) {
    var self = this

    var query = {
        ack     : { $exists : true },
        visible : { $gt : now() },
        deleted : null,
    }

    self.col.countDocuments(query, function(err, count) {
        if (err) return callback(err)
        callback(null, count)
    })
}

Queue.prototype.done = function(callback) {
    var self = this

    var query = {
        deleted : { $exists : true },
    }

    self.col.countDocuments(query, function(err, count) {
        if (err) return callback(err)
        callback(null, count)
    })
}


================================================
FILE: package.json
================================================
{
  "name": "mongodb-queue",
  "version": "5.0.0",
  "description": "Message queues which uses MongoDB.",
  "main": "mongodb-queue.js",
  "scripts": {
    "test": "set -e; for FILE in test/*.js; do echo --- $FILE ---; node $FILE; done"
  },
  "dependencies": {},
  "devDependencies": {
    "async": "^2.6.2",
    "mongodb": "^4.0.0",
    "tape": "^4.10.1"
  },
  "homepage": "https://github.com/chilts/mongodb-queue",
  "repository": {
    "type": "git",
    "url": "git://github.com/chilts/mongodb-queue.git"
  },
  "bugs": {
    "url": "http://github.com/chilts/mongodb-queue/issues",
    "mail": "andychilton@gmail.com"
  },
  "author": {
    "name": "Andrew Chilton",
    "email": "andychilton@gmail.com",
    "url": "http://chilts.org/"
  },
  "license": "MIT",
  "keywords": [
    "mongodb",
    "queue"
  ]
}


================================================
FILE: test/clean.js
================================================
var async = require('async')
var test = require('tape')

var setup = require('./setup.js')
var mongoDbQueue = require('../')

setup(function(client, db) {

    test('clean: check deleted messages are deleted', function(t) {
        var queue = mongoDbQueue(db, 'clean', { visibility : 3 })
        var msg

        async.series(
            [
                function(next) {
                    queue.size(function(err, size) {
                        t.ok(!err, 'There is no error.')
                        t.equal(size, 0, 'There is currently nothing on the queue')
                        next()
                    })
                },
                function(next) {
                    queue.total(function(err, size) {
                        t.ok(!err, 'There is no error.')
                        t.equal(size, 0, 'There is currently nothing in the queue at all')
                        next()
                    })
                },
                function(next) {
                    queue.clean(function(err) {
                        t.ok(!err, 'There is no error.')
                        next()
                    })
                },
                function(next) {
                    queue.size(function(err, size) {
                        t.ok(!err, 'There is no error.')
                        t.equal(size, 0, 'There is currently nothing on the queue')
                        next()
                    })
                },
                function(next) {
                    queue.total(function(err, size) {
                        t.ok(!err, 'There is no error.')
                        t.equal(size, 0, 'There is currently nothing in the queue at all')
                        next()
                    })
                },
                function(next) {
                    queue.add('Hello, World!', function(err) {
                        t.ok(!err, 'There is no error when adding a message.')
                        next()
                    })
                },
                function(next) {
                    queue.clean(function(err) {
                        t.ok(!err, 'There is no error.')
                        next()
                    })
                },
                function(next) {
                    queue.size(function(err, size) {
                        t.ok(!err, 'There is no error.')
                        t.equal(size, 1, 'Queue size is correct')
                        next()
                    })
                },
                function(next) {
                    queue.total(function(err, size) {
                        t.ok(!err, 'There is no error.')
                        t.equal(size, 1, 'Queue total is correct')
                        next()
                    })
                },
                function(next) {
                    queue.get(function(err, newMsg) {
                        msg = newMsg
                        t.ok(msg.id, 'Got a msg.id (sanity check)')
                        next()
                    })
                },
                function(next) {
                    queue.size(function(err, size) {
                        t.ok(!err, 'There is no error.')
                        t.equal(size, 0, 'Queue size is correct')
                        next()
                    })
                },
                function(next) {
                    queue.total(function(err, size) {
                        t.ok(!err, 'There is no error.')
                        t.equal(size, 1, 'Queue total is correct')
                        next()
                    })
                },
                function(next) {
                    queue.clean(function(err) {
                        t.ok(!err, 'There is no error.')
                        next()
                    })
                },
                function(next) {
                    queue.size(function(err, size) {
                        t.ok(!err, 'There is no error.')
                        t.equal(size, 0, 'Queue size is correct')
                        next()
                    })
                },
                function(next) {
                    queue.total(function(err, size) {
                        t.ok(!err, 'There is no error.')
                        t.equal(size, 1, 'Queue total is correct')
                        next()
                    })
                },
                function(next) {
                    queue.ack(msg.ack, function(err, id) {
                        t.ok(!err, 'No error when acking the message')
                        t.ok(id, 'Received an id when acking this message')
                        next()
                    })
                },
                function(next) {
                    queue.size(function(err, size) {
                        t.ok(!err, 'There is no error.')
                        t.equal(size, 0, 'Queue size is correct')
                        next()
                    })
                },
                function(next) {
                    queue.total(function(err, size) {
                        t.ok(!err, 'There is no error.')
                        t.equal(size, 1, 'Queue total is correct')
                        next()
                    })
                },
                function(next) {
                    queue.clean(function(err) {
                        t.ok(!err, 'There is no error.')
                        next()
                    })
                },
                function(next) {
                    queue.size(function(err, size) {
                        t.ok(!err, 'There is no error.')
                        t.equal(size, 0, 'Queue size is correct')
                        next()
                    })
                },
                function(next) {
                  queue.total(function(err, size) {
                    t.ok(!err, 'There is no error.')
                    t.equal(size, 0, 'Queue total is correct')
                    next()
                  })
                },
            ],
            function(err) {
                if (err) t.fail(err)
                t.pass('Finished test ok')
                t.end()
            }
        )
    })

    test('client.close()', function(t) {
        t.pass('client.close()')
        client.close()
        t.end()
    })

})


================================================
FILE: test/dead-queue.js
================================================
var async = require('async')
var test = require('tape')

var setup = require('./setup.js')
var mongoDbQueue = require('../')

setup(function(client, db) {

    test('first test', function(t) {
        var queue = mongoDbQueue(db, 'queue', { visibility : 3, deadQueue : 'dead-queue' })
        t.ok(queue, 'Queue created ok')
        t.end()
    });

    test('single message going over 5 tries, should appear on dead-queue', function(t) {
        var deadQueue = mongoDbQueue(db, 'dead-queue')
        var queue = mongoDbQueue(db, 'queue', { visibility : 1, deadQueue : deadQueue })
        var msg
        var origId

        async.series(
            [
                function(next) {
                    queue.add('Hello, World!', function(err, id) {
                        t.ok(!err, 'There is no error when adding a message.')
                        t.ok(id, 'Received an id for this message')
                        origId = id
                        next()
                    })
                },
                function(next) {
                    queue.get(function(err, thisMsg) {
                        setTimeout(function() {
                            t.pass('First expiration')
                            next()
                        }, 2 * 1000)
                    })
                },
                function(next) {
                    queue.get(function(err, thisMsg) {
                        setTimeout(function() {
                            t.pass('Second expiration')
                            next()
                        }, 2 * 1000)
                    })
                },
                function(next) {
                    queue.get(function(err, thisMsg) {
                        setTimeout(function() {
                            t.pass('Third expiration')
                            next()
                        }, 2 * 1000)
                    })
                },
                function(next) {
                    queue.get(function(err, thisMsg) {
                        setTimeout(function() {
                            t.pass('Fourth expiration')
                            next()
                        }, 2 * 1000)
                    })
                },
                function(next) {
                    queue.get(function(err, thisMsg) {
                        setTimeout(function() {
                            t.pass('Fifth expiration')
                            next()
                        }, 2 * 1000)
                    })
                },
                function(next) {
                    queue.get(function(err, id) {
                        t.ok(!err, 'No error when getting no messages')
                        t.ok(!msg, 'No msg received')
                        next()
                    })
                },
                function(next) {
                    deadQueue.get(function(err, msg) {
                        t.ok(!err, 'No error when getting from the deadQueue')
                        t.ok(msg.id, 'Got a message id from the deadQueue')
                        t.equal(msg.payload.id, origId, 'Got the same message id as the original message')
                        t.equal(msg.payload.payload, 'Hello, World!', 'Got the same as the original message')
                        t.equal(msg.payload.tries, 6, 'Got the tries as 6')
                        next()
                    })
                },
            ],
            function(err) {
                t.ok(!err, 'No error during single round-trip test')
                t.end()
            }
        )
    })

    test('two messages, with first going over 3 tries', function(t) {
        var deadQueue = mongoDbQueue(db, 'dead-queue-2')
        var queue = mongoDbQueue(db, 'queue-2', { visibility : 1, deadQueue : deadQueue, maxRetries : 3 })
        var msg
        var origId, origId2

        async.series(
            [
                function(next) {
                    queue.add('Hello, World!', function(err, id) {
                        t.ok(!err, 'There is no error when adding a message.')
                        t.ok(id, 'Received an id for this message')
                        origId = id
                        next()
                    })
                },
                function(next) {
                    queue.add('Part II', function(err, id) {
                        t.ok(!err, 'There is no error when adding another message.')
                        t.ok(id, 'Received an id for this message')
                        origId2 = id
                        next()
                    })
                },
                function(next) {
                    queue.get(function(err, thisMsg) {
                        t.equal(thisMsg.id, origId, 'We return the first message on first go')
                        setTimeout(function() {
                            t.pass('First expiration')
                            next()
                        }, 2 * 1000)
                    })
                },
                function(next) {
                    queue.get(function(err, thisMsg) {
                        t.equal(thisMsg.id, origId, 'We return the first message on second go')
                        setTimeout(function() {
                            t.pass('Second expiration')
                            next()
                        }, 2 * 1000)
                    })
                },
                function(next) {
                    queue.get(function(err, thisMsg) {
                        t.equal(thisMsg.id, origId, 'We return the first message on third go')
                        setTimeout(function() {
                            t.pass('Third expiration')
                            next()
                        }, 2 * 1000)
                    })
                },
                function(next) {
                    // This is the 4th time, so we SHOULD have moved it to the dead queue
                    // pior to it being returned.
                    queue.get(function(err, msg) {
                        t.ok(!err, 'No error when getting the 2nd message')
                        t.equal(msg.id, origId2, 'Got the ID of the 2nd message')
                        t.equal(msg.payload, 'Part II', 'Got the same payload as the 2nd message')
                        next()
                    })
                },
                function(next) {
                    deadQueue.get(function(err, msg) {
                        t.ok(!err, 'No error when getting from the deadQueue')
                        t.ok(msg.id, 'Got a message id from the deadQueue')
                        t.equal(msg.payload.id, origId, 'Got the same message id as the original message')
                        t.equal(msg.payload.payload, 'Hello, World!', 'Got the same as the original message')
                        t.equal(msg.payload.tries, 4, 'Got the tries as 4')
                        next()
                    })
                },
            ],
            function(err) {
                t.ok(!err, 'No error during single round-trip test')
                t.end()
            }
        )
    })

    test('client.close()', function(t) {
        t.pass('client.close()')
        client.close()
        t.end()
    })

})


================================================
FILE: test/default.js
================================================
var async = require('async')
var test = require('tape')

var setup = require('./setup.js')
var mongoDbQueue = require('../')

setup(function(client, db) {

    test('first test', function(t) {
        var queue = mongoDbQueue(db, 'default')
        t.ok(queue, 'Queue created ok')
        t.end()
    });

    test('single round trip', function(t) {
        var queue = mongoDbQueue(db, 'default')
        var msg

        async.series(
            [
                function(next) {
                    queue.add('Hello, World!', function(err, id) {
                        t.ok(!err, 'There is no error when adding a message.')
                        t.ok(id, 'Received an id for this message')
                        next()
                    })
                },
                function(next) {
                    queue.get(function(err, thisMsg) {
                        console.log(thisMsg)
                        msg = thisMsg
                        t.ok(msg.id, 'Got a msg.id')
                        t.equal(typeof msg.id, 'string', 'msg.id is a string')
                        t.ok(msg.ack, 'Got a msg.ack')
                        t.equal(typeof msg.ack, 'string', 'msg.ack is a string')
                        t.ok(msg.tries, 'Got a msg.tries')
                        t.equal(typeof msg.tries, 'number', 'msg.tries is a number')
                        t.equal(msg.tries, 1, 'msg.tries is currently one')
                        t.equal(msg.payload, 'Hello, World!', 'Payload is correct')
                        next()
                    })
                },
                function(next) {
                    queue.ack(msg.ack, function(err, id) {
                        t.ok(!err, 'No error when acking the message')
                        t.ok(id, 'Received an id when acking this message')
                        next()
                    })
                },
            ],
            function(err) {
                t.ok(!err, 'No error during single round-trip test')
                t.end()
            }
        )
    })

    test("single round trip, can't be acked again", function(t) {
        var queue = mongoDbQueue(db, 'default')
        var msg

        async.series(
            [
                function(next) {
                    queue.add('Hello, World!', function(err, id) {
                        t.ok(!err, 'There is no error when adding a message.')
                        t.ok(id, 'Received an id for this message')
                        next()
                    })
                },
                function(next) {
                    queue.get(function(err, thisMsg) {
                        msg = thisMsg
                        t.ok(msg.id, 'Got a msg.id')
                        t.equal(typeof msg.id, 'string', 'msg.id is a string')
                        t.ok(msg.ack, 'Got a msg.ack')
                        t.equal(typeof msg.ack, 'string', 'msg.ack is a string')
                        t.ok(msg.tries, 'Got a msg.tries')
                        t.equal(typeof msg.tries, 'number', 'msg.tries is a number')
                        t.equal(msg.tries, 1, 'msg.tries is currently one')
                        t.equal(msg.payload, 'Hello, World!', 'Payload is correct')
                        next()
                    })
                },
                function(next) {
                    queue.ack(msg.ack, function(err, id) {
                        t.ok(!err, 'No error when acking the message')
                        t.ok(id, 'Received an id when acking this message')
                        next()
                    })
                },
                function(next) {
                    queue.ack(msg.ack, function(err, id) {
                        t.ok(err, 'There is an error when acking the message again')
                        t.ok(!id, 'No id received when trying to ack an already deleted message')
                        next()
                    })
                },
            ],
            function(err) {
                t.ok(!err, 'No error during single round-trip when trying to double ack')
                t.end()
            }
        )
    })

    test('client.close()', function(t) {
        t.pass('client.close()')
        client.close()
        t.end()
    })

})


================================================
FILE: test/delay.js
================================================
var async = require('async')
var test = require('tape')

var setup = require('./setup.js')
var mongoDbQueue = require('../')

setup(function(client, db) {

    test('delay: check messages on this queue are returned after the delay', function(t) {
        var queue = mongoDbQueue(db, 'delay', { delay : 3 })

        async.series(
            [
                function(next) {
                    queue.add('Hello, World!', function(err, id) {
                        t.ok(!err, 'There is no error when adding a message.')
                        t.ok(id, 'There is an id returned when adding a message.')
                        next()
                    })
                },
                function(next) {
                    // get something now and it shouldn't be there
                    queue.get(function(err, msg) {
                        t.ok(!err, 'No error when getting no messages')
                        t.ok(!msg, 'No msg received')
                        // now wait 4s
                        setTimeout(next, 4 * 1000)
                    })
                },
                function(next) {
                    // get something now and it SHOULD be there
                    queue.get(function(err, msg) {
                        t.ok(!err, 'No error when getting a message')
                        t.ok(msg.id, 'Got a message id now that the message delay has passed')
                        queue.ack(msg.ack, next)
                    })
                },
                function(next) {
                    queue.get(function(err, msg) {
                        // no more messages
                        t.ok(!err, 'No error when getting no messages')
                        t.ok(!msg, 'No more messages')
                        next()
                    })
                },
            ],
            function(err) {
                if (err) t.fail(err)
                t.pass('Finished test ok')
                t.end()
            }
        )
    })

    test('delay: check an individual message delay overrides the queue delay', function(t) {
        var queue = mongoDbQueue(db, 'delay')

        async.series(
            [
                function(next) {
                  queue.add('I am delayed by 3 seconds', { delay : 3 }, function(err, id) {
                        t.ok(!err, 'There is no error when adding a message.')
                        t.ok(id, 'There is an id returned when adding a message.')
                        next()
                    })
                },
                function(next) {
                    // get something now and it shouldn't be there
                    queue.get(function(err, msg) {
                        t.ok(!err, 'No error when getting no messages')
                        t.ok(!msg, 'No msg received')
                        // now wait 4s
                        setTimeout(next, 4 * 1000)
                    })
                },
                function(next) {
                    // get something now and it SHOULD be there
                    queue.get(function(err, msg) {
                        t.ok(!err, 'No error when getting a message')
                        t.ok(msg.id, 'Got a message id now that the message delay has passed')
                        queue.ack(msg.ack, next)
                    })
                },
                function(next) {
                    queue.get(function(err, msg) {
                        // no more messages
                        t.ok(!err, 'No error when getting no messages')
                        t.ok(!msg, 'No more messages')
                        next()
                    })
                },
            ],
            function(err) {
                if (err) t.fail(err)
                t.pass('Finished test ok')
                t.end()
            }
        )
    })

    test('client.close()', function(t) {
        t.pass('client.close()')
        client.close()
        t.end()
    })

})


================================================
FILE: test/indexes.js
================================================
var async = require('async')
var test = require('tape')

var setup = require('./setup.js')
var mongoDbQueue = require('../')

setup(function(client, db) {

    test('visibility: check message is back in queue after 3s', function(t) {
        t.plan(2)

        var queue = mongoDbQueue(db, 'visibility', { visibility : 3 })

        queue.createIndexes(function(err, indexName) {
            t.ok(!err, 'There was no error when running .ensureIndexes()')
            t.ok(indexName, 'receive indexName we created')
            t.end()
        })
    })

    test('client.close()', function(t) {
        t.pass('client.close()')
        client.close()
        t.end()
    })

})


================================================
FILE: test/many.js
================================================
var async = require('async')
var test = require('tape')

var setup = require('./setup.js')
var mongoDbQueue = require('../')

var total = 250

setup(function(client, db) {

    test('many: add ' + total + ' messages, get ' + total + ' back', function(t) {
        var queue = mongoDbQueue(db, 'many')
        var msgs = []
        var msgsToQueue = []

        async.series(
            [
                function(next) {
                    var i
                    for(i=0; i<total; i++) {
                        msgsToQueue.push('no=' + i)
                    }
                    queue.add(msgsToQueue, function(err) {
                        if (err) return t.fail('Failed adding a message')
                        t.pass('All ' + total + ' messages sent to MongoDB')
                        next()
                    })
                },
                function(next) {
                    function getOne() {
                        queue.get(function(err, msg) {
                            if (err || !msg) return t.fail('Failed getting a message')
                            msgs.push(msg)
                            if (msgs.length === total) {
                                t.pass('Received all ' + total + ' messages')
                                next()
                            }
                            else {
                                getOne()
                            }
                        })
                    }
                    getOne()
                },
                function(next) {
                    var acked = 0
                    msgs.forEach(function(msg) {
                        queue.ack(msg.ack, function(err) {
                            if (err) return t.fail('Failed acking a message')
                            acked++
                            if (acked === total) {
                                t.pass('Acked all ' + total + ' messages')
                                next()
                            }
                        })
                    })
                },
            ],
            function(err) {
                if (err) t.fail(err)
                t.pass('Finished test ok')
                t.end()
            }
        )
    })

    test('many: add no messages, receive err in callback', function(t) {
        var queue = mongoDbQueue(db, 'many')
        var messages = []
        queue.add([], function(err) {
            if (!err) t.fail('Error was not received')
            t.pass('Finished test ok')
            t.end()
        });
    })

    test('client.close()', function(t) {
        t.pass('client.close()')
        client.close()
        t.end()
    })

})


================================================
FILE: test/multi.js
================================================
var async = require('async')
var test = require('tape')

var setup = require('./setup.js')
var mongoDbQueue = require('../')

var total = 250

setup(function(client, db) {

    test('multi: add ' + total + ' messages, get ' + total + ' back', function(t) {
        var queue = mongoDbQueue(db, 'multi')
        var msgs = []

        async.series(
            [
                function(next) {
                    var i, done = 0
                    for(i=0; i<total; i++) {
                        queue.add('no=' + i, function(err) {
                            if (err) return t.fail('Failed adding a message')
                            done++
                            if (done === total) {
                                t.pass('All ' + total + ' messages sent to MongoDB')
                                next()
                            }
                        })
                    }
                },
                function(next) {
                    function getOne() {
                        queue.get(function(err, msg) {
                            if (err) return t.fail('Failed getting a message')
                            msgs.push(msg)
                            if (msgs.length === total) {
                                t.pass('Received all ' + total + ' messages')
                                next()
                            }
                            else {
                                getOne()
                            }
                        })
                    }
                    getOne()
                },
                function(next) {
                    var acked = 0
                    msgs.forEach(function(msg) {
                        queue.ack(msg.ack, function(err) {
                            if (err) return t.fail('Failed acking a message')
                            acked++
                            if (acked === total) {
                                t.pass('Acked all ' + total + ' messages')
                                next()
                            }
                        })
                    })
                },
            ],
            function(err) {
                if (err) t.fail(err)
                t.pass('Finished test ok')
                t.end()
            }
        )
    })

    test('client.close()', function(t) {
        t.pass('client.close()')
        client.close()
        t.end()
    })

})


================================================
FILE: test/ping.js
================================================
var async = require('async')
var test = require('tape')

var setup = require('./setup.js')
var mongoDbQueue = require('../')

setup(function(client, db) {

    test('ping: check a retrieved message with a ping can still be acked', function(t) {
        var queue = mongoDbQueue(db, 'ping', { visibility : 5 })
        var msg

        async.series(
            [
                function(next) {
                    queue.add('Hello, World!', function(err, id) {
                        t.ok(!err, 'There is no error when adding a message.')
                        t.ok(id, 'There is an id returned when adding a message.')
                        next()
                    })
                },
                function(next) {
                    // get something now and it shouldn't be there
                    queue.get(function(err, thisMsg) {
                        msg = thisMsg
                        t.ok(!err, 'No error when getting this message')
                        t.ok(msg.id, 'Got this message id')
                        // now wait 4s
                        setTimeout(next, 4 * 1000)
                    })
                },
                function(next) {
                    // ping this message so it will be kept alive longer, another 5s
                    queue.ping(msg.ack, function(err, id) {
                        t.ok(!err, 'No error when pinging a message')
                        t.ok(id, 'Received an id when acking this message')
                        // now wait 4s
                        setTimeout(next, 4 * 1000)
                    })
                },
                function(next) {
                    queue.ack(msg.ack, function(err, id) {
                        t.ok(!err, 'No error when acking this message')
                        t.ok(id, 'Received an id when acking this message')
                        next()
                    })
                },
                function(next) {
                    queue.get(function(err, msg) {
                        t.ok(!err, 'No error when getting no messages')
                        t.ok(!msg, 'No message when getting from an empty queue')
                        next()
                    })
                },
            ],
            function(err) {
                if (err) t.fail(err)
                t.pass('Finished test ok')
                t.end()
            }
        )
    })

    test("ping: check that an acked message can't be pinged", function(t) {
        var queue = mongoDbQueue(db, 'ping', { visibility : 5 })
        var msg

        async.series(
            [
                function(next) {
                    queue.add('Hello, World!', function(err, id) {
                        t.ok(!err, 'There is no error when adding a message.')
                        t.ok(id, 'There is an id returned when adding a message.')
                        next()
                    })
                },
                function(next) {
                    // get something now and it shouldn't be there
                    queue.get(function(err, thisMsg) {
                        msg = thisMsg
                        t.ok(!err, 'No error when getting this message')
                        t.ok(msg.id, 'Got this message id')
                        next()
                    })
                },
                function(next) {
                    // ack the message
                    queue.ack(msg.ack, function(err, id) {
                        t.ok(!err, 'No error when acking this message')
                        t.ok(id, 'Received an id when acking this message')
                        next()
                    })
                },
                function(next) {
                    // ping this message, even though it has been acked
                    queue.ping(msg.ack, function(err, id) {
                        t.ok(err, 'Error when pinging an acked message')
                        t.ok(!id, 'Received no id when pinging an acked message')
                        next()
                    })
                },
            ],
            function(err) {
                if (err) t.fail(err)
                t.pass('Finished test ok')
                t.end()
            }
        )
    })

test("ping: check visibility option overrides the queue visibility", function(t) {
        var queue = mongoDbQueue(db, 'ping', { visibility : 3 })
        var msg

        async.series(
            [
                function(next) {
                    queue.add('Hello, World!', function(err, id) {
                        t.ok(!err, 'There is no error when adding a message.')
                        t.ok(id, 'There is an id returned when adding a message.')
                        next()
                    })
                },
                function(next) {
                    queue.get(function(err, thisMsg) {
                        msg = thisMsg
                        // message should reset in three seconds
                        t.ok(msg.id, 'Got a msg.id (sanity check)')
                        setTimeout(next, 2 * 1000)
                    })
                },
                function(next) {
                    // ping this message so it will be kept alive longer, another 5s instead of 3s
                    queue.ping(msg.ack, { visibility: 5 }, function(err, id) {
                        t.ok(!err, 'No error when pinging a message')
                        t.ok(id, 'Received an id when acking this message')
                        // wait 4s so the msg would normally have returns to the queue
                        setTimeout(next, 4 * 1000)
                    })
                },
                function(next) {
                    queue.get(function(err, msg) {
                        // messages should not be back yet
                        t.ok(!err, 'No error when getting no messages')
                        t.ok(!msg, 'No msg received')
                        // wait 2s so the msg should have returns to the queue
                        setTimeout(next, 2 * 1000)
                    })
                },
                function(next) {
                    queue.get(function(err, msg) {
                        // yes, there should be a message on the queue again
                        t.ok(msg.id, 'Got a msg.id (sanity check)')
                        queue.ack(msg.ack, function(err) {
                            t.ok(!err, 'No error when acking the message')
                            next()
                        })
                    })
                },
                function(next) {
                    queue.get(function(err, msg) {
                        // no more messages
                        t.ok(!err, 'No error when getting no messages')
                        t.ok(!msg, 'No msg received')
                        next()
                    })
                }
            ],
            function(err) {
                if (err) t.fail(err)
                t.pass('Finished test ok')
                t.end()
            }
        )
    })

    test('client.close()', function(t) {
        t.pass('client.close()')
        client.close()
        t.end()
    })

})


================================================
FILE: test/setup.js
================================================
const mongodb = require('mongodb')

const url = 'mongodb://localhost:27017/'
const dbName = 'mongodb-queue'

const collections = [
  'default',
  'delay',
  'multi',
  'visibility',
  'clean',
  'ping',
  'stats1',
  'stats2',
  'queue',
  'dead-queue',
  'queue-2',
  'dead-queue-2',
]

module.exports = function(callback) {
  const client = new mongodb.MongoClient(url, { useNewUrlParser: true })

  client.connect(err => {
    // we can throw since this is test-only
    if (err) throw err

    const db = client.db(dbName)

    // empty out some collections to make sure there are no messages
    let done = 0
    collections.forEach((col) => {
      db.collection(col).deleteMany(() => {
        done += 1
        if ( done === collections.length ) {
          callback(client, db)
        }
      })
    })
  })

}


================================================
FILE: test/stats.js
================================================
var async = require('async')
var test = require('tape')

var setup = require('./setup.js')
var mongoDbQueue = require('../')

setup(function(client, db) {

    test('first test', function(t) {
        var queue = mongoDbQueue(db, 'stats')
        t.ok(queue, 'Queue created ok')
        t.end()
    });

    test('stats for a single message added, received and acked', function(t) {
        var queue = mongoDbQueue(db, 'stats1')
        var msg

        async.series(
            [
                function(next) {
                    queue.add('Hello, World!', function(err, id) {
                        t.ok(!err, 'There is no error when adding a message.')
                        t.ok(id, 'Received an id for this message')
                        next()
                    })
                },
                function(next) {
                    queue.total(function(err, count) {
                        t.equal(count, 1, 'Total number of messages is one')
                        next()
                    })
                },
                function(next) {
                    queue.size(function(err, count) {
                        t.equal(count, 1, 'Size of queue is one')
                        next()
                    })
                },
                function(next) {
                    queue.inFlight(function(err, count) {
                        t.equal(count, 0, 'There are no inFlight messages')
                        next()
                    })
                },
                function(next) {
                    queue.done(function(err, count) {
                        t.equal(count, 0, 'There are no done messages')
                        next()
                    })
                },
                function(next) {
                    // let's set one to be inFlight
                    queue.get(function(err, newMsg) {
                        msg = newMsg
                        next()
                    })
                },
                function(next) {
                    queue.total(function(err, count) {
                        t.equal(count, 1, 'Total number of messages is still one')
                        next()
                    })
                },
                function(next) {
                    queue.size(function(err, count) {
                        t.equal(count, 0, 'Size of queue is now zero (ie. none to come)')
                        next()
                    })
                },
                function(next) {
                    queue.inFlight(function(err, count) {
                        t.equal(count, 1, 'There is one inflight message')
                        next()
                    })
                },
                function(next) {
                    queue.done(function(err, count) {
                        t.equal(count, 0, 'There are still no done messages')
                        next()
                    })
                },
                function(next) {
                    // now ack that message
                    queue.ack(msg.ack, function(err, newMsg) {
                        msg = newMsg
                        next()
                    })
                },
                function(next) {
                    queue.total(function(err, count) {
                        t.equal(count, 1, 'Total number of messages is again one')
                        next()
                    })
                },
                function(next) {
                    queue.size(function(err, count) {
                        t.equal(count, 0, 'Size of queue is still zero (ie. none to come)')
                        next()
                    })
                },
                function(next) {
                    queue.inFlight(function(err, count) {
                        t.equal(count, 0, 'There are no inflight messages anymore')
                        next()
                    })
                },
                function(next) {
                    queue.done(function(err, count) {
                        t.equal(count, 1, 'There is now one processed message')
                        next()
                    })
                },
            ],
            function(err) {
                t.ok(!err, 'No error when doing stats on one message')
                t.end()
            }
        )
    })


    // ToDo: add more tests for adding a message, getting it and letting it lapse
    // then re-checking all stats.

    test('stats for a single message added, received, timed-out and back on queue', function(t) {
        var queue = mongoDbQueue(db, 'stats2', { visibility : 3 })

        async.series(
            [
                function(next) {
                    queue.add('Hello, World!', function(err, id) {
                        t.ok(!err, 'There is no error when adding a message.')
                        t.ok(id, 'Received an id for this message')
                        next()
                    })
                },
                function(next) {
                    queue.total(function(err, count) {
                        t.equal(count, 1, 'Total number of messages is one')
                        next()
                    })
                },
                function(next) {
                    queue.size(function(err, count) {
                        t.equal(count, 1, 'Size of queue is one')
                        next()
                    })
                },
                function(next) {
                    queue.inFlight(function(err, count) {
                        t.equal(count, 0, 'There are no inFlight messages')
                        next()
                    })
                },
                function(next) {
                    queue.done(function(err, count) {
                        t.equal(count, 0, 'There are no done messages')
                        next()
                    })
                },
                function(next) {
                    // let's set one to be inFlight
                    queue.get(function(err, msg) {
                        // msg is ignored, we don't care about the message here
                        setTimeout(next, 4 * 1000)
                    })
                },
                function(next) {
                    queue.total(function(err, count) {
                        t.equal(count, 1, 'Total number of messages is still one')
                        next()
                    })
                },
                function(next) {
                    queue.size(function(err, count) {
                        t.equal(count, 1, 'Size of queue is still at one')
                        next()
                    })
                },
                function(next) {
                    queue.inFlight(function(err, count) {
                        t.equal(count, 0, 'There are no inflight messages again')
                        next()
                    })
                },
                function(next) {
                    queue.done(function(err, count) {
                        t.equal(count, 0, 'There are still no done messages')
                        next()
                    })
                },
            ],
            function(err) {
                t.ok(!err, 'No error when doing stats on one message')
                t.end()
            }
        )
    })

    test('client.close()', function(t) {
        t.pass('client.close()')
        client.close()
        t.end()
    })

})



================================================
FILE: test/visibility.js
================================================
var async = require('async')
var test = require('tape')

var setup = require('./setup.js')
var mongoDbQueue = require('../')

setup(function(client, db) {

    test('visibility: check message is back in queue after 3s', function(t) {
        var queue = mongoDbQueue(db, 'visibility', { visibility : 3 })

        async.series(
            [
                function(next) {
                    queue.add('Hello, World!', function(err) {
                        t.ok(!err, 'There is no error when adding a message.')
                        next()
                    })
                },
                function(next) {
                    queue.get(function(err, msg) {
                        // wait over 3s so the msg returns to the queue
                        t.ok(msg.id, 'Got a msg.id (sanity check)')
                        setTimeout(next, 4 * 1000)
                    })
                },
                function(next) {
                    queue.get(function(err, msg) {
                        // yes, there should be a message on the queue again
                        t.ok(msg.id, 'Got a msg.id (sanity check)')
                        queue.ack(msg.ack, function(err) {
                            t.ok(!err, 'No error when acking the message')
                            next()
                        })
                    })
                },
                function(next) {
                    queue.get(function(err, msg) {
                        // no more messages
                        t.ok(!err, 'No error when getting no messages')
                        t.ok(!msg, 'No msg received')
                        next()
                    })
                },
            ],
            function(err) {
                if (err) t.fail(err)
                t.pass('Finished test ok')
                t.end()
            }
        )
    })

    test("visibility: check that a late ack doesn't remove the msg", function(t) {
        var queue = mongoDbQueue(db, 'visibility', { visibility : 3 })
        var originalAck

        async.series(
            [
                function(next) {
                    queue.add('Hello, World!', function(err) {
                        t.ok(!err, 'There is no error when adding a message.')
                        next()
                    })
                },
                function(next) {
                    queue.get(function(err, msg) {
                        t.ok(msg.id, 'Got a msg.id (sanity check)')

                        // remember this original ack
                        originalAck = msg.ack

                        // wait over 3s so the msg returns to the queue
                        setTimeout(function() {
                            t.pass('Back from timeout, now acking the message')

                            // now ack the message but too late - it shouldn't be deleted
                            queue.ack(msg.ack, function(err, msg) {
                                t.ok(err, 'Got an error when acking the message late')
                                t.ok(!msg, 'No message was updated')
                                next()
                            })
                        }, 4 * 1000)
                    })
                },
                function(next) {
                    queue.get(function(err, msg) {
                        // the message should now be able to be retrieved, with a new 'ack' id
                        t.ok(msg.id, 'Got a msg.id (sanity check)')
                        t.notEqual(msg.ack, originalAck, 'Original ack and new ack are different')

                        // now ack this new retrieval
                        queue.ack(msg.ack, next)
                    })
                },
                function(next) {
                    queue.get(function(err, msg) {
                        // no more messages
                        t.ok(!err, 'No error when getting no messages')
                        t.ok(!msg, 'No msg received')
                        next()
                    })
                },
            ],
            function(err) {
                if (err) t.fail(err)
                t.pass('Finished test ok')
                t.end()
            }
        )
    })

    test("visibility: check visibility option overrides the queue visibility", function(t) {
        var queue = mongoDbQueue(db, 'visibility', { visibility : 2 })
        var originalAck

        async.series(
            [
                function(next) {
                    queue.add('Hello, World!', function(err) {
                        t.ok(!err, 'There is no error when adding a message.')
                        next()
                    })
                },
                function(next) {
                    queue.get({ visibility: 4 }, function(err, msg) {
                        // wait over 2s so the msg would normally have returns to the queue
                        t.ok(msg.id, 'Got a msg.id (sanity check)')
                        setTimeout(next, 3 * 1000)
                    })
                },
                function(next) {
                    queue.get(function(err, msg) {
                        // messages should not be back yet
                        t.ok(!err, 'No error when getting no messages')
                        t.ok(!msg, 'No msg received')
                        // wait 2s so the msg should have returns to the queue
                        setTimeout(next, 2 * 1000)
                    })
                },
                function(next) {
                    queue.get(function(err, msg) {
                        // yes, there should be a message on the queue again
                        t.ok(msg.id, 'Got a msg.id (sanity check)')
                        queue.ack(msg.ack, function(err) {
                            t.ok(!err, 'No error when acking the message')
                            next()
                        })
                    })
                },
                function(next) {
                    queue.get(function(err, msg) {
                        // no more messages
                        t.ok(!err, 'No error when getting no messages')
                        t.ok(!msg, 'No msg received')
                        next()
                    })
                }
            ],
            function(err) {
                if (err) t.fail(err)
                t.pass('Finished test ok')
                t.end()
            }
        )
    })

    test('client.close()', function(t) {
        t.pass('client.close()')
        client.close()
        t.end()
    })

})
Download .txt
gitextract_5_hou0nf/

├── .gitignore
├── .travis.yml
├── README.md
├── mongodb-queue.js
├── package.json
└── test/
    ├── clean.js
    ├── dead-queue.js
    ├── default.js
    ├── delay.js
    ├── indexes.js
    ├── many.js
    ├── multi.js
    ├── ping.js
    ├── setup.js
    ├── stats.js
    └── visibility.js
Download .txt
SYMBOL INDEX (6 symbols across 3 files)

FILE: mongodb-queue.js
  function id (line 16) | function id() {
  function now (line 20) | function now() {
  function nowPlusSecs (line 24) | function nowPlusSecs(secs) {
  function Queue (line 33) | function Queue(db, name, opts) {

FILE: test/many.js
  function getOne (line 30) | function getOne() {

FILE: test/multi.js
  function getOne (line 31) | function getOne() {
Condensed preview — 16 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (78K chars).
[
  {
    "path": ".gitignore",
    "chars": 24,
    "preview": "node_modules/*\n*.log\n*~\n"
  },
  {
    "path": ".travis.yml",
    "chars": 71,
    "preview": "language: node_js\nnode_js:\n  - \"8\"\n  - \"10\"\n  - \"11\"\nservices: mongodb\n"
  },
  {
    "path": "README.md",
    "chars": 17338,
    "preview": "# mongodb-queue #\n\n[![Build Status](https://travis-ci.org/chilts/mongodb-queue.png)](https://travis-ci.org/chilts/mongod"
  },
  {
    "path": "mongodb-queue.js",
    "chars": 6854,
    "preview": "/**\n *\n * mongodb-queue.js - Use your existing MongoDB as a local queue.\n *\n * Copyright (c) 2014 Andrew Chilton\n * - ht"
  },
  {
    "path": "package.json",
    "chars": 816,
    "preview": "{\n  \"name\": \"mongodb-queue\",\n  \"version\": \"5.0.0\",\n  \"description\": \"Message queues which uses MongoDB.\",\n  \"main\": \"mon"
  },
  {
    "path": "test/clean.js",
    "chars": 6345,
    "preview": "var async = require('async')\nvar test = require('tape')\n\nvar setup = require('./setup.js')\nvar mongoDbQueue = require('."
  },
  {
    "path": "test/dead-queue.js",
    "chars": 7282,
    "preview": "var async = require('async')\nvar test = require('tape')\n\nvar setup = require('./setup.js')\nvar mongoDbQueue = require('."
  },
  {
    "path": "test/default.js",
    "chars": 4298,
    "preview": "var async = require('async')\nvar test = require('tape')\n\nvar setup = require('./setup.js')\nvar mongoDbQueue = require('."
  },
  {
    "path": "test/delay.js",
    "chars": 3980,
    "preview": "var async = require('async')\nvar test = require('tape')\n\nvar setup = require('./setup.js')\nvar mongoDbQueue = require('."
  },
  {
    "path": "test/indexes.js",
    "chars": 678,
    "preview": "var async = require('async')\nvar test = require('tape')\n\nvar setup = require('./setup.js')\nvar mongoDbQueue = require('."
  },
  {
    "path": "test/many.js",
    "chars": 2687,
    "preview": "var async = require('async')\nvar test = require('tape')\n\nvar setup = require('./setup.js')\nvar mongoDbQueue = require('."
  },
  {
    "path": "test/multi.js",
    "chars": 2435,
    "preview": "var async = require('async')\nvar test = require('tape')\n\nvar setup = require('./setup.js')\nvar mongoDbQueue = require('."
  },
  {
    "path": "test/ping.js",
    "chars": 7229,
    "preview": "var async = require('async')\nvar test = require('tape')\n\nvar setup = require('./setup.js')\nvar mongoDbQueue = require('."
  },
  {
    "path": "test/setup.js",
    "chars": 821,
    "preview": "const mongodb = require('mongodb')\n\nconst url = 'mongodb://localhost:27017/'\nconst dbName = 'mongodb-queue'\n\nconst colle"
  },
  {
    "path": "test/stats.js",
    "chars": 7507,
    "preview": "var async = require('async')\nvar test = require('tape')\n\nvar setup = require('./setup.js')\nvar mongoDbQueue = require('."
  },
  {
    "path": "test/visibility.js",
    "chars": 6625,
    "preview": "var async = require('async')\nvar test = require('tape')\n\nvar setup = require('./setup.js')\nvar mongoDbQueue = require('."
  }
]

About this extraction

This page contains the full source code of the chilts/mongodb-queue GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 16 files (73.2 KB), approximately 15.9k tokens, and a symbol index with 6 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.

Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.

Copied to clipboard!