start.mjs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326
  1. #!/usr/bin/env node
  2. /**
  3. * 一键启动:环境自检 → 装依赖(缺什么装什么)→ 拉起 Python 工具服务 → 拉起 BFF → 打开浏览器。
  4. *
  5. * node scripts/start.mjs # 正常启动
  6. * node scripts/start.mjs --no-open # 不自动开浏览器
  7. * node scripts/start.mjs --skip-install # 跳过依赖安装检查(离线环境)
  8. * node scripts/start.mjs --rebuild # 强制重新构建前端/BFF
  9. *
  10. * 退出码:0 正常;1 环境不满足;2 依赖安装失败;3 服务启动失败。
  11. */
  12. import { spawn, spawnSync } from 'node:child_process';
  13. import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
  14. import net from 'node:net';
  15. import os from 'node:os';
  16. import path from 'node:path';
  17. const ROOT = path.resolve(import.meta.dirname, '..');
  18. const RUN_DIR = path.join(ROOT, '.run');
  19. const PID_FILE = path.join(RUN_DIR, 'pids.json');
  20. const args = new Set(process.argv.slice(2));
  21. const IS_WINDOWS = process.platform === 'win32';
  22. const VENV_PYTHON = path.join(ROOT, '.venv', IS_WINDOWS ? 'Scripts/python.exe' : 'bin/python');
  23. let PYTHON = process.env.CDA_PYTHON ?? (existsSync(VENV_PYTHON) ? VENV_PYTHON : (IS_WINDOWS ? 'python' : 'python3'));
  24. // --------------------------------------------------------------------- 输出
  25. const C = {
  26. reset: '\u001b[0m',
  27. dim: '\u001b[2m',
  28. green: '\u001b[32m',
  29. yellow: '\u001b[33m',
  30. red: '\u001b[31m',
  31. cyan: '\u001b[36m',
  32. bold: '\u001b[1m',
  33. };
  34. const paint = (color, text) => `${C[color]}${text}${C.reset}`;
  35. const step = (index, total, text) => console.log(`${paint('cyan', `[${index}/${total}]`)} ${text}`);
  36. const info = (text) => console.log(` ${C.dim}${text}${C.reset}`);
  37. const ok = (text) => console.log(` ${paint('green', '✓')} ${text}`);
  38. const warn = (text) => console.log(` ${paint('yellow', '!')} ${text}`);
  39. const fail = (text) => console.error(` ${paint('red', '✗')} ${text}`);
  40. function loadDotEnv() {
  41. const file = path.join(ROOT, '.env');
  42. if (!existsSync(file)) return;
  43. for (const rawLine of readFileSync(file, 'utf8').split(/\r?\n/)) {
  44. const line = rawLine.trim();
  45. if (!line || line.startsWith('#')) continue;
  46. const index = line.indexOf('=');
  47. if (index <= 0) continue;
  48. const key = line.slice(0, index).trim();
  49. let value = line.slice(index + 1).trim();
  50. if ((value.startsWith('"') && value.endsWith('"')) || (value.startsWith("'") && value.endsWith("'"))) {
  51. value = value.slice(1, -1);
  52. }
  53. if (process.env[key] === undefined) process.env[key] = value;
  54. }
  55. }
  56. function needsShell(command) {
  57. // 只有 .cmd/.bat 需要走 cmd.exe;python/node 直接 spawn 更安全(也避免 DEP0190 警告)
  58. return IS_WINDOWS && /\.(cmd|bat)$/i.test(command);
  59. }
  60. function run(command, argv, options = {}) {
  61. const result = spawnSync(command, argv, {
  62. cwd: options.cwd ?? ROOT,
  63. stdio: options.capture ? 'pipe' : 'inherit',
  64. shell: needsShell(command),
  65. env: { ...process.env, ...(options.env ?? {}) },
  66. encoding: 'utf8',
  67. });
  68. return { code: result.status ?? 1, stdout: result.stdout ?? '', stderr: result.stderr ?? '' };
  69. }
  70. function probePython() {
  71. const result = run(PYTHON, ['--version'], { capture: true });
  72. if (result.code !== 0) return null;
  73. return (result.stdout || result.stderr).trim();
  74. }
  75. function pythonHasDeps() {
  76. const code = 'import fastapi, uvicorn, openpyxl, multipart, pydantic; print("ok")';
  77. const result = run(PYTHON, ['-c', code], { capture: true, cwd: path.join(ROOT, 'tools-service') });
  78. return result.code === 0 && result.stdout.includes('ok');
  79. }
  80. function portFree(port) {
  81. return new Promise((resolve) => {
  82. const server = net.createServer();
  83. server.once('error', () => resolve(false));
  84. server.once('listening', () => server.close(() => resolve(true)));
  85. server.listen(port, '127.0.0.1');
  86. });
  87. }
  88. async function waitFor(url, timeoutMs, label) {
  89. const deadline = Date.now() + timeoutMs;
  90. while (Date.now() < deadline) {
  91. try {
  92. const response = await fetch(url, { signal: AbortSignal.timeout(2500) });
  93. if (response.ok) return true;
  94. } catch {
  95. /* 还没起来 */
  96. }
  97. await new Promise((resolve) => setTimeout(resolve, 600));
  98. }
  99. fail(`${label} 在 ${Math.round(timeoutMs / 1000)} 秒内没有就绪:${url}`);
  100. return false;
  101. }
  102. function openBrowser(url) {
  103. if (IS_WINDOWS) {
  104. spawn('cmd', ['/c', 'start', '""', url], { detached: true, stdio: 'ignore' }).unref();
  105. } else if (process.platform === 'darwin') {
  106. spawn('open', [url], { detached: true, stdio: 'ignore' }).unref();
  107. } else {
  108. spawn('xdg-open', [url], { detached: true, stdio: 'ignore' }).unref();
  109. }
  110. }
  111. const children = [];
  112. function startProcess(name, command, argv, options = {}) {
  113. const child = spawn(command, argv, {
  114. cwd: options.cwd ?? ROOT,
  115. env: { ...process.env, ...(options.env ?? {}) },
  116. stdio: options.silent ? 'ignore' : 'inherit',
  117. shell: needsShell(command),
  118. });
  119. child.on('exit', (code, signal) => {
  120. if (!shuttingDown && name !== 'X') {
  121. console.log(`\n${paint('yellow', `[${name}] 进程退出 code=${code} signal=${signal}`)}`);
  122. if (!options.optional) shutdown(1);
  123. }
  124. });
  125. children.push({ name, child });
  126. return child;
  127. }
  128. let shuttingDown = false;
  129. function shutdown(code = 0) {
  130. if (shuttingDown) return;
  131. shuttingDown = true;
  132. console.log(`\n${paint('dim', '正在停止服务…')}`);
  133. for (const { name, child } of children.slice().reverse()) {
  134. try {
  135. if (IS_WINDOWS) {
  136. spawnSync('taskkill', ['/pid', String(child.pid), '/T', '/F'], { stdio: 'ignore' });
  137. } else {
  138. child.kill('SIGTERM');
  139. }
  140. console.log(` ${paint('dim', '已停止')} ${name}`);
  141. } catch {
  142. /* 忽略 */
  143. }
  144. }
  145. try {
  146. if (existsSync(PID_FILE)) writeFileSync(PID_FILE, JSON.stringify({ stoppedAt: new Date().toISOString() }, null, 2));
  147. } catch {
  148. /* 忽略 */
  149. }
  150. setTimeout(() => process.exit(code), 300);
  151. }
  152. process.on('SIGINT', () => shutdown(0));
  153. process.on('SIGTERM', () => shutdown(0));
  154. // --------------------------------------------------------------------- main
  155. async function main() {
  156. console.log(paint('bold', '\n海关问数 Agent · 一键启动\n'));
  157. const total = 7;
  158. loadDotEnv();
  159. PYTHON = process.env.CDA_PYTHON ?? PYTHON;
  160. mkdirSync(RUN_DIR, { recursive: true });
  161. // 1. Node
  162. step(1, total, '检查运行环境');
  163. const nodeMajor = Number(process.versions.node.split('.')[0]);
  164. if (nodeMajor < 22) {
  165. fail(`Node 版本过低:${process.version},需要 >= 22.5(推荐 24.x)`);
  166. return 1;
  167. }
  168. ok(`Node ${process.version}`);
  169. const pythonVersion = probePython();
  170. if (!pythonVersion) {
  171. fail(`找不到 Python(命令:${PYTHON})。请安装 Python 3.11+ 并加入 PATH,或用 CDA_PYTHON 指定路径。`);
  172. return 1;
  173. }
  174. ok(`${pythonVersion}(${PYTHON})`);
  175. // 2. 端口
  176. step(2, total, '检查端口占用');
  177. const port = Number(process.env.CDA_PORT ?? 8787);
  178. const toolsPort = Number(process.env.CDA_TOOLS_PORT ?? 8788);
  179. for (const [label, value] of [
  180. ['BFF', port],
  181. ['工具服务', toolsPort],
  182. ]) {
  183. if (!(await portFree(value))) {
  184. warn(`${label} 端口 ${value} 已被占用,可能已经启动过(可直接访问 http://127.0.0.1:${port})`);
  185. } else {
  186. ok(`${label} 端口 ${value} 可用`);
  187. }
  188. }
  189. // 3. Python 依赖
  190. step(3, total, '检查 Python 依赖');
  191. if (args.has('--skip-install')) {
  192. warn('按 --skip-install 跳过依赖安装');
  193. } else if (pythonHasDeps()) {
  194. ok('fastapi / uvicorn / openpyxl / python-multipart 已安装');
  195. } else {
  196. const wheels = path.join(ROOT, 'offline', 'wheels');
  197. const offline = existsSync(wheels);
  198. info(offline ? `离线安装:使用 ${wheels}` : '在线安装:从 PyPI 拉取');
  199. const installArgs = ['-m', 'pip', 'install', '-r', 'requirements.txt'];
  200. if (offline) installArgs.push('--no-index', '--find-links', wheels);
  201. const result = run(PYTHON, installArgs, { cwd: path.join(ROOT, 'tools-service') });
  202. if (result.code !== 0) {
  203. fail('Python 依赖安装失败。离线环境请把 wheel 放进 offline/wheels 后重试。');
  204. return 2;
  205. }
  206. ok('Python 依赖安装完成');
  207. }
  208. // 4. BFF / 前端构建
  209. step(4, total, '检查构建产物');
  210. const bffEntry = path.join(ROOT, 'bff', 'dist', 'src', 'index.js');
  211. const webEntry = path.join(ROOT, 'web', 'dist', 'index.html');
  212. const needBuild = args.has('--rebuild') || !existsSync(bffEntry) || !existsSync(webEntry);
  213. if (!needBuild) {
  214. ok('BFF 与前端已构建(web/dist 存在)');
  215. } else if (args.has('--skip-install')) {
  216. if (!existsSync(bffEntry)) {
  217. fail('缺少 bff/dist,且指定了 --skip-install。请先执行 npm install && npm run build。');
  218. return 2;
  219. }
  220. warn('缺少前端构建产物,将只提供 API(页面无法打开)');
  221. } else {
  222. for (const [name, dir] of [
  223. ['BFF', path.join(ROOT, 'bff')],
  224. ['前端', path.join(ROOT, 'web')],
  225. ]) {
  226. if (!existsSync(path.join(dir, 'node_modules'))) {
  227. info(`${name}:安装 npm 依赖(首次较慢)`);
  228. const npmCommand = IS_WINDOWS ? 'npm.cmd' : 'npm';
  229. const installed = run(npmCommand, ['install', '--no-audit', '--no-fund'], { cwd: dir });
  230. if (installed.code !== 0) {
  231. fail(`${name} npm install 失败`);
  232. return 2;
  233. }
  234. }
  235. info(`${name}:构建`);
  236. const npmCommand = IS_WINDOWS ? 'npm.cmd' : 'npm';
  237. const built = run(npmCommand, ['run', 'build'], { cwd: dir });
  238. if (built.code !== 0) {
  239. fail(`${name} 构建失败`);
  240. return 2;
  241. }
  242. ok(`${name} 构建完成`);
  243. }
  244. }
  245. // 5. 工具服务
  246. step(5, total, '启动 Python 工具服务');
  247. if (!(await portFree(toolsPort))) {
  248. warn(`工具服务端口 ${toolsPort} 已被占用,跳过启动(复用已有进程)`);
  249. } else {
  250. startProcess('tools', PYTHON, ['-m', 'toolsvc'], {
  251. cwd: path.join(ROOT, 'tools-service'),
  252. env: { CDA_DATA_DIR: process.env.CDA_DATA_DIR ?? path.join(ROOT, 'data'), CDA_TOOLS_PORT: String(toolsPort) },
  253. });
  254. if (!(await waitFor(`http://127.0.0.1:${toolsPort}/health`, 90_000, '工具服务'))) return 3;
  255. ok(`工具服务就绪:http://127.0.0.1:${toolsPort}`);
  256. }
  257. // 6. BFF
  258. step(6, total, '启动 BFF(Web/API)');
  259. if (!(await portFree(port))) {
  260. warn(`BFF 端口 ${port} 已被占用;如果你刚启动过,直接打开页面即可`);
  261. } else {
  262. startProcess('bff', process.execPath, [bffEntry], {
  263. env: {
  264. CDA_TOOLS_URL: process.env.CDA_TOOLS_URL ?? `http://127.0.0.1:${toolsPort}`,
  265. CDA_PORT: String(port),
  266. CDA_BFF_DATA_DIR: process.env.CDA_BFF_DATA_DIR ?? path.join(ROOT, 'data', 'bff'),
  267. },
  268. });
  269. if (!(await waitFor(`http://127.0.0.1:${port}/api/health`, 60_000, 'BFF'))) return 3;
  270. ok(`BFF 就绪:http://127.0.0.1:${port}`);
  271. }
  272. // 7. 完成
  273. step(7, total, '启动完成');
  274. const url = `http://127.0.0.1:${port}`;
  275. console.log(`\n ${paint('green', paint('bold', '海关问数 Agent 已启动'))}`);
  276. console.log(` 地址:${paint('cyan', url)}`);
  277. console.log(` 数据目录:${paint('dim', path.join(ROOT, 'data'))}`);
  278. if (!process.env.DEEPSEEK_API_KEY) {
  279. console.log(` ${paint('yellow', '注意:未配置 DEEPSEEK_API_KEY,对话功能不可用(数据处理仍可用)')}`);
  280. console.log(` ${paint('dim', '在项目根目录创建 .env,写入 DEEPSEEK_API_KEY=sk-xxx 后重启')}`);
  281. }
  282. console.log(` ${paint('dim', '按 Ctrl+C 停止全部服务')}\n`);
  283. writeFileSync(
  284. PID_FILE,
  285. JSON.stringify({ startedAt: new Date().toISOString(), url, children: children.map((item) => ({ name: item.name, pid: item.child.pid })) }, null, 2),
  286. );
  287. if (!args.has('--no-open')) openBrowser(url);
  288. // 保持前台运行(Ctrl+C 停止)
  289. await new Promise(() => {});
  290. }
  291. main()
  292. .then((code) => {
  293. if (typeof code === 'number') shutdown(code);
  294. })
  295. .catch((error) => {
  296. fail(`启动失败:${error?.stack ?? error}`);
  297. shutdown(3);
  298. });