diff --git a/app/common/http_client.py b/app/common/http_client.py index cbe40e3..e721b3c 100644 --- a/app/common/http_client.py +++ b/app/common/http_client.py @@ -7,6 +7,16 @@ logger = getLogger(__name__) +async_proxy_mounts = { + "http://": httpx.AsyncHTTPTransport(proxy=config.http_proxy), + "https://": httpx.AsyncHTTPTransport(proxy=config.http_proxy) +} if config.http_proxy else {} + +sync_proxy_mounts = { + "http://": httpx.HTTPTransport(proxy=config.http_proxy), + "https://": httpx.HTTPTransport(proxy=config.http_proxy) +} if config.http_proxy else {} + async def async_hook_request_tracing(request): trace_id = ctx_trace_id.get(None) @@ -20,12 +30,43 @@ def hook_request_tracing(request): request.headers[config.tracing_header] = trace_id -# Provides an instacne of httpx.AsyncClient with preconfigured hooks for -# propagating the x-cdp-request-id header to allow requets to be traced across -# service boundaries as well as adding in request/response logging. -def async_client(): - return httpx.AsyncClient(event_hooks={"request": [async_hook_request_tracing]}) +def create_async_client(request_timeout: int = 30) -> httpx.AsyncClient: + """ + Create an async HTTP client with configurable timeout. + + Args: + request_timeout: Request timeout in seconds + + Returns: + Configured httpx.AsyncClient instance + """ + client_kwargs = { + "timeout": request_timeout, + "event_hooks": {"request": [async_hook_request_tracing]} + } + + if config.http_proxy: + client_kwargs["mounts"] = async_proxy_mounts + + return httpx.AsyncClient(**client_kwargs) + + +def create_client(request_timeout: int = 30) -> httpx.Client: + """ + Create a sync HTTP client with configurable timeout. + + Args: + request_timeout: Request timeout in seconds + + Returns: + Configured httpx.Client instance + """ + client_kwargs = { + "timeout": request_timeout, + "event_hooks": {"request": [hook_request_tracing]} + } + if config.http_proxy: + client_kwargs["mounts"] = sync_proxy_mounts -def client(): - return httpx.Client(event_hooks={"request": [hook_request_tracing]}) + return httpx.Client(**client_kwargs) diff --git a/app/example/router.py b/app/example/router.py index 5b5c4b4..acd2af3 100644 --- a/app/example/router.py +++ b/app/example/router.py @@ -2,7 +2,7 @@ from fastapi import APIRouter, Depends -from app.common.http_client import async_client +from app.common.http_client import create_async_client from app.common.mongo import get_db from app.config import config @@ -25,7 +25,7 @@ async def db_query(db=Depends(get_db)): @router.get("/http") -async def http_query(client=Depends(async_client)): +async def http_query(client=Depends(create_async_client)): endpoint = config.aws_endpoint_url or "http://localstack:4566" resp = await client.get(f"{endpoint}/health") return {"ok": resp.status_code}