Coverage for src/robot_dispatch/api/routers/health.py: 89%

27 statements  

« prev     ^ index     » next       coverage.py v7.17.2, created at 2026-11-07 17:18 +0000

1from __future__ import annotations 

2 

3from typing import Annotated 

4 

5from fastapi import APIRouter, Depends, Response, status 

6 

7from robot_dispatch.api.deps import get_broker, get_settings_dep, get_uow_factory 

8from robot_dispatch.api.schemas import HealthResponse 

9from robot_dispatch.config import Settings 

10from robot_dispatch.messaging.broker import Broker 

11from robot_dispatch.repositories.protocols import UnitOfWorkFactory 

12 

13router = APIRouter(prefix="/health", tags=["health"]) 

14 

15 

16@router.get("/live", response_model=HealthResponse) 

17async def liveness() -> HealthResponse: 

18 return HealthResponse(status="ok", checks={}) 

19 

20 

21@router.get("/ready", response_model=HealthResponse) 

22async def readiness( 

23 response: Response, 

24 uow_factory: Annotated[UnitOfWorkFactory, Depends(get_uow_factory)], 

25 broker: Annotated[Broker | None, Depends(get_broker)], 

26 settings: Annotated[Settings, Depends(get_settings_dep)], 

27) -> HealthResponse: 

28 checks: dict[str, str] = {} 

29 

30 try: 

31 async with uow_factory() as uow: 

32 await uow.tasks.count_by_status() 

33 checks["database"] = "ok" 

34 except Exception as exc: # noqa: BLE001 - readiness must report, not raise 

35 checks["database"] = f"error: {exc}" 

36 

37 if settings.database_url: # broker is optional for the API process 

38 checks["rabbitmq"] = "ok" if broker is not None and broker.connected else "unavailable" 

39 

40 healthy = checks.get("database") == "ok" 

41 if not healthy: 

42 response.status_code = status.HTTP_503_SERVICE_UNAVAILABLE 

43 return HealthResponse(status="ok" if healthy else "degraded", checks=checks)