UNPKG

zookeeper

Version:

apache zookeeper client (zookeeper async API v3.5.x - v3.8.x)

56 lines (45 loc) 1.45 kB
const { constants } = require('./wrapper'); const notifier = require('./notifier'); const logger = require('./logger'); function emit(client, path) { logger.log(`Elect leader: (${path}) ${client.client_id}`); notifier.emit('leader'); } function onData(client, path, rc, error, stat, data) { const clientId = client.client_id; if (data && data.toString() === clientId) { emit(client, path); } } async function watcher(client, path, checkFunc, retryFunc, rc) { if (rc === -1) { await checkFunc(client, path, retryFunc); } else if (rc === 2) { await retryFunc(client, path); } } async function checkMaster(client, path, retryFunc) { const watchFunc = watcher.bind(null, client, path, checkMaster, retryFunc); try { const res = await client.w_get(path, watchFunc); onData(client, path, res.rc, res.error, res.stat, res.data); } catch (error) { logger.error('checkMaster:', error.message); } } async function runForLeader(client, path) { const clientId = client.client_id; try { await client.create(path, `${clientId}`, constants.ZOO_EPHEMERAL); emit(client, path); } catch (error) { logger.error('runForLeader:', error.message); await checkMaster(client, path, runForLeader); } } async function electLeader(client, path) { runForLeader(client, path); } module.exports = { electLeader, };