From cc46a778002a673a731ec881b1df0c4f82a31708 Mon Sep 17 00:00:00 2001 From: Lutchy Horace Date: Wed, 2 Apr 2025 17:39:25 -0400 Subject: [PATCH] Refactored code completely, to work better! --- nginx_request_checker.py | 58 ++++++++++++++++++++++------------------ 1 file changed, 32 insertions(+), 26 deletions(-) diff --git a/nginx_request_checker.py b/nginx_request_checker.py index eeadc8e..dbb1145 100644 --- a/nginx_request_checker.py +++ b/nginx_request_checker.py @@ -1,6 +1,6 @@ from fastapi import FastAPI, Request, Response import redis -import httpx +import aiohttp import os import logging @@ -62,36 +62,42 @@ async def proxy_request(path: str, request: Request): """ return Response(content=error_xml, status_code=403, media_type="application/xml") - # Proxy request to MinIO + query_string = request.url.query minio_url = f"{MINIO_ENDPOINT}/{path}" + if query_string: + minio_url += f"?{query_string}" headers = dict(request.headers) - async with httpx.AsyncClient(timeout=300.0) as client: - logging.info(f"Proxying request to MinIO: {minio_url}") - if request.method in ["PUT", "POST"]: - # Stream request body to MinIO - async def request_stream(): - async for chunk in request.stream(): - yield chunk - - minio_response = await client.request( + try: + async with aiohttp.ClientSession() as session: + async with session.request( method=request.method, url=minio_url, headers=headers, - content=request_stream() - ) - else: - # For GET and DELETE, we don’t send a body - minio_response = await client.request( - method=request.method, - url=minio_url, - headers=headers - ) + data=request.stream() if request.method in ["PUT", "POST"] else None + ) as minio_response: + + # Try reading the response body + try: + body = await minio_response.read() + except aiohttp.ClientConnectionError: + body = b"" # If MinIO closes connection, return an empty response - logging.info(f"MinIO response: {minio_response.status_code}") + # Forward MinIO's response as-is + return Response( + content=body, + status_code=minio_response.status, + headers=dict(minio_response.headers) + ) - return Response( - content=minio_response.content, - status_code=minio_response.status_code, - headers=minio_response.headers - ) + except aiohttp.ClientConnectionError: + return Response(content=b"", status_code=200) # Silently ignore MinIO disconnection + + except aiohttp.ClientResponseError as e: + return Response(content=e.message, status_code=e.status) + + except aiohttp.ClientError: + return Response(content="An error occurred while communicating with MinIO.", status_code=502) + + except Exception: + return Response(content="Internal Server Error", status_code=500)