Fixed auto approver
This commit is contained in:
53
sia/web/auto_approver_websocket.py
Normal file
53
sia/web/auto_approver_websocket.py
Normal file
@@ -0,0 +1,53 @@
|
||||
from aiohttp import web, WSMsgType
|
||||
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": 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": 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
|
||||
Reference in New Issue
Block a user