Files
OSIT-AE-API-FastAPI/app/routers/health.py
Scott Idem 32560d2257 feat: Operational hardening — healthcheck, config refactor, requirements lock
- Add GET /health route (DB + Redis ping, 200/503) with Dockerfile HEALTHCHECK directive
- Replace config.py stub with real pydantic BaseSettings reading directly from env vars;
  remove external config file mount from docker-compose
- Add requirements.lock (pip freeze snapshot for bit-identical builds)
- Untrack config.py globally but allow app/config.py via .gitignore negation

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-10 18:44:58 -04:00

43 lines
1.2 KiB
Python

"""
Health check endpoint for Docker orchestration.
Verifies DB and Redis connectivity.
"""
import logging
from fastapi import APIRouter
from fastapi.responses import JSONResponse
from sqlalchemy import text
log = logging.getLogger(__name__)
router = APIRouter()
@router.get('/health', tags=['Root'], include_in_schema=True)
async def health_check():
"""
Checks liveness of the DB and Redis connections.
Returns 200 if both are reachable, 503 otherwise.
"""
status = {'db': False, 'redis': False}
# --- DB check ---
try:
from app.lib_sql_core import engine
with engine.connect() as conn:
conn.execute(text('SELECT 1'))
status['db'] = True
except Exception as e:
log.error(f'Health check: DB ping failed: {e}')
# --- Redis check ---
try:
from app.lib_redis_helpers import redis_client
redis_client.ping()
status['redis'] = True
except Exception as e:
log.error(f'Health check: Redis ping failed: {e}')
all_ok = all(status.values())
http_status = 200 if all_ok else 503
return JSONResponse(content={'status': 'ok' if all_ok else 'degraded', **status}, status_code=http_status)