ASGI: Wait for response to complete before sending disconnect message (#919)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
* asgi: Wait for response to complete before sending disconnect message * Dial back type checking + remove concurrency module * Remove somewhat redundant comment
authored by Jamie Hewland · committed by GitHub · parent 560b119 · Browse files · 4 files·+31 added−8 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
4 files+31 added−8 removed
- tests:+1 added−2 removed
- other:+30 added−6 removed
Provenance
- Commit
d568ecd- Tree
9bad467- Author
Jamie Hewland <jhewland@gmail.com>- Committer
GitHub <noreply@github.com>- Parent
560b119
4 files changed+31 added−8 removed
modified:httpx/_dispatch/asgi.py+28 added-6 removed
1+import typing2 from typing import Callable, Dict, List, Optional, Tuple3 4 import httpcore5+import sniffio6 7 from .._content_streams import ByteStream8 9+if typing.TYPE_CHECKING: # pragma: no cover10+ import asyncio11+ import trio12 13+ Event = typing.Union[asyncio.Event, trio.Event]14+15+16+def create_event() -> "Event":17+ if sniffio.current_async_library() == "trio":18+ import trio19+20+ return trio.Event()21+ else:22+ import asyncio23+24+ return asyncio.Event()25+26+27 class ASGIDispatch(httpcore.AsyncHTTPTransport):28 """29 A custom AsyncDispatcher that handles sending requests directly to an ASGI app.30 The simplest way to use this functionality is to use the `app` argument.63 unmodified lines94 }95 status_code = None96 response_headers = None97 body_parts = []98+ request_complete = False99 response_started = False80- response_complete = False100+ response_complete = create_event()101 102 headers = [] if headers is None else headers103 stream = ByteStream(b"") if stream is None else stream104 105 request_body_chunks = stream.__aiter__()106 107 async def receive() -> dict:88- nonlocal response_complete108+ nonlocal request_complete, response_complete109 90- if response_complete:110+ if request_complete:111+ await response_complete.wait()112 return {"type": "http.disconnect"}113 114 try:115 body = await request_body_chunks.__anext__()116 except StopAsyncIteration:117+ request_complete = True118 return {"type": "http.request", "body": b"", "more_body": False}119 return {"type": "http.request", "body": body, "more_body": True}120 121 async def send(message: dict) -> None:7 unmodified lines129 response_headers = message.get("headers", [])130 response_started = True131 132 elif message["type"] == "http.response.body":111- assert not response_complete133+ assert not response_complete.is_set()134 body = message.get("body", b"")135 more_body = message.get("more_body", False)136 137 if body and method != b"HEAD":138 body_parts.append(body)139 140 if not more_body:119- response_complete = True141+ response_complete.set()142 143 try:144 await self.app(scope, receive, send)145 except Exception:146 if self.raise_app_exceptions or not response_complete:147 raise148 127- assert response_complete149+ assert response_complete.is_set()150 assert status_code is not None151 assert response_headers is not None152 153 stream = ByteStream(b"".join(body_parts))2 unmodified linesmodified:tests/test_asgi.py+1 added-2 removed
67 unmodified lines68 with pytest.raises(ValueError):69 await client.get("http://www.example.org/")70 71 72-@pytest.mark.asyncio73-async def test_asgi_disconnect_after_response_complete():72+async def test_asgi_disconnect_after_response_complete(async_environment):73 disconnect = False74 75 async def read_body(scope, receive, send):76 nonlocal disconnect25 unmodified linesmodified:requirements.txt+1 added
24 unmodified lines25 pytest-asyncio26 pytest-trio27 pytest-cov28 trio29+trio-typing30 trustme31 uvicorn32 seed-isort-config33 1 unmodified linemodified:setup.py+1 added
59 unmodified lines60 "chardet==3.*",61 "idna==2.*",62 "rfc3986>=1.3,<2",63 "httpcore>=0.8.3",64+ "sniffio",65 ],66 classifiers=[67 "Development Status :: 4 - Beta",68 "Environment :: Web Environment",13 unmodified lines