Skip to content
Myr

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

8 files+281 added−234 removed

modified:httpcore/__init__.py+2 added-1 removed
1from .config import PoolLimits, SSLConfig, TimeoutConfig2from .connections import Connection2from .datastructures import URL, Request, Response3from .datastructures import URL, Origin, Request, Response4from .exceptions import (5 BadResponse,6 ConnectTimeout,7 PoolTimeout,
8 unmodified lines
modified:httpcore/config.py+55 added
1import asyncio2import os3import ssl4import typing56import certifi7
26 unmodified lines
34 def __repr__(self) -> str:35 class_name = self.__class__.__name__36 return f"{class_name}(cert={self.cert}, verify={self.verify})"3738 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 )4849 return self.ssl_context5051 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 context6162 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 )7576 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)8182 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])8788 return context899091class TimeoutConfig:92 """93 Timeout values.94 """
78 unmodified lines
modified:httpcore/connections.py+79 added-48 removed
1import asyncio2import ssl2import typing34import h1157from .config import TimeoutConfig8from .datastructures import Request, Response6from .config import DEFAULT_SSL_CONFIG, DEFAULT_TIMEOUT_CONFIG, SSLConfig, TimeoutConfig7from .datastructures import Client, Origin, Request, Response8from .exceptions import ConnectTimeout, ReadTimeout910H11Event = typing.Union[11 h11.Request,
4 unmodified lines
16 h11.ConnectionClosed,17]181921class 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)20class 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)3536 @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)3933 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.origin4844 async def send(self, request: Request) -> Response:49 if ssl is None:50 ssl = self.ssl51 if timeout is None:52 timeout = self.timeout5354 # Make the connection55 if self._reader is None:56 await self._connect(ssl, timeout)5758 #  Start sending the request.59 method = request.method.encode()60 target = request.url.target61 headers = request.headers4849 #  Start sending the request.62 event = h11.Request(method=method, target=target, headers=headers)63 await self._send_event(event)6465 # Send the request body.
9 unmodified lines
75 event = h11.EndOfMessage()76 await self._send_event(event)7778 # 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 )9495 async def _connect(self, ssl: SSLConfig, timeout: TimeoutConfig) -> None:96 ssl_context = await ssl.load_ssl_context() if self.origin.is_secure else None9798 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()10779 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)114115 async def _send_event(self, event: H11Event) -> None:87 assert self.writer is not None116 assert self._writer is not None11789 data = self.state.send(event)90 self.writer.write(data)118 data = self._h11_state.send(event)119 self._writer.write(data)12092 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 None12395 event = self.state.next_event()124 event = self._h11_state.next_event()125126 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()135136 return event137138 async def _release(self) -> None:110 assert self.writer is not None139 assert self._writer is not None140112 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()148149 if self.on_release is not None:150 await self.on_release(self)151120 def close(self) -> None:121 assert self.writer is not None122152 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 pass161162 if self._writer is not None:132 self.writer.close()163 self._writer.close()
modified:httpcore/datastructures.py+75 added
1import http2import typing3from types import TracebackType4from urllib.parse import urlsplit56from .config import SSLConfig, TimeoutConfig7from .decoders import (8 ACCEPT_ENCODING,9 SUPPORTED_DECODERS,10 Decoder,
51 unmodified lines
62 @property63 def is_secure(self) -> bool:64 return self.components.scheme == "https"6566 @property67 def origin(self) -> "Origin":68 return Origin(self)697071class 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.port7879 @property80 def is_secure(self) -> bool:81 return self.scheme == "https"8283 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 )9091 def __hash__(self) -> int:92 return hash((self.scheme, self.hostname, self.port))939495class Request:96 def __init__(97 self,98 method: str,
137 unmodified lines
236 if not self.is_closed:237 self.is_closed = True238 if self.on_close is not None:239 await self.on_close()240241242class 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 response262263 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: nocover271272 async def close(self) -> None:273 raise NotImplementedError() # pragma: nocover274275 async def __aenter__(self) -> "Client":276 return self277278 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
1import asyncio2import functools3import os4import ssl2import typing6from types import TracebackType34from .config import (5 DEFAULT_CA_BUNDLE_PATH,6 DEFAULT_POOL_LIMITS,
3 unmodified lines
10 SSLConfig,11 TimeoutConfig,12)13from .connections import Connection18from .datastructures import URL, Request, Response14from .datastructures import Client, Origin, Request, Response15from .exceptions import PoolTimeout1621ConnectionKey = typing.Tuple[str, str, int, SSLConfig, TimeoutConfig]172324class ConnectionSemaphore:25 def __init__(self, max_connections: int = None):26 if max_connections is not None:27 self.semaphore = asyncio.BoundedSemaphore(value=max_connections)2829 async def acquire(self) -> None:30 if hasattr(self, "semaphore"):31 await self.semaphore.acquire()3233 def release(self) -> None:34 if hasattr(self, "semaphore"):35 self.semaphore.release()363738class ConnectionPool:18class 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 )3859 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.timeout7475 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 response4950 @property51 def num_connections(self) -> int:52 return self.num_active_connections + self.num_keepalive_connections5354 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 += 16364 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_timeout6970 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)8182 return connection83116 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 line
90 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]102137 async def get_ssl_context(138 self, url: URL, config: SSLConfig139 ) -> typing.Optional[ssl.SSLContext]:140 if not url.is_secure:141 return None142143 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 )152153 return self.ssl_context154155 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 context165166 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 )179180 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)185186 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])191192 return context193103 async def close(self) -> None:104 self.is_closed = True105197 async def __aenter__(self) -> "ConnectionPool":198 return self106200 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()107class ConnectionSemaphore:108 def __init__(self, max_connections: int = None):109 if max_connections is not None:110 self.semaphore = asyncio.BoundedSemaphore(value=max_connections)111112 async def acquire(self) -> None:113 if hasattr(self, "semaphore"):114 await self.semaphore.acquire()115116 def release(self) -> None:117 if hasattr(self, "semaphore"):118 self.semaphore.release()
added:httpcore/sync.py
added:tests/test_connections.py+20 added
1import pytest23import httpcore456@pytest.mark.asyncio7async 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!"121314@pytest.mark.asyncio15async 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 == 200
modified:tests/test_responses.py+10 added-57 removed
1 unmodified line
23import httpcore456class MockHTTP(httpcore.ConnectionPool):7 async def request(8 self, method, url, *, headers=(), body=b"", stream=False9 ) -> httpcore.Response:10 if stream:6async def streaming_body():7 yield b"Hello, "8 yield b"world!"912 async def streaming_body():13 yield b"Hello, "14 yield b"world!"1016 return httpcore.Response(200, body=streaming_body())17 return httpcore.Response(200, body=b"Hello, world!")181920http = MockHTTP()212223@pytest.mark.asyncio24async def test_request():25 response = await http.request("GET", "http://example.com")11def 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_closed171819@pytest.mark.asyncio20async def test_read_response():34 response = await http.request("GET", "http://example.com")21 response = httpcore.Response(200, body=b"Hello, world!")2223 assert response.status_code == 20024 assert response.body == b"Hello, world!"25 assert response.is_closed
5 unmodified lines
31 assert response.is_closed323334@pytest.mark.asyncio48async def test_stream_response():49 response = await http.request("GET", "http://example.com")35async def test_streaming_response():36 response = httpcore.Response(200, body=streaming_body())3738 assert response.status_code == 20052 assert response.body == b"Hello, world!"53 assert response.is_closed5455 body = b""56 async for part in response.stream():57 body += part5859 assert body == b"Hello, world!"60 assert response.body == b"Hello, world!"61 assert response.is_closed626364@pytest.mark.asyncio65async def test_read_streaming_response():66 response = await http.request("GET", "http://example.com", stream=True)6768 assert response.status_code == 20039 assert not hasattr(response, "body")40 assert not response.is_closed4142 body = await response.read()
3 unmodified lines
46 assert response.is_closed474849@pytest.mark.asyncio80async def test_stream_streaming_response():81 response = await http.request("GET", "http://example.com", stream=True)8283 assert response.status_code == 20084 assert not hasattr(response, "body")85 assert not response.is_closed8687 body = b""88 async for part in response.stream():89 body += part9091 assert body == b"Hello, world!"92 assert not hasattr(response, "body")93 assert response.is_closed949596@pytest.mark.asyncio50async 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())5253 body = b""54 async for part in response.stream():55 body += part
3 unmodified lines
596061@pytest.mark.asyncio62async 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())6465 await response.close()6667 with pytest.raises(httpcore.ResponseClosed):
7 unmodified lines