Worker.js 53 KB

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