oms/backend/app/schedule/purgeApiLogs.js
liufumingren 6facd9c6f3 perf(log): 日志表按天分区,只保留 10 天
callback_logs / api_outbound_logs / request_logs 只增不减,DELETE 只标记删除、
磁盘不还。改为按 TO_DAYS(created_at) 做天分区,用 DROP PARTITION 物理删除。

- 迁移 20261107080000:三张日志表主键改为 (id, created_at)(MySQL 要求分区键
  包含在主键里),分区布局 p_old + 最近 10 天 + 未来 2 天 + pmax
- 新增 logRetention service:补未来分区(REORGANIZE pmax)→ DROP 过期分区;
  表若未分区则退化为分批 DELETE + OPTIMIZE 兜底
- 新增每日任务 purgeApiLogs(03:30):clean_request_logs 改为 disable,
  避免两条清理逻辑抢同一张表
- 保留天数默认 10 天,可用 LOG_RETENTION_DAYS 覆盖
- 文档补分区口径、为什么要 DROP PARTITION、上线注意

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-11-07 08:43:16 +08:00

41 lines
1.1 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

'use strict';
/**
* 每日清理日志表(callback_logs / api_outbound_logs / request_logs)。
*
* 保留天数默认 10 天(`LOG_RETENTION_DAYS` 可覆盖)。表按天分区,
* 清理方式是 `DROP PARTITION`(瞬时物理删除、立刻释放磁盘),不是 DELETE:
* DELETE 只标记删除,磁盘空间不会还给系统。
*
* 顺带补建未来 2 天的分区,避免跨天后新数据落到 pmax 分区导致不能按天回收。
* 若某张表还没分区(例如老库未跑迁移),退化为「分批 DELETE + OPTIMIZE TABLE」。
*/
let running = false;
module.exports = {
schedule: {
// 每天 03:30 执行(低峰)
cron: '0 30 3 * * *',
type: 'worker',
disable: false,
},
/**
* 执行清理
* @param {Egg.Context} ctx egg context
* @return {Promise<Array<Object>>} 各表清理结果
*/
async task(ctx) {
if (running) {
ctx.logger.info('[log-retention] 上一轮仍在执行,跳过本次');
return { skipped: true };
}
running = true;
try {
return await ctx.service.logRetention.runAll();
} finally {
running = false;
}
},
};