Skip to content
Myr

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

4 files+51 added−12 removed

modified:httpx/concurrency/asyncio.py+7 added-2 removed
49 unmodified lines
50 ):51 self.stream_reader = stream_reader52 self.stream_writer = stream_writer53 self.timeout = timeout54 self.read_lock = asyncio.Lock()5556 self._inner: typing.Optional[SocketStream] = None5758 async def start_tls(
85 unmodified lines
144 # 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 chance
1 unmodified line
157 # 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 break163164 return data165166 def write_no_block(self, data: bytes) -> None:
192 unmodified lines
modified:httpx/concurrency/trio.py+3 added-1 removed
30 unmodified lines
31 ) -> None:32 self.stream = stream33 self.timeout = timeout34 self.write_buffer = b""35 self.read_lock = trio.Lock()36 self.write_lock = trio.Lock()3738 async def start_tls(39 self, hostname: str, ssl_context: ssl.SSLContext, timeout: TimeoutConfig
34 unmodified lines
74 should_raise = flag is None or flag.raise_on_read_timeout75 read_timeout = _or_inf(timeout.read_timeout if should_raise else 0.01)7677 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)8081 if should_raise:82 raise ReadTimeout() from None83
211 unmodified lines
modified:tests/concurrency.py+24 added-9 removed
3 unmodified lines
4"""56import asyncio7import functools8import typing910import trio1112from httpx import AsyncioBackend13from httpx.concurrency.trio import TrioBackend141516@functools.singledispatch17async def sleep(backend, seconds: int):
4 unmodified lines
22async def _sleep_asyncio(backend, seconds: int):23 await asyncio.sleep(seconds)242522try:23 import trio24 from httpx.concurrency.trio import TrioBackend25except ImportError: # pragma: no cover26 pass27else:26@sleep.register(TrioBackend)27async def _sleep_trio(backend, seconds: int):28 await trio.sleep(seconds)2929 @sleep.register(TrioBackend)30 async def _sleep_trio(backend, seconds: int):31 await trio.sleep(seconds)3031@functools.singledispatch32async def run_concurrently(backend, *coroutines: typing.Callable[[], typing.Awaitable]):33 raise NotImplementedError # pragma: no cover343536@run_concurrently.register(AsyncioBackend)37async def _run_concurrently_asyncio(backend, *coroutines):38 coros = (coroutine() for coroutine in coroutines)39 await asyncio.gather(*coros)404142@run_concurrently.register(TrioBackend)43async 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 line
2import trio34from httpx import AsyncioBackend, HTTPVersionConfig, SSLConfig, TimeoutConfig5from httpx.concurrency.trio import TrioBackend6from tests.concurrency import run_concurrently789@pytest.mark.parametrize(10 "backend, get_cipher",
61 unmodified lines
72 assert read.startswith(b"HTTP/1.1 200 OK\r\n")7374 finally:75 await stream.close()767778async 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()