Download src/lib/rateLimiter.ts from HonzaH/Letschat: direct link, hf CLI and curl.
- Browser
- Download file 1.3 kB
-
https://huggingface.co/spaces/HonzaH/Letschat/resolve/main/src/lib/rateLimiter.ts
- Command line
-
hf download hf://spaces/HonzaH/Letschat/src/lib/rateLimiter.ts
-
curl -L -o rateLimiter.ts https://huggingface.co/spaces/HonzaH/Letschat/resolve/main/src/lib/rateLimiter.ts
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) | |
| } | |