Worker.js 42 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103
  1. const path = require('path')
  2. const mq = require('../../plugin/mq')
  3. const { assertRunforgeTaskIngress, TASK_QUEUE } = require('../../plugin/mq/runforgeTaskMq')
  4. const db = require('../../plugin/DataBase/db')
  5. const Redis = require('../../plugin/DataBase/Redis')
  6. const EmailTemplate = require('../../plugin/Email/emailTemplate')
  7. const jkesRedisKeys = require('../../plugin/jkes/redisKeys')
  8. const Logger = require('../Logger')
  9. class Worker {
  10. constructor() {
  11. this.logger = new Logger(
  12. path.join(__dirname, '../logs/LepaoWorker.log'),
  13. 'INFO'
  14. )
  15. this.handlers = {}
  16. this.running = false
  17. this._consuming = false
  18. this._consumeTag = null
  19. this.taskQueue = TASK_QUEUE
  20. this.resultQueue = 'runforge_task_result_queue'
  21. this.deadQueue = 'runforge_task_dead_queue'
  22. this.noticeQueue = 'runforge_message_queue'
  23. this.channelName = 'lepao_worker'
  24. this.maxRetry = 3
  25. this.timeout = 15000
  26. this._lepaoRecordPathColumn = null
  27. // 预扣标记需覆盖“跑步+同步+重试”窗口,避免结算返还时标记已过期
  28. this.lepaoBalanceMarkerTtlSec = 24 * 3600
  29. }
  30. roundKm(n) {
  31. const v = Number(n)
  32. if (!Number.isFinite(v)) return 0
  33. return Math.round(v * 100) / 100
  34. }
  35. traceId() {
  36. return Date.now() + '_' + Math.random().toString(36).slice(2, 8)
  37. }
  38. sleep(ms) {
  39. return new Promise((r) => setTimeout(r, ms))
  40. }
  41. getLepaoBalanceBaseKey(req, ctx) {
  42. const stableTraceId = req?.traceId || ctx?.traceId
  43. if (stableTraceId) return String(stableTraceId)
  44. return `${ctx?.taskId || req?.account || req?.uuid || 'unknown'}`
  45. }
  46. async markLoginExpired(account) {
  47. if (!account) return
  48. try {
  49. const sql = 'UPDATE lepao_account SET state = 0 WHERE student_num = ?'
  50. await db.query(sql, [account])
  51. try {
  52. await Redis.del(jkesRedisKeys.runnerFlag(account))
  53. } catch (e) {
  54. this.logger.warn(`${account} 清理 jkes_runner 标记失败:${e.message || e}`)
  55. }
  56. this.logger.warn(`${account} 登录状态已失效,已自动更新账号状态`)
  57. } catch (error) {
  58. this.logger.error(`更新账号登录状态失败:${error.stack || error}`)
  59. }
  60. }
  61. async writeSuccessRedis(account) {
  62. if (!account) return
  63. try {
  64. const now = new Date()
  65. const tomorrow = new Date().setHours(24, 0, 0, 0)
  66. const exp = Math.floor((tomorrow - now) / 1000)
  67. await Redis.set(jkesRedisKeys.lepaoSuccess(account), account, { EX: exp })
  68. } catch (error) {
  69. this.logger.error(`写入乐跑成功缓存失败: ${error.stack || error}`)
  70. }
  71. }
  72. async getLepaoRecordPathColumn() {
  73. if (this._lepaoRecordPathColumn) return this._lepaoRecordPathColumn
  74. try {
  75. await db.query('SELECT path_data FROM lepao_record LIMIT 1')
  76. this._lepaoRecordPathColumn = 'path_data'
  77. } catch (e) {
  78. if ((e?.message || '').includes("Unknown column 'path_data'")) {
  79. this._lepaoRecordPathColumn = 'point_data'
  80. } else {
  81. throw e
  82. }
  83. }
  84. return this._lepaoRecordPathColumn
  85. }
  86. async createLepaoRecord({ uuid, account, result = {}, pathId = null, pathData = [], state = 0 }) {
  87. if (!uuid || !account) return null
  88. const pathCol = await this.getLepaoRecordPathColumn()
  89. const sql = `INSERT INTO lepao_record (uuid, time, lepao_account, result, path_id, ${pathCol}, state) VALUES (?, ?, ?, ?, ?, ?, ?)`
  90. const r = await db.query(sql, [
  91. uuid,
  92. Date.now(),
  93. account,
  94. JSON.stringify(result || {}),
  95. pathId,
  96. JSON.stringify(pathData || []),
  97. state
  98. ])
  99. return r?.insertId || null
  100. }
  101. async updateLepaoRecord(id, { result, pathData, state } = {}) {
  102. if (!id) return
  103. const pathCol = await this.getLepaoRecordPathColumn()
  104. const sets = []
  105. const params = []
  106. if (result !== undefined) {
  107. sets.push('result = ?')
  108. params.push(JSON.stringify(result || {}))
  109. }
  110. if (pathData !== undefined) {
  111. sets.push(`${pathCol} = ?`)
  112. params.push(JSON.stringify(pathData || []))
  113. }
  114. if (state !== undefined) {
  115. sets.push('state = ?')
  116. params.push(state)
  117. }
  118. if (!sets.length) return
  119. params.push(id)
  120. await db.query(`UPDATE lepao_record SET ${sets.join(', ')} WHERE id = ?`, params)
  121. }
  122. async syncJkesRunCount(req) {
  123. const sid = req?.student_id || req?.account
  124. const token = req?.token
  125. if (!sid || !token) return
  126. const { fetchJkesMonthKm, fetchJkesTotalKm } = require('../../plugin/jkes/stats')
  127. const { readState, writeState } = require('../../plugin/jkes/monthPolicy')
  128. const now = new Date()
  129. const y = now.getFullYear()
  130. const m = now.getMonth() + 1
  131. const monthKm = await fetchJkesMonthKm(token, y, m)
  132. const totalKm = await fetchJkesTotalKm(token)
  133. const sql = 'UPDATE lepao_account SET term_num = ?, total_num = ? WHERE student_num = ?'
  134. const rows = await db.query(sql, [monthKm, totalKm, sid])
  135. if (!rows || rows.affectedRows !== 1) {
  136. this.logger.warn(`${sid} JKES 更新里程字段失败`)
  137. } else {
  138. this.logger.info(`${sid} JKES 同步里程 本月=${monthKm} 累计=${totalKm}`)
  139. }
  140. const prevLocal = await readState(sid, now)
  141. await writeState(sid, { km: monthKm, doubles: prevLocal.doubles }, now)
  142. }
  143. async syncRunCount(req) {
  144. try {
  145. await this.syncJkesRunCount(req)
  146. } catch (error) {
  147. this.logger.warn(`${req?.account || 'unknown'}同步乐跑里程失败: ${error.message || error}`)
  148. }
  149. }
  150. async enqueueTask(channel, type, data, options = {}) {
  151. const payload = {
  152. id: options.id || this.traceId(),
  153. type,
  154. data,
  155. retry: options.retry ?? 0
  156. }
  157. // 这里不要直接用传入的 channel:断线后它可能已 close
  158. await mq.sendToQueueSafe(
  159. this.channelName,
  160. this.taskQueue,
  161. Buffer.from(JSON.stringify(payload)),
  162. { persistent: true, contentType: 'application/json' }
  163. )
  164. return payload.id
  165. }
  166. async withTimeout(promise, name, ms) {
  167. const limit = typeof ms === 'number' && ms > 0 ? ms : this.timeout
  168. return Promise.race([
  169. promise,
  170. new Promise((_, reject) =>
  171. setTimeout(() => reject(new Error(`${name} 超时`)), limit)
  172. )
  173. ])
  174. }
  175. async retry(fn, name) {
  176. let lastErr
  177. for (let i = 0; i < this.maxRetry; i++) {
  178. try {
  179. return await fn()
  180. } catch (err) {
  181. lastErr = err
  182. if (!this.isRetryableTaskError(err)) {
  183. throw err
  184. }
  185. this.logger.warn(`[RETRY] ${name} 第${i + 1}次失败`)
  186. await this.sleep(1000 * (i + 1))
  187. }
  188. }
  189. throw lastErr
  190. }
  191. isNetworkError(err) {
  192. if (!err) return false
  193. if (
  194. err.code &&
  195. ['ECONNRESET', 'ECONNABORTED', 'ETIMEDOUT', 'ENOTFOUND', 'EAI_AGAIN'].includes(err.code)
  196. ) {
  197. return true
  198. }
  199. if (err.isAxiosError && !err.response) return true
  200. const msg = (err.message || '').toLowerCase()
  201. return msg.includes('timeout') || msg.includes('network')
  202. }
  203. isRetryableTaskError(err) {
  204. if (!err) return false
  205. if (err.retryable === true) return true
  206. if (this.isNetworkError(err)) return true
  207. return ['PATH_SELECT_FAILED', 'CHECKPOINT_FETCH_FAILED', 'CHECKPOINT_INSUFFICIENT'].includes(
  208. err.code
  209. )
  210. }
  211. safeStringify(obj) {
  212. const seen = new WeakSet()
  213. return JSON.stringify(obj, (key, value) => {
  214. if (typeof value === 'object' && value !== null) {
  215. if (seen.has(value)) return '[Circular]'
  216. seen.add(value)
  217. }
  218. return value
  219. })
  220. }
  221. log(traceId, type, msg, data) {
  222. this.logger.info(`[${traceId}] [${type}] ${msg} ${data ? this.safeStringify(data) : ''}`)
  223. }
  224. logErr(traceId, msg, err) {
  225. this.logger.error(`[${traceId}] ${msg} ${err.stack || err}`)
  226. }
  227. register(type, handler) {
  228. this.handlers[type] = handler
  229. this.logger.info(`注册任务: ${type}`)
  230. }
  231. /**
  232. * 仅选取轨迹几何(闭合环路),实际跑步距离与配速由 runJkesRecord 的 distanceM / paceSecPerKm 决定,不再按 path_data.distance 筛选
  233. */
  234. async selectJkesPathRow(account) {
  235. const accountSql = 'SELECT area FROM lepao_account WHERE student_num = ?'
  236. const rows = await db.query(accountSql, [account])
  237. const area = rows?.[0]?.area
  238. let pathSql = 'SELECT id, data FROM path_data WHERE state = 1 '
  239. const pathParams = []
  240. if (area) {
  241. pathSql += ' AND run_zone_name = ?'
  242. pathParams.push(area)
  243. }
  244. pathSql += ' ORDER BY count ASC LIMIT 1'
  245. const paths = await db.query(pathSql, pathParams)
  246. if (!paths || paths.length === 0) {
  247. const err = new Error('未找到符合条件的路线,请改变路径选择条件')
  248. err.code = 'PATH_SELECT_FAILED'
  249. err.retryable = true
  250. throw err
  251. }
  252. const picked = paths[0]
  253. await db.query('UPDATE path_data SET count = count + 1 WHERE id = ?', [picked.id])
  254. return picked
  255. }
  256. initHandlers() {
  257. this.register('lepao.startRun', async (req, ctx) => {
  258. const traceId = ctx.traceId
  259. const maxPathRetry = 5
  260. let pathRetry = 0
  261. let userData = null
  262. let recordDbId = null
  263. let deductedKm = 0
  264. try {
  265. // const isSuccess = await Redis.get(jkesRedisKeys.lepaoSuccess(req.account))
  266. // if (isSuccess) throw new Error('该账号当天已乐跑成功!请勿重复乐跑')
  267. userData = await this.handlers['lepao.getUserData'](req, ctx)
  268. req = {
  269. ...req,
  270. ...userData,
  271. student_id: req.account
  272. }
  273. const progressKey = jkesRedisKeys.lepaoProgress(req.account)
  274. const inProgress = await Redis.get(progressKey)
  275. if (inProgress) {
  276. throw new Error('该账号已进入乐跑任务队列,请等待乐跑完成后再进行乐跑操作')
  277. }
  278. await Redis.set(progressKey, req.account, { EX: 1800 })
  279. const hour = new Date().getHours()
  280. // if (hour < 7) {
  281. // throw new Error('当前不在有效乐跑时间范围内。哪吒乐跑支持乐跑时间段为7:00~24:00')
  282. // }
  283. const { runJkesRecord } = require('../../plugin/jkes/runRecord')
  284. const { getJkesSettings } = require('../../plugin/jkes/jkesSettings')
  285. const { randomPaceSecPerKm } = require('../../plugin/jkes/paceUtils')
  286. const { isJkesRecordValidInCampus } = require('../../plugin/jkes/stats')
  287. const manual = req.manual === true || req.manual === 'true'
  288. const jkesSettings = getJkesSettings()
  289. let targetKm = Number(req.targetKm)
  290. if (!Number.isFinite(targetKm) || targetKm < 1) targetKm = 1
  291. const maxAutoKm = Math.max(2, Number(jkesSettings.autoSingleRunMaxKm) || 10)
  292. if (manual) {
  293. if (targetKm > 10) targetKm = 10
  294. } else if (targetKm > maxAutoKm) {
  295. targetKm = maxAutoKm
  296. }
  297. targetKm = this.roundKm(targetKm)
  298. const distanceM = targetKm * 1000
  299. deductedKm = targetKm
  300. let pace
  301. if (manual) {
  302. const p = Number(req.paceSecPerKm)
  303. if (!Number.isFinite(p) || p < 180 || p > 600) {
  304. throw new Error('手动乐跑任务缺少有效配速 paceSecPerKm(3:00–10:00/km)')
  305. }
  306. pace = p
  307. } else {
  308. const rMin = Number(req.paceRandomMinSecPerKm)
  309. const rMax = Number(req.paceRandomMaxSecPerKm)
  310. if (Number.isFinite(rMin) && Number.isFinite(rMax)) {
  311. pace = randomPaceSecPerKm(rMin, rMax)
  312. } else {
  313. pace = randomPaceSecPerKm(
  314. jkesSettings.paceRandomMinSecPerKm,
  315. jkesSettings.paceRandomMaxSecPerKm
  316. )
  317. }
  318. }
  319. await this.handlers['lepao.consumeCount'](
  320. {
  321. account: req.account,
  322. uuid: userData?.create_user,
  323. amountKm: deductedKm,
  324. traceId
  325. },
  326. ctx
  327. )
  328. let jkesPathId = null
  329. let jkesEnd = null
  330. while (pathRetry < maxPathRetry) {
  331. try {
  332. const pathRow = await this.selectJkesPathRow(req.account)
  333. jkesPathId = pathRow.id
  334. let rawData = pathRow.data
  335. if (typeof rawData === 'string') {
  336. rawData = JSON.parse(rawData)
  337. }
  338. if (!Array.isArray(rawData) || rawData.length === 0) {
  339. pathRetry++
  340. this.logger.warn(`[${traceId}] JKES 轨迹数据无效,换路径 第${pathRetry}次`)
  341. continue
  342. }
  343. if (!recordDbId) {
  344. recordDbId = await this.createLepaoRecord({
  345. uuid: userData?.create_user,
  346. account: req.account,
  347. pathId: jkesPathId,
  348. pathData: [],
  349. result: {
  350. phase: 'running',
  351. planned_km: targetKm,
  352. pace_sec_per_km: pace
  353. },
  354. state: 0
  355. })
  356. }
  357. jkesEnd = await runJkesRecord({
  358. token: req.token,
  359. recordDbId,
  360. pathPoints: rawData,
  361. distanceM,
  362. paceSecPerKm: pace,
  363. log: (msg) => this.logger.info(`[${traceId}] ${msg}`)
  364. })
  365. break
  366. } catch (err) {
  367. if (!this.isRetryableTaskError(err)) {
  368. throw err
  369. }
  370. this.logger.warn(`[${traceId}] JKES 可重试错误 第${pathRetry + 1}次:${err.message}`)
  371. pathRetry++
  372. await this.sleep(1000 * pathRetry)
  373. }
  374. }
  375. if (!jkesEnd) {
  376. throw new Error('JKES 乐跑失败:未获得有效跑步结果')
  377. }
  378. const info = jkesEnd.endJson?.data?.info
  379. const infoWithMeta = info
  380. ? {
  381. ...info,
  382. planned_km: targetKm,
  383. deducted_km: deductedKm,
  384. pace_sec_per_km: pace
  385. }
  386. : null
  387. if (!recordDbId) {
  388. recordDbId = await this.createLepaoRecord({
  389. uuid: userData?.create_user,
  390. account: req.account,
  391. pathId: jkesPathId,
  392. pathData: jkesEnd.uploadedPayloadPoints || [],
  393. result: infoWithMeta || jkesEnd.endJson?.data || {},
  394. state: 1
  395. })
  396. } else {
  397. await this.updateLepaoRecord(recordDbId, {
  398. result: infoWithMeta || jkesEnd.endJson?.data || {},
  399. pathData: jkesEnd.uploadedPayloadPoints || [],
  400. state: 1
  401. })
  402. }
  403. const ok = isJkesRecordValidInCampus(info || {})
  404. if (!ok) {
  405. const reason =
  406. info?.dataStatus?.label || info?.status?.label || '跑步记录未记作校内有效'
  407. throw new Error(reason)
  408. }
  409. await this.writeSuccessRedis(req.account)
  410. const autoDoubleSlot =
  411. !manual && (req.autoDoubleSlot === true || req.autoDoubleSlot === 'true')
  412. const finalizeTask = {
  413. account: req.account,
  414. token: req.token,
  415. uuid: userData?.create_user,
  416. recordDbId,
  417. jkesRecordId: jkesEnd.recordId || info?.id,
  418. deductedKm,
  419. targetKm,
  420. autoDoubleSlot,
  421. traceId
  422. }
  423. if (ctx.channel) {
  424. try {
  425. await this.enqueueTask(ctx.channel, 'lepao.finalizeRunSync', finalizeTask, {
  426. id: `${traceId}:finalize:${req.account}`
  427. })
  428. } catch (e) {
  429. this.logger.warn(`[${traceId}] finalize 任务投递失败,改为同步执行:${e.message || e}`)
  430. await this.handlers['lepao.finalizeRunSync'](finalizeTask, ctx)
  431. }
  432. } else {
  433. await this.handlers['lepao.finalizeRunSync'](finalizeTask, ctx)
  434. }
  435. return { traceId, jkes: true, endJson: jkesEnd.endJson }
  436. } catch (err) {
  437. this.logger.error(`[${traceId}] 乐跑流程失败:`, err)
  438. try {
  439. await this.handlers['lepao.refundCount'](
  440. {
  441. account: req.account,
  442. uuid: userData?.create_user,
  443. amountKm: deductedKm,
  444. traceId
  445. },
  446. ctx
  447. )
  448. } catch (e) {
  449. this.logger.error(`[${traceId}] 返还乐跑公里失败:${e.stack || e}`)
  450. }
  451. if (recordDbId) {
  452. try {
  453. await this.updateLepaoRecord(recordDbId, {
  454. result: { phase: 'error', reason: err.message || '未知错误' },
  455. state: 3
  456. })
  457. } catch (e) {
  458. this.logger.error(`[${traceId}] 更新乐跑记录失败:${e.stack || e}`)
  459. }
  460. }
  461. if (ctx.channel) {
  462. await this.enqueueTask(ctx.channel, 'lepao.sendNotice', {
  463. account: req.account,
  464. success: false,
  465. reason: err.message || '未知错误',
  466. traceId
  467. }, { id: `${traceId}:notice:fail` })
  468. }
  469. throw err
  470. } finally {
  471. if (req?.account) {
  472. await Redis.del(jkesRedisKeys.lepaoProgress(req.account))
  473. }
  474. }
  475. })
  476. this.register('lepao.finalizeRunSync', async (req, ctx) => {
  477. const traceId = req?.traceId || ctx?.traceId || this.traceId()
  478. const {
  479. account,
  480. token,
  481. uuid,
  482. recordDbId,
  483. jkesRecordId,
  484. deductedKm,
  485. targetKm,
  486. autoDoubleSlot
  487. } = req || {}
  488. if (!account || !token || !recordDbId || !jkesRecordId) {
  489. throw new Error('finalizeRunSync 参数缺失')
  490. }
  491. const {
  492. fetchJkesRecordById,
  493. isJkesRecordFullySynced,
  494. isJkesRecordValidInCampus,
  495. recordDistanceKm
  496. } = require('../../plugin/jkes/stats')
  497. const { recordSuccess } = require('../../plugin/jkes/monthPolicy')
  498. const pollCount = 40
  499. const pollIntervalMs = 90 * 1000
  500. let latest = null
  501. let synced = false
  502. for (let i = 1; i <= pollCount; i++) {
  503. latest = await fetchJkesRecordById(token, jkesRecordId, 10)
  504. if (latest && isJkesRecordFullySynced(latest)) {
  505. synced = true
  506. break
  507. }
  508. if (i < pollCount) {
  509. await this.sleep(pollIntervalMs)
  510. }
  511. }
  512. if (!latest || !isJkesRecordValidInCampus(latest)) {
  513. await this.updateLepaoRecord(recordDbId, {
  514. result: latest || { phase: 'finalize_failed', reason: '记录未校内有效' },
  515. state: 3
  516. })
  517. await this.handlers['lepao.refundCount'](
  518. {
  519. account,
  520. uuid,
  521. amountKm: this.roundKm(deductedKm || targetKm || 0),
  522. traceId
  523. },
  524. { ...ctx, taskId: `${ctx?.taskId || traceId}:finalize_refund_full` }
  525. )
  526. if (ctx.channel) {
  527. await this.enqueueTask(ctx.channel, 'lepao.sendNotice', {
  528. account,
  529. success: false,
  530. reason: '乐跑记录未同步为校内有效,已退还预扣公里',
  531. traceId
  532. }, { id: `${traceId}:notice:fail:finalize` })
  533. }
  534. return { traceId, finalized: false, refunded: true }
  535. }
  536. if (!synced) {
  537. await this.updateLepaoRecord(recordDbId, {
  538. result: latest,
  539. state: 1
  540. })
  541. const err = new Error('官方记录尚未完全同步(distance/speed)')
  542. err.retryable = true
  543. throw err
  544. }
  545. const officialKmRaw = this.roundKm(recordDistanceKm(latest))
  546. const officialKm = officialKmRaw > 0 ? officialKmRaw : this.roundKm(targetKm || 0)
  547. const preDeduct = this.roundKm(deductedKm || targetKm || 0)
  548. const refundKm = this.roundKm(Math.max(0, preDeduct - officialKm))
  549. if (refundKm > 0) {
  550. await this.handlers['lepao.refundCount'](
  551. {
  552. account,
  553. uuid,
  554. amountKm: refundKm,
  555. traceId
  556. },
  557. { ...ctx, taskId: `${ctx?.taskId || traceId}:finalize_refund_over` }
  558. )
  559. }
  560. await this.updateLepaoRecord(recordDbId, {
  561. result: {
  562. ...(latest || {}),
  563. planned_km: this.roundKm(targetKm || 0),
  564. deducted_km: preDeduct,
  565. official_km: officialKm,
  566. refunded_km: refundKm
  567. },
  568. state: 2
  569. })
  570. await recordSuccess(account, officialKm, { autoDoubleSlot: officialKm >= 2 && !!autoDoubleSlot })
  571. await this.syncRunCount({ account, student_id: account, token })
  572. // 达成本月预设目标后:关闭自动乐跑并发送目标完成邮件(target_count=0 表示不限制)
  573. try {
  574. const accRows = await db.query(
  575. 'SELECT name, email, notice_type, auto_run, target_count, term_num, total_num FROM lepao_account WHERE student_num = ?',
  576. [account]
  577. )
  578. if (accRows && accRows.length) {
  579. const acc = accRows[0]
  580. const targetKm = Number(acc.target_count) || 0
  581. const monthKm = Number(acc.term_num) || 0
  582. if (acc.auto_run === 1 && targetKm !== 0 && monthKm >= targetKm) {
  583. await db.query('UPDATE lepao_account SET auto_run = 0 WHERE student_num = ?', [account])
  584. if (acc.notice_type === 'email' && acc.email) {
  585. await EmailTemplate.lepaoOver(acc.email, {
  586. name: acc.name || account,
  587. month_km: monthKm,
  588. target_km: targetKm
  589. })
  590. }
  591. }
  592. }
  593. } catch (e) {
  594. this.logger.warn(`[${traceId}] 目标达成处理失败:${e.message || e}`)
  595. }
  596. if (ctx.channel) {
  597. await this.enqueueTask(ctx.channel, 'lepao.sendNotice', {
  598. account,
  599. success: true,
  600. data: {
  601. distance: officialKm,
  602. time: Number(latest.useTime) || 0,
  603. record_failed_reason: '',
  604. refundedKm: refundKm
  605. },
  606. traceId
  607. }, { id: `${traceId}:notice:success:finalize` })
  608. }
  609. return { traceId, finalized: true, officialKm, refundKm }
  610. })
  611. this.register('lepao.sendNotice', async (req, ctx) => {
  612. const { account, success, data, reason, traceId } = req || {}
  613. if (!account) {
  614. throw new Error('发送通知失败:缺少 account')
  615. }
  616. const emailSql = `
  617. SELECT
  618. a.name,
  619. a.email,
  620. a.target_count,
  621. a.term_num,
  622. a.total_num,
  623. a.notice_type,
  624. e.bot_umo
  625. FROM
  626. lepao_account a
  627. LEFT JOIN
  628. lepao_extra e
  629. ON
  630. a.student_num = e.student_num
  631. WHERE
  632. a.student_num = ?
  633. `
  634. const rows = await db.query(emailSql, [account])
  635. if (!rows || rows.length === 0) {
  636. throw new Error('发送通知失败:未找到用户通知配置')
  637. }
  638. const user = rows[0]
  639. const noticeType = user.notice_type || 'none'
  640. let runZoneName = data?.run_zone_name
  641. if (!runZoneName && success) {
  642. try {
  643. const z = await db.query(
  644. `
  645. SELECT p.run_zone_name
  646. FROM lepao_record r
  647. LEFT JOIN path_data p ON r.path_id = p.id
  648. WHERE r.lepao_account = ?
  649. ORDER BY r.id DESC
  650. LIMIT 1
  651. `,
  652. [account]
  653. )
  654. runZoneName = z?.length ? z[0].run_zone_name : null
  655. } catch (e) {
  656. this.logger.warn(`[${traceId}] 查询跑区失败:${e.message || e}`)
  657. }
  658. }
  659. const payload = success
  660. ? {
  661. ...(data && typeof data === 'object' ? data : {}),
  662. type: 'lepao_success',
  663. umo: user.bot_umo,
  664. run_zone_name: runZoneName,
  665. month_km: Number(user.term_num) || 0,
  666. total_km: Number(user.total_num) || 0,
  667. target_km: Number(user.target_count) || 0,
  668. name: user.name,
  669. account,
  670. traceId
  671. }
  672. : {
  673. type: 'lepao_fail',
  674. umo: user.bot_umo,
  675. name: user.name,
  676. account,
  677. reason,
  678. traceId
  679. }
  680. if (noticeType === 'bot' && user.bot_umo) {
  681. const ch = await mq.getChannel(this.noticeQueue)
  682. await ch.assertQueue(this.noticeQueue, { durable: true })
  683. await mq.sendToQueueSafe(
  684. this.noticeQueue,
  685. this.noticeQueue,
  686. Buffer.from(JSON.stringify(payload)),
  687. { persistent: true, contentType: 'application/json' }
  688. )
  689. return { delivered: true, via: 'bot' }
  690. }
  691. if (noticeType === 'email' && user.email) {
  692. if (success) {
  693. await EmailTemplate.lepaoSuccess(user.email, payload)
  694. return { delivered: true, via: 'email' }
  695. }
  696. await EmailTemplate.lepaoFail(user.email, {
  697. name: user.name,
  698. account,
  699. reason: reason || '系统繁忙,请联系客服或稍后再试',
  700. traceId
  701. })
  702. return { delivered: true, via: 'email' }
  703. }
  704. return { delivered: false, via: 'none' }
  705. })
  706. this.register('lepao.consumeCount', async (req, ctx) => {
  707. const account = req?.account
  708. const uuid = req?.uuid
  709. const amountKm = this.roundKm(req?.amountKm ?? 1)
  710. if (!uuid) {
  711. throw new Error('扣减乐跑公里失败:缺少 uuid')
  712. }
  713. if (!(amountKm > 0)) {
  714. throw new Error('扣减乐跑公里失败:amountKm 无效')
  715. }
  716. const baseKey = this.getLepaoBalanceBaseKey(req, ctx)
  717. const consumeKey = jkesRedisKeys.consume(baseKey)
  718. const existed = await Redis.get(consumeKey)
  719. if (existed) {
  720. return true
  721. }
  722. this.logger.info(`${account || uuid}开始扣减乐跑公里 ${amountKm}km`)
  723. const useLepaoCountSql =
  724. 'UPDATE users SET lepao_count = ROUND(lepao_count - ?, 2) WHERE uuid = ? AND lepao_count >= ?'
  725. const r = await db.query(useLepaoCountSql, [amountKm, uuid, amountKm])
  726. if (!r || r.affectedRows !== 1) {
  727. throw new Error(`扣减乐跑公里失败:余额不足(需 ${amountKm}km)`)
  728. }
  729. this.logger.info(`${account || uuid}扣减乐跑公里完成`)
  730. await Redis.set(consumeKey, '1', { EX: this.lepaoBalanceMarkerTtlSec })
  731. return true
  732. })
  733. this.register('lepao.refundCount', async (req, ctx) => {
  734. const account = req?.account
  735. const uuid = req?.uuid
  736. const amountKm = this.roundKm(req?.amountKm ?? 0)
  737. if (!uuid) {
  738. return true
  739. }
  740. if (!(amountKm > 0)) return true
  741. const baseKey = this.getLepaoBalanceBaseKey(req, ctx)
  742. const consumeKey = jkesRedisKeys.consume(baseKey)
  743. const refundKey = jkesRedisKeys.refund(baseKey)
  744. const consumed = await Redis.get(consumeKey)
  745. if (!consumed) {
  746. return true
  747. }
  748. const refunded = await Redis.get(refundKey)
  749. if (refunded) {
  750. return true
  751. }
  752. this.logger.info(`${account || uuid}开始返还乐跑公里 ${amountKm}km`)
  753. const sql = 'UPDATE users SET lepao_count = ROUND(lepao_count + ?, 2) WHERE uuid = ?'
  754. const r = await db.query(sql, [amountKm, uuid])
  755. if (!r || r.affectedRows !== 1) {
  756. throw new Error('返还乐跑公里失败:数据库更新失败')
  757. }
  758. this.logger.info(`${account || uuid}返还乐跑公里完成`)
  759. await Redis.set(refundKey, '1', { EX: this.lepaoBalanceMarkerTtlSec })
  760. return true
  761. })
  762. this.register('lepao.getUserData', async (req, ctx) => {
  763. const account = req.account
  764. this.logger.info(`${account}开始获取用户数据`)
  765. const accountSql = `
  766. SELECT
  767. u.uuid,
  768. u.lepao_count,
  769. l.create_user,
  770. l.name,
  771. l.student_num,
  772. l.area,
  773. l.sex,
  774. l.state,
  775. l.token,
  776. l.userAgent,
  777. l.deviceModel,
  778. l.notice_type,
  779. l.email,
  780. e.bot_account
  781. FROM
  782. lepao_account l
  783. LEFT JOIN
  784. users u
  785. ON
  786. l.create_user = u.uuid
  787. LEFT JOIN
  788. lepao_extra e
  789. ON
  790. l.student_num = e.student_num
  791. WHERE
  792. l.student_num = ?
  793. `
  794. const rows = await db.query(accountSql, [account])
  795. if (!rows || rows.length === 0) {
  796. this.logger.error(`${account}无法获取账号数据`)
  797. throw new Error('无法获取账号数据,请联系客服或稍后再试')
  798. }
  799. let userData = rows[0]
  800. if (!userData.create_user || !userData.uuid) {
  801. this.logger.warn(`${account}账号状态异常`)
  802. throw new Error('当前账号状态异常,请联系客服')
  803. }
  804. if (userData.state !== 1) {
  805. this.logger.warn(`${account}登录状态异常 state=${userData.state}`)
  806. throw new Error('乐跑账号登录已过期,请尝试使用登录器重新登录')
  807. }
  808. if (Number(userData.lepao_count) <= 0) {
  809. this.logger.warn(`${account}乐跑公里余额不足`)
  810. throw new Error('用户乐跑公里余额不足,请购买后重试!')
  811. }
  812. if (!userData.userAgent) {
  813. userData.userAgent =
  814. 'Mozilla/5.0 (iPhone; CPU iPhone OS 18_7 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148 MicroMessenger/8.0.69 NetType/WIFI Language/zh_CN'
  815. }
  816. if (!userData.deviceModel) userData.deviceModel = 'unknown'
  817. return userData
  818. })
  819. }
  820. async start() {
  821. if (this.running) return
  822. this.running = true
  823. this.logger.info('Worker 启动中(JKES)...')
  824. try {
  825. this.initHandlers()
  826. await this.startConsumeLoop()
  827. this.logger.info('哪吒乐跑 Worker 启动成功(JKES)')
  828. } catch (err) {
  829. this.logger.error('哪吒乐跑 Worker 启动失败: ' + (err.stack || err))
  830. }
  831. }
  832. async startConsumeLoop() {
  833. if (!this.running) return
  834. if (this._consuming) return
  835. this._consuming = true
  836. const channel = await mq.getChannel(this.channelName)
  837. channel.on('close', () => {
  838. // close 事件可能重复触发;这里仅触发一次重启
  839. if (!this.running) return
  840. this._consuming = false
  841. this.logger.warn('Worker channel 已关闭,准备重启消费')
  842. setTimeout(() => {
  843. this.startConsumeLoop().catch((e) => {
  844. this.logger.error('重启 Worker 消费失败: ' + (e?.stack || e))
  845. })
  846. }, 1000)
  847. })
  848. await channel.prefetch(5)
  849. await assertRunforgeTaskIngress(channel, this.logger)
  850. await channel.assertQueue(this.resultQueue, { durable: true })
  851. await channel.assertQueue(this.deadQueue, { durable: true })
  852. const handleTaskMessage = async (msg) => {
  853. if (!msg) return
  854. let content
  855. let acked = false
  856. const safeAck = () => {
  857. if (!msg || acked) return true
  858. try {
  859. channel.ack(msg)
  860. acked = true
  861. return true
  862. } catch (e) {
  863. this.logger.warn(`消息 ack 失败(可能 channel 已关闭):${e?.message || e}`)
  864. return false
  865. }
  866. }
  867. try {
  868. content = JSON.parse(msg.content.toString())
  869. } catch {
  870. return safeAck()
  871. }
  872. const { id, type, data, retry = 0 } = content
  873. const traceId = this.traceId()
  874. const handler = this.handlers[type]
  875. if (!handler) {
  876. this.log(traceId, 'ERROR', '未知任务', { type })
  877. return safeAck()
  878. }
  879. try {
  880. const runMs =
  881. type === 'lepao.startRun'
  882. ? 3600000
  883. : type === 'lepao.finalizeRunSync'
  884. ? 4 * 3600000
  885. : undefined
  886. /**
  887. * RabbitMQ consumer_timeout 默认常见为 30min。
  888. * lepao.startRun / finalizeRunSync 可能长时间运行,若一直不 ack 会触发 PRECONDITION_FAILED 并关闭 channel。
  889. * 对长任务先 ack,再由本地重试/死信逻辑托底,避免进程因 channel closed 崩溃。
  890. */
  891. const needEarlyAck = Number.isFinite(runMs) && runMs >= 25 * 60 * 1000
  892. if (needEarlyAck) {
  893. safeAck()
  894. }
  895. const result = await this.withTimeout(
  896. handler(data, { traceId, channel, taskId: id }),
  897. type,
  898. runMs
  899. )
  900. await this.sendResult(channel, {
  901. id,
  902. success: true,
  903. result
  904. })
  905. this.log(traceId, 'DONE', `任务完成 ${type}`)
  906. safeAck()
  907. } catch (err) {
  908. this.logErr(traceId, `任务失败 ${type}`, err)
  909. if (err?.loginExpired) {
  910. const account = data?.account || data?.student_num || data?.studentNum
  911. await this.markLoginExpired(account)
  912. }
  913. if (retry < this.maxRetry && this.isRetryableTaskError(err)) {
  914. try {
  915. await mq.sendToQueueSafe(
  916. this.channelName,
  917. this.taskQueue,
  918. Buffer.from(
  919. JSON.stringify({
  920. ...content,
  921. retry: retry + 1
  922. })
  923. ),
  924. { persistent: true, contentType: 'application/json' }
  925. )
  926. } catch (e) {
  927. this.logger.error(
  928. `[${traceId}] 重试消息投递失败(将直接 ack,避免进程崩溃):${e?.message || e}`
  929. )
  930. }
  931. this.log(traceId, 'RETRY', `重试第${retry + 1}次`)
  932. } else {
  933. try {
  934. await mq.sendToQueueSafe(
  935. this.channelName,
  936. this.deadQueue,
  937. Buffer.from(JSON.stringify(content)),
  938. { persistent: true, contentType: 'application/json' }
  939. )
  940. } catch (e) {
  941. this.logger.error(
  942. `[${traceId}] 死信投递失败(将直接 ack,避免进程崩溃):${e?.message || e}`
  943. )
  944. }
  945. this.log(traceId, 'DEAD', '进入死信队列')
  946. }
  947. try {
  948. await this.sendResult(channel, {
  949. id,
  950. success: false,
  951. error: err.message
  952. })
  953. } catch (e) {
  954. this.logger.error(
  955. `[${traceId}] 结果投递失败(忽略):${e?.message || e}`
  956. )
  957. }
  958. safeAck()
  959. }
  960. }
  961. const ok = await channel.consume(this.taskQueue, handleTaskMessage, { noAck: false })
  962. this._consumeTag = ok?.consumerTag || null
  963. }
  964. async sendResult(channel, data) {
  965. // 结果队列同样可能因断线导致 channel 关闭,这里用安全投递兜底
  966. await mq.sendToQueueSafe(
  967. this.channelName,
  968. this.resultQueue,
  969. Buffer.from(JSON.stringify(data)),
  970. { persistent: true, contentType: 'application/json' }
  971. )
  972. }
  973. async stop() {
  974. this.running = false
  975. await mq.close()
  976. this.logger.info('哪吒乐跑 Worker 已停止')
  977. }
  978. }
  979. module.exports = Worker