From 2d17a05ff25dc91237f754ad763fc509db7ed88a Mon Sep 17 00:00:00 2001 From: Georgy Butaev <41178744+g-but@users.noreply.github.com> Date: Thu, 4 Jun 2026 00:54:35 +0200 Subject: [PATCH] feat(cron): prune delivered webhook deliveries older than 30 days MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit webhook_deliveries grows unbounded today — every successful fire accumulates a row forever (worker writes status='delivered' then never deletes), and the deliveries drawer would eventually take ages to render. Silent issue at any scale beyond MVP. The 02:00 UTC cleanup cron 3d9e9acb wired up already had a per-task fanout pattern: add a new task to the `tasks` array, response widens automatically. This commit drops in a second task next to the idempotency_results pruner. Service (deliveryService.pruneDeliveredWebhookDeliveries): - Deletes status='delivered' rows older than retentionDays (default 30) - Failed + pending rows are intentionally KEPT failed → operator audit trail; never re-runs, useful for postmortems pending → in-flight; the worker still owns these rows - Errors logged + swallowed so the cleanup cron's other tasks still run. - 30 days is well past the 24h exp-backoff cap and gives operators a month of context. Route doc-comment updated to describe both tasks honestly. 47 suites · 610 tests · 0 failures. tsc + eslint clean. Co-Authored-By: Claude Opus 4.7 (1M context) --- src/app/api/cron/cleanup/route.ts | 22 ++++++++++++++- src/services/webhooks/deliveryService.ts | 35 ++++++++++++++++++++++++ 2 files changed, 56 insertions(+), 1 deletion(-) 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,