72 lines
2.7 KiB
JavaScript
72 lines
2.7 KiB
JavaScript
// app/schedule/wechat_agreement_cleanup.js
|
||
'use strict';
|
||
|
||
/**
|
||
* 微信用户须知版本清理定时任务。
|
||
*
|
||
* 默认每 1 小时整点(cron:秒 分 时 日 月 周 = 0 0 * * * *)在单 worker 中执行一次,
|
||
* 真实删除 wms_wechat_agreement_version 中「未被使用且不是对应 appid 最终版」的历史版本,
|
||
* 释放 MySQL 磁盘空间。保留规则:各 appid 最终版(version 最大)+ 被
|
||
* wms_user_oauth.agreement_version_id 引用的版本。
|
||
* cron 从 config.wechatAgreementCleanup.cron 读取(config.default.js 提供默认值),
|
||
* 本地环境可在 config.local.js 覆盖为短间隔以便快速验证;enable=false 时不注册本任务;
|
||
* 实际清理逻辑收敛在 service.systems.wechat.cleanupUnusedAgreementVersions。
|
||
*
|
||
* @param {Object} app Egg 应用实例。
|
||
* @return {Object} 定时任务定义(含 schedule 与 task)。
|
||
*/
|
||
module.exports = app => {
|
||
const cleanupConfig = (app.config && app.config.wechatAgreementCleanup) || {};
|
||
const cleanupCron = typeof cleanupConfig.cron === 'string' && cleanupConfig.cron
|
||
? cleanupConfig.cron
|
||
: '0 0 * * * *';
|
||
|
||
return {
|
||
schedule: {
|
||
cron: cleanupCron,
|
||
type: 'worker',
|
||
immediate: false,
|
||
disable: cleanupConfig.enable === false,
|
||
},
|
||
|
||
/**
|
||
* 执行用户须知历史版本清理。
|
||
*
|
||
* 采用单 worker 防重入:上一轮未结束时跳过本轮;
|
||
* 任务失败只记录错误日志,不向上抛出,避免导致 schedule 崩溃。
|
||
*
|
||
* @param {Object} ctx Egg 上下文。
|
||
* @return {Promise<void>} 无返回值。
|
||
*/
|
||
async task(ctx) {
|
||
const scheduleName = 'wechat_agreement_cleanup';
|
||
|
||
if (ctx.app._wechatAgreementCleanupRunning) {
|
||
ctx.logger.info(`[${scheduleName}] 本轮任务跳过,上一轮尚未结束`);
|
||
return;
|
||
}
|
||
|
||
ctx.app._wechatAgreementCleanupRunning = true;
|
||
const startedAt = Date.now();
|
||
try {
|
||
const config = ctx.app.config.wechatAgreementCleanup || {};
|
||
const batchSize = Number(config.batchSize) > 0
|
||
? Math.floor(Number(config.batchSize))
|
||
: 500;
|
||
|
||
const summary = await ctx.service.systems.wechat.cleanupUnusedAgreementVersions(batchSize);
|
||
|
||
ctx.logger.info(
|
||
`[${scheduleName}] 本轮完成 deleted=${summary.deleted} kept_latest=${summary.kept_latest}`
|
||
+ ` kept_in_use=${summary.kept_in_use} total=${summary.total}`
|
||
+ ` duration=${Date.now() - startedAt}ms`
|
||
);
|
||
} catch (error) {
|
||
ctx.logger.error(`[${scheduleName}] 执行失败: ${error.message}`);
|
||
} finally {
|
||
ctx.app._wechatAgreementCleanupRunning = false;
|
||
}
|
||
},
|
||
};
|
||
};
|