UNPKG

@duongtrungnguyen/nestro

Version:
63 lines 1.91 kB
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(); } } export { ResponseTimeStrategy }; //# sourceMappingURL=response-time.strategy.js.map