"""Pre-payload limits and bounded reassembly for Uvicorn legacy WebSocket backend. Eight queued messages plus one assembling and one delivered message fit the 96,000-byte application receive budget even for maximum-size binary messages. Validated LIVE_* settings lower binary/control limits and queue/audio capacity. """ import asyncio import codecs from uvicorn.protocols.websockets.websockets_impl import WebSocketProtocol from websockets.exceptions import ProtocolError from websockets.legacy.framing import Frame from app.modules.voice.settings import RuntimeSettings from app.modules.voice.configuration import VoiceSettings class BoundedWebSocketProtocol(WebSocketProtocol): def __init__(self, config, server_state, app_state, _loop=None): settings = getattr(config, 'ws_settings', None) or RuntimeSettings.for_provider(VoiceSettings().provider) self.settings = settings self.max_binary_message_bytes = settings.max_binary_message_bytes self.max_client_control_bytes = settings.max_client_control_bytes self.max_queued_audio_bytes = settings.max_queued_audio_bytes self.max_queued_audio_messages = settings.max_queued_audio_messages max_size = max(self.max_binary_message_bytes, self.max_client_control_bytes) config.ws_max_size = max_size config.ws_per_message_deflate = False audio_budget = min( self.max_queued_audio_messages, max(1, self.max_queued_audio_bytes // self.max_binary_message_bytes) ) queue_cap = max(1, audio_budget - 2) if audio_budget > 2 else 1 config.ws_max_queue = queue_cap self.max_audio_messages = audio_budget super().__init__(config, server_state, app_state, _loop) self.message_remaining = None self.assembling_scratch = None self.assembling_type = None self.in_flight_message = None self.capacity_available = asyncio.Event() self.capacity_available.set() self.rejection_code = None @property def total_message_count(self): count = 1 if self.assembling_type is not None else 0 count += len(self.messages) if self.in_flight_message is not None: count += 1 return count @property def current_audio_bytes(self): total = len(self.assembling_scratch) if (self.assembling_scratch is not None and self.assembling_type == 2) else 0 total += sum(len(m) for m in self.messages if isinstance(m, (bytes, bytearray))) if self.in_flight_message is not None and isinstance(self.in_flight_message, (bytes, bytearray)): total += len(self.in_flight_message) return total def has_capacity(self): if self.closed_event.is_set(): return True if self.total_message_count >= self.max_audio_messages: return False if self.current_audio_bytes + self.max_binary_message_bytes > self.max_queued_audio_bytes: return False return True async def wait_for_capacity(self): while not self.closed_event.is_set(): if self.has_capacity(): return self.capacity_available.clear() await self.capacity_available.wait() async def read_frame(self, max_size): header = await self.reader.readexactly(2) # Reject compressed/reserved bits before reading lengths, masks or payloads. if header[0] & 0x70: raise ProtocolError('Reserved bits are unsupported') opcode = header[0] & 0x0f if opcode in (1, 2): if self.message_remaining is not None: raise ProtocolError('Interleaved data message') limit = self.max_client_control_bytes if opcode == 1 else self.max_binary_message_bytes self.message_remaining = limit elif opcode == 0: if self.message_remaining is None: raise ProtocolError('Unexpected continuation') elif opcode not in (8, 9, 10): raise ProtocolError('Invalid opcode') bound = self.message_remaining if opcode in (0, 1, 2) else 125 if max_size is not None and opcode in (0, 1, 2): bound = min(bound, max_size) first = True async def read(size): nonlocal first if first: first = False return header return await self.reader.readexactly(size) try: frame = await Frame.read(read, mask=True, max_size=bound, extensions=[]) except Exception: if opcode in (0, 1, 2): self.message_remaining = None raise if opcode in (0, 1, 2): self.message_remaining -= len(frame.data) if frame.fin: self.message_remaining = None return frame async def read_message(self): await self.wait_for_capacity() if self.closed_event.is_set(): return None frame = await self.read_data_frame(max_size=self.max_size) if frame is None: return None if frame.opcode == 1: text = True elif frame.opcode == 2: text = False else: raise ProtocolError('unexpected opcode') if frame.fin: if text: return frame.data.decode('utf-8') return bytes(frame.data) # Fragmentation with finite retained metadata and scratch storage scratch = bytearray() self.assembling_scratch = scratch self.assembling_type = 1 if text else 2 try: if text: decoder = codecs.getincrementaldecoder('utf-8')(errors='strict') decoder.decode(frame.data, frame.fin) if frame.data: scratch.extend(frame.data) while not frame.fin: frame = await self.read_data_frame(max_size=self.message_remaining) if frame is None: raise ProtocolError('incomplete fragmented message') if frame.opcode != 0: raise ProtocolError('expected continuation frame') if text: decoder.decode(frame.data, frame.fin) if frame.data: scratch.extend(frame.data) if text: return scratch.decode('utf-8') return bytes(scratch) finally: self.assembling_scratch = None self.assembling_type = None self.message_remaining = None self.capacity_available.set() async def recv(self): self._release_in_flight() msg = await super().recv() self._record_in_flight(msg) return msg def _release_in_flight(self): if self.in_flight_message is not None: self.in_flight_message = None self.capacity_available.set() def _record_in_flight(self, msg): self.in_flight_message = msg def _cleanup_resources(self): self.assembling_scratch = None self.assembling_type = None self.message_remaining = None self.in_flight_message = None self.capacity_available.set() def connection_lost(self, exc): self._cleanup_resources() super().connection_lost(exc) def fail_connection(self, code=1006, reason=''): if code in (1002, 1007, 1009): self.rejection_code = code self._cleanup_resources() super().fail_connection(code, reason) async def asgi_receive(self): message = await super().asgi_receive() if message['type'] == 'websocket.disconnect' and self.rejection_code is not None: # A failed parser stops reading, so close_code can be 1006 even after # sending a standards-compliant 1007. Preserve the actual rejection. message = dict(message, code=self.rejection_code) return message async def close(self, code=1000, reason=''): self._cleanup_resources() return await super().close(code, reason)