@ultipa-graph/ultipa-driver
Version:
NodeJS SDK for ultipa-server 5.2
103 lines • 3.73 kB
JavaScript
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.ConnectionPool = void 0;
const connection_final_1 = require("./connection.final");
const bluebird_1 = __importDefault(require("bluebird"));
/** Ultipa connection pool */
class ConnectionPool {
hosts;
username;
password;
crt;
defaultConfig;
currentIndex;
connectionCache = new Map();
constructor(hosts, username, password, crt, defaultConfig) {
this.hosts = hosts;
this.username = username;
this.password = password;
this.crt = crt;
this.defaultConfig = defaultConfig;
this.currentIndex = 0;
}
getOrCreateConnection(host, crt) {
const cacheKey = `${host}-${crt ? 'https' : 'http'}`;
if (!this.connectionCache.has(cacheKey)) {
const client = new connection_final_1.ConnectionFinal(host, this.username, this.password, crt || this.crt, this.defaultConfig);
this.connectionCache.set(cacheKey, client);
}
return this.connectionCache.get(cacheKey);
}
/** Get active client */
async getActive(hosts) {
hosts = hosts || this.hosts;
let client = await this._getActive(hosts);
if (!client.testConnectResult && !this.crt) {
try {
// https
let client_https = await this._getActive(hosts, this.crt);
console.log("try https:", hosts);
if (client_https.testConnectResult) {
return client_https;
}
}
catch (error) {
console.log(error);
}
}
return client;
}
async _getActive(hosts, crt) {
const availableClients = [];
await bluebird_1.default.map(hosts, async (host) => {
const client = this.getOrCreateConnection(host, crt);
const test = await client.test();
client.testConnectResult = test;
if (test) {
availableClients.push(client);
}
});
if (availableClients.length === 0) {
return this.getOrCreateConnection(hosts[hosts.length - 1], crt);
}
const randomIndex = Math.floor(Math.random() * availableClients.length);
return availableClients[randomIndex];
}
async _testActiveMaybeSlow(noBalanced = false) {
let m = noBalanced ? 0 : 1;
let client = null;
for (let index = 0; index < this.hosts.length; index++) {
let i = (index + this.currentIndex + m) % this.hosts.length;
let host = this.hosts[i];
client = this.getOrCreateConnection(host);
let test = await client.test();
if (test) {
this.currentIndex = i;
return client;
}
}
return client;
}
async test() {
let v = false;
await bluebird_1.default.map(this.hosts, async (host) => {
let client = await this.getActive([host]);
let test = await client.test_has_message({
host: host,
});
v = test.connect;
});
return v;
}
setGraph(graphName) {
this.defaultConfig.defaultGraph = graphName;
this.connectionCache.forEach((client) => {
client.setGraph(graphName);
});
}
}
exports.ConnectionPool = ConnectionPool;
//# sourceMappingURL=connection.pool.js.map