default.py
This file
Path
httpcore/backends/default.py
128 lines · 3.9 KiB · Python
Last changed by
Reorganise structureTom Christiebefore adoption0c6f618
History of this fileTake it
Reorganise structureTom Christiebefore adoption0c6f618
lines 1–128why, one step back1"""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 ssl13import typing1415from ..config import DEFAULT_TIMEOUT_CONFIG, PoolLimits, TimeoutConfig16from ..constants import Protocol17from ..exceptions import ConnectTimeout, PoolTimeout, ReadTimeout, WriteTimeout18from ..interfaces import BasePoolSemaphore, BaseReader, BaseWriter1920OptionalTimeout = typing.Optional[TimeoutConfig]212223class Reader(BaseReader):24 def __init__(25 self, stream_reader: asyncio.StreamReader, timeout: TimeoutConfig26 ) -> None:27 self.stream_reader = stream_reader28 self.timeout = timeout2930 async def read(self, n: int, timeout: OptionalTimeout = None) -> bytes:31 if timeout is None:32 timeout = self.timeout3334 try:35 data = await asyncio.wait_for(36 self.stream_reader.read(n), timeout.read_timeout37 )38 except asyncio.TimeoutError:39 raise ReadTimeout()4041 return data424344class Writer(BaseWriter):45 def __init__(self, stream_writer: asyncio.StreamWriter, timeout: TimeoutConfig):46 self.stream_writer = stream_writer47 self.timeout = timeout4849 def write_no_block(self, data: bytes) -> None:50 self.stream_writer.write(data)5152 async def write(self, data: bytes, timeout: OptionalTimeout = None) -> None:53 if not data:54 return5556 if timeout is None:57 timeout = self.timeout5859 self.stream_writer.write(data)60 try:61 data = await asyncio.wait_for( # type: ignore62 self.stream_writer.drain(), timeout.write_timeout63 )64 except asyncio.TimeoutError:65 raise WriteTimeout()6667 async def close(self) -> None:68 self.stream_writer.close()697071class PoolSemaphore(BasePoolSemaphore):72 def __init__(self, pool_limits: PoolLimits):73 self.pool_limits = pool_limits7475 @property76 def semaphore(self) -> typing.Optional[asyncio.BoundedSemaphore]:77 if not hasattr(self, "_semaphore"):78 max_connections = self.pool_limits.hard_limit79 if max_connections is None:80 self._semaphore = None81 else:82 self._semaphore = asyncio.BoundedSemaphore(value=max_connections)83 return self._semaphore8485 async def acquire(self) -> None:86 if self.semaphore is None:87 return8889 timeout = self.pool_limits.pool_timeout90 try:91 await asyncio.wait_for(self.semaphore.acquire(), timeout)92 except asyncio.TimeoutError:93 raise PoolTimeout()9495 def release(self) -> None:96 if self.semaphore is None:97 return9899 self.semaphore.release()100101102async def connect(103 hostname: str,104 port: int,105 ssl_context: typing.Optional[ssl.SSLContext] = None,106 timeout: TimeoutConfig = DEFAULT_TIMEOUT_CONFIG,107) -> typing.Tuple[Reader, Writer, Protocol]:108 try:109 stream_reader, stream_writer = await asyncio.wait_for( # type: ignore110 asyncio.open_connection(hostname, port, ssl=ssl_context),111 timeout.connect_timeout,112 )113 except asyncio.TimeoutError:114 raise ConnectTimeout()115116 ssl_object = stream_writer.get_extra_info("ssl_object")117 if ssl_object is None:118 ident = "http/1.1"119 else:120 ident = ssl_object.selected_alpn_protocol()121 if ident is None:122 ident = ssl_object.selected_npn_protocol()123124 reader = Reader(stream_reader=stream_reader, timeout=timeout)125 writer = Writer(stream_writer=stream_writer, timeout=timeout)126 protocol = Protocol.HTTP_2 if ident == "h2" else Protocol.HTTP_11127128 return (reader, writer, protocol)