@daiso-tech/core
Version:
The library offers flexible, framework-agnostic solutions for modern web applications, built on adaptable components that integrate seamlessly with popular frameworks like Next Js.
73 lines • 2.23 kB
JavaScript
/**
* @module RateLimiter
*/
import {} from "../../../../rate-limiter/contracts/_module.js";
import { TO_MILLISECONDS, } from "../../../../time-span/contracts/_module.js";
import { TimeSpan } from "../../../../time-span/implementations/_module.js";
/**
* @internal
*/
export function resolveFixedWindowLimiterSettings(settings) {
const { window = TimeSpan.fromSeconds(1) } = settings;
return {
window,
};
}
/**
* @internal
*/
export function serializeFixedWindowLimiterSettings(settings) {
const { window } = resolveFixedWindowLimiterSettings(settings);
return {
window: window[TO_MILLISECONDS](),
};
}
/**
* Each request inside a fixed time increases a counter.
* Once the counter reaches the maximum allowed number, all further attempts are
* rejected.
*
* **Pro:**
*
* - Newer attempts are not starved by old ones.
* - Low storage cost.
*
* **Con:**
*
* A burst of attempts near the boundary of a window can result in a very
* high request rate because two windows will be filled with attempts quickly.
*
* IMPORT_PATH: `"@daiso-tech/core/rate-limiter/policies"`
* @group Policies
*/
export class FixedWindowLimiter {
window;
constructor(settings = {}) {
const { window } = resolveFixedWindowLimiterSettings(settings);
this.window = TimeSpan.fromTimeSpan(window);
}
initialMetrics(currentDate) {
return {
attempt: 0,
lastAttemptAt: currentDate.getTime(),
};
}
shouldBlock(currentMetrics, limit, currentDate) {
const timeSinceLastAttempt = currentDate.getTime() - currentMetrics.lastAttemptAt;
return (timeSinceLastAttempt < this.window.toMilliseconds() &&
currentMetrics.attempt >= limit);
}
getExpiration(currentMetrics, _currentDate) {
return this.window.toEndDate(new Date(currentMetrics.lastAttemptAt));
}
getAttempts(currentMetrics, _currentDate) {
return currentMetrics.attempt;
}
updateMetrics(currentMetrics, currentDate) {
return {
attempt: currentMetrics.attempt + 1,
lastAttemptAt: currentDate.getTime(),
};
}
}
//# sourceMappingURL=fixed-window-limiter.js.map