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
+70
View File
@@ -0,0 +1,70 @@
/** Retention purges must never hold a visitor's request. */
import type { PayloadRequest } from 'payload'
import { describe, expect, test, vi } from 'vitest'
import { buildConsentLogEndpoint } from '../src/modules/consent/consentLog.js'
import { buildStatsEndpoint } from '../src/modules/stats/endpoint.js'
const CHROME = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130.0 Safari/537.36'
/** A purge that never finishes — the request must still answer. */
function fakePayload() {
return {
create: vi.fn(async ({ data }: { data: object }) => ({ id: 1, ...data })),
db: { deleteMany: vi.fn(() => new Promise<void>(() => {})) },
delete: vi.fn(() => new Promise(() => {})),
find: vi.fn(async () => ({ docs: [] })),
findGlobal: vi.fn(async () => ({})),
logger: { error: vi.fn() },
}
}
const call = (endpoint: { handler: unknown }, payload: unknown, body: unknown) =>
(endpoint.handler as (r: PayloadRequest) => Promise<Response>)(
Object.assign(
new Request('http://acme.pl/api/x', {
body: JSON.stringify(body),
headers: { 'content-type': 'application/json', host: 'acme.pl', 'user-agent': CHROME, 'x-real-ip': '203.0.113.9' },
method: 'POST',
}),
{ payload, user: null },
) as unknown as PayloadRequest,
)
const settle = <T>(p: Promise<T>) => Promise.race([p, new Promise<'hung'>((r) => setTimeout(() => r('hung'), 200))])
describe('retention purge runs off the request', () => {
test('stats hit answers while the purge is still running; one bulk query, once a day', async () => {
const payload = fakePayload()
const endpoint = buildStatsEndpoint({ timeZone: 'UTC' })
const res = await settle(call(endpoint, payload, { p: '/pl' }))
expect(res).not.toBe('hung')
expect((res as Response).status).toBe(204)
await new Promise((r) => setTimeout(r, 0))
expect(payload.db.deleteMany).toHaveBeenCalledOnce()
expect(payload.delete).not.toHaveBeenCalled()
await call(endpoint, payload, { p: '/pl/oferta' })
expect(payload.db.deleteMany).toHaveBeenCalledOnce()
})
test('consent log answers while the purge is still running', async () => {
const payload = fakePayload()
const body = { id: 'ab'.repeat(16), state: { analytics: true, functional: true, marketing: false, necessary: true }, version: 1 }
const res = await settle(call(buildConsentLogEndpoint(), payload, body))
expect(res).not.toBe('hung')
expect((res as Response).status).toBe(201)
await new Promise((r) => setTimeout(r, 0))
expect(payload.db.deleteMany).toHaveBeenCalledOnce()
})
test('a failed purge is logged, not thrown at the visitor', async () => {
const payload = { ...fakePayload(), db: { deleteMany: vi.fn(async () => { throw new Error('db down') }) } }
vi.useFakeTimers({ now: Date.now() + 2 * 86_400_000, toFake: ['Date'] })
const res = await call(buildStatsEndpoint({ timeZone: 'UTC' }), payload, { p: '/pl' })
vi.useRealTimers()
expect(res.status).toBe(204)
await new Promise((r) => setTimeout(r, 0))
expect(payload.logger.error).toHaveBeenCalledWith(expect.stringContaining('retention purge failed'))
})
})