Skip to content

add health check point #1556

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
47 changes: 42 additions & 5 deletions backend/app/main.py
Original file line number Diff line number Diff line change
@@ -1,16 +1,18 @@
import time
from datetime import datetime
import sentry_sdk
from fastapi import FastAPI
from fastapi import FastAPI, Depends
from fastapi.routing import APIRoute
from starlette.middleware.cors import CORSMiddleware
from sqlalchemy.ext.asyncio import AsyncSession

from app.api.main import api_router
from app.core.config import settings

from app.db.session import async_session # Make sure this import exists

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


if settings.SENTRY_DSN and settings.ENVIRONMENT != "local":
sentry_sdk.init(dsn=str(settings.SENTRY_DSN), enable_tracing=True)

Expand All @@ -20,7 +22,42 @@ def custom_generate_unique_id(route: APIRoute) -> str:
generate_unique_id_function=custom_generate_unique_id,
)

# Set all CORS enabled origins
# --- Enhanced Health Check ---
async def check_db_health() -> dict:
"""Test database connectivity with latency measurement"""
start_time = time.monotonic()
try:
async with async_session() as db:
await db.execute("SELECT 1")
return {
"status": "ok",
"latency_ms": int((time.monotonic() - start_time) * 1000)
}
except Exception as e:
return {"status": "error", "error": str(e)}

@app.get("/health", tags=["health"], include_in_schema=False) # Hidden from docs
async def health_check(verbose: bool = False):
"""Enhanced health endpoint with system diagnostics"""
db_status = await check_db_health()

response = {
"status": "ok" if db_status["status"] == "ok" else "degraded",
"service": settings.PROJECT_NAME,
"version": settings.VERSION,
"timestamp": datetime.utcnow().isoformat(),
}

if verbose or db_status["status"] != "ok":
response["details"] = {
"database": db_status,
# Add other checks here (redis, storage, etc.)
}

return response
# --- End Health Check ---

# Existing CORS setup
if settings.all_cors_origins:
app.add_middleware(
CORSMiddleware,
Expand All @@ -30,4 +67,4 @@ def custom_generate_unique_id(route: APIRoute) -> str:
allow_headers=["*"],
)

app.include_router(api_router, prefix=settings.API_V1_STR)
app.include_router(api_router, prefix=settings.API_V1_STR)
Loading