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 1c1b89e873..9f7794f2e8 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.2.0 # via requests click==8.1.5 @@ -24,6 +26,8 @@ click==8.1.5 # 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/docs/source/conf.py b/docs/source/conf.py index cc9f63c4c9..91ce7d884c 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"), # these are not defined in https://docs.python.org/3/objects.inv ("py:class", "socket.AddressFamily"), ("py:class", "socket.SocketKind"), diff --git a/docs/source/reference-core.rst b/docs/source/reference-core.rst index 26554af558..980a3106e5 100644 --- a/docs/source/reference-core.rst +++ b/docs/source/reference-core.rst @@ -922,6 +922,8 @@ 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 a3291ef2ae..9ad11b2c5a 100644 --- a/docs/source/reference-io.rst +++ b/docs/source/reference-io.rst @@ -304,6 +304,9 @@ unfortunately that's not yet possible. .. automethod:: statistics +.. autoclass:: DTLSChannelStatistics + :members: + .. module:: trio.socket Low-level networking with :mod:`trio.socket` diff --git a/pyproject.toml b/pyproject.toml index 280ba165b4..3b14a075da 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -46,10 +46,14 @@ disallow_untyped_defs = false [[tool.mypy.overrides]] module = [ + "trio._dtls", "trio._abc" ] 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/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/__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/_channel.py b/trio/_channel.py index f77950c4e4..c8d27695b8 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/_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..ce8feb2827 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(metaclass=Final): _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 722a9499f8..8675cb75b6 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, +) +from weakref import ReferenceType, WeakValueDictionary 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 Address, _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,19 @@ class OpaqueHandshakeMessage: record: Record +_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 +406,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 +548,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 +562,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: Address, client_hello_bits: bytes +) -> bytes: assert len(salt) == SALT_BYTES assert len(key) == KEY_BYTES @@ -548,7 +580,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: Address, client_hello_bits: bytes +) -> bool: if len(cookie) > SALT_BYTES: salt = cookie[:SALT_BYTES] @@ -568,7 +602,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: Address, 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 +644,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") -def _read_loop(read_fn): +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: Callable[[int], bytes]) -> bytes: chunks = [] while True: try: @@ -624,7 +663,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: Address, packet: bytes +) -> None: if endpoint._listening_context is None: return @@ -697,7 +738,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: ReferenceType[DTLSEndpoint], sock: _SocketType +) -> None: try: while True: try: @@ -732,7 +775,8 @@ async def dtls_receive_loop(endpoint_ref, sock): 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: @@ -754,6 +798,17 @@ async def dtls_receive_loop(endpoint_ref, sock): @attr.frozen class DTLSChannelStatistics: + """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 @@ -773,7 +828,7 @@ class DTLSChannel(trio.abc.Channel[bytes], metaclass=NoPublicConstructor): """ - def __init__(self, endpoint, peer_address, ctx): + def __init__(self, endpoint: DTLSEndpoint, peer_address: Address, ctx: Context): self.endpoint = endpoint self.peer_address = peer_address self._packets_dropped_in_trio = 0 @@ -784,25 +839,32 @@ 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 +898,7 @@ def close(self) -> None: # ClosedResourceError self._q.r.close() - def __enter__(self): + def __enter__(self) -> Self: return self def __exit__( @@ -847,7 +909,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 +919,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 +927,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,16 +963,17 @@ 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 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 @@ -998,7 +1061,7 @@ def read_volley(): self._handshake_mtu, worst_case_mtu(self.endpoint.socket) ) - async def send(self, data): + async def send(self, data: bytes) -> None: """Send a packet of data, securely.""" if self._closed: @@ -1014,7 +1077,7 @@ async def send(self, data): _read_loop(self._ssl.bio_read), self.peer_address ) - async def receive(self): + async def receive(self) -> bytes: """Fetch the next packet of data from this connection's peer, waiting if necessary. @@ -1040,7 +1103,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 +1138,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,21 +1147,10 @@ def get_cleartext_mtu(self): """ if not self._did_handshake: raise trio.NeedHandshakeError - return self._ssl.get_cleartext_mtu() - - def statistics(self): - """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? + return self._ssl.get_cleartext_mtu() # type: ignore[no-any-return] - """ + def statistics(self) -> DTLSChannelStatistics: + """Returns a `DTLSChannelStatistics` object with statistics about this connection.""" return DTLSChannelStatistics(self._packets_dropped_in_trio) @@ -1126,18 +1178,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 +1198,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: WeakValueDictionary[Address, DTLSChannel] = 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 +1216,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 +1238,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 +1255,20 @@ def __exit__( ) -> None: return self.close() - def _check_closed(self): + 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, async_fn, *args, task_status=trio.TASK_STATUS_IGNORED - ): + self, + ssl_context: Context, + async_fn: Callable[..., Awaitable[object]], + *args: Any, + 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. @@ -1257,7 +1312,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 +1322,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/_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: diff --git a/trio/_tests/verify_types.json b/trio/_tests/verify_types.json index c506eb6d8f..ba26a34e9f 100644 --- a/trio/_tests/verify_types.json +++ b/trio/_tests/verify_types.json @@ -7,11 +7,11 @@ "warningCount": 0 }, "typeCompleteness": { - "completenessScore": 0.884430176565008, + "completenessScore": 0.8832, "exportedSymbolCounts": { "withAmbiguousType": 1, - "withKnownType": 551, - "withUnknownType": 71 + "withKnownType": 552, + "withUnknownType": 72 }, "ignoreUnknownTypesFromImports": true, "missingClassDocStringCount": 1, @@ -45,9 +45,9 @@ } ], "otherSymbolCounts": { - "withAmbiguousType": 8, - "withKnownType": 448, - "withUnknownType": 120 + "withAmbiguousType": 6, + "withKnownType": 475, + "withUnknownType": 114 }, "packageName": "trio", "symbols": [ @@ -61,6 +61,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__", @@ -69,22 +71,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.__init__", "trio._highlevel_socket.SocketStream.__init__", "trio._highlevel_socket.SocketStream.getsockopt",