concurrency.py
This file
Path
httpcore/concurrency.py
169 lines · 5.0 KiB · Python
Last changed by
Merge pull request #60 from encode/concurrency-backend-classTom Christiebefore adoption3d997af
History of this fileTake it
Merge pull request #58 from encode/sync-by-defaultTom Christiebefore adoptionb6c27f0
lines 1–16why, 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 .exceptions import ConnectTimeout, PoolTimeout, ReadTimeout, WriteTimeoutMerge pull request #60 from encode/concurrency-backend-classTom Christiebefore adoption3d997af
lines 17–23why, one step back17from .interfaces import (18 BasePoolSemaphore,19 BaseReader,20 BaseWriter,21 ConcurrencyBackend,22 Protocol,23)Merge pull request #58 from encode/sync-by-defaultTom Christiebefore adoptionb6c27f0
lines 24–27why, one step back2425OptionalTimeout = typing.Optional[TimeoutConfig]2627Merge pull request #60 from encode/concurrency-backend-classTom Christiebefore adoption3d997af
line 28why, one step back28SSL_MONKEY_PATCH_APPLIED = FalseMerge pull request #58 from encode/sync-by-defaultTom Christiebefore adoptionb6c27f0
lines 29–30why, one step back2930Merge pull request #60 from encode/concurrency-backend-classTom Christiebefore adoption3d997af
lines 31–33why, one step back31def ssl_monkey_patch() -> None:32 """33 Monky-patch for https://bugs.python.org/issue36709Merge pull request #58 from encode/sync-by-defaultTom Christiebefore adoptionb6c27f0
line 34why, one step back34Merge pull request #60 from encode/concurrency-backend-classTom Christiebefore adoption3d997af
lines 35–36why, one step back35 This prevents console errors when outstanding HTTPS connections36 still exist at the point of exiting.Merge pull request #58 from encode/sync-by-defaultTom Christiebefore adoptionb6c27f0
line 37why, one step back37Merge pull request #60 from encode/concurrency-backend-classTom Christiebefore adoption3d997af
lines 38–41why, one step back38 Clients which have been opened using a `with` block, or which have39 had `close()` closed, will not exhibit this issue in the first place.40 """41 MonkeyPatch = asyncio.selector_events._SelectorSocketTransport # type: ignoreMerge pull request #58 from encode/sync-by-defaultTom Christiebefore adoptionb6c27f0
line 42why, one step back42Merge pull request #60 from encode/concurrency-backend-classTom Christiebefore adoption3d997af
line 43why, one step back43 _write = MonkeyPatch.writeMerge pull request #58 from encode/sync-by-defaultTom Christiebefore adoptionb6c27f0
line 44why, one step back44Merge pull request #60 from encode/concurrency-backend-classTom Christiebefore adoption3d997af
lines 45–47why, one step back45 def _fixed_write(self, data: bytes) -> None: # type: ignore46 if not self._loop.is_closed():47 _write(self, data)Merge pull request #58 from encode/sync-by-defaultTom Christiebefore adoptionb6c27f0
line 48why, one step back48Merge pull request #60 from encode/concurrency-backend-classTom Christiebefore adoption3d997af
line 49why, one step back49 MonkeyPatch.write = _fixed_writeMerge pull request #58 from encode/sync-by-defaultTom Christiebefore adoptionb6c27f0
line 50why, one step back50Merge pull request #60 from encode/concurrency-backend-classTom Christiebefore adoption3d997af
line 51why, one step back51Merge pull request #58 from encode/sync-by-defaultTom Christiebefore adoptionb6c27f0
lines 52–130why, one step back52class Reader(BaseReader):53 def __init__(54 self, stream_reader: asyncio.StreamReader, timeout: TimeoutConfig55 ) -> None:56 self.stream_reader = stream_reader57 self.timeout = timeout5859 async def read(self, n: int, timeout: OptionalTimeout = None) -> bytes:60 if timeout is None:61 timeout = self.timeout6263 try:64 data = await asyncio.wait_for(65 self.stream_reader.read(n), timeout.read_timeout66 )67 except asyncio.TimeoutError:68 raise ReadTimeout()6970 return data717273class Writer(BaseWriter):74 def __init__(self, stream_writer: asyncio.StreamWriter, timeout: TimeoutConfig):75 self.stream_writer = stream_writer76 self.timeout = timeout7778 def write_no_block(self, data: bytes) -> None:79 self.stream_writer.write(data)8081 async def write(self, data: bytes, timeout: OptionalTimeout = None) -> None:82 if not data:83 return8485 if timeout is None:86 timeout = self.timeout8788 self.stream_writer.write(data)89 try:90 await asyncio.wait_for( # type: ignore91 self.stream_writer.drain(), timeout.write_timeout92 )93 except asyncio.TimeoutError:94 raise WriteTimeout()9596 async def close(self) -> None:97 self.stream_writer.close()9899100class PoolSemaphore(BasePoolSemaphore):101 def __init__(self, pool_limits: PoolLimits):102 self.pool_limits = pool_limits103104 @property105 def semaphore(self) -> typing.Optional[asyncio.BoundedSemaphore]:106 if not hasattr(self, "_semaphore"):107 max_connections = self.pool_limits.hard_limit108 if max_connections is None:109 self._semaphore = None110 else:111 self._semaphore = asyncio.BoundedSemaphore(value=max_connections)112 return self._semaphore113114 async def acquire(self) -> None:115 if self.semaphore is None:116 return117118 timeout = self.pool_limits.pool_timeout119 try:120 await asyncio.wait_for(self.semaphore.acquire(), timeout)121 except asyncio.TimeoutError:122 raise PoolTimeout()123124 def release(self) -> None:125 if self.semaphore is None:126 return127128 self.semaphore.release()129130Merge pull request #60 from encode/concurrency-backend-classTom Christiebefore adoption3d997af
lines 131–133why, one step back131class AsyncioBackend(ConcurrencyBackend):132 def __init__(self) -> None:133 global SSL_MONKEY_PATCH_APPLIEDMerge pull request #58 from encode/sync-by-defaultTom Christiebefore adoptionb6c27f0
line 134why, one step back134Merge pull request #60 from encode/concurrency-backend-classTom Christiebefore adoption3d997af
lines 135–137why, one step back135 if not SSL_MONKEY_PATCH_APPLIED:136 ssl_monkey_patch()137 SSL_MONKEY_PATCH_APPLIED = TrueMerge pull request #58 from encode/sync-by-defaultTom Christiebefore adoptionb6c27f0
line 138why, one step back138Merge pull request #60 from encode/concurrency-backend-classTom Christiebefore adoption3d997af
lines 139–152why, one step back139 async def connect(140 self,141 hostname: str,142 port: int,143 ssl_context: typing.Optional[ssl.SSLContext],144 timeout: TimeoutConfig,145 ) -> typing.Tuple[BaseReader, BaseWriter, Protocol]:146 try:147 stream_reader, stream_writer = await asyncio.wait_for( # type: ignore148 asyncio.open_connection(hostname, port, ssl=ssl_context),149 timeout.connect_timeout,150 )151 except asyncio.TimeoutError:152 raise ConnectTimeout()Merge pull request #58 from encode/sync-by-defaultTom Christiebefore adoptionb6c27f0
line 153why, one step back153Merge pull request #60 from encode/concurrency-backend-classTom Christiebefore adoption3d997af
lines 154–169why, one step back154 ssl_object = stream_writer.get_extra_info("ssl_object")155 if ssl_object is None:156 ident = "http/1.1"157 else:158 ident = ssl_object.selected_alpn_protocol()159 if ident is None:160 ident = ssl_object.selected_npn_protocol()161162 reader = Reader(stream_reader=stream_reader, timeout=timeout)163 writer = Writer(stream_writer=stream_writer, timeout=timeout)164 protocol = Protocol.HTTP_2 if ident == "h2" else Protocol.HTTP_11165166 return (reader, writer, protocol)167168 def get_semaphore(self, limits: PoolLimits) -> BasePoolSemaphore:169 return PoolSemaphore(limits)