npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

leader-election-mongo

v0.0.2

Published

Leader election backed by MongoDB

Downloads

7

Readme

leader-election-mongo

A leader election package which uses MongoDB. A single leader is chosen from a group of instances in a single, non-recurring election.

Use cases

This package is useful when doing a single election for tasks such as a once-daily cron job (as opposed to having a group of instances continuously trying to determine a leader). It is intended for a relatively small number of instances, such as 5 or 10, not 10,000.

Install

npm install leader-election-mongo

Example

Here is an example using promises:

const crypto = require('crypto')
const { Leader } = require('leader-election-mongo')
const { MongoClient } = require('mongodb')

const url = 'mongodb://localhost:27017'

MongoClient.connect(
    url,
    {
        useNewUrlParser: true,
        useUnifiedTopology: true
    },
    function (err, client) {
        const id = process.pid + '-' + crypto.randomBytes(8).toString('hex')
        const db = client.db('leadertest')
        const candidate = new Leader(db, { id, ttl: 10000 })

        candidate
            .initDatabase()
            .then(collectionExists => {
                if (collectionExists) {
                    return candidate.elect()
                }
                console.log(`${id} collection was not initialized!`)
                process.exit()
            })
            .then(isLeader => {
                if (isLeader) {
                    console.log(`${id} is the LEADER`)
                    // do your stuff here
                    return candidate.cleanup()
                } else {
                    console.log(`${id} is not the leader`)
                    process.exit()
                }
            })
            .then(() => {
                console.log(`${id} Cleanup finished`)
                process.exit()
            })
    }
)

This package can also be used with async/await:

const crypto = require('crypto')
const { Leader } = require('leader-election-mongo')
const { MongoClient } = require('mongodb')

const url = 'mongodb://localhost:27017'

MongoClient.connect(
    url,
    {
        useNewUrlParser: true,
        useUnifiedTopology: true
    },
    async function (err, client) {
        const id = process.pid + '-' + crypto.randomBytes(8).toString('hex')
        const db = client.db('leadertest')
        const candidate = new Leader(db, { id })

        const collectionExists = await candidate.initDatabase()
        if (!collectionExists) {
            console.log(`${id} collection was not initialized!`)
            process.exit()
        }

        const isLeader = await candidate.elect()
        if (!isLeader) {
            console.log(`${id} is not the leader`)
            process.exit()
        }

        console.log(`${id} is the LEADER`)
        // do your stuff here

        await candidate.cleanup()
        console.log(`${id} Cleanup finished`)
        process.exit()
    }
)

API

new Leader(db, options)

Create a new Leader class.

db is a MongoClient.Db object.

options.id is an optional ID for this instance. Default is a random hex string.

options.ttl is the lock time-to-live in milliseconds. Will be automatically released after that time. The default and minimum value is 5000.

If the provided MongoClient.Db object doesn't have admin privileges, the TTL cleanup will only happen every 60 seconds (the MongoDB default) which might cause a problem if the leader doesn't call cleanup() and you try to run multiple elections within 60 seconds.

options.key is a unique identifier for the group of instances trying to be elected as leader. Default value is 'default'

initDatabase()

Initializes the election collection. Returns a promise that resolves to a boolean indicating whether the collection exists.

elect()

Performs the election and returns a promise that resolves to true if the instance is the leader; otherwise, false.

cleanup()

Removes the election collection. Returns a promise that resolves to void.

Events

elected The event fired when the instance becomes a leader.

cleaned The event fired when the cleanup is finished.

License

See the LICENSE file (spoiler alert, it's Apache-2.0).

Credits

Inspired by the mongo-leader package, but with a modified API and different election algorithm.