Drop BackgroundManager in favor of fork(func1, func2) (#603)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
* Drop BackgroundManager in favor of fork(func1, func2) * Please mypy
authored by Florimond Manca · committed by Tom Christie · parent bb6e52f · Browse files · 7 files·+119 added−95 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
7 files+119 added−95 removed
- tests:+47 added−1 removed
- other:+72 added−94 removed
Provenance
- Commit
c38fd68- Tree
e2c8b41- Author
Florimond Manca <florimond.manca@gmail.com>- Committer
Tom Christie <tom@tomchristie.com>- Parent
bb6e52f
7 files changed+119 added−95 removed
modified:httpx/concurrency/asyncio.py+22 added-28 removed
1 unmodified line2 import functools3 import ssl4 import sys5 import typing6-from types import TracebackType6 7 from ..config import PoolLimits, Timeout8 from ..exceptions import ConnectTimeout, PoolTimeout, ReadTimeout, WriteTimeout9 from .base import (11- BaseBackgroundManager,10 BaseEvent,11 BasePoolSemaphore,12 BaseSocketStream,13 ConcurrencyBackend,300 unmodified lines314 return self.loop.run_until_complete(coroutine(*args, **kwargs))315 finally:316 self._loop = loop317 318+ async def fork(319+ self,320+ coroutine1: typing.Callable,321+ args1: typing.Sequence,322+ coroutine2: typing.Callable,323+ args2: typing.Sequence,324+ ) -> None:325+ task1 = self.loop.create_task(coroutine1(*args1))326+ task2 = self.loop.create_task(coroutine2(*args2))327+328+ try:329+ await asyncio.gather(task1, task2)330+ finally:331+ pending: typing.Set[asyncio.Future[typing.Any]] # Please mypy.332+ _, pending = await asyncio.wait({task1, task2}, timeout=0)333+ for task in pending:334+ task.cancel()335+ try:336+ await task337+ except asyncio.CancelledError:338+ pass339+340 def get_semaphore(self, limits: PoolLimits) -> BasePoolSemaphore:341 return PoolSemaphore(limits)342 343 def create_event(self) -> BaseEvent:344 return typing.cast(BaseEvent, asyncio.Event())325-326- def background_manager(327- self, coroutine: typing.Callable, *args: typing.Any328- ) -> "BackgroundManager":329- return BackgroundManager(coroutine, args)330-331-332-class BackgroundManager(BaseBackgroundManager):333- def __init__(self, coroutine: typing.Callable, args: typing.Any) -> None:334- self.coroutine = coroutine335- self.args = args336-337- async def __aenter__(self) -> "BackgroundManager":338- loop = asyncio.get_event_loop()339- self.task = loop.create_task(self.coroutine(*self.args))340- return self341-342- async def __aexit__(343- self,344- exc_type: typing.Type[BaseException] = None,345- exc_value: BaseException = None,346- traceback: TracebackType = None,347- ) -> None:348- await self.task349- if exc_type is None:350- self.task.result()modified:httpx/concurrency/auto.py-6 removed
3 unmodified lines4 import sniffio5 6 from ..config import PoolLimits, Timeout7 from .base import (8- BaseBackgroundManager,8 BaseEvent,9 BasePoolSemaphore,10 BaseSocketStream,11 ConcurrencyBackend,38 unmodified lines50 return await self.backend.run_in_threadpool(func, *args, **kwargs)51 52 def create_event(self) -> BaseEvent:53 return self.backend.create_event()55-56- def background_manager(57- self, coroutine: typing.Callable, *args: typing.Any58- ) -> BaseBackgroundManager:59- return self.backend.background_manager(coroutine, *args)modified:httpx/concurrency/base.py+14 added-22 removed
1 import ssl2 import typing3-from types import TracebackType3 4 from ..config import PoolLimits, Timeout5 6 145 unmodified lines152 153 def create_event(self) -> BaseEvent:154 raise NotImplementedError() # pragma: no cover155 157- def background_manager(158- self, coroutine: typing.Callable, *args: typing.Any159- ) -> "BaseBackgroundManager":160- raise NotImplementedError() # pragma: no cover161-162-163-class BaseBackgroundManager:164- async def __aenter__(self) -> "BaseBackgroundManager":165- raise NotImplementedError() # pragma: no cover166-167- async def __aexit__(156+ async def fork(157 self,169- exc_type: typing.Type[BaseException] = None,170- exc_value: BaseException = None,171- traceback: TracebackType = None,158+ coroutine1: typing.Callable,159+ args1: typing.Sequence,160+ coroutine2: typing.Callable,161+ args2: typing.Sequence,162 ) -> None:173- raise NotImplementedError() # pragma: no cover163+ """164+ Run two coroutines concurrently.165 175- async def close(self, exception: BaseException = None) -> None:176- if exception is None:177- await self.__aexit__(None, None, None)178- else:179- traceback = exception.__traceback__ # type: ignore180- await self.__aexit__(type(exception), exception, traceback)166+ This should start 'coroutine1' with '*args1' and 'coroutine2' with '*args2',167+ and wait for them to finish.168+169+ In case one of the coroutines raises an exception, cancel the other one then170+ raise. If the other coroutine had also raised an exception, ignore it (for now).171+ """172+ raise NotImplementedError() # pragma: no covermodified:httpx/concurrency/trio.py+19 added-29 removed
1 import functools2 import ssl3 import typing4-from types import TracebackType4 5 import trio6 7 from ..config import PoolLimits, Timeout8 from ..exceptions import ConnectTimeout, PoolTimeout, ReadTimeout, WriteTimeout9 from .base import (11- BaseBackgroundManager,10 BaseEvent,11 BasePoolSemaphore,12 BaseSocketStream,13 ConcurrencyBackend,187 unmodified lines201 return trio.run(202 functools.partial(coroutine, **kwargs) if kwargs else coroutine, *args203 )204 205+ async def fork(206+ self,207+ coroutine1: typing.Callable,208+ args1: typing.Sequence,209+ coroutine2: typing.Callable,210+ args2: typing.Sequence,211+ ) -> None:212+ try:213+ async with trio.open_nursery() as nursery:214+ nursery.start_soon(coroutine1, *args1)215+ nursery.start_soon(coroutine2, *args2)216+ except trio.MultiError as exc:217+ # NOTE: asyncio doesn't handle multi-errors yet, so we must align on its218+ # behavior here, and need to arbitrarily decide which exception to raise.219+ # We may want to add an 'httpx.MultiError', manually add support220+ # for this situation in the asyncio backend, and re-raise221+ # an 'httpx.MultiError' from trio's here.222+ raise exc.exceptions[0]223+224 def get_semaphore(self, limits: PoolLimits) -> BasePoolSemaphore:225 return PoolSemaphore(limits)226 227 def create_event(self) -> BaseEvent:228 return Event()229 213- def background_manager(214- self, coroutine: typing.Callable, *args: typing.Any215- ) -> "BackgroundManager":216- return BackgroundManager(coroutine, *args)230 218-231 class Event(BaseEvent):232 def __init__(self) -> None:233 self._event = trio.Event()234 9 unmodified lines244 def clear(self) -> None:245 # trio.Event.clear() was deprecated in Trio 0.12.246 # https://github.com/python-trio/trio/issues/637247 self._event = trio.Event()236-237-238-class BackgroundManager(BaseBackgroundManager):239- def __init__(self, coroutine: typing.Callable, *args: typing.Any) -> None:240- self.coroutine = coroutine241- self.args = args242- self.nursery_manager = trio.open_nursery()243- self.nursery: typing.Optional[trio.Nursery] = None244-245- async def __aenter__(self) -> "BackgroundManager":246- self.nursery = await self.nursery_manager.__aenter__()247- self.nursery.start_soon(self.coroutine, *self.args)248- return self249-250- async def __aexit__(251- self,252- exc_type: typing.Type[BaseException] = None,253- exc_value: BaseException = None,254- traceback: TracebackType = None,255- ) -> None:256- assert self.nursery is not None257- await self.nursery_manager.__aexit__(exc_type, exc_value, traceback)modified:httpx/dispatch/http2.py+16 added-2 removed
63 unmodified lines64 self.events[stream_id] = []65 self.timeout_flags[stream_id] = TimeoutFlag()66 self.window_update_received[stream_id] = self.backend.create_event()67 68- task, args = self.send_request_data, [stream_id, request.stream(), timeout]69- async with self.backend.background_manager(task, *args):68+ status_code: typing.Optional[int] = None69+ headers: typing.Optional[list] = None70+71+ async def receive_response(stream_id: int, timeout: Timeout) -> None:72+ nonlocal status_code, headers73 status_code, headers = await self.receive_response(stream_id, timeout)74+75+ await self.backend.fork(76+ self.send_request_data,77+ [stream_id, request.stream(), timeout],78+ receive_response,79+ [stream_id, timeout],80+ )81+82+ assert status_code is not None83+ assert headers is not None84+85 content = self.body_iter(stream_id, timeout)86 on_close = functools.partial(self.response_closed, stream_id=stream_id)87 88 return Response(185 unmodified linesmodified:httpx/__init__.py+1 added-7 removed
1 unmodified line2 from .api import delete, get, head, options, patch, post, put, request, stream3 from .auth import BasicAuth, DigestAuth4 from .client import Client5 from .concurrency.asyncio import AsyncioBackend6-from .concurrency.base import (7- BaseBackgroundManager,8- BasePoolSemaphore,9- BaseSocketStream,10- ConcurrencyBackend,11-)6+from .concurrency.base import BasePoolSemaphore, BaseSocketStream, ConcurrencyBackend7 from .config import (8 USER_AGENT,9 CertTypes,10 PoolLimits,72 unmodified lines83 "TimeoutConfig",84 "VerifyTypes",85 "HTTPConnection",86 "BasePoolSemaphore",92- "BaseBackgroundManager",87 "ConnectionPool",88 "HTTPProxy",89 "HTTPProxyMode",90 "ConnectTimeout",40 unmodified linesmodified:tests/test_concurrency.py+47 added-1 removed
1 unmodified line2 import trio3 4 from httpx import AsyncioBackend, SSLConfig, Timeout5 from httpx.concurrency.trio import TrioBackend6-from tests.concurrency import run_concurrently6+from tests.concurrency import run_concurrently, sleep7 8 9 def get_asyncio_cipher(stream):10 return stream.stream_writer.get_extra_info("cipher", default=None)98 unmodified lines109 backend, lambda: stream.read(10), lambda: stream.read(10)110 )111 finally:112 await stream.close()113+114+115+async def test_fork(backend):116+ ok_counter = 0117+118+ async def ok(delay: int) -> None:119+ nonlocal ok_counter120+ await sleep(backend, delay)121+ ok_counter += 1122+123+ async def fail(message: str, delay: int) -> None:124+ await sleep(backend, delay)125+ raise RuntimeError(message)126+127+ await backend.fork(ok, [0], ok, [0])128+ assert ok_counter == 2129+130+ with pytest.raises(RuntimeError, match="Oops"):131+ await backend.fork(ok, [0], fail, ["Oops", 0.01])132+133+ assert ok_counter == 3134+135+ with pytest.raises(RuntimeError, match="Oops"):136+ await backend.fork(ok, [0.01], fail, ["Oops", 0])137+138+ assert ok_counter == 3139+140+ with pytest.raises(RuntimeError, match="Oops"):141+ await backend.fork(fail, ["Oops", 0.01], ok, [0])142+143+ assert ok_counter == 4144+145+ with pytest.raises(RuntimeError, match="Oops"):146+ await backend.fork(fail, ["Oops", 0], ok, [0.01])147+148+ assert ok_counter == 4149+150+ with pytest.raises(RuntimeError, match="My bad"):151+ await backend.fork(fail, ["My bad", 0], fail, ["Oops", 0.01])152+153+ with pytest.raises(RuntimeError, match="Oops"):154+ await backend.fork(fail, ["My bad", 0.01], fail, ["Oops", 0])155+156+ # No 'match', since we can't know which will be raised first.157+ with pytest.raises(RuntimeError):158+ await backend.fork(fail, ["My bad", 0], fail, ["Oops", 0])