Skip to content
Myr

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

3 files+77 added−51 removed

modified:httpcore/connection_pool.py+3 added-35 removed
1import asyncio1import typing23from .config import (4 DEFAULT_CA_BUNDLE_PATH,
6 unmodified lines
11)12from .connection import HTTPConnection13from .exceptions import PoolTimeout14from .models import Client, Origin, Request, Response15from .streams import PoolSemaphore161718class ConnectionPool(Client):19 def __init__(
11 unmodified lines
31 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)3637 async def send(38 self,39 request: Request,
19 unmodified lines
59 self.num_keepalive_connections -= 160 self.num_active_connections += 16162 except (KeyError, IndexError):65 if timeout is None:66 pool_timeout = self.timeout.pool_timeout67 else:68 pool_timeout = timeout.pool_timeout6970 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 lines
97 all_connections.extend(list(connections))98 self._keepalive_connections.clear()99 for connection in all_connections:100 await connection.close()111112113class ConnectionSemaphore:114 def __init__(self, max_connections: int = None):115 self.max_connections = max_connections116117 @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._semaphore125126 async def acquire(self) -> None:127 if self.semaphore is not None:128 await self.semaphore.acquire()129130 def release(self) -> None:131 if self.semaphore is not None:132 self.semaphore.release()
modified:httpcore/streams.py+50 added-3 removed
1"""2The `Reader` and `Writer` classes here provide a lightweight layer over3`asyncio.StreamReader` and `asyncio.StreamWriter`.45Similarly `PoolSemaphore` is a lightweight layer over `BoundedSemaphore`.65They help encapsulate the timeout logic, make it easier to unit-test7These classes help encapsulate the timeout logic, make it easier to unit-test8protocols, and help keep the rest of the package more `async`/`await`9based, and less strictly `asyncio`-specific.10"""11import asyncio12import enum13import ssl14import typing1514from .config import TimeoutConfig, DEFAULT_TIMEOUT_CONFIG15from .exceptions import ConnectTimeout, ReadTimeout, WriteTimeout16from .config import DEFAULT_TIMEOUT_CONFIG, PoolLimits, TimeoutConfig17from .exceptions import ConnectTimeout, ReadTimeout, PoolTimeout, WriteTimeout1819OptionalTimeout = typing.Optional[TimeoutConfig]2021
17 unmodified lines
39 async def close(self) -> None:40 raise NotImplementedError() # pragma: no cover414243class BasePoolSemaphore:44 def __init__(self, limits: PoolLimits, timeout: TimeoutConfig):45 raise NotImplementedError() # pragma: no cover4647 async def acquire(self, timeout: OptionalTimeout = None) -> None:48 raise NotImplementedError() # pragma: no cover4950 def release(self) -> None:51 raise NotImplementedError() # pragma: no cover525354class Reader(BaseReader):55 def __init__(56 self, stream_reader: asyncio.StreamReader, timeout: TimeoutConfig57 ) -> None:
40 unmodified lines
98 async def close(self) -> None:99 self.stream_writer.close()100101102class PoolSemaphore(BasePoolSemaphore):103 def __init__(self, limits: PoolLimits, timeout: TimeoutConfig):104 self.limits = limits105 self.timeout = timeout106107 @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._semaphore116117 async def acquire(self, timeout: OptionalTimeout = None) -> None:118 if self.semaphore is None:119 return120121 if timeout is None:122 timeout = self.timeout123124 try:125 await asyncio.wait_for(self.semaphore.acquire(), timeout.pool_timeout)126 except asyncio.TimeoutError:127 raise PoolTimeout()128129 def release(self) -> None:130 if self.semaphore is None:131 return132133 self.semaphore.release()134135136async def connect(137 hostname: str,138 port: int,139 ssl_context: typing.Optional[ssl.SSLContext] = None,
23 unmodified lines
modified:tests/test_http2.py+24 added-13 removed
1import json23import h2.config4import h2.connection5import h2.events6import pytest5import json78import httpcore910
50 unmodified lines
6162 request_headers = dict(request["headers"])63 request_data = request["data"]6464 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()7270 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 line
79@pytest.mark.asyncio80async 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 line
91@pytest.mark.asyncio92async 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 }105106107@pytest.mark.asyncio108async 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