Skip to content
Myr

First pass at HTTP/2 support

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 91a2a1b · Browse files · 10 files+322 added−70 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

10 files+322 added−70 removed

  • tests:+4 added−4 removed
  • other:+318 added−66 removed

10 files+322 added−70 removed

modified:httpcore/__init__.py+2 added
1from .config import PoolLimits, SSLConfig, TimeoutConfig2from .connection import HTTPConnection3from .connectionpool import ConnectionPool4from .datastructures import URL, Origin, Request, Response5from .exceptions import (6 ConnectTimeout,
3 unmodified lines
10 ResponseClosed,11 StreamConsumed,12 Timeout,13)14from .http2 import HTTP2Connection15from .http11 import HTTP11Connection16from .sync import SyncClient, SyncConnectionPool1718__version__ = "0.2.1"
modified:httpcore/config.py+17 added-1 removed
71 unmodified lines
72 "Could not find a suitable TLS CA certificate bundle, "73 "invalid path: {}".format(self.verify)74 )7576 context = ssl.create_default_context()76 context = ssl.create_default_context(purpose=ssl.Purpose.CLIENT_AUTH)7778 context.options |= ssl.OP_NO_SSLv279 context.options |= ssl.OP_NO_SSLv380 context.options |= ssl.OP_NO_COMPRESSION8182 # RFC 7540 Section 9.2.2: "deployments of HTTP/2 that use TLS 1.2 MUST83 # support TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256". In practice, the84 # blacklist defined in this section allows only the AES GCM and ChaCha2085 # cipher suites with ephemeral key negotiation.86 context.set_ciphers("ECDHE+AESGCM:ECDHE+CHACHA20:DHE+AESGCM:DHE+CHACHA20")8788 if ssl.HAS_ALPN:89 context.set_alpn_protocols(["h2", "http/1.1"])90 if ssl.HAS_NPN:91 context.set_npn_protocols(["h2", "http/1.1"])9293 if os.path.isfile(ca_bundle_path):94 context.load_verify_locations(cafile=ca_bundle_path)95 elif os.path.isdir(ca_bundle_path):96 context.load_verify_locations(capath=ca_bundle_path)
92 unmodified lines
added:httpcore/connection.py+106 added
1import asyncio2import typing34import h2.connection5import h1167from .config import DEFAULT_SSL_CONFIG, DEFAULT_TIMEOUT_CONFIG, SSLConfig, TimeoutConfig8from .datastructures import Client, Origin, Request, Response9from .exceptions import ConnectTimeout10from .http2 import HTTP2Connection11from .http11 import HTTP11Connection121314class HTTPConnection(Client):15 def __init__(16 self,17 origin: typing.Union[str, Origin],18 ssl: SSLConfig = DEFAULT_SSL_CONFIG,19 timeout: TimeoutConfig = DEFAULT_TIMEOUT_CONFIG,20 on_release: typing.Callable = None,21 ):22 self.origin = Origin(origin) if isinstance(origin, str) else origin23 self.ssl = ssl24 self.timeout = timeout25 self.on_release = on_release26 self.h11_connection = None # type: typing.Optional[HTTP11Connection]27 self.h2_connection = None # type: typing.Optional[HTTP2Connection]2829 async def send(30 self,31 request: Request,32 *,33 ssl: typing.Optional[SSLConfig] = None,34 timeout: typing.Optional[TimeoutConfig] = None,35 ) -> Response:36 if self.h11_connection is None and self.h2_connection is None:37 if ssl is None:38 ssl = self.ssl39 if timeout is None:40 timeout = self.timeout4142 reader, writer, protocol = await self.connect(ssl, timeout)43 if protocol == "h2":44 self.h2_connection = HTTP2Connection(45 reader,46 writer,47 origin=self.origin,48 timeout=self.timeout,49 on_release=self.on_release,50 )51 else:52 self.h11_connection = HTTP11Connection(53 reader,54 writer,55 origin=self.origin,56 timeout=self.timeout,57 on_release=self.on_release,58 )5960 if self.h2_connection is not None:61 response = await self.h2_connection.send(request, ssl=ssl, timeout=timeout)62 else:63 assert self.h11_connection is not None64 response = await self.h11_connection.send(request, ssl=ssl, timeout=timeout)6566 return response6768 async def close(self) -> None:69 if self.h2_connection is not None:70 await self.h2_connection.close()71 else:72 assert self.h11_connection is not None73 await self.h11_connection.close()7475 @property76 def is_closed(self) -> bool:77 if self.h2_connection is not None:78 return self.h2_connection.is_closed79 else:80 assert self.h11_connection is not None81 return self.h11_connection.is_closed8283 async def connect(84 self, ssl: SSLConfig, timeout: TimeoutConfig85 ) -> typing.Tuple[asyncio.StreamReader, asyncio.StreamWriter, str]:86 hostname = self.origin.hostname87 port = self.origin.port88 ssl_context = await ssl.load_ssl_context() if self.origin.is_ssl else None8990 try:91 reader, writer = await asyncio.wait_for( # type: ignore92 asyncio.open_connection(hostname, port, ssl=ssl_context),93 timeout.connect_timeout,94 )95 except asyncio.TimeoutError:96 raise ConnectTimeout()9798 ssl_object = writer.get_extra_info("ssl_object")99 if ssl_object is None:100 protocol = "http/1.1"101 else:102 protocol = ssl_object.selected_alpn_protocol()103 if protocol is None:104 protocol = ssl_object.selected_npn_protocol()105106 return (reader, writer, protocol)
modified:httpcore/connectionpool.py+5 added-5 removed
8 unmodified lines
9 PoolLimits,10 SSLConfig,11 TimeoutConfig,12)13from .connection import HTTPConnection14from .datastructures import Client, Origin, Request, Response15from .exceptions import PoolTimeout15from .http11 import HTTP11Connection161718class ConnectionPool(Client):19 def __init__(
10 unmodified lines
30 self.num_active_connections = 031 self.num_keepalive_connections = 032 self._keepalive_connections = (33 {}34 ) # type: typing.Dict[Origin, typing.List[HTTP11Connection]]34 ) # type: typing.Dict[Origin, typing.List[HTTPConnection]]35 self._max_connections = ConnectionSemaphore(36 max_connections=self.limits.hard_limit37 )38
13 unmodified lines
52 return self.num_active_connections + self.num_keepalive_connections5354 async def acquire_connection(55 self, origin: Origin, timeout: typing.Optional[TimeoutConfig] = None56 ) -> HTTP11Connection:56 ) -> HTTPConnection:57 try:58 connection = self._keepalive_connections[origin].pop()59 if not self._keepalive_connections[origin]:60 del self._keepalive_connections[origin]
9 unmodified lines
70 try:71 await asyncio.wait_for(self._max_connections.acquire(), pool_timeout)72 except asyncio.TimeoutError:73 raise PoolTimeout()74 connection = HTTP11Connection(74 connection = HTTPConnection(75 origin,76 ssl=self.ssl,77 timeout=self.timeout,78 on_release=self.release_connection,
1 unmodified line
80 self.num_active_connections += 18182 return connection8384 async def release_connection(self, connection: HTTP11Connection) -> None:84 async def release_connection(self, connection: HTTPConnection) -> None:85 if connection.is_closed:86 self._max_connections.release()87 self.num_active_connections -= 188 elif (
44 unmodified lines
modified:httpcore/datastructures.py+8 added-5 removed
50 unmodified lines
51 return {"https": 443, "http": 80}[self.scheme]52 return port5354 @property55 def target(self) -> str:55 def full_path(self) -> str:56 path = self.path or "/"57 query = self.query58 if query:59 return path + "?" + query
77 unmodified lines
137138 return headers139140 async def stream(self) -> typing.AsyncIterator[bytes]:141 assert self.is_streaming141 if self.is_streaming:142 async for part in self.body_aiter:143 yield part144 elif self.body:145 yield self.body146143 async for part in self.body_aiter:144 yield part147146148class Response:149 def __init__(150 self,151 status_code: int,152 *,153 reason: typing.Optional[str] = None,154 protocol: typing.Optional[str] = None,155 headers: typing.Sequence[typing.Tuple[bytes, bytes]] = (),156 body: typing.Union[bytes, typing.AsyncIterator[bytes]] = b"",157 on_close: typing.Callable = None,158 ):
4 unmodified lines
163 except ValueError as exc:164 self.reason = ""165 else:166 self.reason = reason167 self.protocol = protocol168 self.headers = list(headers)169 self.on_close = on_close170 self.is_closed = False171 self.is_streamed = False
112 unmodified lines
modified:httpcore/http11.py+27 added-55 removed
18 unmodified lines
1920class HTTP11Connection(Client):21 def __init__(22 self,23 origin: typing.Union[str, Origin],24 ssl: SSLConfig = DEFAULT_SSL_CONFIG,23 reader: asyncio.StreamReader,24 writer: asyncio.StreamWriter,25 origin: Origin,26 timeout: TimeoutConfig = DEFAULT_TIMEOUT_CONFIG,27 on_release: typing.Callable = None,28 ):28 self.origin = Origin(origin) if isinstance(origin, str) else origin29 self.ssl = ssl29 self.origin = origin30 self.reader = reader31 self.writer = writer32 self.timeout = timeout33 self.on_release = on_release32 self._reader = None33 self._writer = None34 self._h11_state = h11.Connection(our_role=h11.CLIENT)34 self.h11_state = h11.Connection(our_role=h11.CLIENT)3536 @property37 def is_closed(self) -> bool:38 return self._h11_state.our_state in (h11.CLOSED, h11.ERROR)38 return self.h11_state.our_state in (h11.CLOSED, h11.ERROR)3940 async def send(41 self,42 request: Request,43 *,44 ssl: typing.Optional[SSLConfig] = None,45 timeout: typing.Optional[TimeoutConfig] = None,45 timeout: typing.Optional[TimeoutConfig] = None46 ) -> Response:47 assert request.url.origin == self.origin4849 if ssl is None:50 ssl = self.ssl47 if timeout is None:48 timeout = self.timeout4954 # Make the connection55 if self._reader is None:56 await self._connect(ssl, timeout)5750 #  Start sending the request.51 method = request.method.encode()60 target = request.url.target52 target = request.url.full_path53 headers = request.headers54 event = h11.Request(method=method, target=target, headers=headers)55 await self._send_event(event)5657 # Send the request body.66 if request.is_streaming:67 async for data in request.stream():68 event = h11.Data(data=data)58 async for data in request.stream():59 event = h11.Data(data=data)69 await self._send_event(event)70 elif request.body:71 event = h11.Data(data=request.body)60 await self._send_event(event)6162 # Finalize sending the request.63 event = h11.EndOfMessage()
2 unmodified lines
66 # Start getting the response.67 event = await self._receive_event(timeout)68 if isinstance(event, h11.InformationalResponse):69 event = await self._receive_event(timeout)7071 assert isinstance(event, h11.Response)72 reason = event.reason.decode("latin1")73 status_code = event.status_code74 headers = event.headers75 body = self._body_iter(timeout)7677 return Response(78 status_code=status_code,79 reason=reason,80 protocol="HTTP/1.1",81 headers=headers,82 body=body,83 on_close=self._release,84 )8595 async def _connect(self, ssl: SSLConfig, timeout: TimeoutConfig) -> None:96 hostname = self.origin.hostname97 port = self.origin.port98 ssl_context = await ssl.load_ssl_context() if self.origin.is_ssl else None99100 try:101 self._reader, self._writer = await asyncio.wait_for( # type: ignore102 asyncio.open_connection(hostname, port, ssl=ssl_context),103 timeout.connect_timeout,104 )105 except asyncio.TimeoutError:106 raise ConnectTimeout()10786 async def _body_iter(self, timeout: TimeoutConfig) -> typing.AsyncIterator[bytes]:87 event = await self._receive_event(timeout)88 while isinstance(event, h11.Data):89 yield event.data90 event = await self._receive_event(timeout)91 assert isinstance(event, h11.EndOfMessage)9293 async def _send_event(self, event: H11Event) -> None:116 assert self._writer is not None94 data = self.h11_state.send(event)95 self.writer.write(data)96118 data = self._h11_state.send(event)119 self._writer.write(data)12097 async def _receive_event(self, timeout: TimeoutConfig) -> H11Event:122 assert self._reader is not None98 event = self.h11_state.next_event()99124 event = self._h11_state.next_event()125100 while event is h11.NEED_DATA:101 try:102 data = await asyncio.wait_for(129 self._reader.read(2048), timeout.read_timeout103 self.reader.read(2048), timeout.read_timeout104 )105 except asyncio.TimeoutError:106 raise ReadTimeout()133 self._h11_state.receive_data(data)134 event = self._h11_state.next_event()107 self.h11_state.receive_data(data)108 event = self.h11_state.next_event()109110 return event111112 async def _release(self) -> None:139 assert self._writer is not None140113 if (142 self._h11_state.our_state is h11.DONE143 and self._h11_state.their_state is h11.DONE114 self.h11_state.our_state is h11.DONE115 and self.h11_state.their_state is h11.DONE116 ):145 self._h11_state.start_next_cycle()117 self.h11_state.start_next_cycle()118 else:119 await self.close()120121 if self.on_release is not None:
2 unmodified lines
124 async def close(self) -> None:125 event = h11.ConnectionClosed()126 try:127 # If we're in h11.MUST_CLOSE then we'll end up in h11.CLOSED.156 self._h11_state.send(event)128 self.h11_state.send(event)129 except h11.ProtocolError:130 # If we're in some other state then it's a premature close,131 # and we'll end up in h11.ERROR.132 pass133162 if self._writer is not None:163 self._writer.close()134 if self.writer is not None:135 self.writer.close()
added:httpcore/http2.py+152 added
1import asyncio2import typing34import h2.connection5import h2.events67from .config import DEFAULT_SSL_CONFIG, DEFAULT_TIMEOUT_CONFIG, SSLConfig, TimeoutConfig8from .datastructures import Client, Origin, Request, Response9from .exceptions import ConnectTimeout, ReadTimeout101112class HTTP2Connection(Client):13 def __init__(14 self,15 reader: asyncio.StreamReader,16 writer: asyncio.StreamWriter,17 origin: Origin,18 timeout: TimeoutConfig = DEFAULT_TIMEOUT_CONFIG,19 on_release: typing.Callable = None,20 ):21 self.origin = origin22 self.reader = reader23 self.writer = writer24 self.timeout = timeout25 self.on_release = on_release26 self.h2_state = h2.connection.H2Connection()27 self.events = [] # type: typing.List[h2.events.Event]2829 @property30 def is_closed(self) -> bool:31 return False3233 async def send(34 self,35 request: Request,36 *,37 ssl: typing.Optional[SSLConfig] = None,38 timeout: typing.Optional[TimeoutConfig] = None39 ) -> Response:40 if timeout is None:41 timeout = self.timeout4243 #  Start sending the request.44 await self._initiate_connection()45 await self._send_headers(request)4647 # Send the request body.48 if request.body:49 await self._send_data(request.body)5051 # Finalize sending the request.52 await self._end_stream()5354 # Start getting the response.55 while True:56 event = await self._receive_event(timeout)57 if isinstance(event, h2.events.ResponseReceived):58 break5960 status_code = 20061 headers = []62 for k, v in event.headers:63 if k == b":status":64 status_code = int(v.decode())65 elif not k.startswith(b":"):66 headers.append((k, v))6768 body = self._body_iter(timeout)69 return Response(70 status_code=status_code,71 protocol="HTTP/2",72 headers=headers,73 body=body,74 on_close=self._release,75 )7677 async def _initiate_connection(self) -> None:78 self.h2_state.initiate_connection()79 data_to_send = self.h2_state.data_to_send()80 self.writer.write(data_to_send)8182 async def _send_headers(self, request: Request) -> None:83 headers = [84 (b":method", request.method.encode()),85 (b":authority", request.url.hostname.encode()),86 (b":scheme", request.url.scheme.encode()),87 (b":path", request.url.full_path.encode()),88 ] + request.headers89 self.h2_state.send_headers(1, headers)90 data_to_send = self.h2_state.data_to_send()91 self.writer.write(data_to_send)9293 async def _send_data(self, data: bytes) -> None:94 self.h2_state.send_data(1, data)95 data_to_send = self.h2_state.data_to_send()96 self.writer.write(data_to_send)9798 async def _end_stream(self) -> None:99 self.h2_state.end_stream(1)100 data_to_send = self.h2_state.data_to_send()101 self.writer.write(data_to_send)102103 async def _body_iter(self, timeout: TimeoutConfig) -> typing.AsyncIterator[bytes]:104 while True:105 event = await self._receive_event(timeout)106 if isinstance(event, h2.events.DataReceived):107 yield event.data108 elif isinstance(event, h2.events.StreamEnded):109 break110111 async def _receive_event(self, timeout: TimeoutConfig) -> h2.events.Event:112 while not self.events:113 try:114 data = await asyncio.wait_for(115 self.reader.read(2048), timeout.read_timeout116 )117 except asyncio.TimeoutError:118 raise ReadTimeout()119120 events = self.h2_state.receive_data(data)121 self.events.extend(events)122123 data_to_send = self.h2_state.data_to_send()124 if data_to_send:125 self.writer.write(data_to_send)126127 return self.events.pop(0)128129 async def _release(self) -> None:130 # if (131 # self.h11_state.our_state is h11.DONE132 # and self.h11_state.their_state is h11.DONE133 # ):134 # self.h11_state.start_next_cycle()135 # else:136 # await self.close()137138 if self.on_release is not None:139 await self.on_release(self)140141 async def close(self) -> None:142 # event = h11.ConnectionClosed()143 # try:144 # # If we're in h11.MUST_CLOSE then we'll end up in h11.CLOSED.145 # self.h11_state.send(event)146 # except h11.ProtocolError:147 # # If we're in some other state then it's a premature close,148 # # and we'll end up in h11.ERROR.149 # pass150151 if self.writer is not None:152 self.writer.close()
modified:tests/test_connections.py+2 added-2 removed
3 unmodified lines
456@pytest.mark.asyncio7async def test_get(server):8 http = httpcore.HTTP11Connection(origin="http://127.0.0.1:8000/")8 http = httpcore.HTTPConnection(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.HTTP11Connection(origin="http://127.0.0.1:8000/")16 http = httpcore.HTTPConnection(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_requests.py+2 added-2 removed
71 unmodified lines
72def test_url():73 request = httpcore.Request("GET", "http://example.org")74 assert request.url.scheme == "http"75 assert request.url.port == 8076 assert request.url.target == "/"76 assert request.url.full_path == "/"7778 request = httpcore.Request("GET", "https://example.org/abc?foo=bar")79 assert request.url.scheme == "https"80 assert request.url.port == 44381 assert request.url.target == "/abc?foo=bar"81 assert request.url.full_path == "/abc?foo=bar"828384def test_invalid_urls():85 with pytest.raises(ValueError):
7 unmodified lines
modified:requirements.txt+1 added
1certifi2h113h245# Optional6brotlipy7
10 unmodified lines