42 lines
1.3 KiB
Python
42 lines
1.3 KiB
Python
"""
|
|
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."
|
|
}
|
|
)
|
|
|