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:
co-authored by
Claude Opus 5.5
parent
78f4f5c16b
commit
0bfc509102
@@ -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)}`)
|
||||
})
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user