Worker.js 45 KB

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