Worker.js 40 KB

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