Rename BaseTCPStream/TCPStream to BaseSocketStream/SocketStream (#517)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Jonas Lundberg · committed by Florimond Manca · parent 586acdd · Browse files · 8 files·+37 added−32 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
8 files+37 added−32 removed
- tests:+7 added−7 removed
- other:+30 added−25 removed
Provenance
- Commit
1a32cf0- Tree
0e108e2- Author
Jonas Lundberg <jonas@5monkeys.se>- Committer
Florimond Manca <florimond.manca@gmail.com>- Parent
586acdd
8 files changed+37 added−32 removed
modified:httpx/concurrency/asyncio.py+8 added-8 removed
10 unmodified lines11 BaseBackgroundManager,12 BaseEvent,13 BasePoolSemaphore,14 BaseQueue,15- BaseTCPStream,15+ BaseSocketStream,16 ConcurrencyBackend,17 TimeoutFlag,18 )19 20 unmodified lines40 41 MonkeyPatch.write = _fixed_write42 43 44-class TCPStream(BaseTCPStream):44+class SocketStream(BaseSocketStream):45 def __init__(46 self,47 stream_reader: asyncio.StreamReader,48 stream_writer: asyncio.StreamWriter,2 unmodified lines51 self.stream_reader = stream_reader52 self.stream_writer = stream_writer53 self.timeout = timeout54 55- self._inner: typing.Optional[TCPStream] = None55+ self._inner: typing.Optional[SocketStream] = None56 57 async def start_tls(58 self, hostname: str, ssl_context: ssl.SSLContext, timeout: TimeoutConfig59- ) -> BaseTCPStream:59+ ) -> "SocketStream":60 loop = asyncio.get_event_loop()61 if not hasattr(loop, "start_tls"): # pragma: no cover62 raise NotImplementedError(63 "asyncio.AbstractEventLoop.start_tls() is only available in Python 3.7+"18 unmodified lines82 stream_writer = asyncio.StreamWriter(83 transport=transport, protocol=protocol, reader=stream_reader, loop=loop84 )85 86- ssl_stream = TCPStream(stream_reader, stream_writer, self.timeout)87- # When we return a new TCPStream with new StreamReader/StreamWriter instances,86+ ssl_stream = SocketStream(stream_reader, stream_writer, self.timeout)87+ # When we return a new SocketStream with new StreamReader/StreamWriter instances88 # we need to keep references to the old StreamReader/StreamWriter so that they89 # are not garbage collected and closed while we're still using them.90 ssl_stream._inner = self91 return ssl_stream136 unmodified lines228 hostname: str,229 port: int,230 ssl_context: typing.Optional[ssl.SSLContext],231 timeout: TimeoutConfig,232- ) -> BaseTCPStream:232+ ) -> SocketStream:233 try:234 stream_reader, stream_writer = await asyncio.wait_for( # type: ignore235 asyncio.open_connection(hostname, port, ssl=ssl_context),236 timeout.connect_timeout,237 )238 except asyncio.TimeoutError:239 raise ConnectTimeout()240 241- return TCPStream(241+ return SocketStream(242 stream_reader=stream_reader, stream_writer=stream_writer, timeout=timeout243 )244 245 async def run_in_threadpool(52 unmodified linesmodified:httpx/concurrency/base.py+4 added-4 removed
35 unmodified lines36 self.raise_on_read_timeout = False37 self.raise_on_write_timeout = True38 39 40-class BaseTCPStream:40+class BaseSocketStream:41 """42- A TCP stream with read/write operations. Abstracts away any asyncio-specific42+ A socket stream with read/write operations. Abstracts away any asyncio-specific43 interfaces into a more generic base class, that we can use with alternate44 backends, or for stand-alone test cases.45 """46 1 unmodified line48 raise NotImplementedError() # pragma: no cover49 50 async def start_tls(51 self, hostname: str, ssl_context: ssl.SSLContext, timeout: TimeoutConfig52- ) -> "BaseTCPStream":52+ ) -> "BaseSocketStream":53 raise NotImplementedError() # pragma: no cover54 55 async def read(56 self, n: int, timeout: TimeoutConfig = None, flag: typing.Any = None63 unmodified lines120 hostname: str,121 port: int,122 ssl_context: typing.Optional[ssl.SSLContext],123 timeout: TimeoutConfig,124- ) -> BaseTCPStream:124+ ) -> BaseSocketStream:125 raise NotImplementedError() # pragma: no cover126 127 def get_semaphore(self, limits: PoolLimits) -> BasePoolSemaphore:128 raise NotImplementedError() # pragma: no cover64 unmodified linesmodified:httpx/concurrency/trio.py+6 added-6 removed
11 unmodified lines12 BaseBackgroundManager,13 BaseEvent,14 BasePoolSemaphore,15 BaseQueue,16- BaseTCPStream,16+ BaseSocketStream,17 ConcurrencyBackend,18 TimeoutFlag,19 )20 1 unmodified line22 def _or_inf(value: typing.Optional[float]) -> float:23 return value if value is not None else float("inf")24 25 26-class TCPStream(BaseTCPStream):26+class SocketStream(BaseSocketStream):27 def __init__(28 self,29 stream: typing.Union[trio.SocketStream, trio.SSLStream],30 timeout: TimeoutConfig,4 unmodified lines35 self.write_lock = trio.Lock()36 37 async def start_tls(38 self, hostname: str, ssl_context: ssl.SSLContext, timeout: TimeoutConfig39- ) -> BaseTCPStream:39+ ) -> "SocketStream":40 # Check that the write buffer is empty. We should never start a TLS stream41 # while there is still pending data to write.42 assert self.write_buffer == b""43 7 unmodified lines51 52 if cancel_scope.cancelled_caught:53 raise ConnectTimeout()54 55- return TCPStream(ssl_stream, self.timeout)55+ return SocketStream(ssl_stream, self.timeout)56 57 def get_http_version(self) -> str:58 if not isinstance(self.stream, trio.SSLStream):59 return "HTTP/1.1"116 unmodified lines176 hostname: str,177 port: int,178 ssl_context: typing.Optional[ssl.SSLContext],179 timeout: TimeoutConfig,180- ) -> TCPStream:180+ ) -> SocketStream:181 connect_timeout = _or_inf(timeout.connect_timeout)182 183 with trio.move_on_after(connect_timeout) as cancel_scope:184 stream: trio.SocketStream = await trio.open_tcp_stream(hostname, port)3 unmodified lines188 189 if cancel_scope.cancelled_caught:190 raise ConnectTimeout()191 192- return TCPStream(stream=stream, timeout=timeout)192+ return SocketStream(stream=stream, timeout=timeout)193 194 async def run_in_threadpool(195 self, func: typing.Callable, *args: typing.Any, **kwargs: typing.Any196 ) -> typing.Any:76 unmodified linesmodified:httpx/dispatch/http11.py+2 added-2 removed
1 import typing2 3 import h114 5-from ..concurrency.base import BaseTCPStream, ConcurrencyBackend, TimeoutFlag5+from ..concurrency.base import BaseSocketStream, ConcurrencyBackend, TimeoutFlag6 from ..config import TimeoutConfig, TimeoutTypes7 from ..models import AsyncRequest, AsyncResponse8 from ..utils import get_logger9 20 unmodified lines30 READ_NUM_BYTES = 409631 32 def __init__(33 self,34- stream: BaseTCPStream,34+ stream: BaseSocketStream,35 backend: ConcurrencyBackend,36 on_release: typing.Optional[OnReleaseCallback] = None,37 ):38 self.stream = stream170 unmodified linesmodified:httpx/dispatch/http2.py+7 added-2 removed
3 unmodified lines4 import h2.connection5 import h2.events6 from h2.settings import SettingCodes, Settings7 8-from ..concurrency.base import BaseEvent, BaseTCPStream, ConcurrencyBackend, TimeoutFlag8+from ..concurrency.base import (9+ BaseEvent,10+ BaseSocketStream,11+ ConcurrencyBackend,12+ TimeoutFlag,13+)14 from ..config import TimeoutConfig, TimeoutTypes15 from ..exceptions import ProtocolError16 from ..models import AsyncRequest, AsyncResponse17 from ..utils import get_logger5 unmodified lines23 READ_NUM_BYTES = 409624 25 def __init__(26 self,22- stream: BaseTCPStream,27+ stream: BaseSocketStream,28 backend: ConcurrencyBackend,29 on_release: typing.Callable = None,30 ):31 self.stream = stream225 unmodified linesmodified:httpx/dispatch/proxy_http.py+1 added-1 removed
177 unmodified lines178 on_release = http_connection.on_release179 stream = http_connection.stream180 181 # If we need to start TLS again for the target server182- # we need to pull the TCP stream off the internal182+ # we need to pull the socket stream off the internal183 # HTTP connection object and run start_tls()184 if origin.is_ssl:185 ssl_config = SSLConfig(cert=self.cert, verify=self.verify)186 timeout = connection.timeout67 unmodified linesmodified:httpx/__init__.py+2 added-2 removed
3 unmodified lines4 from .concurrency.asyncio import AsyncioBackend5 from .concurrency.base import (6 BaseBackgroundManager,7 BasePoolSemaphore,8- BaseTCPStream,8+ BaseSocketStream,9 ConcurrencyBackend,10 )11 from .config import (12 USER_AGENT,100 unmodified lines113 "Timeout",114 "TooManyRedirects",115 "WriteTimeout",116 "AsyncDispatcher",117- "BaseTCPStream",117+ "BaseSocketStream",118 "ConcurrencyBackend",119 "Dispatcher",120 "URL",121 "URLTypes",24 unmodified linesmodified:tests/dispatch/utils.py+7 added-7 removed
3 unmodified lines4 import h2.config5 import h2.connection6 import h2.events7 8-from httpx import AsyncioBackend, BaseTCPStream, Request, TimeoutConfig8+from httpx import AsyncioBackend, BaseSocketStream, Request, TimeoutConfig9 from tests.concurrency import sleep10 11 12 class MockHTTP2Backend:7 unmodified lines20 hostname: str,21 port: int,22 ssl_context: typing.Optional[ssl.SSLContext],23 timeout: TimeoutConfig,24- ) -> BaseTCPStream:24+ ) -> BaseSocketStream:25 self.server = MockHTTP2Server(self.app, backend=self.backend)26 return self.server27 28 # Defer all other attributes and methods to the underlying backend.29 def __getattr__(self, name: str) -> typing.Any:30 return getattr(self.backend, name)31 32 33-class MockHTTP2Server(BaseTCPStream):33+class MockHTTP2Server(BaseSocketStream):34 def __init__(self, app, backend):35 config = h2.config.H2Configuration(client_side=False)36 self.conn = h2.connection.H2Connection(config=config)37 self.app = app4 unmodified lines42 self.return_data = {}43 self.returning = {}44 self.settings_changed = []45 46- # TCP stream interface46+ # Socket stream interface47 48 def get_http_version(self) -> str:49 return "HTTP/2"50 126 unmodified lines177 hostname: str,178 port: int,179 ssl_context: typing.Optional[ssl.SSLContext],180 timeout: TimeoutConfig,181- ) -> BaseTCPStream:181+ ) -> BaseSocketStream:182 self.received_data.append(183 b"--- CONNECT(%s, %d) ---" % (hostname.encode(), port)184 )185 return self.stream2 unmodified lines188 def __getattr__(self, name: str) -> typing.Any:189 return getattr(self.backend, name)190 191 192-class MockRawSocketStream(BaseTCPStream):192+class MockRawSocketStream(BaseSocketStream):193 def __init__(self, backend: MockRawSocketBackend):194 self.backend = backend195 196 async def start_tls(197 self, hostname: str, ssl_context: ssl.SSLContext, timeout: TimeoutConfig198- ) -> BaseTCPStream:198+ ) -> BaseSocketStream:199 self.backend.received_data.append(b"--- START_TLS(%s) ---" % hostname.encode())200 return MockRawSocketStream(self.backend)201 202 def get_http_version(self) -> str:20 unmodified lines