UNPKG

@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.

75 lines (74 loc) 2.35 kB
/** * @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 FixedWindowLimiterSettings = { /** * 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; }; /** * @internal */ export declare function resolveFixedWindowLimiterSettings(settings: FixedWindowLimiterSettings): Required<FixedWindowLimiterSettings>; /** * @internal */ export type SerializedFixedWindowLimiterSettings = { window?: number; }; /** * @internal */ export declare function serializeFixedWindowLimiterSettings(settings: FixedWindowLimiterSettings): Required<SerializedFixedWindowLimiterSettings>; /** * IMPORT_PATH: `"@daiso-tech/core/rate-limiter/policies"` * @group Policies */ export type FixedWindowLimiterState = { attempt: number; /** * Unix timestamp in ms */ lastAttemptAt: number; }; /** * 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 declare class FixedWindowLimiter implements IRateLimiterPolicy<FixedWindowLimiterState> { private readonly window; constructor(settings?: FixedWindowLimiterSettings); initialMetrics(currentDate: Date): FixedWindowLimiterState; shouldBlock(currentMetrics: FixedWindowLimiterState, limit: number, currentDate: Date): boolean; getExpiration(currentMetrics: FixedWindowLimiterState, _currentDate: Date): Date; getAttempts(currentMetrics: FixedWindowLimiterState, _currentDate: Date): number; updateMetrics(currentMetrics: FixedWindowLimiterState, currentDate: Date): FixedWindowLimiterState; }