health-check.ts 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. /**
  2. * 本地 dev 服务健康预热:在 e2e 运行前 fail-fast,
  3. * 避免服务掉线时把 page.goto('/') / authedPage 失败误判为业务回归。
  4. *
  5. * 边界:
  6. * - 仅检查可达性(Connection)+ 状态码 < 500;不校验业务响应
  7. * - 不引入新依赖(Node 18+ 内置 fetch)
  8. * - 不自动启动/重启服务;仅指明修复路径
  9. * - 不访问数据库
  10. */
  11. const WEB_URL = process.env.AIDOP_E2E_WEB_HEALTH_URL ?? 'http://localhost:8888/';
  12. const API_URL = process.env.AIDOP_E2E_API_HEALTH_URL ?? 'http://localhost:5005/';
  13. const TIMEOUT_MS = Number(process.env.AIDOP_E2E_HEALTH_TIMEOUT_MS ?? 5000);
  14. const RESTART_HINT = 'bash /home/yy968/work/New9S/restart_aidop.sh';
  15. type ProbeOutcome =
  16. | { ok: true; status: number }
  17. | { ok: false; reason: string };
  18. async function probe(name: string, url: string): Promise<ProbeOutcome> {
  19. const controller = new AbortController();
  20. const timer = setTimeout(() => controller.abort(), TIMEOUT_MS);
  21. try {
  22. const resp = await fetch(url, { method: 'GET', redirect: 'manual', signal: controller.signal });
  23. if (resp.status >= 500) {
  24. return { ok: false, reason: `${name} responded ${resp.status} (server-side error)` };
  25. }
  26. return { ok: true, status: resp.status };
  27. } catch (err: unknown) {
  28. const msg = err instanceof Error ? err.message : String(err);
  29. return { ok: false, reason: `${name} unreachable (${msg})` };
  30. } finally {
  31. clearTimeout(timer);
  32. }
  33. }
  34. export async function assertServicesHealthy(): Promise<void> {
  35. const [web, api] = await Promise.all([
  36. probe('Web', WEB_URL),
  37. probe('API', API_URL),
  38. ]);
  39. const failures: string[] = [];
  40. if (!web.ok) failures.push(` - Web ${WEB_URL} → ${web.reason}`);
  41. if (!api.ok) failures.push(` - API ${API_URL} → ${api.reason}`);
  42. if (failures.length > 0) {
  43. const msg = [
  44. '[e2e health-check] dev services are not healthy:',
  45. ...failures,
  46. '',
  47. `Fix: ${RESTART_HINT}`,
  48. '(or override URLs via AIDOP_E2E_WEB_HEALTH_URL / AIDOP_E2E_API_HEALTH_URL)',
  49. ].join('\n');
  50. throw new Error(msg);
  51. }
  52. // Concise success line so reviewers can confirm the gate ran.
  53. console.log(`[e2e health-check] OK Web=${web.status} API=${api.status}`);
  54. }