Files
SIA/sia/web/auto_approver_websocket.py

55 lines
1.8 KiB
Python

from aiohttp import web, WSMsgType
from dataclasses import asdict
from typing import Dict, Set
from ..auto_approver import AutoApprover, AutoApproverConfig
from .util import wrap_async
class AutoApproverWebSocket:
"""
WebSocket handler for AutoApprover configuration.
Broadcasts config updates to all connected clients.
"""
def __init__(self, auto_approver: AutoApprover):
self._auto_approver = auto_approver
self._clients: Set[web.WebSocketResponse] = set()
self._auto_approver.add_config_change_handler(wrap_async(self._handle_config_change))
async def _broadcast_message(self, message: Dict):
"""Broadcast message to all connected clients."""
disconnected = set()
for ws in self._clients:
try:
await ws.send_json(message)
except ConnectionResetError:
disconnected.add(ws)
self._clients -= disconnected
async def _handle_config_change(self, config: AutoApproverConfig):
"""Handle config changes from the AutoApprover."""
await self._broadcast_message({
"config": asdict(config)
})
async def handle_connection(self, request: web.Request) -> web.WebSocketResponse:
"""Handle new WebSocket connections."""
ws = web.WebSocketResponse(heartbeat=30)
await ws.prepare(request)
self._clients.add(ws)
try:
# Send initial config
await ws.send_json({
"config": asdict(self._auto_approver.config)
})
async for msg in ws:
if msg.type == WSMsgType.ERROR:
print(f"WebSocket connection closed with error: {ws.exception()}")
finally:
self._clients.remove(ws)
return ws