import type { Prisma } from '@generated/prisma/client'; export type RateLimitDb = { rateLimitEvent: Prisma.RateLimitEventDelegate }; /* Sliding window counted in `rate_limit_events`: returns false (and records nothing) once `key` reached `limit` hits inside the window. Old hits of the same key are swept on the way. */ export async function consumeRateLimit( db: RateLimitDb, key: string, options: { limit: number; windowMs: number; now: Date }, ): Promise { const windowStart = new Date(options.now.getTime() - options.windowMs); await db.rateLimitEvent.deleteMany({ where: { key, createdAt: { lt: windowStart } } }); const hits = await db.rateLimitEvent.count({ where: { key, createdAt: { gte: windowStart } } }); if (hits >= options.limit) return false; await db.rateLimitEvent.create({ data: { key, createdAt: options.now } }); return true; }