Skip to content
Myr

Drop `run` and `run_in_threadpool` (#710)

Before adoption: this commit came in with the history the project adopted, so no landing records it.

* Drop run and run_in_threadpool * Fix server restart errors * Re-introduce 'sleep' as a concurrency test utility * Simpler test concurrency utils

authored by Tom Christie · committed by GitHub · parent bd57b65 · Browse files · 8 files+43 added−141 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Trailers

  • Co-authored-by: Florimond Manca <florimond.manca@gmail.com>

Diff stats

8 files+43 added−141 removed

  • tests:+43 added−82 removed
  • other:+0 added−59 removed

8 files+43 added−141 removed

modified:httpx/backends/asyncio.py-29 removed
1import asyncio2import functools2import ssl3import typing45from ..config import Timeout
174 unmodified lines
180 if not SSL_MONKEY_PATCH_APPLIED:181 ssl_monkey_patch()182 SSL_MONKEY_PATCH_APPLIED = True183185 @property186 def loop(self) -> asyncio.AbstractEventLoop:187 if not hasattr(self, "_loop"):188 try:189 self._loop = asyncio.get_event_loop()190 except RuntimeError:191 self._loop = asyncio.new_event_loop()192 return self._loop193184 async def open_tcp_stream(185 self,186 hostname: str,187 port: int,
34 unmodified lines
222 def time(self) -> float:223 loop = asyncio.get_event_loop()224 return loop.time()225236 async def run_in_threadpool(237 self, func: typing.Callable, *args: typing.Any, **kwargs: typing.Any238 ) -> typing.Any:239 if kwargs:240 # loop.run_in_executor doesn't accept 'kwargs', so bind them in here241 func = functools.partial(func, **kwargs)242 return await self.loop.run_in_executor(None, func, *args)243244 def run(245 self, coroutine: typing.Callable, *args: typing.Any, **kwargs: typing.Any246 ) -> typing.Any:247 loop = self.loop248 if loop.is_running():249 self._loop = asyncio.new_event_loop()250 try:251 return self.loop.run_until_complete(coroutine(*args, **kwargs))252 finally:253 self._loop = loop254226 def create_semaphore(self, max_value: int, exc_class: type) -> BaseSemaphore:227 return Semaphore(max_value, exc_class)228229 def create_lock(self) -> BaseLock:
33 unmodified lines
modified:httpx/backends/auto.py-5 removed
42 unmodified lines
4344 def time(self) -> float:45 return self.backend.time()4647 async def run_in_threadpool(48 self, func: typing.Callable, *args: typing.Any, **kwargs: typing.Any49 ) -> typing.Any:50 return await self.backend.run_in_threadpool(func, *args, **kwargs)5147 def create_semaphore(self, max_value: int, exc_class: type) -> BaseSemaphore:48 return self.backend.create_semaphore(max_value, exc_class)4950 def create_lock(self) -> BaseLock:
1 unmodified line
modified:httpx/backends/base.py-10 removed
112 unmodified lines
113114 def time(self) -> float:115 raise NotImplementedError() # pragma: no cover116117 async def run_in_threadpool(118 self, func: typing.Callable, *args: typing.Any, **kwargs: typing.Any119 ) -> typing.Any:120 raise NotImplementedError() # pragma: no cover121122 def run(123 self, coroutine: typing.Callable, *args: typing.Any, **kwargs: typing.Any124 ) -> typing.Any:125 raise NotImplementedError() # pragma: no cover126117 def create_semaphore(self, max_value: int, exc_class: type) -> BaseSemaphore:118 raise NotImplementedError() # pragma: no cover119120 def create_lock(self) -> BaseLock:
1 unmodified line
modified:httpx/backends/trio.py-15 removed
1import functools1import ssl2import typing34import trio
113 unmodified lines
118 return SocketStream(stream=stream)119120 raise ConnectTimeout()121123 async def run_in_threadpool(124 self, func: typing.Callable, *args: typing.Any, **kwargs: typing.Any125 ) -> typing.Any:126 return await trio.to_thread.run_sync(127 functools.partial(func, **kwargs) if kwargs else func, *args128 )129130 def run(131 self, coroutine: typing.Callable, *args: typing.Any, **kwargs: typing.Any132 ) -> typing.Any:133 return trio.run(134 functools.partial(coroutine, **kwargs) if kwargs else coroutine, *args135 )136122 def time(self) -> float:123 return trio.current_time()124125 def create_semaphore(self, max_value: int, exc_class: type) -> BaseSemaphore:
39 unmodified lines
modified:tests/dispatch/test_connection_pools.py+6 added-8 removed
165 unmodified lines
166 assert len(http.keepalive_connections) == 0167168169@pytest.mark.usefixtures("async_environment")170async def test_keepalive_connection_closed_by_server_is_reestablished(server, restart):170async def test_keepalive_connection_closed_by_server_is_reestablished(server):171 """172 Upon keep-alive connection closed by remote a new connection173 should be reestablished.174 """
1 unmodified line
176 response = await http.request("GET", server.url)177 await response.aread()178179 # Shutdown the server to close the keep-alive connection180 await restart(server)180 await server.restart()181182 response = await http.request("GET", server.url)183 await response.aread()184 assert len(http.active_connections) == 0185 assert len(http.keepalive_connections) == 1186187188@pytest.mark.usefixtures("async_environment")189async def test_keepalive_http2_connection_closed_by_server_is_reestablished(190 server, restart191):189async def test_keepalive_http2_connection_closed_by_server_is_reestablished(server):190 """191 Upon keep-alive connection closed by remote a new connection192 should be reestablished.193 """
1 unmodified line
195 response = await http.request("GET", server.url)196 await response.aread()197198 # Shutdown the server to close the keep-alive connection201 await restart(server)199 await server.restart()200201 response = await http.request("GET", server.url)202 await response.aread()203 assert len(http.active_connections) == 0204 assert len(http.keepalive_connections) == 1205206207@pytest.mark.usefixtures("async_environment")210async def test_connection_closed_free_semaphore_on_acquire(server, restart):208async def test_connection_closed_free_semaphore_on_acquire(server):209 """210 Verify that max_connections semaphore is released211 properly on a disconnected connection.212 """
1 unmodified line
214 response = await http.request("GET", server.url)215 await response.aread()216217 # Close the connection so we're forced to recycle it220 await restart(server)218 await server.restart()219220 response = await http.request("GET", server.url)221 assert response.status_code == 200222
24 unmodified lines
modified:tests/concurrency.py+23 added-43 removed
2 unmodified lines
3required as part of the ConcurrencyBackend API.4"""56import asyncio7import functools8import typing78import sniffio9import trio1012from httpx.backends.asyncio import AsyncioBackend13from httpx.backends.auto import AutoBackend14from httpx.backends.trio import TrioBackend1112async def sleep(seconds: float):13 if sniffio.current_async_library() == "trio":14 await trio.sleep(seconds)15 else:16 await asyncio.sleep(seconds)1717@functools.singledispatch18async def run_concurrently(backend, *coroutines: typing.Callable[[], typing.Awaitable]):19 raise NotImplementedError # pragma: no cover1819async def run_concurrently(*coroutines):20 if sniffio.current_async_library() == "trio":21 async with trio.open_nursery() as nursery:22 for coroutine in coroutines:23 nursery.start_soon(coroutine)24 else:25 coros = (coroutine() for coroutine in coroutines)26 await asyncio.gather(*coros)2722@run_concurrently.register(AutoBackend)23async def _run_concurrently_auto(backend, *coroutines):24 await run_concurrently(backend.backend, *coroutines)282627@run_concurrently.register(AsyncioBackend)28async def _run_concurrently_asyncio(backend, *coroutines):29 coros = (coroutine() for coroutine in coroutines)30 await asyncio.gather(*coros)313233@run_concurrently.register(TrioBackend)34async def _run_concurrently_trio(backend, *coroutines):35 async with trio.open_nursery() as nursery:36 for coroutine in coroutines:37 nursery.start_soon(coroutine)383940@functools.singledispatch41def get_cipher(backend, stream):42 raise NotImplementedError # pragma: no cover434445@get_cipher.register(AutoBackend)46def _get_cipher_auto(backend, stream):47 return get_cipher(backend.backend, stream)484950@get_cipher.register(AsyncioBackend)51def _get_cipher_asyncio(backend, stream):52 return stream.stream_writer.get_extra_info("cipher", default=None)535455@get_cipher.register(TrioBackend)56def get_trio_cipher(backend, stream):57 return stream.stream.cipher() if isinstance(stream.stream, trio.SSLStream) else None29def get_cipher(stream):30 if sniffio.current_async_library() == "trio":31 return (32 stream.stream.cipher()33 if isinstance(stream.stream, trio.SSLStream)34 else None35 )36 else:37 return stream.stream_writer.get_extra_info("cipher", default=None)
modified:tests/conftest.py+9 added-26 removed
16 unmodified lines
17from uvicorn.config import Config18from uvicorn.main import Server1920from httpx import URL21from httpx.backends.asyncio import AsyncioBackend22from httpx.backends.base import lookup_backend21from tests.concurrency import sleep2223ENVIRONMENT_VARIABLES = {24 "SSL_CERT_FILE",25 "SSL_CERT_DIR",
80 unmodified lines
106 try:107 delay_ms = float(delay_ms_str)108 except ValueError:109 delay_ms = 100111 await asyncio.sleep(delay_ms / 1000.0)110 await sleep(delay_ms / 1000.0)111 await send(112 {113 "type": "http.response.start",114 "status": 200,
135 unmodified lines
250 }251 await asyncio.wait(tasks)252253 async def restart(self) -> None:255 # Ensure we are in an asyncio environment.256 assert asyncio.get_event_loop() is not None257 # This may be called from a different thread than the one the server is258 # running on. For this reason, we use an event to coordinate with the server259 # instead of calling shutdown()/startup() directly.260 self.restart_requested.set()254 # This coroutine may be called from a different thread than the one the255 # server is running on, and from an async environment that's not asyncio.256 # For this reason, we use an event to coordinate with the server257 # instead of calling shutdown()/startup() directly, and should not make258 # any asyncio-specific operations.259 self.started = False260 self.restart_requested.set()261 while not self.started:263 await asyncio.sleep(0.5)262 await sleep(0.2)263264 async def watch_restarts(self):265 while True:266 if self.should_exit:
8 unmodified lines
275 await self.shutdown()276 await self.startup()277278280@pytest.fixture281def restart():282 """Restart the running server from an async test function.283284 This fixture deals with possible differences between the environment of the285 test function and that of the server.286 """287 asyncio_backend = AsyncioBackend()288289 async def restart(server):290 backend = lookup_backend()291 await backend.run_in_threadpool(asyncio_backend.run, server.restart)292293 return restart294295279def serve_in_thread(server: Server):280 thread = threading.Thread(target=server.run)281 thread.start()282 try:
53 unmodified lines
modified:tests/test_concurrency.py+5 added-5 removed
39 unmodified lines
40 )4142 try:43 assert stream.is_connection_dropped() is False44 assert get_cipher(backend, stream) is None44 assert get_cipher(stream) is None4546 stream = await stream.start_tls(https_server.url.host, ctx, timeout)47 assert stream.is_connection_dropped() is False48 assert get_cipher(backend, stream) is not None48 assert get_cipher(stream) is not None4950 await stream.write(b"GET / HTTP/1.1\r\n\r\n", timeout)5152 response = await read_response(stream, timeout, should_contain=b"Hello, world")
14 unmodified lines
67 )6869 try:70 assert stream.is_connection_dropped() is False71 assert get_cipher(backend, stream) is None71 assert get_cipher(stream) is None7273 stream = await stream.start_tls(https_uds_server.url.host, ctx, timeout)74 assert stream.is_connection_dropped() is False75 assert get_cipher(backend, stream) is not None75 assert get_cipher(stream) is not None7677 await stream.write(b"GET / HTTP/1.1\r\n\r\n", timeout)7879 response = await read_response(stream, timeout, should_contain=b"Hello, world")
15 unmodified lines
95 timeout = Timeout(5)96 try:97 await stream.write(b"GET / HTTP/1.1\r\n\r\n", timeout)98 await run_concurrently(99 backend, lambda: stream.read(10, timeout), lambda: stream.read(10, timeout)99 lambda: stream.read(10, timeout), lambda: stream.read(10, timeout)100 )101 finally:102 await stream.close()103
19 unmodified lines