Worker.js 51 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387
  1. const path = require('path')
  2. const axios = require('axios')
  3. const OSS = require('ali-oss')
  4. const mq = require('../../plugin/mq')
  5. const { mq: mqName } = require('../../plugin/mq/mqPrefix')
  6. const { assertRunforgeTaskIngress, TASK_QUEUE } = require('../../plugin/mq/runforgeTaskMq')
  7. const db = require('../../plugin/DataBase/db')
  8. const Redis = require('../../plugin/DataBase/Redis')
  9. const EmailTemplate = require('../../plugin/Email/emailTemplate')
  10. const { URLSearchParams } = require('url')
  11. const {
  12. getPathData,
  13. selectCheckpoints,
  14. generateCadence
  15. } = require('../../plugin/Lepao/Path')
  16. const {
  17. dataEncrypt,
  18. dataDecrypt,
  19. dataSign
  20. } = require('../../plugin/Lepao/Crypto')
  21. const generateGyrFromPath = require('../../plugin/Lepao/generateGyrFromPath')
  22. const { syncAccountInfo } = require('./syncAccountInfo')
  23. const { insertLedgerRecord } = require('./CountLedger')
  24. const Logger = require('../Logger')
  25. class Worker {
  26. constructor() {
  27. this.logger = new Logger(
  28. path.join(__dirname, '../logs/LepaoWorker.log'),
  29. 'INFO'
  30. )
  31. this.handlers = {}
  32. this.running = false
  33. this.baseUrl = 'https://lepao.ctbu.edu.cn/v3/api.php'
  34. this.taskQueue = TASK_QUEUE
  35. this.resultQueue = mqName('runforge_task_result_queue')
  36. this.deadQueue = mqName('runforge_task_dead_queue')
  37. this.noticeQueue = mqName('runforge_message_queue')
  38. this.channelName = 'lepao_worker'
  39. this.maxRetry = 3
  40. this.timeout = 15000
  41. this.maxQueueLength = 2000
  42. 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'
  43. // 调试模式:将 axios 请求走本地代理(例如 charles/fiddler)
  44. // 开启方式:设置环境变量 LEPAO_DEBUG_PROXY=1
  45. this.debugProxyEnabled = String(process.env.LEPAO_DEBUG_PROXY || '').trim() === '1'
  46. this.debugProxyHost = process.env.LEPAO_DEBUG_PROXY_HOST || '127.0.0.1'
  47. this.debugProxyPort = Number(process.env.LEPAO_DEBUG_PROXY_PORT || 9000)
  48. }
  49. /* ================= 工具 ================= */
  50. api(path) {
  51. return this.baseUrl + path
  52. }
  53. traceId() {
  54. return Date.now() + '_' + Math.random().toString(36).slice(2, 8)
  55. }
  56. sleep(ms) {
  57. return new Promise(r => setTimeout(r, ms))
  58. }
  59. isRunSuccess(bindResponse) {
  60. const payload = bindResponse?.data
  61. if (!bindResponse || bindResponse.status !== 1 || !payload) {
  62. return {
  63. ok: false,
  64. reason: bindResponse?.info || '系统繁忙,请联系客服或稍后再试'
  65. }
  66. }
  67. const failedReason = payload.record_failed_reason || ''
  68. if (failedReason === '' || failedReason === '自动确认有效') {
  69. return { ok: true, payload }
  70. }
  71. return {
  72. ok: false,
  73. reason: failedReason,
  74. payload
  75. }
  76. }
  77. extractApiErrorMessage(name, result) {
  78. if (!result) {
  79. this.logger.error(`${name} 接口无响应数据: ${this.safeStringify(result)}`)
  80. return `系统繁忙,请联系客服或稍后再试`
  81. }
  82. const candidates = [
  83. result.info,
  84. result.msg,
  85. result.message,
  86. result?.data?.info,
  87. result?.data?.msg,
  88. result?.data?.message,
  89. result?.data?.record_failed_reason
  90. ]
  91. const reason = candidates.find(v => typeof v === 'string' && v.trim() !== '')
  92. if (reason) {
  93. return reason
  94. }
  95. if (result.code !== undefined || result.status !== undefined) {
  96. this.logger.error(`${name} 接口返回异常: ${this.safeStringify(result)}`)
  97. return `系统繁忙,请联系客服或稍后再试`
  98. }
  99. return `系统繁忙,请联系客服或稍后再试`
  100. }
  101. async markLoginExpired(account) {
  102. if (!account) return
  103. try {
  104. const sql = 'UPDATE lepao_account SET state = 0 WHERE student_num = ?'
  105. await db.query(sql, [account])
  106. this.logger.warn(`${account} 登录状态已失效,已自动更新为未登录`)
  107. } catch (error) {
  108. this.logger.error(`更新账号登录状态失败:${error.stack || error}`)
  109. }
  110. }
  111. async writeSuccessRedis(account) {
  112. if (!account) return
  113. try {
  114. const now = new Date()
  115. const tomorrow = new Date().setHours(24, 0, 0, 0)
  116. const exp = Math.floor((tomorrow - now) / 1000)
  117. await Redis.set(`lepaoSuccess:${account}`, account, { EX: exp })
  118. } catch (error) {
  119. this.logger.error(`写入乐跑成功缓存失败: ${error.stack || error}`)
  120. }
  121. }
  122. async addLepaoRecord(uuid, account, result, pathId, pointData) {
  123. if (!uuid || !account || !result || !pathId) return
  124. try {
  125. const time = Date.now()
  126. const sql = 'INSERT INTO lepao_record (uuid, time, lepao_account, result, path_id, point_data, state) VALUES (?, ?, ?, ?, ?, ?, ?)'
  127. await db.query(sql, [uuid, time, account, result, pathId, JSON.stringify(pointData || []), 1])
  128. } catch (error) {
  129. this.logger.error(`写入乐跑记录失败: ${error.stack || error}`)
  130. }
  131. }
  132. async syncRunCount(req, ctx) {
  133. try {
  134. const sid = req?.student_id || req?.account
  135. if (
  136. req?.uid == null ||
  137. req?.token == null ||
  138. String(req.token).trim() === '' ||
  139. req?.school_id == null ||
  140. !sid
  141. ) {
  142. return { ok: false, reason: '缺少同步乐跑次数所需凭证' }
  143. }
  144. const recordData = await this.handlers['lepao.getRecord'](req, ctx)
  145. const data = recordData?.data
  146. if (!data) {
  147. return { ok: false, reason: 'getRecord 无有效 data' }
  148. }
  149. const term_num = Number(data.term_num ?? 30)
  150. const total_num = Number(data.total_num ?? 0)
  151. const sql = 'UPDATE lepao_account SET term_num = ?, total_num = ? WHERE student_num = ?'
  152. const rows = await db.query(sql, [term_num, total_num, req.account])
  153. if (!rows || rows.affectedRows !== 1) {
  154. this.logger.warn(`${req.account}更新乐跑次数失败`)
  155. return { ok: false, reason: '数据库更新 lepao_account 失败', term_num, total_num }
  156. }
  157. this.logger.info(`${req.account}更新乐跑次数成功 term_num=${term_num}, total_num=${total_num}`)
  158. return { ok: true, term_num, total_num }
  159. } catch (error) {
  160. this.logger.warn(`${req?.account || 'unknown'}同步乐跑次数失败: ${error.message || error}`)
  161. return { ok: false, reason: error.message || String(error) }
  162. }
  163. }
  164. lepaoTimestamp() {
  165. return Number((Date.now() / 1000).toFixed(3))
  166. }
  167. axiosProxyConfig() {
  168. if (!this.debugProxyEnabled) {
  169. return { proxy: false }
  170. }
  171. this.logger.info(`使用本地代理: ${this.debugProxyHost}:${this.debugProxyPort}`)
  172. return {
  173. proxy: {
  174. host: this.debugProxyHost,
  175. port: this.debugProxyPort,
  176. protocol: 'http'
  177. }
  178. }
  179. }
  180. async enqueueTask(channel, type, data, options = {}) {
  181. const payload = {
  182. id: options.id || this.traceId(),
  183. type,
  184. data,
  185. retry: options.retry ?? 0
  186. }
  187. await channel.sendToQueue(
  188. this.taskQueue,
  189. Buffer.from(JSON.stringify(payload)),
  190. { persistent: true, contentType: 'application/json' }
  191. )
  192. return payload.id
  193. }
  194. async withTimeout(promise, name) {
  195. return Promise.race([
  196. promise,
  197. new Promise((_, reject) =>
  198. setTimeout(() => reject(new Error(`${name} 超时`)), this.timeout)
  199. )
  200. ])
  201. }
  202. async retry(fn, name) {
  203. let lastErr
  204. for (let i = 0; i < this.maxRetry; i++) {
  205. try {
  206. return await fn()
  207. } catch (err) {
  208. lastErr = err
  209. if (!this.isRetryableTaskError(err)) {
  210. throw err
  211. }
  212. this.logger.warn(`[RETRY] ${name} 第${i + 1}次失败`)
  213. await this.sleep(1000 * (i + 1)) // 指数退避
  214. }
  215. }
  216. throw lastErr
  217. }
  218. isNetworkError(err) {
  219. if (!err) return false
  220. if (err.code && ['ECONNRESET', 'ECONNABORTED', 'ETIMEDOUT', 'ENOTFOUND', 'EAI_AGAIN'].includes(err.code)) {
  221. return true
  222. }
  223. if (err.isAxiosError && !err.response) return true
  224. const msg = (err.message || '').toLowerCase()
  225. return msg.includes('timeout') || msg.includes('network')
  226. }
  227. isRetryableTaskError(err) {
  228. if (!err) return false
  229. if (err.retryable === true) return true
  230. if (this.isNetworkError(err)) return true
  231. return ['PATH_SELECT_FAILED', 'CHECKPOINT_FETCH_FAILED', 'CHECKPOINT_INSUFFICIENT'].includes(err.code)
  232. }
  233. safeStringify(obj) {
  234. const seen = new WeakSet();
  235. return JSON.stringify(obj, (key, value) => {
  236. if (typeof value === 'object' && value !== null) {
  237. if (seen.has(value)) return '[Circular]';
  238. seen.add(value);
  239. }
  240. return value;
  241. })
  242. }
  243. log(traceId, type, msg, data) {
  244. this.logger.info(`[${traceId}] [${type}] ${msg} ${data ? this.safeStringify(data) : ''}`)
  245. }
  246. logErr(traceId, msg, err) {
  247. this.logger.error(`[${traceId}] ${msg} ${err.stack || err}`)
  248. }
  249. async request(traceId, name, url, raw, headers = {}) {
  250. return this.retry(async () => {
  251. this.log(traceId, 'REQ', name, raw)
  252. const mergedHeaders = {
  253. 'Content-Type': 'application/x-www-form-urlencoded',
  254. 'Accept': '*/*',
  255. 'Accept-Language': 'zh-CN,zh-Hans;q=0.9',
  256. 'Accept-Encoding': 'gzip, deflate, br',
  257. 'Referer': 'https://servicewechat.com/wxf94c4ddb63d87ede/32/page-frame.html',
  258. ...headers
  259. }
  260. if (!mergedHeaders['User-Agent']) {
  261. mergedHeaders['User-Agent'] = this.defaultUserAgent
  262. }
  263. const form = new URLSearchParams()
  264. form.append('ostype', '5')
  265. form.append('data', dataEncrypt(JSON.stringify(raw)))
  266. const res = await this.withTimeout(
  267. axios.post(
  268. url,
  269. form,
  270. {
  271. headers: mergedHeaders,
  272. ...this.axiosProxyConfig()
  273. }
  274. ),
  275. name
  276. )
  277. let result = res.data
  278. if (result?.data && result?.is_encrypt === 1) {
  279. result.data = JSON.parse(dataDecrypt(result.data))
  280. }
  281. this.log(traceId, 'RES', name, result)
  282. // 除 bindData 外,其余调用若接口已明确返回失败,直接抛出该失败原因
  283. // bindData 需要保留完整响应由 isRunSuccess 统一判定。
  284. if (name !== 'bindData') {
  285. const hasCode = result && Object.prototype.hasOwnProperty.call(result, 'code')
  286. const hasStatus = result && Object.prototype.hasOwnProperty.call(result, 'status')
  287. const failedByCode = hasCode && Number(result.code) !== 1 && Number(result.code) !== 200
  288. const failedByStatus = hasStatus && Number(result.status) !== 1
  289. if (failedByCode || failedByStatus) {
  290. const message = this.extractApiErrorMessage(name, result)
  291. const err = new Error(message)
  292. // 学习 Lepao.js:若明确提示重新登录,自动标记账号失效
  293. if (message.includes('重新登录')) {
  294. await this.markLoginExpired(raw?.student_num)
  295. }
  296. // 接口已返回业务错误,禁止重试
  297. err.retryable = false
  298. throw err
  299. }
  300. }
  301. return result
  302. }, name)
  303. }
  304. /**
  305. * 累计完成次数 >= 跑友目标(且目标>0)时:关闭 auto_run,并发送乐跑目标完成邮件 / Bot 通知
  306. */
  307. async handleLepaoTargetComplete(account, user, totalNum, traceId) {
  308. const target = Number(user?.target_count) || 0
  309. const total = Number(totalNum) || 0
  310. if (target <= 0 || total < target) return
  311. try {
  312. const up = await db.query(
  313. 'UPDATE lepao_account SET auto_run = 0 WHERE student_num = ? AND auto_run = 1',
  314. [account]
  315. )
  316. if (up?.affectedRows !== 1) {
  317. return
  318. }
  319. this.logger.info(
  320. `${account} 已达目标次数(${total}/${target}),关闭自动乐跑`
  321. )
  322. } catch (e) {
  323. this.logger.error(`关闭自动乐跑失败 ${account}: ${e.message || e}`)
  324. return
  325. }
  326. const noticeType = user.notice_type || 'none'
  327. const overPayload = {
  328. type: 'lepao_over',
  329. umo: user.bot_umo,
  330. name: user.name,
  331. account,
  332. total_num: total,
  333. target_count: target,
  334. traceId
  335. }
  336. if (noticeType === 'email' && user.email) {
  337. try {
  338. await EmailTemplate.lepaoOver(user.email, {
  339. name: user.name,
  340. account
  341. })
  342. } catch (e) {
  343. this.logger.error(`lepaoOver 邮件发送失败: ${e.message || e}`)
  344. }
  345. }
  346. if (noticeType === 'bot' && user.bot_umo) {
  347. try {
  348. const ch = await mq.getChannel(this.noticeQueue)
  349. await ch.assertQueue(this.noticeQueue, { durable: true })
  350. ch.sendToQueue(
  351. this.noticeQueue,
  352. Buffer.from(JSON.stringify(overPayload)),
  353. {
  354. persistent: true,
  355. contentType: 'application/json'
  356. }
  357. )
  358. } catch (e) {
  359. this.logger.error(`lepao_over Bot 通知失败: ${e.message || e}`)
  360. }
  361. }
  362. }
  363. register(type, handler) {
  364. this.handlers[type] = handler
  365. this.logger.info(`注册任务: ${type}`)
  366. }
  367. /* ================= 业务 ================= */
  368. initHandlers() {
  369. this.register('lepao.syncAccountInfo', async (req) => {
  370. const studentNum = req?.student_num
  371. if (!studentNum) {
  372. throw new Error('同步乐跑账号失败:缺少 student_num')
  373. }
  374. const syncResult = await syncAccountInfo({
  375. studentNum,
  376. logger: this.logger
  377. })
  378. if (!syncResult.ok) {
  379. const err = new Error(syncResult.msg || '同步乐跑账号失败')
  380. err.retryable = false
  381. throw err
  382. }
  383. return syncResult.data
  384. })
  385. /* ---------------- 开始乐跑 ---------------- */
  386. this.register('lepao.startRun', async (req, ctx) => {
  387. const traceId = ctx.traceId
  388. const maxPathRetry = 20 // 自动获取路径失败最大重试次数
  389. let pathRetry = 0
  390. let pointData = null
  391. let pathData = null
  392. let newPathData = null
  393. let ossPath = null
  394. let ossSts = null
  395. let userData = null
  396. let pathId = null
  397. let runZoneId = 0
  398. let bindRes = null
  399. try {
  400. // 检查redis是否存在当天乐跑成功记录
  401. const isSuccess = await Redis.get(`lepaoSuccess:${req.account}`)
  402. if (isSuccess)
  403. throw new Error('该账号当天已乐跑成功!请勿重复乐跑')
  404. userData = await this.handlers['lepao.getUserData'](req, ctx)
  405. // 立刻合并账号凭证,保证后续任意 throw 时 finally 里 syncRunCount 不会用空 token 调 getRecord
  406. req = {
  407. ...req,
  408. ...userData,
  409. student_id: req.account
  410. }
  411. // 进入乐跑进程后写入进行中缓存
  412. const progressKey = `lepaoProgress:${req.account}`
  413. const inProgress = await Redis.get(progressKey)
  414. if (inProgress) {
  415. throw new Error('该账号已进入乐跑任务队列,请等待乐跑完成后再进行乐跑操作')
  416. }
  417. await Redis.set(progressKey, req.account, { EX: 1800 })
  418. ossSts = await this.handlers['lepao.getOssSts'](req, ctx)
  419. if (!ossSts?.bucket || !ossSts?.AccessKeyId || !ossSts?.AccessKeySecret || !ossSts?.SecurityToken) {
  420. throw new Error('获取 OSS 凭证失败,请联系客服或稍后再试')
  421. }
  422. req = {
  423. ...req,
  424. ossSts
  425. }
  426. // 晚上10点后提前
  427. let run_end_time = Math.floor(Date.now() / 1000) - 300 // 提前5分钟
  428. let hour = new Date().getHours()
  429. if (hour < 7)
  430. throw new Error('当前不在有效乐跑时间范围内。RunForge支持乐跑时间段为7:00~24:00')
  431. if (hour >= 22) {
  432. this.logger.info(`${req.account}当前时间为${hour}点,调整run_end_time提前5小时`)
  433. run_end_time -= 18000
  434. }
  435. req = {
  436. ...req,
  437. run_end_time
  438. }
  439. // 1.5️⃣ 乐跑开始前扣减次数(失败会返还,且有幂等保护)
  440. await this.handlers['lepao.consumeCount']({
  441. account: req.account,
  442. uuid: userData?.create_user
  443. }, ctx)
  444. while (pathRetry < maxPathRetry) {
  445. try {
  446. // 2️⃣ 获取路径(仅路径选择失败时重试)
  447. const pathRes = await this.handlers['lepao.getPath'](req, ctx)
  448. pathData = pathRes.pathData
  449. pathId = pathData?.id || null
  450. newPathData = getPathData(pathData.data, req.run_end_time, pathData.time)
  451. // 3️⃣ 切换跑区
  452. const zoneRes = await this.handlers['lepao.setZone']({ ...req, pathData }, ctx)
  453. runZoneId = zoneRes?.run_zone_id || 0
  454. // 4️⃣ 上传 OSS 文件、生成打卡点
  455. const uploadRes = await this.handlers['lepao.uploadOssFile']({ ...req, pathData, newPathData }, ctx)
  456. ossPath = uploadRes.oss_path
  457. pointData = uploadRes.point_data
  458. if (!pointData) {
  459. pathRetry++
  460. this.logger.warn(`[${traceId}] 打卡点不满足要求,重新获取路径 第${pathRetry}次`)
  461. continue
  462. }
  463. // 打卡点符合要求,跳出循环
  464. break
  465. } catch (err) {
  466. if (!this.isRetryableTaskError(err)) {
  467. throw err
  468. }
  469. this.logger.warn(`[${traceId}] 可重试错误,重新获取路径 第${pathRetry + 1}次,原因:${err.message}`)
  470. pathRetry++
  471. await this.sleep(1000 * pathRetry)
  472. }
  473. }
  474. if (!pointData) {
  475. throw new Error('打卡点获取失败,乐跑任务终止')
  476. }
  477. // 5️⃣ 提交跑步数据
  478. bindRes = await this.handlers['lepao.bindData']({
  479. ...req,
  480. pathData,
  481. run_zone_id: runZoneId,
  482. record_file: ossPath,
  483. point_data: pointData
  484. }, ctx)
  485. // 绑定接口有返回即入库
  486. if (bindRes && bindRes.data) {
  487. await this.addLepaoRecord(userData?.create_user, req.account, bindRes.data, pathId, pointData)
  488. }
  489. const runResult = this.isRunSuccess(bindRes)
  490. if (runResult.ok || runResult.reason === '当天关联成绩次数已达到上限') {
  491. await this.writeSuccessRedis(req.account)
  492. }
  493. if (!runResult.ok) {
  494. throw new Error(runResult.reason)
  495. }
  496. if (bindRes && bindRes.data && bindRes.data.record_id) {
  497. const gyrRes = await this.handlers['lepao.uploadGyrOssFile']({ ...req, newPathData, record_id: bindRes.data.record_id }, ctx)
  498. if (gyrRes?.status === 1) {
  499. this.logger.info(`${req.account}上传加速度数据成功!`)
  500. } else {
  501. this.logger.error(`${req.account}上传加速度数据失败!原因:${gyrRes.info || '未知错误'}`)
  502. }
  503. }
  504. // 同步乐跑次数(通知里要带 total_num / term_num,与 getRecord 一致)
  505. const syncResult = await this.syncRunCount(req, ctx)
  506. if (!syncResult?.ok) {
  507. this.logger.error(
  508. `[${traceId}] 同步乐跑次数失败:${syncResult?.reason || 'unknown'}`
  509. )
  510. }
  511. // 6️⃣ 发送通知(把同步后的学期次数、累计完成次数传给 Bot / 邮件)
  512. if (ctx.channel) {
  513. await this.enqueueTask(
  514. ctx.channel,
  515. 'lepao.sendNotice',
  516. {
  517. account: req.account,
  518. success: true,
  519. data: runResult.payload,
  520. traceId,
  521. total_num: syncResult?.ok ? syncResult.total_num : undefined
  522. },
  523. { id: `${traceId}:notice:success` }
  524. )
  525. }
  526. return { traceId, ossPath, pointData, bindRes }
  527. } catch (err) {
  528. this.logger.error(`[${traceId}] 乐跑流程失败:`, err)
  529. // 若已扣减次数,则失败时返还(幂等)
  530. try {
  531. await this.handlers['lepao.refundCount']({
  532. account: req.account,
  533. uuid: userData?.create_user
  534. }, ctx)
  535. } catch (e) {
  536. this.logger.error(`[${traceId}] 返还乐跑次数失败:${e.stack || e}`)
  537. }
  538. if (ctx.channel) {
  539. await this.enqueueTask(ctx.channel, 'lepao.sendNotice', {
  540. account: req.account,
  541. success: false,
  542. reason: err.message || '未知错误',
  543. traceId
  544. }, { id: `${traceId}:notice:fail` })
  545. }
  546. throw err
  547. } finally {
  548. await Redis.del(`lepaoProgress:${req.account}`)
  549. }
  550. })
  551. /* ---------------- 发送通知(独立 MQ 任务) ---------------- */
  552. this.register('lepao.sendNotice', async (req, ctx) => {
  553. const { account, success, data, reason, traceId, total_num: totalNumArg } = req || {}
  554. if (!account) {
  555. throw new Error('发送通知失败:缺少 account')
  556. }
  557. const emailSql = `
  558. SELECT
  559. a.name,
  560. a.email,
  561. a.target_count,
  562. a.notice_type,
  563. e.bot_umo
  564. FROM
  565. lepao_account a
  566. LEFT JOIN
  567. lepao_extra e
  568. ON
  569. a.student_num = e.student_num
  570. WHERE
  571. a.student_num = ?
  572. `
  573. const rows = await db.query(emailSql, [account])
  574. if (!rows || rows.length === 0) {
  575. throw new Error('发送通知失败:未找到用户通知配置')
  576. }
  577. const user = rows[0]
  578. const noticeType = user.notice_type || 'none'
  579. let totalForNotice = totalNumArg
  580. if (
  581. success &&
  582. (totalForNotice === undefined || totalForNotice === null)
  583. ) {
  584. const accRows = await db.query(
  585. 'SELECT total_num FROM lepao_account WHERE student_num = ?',
  586. [account]
  587. )
  588. if (accRows && accRows[0]) {
  589. totalForNotice = accRows[0].total_num
  590. }
  591. }
  592. if (totalForNotice === undefined || totalForNotice === null) {
  593. totalForNotice = 0
  594. }
  595. totalForNotice = Number(totalForNotice)
  596. const targetCount = Number(user.target_count) || 0
  597. const payload = success ? {
  598. ...(data && typeof data === 'object' ? data : {}),
  599. type: 'lepao_success',
  600. umo: user.bot_umo,
  601. total_num: totalForNotice,
  602. target_count: targetCount,
  603. name: user.name,
  604. account,
  605. traceId
  606. } : {
  607. type: 'lepao_fail',
  608. umo: user.bot_umo,
  609. name: user.name,
  610. account,
  611. reason,
  612. traceId
  613. }
  614. const afterSuccessNotify = async () => {
  615. if (success) {
  616. await this.handleLepaoTargetComplete(account, user, totalForNotice, traceId)
  617. }
  618. }
  619. if (noticeType === 'bot' && user.bot_umo) {
  620. const ch = await mq.getChannel(this.noticeQueue)
  621. await ch.assertQueue(this.noticeQueue, { durable: true })
  622. ch.sendToQueue(
  623. this.noticeQueue,
  624. Buffer.from(JSON.stringify(payload)),
  625. {
  626. persistent: true,
  627. contentType: 'application/json'
  628. }
  629. )
  630. await afterSuccessNotify()
  631. return { delivered: true, via: 'bot' }
  632. }
  633. if (noticeType === 'email' && user.email) {
  634. if (success) {
  635. await EmailTemplate.lepaoSuccess(user.email, payload)
  636. await afterSuccessNotify()
  637. return { delivered: true, via: 'email' }
  638. }
  639. await EmailTemplate.lepaoFail(user.email, {
  640. name: user.name,
  641. account,
  642. reason: reason || '系统繁忙,请联系客服或稍后再试',
  643. traceId
  644. })
  645. return { delivered: true, via: 'email' }
  646. }
  647. await afterSuccessNotify()
  648. return { delivered: false, via: 'none' }
  649. })
  650. /* ---------------- 扣减次数 ---------------- */
  651. this.register('lepao.consumeCount', async (req, ctx) => {
  652. const account = req?.account
  653. const uuid = req?.uuid
  654. if (!uuid) {
  655. throw new Error('扣减乐跑次数失败:缺少 uuid')
  656. }
  657. // 幂等:同一 taskId 只扣一次
  658. const consumeKey = `lepao:consume:${ctx?.taskId || ctx?.traceId || account || uuid}`
  659. const existed = await Redis.get(consumeKey)
  660. if (existed) {
  661. return true
  662. }
  663. this.logger.info(`${account || uuid}开始扣减乐跑次数`)
  664. const conn = await db.connect()
  665. try {
  666. await conn.beginTransaction()
  667. const [userRows] = await conn.execute(
  668. 'SELECT lepao_count FROM users WHERE uuid = ? FOR UPDATE',
  669. [uuid]
  670. )
  671. if (!userRows || userRows.length !== 1) {
  672. await conn.rollback()
  673. throw new Error('扣减乐跑次数失败:用户不存在')
  674. }
  675. const beforeCount = Number(userRows[0].lepao_count || 0)
  676. if (beforeCount < 1) {
  677. await conn.rollback()
  678. throw new Error('用户乐跑次数不足,请购买乐跑次数后重试!')
  679. }
  680. const [r] = await conn.execute(
  681. 'UPDATE users SET lepao_count = lepao_count - 1 WHERE uuid = ?',
  682. [uuid]
  683. )
  684. if (!r || r.affectedRows !== 1) {
  685. await conn.rollback()
  686. throw new Error('扣减乐跑次数失败:数据库更新失败')
  687. }
  688. await insertLedgerRecord({
  689. executor: conn,
  690. userUuid: uuid,
  691. delta: -1,
  692. balanceBefore: beforeCount,
  693. balanceAfter: beforeCount - 1,
  694. bizType: 'run_consume',
  695. bizId: consumeKey,
  696. remark: `${account || uuid}乐跑扣除`
  697. })
  698. await conn.commit()
  699. } catch (error) {
  700. try { await conn.rollback() } catch (_) { }
  701. throw error
  702. } finally {
  703. if (conn?.connection && typeof conn.connection.release === 'function' && typeof conn?.release === 'function') {
  704. conn.release()
  705. }
  706. }
  707. this.logger.info(`${account || uuid}扣减乐跑次数完成`)
  708. await Redis.set(consumeKey, '1', { EX: 3600 })
  709. return true
  710. })
  711. /* ---------------- 返还次数(失败时执行) ---------------- */
  712. this.register('lepao.refundCount', async (req, ctx) => {
  713. const account = req?.account
  714. const uuid = req?.uuid
  715. if (!uuid) {
  716. return true
  717. }
  718. const baseKey = `${ctx?.taskId || ctx?.traceId || account || uuid}`
  719. const consumeKey = `lepao:consume:${baseKey}`
  720. const refundKey = `lepao:refund:${baseKey}`
  721. const consumed = await Redis.get(consumeKey)
  722. if (!consumed) {
  723. return true
  724. }
  725. const refunded = await Redis.get(refundKey)
  726. if (refunded) {
  727. return true
  728. }
  729. this.logger.info(`${account || uuid}开始返还乐跑次数`)
  730. const conn = await db.connect()
  731. try {
  732. await conn.beginTransaction()
  733. const [userRows] = await conn.execute(
  734. 'SELECT lepao_count FROM users WHERE uuid = ? FOR UPDATE',
  735. [uuid]
  736. )
  737. if (!userRows || userRows.length !== 1) {
  738. await conn.rollback()
  739. throw new Error('返还乐跑次数失败:用户不存在')
  740. }
  741. const beforeCount = Number(userRows[0].lepao_count || 0)
  742. const [r] = await conn.execute(
  743. 'UPDATE users SET lepao_count = lepao_count + 1 WHERE uuid = ?',
  744. [uuid]
  745. )
  746. if (!r || r.affectedRows !== 1) {
  747. await conn.rollback()
  748. throw new Error('返还乐跑次数失败:数据库更新失败')
  749. }
  750. await insertLedgerRecord({
  751. executor: conn,
  752. userUuid: uuid,
  753. delta: 1,
  754. balanceBefore: beforeCount,
  755. balanceAfter: beforeCount + 1,
  756. bizType: 'run_refund',
  757. bizId: refundKey,
  758. remark: `${account || uuid}乐跑失败返还`
  759. })
  760. await conn.commit()
  761. } catch (error) {
  762. try { await conn.rollback() } catch (_) { }
  763. throw error
  764. } finally {
  765. if (conn?.connection && typeof conn.connection.release === 'function' && typeof conn?.release === 'function') {
  766. conn.release()
  767. }
  768. }
  769. this.logger.info(`${account || uuid}返还乐跑次数完成`)
  770. await Redis.set(refundKey, '1', { EX: 3600 })
  771. return true
  772. })
  773. this.register('lepao.getUserData', async (req, ctx) => {
  774. const account = req.account
  775. this.logger.info(`${account}开始获取用户数据`)
  776. const accountSql = `
  777. SELECT
  778. u.uuid,
  779. u.lepao_count,
  780. l.create_user,
  781. l.name,
  782. l.student_num,
  783. l.area,
  784. l.sex,
  785. l.state,
  786. l.token,
  787. l.uid,
  788. l.school_id,
  789. l.userAgent,
  790. l.deviceModel,
  791. l.notice_type,
  792. l.email,
  793. e.bot_account
  794. FROM
  795. lepao_account l
  796. LEFT JOIN
  797. users u
  798. ON
  799. l.create_user = u.uuid
  800. LEFT JOIN
  801. lepao_extra e
  802. ON
  803. l.student_num = e.student_num
  804. WHERE
  805. l.student_num = ?
  806. `
  807. const rows = await db.query(accountSql, [account])
  808. if (!rows || rows.length === 0) {
  809. this.logger.error(`${account}无法获取账号数据`)
  810. throw new Error('无法获取账号数据,请联系客服或稍后再试')
  811. }
  812. let userData = rows[0]
  813. if (!userData.create_user || !userData.uuid) {
  814. this.logger.warn(`${account}账号状态异常`)
  815. throw new Error('当前账号状态异常,请联系客服')
  816. }
  817. if (userData.state !== 1) {
  818. this.logger.warn(`${account}登录状态异常 state=${userData.state}`)
  819. throw new Error('乐跑账号登录已过期,请尝试使用登录器重新登录')
  820. }
  821. if (userData.lepao_count < 1) {
  822. this.logger.warn(`${account}乐跑次数不足`)
  823. throw new Error('用户乐跑次数不足,请购买乐跑次数后重试!')
  824. }
  825. if (!userData.userAgent)
  826. 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'
  827. if (!userData.deviceModel)
  828. userData.deviceModel = '2211133C'
  829. return userData
  830. })
  831. this.register('lepao.getPath', async (req, ctx) => {
  832. const account = req.account
  833. this.logger.info(`${account}开始获取路径`)
  834. const accountSql = 'SELECT area, sex FROM lepao_account WHERE student_num = ?'
  835. const rows = await db.query(accountSql, [account])
  836. if (!rows || rows.length === 0) {
  837. this.logger.error(`${account}无法获取账号数据`)
  838. throw new Error('无法获取账号数据')
  839. }
  840. const { area, sex } = rows[0]
  841. let max = 4.00
  842. let min = 2.00
  843. if (sex === 2) {
  844. max = 2.00
  845. min = 1.60
  846. }
  847. this.logger.info(`${account}路径参数: area=${area ?? '随机'}, max_distance=${max}, min_distance=${min}`)
  848. let pathSql = 'SELECT * FROM path_data WHERE state = 1 AND distance < ? AND distance > ? '
  849. const pathParams = [max, min]
  850. if (area) {
  851. pathSql += ' AND run_zone_name = ?'
  852. pathParams.push(area)
  853. }
  854. pathSql += ' ORDER BY count ASC LIMIT 1'
  855. const paths = await db.query(pathSql, pathParams)
  856. if (!paths || paths.length === 0) {
  857. this.logger.error(`${account}未找到符合条件的路线`)
  858. const err = new Error('未找到符合条件的路线,请改变路径选择条件')
  859. err.code = 'PATH_SELECT_FAILED'
  860. err.retryable = true
  861. throw err
  862. }
  863. const randomPath = paths[0]
  864. const updateSql = 'UPDATE path_data SET count = count + 1 WHERE id = ?'
  865. await db.query(updateSql, [randomPath.id])
  866. this.logger.info(`${account}路径选中id=${randomPath.id},计数加1成功`)
  867. return { pathData: randomPath }
  868. })
  869. /* ---------------- 获取跑步记录 ---------------- */
  870. this.register('lepao.getRecord', async (req, ctx) => {
  871. const now = this.lepaoTimestamp()
  872. const raw = {
  873. uid: req.uid,
  874. token: req.token,
  875. school_id: req.school_id,
  876. term_id: 0,
  877. course_id: 0,
  878. class_id: 0,
  879. student_num: req.student_id,
  880. card_id: req.student_id,
  881. timestamp: now,
  882. version: 1,
  883. nonce: String(Math.floor(Math.random() * 900000 + 100000)),
  884. ostype: 5
  885. }
  886. raw.sign = dataSign(raw)
  887. return this.request(
  888. ctx.traceId,
  889. 'getRecord',
  890. this.api('/Run2/beforeRunV260'),
  891. raw,
  892. {
  893. 'User-Agent': req.userAgent,
  894. 'charset': 'utf-8',
  895. 'Referer': 'https://servicewechat.com/wxf94c4ddb63d87ede/32/page-frame.html',
  896. }
  897. )
  898. })
  899. /* ---------------- 切换跑区 ---------------- */
  900. this.register('lepao.setZone', async (req, ctx) => {
  901. const runZoneMap = {
  902. '兰花湖校区跑区': 2,
  903. '主校区北跑区': 3,
  904. '主校区南跑区': 5,
  905. '重庆工商大学茶园校区': 6
  906. }
  907. const { pathData } = req
  908. const runZoneId = runZoneMap[pathData.run_zone_name]
  909. if (!runZoneId) throw new Error('跑区不存在')
  910. const raw = {
  911. uid: req.uid,
  912. token: req.token,
  913. school_id: req.school_id,
  914. term_id: 0,
  915. course_id: 0,
  916. class_id: 0,
  917. student_num: req.student_id,
  918. card_id: req.student_id,
  919. timestamp: this.lepaoTimestamp(),
  920. version: 1,
  921. nonce: String(Math.floor(Math.random() * 900000 + 100000)),
  922. ostype: 5,
  923. run_zone_id: String(runZoneId)
  924. }
  925. raw.sign = dataSign(raw)
  926. await this.request(
  927. ctx.traceId,
  928. 'setZone',
  929. this.api('/Run/setRunZone'),
  930. raw
  931. )
  932. return { run_zone_id: runZoneId }
  933. })
  934. /* ---------------- 获取 OSS STS ---------------- */
  935. this.register('lepao.getOssSts', async (req, ctx) => {
  936. const raw = {
  937. uid: req.uid,
  938. token: req.token,
  939. school_id: req.school_id,
  940. term_id: 0,
  941. course_id: 0,
  942. class_id: 0,
  943. student_num: req.student_id,
  944. card_id: req.student_id,
  945. timestamp: this.lepaoTimestamp(),
  946. version: 1,
  947. nonce: String(Math.floor(Math.random() * 900000 + 100000)),
  948. ostype: 5
  949. }
  950. raw.sign = dataSign(raw)
  951. const res = await this.request(
  952. ctx.traceId,
  953. 'getOssSts',
  954. this.api('/WpIndex/getOssSts'),
  955. raw
  956. )
  957. return res.data
  958. })
  959. /* ---------------- 上传 OSS 文件 ---------------- */
  960. this.register('lepao.uploadOssFile', async (req, ctx) => {
  961. const { pathData, newPathData, ossSts: sts } = req
  962. // 处理跑步路径
  963. const pathResult = dataEncrypt(JSON.stringify(newPathData))
  964. // 获取跑步规则参数
  965. const runRule = await this.handlers['lepao.getRecord'](req, ctx)
  966. const ruleData = runRule?.data
  967. if (!ruleData?.run_line_info?.point_list || !ruleData?.time_rule_arr?.length) {
  968. const err = new Error('获取打卡点规则失败')
  969. err.code = 'CHECKPOINT_FETCH_FAILED'
  970. err.retryable = true
  971. throw err
  972. }
  973. const check_points = ruleData.run_line_info.point_list
  974. let min_log_num = ruleData.time_rule_arr[0]?.min_log_num || 4
  975. const point_update_distance = parseFloat(ruleData.run_line_info.point_update_distance || 0) * 1000
  976. const log_max_distance = Number(ruleData.run_line_info.log_max_distance || 0)
  977. // 生成打卡点
  978. const point_data = selectCheckpoints(newPathData, check_points, min_log_num, point_update_distance, log_max_distance, req.run_end_time, pathData.time)
  979. if (!point_data) {
  980. this.logger.warn(`[RETRY] 打卡点数量不足,重新更换路径`)
  981. const err = new Error('打卡点数量不足')
  982. err.code = 'CHECKPOINT_INSUFFICIENT'
  983. err.retryable = true
  984. throw err
  985. }
  986. const now = new Date()
  987. const yyyy = now.getFullYear()
  988. const mm = String(now.getMonth() + 1).padStart(2, '0')
  989. const dd = String(now.getDate()).padStart(2, '0')
  990. const formattedToday = `${yyyy}-${mm}-${dd}`
  991. const boundary = String(Date.now())
  992. const timestamp = String(Date.now())
  993. const ossPath = `Public/Upload/file/run_record/${boundary.slice(-3)}/${formattedToday}/${timestamp}-${Math.floor(Math.random() * 150)}.txt`
  994. const client = new OSS({
  995. bucket: sts.bucket,
  996. region: sts.region || 'oss-cn-hangzhou',
  997. accessKeyId: sts.AccessKeyId,
  998. accessKeySecret: sts.AccessKeySecret,
  999. stsToken: sts.SecurityToken,
  1000. secure: true
  1001. })
  1002. await client.put(ossPath, Buffer.from(pathResult, 'utf-8'))
  1003. return { oss_path: ossPath, point_data: point_data }
  1004. })
  1005. this.register('lepao.uploadGyrOssFile', async (req, ctx) => {
  1006. const { newPathData, ossSts: sts, record_id } = req
  1007. // 生成加速度数据
  1008. const gyrData = generateGyrFromPath(newPathData)
  1009. if (!Array.isArray(gyrData) || gyrData.length === 0) {
  1010. this.logger.error('生成加速度数据失败')
  1011. return { status: 0, info: '生成加速度数据失败' }
  1012. }
  1013. const now = new Date()
  1014. const yyyy = now.getFullYear()
  1015. const mm = String(now.getMonth() + 1).padStart(2, '0')
  1016. const dd = String(now.getDate()).padStart(2, '0')
  1017. const formattedToday = `${yyyy}-${mm}-${dd}`
  1018. const boundary = String(Date.now())
  1019. const timestamp = String(Date.now())
  1020. const ossPath = `Public/Upload/file/run_gyroscope/${boundary.slice(-3)}/${formattedToday}/${timestamp}-${Math.floor(Math.random() * 150)}.txt`
  1021. const client = new OSS({
  1022. bucket: sts.bucket,
  1023. region: sts.region || 'oss-cn-hangzhou',
  1024. accessKeyId: sts.AccessKeyId,
  1025. accessKeySecret: sts.AccessKeySecret,
  1026. stsToken: sts.SecurityToken,
  1027. secure: true
  1028. })
  1029. await client.put(ossPath, Buffer.from(JSON.stringify(gyrData), 'utf-8'))
  1030. const data = {
  1031. uid: req.uid,
  1032. token: req.token,
  1033. school_id: req.school_id,
  1034. term_id: 0,
  1035. course_id: 0,
  1036. class_id: 0,
  1037. student_num: req.student_id,
  1038. card_id: req.student_id,
  1039. timestamp: this.lepaoTimestamp(),
  1040. version: 1,
  1041. nonce: String(Math.floor(Math.random() * 900000 + 100000)),
  1042. ostype: 5,
  1043. record_id: record_id,
  1044. gyroscope_file: ossPath
  1045. }
  1046. data.sign = dataSign(data)
  1047. return this.request(
  1048. ctx.traceId,
  1049. 'bindData',
  1050. this.api('/Run2/gyroscope'),
  1051. data
  1052. )
  1053. })
  1054. /* ---------------- 提交跑步数据 ---------------- */
  1055. this.register('lepao.bindData', async (req, ctx) => {
  1056. const { pathData } = req
  1057. const distance = Number(Number(pathData.distance || 0).toFixed(2))
  1058. const stepData = generateCadence(distance, pathData.time)
  1059. const stepInfo = JSON.stringify({ interval: 60, list: stepData.cadence_list })
  1060. let points = req.point_data.map(({ address, jingwei, ...rest }) => rest)
  1061. points = JSON.stringify(points)
  1062. const data = {
  1063. uid: req.uid,
  1064. token: req.token,
  1065. school_id: req.school_id,
  1066. term_id: 1,
  1067. course_id: 0,
  1068. class_id: 0,
  1069. student_num: req.student_id,
  1070. card_id: req.student_id,
  1071. timestamp: this.lepaoTimestamp(),
  1072. version: 1,
  1073. nonce: String(Math.floor(Math.random() * 900000 + 100000)),
  1074. ostype: 5,
  1075. game_id: String(req.run_zone_id || 0),
  1076. start_time: req.run_end_time - Number(pathData.time),
  1077. end_time: req.run_end_time,
  1078. distance,
  1079. record_img: "",
  1080. log_data: points,
  1081. file_img: "",
  1082. is_running_area_valid: 1,
  1083. mobileDeviceId: 1,
  1084. mobileModel: req.deviceModel,
  1085. step_info: stepInfo,
  1086. step_num: stepData.total_steps,
  1087. used_time: pathData.time,
  1088. mobileOsVersion: 1,
  1089. record_file: req.record_file
  1090. }
  1091. data.sign = dataSign(data)
  1092. return this.request(
  1093. ctx.traceId,
  1094. 'bindData',
  1095. this.api('/Run/stopRunV278'),
  1096. data
  1097. )
  1098. })
  1099. }
  1100. /* ================= Worker核心 ================= */
  1101. async start() {
  1102. if (this.running) return
  1103. this.running = true
  1104. this.logger.info('Worker 启动中...')
  1105. try {
  1106. this.initHandlers()
  1107. const channel = await mq.getChannel(this.channelName)
  1108. await channel.prefetch(5)
  1109. await assertRunforgeTaskIngress(channel, this.logger)
  1110. await channel.assertQueue(this.resultQueue, {
  1111. durable: true,
  1112. arguments: {
  1113. 'x-max-length': this.maxQueueLength
  1114. }
  1115. })
  1116. await channel.assertQueue(this.deadQueue, {
  1117. durable: true,
  1118. arguments: {
  1119. 'x-max-length': this.maxQueueLength
  1120. }
  1121. })
  1122. await channel.consume(this.taskQueue, async (msg) => {
  1123. if (!msg) return
  1124. let content
  1125. try {
  1126. content = JSON.parse(msg.content.toString())
  1127. } catch {
  1128. return channel.ack(msg)
  1129. }
  1130. const { id, type, data, retry = 0 } = content
  1131. const traceId = this.traceId()
  1132. const handler = this.handlers[type]
  1133. if (!handler) {
  1134. this.log(traceId, 'ERROR', '未知任务', { type })
  1135. return channel.ack(msg)
  1136. }
  1137. try {
  1138. const result = await this.withTimeout(
  1139. handler(data, { traceId, channel, taskId: id }),
  1140. type
  1141. )
  1142. await this.sendResult(channel, {
  1143. id,
  1144. success: true,
  1145. result
  1146. })
  1147. this.log(traceId, 'DONE', `任务完成 ${type}`)
  1148. channel.ack(msg)
  1149. } catch (err) {
  1150. this.logErr(traceId, `任务失败 ${type}`, err)
  1151. if (retry < this.maxRetry && this.isRetryableTaskError(err)) {
  1152. // 重试
  1153. await channel.sendToQueue(
  1154. this.taskQueue,
  1155. Buffer.from(JSON.stringify({
  1156. ...content,
  1157. retry: retry + 1
  1158. })),
  1159. { persistent: true }
  1160. )
  1161. this.log(traceId, 'RETRY', `重试第${retry + 1}次`)
  1162. } else {
  1163. // 死信
  1164. await channel.sendToQueue(
  1165. this.deadQueue,
  1166. Buffer.from(JSON.stringify(content)),
  1167. { persistent: true }
  1168. )
  1169. this.log(traceId, 'DEAD', '进入死信队列')
  1170. }
  1171. await this.sendResult(channel, {
  1172. id,
  1173. success: false,
  1174. error: err.message
  1175. })
  1176. channel.ack(msg)
  1177. }
  1178. })
  1179. this.logger.info('RunForge Worker 启动成功')
  1180. } catch (err) {
  1181. this.logger.error('RunForge Worker 启动失败: ' + err.stack)
  1182. }
  1183. }
  1184. async sendResult(channel, data) {
  1185. channel.sendToQueue(
  1186. this.resultQueue,
  1187. Buffer.from(JSON.stringify(data)),
  1188. { persistent: true }
  1189. )
  1190. }
  1191. async stop() {
  1192. this.running = false
  1193. await mq.close()
  1194. this.logger.info('RunForge Worker 已停止')
  1195. }
  1196. }
  1197. module.exports = Worker