const http = require('http'); const httpProxy = require('http-proxy'); const { spawn } = require('child_process'); const path = require('path'); console.log('Starting proxy.js...'); // 检查 runner.cjs 是否存在 const runnerPath = path.join(__dirname, 'runner.cjs'); console.log('Looking for runner at:', runnerPath); const fs = require('fs'); if (!fs.existsSync(runnerPath)) { console.error('ERROR: runner.cjs not found at', runnerPath); process.exit(1); } else { console.log('✅ runner.cjs found'); } // 创建代理,目标改为 IPv4 地址 127.0.0.1(避免 IPv6 解析) const proxy = httpProxy.createProxyServer({ target: 'http://127.0.0.1:2333', ws: true, }); proxy.on('error', (err, req, res) => { console.error('Proxy error:', err.message); if (res && !res.headersSent) { res.writeHead(502, { 'Content-Type': 'text/plain' }); res.end('Bad Gateway'); } }); // 启动 runner.cjs(主程序,监听 2333) const runner = spawn('node', [runnerPath], { stdio: 'inherit', env: process.env, }); runner.on('error', (err) => { console.error('Failed to start runner:', err); process.exit(1); }); runner.on('exit', (code, signal) => { console.log(`Runner exited with code ${code}, signal ${signal}`); process.exit(code || 1); }); // 创建 HTTP 服务器监听 7860 const server = http.createServer((req, res) => { // 健康检查 if (req.url === '/') { res.writeHead(200, { 'Content-Type': 'text/plain' }); res.end('OK'); return; } // 其他请求代理到 2333 proxy.web(req, res); }); server.on('upgrade', (req, socket, head) => { proxy.ws(req, socket, head); }); const PORT = process.env.PORT || 7860; server.listen(PORT, '0.0.0.0', () => { console.log(`✅ Proxy listening on ${PORT} -> 127.0.0.1:2333`); console.log(`✅ Runner process started (PID: ${runner.pid})`); }); // 优雅关闭 process.on('SIGTERM', () => { console.log('Received SIGTERM, shutting down...'); server.close(() => { runner.kill('SIGTERM'); process.exit(0); }); });