Skip to content
Myr

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

6 files+129 added−74 removed

modified:httpcore/connection_pool.py+84 added-35 removed
1import collections.abc2import typing34from .config import (5 DEFAULT_CA_BUNDLE_PATH,
8 unmodified lines
14from .exceptions import PoolTimeout15from .models import Client, Origin, Request, Response16from .streams import PoolSemaphore1718CONNECTIONS_DICT = typing.Dict[Origin, typing.List[HTTPConnection]]192021class ConnectionStore(collections.abc.Sequence):22 """23 We need to maintain collections of connections in a way that allows us to:2425 * Lookup connections by origin.26 * Iterate over connections by insertion time.27 * Return the total number of connections.28 """2930 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]]3536 def pop_by_origin(self, origin: Origin) -> typing.Optional[HTTPConnection]:37 try:38 connections = self.by_origin[origin]39 except KeyError:40 return None4142 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]4748 return connection4950 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}5657 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]6263 def clear(self) -> None:64 self.all.clear()65 self.by_origin.clear()6667 def __iter__(self) -> typing.Iterator[HTTPConnection]:68 return iter(self.all.keys())6970 def __getitem__(self, key: typing.Any) -> typing.Any:71 if key in self.all:72 return key73 return None7475 def __len__(self) -> int:76 return len(self.all)777879class ConnectionPool(Client):80 def __init__(81 self,82 *,
4 unmodified lines
87 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)9192 self.max_connections = PoolSemaphore(limits, timeout)93 self.keepalive_connections = ConnectionStore()94 self.active_connections = ConnectionStore()9596 @property97 def num_connections(self) -> int:98 return len(self.keepalive_connections) + len(self.active_connections)99100 async def send(101 self,102 request: Request,103 *,
3 unmodified lines
107 connection = await self.acquire_connection(request.url.origin, timeout=timeout)108 response = await connection.send(request, ssl=ssl, timeout=timeout)109 return response11048 @property49 def num_connections(self) -> int:50 return self.num_active_connections + self.num_keepalive_connections51111 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)11562 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 += 1124125 self.active_connections.add(connection)126127 return connection128129 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)143144 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
1import functools2import typing34import h2.connection5import h11
11 unmodified lines
17 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]2930 async def send(
12 unmodified lines
43 hostname = self.origin.hostname44 port = self.origin.port45 ssl_context = await ssl.load_ssl_context() if self.origin.is_ssl else None4647 if self.pool_release_func is None:48 on_release = None49 else:50 on_release = functools.partial(self.pool_release_func, self)5152 reader, writer, protocol = await connect(53 hostname, port, ssl_context, timeout54 )55 if protocol == Protocol.HTTP_2:
1 unmodified line
57 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 )7172 if self.h2_connection is not None:73 response = await self.h2_connection.send(request, ssl=ssl, timeout=timeout)
19 unmodified lines
modified:httpcore/http11.py+3 added-3 removed
80 unmodified lines
81 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 )8788 async def _body_iter(self, timeout: OptionalTimeout) -> typing.AsyncIterator[bytes]:89 event = await self._receive_event(timeout)
15 unmodified lines
105 event = self.h11_state.next_event()106107 return event108109 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 line
115 else:116 await self.close()117118 if self.on_release is not None:119 await self.on_release(self)119 await self.on_release()120121 async def close(self) -> None:122 event = h11.ConnectionClosed()123 try:
8 unmodified lines
modified:httpcore/http2.py+1 added-1 removed
139 unmodified lines
140 return self.events[stream_id].pop(0)141142 async def release(self) -> None:143 if self.on_release is not None:144 await self.on_release(self)144 await self.on_release()145146 async def close(self) -> None:147 await self.writer.close()
modified:httpcore/streams.py+1 added-1 removed
12 unmodified lines
13import ssl14import typing1516from .config import DEFAULT_TIMEOUT_CONFIG, PoolLimits, TimeoutConfig17from .exceptions import ConnectTimeout, ReadTimeout, PoolTimeout, WriteTimeout17from .exceptions import ConnectTimeout, PoolTimeout, ReadTimeout, WriteTimeout1819OptionalTimeout = typing.Optional[TimeoutConfig]2021
141 unmodified lines
modified:tests/test_connection_pools.py+30 added-30 removed
8 unmodified lines
9 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) == 11516 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) == 1192021@pytest.mark.asyncio22async def test_differing_connection_keys(server):
1 unmodified line
24 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) == 13031 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) == 2343536@pytest.mark.asyncio37async def test_soft_limit(server):
3 unmodified lines
41 limits = httpcore.PoolLimits(soft_limit=1)4243 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) == 14748 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) == 1515253@pytest.mark.asyncio54async def test_streaming_response_holds_connection(server):
1 unmodified line
56 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) == 06263 await response.read()6465 assert http.num_active_connections == 066 assert http.num_keepalive_connections == 165 assert len(http.active_connections) == 066 assert len(http.keepalive_connections) == 1676869@pytest.mark.asyncio70async def test_multiple_concurrent_connections(server):
1 unmodified line
72 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) == 07879 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) == 08283 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) == 18687 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) == 2909192@pytest.mark.asyncio93async def test_close_connections(server):
2 unmodified lines
96 """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) == 0102103104@pytest.mark.asyncio105async def test_standard_response_close(server):
3 unmodified lines
109 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) == 1115116117@pytest.mark.asyncio118async def test_premature_response_close(server):
2 unmodified lines
121 """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