From 0bfc509102764b7c09710e43209a2415b93d4b7d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rados=C5=82aw=20Smoli=C5=84ski?= Date: Thu, 22 Oct 2026 17:04:09 +0200 Subject: [PATCH] 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 --- docs/consent.md | 2 +- docs/stats.md | 4 +- src/modules/consent/consentLog.ts | 13 ++---- src/modules/shared/purge.ts | 29 +++++++++++++ src/modules/stats/endpoint.ts | 12 ++---- test/retentionPurge.test.ts | 70 +++++++++++++++++++++++++++++++ 6 files changed, 109 insertions(+), 21 deletions(-) create mode 100644 src/modules/shared/purge.ts create mode 100644 test/retentionPurge.test.ts diff --git a/docs/consent.md b/docs/consent.md index 6d2c0ea..e56e50b 100644 --- a/docs/consent.md +++ b/docs/consent.md @@ -305,7 +305,7 @@ chcesz zachować sprzątanie locale (albo zaimportuj `LOCALE_COOKIE_NAME` i doda - **Rejestr zgód (dowód zgody, art. 7 ust. 1 RODO):** `ipalKit({ consentLog: true })` + ``. Zapisuje losowy identyfikator (ten sam co w ciasteczku), wybory, wersję polityki i czas — **bez IP i user-agenta**. Kolekcja *Consent records* - (tylko admin), automatyczne czyszczenie po `retentionDays` (domyślnie 1095). Postgres: `migrate:create`. + (tylko admin), automatyczne czyszczenie po `retentionDays` (domyślnie 1095; raz na dobę, w tle — zapis zgody na nie nie czeka). Postgres: `migrate:create`. - **Tabela ciasteczek** dla strony polityki: Cookie Settings → *Cookies* (wypełniana skanem, skill `ipal-consent-check` → cookie-scan) + `getCookieTable` + `` z `/rsc`. - Ciasteczko zgody ma `Secure` na HTTPS. diff --git a/docs/stats.md b/docs/stats.md index 9e781f2..fbc29f4 100644 --- a/docs/stats.md +++ b/docs/stats.md @@ -87,7 +87,9 @@ Ciąg odsłon z przerwami poniżej 30 minut, w ramach jednego dnia. Restart serw (każda ma własną sól) mogą rozbić trwającą wizytę na dwie — dla statystyk bez znaczenia. **Nie** zapisuj soli w bazie, żeby to „naprawić”: wtedy wczorajsze hashe dałoby się odwrócić do IP. -Wizyty starsze niż `retentionDays` są usuwane automatycznie (raz na dobę, przy pierwszej odsłonie). +Wizyty starsze niż `retentionDays` są usuwane automatycznie (raz na dobę na proces, przy pierwszej odsłonie) +jednym zapytaniem `db.deleteMany`, **w tle** — odsłona nie czeka na czyszczenie; błąd trafia do logu i +czyszczenie ponawia się przy następnej odsłonie. ## Prawa odwiedzającego (RODO) diff --git a/src/modules/consent/consentLog.ts b/src/modules/consent/consentLog.ts index 83e0337..8f1f72b 100644 --- a/src/modules/consent/consentLog.ts +++ b/src/modules/consent/consentLog.ts @@ -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)}`) diff --git a/src/modules/shared/purge.ts b/src/modules/shared/purge.ts new file mode 100644 index 0000000..7367ee7 --- /dev/null +++ b/src/modules/shared/purge.ts @@ -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)}`) + }) + } +} diff --git a/src/modules/stats/endpoint.ts b/src/modules/stats/endpoint.ts index 1d268ed..5857257 100644 --- a/src/modules/stats/endpoint.ts +++ b/src/modules/stats/endpoint.ts @@ -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)}`) } diff --git a/test/retentionPurge.test.ts b/test/retentionPurge.test.ts new file mode 100644 index 0000000..da5f656 --- /dev/null +++ b/test/retentionPurge.test.ts @@ -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(() => {})) }, + 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)( + 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 = (p: Promise) => 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')) + }) +})