connection_pool.py
This file
Path
httpcore/dispatch/connection_pool.py
158 lines · 4.9 KiB · Python
Last changed by
Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
History of this fileTake it
Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 1–158why, one step back1import collections.abc2import typing34from ..config import (5 DEFAULT_CA_BUNDLE_PATH,6 DEFAULT_POOL_LIMITS,7 DEFAULT_SSL_CONFIG,8 DEFAULT_TIMEOUT_CONFIG,9 PoolLimits,10 SSLConfig,11 TimeoutConfig,12)13from ..decoders import ACCEPT_ENCODING14from ..exceptions import PoolTimeout15from ..interfaces import Adapter16from ..models import Origin, Request, Response17from ..streams import PoolSemaphore18from .connection import HTTPConnection1920CONNECTIONS_DICT = typing.Dict[Origin, typing.List[HTTPConnection]]212223class ConnectionStore(collections.abc.Sequence):24 """25 We need to maintain collections of connections in a way that allows us to:2627 * Lookup connections by origin.28 * Iterate over connections by insertion time.29 * Return the total number of connections.30 """3132 def __init__(self) -> None:33 self.all = {} # type: typing.Dict[HTTPConnection, float]34 self.by_origin = (35 {}36 ) # type: typing.Dict[Origin, typing.Dict[HTTPConnection, float]]3738 def pop_by_origin(39 self, origin: Origin, http2_only: bool = False40 ) -> typing.Optional[HTTPConnection]:41 try:42 connections = self.by_origin[origin]43 except KeyError:44 return None4546 connection = next(reversed(list(connections.keys())))47 if http2_only and not connection.is_http2:48 return None4950 del connections[connection]51 if not connections:52 del self.by_origin[origin]53 del self.all[connection]5455 return connection5657 def add(self, connection: HTTPConnection) -> None:58 self.all[connection] = 0.059 try:60 self.by_origin[connection.origin][connection] = 0.061 except KeyError:62 self.by_origin[connection.origin] = {connection: 0.0}6364 def remove(self, connection: HTTPConnection) -> None:65 del self.all[connection]66 del self.by_origin[connection.origin][connection]67 if not self.by_origin[connection.origin]:68 del self.by_origin[connection.origin]6970 def clear(self) -> None:71 self.all.clear()72 self.by_origin.clear()7374 def __iter__(self) -> typing.Iterator[HTTPConnection]:75 return iter(self.all.keys())7677 def __getitem__(self, key: typing.Any) -> typing.Any:78 if key in self.all:79 return key80 return None8182 def __len__(self) -> int:83 return len(self.all)848586class ConnectionPool(Adapter):87 def __init__(88 self,89 *,90 ssl: SSLConfig = DEFAULT_SSL_CONFIG,91 timeout: TimeoutConfig = DEFAULT_TIMEOUT_CONFIG,92 limits: PoolLimits = DEFAULT_POOL_LIMITS,93 ):94 self.ssl = ssl95 self.timeout = timeout96 self.limits = limits97 self.is_closed = False9899 self.max_connections = PoolSemaphore(limits)100 self.keepalive_connections = ConnectionStore()101 self.active_connections = ConnectionStore()102103 @property104 def num_connections(self) -> int:105 return len(self.keepalive_connections) + len(self.active_connections)106107 def prepare_request(self, request: Request) -> None:108 request.prepare()109110 async def send(self, request: Request, **options: typing.Any) -> Response:111 connection = await self.acquire_connection(request.url.origin)112 try:113 response = await connection.send(request, **options)114 except BaseException as exc:115 self.active_connections.remove(connection)116 self.max_connections.release()117 raise exc118 return response119120 async def acquire_connection(self, origin: Origin) -> HTTPConnection:121 connection = self.active_connections.pop_by_origin(origin, http2_only=True)122 if connection is None:123 connection = self.keepalive_connections.pop_by_origin(origin)124125 if connection is None:126 await self.max_connections.acquire()127 connection = HTTPConnection(128 origin,129 ssl=self.ssl,130 timeout=self.timeout,131 release_func=self.release_connection,132 )133134 self.active_connections.add(connection)135136 return connection137138 async def release_connection(self, connection: HTTPConnection) -> None:139 if connection.is_closed:140 self.active_connections.remove(connection)141 self.max_connections.release()142 elif (143 self.limits.soft_limit is not None144 and self.num_connections > self.limits.soft_limit145 ):146 self.active_connections.remove(connection)147 self.max_connections.release()148 await connection.close()149 else:150 self.active_connections.remove(connection)151 self.keepalive_connections.add(connection)152153 async def close(self) -> None:154 self.is_closed = True155 connections = list(self.keepalive_connections)156 self.keepalive_connections.clear()157 for connection in connections:158 await connection.close()