"""Health check and error metrics endpoints.""" import logging from fastapi import APIRouter, Depends, HTTPException, status from sqlalchemy import text from sqlalchemy.ext.asyncio import AsyncSession from cartsnitch_api.auth.dependencies import verify_service_key from cartsnitch_api.database import get_db from cartsnitch_api.middleware.error_handler import get_error_monitor logger = logging.getLogger(__name__) router = APIRouter(tags=["health"]) @router.get("/health") async def health(db: AsyncSession = Depends(get_db)): """Liveness + DB connectivity probe. Returns HTTP 200 when the API process is responsive *and* the database is reachable, so Kubernetes readiness probes can correctly route traffic away from pods that have lost their database connection. Returns HTTP 503 when the database is unreachable so K8s marks the pod unhealthy and stops sending traffic to it. """ try: await db.execute(text("SELECT 1")) except Exception as exc: logger.exception("Health check failed: database unreachable") raise HTTPException( status_code=status.HTTP_503_SERVICE_UNAVAILABLE, detail={"status": "unavailable", "database": "disconnected"}, ) from exc return {"status": "ok", "database": "connected"} @router.get("/internal/error-stats", dependencies=[Depends(verify_service_key)]) async def error_stats(): """Error monitoring stats — internal only (requires X-Service-Key).""" monitor = get_error_monitor() return monitor.get_stats()