Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
55 changes: 48 additions & 7 deletions app/common/http_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand All @@ -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)
4 changes: 2 additions & 2 deletions app/example/router.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand All @@ -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}