@hotmeshio/hotmesh
Version:
Permanent-Memory Workflows & AI Agents
77 lines (76 loc) • 2.65 kB
JavaScript
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ThrottleManager = void 0;
const config_1 = require("../config");
class ThrottleManager {
constructor(initialThrottle = 0) {
this.throttle = 0;
this.isSleeping = false;
this.sleepPromiseResolve = null;
this.innerPromiseResolve = null;
this.sleepTimeout = null;
this.throttle = initialThrottle;
}
getThrottle() {
return this.throttle;
}
setThrottle(delayInMillis) {
const wasDecreased = delayInMillis < this.throttle;
this.throttle = delayInMillis;
// If the throttle was decreased, and we're in the middle of a sleep cycle, adjust immediately
if (wasDecreased) {
if (this.sleepTimeout) {
clearTimeout(this.sleepTimeout);
}
if (this.innerPromiseResolve) {
this.innerPromiseResolve();
}
}
}
isPaused() {
return this.throttle === config_1.MAX_DELAY;
}
/**
* An adjustable throttle that will interrupt a sleeping
* router if the throttle is reduced and the sleep time
* has elapsed. If the throttle is increased, or if
* the sleep time has not elapsed, the router will continue
* to sleep until the new termination point. This
* allows for dynamic, elastic throttling with smooth
* acceleration and deceleration.
*/
async customSleep() {
if (this.throttle === 0)
return;
if (this.isSleeping)
return;
this.isSleeping = true;
const startTime = Date.now(); //anchor the origin
await new Promise(async (outerResolve) => {
this.sleepPromiseResolve = outerResolve;
let elapsedTime = Date.now() - startTime;
while (elapsedTime < this.throttle) {
await new Promise((innerResolve) => {
this.innerPromiseResolve = innerResolve;
this.sleepTimeout = setTimeout(innerResolve, this.throttle - elapsedTime);
});
elapsedTime = Date.now() - startTime;
}
this.resetThrottleState();
outerResolve();
});
}
cancelThrottle() {
if (this.sleepTimeout) {
clearTimeout(this.sleepTimeout);
}
this.resetThrottleState();
}
resetThrottleState() {
this.sleepPromiseResolve = null;
this.innerPromiseResolve = null;
this.isSleeping = false;
this.sleepTimeout = null;
}
}
exports.ThrottleManager = ThrottleManager;