'use strict'; const fs = require('fs'); const path = require('path'); /** * 定时清理导出文件与记录:每日凌晨 2:30 执行,删除超过 90 天且已终态(完成/失败)的导出任务, * 同时删除其落盘文件(路径以 exports/ 开头,防止穿越),释放磁盘与数据库空间。 */ module.exports = { schedule: { cron: '0 30 2 * * *', type: 'worker', disable: false, }, async task(ctx) { const keepDays = 90; const Op = ctx.app.Sequelize.Op; const threshold = new Date(Date.now() - keepDays * 24 * 60 * 60 * 1000); const rows = await ctx.model.ExportTask.findAll({ where: { created_at: { [Op.lt]: threshold }, status: { [Op.in]: [ 2, 3 ] }, }, }); const uploadDir = ctx.app.config.upload.dir; let deleted = 0; for (const r of rows) { if (r.file_path && !r.file_path.includes('..') && /^exports\//.test(r.file_path)) { const abs = path.join(uploadDir, r.file_path); try { fs.unlinkSync(abs); } catch (e) { ctx.logger.warn('[export-cleanup] 删除文件失败 ' + abs, e.message); } } await r.destroy(); deleted += 1; } ctx.logger.info(`[export-cleanup] 已清理 ${keepDays} 天前的导出记录 ${deleted} 条`); return deleted; }, };