Non puoi selezionare più di 25 argomenti Gli argomenti devono iniziare con una lettera o un numero, possono includere trattini ('-') e possono essere lunghi fino a 35 caratteri.
 
 
 
 

188 righe
6.4 KiB

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