dev.mjs 9.48 KB
// scripts/dev.mjs
// CodeRio 开发模式启动器 / 后端生命周期 supervisor。
//
// 设计要点:
//  - 本进程(supervisor)常驻,独立控制端口 4174,永远活着;
//    它只负责 spawn / kill 后端(4173) 子进程,不随后端一起退出。
//  - 前端(Vite 5173)也由本进程拉起,因此「停止/重启后端」只会影响 API 与 SSE,
//    前端 UI 始终保持在线,且能随时通过 supervisor 把后端重新拉起。
//    这正是修复「关闭服务后前端再也起不来」的关键:关闭后端不再杀死能接收
//    启动指令的进程。
//  - 后端以 COD_SERVE_WEB=0 启动,不托管 apps/web/dist;UI 唯一入口是 Vite 的
//    5173,代理把 /api 与 /api/stream(SSE) 转发到 4173,/devctl 转发到 4174(supervisor)。
//  - 统一捕获 SIGINT/SIGTERM,按进程树回收后端与 web 及其子进程(esbuild/vite 等)。
import { spawn, spawnSync, execSync } from 'node:child_process';
import http from 'node:http';
import path from 'node:path';
import { fileURLToPath } from 'node:url';

const __dirname = path.dirname(fileURLToPath(import.meta.url));
const ROOT = path.resolve(__dirname, '..');
const WEB_PORT = process.env.COD_WEB_PORT || '5173';
const CTL_PORT = Number(process.env.COD_CTL_PORT || '4174');
const BACKEND_PORT = Number(process.env.COD_PORT || '4173');

const out_write = (s) => process.stdout.write(s);
const tag = (label) => `\u001b[36m[${label}]\u001b[0m `;

// ---- 启动前端口清理 ----
// 回收上一次未彻底退出的 supervisor 树占用本项目的端口,避免新进程被迫换端口
// (前端 Vite) 或反复 EADDRINUSE 重试 (后端)。排除自身,避免自杀。
// 用 taskkill /f /t 杀整棵进程树(含 vite / esbuild 等孙进程),确保端口真正释放。
function killStalePort(port) {
  try {
    const out = execSync('netstat -ano', { stdio: ['ignore', 'pipe', 'ignore'] }).toString();
    const re = new RegExp(`:${port}\\s+\\S+\\s+LISTENING\\s+(\\d+)`, 'g');
    const pids = new Set();
    let m;
    while ((m = re.exec(out))) {
      const pid = Number(m[1]);
      if (pid !== process.pid) pids.add(pid);
    }
    for (const pid of pids) {
      try {
        spawnSync('taskkill', ['/pid', String(pid), '/f', '/t'], { stdio: 'ignore', windowsHide: true });
      } catch {
        /* ignore */
      }
    }
    if (pids.size) {
      out_write(tag('dev') + `已清理端口 ${port} 上的陈旧进程: ${[...pids].join(', ')}\n`);
    }
  } catch {
    /* ignore */
  }
}

// 启动前先回收三处端口,再拉起任何子进程(统一等 OS 释放端口)。
killStalePort(WEB_PORT);
killStalePort(BACKEND_PORT);
killStalePort(CTL_PORT);
Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 300);

// ---- 前端 Vite(常驻,UI 入口)----
// 注意:web 不在启动时立即拉起,而是等后端健康检查通过后再启动(见底部 boot 序列),
// 避免 Vite 已就绪、前端立刻发起 /api/stream(SSE) 代理时后端 4173 尚未 listen 而
// 出现 ECONNREFUSED。后端「重启」不影响 web(web 仅启动一次)。
// detached: 让子进程脱离控制台前台进程组,Ctrl+C 不会直接发给被 cmd 包裹的
// npm/vite,从而避免 Windows 弹出 "Terminate batch job (Y/N)?" 卡住。回收由
// supervisor 的 SIGINT/SIGTERM handler 统一 taskkill 完成。
const pipe = (stream, label) => {
  let buf = '';
  stream.on('data', (d) => {
    buf += d.toString();
    const lines = buf.split('\n');
    buf = lines.pop() ?? '';
    for (const line of lines) out_write(tag(label) + line + '\n');
  });
};
let web = null;
function startWeb() {
  if (web && !web.killed) return web;
  web = spawn('npm', ['--prefix', 'apps/web', 'run', 'dev'], {
    cwd: ROOT,
    env: { ...process.env },
    shell: true,
    windowsHide: true,
    detached: true,
  });
  pipe(web.stdout, 'web');
  pipe(web.stderr, 'web');
  web.on('exit', (code, signal) =>
    out_write(tag('web') + `exited (code=${code ?? 'null'}, signal=${signal ?? 'null'})\n`),
  );
  return web;
}

// ---- 后端(受 supervisor 管理的子进程)----
let backend = null;

function startBackend() {
  if (backend && !backend.killed) return backend;
  // 重启场景下旧后端可能尚未释放端口,启动前先回收,避免 EADDRINUSE。
  killStalePort(BACKEND_PORT);
  const p = spawn('npx', ['tsx', 'apps/server/src/index.ts'], {
    cwd: ROOT,
    env: { ...process.env, COD_SERVE_WEB: '0', COD_WEB_PORT: WEB_PORT, COD_PORT: String(BACKEND_PORT) },
    shell: true,
    windowsHide: true,
    detached: true,
  });
  pipe(p.stdout, 'server');
  pipe(p.stderr, 'server');
  p.on('exit', (code, signal) => {
    out_write(tag('server') + `exited (code=${code ?? 'null'}, signal=${signal ?? 'null'})\n`);
    if (backend === p) backend = null;
  });
  backend = p;
  return p;
}

// 轮询后端 /api/health,直到返回 200(或超时),用于启动初期与 web 同步,
// 确保 Vite 就绪时 4173 已在监听,避免 SSE 代理 ECONNREFUSED。
function waitForBackend(timeoutMs = 30000) {
  return new Promise((resolve) => {
    const probe = () => {
      const req = http.get(
        { host: '127.0.0.1', port: BACKEND_PORT, path: '/api/health', timeout: 1000 },
        (r) => {
          r.resume();
          if (r.statusCode === 200) {
            out_write(tag('dev') + `后端已就绪 (http://127.0.0.1:${BACKEND_PORT}/)\n`);
            resolve(true);
          } else {
            setTimeout(probe, 400);
          }
        },
      );
      req.on('error', () => setTimeout(probe, 400));
      req.on('timeout', () => {
        req.destroy();
        setTimeout(probe, 400);
      });
    };
    probe();
    // 超时兜底:即便后端迟迟未就绪,也照常拉起前端(SSE 会自行重连)。
    setTimeout(() => resolve(false), timeoutMs);
  });
}

function stopBackend() {
  if (!backend) return;
  const p = backend;
  backend = null;
  try {
    p.kill('SIGTERM');
  } catch {
    /* ignore */
  }
  // 兜底:Windows 上 SIGTERM 可能被忽略,树杀确保回收
  try {
    spawn('taskkill', ['/pid', String(p.pid), '/f', '/t'], { stdio: 'ignore', windowsHide: true });
  } catch {
    /* ignore */
  }
}

function restartBackend() {
  stopBackend();
  setTimeout(startBackend, 600);
}

// 信号监听:在启动序列之前注册,确保等待后端就绪期间也能优雅退出并回收子进程。
process.on('SIGINT', shutdown);
process.on('SIGTERM', shutdown);

// ---- 启动序列:后端先起,健康检查通过后(4173 已在监听)再拉起前端 ----
// 这样 Vite 就绪时后端已可用,前端首次 /api/stream(SSE) 代理不会 ECONNREFUSED。
startBackend();
await waitForBackend();
startWeb();

out_write(`\n\u001b[32mCodeRio 开发模式已启动(supervisor 常驻):\u001b[0m\n`);
out_write(`  前端 UI  : http://localhost:${WEB_PORT}/\n`);
out_write(`  后端 API : http://localhost:${BACKEND_PORT}/  (受 supervisor 管理,可在「设置」中启动/停止/重启)\n`);
out_write(`  supervisor: http://localhost:${CTL_PORT}/  (控制端口,常驻)\n`);
out_write(`  按 Ctrl+C 停止全部。\n\n`);

// ---- supervisor 控制 HTTP 服务(常驻,独立于后端)----
// 控制端口(4174)已在启动时由 killStalePort() 统一清理(见文件顶部),
// 上一次未彻底退出的 supervisor 进程在启动前已被回收,避免新进程 EADDRINUSE
// 以及前端代理打到没有 /shutdown 路由的旧代码。
const ctl = http.createServer((req, res) => {
  res.setHeader('Access-Control-Allow-Origin', '*');
  res.setHeader('Content-Type', 'application/json; charset=utf-8');
  const send = (code, obj) => {
    res.writeHead(code);
    res.end(JSON.stringify(obj));
  };
  const url = (req.url || '').split('?')[0];
  if (req.method === 'GET' && url === '/backend/status') {
    send(200, { running: !!(backend && !backend.killed) });
    return;
  }
  if (req.method === 'POST' && url === '/backend/stop') {
    stopBackend();
    send(200, { ok: true });
    return;
  }
  if (req.method === 'POST' && url === '/backend/start') {
    startBackend();
    send(200, { ok: true });
    return;
  }
  if (req.method === 'POST' && url === '/backend/restart') {
    restartBackend();
    send(200, { ok: true });
    return;
  }
  // 停止全部:supervisor 自杀式退出,按进程树回收前端(Vite)与后端。
  // 经 /devctl 调用,用于前端「停止全部」按钮;仅在开发模式(supervisor 常驻)可用。
  if (req.method === 'POST' && url === '/shutdown') {
    send(200, { ok: true });
    setTimeout(shutdown, 120);
    return;
  }
  send(404, { error: 'not found' });
});
function listenCtl(attempt = 0) {
  ctl.listen(CTL_PORT, '127.0.0.1');
  ctl.once('error', (err) => {
    if (err.code === 'EADDRINUSE' && attempt < 15) {
      setTimeout(() => listenCtl(attempt + 1), 300);
    } else {
      out_write(tag('supervisor') + `无法绑定 ${CTL_PORT}: ${err.message}\n`);
      process.exit(1);
    }
  });
}
ctl.once('listening', () => {
  out_write(tag('supervisor') + `control server on http://localhost:${CTL_PORT}/\n`);
});
listenCtl();

// ---- 退出时回收所有子进程 ----
let shutting = false;
function shutdown() {
  if (shutting) return;
  shutting = true;
  out_write(`\n\u001b[33m[dev] 收到退出信号,正在按进程树回收子进程...\u001b[0m\n`);
  stopBackend();
  try {
    spawn('taskkill', ['/pid', String(web.pid), '/f', '/t'], { stdio: 'ignore', windowsHide: true });
  } catch {
    try {
      web.kill('SIGTERM');
    } catch {
      /* ignore */
    }
  }
  setTimeout(() => process.exit(0), 600);
}