|
| 1 | +"""Client pool for efficient connection reuse.""" |
| 2 | + |
| 3 | +import asyncio |
| 4 | +import atexit |
| 5 | +import threading |
| 6 | +from collections.abc import AsyncIterator |
| 7 | +from contextlib import asynccontextmanager |
| 8 | +from typing import Any |
| 9 | + |
| 10 | +import httpx |
| 11 | + |
| 12 | +from .config import get_config |
| 13 | +from .transport import httpx_client_factory |
| 14 | + |
| 15 | +# global client pool keyed by config |
| 16 | +_clients: dict[tuple[str, str], httpx.AsyncClient] = {} |
| 17 | +_lock = threading.Lock() |
| 18 | + |
| 19 | + |
| 20 | +def _make_client_key(config: dict[str, Any]) -> tuple[str, str]: |
| 21 | + """Generate a unique key for client pooling based on config.""" |
| 22 | + base_url = config.get("data_api_root_url") or "" |
| 23 | + api_key = config.get("api_key") or "" |
| 24 | + return (base_url, api_key) |
| 25 | + |
| 26 | + |
| 27 | +def get_client() -> httpx.AsyncClient: |
| 28 | + """Get or create a client for the current config. Thread-safe.""" |
| 29 | + config = get_config() |
| 30 | + key = _make_client_key(config) |
| 31 | + |
| 32 | + # fast path: no lock if client exists |
| 33 | + if key in _clients: |
| 34 | + return _clients[key] |
| 35 | + |
| 36 | + # slow path: acquire lock for creation |
| 37 | + with _lock: |
| 38 | + # double-check after acquiring lock |
| 39 | + if key not in _clients: |
| 40 | + base_url = config.get("data_api_root_url") |
| 41 | + if not base_url: |
| 42 | + raise RuntimeError("data_api_root_url") |
| 43 | + api_key = config.get("api_key") |
| 44 | + if not api_key: |
| 45 | + raise RuntimeError("api_key") |
| 46 | + _clients[key] = httpx_client_factory(base_url=base_url, api_key=api_key) |
| 47 | + return _clients[key] |
| 48 | + |
| 49 | + |
| 50 | +async def close_clients() -> None: |
| 51 | + """Close all clients in the pool. Thread-safe. Safe to call multiple times.""" |
| 52 | + with _lock: |
| 53 | + clients_to_close = list(_clients.values()) |
| 54 | + _clients.clear() |
| 55 | + |
| 56 | + for client in clients_to_close: |
| 57 | + await client.aclose() |
| 58 | + |
| 59 | + |
| 60 | +@asynccontextmanager |
| 61 | +async def client_scope() -> AsyncIterator[None]: |
| 62 | + """Scope that ensures close_clients() is called on exit.""" |
| 63 | + try: |
| 64 | + yield |
| 65 | + finally: |
| 66 | + await close_clients() |
| 67 | + |
| 68 | + |
| 69 | +def _atexit_cleanup() -> None: |
| 70 | + """Best-effort cleanup at interpreter exit.""" |
| 71 | + with _lock: |
| 72 | + clients_to_close = list(_clients.values()) |
| 73 | + _clients.clear() |
| 74 | + |
| 75 | + if not clients_to_close: |
| 76 | + return |
| 77 | + |
| 78 | + # check if there's already a running loop |
| 79 | + try: |
| 80 | + running_loop = asyncio.get_running_loop() |
| 81 | + except RuntimeError: |
| 82 | + running_loop = None |
| 83 | + |
| 84 | + try: |
| 85 | + if running_loop is not None: |
| 86 | + # loop still running at atexit, schedule cleanup tasks |
| 87 | + for client in clients_to_close: |
| 88 | + running_loop.create_task(client.aclose()) |
| 89 | + else: |
| 90 | + # no running loop, create one for cleanup |
| 91 | + loop = asyncio.new_event_loop() |
| 92 | + for client in clients_to_close: |
| 93 | + loop.run_until_complete(client.aclose()) |
| 94 | + loop.close() |
| 95 | + except Exception: |
| 96 | + pass |
| 97 | + |
| 98 | + |
| 99 | +atexit.register(_atexit_cleanup) |
0 commit comments