From 3d9e9acbe93e277387fdfbc67ada8914f47dfd2d Mon Sep 17 00:00:00 2001 From: Georgy Butaev <41178744+g-but@users.noreply.github.com> Date: Wed, 3 Jun 2026 23:00:33 +0200 Subject: [PATCH] =?UTF-8?q?feat(cron):=20wire=20/api/cron/cleanup=20?= =?UTF-8?q?=E2=86=92=20prune=20expired=20idempotency=5Fresults?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit vercel.json already schedules /api/cron/cleanup daily at 02:00 UTC, but the route didn't exist — the cron was firing into a 404 every night since the public API shipped. This route is a per-task fanout: each cleanup runs independently, one failing doesn't stop the others, the response reports per-task counts so Vercel logs show what was pruned. Today's only task is the idempotency_results table (24h TTL, would otherwise grow unbounded); new expirable plumbing can be added by appending to `tasks`. Co-Authored-By: Claude Opus 4.7 (1M context) --- src/app/api/cron/cleanup/route.ts | 99 +++++++++++++++++++++++++++++++ 1 file changed, 99 insertions(+) create mode 100644 src/app/api/cron/cleanup/route.ts diff --git a/src/app/api/cron/cleanup/route.ts b/src/app/api/cron/cleanup/route.ts new file mode 100644 index 000000000..b1254e42c --- /dev/null +++ b/src/app/api/cron/cleanup/route.ts @@ -0,0 +1,99 @@ +/** + * Generic Cleanup Cron Route + * + * Vercel Cron: runs daily at 02:00 UTC. + * vercel.json: { "path": "/api/cron/cleanup", "schedule": "0 2 * * *" } + * + * Housekeeping for plumbing tables that grow unbounded otherwise. + * Each cleanup is independent — one failing doesn't stop the others — + * and the response reports per-task counts so we can see what was pruned + * in the Vercel logs. + * + * Today's tasks: + * - idempotency_results: delete rows past expires_at (24h TTL from + * the original migration). Without this, every API write + * accumulates a row forever; the cleanup keeps the table bounded + * to roughly one day of recent writes. + * + * When you add another expirable plumbing table, add a new task to the + * `tasks` array and the response will widen automatically. + * + * Created: 2026-06-03 + */ + +import { createAdminClient } from '@/lib/supabase/admin'; +import { DATABASE_TABLES } from '@/config/database-tables'; +import { logger } from '@/utils/logger'; +import { apiSuccess, apiError, apiUnauthorized } from '@/lib/api/standardResponse'; + +export const dynamic = 'force-dynamic'; +export const maxDuration = 60; + +const LOG_SOURCE = 'CronCleanup'; + +function verifyCronSecret(request: Request): boolean { + const authHeader = request.headers.get('authorization'); + return authHeader === `Bearer ${process.env.CRON_SECRET}`; +} + +interface CleanupResult { + task: string; + deleted: number; + error?: string; +} + +async function pruneExpiredIdempotencyResults(): Promise { + const admin = createAdminClient(); + const nowIso = new Date().toISOString(); + + const { count, error } = await admin + .from(DATABASE_TABLES.IDEMPOTENCY_RESULTS) + .delete({ count: 'exact' }) + .lt('expires_at', nowIso); + + if (error) { + return { + task: 'idempotency_results', + deleted: 0, + error: error.message, + }; + } + + return { task: 'idempotency_results', deleted: count ?? 0 }; +} + +export async function GET(request: Request) { + if (!verifyCronSecret(request)) { + return apiUnauthorized(); + } + + try { + const tasks: Array<() => Promise> = [pruneExpiredIdempotencyResults]; + + const results = await Promise.all(tasks.map(task => task())); + + const summary = results.reduce>((acc, r) => { + acc[r.task] = r.error ? `error: ${r.error}` : r.deleted; + return acc; + }, {}); + + const hadError = results.some(r => r.error); + if (hadError) { + logger.error('Cleanup cron partial failure', { results }, LOG_SOURCE); + } else { + logger.info('Cleanup cron completed', { results }, LOG_SOURCE); + } + + return apiSuccess({ + ranAt: new Date().toISOString(), + tasks: summary, + }); + } catch (error) { + logger.error( + 'Cleanup cron failed', + { error: error instanceof Error ? error.message : error }, + LOG_SOURCE + ); + return apiError('Internal error', 'INTERNAL_ERROR', 500); + } +}