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
Provenance
- Commit
6ac49da- Tree
fbde9d2- Author
Tom Christie <tom@tomchristie.com>- Committer
GitHub <noreply@github.com>- Parent
bd57b65
8 files changed+43 added−141 removed
modified:httpx/backends/asyncio.py-29 removed
1 import asyncio2-import functools2 import ssl3 import typing4 5 from ..config import Timeout174 unmodified lines180 if not SSL_MONKEY_PATCH_APPLIED:181 ssl_monkey_patch()182 SSL_MONKEY_PATCH_APPLIED = True183 185- @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._loop193-184 async def open_tcp_stream(185 self,186 hostname: str,187 port: int,34 unmodified lines222 def time(self) -> float:223 loop = asyncio.get_event_loop()224 return loop.time()225 236- 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)243-244- 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 = loop254-226 def create_semaphore(self, max_value: int, exc_class: type) -> BaseSemaphore:227 return Semaphore(max_value, exc_class)228 229 def create_lock(self) -> BaseLock:33 unmodified linesmodified:httpx/backends/auto.py-5 removed
42 unmodified lines43 44 def time(self) -> float:45 return self.backend.time()46 47- 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)51-47 def create_semaphore(self, max_value: int, exc_class: type) -> BaseSemaphore:48 return self.backend.create_semaphore(max_value, exc_class)49 50 def create_lock(self) -> BaseLock:1 unmodified linemodified:httpx/backends/base.py-10 removed
112 unmodified lines113 114 def time(self) -> float:115 raise NotImplementedError() # pragma: no cover116 117- async def run_in_threadpool(118- self, func: typing.Callable, *args: typing.Any, **kwargs: typing.Any119- ) -> typing.Any:120- raise NotImplementedError() # pragma: no cover121-122- def run(123- self, coroutine: typing.Callable, *args: typing.Any, **kwargs: typing.Any124- ) -> typing.Any:125- raise NotImplementedError() # pragma: no cover126-117 def create_semaphore(self, max_value: int, exc_class: type) -> BaseSemaphore:118 raise NotImplementedError() # pragma: no cover119 120 def create_lock(self) -> BaseLock:1 unmodified linemodified:httpx/backends/trio.py-15 removed
1-import functools1 import ssl2 import typing3 4 import trio113 unmodified lines118 return SocketStream(stream=stream)119 120 raise ConnectTimeout()121 123- 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- )129-130- 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- )136-122 def time(self) -> float:123 return trio.current_time()124 125 def create_semaphore(self, max_value: int, exc_class: type) -> BaseSemaphore:39 unmodified linesmodified:tests/dispatch/test_connection_pools.py+6 added-8 removed
165 unmodified lines166 assert len(http.keepalive_connections) == 0167 168 169 @pytest.mark.usefixtures("async_environment")170-async def test_keepalive_connection_closed_by_server_is_reestablished(server, restart):170+async 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 line176 response = await http.request("GET", server.url)177 await response.aread()178 179 # Shutdown the server to close the keep-alive connection180- await restart(server)180+ await server.restart()181 182 response = await http.request("GET", server.url)183 await response.aread()184 assert len(http.active_connections) == 0185 assert len(http.keepalive_connections) == 1186 187 188 @pytest.mark.usefixtures("async_environment")189-async def test_keepalive_http2_connection_closed_by_server_is_reestablished(190- server, restart191-):189+async 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 line195 response = await http.request("GET", server.url)196 await response.aread()197 198 # Shutdown the server to close the keep-alive connection201- await restart(server)199+ await server.restart()200 201 response = await http.request("GET", server.url)202 await response.aread()203 assert len(http.active_connections) == 0204 assert len(http.keepalive_connections) == 1205 206 207 @pytest.mark.usefixtures("async_environment")210-async def test_connection_closed_free_semaphore_on_acquire(server, restart):208+async 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 line214 response = await http.request("GET", server.url)215 await response.aread()216 217 # Close the connection so we're forced to recycle it220- await restart(server)218+ await server.restart()219 220 response = await http.request("GET", server.url)221 assert response.status_code == 200222 24 unmodified linesmodified:tests/concurrency.py+23 added-43 removed
2 unmodified lines3 required as part of the ConcurrencyBackend API.4 """5 6 import asyncio7-import functools8-import typing7 8+import sniffio9 import trio10 12-from httpx.backends.asyncio import AsyncioBackend13-from httpx.backends.auto import AutoBackend14-from httpx.backends.trio import TrioBackend11 12+async def sleep(seconds: float):13+ if sniffio.current_async_library() == "trio":14+ await trio.sleep(seconds)15+ else:16+ await asyncio.sleep(seconds)17 17-@functools.singledispatch18-async def run_concurrently(backend, *coroutines: typing.Callable[[], typing.Awaitable]):19- raise NotImplementedError # pragma: no cover18 19+async 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)27 22-@run_concurrently.register(AutoBackend)23-async def _run_concurrently_auto(backend, *coroutines):24- await run_concurrently(backend.backend, *coroutines)28 26-27-@run_concurrently.register(AsyncioBackend)28-async def _run_concurrently_asyncio(backend, *coroutines):29- coros = (coroutine() for coroutine in coroutines)30- await asyncio.gather(*coros)31-32-33-@run_concurrently.register(TrioBackend)34-async def _run_concurrently_trio(backend, *coroutines):35- async with trio.open_nursery() as nursery:36- for coroutine in coroutines:37- nursery.start_soon(coroutine)38-39-40-@functools.singledispatch41-def get_cipher(backend, stream):42- raise NotImplementedError # pragma: no cover43-44-45-@get_cipher.register(AutoBackend)46-def _get_cipher_auto(backend, stream):47- return get_cipher(backend.backend, stream)48-49-50-@get_cipher.register(AsyncioBackend)51-def _get_cipher_asyncio(backend, stream):52- return stream.stream_writer.get_extra_info("cipher", default=None)53-54-55-@get_cipher.register(TrioBackend)56-def get_trio_cipher(backend, stream):57- return stream.stream.cipher() if isinstance(stream.stream, trio.SSLStream) else None29+def 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 lines17 from uvicorn.config import Config18 from uvicorn.main import Server19 20 from httpx import URL21-from httpx.backends.asyncio import AsyncioBackend22-from httpx.backends.base import lookup_backend21+from tests.concurrency import sleep22 23 ENVIRONMENT_VARIABLES = {24 "SSL_CERT_FILE",25 "SSL_CERT_DIR",80 unmodified lines106 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 lines250 }251 await asyncio.wait(tasks)252 253 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)263 264 async def watch_restarts(self):265 while True:266 if self.should_exit:8 unmodified lines275 await self.shutdown()276 await self.startup()277 278 280-@pytest.fixture281-def restart():282- """Restart the running server from an async test function.283-284- This fixture deals with possible differences between the environment of the285- test function and that of the server.286- """287- asyncio_backend = AsyncioBackend()288-289- async def restart(server):290- backend = lookup_backend()291- await backend.run_in_threadpool(asyncio_backend.run, server.restart)292-293- return restart294-295-279 def serve_in_thread(server: Server):280 thread = threading.Thread(target=server.run)281 thread.start()282 try:53 unmodified linesmodified:tests/test_concurrency.py+5 added-5 removed
39 unmodified lines40 )41 42 try:43 assert stream.is_connection_dropped() is False44- assert get_cipher(backend, stream) is None44+ assert get_cipher(stream) is None45 46 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 None49 50 await stream.write(b"GET / HTTP/1.1\r\n\r\n", timeout)51 52 response = await read_response(stream, timeout, should_contain=b"Hello, world")14 unmodified lines67 )68 69 try:70 assert stream.is_connection_dropped() is False71- assert get_cipher(backend, stream) is None71+ assert get_cipher(stream) is None72 73 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 None76 77 await stream.write(b"GET / HTTP/1.1\r\n\r\n", timeout)78 79 response = await read_response(stream, timeout, should_contain=b"Hello, world")15 unmodified lines95 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