messages.py 10 KB

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