From 4678d44ede954b8e3431b56d0c973bdebacd683a Mon Sep 17 00:00:00 2001
From: jakkdl
Date: Thu, 13 Jul 2023 16:12:23 +0200
Subject: [PATCH 1/8] typecheck trio/_dtls.py
---
pyproject.toml | 7 ++
trio/_channel.py | 10 +-
trio/_dtls.py | 195 +++++++++++++++++++++-------------
trio/_tests/verify_types.json | 21 +---
4 files changed, 140 insertions(+), 93 deletions(-)
diff --git a/pyproject.toml b/pyproject.toml
index cfb4060ee7..ee0c019af7 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -44,6 +44,13 @@ disallow_untyped_defs = false
# DO NOT use `ignore_errors`; it doesn't apply
# downstream and users have to deal with them.
+[[tool.mypy.overrides]]
+module = [
+ "trio._dtls"
+]
+disallow_incomplete_defs = true
+disallow_untyped_defs = true
+
[tool.pytest.ini_options]
addopts = ["--strict-markers", "--strict-config"]
faulthandler_timeout = 60
diff --git a/trio/_channel.py b/trio/_channel.py
index 7c8ff4660d..df596adddd 100644
--- a/trio/_channel.py
+++ b/trio/_channel.py
@@ -20,7 +20,7 @@
def _open_memory_channel(
- max_buffer_size: int,
+ max_buffer_size: int | float,
) -> tuple[MemorySendChannel[T], MemoryReceiveChannel[T]]:
"""Open a channel for passing objects between tasks within a process.
@@ -92,11 +92,11 @@ def _open_memory_channel(
# Need to use Tuple instead of tuple due to CI check running on 3.8
class open_memory_channel(Tuple[MemorySendChannel[T], MemoryReceiveChannel[T]]):
def __new__( # type: ignore[misc] # "must return a subtype"
- cls, max_buffer_size: int
+ cls, max_buffer_size: int | float
) -> tuple[MemorySendChannel[T], MemoryReceiveChannel[T]]:
return _open_memory_channel(max_buffer_size)
- def __init__(self, max_buffer_size: int):
+ def __init__(self, max_buffer_size: int | float):
...
else:
@@ -108,7 +108,7 @@ def __init__(self, max_buffer_size: int):
@attr.s(frozen=True, slots=True)
class MemoryChannelStats:
current_buffer_used: int = attr.ib()
- max_buffer_size: int = attr.ib()
+ max_buffer_size: int | float = attr.ib()
open_send_channels: int = attr.ib()
open_receive_channels: int = attr.ib()
tasks_waiting_send: int = attr.ib()
@@ -117,7 +117,7 @@ class MemoryChannelStats:
@attr.s(slots=True)
class MemoryChannelState(Generic[T]):
- max_buffer_size: int = attr.ib()
+ max_buffer_size: int | float = attr.ib()
data: deque[T] = attr.ib(factory=deque)
# Counts of open endpoints using this state
open_send_channels: int = attr.ib(default=0)
diff --git a/trio/_dtls.py b/trio/_dtls.py
index 722a9499f8..acc5f950eb 100644
--- a/trio/_dtls.py
+++ b/trio/_dtls.py
@@ -16,34 +16,53 @@
import warnings
import weakref
from itertools import count
-from typing import TYPE_CHECKING
+from typing import (
+ TYPE_CHECKING,
+ Any,
+ Awaitable,
+ Callable,
+ Generic,
+ Iterable,
+ Iterator,
+ TypeVar,
+ Union,
+ cast,
+)
import attr
+from OpenSSL import SSL
import trio
-from trio._util import Final, NoPublicConstructor
+
+from ._util import Final, NoPublicConstructor
if TYPE_CHECKING:
from types import TracebackType
+ from OpenSSL.SSL import Context
+ from typing_extensions import Self, TypeAlias
+
+ from ._core._run import _TaskStatus
+ from ._socket import _SocketType
+
MAX_UDP_PACKET_SIZE = 65527
-def packet_header_overhead(sock):
+def packet_header_overhead(sock: _SocketType) -> int:
if sock.family == trio.socket.AF_INET:
return 28
else:
return 48
-def worst_case_mtu(sock):
+def worst_case_mtu(sock: _SocketType) -> int:
if sock.family == trio.socket.AF_INET:
return 576 - packet_header_overhead(sock)
else:
return 1280 - packet_header_overhead(sock)
-def best_guess_mtu(sock):
+def best_guess_mtu(sock: _SocketType) -> int:
return 1500 - packet_header_overhead(sock)
@@ -105,14 +124,14 @@ class BadPacket(Exception):
# ChangeCipherSpec is used during the handshake but has its own ContentType.
#
# Cannot fail.
-def part_of_handshake_untrusted(packet):
+def part_of_handshake_untrusted(packet: bytes) -> bool:
# If the packet is too short, then slicing will successfully return a
# short string, which will necessarily fail to match.
return packet[3:5] == b"\x00\x00"
# Cannot fail
-def is_client_hello_untrusted(packet):
+def is_client_hello_untrusted(packet: bytes) -> bool:
try:
return (
packet[0] == ContentType.handshake
@@ -147,7 +166,7 @@ class Record:
payload: bytes = attr.ib(repr=to_hex)
-def records_untrusted(packet):
+def records_untrusted(packet: bytes) -> Iterator[Record]:
i = 0
while i < len(packet):
try:
@@ -165,7 +184,7 @@ def records_untrusted(packet):
yield Record(ct, version, epoch_seqno, payload)
-def encode_record(record):
+def encode_record(record: Record) -> bytes:
header = RECORD_HEADER.pack(
record.content_type,
record.version,
@@ -194,7 +213,7 @@ class HandshakeFragment:
frag: bytes = attr.ib(repr=to_hex)
-def decode_handshake_fragment_untrusted(payload):
+def decode_handshake_fragment_untrusted(payload: bytes) -> HandshakeFragment:
# Raises BadPacket if decoding fails
try:
(
@@ -224,7 +243,7 @@ def decode_handshake_fragment_untrusted(payload):
)
-def encode_handshake_fragment(hsf):
+def encode_handshake_fragment(hsf: HandshakeFragment) -> bytes:
hs_header = HANDSHAKE_MESSAGE_HEADER.pack(
hsf.msg_type,
hsf.msg_len.to_bytes(3, "big"),
@@ -235,7 +254,7 @@ def encode_handshake_fragment(hsf):
return hs_header + hsf.frag
-def decode_client_hello_untrusted(packet):
+def decode_client_hello_untrusted(packet: bytes) -> tuple[int, bytes, bytes]:
# Raises BadPacket if parsing fails
# Returns (record epoch_seqno, cookie from the packet, data that should be
# hashed into cookie)
@@ -331,12 +350,20 @@ class OpaqueHandshakeMessage:
record: Record
+# for some reason doesn't work with |
+_AnyHandshakeMessage: TypeAlias = Union[
+ HandshakeMessage, PseudoHandshakeMessage, OpaqueHandshakeMessage
+]
+
+
# This takes a raw outgoing handshake volley that openssl generated, and
# reconstructs the handshake messages inside it, so that we can repack them
# into records while retransmitting. So the data ought to be well-behaved --
# it's not coming from the network.
-def decode_volley_trusted(volley):
- messages = []
+def decode_volley_trusted(
+ volley: bytes,
+) -> list[_AnyHandshakeMessage]:
+ messages: list[_AnyHandshakeMessage] = []
messages_by_seq = {}
for record in records_untrusted(volley):
# ChangeCipherSpec isn't a handshake message, so it can't be fragmented.
@@ -380,13 +407,17 @@ def decode_volley_trusted(volley):
class RecordEncoder:
- def __init__(self):
+ def __init__(self) -> None:
self._record_seq = count()
- def set_first_record_number(self, n):
+ def set_first_record_number(self, n: int) -> None:
self._record_seq = count(n)
- def encode_volley(self, messages, mtu):
+ def encode_volley(
+ self,
+ messages: Iterable[_AnyHandshakeMessage],
+ mtu: int,
+ ) -> list[bytearray]:
packets = []
packet = bytearray()
for message in messages:
@@ -518,13 +549,13 @@ def encode_volley(self, messages, mtu):
COOKIE_LENGTH = 32
-def _current_cookie_tick():
+def _current_cookie_tick() -> int:
return int(trio.current_time() / COOKIE_REFRESH_INTERVAL)
# Simple deterministic and invertible serializer -- i.e., a useful tool for converting
# structured data into something we can cryptographically sign.
-def _signable(*fields):
+def _signable(*fields: bytes) -> bytes:
out = []
for field in fields:
out.append(struct.pack("!Q", len(field)))
@@ -532,7 +563,9 @@ def _signable(*fields):
return b"".join(out)
-def _make_cookie(key, salt, tick, address, client_hello_bits):
+def _make_cookie(
+ key: bytes, salt: bytes, tick: int, address: Any, client_hello_bits: bytes
+) -> bytes:
assert len(salt) == SALT_BYTES
assert len(key) == KEY_BYTES
@@ -548,7 +581,9 @@ def _make_cookie(key, salt, tick, address, client_hello_bits):
return (salt + hmac.digest(key, signable_data, COOKIE_HASH))[:COOKIE_LENGTH]
-def valid_cookie(key, cookie, address, client_hello_bits):
+def valid_cookie(
+ key: bytes, cookie: bytes, address: Any, client_hello_bits: bytes
+) -> bool:
if len(cookie) > SALT_BYTES:
salt = cookie[:SALT_BYTES]
@@ -568,7 +603,9 @@ def valid_cookie(key, cookie, address, client_hello_bits):
return False
-def challenge_for(key, address, epoch_seqno, client_hello_bits):
+def challenge_for(
+ key: bytes, address: Any, epoch_seqno: int, client_hello_bits: bytes
+) -> bytes:
salt = os.urandom(SALT_BYTES)
tick = _current_cookie_tick()
cookie = _make_cookie(key, salt, tick, address, client_hello_bits)
@@ -608,12 +645,15 @@ def challenge_for(key, address, epoch_seqno, client_hello_bits):
return packet
-class _Queue:
- def __init__(self, incoming_packets_buffer):
- self.s, self.r = trio.open_memory_channel(incoming_packets_buffer)
+T = TypeVar("T")
+
+class _Queue(Generic[T]):
+ def __init__(self, incoming_packets_buffer: int | float):
+ self.s, self.r = trio.open_memory_channel[T](incoming_packets_buffer)
-def _read_loop(read_fn):
+
+def _read_loop(read_fn: Callable[[int], bytes]) -> bytes:
chunks = []
while True:
try:
@@ -624,7 +664,9 @@ def _read_loop(read_fn):
return b"".join(chunks)
-async def handle_client_hello_untrusted(endpoint, address, packet):
+async def handle_client_hello_untrusted(
+ endpoint: DTLSEndpoint, address: Any, packet: bytes
+) -> None:
if endpoint._listening_context is None:
return
@@ -697,7 +739,9 @@ async def handle_client_hello_untrusted(endpoint, address, packet):
endpoint._incoming_connections_q.s.send_nowait(stream)
-async def dtls_receive_loop(endpoint_ref, sock):
+async def dtls_receive_loop(
+ endpoint_ref: weakref.ReferenceType[DTLSEndpoint], sock: _SocketType
+) -> None:
try:
while True:
try:
@@ -773,7 +817,7 @@ class DTLSChannel(trio.abc.Channel[bytes], metaclass=NoPublicConstructor):
"""
- def __init__(self, endpoint, peer_address, ctx):
+ def __init__(self, endpoint: DTLSEndpoint, peer_address: Any, ctx: Context):
self.endpoint = endpoint
self.peer_address = peer_address
self._packets_dropped_in_trio = 0
@@ -784,25 +828,27 @@ def __init__(self, endpoint, peer_address, ctx):
# OP_NO_RENEGOTIATION disables renegotiation, which is too complex for us to
# support and isn't useful anyway -- especially for DTLS where it's equivalent
# to just performing a new handshake.
- ctx.set_options(SSL.OP_NO_QUERY_MTU | SSL.OP_NO_RENEGOTIATION)
+ ctx.set_options(SSL.OP_NO_QUERY_MTU | SSL.OP_NO_RENEGOTIATION) # type: ignore[attr-defined]
self._ssl = SSL.Connection(ctx)
- self._handshake_mtu = None
+ self._handshake_mtu = 0
# This calls self._ssl.set_ciphertext_mtu, which is important, because if you
# don't call it then openssl doesn't work.
self.set_ciphertext_mtu(best_guess_mtu(self.endpoint.socket))
self._replaced = False
self._closed = False
- self._q = _Queue(endpoint.incoming_packets_buffer)
+ self._q = _Queue[bytes](endpoint.incoming_packets_buffer)
self._handshake_lock = trio.Lock()
- self._record_encoder = RecordEncoder()
+ self._record_encoder: RecordEncoder = RecordEncoder()
+
+ self._final_volley: list[_AnyHandshakeMessage] = []
- def _set_replaced(self):
+ def _set_replaced(self) -> None:
self._replaced = True
# Any packets we already received could maybe possibly still be processed, but
# there are no more coming. So we close this on the sender side.
self._q.s.close()
- def _check_replaced(self):
+ def _check_replaced(self) -> None:
if self._replaced:
raise trio.BrokenResourceError(
"peer tore down this connection to start a new one"
@@ -836,7 +882,7 @@ def close(self) -> None:
# ClosedResourceError
self._q.r.close()
- def __enter__(self):
+ def __enter__(self) -> Self:
return self
def __exit__(
@@ -847,7 +893,7 @@ def __exit__(
) -> None:
return self.close()
- async def aclose(self):
+ async def aclose(self) -> None:
"""Close this connection, but asynchronously.
This is included to satisfy the `trio.abc.Channel` contract. It's
@@ -857,7 +903,7 @@ async def aclose(self):
self.close()
await trio.lowlevel.checkpoint()
- async def _send_volley(self, volley_messages):
+ async def _send_volley(self, volley_messages: list[_AnyHandshakeMessage]) -> None:
packets = self._record_encoder.encode_volley(
volley_messages, self._handshake_mtu
)
@@ -865,10 +911,10 @@ async def _send_volley(self, volley_messages):
async with self.endpoint._send_lock:
await self.endpoint.socket.sendto(packet, self.peer_address)
- async def _resend_final_volley(self):
+ async def _resend_final_volley(self) -> None:
await self._send_volley(self._final_volley)
- async def do_handshake(self, *, initial_retransmit_timeout=1.0):
+ async def do_handshake(self, *, initial_retransmit_timeout: float = 1.0) -> None:
"""Perform the handshake.
Calling this is optional – if you don't, then it will be automatically called
@@ -901,17 +947,19 @@ async def do_handshake(self, *, initial_retransmit_timeout=1.0):
return
timeout = initial_retransmit_timeout
- volley_messages = []
+ volley_messages: list[_AnyHandshakeMessage] = []
volley_failed_sends = 0
- def read_volley():
+ def read_volley() -> list[_AnyHandshakeMessage]:
volley_bytes = _read_loop(self._ssl.bio_read)
new_volley_messages = decode_volley_trusted(volley_bytes)
if (
new_volley_messages
and volley_messages
and isinstance(new_volley_messages[0], HandshakeMessage)
- and new_volley_messages[0].msg_seq == volley_messages[0].msg_seq
+ # TODO: add isinstance or do a cast?
+ and new_volley_messages[0].msg_seq
+ == cast(HandshakeMessage, volley_messages[0]).msg_seq
):
# openssl decided to retransmit; discard because we handle
# retransmits ourselves
@@ -995,10 +1043,13 @@ def read_volley():
# PMTU estimate is wrong? Let's try dropping it to the minimum
# and hope that helps.
self._handshake_mtu = min(
- self._handshake_mtu, worst_case_mtu(self.endpoint.socket)
+ self._handshake_mtu,
+ worst_case_mtu(self.endpoint.socket),
)
- async def send(self, data):
+ async def send(
+ self, data: bytes
+ ) -> None: # or str? SendChannel defines it as bytes
"""Send a packet of data, securely."""
if self._closed:
@@ -1014,7 +1065,7 @@ async def send(self, data):
_read_loop(self._ssl.bio_read), self.peer_address
)
- async def receive(self):
+ async def receive(self) -> bytes: # or str?
"""Fetch the next packet of data from this connection's peer, waiting if
necessary.
@@ -1040,7 +1091,7 @@ async def receive(self):
if cleartext:
return cleartext
- def set_ciphertext_mtu(self, new_mtu):
+ def set_ciphertext_mtu(self, new_mtu: int) -> None:
"""Tells Trio the `largest amount of data that can be sent in a single packet to
this peer `__.
@@ -1075,7 +1126,7 @@ def set_ciphertext_mtu(self, new_mtu):
self._handshake_mtu = new_mtu
self._ssl.set_ciphertext_mtu(new_mtu)
- def get_cleartext_mtu(self):
+ def get_cleartext_mtu(self) -> int:
"""Returns the largest number of bytes that you can pass in a single call to
`send` while still fitting within the network-level MTU.
@@ -1084,9 +1135,9 @@ def get_cleartext_mtu(self):
"""
if not self._did_handshake:
raise trio.NeedHandshakeError
- return self._ssl.get_cleartext_mtu()
+ return self._ssl.get_cleartext_mtu() # type: ignore[no-any-return]
- def statistics(self):
+ def statistics(self) -> DTLSChannelStatistics:
"""Returns an object with statistics about this connection.
Currently this has only one attribute:
@@ -1126,18 +1177,18 @@ class DTLSEndpoint(metaclass=Final):
"""
- def __init__(self, socket, *, incoming_packets_buffer=10):
+ def __init__(self, socket: _SocketType, *, incoming_packets_buffer: int = 10):
# We do this lazily on first construction, so only people who actually use DTLS
# have to install PyOpenSSL.
global SSL
from OpenSSL import SSL
- # TODO: create a `self._initialized` for `__del__`, so self.socket can be typed
- # as trio.socket.SocketType and `is not None` checks can be removed.
- self.socket = None # for __del__, in case the next line raises
+ # for __del__, in case the next line raises
+ self._initialized: bool = False
if socket.type != trio.socket.SOCK_DGRAM:
raise ValueError("DTLS requires a SOCK_DGRAM socket")
- self.socket = socket
+ self._initialized = True
+ self.socket: _SocketType = socket
self.incoming_packets_buffer = incoming_packets_buffer
self._token = trio.lowlevel.current_trio_token()
@@ -1146,15 +1197,15 @@ def __init__(self, socket, *, incoming_packets_buffer=10):
# as a peer provides a valid cookie, we can immediately tear down the
# old connection.
# {remote address: DTLSChannel}
- self._streams = weakref.WeakValueDictionary()
- self._listening_context = None
- self._listening_key = None
- self._incoming_connections_q = _Queue(float("inf"))
+ self._streams: weakref.WeakValueDictionary = weakref.WeakValueDictionary()
+ self._listening_context: Context | None = None
+ self._listening_key: bytes | None = None
+ self._incoming_connections_q = _Queue[DTLSChannel](float("inf"))
self._send_lock = trio.Lock()
self._closed = False
self._receive_loop_spawned = False
- def _ensure_receive_loop(self):
+ def _ensure_receive_loop(self) -> None:
# We have to spawn this lazily, because on Windows it will immediately error out
# if the socket isn't already bound -- which for clients might not happen until
# after we send our first packet.
@@ -1164,9 +1215,9 @@ def _ensure_receive_loop(self):
)
self._receive_loop_spawned = True
- def __del__(self):
+ def __del__(self) -> None:
# Do nothing if this object was never fully constructed
- if self.socket is None:
+ if not self._initialized:
return
# Close the socket in Trio context (if our Trio context still exists), so that
# the background task gets notified about the closure and can exit.
@@ -1186,17 +1237,13 @@ def close(self) -> None:
This object can also be used as a context manager.
"""
- # Do nothing if this object was never fully constructed
- if self.socket is None: # pragma: no cover
- return
-
self._closed = True
self.socket.close()
for stream in list(self._streams.values()):
stream.close()
self._incoming_connections_q.s.close()
- def __enter__(self):
+ def __enter__(self) -> Self:
return self
def __exit__(
@@ -1207,13 +1254,17 @@ def __exit__(
) -> None:
return self.close()
- def _check_closed(self):
+ def _check_closed(self) -> None:
if self._closed:
raise trio.ClosedResourceError
async def serve(
- self, ssl_context, async_fn, *args, task_status=trio.TASK_STATUS_IGNORED
- ):
+ self,
+ ssl_context: Context,
+ async_fn: Callable[[DTLSChannel], Awaitable],
+ *args: Any,
+ task_status: _TaskStatus = trio.TASK_STATUS_IGNORED,
+ ) -> None:
"""Listen for incoming connections, and spawn a handler for each using an
internal nursery.
@@ -1257,7 +1308,7 @@ async def handler(dtls_channel):
self._listening_context = ssl_context
task_status.started()
- async def handler_wrapper(stream):
+ async def handler_wrapper(stream: DTLSChannel) -> None:
with stream:
await async_fn(stream, *args)
@@ -1267,7 +1318,7 @@ async def handler_wrapper(stream):
finally:
self._listening_context = None
- def connect(self, address, ssl_context):
+ def connect(self, address: tuple[str, int], ssl_context: Context) -> DTLSChannel:
"""Initiate an outgoing DTLS connection.
Notice that this is a synchronous method. That's because it doesn't actually
diff --git a/trio/_tests/verify_types.json b/trio/_tests/verify_types.json
index 9d7d7aa912..cf1e7eccfb 100644
--- a/trio/_tests/verify_types.json
+++ b/trio/_tests/verify_types.json
@@ -45,9 +45,9 @@
}
],
"otherSymbolCounts": {
- "withAmbiguousType": 8,
- "withKnownType": 433,
- "withUnknownType": 135
+ "withAmbiguousType": 6,
+ "withKnownType": 460,
+ "withUnknownType": 129
},
"packageName": "trio",
"symbols": [
@@ -73,6 +73,8 @@
"trio._core._mock_clock.MockClock.jump",
"trio._core._run.Nursery.start",
"trio._core._run.Nursery.start_soon",
+ "trio._core._run._TaskStatus.__repr__",
+ "trio._core._run._TaskStatus.started",
"trio._core._unbounded_queue.UnboundedQueue.__aiter__",
"trio._core._unbounded_queue.UnboundedQueue.__anext__",
"trio._core._unbounded_queue.UnboundedQueue.__repr__",
@@ -81,22 +83,9 @@
"trio._core._unbounded_queue.UnboundedQueue.get_batch_nowait",
"trio._core._unbounded_queue.UnboundedQueue.qsize",
"trio._core._unbounded_queue.UnboundedQueue.statistics",
- "trio._dtls.DTLSChannel.__enter__",
"trio._dtls.DTLSChannel.__init__",
- "trio._dtls.DTLSChannel.aclose",
- "trio._dtls.DTLSChannel.do_handshake",
- "trio._dtls.DTLSChannel.get_cleartext_mtu",
- "trio._dtls.DTLSChannel.receive",
- "trio._dtls.DTLSChannel.send",
- "trio._dtls.DTLSChannel.set_ciphertext_mtu",
- "trio._dtls.DTLSChannel.statistics",
- "trio._dtls.DTLSEndpoint.__del__",
- "trio._dtls.DTLSEndpoint.__enter__",
"trio._dtls.DTLSEndpoint.__init__",
- "trio._dtls.DTLSEndpoint.connect",
- "trio._dtls.DTLSEndpoint.incoming_packets_buffer",
"trio._dtls.DTLSEndpoint.serve",
- "trio._dtls.DTLSEndpoint.socket",
"trio._highlevel_socket.SocketListener",
"trio._highlevel_socket.SocketListener.__init__",
"trio._highlevel_socket.SocketStream.__init__",
From 40ff89f65c22397c4ecae52be49fe5b7d5974b34 Mon Sep 17 00:00:00 2001
From: jakkdl
Date: Thu, 13 Jul 2023 16:51:33 +0200
Subject: [PATCH 2/8] ignore weird error with TASK_STATUS_IGNORED, add
pyOpenSSL to docs-requirements
---
docs-requirements.in | 3 +++
docs-requirements.txt | 8 ++++++++
trio/_dtls.py | 15 ++++++++++++++-
3 files changed, 25 insertions(+), 1 deletion(-)
diff --git a/docs-requirements.in b/docs-requirements.in
index 98d5030bc5..d6214ec1d0 100644
--- a/docs-requirements.in
+++ b/docs-requirements.in
@@ -19,3 +19,6 @@ exceptiongroup >= 1.0.0rc9
# See note in test-requirements.in
immutables >= 0.6
+
+# types used in annotations
+pyOpenSSL
diff --git a/docs-requirements.txt b/docs-requirements.txt
index 06136fd765..c607f4f186 100644
--- a/docs-requirements.txt
+++ b/docs-requirements.txt
@@ -16,6 +16,8 @@ babel==2.12.1
# via sphinx
certifi==2023.5.7
# via requests
+cffi==1.15.1
+ # via cryptography
charset-normalizer==3.1.0
# via requests
click==8.1.3
@@ -24,6 +26,8 @@ click==8.1.3
# towncrier
click-default-group==1.2.2
# via towncrier
+cryptography==41.0.2
+ # via pyopenssl
docutils==0.18.1
# via
# sphinx
@@ -55,8 +59,12 @@ outcome==1.2.0
# via -r docs-requirements.in
packaging==23.1
# via sphinx
+pycparser==2.21
+ # via cffi
pygments==2.15.1
# via sphinx
+pyopenssl==23.2.0
+ # via -r docs-requirements.in
pytz==2023.3
# via babel
requests==2.31.0
diff --git a/trio/_dtls.py b/trio/_dtls.py
index acc5f950eb..0af8340732 100644
--- a/trio/_dtls.py
+++ b/trio/_dtls.py
@@ -798,6 +798,19 @@ async def dtls_receive_loop(
@attr.frozen
class DTLSChannelStatistics:
+ """An object with statistics about this connection.
+
+ Currently this has only one attribute:
+
+ - ``incoming_packets_dropped_in_trio`` (``int``): Gives a count of the number of
+ incoming packets from this peer that Trio successfully received from the
+ network, but then got dropped because the internal channel buffer was full. If
+ this is non-zero, then you might want to call ``receive`` more often, or use a
+ larger ``incoming_packets_buffer``, or just not worry about it because your
+ UDP-based protocol should be able to handle the occasional lost packet, right?
+
+ """
+
incoming_packets_dropped_in_trio: int
@@ -1263,7 +1276,7 @@ async def serve(
ssl_context: Context,
async_fn: Callable[[DTLSChannel], Awaitable],
*args: Any,
- task_status: _TaskStatus = trio.TASK_STATUS_IGNORED,
+ task_status: _TaskStatus = trio.TASK_STATUS_IGNORED, # type: ignore[has-type]
) -> None:
"""Listen for incoming connections, and spawn a handler for each using an
internal nursery.
From 128a8d26945ee24ac6780b336c13a06c7846991e Mon Sep 17 00:00:00 2001
From: jakkdl
Date: Thu, 20 Jul 2023 13:48:44 +0200
Subject: [PATCH 3/8] fix RTD, and export DTLSChannelStatistics and TaskStatus
---
docs/source/conf.py | 4 ++++
docs/source/reference-core.rst | 1 +
docs/source/reference-io.rst | 2 ++
trio/__init__.py | 7 ++++++-
trio/_core/__init__.py | 1 +
trio/_core/_run.py | 8 ++++----
trio/_dtls.py | 4 ++--
trio/_tests/verify_types.json | 10 +++++-----
8 files changed, 25 insertions(+), 12 deletions(-)
diff --git a/docs/source/conf.py b/docs/source/conf.py
index 68a5a22a81..8efc702f02 100755
--- a/docs/source/conf.py
+++ b/docs/source/conf.py
@@ -63,6 +63,10 @@
("py:obj", "trio._abc.T"),
("py:obj", "trio._abc.T_resource"),
("py:class", "types.FrameType"),
+ # TODO: figure out if you can link this to SSL
+ ("py:class", "Context"),
+ # TODO: temporary type
+ ("py:class", "_SocketType"),
]
autodoc_inherit_docstrings = False
default_role = "obj"
diff --git a/docs/source/reference-core.rst b/docs/source/reference-core.rst
index f571d23294..434b8c8b5b 100644
--- a/docs/source/reference-core.rst
+++ b/docs/source/reference-core.rst
@@ -922,6 +922,7 @@ The nursery API
See :meth:`~Nursery.start`.
+.. autoclass:: TaskStatus
.. _task-local-storage:
diff --git a/docs/source/reference-io.rst b/docs/source/reference-io.rst
index a3291ef2ae..3ae66699e1 100644
--- a/docs/source/reference-io.rst
+++ b/docs/source/reference-io.rst
@@ -304,6 +304,8 @@ unfortunately that's not yet possible.
.. automethod:: statistics
+.. autoclass:: DTLSChannelStatistics
+
.. module:: trio.socket
Low-level networking with :mod:`trio.socket`
diff --git a/trio/__init__.py b/trio/__init__.py
index 2b8810504b..ac0687f529 100644
--- a/trio/__init__.py
+++ b/trio/__init__.py
@@ -34,6 +34,7 @@
EndOfChannel as EndOfChannel,
Nursery as Nursery,
RunFinishedError as RunFinishedError,
+ TaskStatus as TaskStatus,
TrioInternalError as TrioInternalError,
WouldBlock as WouldBlock,
current_effective_deadline as current_effective_deadline,
@@ -46,7 +47,11 @@
NonBaseMultiError as _NonBaseMultiError,
)
from ._deprecate import TrioDeprecationWarning as TrioDeprecationWarning
-from ._dtls import DTLSChannel as DTLSChannel, DTLSEndpoint as DTLSEndpoint
+from ._dtls import (
+ DTLSChannel as DTLSChannel,
+ DTLSChannelStatistics as DTLSChannelStatistics,
+ DTLSEndpoint as DTLSEndpoint,
+)
from ._file_io import open_file as open_file, wrap_file as wrap_file
from ._highlevel_generic import (
StapledStream as StapledStream,
diff --git a/trio/_core/__init__.py b/trio/_core/__init__.py
index abd58245e3..aa898fffe0 100644
--- a/trio/_core/__init__.py
+++ b/trio/_core/__init__.py
@@ -28,6 +28,7 @@
CancelScope,
Nursery,
Task,
+ TaskStatus,
add_instrument,
checkpoint,
checkpoint_if_cancelled,
diff --git a/trio/_core/_run.py b/trio/_core/_run.py
index 4f90889c5f..279061f872 100644
--- a/trio/_core/_run.py
+++ b/trio/_core/_run.py
@@ -783,7 +783,7 @@ def cancel_called(self) -> bool:
# This code needs to be read alongside the code from Nursery.start to make
# sense.
@attr.s(eq=False, hash=False, repr=False)
-class _TaskStatus:
+class TaskStatus:
_old_nursery = attr.ib()
_new_nursery = attr.ib()
_called_started = attr.ib(default=False)
@@ -1137,16 +1137,16 @@ async def async_fn(arg1, arg2, *, task_status=trio.TASK_STATUS_IGNORED):
try:
self._pending_starts += 1
async with open_nursery() as old_nursery:
- task_status = _TaskStatus(old_nursery, self)
+ task_status = TaskStatus(old_nursery, self)
thunk = functools.partial(async_fn, task_status=task_status)
task = GLOBAL_RUN_CONTEXT.runner.spawn_impl(
thunk, args, old_nursery, name
)
task._eventual_parent_nursery = self
- # Wait for either _TaskStatus.started or an exception to
+ # Wait for either TaskStatus.started or an exception to
# cancel this nursery:
# If we get here, then the child either got reparented or exited
- # normally. The complicated logic is all in _TaskStatus.started().
+ # normally. The complicated logic is all in TaskStatus.started().
# (Any exceptions propagate directly out of the above.)
if not task_status._called_started:
raise RuntimeError("child exited without calling task_status.started()")
diff --git a/trio/_dtls.py b/trio/_dtls.py
index 0af8340732..3b15c83b7e 100644
--- a/trio/_dtls.py
+++ b/trio/_dtls.py
@@ -42,7 +42,7 @@
from OpenSSL.SSL import Context
from typing_extensions import Self, TypeAlias
- from ._core._run import _TaskStatus
+ from ._core._run import TaskStatus
from ._socket import _SocketType
MAX_UDP_PACKET_SIZE = 65527
@@ -1276,7 +1276,7 @@ async def serve(
ssl_context: Context,
async_fn: Callable[[DTLSChannel], Awaitable],
*args: Any,
- task_status: _TaskStatus = trio.TASK_STATUS_IGNORED, # type: ignore[has-type]
+ task_status: TaskStatus = trio.TASK_STATUS_IGNORED, # type: ignore[has-type]
) -> None:
"""Listen for incoming connections, and spawn a handler for each using an
internal nursery.
diff --git a/trio/_tests/verify_types.json b/trio/_tests/verify_types.json
index cf1e7eccfb..65bfd6a301 100644
--- a/trio/_tests/verify_types.json
+++ b/trio/_tests/verify_types.json
@@ -7,11 +7,11 @@
"warningCount": 0
},
"typeCompleteness": {
- "completenessScore": 0.8764044943820225,
+ "completenessScore": 0.8752,
"exportedSymbolCounts": {
"withAmbiguousType": 1,
- "withKnownType": 546,
- "withUnknownType": 76
+ "withKnownType": 547,
+ "withUnknownType": 77
},
"ignoreUnknownTypesFromImports": true,
"missingClassDocStringCount": 1,
@@ -73,8 +73,8 @@
"trio._core._mock_clock.MockClock.jump",
"trio._core._run.Nursery.start",
"trio._core._run.Nursery.start_soon",
- "trio._core._run._TaskStatus.__repr__",
- "trio._core._run._TaskStatus.started",
+ "trio._core._run.TaskStatus.__repr__",
+ "trio._core._run.TaskStatus.started",
"trio._core._unbounded_queue.UnboundedQueue.__aiter__",
"trio._core._unbounded_queue.UnboundedQueue.__anext__",
"trio._core._unbounded_queue.UnboundedQueue.__repr__",
From 0e9aedd9de39bd3f413096ff416f6ec13e568c8e Mon Sep 17 00:00:00 2001
From: jakkdl
Date: Fri, 21 Jul 2023 12:38:56 +0200
Subject: [PATCH 4/8] update .gitattributes
---
.gitattributes | 1 +
1 file changed, 1 insertion(+)
diff --git a/.gitattributes b/.gitattributes
index 991065e069..3fd55705b6 100644
--- a/.gitattributes
+++ b/.gitattributes
@@ -2,3 +2,4 @@
trio/_core/_generated* linguist-generated=true
# Treat generated files as binary in git diff
trio/_core/_generated* -diff
+trio/_tests/verify_types.json merge=binary
From c5b43a0d7d02b45782b007aecb967777a43903a1 Mon Sep 17 00:00:00 2001
From: jakkdl
Date: Sat, 22 Jul 2023 00:26:06 +0200
Subject: [PATCH 5/8] fixes after review from ZacHD
---
docs/source/reference-core.rst | 1 +
docs/source/reference-io.rst | 1 +
trio/_dtls.py | 28 ++++++++--------------------
3 files changed, 10 insertions(+), 20 deletions(-)
diff --git a/docs/source/reference-core.rst b/docs/source/reference-core.rst
index 5f9381cbfc..980a3106e5 100644
--- a/docs/source/reference-core.rst
+++ b/docs/source/reference-core.rst
@@ -923,6 +923,7 @@ The nursery API
See :meth:`~Nursery.start`.
.. autoclass:: TaskStatus
+ :members:
.. _task-local-storage:
diff --git a/docs/source/reference-io.rst b/docs/source/reference-io.rst
index 3ae66699e1..9ad11b2c5a 100644
--- a/docs/source/reference-io.rst
+++ b/docs/source/reference-io.rst
@@ -305,6 +305,7 @@ unfortunately that's not yet possible.
.. automethod:: statistics
.. autoclass:: DTLSChannelStatistics
+ :members:
.. module:: trio.socket
diff --git a/trio/_dtls.py b/trio/_dtls.py
index 3b15c83b7e..7885b1ff21 100644
--- a/trio/_dtls.py
+++ b/trio/_dtls.py
@@ -798,9 +798,7 @@ async def dtls_receive_loop(
@attr.frozen
class DTLSChannelStatistics:
- """An object with statistics about this connection.
-
- Currently this has only one attribute:
+ """Currently this has only one attribute:
- ``incoming_packets_dropped_in_trio`` (``int``): Gives a count of the number of
incoming packets from this peer that Trio successfully received from the
@@ -1060,9 +1058,7 @@ def read_volley() -> list[_AnyHandshakeMessage]:
worst_case_mtu(self.endpoint.socket),
)
- async def send(
- self, data: bytes
- ) -> None: # or str? SendChannel defines it as bytes
+ async def send(self, data: bytes) -> None:
"""Send a packet of data, securely."""
if self._closed:
@@ -1078,7 +1074,7 @@ async def send(
_read_loop(self._ssl.bio_read), self.peer_address
)
- async def receive(self) -> bytes: # or str?
+ async def receive(self) -> bytes:
"""Fetch the next packet of data from this connection's peer, waiting if
necessary.
@@ -1151,18 +1147,7 @@ def get_cleartext_mtu(self) -> int:
return self._ssl.get_cleartext_mtu() # type: ignore[no-any-return]
def statistics(self) -> DTLSChannelStatistics:
- """Returns an object with statistics about this connection.
-
- Currently this has only one attribute:
-
- - ``incoming_packets_dropped_in_trio`` (``int``): Gives a count of the number of
- incoming packets from this peer that Trio successfully received from the
- network, but then got dropped because the internal channel buffer was full. If
- this is non-zero, then you might want to call ``receive`` more often, or use a
- larger ``incoming_packets_buffer``, or just not worry about it because your
- UDP-based protocol should be able to handle the occasional lost packet, right?
-
- """
+ """Returns a `DTLSChannelStatistics` object with statistics about this connection."""
return DTLSChannelStatistics(self._packets_dropped_in_trio)
@@ -1271,10 +1256,13 @@ def _check_closed(self) -> None:
if self._closed:
raise trio.ClosedResourceError
+ # async_fn cannot be typed with ParamSpec, since we don't accept
+ # kwargs. Can be typed with TypeVarTuple once it's fully supported
+ # in mypy.
async def serve(
self,
ssl_context: Context,
- async_fn: Callable[[DTLSChannel], Awaitable],
+ async_fn: Callable[[...], Awaitable],
*args: Any,
task_status: TaskStatus = trio.TASK_STATUS_IGNORED, # type: ignore[has-type]
) -> None:
From 58e4412e9c7f4e4b56dddc3f2d61b3d122e3b83a Mon Sep 17 00:00:00 2001
From: jakkdl
Date: Sun, 23 Jul 2023 23:26:06 +0200
Subject: [PATCH 6/8] fixes after review by a5rocks
---
pyproject.toml | 3 +++
trio/_dtls.py | 37 ++++++++++++++++++++-----------------
trio/_socket.py | 9 +++++++--
3 files changed, 30 insertions(+), 19 deletions(-)
diff --git a/pyproject.toml b/pyproject.toml
index 4fe96b06b6..3b14a075da 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -51,6 +51,9 @@ module = [
]
disallow_incomplete_defs = true
disallow_untyped_defs = true
+disallow_any_generics = true
+disallow_any_decorated = true
+disallow_subclassing_any = true
[tool.pytest.ini_options]
addopts = ["--strict-markers", "--strict-config"]
diff --git a/trio/_dtls.py b/trio/_dtls.py
index 7885b1ff21..6ba5f7931e 100644
--- a/trio/_dtls.py
+++ b/trio/_dtls.py
@@ -26,7 +26,6 @@
Iterator,
TypeVar,
Union,
- cast,
)
import attr
@@ -43,7 +42,7 @@
from typing_extensions import Self, TypeAlias
from ._core._run import TaskStatus
- from ._socket import _SocketType
+ from ._socket import Address, _SocketType
MAX_UDP_PACKET_SIZE = 65527
@@ -350,7 +349,7 @@ class OpaqueHandshakeMessage:
record: Record
-# for some reason doesn't work with |
+# Needs Union until <3.10 is dropped
_AnyHandshakeMessage: TypeAlias = Union[
HandshakeMessage, PseudoHandshakeMessage, OpaqueHandshakeMessage
]
@@ -564,7 +563,7 @@ def _signable(*fields: bytes) -> bytes:
def _make_cookie(
- key: bytes, salt: bytes, tick: int, address: Any, client_hello_bits: bytes
+ key: bytes, salt: bytes, tick: int, address: Address, client_hello_bits: bytes
) -> bytes:
assert len(salt) == SALT_BYTES
assert len(key) == KEY_BYTES
@@ -582,7 +581,7 @@ def _make_cookie(
def valid_cookie(
- key: bytes, cookie: bytes, address: Any, client_hello_bits: bytes
+ key: bytes, cookie: bytes, address: Address, client_hello_bits: bytes
) -> bool:
if len(cookie) > SALT_BYTES:
salt = cookie[:SALT_BYTES]
@@ -604,7 +603,7 @@ def valid_cookie(
def challenge_for(
- key: bytes, address: Any, epoch_seqno: int, client_hello_bits: bytes
+ key: bytes, address: Address, epoch_seqno: int, client_hello_bits: bytes
) -> bytes:
salt = os.urandom(SALT_BYTES)
tick = _current_cookie_tick()
@@ -665,7 +664,7 @@ def _read_loop(read_fn: Callable[[int], bytes]) -> bytes:
async def handle_client_hello_untrusted(
- endpoint: DTLSEndpoint, address: Any, packet: bytes
+ endpoint: DTLSEndpoint, address: Address, packet: bytes
) -> None:
if endpoint._listening_context is None:
return
@@ -776,7 +775,8 @@ async def dtls_receive_loop(
await stream._resend_final_volley()
else:
try:
- stream._q.s.send_nowait(packet)
+ # mypy for some reason cannot determine type of _q
+ stream._q.s.send_nowait(packet) # type:ignore[has-type]
except trio.WouldBlock:
stream._packets_dropped_in_trio += 1
else:
@@ -828,7 +828,7 @@ class DTLSChannel(trio.abc.Channel[bytes], metaclass=NoPublicConstructor):
"""
- def __init__(self, endpoint: DTLSEndpoint, peer_address: Any, ctx: Context):
+ def __init__(self, endpoint: DTLSEndpoint, peer_address: Address, ctx: Context):
self.endpoint = endpoint
self.peer_address = peer_address
self._packets_dropped_in_trio = 0
@@ -839,7 +839,12 @@ def __init__(self, endpoint: DTLSEndpoint, peer_address: Any, ctx: Context):
# OP_NO_RENEGOTIATION disables renegotiation, which is too complex for us to
# support and isn't useful anyway -- especially for DTLS where it's equivalent
# to just performing a new handshake.
- ctx.set_options(SSL.OP_NO_QUERY_MTU | SSL.OP_NO_RENEGOTIATION) # type: ignore[attr-defined]
+ ctx.set_options(
+ (
+ SSL.OP_NO_QUERY_MTU
+ | SSL.OP_NO_RENEGOTIATION # type: ignore[attr-defined]
+ )
+ )
self._ssl = SSL.Connection(ctx)
self._handshake_mtu = 0
# This calls self._ssl.set_ciphertext_mtu, which is important, because if you
@@ -968,9 +973,8 @@ def read_volley() -> list[_AnyHandshakeMessage]:
new_volley_messages
and volley_messages
and isinstance(new_volley_messages[0], HandshakeMessage)
- # TODO: add isinstance or do a cast?
- and new_volley_messages[0].msg_seq
- == cast(HandshakeMessage, volley_messages[0]).msg_seq
+ and isinstance(volley_messages[0], HandshakeMessage)
+ and new_volley_messages[0].msg_seq == volley_messages[0].msg_seq
):
# openssl decided to retransmit; discard because we handle
# retransmits ourselves
@@ -1054,8 +1058,7 @@ def read_volley() -> list[_AnyHandshakeMessage]:
# PMTU estimate is wrong? Let's try dropping it to the minimum
# and hope that helps.
self._handshake_mtu = min(
- self._handshake_mtu,
- worst_case_mtu(self.endpoint.socket),
+ self._handshake_mtu, worst_case_mtu(self.endpoint.socket)
)
async def send(self, data: bytes) -> None:
@@ -1195,7 +1198,7 @@ def __init__(self, socket: _SocketType, *, incoming_packets_buffer: int = 10):
# as a peer provides a valid cookie, we can immediately tear down the
# old connection.
# {remote address: DTLSChannel}
- self._streams: weakref.WeakValueDictionary = weakref.WeakValueDictionary()
+ self._streams = weakref.WeakValueDictionary[Address, DTLSChannel]()
self._listening_context: Context | None = None
self._listening_key: bytes | None = None
self._incoming_connections_q = _Queue[DTLSChannel](float("inf"))
@@ -1262,7 +1265,7 @@ def _check_closed(self) -> None:
async def serve(
self,
ssl_context: Context,
- async_fn: Callable[[...], Awaitable],
+ async_fn: Callable[..., Awaitable[object]],
*args: Any,
task_status: TaskStatus = trio.TASK_STATUS_IGNORED, # type: ignore[has-type]
) -> None:
diff --git a/trio/_socket.py b/trio/_socket.py
index 659f844078..26b03fc3e0 100644
--- a/trio/_socket.py
+++ b/trio/_socket.py
@@ -5,7 +5,7 @@
import socket as _stdlib_socket
import sys
from functools import wraps as _wraps
-from typing import TYPE_CHECKING
+from typing import TYPE_CHECKING, Tuple, Union
import idna as _idna
@@ -17,7 +17,12 @@
from collections.abc import Iterable
from types import TracebackType
- from typing_extensions import Self
+ from typing_extensions import Self, TypeAlias
+
+# must use old-style typing because it's evaluated at runtime
+Address: TypeAlias = Union[
+ str, bytes, Tuple[str, int], Tuple[str, int, int], Tuple[str, int, int, int]
+]
# Usage:
From eda238b1feb919c01740d701831a7568e6a50173 Mon Sep 17 00:00:00 2001
From: jakkdl
Date: Sun, 23 Jul 2023 23:40:33 +0200
Subject: [PATCH 7/8] oopsies
---
trio/_dtls.py | 5 +++--
1 file changed, 3 insertions(+), 2 deletions(-)
diff --git a/trio/_dtls.py b/trio/_dtls.py
index 6ba5f7931e..e8888d7871 100644
--- a/trio/_dtls.py
+++ b/trio/_dtls.py
@@ -27,6 +27,7 @@
TypeVar,
Union,
)
+from weakref import ReferenceType, WeakValueDictionary
import attr
from OpenSSL import SSL
@@ -739,7 +740,7 @@ async def handle_client_hello_untrusted(
async def dtls_receive_loop(
- endpoint_ref: weakref.ReferenceType[DTLSEndpoint], sock: _SocketType
+ endpoint_ref: ReferenceType[DTLSEndpoint], sock: _SocketType
) -> None:
try:
while True:
@@ -1198,7 +1199,7 @@ def __init__(self, socket: _SocketType, *, incoming_packets_buffer: int = 10):
# as a peer provides a valid cookie, we can immediately tear down the
# old connection.
# {remote address: DTLSChannel}
- self._streams = weakref.WeakValueDictionary[Address, DTLSChannel]()
+ self._streams: WeakValueDictionary[Address, DTLSChannel] = WeakValueDictionary()
self._listening_context: Context | None = None
self._listening_key: bytes | None = None
self._incoming_connections_q = _Queue[DTLSChannel](float("inf"))
From 3da4ff619efbe9025f780b6110a0eac97ad4b2ef Mon Sep 17 00:00:00 2001
From: jakkdl
Date: Wed, 26 Jul 2023 13:12:53 +0200
Subject: [PATCH 8/8] minor nitpicks from a5rocks fixed
---
test-requirements.in | 2 +-
trio/_dtls.py | 7 +++----
2 files changed, 4 insertions(+), 5 deletions(-)
diff --git a/test-requirements.in b/test-requirements.in
index 03997ad2e7..23f128f99a 100644
--- a/test-requirements.in
+++ b/test-requirements.in
@@ -13,7 +13,7 @@ cryptography>=41.0.0 # cryptography<41 segfaults on pypy3.10
# Tools
black; implementation_name == "cpython"
mypy; implementation_name == "cpython"
-types-pyOpenSSL; implementation_name == "cpython"
+types-pyOpenSSL; implementation_name == "cpython" # and annotations
flake8
flake8-pyproject
astor # code generation
diff --git a/trio/_dtls.py b/trio/_dtls.py
index e8888d7871..8675cb75b6 100644
--- a/trio/_dtls.py
+++ b/trio/_dtls.py
@@ -350,7 +350,6 @@ class OpaqueHandshakeMessage:
record: Record
-# Needs Union until <3.10 is dropped
_AnyHandshakeMessage: TypeAlias = Union[
HandshakeMessage, PseudoHandshakeMessage, OpaqueHandshakeMessage
]
@@ -645,12 +644,12 @@ def challenge_for(
return packet
-T = TypeVar("T")
+_T = TypeVar("_T")
-class _Queue(Generic[T]):
+class _Queue(Generic[_T]):
def __init__(self, incoming_packets_buffer: int | float):
- self.s, self.r = trio.open_memory_channel[T](incoming_packets_buffer)
+ self.s, self.r = trio.open_memory_channel[_T](incoming_packets_buffer)
def _read_loop(read_fn: Callable[[int], bytes]) -> bytes: