falkordb
Version:
A FalkorDB javascript library
83 lines (82 loc) • 2.99 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.Sentinel = void 0;
const single_1 = require("./single");
const client_1 = require("@redis/client");
function extractDetails(masters) {
const allDetails = [];
for (const master of masters) {
const details = {};
for (let i = 0; i < master.length; i += 2) {
details[master[i]] = master[i + 1];
}
allDetails.push(details);
}
return allDetails;
}
class Sentinel extends single_1.Single {
sentinelClient;
init(falkordb) {
const redisOption = (this.client.options ?? {});
return this.tryConnectSentinelServer(this.client, redisOption, falkordb);
}
/**
* Connect to the server using the details from sentinel server
* Register error event to reconnect on error from the sentinel server
*/
async tryConnectSentinelServer(client, redisOption, falkordb) {
// TODO support multi sentinels
const masters = await client.falkordb.sentinelMasters();
const details = extractDetails(masters);
if (details.length > 1) {
throw new Error("Multiple masters are not supported");
}
// Connect to the server with the details from sentinel
const socketOptions = {
...redisOption.socket,
host: details[0]["ip"],
port: parseInt(details[0]["port"]),
};
const serverOptions = {
...redisOption,
socket: socketOptions,
};
const realClient = (0, client_1.createClient)(serverOptions);
// Save sentinel client to quit on quit()
this.sentinelClient = client;
// Set original client as sentinel and server client as client
this.client = realClient;
await realClient
.on("error", async (err) => {
console.debug("Error on server connection", err);
// Disconnect the client to avoid further errors and retries
realClient.disconnect();
// If error occurs on previous server connection, no need to reconnect
if (this.client !== realClient) {
return;
}
try {
await this.tryConnectSentinelServer(client, redisOption, falkordb);
console.debug("Connected to server");
}
catch (e) {
console.debug("Error on server reconnect", e);
// Forward errors if reconnection fails
falkordb.emit("error", err);
}
})
.connect();
}
quit() {
return this.disconnect();
}
async disconnect() {
const promises = [super.disconnect()];
if (this.sentinelClient) {
const reply = this.sentinelClient.disconnect();
promises.push(reply.then(() => { }));
}
return Promise.all(promises).then(() => { });
}
}
exports.Sentinel = Sentinel;