'use strict'; const SHORT_TASK_QUERY_TIMEOUT_MS = 15000; const SHORT_TASK_EXECUTION_TIMEOUT_MS = 30000; const EXECUTION_LOG_CACHE_KEY = 'schedule:sync_outbound_orders_to_delivery:last_execution'; const EXECUTION_LOG_CACHE_TTL = 300; // 5 分钟 const EXECUTION_LOG_HISTORY_CACHE_KEY = 'schedule:sync_outbound_orders_to_delivery:history'; const EXECUTION_LOG_HISTORY_MAX = 20; // 保留最近 20 次执行记录 const EXECUTION_LOG_HISTORY_TTL = 86400; // 1 天 /** * 将本次执行日志写入缓存。 * * @param {Object} ctx Egg 上下文。 * @param {Object} logEntry 日志条目。 * @return {Promise} */ async function writeExecutionLogToCache(ctx, logEntry) { try { if (ctx.app && typeof ctx.app.setCacheAsync === 'function') { await ctx.app.setCacheAsync(EXECUTION_LOG_CACHE_KEY, logEntry, EXECUTION_LOG_CACHE_TTL); } } catch (err) { // 缓存写入失败不影响主流程 ctx.logger.warn(`[sync-outbound-orders-to-delivery] 写入执行日志缓存失败: ${err.message}`); } } /** * 将本次执行日志追加到历史记录缓存(保留最近 N 次)。 * * 用于不翻日志文件也能观察定时任务每轮执行情况(selected/created/status/error), * 便于排查「订单满足迁移条件但迟迟未切表」类问题。 * * @param {Object} ctx Egg 上下文。 * @param {Object} logEntry 日志条目。 * @return {Promise} 无返回值。 */ async function appendExecutionHistory(ctx, logEntry) { try { if (typeof ctx.app.getCacheAsync !== 'function' || typeof ctx.app.setCacheAsync !== 'function') { return; } const rawHistory = await ctx.app.getCacheAsync(EXECUTION_LOG_HISTORY_CACHE_KEY); const history = Array.isArray(rawHistory) ? rawHistory : []; history.unshift(logEntry); await ctx.app.setCacheAsync( EXECUTION_LOG_HISTORY_CACHE_KEY, history.slice(0, EXECUTION_LOG_HISTORY_MAX), EXECUTION_LOG_HISTORY_TTL ); } catch (err) { // 历史日志写入失败不影响主流程 ctx.logger.warn(`[sync-outbound-orders-to-delivery] 写入执行历史缓存失败: ${err.message}`); } } /** * 提取错误详情,方便定位问题位置。 * * @param {Error} error 错误对象。 * @return {Object} 错误详情。 */ function extractErrorDetail(error) { if (!error) return {}; const detail = { name: error.name || '', message: error.message || '', code: error.code || '', }; // Sequelize 父级错误(通常包含 SQL 信息) if (error.parent) { detail.parent = { name: error.parent.name || '', message: error.parent.message || '', code: error.parent.code || '', sql: error.parent.sql || '', }; } // SequelizeValidationError 的 fields 列表 if (Array.isArray(error.errors)) { detail.validation_errors = error.errors.map(e => ({ message: e.message, type: e.type, path: e.path, value: String(e.value ?? ''), })); } // 堆栈前 3 行(定位调用链) if (error.stack) { detail.stack_top = error.stack.split('\n').slice(0, 4).map(s => s.trim()); } return detail; } /** * 每 1 分钟在单 worker 中同步一次正常出库订单到配送表。 */ module.exports = { schedule: { interval: '1m', type: 'worker', immediate: false, disable: false, }, queryTimeoutMs: SHORT_TASK_QUERY_TIMEOUT_MS, executionTimeoutMs: SHORT_TASK_EXECUTION_TIMEOUT_MS, /** * 执行已出库订单迁移任务。 * * @param {Object} ctx Egg 上下文。 * @return {Promise} 无返回值。 */ async task(ctx) { if (ctx.app._syncOutboundOrdersToDeliveryRunning) { return; } ctx.app._syncOutboundOrdersToDeliveryRunning = true; const startedAt = Date.now(); let status = 'success'; let errorMessage = ''; let errorDetail = null; let result = null; try { result = await ctx.service.systems.orderDeliveryMigration.syncOutboundOrdersToDelivery({ queryTimeoutMs: SHORT_TASK_QUERY_TIMEOUT_MS, executionTimeoutMs: SHORT_TASK_EXECUTION_TIMEOUT_MS, }); if (result && result.retryableFailure) { status = 'retryable_failure'; errorMessage = `retryableFailureType=${result.retryableFailureType}, timeoutCount=${result.timeoutCount || 0}`; ctx.logger.warn(`[sync-outbound-orders-to-delivery] 正常迁移遇到 ${result.retryableFailureType},已标记 ${result.timeoutCount || 0} 条订单为出库超时`); } else if (result && result.totalCreated > 0) { ctx.logger.info(`[sync-outbound-orders-to-delivery] 同步 ${result.totalCreated} 条已出库订单`); } // 始终输出汇总日志(含 0 条场景,确认定时任务在跑) ctx.logger.info(`[sync-outbound-orders-to-delivery] 本轮完成 selected=${result ? result.totalSelected : 0} created=${result ? result.totalCreated : 0} skipped=${result ? result.totalSkipped : 0} timeout=${result ? result.totalTimeout : 0}`); } catch (error) { status = 'error'; errorMessage = error.message; errorDetail = extractErrorDetail(error); ctx.logger.error(`[sync-outbound-orders-to-delivery] 同步失败: ${error.message}`, errorDetail); } finally { ctx.app._syncOutboundOrdersToDeliveryRunning = false; } // 写入执行日志到缓存 const logEntry = { executed_at: new Date().toISOString(), duration_ms: Date.now() - startedAt, status, error_message: errorMessage, error_detail: errorDetail, total_selected: result ? result.totalSelected : 0, total_created: result ? result.totalCreated : 0, total_skipped: result ? result.totalSkipped : 0, total_timeout: result ? result.totalTimeout : 0, warehouse_ids: result ? result.warehouseIds : [], }; await writeExecutionLogToCache(ctx, logEntry); await appendExecutionHistory(ctx, logEntry); ctx.logger.info(`[sync-outbound-orders-to-delivery] 执行日志已写入缓存 key=${EXECUTION_LOG_CACHE_KEY} history=${EXECUTION_LOG_HISTORY_CACHE_KEY}`); }, };