diff --git a/src/app/api/cron/cleanup/route.ts b/src/app/api/cron/cleanup/route.ts index b1254e42c..24b79d81c 100644 --- a/src/app/api/cron/cleanup/route.ts +++ b/src/app/api/cron/cleanup/route.ts @@ -14,6 +14,9 @@ * 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. + * - webhook_deliveries (delivered only): prune rows older than 30 + * days. Failed + pending rows are kept — failed is the operator + * audit trail, pending is in-flight work the worker still owns. * * When you add another expirable plumbing table, add a new task to the * `tasks` array and the response will widen automatically. @@ -25,6 +28,7 @@ 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'; +import { pruneDeliveredWebhookDeliveries } from '@/services/webhooks/deliveryService'; export const dynamic = 'force-dynamic'; export const maxDuration = 60; @@ -42,6 +46,19 @@ interface CleanupResult { error?: string; } +async function pruneOldDeliveredWebhooks(): Promise { + try { + const deleted = await pruneDeliveredWebhookDeliveries(); + return { task: 'webhook_deliveries_delivered', deleted }; + } catch (error) { + return { + task: 'webhook_deliveries_delivered', + deleted: 0, + error: error instanceof Error ? error.message : String(error), + }; + } +} + async function pruneExpiredIdempotencyResults(): Promise { const admin = createAdminClient(); const nowIso = new Date().toISOString(); @@ -68,7 +85,10 @@ export async function GET(request: Request) { } try { - const tasks: Array<() => Promise> = [pruneExpiredIdempotencyResults]; + const tasks: Array<() => Promise> = [ + pruneExpiredIdempotencyResults, + pruneOldDeliveredWebhooks, + ]; const results = await Promise.all(tasks.map(task => task())); diff --git a/src/services/webhooks/deliveryService.ts b/src/services/webhooks/deliveryService.ts index 0f5e40523..76c6580bc 100644 --- a/src/services/webhooks/deliveryService.ts +++ b/src/services/webhooks/deliveryService.ts @@ -221,6 +221,41 @@ export async function markDelivered( } } +/** + * Prune old DELIVERED rows. Without this the table grows unbounded — + * every successful webhook fire accumulates a row forever, and the + * deliveries drawer would eventually take ages to render. + * + * Failed + pending rows are intentionally NOT pruned: failed is the + * audit trail operators reach for during incidents; pending is in-flight + * work the worker needs to see. + * + * Default retention: 30 days. That's well past any reasonable retry + * window (24h cap on the exp-backoff schedule) and gives operators a + * month of context for delivered events without unbounded growth. + * + * Returns the number of rows deleted. Errors are logged + swallowed so + * the cleanup cron's other tasks still run. + */ +export async function pruneDeliveredWebhookDeliveries( + retentionDays: number = 30, + now: Date = new Date() +): Promise { + const cutoff = new Date(now.getTime() - retentionDays * 24 * 60 * 60 * 1000); + const admin = createAdminClient(); + const { count, error } = await admin + .from(DATABASE_TABLES.WEBHOOK_DELIVERIES) + .delete({ count: 'exact' }) + .eq('status', 'delivered') + .lt('created_at', cutoff.toISOString()); + + if (error) { + logger.warn('pruneDeliveredWebhookDeliveries failed (non-fatal)', { error }); + return 0; + } + return count ?? 0; +} + export async function markFailedOrRetry( delivery: DeliveryRow, responseStatus: number | null,