All checks were successful
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
35 lines
1.0 KiB
TypeScript
35 lines
1.0 KiB
TypeScript
/** Счётчики в памяти процесса: окно windowMs, ключи не пишутся ни в БД, ни в логи. */
|
|
export class RateLimiter {
|
|
private readonly hits = new Map<string, number[]>();
|
|
private readonly max: number;
|
|
private readonly windowMs: number;
|
|
private readonly now: () => number;
|
|
|
|
constructor(max: number, windowMs = 15 * 60 * 1000, now: () => number = Date.now) {
|
|
this.max = max;
|
|
this.windowMs = windowMs;
|
|
this.now = now;
|
|
}
|
|
|
|
private recent(key: string): number[] {
|
|
const cutoff = this.now() - this.windowMs;
|
|
const list = (this.hits.get(key) ?? []).filter((t) => t > cutoff);
|
|
if (list.length) this.hits.set(key, list);
|
|
else this.hits.delete(key);
|
|
return list;
|
|
}
|
|
|
|
/** true, если лимит уже исчерпан. */
|
|
blocked(key: string): boolean {
|
|
return this.recent(key).length >= this.max;
|
|
}
|
|
|
|
hit(key: string): void {
|
|
this.hits.set(key, [...this.recent(key), this.now()]);
|
|
}
|
|
|
|
reset(key: string): void {
|
|
this.hits.delete(key);
|
|
}
|
|
}
|