Fix race condition on stream.read (#535)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
* Fix race condition on stream.read * Refactor run_concurrently
authored by Florimond Manca · committed by GitHub · parent f06ca87 · Browse files · 4 files·+51 added−12 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+51 added−12 removed
- tests:+41 added−9 removed
- other:+10 added−3 removed
Provenance
- Commit
a05ba2e- Tree
9d1da94- Author
Florimond Manca <florimond.manca@gmail.com>- Committer
GitHub <noreply@github.com>- Parent
f06ca87
4 files changed+51 added−12 removed
modified:httpx/concurrency/asyncio.py+7 added-2 removed
49 unmodified lines50 ):51 self.stream_reader = stream_reader52 self.stream_writer = stream_writer53 self.timeout = timeout54+ self.read_lock = asyncio.Lock()55 56 self._inner: typing.Optional[SocketStream] = None57 58 async def start_tls(85 unmodified lines144 # grained retry loop if we're not yet in read-timeout mode.145 should_raise = flag is None or flag.raise_on_read_timeout146 read_timeout = timeout.read_timeout if should_raise else 0.01147 try:147- data = await asyncio.wait_for(self.stream_reader.read(n), read_timeout)148- break148+ async with self.read_lock:149+ data = await asyncio.wait_for(150+ self.stream_reader.read(n), read_timeout151+ )152 except asyncio.TimeoutError:153 if should_raise:154 raise ReadTimeout() from None155 # FIX(py3.6): yield control back to the event loop to give it a chance1 unmodified line157 # This prevents concurrent `.read()` calls, which asyncio158 # doesn't seem to allow on 3.6.159 # See: https://github.com/encode/httpx/issues/382160 await asyncio.sleep(0)161+ else:162+ break163 164 return data165 166 def write_no_block(self, data: bytes) -> None:192 unmodified linesmodified:httpx/concurrency/trio.py+3 added-1 removed
30 unmodified lines31 ) -> None:32 self.stream = stream33 self.timeout = timeout34 self.write_buffer = b""35+ self.read_lock = trio.Lock()36 self.write_lock = trio.Lock()37 38 async def start_tls(39 self, hostname: str, ssl_context: ssl.SSLContext, timeout: TimeoutConfig34 unmodified lines74 should_raise = flag is None or flag.raise_on_read_timeout75 read_timeout = _or_inf(timeout.read_timeout if should_raise else 0.01)76 77 with trio.move_on_after(read_timeout):78+ async with self.read_lock:77- return await self.stream.receive_some(max_bytes=n)79+ return await self.stream.receive_some(max_bytes=n)80 81 if should_raise:82 raise ReadTimeout() from None83 211 unmodified linesmodified:tests/concurrency.py+24 added-9 removed
3 unmodified lines4 """5 6 import asyncio7 import functools8+import typing9 10+import trio11+12 from httpx import AsyncioBackend13+from httpx.concurrency.trio import TrioBackend14 15 16 @functools.singledispatch17 async def sleep(backend, seconds: int):4 unmodified lines22 async def _sleep_asyncio(backend, seconds: int):23 await asyncio.sleep(seconds)24 25 22-try:23- import trio24- from httpx.concurrency.trio import TrioBackend25-except ImportError: # pragma: no cover26- pass27-else:26+@sleep.register(TrioBackend)27+async def _sleep_trio(backend, seconds: int):28+ await trio.sleep(seconds)29 29- @sleep.register(TrioBackend)30- async def _sleep_trio(backend, seconds: int):31- await trio.sleep(seconds)30+31+@functools.singledispatch32+async def run_concurrently(backend, *coroutines: typing.Callable[[], typing.Awaitable]):33+ raise NotImplementedError # pragma: no cover34+35+36+@run_concurrently.register(AsyncioBackend)37+async def _run_concurrently_asyncio(backend, *coroutines):38+ coros = (coroutine() for coroutine in coroutines)39+ await asyncio.gather(*coros)40+41+42+@run_concurrently.register(TrioBackend)43+async def _run_concurrently_trio(backend, *coroutines):44+ async with trio.open_nursery() as nursery:45+ for coroutine in coroutines:46+ nursery.start_soon(coroutine)modified:tests/test_concurrency.py+17 added
1 unmodified line2 import trio3 4 from httpx import AsyncioBackend, HTTPVersionConfig, SSLConfig, TimeoutConfig5 from httpx.concurrency.trio import TrioBackend6+from tests.concurrency import run_concurrently7 8 9 @pytest.mark.parametrize(10 "backend, get_cipher",61 unmodified lines72 assert read.startswith(b"HTTP/1.1 200 OK\r\n")73 74 finally:75 await stream.close()76+77+78+async def test_concurrent_read(server, backend):79+ """80+ Regression test for: https://github.com/encode/httpx/issues/52781+ """82+ stream = await backend.open_tcp_stream(83+ server.url.host, server.url.port, ssl_context=None, timeout=TimeoutConfig(5)84+ )85+ try:86+ await stream.write(b"GET / HTTP/1.1\r\n\r\n")87+ await run_concurrently(88+ backend, lambda: stream.read(10), lambda: stream.read(10)89+ )90+ finally:91+ await stream.close()