Skip to content
Myr

default.py

This file

Path

httpcore/backends/default.py

147 lines · 4.5 KiB · Python

Last changed by

Merge pull request #40 from encode/graceful-behavior-for-unclosed-https-connectionsTom Christiebefore adoption698cb5a

History of this file

Take it

Reorganise structureTom Christiebefore adoption0c6f618

lines 1–22why, one step back
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 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]2122

Merge pull request #40 from encode/graceful-behavior-for-unclosed-https-connectionsTom Christiebefore adoption698cb5a

lines 23–39why, one step back
23# Monky-patch for https://bugs.python.org/issue36709
24#25# This prevents console errors when outstanding HTTPS connections26# still exist at the point of exiting.27#28# Clients which have been opened using a `with` block, or which have29# had `close()` closed, will not exhibit this issue in the first place.3031_write = asyncio.selector_events._SelectorSocketTransport.write3233def _fixed_write(self, exc):34 if not self._loop.is_closed():35 _write(self, exc)3637asyncio.selector_events._SelectorSocketTransport.write = _fixed_write3839

Reorganise structureTom Christiebefore adoption0c6f618

lines 40–77why, one step back
40class Reader(BaseReader):
41 def __init__(42 self, stream_reader: asyncio.StreamReader, timeout: TimeoutConfig43 ) -> None:44 self.stream_reader = stream_reader45 self.timeout = timeout4647 async def read(self, n: int, timeout: OptionalTimeout = None) -> bytes:48 if timeout is None:49 timeout = self.timeout5051 try:52 data = await asyncio.wait_for(53 self.stream_reader.read(n), timeout.read_timeout54 )55 except asyncio.TimeoutError:56 raise ReadTimeout()5758 return data596061class Writer(BaseWriter):62 def __init__(self, stream_writer: asyncio.StreamWriter, timeout: TimeoutConfig):63 self.stream_writer = stream_writer64 self.timeout = timeout6566 def write_no_block(self, data: bytes) -> None:67 self.stream_writer.write(data)6869 async def write(self, data: bytes, timeout: OptionalTimeout = None) -> None:70 if not data:71 return7273 if timeout is None:74 timeout = self.timeout7576 self.stream_writer.write(data)77 try:

Merge pull request #40 from encode/graceful-behavior-for-unclosed-https-connectionsTom Christiebefore adoption698cb5a

line 78why, one step back
78 await asyncio.wait_for( # type: ignore

Reorganise structureTom Christiebefore adoption0c6f618

lines 79–139why, one step back
79 self.stream_writer.drain(), timeout.write_timeout
80 )81 except asyncio.TimeoutError:82 raise WriteTimeout()8384 async def close(self) -> None:85 self.stream_writer.close()868788class PoolSemaphore(BasePoolSemaphore):89 def __init__(self, pool_limits: PoolLimits):90 self.pool_limits = pool_limits9192 @property93 def semaphore(self) -> typing.Optional[asyncio.BoundedSemaphore]:94 if not hasattr(self, "_semaphore"):95 max_connections = self.pool_limits.hard_limit96 if max_connections is None:97 self._semaphore = None98 else:99 self._semaphore = asyncio.BoundedSemaphore(value=max_connections)100 return self._semaphore101102 async def acquire(self) -> None:103 if self.semaphore is None:104 return105106 timeout = self.pool_limits.pool_timeout107 try:108 await asyncio.wait_for(self.semaphore.acquire(), timeout)109 except asyncio.TimeoutError:110 raise PoolTimeout()111112 def release(self) -> None:113 if self.semaphore is None:114 return115116 self.semaphore.release()117118119async def connect(120 hostname: str,121 port: int,122 ssl_context: typing.Optional[ssl.SSLContext] = None,123 timeout: TimeoutConfig = DEFAULT_TIMEOUT_CONFIG,124) -> typing.Tuple[Reader, Writer, Protocol]:125 try:126 stream_reader, stream_writer = await asyncio.wait_for( # type: ignore127 asyncio.open_connection(hostname, port, ssl=ssl_context),128 timeout.connect_timeout,129 )130 except asyncio.TimeoutError:131 raise ConnectTimeout()132133 ssl_object = stream_writer.get_extra_info("ssl_object")134 if ssl_object is None:135 ident = "http/1.1"136 else:137 ident = ssl_object.selected_alpn_protocol()138 if ident is None:139 ident = ssl_object.selected_npn_protocol()

Merge pull request #40 from encode/graceful-behavior-for-unclosed-https-connectionsTom Christiebefore adoption698cb5a

lines 140–141why, one step back
140
141 stream_writer.transport.set_write_buffer_limits(high=0, low=0)

Reorganise structureTom Christiebefore adoption0c6f618

lines 142–147why, one step back
142
143 reader = Reader(stream_reader=stream_reader, timeout=timeout)144 writer = Writer(stream_writer=stream_writer, timeout=timeout)145 protocol = Protocol.HTTP_2 if ident == "h2" else Protocol.HTTP_11146147 return (reader, writer, protocol)