implement-ready-endpoint-logic #42

Merged
brian merged 3 commits from implement-ready-endpoint-logic into main 2026-01-27 21:26:08 +01:00
Showing only changes of commit b2aa71b95b - Show all commits
+49 -7
View File
@@ -1,6 +1,7 @@
"""Health check router for monitoring endpoints.""" """Health check router for monitoring endpoints."""
from fastapi import APIRouter import os
from fastapi import APIRouter, HTTPException
router = APIRouter(tags=["health"]) router = APIRouter(tags=["health"])
@@ -20,11 +21,51 @@ def readiness_check() -> dict[str, str]:
""" """
Readiness check endpoint for container orchestration. Readiness check endpoint for container orchestration.
Returns 200 if the service is ready to accept traffic. Returns 200 if the service is ready to accept traffic, else 503.
This can include checks for database connectivity, external services, etc.
""" """
# 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"} return {"status": "ready"}
@@ -60,9 +101,10 @@ def service_info() -> dict:
# Check current configuration # Check current configuration
config = { config = {
"environment": os.getenv("ENVIRONMENT", "production"), "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 { return {
"service": "baby-monitor", "service": "baby-monitor",