import { PLAN_LIMITS, PLANS } from "@fetcha/core"; import { db, sql } from "@fetcha/db"; /** * Retention: request metadata is kept per plan (3/7/30/90/365 days). Attempts cascade with * their request. Usage events (billing ledger) and audit logs are never pruned here. * Also expires stale proxy sessions. */ export async function pruneRetention(log: { info: (m: string) => void } = console): Promise { let total = 0; for (const plan of PLANS) { const days = PLAN_LIMITS[plan].retention_days; const res = await db.execute(sql` delete from fetch_requests r using organizations o where r.organization_id = o.id and o.plan = ${plan} and r.created_at < now() - make_interval(days => ${days}) `); total += Number((res as { rowCount?: number }).rowCount ?? 0); } for (const plan of PLANS) { const days = PLAN_LIMITS[plan].retention_days; await db.execute(sql` delete from crawl_jobs j using organizations o where j.organization_id = o.id and o.plan = ${plan} and j.created_at < now() - make_interval(days => ${days}) `); } await db.execute(sql`update proxy_sessions set status = 'expired' where status = 'active' and expires_at < now()`); await db.execute(sql`delete from provider_health where checked_at < now() - interval '30 days'`); await db.execute(sql`delete from verifications where expires_at < now() - interval '1 day'`); log.info(`retention prune complete (${total} requests removed)`); }