1+ import time
2+ from datetime import datetime
13import sentry_sdk
2- from fastapi import FastAPI
4+ from fastapi import FastAPI , Depends
35from fastapi .routing import APIRoute
46from starlette .middleware .cors import CORSMiddleware
7+ from sqlalchemy .ext .asyncio import AsyncSession
58
69from app .api .main import api_router
710from app .core .config import settings
8-
11+ from app . db . session import async_session # Make sure this import exists
912
1013def custom_generate_unique_id (route : APIRoute ) -> str :
1114 return f"{ route .tags [0 ]} -{ route .name } "
1215
13-
1416if settings .SENTRY_DSN and settings .ENVIRONMENT != "local" :
1517 sentry_sdk .init (dsn = str (settings .SENTRY_DSN ), enable_tracing = True )
1618
@@ -20,12 +22,42 @@ def custom_generate_unique_id(route: APIRoute) -> str:
2022 generate_unique_id_function = custom_generate_unique_id ,
2123)
2224
23- # Add health check endpoint directly to main app
24- @app .get ("/health" , tags = ["health" ])
25- async def health_check ():
26- return {"status" : "ok" , "message" : "Service is healthy" }
25+ # --- Enhanced Health Check ---
26+ async def check_db_health () -> dict :
27+ """Test database connectivity with latency measurement"""
28+ start_time = time .monotonic ()
29+ try :
30+ async with async_session () as db :
31+ await db .execute ("SELECT 1" )
32+ return {
33+ "status" : "ok" ,
34+ "latency_ms" : int ((time .monotonic () - start_time ) * 1000 )
35+ }
36+ except Exception as e :
37+ return {"status" : "error" , "error" : str (e )}
38+
39+ @app .get ("/health" , tags = ["health" ], include_in_schema = False ) # Hidden from docs
40+ async def health_check (verbose : bool = False ):
41+ """Enhanced health endpoint with system diagnostics"""
42+ db_status = await check_db_health ()
43+
44+ response = {
45+ "status" : "ok" if db_status ["status" ] == "ok" else "degraded" ,
46+ "service" : settings .PROJECT_NAME ,
47+ "version" : settings .VERSION ,
48+ "timestamp" : datetime .utcnow ().isoformat (),
49+ }
50+
51+ if verbose or db_status ["status" ] != "ok" :
52+ response ["details" ] = {
53+ "database" : db_status ,
54+ # Add other checks here (redis, storage, etc.)
55+ }
56+
57+ return response
58+ # --- End Health Check ---
2759
28- # Set all CORS enabled origins
60+ # Existing CORS setup
2961if settings .all_cors_origins :
3062 app .add_middleware (
3163 CORSMiddleware ,
0 commit comments