connection_pool.py
This file
Path
httpcore/dispatch/connection_pool.py
161 lines · 5.0 KiB · Python
Last changed by
Drop unused interface on ConnectionStore (#70)Tom Christiebefore adoption3ed0885
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–14why, one step back4from ..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 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–85why, one step back81 def __init__(82 self,83 *,84 ssl: SSLConfig = DEFAULT_SSL_CONFIG,85 timeout: TimeoutConfig = DEFAULT_TIMEOUT_CONFIG,Truckin' onTom Christiebefore adoption6b60d95
line 86why, one step back86 pool_limits: PoolLimits = DEFAULT_POOL_LIMITS,Merge pull request #60 from encode/concurrency-backend-classTom Christiebefore adoption3d997af
line 87why, one step back87 backend: ConcurrencyBackend = None,Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 88–90why, one step back88 ):89 self.ssl = ssl90 self.timeout = timeoutTruckin' onTom Christiebefore adoption6b60d95
line 91why, one step back91 self.pool_limits = pool_limitsMerge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 92–96why, one step back92 self.is_closed = False9394 self.keepalive_connections = ConnectionStore()95 self.active_connections = ConnectionStore()96Merge pull request #60 from encode/concurrency-backend-classTom Christiebefore adoption3d997af
lines 97–99why, one step back97 self.backend = AsyncioBackend() if backend is None else backend98 self.max_connections = self.backend.get_semaphore(pool_limits)99Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 100–103why, one step back100 @property101 def num_connections(self) -> int:102 return len(self.keepalive_connections) + len(self.active_connections)103Merge pull request #55 from encode/drop-adaptersTom Christiebefore adoptiond72a144
lines 104–110why, one step back104 async def send(105 self,106 request: Request,107 stream: bool = False,108 ssl: SSLConfig = None,109 timeout: TimeoutConfig = None,110 ) -> Response:Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 111–112why, one step back111 connection = await self.acquire_connection(request.url.origin)112 try:Merge pull request #55 from encode/drop-adaptersTom Christiebefore adoptiond72a144
lines 113–115why, one step back113 response = await connection.send(114 request, stream=stream, ssl=ssl, timeout=timeout115 )Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 116–132why, one step back116 except BaseException as exc:117 self.active_connections.remove(connection)118 self.max_connections.release()119 raise exc120 return response121122 async def acquire_connection(self, origin: Origin) -> HTTPConnection:123 connection = self.active_connections.pop_by_origin(origin, http2_only=True)124 if connection is None:125 connection = self.keepalive_connections.pop_by_origin(origin)126127 if connection is None:128 await self.max_connections.acquire()129 connection = HTTPConnection(130 origin,131 ssl=self.ssl,132 timeout=self.timeout,Merge pull request #60 from encode/concurrency-backend-classTom Christiebefore adoption3d997af
line 133why, one step back133 backend=self.backend,Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 134–145why, one step back134 release_func=self.release_connection,135 )136137 self.active_connections.add(connection)138139 return connection140141 async def release_connection(self, connection: HTTPConnection) -> None:142 if connection.is_closed:143 self.active_connections.remove(connection)144 self.max_connections.release()145 elif (Truckin' onTom Christiebefore adoption6b60d95
lines 146–147why, one step back146 self.pool_limits.soft_limit is not None147 and self.num_connections > self.pool_limits.soft_limitMerge pull request #23 from encode/adaptersTom Christiebefore adoption696c054
lines 148–161why, one step back148 ):149 self.active_connections.remove(connection)150 self.max_connections.release()151 await connection.close()152 else:153 self.active_connections.remove(connection)154 self.keepalive_connections.add(connection)155156 async def close(self) -> None:157 self.is_closed = True158 connections = list(self.keepalive_connections)159 self.keepalive_connections.clear()160 for connection in connections:161 await connection.close()