Add soft_limit and hard_limit support to PoolLimits
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Tom Christie · committed by Tom Christie · parent 5f3a8bd · Browse files · 4 files·+74 added−19 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
4 files+74 added−19 removed
- tests:+17 added−0 removed
- other:+57 added−19 removed
Provenance
- Commit
29cb53f- Tree
85bf602- Author
Tom Christie <tom@tomchristie.com>- Committer
Tom Christie <tom@tomchristie.com>- Parent
5f3a8bd
4 files changed+74 added−19 removed
modified:httpcore/config.py+8 added-4 removed
43 unmodified lines44 """45 Limits on the number of connections in a connection pool.46 """47 48- def __init__(self, *, max_hosts: int, conns_per_host: int, hard_limit: bool):49- self.max_hosts = max_hosts50- self.conns_per_host = conns_per_host48+ def __init__(49+ self,50+ *,51+ soft_limit: typing.Optional[int] = None,52+ hard_limit: typing.Optional[int] = None53+ ):54+ self.soft_limit = soft_limit55 self.hard_limit = hard_limit56 57 58 DEFAULT_SSL_CONFIG = SSLConfig(cert=None, verify=True)59 DEFAULT_TIMEOUT_CONFIG = TimeoutConfig(timeout=5.0)56-DEFAULT_POOL_LIMITS = PoolLimits(max_hosts=10, conns_per_host=10, hard_limit=False)60+DEFAULT_POOL_LIMITS = PoolLimits(soft_limit=10, hard_limit=100)61 DEFAULT_CA_BUNDLE_PATH = certifi.where()modified:httpcore/connections.py+15 added-13 removed
109 unmodified lines110 111 if self.state.our_state is h11.DONE and self.state.their_state is h11.DONE:112 self.state.start_next_cycle()113 else:114- event = h11.ConnectionClosed()115- try:116- # If we're in h11.MUST_CLOSE then we'll end up in h11.CLOSED.117- self.state.send(event)118- except h11.ProtocolError:119- # If we're in some other state then it's a premature close,120- # and we'll end up in h11.ERROR.121- pass114+ self.close()115 123- if self.is_closed:124- self.writer.close()125- if hasattr(self.writer, "wait_closed"):126- await self.writer.wait_closed()127-116 if self.on_release is not None:117 await self.on_release(self)118+119+ def close(self) -> None:120+ assert self.writer is not None121+122+ event = h11.ConnectionClosed()123+ try:124+ # If we're in h11.MUST_CLOSE then we'll end up in h11.CLOSED.125+ self.state.send(event)126+ except h11.ProtocolError:127+ # If we're in some other state then it's a premature close,128+ # and we'll end up in h11.ERROR.129+ pass130+131+ self.writer.close()modified:httpcore/pool.py+34 added-2 removed
18 unmodified lines19 20 ConnectionKey = typing.Tuple[str, str, int] # (scheme, host, port)21 22 23+class ConnectionSemaphore:24+ def __init__(self, max_connections: int = None):25+ if max_connections is not None:26+ self.semaphore = asyncio.BoundedSemaphore(value=max_connections)27+28+ async def acquire(self) -> None:29+ if hasattr(self, "semaphore"):30+ await self.semaphore.acquire()31+32+ def release(self) -> None:33+ if hasattr(self, "semaphore"):34+ self.semaphore.release()35+36+37 class ConnectionPool:38 def __init__(39 self,40 *,9 unmodified lines50 self.num_keepalive_connections = 051 self._connections = (52 {}53 ) # type: typing.Dict[ConnectionKey, typing.List[Connection]]54+ self._connection_semaphore = ConnectionSemaphore(55+ max_connections=self.limits.hard_limit56+ )57 58 async def request(59 self,60 method: str,14 unmodified lines75 finally:76 await response.close()77 return response78 79+ @property80+ def num_connections(self) -> int:81+ return self.num_active_connections + self.num_keepalive_connections82+83 async def acquire_connection(84 self, url: URL, *, ssl: typing.Optional[ssl.SSLContext] = None85 ) -> Connection:86 key = (url.scheme, url.hostname, url.port)4 unmodified lines91 self.num_keepalive_connections -= 192 self.num_active_connections += 193 94 except (KeyError, IndexError):95+ await self._connection_semaphore.acquire()96 release = functools.partial(self.release_connection, key=key)97 connection = Connection(timeout=self.timeout, on_release=release)98 self.num_active_connections += 199 await connection.open(url.hostname, url.port, ssl=ssl)2 unmodified lines102 103 async def release_connection(104 self, connection: Connection, key: ConnectionKey105 ) -> None:84- self.num_active_connections -= 185- if not connection.is_closed:106+ if connection.is_closed:107+ self._connection_semaphore.release()108+ self.num_active_connections -= 1109+ elif (110+ self.limits.soft_limit is not None111+ and self.num_connections > self.limits.soft_limit112+ ):113+ self._connection_semaphore.release()114+ self.num_active_connections -= 1115+ connection.close()116+ else:117+ self.num_active_connections -= 1118 self.num_keepalive_connections += 1119 try:120 self._connections[key].append(connection)121 except KeyError:73 unmodified linesmodified:tests/test_pool.py+17 added
32 unmodified lines33 assert http.num_keepalive_connections == 234 35 36 @pytest.mark.asyncio37+async def test_soft_limit(server):38+ """39+ The soft_limit config should limit the maximum number of keep-alive connections.40+ """41+ limits = httpcore.PoolLimits(soft_limit=1)42+43+ async with httpcore.ConnectionPool(limits=limits) as http:44+ response = await http.request("GET", "http://127.0.0.1:8000/")45+ assert http.num_active_connections == 046+ assert http.num_keepalive_connections == 147+48+ response = await http.request("GET", "http://localhost:8000/")49+ assert http.num_active_connections == 050+ assert http.num_keepalive_connections == 151+52+53+@pytest.mark.asyncio54 async def test_streaming_response_holds_connection(server):55 """56 A streaming request should hold the connection open until the response is read.57 """69 unmodified lines