Worker.js 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948
  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. if (!recordDbId) {
  361. recordDbId = await this.createLepaoRecord({
  362. uuid: userData?.create_user,
  363. account: req.account,
  364. pathId: jkesPathId,
  365. pathData: jkesEnd.uploadedPayloadPoints || [],
  366. result: info || jkesEnd.endJson?.data || {},
  367. state: 1
  368. })
  369. } else {
  370. await this.updateLepaoRecord(recordDbId, {
  371. result: info || jkesEnd.endJson?.data || {},
  372. pathData: jkesEnd.uploadedPayloadPoints || [],
  373. state: 1
  374. })
  375. }
  376. const ok = isJkesRecordValidInCampus(info || {})
  377. if (!ok) {
  378. const reason =
  379. info?.dataStatus?.label || info?.status?.label || '跑步记录未记作校内有效'
  380. throw new Error(reason)
  381. }
  382. await this.writeSuccessRedis(req.account)
  383. const autoDoubleSlot =
  384. !manual && (req.autoDoubleSlot === true || req.autoDoubleSlot === 'true')
  385. const finalizeTask = {
  386. account: req.account,
  387. token: req.token,
  388. uuid: userData?.create_user,
  389. recordDbId,
  390. jkesRecordId: jkesEnd.recordId || info?.id,
  391. deductedKm,
  392. targetKm,
  393. autoDoubleSlot,
  394. traceId
  395. }
  396. if (ctx.channel) {
  397. try {
  398. await this.enqueueTask(ctx.channel, 'lepao.finalizeRunSync', finalizeTask, {
  399. id: `${traceId}:finalize:${req.account}`
  400. })
  401. } catch (e) {
  402. this.logger.warn(`[${traceId}] finalize 任务投递失败,改为同步执行:${e.message || e}`)
  403. await this.handlers['lepao.finalizeRunSync'](finalizeTask, ctx)
  404. }
  405. } else {
  406. await this.handlers['lepao.finalizeRunSync'](finalizeTask, ctx)
  407. }
  408. return { traceId, jkes: true, endJson: jkesEnd.endJson }
  409. } catch (err) {
  410. this.logger.error(`[${traceId}] 乐跑流程失败:`, err)
  411. try {
  412. await this.handlers['lepao.refundCount'](
  413. {
  414. account: req.account,
  415. uuid: userData?.create_user,
  416. amountKm: deductedKm
  417. },
  418. ctx
  419. )
  420. } catch (e) {
  421. this.logger.error(`[${traceId}] 返还乐跑公里失败:${e.stack || e}`)
  422. }
  423. if (recordDbId) {
  424. try {
  425. await this.updateLepaoRecord(recordDbId, {
  426. result: { phase: 'error', reason: err.message || '未知错误' },
  427. state: 3
  428. })
  429. } catch (e) {
  430. this.logger.error(`[${traceId}] 更新乐跑记录失败:${e.stack || e}`)
  431. }
  432. }
  433. if (ctx.channel) {
  434. await this.enqueueTask(ctx.channel, 'lepao.sendNotice', {
  435. account: req.account,
  436. success: false,
  437. reason: err.message || '未知错误',
  438. traceId
  439. }, { id: `${traceId}:notice:fail` })
  440. }
  441. throw err
  442. } finally {
  443. if (req?.account) {
  444. await Redis.del(jkesRedisKeys.lepaoProgress(req.account))
  445. }
  446. }
  447. })
  448. this.register('lepao.finalizeRunSync', async (req, ctx) => {
  449. const traceId = req?.traceId || ctx?.traceId || this.traceId()
  450. const {
  451. account,
  452. token,
  453. uuid,
  454. recordDbId,
  455. jkesRecordId,
  456. deductedKm,
  457. targetKm,
  458. autoDoubleSlot
  459. } = req || {}
  460. if (!account || !token || !recordDbId || !jkesRecordId) {
  461. throw new Error('finalizeRunSync 参数缺失')
  462. }
  463. const {
  464. fetchJkesRecordById,
  465. isJkesRecordFullySynced,
  466. isJkesRecordValidInCampus,
  467. recordDistanceKm
  468. } = require('../../plugin/jkes/stats')
  469. const { recordSuccess } = require('../../plugin/jkes/monthPolicy')
  470. const pollCount = 40
  471. const pollIntervalMs = 90 * 1000
  472. let latest = null
  473. let synced = false
  474. for (let i = 1; i <= pollCount; i++) {
  475. latest = await fetchJkesRecordById(token, jkesRecordId, 10)
  476. if (latest && isJkesRecordFullySynced(latest)) {
  477. synced = true
  478. break
  479. }
  480. if (i < pollCount) {
  481. await this.sleep(pollIntervalMs)
  482. }
  483. }
  484. if (!latest || !isJkesRecordValidInCampus(latest)) {
  485. await this.updateLepaoRecord(recordDbId, {
  486. result: latest || { phase: 'finalize_failed', reason: '记录未校内有效' },
  487. state: 3
  488. })
  489. await this.handlers['lepao.refundCount'](
  490. {
  491. account,
  492. uuid,
  493. amountKm: this.roundKm(deductedKm || targetKm || 0)
  494. },
  495. { ...ctx, taskId: `${ctx?.taskId || traceId}:finalize_refund_full` }
  496. )
  497. if (ctx.channel) {
  498. await this.enqueueTask(ctx.channel, 'lepao.sendNotice', {
  499. account,
  500. success: false,
  501. reason: '乐跑记录未同步为校内有效,已退还预扣公里',
  502. traceId
  503. }, { id: `${traceId}:notice:fail:finalize` })
  504. }
  505. return { traceId, finalized: false, refunded: true }
  506. }
  507. if (!synced) {
  508. await this.updateLepaoRecord(recordDbId, {
  509. result: latest,
  510. state: 1
  511. })
  512. const err = new Error('官方记录尚未完全同步(distance/speed)')
  513. err.retryable = true
  514. throw err
  515. }
  516. const officialKmRaw = this.roundKm(recordDistanceKm(latest))
  517. const officialKm = officialKmRaw > 0 ? officialKmRaw : this.roundKm(targetKm || 0)
  518. const preDeduct = this.roundKm(deductedKm || targetKm || 0)
  519. const refundKm = this.roundKm(Math.max(0, preDeduct - officialKm))
  520. if (refundKm > 0) {
  521. await this.handlers['lepao.refundCount'](
  522. {
  523. account,
  524. uuid,
  525. amountKm: refundKm
  526. },
  527. { ...ctx, taskId: `${ctx?.taskId || traceId}:finalize_refund_over` }
  528. )
  529. }
  530. await this.updateLepaoRecord(recordDbId, {
  531. result: latest,
  532. state: 2
  533. })
  534. await recordSuccess(account, officialKm, { autoDoubleSlot: officialKm >= 2 && !!autoDoubleSlot })
  535. await this.syncRunCount({ account, student_id: account, token })
  536. if (ctx.channel) {
  537. await this.enqueueTask(ctx.channel, 'lepao.sendNotice', {
  538. account,
  539. success: true,
  540. data: {
  541. distance: officialKm,
  542. time: Number(latest.useTime) || 0,
  543. record_failed_reason: '',
  544. refundedKm: refundKm
  545. },
  546. traceId
  547. }, { id: `${traceId}:notice:success:finalize` })
  548. }
  549. return { traceId, finalized: true, officialKm, refundKm }
  550. })
  551. this.register('lepao.sendNotice', async (req, ctx) => {
  552. const { account, success, data, reason, traceId } = req || {}
  553. if (!account) {
  554. throw new Error('发送通知失败:缺少 account')
  555. }
  556. const emailSql = `
  557. SELECT
  558. a.name,
  559. a.email,
  560. a.target_count,
  561. a.notice_type,
  562. e.bot_umo
  563. FROM
  564. lepao_account a
  565. LEFT JOIN
  566. lepao_extra e
  567. ON
  568. a.student_num = e.student_num
  569. WHERE
  570. a.student_num = ?
  571. `
  572. const rows = await db.query(emailSql, [account])
  573. if (!rows || rows.length === 0) {
  574. throw new Error('发送通知失败:未找到用户通知配置')
  575. }
  576. const user = rows[0]
  577. const noticeType = user.notice_type || 'none'
  578. const payload = success
  579. ? {
  580. ...(data && typeof data === 'object' ? data : {}),
  581. type: 'lepao_success',
  582. umo: user.bot_umo,
  583. term_num: user.target_count ?? 0,
  584. name: user.name,
  585. account,
  586. traceId
  587. }
  588. : {
  589. type: 'lepao_fail',
  590. umo: user.bot_umo,
  591. name: user.name,
  592. account,
  593. reason,
  594. traceId
  595. }
  596. if (noticeType === 'bot' && user.bot_umo) {
  597. const ch = await mq.getChannel(this.noticeQueue)
  598. await ch.assertQueue(this.noticeQueue, { durable: true })
  599. ch.sendToQueue(
  600. this.noticeQueue,
  601. Buffer.from(JSON.stringify(payload)),
  602. {
  603. persistent: true,
  604. contentType: 'application/json'
  605. }
  606. )
  607. return { delivered: true, via: 'bot' }
  608. }
  609. if (noticeType === 'email' && user.email) {
  610. if (success) {
  611. await EmailTemplate.lepaoSuccess(user.email, payload)
  612. return { delivered: true, via: 'email' }
  613. }
  614. await EmailTemplate.lepaoFail(user.email, {
  615. name: user.name,
  616. account,
  617. reason: reason || '系统繁忙,请联系客服或稍后再试',
  618. traceId
  619. })
  620. return { delivered: true, via: 'email' }
  621. }
  622. return { delivered: false, via: 'none' }
  623. })
  624. this.register('lepao.consumeCount', async (req, ctx) => {
  625. const account = req?.account
  626. const uuid = req?.uuid
  627. const amountKm = this.roundKm(req?.amountKm ?? 1)
  628. if (!uuid) {
  629. throw new Error('扣减乐跑公里失败:缺少 uuid')
  630. }
  631. if (!(amountKm > 0)) {
  632. throw new Error('扣减乐跑公里失败:amountKm 无效')
  633. }
  634. const baseKey = `${ctx?.taskId || ctx?.traceId || account || uuid}`
  635. const consumeKey = jkesRedisKeys.consume(baseKey)
  636. const existed = await Redis.get(consumeKey)
  637. if (existed) {
  638. return true
  639. }
  640. this.logger.info(`${account || uuid}开始扣减乐跑公里 ${amountKm}km`)
  641. const useLepaoCountSql =
  642. 'UPDATE users SET lepao_count = ROUND(lepao_count - ?, 2) WHERE uuid = ? AND lepao_count >= ?'
  643. const r = await db.query(useLepaoCountSql, [amountKm, uuid, amountKm])
  644. if (!r || r.affectedRows !== 1) {
  645. throw new Error(`扣减乐跑公里失败:余额不足(需 ${amountKm}km)`)
  646. }
  647. this.logger.info(`${account || uuid}扣减乐跑公里完成`)
  648. await Redis.set(consumeKey, '1', { EX: 3600 })
  649. return true
  650. })
  651. this.register('lepao.refundCount', async (req, ctx) => {
  652. const account = req?.account
  653. const uuid = req?.uuid
  654. const amountKm = this.roundKm(req?.amountKm ?? 0)
  655. if (!uuid) {
  656. return true
  657. }
  658. if (!(amountKm > 0)) return true
  659. const baseKey = `${ctx?.taskId || ctx?.traceId || account || uuid}`
  660. const consumeKey = jkesRedisKeys.consume(baseKey)
  661. const refundKey = jkesRedisKeys.refund(baseKey)
  662. const consumed = await Redis.get(consumeKey)
  663. if (!consumed) {
  664. return true
  665. }
  666. const refunded = await Redis.get(refundKey)
  667. if (refunded) {
  668. return true
  669. }
  670. this.logger.info(`${account || uuid}开始返还乐跑公里 ${amountKm}km`)
  671. const sql = 'UPDATE users SET lepao_count = ROUND(lepao_count + ?, 2) WHERE uuid = ?'
  672. const r = await db.query(sql, [amountKm, uuid])
  673. if (!r || r.affectedRows !== 1) {
  674. throw new Error('返还乐跑公里失败:数据库更新失败')
  675. }
  676. this.logger.info(`${account || uuid}返还乐跑公里完成`)
  677. await Redis.set(refundKey, '1', { EX: 3600 })
  678. return true
  679. })
  680. this.register('lepao.getUserData', async (req, ctx) => {
  681. const account = req.account
  682. this.logger.info(`${account}开始获取用户数据`)
  683. const accountSql = `
  684. SELECT
  685. u.uuid,
  686. u.lepao_count,
  687. l.create_user,
  688. l.name,
  689. l.student_num,
  690. l.area,
  691. l.sex,
  692. l.state,
  693. l.token,
  694. l.userAgent,
  695. l.deviceModel,
  696. l.notice_type,
  697. l.email,
  698. e.bot_account
  699. FROM
  700. lepao_account l
  701. LEFT JOIN
  702. users u
  703. ON
  704. l.create_user = u.uuid
  705. LEFT JOIN
  706. lepao_extra e
  707. ON
  708. l.student_num = e.student_num
  709. WHERE
  710. l.student_num = ?
  711. `
  712. const rows = await db.query(accountSql, [account])
  713. if (!rows || rows.length === 0) {
  714. this.logger.error(`${account}无法获取账号数据`)
  715. throw new Error('无法获取账号数据,请联系客服或稍后再试')
  716. }
  717. let userData = rows[0]
  718. if (!userData.create_user || !userData.uuid) {
  719. this.logger.warn(`${account}账号状态异常`)
  720. throw new Error('当前账号状态异常,请联系客服')
  721. }
  722. if (userData.state !== 1) {
  723. this.logger.warn(`${account}登录状态异常 state=${userData.state}`)
  724. throw new Error('乐跑账号登录已过期,请尝试使用登录器重新登录')
  725. }
  726. if (Number(userData.lepao_count) <= 0) {
  727. this.logger.warn(`${account}乐跑公里余额不足`)
  728. throw new Error('用户乐跑公里余额不足,请购买后重试!')
  729. }
  730. if (!userData.userAgent) {
  731. userData.userAgent =
  732. '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'
  733. }
  734. if (!userData.deviceModel) userData.deviceModel = 'unknown'
  735. return userData
  736. })
  737. }
  738. async start() {
  739. if (this.running) return
  740. this.running = true
  741. this.logger.info('Worker 启动中(JKES)...')
  742. try {
  743. this.initHandlers()
  744. const channel = await mq.getChannel(this.channelName)
  745. await channel.prefetch(5)
  746. await assertRunforgeTaskIngress(channel, this.logger)
  747. await channel.assertQueue(this.resultQueue, { durable: true })
  748. await channel.assertQueue(this.deadQueue, { durable: true })
  749. const handleTaskMessage = async (msg) => {
  750. if (!msg) return
  751. let content
  752. try {
  753. content = JSON.parse(msg.content.toString())
  754. } catch {
  755. return channel.ack(msg)
  756. }
  757. const { id, type, data, retry = 0 } = content
  758. const traceId = this.traceId()
  759. const handler = this.handlers[type]
  760. if (!handler) {
  761. this.log(traceId, 'ERROR', '未知任务', { type })
  762. return channel.ack(msg)
  763. }
  764. try {
  765. const runMs =
  766. type === 'lepao.startRun'
  767. ? 3600000
  768. : type === 'lepao.finalizeRunSync'
  769. ? 4 * 3600000
  770. : undefined
  771. const result = await this.withTimeout(
  772. handler(data, { traceId, channel, taskId: id }),
  773. type,
  774. runMs
  775. )
  776. await this.sendResult(channel, {
  777. id,
  778. success: true,
  779. result
  780. })
  781. this.log(traceId, 'DONE', `任务完成 ${type}`)
  782. channel.ack(msg)
  783. } catch (err) {
  784. this.logErr(traceId, `任务失败 ${type}`, err)
  785. if (retry < this.maxRetry && this.isRetryableTaskError(err)) {
  786. await channel.sendToQueue(
  787. this.taskQueue,
  788. Buffer.from(
  789. JSON.stringify({
  790. ...content,
  791. retry: retry + 1
  792. })
  793. ),
  794. { persistent: true }
  795. )
  796. this.log(traceId, 'RETRY', `重试第${retry + 1}次`)
  797. } else {
  798. await channel.sendToQueue(
  799. this.deadQueue,
  800. Buffer.from(JSON.stringify(content)),
  801. { persistent: true }
  802. )
  803. this.log(traceId, 'DEAD', '进入死信队列')
  804. }
  805. await this.sendResult(channel, {
  806. id,
  807. success: false,
  808. error: err.message
  809. })
  810. channel.ack(msg)
  811. }
  812. }
  813. await channel.consume(this.taskQueue, handleTaskMessage, { noAck: false })
  814. this.logger.info('RunForge Worker 启动成功(JKES)')
  815. } catch (err) {
  816. this.logger.error('RunForge Worker 启动失败: ' + err.stack)
  817. }
  818. }
  819. async sendResult(channel, data) {
  820. channel.sendToQueue(
  821. this.resultQueue,
  822. Buffer.from(JSON.stringify(data)),
  823. { persistent: true }
  824. )
  825. }
  826. async stop() {
  827. this.running = false
  828. await mq.close()
  829. this.logger.info('RunForge Worker 已停止')
  830. }
  831. }
  832. module.exports = Worker