Connection pooling
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 63d73ad · Browse files · 4 files·+177 added−18 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
4 files+177 added−18 removed
- tests:+112 added−1 removed
- other:+65 added−17 removed
Provenance
- Commit
5f3a8bd- Tree
36bb200- Author
Tom Christie <tom@tomchristie.com>- Committer
Tom Christie <tom@tomchristie.com>- Parent
63d73ad
4 files changed+177 added−18 removed
modified:httpcore/connections.py+29 added-12 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),30 unmodified lines69 event = await self._receive_event()70 assert isinstance(event, h11.Response)71 status_code = event.status_code72 headers = event.headers72- body = self.body_iter()73+ body = self._body_iter()74 return Response(74- status_code=status_code, headers=headers, body=body, on_close=self.close75+ status_code=status_code, headers=headers, body=body, on_close=self._release76 )77 77- async def body_iter(self) -> typing.AsyncIterator[bytes]:78+ async def _body_iter(self) -> typing.AsyncIterator[bytes]:79 event = await self._receive_event()80 while isinstance(event, h11.Data):81 yield event.data82 event = await self._receive_event()83 assert isinstance(event, h11.EndOfMessage)83- 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 108- async def close(self) -> None:109- if self.writer is not None: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+ event = h11.ConnectionClosed()115+ try:116+ # If we're in h11.MUST_CLOSE then we'll end up in h11.CLOSED.117+ self.state.send(event)118+ except h11.ProtocolError:119+ # If we're in some other state then it's a premature close,120+ # and we'll end up in h11.ERROR.121+ pass122+123+ if self.is_closed:124 self.writer.close()125 if hasattr(self.writer, "wait_closed"):126 await self.writer.wait_closed()127+128+ if self.on_release is not None:129+ await self.on_release(self)modified:httpcore/pool.py+36 added-5 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 ConnectionPool:24 def __init__(25 self,26 *,4 unmodified lines31 self.ssl_config = ssl32 self.timeout = timeout33 self.limits = limits34 self.is_closed = False35+ self.num_active_connections = 036+ self.num_keepalive_connections = 037+ self._connections = (38+ {}39+ ) # type: typing.Dict[ConnectionKey, typing.List[Connection]]40 41 async def request(42 self,43 method: str,15 unmodified lines59 await response.close()60 return response61 62 async def acquire_connection(55- self, url: URL, *, ssl: typing.Union[bool, ssl.SSLContext] = False63+ self, url: URL, *, ssl: typing.Optional[ssl.SSLContext] = None64 ) -> Connection:57- connection = Connection(timeout=self.timeout)58- await connection.open(url.hostname, url.port, ssl=ssl)65+ key = (url.scheme, url.hostname, url.port)66+ try:67+ connection = self._connections[key].pop()68+ if not self._connections[key]:69+ del self._connections[key]70+ self.num_keepalive_connections -= 171+ self.num_active_connections += 172+73+ except (KeyError, IndexError):74+ release = functools.partial(self.release_connection, key=key)75+ connection = Connection(timeout=self.timeout, on_release=release)76+ self.num_active_connections += 177+ await connection.open(url.hostname, url.port, ssl=ssl)78+79 return connection80 81+ async def release_connection(82+ self, connection: Connection, key: ConnectionKey83+ ) -> None:84+ self.num_active_connections -= 185+ if not connection.is_closed:86+ self.num_keepalive_connections += 187+ try:88+ self._connections[key].append(connection)89+ except KeyError:90+ self._connections[key] = [connection]91+61- async def get_ssl_context(self, url: URL) -> typing.Union[bool, ssl.SSLContext]:92+ async def get_ssl_context(self, url: URL) -> typing.Optional[ssl.SSLContext]:93 if not url.is_secure:63- return False94+ return None95 96 if not hasattr(self, "ssl_context"):97 if not self.ssl_config.verify:98 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+109 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_streaming_response_holds_connection(server):38+ """39+ A streaming request should hold the connection open until the response is read.40+ """41+ async with httpcore.ConnectionPool() as http:42+ response = await http.request("GET", "http://127.0.0.1:8000/", stream=True)43+ assert http.num_active_connections == 144+ assert http.num_keepalive_connections == 045+46+ await response.read()47+48+ assert http.num_active_connections == 049+ assert http.num_keepalive_connections == 150+51+52+@pytest.mark.asyncio53+async def test_multiple_concurrent_connections(server):54+ """55+ Multiple conncurrent requests should open multiple conncurrent connections.56+ """57+ async with httpcore.ConnectionPool() as http:58+ response_a = await http.request("GET", "http://127.0.0.1:8000/", stream=True)59+ assert http.num_active_connections == 160+ assert http.num_keepalive_connections == 061+62+ response_b = await http.request("GET", "http://127.0.0.1:8000/", stream=True)63+ assert http.num_active_connections == 264+ assert http.num_keepalive_connections == 065+66+ await response_b.read()67+ assert http.num_active_connections == 168+ assert http.num_keepalive_connections == 169+70+ await response_a.read()71+ assert http.num_active_connections == 072+ assert http.num_keepalive_connections == 273+74+75+@pytest.mark.asyncio76+async def test_close_connections(server):77+ """78+ Using a `Connection: close` header should close the connection.79+ """80+ headers = [(b"connection", b"close")]81+ async with httpcore.ConnectionPool() as http:82+ response = await http.request("GET", "http://127.0.0.1:8000/", headers=headers)83+ assert http.num_active_connections == 084+ assert http.num_keepalive_connections == 085+86+87+@pytest.mark.asyncio88+async def test_standard_response_close(server):89+ """90+ A standard close should keep the connection open.91+ """92+ async with httpcore.ConnectionPool() as http:93+ response = await http.request("GET", "http://127.0.0.1:8000/", stream=True)94+ await response.read()95+ await response.close()96+ assert http.num_active_connections == 097+ assert http.num_keepalive_connections == 198+99+100+@pytest.mark.asyncio101+async def test_premature_response_close(server):102+ """103+ A premature close should close the connection.104+ """105+ async with httpcore.ConnectionPool() as http:106+ response = await http.request("GET", "http://127.0.0.1:8000/", stream=True)107+ await response.close()108+ assert http.num_active_connections == 0109+ assert http.num_keepalive_connections == 0