_streams.py 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237
  1. from __future__ import annotations
  2. from abc import ABCMeta, abstractmethod
  3. from collections.abc import Callable
  4. from typing import TYPE_CHECKING, Any, Generic, TypeAlias, TypeVar
  5. from .._core._exceptions import EndOfStream
  6. from .._core._typedattr import TypedAttributeProvider
  7. from ._resources import AsyncResource
  8. if TYPE_CHECKING:
  9. from ._tasks import TaskGroup
  10. T_Item = TypeVar("T_Item")
  11. T_co = TypeVar("T_co", covariant=True)
  12. T_contra = TypeVar("T_contra", contravariant=True)
  13. class UnreliableObjectReceiveStream(
  14. AsyncResource, TypedAttributeProvider, Generic[T_co]
  15. ):
  16. """
  17. An interface for receiving objects.
  18. This interface makes no guarantees that the received messages arrive in the order in
  19. which they were sent, or that no messages are missed.
  20. Asynchronously iterating over objects of this type will yield objects matching the
  21. given type parameter.
  22. """
  23. def __aiter__(self) -> UnreliableObjectReceiveStream[T_co]:
  24. return self
  25. async def __anext__(self) -> T_co:
  26. try:
  27. return await self.receive()
  28. except EndOfStream:
  29. raise StopAsyncIteration from None
  30. @abstractmethod
  31. async def receive(self) -> T_co:
  32. """
  33. Receive the next item.
  34. :raises ~anyio.ClosedResourceError: if the receive stream has been explicitly
  35. closed
  36. :raises ~anyio.EndOfStream: if this stream has been closed from the other end
  37. :raises ~anyio.BrokenResourceError: if this stream has been rendered unusable
  38. due to external causes
  39. """
  40. class UnreliableObjectSendStream(
  41. AsyncResource, TypedAttributeProvider, Generic[T_contra]
  42. ):
  43. """
  44. An interface for sending objects.
  45. This interface makes no guarantees that the messages sent will reach the
  46. recipient(s) in the same order in which they were sent, or at all.
  47. """
  48. @abstractmethod
  49. async def send(self, item: T_contra) -> None:
  50. """
  51. Send an item to the peer(s).
  52. :param item: the item to send
  53. :raises ~anyio.ClosedResourceError: if the send stream has been explicitly
  54. closed
  55. :raises ~anyio.BrokenResourceError: if this stream has been rendered unusable
  56. due to external causes
  57. """
  58. class UnreliableObjectStream(
  59. UnreliableObjectReceiveStream[T_Item], UnreliableObjectSendStream[T_Item]
  60. ):
  61. """
  62. A bidirectional message stream which does not guarantee the order or reliability of
  63. message delivery.
  64. """
  65. class ObjectReceiveStream(UnreliableObjectReceiveStream[T_co]):
  66. """
  67. A receive message stream which guarantees that messages are received in the same
  68. order in which they were sent, and that no messages are missed.
  69. """
  70. class ObjectSendStream(UnreliableObjectSendStream[T_contra]):
  71. """
  72. A send message stream which guarantees that messages are delivered in the same order
  73. in which they were sent, without missing any messages in the middle.
  74. """
  75. class ObjectStream(
  76. ObjectReceiveStream[T_Item],
  77. ObjectSendStream[T_Item],
  78. UnreliableObjectStream[T_Item],
  79. ):
  80. """
  81. A bidirectional message stream which guarantees the order and reliability of message
  82. delivery.
  83. """
  84. @abstractmethod
  85. async def send_eof(self) -> None:
  86. """
  87. Send an end-of-file indication to the peer.
  88. You should not try to send any further data to this stream after calling this
  89. method. This method is idempotent (does nothing on successive calls).
  90. """
  91. class ByteReceiveStream(AsyncResource, TypedAttributeProvider):
  92. """
  93. An interface for receiving bytes from a single peer.
  94. Iterating this byte stream will yield a byte string of arbitrary length, but no more
  95. than 65536 bytes.
  96. """
  97. def __aiter__(self) -> ByteReceiveStream:
  98. return self
  99. async def __anext__(self) -> bytes:
  100. try:
  101. return await self.receive()
  102. except EndOfStream:
  103. raise StopAsyncIteration from None
  104. @abstractmethod
  105. async def receive(self, max_bytes: int = 65536) -> bytes:
  106. """
  107. Receive at most ``max_bytes`` bytes from the peer.
  108. .. note:: Implementers of this interface should not return an empty
  109. :class:`bytes` object, and users should ignore them.
  110. :param max_bytes: maximum number of bytes to receive (must be a positive
  111. integer)
  112. :return: the received bytes
  113. :raises ValueError: if ``max_bytes`` is less than 1
  114. :raises ~anyio.EndOfStream: if this stream has been closed from the other end
  115. """
  116. class ByteSendStream(AsyncResource, TypedAttributeProvider):
  117. """An interface for sending bytes to a single peer."""
  118. @abstractmethod
  119. async def send(self, item: bytes) -> None:
  120. """
  121. Send the given bytes to the peer.
  122. :param item: the bytes to send
  123. """
  124. class ByteStream(ByteReceiveStream, ByteSendStream):
  125. """A bidirectional byte stream."""
  126. @abstractmethod
  127. async def send_eof(self) -> None:
  128. """
  129. Send an end-of-file indication to the peer.
  130. You should not try to send any further data to this stream after calling this
  131. method. This method is idempotent (does nothing on successive calls).
  132. """
  133. #: Type alias for all unreliable bytes-oriented receive streams.
  134. AnyUnreliableByteReceiveStream: TypeAlias = (
  135. UnreliableObjectReceiveStream[bytes] | ByteReceiveStream
  136. )
  137. #: Type alias for all unreliable bytes-oriented send streams.
  138. AnyUnreliableByteSendStream: TypeAlias = (
  139. UnreliableObjectSendStream[bytes] | ByteSendStream
  140. )
  141. #: Type alias for all unreliable bytes-oriented streams.
  142. AnyUnreliableByteStream: TypeAlias = UnreliableObjectStream[bytes] | ByteStream
  143. #: Type alias for all bytes-oriented receive streams.
  144. AnyByteReceiveStream: TypeAlias = ObjectReceiveStream[bytes] | ByteReceiveStream
  145. #: Type alias for all bytes-oriented send streams.
  146. AnyByteSendStream: TypeAlias = ObjectSendStream[bytes] | ByteSendStream
  147. #: Type alias for all bytes-oriented streams.
  148. AnyByteStream: TypeAlias = ObjectStream[bytes] | ByteStream
  149. class Listener(AsyncResource, TypedAttributeProvider, Generic[T_co]):
  150. """An interface for objects that let you accept incoming connections."""
  151. @abstractmethod
  152. async def serve(
  153. self, handler: Callable[[T_co], Any], task_group: TaskGroup | None = None
  154. ) -> None:
  155. """
  156. Accept incoming connections as they come in and start tasks to handle them.
  157. :param handler: a callable that will be used to handle each accepted connection
  158. :param task_group: the task group that will be used to start tasks for handling
  159. each accepted connection (if omitted, an ad-hoc task group will be created)
  160. """
  161. class ObjectStreamConnectable(Generic[T_co], metaclass=ABCMeta):
  162. @abstractmethod
  163. async def connect(self) -> ObjectStream[T_co]:
  164. """
  165. Connect to the remote endpoint.
  166. :return: an object stream connected to the remote end
  167. :raises ConnectionFailed: if the connection fails
  168. """
  169. class ByteStreamConnectable(metaclass=ABCMeta):
  170. @abstractmethod
  171. async def connect(self) -> ByteStream:
  172. """
  173. Connect to the remote endpoint.
  174. :return: a bytestream connected to the remote end
  175. :raises ConnectionFailed: if the connection fails
  176. """
  177. #: Type alias for all connectables returning bytestreams or bytes-oriented object streams
  178. AnyByteStreamConnectable: TypeAlias = (
  179. ObjectStreamConnectable[bytes] | ByteStreamConnectable
  180. )