diff --git a/muxplex/main.py b/muxplex/main.py index 434eab9..cb5417f 100644 --- a/muxplex/main.py +++ b/muxplex/main.py @@ -180,15 +180,16 @@ async def lifespan(app: FastAPI): yield - await app.state.federation_client.aclose() - - # Shutdown: cancel the poll loop task and wait for it to finish. - if _poll_task is not None: - _poll_task.cancel() - try: - await _poll_task - except (asyncio.CancelledError, Exception): - pass + try: + await app.state.federation_client.aclose() + finally: + # Shutdown: cancel the poll loop task and wait for it to finish. + if _poll_task is not None: + _poll_task.cancel() + try: + await _poll_task + except (asyncio.CancelledError, Exception): + pass # --------------------------------------------------------------------------- diff --git a/muxplex/tests/test_api.py b/muxplex/tests/test_api.py index 339142e..4234bbc 100644 --- a/muxplex/tests/test_api.py +++ b/muxplex/tests/test_api.py @@ -1464,3 +1464,10 @@ def test_federation_client_exists_on_app_state(monkeypatch): assert isinstance(app.state.federation_client, httpx.AsyncClient), ( "app.state.federation_client must be an httpx.AsyncClient instance" ) + # Capture reference before lifespan shuts down + client_ref = app.state.federation_client + + # After lifespan shutdown completes, the client must be closed + assert client_ref.is_closed, ( + "app.state.federation_client must be closed after lifespan shutdown" + )