memory.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326
  1. from __future__ import annotations
  2. __all__ = (
  3. "MemoryObjectReceiveStream",
  4. "MemoryObjectSendStream",
  5. "MemoryObjectStreamStatistics",
  6. )
  7. import warnings
  8. from collections import OrderedDict, deque
  9. from dataclasses import dataclass, field
  10. from types import TracebackType
  11. from typing import Generic, NamedTuple, TypeVar
  12. from .. import (
  13. BrokenResourceError,
  14. ClosedResourceError,
  15. EndOfStream,
  16. WouldBlock,
  17. )
  18. from .._core._synchronization import Event
  19. from .._core._testing import TaskInfo, get_current_task
  20. from ..abc import ObjectReceiveStream, ObjectSendStream
  21. from ..lowlevel import checkpoint
  22. T_Item = TypeVar("T_Item")
  23. T_co = TypeVar("T_co", covariant=True)
  24. T_contra = TypeVar("T_contra", contravariant=True)
  25. class MemoryObjectStreamStatistics(NamedTuple):
  26. current_buffer_used: int #: number of items stored in the buffer
  27. #: maximum number of items that can be stored on this stream (or :data:`math.inf`)
  28. max_buffer_size: float
  29. open_send_streams: int #: number of unclosed clones of the send stream
  30. open_receive_streams: int #: number of unclosed clones of the receive stream
  31. #: number of tasks blocked on :meth:`MemoryObjectSendStream.send`
  32. tasks_waiting_send: int
  33. #: number of tasks blocked on :meth:`MemoryObjectReceiveStream.receive`
  34. tasks_waiting_receive: int
  35. @dataclass(eq=False)
  36. class _MemoryObjectItemReceiver(Generic[T_Item]):
  37. task_info: TaskInfo = field(init=False, default_factory=get_current_task)
  38. item: T_Item = field(init=False)
  39. def __repr__(self) -> str:
  40. # When item is not defined, we get following error with default __repr__:
  41. # AttributeError: 'MemoryObjectItemReceiver' object has no attribute 'item'
  42. item = getattr(self, "item", None)
  43. return f"{self.__class__.__name__}(task_info={self.task_info}, item={item!r})"
  44. @dataclass(eq=False)
  45. class _MemoryObjectStreamState(Generic[T_Item]):
  46. max_buffer_size: float = field()
  47. buffer: deque[T_Item] = field(init=False, default_factory=deque)
  48. open_send_channels: int = field(init=False, default=0)
  49. open_receive_channels: int = field(init=False, default=0)
  50. waiting_receivers: OrderedDict[Event, _MemoryObjectItemReceiver[T_Item]] = field(
  51. init=False, default_factory=OrderedDict
  52. )
  53. waiting_senders: OrderedDict[Event, T_Item] = field(
  54. init=False, default_factory=OrderedDict
  55. )
  56. def statistics(self) -> MemoryObjectStreamStatistics:
  57. return MemoryObjectStreamStatistics(
  58. len(self.buffer),
  59. self.max_buffer_size,
  60. self.open_send_channels,
  61. self.open_receive_channels,
  62. len(self.waiting_senders),
  63. len(self.waiting_receivers),
  64. )
  65. @dataclass(eq=False)
  66. class MemoryObjectReceiveStream(Generic[T_co], ObjectReceiveStream[T_co]):
  67. _state: _MemoryObjectStreamState[T_co]
  68. _closed: bool = field(init=False, default=False)
  69. def __post_init__(self) -> None:
  70. self._state.open_receive_channels += 1
  71. def receive_nowait(self) -> T_co:
  72. """
  73. Receive the next item if it can be done without waiting.
  74. :return: the received item
  75. :raises ~anyio.ClosedResourceError: if this send stream has been closed
  76. :raises ~anyio.EndOfStream: if the buffer is empty and this stream has been
  77. closed from the sending end
  78. :raises ~anyio.WouldBlock: if there are no items in the buffer and no tasks
  79. waiting to send
  80. """
  81. if self._closed:
  82. raise ClosedResourceError
  83. if self._state.waiting_senders:
  84. # Get the item from the next sender
  85. send_event, item = self._state.waiting_senders.popitem(last=False)
  86. self._state.buffer.append(item)
  87. send_event.set()
  88. if self._state.buffer:
  89. return self._state.buffer.popleft()
  90. elif not self._state.open_send_channels:
  91. raise EndOfStream
  92. raise WouldBlock
  93. async def receive(self) -> T_co:
  94. await checkpoint()
  95. try:
  96. return self.receive_nowait()
  97. except WouldBlock:
  98. # Add ourselves in the queue
  99. receive_event = Event()
  100. receiver = _MemoryObjectItemReceiver[T_co]()
  101. self._state.waiting_receivers[receive_event] = receiver
  102. try:
  103. await receive_event.wait()
  104. finally:
  105. self._state.waiting_receivers.pop(receive_event, None)
  106. try:
  107. return receiver.item
  108. except AttributeError:
  109. raise EndOfStream from None
  110. def clone(self) -> MemoryObjectReceiveStream[T_co]:
  111. """
  112. Create a clone of this receive stream.
  113. Each clone can be closed separately. Only when all clones have been closed will
  114. the receiving end of the memory stream be considered closed by the sending ends.
  115. :return: the cloned stream
  116. """
  117. if self._closed:
  118. raise ClosedResourceError
  119. return MemoryObjectReceiveStream(_state=self._state)
  120. def close(self) -> None:
  121. """
  122. Close the stream.
  123. This works the exact same way as :meth:`aclose`, but is provided as a special
  124. case for the benefit of synchronous callbacks.
  125. """
  126. if not self._closed:
  127. self._closed = True
  128. self._state.open_receive_channels -= 1
  129. if self._state.open_receive_channels == 0:
  130. send_events = list(self._state.waiting_senders.keys())
  131. for event in send_events:
  132. event.set()
  133. async def aclose(self) -> None:
  134. self.close()
  135. def statistics(self) -> MemoryObjectStreamStatistics:
  136. """
  137. Return statistics about the current state of this stream.
  138. .. versionadded:: 3.0
  139. """
  140. return self._state.statistics()
  141. def __enter__(self) -> MemoryObjectReceiveStream[T_co]:
  142. return self
  143. def __exit__(
  144. self,
  145. exc_type: type[BaseException] | None,
  146. exc_val: BaseException | None,
  147. exc_tb: TracebackType | None,
  148. ) -> None:
  149. self.close()
  150. def __del__(self) -> None:
  151. if not self._closed:
  152. warnings.warn(
  153. f"Unclosed <{self.__class__.__name__} at {id(self):x}>",
  154. ResourceWarning,
  155. stacklevel=1,
  156. source=self,
  157. )
  158. @dataclass(eq=False)
  159. class MemoryObjectSendStream(Generic[T_contra], ObjectSendStream[T_contra]):
  160. _state: _MemoryObjectStreamState[T_contra]
  161. _closed: bool = field(init=False, default=False)
  162. def __post_init__(self) -> None:
  163. self._state.open_send_channels += 1
  164. def send_nowait(self, item: T_contra) -> None:
  165. """
  166. Send an item immediately if it can be done without waiting.
  167. :param item: the item to send
  168. :raises ~anyio.ClosedResourceError: if this send stream has been closed
  169. :raises ~anyio.BrokenResourceError: if the stream has been closed from the
  170. receiving end
  171. :raises ~anyio.WouldBlock: if the buffer is full and there are no tasks waiting
  172. to receive
  173. """
  174. if self._closed:
  175. raise ClosedResourceError
  176. if not self._state.open_receive_channels:
  177. raise BrokenResourceError
  178. while self._state.waiting_receivers:
  179. receive_event, receiver = self._state.waiting_receivers.popitem(last=False)
  180. if not receiver.task_info.has_pending_cancellation():
  181. receiver.item = item
  182. receive_event.set()
  183. return
  184. if len(self._state.buffer) < self._state.max_buffer_size:
  185. self._state.buffer.append(item)
  186. else:
  187. raise WouldBlock
  188. async def send(self, item: T_contra) -> None:
  189. """
  190. Send an item to the stream.
  191. If the buffer is full, this method blocks until there is again room in the
  192. buffer or the item can be sent directly to a receiver.
  193. :param item: the item to send
  194. :raises ~anyio.ClosedResourceError: if this send stream has been closed
  195. :raises ~anyio.BrokenResourceError: if the stream has been closed from the
  196. receiving end
  197. """
  198. await checkpoint()
  199. try:
  200. self.send_nowait(item)
  201. except WouldBlock:
  202. # Wait until there's someone on the receiving end
  203. send_event = Event()
  204. self._state.waiting_senders[send_event] = item
  205. try:
  206. await send_event.wait()
  207. except BaseException:
  208. self._state.waiting_senders.pop(send_event, None)
  209. raise
  210. if send_event in self._state.waiting_senders:
  211. del self._state.waiting_senders[send_event]
  212. raise BrokenResourceError from None
  213. def clone(self) -> MemoryObjectSendStream[T_contra]:
  214. """
  215. Create a clone of this send stream.
  216. Each clone can be closed separately. Only when all clones have been closed will
  217. the sending end of the memory stream be considered closed by the receiving ends.
  218. :return: the cloned stream
  219. """
  220. if self._closed:
  221. raise ClosedResourceError
  222. return MemoryObjectSendStream(_state=self._state)
  223. def close(self) -> None:
  224. """
  225. Close the stream.
  226. This works the exact same way as :meth:`aclose`, but is provided as a special
  227. case for the benefit of synchronous callbacks.
  228. """
  229. if not self._closed:
  230. self._closed = True
  231. self._state.open_send_channels -= 1
  232. if self._state.open_send_channels == 0:
  233. receive_events = list(self._state.waiting_receivers.keys())
  234. self._state.waiting_receivers.clear()
  235. for event in receive_events:
  236. event.set()
  237. async def aclose(self) -> None:
  238. self.close()
  239. def statistics(self) -> MemoryObjectStreamStatistics:
  240. """
  241. Return statistics about the current state of this stream.
  242. .. versionadded:: 3.0
  243. """
  244. return self._state.statistics()
  245. def __enter__(self) -> MemoryObjectSendStream[T_contra]:
  246. return self
  247. def __exit__(
  248. self,
  249. exc_type: type[BaseException] | None,
  250. exc_val: BaseException | None,
  251. exc_tb: TracebackType | None,
  252. ) -> None:
  253. self.close()
  254. def __del__(self) -> None:
  255. if not self._closed:
  256. warnings.warn(
  257. f"Unclosed <{self.__class__.__name__} at {id(self):x}>",
  258. ResourceWarning,
  259. stacklevel=1,
  260. source=self,
  261. )