Skip to content
Myr

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 file

Take it

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 1–2why, one step back
1import typing
2

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

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 4–7why, one step back
4from ..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 back
8 CertTypes,

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

line 9why, one step back
9 PoolLimits,

Work on bringing API into parity with `requests`. (#76)Tom Christiebefore adoption9574041

lines 10–11why, one step back
10 TimeoutTypes,
11 VerifyTypes,

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 12–14why, one step back
12)
13from ..decoders import ACCEPT_ENCODING14from ..exceptions import PoolTimeout

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

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 16–21why, one step back
16from ..models import Origin, Request, Response
17from .connection import HTTPConnection1819CONNECTIONS_DICT = typing.Dict[Origin, typing.List[HTTPConnection]]2021

Drop unused interface on ConnectionStore (#70)Tom Christiebefore adoption3ed0885

line 22why, one step back
22class ConnectionStore:

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 23–79why, one step back
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)7879

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

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 81–83why, one step back
81 def __init__(
82 self,83 *,

Work on bringing API into parity with `requests`. (#76)Tom Christiebefore adoption9574041

lines 84–86why, one step back
84 verify: VerifyTypes = True,
85 cert: CertTypes = None,86 timeout: TimeoutTypes = DEFAULT_TIMEOUT_CONFIG,

Truckin' onTom Christiebefore adoption6b60d95

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

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

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

line 89why, one step back
89 ):

Work on bringing API into parity with `requests`. (#76)Tom Christiebefore adoption9574041

lines 90–91why, one step back
90 self.verify = verify
91 self.cert = cert

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

line 92why, one step back
92 self.timeout = timeout

Truckin' onTom Christiebefore adoption6b60d95

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 94–98why, one step back
94 self.is_closed = False
9596 self.keepalive_connections = ConnectionStore()97 self.active_connections = ConnectionStore()98

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

lines 99–101why, one step back
99 self.backend = AsyncioBackend() if backend is None else backend
100 self.max_connections = self.backend.get_semaphore(pool_limits)101

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 102–105why, one step back
102 @property
103 def num_connections(self) -> int:104 return len(self.keepalive_connections) + len(self.active_connections)105

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

lines 106–109why, one step back
106 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 back
110 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 back
113 ) -> Response:

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

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

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

line 116why, one step back
116 response = await connection.send(

Work on bringing API into parity with `requests`. (#76)Tom Christiebefore adoption9574041

line 117why, one step back
117 request, stream=stream, verify=verify, cert=cert, timeout=timeout

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

line 118why, one step back
118 )

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 119–133why, one step back
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,

Work on bringing API into parity with `requests`. (#76)Tom Christiebefore adoption9574041

lines 134–135why, one step back
134 verify=self.verify,
135 cert=self.cert,

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

line 136why, one step back
136 timeout=self.timeout,

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

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 138–149why, one step back
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 (

Truckin' onTom Christiebefore adoption6b60d95

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

Merge pull request #23 from encode/adaptersTom Christiebefore adoption696c054

lines 152–165why, one step back
152 ):
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()