@duongtrungnguyen/nestro
Version:
Service registry for Nest JS
86 lines • 2.98 kB
JavaScript
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 response_time_strategy_exports = {};
__export(response_time_strategy_exports, {
ResponseTimeStrategy: () => ResponseTimeStrategy
});
module.exports = __toCommonJS(response_time_strategy_exports);
class ResponseTimeStrategy {
constructor() {
this.responseTimes = /* @__PURE__ */ new Map();
this.maxSamples = 10;
}
// Number of samples to keep for average calculation
selectInstance(instances) {
if (!instances || instances.length === 0) {
return null;
}
if (instances.length === 1) {
return instances[0];
}
let fastestInstance = instances[0];
let fastestTime = this.getAverageResponseTime(this.getInstanceId(fastestInstance));
const hasData = fastestTime !== null;
if (!hasData) {
const randomIndex = Math.floor(Math.random() * instances.length);
return instances[randomIndex];
}
for (let i = 1; i < instances.length; i++) {
const instanceId = this.getInstanceId(instances[i]);
const avgTime = this.getAverageResponseTime(instanceId);
if (avgTime !== null && (fastestTime === null || avgTime < fastestTime)) {
fastestTime = avgTime;
fastestInstance = instances[i];
}
}
return fastestInstance;
}
/**
* Record response time for an instance
*/
recordResponseTime(instanceId, responseTimeMs) {
let times = this.responseTimes.get(instanceId) || [];
times.push(responseTimeMs);
if (times.length > this.maxSamples) {
times = times.slice(-this.maxSamples);
}
this.responseTimes.set(instanceId, times);
}
/**
* Get average response time for an instance
*/
getAverageResponseTime(instanceId) {
const times = this.responseTimes.get(instanceId);
if (!times || times.length === 0) {
return null;
}
const sum = times.reduce((acc, time) => acc + time, 0);
return sum / times.length;
}
getInstanceId(instance) {
return `${instance.name}:${instance.host}:${instance.port}`;
}
reset() {
this.responseTimes.clear();
}
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
ResponseTimeStrategy
});
//# sourceMappingURL=response-time.strategy.js.map