Worker.js 50 KB

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