Refactor get_semaphore (#625)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Tom Christie · committed by GitHub · parent 66e0f4b · Browse files · 5 files·+32 added−42 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
5 files+32 added−42 removed
- other:+32 added−42 removed
Provenance
- Commit
00a875d- Tree
581a30a- Author
Tom Christie <tom@tomchristie.com>- Committer
GitHub <noreply@github.com>- Parent
66e0f4b
5 files changed+32 added−42 removed
modified:httpx/concurrency/asyncio.py+7 added-17 removed
2 unmodified lines3 import ssl4 import sys5 import typing6 7-from ..config import PoolLimits, Timeout7+from ..config import Timeout8 from ..exceptions import ConnectTimeout, PoolTimeout, ReadTimeout, WriteTimeout9 from .base import BaseEvent, BasePoolSemaphore, BaseSocketStream, ConcurrencyBackend10 11 SSL_MONKEY_PATCH_APPLIED = False155 unmodified lines167 await self.stream_writer.wait_closed()168 169 170 class PoolSemaphore(BasePoolSemaphore):171- def __init__(self, pool_limits: PoolLimits):172- self.pool_limits = pool_limits171+ def __init__(self, max_value: int) -> None:172+ self.max_value = max_value173 174 @property175- def semaphore(self) -> typing.Optional[asyncio.BoundedSemaphore]:175+ def semaphore(self) -> asyncio.BoundedSemaphore:176 if not hasattr(self, "_semaphore"):177- max_connections = self.pool_limits.hard_limit178- if max_connections is None:179- self._semaphore = None180- else:181- self._semaphore = asyncio.BoundedSemaphore(value=max_connections)177+ self._semaphore = asyncio.BoundedSemaphore(value=self.max_value)178 return self._semaphore179 180 async def acquire(self, timeout: float = None) -> None:185- if self.semaphore is None:186- return187-181 try:182 await asyncio.wait_for(self.semaphore.acquire(), timeout)183 except asyncio.TimeoutError:184 raise PoolTimeout()185 186 def release(self) -> None:194- if self.semaphore is None:195- return196-187 self.semaphore.release()188 189 190 class AsyncioBackend(ConcurrencyBackend):69 unmodified lines260 return self.loop.run_until_complete(coroutine(*args, **kwargs))261 finally:262 self._loop = loop263 274- def get_semaphore(self, limits: PoolLimits) -> BasePoolSemaphore:275- return PoolSemaphore(limits)264+ def get_semaphore(self, max_value: int) -> BasePoolSemaphore:265+ return PoolSemaphore(max_value)266 267 def create_event(self) -> BaseEvent:268 return typing.cast(BaseEvent, asyncio.Event())modified:httpx/concurrency/auto.py+3 added-3 removed
1 unmodified line2 import typing3 4 import sniffio5 6-from ..config import PoolLimits, Timeout6+from ..config import Timeout7 from .base import (8 BaseEvent,9 BasePoolSemaphore,10 BaseSocketStream,29 unmodified lines40 timeout: Timeout,41 ) -> BaseSocketStream:42 return await self.backend.open_uds_stream(path, hostname, ssl_context, timeout)43 44- def get_semaphore(self, limits: PoolLimits) -> BasePoolSemaphore:45- return self.backend.get_semaphore(limits)44+ def get_semaphore(self, max_value: int) -> BasePoolSemaphore:45+ return self.backend.get_semaphore(max_value)46 47 async def run_in_threadpool(48 self, func: typing.Callable, *args: typing.Any, **kwargs: typing.Any49 ) -> typing.Any:4 unmodified linesmodified:httpx/concurrency/base.py+2 added-2 removed
1 import ssl2 import typing3 4-from ..config import PoolLimits, Timeout4+from ..config import Timeout5 6 7 def lookup_backend(8 backend: typing.Union[str, "ConcurrencyBackend"] = "auto"95 unmodified lines104 timeout: Timeout,105 ) -> BaseSocketStream:106 raise NotImplementedError() # pragma: no cover107 108- def get_semaphore(self, limits: PoolLimits) -> BasePoolSemaphore:108+ def get_semaphore(self, max_value: int) -> BasePoolSemaphore:109 raise NotImplementedError() # pragma: no cover110 111 async def run_in_threadpool(112 self, func: typing.Callable, *args: typing.Any, **kwargs: typing.Any10 unmodified linesmodified:httpx/concurrency/trio.py+7 added-19 removed
2 unmodified lines3 import typing4 5 import trio6 7-from ..config import PoolLimits, Timeout7+from ..config import Timeout8 from ..exceptions import ConnectTimeout, PoolTimeout, ReadTimeout, WriteTimeout9 from .base import BaseEvent, BasePoolSemaphore, BaseSocketStream, ConcurrencyBackend10 11 70 unmodified lines82 await self.stream.aclose()83 84 85 class PoolSemaphore(BasePoolSemaphore):86- def __init__(self, pool_limits: PoolLimits):87- self.pool_limits = pool_limits86+ def __init__(self, max_value: int):87+ self.max_value = max_value88 89 @property90- def semaphore(self) -> typing.Optional[trio.Semaphore]:90+ def semaphore(self) -> trio.Semaphore:91 if not hasattr(self, "_semaphore"):92- max_connections = self.pool_limits.hard_limit93- if max_connections is None:94- self._semaphore = None95- else:96- self._semaphore = trio.Semaphore(97- max_connections, max_value=max_connections98- )92+ self._semaphore = trio.Semaphore(self.max_value, max_value=self.max_value)93 return self._semaphore94 95 async def acquire(self, timeout: float = None) -> None:102- if self.semaphore is None:103- return104-96 timeout = none_as_inf(timeout)97 98 with trio.move_on_after(timeout):99 await self.semaphore.acquire()1 unmodified line101 102 raise PoolTimeout()103 104 def release(self) -> None:114- if self.semaphore is None:115- return116-105 self.semaphore.release()106 107 108 class TrioBackend(ConcurrencyBackend):46 unmodified lines155 return trio.run(156 functools.partial(coroutine, **kwargs) if kwargs else coroutine, *args157 )158 171- def get_semaphore(self, limits: PoolLimits) -> BasePoolSemaphore:172- return PoolSemaphore(limits)159+ def get_semaphore(self, max_value: int) -> BasePoolSemaphore:160+ return PoolSemaphore(max_value)161 162 def create_event(self) -> BaseEvent:163 return Event()164 18 unmodified linesmodified:httpx/dispatch/connection_pool.py+13 added-1 removed
11 unmodified lines12 13 logger = get_logger(__name__)14 15 16+class NullSemaphore(BasePoolSemaphore):17+ async def acquire(self, timeout: float = None) -> None:18+ return19+20+ def release(self) -> None:21+ return22+23+24 class ConnectionStore:25 """26 We need to maintain collections of connections in a way that allows us to:27 78 unmodified lines106 def max_connections(self) -> BasePoolSemaphore:107 # We do this lazily, to make sure backend autodetection always108 # runs within an async context.109 if not hasattr(self, "_max_connections"):110+ limit = self.pool_limits.hard_limit111+ if not limit:112+ self._max_connections = NullSemaphore() # type: BasePoolSemaphore113+ else:102- self._max_connections = self.backend.get_semaphore(self.pool_limits)114+ self._max_connections = self.backend.get_semaphore(limit)115 return self._max_connections116 117 @property118 def num_connections(self) -> int:84 unmodified lines