Skip to content
Myr

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

4 files+177 added−18 removed

modified:httpcore/connections.py+29 added-12 removed
17 unmodified lines
18]192021class 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_release2829 @property30 def is_closed(self) -> bool:31 return self.state.our_state in (h11.CLOSED, h11.ERROR)3233 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 lines
69 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 )7777 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()8485 async def _send_event(self, event: H11Event) -> None:86 assert self.writer is not None87
16 unmodified lines
104 event = self.state.next_event()105106 return event107108 async def close(self) -> None:109 if self.writer is not None:108 async def _release(self) -> None:109 assert self.writer is not None110111 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 pass122123 if self.is_closed:124 self.writer.close()125 if hasattr(self.writer, "wait_closed"):126 await self.writer.wait_closed()127128 if self.on_release is not None:129 await self.on_release(self)
modified:httpcore/pool.py+36 added-5 removed
1import asyncio2import functools3import os4import ssl5import typing6from types import TracebackType
9 unmodified lines
16)17from .connections import Connection18from .datastructures import URL, Request, Response1920ConnectionKey = typing.Tuple[str, str, int] # (scheme, host, port)212223class ConnectionPool:24 def __init__(25 self,26 *,
4 unmodified lines
31 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]]4041 async def request(42 self,43 method: str,
15 unmodified lines
59 await response.close()60 return response6162 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 += 17273 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)7879 return connection8081 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]9161 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 None9596 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 lines
modified:tests/conftest.py+3 added-1 removed
25 unmodified lines
26 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 task
added:tests/test_pool.py+109 added
1import pytest23import httpcore456@pytest.mark.asyncio7async 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 == 11516 response = await http.request("GET", "http://127.0.0.1:8000/")17 assert http.num_active_connections == 018 assert http.num_keepalive_connections == 1192021@pytest.mark.asyncio22async 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 == 13031 response = await http.request("GET", "http://localhost:8000/")32 assert http.num_active_connections == 033 assert http.num_keepalive_connections == 2343536@pytest.mark.asyncio37async 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 == 04546 await response.read()4748 assert http.num_active_connections == 049 assert http.num_keepalive_connections == 1505152@pytest.mark.asyncio53async 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 == 06162 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 == 06566 await response_b.read()67 assert http.num_active_connections == 168 assert http.num_keepalive_connections == 16970 await response_a.read()71 assert http.num_active_connections == 072 assert http.num_keepalive_connections == 2737475@pytest.mark.asyncio76async 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 == 0858687@pytest.mark.asyncio88async 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 == 19899100@pytest.mark.asyncio101async 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