const fs = require("node:fs"); const path = require("node:path"); const { getDb } = require("../config/db"); const { config } = require("../config/env"); const { paths } = require("../config/paths"); const { cleanupTemp, rotateCache } = require("./rotation"); const { createLogger } = require("../monitoring/logger"); const log = createLogger("CacheCleanup"); async function runCleanup() { log.info("Starting automated cleanup sequence..."); // 1. Clean temp directory on disk try { log.info(`Sweeping disk temporary files in: ${paths.temp}`); await cleanupTemp(); } catch (err) { log.error("Failed to clean up temporary disk files:", err); } // 2. Rotate local cache files try { log.info(`Rotating local cache files...`); await rotateCache(); } catch (err) { log.error("Failed to rotate cache files:", err); } // 3. Clean SQLite cache database records older than limit try { const db = getDb(); const maxAgeDays = config.storage.logRetentionDays || 7; const maxAgeMs = maxAgeDays * 24 * 60 * 60 * 1000; const thresholdTime = Date.now() - maxAgeMs; log.info(`Purging SQLite cache entries older than ${maxAgeDays} days...`); const countBefore = db.prepare("SELECT COUNT(*) as count FROM cache").get().count; const thresholdIso = new Date(thresholdTime).toISOString(); const stmt = db.prepare("DELETE FROM cache WHERE last_used_at < ?"); const result = stmt.run(thresholdIso); const countAfter = db.prepare("SELECT COUNT(*) as count FROM cache").get().count; log.info(`Database cache cleanup finished. Purged ${result.changes} records. Cache entries remaining: ${countAfter} (from ${countBefore}).`); } catch (err) { log.error("Failed to purge stale database cache records:", err); } log.info("Automated cleanup sequence completed."); } function startCleanupSchedule(intervalMs = 6 * 60 * 60 * 1000) { log.info(`Scheduling automated cache & disk cleanup sweeps to run every ${intervalMs / (60 * 60 * 1000)} hours.`); // Run once immediately on startup asynchronously runCleanup().catch(err => log.error("Initial startup cleanup failed:", err)); const timer = setInterval(() => { runCleanup().catch(err => log.error("Interval cleanup execution failed:", err)); }, intervalMs); return timer; } module.exports = { runCleanup, startCleanupSchedule };