type Bucket = { count: number; resetAt: number; }; const buckets = new Map(); export type RateLimitResult = { ok: boolean; retryAfterSeconds: number; }; /** * 단일 서버(OCI/VPS) 운영을 전제로 한 메모리 기반 제한입니다. * 서버를 여러 대로 늘릴 경우 Redis/DB 기반으로 교체해야 합니다. */ export function rateLimit(key: string, limit: number, windowMs: number): RateLimitResult { const now = Date.now(); const current = buckets.get(key); if (!current || current.resetAt <= now) { buckets.set(key, { count: 1, resetAt: now + windowMs }); return { ok: true, retryAfterSeconds: 0 }; } if (current.count >= limit) { return { ok: false, retryAfterSeconds: Math.max(1, Math.ceil((current.resetAt - now) / 1000)), }; } current.count += 1; return { ok: true, retryAfterSeconds: 0 }; } // 오래된 버킷이 무한히 쌓이지 않도록 가끔 정리합니다. if (typeof setInterval !== "undefined") { const timer = setInterval(() => { const now = Date.now(); for (const [key, bucket] of buckets) { if (bucket.resetAt <= now) buckets.delete(key); } }, 10 * 60 * 1000); if (typeof timer === "object" && "unref" in timer) timer.unref(); }