diff --git a/src/baby_monitor/routers/health.py b/src/baby_monitor/routers/health.py index 9bf7c88..64e71ed 100644 --- a/src/baby_monitor/routers/health.py +++ b/src/baby_monitor/routers/health.py @@ -1,6 +1,7 @@ """Health check router for monitoring endpoints.""" -from fastapi import APIRouter +import os +from fastapi import APIRouter, HTTPException router = APIRouter(tags=["health"]) @@ -20,11 +21,51 @@ def readiness_check() -> dict[str, str]: """ Readiness check endpoint for container orchestration. - Returns 200 if the service is ready to accept traffic. - This can include checks for database connectivity, external services, etc. + Returns 200 if the service is ready to accept traffic, else 503. """ - # Add dependency checks here if needed (database, cache, etc.) - # For now, simple readiness check + + # Determine if configured to use Redis + redis_uri = os.getenv("REDIS_URI") + + # If Redis is used, check connectivity + if redis_uri: + try: + import redis + redis_client = redis.from_url(redis_uri) + redis_client.ping() + except Exception as exc: + raise HTTPException( + status_code=503, + detail={ + "status": "not ready", + "reason": "No connection to Redis", + "exception": str(exc), + }, + ) from exc + # Determine if configured to use PostgreSQL + postgres_uri = os.getenv("POSTGRES_URI") + + # If PostgreSQL is used, check connectivity + if postgres_uri: + try: + from sqlalchemy import create_engine + from sqlalchemy.orm import sessionmaker + from sqlalchemy import text + engine = create_engine(postgres_uri) + SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine) + with SessionLocal() as db: + db.execute(text("SELECT 1")) + except Exception as exc: + raise HTTPException( + status_code=503, + detail={ + "status": "not ready", + "reason": "No connection to PostgreSQL", + "exception": str(exc), + }, + ) from exc + + # Unable to prove not ready, so assume ready return {"status": "ready"} @@ -60,9 +101,10 @@ def service_info() -> dict: # Check current configuration config = { "environment": os.getenv("ENVIRONMENT", "production"), - "data_dir": os.getenv("DATA_DIR", "/data"), - "redis_configured": bool(os.getenv("REDIS_URI")), } + if not features["postgresql"]: + config["data_dir"] = os.getenv("DATA_DIR", "/data") + return { "service": "baby-monitor",