Worker.js 38 KB

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