UNPKG

@duongtrungnguyen/nestro

Version:
75 lines 2.83 kB
var __defProp = Object.defineProperty; var __getOwnPropDesc = Object.getOwnPropertyDescriptor; var __getOwnPropNames = Object.getOwnPropertyNames; var __hasOwnProp = Object.prototype.hasOwnProperty; var __export = (target, all) => { for (var name in all) __defProp(target, name, { get: all[name], enumerable: true }); }; var __copyProps = (to, from, except, desc) => { if (from && typeof from === "object" || typeof from === "function") { for (let key of __getOwnPropNames(from)) if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); } return to; }; var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); var least_connection_strategy_exports = {}; __export(least_connection_strategy_exports, { LeastConnectionsStrategy: () => LeastConnectionsStrategy }); module.exports = __toCommonJS(least_connection_strategy_exports); class LeastConnectionsStrategy { constructor() { this.connectionCounters = /* @__PURE__ */ new Map(); } selectInstance(instances) { if (!instances || instances.length === 0) { return null; } if (instances.length === 1) { return instances[0]; } let minConnections = Number.MAX_SAFE_INTEGER; let selectedInstance = instances[0]; let candidatesWithSameConnections = []; for (const instance of instances) { const instanceId = this.getInstanceId(instance); const connections = this.connectionCounters.get(instanceId) || 0; if (connections < minConnections) { minConnections = connections; selectedInstance = instance; candidatesWithSameConnections = [instance]; } else if (connections === minConnections) { candidatesWithSameConnections.push(instance); } } if (candidatesWithSameConnections.length > 1) { const randomIndex = Math.floor(Math.random() * candidatesWithSameConnections.length); selectedInstance = candidatesWithSameConnections[randomIndex]; } return selectedInstance; } trackConnectionStart(instanceId) { const currentCount = this.connectionCounters.get(instanceId) || 0; this.connectionCounters.set(instanceId, currentCount + 1); } trackConnectionEnd(instanceId) { const currentCount = this.connectionCounters.get(instanceId) || 0; if (currentCount > 0) { this.connectionCounters.set(instanceId, currentCount - 1); } } reset() { this.connectionCounters.clear(); } getInstanceId(instance) { return `${instance.name}:${instance.host}:${instance.port}`; } } // Annotate the CommonJS export names for ESM import in node: 0 && (module.exports = { LeastConnectionsStrategy }); //# sourceMappingURL=least-connection.strategy.js.map