Tighten up connection acquiry/release
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Tom Christie · committed by Tom Christie · parent 286f04f · Browse files · 6 files·+129 added−74 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
6 files+129 added−74 removed
- tests:+30 added−30 removed
- other:+99 added−44 removed
Provenance
- Commit
28c505a- Tree
3abaea5- Author
Tom Christie <tom@tomchristie.com>- Committer
Tom Christie <tom@tomchristie.com>- Parent
286f04f
6 files changed+129 added−74 removed
modified:httpcore/connection_pool.py+84 added-35 removed
1+import collections.abc2 import typing3 4 from .config import (5 DEFAULT_CA_BUNDLE_PATH,8 unmodified lines14 from .exceptions import PoolTimeout15 from .models import Client, Origin, Request, Response16 from .streams import PoolSemaphore17 18+CONNECTIONS_DICT = typing.Dict[Origin, typing.List[HTTPConnection]]19 20+21+class ConnectionStore(collections.abc.Sequence):22+ """23+ We need to maintain collections of connections in a way that allows us to:24+25+ * Lookup connections by origin.26+ * Iterate over connections by insertion time.27+ * Return the total number of connections.28+ """29+30+ def __init__(self) -> None:31+ self.all = {} # type: typing.Dict[HTTPConnection, float]32+ self.by_origin = (33+ {}34+ ) # type: typing.Dict[Origin, typing.Dict[HTTPConnection, float]]35+36+ def pop_by_origin(self, origin: Origin) -> typing.Optional[HTTPConnection]:37+ try:38+ connections = self.by_origin[origin]39+ except KeyError:40+ return None41+42+ connection = next(reversed(list(connections.keys())))43+ del connections[connection]44+ if not connections:45+ del self.by_origin[origin]46+ del self.all[connection]47+48+ return connection49+50+ def add(self, connection: HTTPConnection) -> None:51+ self.all[connection] = 0.052+ try:53+ self.by_origin[connection.origin][connection] = 0.054+ except KeyError:55+ self.by_origin[connection.origin] = {connection: 0.0}56+57+ def remove(self, connection: HTTPConnection) -> None:58+ del self.all[connection]59+ del self.by_origin[connection.origin][connection]60+ if not self.by_origin[connection.origin]:61+ del self.by_origin[connection.origin]62+63+ def clear(self) -> None:64+ self.all.clear()65+ self.by_origin.clear()66+67+ def __iter__(self) -> typing.Iterator[HTTPConnection]:68+ return iter(self.all.keys())69+70+ def __getitem__(self, key: typing.Any) -> typing.Any:71+ if key in self.all:72+ return key73+ return None74+75+ def __len__(self) -> int:76+ return len(self.all)77+78+79 class ConnectionPool(Client):80 def __init__(81 self,82 *,4 unmodified lines87 self.ssl = ssl88 self.timeout = timeout89 self.limits = limits90 self.is_closed = False30- self.num_active_connections = 031- self.num_keepalive_connections = 032- self._keepalive_connections = (33- {}34- ) # type: typing.Dict[Origin, typing.List[HTTPConnection]]35- self._max_connections = PoolSemaphore(limits, timeout)91 92+ self.max_connections = PoolSemaphore(limits, timeout)93+ self.keepalive_connections = ConnectionStore()94+ self.active_connections = ConnectionStore()95+96+ @property97+ def num_connections(self) -> int:98+ return len(self.keepalive_connections) + len(self.active_connections)99+100 async def send(101 self,102 request: Request,103 *,3 unmodified lines107 connection = await self.acquire_connection(request.url.origin, timeout=timeout)108 response = await connection.send(request, ssl=ssl, timeout=timeout)109 return response110 48- @property49- def num_connections(self) -> int:50- return self.num_active_connections + self.num_keepalive_connections51-111 async def acquire_connection(112 self, origin: Origin, timeout: typing.Optional[TimeoutConfig] = None113 ) -> HTTPConnection:55- try:56- connection = self._keepalive_connections[origin].pop()57- if not self._keepalive_connections[origin]:58- del self._keepalive_connections[origin]59- self.num_keepalive_connections -= 160- self.num_active_connections += 1114+ connection = self.keepalive_connections.pop_by_origin(origin)115 62- except (KeyError, IndexError):63- await self._max_connections.acquire(timeout)116+ if connection is None:117+ await self.max_connections.acquire(timeout)118 connection = HTTPConnection(119 origin,120 ssl=self.ssl,121 timeout=self.timeout,68- on_release=self.release_connection,122+ pool_release_func=self.release_connection,123 )70- self.num_active_connections += 1124 125+ self.active_connections.add(connection)126+127 return connection128 129 async def release_connection(self, connection: HTTPConnection) -> None:130 if connection.is_closed:76- self._max_connections.release()77- self.num_active_connections -= 1131+ self.active_connections.remove(connection)132+ self.max_connections.release()133 elif (134 self.limits.soft_limit is not None135 and self.num_connections > self.limits.soft_limit136 ):82- self._max_connections.release()83- self.num_active_connections -= 1137+ self.active_connections.remove(connection)138+ self.max_connections.release()139 await connection.close()140 else:86- self.num_active_connections -= 187- self.num_keepalive_connections += 188- try:89- self._keepalive_connections[connection.origin].append(connection)90- except KeyError:91- self._keepalive_connections[connection.origin] = [connection]141+ self.active_connections.remove(connection)142+ self.keepalive_connections.add(connection)143 144 async def close(self) -> None:145 self.is_closed = True95- all_connections = []96- for connections in self._keepalive_connections.values():97- all_connections.extend(list(connections))98- self._keepalive_connections.clear()99- for connection in all_connections:146+ connections = list(self.keepalive_connections)147+ self.keepalive_connections.clear()148+ for connection in connections:149 await connection.close()modified:httpcore/connection.py+10 added-4 removed
1+import functools2 import typing3 4 import h2.connection5 import h1111 unmodified lines17 self,18 origin: typing.Union[str, Origin],19 ssl: SSLConfig = DEFAULT_SSL_CONFIG,20 timeout: TimeoutConfig = DEFAULT_TIMEOUT_CONFIG,20- on_release: typing.Callable = None,21+ pool_release_func: typing.Callable = None,22 ):23 self.origin = Origin(origin) if isinstance(origin, str) else origin24 self.ssl = ssl25 self.timeout = timeout25- self.on_release = on_release26+ self.pool_release_func = pool_release_func27 self.h11_connection = None # type: typing.Optional[HTTP11Connection]28 self.h2_connection = None # type: typing.Optional[HTTP2Connection]29 30 async def send(12 unmodified lines43 hostname = self.origin.hostname44 port = self.origin.port45 ssl_context = await ssl.load_ssl_context() if self.origin.is_ssl else None46 47+ if self.pool_release_func is None:48+ on_release = None49+ else:50+ on_release = functools.partial(self.pool_release_func, self)51+52 reader, writer, protocol = await connect(53 hostname, port, ssl_context, timeout54 )55 if protocol == Protocol.HTTP_2:1 unmodified line57 reader,58 writer,59 origin=self.origin,60 timeout=self.timeout,55- on_release=self.on_release,61+ on_release=on_release,62 )63 else:64 self.h11_connection = HTTP11Connection(65 reader,66 writer,67 origin=self.origin,68 timeout=self.timeout,63- on_release=self.on_release,69+ on_release=on_release,70 )71 72 if self.h2_connection is not None:73 response = await self.h2_connection.send(request, ssl=ssl, timeout=timeout)19 unmodified linesmodified:httpcore/http11.py+3 added-3 removed
80 unmodified lines81 reason=reason,82 protocol="HTTP/1.1",83 headers=headers,84 body=body,85- on_close=self._release,85+ on_close=self.response_closed,86 )87 88 async def _body_iter(self, timeout: OptionalTimeout) -> typing.AsyncIterator[bytes]:89 event = await self._receive_event(timeout)15 unmodified lines105 event = self.h11_state.next_event()106 107 return event108 109- async def _release(self) -> None:109+ async def response_closed(self) -> None:110 if (111 self.h11_state.our_state is h11.DONE112 and self.h11_state.their_state is h11.DONE113 ):1 unmodified line115 else:116 await self.close()117 118 if self.on_release is not None:119- await self.on_release(self)119+ await self.on_release()120 121 async def close(self) -> None:122 event = h11.ConnectionClosed()123 try:8 unmodified linesmodified:httpcore/http2.py+1 added-1 removed
139 unmodified lines140 return self.events[stream_id].pop(0)141 142 async def release(self) -> None:143 if self.on_release is not None:144- await self.on_release(self)144+ await self.on_release()145 146 async def close(self) -> None:147 await self.writer.close()modified:httpcore/streams.py+1 added-1 removed
12 unmodified lines13 import ssl14 import typing15 16 from .config import DEFAULT_TIMEOUT_CONFIG, PoolLimits, TimeoutConfig17-from .exceptions import ConnectTimeout, ReadTimeout, PoolTimeout, WriteTimeout17+from .exceptions import ConnectTimeout, PoolTimeout, ReadTimeout, WriteTimeout18 19 OptionalTimeout = typing.Optional[TimeoutConfig]20 21 141 unmodified linesmodified:tests/test_connection_pools.py+30 added-30 removed
8 unmodified lines9 Connections should default to staying in a keep-alive state.10 """11 async with httpcore.ConnectionPool() as http:12 response = await http.request("GET", "http://127.0.0.1:8000/")13- assert http.num_active_connections == 014- assert http.num_keepalive_connections == 113+ assert len(http.active_connections) == 014+ assert len(http.keepalive_connections) == 115 16 response = await http.request("GET", "http://127.0.0.1:8000/")17- assert http.num_active_connections == 018- assert http.num_keepalive_connections == 117+ assert len(http.active_connections) == 018+ assert len(http.keepalive_connections) == 119 20 21 @pytest.mark.asyncio22 async def test_differing_connection_keys(server):1 unmodified line24 Connnections to differing connection keys should result in multiple connections.25 """26 async with httpcore.ConnectionPool() as http:27 response = await http.request("GET", "http://127.0.0.1:8000/")28- assert http.num_active_connections == 029- assert http.num_keepalive_connections == 128+ assert len(http.active_connections) == 029+ assert len(http.keepalive_connections) == 130 31 response = await http.request("GET", "http://localhost:8000/")32- assert http.num_active_connections == 033- assert http.num_keepalive_connections == 232+ assert len(http.active_connections) == 033+ assert len(http.keepalive_connections) == 234 35 36 @pytest.mark.asyncio37 async def test_soft_limit(server):3 unmodified lines41 limits = httpcore.PoolLimits(soft_limit=1)42 43 async with httpcore.ConnectionPool(limits=limits) as http:44 response = await http.request("GET", "http://127.0.0.1:8000/")45- assert http.num_active_connections == 046- assert http.num_keepalive_connections == 145+ assert len(http.active_connections) == 046+ assert len(http.keepalive_connections) == 147 48 response = await http.request("GET", "http://localhost:8000/")49- assert http.num_active_connections == 050- assert http.num_keepalive_connections == 149+ assert len(http.active_connections) == 050+ assert len(http.keepalive_connections) == 151 52 53 @pytest.mark.asyncio54 async def test_streaming_response_holds_connection(server):1 unmodified line56 A streaming request should hold the connection open until the response is read.57 """58 async with httpcore.ConnectionPool() as http:59 response = await http.request("GET", "http://127.0.0.1:8000/", stream=True)60- assert http.num_active_connections == 161- assert http.num_keepalive_connections == 060+ assert len(http.active_connections) == 161+ assert len(http.keepalive_connections) == 062 63 await response.read()64 65- assert http.num_active_connections == 066- assert http.num_keepalive_connections == 165+ assert len(http.active_connections) == 066+ assert len(http.keepalive_connections) == 167 68 69 @pytest.mark.asyncio70 async def test_multiple_concurrent_connections(server):1 unmodified line72 Multiple conncurrent requests should open multiple conncurrent connections.73 """74 async with httpcore.ConnectionPool() as http:75 response_a = await http.request("GET", "http://127.0.0.1:8000/", stream=True)76- assert http.num_active_connections == 177- assert http.num_keepalive_connections == 076+ assert len(http.active_connections) == 177+ assert len(http.keepalive_connections) == 078 79 response_b = await http.request("GET", "http://127.0.0.1:8000/", stream=True)80- assert http.num_active_connections == 281- assert http.num_keepalive_connections == 080+ assert len(http.active_connections) == 281+ assert len(http.keepalive_connections) == 082 83 await response_b.read()84- assert http.num_active_connections == 185- assert http.num_keepalive_connections == 184+ assert len(http.active_connections) == 185+ assert len(http.keepalive_connections) == 186 87 await response_a.read()88- assert http.num_active_connections == 089- assert http.num_keepalive_connections == 288+ assert len(http.active_connections) == 089+ assert len(http.keepalive_connections) == 290 91 92 @pytest.mark.asyncio93 async def test_close_connections(server):2 unmodified lines96 """97 headers = [(b"connection", b"close")]98 async with httpcore.ConnectionPool() as http:99 response = await http.request("GET", "http://127.0.0.1:8000/", headers=headers)100- assert http.num_active_connections == 0101- assert http.num_keepalive_connections == 0100+ assert len(http.active_connections) == 0101+ assert len(http.keepalive_connections) == 0102 103 104 @pytest.mark.asyncio105 async def test_standard_response_close(server):3 unmodified lines109 async with httpcore.ConnectionPool() as http:110 response = await http.request("GET", "http://127.0.0.1:8000/", stream=True)111 await response.read()112 await response.close()113- assert http.num_active_connections == 0114- assert http.num_keepalive_connections == 1113+ assert len(http.active_connections) == 0114+ assert len(http.keepalive_connections) == 1115 116 117 @pytest.mark.asyncio118 async def test_premature_response_close(server):2 unmodified lines121 """122 async with httpcore.ConnectionPool() as http:123 response = await http.request("GET", "http://127.0.0.1:8000/", stream=True)124 await response.close()125- assert http.num_active_connections == 0126- assert http.num_keepalive_connections == 0125+ assert len(http.active_connections) == 0126+ assert len(http.keepalive_connections) == 0