import time import requests from fastapi import APIRouter, Depends from sqlalchemy.orm import Session from sqlalchemy import text from typing import Any, Dict from app.core.database.db_session import get_db from app.core.config.Config import settings from app.core.permissions.RoleChecker import RoleChecker router = APIRouter(prefix="/health", tags=["System Health & Telemetry"]) @router.get("", response_model=Dict[str, Any]) def get_overall_health(db: Session = Depends(get_db)) -> Dict[str, Any]: """Lightweight public health check for load balancers and uptime monitoring.""" try: db.execute(text("SELECT 1")) db_ok = True except Exception: db_ok = False return { "status": "healthy" if db_ok else "degraded", "timestamp": int(time.time()) } @router.get("/detailed", response_model=Dict[str, Any], dependencies=[Depends(RoleChecker(["Super Admin", "Admin"]))]) def get_detailed_health(db: Session = Depends(get_db)) -> Dict[str, Any]: """Returns detailed health telemetry across core components (Admin only).""" db_status = check_db_health(db) redis_status = check_redis_health() whatsapp_status = check_whatsapp_health() email_status = check_email_health() all_healthy = all( c.get("status") in ["healthy", "connected", "ready"] for c in [db_status, redis_status] ) return { "status": "healthy" if all_healthy else "degraded", "service": settings.PROJECT_NAME, "environment": settings.ENVIRONMENT, "timestamp": time.time(), "components": { "database": db_status, "redis_streams": redis_status, "whatsapp_gateway": whatsapp_status, "email_gateway": email_status } } @router.get("/db", dependencies=[Depends(RoleChecker(["Super Admin", "Admin"]))]) def check_db_endpoint(db: Session = Depends(get_db)) -> Dict[str, Any]: """Endpoint checking MySQL database connectivity and latency (Admin only).""" return check_db_health(db) @router.get("/redis", dependencies=[Depends(RoleChecker(["Super Admin", "Admin"]))]) def check_redis_endpoint() -> Dict[str, Any]: """Endpoint checking Redis Streams connection and queue depth (Admin only).""" return check_redis_health() @router.get("/whatsapp", dependencies=[Depends(RoleChecker(["Super Admin", "Admin"]))]) def check_whatsapp_endpoint() -> Dict[str, Any]: """Endpoint checking OpenWA WhatsApp Web gateway connection state (Admin only).""" return check_whatsapp_health() @router.get("/email", dependencies=[Depends(RoleChecker(["Super Admin", "Admin"]))]) def check_email_endpoint() -> Dict[str, Any]: """Endpoint checking ZeptoMail / Zoho CPaaS email gateway configuration (Admin only).""" return check_email_health() def check_db_health(db: Session) -> Dict[str, Any]: start = time.time() try: db.execute(text("SELECT 1")) latency_ms = round((time.time() - start) * 1000, 2) return {"status": "healthy", "latency_ms": latency_ms} except Exception as e: return {"status": "unhealthy", "error": str(e)} def check_redis_health() -> Dict[str, Any]: start = time.time() try: import redis client = redis.Redis.from_url(settings.REDIS_URL, decode_responses=True, socket_timeout=1) ping_res = client.ping() latency_ms = round((time.time() - start) * 1000, 2) return {"status": "healthy" if ping_res else "unhealthy", "latency_ms": latency_ms} except Exception as e: return {"status": "offline_fallback", "notice": "Events fallback to DB audit stream", "error": str(e)} def check_whatsapp_health() -> Dict[str, Any]: try: res = requests.get(f"{settings.OPENWA_GATEWAY_URL}/status", timeout=1.5) if res.status_code == 200: data = res.json() return { "status": "connected" if data.get("state") == "CONNECTED" else "disconnected", "session_state": data.get("state", "DISCONNECTED"), "battery_level": data.get("battery", None) } except Exception: pass return { "status": "standby", "gateway_url": settings.OPENWA_GATEWAY_URL, "notice": "OpenWA microservice ready for QR pairing" } def check_email_health() -> Dict[str, Any]: return { "status": "ready", "provider": "ZeptoMail / Zoho CPaaS", "sender_email": settings.EMAIL_SENDER_ADDRESS, "api_endpoint": settings.ZEPTOMAIL_API_ENDPOINT, "configured": bool(settings.ZEPTOMAIL_API_KEY) }