connection_pool.py
This file
Path
httpcore/dispatch/connection_pool.py
165 lines · 5.2 KiB · Python
Last changed by
Work on bringing API into parity with `requests`. (#76)Tom Christiebefore adoption9574041
History of this fileTake it
1import typing23from ..concurrency import AsyncioBackend4from ..config import (5 DEFAULT_CA_BUNDLE_PATH,6 DEFAULT_POOL_LIMITS,7 DEFAULT_TIMEOUT_CONFIG,8 CertTypes,9 PoolLimits,10 TimeoutTypes,11 VerifyTypes,12)13from ..decoders import ACCEPT_ENCODING14from ..exceptions import PoolTimeout15from ..interfaces import ConcurrencyBackend, Dispatcher16from ..models import Origin, Request, Response17from .connection import HTTPConnection1819CONNECTIONS_DICT = typing.Dict[Origin, typing.List[HTTPConnection]]202122class ConnectionStore:23 """24 We need to maintain collections of connections in a way that allows us to:2526 * Lookup connections by origin.27 * Iterate over connections by insertion time.28 * Return the total number of connections.29 """3031 def __init__(self) -> None:32 self.all = {} # type: typing.Dict[HTTPConnection, float]33 self.by_origin = (34 {}35 ) # type: typing.Dict[Origin, typing.Dict[HTTPConnection, float]]3637 def pop_by_origin(38 self, origin: Origin, http2_only: bool = False39 ) -> typing.Optional[HTTPConnection]:40 try:41 connections = self.by_origin[origin]42 except KeyError:43 return None4445 connection = next(reversed(list(connections.keys())))46 if http2_only and not connection.is_http2:47 return None4849 del connections[connection]50 if not connections:51 del self.by_origin[origin]52 del self.all[connection]5354 return connection5556 def add(self, connection: HTTPConnection) -> None:57 self.all[connection] = 0.058 try:59 self.by_origin[connection.origin][connection] = 0.060 except KeyError:61 self.by_origin[connection.origin] = {connection: 0.0}6263 def remove(self, connection: HTTPConnection) -> None:64 del self.all[connection]65 del self.by_origin[connection.origin][connection]66 if not self.by_origin[connection.origin]:67 del self.by_origin[connection.origin]6869 def clear(self) -> None:70 self.all.clear()71 self.by_origin.clear()7273 def __iter__(self) -> typing.Iterator[HTTPConnection]:74 return iter(self.all.keys())7576 def __len__(self) -> int:77 return len(self.all)787980class ConnectionPool(Dispatcher):81 def __init__(82 self,83 *,84 verify: VerifyTypes = True,85 cert: CertTypes = None,86 timeout: TimeoutTypes = DEFAULT_TIMEOUT_CONFIG,87 pool_limits: PoolLimits = DEFAULT_POOL_LIMITS,88 backend: ConcurrencyBackend = None,89 ):90 self.verify = verify91 self.cert = cert92 self.timeout = timeout93 self.pool_limits = pool_limits94 self.is_closed = False9596 self.keepalive_connections = ConnectionStore()97 self.active_connections = ConnectionStore()9899 self.backend = AsyncioBackend() if backend is None else backend100 self.max_connections = self.backend.get_semaphore(pool_limits)101102 @property103 def num_connections(self) -> int:104 return len(self.keepalive_connections) + len(self.active_connections)105106 async def send(107 self,108 request: Request,109 stream: bool = False,110 verify: VerifyTypes = None,111 cert: CertTypes = None,112 timeout: TimeoutTypes = None,113 ) -> Response:114 connection = await self.acquire_connection(request.url.origin)115 try:116 response = await connection.send(117 request, stream=stream, verify=verify, cert=cert, timeout=timeout118 )119 except BaseException as exc:120 self.active_connections.remove(connection)121 self.max_connections.release()122 raise exc123 return response124125 async def acquire_connection(self, origin: Origin) -> HTTPConnection:126 connection = self.active_connections.pop_by_origin(origin, http2_only=True)127 if connection is None:128 connection = self.keepalive_connections.pop_by_origin(origin)129130 if connection is None:131 await self.max_connections.acquire()132 connection = HTTPConnection(133 origin,134 verify=self.verify,135 cert=self.cert,136 timeout=self.timeout,137 backend=self.backend,138 release_func=self.release_connection,139 )140141 self.active_connections.add(connection)142143 return connection144145 async def release_connection(self, connection: HTTPConnection) -> None:146 if connection.is_closed:147 self.active_connections.remove(connection)148 self.max_connections.release()149 elif (150 self.pool_limits.soft_limit is not None151 and self.num_connections > self.pool_limits.soft_limit152 ):153 self.active_connections.remove(connection)154 self.max_connections.release()155 await connection.close()156 else:157 self.active_connections.remove(connection)158 self.keepalive_connections.add(connection)159160 async def close(self) -> None:161 self.is_closed = True162 connections = list(self.keepalive_connections)163 self.keepalive_connections.clear()164 for connection in connections:165 await connection.close()