messages.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316
  1. from __future__ import annotations
  2. import asyncio
  3. import codecs
  4. import collections
  5. from collections.abc import AsyncIterator, Iterable
  6. from typing import Any, Callable, Generic, Literal, TypeVar, overload
  7. from ..exceptions import ConcurrencyError
  8. from ..frames import OP_BINARY, OP_CONT, OP_TEXT, Frame
  9. from ..typing import Data
  10. __all__ = ["Assembler"]
  11. UTF8Decoder = codecs.getincrementaldecoder("utf-8")
  12. T = TypeVar("T")
  13. class SimpleQueue(Generic[T]):
  14. """
  15. Simplified version of :class:`asyncio.Queue`.
  16. Provides only the subset of functionality needed by :class:`Assembler`.
  17. """
  18. def __init__(self) -> None:
  19. self.loop = asyncio.get_running_loop()
  20. self.get_waiter: asyncio.Future[None] | None = None
  21. self.queue: collections.deque[T] = collections.deque()
  22. def __len__(self) -> int:
  23. return len(self.queue)
  24. def put(self, item: T) -> None:
  25. """Put an item into the queue."""
  26. self.queue.append(item)
  27. if self.get_waiter is not None and not self.get_waiter.done():
  28. self.get_waiter.set_result(None)
  29. async def get(self, block: bool = True) -> T:
  30. """Remove and return an item from the queue, waiting if necessary."""
  31. if not self.queue:
  32. if not block:
  33. raise EOFError("stream of frames ended")
  34. assert self.get_waiter is None, "cannot call get() concurrently"
  35. self.get_waiter = self.loop.create_future()
  36. try:
  37. await self.get_waiter
  38. finally:
  39. self.get_waiter.cancel()
  40. self.get_waiter = None
  41. return self.queue.popleft()
  42. def reset(self, items: Iterable[T]) -> None:
  43. """Put back items into an empty, idle queue."""
  44. assert self.get_waiter is None, "cannot reset() while get() is running"
  45. assert not self.queue, "cannot reset() while queue isn't empty"
  46. self.queue.extend(items)
  47. def abort(self) -> None:
  48. """Close the queue, raising EOFError in get() if necessary."""
  49. if self.get_waiter is not None and not self.get_waiter.done():
  50. self.get_waiter.set_exception(EOFError("stream of frames ended"))
  51. class Assembler:
  52. """
  53. Assemble messages from frames.
  54. :class:`Assembler` expects only data frames. The stream of frames must
  55. respect the protocol; if it doesn't, the behavior is undefined.
  56. Args:
  57. pause: Called when the buffer of frames goes above the high water mark;
  58. should pause reading from the network.
  59. resume: Called when the buffer of frames goes below the low water mark;
  60. should resume reading from the network.
  61. """
  62. def __init__(
  63. self,
  64. high: int | None = None,
  65. low: int | None = None,
  66. pause: Callable[[], Any] = lambda: None,
  67. resume: Callable[[], Any] = lambda: None,
  68. ) -> None:
  69. # Queue of incoming frames.
  70. self.frames: SimpleQueue[Frame] = SimpleQueue()
  71. # We cannot put a hard limit on the size of the queue because a single
  72. # call to Protocol.data_received() could produce thousands of frames,
  73. # which must be buffered. Instead, we pause reading when the buffer goes
  74. # above the high limit and we resume when it goes under the low limit.
  75. if high is not None and low is None:
  76. low = high // 4
  77. if high is None and low is not None:
  78. high = low * 4
  79. if high is not None and low is not None:
  80. if low < 0:
  81. raise ValueError("low must be positive or equal to zero")
  82. if high < low:
  83. raise ValueError("high must be greater than or equal to low")
  84. self.high, self.low = high, low
  85. self.pause = pause
  86. self.resume = resume
  87. self.paused = False
  88. # This flag prevents concurrent calls to get() by user code.
  89. self.get_in_progress = False
  90. # This flag marks the end of the connection.
  91. self.closed = False
  92. @overload
  93. async def get(self, decode: Literal[True]) -> str: ...
  94. @overload
  95. async def get(self, decode: Literal[False]) -> bytes: ...
  96. @overload
  97. async def get(self, decode: bool | None = None) -> Data: ...
  98. async def get(self, decode: bool | None = None) -> Data:
  99. """
  100. Read the next message.
  101. :meth:`get` returns a single :class:`str` or :class:`bytes`.
  102. If the message is fragmented, :meth:`get` waits until the last frame is
  103. received, then it reassembles the message and returns it. To receive
  104. messages frame by frame, use :meth:`get_iter` instead.
  105. Args:
  106. decode: :obj:`False` disables UTF-8 decoding of text frames and
  107. returns :class:`bytes`. :obj:`True` forces UTF-8 decoding of
  108. binary frames and returns :class:`str`.
  109. Raises:
  110. EOFError: If the stream of frames has ended.
  111. UnicodeDecodeError: If a text frame contains invalid UTF-8.
  112. ConcurrencyError: If two coroutines run :meth:`get` or
  113. :meth:`get_iter` concurrently.
  114. """
  115. if self.get_in_progress:
  116. raise ConcurrencyError("get() or get_iter() is already running")
  117. self.get_in_progress = True
  118. # Locking with get_in_progress prevents concurrent execution
  119. # until get() fetches a complete message or is canceled.
  120. try:
  121. # Fetch the first frame.
  122. frame = await self.frames.get(not self.closed)
  123. self.maybe_resume()
  124. assert frame.opcode is OP_TEXT or frame.opcode is OP_BINARY
  125. if decode is None:
  126. decode = frame.opcode is OP_TEXT
  127. frames = [frame]
  128. # Fetch subsequent frames for fragmented messages.
  129. while not frame.fin:
  130. try:
  131. frame = await self.frames.get(not self.closed)
  132. except asyncio.CancelledError:
  133. # Put frames already received back into the queue
  134. # so that future calls to get() can return them.
  135. self.frames.reset(frames)
  136. raise
  137. self.maybe_resume()
  138. assert frame.opcode is OP_CONT
  139. frames.append(frame)
  140. finally:
  141. self.get_in_progress = False
  142. # This converts frame.data to bytes when it's a bytearray.
  143. data = b"".join(frame.data for frame in frames)
  144. if decode:
  145. return data.decode()
  146. else:
  147. return data
  148. @overload
  149. def get_iter(self, decode: Literal[True]) -> AsyncIterator[str]: ...
  150. @overload
  151. def get_iter(self, decode: Literal[False]) -> AsyncIterator[bytes]: ...
  152. @overload
  153. def get_iter(self, decode: bool | None = None) -> AsyncIterator[Data]: ...
  154. async def get_iter(self, decode: bool | None = None) -> AsyncIterator[Data]:
  155. """
  156. Stream the next message.
  157. Iterating the return value of :meth:`get_iter` asynchronously yields a
  158. :class:`str` or :class:`bytes` for each frame in the message.
  159. The iterator must be fully consumed before calling :meth:`get_iter` or
  160. :meth:`get` again. Else, :exc:`ConcurrencyError` is raised.
  161. This method only makes sense for fragmented messages. If messages aren't
  162. fragmented, use :meth:`get` instead.
  163. Args:
  164. decode: :obj:`False` disables UTF-8 decoding of text frames and
  165. returns :class:`bytes`. :obj:`True` forces UTF-8 decoding of
  166. binary frames and returns :class:`str`.
  167. Raises:
  168. EOFError: If the stream of frames has ended.
  169. UnicodeDecodeError: If a text frame contains invalid UTF-8.
  170. ConcurrencyError: If two coroutines run :meth:`get` or
  171. :meth:`get_iter` concurrently.
  172. """
  173. if self.get_in_progress:
  174. raise ConcurrencyError("get() or get_iter() is already running")
  175. self.get_in_progress = True
  176. # Locking with get_in_progress prevents concurrent execution
  177. # until get_iter() fetches a complete message or is canceled.
  178. # If get_iter() raises an exception e.g. in decoder.decode(),
  179. # get_in_progress remains set and the connection becomes unusable.
  180. # Yield the first frame.
  181. try:
  182. frame = await self.frames.get(not self.closed)
  183. except asyncio.CancelledError:
  184. self.get_in_progress = False
  185. raise
  186. self.maybe_resume()
  187. assert frame.opcode is OP_TEXT or frame.opcode is OP_BINARY
  188. if decode is None:
  189. decode = frame.opcode is OP_TEXT
  190. if decode:
  191. decoder = UTF8Decoder()
  192. yield decoder.decode(frame.data, frame.fin)
  193. else:
  194. # Convert to bytes when frame.data is a bytearray.
  195. yield bytes(frame.data)
  196. # Yield subsequent frames for fragmented messages.
  197. while not frame.fin:
  198. # We cannot handle asyncio.CancelledError because we don't buffer
  199. # previous fragments — we're streaming them. Canceling get_iter()
  200. # here will leave the assembler in a stuck state. Future calls to
  201. # get() or get_iter() will raise ConcurrencyError.
  202. frame = await self.frames.get(not self.closed)
  203. self.maybe_resume()
  204. assert frame.opcode is OP_CONT
  205. if decode:
  206. yield decoder.decode(frame.data, frame.fin)
  207. else:
  208. # Convert to bytes when frame.data is a bytearray.
  209. yield bytes(frame.data)
  210. self.get_in_progress = False
  211. def put(self, frame: Frame) -> None:
  212. """
  213. Add ``frame`` to the next message.
  214. Raises:
  215. EOFError: If the stream of frames has ended.
  216. """
  217. if self.closed:
  218. raise EOFError("stream of frames ended")
  219. self.frames.put(frame)
  220. self.maybe_pause()
  221. def maybe_pause(self) -> None:
  222. """Pause the writer if queue is above the high water mark."""
  223. # Skip if flow control is disabled.
  224. if self.high is None:
  225. return
  226. # Check for "> high" to support high = 0.
  227. if len(self.frames) > self.high and not self.paused:
  228. self.paused = True
  229. self.pause()
  230. def maybe_resume(self) -> None:
  231. """Resume the writer if queue is below the low water mark."""
  232. # Skip if flow control is disabled.
  233. if self.low is None:
  234. return
  235. # Check for "<= low" to support low = 0.
  236. if len(self.frames) <= self.low and self.paused:
  237. self.paused = False
  238. self.resume()
  239. def close(self) -> None:
  240. """
  241. End the stream of frames.
  242. Calling :meth:`close` concurrently with :meth:`get`, :meth:`get_iter`,
  243. or :meth:`put` is safe. They will raise :exc:`EOFError`.
  244. """
  245. if self.closed:
  246. return
  247. self.closed = True
  248. # Unblock get() or get_iter().
  249. self.frames.abort()