import { getSettings, getInternalFlag, setInternalFlag } from "./settingsStore.js"; import { purgeOldLogs } from "./logRetention.js"; import { recordAudit } from "./audit.js"; const LAST_RUN_FLAG = "logRetentionLastRunAt"; async function runPurge(): Promise { const { logRetention } = await getSettings(); if (!logRetention.enabled) return; const result = await purgeOldLogs(logRetention.retentionDays); await setInternalFlag(LAST_RUN_FLAG, new Date().toISOString()); if (result.diagDeleted || result.auditDeleted) { // Trimming the audit log is itself something to be able to look back on — attributed to the system, since no one asked for it. await recordAudit({ category: "settings", action: "purge_logs", detail: { automatic: true, retentionDays: logRetention.retentionDays, ...result }, }); console.log( `[logRetention] purged ${result.diagDeleted} diagnostic log and ${result.auditDeleted} audit log entries older than ${logRetention.retentionDays} days`, ); } } let currentTimer: ReturnType | null = null; /** (Re)arms the periodic purge timer per the current settings. Call again after settings change. */ export async function scheduleLogRetentionPurge(): Promise { if (currentTimer) { clearInterval(currentTimer); currentTimer = null; } const { logRetention } = await getSettings(); if (!logRetention.enabled) { console.log("[logRetention] automatic purge disabled"); return; } const intervalMs = logRetention.intervalHours * 60 * 60 * 1000; currentTimer = setInterval(() => { runPurge().catch((err) => console.error("[logRetention] purge failed:", err)); }, intervalMs); console.log(`[logRetention] automatic purge scheduled every ${logRetention.intervalHours}h, keeping ${logRetention.retentionDays} days`); } /** Runs immediately at startup if a purge is overdue (e.g. the server was down past the interval), then arms the periodic timer. */ export async function initLogRetentionScheduler(): Promise { const { logRetention } = await getSettings(); if (logRetention.enabled) { const lastRun = await getInternalFlag(LAST_RUN_FLAG); const dueAt = lastRun ? new Date(lastRun).getTime() + logRetention.intervalHours * 60 * 60 * 1000 : 0; if (Date.now() >= dueAt) { await runPurge().catch((err) => console.error("[logRetention] purge failed:", err)); } } await scheduleLogRetentionPurge(); }