/** * 确定性排查:同一 keep-alive 连接上连发多个 POST,看响应会不会错位。 * 用法: node scripts/probe-keepalive.mjs [base] */ import http from 'node:http'; const BASE = process.argv[2] || 'http://127.0.0.1:5399'; const url = new URL(BASE); function requestOnce(agent, index) { return new Promise((resolve) => { const payload = JSON.stringify({ name: 'shell', args: { command: `echo req-${index}` } }); const req = http.request( { hostname: url.hostname, port: url.port, path: '/api/tools/run', method: 'POST', agent, headers: { 'Content-Type': 'application/json', 'Content-Length': Buffer.byteLength(payload) }, }, (res) => { let data = ''; res.on('data', (c) => (data += c)); res.on('end', () => resolve({ index, status: res.statusCode, keepAlive: res.headers.connection, body: data.slice(0, 160) }), ); }, ); req.on('error', (e) => resolve({ index, status: 0, body: `ERR ${e.message}` })); req.end(payload); }); } const agent = new http.Agent({ keepAlive: true, maxSockets: 1 }); console.log('=== 同一连接串行 5 次 ==='); for (let i = 1; i <= 5; i += 1) { const r = await requestOnce(agent, i); const matched = r.body.includes(`req-${i}`); console.log(`${matched ? '✅' : '❌'} #${i} status=${r.status} conn=${r.keepAlive} ${r.body.replace(/\s+/g, ' ')}`); } agent.destroy(); console.log('\n=== 每次新连接(Connection: close)==='); const closeAgent = new http.Agent({ keepAlive: false }); for (let i = 1; i <= 3; i += 1) { const r = await requestOnce(closeAgent, i); const matched = r.body.includes(`req-${i}`); console.log(`${matched ? '✅' : '❌'} #${i} status=${r.status} ${r.body.replace(/\s+/g, ' ')}`); }