Worker.js 51 KB

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