| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501 |
- const path = require('path')
- const axios = require('axios')
- const OSS = require('ali-oss')
- const mq = require('../../plugin/mq')
- const { mq: mqName } = require('../../plugin/mq/mqPrefix')
- const { assertRunforgeTaskIngress, TASK_QUEUE } = require('../../plugin/mq/runforgeTaskMq')
- const db = require('../../plugin/DataBase/db')
- const Redis = require('../../plugin/DataBase/Redis')
- const EmailTemplate = require('../../plugin/Email/emailTemplate')
- const { URLSearchParams } = require('url')
- const {
- getPathData,
- selectCheckpoints,
- generateCadence
- } = require('../../plugin/Lepao/Path')
- const { v4: uuidv4 } = require('uuid')
- const {
- dataEncrypt,
- dataDecrypt,
- dataSign
- } = require('../../plugin/Lepao/Crypto')
- const generateGyrFromPath = require('../../plugin/Lepao/generateGyrFromPath')
- const { syncAccountInfo } = require('./syncAccountInfo')
- const { insertLedgerRecord } = require('./CountLedger')
- const {
- getWebVpnCookieHeader,
- invalidateWebVpnCookie,
- isProbablyVpnLoginHtml,
- isWebVpnUnifiedAuthCredentialFailure,
- markLepaoUnifiedAuthFailed,
- assertLepaoJwBindingOrThrow
- } = require('./webvpnCookie')
- const { withLepaoAccountProxy } = require('./lepaoOutboundProxy')
- const Logger = require('../Logger')
- class Worker {
- constructor() {
- this.logger = new Logger(
- path.join(__dirname, '../logs/LepaoWorker.log'),
- 'INFO'
- )
- this.handlers = {}
- this.running = false
- this.baseUrl = 'https://lepao.ctbu.edu.cn/v3/api.php'
- this.taskQueue = TASK_QUEUE
- this.resultQueue = mqName('runforge_task_result_queue')
- this.deadQueue = mqName('runforge_task_dead_queue')
- this.noticeQueue = mqName('runforge_message_queue')
- this.channelName = 'lepao_worker'
- this.maxRetry = 3
- this.timeout = 15000
- this.maxQueueLength = 2000
- this.defaultUserAgent = 'Mozilla/5.0 (Linux; Android 16; 2211133C Build/BP2A.250605.031.A3; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/138.0.7204.180 Mobile Safari/537.36 XWEB/1380347 MMWEBSDK/20250202 MMWEBID/1020 wxwork/5.0.6.66174 MicroMessenger/8.0.28.48(0x28001c30) MiniProgramEnv/android Luggage/3.0.2.95ef3f83 NetType/WIFI Language/zh_CN ABI/arm64'
- // 调试模式:将 axios 请求走本地代理(例如 charles/fiddler)
- // 开启方式:设置环境变量 LEPAO_DEBUG_PROXY=1
- this.debugProxyEnabled = String(process.env.LEPAO_DEBUG_PROXY || '').trim() === '1'
- this.debugProxyHost = process.env.LEPAO_DEBUG_PROXY_HOST || '127.0.0.1'
- this.debugProxyPort = Number(process.env.LEPAO_DEBUG_PROXY_PORT || 9000)
- }
- /* ================= 工具 ================= */
- api(path) {
- return this.baseUrl + path
- }
- traceId() {
- return Date.now() + '_' + Math.random().toString(36).slice(2, 8)
- }
- sleep(ms) {
- return new Promise(r => setTimeout(r, ms))
- }
- isRunSuccess(bindResponse) {
- const payload = bindResponse?.data
- if (!bindResponse || bindResponse.status !== 1 || !payload) {
- return {
- ok: false,
- reason: bindResponse?.info || '系统繁忙,请联系客服或稍后再试'
- }
- }
- const failedReason = payload.record_failed_reason || ''
- if (failedReason === '' || failedReason === '自动确认有效') {
- return { ok: true, payload }
- }
- return {
- ok: false,
- reason: failedReason,
- payload
- }
- }
- extractApiErrorMessage(name, result) {
- if (!result) {
- this.logger.error(`${name} 接口无响应数据: ${this.safeStringify(result)}`)
- return `系统繁忙,请联系客服或稍后再试`
- }
- const candidates = [
- result.info,
- result.msg,
- result.message,
- result?.data?.info,
- result?.data?.msg,
- result?.data?.message,
- result?.data?.record_failed_reason
- ]
- const reason = candidates.find(v => typeof v === 'string' && v.trim() !== '')
- if (reason) {
- return reason
- }
- if (result.code !== undefined || result.status !== undefined) {
- this.logger.error(`${name} 接口返回异常: ${this.safeStringify(result)}`)
- return `系统繁忙,请联系客服或稍后再试`
- }
- return `系统繁忙,请联系客服或稍后再试`
- }
- async markLoginExpired(account) {
- if (!account) return
- try {
- const ownerRows = await db.query(
- 'SELECT create_user FROM lepao_account WHERE student_num = ? LIMIT 1',
- [account]
- )
- const owner = ownerRows?.[0]?.create_user
- const now = Date.now()
- await db.query('UPDATE lepao_account SET state = 0, update_time = ? WHERE student_num = ?', [
- now,
- account
- ])
- if (owner) {
- await db.query(
- 'UPDATE jw_account SET state = 0, update_time = ? WHERE create_user = ? AND username = ?',
- [now, owner, account]
- )
- }
- this.logger.warn(`${account} 乐跑登录失效,lepao_account / jw_account 状态已回写`)
- } catch (error) {
- this.logger.error(`更新账号登录状态失败:${error.stack || error}`)
- }
- }
- async writeSuccessRedis(account) {
- if (!account) return
- try {
- const now = new Date()
- const tomorrow = new Date().setHours(24, 0, 0, 0)
- const exp = Math.floor((tomorrow - now) / 1000)
- await Redis.set(`lepaoSuccess:${account}`, account, { EX: exp })
- } catch (error) {
- this.logger.error(`写入乐跑成功缓存失败: ${error.stack || error}`)
- }
- }
- async addLepaoRecord(uuid, account, result, pathId, pointData, runMode = 'auto') {
- if (!uuid || !account || !result || !pathId) return
- try {
- const time = Date.now()
- const publicId = uuidv4()
- const safeRunMode = runMode === 'manual' ? 'manual' : 'auto'
- const sql = 'INSERT INTO lepao_record (public_id, uuid, time, lepao_account, result, path_id, point_data, state, run_mode) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)'
- await db.query(sql, [publicId, uuid, time, account, result, pathId, JSON.stringify(pointData || []), 1, safeRunMode])
- } catch (error) {
- this.logger.error(`写入乐跑记录失败: ${error.stack || error}`)
- }
- }
- async syncRunCount(req, ctx) {
- try {
- const sid = req?.student_id || req?.account
- if (
- req?.uid == null ||
- req?.token == null ||
- String(req.token).trim() === '' ||
- req?.school_id == null ||
- !sid
- ) {
- return { ok: false, reason: '缺少同步乐跑次数所需凭证' }
- }
- const recordData = await this.handlers['lepao.getRecord'](req, ctx)
- const data = recordData?.data
- if (!data) {
- return { ok: false, reason: 'getRecord 无有效 data' }
- }
- const term_num = Number(data.term_num ?? 30)
- const total_num = Number(data.total_num ?? 0)
- const sql = 'UPDATE lepao_account SET term_num = ?, total_num = ? WHERE student_num = ?'
- const rows = await db.query(sql, [term_num, total_num, req.account])
- if (!rows || rows.affectedRows !== 1) {
- this.logger.warn(`${req.account}更新乐跑次数失败`)
- return { ok: false, reason: '数据库更新 lepao_account 失败', term_num, total_num }
- }
- this.logger.info(`${req.account}更新乐跑次数成功 term_num=${term_num}, total_num=${total_num}`)
- return { ok: true, term_num, total_num }
- } catch (error) {
- this.logger.warn(`${req?.account || 'unknown'}同步乐跑次数失败: ${error.message || error}`)
- return { ok: false, reason: error.message || String(error) }
- }
- }
- lepaoTimestamp() {
- return Number((Date.now() / 1000).toFixed(3))
- }
- axiosProxyConfig() {
- if (!this.debugProxyEnabled) {
- return { proxy: false }
- }
- this.logger.info(`使用本地代理: ${this.debugProxyHost}:${this.debugProxyPort}`)
- return {
- proxy: {
- host: this.debugProxyHost,
- port: this.debugProxyPort,
- protocol: 'http'
- }
- }
- }
- async enqueueTask(channel, type, data, options = {}) {
- const payload = {
- id: options.id || this.traceId(),
- type,
- data,
- retry: options.retry ?? 0
- }
- await channel.sendToQueue(
- this.taskQueue,
- Buffer.from(JSON.stringify(payload)),
- { persistent: true, contentType: 'application/json' }
- )
- return payload.id
- }
- async withTimeout(promise, name) {
- return Promise.race([
- promise,
- new Promise((_, reject) =>
- setTimeout(() => reject(new Error(`${name} 超时`)), this.timeout)
- )
- ])
- }
- async retry(fn, name) {
- let lastErr
- for (let i = 0; i < this.maxRetry; i++) {
- try {
- return await fn()
- } catch (err) {
- lastErr = err
- if (!this.isRetryableTaskError(err)) {
- throw err
- }
- this.logger.warn(`[RETRY] ${name} 第${i + 1}次失败`)
- await this.sleep(1000 * (i + 1)) // 指数退避
- }
- }
- throw lastErr
- }
- isNetworkError(err) {
- if (!err) return false
- if (err.code && ['ECONNRESET', 'ECONNABORTED', 'ETIMEDOUT', 'ENOTFOUND', 'EAI_AGAIN'].includes(err.code)) {
- return true
- }
- if (err.isAxiosError && !err.response) return true
- const msg = (err.message || '').toLowerCase()
- return msg.includes('timeout') || msg.includes('network')
- }
- isRetryableTaskError(err) {
- if (!err) return false
- if (err.retryable === true) return true
- if (this.isNetworkError(err)) return true
- return ['PATH_SELECT_FAILED', 'CHECKPOINT_FETCH_FAILED', 'CHECKPOINT_INSUFFICIENT'].includes(err.code)
- }
- safeStringify(obj) {
- const seen = new WeakSet();
- return JSON.stringify(obj, (key, value) => {
- if (typeof value === 'object' && value !== null) {
- if (seen.has(value)) return '[Circular]';
- seen.add(value);
- }
- return value;
- })
- }
- log(traceId, type, msg, data) {
- this.logger.info(`[${traceId}] [${type}] ${msg} ${data ? this.safeStringify(data) : ''}`)
- }
- logErr(traceId, msg, err) {
- this.logger.error(`[${traceId}] ${msg} ${err.stack || err}`)
- }
- async request(traceId, name, url, raw, headers = {}, ctx = null) {
- return this.retry(async () => {
- this.log(traceId, 'REQ', name, raw)
- const buildHeaders = () => {
- const mergedHeaders = {
- 'Content-Type': 'application/x-www-form-urlencoded',
- 'Accept': '*/*',
- 'Accept-Language': 'zh-CN,zh-Hans;q=0.9',
- 'Accept-Encoding': 'gzip, deflate, br',
- 'Referer': 'https://servicewechat.com/wxf94c4ddb63d87ede/32/page-frame.html',
- ...headers
- }
- if (!mergedHeaders['User-Agent']) {
- mergedHeaders['User-Agent'] = this.defaultUserAgent
- }
- if (ctx?.webvpnCookie) {
- mergedHeaders.Cookie = ctx.webvpnCookie
- }
- return mergedHeaders
- }
- const form = new URLSearchParams()
- form.append('ostype', '5')
- form.append('data', dataEncrypt(JSON.stringify(raw)))
- const postOnce = async () => {
- const execPost = (extraAxios) =>
- axios.post(url, form, {
- headers: buildHeaders(),
- ...extraAxios,
- responseType: 'text',
- transformResponse: [(body) => body]
- })
- return withLepaoAccountProxy(execPost, {
- createUserUuid: ctx?.create_user || null,
- studentNum: ctx?.lepaoStudentNum || null,
- debugAxiosOpts: this.axiosProxyConfig(),
- logger: this.logger
- })
- }
- let res = await this.withTimeout(postOnce(), name)
- let result
- try {
- result = JSON.parse(res.data)
- } catch {
- result = res.data
- }
- if (
- typeof result === 'string' &&
- isProbablyVpnLoginHtml(result) &&
- ctx?.create_user &&
- ctx?.lepaoStudentNum
- ) {
- this.log(traceId, 'VPN', '响应疑似统一身份认证登录页,刷新 Cookie 后重试', { name })
- await invalidateWebVpnCookie(ctx.create_user, ctx.lepaoStudentNum)
- try {
- ctx.webvpnCookie = await getWebVpnCookieHeader(ctx.create_user, ctx.lepaoStudentNum, {
- skipCache: true,
- logger: this.logger
- })
- } catch (vpnRefreshErr) {
- if (isWebVpnUnifiedAuthCredentialFailure(vpnRefreshErr)) {
- await markLepaoUnifiedAuthFailed(
- ctx.lepaoStudentNum,
- ctx.create_user,
- ctx.lepaoStudentNum
- )
- }
- throw vpnRefreshErr
- }
- res = await this.withTimeout(postOnce(), name)
- try {
- result = JSON.parse(res.data)
- } catch {
- result = res.data
- }
- }
- if (result?.data && result?.is_encrypt === 1) {
- result.data = JSON.parse(dataDecrypt(result.data))
- }
- this.log(traceId, 'RES', name, result)
- // 除 bindData 外,其余调用若接口已明确返回失败,直接抛出该失败原因
- // bindData 需要保留完整响应由 isRunSuccess 统一判定。
- if (name !== 'bindData') {
- const hasCode = result && Object.prototype.hasOwnProperty.call(result, 'code')
- const hasStatus = result && Object.prototype.hasOwnProperty.call(result, 'status')
- const failedByCode = hasCode && Number(result.code) !== 1 && Number(result.code) !== 200
- const failedByStatus = hasStatus && Number(result.status) !== 1
- if (failedByCode || failedByStatus) {
- const message = this.extractApiErrorMessage(name, result)
- const err = new Error(message)
- // 学习 Lepao.js:若明确提示重新登录,自动标记账号失效
- if (message.includes('重新登录')) {
- await this.markLoginExpired(raw?.student_num)
- }
- // 接口已返回业务错误,禁止重试
- err.retryable = false
- throw err
- }
- }
- return result
- }, name)
- }
- /**
- * 累计完成次数 >= 跑友目标(且目标>0)时:关闭 auto_run,并发送乐跑目标完成邮件 / Bot 通知
- */
- async handleLepaoTargetComplete(account, user, totalNum, traceId) {
- const target = Number(user?.target_count) || 0
- const total = Number(totalNum) || 0
- if (target <= 0 || total < target) return
- try {
- const up = await db.query(
- 'UPDATE lepao_account SET auto_run = 0 WHERE student_num = ? AND auto_run = 1',
- [account]
- )
- if (up?.affectedRows !== 1) {
- return
- }
- this.logger.info(
- `${account} 已达目标次数(${total}/${target}),关闭自动乐跑`
- )
- } catch (e) {
- this.logger.error(`关闭自动乐跑失败 ${account}: ${e.message || e}`)
- return
- }
- const noticeType = user.notice_type || 'none'
- const overPayload = {
- type: 'lepao_over',
- umo: user.bot_umo,
- name: user.name,
- account,
- total_num: total,
- target_count: target,
- traceId
- }
- if (noticeType === 'email' && user.email) {
- try {
- await EmailTemplate.lepaoOver(user.email, {
- name: user.name,
- account
- })
- } catch (e) {
- this.logger.error(`lepaoOver 邮件发送失败: ${e.message || e}`)
- }
- }
- if (noticeType === 'bot' && user.bot_umo) {
- try {
- const ch = await mq.getChannel(this.noticeQueue)
- await ch.assertQueue(this.noticeQueue, { durable: true })
- ch.sendToQueue(
- this.noticeQueue,
- Buffer.from(JSON.stringify(overPayload)),
- {
- persistent: true,
- contentType: 'application/json'
- }
- )
- } catch (e) {
- this.logger.error(`lepao_over Bot 通知失败: ${e.message || e}`)
- }
- }
- }
- register(type, handler) {
- this.handlers[type] = handler
- this.logger.info(`注册任务: ${type}`)
- }
- /* ================= 业务 ================= */
- initHandlers() {
- this.register('lepao.syncAccountInfo', async (req) => {
- const studentNum = req?.student_num
- if (!studentNum) {
- throw new Error('同步乐跑账号失败:缺少 student_num')
- }
- const syncResult = await syncAccountInfo({
- studentNum,
- logger: this.logger
- })
- if (!syncResult.ok) {
- const err = new Error(syncResult.msg || '同步乐跑账号失败')
- err.retryable = false
- throw err
- }
- return syncResult.data
- })
- /* ---------------- 开始乐跑 ---------------- */
- this.register('lepao.startRun', async (req, ctx) => {
- const traceId = ctx.traceId
- const maxPathRetry = 20 // 自动获取路径失败最大重试次数
- let pathRetry = 0
- let pointData = null
- let pathData = null
- let newPathData = null
- let ossPath = null
- let ossSts = null
- let userData = null
- let pathId = null
- let runZoneId = 0
- let bindRes = null
- try {
- // 检查redis是否存在当天乐跑成功记录
- const isSuccess = await Redis.get(`lepaoSuccess:${req.account}`)
- if (isSuccess)
- throw new Error('该账号当天已乐跑成功!请勿重复乐跑')
- userData = await this.handlers['lepao.getUserData'](req, ctx)
- try {
- ctx.webvpnCookie = await getWebVpnCookieHeader(userData.create_user, userData.student_num, {
- logger: this.logger
- })
- ctx.create_user = userData.create_user
- ctx.lepaoStudentNum = userData.student_num
- } catch (vpnErr) {
- this.logErr(traceId, '统一认证登录失败', vpnErr)
- if (isWebVpnUnifiedAuthCredentialFailure(vpnErr) && userData.student_num) {
- try {
- await markLepaoUnifiedAuthFailed(
- userData.student_num,
- userData.create_user,
- userData.student_num
- )
- } catch (markErr) {
- this.logger.error(`标记统一认证失败 state=3 失败: ${markErr.message || markErr}`)
- }
- }
- throw new Error(vpnErr.message || '统一认证登录失败,请检查统一认证账号密码是否已在乐跑绑定中填写正确')
- }
- // 立刻合并账号凭证,保证后续任意 throw 时 finally 里 syncRunCount 不会用空 token 调 getRecord
- req = {
- ...req,
- ...userData,
- student_id: req.account
- }
- // 进入乐跑进程后写入进行中缓存
- const progressKey = `lepaoProgress:${req.account}`
- const inProgress = await Redis.get(progressKey)
- if (inProgress) {
- throw new Error('该账号已进入乐跑任务队列,请等待乐跑完成后再进行乐跑操作')
- }
- await Redis.set(progressKey, req.account, { EX: 1800 })
- ossSts = await this.handlers['lepao.getOssSts'](req, ctx)
- if (!ossSts?.bucket || !ossSts?.AccessKeyId || !ossSts?.AccessKeySecret || !ossSts?.SecurityToken) {
- throw new Error('获取 OSS 凭证失败,请联系客服或稍后再试')
- }
- req = {
- ...req,
- ossSts
- }
- // 晚上10点后提前
- let run_end_time = Math.floor(Date.now() / 1000) - 300 // 提前5分钟
- let hour = new Date().getHours()
- if (hour < 7)
- throw new Error('当前不在有效乐跑时间范围内。RunForge支持乐跑时间段为7:00~24:00')
- if (hour >= 22) {
- this.logger.info(`${req.account}当前时间为${hour}点,调整run_end_time提前5小时`)
- run_end_time -= 18000
- }
- req = {
- ...req,
- run_end_time
- }
- // 1.5️⃣ 乐跑开始前扣减次数(失败会返还,且有幂等保护)
- await this.handlers['lepao.consumeCount']({
- account: req.account,
- uuid: userData?.create_user
- }, ctx)
- while (pathRetry < maxPathRetry) {
- try {
- // 2️⃣ 获取路径(仅路径选择失败时重试)
- const pathRes = await this.handlers['lepao.getPath'](req, ctx)
- pathData = pathRes.pathData
- pathId = pathData?.id || null
- newPathData = getPathData(pathData.data, req.run_end_time, pathData.time)
- // 3️⃣ 切换跑区
- const zoneRes = await this.handlers['lepao.setZone']({ ...req, pathData }, ctx)
- runZoneId = zoneRes?.run_zone_id || 0
- // 4️⃣ 上传 OSS 文件、生成打卡点
- const uploadRes = await this.handlers['lepao.uploadOssFile']({ ...req, pathData, newPathData }, ctx)
- ossPath = uploadRes.oss_path
- pointData = uploadRes.point_data
- if (!pointData) {
- pathRetry++
- this.logger.warn(`[${traceId}] 打卡点不满足要求,重新获取路径 第${pathRetry}次`)
- continue
- }
- // 打卡点符合要求,跳出循环
- break
- } catch (err) {
- if (!this.isRetryableTaskError(err)) {
- throw err
- }
- this.logger.warn(`[${traceId}] 可重试错误,重新获取路径 第${pathRetry + 1}次,原因:${err.message}`)
- pathRetry++
- await this.sleep(1000 * pathRetry)
- }
- }
- if (!pointData) {
- throw new Error('打卡点获取失败,乐跑任务终止')
- }
- // 5️⃣ 提交跑步数据
- bindRes = await this.handlers['lepao.bindData']({
- ...req,
- pathData,
- run_zone_id: runZoneId,
- record_file: ossPath,
- point_data: pointData
- }, ctx)
- // 绑定接口有返回即入库
- if (bindRes && bindRes.data) {
- await this.addLepaoRecord(userData?.create_user, req.account, bindRes.data, pathId, pointData, req.runMode)
- }
- const runResult = this.isRunSuccess(bindRes)
- if (runResult.ok || runResult.reason === '当天关联成绩次数已达到上限') {
- await this.writeSuccessRedis(req.account)
- }
- if (!runResult.ok) {
- throw new Error(runResult.reason)
- }
- if (bindRes && bindRes.data && bindRes.data.record_id) {
- const gyrRes = await this.handlers['lepao.uploadGyrOssFile']({ ...req, newPathData, record_id: bindRes.data.record_id }, ctx)
- if (gyrRes?.status === 1) {
- this.logger.info(`${req.account}上传加速度数据成功!`)
- } else {
- this.logger.error(`${req.account}上传加速度数据失败!原因:${gyrRes.info || '未知错误'}`)
- }
- }
- // 同步乐跑次数(通知里要带 total_num / term_num,与 getRecord 一致)
- const syncResult = await this.syncRunCount(req, ctx)
- if (!syncResult?.ok) {
- this.logger.error(
- `[${traceId}] 同步乐跑次数失败:${syncResult?.reason || 'unknown'}`
- )
- }
- // 6️⃣ 发送通知(把同步后的学期次数、累计完成次数传给 Bot / 邮件)
- if (ctx.channel) {
- await this.enqueueTask(
- ctx.channel,
- 'lepao.sendNotice',
- {
- account: req.account,
- success: true,
- data: runResult.payload,
- traceId,
- total_num: syncResult?.ok ? syncResult.total_num : undefined
- },
- { id: `${traceId}:notice:success` }
- )
- }
- return { traceId, ossPath, pointData, bindRes }
- } catch (err) {
- this.logger.error(`[${traceId}] 乐跑流程失败:`, err)
- // 若已扣减次数,则失败时返还(幂等)
- try {
- await this.handlers['lepao.refundCount']({
- account: req.account,
- uuid: userData?.create_user
- }, ctx)
- } catch (e) {
- this.logger.error(`[${traceId}] 返还乐跑次数失败:${e.stack || e}`)
- }
- if (ctx.channel) {
- await this.enqueueTask(ctx.channel, 'lepao.sendNotice', {
- account: req.account,
- success: false,
- reason: err.message || '未知错误',
- traceId
- }, { id: `${traceId}:notice:fail` })
- }
- throw err
- } finally {
- await Redis.del(`lepaoProgress:${req.account}`)
- }
- })
- /* ---------------- 发送通知(独立 MQ 任务) ---------------- */
- this.register('lepao.sendNotice', async (req, ctx) => {
- const { account, success, data, reason, traceId, total_num: totalNumArg } = req || {}
- if (!account) {
- throw new Error('发送通知失败:缺少 account')
- }
- const emailSql = `
- SELECT
- a.name,
- a.email,
- a.target_count,
- a.notice_type,
- e.bot_umo
- FROM
- lepao_account a
- LEFT JOIN
- lepao_extra e
- ON
- a.student_num = e.student_num
- WHERE
- a.student_num = ?
- `
- const rows = await db.query(emailSql, [account])
- if (!rows || rows.length === 0) {
- throw new Error('发送通知失败:未找到用户通知配置')
- }
- const user = rows[0]
- const noticeType = user.notice_type || 'none'
- let totalForNotice = totalNumArg
- if (
- success &&
- (totalForNotice === undefined || totalForNotice === null)
- ) {
- const accRows = await db.query(
- 'SELECT total_num FROM lepao_account WHERE student_num = ?',
- [account]
- )
- if (accRows && accRows[0]) {
- totalForNotice = accRows[0].total_num
- }
- }
- if (totalForNotice === undefined || totalForNotice === null) {
- totalForNotice = 0
- }
- totalForNotice = Number(totalForNotice)
- const targetCount = Number(user.target_count) || 0
- const payload = success ? {
- ...(data && typeof data === 'object' ? data : {}),
- type: 'lepao_success',
- umo: user.bot_umo,
- total_num: totalForNotice,
- target_count: targetCount,
- name: user.name,
- account,
- traceId
- } : {
- type: 'lepao_fail',
- umo: user.bot_umo,
- name: user.name,
- account,
- reason,
- traceId
- }
- const afterSuccessNotify = async () => {
- if (success) {
- await this.handleLepaoTargetComplete(account, user, totalForNotice, traceId)
- }
- }
- if (noticeType === 'bot' && user.bot_umo) {
- const ch = await mq.getChannel(this.noticeQueue)
- await ch.assertQueue(this.noticeQueue, { durable: true })
- ch.sendToQueue(
- this.noticeQueue,
- Buffer.from(JSON.stringify(payload)),
- {
- persistent: true,
- contentType: 'application/json'
- }
- )
- await afterSuccessNotify()
- return { delivered: true, via: 'bot' }
- }
- if (noticeType === 'email' && user.email) {
- if (success) {
- await EmailTemplate.lepaoSuccess(user.email, payload)
- await afterSuccessNotify()
- return { delivered: true, via: 'email' }
- }
- await EmailTemplate.lepaoFail(user.email, {
- name: user.name,
- account,
- reason: reason || '系统繁忙,请联系客服或稍后再试',
- traceId
- })
- return { delivered: true, via: 'email' }
- }
- await afterSuccessNotify()
- return { delivered: false, via: 'none' }
- })
- /* ---------------- 扣减次数 ---------------- */
- this.register('lepao.consumeCount', async (req, ctx) => {
- const account = req?.account
- const uuid = req?.uuid
- if (!uuid) {
- throw new Error('扣减乐跑次数失败:缺少 uuid')
- }
- // 幂等:同一 taskId 只扣一次
- const consumeKey = `lepao:consume:${ctx?.taskId || ctx?.traceId || account || uuid}`
- const existed = await Redis.get(consumeKey)
- if (existed) {
- return true
- }
- this.logger.info(`${account || uuid}开始扣减乐跑次数`)
- const conn = await db.connect()
- try {
- await conn.beginTransaction()
- const [userRows] = await conn.execute(
- 'SELECT lepao_count FROM users WHERE uuid = ? FOR UPDATE',
- [uuid]
- )
- if (!userRows || userRows.length !== 1) {
- await conn.rollback()
- throw new Error('扣减乐跑次数失败:用户不存在')
- }
- const beforeCount = Number(userRows[0].lepao_count || 0)
- if (beforeCount < 1) {
- await conn.rollback()
- throw new Error('用户乐跑次数不足,请购买乐跑次数后重试!')
- }
- const [r] = await conn.execute(
- 'UPDATE users SET lepao_count = lepao_count - 1 WHERE uuid = ?',
- [uuid]
- )
- if (!r || r.affectedRows !== 1) {
- await conn.rollback()
- throw new Error('扣减乐跑次数失败:数据库更新失败')
- }
- await insertLedgerRecord({
- executor: conn,
- userUuid: uuid,
- delta: -1,
- balanceBefore: beforeCount,
- balanceAfter: beforeCount - 1,
- bizType: 'run_consume',
- bizId: consumeKey,
- remark: `${account || uuid}乐跑扣除`
- })
- await conn.commit()
- } catch (error) {
- try { await conn.rollback() } catch (_) { }
- throw error
- } finally {
- if (conn?.connection && typeof conn.connection.release === 'function' && typeof conn?.release === 'function') {
- conn.release()
- }
- }
- this.logger.info(`${account || uuid}扣减乐跑次数完成`)
- await Redis.set(consumeKey, '1', { EX: 3600 })
- return true
- })
- /* ---------------- 返还次数(失败时执行) ---------------- */
- this.register('lepao.refundCount', async (req, ctx) => {
- const account = req?.account
- const uuid = req?.uuid
- if (!uuid) {
- return true
- }
- const baseKey = `${ctx?.taskId || ctx?.traceId || account || uuid}`
- const consumeKey = `lepao:consume:${baseKey}`
- const refundKey = `lepao:refund:${baseKey}`
- const consumed = await Redis.get(consumeKey)
- if (!consumed) {
- return true
- }
- const refunded = await Redis.get(refundKey)
- if (refunded) {
- return true
- }
- this.logger.info(`${account || uuid}开始返还乐跑次数`)
- const conn = await db.connect()
- try {
- await conn.beginTransaction()
- const [userRows] = await conn.execute(
- 'SELECT lepao_count FROM users WHERE uuid = ? FOR UPDATE',
- [uuid]
- )
- if (!userRows || userRows.length !== 1) {
- await conn.rollback()
- throw new Error('返还乐跑次数失败:用户不存在')
- }
- const beforeCount = Number(userRows[0].lepao_count || 0)
- const [r] = await conn.execute(
- 'UPDATE users SET lepao_count = lepao_count + 1 WHERE uuid = ?',
- [uuid]
- )
- if (!r || r.affectedRows !== 1) {
- await conn.rollback()
- throw new Error('返还乐跑次数失败:数据库更新失败')
- }
- await insertLedgerRecord({
- executor: conn,
- userUuid: uuid,
- delta: 1,
- balanceBefore: beforeCount,
- balanceAfter: beforeCount + 1,
- bizType: 'run_refund',
- bizId: refundKey,
- remark: `${account || uuid}乐跑失败返还`
- })
- await conn.commit()
- } catch (error) {
- try { await conn.rollback() } catch (_) { }
- throw error
- } finally {
- if (conn?.connection && typeof conn.connection.release === 'function' && typeof conn?.release === 'function') {
- conn.release()
- }
- }
- this.logger.info(`${account || uuid}返还乐跑次数完成`)
- await Redis.set(refundKey, '1', { EX: 3600 })
- return true
- })
- this.register('lepao.getUserData', async (req, ctx) => {
- const account = req.account
- this.logger.info(`${account}开始获取用户数据`)
- const accountSql = `
- SELECT
- u.uuid,
- u.lepao_count,
- l.create_user,
- l.name,
- l.student_num,
- l.area,
- l.sex,
- l.state,
- l.token,
- l.uid,
- l.school_id,
- l.userAgent,
- l.deviceModel,
- l.notice_type,
- l.email,
- e.bot_account
- FROM
- lepao_account l
- LEFT JOIN
- users u
- ON
- l.create_user = u.uuid
- LEFT JOIN
- lepao_extra e
- ON
- l.student_num = e.student_num
- WHERE
- l.student_num = ?
- `
- const rows = await db.query(accountSql, [account])
- if (!rows || rows.length === 0) {
- this.logger.error(`${account}无法获取账号数据`)
- throw new Error('无法获取账号数据,请联系客服或稍后再试')
- }
- let userData = rows[0]
- if (!userData.create_user || !userData.uuid) {
- this.logger.warn(`${account}账号状态异常`)
- throw new Error('当前账号状态异常,请联系客服')
- }
- try {
- await assertLepaoJwBindingOrThrow(userData.create_user, userData.student_num)
- } catch (jwBindErr) {
- this.logger.warn(`${account}统一认证绑定校验失败: ${jwBindErr.message || jwBindErr}`)
- throw jwBindErr
- }
- if (userData.state !== 1) {
- this.logger.warn(`${account}登录状态异常 state=${userData.state}`)
- if (Number(userData.state) === 3) {
- throw new Error('统一认证登录失败,请在乐跑绑定中核对统一认证密码后重新保存,并完成教务账号激活')
- }
- throw new Error('乐跑账号登录已过期,请尝试使用登录器重新登录')
- }
- if (userData.lepao_count < 1) {
- this.logger.warn(`${account}乐跑次数不足`)
- throw new Error('用户乐跑次数不足,请购买乐跑次数后重试!')
- }
- if (!userData.userAgent)
- userData.userAgent = 'Mozilla/5.0 (Linux; Android 16; 2211133C Build/BP2A.250605.031.A3; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/138.0.7204.180 Mobile Safari/537.36 XWEB/1380347 MMWEBSDK/20250202 MMWEBID/1020 wxwork/5.0.6.66174 MicroMessenger/8.0.28.48(0x28001c30) MiniProgramEnv/android Luggage/3.0.2.95ef3f83 NetType/WIFI Language/zh_CN ABI/arm64'
- if (!userData.deviceModel)
- userData.deviceModel = '2211133C'
- return userData
- })
- this.register('lepao.getPath', async (req, ctx) => {
- const account = req.account
- this.logger.info(`${account}开始获取路径`)
- const accountSql = 'SELECT area, sex FROM lepao_account WHERE student_num = ?'
- const rows = await db.query(accountSql, [account])
- if (!rows || rows.length === 0) {
- this.logger.error(`${account}无法获取账号数据`)
- throw new Error('无法获取账号数据')
- }
- const { area, sex } = rows[0]
- let max = 4.00
- let min = 2.00
- if (sex === 2) {
- max = 2.00
- min = 1.60
- }
- this.logger.info(`${account}路径参数: area=${area ?? '随机'}, max_distance=${max}, min_distance=${min}`)
- let pathSql = 'SELECT * FROM path_data WHERE state = 1 AND distance < ? AND distance > ? '
- const pathParams = [max, min]
- if (area) {
- pathSql += ' AND run_zone_name = ?'
- pathParams.push(area)
- }
- pathSql += ' ORDER BY count ASC LIMIT 1'
- const paths = await db.query(pathSql, pathParams)
- if (!paths || paths.length === 0) {
- this.logger.error(`${account}未找到符合条件的路线`)
- const err = new Error('未找到符合条件的路线,请改变路径选择条件')
- err.code = 'PATH_SELECT_FAILED'
- err.retryable = true
- throw err
- }
- const randomPath = paths[0]
- const updateSql = 'UPDATE path_data SET count = count + 1 WHERE id = ?'
- await db.query(updateSql, [randomPath.id])
- this.logger.info(`${account}路径选中id=${randomPath.id},计数加1成功`)
- return { pathData: randomPath }
- })
- /* ---------------- 获取跑步记录 ---------------- */
- this.register('lepao.getRecord', async (req, ctx) => {
- const now = this.lepaoTimestamp()
- const raw = {
- uid: req.uid,
- token: req.token,
- school_id: req.school_id,
- term_id: 0,
- course_id: 0,
- class_id: 0,
- student_num: req.student_id,
- card_id: req.student_id,
- timestamp: now,
- version: 1,
- nonce: String(Math.floor(Math.random() * 900000 + 100000)),
- ostype: 5
- }
- raw.sign = dataSign(raw)
- return this.request(
- ctx.traceId,
- 'getRecord',
- this.api('/Run2/beforeRunV260'),
- raw,
- {
- 'User-Agent': req.userAgent,
- 'charset': 'utf-8',
- 'Referer': 'https://servicewechat.com/wxf94c4ddb63d87ede/32/page-frame.html',
- },
- ctx
- )
- })
- /* ---------------- 切换跑区 ---------------- */
- this.register('lepao.setZone', async (req, ctx) => {
- const runZoneMap = {
- '兰花湖校区跑区': 2,
- '主校区北跑区': 3,
- '主校区南跑区': 5,
- '重庆工商大学茶园校区': 6
- }
- const { pathData } = req
- const runZoneId = runZoneMap[pathData.run_zone_name]
- if (!runZoneId) throw new Error('跑区不存在')
- const raw = {
- uid: req.uid,
- token: req.token,
- school_id: req.school_id,
- term_id: 0,
- course_id: 0,
- class_id: 0,
- student_num: req.student_id,
- card_id: req.student_id,
- timestamp: this.lepaoTimestamp(),
- version: 1,
- nonce: String(Math.floor(Math.random() * 900000 + 100000)),
- ostype: 5,
- run_zone_id: String(runZoneId)
- }
- raw.sign = dataSign(raw)
- await this.request(
- ctx.traceId,
- 'setZone',
- this.api('/Run/setRunZone'),
- raw,
- {},
- ctx
- )
- return { run_zone_id: runZoneId }
- })
- /* ---------------- 获取 OSS STS ---------------- */
- this.register('lepao.getOssSts', async (req, ctx) => {
- const raw = {
- uid: req.uid,
- token: req.token,
- school_id: req.school_id,
- term_id: 0,
- course_id: 0,
- class_id: 0,
- student_num: req.student_id,
- card_id: req.student_id,
- timestamp: this.lepaoTimestamp(),
- version: 1,
- nonce: String(Math.floor(Math.random() * 900000 + 100000)),
- ostype: 5
- }
- raw.sign = dataSign(raw)
- const res = await this.request(
- ctx.traceId,
- 'getOssSts',
- this.api('/WpIndex/getOssSts'),
- raw,
- {},
- ctx
- )
- return res.data
- })
- /* ---------------- 上传 OSS 文件 ---------------- */
- this.register('lepao.uploadOssFile', async (req, ctx) => {
- const { pathData, newPathData, ossSts: sts } = req
- // 处理跑步路径
- const pathResult = dataEncrypt(JSON.stringify(newPathData))
- // 获取跑步规则参数
- const runRule = await this.handlers['lepao.getRecord'](req, ctx)
- const ruleData = runRule?.data
- if (!ruleData?.run_line_info?.point_list || !ruleData?.time_rule_arr?.length) {
- const err = new Error('获取打卡点规则失败')
- err.code = 'CHECKPOINT_FETCH_FAILED'
- err.retryable = true
- throw err
- }
- const check_points = ruleData.run_line_info.point_list
- let min_log_num = ruleData.time_rule_arr[0]?.min_log_num || 4
- const point_update_distance = parseFloat(ruleData.run_line_info.point_update_distance || 0) * 1000
- const log_max_distance = Number(ruleData.run_line_info.log_max_distance || 0)
- // 生成打卡点
- const point_data = selectCheckpoints(newPathData, check_points, min_log_num, point_update_distance, log_max_distance, req.run_end_time, pathData.time)
- if (!point_data) {
- this.logger.warn(`[RETRY] 打卡点数量不足,重新更换路径`)
- const err = new Error('打卡点数量不足')
- err.code = 'CHECKPOINT_INSUFFICIENT'
- err.retryable = true
- throw err
- }
- const now = new Date()
- const yyyy = now.getFullYear()
- const mm = String(now.getMonth() + 1).padStart(2, '0')
- const dd = String(now.getDate()).padStart(2, '0')
- const formattedToday = `${yyyy}-${mm}-${dd}`
- const boundary = String(Date.now())
- const timestamp = String(Date.now())
- const ossPath = `Public/Upload/file/run_record/${boundary.slice(-3)}/${formattedToday}/${timestamp}-${Math.floor(Math.random() * 150)}.txt`
- const client = new OSS({
- bucket: sts.bucket,
- region: sts.region || 'oss-cn-hangzhou',
- accessKeyId: sts.AccessKeyId,
- accessKeySecret: sts.AccessKeySecret,
- stsToken: sts.SecurityToken,
- secure: true
- })
- await client.put(ossPath, Buffer.from(pathResult, 'utf-8'))
- return { oss_path: ossPath, point_data: point_data }
- })
- this.register('lepao.uploadGyrOssFile', async (req, ctx) => {
- const { newPathData, ossSts: sts, record_id } = req
- // 生成加速度数据
- const gyrData = generateGyrFromPath(newPathData)
- if (!Array.isArray(gyrData) || gyrData.length === 0) {
- this.logger.error('生成加速度数据失败')
- return { status: 0, info: '生成加速度数据失败' }
- }
- const now = new Date()
- const yyyy = now.getFullYear()
- const mm = String(now.getMonth() + 1).padStart(2, '0')
- const dd = String(now.getDate()).padStart(2, '0')
- const formattedToday = `${yyyy}-${mm}-${dd}`
- const boundary = String(Date.now())
- const timestamp = String(Date.now())
- const ossPath = `Public/Upload/file/run_gyroscope/${boundary.slice(-3)}/${formattedToday}/${timestamp}-${Math.floor(Math.random() * 150)}.txt`
- const client = new OSS({
- bucket: sts.bucket,
- region: sts.region || 'oss-cn-hangzhou',
- accessKeyId: sts.AccessKeyId,
- accessKeySecret: sts.AccessKeySecret,
- stsToken: sts.SecurityToken,
- secure: true
- })
- await client.put(ossPath, Buffer.from(JSON.stringify(gyrData), 'utf-8'))
- const data = {
- uid: req.uid,
- token: req.token,
- school_id: req.school_id,
- term_id: 0,
- course_id: 0,
- class_id: 0,
- student_num: req.student_id,
- card_id: req.student_id,
- timestamp: this.lepaoTimestamp(),
- version: 1,
- nonce: String(Math.floor(Math.random() * 900000 + 100000)),
- ostype: 5,
- record_id: record_id,
- gyroscope_file: ossPath
- }
- data.sign = dataSign(data)
- return this.request(
- ctx.traceId,
- 'bindData',
- this.api('/Run2/gyroscope'),
- data,
- {},
- ctx
- )
- })
- /* ---------------- 提交跑步数据 ---------------- */
- this.register('lepao.bindData', async (req, ctx) => {
- const { pathData } = req
- const distance = Number(Number(pathData.distance || 0).toFixed(2))
- const stepData = generateCadence(distance, pathData.time)
- const stepInfo = JSON.stringify({ interval: 60, list: stepData.cadence_list })
- let points = req.point_data.map(({ address, jingwei, ...rest }) => rest)
- points = JSON.stringify(points)
- const data = {
- uid: req.uid,
- token: req.token,
- school_id: req.school_id,
- term_id: 1,
- course_id: 0,
- class_id: 0,
- student_num: req.student_id,
- card_id: req.student_id,
- timestamp: this.lepaoTimestamp(),
- version: 1,
- nonce: String(Math.floor(Math.random() * 900000 + 100000)),
- ostype: 5,
- game_id: String(req.run_zone_id || 0),
- start_time: req.run_end_time - Number(pathData.time),
- end_time: req.run_end_time,
- distance,
- record_img: "",
- log_data: points,
- file_img: "",
- is_running_area_valid: 1,
- mobileDeviceId: 1,
- mobileModel: req.deviceModel,
- step_info: stepInfo,
- step_num: stepData.total_steps,
- used_time: pathData.time,
- mobileOsVersion: 1,
- record_file: req.record_file
- }
- data.sign = dataSign(data)
- return this.request(
- ctx.traceId,
- 'bindData',
- this.api('/Run/stopRunV278'),
- data,
- {},
- ctx
- )
- })
- }
- /* ================= Worker核心 ================= */
- async start() {
- if (this.running) return
- this.running = true
- this.logger.info('Worker 启动中...')
- try {
- this.initHandlers()
- const channel = await mq.getChannel(this.channelName)
- await channel.prefetch(5)
- await assertRunforgeTaskIngress(channel, this.logger)
- await channel.assertQueue(this.resultQueue, {
- durable: true,
- arguments: {
- 'x-max-length': this.maxQueueLength
- }
- })
- await channel.assertQueue(this.deadQueue, {
- durable: true,
- arguments: {
- 'x-max-length': this.maxQueueLength
- }
- })
- await channel.consume(this.taskQueue, async (msg) => {
- if (!msg) return
- let content
- try {
- content = JSON.parse(msg.content.toString())
- } catch {
- return channel.ack(msg)
- }
- const { id, type, data, retry = 0 } = content
- const traceId = this.traceId()
- const handler = this.handlers[type]
- if (!handler) {
- this.log(traceId, 'ERROR', '未知任务', { type })
- return channel.ack(msg)
- }
- try {
- const result = await this.withTimeout(
- handler(data, { traceId, channel, taskId: id }),
- type
- )
- await this.sendResult(channel, {
- id,
- success: true,
- result
- })
- this.log(traceId, 'DONE', `任务完成 ${type}`)
- channel.ack(msg)
- } catch (err) {
- this.logErr(traceId, `任务失败 ${type}`, err)
- if (retry < this.maxRetry && this.isRetryableTaskError(err)) {
- // 重试
- await channel.sendToQueue(
- this.taskQueue,
- Buffer.from(JSON.stringify({
- ...content,
- retry: retry + 1
- })),
- { persistent: true }
- )
- this.log(traceId, 'RETRY', `重试第${retry + 1}次`)
- } else {
- // 死信
- await channel.sendToQueue(
- this.deadQueue,
- Buffer.from(JSON.stringify(content)),
- { persistent: true }
- )
- this.log(traceId, 'DEAD', '进入死信队列')
- }
- await this.sendResult(channel, {
- id,
- success: false,
- error: err.message
- })
- channel.ack(msg)
- }
- })
- this.logger.info('RunForge Worker 启动成功')
- } catch (err) {
- this.logger.error('RunForge Worker 启动失败: ' + err.stack)
- }
- }
- async sendResult(channel, data) {
- channel.sendToQueue(
- this.resultQueue,
- Buffer.from(JSON.stringify(data)),
- { persistent: true }
- )
- }
- async stop() {
- this.running = false
- await mq.close()
- this.logger.info('RunForge Worker 已停止')
- }
- }
- module.exports = Worker
|