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.

70 lines 2.7 kB
/** * @module RateLimiter */ import {} from "../../../../backoff-policies/contracts/_module.js"; import { RATE_LIMITER_STATE, } from "../../../../rate-limiter/contracts/_module.js"; import { TimeSpan } from "../../../../time-span/implementations/_module.js"; import { callInvokable } from "../../../../utilities/_module.js"; /** * @internal */ export class InternalRateLimiterPolicy { rateLimiterPolicy; constructor(rateLimiterPolicy) { this.rateLimiterPolicy = rateLimiterPolicy; } initialState(currentDate) { return { type: RATE_LIMITER_STATE.ALLOWED, metrics: this.rateLimiterPolicy.initialMetrics(currentDate), }; } whenAllowed(currentState, limit, currentDate) { if (this.rateLimiterPolicy.shouldBlock(currentState.metrics, limit, currentDate)) { return { type: RATE_LIMITER_STATE.BLOCKED, attempt: 1, startedAt: currentDate.getTime(), }; } return currentState; } whenBlocked(currentState, settings) { const waitTime = TimeSpan.fromTimeSpan(callInvokable(settings.backoffPolicy, currentState.attempt, null)); const endDate = waitTime.toEndDate(new Date(currentState.startedAt)); const isWaitTimeOver = endDate.getTime() <= settings.currentDate.getTime(); if (isWaitTimeOver) { return { type: RATE_LIMITER_STATE.ALLOWED, metrics: this.rateLimiterPolicy.initialMetrics(settings.currentDate), }; } return currentState; } trackWhenAllowed(currentState, currentDate) { return { type: currentState.type, metrics: this.rateLimiterPolicy.updateMetrics(currentState.metrics, currentDate), }; } trackWhenBlocked(currentState) { return { type: currentState.type, startedAt: currentState.startedAt, attempt: currentState.attempt + 1, }; } getExpiration(currentState, settings) { if (currentState.type === RATE_LIMITER_STATE.ALLOWED) { return this.rateLimiterPolicy.getExpiration(currentState.metrics, settings.currentDate); } return TimeSpan.fromTimeSpan(callInvokable(settings.backoffPolicy, currentState.attempt, null)).toEndDate(settings.currentDate); } getAttempts(currentState, currentDate) { if (currentState.type === RATE_LIMITER_STATE.ALLOWED) { return this.rateLimiterPolicy.getAttempts(currentState.metrics, currentDate); } return currentState.attempt; } } //# sourceMappingURL=internal-rate-limiter-policy.js.map