update
This commit is contained in:
41
Backend/src/middleware/timeout.py
Normal file
41
Backend/src/middleware/timeout.py
Normal file
@@ -0,0 +1,41 @@
|
||||
"""
|
||||
Request timeout middleware
|
||||
"""
|
||||
import asyncio
|
||||
from fastapi import Request, HTTPException, status
|
||||
from starlette.middleware.base import BaseHTTPMiddleware
|
||||
from ..config.logging_config import get_logger
|
||||
from ..config.settings import settings
|
||||
|
||||
logger = get_logger(__name__)
|
||||
|
||||
|
||||
class TimeoutMiddleware(BaseHTTPMiddleware):
|
||||
"""Add timeout to requests"""
|
||||
|
||||
async def dispatch(self, request: Request, call_next):
|
||||
try:
|
||||
# Use asyncio.wait_for to add timeout
|
||||
response = await asyncio.wait_for(
|
||||
call_next(request),
|
||||
timeout=settings.REQUEST_TIMEOUT
|
||||
)
|
||||
return response
|
||||
except asyncio.TimeoutError:
|
||||
logger.warning(
|
||||
f"Request timeout: {request.method} {request.url.path}",
|
||||
extra={
|
||||
"request_id": getattr(request.state, "request_id", None),
|
||||
"method": request.method,
|
||||
"path": request.url.path,
|
||||
"timeout": settings.REQUEST_TIMEOUT
|
||||
}
|
||||
)
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_504_GATEWAY_TIMEOUT,
|
||||
detail={
|
||||
"status": "error",
|
||||
"message": "Request timeout. Please try again."
|
||||
}
|
||||
)
|
||||
|
||||
Reference in New Issue
Block a user