// app/schedule/domain_verify_scan.js 'use strict'; /** * 域名验证扫描定时任务。 * * 按 config.frontConfig.domainVerify.interval 周期性触发(默认 10m), * 扫描 wms_warehouse_front_config 中「已生成待校验 TXT 记录、且尚未通过验证」的行, * 逐行解析 DNS TXT 记录并回写 domain_status / domain_verified_at / * domain_verify_attempts / domain_last_error;只有通过验证的域名才会被公共拉取接口 * 与 nginx server 块生成流程放行。 * * 并发控制(双保险): * 1. 进程内重入标志 ctx.app._domainVerifyScanRunning:上一轮未结束时跳过本轮; * 2. Redis 跨进程互斥锁 SET NX EX:多实例部署时同一轮只有一个实例执行, * TTL 取 config.frontConfig.domainVerify.lockTtlSeconds(默认 600s); * Redis 不可用或抛错时降级为「仅进程内防重入」并 WARN, * 不因缓存故障中断域名验证。 * * 业务逻辑全部委托 service.systems.frontConfig.verifyPendingDomains(本文件不写 SQL); * 任务失败只记录错误日志,不向上抛出,避免 schedule 崩溃。 * * 关闭方式:config.frontConfig.domainVerify.enable = false,此时 schedule * 标记为 disable,Egg 不注册本任务(进程内不会执行)。 */ /** @type {string} 跨进程互斥锁 key */ const LOCK_CACHE_KEY = 'schedule:domain_verify_scan:lock'; /** @type {string} 日志前缀 tag */ const LOG_TAG = '[domain_verify_scan]'; /** @type {number} 锁 TTL 兜底值(秒) */ const DEFAULT_LOCK_TTL_SECONDS = 600; /** @type {string} 扫描间隔兜底值 */ const DEFAULT_INTERVAL = '10m'; /** * 获取 Redis cache 客户端。 * * @param {Object} app Egg 应用实例。 * @return {Object|null} Redis 客户端或 null。 */ function getCacheRedisClient(app) { if (!app || !app.redis || typeof app.redis.get !== 'function') { return null; } try { return app.redis.get('cache') || null; } catch (error) { return null; } } /** * 获取跨进程互斥锁(SET NX EX)。 * * @param {Object} ctx Egg 上下文。 * @param {number} ttlSeconds 锁 TTL(秒)。 * @param {string} lockValue 锁持有者标识(pid + 时间戳)。 * @return {Promise} 是否获取成功;Redis 不可用时返回 true(退化为进程内防重入)。 */ async function acquireLock(ctx, ttlSeconds, lockValue) { const redis = getCacheRedisClient(ctx.app); if (!redis || typeof redis.set !== 'function') { ctx.logger.warn(`${LOG_TAG} Redis 不可用,跨进程互斥降级为进程内防重入`); return true; } try { const result = await redis.set(LOCK_CACHE_KEY, lockValue, 'EX', ttlSeconds, 'NX'); return result === 'OK'; } catch (error) { ctx.logger.warn(`${LOG_TAG} 获取互斥锁失败(按未加锁继续): ${error.message}`); return true; } } /** * 释放跨进程互斥锁(GET 比对 value 后再 DEL,避免误删他人锁)。 * * 仍存在极小竞态窗口:本进程 GET 到自己的 value 后、DEL 之前锁恰好 TTL 到期 * 并被其它实例抢到(value 为 pid + 时间戳,重复概率极低),最坏结果是提前释放 * 一次锁,不会造成数据错误(service 层 update 自带 id + domain 防并发守卫), * 因此接受该窗口而不引入 Lua 脚本。 * * @param {Object} ctx Egg 上下文。 * @param {string} lockValue 锁持有者标识(与获取时一致)。 * @return {Promise} 无返回值。 */ async function releaseLock(ctx, lockValue) { const redis = getCacheRedisClient(ctx.app); if (!redis || typeof redis.get !== 'function' || typeof redis.del !== 'function') { // Redis 不可用则跳过释放,等待 TTL 自然过期 return; } try { const current = await redis.get(LOCK_CACHE_KEY); if (current !== lockValue) { return; } await redis.del(LOCK_CACHE_KEY); } catch (error) { ctx.logger.warn(`${LOG_TAG} 释放互斥锁失败(等待 TTL 过期): ${error.message}`); } } /** * 域名验证扫描定时任务。 * * @param {Object} app Egg 应用实例。 * @return {Object} 定时任务定义(含 schedule 与 task)。 */ module.exports = app => { // 工厂内动态读取配置:interval / lockTtlSeconds / enable 变更后无需改代码 const frontConfig = (app.config && app.config.frontConfig) || {}; const domainVerify = frontConfig.domainVerify || {}; const interval = typeof domainVerify.interval === 'string' && domainVerify.interval ? domainVerify.interval : DEFAULT_INTERVAL; const lockTtlSeconds = Number(domainVerify.lockTtlSeconds) > 0 ? Math.floor(Number(domainVerify.lockTtlSeconds)) : DEFAULT_LOCK_TTL_SECONDS; return { schedule: { // 固定间隔触发;domainVerify.enable === false 时 disable 为 true, // Egg 直接不注册本任务(不会进入 task,也不会占用 worker 周期) interval, type: 'worker', immediate: false, disable: domainVerify.enable === false, }, /** * 执行一轮域名验证扫描。 * * @param {Object} ctx Egg 上下文。 * @return {Promise} 无返回值。 */ async task(ctx) { // 进程内防重入:单实例上一轮未结束时不再叠加下一轮 if (ctx.app._domainVerifyScanRunning) { ctx.logger.info(`${LOG_TAG} 本轮任务跳过,上一轮尚未结束`); return; } const lockValue = `${process.pid}-${Date.now()}`; const locked = await acquireLock(ctx, lockTtlSeconds, lockValue); if (!locked) { ctx.logger.info(`${LOG_TAG} 未获取到跨进程互斥锁,本轮跳过(其它实例正在执行)`); return; } ctx.app._domainVerifyScanRunning = true; const startedAt = Date.now(); try { // 业务逻辑一律委托 service,schedule 内不写 SQL const summary = await ctx.service.systems.frontConfig.verifyPendingDomains({}); ctx.logger.info( `${LOG_TAG} 本轮完成 scanned=${summary.scanned} verified=${summary.verified}` + ` failed=${summary.failed} skipped=${summary.skipped}` + ` errors=${summary.errors.length} duration=${Date.now() - startedAt}ms` ); if (summary.errors.length > 0) { ctx.logger.warn(`${LOG_TAG} 本轮错误摘要: ${summary.errors.slice(0, 5).join(' | ')}`); } } catch (error) { // service 层已 fail-soft(迁移未执行时返回零统计),此处为最后兜底: // 只记日志不上抛,避免 schedule 崩溃 ctx.logger.error(`${LOG_TAG} 本轮执行异常: ${error && error.message ? error.message : String(error)}`); } finally { ctx.app._domainVerifyScanRunning = false; await releaseLock(ctx, lockValue); } }, }; };