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 -9
View File
@@ -3,6 +3,7 @@ import type { Endpoint, PayloadRequest } from 'payload'
import type { StatsOptions, StatsPage, StatsVisit } from './collection.js'
import { CONSENT_COOKIE, CONSENT_VERSION, parseConsent } from '../consent/storage.js'
import { createDailyPurge } from '../shared/purge.js'
import { clientIp, consumeRateLimit } from '../shared/rateLimit.js'
import { STATS_SLUG } from './collection.js'
import { dayOf, deviceFromUa, isBot, referrerHost, sanitizePath, VISITOR_ID_PATTERN } from './parse.js'
@@ -11,7 +12,7 @@ import { visitKey } from './visitKey.js'
const VISIT_GAP_MS = 30 * 60 * 1000
const MAX_PAGES = 200
let lastPurge = 0
const purge = createDailyPurge(STATS_SLUG)
let policy: { at: number; version: number } | null = null
/** Cookie Settings → Policy version, cached for a minute (read on every hit). */
@@ -139,14 +140,7 @@ export function buildStatsEndpoint({ retentionDays = 90, timeZone = 'Europe/Wars
})
}
if (now.getTime() - lastPurge > 24 * 60 * 60 * 1000) {
lastPurge = now.getTime()
await req.payload.delete({
collection: STATS_SLUG as never,
overrideAccess: true,
where: { lastAt: { less_than: new Date(now.getTime() - retentionDays * 86_400_000).toISOString() } },
})
}
purge(req.payload, { lastAt: { less_than: new Date(now.getTime() - retentionDays * 86_400_000).toISOString() } })
} catch (err) {
req.payload.logger.error(`[ipal] stats hit failed: ${err instanceof Error ? err.message : String(err)}`)
}