|
| 1 | +import logging |
| 2 | +from datetime import UTC, datetime |
| 3 | +from typing import Annotated |
| 4 | + |
| 5 | +from fastapi import APIRouter, Depends, status |
| 6 | +from fastapi.responses import JSONResponse |
| 7 | +from redis.asyncio import Redis |
| 8 | +from sqlalchemy.ext.asyncio import AsyncSession |
| 9 | + |
| 10 | +from ...core.config import settings |
| 11 | +from ...core.db.database import async_get_db |
| 12 | +from ...core.health import check_database_health, check_redis_health |
| 13 | +from ...core.schemas import HealthCheck, ReadyCheck |
| 14 | +from ...core.utils.cache import async_get_redis |
| 15 | + |
| 16 | +router = APIRouter(tags=["health"]) |
| 17 | + |
| 18 | +STATUS_HEALTHY = "healthy" |
| 19 | +STATUS_UNHEALTHY = "unhealthy" |
| 20 | + |
| 21 | +LOGGER = logging.getLogger(__name__) |
| 22 | + |
| 23 | + |
| 24 | +@router.get("/health", response_model=HealthCheck) |
| 25 | +async def health(): |
| 26 | + http_status = status.HTTP_200_OK |
| 27 | + response = { |
| 28 | + "status": STATUS_HEALTHY, |
| 29 | + "environment": settings.ENVIRONMENT.value, |
| 30 | + "version": settings.APP_VERSION, |
| 31 | + "timestamp": datetime.now(UTC).isoformat(timespec="seconds"), |
| 32 | + } |
| 33 | + |
| 34 | + return JSONResponse(status_code=http_status, content=response) |
| 35 | + |
| 36 | + |
| 37 | +@router.get("/ready", response_model=ReadyCheck) |
| 38 | +async def ready(redis: Annotated[Redis, Depends(async_get_redis)], db: Annotated[AsyncSession, Depends(async_get_db)]): |
| 39 | + database_status = await check_database_health(db=db) |
| 40 | + LOGGER.debug(f"Database health check status: {database_status}") |
| 41 | + redis_status = await check_redis_health(redis=redis) |
| 42 | + LOGGER.debug(f"Redis health check status: {redis_status}") |
| 43 | + |
| 44 | + overall_status = STATUS_HEALTHY if database_status and redis_status else STATUS_UNHEALTHY |
| 45 | + http_status = status.HTTP_200_OK if overall_status == STATUS_HEALTHY else status.HTTP_503_SERVICE_UNAVAILABLE |
| 46 | + |
| 47 | + response = { |
| 48 | + "status": overall_status, |
| 49 | + "environment": settings.ENVIRONMENT.value, |
| 50 | + "version": settings.APP_VERSION, |
| 51 | + "app": STATUS_HEALTHY, |
| 52 | + "database": STATUS_HEALTHY if database_status else STATUS_UNHEALTHY, |
| 53 | + "redis": STATUS_HEALTHY if redis_status else STATUS_UNHEALTHY, |
| 54 | + "timestamp": datetime.now(UTC).isoformat(timespec="seconds"), |
| 55 | + } |
| 56 | + |
| 57 | + return JSONResponse(status_code=http_status, content=response) |
0 commit comments