Added /health check for Prometheus and added failure capturing incase something went wrong, previous approach would not increase the counter
All checks were successful
Build & Publish to GHCR / build (push) Successful in 14s
All checks were successful
Build & Publish to GHCR / build (push) Successful in 14s
This commit is contained in:
parent
e944acaedd
commit
4d586f4371
32
src/main.py
32
src/main.py
@ -1,4 +1,4 @@
|
|||||||
from fastapi import FastAPI, Depends, HTTPException, Request
|
from fastapi import FastAPI, Depends, HTTPException, Request, JSONResponse
|
||||||
from fastapi.responses import JSONResponse
|
from fastapi.responses import JSONResponse
|
||||||
from fastapi.security.api_key import APIKeyHeader
|
from fastapi.security.api_key import APIKeyHeader
|
||||||
from starlette.exceptions import HTTPException as StarletteHTTPException
|
from starlette.exceptions import HTTPException as StarletteHTTPException
|
||||||
@ -53,12 +53,36 @@ api = FastAPI(
|
|||||||
lifespan=lifespan
|
lifespan=lifespan
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
@api.middleware("http")
|
@api.middleware("http")
|
||||||
async def prometheus_middleware(request, call_next):
|
async def prometheus_middleware(request: Request, call_next):
|
||||||
response = await call_next(request)
|
status = 500
|
||||||
REQUEST_COUNTER.labels(request.method, request.url.path, response.status_code).inc()
|
try:
|
||||||
|
response = await call_next(request)
|
||||||
|
status = response.status_code
|
||||||
|
except Exception:
|
||||||
|
raise
|
||||||
|
finally:
|
||||||
|
REQUEST_COUNTER.labels(request.method, request.url.path, status).inc()
|
||||||
return response
|
return response
|
||||||
|
|
||||||
|
@api.get("/health", tags=["Health"])
|
||||||
|
async def return_health(db=Depends(get_db)):
|
||||||
|
try:
|
||||||
|
cursor = db.cursor()
|
||||||
|
cursor.execute("SELECT 1")
|
||||||
|
cursor.fetchone()
|
||||||
|
db_status = "ok"
|
||||||
|
except Exception:
|
||||||
|
logger.error(f"Health check DB failed: {e}")
|
||||||
|
db_status = "error"
|
||||||
|
|
||||||
|
return JSONResponse(
|
||||||
|
status_code=200 if db_status == "ok" else 500,
|
||||||
|
content={"status": db_status, "message": "Service is running"}
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
def verify_api_key_dependency(db=Depends(get_db), api_key: str = Depends(api_key_header)) -> int:
|
def verify_api_key_dependency(db=Depends(get_db), api_key: str = Depends(api_key_header)) -> int:
|
||||||
cursor = db.cursor()
|
cursor = db.cursor()
|
||||||
cursor.execute("SELECT user_id, api_key FROM users WHERE status = 'active'")
|
cursor.execute("SELECT user_id, api_key FROM users WHERE status = 'active'")
|
||||||
|
|||||||
Loading…
x
Reference in New Issue
Block a user