Run stats and consent-log retention purges off the request

The daily purge was awaited inside the visitor's request via payload.delete,
which loads and deletes expired documents one by one. It now runs as one
db.deleteMany in the background; failures are logged and retried.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
Radosław Smoliński
2026-10-22 17:04:09 +02:00
co-authored by Claude Opus 5.5
parent 78f4f5c16b
commit 0bfc509102
6 changed files with 109 additions and 21 deletions
+3 -10
View File
@@ -1,6 +1,7 @@
import type { CollectionConfig, Endpoint, PayloadRequest } from 'payload'
import { isAdmin } from '../access/predicates.js'
import { createDailyPurge } from '../shared/purge.js'
import { clientIp, consumeRateLimit } from '../shared/rateLimit.js'
import { CONSENT_CATEGORIES } from './categories.js'
@@ -53,7 +54,7 @@ export function buildConsentLogCollection(): CollectionConfig {
}
}
let lastPurge = 0
const purge = createDailyPurge(CONSENT_LOG_SLUG)
export function buildConsentLogEndpoint({ retentionDays = 1095 }: ConsentLogOptions = {}): Endpoint {
return {
@@ -89,15 +90,7 @@ export function buildConsentLogEndpoint({ retentionDays = 1095 }: ConsentLogOpti
} as never,
overrideAccess: true,
})
const now = Date.now()
if (now - lastPurge > 24 * 60 * 60 * 1000) {
lastPurge = now
await req.payload.delete({
collection: CONSENT_LOG_SLUG as never,
overrideAccess: true,
where: { createdAt: { less_than: new Date(now - retentionDays * 86_400_000).toISOString() } },
})
}
purge(req.payload, { createdAt: { less_than: new Date(Date.now() - retentionDays * 86_400_000).toISOString() } })
return Response.json({ ok: true }, { status: 201 })
} catch (err) {
req.payload.logger.error(`[ipal] consent log write failed: ${err instanceof Error ? err.message : String(err)}`)