streams.py
This file
Path
httpcore/streams.py
133 lines · 3.9 KiB · Python
Last changed by
Merge branch 'master' into wait-for-connection-closeTom Christiebefore adoption20bc1f3
History of this fileTake it
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`.67These 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 typing1516from .config import DEFAULT_TIMEOUT_CONFIG, PoolLimits, TimeoutConfig17from .exceptions import ConnectTimeout, PoolTimeout, ReadTimeout, WriteTimeout18from .interfaces import BasePoolSemaphore, BaseReader, BaseWriter1920OptionalTimeout = typing.Optional[TimeoutConfig]212223class Protocol(enum.Enum):24 HTTP_11 = 125 HTTP_2 = 2262728class Reader(BaseReader):29 def __init__(30 self, stream_reader: asyncio.StreamReader, timeout: TimeoutConfig31 ) -> None:32 self.stream_reader = stream_reader33 self.timeout = timeout3435 async def read(self, n: int, timeout: OptionalTimeout = None) -> bytes:36 if timeout is None:37 timeout = self.timeout3839 try:40 data = await asyncio.wait_for(41 self.stream_reader.read(n), timeout.read_timeout42 )43 except asyncio.TimeoutError:44 raise ReadTimeout()4546 return data474849class Writer(BaseWriter):50 def __init__(self, stream_writer: asyncio.StreamWriter, timeout: TimeoutConfig):51 self.stream_writer = stream_writer52 self.timeout = timeout5354 def write_no_block(self, data: bytes) -> None:55 self.stream_writer.write(data)5657 async def write(self, data: bytes, timeout: OptionalTimeout = None) -> None:58 if not data:59 return6061 if timeout is None:62 timeout = self.timeout6364 self.stream_writer.write(data)65 try:66 data = await asyncio.wait_for( # type: ignore67 self.stream_writer.drain(), timeout.write_timeout68 )69 except asyncio.TimeoutError:70 raise WriteTimeout()7172 async def close(self) -> None:73 self.stream_writer.close()747576class PoolSemaphore(BasePoolSemaphore):77 def __init__(self, limits: PoolLimits):78 self.limits = limits7980 @property81 def semaphore(self) -> typing.Optional[asyncio.BoundedSemaphore]:82 if not hasattr(self, "_semaphore"):83 max_connections = self.limits.hard_limit84 if max_connections is None:85 self._semaphore = None86 else:87 self._semaphore = asyncio.BoundedSemaphore(value=max_connections)88 return self._semaphore8990 async def acquire(self) -> None:91 if self.semaphore is None:92 return9394 timeout = self.limits.pool_timeout95 try:96 await asyncio.wait_for(self.semaphore.acquire(), timeout)97 except asyncio.TimeoutError:98 raise PoolTimeout()99100 def release(self) -> None:101 if self.semaphore is None:102 return103104 self.semaphore.release()105106107async def connect(108 hostname: str,109 port: int,110 ssl_context: typing.Optional[ssl.SSLContext] = None,111 timeout: TimeoutConfig = DEFAULT_TIMEOUT_CONFIG,112) -> typing.Tuple[Reader, Writer, Protocol]:113 try:114 stream_reader, stream_writer = await asyncio.wait_for( # type: ignore115 asyncio.open_connection(hostname, port, ssl=ssl_context),116 timeout.connect_timeout,117 )118 except asyncio.TimeoutError:119 raise ConnectTimeout()120121 ssl_object = stream_writer.get_extra_info("ssl_object")122 if ssl_object is None:123 ident = "http/1.1"124 else:125 ident = ssl_object.selected_alpn_protocol()126 if ident is None:127 ident = ssl_object.selected_npn_protocol()128129 reader = Reader(stream_reader=stream_reader, timeout=timeout)130 writer = Writer(stream_writer=stream_writer, timeout=timeout)131 protocol = Protocol.HTTP_2 if ident == "h2" else Protocol.HTTP_11132133 return (reader, writer, protocol)