Initial commit: PodcastYes — AI podcast platform
This commit is contained in:
@@ -0,0 +1,42 @@
|
||||
import { RateLimiterMemory } from "rate-limiter-flexible";
|
||||
|
||||
// In-memory limiters (no Redis). Fine for a single-instance Plesk deployment;
|
||||
// swap for RateLimiterPostgres if the app is ever scaled to multiple nodes.
|
||||
const limiters = new Map<string, RateLimiterMemory>();
|
||||
|
||||
function getLimiter(name: string, points: number, durationSec: number): RateLimiterMemory {
|
||||
let limiter = limiters.get(name);
|
||||
if (!limiter) {
|
||||
limiter = new RateLimiterMemory({ points, duration: durationSec });
|
||||
limiters.set(name, limiter);
|
||||
}
|
||||
return limiter;
|
||||
}
|
||||
|
||||
export interface RateLimitResult {
|
||||
ok: boolean;
|
||||
retryAfterSec?: number;
|
||||
}
|
||||
|
||||
/** Consume one unit for `key` under a named bucket; returns ok=false when throttled. */
|
||||
export async function rateLimit(
|
||||
bucket: string,
|
||||
key: string,
|
||||
opts: { points: number; durationSec: number }
|
||||
): Promise<RateLimitResult> {
|
||||
const limiter = getLimiter(bucket, opts.points, opts.durationSec);
|
||||
try {
|
||||
await limiter.consume(key);
|
||||
return { ok: true };
|
||||
} catch (res) {
|
||||
const retryAfterSec = Math.ceil((res as { msBeforeNext?: number }).msBeforeNext ?? 1000) / 1000;
|
||||
return { ok: false, retryAfterSec: Math.ceil(retryAfterSec) };
|
||||
}
|
||||
}
|
||||
|
||||
// Common presets.
|
||||
export const LIMITS = {
|
||||
generation: { points: 10, durationSec: 60 }, // 10 generations / min / user
|
||||
repurpose: { points: 15, durationSec: 60 },
|
||||
api: { points: 60, durationSec: 60 }, // 60 API calls / min / key
|
||||
} as const;
|
||||
Reference in New Issue
Block a user