mongo-lead
Version:
Leader election backed by MongoDB
88 lines • 2.29 kB
TypeScript
import { Db } from 'mongodb';
import { EventEmitter } from 'events';
export interface LeaderOptions {
/** Collection name. @default 'leader' */
collectionName?: string;
/** Unique identifier for the group of instances trying to be elected as leader. @default 'default' */
groupName?: string;
/** Lock time to live in milliseconds. @minimum 1000 @default 1000 */
ttl?: number;
/** Time between tries getting elected in milliseconds. @minimum 500 @default 500 */
wait?: number;
}
/**
* Leader election backed by MongoDB
*
* @example
*
* ```ts
* import mongoose from 'mongoose'
* import Leader from 'mongo-lead'
*
*
* const leader = new Leader(mongoose.connection.db, {
* groupName: 'all-cron-jobs',
* ttl: 10000,
* wait: 1000,
* })
*
* leader.start()
*
* leader.on('elected', () => {
* console.log('Starting all cron jobs')
* // ...Rest of the code
* })
*
* leader.on('revoked', () => {
* console.log('Stopping all cron jobs')
* // ...Rest of the code
* })
* ```
*/
export default class Leader extends EventEmitter {
private id;
private db;
private options;
private paused;
private initiated;
constructor(db: Db, options?: LeaderOptions);
/**
* Checks if the current instance is the elected leader
*/
isLeader(): Promise<boolean>;
/**
* Attempts to elect this instance as the leader if the current leader expired
* If unsuccessful, retries after the configured wait period
*/
elect(): Promise<void>;
/**
* Renews the leadership status if this instance is the current leader
* If renewal fails, triggers new election process
*/
renew(): Promise<void>;
/**
* Pauses the leader election process
*/
pause(): void;
/**
* Resumes the leader election process
*/
resume(): Promise<void>;
/**
* Starts the leader election process
*/
start(): Promise<void>;
/**
* Initializes the database with required indexes and TTL settings
*/
private initDatabase;
/**
* Creates or retrieves the leader collection
*/
private createCollection;
/**
* Gets the leader collection
*/
private getCollection;
}
//# sourceMappingURL=index.d.ts.map