Skip to content
Myr

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

7 files+253 added−41 removed

modified:httpcore/config.py+8 added-4 removed
43 unmodified lines
44 """45 Limits on the number of connections in a connection pool.46 """4748 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_limit565758DEFAULT_SSL_CONFIG = SSLConfig(cert=None, verify=True)59DEFAULT_TIMEOUT_CONFIG = TimeoutConfig(timeout=5.0)56DEFAULT_POOL_LIMITS = PoolLimits(max_hosts=10, conns_per_host=10, hard_limit=False)60DEFAULT_POOL_LIMITS = PoolLimits(soft_limit=10, hard_limit=100)61DEFAULT_CA_BUNDLE_PATH = certifi.where()
modified:httpcore/connections.py+37 added-29 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),
1 unmodified line
40 )41 except asyncio.TimeoutError:42 raise ConnectTimeout()4343 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 lines
69 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 )7773 if stream:74 body_iter = self.body_iter()75 return Response(status_code=status_code, headers=headers, body=body_iter)7677 #  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()8586 return Response(status_code=status_code, headers=headers, body=body)8788 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()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 event107119 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 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 self.close()115116 if self.on_release is not None:117 await self.on_release(self)118119 def close(self) -> None:120 assert self.writer is not None121122 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 pass130131 self.writer.close()
modified:httpcore/datastructures.py+4 added
188 unmodified lines
189 yield part190 await self.close()191192 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
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 ConnectionSemaphore:24 def __init__(self, max_connections: int = None):25 if max_connections is not None:26 self.semaphore = asyncio.BoundedSemaphore(value=max_connections)2728 async def acquire(self) -> None:29 if hasattr(self, "semaphore"):30 await self.semaphore.acquire()3132 def release(self) -> None:33 if hasattr(self, "semaphore"):34 self.semaphore.release()353637class ConnectionPool:38 def __init__(39 self,40 *,
4 unmodified lines
45 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 )5758 async def request(59 self,60 method: str,
6 unmodified lines
67 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 response7879 @property80 def num_connections(self) -> int:81 return self.num_active_connections + self.num_keepalive_connections8283 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 += 19394 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)100101 return connection102103 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]12356 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 None127128 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 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+126 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_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)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 == 14748 response = await http.request("GET", "http://localhost:8000/")49 assert http.num_active_connections == 050 assert http.num_keepalive_connections == 1515253@pytest.mark.asyncio54async 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 == 06263 await response.read()6465 assert http.num_active_connections == 066 assert http.num_keepalive_connections == 1676869@pytest.mark.asyncio70async 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 == 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 == 08283 await response_b.read()84 assert http.num_active_connections == 185 assert http.num_keepalive_connections == 18687 await response_a.read()88 assert http.num_active_connections == 089 assert http.num_keepalive_connections == 2909192@pytest.mark.asyncio93async 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 == 0102103104@pytest.mark.asyncio105async 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 == 1115116117@pytest.mark.asyncio118async 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 == 0
modified:setup.py+1 added-1 removed
45 unmodified lines
46 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