Skip to content

Commit 47a61af

Browse files
author
mohamedachrefhacheni
committed
enhanced health check system
1 parent d713437 commit 47a61af

File tree

1 file changed

+40
-8
lines changed

1 file changed

+40
-8
lines changed

backend/app/main.py

Lines changed: 40 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,18 @@
1+
import time
2+
from datetime import datetime
13
import sentry_sdk
2-
from fastapi import FastAPI
4+
from fastapi import FastAPI, Depends
35
from fastapi.routing import APIRoute
46
from starlette.middleware.cors import CORSMiddleware
7+
from sqlalchemy.ext.asyncio import AsyncSession
58

69
from app.api.main import api_router
710
from app.core.config import settings
8-
11+
from app.db.session import async_session # Make sure this import exists
912

1013
def custom_generate_unique_id(route: APIRoute) -> str:
1114
return f"{route.tags[0]}-{route.name}"
1215

13-
1416
if 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
2961
if settings.all_cors_origins:
3062
app.add_middleware(
3163
CORSMiddleware,

0 commit comments

Comments
 (0)