TaskScheduler.js 71 KB

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