Merge pull request #12 from encode/refactor
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Refactor
authored by Tom Christie · committed by GitHub · parents 30a03f4, 5b2f3ed · Browse files · 8 files·+281 added−234 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
8 files+281 added−234 removed
- tests:+30 added−57 removed
- other:+251 added−177 removed
Provenance
- Commit
39eb55b- Tree
c0ae1eb- Author
Tom Christie <tom@tomchristie.com>- Committer
GitHub <noreply@github.com>- Parent 1
30a03f4- Parent 2
5b2f3ed
8 files changed+281 added−234 removed
modified:httpcore/__init__.py+2 added-1 removed
1 from .config import PoolLimits, SSLConfig, TimeoutConfig2+from .connections import Connection2-from .datastructures import URL, Request, Response3+from .datastructures import URL, Origin, Request, Response4 from .exceptions import (5 BadResponse,6 ConnectTimeout,7 PoolTimeout,8 unmodified linesmodified:httpcore/config.py+55 added
1+import asyncio2+import os3+import ssl4 import typing5 6 import certifi7 26 unmodified lines34 def __repr__(self) -> str:35 class_name = self.__class__.__name__36 return f"{class_name}(cert={self.cert}, verify={self.verify})"37 38+ async def load_ssl_context(self) -> ssl.SSLContext:39+ if not hasattr(self, "ssl_context"):40+ if not self.verify:41+ self.ssl_context = self.load_ssl_context_no_verify()42+ else:43+ # Run the SSL loading in a threadpool, since it makes disk accesses.44+ loop = asyncio.get_event_loop()45+ self.ssl_context = await loop.run_in_executor(46+ None, self.load_ssl_context_verify47+ )48 49+ return self.ssl_context50+51+ def load_ssl_context_no_verify(self) -> ssl.SSLContext:52+ """53+ Return an SSL context for unverified connections.54+ """55+ context = ssl.SSLContext(ssl.PROTOCOL_SSLv23)56+ context.options |= ssl.OP_NO_SSLv257+ context.options |= ssl.OP_NO_SSLv358+ context.options |= ssl.OP_NO_COMPRESSION59+ context.set_default_verify_paths()60+ return context61+62+ def load_ssl_context_verify(self) -> ssl.SSLContext:63+ """64+ Return an SSL context for verified connections.65+ """66+ if isinstance(self.verify, bool):67+ ca_bundle_path = DEFAULT_CA_BUNDLE_PATH68+ elif os.path.exists(self.verify):69+ ca_bundle_path = self.verify70+ else:71+ raise IOError(72+ "Could not find a suitable TLS CA certificate bundle, "73+ "invalid path: {}".format(self.verify)74+ )75+76+ context = ssl.create_default_context()77+ if os.path.isfile(ca_bundle_path):78+ context.load_verify_locations(cafile=ca_bundle_path)79+ elif os.path.isdir(ca_bundle_path):80+ context.load_verify_locations(capath=ca_bundle_path)81+82+ if self.cert is not None:83+ if isinstance(self.cert, str):84+ context.load_cert_chain(certfile=self.cert)85+ else:86+ context.load_cert_chain(certfile=self.cert[0], keyfile=self.cert[1])87+88+ return context89+90+91 class TimeoutConfig:92 """93 Timeout values.94 """78 unmodified linesmodified:httpcore/connections.py+79 added-48 removed
1 import asyncio2-import ssl2 import typing3 4 import h115 7-from .config import TimeoutConfig8-from .datastructures import Request, Response6+from .config import DEFAULT_SSL_CONFIG, DEFAULT_TIMEOUT_CONFIG, SSLConfig, TimeoutConfig7+from .datastructures import Client, Origin, Request, Response8 from .exceptions import ConnectTimeout, ReadTimeout9 10 H11Event = typing.Union[11 h11.Request,4 unmodified lines16 h11.ConnectionClosed,17 ]18 19 21-class Connection: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)20+class Connection(Client):21+ def __init__(22+ self,23+ origin: typing.Union[str, Origin],24+ ssl: SSLConfig = DEFAULT_SSL_CONFIG,25+ timeout: TimeoutConfig = DEFAULT_TIMEOUT_CONFIG,26+ on_release: typing.Callable = None,27+ ):28+ self.origin = Origin(origin) if isinstance(origin, str) else origin29+ self.ssl = ssl30 self.timeout = timeout31 self.on_release = on_release32+ self._reader = None33+ self._writer = None34+ self._h11_state = h11.Connection(our_role=h11.CLIENT)35 36 @property37 def is_closed(self) -> bool:31- return self.state.our_state in (h11.CLOSED, h11.ERROR)38+ return self._h11_state.our_state in (h11.CLOSED, h11.ERROR)39 33- async def open(34- 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),39- self.timeout.connect_timeout,40- )41- except asyncio.TimeoutError:42- raise ConnectTimeout()40+ async def send(41+ self,42+ request: Request,43+ *,44+ ssl: typing.Optional[SSLConfig] = None,45+ timeout: typing.Optional[TimeoutConfig] = None,46+ ) -> Response:47+ assert request.url.origin == self.origin48 44- async def send(self, request: Request) -> Response:49+ if ssl is None:50+ ssl = self.ssl51+ if timeout is None:52+ timeout = self.timeout53+54+ # Make the connection55+ if self._reader is None:56+ await self._connect(ssl, timeout)57+58+ # Start sending the request.59 method = request.method.encode()60 target = request.url.target61 headers = request.headers48-49- # Start sending the request.62 event = h11.Request(method=method, target=target, headers=headers)63 await self._send_event(event)64 65 # Send the request body.9 unmodified lines75 event = h11.EndOfMessage()76 await self._send_event(event)77 78 # Start getting the response.67- event = await self._receive_event()79+ event = await self._receive_event(timeout)80 if isinstance(event, h11.InformationalResponse):69- event = await self._receive_event()81+ event = await self._receive_event(timeout)82 assert isinstance(event, h11.Response)71- reason = event.reason.decode('latin1')83+ reason = event.reason.decode("latin1")84 status_code = event.status_code85 headers = event.headers74- body = self._body_iter()86+ body = self._body_iter(timeout)87 return Response(76- status_code=status_code, reason=reason, headers=headers, body=body, on_close=self._release88+ status_code=status_code,89+ reason=reason,90+ headers=headers,91+ body=body,92+ on_close=self._release,93 )94 95+ async def _connect(self, ssl: SSLConfig, timeout: TimeoutConfig) -> None:96+ ssl_context = await ssl.load_ssl_context() if self.origin.is_secure else None97+98+ try:99+ self._reader, self._writer = await asyncio.wait_for( # type: ignore100+ asyncio.open_connection(101+ self.origin.hostname, self.origin.port, ssl=ssl_context102+ ),103+ timeout.connect_timeout,104+ )105+ except asyncio.TimeoutError:106+ raise ConnectTimeout()107+79- async def _body_iter(self) -> typing.AsyncIterator[bytes]:80- event = await self._receive_event()108+ async def _body_iter(self, timeout: TimeoutConfig) -> typing.AsyncIterator[bytes]:109+ event = await self._receive_event(timeout)110 while isinstance(event, h11.Data):111 yield event.data83- event = await self._receive_event()112+ event = await self._receive_event(timeout)113 assert isinstance(event, h11.EndOfMessage)114 115 async def _send_event(self, event: H11Event) -> None:87- assert self.writer is not None116+ assert self._writer is not None117 89- data = self.state.send(event)90- self.writer.write(data)118+ data = self._h11_state.send(event)119+ self._writer.write(data)120 92- async def _receive_event(self) -> H11Event:93- assert self.reader is not None121+ async def _receive_event(self, timeout: TimeoutConfig) -> H11Event:122+ assert self._reader is not None123 95- event = self.state.next_event()124+ event = self._h11_state.next_event()125 126 while event is h11.NEED_DATA:127 try:128 data = await asyncio.wait_for(100- self.reader.read(2048), self.timeout.read_timeout129+ self._reader.read(2048), timeout.read_timeout130 )131 except asyncio.TimeoutError:132 raise ReadTimeout()104- self.state.receive_data(data)105- event = self.state.next_event()133+ self._h11_state.receive_data(data)134+ event = self._h11_state.next_event()135 136 return event137 138 async def _release(self) -> None:110- assert self.writer is not None139+ assert self._writer is not None140 112- if self.state.our_state is h11.DONE and self.state.their_state is h11.DONE:113- self.state.start_next_cycle()141+ if (142+ self._h11_state.our_state is h11.DONE143+ and self._h11_state.their_state is h11.DONE144+ ):145+ self._h11_state.start_next_cycle()146 else:115- self.close()147+ await self.close()148 149 if self.on_release is not None:150 await self.on_release(self)151 120- def close(self) -> None:121- assert self.writer is not None122-152+ async def close(self) -> None:153 event = h11.ConnectionClosed()154 try:155 # If we're in h11.MUST_CLOSE then we'll end up in h11.CLOSED.126- self.state.send(event)156+ self._h11_state.send(event)157 except h11.ProtocolError:158 # If we're in some other state then it's a premature close,159 # and we'll end up in h11.ERROR.160 pass161 162+ if self._writer is not None:132- self.writer.close()163+ self._writer.close()modified:httpcore/datastructures.py+75 added
1 import http2 import typing3+from types import TracebackType4 from urllib.parse import urlsplit5 6+from .config import SSLConfig, TimeoutConfig7 from .decoders import (8 ACCEPT_ENCODING,9 SUPPORTED_DECODERS,10 Decoder,51 unmodified lines62 @property63 def is_secure(self) -> bool:64 return self.components.scheme == "https"65 66+ @property67+ def origin(self) -> "Origin":68+ return Origin(self)69 70+71+class Origin:72+ def __init__(self, url: typing.Union[str, URL]) -> None:73+ if isinstance(url, str):74+ url = URL(url)75+ self.scheme = url.scheme76+ self.hostname = url.hostname77+ self.port = url.port78+79+ @property80+ def is_secure(self) -> bool:81+ return self.scheme == "https"82+83+ def __eq__(self, other: typing.Any) -> bool:84+ return (85+ isinstance(other, self.__class__)86+ and self.scheme == other.scheme87+ and self.hostname == other.hostname88+ and self.port == other.port89+ )90+91+ def __hash__(self) -> int:92+ return hash((self.scheme, self.hostname, self.port))93+94+95 class Request:96 def __init__(97 self,98 method: str,137 unmodified lines236 if not self.is_closed:237 self.is_closed = True238 if self.on_close is not None:239 await self.on_close()240+241+242+class Client:243+ async def request(244+ self,245+ method: str,246+ url: typing.Union[str, URL],247+ *,248+ headers: typing.Sequence[typing.Tuple[bytes, bytes]] = (),249+ body: typing.Union[bytes, typing.AsyncIterator[bytes]] = b"",250+ ssl: typing.Optional[SSLConfig] = None,251+ timeout: typing.Optional[TimeoutConfig] = None,252+ stream: bool = False,253+ ) -> Response:254+ request = Request(method, url, headers=headers, body=body)255+ response = await self.send(request, ssl=ssl, timeout=timeout)256+ if not stream:257+ try:258+ await response.read()259+ finally:260+ await response.close()261+ return response262+263+ async def send(264+ self,265+ request: Request,266+ *,267+ ssl: typing.Optional[SSLConfig] = None,268+ timeout: typing.Optional[TimeoutConfig] = None,269+ ) -> Response:270+ raise NotImplementedError() # pragma: nocover271+272+ async def close(self) -> None:273+ raise NotImplementedError() # pragma: nocover274+275+ async def __aenter__(self) -> "Client":276+ return self277+278+ async def __aexit__(279+ self,280+ exc_type: typing.Type[BaseException] = None,281+ exc_value: BaseException = None,282+ traceback: TracebackType = None,283+ ) -> None:284+ await self.close()modified:httpcore/pool.py+40 added-128 removed
1 import asyncio2-import functools3-import os4-import ssl2 import typing6-from types import TracebackType3 4 from .config import (5 DEFAULT_CA_BUNDLE_PATH,6 DEFAULT_POOL_LIMITS,3 unmodified lines10 SSLConfig,11 TimeoutConfig,12 )13 from .connections import Connection18-from .datastructures import URL, Request, Response14+from .datastructures import Client, Origin, Request, Response15 from .exceptions import PoolTimeout16 21-ConnectionKey = typing.Tuple[str, str, int, SSLConfig, TimeoutConfig]17 23-24-class ConnectionSemaphore:25- def __init__(self, max_connections: int = None):26- if max_connections is not None:27- self.semaphore = asyncio.BoundedSemaphore(value=max_connections)28-29- async def acquire(self) -> None:30- if hasattr(self, "semaphore"):31- await self.semaphore.acquire()32-33- def release(self) -> None:34- if hasattr(self, "semaphore"):35- self.semaphore.release()36-37-38-class ConnectionPool:18+class ConnectionPool(Client):19 def __init__(20 self,21 *,22 ssl: SSLConfig = DEFAULT_SSL_CONFIG,23 timeout: TimeoutConfig = DEFAULT_TIMEOUT_CONFIG,24 limits: PoolLimits = DEFAULT_POOL_LIMITS,25 ):46- self.ssl_config = ssl26+ self.ssl = ssl27 self.timeout = timeout28 self.limits = limits29 self.is_closed = False30 self.num_active_connections = 031 self.num_keepalive_connections = 032 self._keepalive_connections = (33 {}54- ) # type: typing.Dict[ConnectionKey, typing.List[Connection]]34+ ) # type: typing.Dict[Origin, typing.List[Connection]]35 self._max_connections = ConnectionSemaphore(36 max_connections=self.limits.hard_limit37 )38 59- async def request(39+ async def send(40 self,61- method: str,62- url: str,41+ request: Request,42 *,64- headers: typing.Sequence[typing.Tuple[bytes, bytes]] = (),65- body: typing.Union[bytes, typing.AsyncIterator[bytes]] = b"",66- stream: bool = False,43 ssl: typing.Optional[SSLConfig] = None,44 timeout: typing.Optional[TimeoutConfig] = None,45 ) -> Response:70- if ssl is None:71- ssl = self.ssl_config72- if timeout is None:73- timeout = self.timeout74-75- parsed_url = URL(url)76- request = Request(method, parsed_url, headers=headers, body=body)77- connection = await self.acquire_connection(parsed_url, ssl=ssl, timeout=timeout)78- response = await connection.send(request)46+ connection = await self.acquire_connection(request.url.origin, timeout=timeout)47+ response = await connection.send(request, ssl=ssl, timeout=timeout)79- if not stream:80- try:81- await response.read()82- finally:83- await response.close()48 return response49 50 @property51 def num_connections(self) -> int:52 return self.num_active_connections + self.num_keepalive_connections53 54 async def acquire_connection(91- self, url: URL, ssl: SSLConfig, timeout: TimeoutConfig55+ self, origin: Origin, timeout: typing.Optional[TimeoutConfig] = None56 ) -> Connection:93- key = (url.scheme, url.hostname, url.port, ssl, timeout)57 try:95- connection = self._keepalive_connections[key].pop()96- if not self._keepalive_connections[key]:97- del self._keepalive_connections[key]58+ connection = self._keepalive_connections[origin].pop()59+ if not self._keepalive_connections[origin]:60+ del self._keepalive_connections[origin]61 self.num_keepalive_connections -= 162 self.num_active_connections += 163 64 except (KeyError, IndexError):102- ssl_context = await self.get_ssl_context(url, ssl)65+ if timeout is None:66+ pool_timeout = self.timeout.pool_timeout67+ else:68+ pool_timeout = timeout.pool_timeout69+70 try:104- await asyncio.wait_for(105- self._max_connections.acquire(), timeout.pool_timeout106- )71+ await asyncio.wait_for(self._max_connections.acquire(), pool_timeout)72 except asyncio.TimeoutError:73 raise PoolTimeout()109- release = functools.partial(self.release_connection, key=key)110- connection = Connection(timeout=timeout, on_release=release)74+ connection = Connection(75+ origin,76+ ssl=self.ssl,77+ timeout=self.timeout,78+ on_release=self.release_connection,79+ )80 self.num_active_connections += 1112- await connection.open(url.hostname, url.port, ssl=ssl_context)81 82 return connection83 116- async def release_connection(117- self, connection: Connection, key: ConnectionKey118- ) -> None:84+ async def release_connection(self, connection: Connection) -> None:85 if connection.is_closed:86 self._max_connections.release()87 self.num_active_connections -= 188 elif (1 unmodified line90 and self.num_connections > self.limits.soft_limit91 ):92 self._max_connections.release()93 self.num_active_connections -= 1128- connection.close()94+ await connection.close()95 else:96 self.num_active_connections -= 197 self.num_keepalive_connections += 198 try:133- self._keepalive_connections[key].append(connection)99+ self._keepalive_connections[connection.origin].append(connection)100 except KeyError:135- self._keepalive_connections[key] = [connection]101+ self._keepalive_connections[connection.origin] = [connection]102 137- async def get_ssl_context(138- self, url: URL, config: SSLConfig139- ) -> typing.Optional[ssl.SSLContext]:140- if not url.is_secure:141- return None142-143- if not hasattr(self, "ssl_context"):144- if not config.verify:145- self.ssl_context = self.get_ssl_context_no_verify()146- else:147- # Run the SSL loading in a threadpool, since it makes disk accesses.148- loop = asyncio.get_event_loop()149- self.ssl_context = await loop.run_in_executor(150- None, self.get_ssl_context_verify151- )152-153- return self.ssl_context154-155- def get_ssl_context_no_verify(self) -> ssl.SSLContext:156- """157- Return an SSL context for unverified connections.158- """159- context = ssl.SSLContext(ssl.PROTOCOL_SSLv23)160- context.options |= ssl.OP_NO_SSLv2161- context.options |= ssl.OP_NO_SSLv3162- context.options |= ssl.OP_NO_COMPRESSION163- context.set_default_verify_paths()164- return context165-166- def get_ssl_context_verify(self, config: SSLConfig) -> ssl.SSLContext:167- """168- Return an SSL context for verified connections.169- """170- if isinstance(config.verify, bool):171- ca_bundle_path = DEFAULT_CA_BUNDLE_PATH172- elif os.path.exists(config.verify):173- ca_bundle_path = config.verify174- else:175- raise IOError(176- "Could not find a suitable TLS CA certificate bundle, "177- "invalid path: {}".format(config.verify)178- )179-180- context = ssl.create_default_context()181- if os.path.isfile(ca_bundle_path):182- context.load_verify_locations(cafile=ca_bundle_path)183- elif os.path.isdir(ca_bundle_path):184- context.load_verify_locations(capath=ca_bundle_path)185-186- if config.cert is not None:187- if isinstance(config.cert, str):188- context.load_cert_chain(certfile=config.cert)189- else:190- context.load_cert_chain(certfile=config.cert[0], keyfile=config.cert[1])191-192- return context193-103 async def close(self) -> None:104 self.is_closed = True105 197- async def __aenter__(self) -> "ConnectionPool":198- return self106 200- async def __aexit__(201- self,202- exc_type: typing.Type[BaseException] = None,203- exc_value: BaseException = None,204- traceback: TracebackType = None,205- ) -> None:206- await self.close()107+class ConnectionSemaphore:108+ def __init__(self, max_connections: int = None):109+ if max_connections is not None:110+ self.semaphore = asyncio.BoundedSemaphore(value=max_connections)111+112+ async def acquire(self) -> None:113+ if hasattr(self, "semaphore"):114+ await self.semaphore.acquire()115+116+ def release(self) -> None:117+ if hasattr(self, "semaphore"):118+ self.semaphore.release()added:httpcore/sync.py
added:tests/test_connections.py+20 added
1+import pytest2+3+import httpcore4+5+6+@pytest.mark.asyncio7+async def test_get(server):8+ http = httpcore.Connection(origin="http://127.0.0.1:8000/")9+ response = await http.request("GET", "http://127.0.0.1:8000/")10+ assert response.status_code == 20011+ assert response.body == b"Hello, world!"12+13+14+@pytest.mark.asyncio15+async def test_post(server):16+ http = httpcore.Connection(origin="http://127.0.0.1:8000/")17+ response = await http.request(18+ "POST", "http://127.0.0.1:8000/", body=b"Hello, world!"19+ )20+ assert response.status_code == 200modified:tests/test_responses.py+10 added-57 removed
1 unmodified line2 3 import httpcore4 5 6-class MockHTTP(httpcore.ConnectionPool):7- async def request(8- self, method, url, *, headers=(), body=b"", stream=False9- ) -> httpcore.Response:10- if stream:6+async def streaming_body():7+ yield b"Hello, "8+ yield b"world!"9 12- async def streaming_body():13- yield b"Hello, "14- yield b"world!"10 16- return httpcore.Response(200, body=streaming_body())17- return httpcore.Response(200, body=b"Hello, world!")18-19-20-http = MockHTTP()21-22-23-@pytest.mark.asyncio24-async def test_request():25- response = await http.request("GET", "http://example.com")11+def test_response():12+ response = httpcore.Response(200, body=b"Hello, world!")13 assert response.status_code == 20014 assert response.reason == "OK"15 assert response.body == b"Hello, world!"16 assert response.is_closed17 18 19 @pytest.mark.asyncio20 async def test_read_response():34- response = await http.request("GET", "http://example.com")21+ response = httpcore.Response(200, body=b"Hello, world!")22 23 assert response.status_code == 20024 assert response.body == b"Hello, world!"25 assert response.is_closed5 unmodified lines31 assert response.is_closed32 33 34 @pytest.mark.asyncio48-async def test_stream_response():49- response = await http.request("GET", "http://example.com")35+async def test_streaming_response():36+ response = httpcore.Response(200, body=streaming_body())37 38 assert response.status_code == 20052- assert response.body == b"Hello, world!"53- assert response.is_closed54-55- body = b""56- async for part in response.stream():57- body += part58-59- assert body == b"Hello, world!"60- assert response.body == b"Hello, world!"61- assert response.is_closed62-63-64-@pytest.mark.asyncio65-async def test_read_streaming_response():66- response = await http.request("GET", "http://example.com", stream=True)67-68- assert response.status_code == 20039 assert not hasattr(response, "body")40 assert not response.is_closed41 42 body = await response.read()3 unmodified lines46 assert response.is_closed47 48 49 @pytest.mark.asyncio80-async def test_stream_streaming_response():81- response = await http.request("GET", "http://example.com", stream=True)82-83- assert response.status_code == 20084- assert not hasattr(response, "body")85- assert not response.is_closed86-87- body = b""88- async for part in response.stream():89- body += part90-91- assert body == b"Hello, world!"92- assert not hasattr(response, "body")93- assert response.is_closed94-95-96-@pytest.mark.asyncio50 async def test_cannot_read_after_stream_consumed():98- response = await http.request("GET", "http://example.com", stream=True)51+ response = httpcore.Response(200, body=streaming_body())52 53 body = b""54 async for part in response.stream():55 body += part3 unmodified lines59 60 61 @pytest.mark.asyncio62 async def test_cannot_read_after_response_closed():110- response = await http.request("GET", "http://example.com", stream=True)63+ response = httpcore.Response(200, body=streaming_body())64 65 await response.close()66 67 with pytest.raises(httpcore.ResponseClosed):7 unmodified lines