Skip to content
Myr

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

7 files+119 added−95 removed

modified:httpx/concurrency/asyncio.py+22 added-28 removed
1 unmodified line
2import functools3import ssl4import sys5import typing6from types import TracebackType67from ..config import PoolLimits, Timeout8from ..exceptions import ConnectTimeout, PoolTimeout, ReadTimeout, WriteTimeout9from .base import (11 BaseBackgroundManager,10 BaseEvent,11 BasePoolSemaphore,12 BaseSocketStream,13 ConcurrencyBackend,
300 unmodified lines
314 return self.loop.run_until_complete(coroutine(*args, **kwargs))315 finally:316 self._loop = loop317318 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))327328 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 pass339340 def get_semaphore(self, limits: PoolLimits) -> BasePoolSemaphore:341 return PoolSemaphore(limits)342343 def create_event(self) -> BaseEvent:344 return typing.cast(BaseEvent, asyncio.Event())325326 def background_manager(327 self, coroutine: typing.Callable, *args: typing.Any328 ) -> "BackgroundManager":329 return BackgroundManager(coroutine, args)330331332class BackgroundManager(BaseBackgroundManager):333 def __init__(self, coroutine: typing.Callable, args: typing.Any) -> None:334 self.coroutine = coroutine335 self.args = args336337 async def __aenter__(self) -> "BackgroundManager":338 loop = asyncio.get_event_loop()339 self.task = loop.create_task(self.coroutine(*self.args))340 return self341342 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 lines
4import sniffio56from ..config import PoolLimits, Timeout7from .base import (8 BaseBackgroundManager,8 BaseEvent,9 BasePoolSemaphore,10 BaseSocketStream,11 ConcurrencyBackend,
38 unmodified lines
50 return await self.backend.run_in_threadpool(func, *args, **kwargs)5152 def create_event(self) -> BaseEvent:53 return self.backend.create_event()5556 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
1import ssl2import typing3from types import TracebackType34from ..config import PoolLimits, Timeout56
145 unmodified lines
152153 def create_event(self) -> BaseEvent:154 raise NotImplementedError() # pragma: no cover155157 def background_manager(158 self, coroutine: typing.Callable, *args: typing.Any159 ) -> "BaseBackgroundManager":160 raise NotImplementedError() # pragma: no cover161162163class BaseBackgroundManager:164 async def __aenter__(self) -> "BaseBackgroundManager":165 raise NotImplementedError() # pragma: no cover166167 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.165175 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.168169 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 cover
modified:httpx/concurrency/trio.py+19 added-29 removed
1import functools2import ssl3import typing4from types import TracebackType45import trio67from ..config import PoolLimits, Timeout8from ..exceptions import ConnectTimeout, PoolTimeout, ReadTimeout, WriteTimeout9from .base import (11 BaseBackgroundManager,10 BaseEvent,11 BasePoolSemaphore,12 BaseSocketStream,13 ConcurrencyBackend,
187 unmodified lines
201 return trio.run(202 functools.partial(coroutine, **kwargs) if kwargs else coroutine, *args203 )204205 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]223224 def get_semaphore(self, limits: PoolLimits) -> BasePoolSemaphore:225 return PoolSemaphore(limits)226227 def create_event(self) -> BaseEvent:228 return Event()229213 def background_manager(214 self, coroutine: typing.Callable, *args: typing.Any215 ) -> "BackgroundManager":216 return BackgroundManager(coroutine, *args)230218231class Event(BaseEvent):232 def __init__(self) -> None:233 self._event = trio.Event()234
9 unmodified lines
244 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()236237238class 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] = None244245 async def __aenter__(self) -> "BackgroundManager":246 self.nursery = await self.nursery_manager.__aenter__()247 self.nursery.start_soon(self.coroutine, *self.args)248 return self249250 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 lines
64 self.events[stream_id] = []65 self.timeout_flags[stream_id] = TimeoutFlag()66 self.window_update_received[stream_id] = self.backend.create_event()6768 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] = None7071 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)7475 await self.backend.fork(76 self.send_request_data,77 [stream_id, request.stream(), timeout],78 receive_response,79 [stream_id, timeout],80 )8182 assert status_code is not None83 assert headers is not None8485 content = self.body_iter(stream_id, timeout)86 on_close = functools.partial(self.response_closed, stream_id=stream_id)8788 return Response(
185 unmodified lines
modified:httpx/__init__.py+1 added-7 removed
1 unmodified line
2from .api import delete, get, head, options, patch, post, put, request, stream3from .auth import BasicAuth, DigestAuth4from .client import Client5from .concurrency.asyncio import AsyncioBackend6from .concurrency.base import (7 BaseBackgroundManager,8 BasePoolSemaphore,9 BaseSocketStream,10 ConcurrencyBackend,11)6from .concurrency.base import BasePoolSemaphore, BaseSocketStream, ConcurrencyBackend7from .config import (8 USER_AGENT,9 CertTypes,10 PoolLimits,
72 unmodified lines
83 "TimeoutConfig",84 "VerifyTypes",85 "HTTPConnection",86 "BasePoolSemaphore",92 "BaseBackgroundManager",87 "ConnectionPool",88 "HTTPProxy",89 "HTTPProxyMode",90 "ConnectTimeout",
40 unmodified lines
modified:tests/test_concurrency.py+47 added-1 removed
1 unmodified line
2import trio34from httpx import AsyncioBackend, SSLConfig, Timeout5from httpx.concurrency.trio import TrioBackend6from tests.concurrency import run_concurrently6from tests.concurrency import run_concurrently, sleep789def get_asyncio_cipher(stream):10 return stream.stream_writer.get_extra_info("cipher", default=None)
98 unmodified lines
109 backend, lambda: stream.read(10), lambda: stream.read(10)110 )111 finally:112 await stream.close()113114115async def test_fork(backend):116 ok_counter = 0117118 async def ok(delay: int) -> None:119 nonlocal ok_counter120 await sleep(backend, delay)121 ok_counter += 1122123 async def fail(message: str, delay: int) -> None:124 await sleep(backend, delay)125 raise RuntimeError(message)126127 await backend.fork(ok, [0], ok, [0])128 assert ok_counter == 2129130 with pytest.raises(RuntimeError, match="Oops"):131 await backend.fork(ok, [0], fail, ["Oops", 0.01])132133 assert ok_counter == 3134135 with pytest.raises(RuntimeError, match="Oops"):136 await backend.fork(ok, [0.01], fail, ["Oops", 0])137138 assert ok_counter == 3139140 with pytest.raises(RuntimeError, match="Oops"):141 await backend.fork(fail, ["Oops", 0.01], ok, [0])142143 assert ok_counter == 4144145 with pytest.raises(RuntimeError, match="Oops"):146 await backend.fork(fail, ["Oops", 0], ok, [0.01])147148 assert ok_counter == 4149150 with pytest.raises(RuntimeError, match="My bad"):151 await backend.fork(fail, ["My bad", 0], fail, ["Oops", 0.01])152153 with pytest.raises(RuntimeError, match="Oops"):154 await backend.fork(fail, ["My bad", 0.01], fail, ["Oops", 0])155156 # 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])