Worker.js 40 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063
  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. })
  572. }
  573. }
  574. }
  575. } catch (e) {
  576. this.logger.warn(`[${traceId}] 目标达成处理失败:${e.message || e}`)
  577. }
  578. if (ctx.channel) {
  579. await this.enqueueTask(ctx.channel, 'lepao.sendNotice', {
  580. account,
  581. success: true,
  582. data: {
  583. distance: officialKm,
  584. time: Number(latest.useTime) || 0,
  585. record_failed_reason: '',
  586. refundedKm: refundKm
  587. },
  588. traceId
  589. }, { id: `${traceId}:notice:success:finalize` })
  590. }
  591. return { traceId, finalized: true, officialKm, refundKm }
  592. })
  593. this.register('lepao.sendNotice', async (req, ctx) => {
  594. const { account, success, data, reason, traceId } = req || {}
  595. if (!account) {
  596. throw new Error('发送通知失败:缺少 account')
  597. }
  598. const emailSql = `
  599. SELECT
  600. a.name,
  601. a.email,
  602. a.target_count,
  603. a.term_num,
  604. a.total_num,
  605. a.notice_type,
  606. e.bot_umo
  607. FROM
  608. lepao_account a
  609. LEFT JOIN
  610. lepao_extra e
  611. ON
  612. a.student_num = e.student_num
  613. WHERE
  614. a.student_num = ?
  615. `
  616. const rows = await db.query(emailSql, [account])
  617. if (!rows || rows.length === 0) {
  618. throw new Error('发送通知失败:未找到用户通知配置')
  619. }
  620. const user = rows[0]
  621. const noticeType = user.notice_type || 'none'
  622. let runZoneName = data?.run_zone_name
  623. if (!runZoneName && success) {
  624. try {
  625. const z = await db.query(
  626. `
  627. SELECT p.run_zone_name
  628. FROM lepao_record r
  629. LEFT JOIN path_data p ON r.path_id = p.id
  630. WHERE r.lepao_account = ?
  631. ORDER BY r.id DESC
  632. LIMIT 1
  633. `,
  634. [account]
  635. )
  636. runZoneName = z?.length ? z[0].run_zone_name : null
  637. } catch (e) {
  638. this.logger.warn(`[${traceId}] 查询跑区失败:${e.message || e}`)
  639. }
  640. }
  641. const payload = success
  642. ? {
  643. ...(data && typeof data === 'object' ? data : {}),
  644. type: 'lepao_success',
  645. umo: user.bot_umo,
  646. run_zone_name: runZoneName,
  647. month_km: Number(user.term_num) || 0,
  648. total_km: Number(user.total_num) || 0,
  649. target_km: Number(user.target_count) || 0,
  650. name: user.name,
  651. account,
  652. traceId
  653. }
  654. : {
  655. type: 'lepao_fail',
  656. umo: user.bot_umo,
  657. name: user.name,
  658. account,
  659. reason,
  660. traceId
  661. }
  662. if (noticeType === 'bot' && user.bot_umo) {
  663. const ch = await mq.getChannel(this.noticeQueue)
  664. await ch.assertQueue(this.noticeQueue, { durable: true })
  665. await mq.sendToQueueSafe(
  666. this.noticeQueue,
  667. this.noticeQueue,
  668. Buffer.from(JSON.stringify(payload)),
  669. { persistent: true, contentType: 'application/json' }
  670. )
  671. return { delivered: true, via: 'bot' }
  672. }
  673. if (noticeType === 'email' && user.email) {
  674. if (success) {
  675. await EmailTemplate.lepaoSuccess(user.email, payload)
  676. return { delivered: true, via: 'email' }
  677. }
  678. await EmailTemplate.lepaoFail(user.email, {
  679. name: user.name,
  680. account,
  681. reason: reason || '系统繁忙,请联系客服或稍后再试',
  682. traceId
  683. })
  684. return { delivered: true, via: 'email' }
  685. }
  686. return { delivered: false, via: 'none' }
  687. })
  688. this.register('lepao.consumeCount', async (req, ctx) => {
  689. const account = req?.account
  690. const uuid = req?.uuid
  691. const amountKm = this.roundKm(req?.amountKm ?? 1)
  692. if (!uuid) {
  693. throw new Error('扣减乐跑公里失败:缺少 uuid')
  694. }
  695. if (!(amountKm > 0)) {
  696. throw new Error('扣减乐跑公里失败:amountKm 无效')
  697. }
  698. const baseKey = `${ctx?.taskId || ctx?.traceId || account || uuid}`
  699. const consumeKey = jkesRedisKeys.consume(baseKey)
  700. const existed = await Redis.get(consumeKey)
  701. if (existed) {
  702. return true
  703. }
  704. this.logger.info(`${account || uuid}开始扣减乐跑公里 ${amountKm}km`)
  705. const useLepaoCountSql =
  706. 'UPDATE users SET lepao_count = ROUND(lepao_count - ?, 2) WHERE uuid = ? AND lepao_count >= ?'
  707. const r = await db.query(useLepaoCountSql, [amountKm, uuid, amountKm])
  708. if (!r || r.affectedRows !== 1) {
  709. throw new Error(`扣减乐跑公里失败:余额不足(需 ${amountKm}km)`)
  710. }
  711. this.logger.info(`${account || uuid}扣减乐跑公里完成`)
  712. await Redis.set(consumeKey, '1', { EX: 3600 })
  713. return true
  714. })
  715. this.register('lepao.refundCount', async (req, ctx) => {
  716. const account = req?.account
  717. const uuid = req?.uuid
  718. const amountKm = this.roundKm(req?.amountKm ?? 0)
  719. if (!uuid) {
  720. return true
  721. }
  722. if (!(amountKm > 0)) return true
  723. const baseKey = `${ctx?.taskId || ctx?.traceId || account || uuid}`
  724. const consumeKey = jkesRedisKeys.consume(baseKey)
  725. const refundKey = jkesRedisKeys.refund(baseKey)
  726. const consumed = await Redis.get(consumeKey)
  727. if (!consumed) {
  728. return true
  729. }
  730. const refunded = await Redis.get(refundKey)
  731. if (refunded) {
  732. return true
  733. }
  734. this.logger.info(`${account || uuid}开始返还乐跑公里 ${amountKm}km`)
  735. const sql = 'UPDATE users SET lepao_count = ROUND(lepao_count + ?, 2) WHERE uuid = ?'
  736. const r = await db.query(sql, [amountKm, uuid])
  737. if (!r || r.affectedRows !== 1) {
  738. throw new Error('返还乐跑公里失败:数据库更新失败')
  739. }
  740. this.logger.info(`${account || uuid}返还乐跑公里完成`)
  741. await Redis.set(refundKey, '1', { EX: 3600 })
  742. return true
  743. })
  744. this.register('lepao.getUserData', async (req, ctx) => {
  745. const account = req.account
  746. this.logger.info(`${account}开始获取用户数据`)
  747. const accountSql = `
  748. SELECT
  749. u.uuid,
  750. u.lepao_count,
  751. l.create_user,
  752. l.name,
  753. l.student_num,
  754. l.area,
  755. l.sex,
  756. l.state,
  757. l.token,
  758. l.userAgent,
  759. l.deviceModel,
  760. l.notice_type,
  761. l.email,
  762. e.bot_account
  763. FROM
  764. lepao_account l
  765. LEFT JOIN
  766. users u
  767. ON
  768. l.create_user = u.uuid
  769. LEFT JOIN
  770. lepao_extra e
  771. ON
  772. l.student_num = e.student_num
  773. WHERE
  774. l.student_num = ?
  775. `
  776. const rows = await db.query(accountSql, [account])
  777. if (!rows || rows.length === 0) {
  778. this.logger.error(`${account}无法获取账号数据`)
  779. throw new Error('无法获取账号数据,请联系客服或稍后再试')
  780. }
  781. let userData = rows[0]
  782. if (!userData.create_user || !userData.uuid) {
  783. this.logger.warn(`${account}账号状态异常`)
  784. throw new Error('当前账号状态异常,请联系客服')
  785. }
  786. if (userData.state !== 1) {
  787. this.logger.warn(`${account}登录状态异常 state=${userData.state}`)
  788. throw new Error('乐跑账号登录已过期,请尝试使用登录器重新登录')
  789. }
  790. if (Number(userData.lepao_count) <= 0) {
  791. this.logger.warn(`${account}乐跑公里余额不足`)
  792. throw new Error('用户乐跑公里余额不足,请购买后重试!')
  793. }
  794. if (!userData.userAgent) {
  795. userData.userAgent =
  796. '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'
  797. }
  798. if (!userData.deviceModel) userData.deviceModel = 'unknown'
  799. return userData
  800. })
  801. }
  802. async start() {
  803. if (this.running) return
  804. this.running = true
  805. this.logger.info('Worker 启动中(JKES)...')
  806. try {
  807. this.initHandlers()
  808. await this.startConsumeLoop()
  809. this.logger.info('哪吒乐跑 Worker 启动成功(JKES)')
  810. } catch (err) {
  811. this.logger.error('哪吒乐跑 Worker 启动失败: ' + (err.stack || err))
  812. }
  813. }
  814. async startConsumeLoop() {
  815. if (!this.running) return
  816. if (this._consuming) return
  817. this._consuming = true
  818. const channel = await mq.getChannel(this.channelName)
  819. channel.on('close', () => {
  820. // close 事件可能重复触发;这里仅触发一次重启
  821. if (!this.running) return
  822. this._consuming = false
  823. this.logger.warn('Worker channel 已关闭,准备重启消费')
  824. setTimeout(() => {
  825. this.startConsumeLoop().catch((e) => {
  826. this.logger.error('重启 Worker 消费失败: ' + (e?.stack || e))
  827. })
  828. }, 1000)
  829. })
  830. await channel.prefetch(5)
  831. await assertRunforgeTaskIngress(channel, this.logger)
  832. await channel.assertQueue(this.resultQueue, { durable: true })
  833. await channel.assertQueue(this.deadQueue, { durable: true })
  834. const handleTaskMessage = async (msg) => {
  835. if (!msg) return
  836. let content
  837. try {
  838. content = JSON.parse(msg.content.toString())
  839. } catch {
  840. return channel.ack(msg)
  841. }
  842. const { id, type, data, retry = 0 } = content
  843. const traceId = this.traceId()
  844. const handler = this.handlers[type]
  845. if (!handler) {
  846. this.log(traceId, 'ERROR', '未知任务', { type })
  847. return channel.ack(msg)
  848. }
  849. try {
  850. const runMs =
  851. type === 'lepao.startRun'
  852. ? 3600000
  853. : type === 'lepao.finalizeRunSync'
  854. ? 4 * 3600000
  855. : undefined
  856. const result = await this.withTimeout(
  857. handler(data, { traceId, channel, taskId: id }),
  858. type,
  859. runMs
  860. )
  861. await this.sendResult(channel, {
  862. id,
  863. success: true,
  864. result
  865. })
  866. this.log(traceId, 'DONE', `任务完成 ${type}`)
  867. channel.ack(msg)
  868. } catch (err) {
  869. this.logErr(traceId, `任务失败 ${type}`, err)
  870. if (err?.loginExpired) {
  871. const account = data?.account || data?.student_num || data?.studentNum
  872. await this.markLoginExpired(account)
  873. }
  874. if (retry < this.maxRetry && this.isRetryableTaskError(err)) {
  875. try {
  876. await mq.sendToQueueSafe(
  877. this.channelName,
  878. this.taskQueue,
  879. Buffer.from(
  880. JSON.stringify({
  881. ...content,
  882. retry: retry + 1
  883. })
  884. ),
  885. { persistent: true, contentType: 'application/json' }
  886. )
  887. } catch (e) {
  888. this.logger.error(
  889. `[${traceId}] 重试消息投递失败(将直接 ack,避免进程崩溃):${e?.message || e}`
  890. )
  891. }
  892. this.log(traceId, 'RETRY', `重试第${retry + 1}次`)
  893. } else {
  894. try {
  895. await mq.sendToQueueSafe(
  896. this.channelName,
  897. this.deadQueue,
  898. Buffer.from(JSON.stringify(content)),
  899. { persistent: true, contentType: 'application/json' }
  900. )
  901. } catch (e) {
  902. this.logger.error(
  903. `[${traceId}] 死信投递失败(将直接 ack,避免进程崩溃):${e?.message || e}`
  904. )
  905. }
  906. this.log(traceId, 'DEAD', '进入死信队列')
  907. }
  908. try {
  909. await this.sendResult(channel, {
  910. id,
  911. success: false,
  912. error: err.message
  913. })
  914. } catch (e) {
  915. this.logger.error(
  916. `[${traceId}] 结果投递失败(忽略):${e?.message || e}`
  917. )
  918. }
  919. channel.ack(msg)
  920. }
  921. }
  922. const ok = await channel.consume(this.taskQueue, handleTaskMessage, { noAck: false })
  923. this._consumeTag = ok?.consumerTag || null
  924. }
  925. async sendResult(channel, data) {
  926. // 结果队列同样可能因断线导致 channel 关闭,这里用安全投递兜底
  927. await mq.sendToQueueSafe(
  928. this.channelName,
  929. this.resultQueue,
  930. Buffer.from(JSON.stringify(data)),
  931. { persistent: true, contentType: 'application/json' }
  932. )
  933. }
  934. async stop() {
  935. this.running = false
  936. await mq.close()
  937. this.logger.info('哪吒乐跑 Worker 已停止')
  938. }
  939. }
  940. module.exports = Worker