File size: 1,704 Bytes
426e8cd
 
 
684d20b
426e8cd
ebf7adb
684d20b
426e8cd
 
 
 
 
 
 
ebf7adb
684d20b
ebf7adb
 
684d20b
ebf7adb
 
 
 
684d20b
ebf7adb
426e8cd
 
 
 
684d20b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
426e8cd
 
 
 
 
684d20b
 
 
 
 
 
426e8cd
 
0d25770
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
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();
    });
}