From 167a7456879ffccd6ff64fec49a9289fdfac6de1 Mon Sep 17 00:00:00 2001 From: sw3205933776 <3205933776@qq.com> Date: Thu, 6 Nov 2025 11:22:36 +0800 Subject: [PATCH 1/2] fix: add health check polling to ensure backend is ready before resolving --- backend/app/controller/health_controller.py | 16 +++++ backend/app/router.py | 7 +- electron/main/init.ts | 78 +++++++++++++++++++-- 3 files changed, 94 insertions(+), 7 deletions(-) create mode 100644 backend/app/controller/health_controller.py diff --git a/backend/app/controller/health_controller.py b/backend/app/controller/health_controller.py new file mode 100644 index 00000000..296655bf --- /dev/null +++ b/backend/app/controller/health_controller.py @@ -0,0 +1,16 @@ +from fastapi import APIRouter +from pydantic import BaseModel + +router = APIRouter(tags=["Health"]) + + +class HealthResponse(BaseModel): + status: str + service: str + + +@router.get("/health", name="health check", response_model=HealthResponse) +async def health_check(): + """Health check endpoint for verifying backend is ready to accept requests.""" + return HealthResponse(status="ok", service="eigent") + diff --git a/backend/app/router.py b/backend/app/router.py index c311d316..3fc6cb25 100644 --- a/backend/app/router.py +++ b/backend/app/router.py @@ -3,7 +3,7 @@ All routers are explicitly registered here for better visibility and maintainability. """ from fastapi import FastAPI -from app.controller import chat_controller, model_controller, task_controller, tool_controller +from app.controller import chat_controller, model_controller, task_controller, tool_controller, health_controller from utils import traceroot_wrapper as traceroot logger = traceroot.get_logger("router") @@ -23,6 +23,11 @@ def register_routers(app: FastAPI, prefix: str = "") -> None: prefix: Optional global prefix for all routes (e.g., "/api") """ routers_config = [ + { + "router": health_controller.router, + "tags": ["Health"], + "description": "Health check endpoint for service readiness" + }, { "router": chat_controller.router, "tags": ["chat"], diff --git a/electron/main/init.ts b/electron/main/init.ts index 11ed6ef3..55f02b89 100644 --- a/electron/main/init.ts +++ b/electron/main/init.ts @@ -4,6 +4,7 @@ import log from 'electron-log' import fs from 'fs' import path from 'path' import * as net from "net"; +import * as http from "http"; import { ipcMain, BrowserWindow, app } from 'electron' import { promisify } from 'util' import { detectInstallationLogs, PromiseReturnType } from "./install-deps"; @@ -195,21 +196,85 @@ export async function startBackend(setPort?: (port: number) => void): Promise { if (!started) { + if (healthCheckInterval) clearInterval(healthCheckInterval); node_process.kill(); reject(new Error('Backend failed to start within timeout')); } }, 30000); // 30 second timeout + // Helper function to poll health endpoint + const pollHealthEndpoint = (): void => { + let attempts = 0; + const maxAttempts = 20; // 5 seconds total (20 * 250ms) + const intervalMs = 250; + + healthCheckInterval = setInterval(() => { + attempts++; + const healthUrl = `http://127.0.0.1:${port}/health`; + + const req = http.get(healthUrl, { timeout: 1000 }, (res) => { + if (res.statusCode === 200) { + log.info(`Backend health check passed after ${attempts} attempts`); + started = true; + clearTimeout(startTimeout); + if (healthCheckInterval) clearInterval(healthCheckInterval); + resolve(node_process); + } else { + // Non-200 status (e.g., 404), continue polling unless max attempts reached + if (attempts >= maxAttempts) { + log.error(`Backend health check failed after ${attempts} attempts with status ${res.statusCode}`); + started = true; + clearTimeout(startTimeout); + if (healthCheckInterval) clearInterval(healthCheckInterval); + node_process.kill(); + reject(new Error(`Backend health check failed: HTTP ${res.statusCode}`)); + } + } + }); + + req.on('error', () => { + // Connection error - backend might not be ready yet, continue polling + if (attempts >= maxAttempts) { + log.error(`Backend health check failed after ${attempts} attempts: unable to connect`); + started = true; + clearTimeout(startTimeout); + if (healthCheckInterval) clearInterval(healthCheckInterval); + node_process.kill(); + reject(new Error('Backend health check failed: unable to connect')); + } + }); + + req.on('timeout', () => { + req.destroy(); + if (attempts >= maxAttempts) { + log.error(`Backend health check timed out after ${attempts} attempts`); + started = true; + clearTimeout(startTimeout); + if (healthCheckInterval) clearInterval(healthCheckInterval); + node_process.kill(); + reject(new Error('Backend health check timed out')); + } + }); + }, intervalMs); + + // Clear interval after max attempts + setTimeout(() => { + if (healthCheckInterval && !started) { + clearInterval(healthCheckInterval); + healthCheckInterval = null; + } + }, maxAttempts * intervalMs); + }; node_process.stdout.on('data', (data) => { displayFilteredLogs(data); // check output content, judge if start success if (!started && data.toString().includes("Uvicorn running on")) { - started = true; - clearTimeout(startTimeout); - resolve(node_process); + log.info('Uvicorn startup detected, starting health check polling...'); + pollHealthEndpoint(); } }); @@ -217,9 +282,8 @@ export async function startBackend(setPort?: (port: number) => void): Promise void): Promise void): Promise { clearTimeout(startTimeout); + if (healthCheckInterval) clearInterval(healthCheckInterval); if (!started) { reject(new Error(`fastapi exited with code ${code}`)); } From 70f3fafbdd9ccb97062a7d5f852157bf1c7491c9 Mon Sep 17 00:00:00 2001 From: Sun Tao <2605127667@qq.com> Date: Thu, 6 Nov 2025 15:01:24 +0800 Subject: [PATCH 2/2] minor update --- electron/main/init.ts | 8 -------- 1 file changed, 8 deletions(-) diff --git a/electron/main/init.ts b/electron/main/init.ts index 55f02b89..b09db659 100644 --- a/electron/main/init.ts +++ b/electron/main/init.ts @@ -259,14 +259,6 @@ export async function startBackend(setPort?: (port: number) => void): Promise { - if (healthCheckInterval && !started) { - clearInterval(healthCheckInterval); - healthCheckInterval = null; - } - }, maxAttempts * intervalMs); }; node_process.stdout.on('data', (data) => {