Merge pull request #4 from encode/connection-pooling
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Connection pooling
authored by Tom Christie · committed by GitHub · parents 6acdfb8, 29cb53f · Browse files · 7 files·+253 added−41 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
7 files+253 added−41 removed
- tests:+129 added−1 removed
- other:+124 added−40 removed
Provenance
- Commit
68c468a- Tree
aa98db2- Author
Tom Christie <tom@tomchristie.com>- Committer
GitHub <noreply@github.com>- Parent 1
6acdfb8- Parent 2
29cb53f
7 files changed+253 added−41 removed
modified:httpcore/config.py+8 added-4 removed
43 unmodified lines44 """45 Limits on the number of connections in a connection pool.46 """47 48- def __init__(self, *, max_hosts: int, conns_per_host: int, hard_limit: bool):49- self.max_hosts = max_hosts50- self.conns_per_host = conns_per_host48+ def __init__(49+ self,50+ *,51+ soft_limit: typing.Optional[int] = None,52+ hard_limit: typing.Optional[int] = None53+ ):54+ self.soft_limit = soft_limit55 self.hard_limit = hard_limit56 57 58 DEFAULT_SSL_CONFIG = SSLConfig(cert=None, verify=True)59 DEFAULT_TIMEOUT_CONFIG = TimeoutConfig(timeout=5.0)56-DEFAULT_POOL_LIMITS = PoolLimits(max_hosts=10, conns_per_host=10, hard_limit=False)60+DEFAULT_POOL_LIMITS = PoolLimits(soft_limit=10, hard_limit=100)61 DEFAULT_CA_BUNDLE_PATH = certifi.where()modified:httpcore/connections.py+37 added-29 removed
17 unmodified lines18 ]19 20 21 class Connection:22- def __init__(self, timeout: TimeoutConfig):22+ def __init__(self, timeout: TimeoutConfig, on_release: typing.Callable = None):23 self.reader = None24 self.writer = None25 self.state = h11.Connection(our_role=h11.CLIENT)26 self.timeout = timeout27+ self.on_release = on_release28 29+ @property30+ def is_closed(self) -> bool:31+ return self.state.our_state in (h11.CLOSED, h11.ERROR)32+33 async def open(29- self,30- hostname: str,31- port: int,32- *,33- ssl: typing.Union[bool, ssl.SSLContext] = False34+ self, hostname: str, port: int, *, ssl: typing.Optional[ssl.SSLContext] = None35 ) -> None:36 try:37 self.reader, self.writer = await asyncio.wait_for( # type: ignore38 asyncio.open_connection(hostname, port, ssl=ssl),1 unmodified line40 )41 except asyncio.TimeoutError:42 raise ConnectTimeout()43 43- async def send(self, request: Request, stream: bool = False) -> Response:44+ async def send(self, request: Request) -> Response:45 method = request.method.encode()46 target = request.url.target47 headers = request.headers48 20 unmodified lines69 event = await self._receive_event()70 assert isinstance(event, h11.Response)71 status_code = event.status_code72 headers = event.headers73+ body = self._body_iter()74+ return Response(75+ status_code=status_code, headers=headers, body=body, on_close=self._release76+ )77 73- if stream:74- body_iter = self.body_iter()75- return Response(status_code=status_code, headers=headers, body=body_iter)76-77- # Get the response body.78- body = b""78+ async def _body_iter(self) -> typing.AsyncIterator[bytes]:79 event = await self._receive_event()80 while isinstance(event, h11.Data):81- body += event.data82- event = await self._receive_event()83- assert isinstance(event, h11.EndOfMessage)84- await self.close()85-86- return Response(status_code=status_code, headers=headers, body=body)87-88- async def body_iter(self) -> typing.AsyncIterator[bytes]:89- event = await self._receive_event()90- while isinstance(event, h11.Data):81 yield event.data82 event = await self._receive_event()83 assert isinstance(event, h11.EndOfMessage)94- await self.close()84 85 async def _send_event(self, event: H11Event) -> None:86 assert self.writer is not None87 16 unmodified lines104 event = self.state.next_event()105 106 return event107 119- async def close(self) -> None:120- if self.writer is not None:121- self.writer.close()122- if hasattr(self.writer, "wait_closed"):123- await self.writer.wait_closed()108+ async def _release(self) -> None:109+ assert self.writer is not None110+111+ if self.state.our_state is h11.DONE and self.state.their_state is h11.DONE:112+ self.state.start_next_cycle()113+ else:114+ self.close()115+116+ if self.on_release is not None:117+ await self.on_release(self)118+119+ def close(self) -> None:120+ assert self.writer is not None121+122+ event = h11.ConnectionClosed()123+ try:124+ # If we're in h11.MUST_CLOSE then we'll end up in h11.CLOSED.125+ self.state.send(event)126+ except h11.ProtocolError:127+ # If we're in some other state then it's a premature close,128+ # and we'll end up in h11.ERROR.129+ pass130+131+ self.writer.close()modified:httpcore/datastructures.py+4 added
188 unmodified lines189 yield part190 await self.close()191 192 async def close(self) -> None:193+ """194+ Close the response and release the connection.195+ Automatically called if the response body is read to completion.196+ """197 if not self.is_closed:198 self.is_closed = True199 if self.on_close is not None:200 await self.on_close()modified:httpcore/pool.py+74 added-6 removed
1 import asyncio2+import functools3 import os4 import ssl5 import typing6 from types import TracebackType9 unmodified lines16 )17 from .connections import Connection18 from .datastructures import URL, Request, Response19 20+ConnectionKey = typing.Tuple[str, str, int] # (scheme, host, port)21 22+23+class ConnectionSemaphore:24+ def __init__(self, max_connections: int = None):25+ if max_connections is not None:26+ self.semaphore = asyncio.BoundedSemaphore(value=max_connections)27+28+ async def acquire(self) -> None:29+ if hasattr(self, "semaphore"):30+ await self.semaphore.acquire()31+32+ def release(self) -> None:33+ if hasattr(self, "semaphore"):34+ self.semaphore.release()35+36+37 class ConnectionPool:38 def __init__(39 self,40 *,4 unmodified lines45 self.ssl_config = ssl46 self.timeout = timeout47 self.limits = limits48 self.is_closed = False49+ self.num_active_connections = 050+ self.num_keepalive_connections = 051+ self._connections = (52+ {}53+ ) # type: typing.Dict[ConnectionKey, typing.List[Connection]]54+ self._connection_semaphore = ConnectionSemaphore(55+ max_connections=self.limits.hard_limit56+ )57 58 async def request(59 self,60 method: str,6 unmodified lines67 parsed_url = URL(url)68 request = Request(method, parsed_url, headers=headers, body=body)69 ssl_context = await self.get_ssl_context(parsed_url)70 connection = await self.acquire_connection(parsed_url, ssl=ssl_context)46- response = await connection.send(request, stream=stream)71+ response = await connection.send(request)72+ if not stream:73+ try:74+ await response.read()75+ finally:76+ await response.close()77 return response78 79+ @property80+ def num_connections(self) -> int:81+ return self.num_active_connections + self.num_keepalive_connections82+83 async def acquire_connection(50- self, url: URL, *, ssl: typing.Union[bool, ssl.SSLContext] = False84+ self, url: URL, *, ssl: typing.Optional[ssl.SSLContext] = None85 ) -> Connection:52- connection = Connection(timeout=self.timeout)53- await connection.open(url.hostname, url.port, ssl=ssl)86+ key = (url.scheme, url.hostname, url.port)87+ try:88+ connection = self._connections[key].pop()89+ if not self._connections[key]:90+ del self._connections[key]91+ self.num_keepalive_connections -= 192+ self.num_active_connections += 193+94+ except (KeyError, IndexError):95+ await self._connection_semaphore.acquire()96+ release = functools.partial(self.release_connection, key=key)97+ connection = Connection(timeout=self.timeout, on_release=release)98+ self.num_active_connections += 199+ await connection.open(url.hostname, url.port, ssl=ssl)100+101 return connection102 103+ async def release_connection(104+ self, connection: Connection, key: ConnectionKey105+ ) -> None:106+ if connection.is_closed:107+ self._connection_semaphore.release()108+ self.num_active_connections -= 1109+ elif (110+ self.limits.soft_limit is not None111+ and self.num_connections > self.limits.soft_limit112+ ):113+ self._connection_semaphore.release()114+ self.num_active_connections -= 1115+ connection.close()116+ else:117+ self.num_active_connections -= 1118+ self.num_keepalive_connections += 1119+ try:120+ self._connections[key].append(connection)121+ except KeyError:122+ self._connections[key] = [connection]123+56- async def get_ssl_context(self, url: URL) -> typing.Union[bool, ssl.SSLContext]:124+ async def get_ssl_context(self, url: URL) -> typing.Optional[ssl.SSLContext]:125 if not url.is_secure:58- return False126+ return None127 128 if not hasattr(self, "ssl_context"):129 if not self.ssl_config.verify:130 self.ssl_context = self.get_ssl_context_no_verify()64 unmodified linesmodified:tests/conftest.py+3 added-1 removed
25 unmodified lines26 while not server.started:27 await asyncio.sleep(0.0001)28 yield server29 finally:30- task.cancel()30+ server.should_exit = True31+ server.force_exit = True32+ await taskadded:tests/test_pool.py+126 added
1+import pytest2+3+import httpcore4+5+6+@pytest.mark.asyncio7+async def test_keepalive_connections(server):8+ """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 == 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 == 119+20+21+@pytest.mark.asyncio22+async def test_differing_connection_keys(server):23+ """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 == 130+31+ response = await http.request("GET", "http://localhost:8000/")32+ assert http.num_active_connections == 033+ assert http.num_keepalive_connections == 234+35+36+@pytest.mark.asyncio37+async def test_soft_limit(server):38+ """39+ The soft_limit config should limit the maximum number of keep-alive connections.40+ """41+ 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 == 147+48+ response = await http.request("GET", "http://localhost:8000/")49+ assert http.num_active_connections == 050+ assert http.num_keepalive_connections == 151+52+53+@pytest.mark.asyncio54+async def test_streaming_response_holds_connection(server):55+ """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 == 062+63+ await response.read()64+65+ assert http.num_active_connections == 066+ assert http.num_keepalive_connections == 167+68+69+@pytest.mark.asyncio70+async def test_multiple_concurrent_connections(server):71+ """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 == 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 == 082+83+ await response_b.read()84+ assert http.num_active_connections == 185+ assert http.num_keepalive_connections == 186+87+ await response_a.read()88+ assert http.num_active_connections == 089+ assert http.num_keepalive_connections == 290+91+92+@pytest.mark.asyncio93+async def test_close_connections(server):94+ """95+ Using a `Connection: close` header should close the connection.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 == 0102+103+104+@pytest.mark.asyncio105+async def test_standard_response_close(server):106+ """107+ A standard close should keep the connection open.108+ """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 == 1115+116+117+@pytest.mark.asyncio118+async def test_premature_response_close(server):119+ """120+ A premature close should close the connection.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 == 0modified:setup.py+1 added-1 removed
45 unmodified lines46 author="Tom Christie",47 author_email="tom@tomchristie.com",48 packages=get_packages("httpcore"),49 data_files=[("", ["LICENSE.md"])],50- install_requires=["h11"],50+ install_requires=["h11", "certifi"],51 classifiers=[52 "Development Status :: 3 - Alpha",53 "Environment :: Web Environment",54 "Intended Audience :: Developers",9 unmodified lines