Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.
 
 
 
 

315 rindas
11 KiB

  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 without waiting."""
  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. # coverage reports incorrectly: "line NN didn't jump to the function exit"
  63. def __init__( # pragma: no cover
  64. self,
  65. high: int | None = None,
  66. low: int | None = None,
  67. pause: Callable[[], Any] = lambda: None,
  68. resume: Callable[[], Any] = lambda: None,
  69. ) -> None:
  70. # Queue of incoming frames.
  71. self.frames: SimpleQueue[Frame] = SimpleQueue()
  72. # We cannot put a hard limit on the size of the queue because a single
  73. # call to Protocol.data_received() could produce thousands of frames,
  74. # which must be buffered. Instead, we pause reading when the buffer goes
  75. # above the high limit and we resume when it goes under the low limit.
  76. if high is not None and low is None:
  77. low = high // 4
  78. if high is None and low is not None:
  79. high = low * 4
  80. if high is not None and low is not None:
  81. if low < 0:
  82. raise ValueError("low must be positive or equal to zero")
  83. if high < low:
  84. raise ValueError("high must be greater than or equal to low")
  85. self.high, self.low = high, low
  86. self.pause = pause
  87. self.resume = resume
  88. self.paused = False
  89. # This flag prevents concurrent calls to get() by user code.
  90. self.get_in_progress = False
  91. # This flag marks the end of the connection.
  92. self.closed = False
  93. @overload
  94. async def get(self, decode: Literal[True]) -> str: ...
  95. @overload
  96. async def get(self, decode: Literal[False]) -> bytes: ...
  97. @overload
  98. async def get(self, decode: bool | None = None) -> Data: ...
  99. async def get(self, decode: bool | None = None) -> Data:
  100. """
  101. Read the next message.
  102. :meth:`get` returns a single :class:`str` or :class:`bytes`.
  103. If the message is fragmented, :meth:`get` waits until the last frame is
  104. received, then it reassembles the message and returns it. To receive
  105. messages frame by frame, use :meth:`get_iter` instead.
  106. Args:
  107. decode: :obj:`False` disables UTF-8 decoding of text frames and
  108. returns :class:`bytes`. :obj:`True` forces UTF-8 decoding of
  109. binary frames and returns :class:`str`.
  110. Raises:
  111. EOFError: If the stream of frames has ended.
  112. UnicodeDecodeError: If a text frame contains invalid UTF-8.
  113. ConcurrencyError: If two coroutines run :meth:`get` or
  114. :meth:`get_iter` concurrently.
  115. """
  116. if self.get_in_progress:
  117. raise ConcurrencyError("get() or get_iter() is already running")
  118. self.get_in_progress = True
  119. # Locking with get_in_progress prevents concurrent execution
  120. # until get() fetches a complete message or is canceled.
  121. try:
  122. # First frame
  123. frame = await self.frames.get(not self.closed)
  124. self.maybe_resume()
  125. assert frame.opcode is OP_TEXT or frame.opcode is OP_BINARY
  126. if decode is None:
  127. decode = frame.opcode is OP_TEXT
  128. frames = [frame]
  129. # Following frames, for fragmented messages
  130. while not frame.fin:
  131. try:
  132. frame = await self.frames.get(not self.closed)
  133. except asyncio.CancelledError:
  134. # Put frames already received back into the queue
  135. # so that future calls to get() can return them.
  136. self.frames.reset(frames)
  137. raise
  138. self.maybe_resume()
  139. assert frame.opcode is OP_CONT
  140. frames.append(frame)
  141. finally:
  142. self.get_in_progress = False
  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. # 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. yield frame.data
  195. # Following frames, for fragmented messages
  196. while not frame.fin:
  197. # We cannot handle asyncio.CancelledError because we don't buffer
  198. # previous fragments — we're streaming them. Canceling get_iter()
  199. # here will leave the assembler in a stuck state. Future calls to
  200. # get() or get_iter() will raise ConcurrencyError.
  201. frame = await self.frames.get(not self.closed)
  202. self.maybe_resume()
  203. assert frame.opcode is OP_CONT
  204. if decode:
  205. yield decoder.decode(frame.data, frame.fin)
  206. else:
  207. yield frame.data
  208. self.get_in_progress = False
  209. def put(self, frame: Frame) -> None:
  210. """
  211. Add ``frame`` to the next message.
  212. Raises:
  213. EOFError: If the stream of frames has ended.
  214. """
  215. if self.closed:
  216. raise EOFError("stream of frames ended")
  217. self.frames.put(frame)
  218. self.maybe_pause()
  219. def maybe_pause(self) -> None:
  220. """Pause the writer if queue is above the high water mark."""
  221. # Skip if flow control is disabled
  222. if self.high is None:
  223. return
  224. # Check for "> high" to support high = 0
  225. if len(self.frames) > self.high and not self.paused:
  226. self.paused = True
  227. self.pause()
  228. def maybe_resume(self) -> None:
  229. """Resume the writer if queue is below the low water mark."""
  230. # Skip if flow control is disabled
  231. if self.low is None:
  232. return
  233. # Check for "<= low" to support low = 0
  234. if len(self.frames) <= self.low and self.paused:
  235. self.paused = False
  236. self.resume()
  237. def close(self) -> None:
  238. """
  239. End the stream of frames.
  240. Calling :meth:`close` concurrently with :meth:`get`, :meth:`get_iter`,
  241. or :meth:`put` is safe. They will raise :exc:`EOFError`.
  242. """
  243. if self.closed:
  244. return
  245. self.closed = True
  246. # Unblock get() or get_iter().
  247. self.frames.abort()