|
| 1 | +#!/usr/bin/env node |
| 2 | +/** |
| 3 | + * Mock Heng Controller |
| 4 | + * 模拟 heng-controller 的 HTTP 行为,用于本地开发测试 |
| 5 | + * |
| 6 | + * 行为: |
| 7 | + * 1. 接受 POST /c/v1/judges → 返回 judgeId |
| 8 | + * 2. 2 秒后模拟 update 回调(JUDGING 状态) |
| 9 | + * 3. 再 1 秒后模拟 finish 回调(默认 AC,或根据代码内容决定结果) |
| 10 | + * |
| 11 | + * 用法: |
| 12 | + * node scripts/mock-heng.js |
| 13 | + * node scripts/mock-heng.js --result=WA # 全部返回 WA |
| 14 | + * node scripts/mock-heng.js --result=CE # 全部返回 CE |
| 15 | + * node scripts/mock-heng.js --result=TLE # 全部返回 TLE |
| 16 | + * node scripts/mock-heng.js --delay=500 # 500ms 后返回结果(默认 2000ms) |
| 17 | + * |
| 18 | + * 配置 .env: |
| 19 | + * HENG_BASE_URL=http://localhost:5010 |
| 20 | + * HENG_AK=mock-ak |
| 21 | + * HENG_SK=mock-sk |
| 22 | + */ |
| 23 | + |
| 24 | +const http = require('http') |
| 25 | +const { randomUUID } = require('crypto') |
| 26 | + |
| 27 | +// ─── CLI 参数解析 ────────────────────────────────────────────────────────────── |
| 28 | +const args = process.argv.slice(2).reduce((acc, arg) => { |
| 29 | + const [key, val] = arg.replace('--', '').split('=') |
| 30 | + acc[key] = val |
| 31 | + return acc |
| 32 | +}, {}) |
| 33 | + |
| 34 | +const DEFAULT_RESULT = args.result || 'AC' |
| 35 | +const DELAY_MS = parseInt(args.delay || '2000', 10) |
| 36 | +const PORT = parseInt(args.port || '5010', 10) |
| 37 | + |
| 38 | +// ─── 预设结果 ────────────────────────────────────────────────────────────────── |
| 39 | +const RESULT_MAP = { |
| 40 | + AC: { |
| 41 | + cases: [ |
| 42 | + { kind: 'Accepted', time: 42, memory: 3145728 }, |
| 43 | + ], |
| 44 | + }, |
| 45 | + WA: { |
| 46 | + cases: [ |
| 47 | + { kind: 'Accepted', time: 38, memory: 2097152 }, |
| 48 | + { kind: 'WrongAnswer', time: 45, memory: 2359296, extraMessage: 'expected 42, got 43' }, |
| 49 | + ], |
| 50 | + }, |
| 51 | + TLE: { |
| 52 | + cases: [ |
| 53 | + { kind: 'Accepted', time: 40, memory: 2097152 }, |
| 54 | + { kind: 'TimeLimitExceeded', time: 2000, memory: 2097152 }, |
| 55 | + ], |
| 56 | + }, |
| 57 | + MLE: { |
| 58 | + cases: [ |
| 59 | + { kind: 'MemoryLimitExceeded', time: 120, memory: 268435456 }, |
| 60 | + ], |
| 61 | + }, |
| 62 | + RE: { |
| 63 | + cases: [ |
| 64 | + { kind: 'RuntimeError', time: 10, memory: 1048576, extraMessage: 'Segmentation fault (core dumped)' }, |
| 65 | + ], |
| 66 | + }, |
| 67 | + CE: { |
| 68 | + cases: [], |
| 69 | + extra: { |
| 70 | + user: { |
| 71 | + compileMessage: "error: 'cout' was not declared in this scope\n cout << \"hello\";\n ^\ncompilation terminated.", |
| 72 | + compileTime: 1200, |
| 73 | + }, |
| 74 | + }, |
| 75 | + }, |
| 76 | + PE: { |
| 77 | + cases: [ |
| 78 | + { kind: 'PresentationError', time: 35, memory: 2097152 }, |
| 79 | + ], |
| 80 | + }, |
| 81 | +} |
| 82 | + |
| 83 | +// ─── HTTP 工具 ───────────────────────────────────────────────────────────────── |
| 84 | +function readBody(req) { |
| 85 | + return new Promise((resolve) => { |
| 86 | + let data = '' |
| 87 | + req.on('data', chunk => data += chunk) |
| 88 | + req.on('end', () => { |
| 89 | + try { resolve(JSON.parse(data || '{}')) } |
| 90 | + catch { resolve({}) } |
| 91 | + }) |
| 92 | + }) |
| 93 | +} |
| 94 | + |
| 95 | +function sendJson(res, status, body) { |
| 96 | + const json = JSON.stringify(body) |
| 97 | + res.writeHead(status, { 'Content-Type': 'application/json', 'Content-Length': Buffer.byteLength(json) }) |
| 98 | + res.end(json) |
| 99 | +} |
| 100 | + |
| 101 | +async function postJson(url, body) { |
| 102 | + return new Promise((resolve, reject) => { |
| 103 | + const urlObj = new URL(url) |
| 104 | + const data = JSON.stringify(body) |
| 105 | + const req = http.request({ |
| 106 | + hostname: urlObj.hostname, |
| 107 | + port: urlObj.port || 80, |
| 108 | + path: urlObj.pathname, |
| 109 | + method: 'POST', |
| 110 | + headers: { 'Content-Type': 'application/json', 'Content-Length': Buffer.byteLength(data) }, |
| 111 | + }, (res) => { |
| 112 | + res.resume() |
| 113 | + resolve(res.statusCode) |
| 114 | + }) |
| 115 | + req.on('error', reject) |
| 116 | + req.write(data) |
| 117 | + req.end() |
| 118 | + }) |
| 119 | +} |
| 120 | + |
| 121 | +// ─── 回调模拟 ────────────────────────────────────────────────────────────────── |
| 122 | +async function simulateJudge(submissionId, judgeId, callbackUrls, result) { |
| 123 | + const updateUrl = callbackUrls.update.replace(':submissionId', submissionId).replace(':judgeId', judgeId) |
| 124 | + const finishUrl = callbackUrls.finish.replace(':submissionId', submissionId).replace(':judgeId', judgeId) |
| 125 | + |
| 126 | + // 第一步:JUDGING 状态更新 |
| 127 | + await new Promise(r => setTimeout(r, DELAY_MS * 0.5)) |
| 128 | + console.log(`[mock-heng] → update(JUDGING) submissionId=${submissionId}`) |
| 129 | + try { |
| 130 | + await postJson(updateUrl, { state: 'judging' }) |
| 131 | + } catch (e) { |
| 132 | + console.error(`[mock-heng] update callback failed: ${e.message}`) |
| 133 | + } |
| 134 | + |
| 135 | + // 第二步:finish 最终结果 |
| 136 | + await new Promise(r => setTimeout(r, DELAY_MS * 0.5)) |
| 137 | + console.log(`[mock-heng] → finish(${result}) submissionId=${submissionId}`) |
| 138 | + try { |
| 139 | + const finishBody = { ...RESULT_MAP[result], judger: 'mock-heng' } |
| 140 | + await postJson(finishUrl, finishBody) |
| 141 | + } catch (e) { |
| 142 | + console.error(`[mock-heng] finish callback failed: ${e.message}`) |
| 143 | + } |
| 144 | +} |
| 145 | + |
| 146 | +// ─── 交互式模式(每次提交前询问结果)────────────────────────────────────────── |
| 147 | +const pendingJobs = [] // { submissionId, judgeId, callbackUrls } |
| 148 | + |
| 149 | +function promptForResult() { |
| 150 | + if (pendingJobs.length === 0) return |
| 151 | + const job = pendingJobs.shift() |
| 152 | + const readline = require('readline').createInterface({ input: process.stdin, output: process.stdout }) |
| 153 | + readline.question(`\n[mock-heng] submissionId=${job.submissionId} 结果? (AC/WA/TLE/MLE/RE/CE/PE, 默认${DEFAULT_RESULT}): `, (answer) => { |
| 154 | + readline.close() |
| 155 | + const result = RESULT_MAP[answer?.toUpperCase()] ? answer.toUpperCase() : DEFAULT_RESULT |
| 156 | + simulateJudge(job.submissionId, job.judgeId, job.callbackUrls, result) |
| 157 | + .then(() => promptForResult()) |
| 158 | + }) |
| 159 | +} |
| 160 | + |
| 161 | +// ─── HTTP Server ─────────────────────────────────────────────────────────────── |
| 162 | +const INTERACTIVE = args.interactive === 'true' || args.i === 'true' |
| 163 | + |
| 164 | +const server = http.createServer(async (req, res) => { |
| 165 | + if (req.method === 'POST' && req.url === '/c/v1/judges') { |
| 166 | + const body = await readBody(req) |
| 167 | + const judgeId = `mock-${randomUUID().slice(0, 8)}` |
| 168 | + |
| 169 | + // 解析 submissionId(从 callbackUrls 路径提取) |
| 170 | + let submissionId = 'unknown' |
| 171 | + if (body.callbackUrls?.finish) { |
| 172 | + const match = body.callbackUrls.finish.match(/\/heng\/finish\/(\d+)\//) |
| 173 | + if (match) submissionId = match[1] |
| 174 | + } |
| 175 | + |
| 176 | + console.log(`[mock-heng] ← createJudge submissionId=${submissionId} judgeId=${judgeId} lang=${body.judge?.user?.environment?.language || '?'}`) |
| 177 | + |
| 178 | + sendJson(res, 200, { judgeId }) |
| 179 | + |
| 180 | + if (INTERACTIVE) { |
| 181 | + pendingJobs.push({ submissionId, judgeId, callbackUrls: body.callbackUrls }) |
| 182 | + if (pendingJobs.length === 1) setTimeout(promptForResult, 100) |
| 183 | + } else { |
| 184 | + // 自动模式:直接返回预设结果 |
| 185 | + simulateJudge(submissionId, judgeId, body.callbackUrls, DEFAULT_RESULT).catch(console.error) |
| 186 | + } |
| 187 | + } else { |
| 188 | + sendJson(res, 404, { error: 'Not found' }) |
| 189 | + } |
| 190 | +}) |
| 191 | + |
| 192 | +server.listen(PORT, () => { |
| 193 | + console.log(` |
| 194 | +╔══════════════════════════════════════════════════════╗ |
| 195 | +║ 🎭 Mock Heng Controller ║ |
| 196 | +╠══════════════════════════════════════════════════════╣ |
| 197 | +║ 监听端口: ${PORT} ║ |
| 198 | +║ 默认结果: ${DEFAULT_RESULT} ║ |
| 199 | +║ 延迟时间: ${DELAY_MS}ms ║ |
| 200 | +║ 交互模式: ${INTERACTIVE ? '✅ 每次提交前询问' : '❌ 全部返回预设结果'} ║ |
| 201 | +╠══════════════════════════════════════════════════════╣ |
| 202 | +║ .env 配置: ║ |
| 203 | +║ HENG_BASE_URL=http://localhost:${PORT} ║ |
| 204 | +║ HENG_AK=mock-ak ║ |
| 205 | +║ HENG_SK=mock-sk ║ |
| 206 | +╚══════════════════════════════════════════════════════╝ |
| 207 | + `) |
| 208 | +}) |
| 209 | + |
| 210 | +server.on('error', (e) => { |
| 211 | + console.error(`[mock-heng] Server error: ${e.message}`) |
| 212 | + process.exit(1) |
| 213 | +}) |
0 commit comments