UNPKG

1.72 kBJavaScriptView Raw
1"use strict";
2Object.defineProperty(exports, "__esModule", { value: true });
3exports.FailoverDetector = void 0;
4const utils_1 = require("../../utils");
5const debug = (0, utils_1.Debug)("FailoverDetector");
6const CHANNEL_NAME = "+switch-master";
7class FailoverDetector {
8 // sentinels can't be used for regular commands after this
9 constructor(connector, sentinels) {
10 this.isDisconnected = false;
11 this.connector = connector;
12 this.sentinels = sentinels;
13 }
14 cleanup() {
15 this.isDisconnected = true;
16 for (const sentinel of this.sentinels) {
17 sentinel.client.disconnect();
18 }
19 }
20 async subscribe() {
21 debug("Starting FailoverDetector");
22 const promises = [];
23 for (const sentinel of this.sentinels) {
24 const promise = sentinel.client.subscribe(CHANNEL_NAME).catch((err) => {
25 debug("Failed to subscribe to failover messages on sentinel %s:%s (%s)", sentinel.address.host || "127.0.0.1", sentinel.address.port || 26739, err.message);
26 });
27 promises.push(promise);
28 sentinel.client.on("message", (channel) => {
29 if (!this.isDisconnected && channel === CHANNEL_NAME) {
30 this.disconnect();
31 }
32 });
33 }
34 await Promise.all(promises);
35 }
36 disconnect() {
37 // Avoid disconnecting more than once per failover.
38 // A new FailoverDetector will be created after reconnecting.
39 this.isDisconnected = true;
40 debug("Failover detected, disconnecting");
41 // Will call this.cleanup()
42 this.connector.disconnect();
43 }
44}
45exports.FailoverDetector = FailoverDetector;