Code Monkey home page Code Monkey logo

mongo-leader's Introduction

mongo-leader

Build Status Dependencies Status Codacy Badge Codacy BadgeMaintainability NPM NPM downloads

mongo-leader is a Node.js package for leader election backed by MongoDB. It is inspired by the redis-leader library. The main class Leader extends the Node.js EventEmmiter class, allowing instances to emit events when they gain or lose leadership status. This makes it a powerful tool for managing distributed systems where only one instance should be in control at any given time.

Install

To install mongo-leader package with npm, you can use the following command:

npm install mongo-leader

Usage

const client = await MongoClient.connect(url)

const leader = new Leader(client.db('test'))
await leader.start() // Optional. If not called, a lazy start is initiated when isLeader is called for the first time.

setInterval(async () => {
  const isLeader = await leader.isLeader()
  console.log(`Am I leader? : ${isLeader}`)
}, 100)

Upgrade from a version earlier than 1.1.144

Breaking changes have been made when upgrading from a version earlier than 1.1.144. All asynchronous operations have been shifted from the constructor to a new method named start(), which needs to be called separately like in the example above.

API

new Leader(db, options)

Creates a new Leader instance.

Parameters

  • db: A MongoClient object.
  • options: An object with the following properties:
    • ttl: Lock time to live in milliseconds. The lock will be automatically released after this time. Default and minimum values are 1000.
    • wait: Time between tries getting elected in milliseconds. Default and minimum values are 100.
    • key: Unique identifier for the group of instances trying to be elected as leader. Default value is 'default'.

When the Leader constructor is invoked, it immediately initiates the election process to become the leader. This means that as soon as a Leader instance is created, it starts competing with other instances (if any) to gain the leadership role. This is done by attempting to acquire a lock in the MongoDB collection. If the lock is successfully acquired, the instance becomes the leader. The lock has a time-to-live (TTL) associated with it, after which it is automatically released. This allows for a continuous and dynamic leadership election process where leadership can change over time, especially in scenarios where the current leader instance becomes unavailable or is shut down.

start()

This method triggers the election process. It carries out the required setup in database and kick-starts the election procedure.

isLeader()

This method checks whether the current instance is the leader or not. It returns a Promise that resolves to a boolean value. If the returned value is true, it means the current instance is the leader. If the returned value is false, it means the current instance is not the leader. If the instance has not been initialized yet, a lazy start is performed.

pause()

This method is used to pause the leader election process. When called, the instance will stop trying to become a leader. This can be useful in scenarios where you want to manually control when your instance is trying to become a leader.

Note: The pause() method does not make the instance resign if it is currently a leader. It simply stops the instance from attempting to become a leader in the future.

resume()

This method is used to resume the leader election process. When called, the instance will start trying to become a leader again. This can be useful in scenarios where you have previously paused the leader election process and now want to allow your instance to become a leader again.

Note: The resume() method does not make the instance become a leader immediately. It simply allows the instance to start attempting to become a leader again.

Events

elected

The elected event is emitted when the instance successfully becomes a leader. This event can be listened to in order to perform actions that should only be done by the leader instance. For example, you might want to start certain tasks or services only when the instance has been elected as the leader.

revoked

The revoked event is emitted when the instance loses its leadership status. This event can be listened to in order to perform actions when the instance is no longer the leader. For example, you might want to stop certain tasks or services when the instance has been revoked from being the leader.

License

This project is licensed under the MIT License.

mongo-leader's People

Contributors

andrewmolyuk avatar dependabot-preview[bot] avatar dependabot[bot] avatar depfu[bot] avatar kapcsandi avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar

mongo-leader's Issues

Depfu Error: No dependency files found

Hello,

We've tried to activate or update your repository on Depfu and couldn't find any supported dependency files. If we were to guess, we would say that this is not actually a project Depfu supports and has probably been activated by error.

Monorepos

Please note that Depfu currently only searches for your dependency files in the root folder. We do support monorepos and non-root files, but don't auto-detect them. If that's the case with this repo, please send us a quick email with the folder you want Depfu to work on and we'll set it up right away!

How to deactivate the project

  • Go to the Settings page of either your own account or the organization you've used
  • Go to "Installed Integrations"
  • Click the "Configure" button on the Depfu integration
  • Remove this repo (andrewmolyuk/mongo-leader) from the list of accessible repos.

Please note that using the "All Repositories" setting doesn't make a lot of sense with Depfu.

If you think that this is a mistake

Please let us know by sending an email to [email protected].


This is an automated issue by Depfu. You're getting it because someone configured Depfu to automatically update dependencies on this project.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.