TaskScheduler.js 65 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479
  1. const crypto = require('crypto')
  2. const bcryptjs = require('bcryptjs')
  3. const config = require('../../config.json')
  4. const db = require('../../plugin/DataBase/db')
  5. const Redis = require('../../plugin/DataBase/Redis')
  6. const Logger = require('../Logger')
  7. const TASK_STATUS = {
  8. PAUSED: 'paused',
  9. PENDING: 'pending',
  10. ASSIGNED: 'assigned',
  11. RUNNING: 'running',
  12. SUCCESS: 'success',
  13. FAILED: 'failed',
  14. CANCELLED: 'cancelled'
  15. }
  16. const REPORT_LOG_EVENTS = new Set([
  17. 'request_result',
  18. 'progress_snapshot',
  19. 'grab_success',
  20. 'grab_fail'
  21. ])
  22. class TaskScheduler {
  23. constructor(options = {}) {
  24. this.leaseMs = options.leaseMs || config.qk?.leaseMs || 90 * 1000
  25. this.heartbeatTtlSeconds = options.heartbeatTtlSeconds || config.qk?.heartbeatTtlSeconds || 45
  26. this.pullLockTtlSeconds = options.pullLockTtlSeconds || 5
  27. this.staleTaskMs = options.staleTaskMs || config.qk?.staleTaskMs || 60 * 60 * 1000
  28. this.memPerSlotMb = options.memPerSlotMb || config.qk?.memPerSlotMb || 3072
  29. this.memReserveMb = options.memReserveMb || config.qk?.memReserveMb || 1024
  30. this.maxSlotsCap = options.maxSlotsCap || config.qk?.maxSlotsCap || 10
  31. this.logger = options.logger || new Logger()
  32. }
  33. calculateMaxSlots(profile = {}) {
  34. const freeMb = Math.max(0, Number(profile.free_mem_mb) || 0)
  35. const totalMb = Math.max(0, Number(profile.total_mem_mb) || 0)
  36. const threads = Math.max(1, Number(profile.cpu_threads) || 1)
  37. const allocatableFreeMb = Math.max(0, freeMb - this.memReserveMb)
  38. const allocatableTotalMb = Math.max(0, totalMb - this.memReserveMb)
  39. const byFreeMem = Math.floor(allocatableFreeMb / this.memPerSlotMb)
  40. const byTotalMem = Math.floor(allocatableTotalMb / this.memPerSlotMb)
  41. const byCpu = Math.floor(threads * 0.8)
  42. const fallbackMem = totalMb > 0 ? byTotalMem : 1
  43. const byMem = freeMb > 0 ? Math.min(byFreeMem, byTotalMem) : fallbackMem
  44. return Math.max(1, Math.min(50, this.maxSlotsCap, byMem, byCpu))
  45. }
  46. resolveClientMaxSlots(client, payload = {}) {
  47. const fromPayload = this.calculateMaxSlots({
  48. free_mem_mb: payload.free_mem_mb ?? client.free_mem_mb,
  49. total_mem_mb: payload.total_mem_mb ?? client.total_mem_mb,
  50. cpu_threads: payload.cpu_threads ?? client.cpu_threads
  51. })
  52. const reported = Number(payload.max_slots || client.max_slots || 0)
  53. if (!reported) return fromPayload
  54. return Math.max(1, Math.min(reported, fromPayload))
  55. }
  56. getClientAvailableSlots(client, payload = {}) {
  57. const maxSlots = this.resolveClientMaxSlots(client, payload)
  58. const currentSlots = Math.max(0, Number(payload.current_slots ?? client.current_slots ?? 0))
  59. return Math.max(0, maxSlots - currentSlots)
  60. }
  61. getInFlightTaskStatuses() {
  62. return [TASK_STATUS.ASSIGNED, TASK_STATUS.RUNNING]
  63. }
  64. /** 同一学号在单次拉取中只保留最早创建的一条待分配任务 */
  65. pickPullableTasks(rows, limit) {
  66. const picked = []
  67. const seenStudentNums = new Set()
  68. for (const row of rows || []) {
  69. const studentNum = String(row.student_num || '').trim()
  70. if (!studentNum || seenStudentNums.has(studentNum)) {
  71. continue
  72. }
  73. seenStudentNums.add(studentNum)
  74. picked.push(row)
  75. if (picked.length >= limit) {
  76. break
  77. }
  78. }
  79. return picked
  80. }
  81. async countOnlineClients() {
  82. const now = Date.now()
  83. const threshold = now - this.heartbeatTtlSeconds * 1000
  84. const rows = await db.query(
  85. `SELECT COUNT(*) AS total FROM qk_client
  86. WHERE enabled = 1 AND online = 1
  87. AND last_heartbeat_at IS NOT NULL AND last_heartbeat_at >= ?`,
  88. [threshold]
  89. )
  90. return Number(rows?.[0]?.total || 0)
  91. }
  92. safeStringify(obj) {
  93. const seen = new WeakSet()
  94. return JSON.stringify(obj, (key, value) => {
  95. if (typeof value === 'object' && value !== null) {
  96. if (seen.has(value)) return '[Circular]'
  97. seen.add(value)
  98. }
  99. return value
  100. })
  101. }
  102. sanitizeForLog(payload) {
  103. if (!payload || typeof payload !== 'object') {
  104. return payload
  105. }
  106. const copy = Array.isArray(payload) ? [...payload] : { ...payload }
  107. for (const key of ['password', 'pass', 'password_enc', 'client_secret']) {
  108. if (key in copy) {
  109. copy[key] = '***'
  110. }
  111. }
  112. return copy
  113. }
  114. buildLogPrefix(tag, ctx = {}) {
  115. const parts = ['[QK]', `[${tag}]`]
  116. if (ctx.taskId) parts.push(`[taskId=${ctx.taskId}]`)
  117. if (ctx.clientId) parts.push(`[clientId=${ctx.clientId}]`)
  118. if (ctx.uuid) parts.push(`[uuid=${ctx.uuid}]`)
  119. return parts.join('')
  120. }
  121. logInfo(tag, message, ctx = {}, data = null) {
  122. const prefix = this.buildLogPrefix(tag, ctx)
  123. const suffix = data != null ? ` ${this.safeStringify(this.sanitizeForLog(data))}` : ''
  124. this.logger.info(`${prefix} ${message}${suffix}`)
  125. }
  126. logWarn(tag, message, ctx = {}, data = null) {
  127. const prefix = this.buildLogPrefix(tag, ctx)
  128. const suffix = data != null ? ` ${this.safeStringify(this.sanitizeForLog(data))}` : ''
  129. this.logger.warn(`${prefix} ${message}${suffix}`)
  130. }
  131. logError(tag, message, ctx = {}, err = null) {
  132. const prefix = this.buildLogPrefix(tag, ctx)
  133. const suffix = err ? ` ${err.stack || err}` : ''
  134. this.logger.error(`${prefix} ${message}${suffix}`)
  135. }
  136. getPasswordKey() {
  137. const source = process.env.QK_PASSWORD_KEY || config.qk?.passwordAesKey || config.database?.password || 'runforge-qk-default-key'
  138. return crypto.createHash('sha256').update(String(source)).digest()
  139. }
  140. encryptPassword(password) {
  141. const iv = crypto.randomBytes(16)
  142. const cipher = crypto.createCipheriv('aes-256-cbc', this.getPasswordKey(), iv)
  143. let encrypted = cipher.update(String(password), 'utf8', 'base64')
  144. encrypted += cipher.final('base64')
  145. return `${iv.toString('base64')}:${encrypted}`
  146. }
  147. decryptPassword(encrypted) {
  148. const [ivText, payload] = String(encrypted || '').split(':')
  149. if (!ivText || !payload) {
  150. return ''
  151. }
  152. const decipher = crypto.createDecipheriv('aes-256-cbc', this.getPasswordKey(), Buffer.from(ivText, 'base64'))
  153. let decrypted = decipher.update(payload, 'base64', 'utf8')
  154. decrypted += decipher.final('utf8')
  155. return decrypted
  156. }
  157. normalizeArray(value) {
  158. if (Array.isArray(value)) {
  159. return value.map(item => String(item).trim()).filter(Boolean)
  160. }
  161. if (typeof value === 'string') {
  162. const trimmed = value.trim()
  163. if (!trimmed) {
  164. return []
  165. }
  166. try {
  167. const parsed = JSON.parse(trimmed)
  168. if (Array.isArray(parsed)) {
  169. return parsed.map(item => String(item).trim()).filter(Boolean)
  170. }
  171. } catch (_) {
  172. return trimmed.split(/[\n,,]/).map(item => item.trim()).filter(Boolean)
  173. }
  174. }
  175. return []
  176. }
  177. countTaskTargets(courses = [], courseGroups = []) {
  178. return this.normalizeArray(courses).length + this.normalizeArray(courseGroups).length
  179. }
  180. getMinTaskInterval(totalCount) {
  181. return totalCount >= 5 ? 500 : 200
  182. }
  183. validateTaskCoursesAndInterval(courses, courseGroups, intervalMs) {
  184. const normalizedCourses = this.normalizeArray(courses)
  185. const normalizedGroups = this.normalizeArray(courseGroups)
  186. const totalCount = normalizedCourses.length + normalizedGroups.length
  187. if (totalCount <= 0) {
  188. throw new Error('至少需要填写一门课程或一个课程分组')
  189. }
  190. if (totalCount > 10) {
  191. throw new Error('每个任务最多选择10门课程或分组')
  192. }
  193. const minInterval = this.getMinTaskInterval(totalCount)
  194. const safeInterval = Number(intervalMs)
  195. if (!Number.isFinite(safeInterval) || safeInterval < minInterval || safeInterval > 10000) {
  196. throw new Error(`当前共 ${totalCount} 个抢课目标,间隔需在 ${minInterval}-10000ms 之间`)
  197. }
  198. return {
  199. courses: normalizedCourses,
  200. courseGroups: normalizedGroups,
  201. intervalMs: safeInterval,
  202. totalCount,
  203. minInterval
  204. }
  205. }
  206. serializeTask(row, includeSecret = false) {
  207. const result = { ...row }
  208. result.enable_ggxxk = Number(result.enable_ggxxk) === 1
  209. result.courses = this.normalizeArray(result.courses)
  210. result.course_groups = this.normalizeArray(result.course_groups)
  211. if (typeof result.result_json === 'string' && result.result_json) {
  212. try {
  213. result.result_json = JSON.parse(result.result_json)
  214. } catch (_) {}
  215. }
  216. result.jx0502zbid = row.batch_jx0502zbid || row.jx0502zbid || ''
  217. result.batch_name = row.batch_name || ''
  218. if (row.batch_enabled !== undefined) {
  219. result.batch_enabled = Number(row.batch_enabled) === 1
  220. }
  221. delete result.batch_jx0502zbid
  222. if (includeSecret) {
  223. result.password = this.decryptPassword(result.password_enc)
  224. }
  225. delete result.password_enc
  226. return result
  227. }
  228. taskBatchJoinSql(alias = 't') {
  229. return `LEFT JOIN qk_batch b ON b.id = ${alias}.batch_id`
  230. }
  231. taskBatchSelectSql(alias = 't') {
  232. return `, b.name AS batch_name, b.jx0502zbid AS batch_jx0502zbid, b.enabled AS batch_enabled`
  233. }
  234. async getBatchById(batchId) {
  235. const rows = await db.query('SELECT * FROM qk_batch WHERE id = ?', [batchId])
  236. if (!rows || rows.length === 0) {
  237. throw new Error('抢课批次不存在')
  238. }
  239. return rows[0]
  240. }
  241. async requireEnabledBatch(batchId) {
  242. const batch = await this.getBatchById(batchId)
  243. if (!Number(batch.enabled)) {
  244. throw new Error('所选抢课批次未启用')
  245. }
  246. return batch
  247. }
  248. resolveTaskBatchId(payload = {}) {
  249. const batchId = Number(payload.batch_id || payload.batchId)
  250. if (!batchId) {
  251. throw new Error('请选择抢课批次')
  252. }
  253. return batchId
  254. }
  255. async releaseAssignedTask(task, now = Date.now()) {
  256. if (!task || ![TASK_STATUS.ASSIGNED, TASK_STATUS.RUNNING].includes(task.status)) {
  257. return false
  258. }
  259. if (task.assigned_client_id) {
  260. await this.decrementClientSlots(task.assigned_client_id, now)
  261. }
  262. return true
  263. }
  264. async pauseTasksByBatch(batchId, reason = '批次已停用,任务已收回') {
  265. const rows = await db.query(
  266. 'SELECT id, status, assigned_client_id FROM qk_task WHERE batch_id = ? AND status IN (?, ?, ?)',
  267. [batchId, TASK_STATUS.PENDING, TASK_STATUS.ASSIGNED, TASK_STATUS.RUNNING]
  268. )
  269. const now = Date.now()
  270. let count = 0
  271. for (const row of rows || []) {
  272. await this.releaseAssignedTask(row, now)
  273. const result = await db.query(
  274. `UPDATE qk_task SET status = ?, assigned_client_id = NULL, lease_expire_at = NULL,
  275. assigned_at = NULL, exclude_client_id = NULL, update_time = ? WHERE id = ? AND status IN (?, ?, ?)`,
  276. [TASK_STATUS.PAUSED, now, row.id, TASK_STATUS.PENDING, TASK_STATUS.ASSIGNED, TASK_STATUS.RUNNING]
  277. )
  278. if (result && result.affectedRows > 0) {
  279. count += 1
  280. await this.logTask(row.id, row.assigned_client_id, 'batch_paused', reason)
  281. }
  282. }
  283. if (count > 0) {
  284. this.logInfo('pauseTasksByBatch', reason, { batchId }, { affected: count })
  285. }
  286. return count
  287. }
  288. async redispatchTasksByBatch(batchId, reason = '批次 ID 已变更,任务已重新进入分配队列') {
  289. const rows = await db.query(
  290. 'SELECT id, status, assigned_client_id FROM qk_task WHERE batch_id = ? AND status IN (?, ?, ?)',
  291. [batchId, TASK_STATUS.PENDING, TASK_STATUS.ASSIGNED, TASK_STATUS.RUNNING]
  292. )
  293. const now = Date.now()
  294. let count = 0
  295. for (const row of rows || []) {
  296. if ([TASK_STATUS.ASSIGNED, TASK_STATUS.RUNNING].includes(row.status)) {
  297. await this.releaseAssignedTask(row, now)
  298. const result = await db.query(
  299. `UPDATE qk_task SET status = ?, assigned_client_id = NULL, lease_expire_at = NULL,
  300. assigned_at = NULL, exclude_client_id = NULL, update_time = ? WHERE id = ? AND status IN (?, ?)`,
  301. [TASK_STATUS.PENDING, now, row.id, TASK_STATUS.ASSIGNED, TASK_STATUS.RUNNING]
  302. )
  303. if (result && result.affectedRows > 0) {
  304. count += 1
  305. await this.logTask(row.id, row.assigned_client_id, 'batch_redispatch', reason)
  306. }
  307. }
  308. }
  309. if (count > 0) {
  310. this.logInfo('redispatchTasksByBatch', reason, { batchId }, { affected: count })
  311. }
  312. return count
  313. }
  314. serializeBatch(row) {
  315. return {
  316. id: row.id,
  317. name: row.name,
  318. jx0502zbid: row.jx0502zbid,
  319. enabled: Number(row.enabled) === 1,
  320. create_time: row.create_time,
  321. update_time: row.update_time
  322. }
  323. }
  324. async listBatches(options = {}) {
  325. const enabledOnly = !!options.enabledOnly
  326. const where = enabledOnly ? 'WHERE enabled = 1' : ''
  327. const rows = await db.query(`SELECT * FROM qk_batch ${where} ORDER BY update_time DESC, id DESC`)
  328. return (rows || []).map(row => this.serializeBatch(row))
  329. }
  330. async createBatch(payload = {}) {
  331. const name = String(payload.name || '').trim()
  332. const jx0502zbid = String(payload.jx0502zbid || '').trim()
  333. if (!name || !jx0502zbid) {
  334. throw new Error('批次名称和批次 ID 不能为空')
  335. }
  336. const now = Date.now()
  337. const result = await db.query(
  338. 'INSERT INTO qk_batch (name, jx0502zbid, enabled, create_time, update_time) VALUES (?, ?, ?, ?, ?)',
  339. [name, jx0502zbid, payload.enabled === false ? 0 : 1, now, now]
  340. )
  341. if (!result || result.affectedRows <= 0) {
  342. throw new Error('创建抢课批次失败')
  343. }
  344. this.logInfo('createBatch', '抢课批次已创建', { batchId: result.insertId }, { name, jx0502zbid })
  345. return result.insertId
  346. }
  347. async updateBatch(batchId, payload = {}) {
  348. const existing = await this.getBatchById(batchId)
  349. const name = payload.name !== undefined ? String(payload.name || '').trim() : existing.name
  350. const jx0502zbid = payload.jx0502zbid !== undefined ? String(payload.jx0502zbid || '').trim() : existing.jx0502zbid
  351. const enabled = payload.enabled !== undefined ? (payload.enabled ? 1 : 0) : Number(existing.enabled)
  352. if (!name || !jx0502zbid) {
  353. throw new Error('批次名称和批次 ID 不能为空')
  354. }
  355. const now = Date.now()
  356. const result = await db.query(
  357. 'UPDATE qk_batch SET name = ?, jx0502zbid = ?, enabled = ?, update_time = ? WHERE id = ?',
  358. [name, jx0502zbid, enabled, now, batchId]
  359. )
  360. if (!result || result.affectedRows <= 0) {
  361. throw new Error('更新抢课批次失败')
  362. }
  363. const disabledNow = Number(existing.enabled) === 1 && enabled === 0
  364. const idChanged = String(existing.jx0502zbid) !== jx0502zbid
  365. if (disabledNow) {
  366. await this.pauseTasksByBatch(batchId)
  367. } else if (idChanged && enabled === 1) {
  368. await this.redispatchTasksByBatch(batchId)
  369. }
  370. this.logInfo('updateBatch', '抢课批次已更新', { batchId }, {
  371. name,
  372. jx0502zbid,
  373. enabled: enabled === 1,
  374. disabledNow,
  375. idChanged
  376. })
  377. }
  378. async logTask(taskId, clientId, event, message = '', payload = null) {
  379. const sql = 'INSERT INTO qk_task_log (task_id, client_id, event, message, payload_json, create_time) VALUES (?, ?, ?, ?, ?, ?)'
  380. await db.query(sql, [
  381. taskId,
  382. clientId || null,
  383. event,
  384. message || '',
  385. payload ? JSON.stringify(payload) : null,
  386. Date.now()
  387. ])
  388. this.logInfo('taskLog', message || event, { taskId, clientId }, payload ? { event, ...this.sanitizeForLog(payload) } : { event })
  389. }
  390. serializeReportLog(row) {
  391. const result = { ...row }
  392. if (typeof result.payload_json === 'string' && result.payload_json) {
  393. try {
  394. result.payload_json = JSON.parse(result.payload_json)
  395. } catch (_) {}
  396. }
  397. return result
  398. }
  399. buildReportMessage(payload = {}) {
  400. if (payload.message) {
  401. return String(payload.message)
  402. }
  403. if (payload.error_msg) {
  404. return String(payload.error_msg)
  405. }
  406. if (payload.error) {
  407. return String(payload.error)
  408. }
  409. if (payload.success === true) {
  410. return payload.label ? `${payload.label} 成功` : '请求成功'
  411. }
  412. return payload.label ? `${payload.label} 失败` : '请求失败'
  413. }
  414. async assertClientTaskAccess(clientId, taskId) {
  415. const rows = await db.query(
  416. 'SELECT id, status, assigned_client_id FROM qk_task WHERE id = ?',
  417. [taskId]
  418. )
  419. if (!rows || rows.length === 0) {
  420. throw new Error('任务不存在')
  421. }
  422. const task = rows[0]
  423. if (task.assigned_client_id !== clientId) {
  424. throw new Error('任务不属于当前客户端')
  425. }
  426. if (![TASK_STATUS.ASSIGNED, TASK_STATUS.RUNNING].includes(task.status)) {
  427. throw new Error('任务当前状态不可上报')
  428. }
  429. return task
  430. }
  431. async reportProgress(clientId, clientSecret, payload = {}) {
  432. const client = await this.authenticateClient(clientId, clientSecret)
  433. if (!client) {
  434. throw new Error('客户端凭证无效')
  435. }
  436. const taskId = Number(payload.task_id || payload.id)
  437. if (!taskId) {
  438. throw new Error('缺少任务 ID')
  439. }
  440. const event = String(payload.event || 'request_result')
  441. if (!REPORT_LOG_EVENTS.has(event) || event === 'grab_success' || event === 'grab_fail') {
  442. throw new Error('不支持的上报类型')
  443. }
  444. const task = await this.assertClientTaskAccess(clientId, taskId)
  445. const message = this.buildReportMessage(payload)
  446. const now = Date.now()
  447. await this.logTask(taskId, clientId, event, message, payload)
  448. const updates = ['update_time = ?']
  449. const params = [now]
  450. if (task.status === TASK_STATUS.ASSIGNED) {
  451. updates.push('status = ?')
  452. params.push(TASK_STATUS.RUNNING)
  453. }
  454. if (payload.success !== true && message) {
  455. updates.push('error_msg = ?')
  456. params.push(message)
  457. }
  458. params.push(taskId, clientId)
  459. await db.query(
  460. `UPDATE qk_task SET ${updates.join(', ')} WHERE id = ? AND assigned_client_id = ?`,
  461. params
  462. )
  463. this.logInfo('reportProgress', '客户端上报抢课进度', { taskId, clientId }, {
  464. event,
  465. success: payload.success === true,
  466. message
  467. })
  468. return { task_id: taskId, event, message }
  469. }
  470. async createTask(uuid, payload) {
  471. const validated = this.validateTaskCoursesAndInterval(
  472. payload.courses || payload.COURSES,
  473. payload.course_groups || payload.COURSE_GROUPS,
  474. payload.interval_ms || payload.INTERVAL_MS || 500
  475. )
  476. const { courses, courseGroups, intervalMs } = validated
  477. const batchId = this.resolveTaskBatchId(payload)
  478. await this.requireEnabledBatch(batchId)
  479. const time = Date.now()
  480. const sql = `INSERT INTO qk_task
  481. (create_user, name, batch_id, jx0502zbid, student_num, password_enc, courses, course_groups, enable_ggxxk, interval_ms, status, create_time, update_time)
  482. VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`
  483. const result = await db.query(sql, [
  484. uuid,
  485. payload.name,
  486. batchId,
  487. '',
  488. payload.student_num || payload.user,
  489. this.encryptPassword(payload.password || payload.pass),
  490. JSON.stringify(courses),
  491. JSON.stringify(courseGroups),
  492. payload.enable_ggxxk || payload.ENABLE_GGXXK ? 1 : 0,
  493. intervalMs,
  494. TASK_STATUS.PAUSED,
  495. time,
  496. time
  497. ])
  498. if (!result || result.affectedRows <= 0) {
  499. throw new Error('创建抢课任务失败')
  500. }
  501. await this.logTask(result.insertId, null, 'created', '用户提交抢课任务(未开始)')
  502. this.logInfo('createTask', '抢课任务已创建', { taskId: result.insertId, uuid }, {
  503. name: payload.name,
  504. batch_id: batchId,
  505. student_num: payload.student_num || payload.user,
  506. courses_count: courses.length,
  507. course_groups_count: courseGroups.length,
  508. interval_ms: intervalMs,
  509. enable_ggxxk: !!(payload.enable_ggxxk || payload.ENABLE_GGXXK)
  510. })
  511. return result.insertId
  512. }
  513. async updateTask(uuid, taskId, payload) {
  514. const rows = await db.query('SELECT status FROM qk_task WHERE id = ? AND create_user = ?', [taskId, uuid])
  515. if (!rows || rows.length === 0) {
  516. throw new Error('任务不存在')
  517. }
  518. if (![TASK_STATUS.PAUSED, TASK_STATUS.FAILED, TASK_STATUS.CANCELLED].includes(rows[0].status)) {
  519. throw new Error('任务进行中或已分配,请先暂停后再修改')
  520. }
  521. const validated = this.validateTaskCoursesAndInterval(
  522. payload.courses || payload.COURSES,
  523. payload.course_groups || payload.COURSE_GROUPS,
  524. payload.interval_ms || payload.INTERVAL_MS || 500
  525. )
  526. const { courses, courseGroups, intervalMs } = validated
  527. const batchId = this.resolveTaskBatchId(payload)
  528. await this.requireEnabledBatch(batchId)
  529. const passwordSql = payload.password || payload.pass ? ', password_enc = ?' : ''
  530. const params = [
  531. payload.name,
  532. batchId,
  533. payload.student_num || payload.user,
  534. JSON.stringify(courses),
  535. JSON.stringify(courseGroups),
  536. payload.enable_ggxxk || payload.ENABLE_GGXXK ? 1 : 0,
  537. intervalMs,
  538. TASK_STATUS.PAUSED,
  539. Date.now()
  540. ]
  541. if (passwordSql) {
  542. params.splice(3, 0, this.encryptPassword(payload.password || payload.pass))
  543. }
  544. params.push(taskId, uuid)
  545. const sql = `UPDATE qk_task SET name = ?, batch_id = ?, student_num = ?${passwordSql}, courses = ?, course_groups = ?, enable_ggxxk = ?, interval_ms = ?, status = ?, jx0502zbid = '', update_time = ?, assigned_client_id = NULL, lease_expire_at = NULL, result_json = NULL, error_msg = NULL, finished_time = NULL WHERE id = ? AND create_user = ?`
  546. const result = await db.query(sql, params)
  547. if (!result || result.affectedRows <= 0) {
  548. throw new Error('更新抢课任务失败')
  549. }
  550. await this.logTask(taskId, null, 'updated', '用户更新抢课任务')
  551. this.logInfo('updateTask', '抢课任务已更新(未开始)', { taskId, uuid }, {
  552. name: payload.name,
  553. student_num: payload.student_num || payload.user,
  554. courses_count: courses.length,
  555. course_groups_count: courseGroups.length,
  556. interval_ms: intervalMs,
  557. password_changed: !!(payload.password || payload.pass)
  558. })
  559. }
  560. async listUserTasks(uuid) {
  561. const rows = await db.query(
  562. `SELECT t.*${this.taskBatchSelectSql('t')}
  563. FROM qk_task t
  564. ${this.taskBatchJoinSql('t')}
  565. WHERE t.create_user = ?
  566. ORDER BY t.create_time DESC`,
  567. [uuid]
  568. )
  569. return (rows || []).map(row => this.serializeTask(row))
  570. }
  571. async getTaskDetail(uuid, taskId) {
  572. const rows = await db.query(
  573. `SELECT t.*${this.taskBatchSelectSql('t')}
  574. FROM qk_task t
  575. ${this.taskBatchJoinSql('t')}
  576. WHERE t.id = ? AND t.create_user = ?`,
  577. [taskId, uuid]
  578. )
  579. if (!rows || rows.length === 0) {
  580. return null
  581. }
  582. const logs = await db.query('SELECT client_id, event, message, payload_json, create_time FROM qk_task_log WHERE task_id = ? ORDER BY create_time DESC LIMIT 100', [taskId])
  583. return {
  584. task: this.serializeTask(rows[0], true),
  585. logs: (logs || []).map(log => {
  586. if (typeof log.payload_json === 'string' && log.payload_json) {
  587. try {
  588. log.payload_json = JSON.parse(log.payload_json)
  589. } catch (_) {}
  590. }
  591. return log
  592. })
  593. }
  594. }
  595. async cancelTask(uuid, taskId) {
  596. const result = await db.query(
  597. 'UPDATE qk_task SET status = ?, update_time = ?, finished_time = ? WHERE id = ? AND create_user = ? AND status IN (?, ?, ?)',
  598. [TASK_STATUS.CANCELLED, Date.now(), Date.now(), taskId, uuid, TASK_STATUS.PAUSED, TASK_STATUS.PENDING, TASK_STATUS.FAILED]
  599. )
  600. if (!result || result.affectedRows <= 0) {
  601. throw new Error('任务不存在或当前状态不可取消')
  602. }
  603. await this.logTask(taskId, null, 'cancelled', '用户取消抢课任务')
  604. this.logInfo('cancelTask', '用户已取消抢课任务', { taskId, uuid })
  605. }
  606. async startTask(uuid, taskId) {
  607. const rows = await db.query('SELECT * FROM qk_task WHERE id = ? AND create_user = ?', [taskId, uuid])
  608. if (!rows || rows.length === 0) {
  609. throw new Error('任务不存在')
  610. }
  611. const task = rows[0]
  612. if (![TASK_STATUS.PAUSED, TASK_STATUS.FAILED].includes(task.status)) {
  613. throw new Error('仅未开始或失败的任务可开启')
  614. }
  615. if (task.batch_id) {
  616. await this.requireEnabledBatch(task.batch_id)
  617. }
  618. const now = Date.now()
  619. const result = await db.query(
  620. `UPDATE qk_task SET status = ?, update_time = ?, assigned_client_id = NULL, lease_expire_at = NULL,
  621. assigned_at = NULL, exclude_client_id = NULL, result_json = NULL, error_msg = NULL, finished_time = NULL
  622. WHERE id = ? AND create_user = ? AND status IN (?, ?)`,
  623. [TASK_STATUS.PENDING, now, taskId, uuid, TASK_STATUS.PAUSED, TASK_STATUS.FAILED]
  624. )
  625. if (!result || result.affectedRows <= 0) {
  626. throw new Error('开启抢课任务失败')
  627. }
  628. await this.logTask(taskId, null, 'started', '用户开启抢课任务,等待分配')
  629. this.logInfo('startTask', '用户已开启抢课任务', { taskId, uuid })
  630. }
  631. async pauseTask(uuid, taskId) {
  632. const rows = await db.query('SELECT * FROM qk_task WHERE id = ? AND create_user = ?', [taskId, uuid])
  633. if (!rows || rows.length === 0) {
  634. throw new Error('任务不存在')
  635. }
  636. const task = rows[0]
  637. if (![TASK_STATUS.PENDING, TASK_STATUS.ASSIGNED, TASK_STATUS.RUNNING].includes(task.status)) {
  638. throw new Error('当前状态不可暂停')
  639. }
  640. const now = Date.now()
  641. const wasAssigned = [TASK_STATUS.ASSIGNED, TASK_STATUS.RUNNING].includes(task.status)
  642. if (wasAssigned && task.assigned_client_id) {
  643. await this.decrementClientSlots(task.assigned_client_id, now)
  644. }
  645. const result = await db.query(
  646. `UPDATE qk_task SET status = ?, update_time = ?, assigned_client_id = NULL, lease_expire_at = NULL,
  647. assigned_at = NULL, exclude_client_id = NULL
  648. WHERE id = ? AND create_user = ? AND status IN (?, ?, ?)`,
  649. [TASK_STATUS.PAUSED, now, taskId, uuid, TASK_STATUS.PENDING, TASK_STATUS.ASSIGNED, TASK_STATUS.RUNNING]
  650. )
  651. if (!result || result.affectedRows <= 0) {
  652. throw new Error('暂停抢课任务失败')
  653. }
  654. await this.logTask(taskId, task.assigned_client_id, 'paused', wasAssigned ? '用户暂停任务,已收回客户端' : '用户暂停抢课任务')
  655. this.logInfo('pauseTask', '用户已暂停抢课任务', { taskId, uuid }, {
  656. released_from_client: wasAssigned ? task.assigned_client_id : null
  657. })
  658. }
  659. async getAdminTask(taskId) {
  660. const rows = await db.query(
  661. `SELECT t.*, u.username, u.avatar${this.taskBatchSelectSql('t')}
  662. FROM qk_task t
  663. LEFT JOIN users u ON u.uuid COLLATE utf8mb4_general_ci = t.create_user COLLATE utf8mb4_general_ci
  664. ${this.taskBatchJoinSql('t')}
  665. WHERE t.id = ?`,
  666. [taskId]
  667. )
  668. if (!rows || rows.length === 0) {
  669. return null
  670. }
  671. return this.serializeTask(rows[0], true)
  672. }
  673. async decrementClientSlots(clientId, now = Date.now()) {
  674. if (!clientId) return
  675. await db.query(
  676. 'UPDATE qk_client SET current_slots = IF(current_slots > 0, current_slots - 1, 0), update_time = ? WHERE client_id = ?',
  677. [now, clientId]
  678. )
  679. }
  680. async adminUpdateTask(taskId, payload) {
  681. const rows = await db.query('SELECT * FROM qk_task WHERE id = ?', [taskId])
  682. if (!rows || rows.length === 0) {
  683. throw new Error('任务不存在')
  684. }
  685. const task = rows[0]
  686. if (task.status === TASK_STATUS.SUCCESS) {
  687. throw new Error('已成功的任务不可编辑')
  688. }
  689. const validated = this.validateTaskCoursesAndInterval(
  690. payload.courses || payload.COURSES,
  691. payload.course_groups || payload.COURSE_GROUPS,
  692. payload.interval_ms || payload.INTERVAL_MS || task.interval_ms || 500
  693. )
  694. const { courses, courseGroups, intervalMs } = validated
  695. const now = Date.now()
  696. const wasAssigned = [TASK_STATUS.ASSIGNED, TASK_STATUS.RUNNING].includes(task.status)
  697. if (wasAssigned) {
  698. await this.decrementClientSlots(task.assigned_client_id, now)
  699. }
  700. const batchId = this.resolveTaskBatchId(payload)
  701. const passwordSql = payload.password || payload.pass ? ', password_enc = ?' : ''
  702. const params = [
  703. payload.name,
  704. batchId,
  705. payload.student_num || payload.user,
  706. JSON.stringify(courses),
  707. JSON.stringify(courseGroups),
  708. payload.enable_ggxxk || payload.ENABLE_GGXXK ? 1 : 0,
  709. intervalMs,
  710. TASK_STATUS.PAUSED,
  711. now
  712. ]
  713. if (passwordSql) {
  714. params.splice(3, 0, this.encryptPassword(payload.password || payload.pass))
  715. }
  716. params.push(taskId)
  717. const sql = `UPDATE qk_task SET name = ?, batch_id = ?, student_num = ?${passwordSql}, courses = ?, course_groups = ?, enable_ggxxk = ?, interval_ms = ?, status = ?, jx0502zbid = '', update_time = ?, assigned_client_id = NULL, lease_expire_at = NULL, assigned_at = NULL, exclude_client_id = NULL, result_json = NULL, error_msg = NULL, finished_time = NULL WHERE id = ?`
  718. const result = await db.query(sql, params)
  719. if (!result || result.affectedRows <= 0) {
  720. throw new Error('更新抢课任务失败')
  721. }
  722. await this.logTask(taskId, task.assigned_client_id, 'admin_updated', wasAssigned ? '管理员更新任务并收回(未开始)' : '管理员更新抢课任务')
  723. this.logInfo('adminUpdateTask', '管理员已更新抢课任务', { taskId }, {
  724. name: payload.name,
  725. student_num: payload.student_num || payload.user,
  726. released_from_client: wasAssigned ? task.assigned_client_id : null
  727. })
  728. }
  729. async adminCancelTask(taskId) {
  730. const rows = await db.query('SELECT id, status, assigned_client_id FROM qk_task WHERE id = ?', [taskId])
  731. if (!rows || rows.length === 0) {
  732. throw new Error('任务不存在')
  733. }
  734. const task = rows[0]
  735. if (![TASK_STATUS.PAUSED, TASK_STATUS.PENDING, TASK_STATUS.ASSIGNED, TASK_STATUS.RUNNING, TASK_STATUS.FAILED].includes(task.status)) {
  736. throw new Error('当前状态不可取消')
  737. }
  738. const now = Date.now()
  739. if ([TASK_STATUS.ASSIGNED, TASK_STATUS.RUNNING].includes(task.status)) {
  740. await this.decrementClientSlots(task.assigned_client_id, now)
  741. }
  742. const result = await db.query(
  743. `UPDATE qk_task SET status = ?, assigned_client_id = NULL, lease_expire_at = NULL, assigned_at = NULL,
  744. exclude_client_id = NULL, update_time = ?, finished_time = ? WHERE id = ? AND status IN (?, ?, ?, ?, ?)`,
  745. [TASK_STATUS.CANCELLED, now, now, taskId, TASK_STATUS.PAUSED, TASK_STATUS.PENDING, TASK_STATUS.ASSIGNED, TASK_STATUS.RUNNING, TASK_STATUS.FAILED]
  746. )
  747. if (!result || result.affectedRows <= 0) {
  748. throw new Error('取消抢课任务失败')
  749. }
  750. await this.logTask(taskId, task.assigned_client_id, 'admin_cancelled', '管理员取消抢课任务')
  751. this.logInfo('adminCancelTask', '管理员已取消抢课任务', { taskId })
  752. }
  753. async adminRetryTask(taskId) {
  754. const rows = await db.query('SELECT id, status FROM qk_task WHERE id = ?', [taskId])
  755. if (!rows || rows.length === 0) {
  756. throw new Error('任务不存在')
  757. }
  758. if (![TASK_STATUS.FAILED, TASK_STATUS.CANCELLED].includes(rows[0].status)) {
  759. throw new Error('仅失败或已取消的任务可重试')
  760. }
  761. const now = Date.now()
  762. const result = await db.query(
  763. `UPDATE qk_task SET status = ?, assigned_client_id = NULL, lease_expire_at = NULL, assigned_at = NULL,
  764. exclude_client_id = NULL, result_json = NULL, error_msg = NULL, finished_time = NULL, update_time = ?
  765. WHERE id = ? AND status IN (?, ?)`,
  766. [TASK_STATUS.PENDING, now, taskId, TASK_STATUS.FAILED, TASK_STATUS.CANCELLED]
  767. )
  768. if (!result || result.affectedRows <= 0) {
  769. throw new Error('重试抢课任务失败')
  770. }
  771. await this.logTask(taskId, null, 'admin_retry', '管理员将任务重新加入待分配队列')
  772. this.logInfo('adminRetryTask', '管理员已重试抢课任务', { taskId })
  773. }
  774. async adminStartTask(taskId) {
  775. const rows = await db.query('SELECT * FROM qk_task WHERE id = ?', [taskId])
  776. if (!rows || rows.length === 0) {
  777. throw new Error('任务不存在')
  778. }
  779. const task = rows[0]
  780. if (![TASK_STATUS.PAUSED, TASK_STATUS.FAILED].includes(task.status)) {
  781. throw new Error('仅未开始或失败的任务可开启')
  782. }
  783. if (task.batch_id) {
  784. await this.requireEnabledBatch(task.batch_id)
  785. }
  786. const now = Date.now()
  787. const result = await db.query(
  788. `UPDATE qk_task SET status = ?, update_time = ?, assigned_client_id = NULL, lease_expire_at = NULL,
  789. assigned_at = NULL, exclude_client_id = NULL, result_json = NULL, error_msg = NULL, finished_time = NULL
  790. WHERE id = ? AND status IN (?, ?)`,
  791. [TASK_STATUS.PENDING, now, taskId, TASK_STATUS.PAUSED, TASK_STATUS.FAILED]
  792. )
  793. if (!result || result.affectedRows <= 0) {
  794. throw new Error('开启抢课任务失败')
  795. }
  796. await this.logTask(taskId, null, 'admin_started', '管理员开启抢课任务,等待分配')
  797. this.logInfo('adminStartTask', '管理员已开启抢课任务', { taskId })
  798. }
  799. async adminPauseTask(taskId) {
  800. const rows = await db.query('SELECT * FROM qk_task WHERE id = ?', [taskId])
  801. if (!rows || rows.length === 0) {
  802. throw new Error('任务不存在')
  803. }
  804. const task = rows[0]
  805. if (![TASK_STATUS.PENDING, TASK_STATUS.ASSIGNED, TASK_STATUS.RUNNING].includes(task.status)) {
  806. throw new Error('当前状态不可暂停')
  807. }
  808. const now = Date.now()
  809. const wasAssigned = [TASK_STATUS.ASSIGNED, TASK_STATUS.RUNNING].includes(task.status)
  810. if (wasAssigned && task.assigned_client_id) {
  811. await this.decrementClientSlots(task.assigned_client_id, now)
  812. }
  813. const result = await db.query(
  814. `UPDATE qk_task SET status = ?, update_time = ?, assigned_client_id = NULL, lease_expire_at = NULL,
  815. assigned_at = NULL, exclude_client_id = NULL
  816. WHERE id = ? AND status IN (?, ?, ?)`,
  817. [TASK_STATUS.PAUSED, now, taskId, TASK_STATUS.PENDING, TASK_STATUS.ASSIGNED, TASK_STATUS.RUNNING]
  818. )
  819. if (!result || result.affectedRows <= 0) {
  820. throw new Error('暂停抢课任务失败')
  821. }
  822. await this.logTask(taskId, task.assigned_client_id, 'admin_paused', wasAssigned ? '管理员暂停任务,已收回客户端' : '管理员暂停抢课任务')
  823. this.logInfo('adminPauseTask', '管理员已暂停抢课任务', { taskId }, {
  824. released_from_client: wasAssigned ? task.assigned_client_id : null
  825. })
  826. }
  827. async authenticateClient(clientId, clientSecret) {
  828. if (!clientId || !clientSecret) {
  829. this.logWarn('authClient', '客户端认证失败:缺少凭证', { clientId: clientId || 'unknown' })
  830. return null
  831. }
  832. const rows = await db.query('SELECT * FROM qk_client WHERE client_id = ? AND enabled = 1', [clientId])
  833. if (!rows || rows.length !== 1) {
  834. this.logWarn('authClient', '客户端认证失败:客户端不存在或已禁用', { clientId })
  835. return null
  836. }
  837. if (!bcryptjs.compareSync(String(clientSecret), rows[0].client_secret_hash)) {
  838. this.logWarn('authClient', '客户端认证失败:密钥不匹配', { clientId })
  839. return null
  840. }
  841. return rows[0]
  842. }
  843. async enrollOrAuthenticateClient(clientId, clientSecret, payload = {}) {
  844. const existing = await this.authenticateClient(clientId, clientSecret)
  845. if (existing) {
  846. return existing
  847. }
  848. if (!clientId || !clientSecret || !String(clientId).startsWith('qk-cli-')) {
  849. throw new Error('客户端凭证无效')
  850. }
  851. const rows = await db.query('SELECT * FROM qk_client WHERE client_id = ?', [clientId])
  852. if (rows && rows.length > 0) {
  853. throw new Error('客户端凭证无效')
  854. }
  855. const time = Date.now()
  856. const label = payload.label || payload.hostname || `auto-${clientId}`
  857. try {
  858. const result = await db.query(
  859. 'INSERT INTO qk_client (client_id, client_secret_hash, label, create_time, update_time) VALUES (?, ?, ?, ?, ?)',
  860. [clientId, bcryptjs.hashSync(String(clientSecret), 10), label, time, time]
  861. )
  862. if (!result || result.affectedRows <= 0) {
  863. throw new Error('客户端自动注册失败')
  864. }
  865. } catch (err) {
  866. if (err?.code === 'ER_DUP_ENTRY') {
  867. const raced = await this.authenticateClient(clientId, clientSecret)
  868. if (raced) {
  869. return raced
  870. }
  871. }
  872. throw err
  873. }
  874. const created = await db.query('SELECT * FROM qk_client WHERE client_id = ? AND enabled = 1', [clientId])
  875. if (!created || created.length !== 1) {
  876. throw new Error('客户端自动注册失败')
  877. }
  878. this.logInfo('enrollClient', '抢课客户端已自动注册', { clientId }, { label })
  879. return created[0]
  880. }
  881. async registerClient(clientId, clientSecret, payload = {}) {
  882. const client = await this.enrollOrAuthenticateClient(clientId, clientSecret, payload)
  883. const maxSlots = this.resolveClientMaxSlots(client, payload)
  884. const currentSlots = Math.max(0, Number(payload.current_slots || 0))
  885. const time = Date.now()
  886. await db.query(
  887. 'UPDATE qk_client SET label = COALESCE(NULLIF(?, \'\'), label), max_slots = ?, current_slots = ?, hostname = ?, os_username = ?, cpu_model = ?, cpu_threads = ?, total_mem_mb = ?, free_mem_mb = ?, platform = ?, last_heartbeat_at = ?, online = 1, update_time = ? WHERE client_id = ?',
  888. [
  889. payload.label || '',
  890. maxSlots,
  891. currentSlots,
  892. payload.hostname || null,
  893. payload.os_username || null,
  894. payload.cpu_model || null,
  895. payload.cpu_threads || null,
  896. payload.total_mem_mb || null,
  897. payload.free_mem_mb || null,
  898. payload.platform || null,
  899. time,
  900. time,
  901. clientId
  902. ]
  903. )
  904. await Redis.set(`qk:client:hb:${clientId}`, String(time), { EX: this.heartbeatTtlSeconds })
  905. this.logInfo('registerClient', '抢课客户端已注册/上线', { clientId }, {
  906. label: payload.label || client.label,
  907. max_slots: maxSlots,
  908. current_slots: currentSlots,
  909. hostname: payload.hostname,
  910. platform: payload.platform,
  911. cpu_threads: payload.cpu_threads,
  912. total_mem_mb: payload.total_mem_mb,
  913. free_mem_mb: payload.free_mem_mb
  914. })
  915. return { client_id: clientId, max_slots: maxSlots, current_slots: currentSlots }
  916. }
  917. async heartbeat(clientId, clientSecret, payload = {}) {
  918. const client = await this.authenticateClient(clientId, clientSecret)
  919. if (!client) {
  920. throw new Error('客户端凭证无效')
  921. }
  922. const runningTasks = Array.isArray(payload.running_tasks) ? payload.running_tasks.map(Number).filter(Boolean) : []
  923. const currentSlots = Math.max(0, Number(payload.current_slots ?? runningTasks.length))
  924. const maxSlots = this.resolveClientMaxSlots(client, payload)
  925. const now = Date.now()
  926. await db.query(
  927. 'UPDATE qk_client SET max_slots = ?, current_slots = ?, hostname = ?, os_username = ?, cpu_model = ?, cpu_threads = ?, total_mem_mb = ?, free_mem_mb = ?, platform = ?, last_heartbeat_at = ?, online = 1, update_time = ? WHERE client_id = ?',
  928. [
  929. maxSlots,
  930. currentSlots,
  931. payload.hostname || null,
  932. payload.os_username || null,
  933. payload.cpu_model || null,
  934. payload.cpu_threads || null,
  935. payload.total_mem_mb || null,
  936. payload.free_mem_mb || null,
  937. payload.platform || null,
  938. now,
  939. now,
  940. clientId
  941. ]
  942. )
  943. await Redis.set(`qk:client:hb:${clientId}`, String(now), { EX: this.heartbeatTtlSeconds })
  944. await Redis.set(`qk:client:slots:${clientId}`, String(currentSlots), { EX: this.heartbeatTtlSeconds })
  945. if (runningTasks.length > 0) {
  946. const leaseExpireAt = now + this.leaseMs
  947. const placeholders = runningTasks.map(() => '?').join(',')
  948. await db.query(
  949. `UPDATE qk_task SET status = ?, lease_expire_at = ?, update_time = ? WHERE assigned_client_id = ? AND id IN (${placeholders}) AND status IN (?, ?)`,
  950. [TASK_STATUS.RUNNING, leaseExpireAt, now, clientId, ...runningTasks, TASK_STATUS.ASSIGNED, TASK_STATUS.RUNNING]
  951. )
  952. this.logInfo('heartbeat', '客户端心跳续租运行中任务', { clientId }, {
  953. running_tasks: runningTasks,
  954. lease_expire_at: leaseExpireAt,
  955. current_slots: currentSlots,
  956. max_slots: maxSlots
  957. })
  958. }
  959. await this.releaseOrphanedClientTasks(clientId, runningTasks, now)
  960. return { client_id: clientId, current_slots: currentSlots, max_slots: maxSlots }
  961. }
  962. async releaseOrphanedClientTasks(clientId, runningTasks, now = Date.now()) {
  963. const assigned = await db.query(
  964. 'SELECT id FROM qk_task WHERE assigned_client_id = ? AND status IN (?, ?)',
  965. [clientId, TASK_STATUS.ASSIGNED, TASK_STATUS.RUNNING]
  966. )
  967. const runningSet = new Set((runningTasks || []).map(Number).filter(Boolean))
  968. let released = 0
  969. for (const row of assigned || []) {
  970. if (runningSet.has(row.id)) continue
  971. const result = await db.query(
  972. 'UPDATE qk_task SET status = ?, assigned_client_id = NULL, lease_expire_at = NULL, assigned_at = NULL, update_time = ? WHERE id = ? AND assigned_client_id = ? AND status IN (?, ?)',
  973. [TASK_STATUS.PENDING, now, row.id, clientId, TASK_STATUS.ASSIGNED, TASK_STATUS.RUNNING]
  974. )
  975. if (result && result.affectedRows > 0) {
  976. released += 1
  977. await this.logTask(row.id, clientId, 'released', '客户端未继续执行,任务已释放回队列')
  978. this.logInfo('releaseOrphaned', '释放未在运行的已分配任务', { taskId: row.id, clientId })
  979. }
  980. }
  981. return released
  982. }
  983. async reclaimTasks(clientId, clientSecret) {
  984. const client = await this.authenticateClient(clientId, clientSecret)
  985. if (!client) {
  986. throw new Error('客户端凭证无效')
  987. }
  988. const now = Date.now()
  989. const leaseExpireAt = now + this.leaseMs
  990. const rows = await db.query(
  991. `SELECT t.*, b.jx0502zbid AS batch_jx0502zbid, b.name AS batch_name, b.enabled AS batch_enabled
  992. FROM qk_task t
  993. LEFT JOIN qk_batch b ON b.id = t.batch_id
  994. WHERE t.assigned_client_id = ? AND t.status IN (?, ?)
  995. ORDER BY t.create_time ASC`,
  996. [clientId, TASK_STATUS.ASSIGNED, TASK_STATUS.RUNNING]
  997. )
  998. if (!rows || rows.length === 0) {
  999. return []
  1000. }
  1001. for (const row of rows) {
  1002. await db.query(
  1003. 'UPDATE qk_task SET status = ?, lease_expire_at = ?, update_time = ? WHERE id = ? AND assigned_client_id = ? AND status IN (?, ?)',
  1004. [TASK_STATUS.RUNNING, leaseExpireAt, now, row.id, clientId, TASK_STATUS.ASSIGNED, TASK_STATUS.RUNNING]
  1005. )
  1006. await this.logTask(row.id, clientId, 'reclaimed', '客户端重连后回收任务继续执行')
  1007. }
  1008. this.logInfo('reclaimTasks', `客户端回收 ${rows.length} 个进行中任务`, { clientId }, {
  1009. task_ids: rows.map(row => row.id),
  1010. lease_expire_at: leaseExpireAt
  1011. })
  1012. return rows.map(row => this.serializeTask({
  1013. ...row,
  1014. assigned_client_id: clientId,
  1015. lease_expire_at: leaseExpireAt,
  1016. status: TASK_STATUS.RUNNING
  1017. }, true))
  1018. }
  1019. async releaseTasks(clientId, clientSecret, payload = {}) {
  1020. const client = await this.authenticateClient(clientId, clientSecret)
  1021. if (!client) {
  1022. throw new Error('客户端凭证无效')
  1023. }
  1024. const now = Date.now()
  1025. const taskIds = Array.isArray(payload.task_ids)
  1026. ? payload.task_ids.map(Number).filter(Boolean)
  1027. : []
  1028. let rows = []
  1029. if (taskIds.length > 0) {
  1030. const placeholders = taskIds.map(() => '?').join(',')
  1031. rows = await db.query(
  1032. `SELECT id FROM qk_task WHERE assigned_client_id = ? AND id IN (${placeholders}) AND status IN (?, ?)`,
  1033. [clientId, ...taskIds, TASK_STATUS.ASSIGNED, TASK_STATUS.RUNNING]
  1034. )
  1035. } else {
  1036. rows = await db.query(
  1037. 'SELECT id FROM qk_task WHERE assigned_client_id = ? AND status IN (?, ?)',
  1038. [clientId, TASK_STATUS.ASSIGNED, TASK_STATUS.RUNNING]
  1039. )
  1040. }
  1041. let released = 0
  1042. for (const row of rows || []) {
  1043. const result = await db.query(
  1044. 'UPDATE qk_task SET status = ?, assigned_client_id = NULL, lease_expire_at = NULL, assigned_at = NULL, update_time = ? WHERE id = ? AND assigned_client_id = ? AND status IN (?, ?)',
  1045. [TASK_STATUS.PENDING, now, row.id, clientId, TASK_STATUS.ASSIGNED, TASK_STATUS.RUNNING]
  1046. )
  1047. if (result && result.affectedRows > 0) {
  1048. released += 1
  1049. await this.logTask(row.id, clientId, 'released', '客户端主动释放任务')
  1050. }
  1051. }
  1052. if (released > 0) {
  1053. this.logInfo('releaseTasks', `客户端释放 ${released} 个任务`, { clientId }, {
  1054. task_ids: (rows || []).map(row => row.id)
  1055. })
  1056. }
  1057. return { released, task_ids: (rows || []).map(row => row.id) }
  1058. }
  1059. async pullTasks(clientId, clientSecret, count) {
  1060. const client = await this.authenticateClient(clientId, clientSecret)
  1061. if (!client) {
  1062. throw new Error('客户端凭证无效')
  1063. }
  1064. const availableSlots = this.getClientAvailableSlots(client)
  1065. const safeCount = Math.max(0, Math.min(50, Number(count || 0), availableSlots))
  1066. if (safeCount <= 0) {
  1067. this.logWarn('pullTasks', '客户端无可用槽位或拉取数量无效,已忽略', { clientId }, {
  1068. count,
  1069. available_slots: availableSlots,
  1070. max_slots: this.resolveClientMaxSlots(client),
  1071. current_slots: client.current_slots,
  1072. free_mem_mb: client.free_mem_mb
  1073. })
  1074. return []
  1075. }
  1076. const lockKey = `qk:pull:lock:${clientId}`
  1077. const locked = await Redis.set(lockKey, '1', { NX: true, EX: this.pullLockTtlSeconds })
  1078. if (!locked) {
  1079. this.logWarn('pullTasks', '拉取任务被并发锁拦截,本次跳过', { clientId }, { count: safeCount })
  1080. return []
  1081. }
  1082. const conn = await db.connect()
  1083. try {
  1084. await conn.beginTransaction()
  1085. const inFlightStatuses = this.getInFlightTaskStatuses()
  1086. const candidateLimit = Math.min(50, Math.max(safeCount, safeCount * 5))
  1087. const [candidateRows] = await conn.execute(
  1088. `SELECT t.*, b.jx0502zbid AS batch_jx0502zbid, b.name AS batch_name, b.enabled AS batch_enabled
  1089. FROM qk_task t
  1090. LEFT JOIN qk_batch b ON b.id = t.batch_id
  1091. WHERE t.status = ?
  1092. AND (t.batch_id IS NULL OR b.enabled = 1)
  1093. AND (t.exclude_client_id IS NULL OR t.exclude_client_id <> ?)
  1094. AND NOT EXISTS (
  1095. SELECT 1 FROM qk_task active
  1096. WHERE active.student_num = t.student_num
  1097. AND active.status IN (?, ?)
  1098. )
  1099. ORDER BY t.create_time ASC LIMIT ${candidateLimit} FOR UPDATE`,
  1100. [TASK_STATUS.PENDING, clientId, ...inFlightStatuses]
  1101. )
  1102. const rows = this.pickPullableTasks(candidateRows, safeCount)
  1103. const now = Date.now()
  1104. const leaseExpireAt = now + this.leaseMs
  1105. for (const row of rows) {
  1106. await conn.execute(
  1107. 'UPDATE qk_task SET status = ?, assigned_client_id = ?, lease_expire_at = ?, assigned_at = ?, exclude_client_id = NULL, update_time = ? WHERE id = ?',
  1108. [TASK_STATUS.ASSIGNED, clientId, leaseExpireAt, now, now, row.id]
  1109. )
  1110. }
  1111. await conn.commit()
  1112. if (rows.length > 0) {
  1113. await db.query(
  1114. 'UPDATE qk_client SET current_slots = current_slots + ?, update_time = ? WHERE client_id = ?',
  1115. [rows.length, now, clientId]
  1116. )
  1117. }
  1118. for (const row of rows) {
  1119. await this.logTask(row.id, clientId, 'assigned', '任务已分配给客户端')
  1120. }
  1121. if (rows.length > 0) {
  1122. this.logInfo('pullTasks', `已分配 ${rows.length} 个抢课任务`, { clientId }, {
  1123. task_ids: rows.map(row => row.id),
  1124. lease_expire_at: leaseExpireAt,
  1125. requested_count: safeCount
  1126. })
  1127. }
  1128. return rows.map(row => this.serializeTask({ ...row, assigned_client_id: clientId, lease_expire_at: leaseExpireAt, status: TASK_STATUS.ASSIGNED }, true))
  1129. } catch (err) {
  1130. await conn.rollback()
  1131. this.logError('pullTasks', '拉取并分配任务失败,事务已回滚', { clientId }, err)
  1132. throw err
  1133. } finally {
  1134. await Redis.del(lockKey)
  1135. }
  1136. }
  1137. async reportResult(clientId, clientSecret, payload = {}) {
  1138. const client = await this.authenticateClient(clientId, clientSecret)
  1139. if (!client) {
  1140. throw new Error('客户端凭证无效')
  1141. }
  1142. const taskId = Number(payload.task_id || payload.id)
  1143. const success = payload.success === true || payload.status === TASK_STATUS.SUCCESS
  1144. const status = success ? TASK_STATUS.SUCCESS : TASK_STATUS.FAILED
  1145. const now = Date.now()
  1146. const resultJson = payload.result ? JSON.stringify(payload.result) : JSON.stringify({
  1147. course: payload.course || '',
  1148. message: payload.message || ''
  1149. })
  1150. const result = await db.query(
  1151. 'UPDATE qk_task SET status = ?, result_json = ?, error_msg = ?, update_time = ?, finished_time = ?, lease_expire_at = NULL WHERE id = ? AND assigned_client_id = ? AND status IN (?, ?)',
  1152. [status, resultJson, success ? null : (payload.error_msg || payload.message || '抢课失败'), now, now, taskId, clientId, TASK_STATUS.ASSIGNED, TASK_STATUS.RUNNING]
  1153. )
  1154. if (!result || result.affectedRows <= 0) {
  1155. this.logWarn('reportResult', '任务结果上报被拒绝:任务不存在或不属于当前客户端', { taskId, clientId }, {
  1156. success,
  1157. status
  1158. })
  1159. throw new Error('任务不存在或不属于当前客户端')
  1160. }
  1161. await db.query(
  1162. `UPDATE qk_client SET current_slots = IF(current_slots > 0, current_slots - 1, 0), total_completed = total_completed + 1, total_success = total_success + ?, update_time = ? WHERE client_id = ?`,
  1163. [success ? 1 : 0, now, clientId]
  1164. )
  1165. await this.logTask(taskId, clientId, success ? 'grab_success' : 'grab_fail', payload.message || payload.error_msg || '', payload.result || payload)
  1166. this.logInfo('reportResult', success ? '抢课成功' : '抢课失败', { taskId, clientId }, {
  1167. success,
  1168. message: payload.message || payload.error_msg || '',
  1169. course: payload.course || payload.result?.course || '',
  1170. result: payload.result || null
  1171. })
  1172. return { task_id: taskId, status }
  1173. }
  1174. async listClients() {
  1175. const rows = await db.query('SELECT id, client_id, label, enabled, max_slots, current_slots, hostname, os_username, cpu_model, cpu_threads, total_mem_mb, free_mem_mb, platform, last_heartbeat_at, online, total_completed, total_success, create_time, update_time FROM qk_client ORDER BY update_time DESC')
  1176. return rows || []
  1177. }
  1178. async deleteClient(clientId) {
  1179. const result = await db.query('UPDATE qk_client SET enabled = 0, online = 0, update_time = ? WHERE client_id = ?', [Date.now(), clientId])
  1180. if (!result || result.affectedRows <= 0) {
  1181. throw new Error('客户端不存在')
  1182. }
  1183. this.logInfo('deleteClient', '抢课客户端已禁用', { clientId })
  1184. }
  1185. async listAdminTasks(filters = {}) {
  1186. const pagesize = Math.max(1, Math.min(100, Number(filters.pagesize || 20)))
  1187. const current = Math.max(1, Number(filters.current || 1))
  1188. const where = ['1 = 1']
  1189. const params = []
  1190. const countParams = []
  1191. if (filters.status) {
  1192. where.push('t.status = ?')
  1193. params.push(filters.status)
  1194. countParams.push(filters.status)
  1195. }
  1196. if (filters.client_id) {
  1197. where.push('t.assigned_client_id = ?')
  1198. params.push(filters.client_id)
  1199. countParams.push(filters.client_id)
  1200. }
  1201. if (filters.student_num) {
  1202. where.push('t.student_num LIKE ?')
  1203. params.push(`%${filters.student_num}%`)
  1204. countParams.push(`%${filters.student_num}%`)
  1205. }
  1206. if (filters.username) {
  1207. where.push('u.username COLLATE utf8mb4_general_ci LIKE (CONVERT(? USING utf8mb4) COLLATE utf8mb4_general_ci)')
  1208. params.push(`%${filters.username}%`)
  1209. countParams.push(`%${filters.username}%`)
  1210. }
  1211. if (filters.batch_id) {
  1212. where.push('t.batch_id = ?')
  1213. params.push(Number(filters.batch_id))
  1214. countParams.push(Number(filters.batch_id))
  1215. }
  1216. const whereSql = where.join(' AND ')
  1217. const offset = (current - 1) * pagesize
  1218. const countRows = await db.query(
  1219. `SELECT COUNT(*) AS total FROM qk_task t
  1220. LEFT JOIN users u ON u.uuid COLLATE utf8mb4_general_ci = t.create_user COLLATE utf8mb4_general_ci
  1221. WHERE ${whereSql}`,
  1222. countParams
  1223. )
  1224. const rows = await db.query(
  1225. `SELECT t.*, u.username, u.avatar${this.taskBatchSelectSql('t')}
  1226. FROM qk_task t
  1227. LEFT JOIN users u ON u.uuid COLLATE utf8mb4_general_ci = t.create_user COLLATE utf8mb4_general_ci
  1228. ${this.taskBatchJoinSql('t')}
  1229. WHERE ${whereSql}
  1230. ORDER BY t.create_time DESC
  1231. LIMIT ${pagesize} OFFSET ${offset}`,
  1232. params
  1233. )
  1234. return {
  1235. list: (rows || []).map(row => this.serializeTask(row, true)),
  1236. total: countRows?.[0]?.total || 0,
  1237. current,
  1238. pagesize
  1239. }
  1240. }
  1241. async listAdminReports(filters = {}) {
  1242. const pagesize = Math.max(1, Math.min(100, Number(filters.pagesize || 20)))
  1243. const current = Math.max(1, Number(filters.current || 1))
  1244. const where = ['l.event IN (?, ?, ?, ?)']
  1245. const params = ['request_result', 'progress_snapshot', 'grab_success', 'grab_fail']
  1246. const countParams = ['request_result', 'progress_snapshot', 'grab_success', 'grab_fail']
  1247. if (filters.task_id) {
  1248. where.push('l.task_id = ?')
  1249. params.push(Number(filters.task_id))
  1250. countParams.push(Number(filters.task_id))
  1251. }
  1252. if (filters.client_id) {
  1253. where.push('l.client_id = ?')
  1254. params.push(String(filters.client_id))
  1255. countParams.push(String(filters.client_id))
  1256. }
  1257. if (filters.event) {
  1258. where.push('l.event = ?')
  1259. params.push(String(filters.event))
  1260. countParams.push(String(filters.event))
  1261. }
  1262. if (filters.start_time) {
  1263. where.push('l.create_time >= ?')
  1264. params.push(Number(filters.start_time))
  1265. countParams.push(Number(filters.start_time))
  1266. }
  1267. if (filters.end_time) {
  1268. where.push('l.create_time <= ?')
  1269. params.push(Number(filters.end_time))
  1270. countParams.push(Number(filters.end_time))
  1271. }
  1272. if (filters.student_num) {
  1273. where.push('t.student_num LIKE ?')
  1274. params.push(`%${filters.student_num}%`)
  1275. countParams.push(`%${filters.student_num}%`)
  1276. }
  1277. if (filters.name || filters.task_name) {
  1278. where.push('t.name LIKE ?')
  1279. params.push(`%${filters.name || filters.task_name}%`)
  1280. countParams.push(`%${filters.name || filters.task_name}%`)
  1281. }
  1282. if (filters.username) {
  1283. where.push('u.username COLLATE utf8mb4_general_ci LIKE (CONVERT(? USING utf8mb4) COLLATE utf8mb4_general_ci)')
  1284. params.push(`%${filters.username}%`)
  1285. countParams.push(`%${filters.username}%`)
  1286. }
  1287. if (filters.client_label) {
  1288. where.push('c.label LIKE ?')
  1289. params.push(`%${filters.client_label}%`)
  1290. countParams.push(`%${filters.client_label}%`)
  1291. }
  1292. const whereSql = where.join(' AND ')
  1293. const offset = (current - 1) * pagesize
  1294. const joinSql = `
  1295. FROM qk_task_log l
  1296. LEFT JOIN qk_task t ON t.id = l.task_id
  1297. LEFT JOIN qk_client c ON c.client_id = l.client_id
  1298. LEFT JOIN users u ON u.uuid COLLATE utf8mb4_general_ci = t.create_user COLLATE utf8mb4_general_ci`
  1299. const countRows = await db.query(
  1300. `SELECT COUNT(*) AS total ${joinSql} WHERE ${whereSql}`,
  1301. countParams
  1302. )
  1303. const rows = await db.query(
  1304. `SELECT l.id, l.task_id, l.client_id, l.event, l.message, l.payload_json, l.create_time,
  1305. t.name AS task_name, t.student_num, t.status AS task_status,
  1306. c.label AS client_label, u.username, u.avatar
  1307. ${joinSql}
  1308. WHERE ${whereSql}
  1309. ORDER BY l.create_time DESC
  1310. LIMIT ${pagesize} OFFSET ${offset}`,
  1311. params
  1312. )
  1313. return {
  1314. list: (rows || []).map(row => this.serializeReportLog(row)),
  1315. total: countRows?.[0]?.total || 0,
  1316. current,
  1317. pagesize
  1318. }
  1319. }
  1320. async reassignStaleRunningTasks() {
  1321. const onlineCount = await this.countOnlineClients()
  1322. if (onlineCount <= 1) {
  1323. return 0
  1324. }
  1325. const now = Date.now()
  1326. const staleBefore = now - this.staleTaskMs
  1327. const rows = await db.query(
  1328. `SELECT id, assigned_client_id FROM qk_task
  1329. WHERE status IN (?, ?)
  1330. AND assigned_at IS NOT NULL
  1331. AND assigned_at < ?`,
  1332. [TASK_STATUS.ASSIGNED, TASK_STATUS.RUNNING, staleBefore]
  1333. )
  1334. let count = 0
  1335. for (const row of rows || []) {
  1336. const result = await db.query(
  1337. `UPDATE qk_task
  1338. SET status = ?, assigned_client_id = NULL, lease_expire_at = NULL,
  1339. assigned_at = NULL, exclude_client_id = ?, update_time = ?
  1340. WHERE id = ? AND status IN (?, ?)`,
  1341. [TASK_STATUS.PENDING, row.assigned_client_id, now, row.id, TASK_STATUS.ASSIGNED, TASK_STATUS.RUNNING]
  1342. )
  1343. if (result && result.affectedRows > 0) {
  1344. count += 1
  1345. if (row.assigned_client_id) {
  1346. await db.query(
  1347. 'UPDATE qk_client SET current_slots = IF(current_slots > 0, current_slots - 1, 0), update_time = ? WHERE client_id = ?',
  1348. [now, row.assigned_client_id]
  1349. )
  1350. }
  1351. await this.logTask(row.id, row.assigned_client_id, 'reassigned', '任务超过1小时未成功,已收回并等待分配给其他客户端')
  1352. this.logWarn('reassignStale', '长时间未成功任务已收回', {
  1353. taskId: row.id,
  1354. clientId: row.assigned_client_id
  1355. }, { online_clients: onlineCount })
  1356. }
  1357. }
  1358. return count
  1359. }
  1360. async requeueExpiredTasks() {
  1361. const now = Date.now()
  1362. const rows = await db.query(
  1363. 'SELECT id, assigned_client_id FROM qk_task WHERE status IN (?, ?) AND lease_expire_at IS NOT NULL AND lease_expire_at < ?',
  1364. [TASK_STATUS.ASSIGNED, TASK_STATUS.RUNNING, now]
  1365. )
  1366. let count = 0
  1367. for (const row of rows || []) {
  1368. const result = await db.query(
  1369. 'UPDATE qk_task SET status = ?, assigned_client_id = NULL, lease_expire_at = NULL, assigned_at = NULL, update_time = ? WHERE id = ? AND status IN (?, ?)',
  1370. [TASK_STATUS.PENDING, now, row.id, TASK_STATUS.ASSIGNED, TASK_STATUS.RUNNING]
  1371. )
  1372. if (result && result.affectedRows > 0) {
  1373. count++
  1374. if (row.assigned_client_id) {
  1375. await db.query(
  1376. 'UPDATE qk_client SET current_slots = IF(current_slots > 0, current_slots - 1, 0), update_time = ? WHERE client_id = ?',
  1377. [now, row.assigned_client_id]
  1378. )
  1379. }
  1380. await this.logTask(row.id, row.assigned_client_id, 'reassigned', '租约过期,任务已重新进入待分配队列')
  1381. this.logWarn('requeueExpired', '租约过期,任务已重新入队', {
  1382. taskId: row.id,
  1383. clientId: row.assigned_client_id
  1384. })
  1385. }
  1386. }
  1387. const offlineResult = await db.query(
  1388. 'UPDATE qk_client SET online = 0, current_slots = 0, update_time = ? WHERE online = 1 AND (last_heartbeat_at IS NULL OR last_heartbeat_at < ?)',
  1389. [now, now - this.heartbeatTtlSeconds * 1000]
  1390. )
  1391. const offlineCount = offlineResult?.affectedRows || 0
  1392. const staleCount = await this.reassignStaleRunningTasks()
  1393. if (count > 0 || offlineCount > 0 || staleCount > 0) {
  1394. this.logInfo('requeueExpired', '租约巡检完成', {}, {
  1395. expired_tasks: (rows || []).length,
  1396. requeued: count,
  1397. stale_reassigned: staleCount,
  1398. clients_marked_offline: offlineCount
  1399. })
  1400. }
  1401. return count + staleCount
  1402. }
  1403. }
  1404. module.exports = {
  1405. TaskScheduler,
  1406. TASK_STATUS
  1407. }