Add PoolSemaphore
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 9ab607d · Browse files · 3 files·+77 added−51 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
3 files+77 added−51 removed
- tests:+24 added−13 removed
- other:+53 added−38 removed
Provenance
- Commit
286f04f- Tree
e865508- Author
Tom Christie <tom@tomchristie.com>- Committer
Tom Christie <tom@tomchristie.com>- Parent
9ab607d
3 files changed+77 added−51 removed
modified:httpcore/connection_pool.py+3 added-35 removed
1-import asyncio1 import typing2 3 from .config import (4 DEFAULT_CA_BUNDLE_PATH,6 unmodified lines11 )12 from .connection import HTTPConnection13 from .exceptions import PoolTimeout14 from .models import Client, Origin, Request, Response15+from .streams import PoolSemaphore16 17 18 class ConnectionPool(Client):19 def __init__(11 unmodified lines31 self.num_keepalive_connections = 032 self._keepalive_connections = (33 {}34 ) # type: typing.Dict[Origin, typing.List[HTTPConnection]]35- self._max_connections = ConnectionSemaphore(36- max_connections=self.limits.hard_limit37- )35+ self._max_connections = PoolSemaphore(limits, timeout)36 37 async def send(38 self,39 request: Request,19 unmodified lines59 self.num_keepalive_connections -= 160 self.num_active_connections += 161 62 except (KeyError, IndexError):65- if timeout is None:66- pool_timeout = self.timeout.pool_timeout67- else:68- pool_timeout = timeout.pool_timeout69-70- try:71- await asyncio.wait_for(self._max_connections.acquire(), pool_timeout)72- except asyncio.TimeoutError:73- raise PoolTimeout()63+ await self._max_connections.acquire(timeout)64 connection = HTTPConnection(65 origin,66 ssl=self.ssl,67 timeout=self.timeout,29 unmodified lines97 all_connections.extend(list(connections))98 self._keepalive_connections.clear()99 for connection in all_connections:100 await connection.close()111-112-113-class ConnectionSemaphore:114- def __init__(self, max_connections: int = None):115- self.max_connections = max_connections116-117- @property118- def semaphore(self) -> typing.Optional[asyncio.BoundedSemaphore]:119- if not hasattr(self, "_semaphore"):120- if self.max_connections is None:121- self._semaphore = None122- else:123- self._semaphore = asyncio.BoundedSemaphore(value=self.max_connections)124- return self._semaphore125-126- async def acquire(self) -> None:127- if self.semaphore is not None:128- await self.semaphore.acquire()129-130- def release(self) -> None:131- if self.semaphore is not None:132- self.semaphore.release()modified:httpcore/streams.py+50 added-3 removed
1 """2 The `Reader` and `Writer` classes here provide a lightweight layer over3 `asyncio.StreamReader` and `asyncio.StreamWriter`.4 5+Similarly `PoolSemaphore` is a lightweight layer over `BoundedSemaphore`.6+5-They help encapsulate the timeout logic, make it easier to unit-test7+These classes help encapsulate the timeout logic, make it easier to unit-test8 protocols, and help keep the rest of the package more `async`/`await`9 based, and less strictly `asyncio`-specific.10 """11 import asyncio12 import enum13 import ssl14 import typing15 14-from .config import TimeoutConfig, DEFAULT_TIMEOUT_CONFIG15-from .exceptions import ConnectTimeout, ReadTimeout, WriteTimeout16+from .config import DEFAULT_TIMEOUT_CONFIG, PoolLimits, TimeoutConfig17+from .exceptions import ConnectTimeout, ReadTimeout, PoolTimeout, WriteTimeout18 19 OptionalTimeout = typing.Optional[TimeoutConfig]20 21 17 unmodified lines39 async def close(self) -> None:40 raise NotImplementedError() # pragma: no cover41 42 43+class BasePoolSemaphore:44+ def __init__(self, limits: PoolLimits, timeout: TimeoutConfig):45+ raise NotImplementedError() # pragma: no cover46+47+ async def acquire(self, timeout: OptionalTimeout = None) -> None:48+ raise NotImplementedError() # pragma: no cover49+50+ def release(self) -> None:51+ raise NotImplementedError() # pragma: no cover52+53+54 class Reader(BaseReader):55 def __init__(56 self, stream_reader: asyncio.StreamReader, timeout: TimeoutConfig57 ) -> None:40 unmodified lines98 async def close(self) -> None:99 self.stream_writer.close()100 101 102+class PoolSemaphore(BasePoolSemaphore):103+ def __init__(self, limits: PoolLimits, timeout: TimeoutConfig):104+ self.limits = limits105+ self.timeout = timeout106+107+ @property108+ def semaphore(self) -> typing.Optional[asyncio.BoundedSemaphore]:109+ if not hasattr(self, "_semaphore"):110+ max_connections = self.limits.hard_limit111+ if max_connections is None:112+ self._semaphore = None113+ else:114+ self._semaphore = asyncio.BoundedSemaphore(value=max_connections)115+ return self._semaphore116+117+ async def acquire(self, timeout: OptionalTimeout = None) -> None:118+ if self.semaphore is None:119+ return120+121+ if timeout is None:122+ timeout = self.timeout123+124+ try:125+ await asyncio.wait_for(self.semaphore.acquire(), timeout.pool_timeout)126+ except asyncio.TimeoutError:127+ raise PoolTimeout()128+129+ def release(self) -> None:130+ if self.semaphore is None:131+ return132+133+ self.semaphore.release()134+135+136 async def connect(137 hostname: str,138 port: int,139 ssl_context: typing.Optional[ssl.SSLContext] = None,23 unmodified linesmodified:tests/test_http2.py+24 added-13 removed
1+import json2+3 import h2.config4 import h2.connection5 import h2.events6 import pytest5-import json7 8 import httpcore9 10 50 unmodified lines61 62 request_headers = dict(request["headers"])63 request_data = request["data"]64 64- response_body = json.dumps({65- "method": request_headers[b":method"].decode(),66- "path": request_headers[b":path"].decode(),67- "body": request_data.decode()68- }).encode()65+ response_body = json.dumps(66+ {67+ "method": request_headers[b":method"].decode(),68+ "path": request_headers[b":path"].decode(),69+ "body": request_data.decode(),70+ }71+ ).encode()72 70- response_headers = (71- (b":status", b"200"),72- )73+ response_headers = ((b":status", b"200"),)74 self.conn.send_headers(stream_id, response_headers)75 self.conn.send_data(stream_id, response_body, end_stream=True)76 self.buffer += self.conn.data_to_send()77 1 unmodified line79 @pytest.mark.asyncio80 async def test_http2_get_request():81 server = MockServer()82 origin = httpcore.Origin("http://example.org")82- async with httpcore.HTTP2Connection(reader=server, writer=server, origin=origin) as client:83+ async with httpcore.HTTP2Connection(84+ reader=server, writer=server, origin=origin85+ ) as client:86 response = await client.request("GET", "http://example.org")87 assert response.status_code == 20088 assert json.loads(response.body) == {"method": "GET", "path": "/", "body": ""}89 1 unmodified line91 @pytest.mark.asyncio92 async def test_http2_post_request():93 server = MockServer()94 origin = httpcore.Origin("http://example.org")92- async with httpcore.HTTP2Connection(reader=server, writer=server, origin=origin) as client:95+ async with httpcore.HTTP2Connection(96+ reader=server, writer=server, origin=origin97+ ) as client:98 response = await client.request("POST", "http://example.org", body=b"<data>")99 assert response.status_code == 20095- assert json.loads(response.body) == {"method": "POST", "path": "/", "body": "<data>"}100+ assert json.loads(response.body) == {101+ "method": "POST",102+ "path": "/",103+ "body": "<data>",104+ }105 106 107 @pytest.mark.asyncio108 async def test_http2_multiple_requests():109 server = MockServer()110 origin = httpcore.Origin("http://example.org")102- async with httpcore.HTTP2Connection(reader=server, writer=server, origin=origin) as client:111+ async with httpcore.HTTP2Connection(112+ reader=server, writer=server, origin=origin113+ ) as client:114 response_1 = await client.request("GET", "http://example.org/1")115 response_2 = await client.request("GET", "http://example.org/2")116 response_3 = await client.request("GET", "http://example.org/3")117 8 unmodified lines