Skip to content
Myr

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

8 files+37 added−32 removed

modified:httpx/concurrency/asyncio.py+8 added-8 removed
10 unmodified lines
11 BaseBackgroundManager,12 BaseEvent,13 BasePoolSemaphore,14 BaseQueue,15 BaseTCPStream,15 BaseSocketStream,16 ConcurrencyBackend,17 TimeoutFlag,18)19
20 unmodified lines
4041 MonkeyPatch.write = _fixed_write424344class TCPStream(BaseTCPStream):44class SocketStream(BaseSocketStream):45 def __init__(46 self,47 stream_reader: asyncio.StreamReader,48 stream_writer: asyncio.StreamWriter,
2 unmodified lines
51 self.stream_reader = stream_reader52 self.stream_writer = stream_writer53 self.timeout = timeout5455 self._inner: typing.Optional[TCPStream] = None55 self._inner: typing.Optional[SocketStream] = None5657 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 lines
82 stream_writer = asyncio.StreamWriter(83 transport=transport, protocol=protocol, reader=stream_reader, loop=loop84 )8586 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_stream
136 unmodified lines
228 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()240241 return TCPStream(241 return SocketStream(242 stream_reader=stream_reader, stream_writer=stream_writer, timeout=timeout243 )244245 async def run_in_threadpool(
52 unmodified lines
modified:httpx/concurrency/base.py+4 added-4 removed
35 unmodified lines
36 self.raise_on_read_timeout = False37 self.raise_on_write_timeout = True383940class BaseTCPStream:40class 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 line
48 raise NotImplementedError() # pragma: no cover4950 async def start_tls(51 self, hostname: str, ssl_context: ssl.SSLContext, timeout: TimeoutConfig52 ) -> "BaseTCPStream":52 ) -> "BaseSocketStream":53 raise NotImplementedError() # pragma: no cover5455 async def read(56 self, n: int, timeout: TimeoutConfig = None, flag: typing.Any = None
63 unmodified lines
120 hostname: str,121 port: int,122 ssl_context: typing.Optional[ssl.SSLContext],123 timeout: TimeoutConfig,124 ) -> BaseTCPStream:124 ) -> BaseSocketStream:125 raise NotImplementedError() # pragma: no cover126127 def get_semaphore(self, limits: PoolLimits) -> BasePoolSemaphore:128 raise NotImplementedError() # pragma: no cover
64 unmodified lines
modified:httpx/concurrency/trio.py+6 added-6 removed
11 unmodified lines
12 BaseBackgroundManager,13 BaseEvent,14 BasePoolSemaphore,15 BaseQueue,16 BaseTCPStream,16 BaseSocketStream,17 ConcurrencyBackend,18 TimeoutFlag,19)20
1 unmodified line
22def _or_inf(value: typing.Optional[float]) -> float:23 return value if value is not None else float("inf")242526class TCPStream(BaseTCPStream):26class SocketStream(BaseSocketStream):27 def __init__(28 self,29 stream: typing.Union[trio.SocketStream, trio.SSLStream],30 timeout: TimeoutConfig,
4 unmodified lines
35 self.write_lock = trio.Lock()3637 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 lines
5152 if cancel_scope.cancelled_caught:53 raise ConnectTimeout()5455 return TCPStream(ssl_stream, self.timeout)55 return SocketStream(ssl_stream, self.timeout)5657 def get_http_version(self) -> str:58 if not isinstance(self.stream, trio.SSLStream):59 return "HTTP/1.1"
116 unmodified lines
176 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)182183 with trio.move_on_after(connect_timeout) as cancel_scope:184 stream: trio.SocketStream = await trio.open_tcp_stream(hostname, port)
3 unmodified lines
188189 if cancel_scope.cancelled_caught:190 raise ConnectTimeout()191192 return TCPStream(stream=stream, timeout=timeout)192 return SocketStream(stream=stream, timeout=timeout)193194 async def run_in_threadpool(195 self, func: typing.Callable, *args: typing.Any, **kwargs: typing.Any196 ) -> typing.Any:
76 unmodified lines
modified:httpx/dispatch/http11.py+2 added-2 removed
1import typing23import h1145from ..concurrency.base import BaseTCPStream, ConcurrencyBackend, TimeoutFlag5from ..concurrency.base import BaseSocketStream, ConcurrencyBackend, TimeoutFlag6from ..config import TimeoutConfig, TimeoutTypes7from ..models import AsyncRequest, AsyncResponse8from ..utils import get_logger9
20 unmodified lines
30 READ_NUM_BYTES = 40963132 def __init__(33 self,34 stream: BaseTCPStream,34 stream: BaseSocketStream,35 backend: ConcurrencyBackend,36 on_release: typing.Optional[OnReleaseCallback] = None,37 ):38 self.stream = stream
170 unmodified lines
modified:httpx/dispatch/http2.py+7 added-2 removed
3 unmodified lines
4import h2.connection5import h2.events6from h2.settings import SettingCodes, Settings78from ..concurrency.base import BaseEvent, BaseTCPStream, ConcurrencyBackend, TimeoutFlag8from ..concurrency.base import (9 BaseEvent,10 BaseSocketStream,11 ConcurrencyBackend,12 TimeoutFlag,13)14from ..config import TimeoutConfig, TimeoutTypes15from ..exceptions import ProtocolError16from ..models import AsyncRequest, AsyncResponse17from ..utils import get_logger
5 unmodified lines
23 READ_NUM_BYTES = 40962425 def __init__(26 self,22 stream: BaseTCPStream,27 stream: BaseSocketStream,28 backend: ConcurrencyBackend,29 on_release: typing.Callable = None,30 ):31 self.stream = stream
225 unmodified lines
modified:httpx/dispatch/proxy_http.py+1 added-1 removed
177 unmodified lines
178 on_release = http_connection.on_release179 stream = http_connection.stream180181 # 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.timeout
67 unmodified lines
modified:httpx/__init__.py+2 added-2 removed
3 unmodified lines
4from .concurrency.asyncio import AsyncioBackend5from .concurrency.base import (6 BaseBackgroundManager,7 BasePoolSemaphore,8 BaseTCPStream,8 BaseSocketStream,9 ConcurrencyBackend,10)11from .config import (12 USER_AGENT,
100 unmodified lines
113 "Timeout",114 "TooManyRedirects",115 "WriteTimeout",116 "AsyncDispatcher",117 "BaseTCPStream",117 "BaseSocketStream",118 "ConcurrencyBackend",119 "Dispatcher",120 "URL",121 "URLTypes",
24 unmodified lines
modified:tests/dispatch/utils.py+7 added-7 removed
3 unmodified lines
4import h2.config5import h2.connection6import h2.events78from httpx import AsyncioBackend, BaseTCPStream, Request, TimeoutConfig8from httpx import AsyncioBackend, BaseSocketStream, Request, TimeoutConfig9from tests.concurrency import sleep101112class MockHTTP2Backend:
7 unmodified lines
20 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.server2728 # Defer all other attributes and methods to the underlying backend.29 def __getattr__(self, name: str) -> typing.Any:30 return getattr(self.backend, name)313233class MockHTTP2Server(BaseTCPStream):33class 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 = app
4 unmodified lines
42 self.return_data = {}43 self.returning = {}44 self.settings_changed = []4546 # TCP stream interface46 # Socket stream interface4748 def get_http_version(self) -> str:49 return "HTTP/2"50
126 unmodified lines
177 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.stream
2 unmodified lines
188 def __getattr__(self, name: str) -> typing.Any:189 return getattr(self.backend, name)190191192class MockRawSocketStream(BaseTCPStream):192class MockRawSocketStream(BaseSocketStream):193 def __init__(self, backend: MockRawSocketBackend):194 self.backend = backend195196 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)201202 def get_http_version(self) -> str:
20 unmodified lines