feat(cron): wire /api/cron/cleanup → prune expired idempotency_results

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) <noreply@anthropic.com>
This commit is contained in:
Georgy ButaevandClaude Opus 4.7 committed 2026-06-03 23:00:33 +02:00
1 parent 4f190c10e8
commit 3d9e9acbe9
1 file changed
+99
+99
View File
@@ -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<CleanupResult> {
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<CleanupResult>> = [pruneExpiredIdempotencyResults];
const results = await Promise.all(tasks.map(task => task()));
const summary = results.reduce<Record<string, number | string>>((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);
}
}