File size: 1,194 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
const fs = require("node:fs/promises");
const { config } = require("../config/env");
const { paths } = require("../config/paths");
const { listFilesRecursive, directorySize, safeUnlink } = require("../utils/fs");
const { logger } = require("../monitoring/logger");

async function cleanupTemp() {
  const files = await listFilesRecursive(paths.temp);
  const cutoff = Date.now() - config.storage.tempRetentionHours * 60 * 60 * 1000;
  for (const file of files) {
    const stat = await fs.stat(file);
    if (stat.mtimeMs < cutoff) await safeUnlink(file);
  }
}

async function rotateCache() {
  const maxBytes = config.storage.maxCacheSizeGb * 1024 * 1024 * 1024;
  let size = await directorySize(paths.cache);
  if (size <= maxBytes) return;
  const files = await listFilesRecursive(paths.cache);
  const stats = await Promise.all(files.map(async (file) => ({ file, stat: await fs.stat(file) })));
  stats.sort((a, b) => a.stat.mtimeMs - b.stat.mtimeMs);
  for (const item of stats) {
    if (size <= maxBytes * 0.9) break;
    await safeUnlink(item.file);
    size -= item.stat.size;
  }
  logger.info({ size }, "Cache rotation completed");
}

module.exports = { cleanupTemp, rotateCache };