"""One shared HTTP client per call chain, without making anyone pass one. Reading an episode is three or four requests to two hosts, and doing them on one client is the difference between one connection and four. But the public functions here are also meant to be usable one at a time — `transcript(video)` should not require the caller to have stood up a client first. So every entry point takes an optional client and wraps it in this: given one, it is borrowed and left open for whoever owns it; given `None`, a client is made and closed on the way out. The `with` statement at the call site reads the same either way. """ from __future__ import annotations from contextlib import AbstractContextManager import httpx class _Borrowed(AbstractContextManager["httpx.Client"]): """Someone else's client. Enters and exits without owning anything.""" def __init__(self, client: httpx.Client) -> None: self._client = client def __enter__(self) -> httpx.Client: return self._client def __exit__(self, *exc: object) -> None: return None def session(client: httpx.Client | None, timeout: float = 30) -> AbstractContextManager[httpx.Client]: """A context manager yielding a client, owning it only if it made it.""" if client is not None: return _Borrowed(client) return httpx.Client(timeout=timeout, follow_redirects=True)