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)}`)
+29
View File
@@ -0,0 +1,29 @@
import type { BasePayload, Where } from 'payload'
const DAY_MS = 24 * 60 * 60 * 1000
/**
* Retention purge for a log collection (stats visits, consent records): at
* most once a day per process, and OFF the visitor's request.
*
* It used to be awaited inside the hit / consent request through
* `payload.delete`, which loads every expired document and deletes them one by
* one — the first purge after months of traffic held a visitor's request for
* as long as that took. `db.deleteMany` is a single query (these collections
* have no hooks to run), started and left to finish on its own; a failure is
* logged and retried on the next request.
*/
export function createDailyPurge(collection: string) {
let lastPurge = 0
return (payload: BasePayload, where: Where): void => {
const now = Date.now()
if (now - lastPurge < DAY_MS) {return}
lastPurge = now
void Promise.resolve()
.then(() => payload.db.deleteMany({ collection: collection as never, where }))
.catch((err: unknown) => {
lastPurge = 0
payload.logger.error(`[ipal] ${collection} retention purge failed: ${err instanceof Error ? err.message : String(err)}`)
})
}
}
+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)}`)
}