Refactor: add rxtx debugger log
This commit is contained in:
parent
ea31261bff
commit
0ee3825563
5 changed files with 264 additions and 9 deletions
|
@ -15,6 +15,7 @@ from ..core.exceptions import ValidationError, MessageProcessingError
|
|||
|
||||
# Setup logging
|
||||
logger = logging.getLogger("detector_worker.message_processor")
|
||||
msg_proc_logger = logging.getLogger("websocket.message_processor") # Detailed message processing logger
|
||||
|
||||
|
||||
class MessageType(Enum):
|
||||
|
@ -161,24 +162,31 @@ class MessageProcessor:
|
|||
Raises:
|
||||
MessageProcessingError: If message is invalid
|
||||
"""
|
||||
msg_proc_logger.debug(f"📨 PARSING MESSAGE: {raw_message[:100]}{'...' if len(raw_message) > 100 else ''}")
|
||||
|
||||
try:
|
||||
data = json.loads(raw_message)
|
||||
except json.JSONDecodeError as e:
|
||||
msg_proc_logger.error(f"❌ JSON PARSE ERROR: {e}")
|
||||
raise MessageProcessingError(f"Invalid JSON: {e}")
|
||||
|
||||
# Validate message structure
|
||||
if not isinstance(data, dict):
|
||||
msg_proc_logger.error(f"❌ INVALID MESSAGE STRUCTURE: Expected dict, got {type(data)}")
|
||||
raise MessageProcessingError("Message must be a JSON object")
|
||||
|
||||
# Extract message type
|
||||
msg_type_str = data.get("type")
|
||||
if not msg_type_str:
|
||||
msg_proc_logger.error("❌ MISSING MESSAGE TYPE")
|
||||
raise MessageProcessingError("Missing 'type' field in message")
|
||||
|
||||
# Convert to MessageType enum
|
||||
try:
|
||||
msg_type = MessageType(msg_type_str)
|
||||
msg_proc_logger.debug(f"✅ PARSED MESSAGE TYPE: {msg_type.value}")
|
||||
except ValueError:
|
||||
msg_proc_logger.error(f"❌ UNKNOWN MESSAGE TYPE: {msg_type_str}")
|
||||
raise MessageProcessingError(f"Unknown message type: {msg_type_str}")
|
||||
|
||||
return msg_type, data
|
||||
|
@ -197,13 +205,22 @@ class MessageProcessor:
|
|||
Raises:
|
||||
ValidationError: If validation fails
|
||||
"""
|
||||
msg_proc_logger.debug(f"🔍 VALIDATING {msg_type.value} MESSAGE")
|
||||
|
||||
# Get validator for message type
|
||||
validator = self.validators.get(msg_type)
|
||||
if not validator:
|
||||
# No validation needed for some message types
|
||||
msg_proc_logger.debug(f"ℹ️ NO VALIDATION NEEDED FOR {msg_type.value}")
|
||||
return data.get("payload", {})
|
||||
|
||||
return validator(data)
|
||||
try:
|
||||
result = validator(data)
|
||||
msg_proc_logger.debug(f"✅ VALIDATION SUCCESS FOR {msg_type.value}")
|
||||
return result
|
||||
except ValidationError as e:
|
||||
msg_proc_logger.error(f"❌ VALIDATION FAILED FOR {msg_type.value}: {e}")
|
||||
raise
|
||||
|
||||
def _validate_subscribe(self, data: Dict[str, Any]) -> SubscribePayload:
|
||||
"""Validate subscribe message."""
|
||||
|
|
|
@ -32,6 +32,7 @@ from ..utils.system_monitor import get_system_metrics
|
|||
# Setup logging
|
||||
logger = logging.getLogger("detector_worker.websocket_handler")
|
||||
ws_logger = logging.getLogger("websocket")
|
||||
ws_rxtx_logger = logging.getLogger("websocket.rxtx") # Dedicated RX/TX logger
|
||||
|
||||
# Type definitions for callbacks
|
||||
MessageHandler = Callable[[Dict[str, Any]], asyncio.coroutine]
|
||||
|
@ -109,7 +110,11 @@ class WebSocketHandler:
|
|||
self.websocket = websocket
|
||||
self.connected = True
|
||||
|
||||
logger.info("WebSocket connection accepted")
|
||||
# Log connection details
|
||||
client_host = getattr(websocket.client, 'host', 'unknown')
|
||||
client_port = getattr(websocket.client, 'port', 'unknown')
|
||||
logger.info(f"🔗 WebSocket connection accepted from {client_host}:{client_port}")
|
||||
ws_rxtx_logger.info(f"CONNECT -> Client: {client_host}:{client_port}")
|
||||
|
||||
# Create concurrent tasks
|
||||
stream_task = asyncio.create_task(self._process_streams())
|
||||
|
@ -126,6 +131,9 @@ class WebSocketHandler:
|
|||
|
||||
finally:
|
||||
self.connected = False
|
||||
client_host = getattr(websocket.client, 'host', 'unknown') if websocket.client else 'unknown'
|
||||
client_port = getattr(websocket.client, 'port', 'unknown') if websocket.client else 'unknown'
|
||||
ws_rxtx_logger.info(f"DISCONNECT -> Client: {client_host}:{client_port}")
|
||||
await self._cleanup()
|
||||
|
||||
async def _cleanup(self) -> None:
|
||||
|
@ -181,7 +189,9 @@ class WebSocketHandler:
|
|||
}
|
||||
}
|
||||
|
||||
ws_logger.info(f"TX -> {json.dumps(state_data, separators=(',', ':'))}")
|
||||
# Compact JSON for RX/TX logging
|
||||
compact_json = json.dumps(state_data, separators=(',', ':'))
|
||||
ws_rxtx_logger.info(f"TX -> {compact_json}")
|
||||
await self.websocket.send_json(state_data)
|
||||
|
||||
await asyncio.sleep(HEARTBEAT_INTERVAL)
|
||||
|
@ -198,16 +208,21 @@ class WebSocketHandler:
|
|||
while self.connected:
|
||||
try:
|
||||
text_data = await self.websocket.receive_text()
|
||||
ws_logger.info(f"RX <- {text_data}")
|
||||
ws_rxtx_logger.info(f"RX <- {text_data}")
|
||||
|
||||
data = json.loads(text_data)
|
||||
msg_type = data.get("type")
|
||||
|
||||
# Log message processing
|
||||
logger.debug(f"📥 Processing message type: {msg_type}")
|
||||
|
||||
if msg_type in self.message_handlers:
|
||||
handler = self.message_handlers[msg_type]
|
||||
await handler(data)
|
||||
logger.debug(f"✅ Message {msg_type} processed successfully")
|
||||
else:
|
||||
logger.error(f"Unknown message type: {msg_type}")
|
||||
logger.error(f"❌ Unknown message type: {msg_type}")
|
||||
ws_rxtx_logger.error(f"UNKNOWN_MSG_TYPE -> {msg_type}")
|
||||
|
||||
except json.JSONDecodeError:
|
||||
logger.error("Received invalid JSON message")
|
||||
|
@ -437,7 +452,7 @@ class WebSocketHandler:
|
|||
"sessionId": session_id
|
||||
}
|
||||
}
|
||||
ws_logger.info(f"TX -> {json.dumps(response, separators=(',', ':'))}")
|
||||
ws_rxtx_logger.info(f"TX -> {json.dumps(response, separators=(',', ':'))}")
|
||||
await self.websocket.send_json(response)
|
||||
|
||||
logger.info(f"Set session {session_id} for display {display_id}")
|
||||
|
@ -463,7 +478,7 @@ class WebSocketHandler:
|
|||
"patchData": patch_data
|
||||
}
|
||||
}
|
||||
ws_logger.info(f"TX -> {json.dumps(response, separators=(',', ':'))}")
|
||||
ws_rxtx_logger.info(f"TX -> {json.dumps(response, separators=(',', ':'))}")
|
||||
await self.websocket.send_json(response)
|
||||
|
||||
async def _handle_set_progression_stage(self, data: Dict[str, Any]) -> None:
|
||||
|
@ -539,7 +554,7 @@ class WebSocketHandler:
|
|||
}
|
||||
|
||||
try:
|
||||
ws_logger.info(f"TX -> {json.dumps(detection_data, separators=(',', ':'))}")
|
||||
ws_rxtx_logger.info(f"TX -> {json.dumps(detection_data, separators=(',', ':'))}")
|
||||
await self.websocket.send_json(detection_data)
|
||||
except RuntimeError as e:
|
||||
if "websocket.close" in str(e):
|
||||
|
@ -571,7 +586,7 @@ class WebSocketHandler:
|
|||
}
|
||||
|
||||
try:
|
||||
ws_logger.info(f"TX -> {json.dumps(detection_data, separators=(',', ':'))}")
|
||||
ws_rxtx_logger.info(f"TX -> {json.dumps(detection_data, separators=(',', ':'))}")
|
||||
await self.websocket.send_json(detection_data)
|
||||
except RuntimeError as e:
|
||||
if "websocket.close" in str(e):
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue