Worker.js 64 KB

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