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