Spaces:
Sleeping
Sleeping
import cron from 'node-cron'; | |
import fs from 'fs/promises'; | |
import path from 'path'; | |
import { tasks } from './index.js'; | |
const TEMP_DIR = '/tmp'; | |
const MAX_AGE_MS = 24 * 60 * 60 * 1000; | |
async function cleanupOldFiles() { | |
try { | |
const files = await fs.readdir(TEMP_DIR); | |
const now = Date.now(); | |
for (const file of files) { | |
if (/\b[0-9a-f]{8}\b-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-\b[0-9a-f]{12}\b/i.test(file)) { | |
const filePath = path.join(TEMP_DIR, file); | |
try { | |
const stats = await fs.stat(filePath); | |
if (now - stats.mtime.getTime() > MAX_AGE_MS) { | |
await fs.unlink(filePath); | |
} | |
} catch (statError) { | |
if (statError.code !== 'ENOENT') { | |
console.error(`Failed to stat file ${filePath}:`, statError); | |
} | |
} | |
} | |
} | |
} catch (readDirError) { | |
if (readDirError.code !== 'ENOENT') { | |
console.error('Error reading temp directory:', readDirError); | |
} | |
} | |
} | |
function cleanupOldTasks() { | |
const now = Date.now(); | |
for (const taskId in tasks) { | |
const task = tasks[taskId]; | |
if (task.submittedAt && (now - task.submittedAt > MAX_AGE_MS)) { | |
if (task.outputFilePath) { | |
fs.unlink(task.outputFilePath).catch(() => {}); | |
} | |
delete tasks[taskId]; | |
} | |
} | |
} | |
export function startCleanupJob() { | |
cleanupOldFiles(); | |
cleanupOldTasks(); | |
cron.schedule('0 * * * *', () => { | |
cleanupOldFiles(); | |
cleanupOldTasks(); | |
}); | |
} | |