Worker.js 64 KB

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