Worker.js 51 KB

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