Spaces:
Sleeping
Sleeping
chore: upload app/api/health.py
Browse files- app/api/health.py +55 -0
app/api/health.py
ADDED
|
@@ -0,0 +1,55 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""健康检查 + 探活."""
|
| 2 |
+
from __future__ import annotations
|
| 3 |
+
|
| 4 |
+
import logging
|
| 5 |
+
|
| 6 |
+
from fastapi import APIRouter, Request
|
| 7 |
+
|
| 8 |
+
from app.config import settings
|
| 9 |
+
from app.deps import get_llm, persist_status
|
| 10 |
+
from app.models.schemas import HealthStatus
|
| 11 |
+
|
| 12 |
+
router = APIRouter(tags=["health"])
|
| 13 |
+
logger = logging.getLogger(__name__)
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
@router.get("/healthz", response_model=HealthStatus)
|
| 17 |
+
async def healthz() -> HealthStatus:
|
| 18 |
+
"""Liveness 探针. 不检查外部依赖, 永远返回 ok (只要进程在)."""
|
| 19 |
+
return HealthStatus(
|
| 20 |
+
status="ok",
|
| 21 |
+
llm=True, # 进程在即代表 LLM 单例已建 (或尝试过)
|
| 22 |
+
persist=persist_status(),
|
| 23 |
+
chroma=False, # 阶段 2 接入
|
| 24 |
+
version=settings.app_version,
|
| 25 |
+
)
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
@router.get("/readyz", response_model=HealthStatus)
|
| 29 |
+
async def readyz(request: Request) -> HealthStatus:
|
| 30 |
+
"""Readiness 探针. 检查 LLM 实际可达 + Chroma + 持久化模式."""
|
| 31 |
+
llm_ok = False
|
| 32 |
+
try:
|
| 33 |
+
llm = get_llm()
|
| 34 |
+
llm_ok = await llm.health_check()
|
| 35 |
+
except Exception as e: # noqa: BLE001
|
| 36 |
+
logger.warning("readyz: LLM health check error: %s", e)
|
| 37 |
+
|
| 38 |
+
chroma_ok = False
|
| 39 |
+
try:
|
| 40 |
+
from app.services.vector_store import get_chroma
|
| 41 |
+
_, coll, _ = get_chroma()
|
| 42 |
+
chroma_ok = coll.count() >= 0 # 任意 count 都不报错即说明连接通
|
| 43 |
+
except Exception as e: # noqa: BLE001
|
| 44 |
+
logger.warning("readyz: Chroma check error: %s", e)
|
| 45 |
+
|
| 46 |
+
persist = persist_status()
|
| 47 |
+
overall = "ok" if (llm_ok and chroma_ok) else "degraded"
|
| 48 |
+
|
| 49 |
+
return HealthStatus(
|
| 50 |
+
status=overall,
|
| 51 |
+
llm=llm_ok,
|
| 52 |
+
persist=persist,
|
| 53 |
+
chroma=chroma_ok,
|
| 54 |
+
version=settings.app_version,
|
| 55 |
+
)
|