Debian Codegraph @

src/trio/_highlevel_generic.py

raw
1 from __future__ import annotations
2
3 from typing import Generic, TypeGuard, TypeVar
4
5 import attrs
6
7 import trio
8 from trio._util import final
9
10 from .abc import AsyncResource, HalfCloseableStream, ReceiveStream, SendStream
11
12 SendStreamT = TypeVar("SendStreamT", bound=SendStream)
13 ReceiveStreamT = TypeVar("ReceiveStreamT", bound=ReceiveStream)
14
15
16 async def aclose_forcefully(resource: AsyncResource) -> None:
17 """Close an async resource or async generator immediately, without
18 blocking to do any graceful cleanup.
19
20 :class:`~trio.abc.AsyncResource` objects guarantee that if their
21 :meth:`~trio.abc.AsyncResource.aclose` method is cancelled, then they will
22 still close the resource (albeit in a potentially ungraceful
23 fashion). :func:`aclose_forcefully` is a convenience function that
24 exploits this behavior to let you force a resource to be closed without
25 blocking: it works by calling ``await resource.aclose()`` and then
26 cancelling it immediately.
27
28 Most users won't need this, but it may be useful on cleanup paths where
29 you can't afford to block, or if you want to close a resource and don't
30 care about handling it gracefully. For example, if
31 :class:`~trio.SSLStream` encounters an error and cannot perform its
32 own graceful close, then there's no point in waiting to gracefully shut
33 down the underlying transport either, so it calls ``await
34 aclose_forcefully(self.transport_stream)``.
35
36 Note that this function is async, and that it acts as a checkpoint, but
37 unlike most async functions it cannot block indefinitely (at least,
38 assuming the underlying resource object is correctly implemented).
39
40 """
41 with trio.CancelScope() as cs:
42 cs.cancel(reason="cancelled during aclose_forcefully")
43 await resource.aclose()
44
45
46 def _is_halfclosable(stream: SendStream) -> TypeGuard[HalfCloseableStream]:
47 """Check if the stream has a send_eof() method."""
48 return hasattr(stream, "send_eof")
49
50
51 @final
52 @attrs.define(eq=False, slots=False)
53 class StapledStream(
54 HalfCloseableStream,
55 Generic[SendStreamT, ReceiveStreamT],
56 ):
57 """This class `staples <https://en.wikipedia.org/wiki/Staple_(fastener)>`__
58 together two unidirectional streams to make single bidirectional stream.
59
60 Args:
61 send_stream (~trio.abc.SendStream): The stream to use for sending.
62 receive_stream (~trio.abc.ReceiveStream): The stream to use for
63 receiving.
64
65 Example:
66
67 A silly way to make a stream that echoes back whatever you write to
68 it::
69
70 left, right = trio.testing.memory_stream_pair()
71 echo_stream = StapledStream(SocketStream(left), SocketStream(right))
72 await echo_stream.send_all(b"x")
73 assert await echo_stream.receive_some() == b"x"
74
75 :class:`StapledStream` objects implement the methods in the
76 :class:`~trio.abc.HalfCloseableStream` interface. They also have two
77 additional public attributes:
78
79 .. attribute:: send_stream
80
81 The underlying :class:`~trio.abc.SendStream`. :meth:`send_all` and
82 :meth:`wait_send_all_might_not_block` are delegated to this object.
83
84 .. attribute:: receive_stream
85
86 The underlying :class:`~trio.abc.ReceiveStream`. :meth:`receive_some`
87 is delegated to this object.
88
89 """
90
91 send_stream: SendStreamT
92 receive_stream: ReceiveStreamT
93
94 async def send_all(self, data: bytes | bytearray | memoryview) -> None:
95 """Calls ``self.send_stream.send_all``."""
96 return await self.send_stream.send_all(data)
97
98 async def wait_send_all_might_not_block(self) -> None:
99 """Calls ``self.send_stream.wait_send_all_might_not_block``."""
100 return await self.send_stream.wait_send_all_might_not_block()
101
102 async def send_eof(self) -> None:
103 """Shuts down the send side of the stream.
104
105 If :meth:`self.send_stream.send_eof() <trio.abc.HalfCloseableStream.send_eof>` exists,
106 then this calls it. Otherwise, this calls
107 :meth:`self.send_stream.aclose() <trio.abc.AsyncResource.aclose>`.
108 """
109 stream = self.send_stream
110 if _is_halfclosable(stream):
111 return await stream.send_eof()
112 else:
113 return await stream.aclose()
114
115 # we intentionally accept more types from the caller than we support returning
116 async def receive_some(self, max_bytes: int | None = None) -> bytes | bytearray:
117 """Calls ``self.receive_stream.receive_some``."""
118 return await self.receive_stream.receive_some(max_bytes)
119
120 async def aclose(self) -> None:
121 """Calls ``aclose`` on both underlying streams."""
122 try:
123 await self.send_stream.aclose()
124 finally:
125 await self.receive_stream.aclose()