Letschat / src /lib /rateLimiter.ts
HonzaH's picture
Upload 171 files
9853b20 verified
Raw History Blame Contribute Delete
1.3 kB
type Bucket = {
failures: number[]
blockedUntil: number
blockCount: number
}
const buckets = new Map<string, Bucket>()
interface FailureConfig {
limit: number
windowMs: number
blockMs: number
escalateAfterBlocks?: number
escalateBlockMs?: number
}
function getBucket(key: string): Bucket {
const existing = buckets.get(key)
if (existing) return existing
const fresh: Bucket = { failures: [], blockedUntil: 0, blockCount: 0 }
buckets.set(key, fresh)
return fresh
}
export function assertNotBlocked(key: string) {
const bucket = getBucket(key)
if (bucket.blockedUntil > Date.now()) {
throw new Error('rate_limited')
}
}
export function noteFailure(key: string, config: FailureConfig) {
const bucket = getBucket(key)
const now = Date.now()
// prune old failures
bucket.failures = bucket.failures.filter((t) => now - t <= config.windowMs)
bucket.failures.push(now)
if (bucket.failures.length >= config.limit) {
bucket.blockCount += 1
if (config.escalateAfterBlocks && config.escalateBlockMs && bucket.blockCount >= config.escalateAfterBlocks) {
bucket.blockedUntil = now + config.escalateBlockMs
} else {
bucket.blockedUntil = now + config.blockMs
}
}
}
export function resetFailures(key: string) {
buckets.delete(key)
}