start.mjs 12 KB

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