messages.py 11 KB

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