|
1 | 1 | """Reader for WebSocket protocol versions 13 and 8.""" |
2 | 2 |
|
3 | | -from typing import Final, List, Optional, Set, Tuple, Union |
| 3 | +import asyncio |
| 4 | +import builtins |
| 5 | +from collections import deque |
| 6 | +from typing import Deque, Final, List, Optional, Set, Tuple, Union |
4 | 7 |
|
| 8 | +from ..base_protocol import BaseProtocol |
5 | 9 | from ..compression_utils import ZLibDecompressor |
6 | | -from ..helpers import set_exception |
7 | | -from ..streams import FlowControlDataQueue |
| 10 | +from ..helpers import _EXC_SENTINEL, set_exception |
| 11 | +from ..streams import EofStream |
8 | 12 | from .helpers import UNPACK_CLOSE_CODE, UNPACK_LEN3, websocket_mask |
9 | 13 | from .models import ( |
10 | 14 | WS_DEFLATE_TRAILING, |
|
39 | 43 |
|
40 | 44 | TUPLE_NEW = tuple.__new__ |
41 | 45 |
|
| 46 | +int_ = int # Prevent Cython from converting to PyInt |
| 47 | + |
| 48 | + |
| 49 | +class WebSocketDataQueue: |
| 50 | + """WebSocketDataQueue resumes and pauses an underlying stream. |
| 51 | +
|
| 52 | + It is a destination for WebSocket data. |
| 53 | + """ |
42 | 54 |
|
43 | | -class WebSocketReader: |
44 | 55 | def __init__( |
| 56 | + self, protocol: BaseProtocol, limit: int, *, loop: asyncio.AbstractEventLoop |
| 57 | + ) -> None: |
| 58 | + self._size = 0 |
| 59 | + self._protocol = protocol |
| 60 | + self._limit = limit * 2 |
| 61 | + self._loop = loop |
| 62 | + self._eof = False |
| 63 | + self._waiter: Optional[asyncio.Future[None]] = None |
| 64 | + self._exception: Union[BaseException, None] = None |
| 65 | + self._buffer: Deque[Tuple[WSMessage, int]] = deque() |
| 66 | + self._get_buffer = self._buffer.popleft |
| 67 | + self._put_buffer = self._buffer.append |
| 68 | + |
| 69 | + def exception(self) -> Optional[BaseException]: |
| 70 | + return self._exception |
| 71 | + |
| 72 | + def set_exception( |
45 | 73 | self, |
46 | | - queue: FlowControlDataQueue[WSMessage], |
47 | | - max_msg_size: int, |
48 | | - compress: bool = True, |
| 74 | + exc: "BaseException", |
| 75 | + exc_cause: builtins.BaseException = _EXC_SENTINEL, |
| 76 | + ) -> None: |
| 77 | + self._eof = True |
| 78 | + self._exception = exc |
| 79 | + if (waiter := self._waiter) is not None: |
| 80 | + self._waiter = None |
| 81 | + set_exception(waiter, exc, exc_cause) |
| 82 | + |
| 83 | + def _release_waiter(self) -> None: |
| 84 | + if (waiter := self._waiter) is None: |
| 85 | + return |
| 86 | + self._waiter = None |
| 87 | + if not waiter.done(): |
| 88 | + waiter.set_result(None) |
| 89 | + |
| 90 | + def feed_eof(self) -> None: |
| 91 | + self._eof = True |
| 92 | + self._release_waiter() |
| 93 | + |
| 94 | + def feed_data(self, data: "WSMessage", size: "int_") -> None: |
| 95 | + self._size += size |
| 96 | + self._put_buffer((data, size)) |
| 97 | + self._release_waiter() |
| 98 | + if self._size > self._limit and not self._protocol._reading_paused: |
| 99 | + self._protocol.pause_reading() |
| 100 | + |
| 101 | + async def read(self) -> WSMessage: |
| 102 | + if not self._buffer and not self._eof: |
| 103 | + assert not self._waiter |
| 104 | + self._waiter = self._loop.create_future() |
| 105 | + try: |
| 106 | + await self._waiter |
| 107 | + except (asyncio.CancelledError, asyncio.TimeoutError): |
| 108 | + self._waiter = None |
| 109 | + raise |
| 110 | + return self._read_from_buffer() |
| 111 | + |
| 112 | + def _read_from_buffer(self) -> WSMessage: |
| 113 | + if self._buffer: |
| 114 | + data, size = self._get_buffer() |
| 115 | + self._size -= size |
| 116 | + if self._size < self._limit and self._protocol._reading_paused: |
| 117 | + self._protocol.resume_reading() |
| 118 | + return data |
| 119 | + if self._exception is not None: |
| 120 | + raise self._exception |
| 121 | + raise EofStream |
| 122 | + |
| 123 | + |
| 124 | +class WebSocketReader: |
| 125 | + def __init__( |
| 126 | + self, queue: WebSocketDataQueue, max_msg_size: int, compress: bool = True |
49 | 127 | ) -> None: |
50 | 128 | self.queue = queue |
51 | | - self._queue_feed_data = queue.feed_data |
52 | 129 | self._max_msg_size = max_msg_size |
53 | 130 |
|
54 | 131 | self._exc: Optional[Exception] = None |
@@ -187,12 +264,12 @@ def _feed_data(self, data: bytes) -> None: |
187 | 264 | # bottleneck, so we use tuple.__new__ to improve performance. |
188 | 265 | # This is not type safe, but many tests should fail in |
189 | 266 | # test_client_ws_functional.py if this is wrong. |
190 | | - self._queue_feed_data( |
| 267 | + self.queue.feed_data( |
191 | 268 | TUPLE_NEW(WSMessage, (WS_MSG_TYPE_TEXT, text, "")), |
192 | 269 | len(payload_merged), |
193 | 270 | ) |
194 | 271 | else: |
195 | | - self._queue_feed_data( |
| 272 | + self.queue.feed_data( |
196 | 273 | TUPLE_NEW(WSMessage, (WS_MSG_TYPE_BINARY, payload_merged, "")), |
197 | 274 | len(payload_merged), |
198 | 275 | ) |
@@ -221,14 +298,14 @@ def _feed_data(self, data: bytes) -> None: |
221 | 298 | else: |
222 | 299 | msg = TUPLE_NEW(WSMessage, (WSMsgType.CLOSE, 0, "")) |
223 | 300 |
|
224 | | - self._queue_feed_data(msg, 0) |
| 301 | + self.queue.feed_data(msg, 0) |
225 | 302 | elif opcode == OP_CODE_PING: |
226 | 303 | msg = TUPLE_NEW(WSMessage, (WSMsgType.PING, payload, "")) |
227 | | - self._queue_feed_data(msg, len(payload)) |
| 304 | + self.queue.feed_data(msg, len(payload)) |
228 | 305 |
|
229 | 306 | elif opcode == OP_CODE_PONG: |
230 | 307 | msg = TUPLE_NEW(WSMessage, (WSMsgType.PONG, payload, "")) |
231 | | - self._queue_feed_data(msg, len(payload)) |
| 308 | + self.queue.feed_data(msg, len(payload)) |
232 | 309 |
|
233 | 310 | else: |
234 | 311 | raise WebSocketError( |
|
0 commit comments