@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.
87 lines (86 loc) • 2.79 kB
TypeScript
/**
* @module RateLimiter
*/
import { type IRateLimiterPolicy } from "../../../../rate-limiter/contracts/_module.js";
import { type ITimeSpan } from "../../../../time-span/contracts/_module.js";
/**
* IMPORT_PATH: `"@daiso-tech/core/rate-limiter/policies"`
* @group Policies
*/
export type SlidingWindowLimiterSettings = {
/**
* The time span in which attempts are active before reseting.
*
* @default
* ```ts
* import { TimeSpan } from "@daiso-tech/core/time-span";
*
* TimeSpan.fromSeconds(1)
* ```
*/
window?: ITimeSpan;
/**
* @default
* ```ts
* import { TimeSpan } from "@daiso-tech/core/time-span";
*
* TimeSpan.fromTimeSpan(window).divide(4)
* ```
*/
margin?: ITimeSpan;
};
/**
* @internal
*/
export declare function resolveSlidingWindowLimiterSettings(settings: SlidingWindowLimiterSettings): Required<SlidingWindowLimiterSettings>;
/**
* @internal
*/
export type SerializedSlidingWindowLimiterSettings = {
window?: number;
margin?: number;
};
/**
* @internal
*/
export declare function serializeSlidingWindowLimiterSettings(settings: SlidingWindowLimiterSettings): Required<SerializedSlidingWindowLimiterSettings>;
/**
* Defines the structure for tracking attempts in the rate limiter.
* The key is the timestamp of the window's start (e.g., 1700000000000).
* The value is the attempts for that window.
*
* IMPORT_PATH: `"@daiso-tech/core/rate-limiter/policies"`
* @group Policies
*/
export type SlidingWindowLimiterState = Partial<Record<number, number>>;
/**
* Combined approach of `slidingLogs` and `fixedWindow` with lower storage
* costs than `slidingLogs` and improved boundary behavior by calculating a
* weighted score between two windows.
*
* **Pro:**
*
* Good performance allows this to scale to very high loads.
*
* **Con:**
*
* Nothing major.
*
* IMPORT_PATH: `"@daiso-tech/core/rate-limiter/policies"`
* @group Policies
*/
export declare class SlidingWindowLimiter implements IRateLimiterPolicy<SlidingWindowLimiterState> {
private readonly window;
private readonly margin;
constructor(settings?: SlidingWindowLimiterSettings);
private currentWindow;
private previousWindow;
private cleanup;
private currentAttempt;
private previousAttempt;
initialMetrics(currentDate: Date): SlidingWindowLimiterState;
shouldBlock(currentMetrics: SlidingWindowLimiterState, limit: number, currentDate: Date): boolean;
getExpiration(_currentMetrics: SlidingWindowLimiterState, currentDate: Date): Date;
getAttempts(currentMetrics: SlidingWindowLimiterState, currentDate: Date): number;
updateMetrics(currentMetrics: SlidingWindowLimiterState, currentDate: Date): SlidingWindowLimiterState;
}