Worker.js 51 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385
  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. })
  697. await conn.commit()
  698. } catch (error) {
  699. try { await conn.rollback() } catch (_) { }
  700. throw error
  701. } finally {
  702. if (conn?.connection && typeof conn.connection.release === 'function' && typeof conn?.release === 'function') {
  703. conn.release()
  704. }
  705. }
  706. this.logger.info(`${account || uuid}扣减乐跑次数完成`)
  707. await Redis.set(consumeKey, '1', { EX: 3600 })
  708. return true
  709. })
  710. /* ---------------- 返还次数(失败时执行) ---------------- */
  711. this.register('lepao.refundCount', async (req, ctx) => {
  712. const account = req?.account
  713. const uuid = req?.uuid
  714. if (!uuid) {
  715. return true
  716. }
  717. const baseKey = `${ctx?.taskId || ctx?.traceId || account || uuid}`
  718. const consumeKey = `lepao:consume:${baseKey}`
  719. const refundKey = `lepao:refund:${baseKey}`
  720. const consumed = await Redis.get(consumeKey)
  721. if (!consumed) {
  722. return true
  723. }
  724. const refunded = await Redis.get(refundKey)
  725. if (refunded) {
  726. return true
  727. }
  728. this.logger.info(`${account || uuid}开始返还乐跑次数`)
  729. const conn = await db.connect()
  730. try {
  731. await conn.beginTransaction()
  732. const [userRows] = await conn.execute(
  733. 'SELECT lepao_count FROM users WHERE uuid = ? FOR UPDATE',
  734. [uuid]
  735. )
  736. if (!userRows || userRows.length !== 1) {
  737. await conn.rollback()
  738. throw new Error('返还乐跑次数失败:用户不存在')
  739. }
  740. const beforeCount = Number(userRows[0].lepao_count || 0)
  741. const [r] = await conn.execute(
  742. 'UPDATE users SET lepao_count = lepao_count + 1 WHERE uuid = ?',
  743. [uuid]
  744. )
  745. if (!r || r.affectedRows !== 1) {
  746. await conn.rollback()
  747. throw new Error('返还乐跑次数失败:数据库更新失败')
  748. }
  749. await insertLedgerRecord({
  750. executor: conn,
  751. userUuid: uuid,
  752. delta: 1,
  753. balanceBefore: beforeCount,
  754. balanceAfter: beforeCount + 1,
  755. bizType: 'run_refund',
  756. bizId: refundKey
  757. })
  758. await conn.commit()
  759. } catch (error) {
  760. try { await conn.rollback() } catch (_) { }
  761. throw error
  762. } finally {
  763. if (conn?.connection && typeof conn.connection.release === 'function' && typeof conn?.release === 'function') {
  764. conn.release()
  765. }
  766. }
  767. this.logger.info(`${account || uuid}返还乐跑次数完成`)
  768. await Redis.set(refundKey, '1', { EX: 3600 })
  769. return true
  770. })
  771. this.register('lepao.getUserData', async (req, ctx) => {
  772. const account = req.account
  773. this.logger.info(`${account}开始获取用户数据`)
  774. const accountSql = `
  775. SELECT
  776. u.uuid,
  777. u.lepao_count,
  778. l.create_user,
  779. l.name,
  780. l.student_num,
  781. l.area,
  782. l.sex,
  783. l.state,
  784. l.token,
  785. l.uid,
  786. l.school_id,
  787. l.userAgent,
  788. l.deviceModel,
  789. l.notice_type,
  790. l.email,
  791. e.bot_account
  792. FROM
  793. lepao_account l
  794. LEFT JOIN
  795. users u
  796. ON
  797. l.create_user = u.uuid
  798. LEFT JOIN
  799. lepao_extra e
  800. ON
  801. l.student_num = e.student_num
  802. WHERE
  803. l.student_num = ?
  804. `
  805. const rows = await db.query(accountSql, [account])
  806. if (!rows || rows.length === 0) {
  807. this.logger.error(`${account}无法获取账号数据`)
  808. throw new Error('无法获取账号数据,请联系客服或稍后再试')
  809. }
  810. let userData = rows[0]
  811. if (!userData.create_user || !userData.uuid) {
  812. this.logger.warn(`${account}账号状态异常`)
  813. throw new Error('当前账号状态异常,请联系客服')
  814. }
  815. if (userData.state !== 1) {
  816. this.logger.warn(`${account}登录状态异常 state=${userData.state}`)
  817. throw new Error('乐跑账号登录已过期,请尝试使用登录器重新登录')
  818. }
  819. if (userData.lepao_count < 1) {
  820. this.logger.warn(`${account}乐跑次数不足`)
  821. throw new Error('用户乐跑次数不足,请购买乐跑次数后重试!')
  822. }
  823. if (!userData.userAgent)
  824. 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'
  825. if (!userData.deviceModel)
  826. userData.deviceModel = '2211133C'
  827. return userData
  828. })
  829. this.register('lepao.getPath', async (req, ctx) => {
  830. const account = req.account
  831. this.logger.info(`${account}开始获取路径`)
  832. const accountSql = 'SELECT area, sex FROM lepao_account WHERE student_num = ?'
  833. const rows = await db.query(accountSql, [account])
  834. if (!rows || rows.length === 0) {
  835. this.logger.error(`${account}无法获取账号数据`)
  836. throw new Error('无法获取账号数据')
  837. }
  838. const { area, sex } = rows[0]
  839. let max = 4.00
  840. let min = 2.00
  841. if (sex === 2) {
  842. max = 2.00
  843. min = 1.60
  844. }
  845. this.logger.info(`${account}路径参数: area=${area ?? '随机'}, max_distance=${max}, min_distance=${min}`)
  846. let pathSql = 'SELECT * FROM path_data WHERE state = 1 AND distance < ? AND distance > ? '
  847. const pathParams = [max, min]
  848. if (area) {
  849. pathSql += ' AND run_zone_name = ?'
  850. pathParams.push(area)
  851. }
  852. pathSql += ' ORDER BY count ASC LIMIT 1'
  853. const paths = await db.query(pathSql, pathParams)
  854. if (!paths || paths.length === 0) {
  855. this.logger.error(`${account}未找到符合条件的路线`)
  856. const err = new Error('未找到符合条件的路线,请改变路径选择条件')
  857. err.code = 'PATH_SELECT_FAILED'
  858. err.retryable = true
  859. throw err
  860. }
  861. const randomPath = paths[0]
  862. const updateSql = 'UPDATE path_data SET count = count + 1 WHERE id = ?'
  863. await db.query(updateSql, [randomPath.id])
  864. this.logger.info(`${account}路径选中id=${randomPath.id},计数加1成功`)
  865. return { pathData: randomPath }
  866. })
  867. /* ---------------- 获取跑步记录 ---------------- */
  868. this.register('lepao.getRecord', async (req, ctx) => {
  869. const now = this.lepaoTimestamp()
  870. const raw = {
  871. uid: req.uid,
  872. token: req.token,
  873. school_id: req.school_id,
  874. term_id: 0,
  875. course_id: 0,
  876. class_id: 0,
  877. student_num: req.student_id,
  878. card_id: req.student_id,
  879. timestamp: now,
  880. version: 1,
  881. nonce: String(Math.floor(Math.random() * 900000 + 100000)),
  882. ostype: 5
  883. }
  884. raw.sign = dataSign(raw)
  885. return this.request(
  886. ctx.traceId,
  887. 'getRecord',
  888. this.api('/Run2/beforeRunV260'),
  889. raw,
  890. {
  891. 'User-Agent': req.userAgent,
  892. 'charset': 'utf-8',
  893. 'Referer': 'https://servicewechat.com/wxf94c4ddb63d87ede/32/page-frame.html',
  894. }
  895. )
  896. })
  897. /* ---------------- 切换跑区 ---------------- */
  898. this.register('lepao.setZone', async (req, ctx) => {
  899. const runZoneMap = {
  900. '兰花湖校区跑区': 2,
  901. '主校区北跑区': 3,
  902. '主校区南跑区': 5,
  903. '重庆工商大学茶园校区': 6
  904. }
  905. const { pathData } = req
  906. const runZoneId = runZoneMap[pathData.run_zone_name]
  907. if (!runZoneId) throw new Error('跑区不存在')
  908. const raw = {
  909. uid: req.uid,
  910. token: req.token,
  911. school_id: req.school_id,
  912. term_id: 0,
  913. course_id: 0,
  914. class_id: 0,
  915. student_num: req.student_id,
  916. card_id: req.student_id,
  917. timestamp: this.lepaoTimestamp(),
  918. version: 1,
  919. nonce: String(Math.floor(Math.random() * 900000 + 100000)),
  920. ostype: 5,
  921. run_zone_id: String(runZoneId)
  922. }
  923. raw.sign = dataSign(raw)
  924. await this.request(
  925. ctx.traceId,
  926. 'setZone',
  927. this.api('/Run/setRunZone'),
  928. raw
  929. )
  930. return { run_zone_id: runZoneId }
  931. })
  932. /* ---------------- 获取 OSS STS ---------------- */
  933. this.register('lepao.getOssSts', async (req, ctx) => {
  934. const raw = {
  935. uid: req.uid,
  936. token: req.token,
  937. school_id: req.school_id,
  938. term_id: 0,
  939. course_id: 0,
  940. class_id: 0,
  941. student_num: req.student_id,
  942. card_id: req.student_id,
  943. timestamp: this.lepaoTimestamp(),
  944. version: 1,
  945. nonce: String(Math.floor(Math.random() * 900000 + 100000)),
  946. ostype: 5
  947. }
  948. raw.sign = dataSign(raw)
  949. const res = await this.request(
  950. ctx.traceId,
  951. 'getOssSts',
  952. this.api('/WpIndex/getOssSts'),
  953. raw
  954. )
  955. return res.data
  956. })
  957. /* ---------------- 上传 OSS 文件 ---------------- */
  958. this.register('lepao.uploadOssFile', async (req, ctx) => {
  959. const { pathData, newPathData, ossSts: sts } = req
  960. // 处理跑步路径
  961. const pathResult = dataEncrypt(JSON.stringify(newPathData))
  962. // 获取跑步规则参数
  963. const runRule = await this.handlers['lepao.getRecord'](req, ctx)
  964. const ruleData = runRule?.data
  965. if (!ruleData?.run_line_info?.point_list || !ruleData?.time_rule_arr?.length) {
  966. const err = new Error('获取打卡点规则失败')
  967. err.code = 'CHECKPOINT_FETCH_FAILED'
  968. err.retryable = true
  969. throw err
  970. }
  971. const check_points = ruleData.run_line_info.point_list
  972. let min_log_num = ruleData.time_rule_arr[0]?.min_log_num || 4
  973. const point_update_distance = parseFloat(ruleData.run_line_info.point_update_distance || 0) * 1000
  974. const log_max_distance = Number(ruleData.run_line_info.log_max_distance || 0)
  975. // 生成打卡点
  976. const point_data = selectCheckpoints(newPathData, check_points, min_log_num, point_update_distance, log_max_distance, req.run_end_time, pathData.time)
  977. if (!point_data) {
  978. this.logger.warn(`[RETRY] 打卡点数量不足,重新更换路径`)
  979. const err = new Error('打卡点数量不足')
  980. err.code = 'CHECKPOINT_INSUFFICIENT'
  981. err.retryable = true
  982. throw err
  983. }
  984. const now = new Date()
  985. const yyyy = now.getFullYear()
  986. const mm = String(now.getMonth() + 1).padStart(2, '0')
  987. const dd = String(now.getDate()).padStart(2, '0')
  988. const formattedToday = `${yyyy}-${mm}-${dd}`
  989. const boundary = String(Date.now())
  990. const timestamp = String(Date.now())
  991. const ossPath = `Public/Upload/file/run_record/${boundary.slice(-3)}/${formattedToday}/${timestamp}-${Math.floor(Math.random() * 150)}.txt`
  992. const client = new OSS({
  993. bucket: sts.bucket,
  994. region: sts.region || 'oss-cn-hangzhou',
  995. accessKeyId: sts.AccessKeyId,
  996. accessKeySecret: sts.AccessKeySecret,
  997. stsToken: sts.SecurityToken,
  998. secure: true
  999. })
  1000. await client.put(ossPath, Buffer.from(pathResult, 'utf-8'))
  1001. return { oss_path: ossPath, point_data: point_data }
  1002. })
  1003. this.register('lepao.uploadGyrOssFile', async (req, ctx) => {
  1004. const { newPathData, ossSts: sts, record_id } = req
  1005. // 生成加速度数据
  1006. const gyrData = generateGyrFromPath(newPathData)
  1007. if (!Array.isArray(gyrData) || gyrData.length === 0) {
  1008. this.logger.error('生成加速度数据失败')
  1009. return { status: 0, info: '生成加速度数据失败' }
  1010. }
  1011. const now = new Date()
  1012. const yyyy = now.getFullYear()
  1013. const mm = String(now.getMonth() + 1).padStart(2, '0')
  1014. const dd = String(now.getDate()).padStart(2, '0')
  1015. const formattedToday = `${yyyy}-${mm}-${dd}`
  1016. const boundary = String(Date.now())
  1017. const timestamp = String(Date.now())
  1018. const ossPath = `Public/Upload/file/run_gyroscope/${boundary.slice(-3)}/${formattedToday}/${timestamp}-${Math.floor(Math.random() * 150)}.txt`
  1019. const client = new OSS({
  1020. bucket: sts.bucket,
  1021. region: sts.region || 'oss-cn-hangzhou',
  1022. accessKeyId: sts.AccessKeyId,
  1023. accessKeySecret: sts.AccessKeySecret,
  1024. stsToken: sts.SecurityToken,
  1025. secure: true
  1026. })
  1027. await client.put(ossPath, Buffer.from(JSON.stringify(gyrData), 'utf-8'))
  1028. const data = {
  1029. uid: req.uid,
  1030. token: req.token,
  1031. school_id: req.school_id,
  1032. term_id: 0,
  1033. course_id: 0,
  1034. class_id: 0,
  1035. student_num: req.student_id,
  1036. card_id: req.student_id,
  1037. timestamp: this.lepaoTimestamp(),
  1038. version: 1,
  1039. nonce: String(Math.floor(Math.random() * 900000 + 100000)),
  1040. ostype: 5,
  1041. record_id: record_id,
  1042. gyroscope_file: ossPath
  1043. }
  1044. data.sign = dataSign(data)
  1045. return this.request(
  1046. ctx.traceId,
  1047. 'bindData',
  1048. this.api('/Run2/gyroscope'),
  1049. data
  1050. )
  1051. })
  1052. /* ---------------- 提交跑步数据 ---------------- */
  1053. this.register('lepao.bindData', async (req, ctx) => {
  1054. const { pathData } = req
  1055. const distance = Number(Number(pathData.distance || 0).toFixed(2))
  1056. const stepData = generateCadence(distance, pathData.time)
  1057. const stepInfo = JSON.stringify({ interval: 60, list: stepData.cadence_list })
  1058. let points = req.point_data.map(({ address, jingwei, ...rest }) => rest)
  1059. points = JSON.stringify(points)
  1060. const data = {
  1061. uid: req.uid,
  1062. token: req.token,
  1063. school_id: req.school_id,
  1064. term_id: 1,
  1065. course_id: 0,
  1066. class_id: 0,
  1067. student_num: req.student_id,
  1068. card_id: req.student_id,
  1069. timestamp: this.lepaoTimestamp(),
  1070. version: 1,
  1071. nonce: String(Math.floor(Math.random() * 900000 + 100000)),
  1072. ostype: 5,
  1073. game_id: String(req.run_zone_id || 0),
  1074. start_time: req.run_end_time - Number(pathData.time),
  1075. end_time: req.run_end_time,
  1076. distance,
  1077. record_img: "",
  1078. log_data: points,
  1079. file_img: "",
  1080. is_running_area_valid: 1,
  1081. mobileDeviceId: 1,
  1082. mobileModel: req.deviceModel,
  1083. step_info: stepInfo,
  1084. step_num: stepData.total_steps,
  1085. used_time: pathData.time,
  1086. mobileOsVersion: 1,
  1087. record_file: req.record_file
  1088. }
  1089. data.sign = dataSign(data)
  1090. return this.request(
  1091. ctx.traceId,
  1092. 'bindData',
  1093. this.api('/Run/stopRunV278'),
  1094. data
  1095. )
  1096. })
  1097. }
  1098. /* ================= Worker核心 ================= */
  1099. async start() {
  1100. if (this.running) return
  1101. this.running = true
  1102. this.logger.info('Worker 启动中...')
  1103. try {
  1104. this.initHandlers()
  1105. const channel = await mq.getChannel(this.channelName)
  1106. await channel.prefetch(5)
  1107. await assertRunforgeTaskIngress(channel, this.logger)
  1108. await channel.assertQueue(this.resultQueue, {
  1109. durable: true,
  1110. arguments: {
  1111. 'x-max-length': this.maxQueueLength
  1112. }
  1113. })
  1114. await channel.assertQueue(this.deadQueue, {
  1115. durable: true,
  1116. arguments: {
  1117. 'x-max-length': this.maxQueueLength
  1118. }
  1119. })
  1120. await channel.consume(this.taskQueue, async (msg) => {
  1121. if (!msg) return
  1122. let content
  1123. try {
  1124. content = JSON.parse(msg.content.toString())
  1125. } catch {
  1126. return channel.ack(msg)
  1127. }
  1128. const { id, type, data, retry = 0 } = content
  1129. const traceId = this.traceId()
  1130. const handler = this.handlers[type]
  1131. if (!handler) {
  1132. this.log(traceId, 'ERROR', '未知任务', { type })
  1133. return channel.ack(msg)
  1134. }
  1135. try {
  1136. const result = await this.withTimeout(
  1137. handler(data, { traceId, channel, taskId: id }),
  1138. type
  1139. )
  1140. await this.sendResult(channel, {
  1141. id,
  1142. success: true,
  1143. result
  1144. })
  1145. this.log(traceId, 'DONE', `任务完成 ${type}`)
  1146. channel.ack(msg)
  1147. } catch (err) {
  1148. this.logErr(traceId, `任务失败 ${type}`, err)
  1149. if (retry < this.maxRetry && this.isRetryableTaskError(err)) {
  1150. // 重试
  1151. await channel.sendToQueue(
  1152. this.taskQueue,
  1153. Buffer.from(JSON.stringify({
  1154. ...content,
  1155. retry: retry + 1
  1156. })),
  1157. { persistent: true }
  1158. )
  1159. this.log(traceId, 'RETRY', `重试第${retry + 1}次`)
  1160. } else {
  1161. // 死信
  1162. await channel.sendToQueue(
  1163. this.deadQueue,
  1164. Buffer.from(JSON.stringify(content)),
  1165. { persistent: true }
  1166. )
  1167. this.log(traceId, 'DEAD', '进入死信队列')
  1168. }
  1169. await this.sendResult(channel, {
  1170. id,
  1171. success: false,
  1172. error: err.message
  1173. })
  1174. channel.ack(msg)
  1175. }
  1176. })
  1177. this.logger.info('RunForge Worker 启动成功')
  1178. } catch (err) {
  1179. this.logger.error('RunForge Worker 启动失败: ' + err.stack)
  1180. }
  1181. }
  1182. async sendResult(channel, data) {
  1183. channel.sendToQueue(
  1184. this.resultQueue,
  1185. Buffer.from(JSON.stringify(data)),
  1186. { persistent: true }
  1187. )
  1188. }
  1189. async stop() {
  1190. this.running = false
  1191. await mq.close()
  1192. this.logger.info('RunForge Worker 已停止')
  1193. }
  1194. }
  1195. module.exports = Worker