File size: 2,376 Bytes
03b405b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
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 };