/** * Phase 10 Task #68 — DSGVO grace-period cron. * * Daily job that scans `User` rows with `pendingDeletion=true` and * `scheduledDeletionAt <= now()`, then dispatches a per-user * dsgvo-deletion job. The cron itself never deletes data — it merely * fans out work to the existing cascade worker (apps/worker/src/jobs/ * dsgvo-deletion.ts) so all the audit + per-table-strategy invariants * stay in one place. * * Host-agnostic: callers supply the user-reader, the dispatcher, and * the audit/logger shims. This keeps the file fully unit-testable * without hauling in BullMQ or Prisma. The worker bootstrap wires it * to the real Prisma + BullMQ implementations. * * Cadence is once per 24h. We deliberately do not run more often: * - Deletion is irreversible past the grace window, so a slightly * delayed dispatch is acceptable (and indeed safer than a tight * loop). * - One row per overdue user per day is enough — re-runs are * idempotent because the dsgvo-deletion job clears the User row. * * Repeat-job registration is exported as `registerDsgvoGraceCron` and * called from `apps/worker/src/index.ts` on the `general` worker * group. We use BullMQ's `Queue.upsertJobScheduler` API so re-deploys * do not stack duplicate schedules. */ export const DSGVO_GRACE_CRON_JOB_ID = "dsgvo-grace-period-scan"; export const DSGVO_GRACE_CRON_EVERY_MS = 24 * 60 * 60 * 1000; export type DsgvoGraceCandidate = { userId: string; tenantId: string | null; scheduledDeletionAt: Date; deletionRequestId: string | null; }; export type DsgvoGraceCronDependencies = { /** Returns every User row currently overdue (pendingDeletion=true AND scheduledDeletionAt<=now). */ listOverdueUsers: (now: Date) => Promise; /** * Enqueue one dsgvo-deletion cascade for the given candidate. Resolves * with a job id for logging. May throw — failures are isolated per * candidate so one bad row does not block the rest. */ enqueueDeletion: (input: { userId: string; tenantId: string | null; requestId: string; actorType: "system"; actorId: string; mode: "delete"; reason: string; }) => Promise<{ jobId?: string }>; /** Optional. Defaults to () => new Date(). */ now?: () => Date; logger: { info: (fields: Record, msg: string) => void; error: (fields: Record, msg: string) => void; }; /** Stable actor id stamped on dispatched-cascade audit rows. Default "dsgvo-grace-cron". */ systemActorId?: string; }; export type DsgvoGraceCronResult = { scanned: number; dispatched: number; failed: number; failures: Array<{ userId: string; error: string }>; }; /** * Run one pass of the grace-period scan. * * Failure-isolation: if one candidate's dispatch throws, log + continue. * Returning a non-zero `failed` count gives the BullMQ wrapper a clear * signal to surface in metrics without blackholing the rest of the batch. */ export async function runDsgvoGraceCron(deps: DsgvoGraceCronDependencies): Promise { const now = deps.now ? deps.now() : new Date(); const systemActorId = deps.systemActorId ?? "dsgvo-grace-cron"; const candidates = await deps.listOverdueUsers(now); let dispatched = 0; const failures: Array<{ userId: string; error: string }> = []; for (const candidate of candidates) { try { // Reuse the deletion-request-id from the original user request so // the dsgvo-deletion cascade's AuditEvent.metadata.requestId // correlates back to the self-service POST that started it. const requestId = candidate.deletionRequestId ?? `grace-${candidate.userId}-${now.getTime()}`; const result = await deps.enqueueDeletion({ userId: candidate.userId, tenantId: candidate.tenantId, requestId, actorType: "system", actorId: systemActorId, mode: "delete", reason: "dsgvo-grace-period-elapsed", }); dispatched += 1; deps.logger.info( { userId: candidate.userId, requestId, jobId: result.jobId ?? null, scheduledDeletionAt: candidate.scheduledDeletionAt.toISOString() }, "dsgvo-grace-cron.dispatched", ); } catch (err) { const message = err instanceof Error ? err.message : String(err); failures.push({ userId: candidate.userId, error: message }); deps.logger.error({ userId: candidate.userId, err: message }, "dsgvo-grace-cron.dispatch-failed"); } } return { scanned: candidates.length, dispatched, failed: failures.length, failures, }; } /** * Helper for the worker bootstrap. Given a BullMQ-like queue with the * `upsertJobScheduler` API, install (or replace) the 24h repeat schedule. * Pinned to the queue's default job name + a stable scheduler key so a * second call is a no-op (idempotent on redeploys). */ export async function registerDsgvoGraceCron(queue: { upsertJobScheduler: ( schedulerId: string, options: { every: number }, template: { name: string; data?: Record }, ) => Promise; }): Promise { // The job-template `data` must satisfy the maintenance CleanupJob // discriminator so the registry-level handler can route on // `payload.task` (see apps/worker/src/handlers.ts maintenance branch). // Prior shape `{ kind: "dsgvo-grace-cron" }` had no `task` field and // tripped UnsupportedWorkerJobError on every tick. await queue.upsertJobScheduler( DSGVO_GRACE_CRON_JOB_ID, { every: DSGVO_GRACE_CRON_EVERY_MS }, { name: DSGVO_GRACE_CRON_JOB_ID, data: { kind: "cleanup.run", task: "dsgvo-grace-period-scan" } }, ); }