Skip to content
Myr

connection_pool.py

This file

Path

httpcore/dispatch/connection_pool.py

167 lines · 5.2 KiB · Python

Last changed by

Merge pull request #60 from encode/concurrency-backend-classTom Christiebefore adoption3d997af

History of this file

Take it

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 1–3why, one step back
1import collections.abc
2import typing3

Merge pull request #60 from encode/concurrency-backend-classTom Christiebefore adoption3d997af

line 4why, one step back
4from ..concurrency import AsyncioBackend

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 5–15why, one step back
5from ..config import (
6 DEFAULT_CA_BUNDLE_PATH,7 DEFAULT_POOL_LIMITS,8 DEFAULT_SSL_CONFIG,9 DEFAULT_TIMEOUT_CONFIG,10 PoolLimits,11 SSLConfig,12 TimeoutConfig,13)14from ..decoders import ACCEPT_ENCODING15from ..exceptions import PoolTimeout

Merge pull request #60 from encode/concurrency-backend-classTom Christiebefore adoption3d997af

line 16why, one step back
16from ..interfaces import ConcurrencyBackend, Dispatcher

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 17–85why, one step back
17from ..models import Origin, Request, Response
18from .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)8485

Merge pull request #55 from encode/drop-adaptersTom Christiebefore adoptiond72a144

line 86why, one step back
86class ConnectionPool(Dispatcher):

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 87–91why, one step back
87 def __init__(
88 self,89 *,90 ssl: SSLConfig = DEFAULT_SSL_CONFIG,91 timeout: TimeoutConfig = DEFAULT_TIMEOUT_CONFIG,

Truckin' onTom Christiebefore adoption6b60d95

line 92why, one step back
92 pool_limits: PoolLimits = DEFAULT_POOL_LIMITS,

Merge pull request #60 from encode/concurrency-backend-classTom Christiebefore adoption3d997af

line 93why, one step back
93 backend: ConcurrencyBackend = None,

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 94–96why, one step back
94 ):
95 self.ssl = ssl96 self.timeout = timeout

Truckin' onTom Christiebefore adoption6b60d95

line 97why, one step back
97 self.pool_limits = pool_limits

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 98–102why, one step back
98 self.is_closed = False
99100 self.keepalive_connections = ConnectionStore()101 self.active_connections = ConnectionStore()102

Merge pull request #60 from encode/concurrency-backend-classTom Christiebefore adoption3d997af

lines 103–105why, one step back
103 self.backend = AsyncioBackend() if backend is None else backend
104 self.max_connections = self.backend.get_semaphore(pool_limits)105

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 106–109why, one step back
106 @property
107 def num_connections(self) -> int:108 return len(self.keepalive_connections) + len(self.active_connections)109

Merge pull request #55 from encode/drop-adaptersTom Christiebefore adoptiond72a144

lines 110–116why, one step back
110 async def send(
111 self,112 request: Request,113 stream: bool = False,114 ssl: SSLConfig = None,115 timeout: TimeoutConfig = None,116 ) -> Response:

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 117–118why, one step back
117 connection = await self.acquire_connection(request.url.origin)
118 try:

Merge pull request #55 from encode/drop-adaptersTom Christiebefore adoptiond72a144

lines 119–121why, one step back
119 response = await connection.send(
120 request, stream=stream, ssl=ssl, timeout=timeout121 )

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 122–138why, one step back
122 except BaseException as exc:
123 self.active_connections.remove(connection)124 self.max_connections.release()125 raise exc126 return response127128 async def acquire_connection(self, origin: Origin) -> HTTPConnection:129 connection = self.active_connections.pop_by_origin(origin, http2_only=True)130 if connection is None:131 connection = self.keepalive_connections.pop_by_origin(origin)132133 if connection is None:134 await self.max_connections.acquire()135 connection = HTTPConnection(136 origin,137 ssl=self.ssl,138 timeout=self.timeout,

Merge pull request #60 from encode/concurrency-backend-classTom Christiebefore adoption3d997af

line 139why, one step back
139 backend=self.backend,

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 140–151why, one step back
140 release_func=self.release_connection,
141 )142143 self.active_connections.add(connection)144145 return connection146147 async def release_connection(self, connection: HTTPConnection) -> None:148 if connection.is_closed:149 self.active_connections.remove(connection)150 self.max_connections.release()151 elif (

Truckin' onTom Christiebefore adoption6b60d95

lines 152–153why, one step back
152 self.pool_limits.soft_limit is not None
153 and self.num_connections > self.pool_limits.soft_limit

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 154–167why, one step back
154 ):
155 self.active_connections.remove(connection)156 self.max_connections.release()157 await connection.close()158 else:159 self.active_connections.remove(connection)160 self.keepalive_connections.add(connection)161162 async def close(self) -> None:163 self.is_closed = True164 connections = list(self.keepalive_connections)165 self.keepalive_connections.clear()166 for connection in connections:167 await connection.close()