Skip to content

Commit e96bab1

Browse files
feat(http): implement shared HTTP client for image fetching
- Create a shared httpx.AsyncClient to reuse connections and reduce overhead - Update _fetch_image to use the shared client for improved performance - Modify image fetching to prefer thumbnails for faster loading
1 parent 3af0372 commit e96bab1

File tree

1 file changed

+22
-7
lines changed

1 file changed

+22
-7
lines changed

api/routers/og_images.py

Lines changed: 22 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -60,12 +60,25 @@ async def get_catalog_og_image(request: Request) -> Response:
6060
)
6161

6262

63+
_http_client: httpx.AsyncClient | None = None
64+
65+
66+
def _get_http_client() -> httpx.AsyncClient:
67+
"""Get or create a shared httpx client for connection reuse (avoids per-request TLS handshakes)."""
68+
global _http_client
69+
if _http_client is None or _http_client.is_closed:
70+
_http_client = httpx.AsyncClient(
71+
timeout=30.0,
72+
limits=httpx.Limits(max_connections=10, max_keepalive_connections=5),
73+
)
74+
return _http_client
75+
76+
6377
async def _fetch_image(url: str) -> bytes:
64-
"""Fetch an image from a URL."""
65-
async with httpx.AsyncClient(timeout=30.0) as client:
66-
response = await client.get(url)
67-
response.raise_for_status()
68-
return response.content
78+
"""Fetch an image from a URL using the shared HTTP client."""
79+
response = await _get_http_client().get(url)
80+
response.raise_for_status()
81+
return response.content
6982

7083

7184
@router.get("/{spec_id}/{library}.png")
@@ -154,8 +167,10 @@ async def get_spec_collage_image(
154167
selected_impls = sorted_impls[:6]
155168

156169
try:
157-
# Fetch all images in parallel for better performance
158-
images = list(await asyncio.gather(*[_fetch_image(impl.preview_url) for impl in selected_impls]))
170+
# Fetch all images in parallel — prefer thumbnails (smaller, faster)
171+
images = list(
172+
await asyncio.gather(*[_fetch_image(impl.preview_thumb or impl.preview_url) for impl in selected_impls])
173+
)
159174
labels = [f"{spec_id} · {impl.library_id}" for impl in selected_impls]
160175

161176
# Create collage

0 commit comments

Comments
 (0)