|
| 1 | +import * as fs from 'node:fs/promises' |
| 2 | +import * as path from 'node:path' |
| 3 | +import { exec } from 'node:child_process' |
| 4 | +import { promisify } from 'node:util' |
| 5 | +import { env } from './env.js' |
| 6 | +const execAsync = promisify(exec) |
| 7 | + |
| 8 | +async function deleteOldFolders() { |
| 9 | + const now = Date.now() |
| 10 | + const ttlInMillis = env.CACHE_TTL * 60 * 60 * 1000 |
| 11 | + |
| 12 | + try { |
| 13 | + const folders = await fs.readdir(env.CACHE_PATH) |
| 14 | + for (const folder of folders) { |
| 15 | + const folderPath = path.join(env.CACHE_PATH, folder) |
| 16 | + const stats = await fs.stat(folderPath) |
| 17 | + |
| 18 | + if (stats.isDirectory() && now - stats.mtimeMs > ttlInMillis) { |
| 19 | + await fs.rm(folderPath, { recursive: true, force: true }) |
| 20 | + console.log(`Deleted folder: ${folderPath}`) |
| 21 | + } |
| 22 | + } |
| 23 | + } catch (err) { |
| 24 | + console.error('Failed to delete old folders:', err) |
| 25 | + } |
| 26 | +} |
| 27 | + |
| 28 | +async function scriptAlreadyRan() { |
| 29 | + try { |
| 30 | + const lastRun = parseInt(await fs.readFile(env.CACHE_TIMESTAMP_FILE, 'utf8')) |
| 31 | + const now = Math.floor(Date.now() / 1000) |
| 32 | + const diff = now - lastRun |
| 33 | + return diff < env.CACHE_SCHEDULE_INTERVAL * 60 * 60 * 1000 |
| 34 | + } catch (err) { |
| 35 | + // File does not exist |
| 36 | + if (err instanceof Error && 'code' in err && err.code === 'ENOENT') { |
| 37 | + return false |
| 38 | + } |
| 39 | + throw err |
| 40 | + } |
| 41 | +} |
| 42 | + |
| 43 | +async function updateTimestampFile() { |
| 44 | + const now = Math.floor(Date.now() / 1000).toString() |
| 45 | + await fs.writeFile(env.CACHE_TIMESTAMP_FILE, now) |
| 46 | +} |
| 47 | + |
| 48 | +/** |
| 49 | + * Get the disk usage of the root directory |
| 50 | + */ |
| 51 | +async function getDiskUsage() { |
| 52 | + // awk 'NR==2 {print $5}' prints the 5th column of the df command which contains the percentage of the total disk space used |
| 53 | + // sed 's/%//' removes the % from the output |
| 54 | + const command = `df / | awk 'NR==2 {print $5}' | sed 's/%//'` |
| 55 | + const { stdout } = await execAsync(command) |
| 56 | + return parseInt(stdout.trim(), 10) |
| 57 | +} |
| 58 | + |
| 59 | +async function getFoldersByModificationTime() { |
| 60 | + const folders = await fs.readdir(env.CACHE_PATH, { withFileTypes: true }) |
| 61 | + const folderStats = await Promise.all( |
| 62 | + folders |
| 63 | + .filter((dirent) => dirent.isDirectory()) |
| 64 | + .map(async (dirent) => { |
| 65 | + const fullPath = path.join(env.CACHE_PATH, dirent.name) |
| 66 | + const stats = await fs.stat(fullPath) |
| 67 | + return { path: fullPath, mtime: stats.mtime.getTime() } |
| 68 | + }) |
| 69 | + ) |
| 70 | + return folderStats.sort((a, b) => a.mtime - b.mtime).map((folder) => folder.path) |
| 71 | +} |
| 72 | + |
| 73 | +export async function deleteCache() { |
| 74 | + if (await scriptAlreadyRan()) { |
| 75 | + console.log(`Script already ran in the last ${env.CACHE_SCHEDULE_INTERVAL} hours, skipping.`) |
| 76 | + return |
| 77 | + } |
| 78 | + |
| 79 | + await updateTimestampFile() |
| 80 | + |
| 81 | + // Always delete old folders based on TTL |
| 82 | + await deleteOldFolders() |
| 83 | + |
| 84 | + let diskUsage = await getDiskUsage() |
| 85 | + |
| 86 | + // If disk usage exceeds the threshold, delete additional old folders |
| 87 | + if (diskUsage >= env.CACHE_DISK_USAGE_THRESHOLD) { |
| 88 | + console.log( |
| 89 | + `Disk usage is at ${diskUsage}%, which is above the threshold of ${env.CACHE_DISK_USAGE_THRESHOLD}%.` |
| 90 | + ) |
| 91 | + |
| 92 | + const folders = await getFoldersByModificationTime() |
| 93 | + |
| 94 | + // Loop through the folders and delete them one by one until disk usage is below the threshold |
| 95 | + for (const folder of folders) { |
| 96 | + console.log(`Deleting folder: ${folder}`) |
| 97 | + await fs.rm(folder, { recursive: true, force: true }) |
| 98 | + |
| 99 | + diskUsage = await getDiskUsage() |
| 100 | + if (diskUsage < env.CACHE_DISK_USAGE_THRESHOLD) { |
| 101 | + console.log(`Disk usage is now at ${diskUsage}%, which is below the threshold.`) |
| 102 | + break |
| 103 | + } |
| 104 | + } |
| 105 | + } else { |
| 106 | + console.log( |
| 107 | + `Disk usage is at ${diskUsage}%, which is below the threshold of ${env.CACHE_DISK_USAGE_THRESHOLD}%.` |
| 108 | + ) |
| 109 | + } |
| 110 | +} |
0 commit comments