Download tasks/linkedin/solution/site/implementation/clone/lib/rate-limit.ts from TIGER-Lab/WebsiteBench: direct link, hf CLI and curl.
- Browser
- Download file 1.81 kB
-
https://huggingface.co/datasets/TIGER-Lab/WebsiteBench/resolve/main/tasks/linkedin/solution/site/implementation/clone/lib/rate-limit.ts
- Command line
-
hf download hf://datasets/TIGER-Lab/WebsiteBench/tasks/linkedin/solution/site/implementation/clone/lib/rate-limit.ts
-
curl -L -o rate-limit.ts https://huggingface.co/datasets/TIGER-Lab/WebsiteBench/resolve/main/tasks/linkedin/solution/site/implementation/clone/lib/rate-limit.ts
1.81 kB
| import { createHash } from "node:crypto"; | |
| import { ApiError } from "./api"; | |
| type Bucket = { | |
| count: number; | |
| resetAt: number; | |
| }; | |
| type Store = Map<string, Bucket>; | |
| const globalForRateLimit = globalThis as unknown as { linkedinRateLimits?: Store }; | |
| const maxBuckets = 5000; | |
| function store() { | |
| if (!globalForRateLimit.linkedinRateLimits) globalForRateLimit.linkedinRateLimits = new Map(); | |
| return globalForRateLimit.linkedinRateLimits; | |
| } | |
| function hashIdentifier(value: string) { | |
| return createHash("sha256").update(value).digest("hex"); | |
| } | |
| function clientIdentifier(request: Request) { | |
| const forwardedFor = request.headers.get("x-forwarded-for")?.split(",")[0]?.trim(); | |
| return forwardedFor | |
| ?? request.headers.get("cf-connecting-ip") | |
| ?? request.headers.get("x-real-ip") | |
| ?? "local"; | |
| } | |
| function pruneExpiredBuckets(values: Store, now: number) { | |
| if (values.size <= maxBuckets) return; | |
| for (const [key, bucket] of values) { | |
| if (bucket.resetAt <= now) values.delete(key); | |
| } | |
| } | |
| export function enforceRateLimit({ scope, identifier, limit, windowMs }: { scope: string, identifier: string, limit: number, windowMs: number }) { | |
| const now = Date.now(); | |
| const values = store(); | |
| pruneExpiredBuckets(values, now); | |
| const key = `${scope}:${hashIdentifier(identifier)}`; | |
| const existing = values.get(key); | |
| const bucket = existing && existing.resetAt > now ? existing : { count: 0, resetAt: now + windowMs }; | |
| if (bucket.count >= limit) { | |
| throw new ApiError(429, "Too many attempts. Try again later.", "rate_limited"); | |
| } | |
| bucket.count += 1; | |
| values.set(key, bucket); | |
| } | |
| export function enforceRequestRateLimit(request: Request, options: { scope: string, limit: number, windowMs: number }) { | |
| enforceRateLimit({ ...options, identifier: clientIdentifier(request) }); | |
| } | |