1
+ import time
2
+ from datetime import datetime
1
3
import sentry_sdk
2
- from fastapi import FastAPI
4
+ from fastapi import FastAPI , Depends
3
5
from fastapi .routing import APIRoute
4
6
from starlette .middleware .cors import CORSMiddleware
7
+ from sqlalchemy .ext .asyncio import AsyncSession
5
8
6
9
from app .api .main import api_router
7
10
from app .core .config import settings
8
-
11
+ from app . db . session import async_session # Make sure this import exists
9
12
10
13
def custom_generate_unique_id (route : APIRoute ) -> str :
11
14
return f"{ route .tags [0 ]} -{ route .name } "
12
15
13
-
14
16
if settings .SENTRY_DSN and settings .ENVIRONMENT != "local" :
15
17
sentry_sdk .init (dsn = str (settings .SENTRY_DSN ), enable_tracing = True )
16
18
@@ -20,12 +22,42 @@ def custom_generate_unique_id(route: APIRoute) -> str:
20
22
generate_unique_id_function = custom_generate_unique_id ,
21
23
)
22
24
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 ---
27
59
28
- # Set all CORS enabled origins
60
+ # Existing CORS setup
29
61
if settings .all_cors_origins :
30
62
app .add_middleware (
31
63
CORSMiddleware ,
0 commit comments