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
Provenance
- Commit
53f3dc4- Tree
29eb0e8- Author
Tom Christie <tom@tomchristie.com>- Committer
Tom Christie <tom@tomchristie.com>- Parent
91a2a1b
10 files changed+322 added−70 removed
modified:httpcore/__init__.py+2 added
1 from .config import PoolLimits, SSLConfig, TimeoutConfig2+from .connection import HTTPConnection3 from .connectionpool import ConnectionPool4 from .datastructures import URL, Origin, Request, Response5 from .exceptions import (6 ConnectTimeout,3 unmodified lines10 ResponseClosed,11 StreamConsumed,12 Timeout,13 )14+from .http2 import HTTP2Connection15 from .http11 import HTTP11Connection16 from .sync import SyncClient, SyncConnectionPool17 18 __version__ = "0.2.1"modified:httpcore/config.py+17 added-1 removed
71 unmodified lines72 "Could not find a suitable TLS CA certificate bundle, "73 "invalid path: {}".format(self.verify)74 )75 76- context = ssl.create_default_context()76+ context = ssl.create_default_context(purpose=ssl.Purpose.CLIENT_AUTH)77+78+ context.options |= ssl.OP_NO_SSLv279+ context.options |= ssl.OP_NO_SSLv380+ context.options |= ssl.OP_NO_COMPRESSION81+82+ # 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")87+88+ 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"])92+93 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 linesadded:httpcore/connection.py+106 added
1+import asyncio2+import typing3+4+import h2.connection5+import h116+7+from .config import DEFAULT_SSL_CONFIG, DEFAULT_TIMEOUT_CONFIG, SSLConfig, TimeoutConfig8+from .datastructures import Client, Origin, Request, Response9+from .exceptions import ConnectTimeout10+from .http2 import HTTP2Connection11+from .http11 import HTTP11Connection12+13+14+class 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]28+29+ 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.timeout41+42+ 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+ )59+60+ 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)65+66+ return response67+68+ 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()74+75+ @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_closed82+83+ 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 None89+90+ 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()97+98+ 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()105+106+ return (reader, writer, protocol)modified:httpcore/connectionpool.py+5 added-5 removed
8 unmodified lines9 PoolLimits,10 SSLConfig,11 TimeoutConfig,12 )13+from .connection import HTTPConnection14 from .datastructures import Client, Origin, Request, Response15 from .exceptions import PoolTimeout15-from .http11 import HTTP11Connection16 17 18 class ConnectionPool(Client):19 def __init__(10 unmodified lines30 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 lines52 return self.num_active_connections + self.num_keepalive_connections53 54 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 lines70 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 line80 self.num_active_connections += 181 82 return connection83 84- 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 linesmodified:httpcore/datastructures.py+8 added-5 removed
50 unmodified lines51 return {"https": 443, "http": 80}[self.scheme]52 return port53 54 @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 + "?" + query77 unmodified lines137 138 return headers139 140 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.body146 143- async for part in self.body_aiter:144- yield part147 146-148 class 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 lines163 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 = False112 unmodified linesmodified:httpcore/http11.py+27 added-55 removed
18 unmodified lines19 20 class 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)35 36 @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)39 40 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.origin48-49- if ssl is None:50- ssl = self.ssl47 if timeout is None:48 timeout = self.timeout49 54- # Make the connection55- if self._reader is None:56- await self._connect(ssl, timeout)57-50 # 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)56 57 # 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)61 62 # Finalize sending the request.63 event = h11.EndOfMessage()2 unmodified lines66 # Start getting the response.67 event = await self._receive_event(timeout)68 if isinstance(event, h11.InformationalResponse):69 event = await self._receive_event(timeout)70+71 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)76+77 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 )85 95- 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 None99-100- 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()107-86 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)92 93 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)96 118- data = self._h11_state.send(event)119- self._writer.write(data)120-97 async def _receive_event(self, timeout: TimeoutConfig) -> H11Event:122- assert self._reader is not None98+ event = self.h11_state.next_event()99 124- event = self._h11_state.next_event()125-100 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()109 110 return event111 112 async def _release(self) -> None:139- assert self._writer is not None140-113 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()120 121 if self.on_release is not None:2 unmodified lines124 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 pass133 162- 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
1+import asyncio2+import typing3+4+import h2.connection5+import h2.events6+7+from .config import DEFAULT_SSL_CONFIG, DEFAULT_TIMEOUT_CONFIG, SSLConfig, TimeoutConfig8+from .datastructures import Client, Origin, Request, Response9+from .exceptions import ConnectTimeout, ReadTimeout10+11+12+class 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]28+29+ @property30+ def is_closed(self) -> bool:31+ return False32+33+ 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.timeout42+43+ # Start sending the request.44+ await self._initiate_connection()45+ await self._send_headers(request)46+47+ # Send the request body.48+ if request.body:49+ await self._send_data(request.body)50+51+ # Finalize sending the request.52+ await self._end_stream()53+54+ # Start getting the response.55+ while True:56+ event = await self._receive_event(timeout)57+ if isinstance(event, h2.events.ResponseReceived):58+ break59+60+ 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))67+68+ 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+ )76+77+ 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)81+82+ 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)92+93+ 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)97+98+ 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)102+103+ 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+ break110+111+ 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()119+120+ events = self.h2_state.receive_data(data)121+ self.events.extend(events)122+123+ data_to_send = self.h2_state.data_to_send()124+ if data_to_send:125+ self.writer.write(data_to_send)126+127+ return self.events.pop(0)128+129+ 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()137+138+ if self.on_release is not None:139+ await self.on_release(self)140+141+ 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+ # pass150+151+ if self.writer is not None:152+ self.writer.close()modified:tests/test_connections.py+2 added-2 removed
3 unmodified lines4 5 6 @pytest.mark.asyncio7 async 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!"12 13 14 @pytest.mark.asyncio15 async 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 == 200modified:tests/test_requests.py+2 added-2 removed
71 unmodified lines72 def 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 == "/"77 78 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"82 83 84 def test_invalid_urls():85 with pytest.raises(ValueError):7 unmodified linesmodified:requirements.txt+1 added
1 certifi2 h113+h24 5 # Optional6 brotlipy7 10 unmodified lines