Stream response body in ASGITransport

KL
5mo ago
+201-85

Ports encode/httpx#3059 (by @jhominal), but integrated into ASGITransport itself rather than as a separate ASGIStreamingTransport class.

The app now runs in a separate task, and response events are streamed as they arrive: a response is returned as soon as the app sends http.response.start, and body chunks can be iterated before the app has fully run. This makes it possible to test streaming endpoints (e.g. SSE) through the ASGI transport, including apps that call send from a sub-task such as Starlette's StreamingResponse.

Differences from the upstream PR:

  • Implemented with anyio directly (hard dependency here), dropping the trio/asyncio dual-path helpers.
  • Closing a response mid-stream no longer breaks: GeneratorExit is caught at the yield and the app task is cancelled, instead of letting it propagate through the task group where anyio/trio would wrap it in a BaseExceptionGroup (found by the new early-close test; the upstream PR never exercised this path).
  • ASGIResponseStream.__aiter__ has no finally cleanup - closing goes through the aclose() chain like BoundAsyncStream, since awaiting cleanup in generator finalization is rejected by trio.

Behavioural notes: the app runs in a separate task, so context variables set within the app are no longer visible to the caller, and exceptions raised after http.response.start now surface while reading the body rather than from handle_async_request (still raised from client.get() for non-streamed requests).

AI Disclaimer

This PR was developed with the assistance of either Claude or Codex. I've reviewed and verified the changes.