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
Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 1–2why, one step back1import typing2Merge pull request #60 from encode/concurrency-backend-classTom Christiebefore adoption3d997af
line 3why, one step back3from ..concurrency import AsyncioBackendMerge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 4–7why, one step back4from ..config import (5 DEFAULT_CA_BUNDLE_PATH,6 DEFAULT_POOL_LIMITS,7 DEFAULT_TIMEOUT_CONFIG,Work on bringing API into parity with `requests`. (#76)Tom Christiebefore adoption9574041
line 8why, one step back8 CertTypes,Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
line 9why, one step back9 PoolLimits,Work on bringing API into parity with `requests`. (#76)Tom Christiebefore adoption9574041
lines 10–11why, one step back10 TimeoutTypes,11 VerifyTypes,Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 12–14why, one step back12)13from ..decoders import ACCEPT_ENCODING14from ..exceptions import PoolTimeoutMerge pull request #60 from encode/concurrency-backend-classTom Christiebefore adoption3d997af
line 15why, one step back15from ..interfaces import ConcurrencyBackend, DispatcherMerge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 16–21why, one step back16from ..models import Origin, Request, Response17from .connection import HTTPConnection1819CONNECTIONS_DICT = typing.Dict[Origin, typing.List[HTTPConnection]]2021Drop unused interface on ConnectionStore (#70)Tom Christiebefore adoption3ed0885
line 22why, one step back22class ConnectionStore:Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 23–79why, one step back23 """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)7879Merge pull request #55 from encode/drop-adaptersTom Christiebefore adoptiond72a144
line 80why, one step back80class ConnectionPool(Dispatcher):Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 81–83why, one step back81 def __init__(82 self,83 *,Work on bringing API into parity with `requests`. (#76)Tom Christiebefore adoption9574041
lines 84–86why, one step back84 verify: VerifyTypes = True,85 cert: CertTypes = None,86 timeout: TimeoutTypes = DEFAULT_TIMEOUT_CONFIG,Truckin' onTom Christiebefore adoption6b60d95
line 87why, one step back87 pool_limits: PoolLimits = DEFAULT_POOL_LIMITS,Merge pull request #60 from encode/concurrency-backend-classTom Christiebefore adoption3d997af
line 88why, one step back88 backend: ConcurrencyBackend = None,Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
line 89why, one step back89 ):Work on bringing API into parity with `requests`. (#76)Tom Christiebefore adoption9574041
lines 90–91why, one step back90 self.verify = verify91 self.cert = certMerge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
line 92why, one step back92 self.timeout = timeoutTruckin' onTom Christiebefore adoption6b60d95
line 93why, one step back93 self.pool_limits = pool_limitsMerge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 94–98why, one step back94 self.is_closed = False9596 self.keepalive_connections = ConnectionStore()97 self.active_connections = ConnectionStore()98Merge pull request #60 from encode/concurrency-backend-classTom Christiebefore adoption3d997af
lines 99–101why, one step back99 self.backend = AsyncioBackend() if backend is None else backend100 self.max_connections = self.backend.get_semaphore(pool_limits)101Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 102–105why, one step back102 @property103 def num_connections(self) -> int:104 return len(self.keepalive_connections) + len(self.active_connections)105Merge pull request #55 from encode/drop-adaptersTom Christiebefore adoptiond72a144
lines 106–109why, one step back106 async def send(107 self,108 request: Request,109 stream: bool = False,Work on bringing API into parity with `requests`. (#76)Tom Christiebefore adoption9574041
lines 110–112why, one step back110 verify: VerifyTypes = None,111 cert: CertTypes = None,112 timeout: TimeoutTypes = None,Merge pull request #55 from encode/drop-adaptersTom Christiebefore adoptiond72a144
line 113why, one step back113 ) -> Response:Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 114–115why, one step back114 connection = await self.acquire_connection(request.url.origin)115 try:Merge pull request #55 from encode/drop-adaptersTom Christiebefore adoptiond72a144
line 116why, one step back116 response = await connection.send(Work on bringing API into parity with `requests`. (#76)Tom Christiebefore adoption9574041
line 117why, one step back117 request, stream=stream, verify=verify, cert=cert, timeout=timeoutMerge pull request #55 from encode/drop-adaptersTom Christiebefore adoptiond72a144
line 118why, one step back118 )Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 119–133why, one step back119 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,Work on bringing API into parity with `requests`. (#76)Tom Christiebefore adoption9574041
lines 134–135why, one step back134 verify=self.verify,135 cert=self.cert,Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
line 136why, one step back136 timeout=self.timeout,Merge pull request #60 from encode/concurrency-backend-classTom Christiebefore adoption3d997af
line 137why, one step back137 backend=self.backend,Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 138–149why, one step back138 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 (Truckin' onTom Christiebefore adoption6b60d95
lines 150–151why, one step back150 self.pool_limits.soft_limit is not None151 and self.num_connections > self.pool_limits.soft_limitMerge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 152–165why, one step back152 ):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()