Fix websocket lock

This commit is contained in:
Nexus 2023-11-07 14:00:47 +00:00
parent f79247928c
commit b673459f19
Signed by: nex
GPG key ID: 0FA334385D0B689F

View file

@ -292,23 +292,33 @@ async def bridge(req: Request):
@app.websocket("/bridge/recv") @app.websocket("/bridge/recv")
async def bridge_recv(ws: WebSocket, secret: str = Header(None)): async def bridge_recv(ws: WebSocket, secret: str = Header(None)):
await ws.accept() await ws.accept()
print("Websocket %r accepted.", ws)
if secret != app.state.bot.http.token: if secret != app.state.bot.http.token:
print("Closing websocket %r, invalid secret.", ws)
raise _WSException(code=1008, reason="Invalid Secret") raise _WSException(code=1008, reason="Invalid Secret")
if app.state.ws_connected.locked(): if app.state.ws_connected.locked():
print("Closing websocket %r, already connected.", ws)
raise _WSException(code=1008, reason="Already connected.") raise _WSException(code=1008, reason="Already connected.")
queue: asyncio.Queue = app.state.bot.bridge_queue queue: asyncio.Queue = app.state.bot.bridge_queue
async with app.state.ws_connected: async with app.state.ws_connected:
while True: while True:
try: try:
data = queue.get_nowait() await ws.send_json({"status": "ping"})
except asyncio.QueueEmpty: except (WebSocketDisconnect, WebSocketException):
await asyncio.sleep(0.5) print("Websocket %r disconnected.", ws)
break
try:
data = await asyncio.wait_for(queue.get(), timeout=5)
except asyncio.TimeoutError:
continue continue
try: try:
print("Sent data %r to websocket %r.", data, ws)
await ws.send_json(data) await ws.send_json(data)
except (WebSocketDisconnect, WebSocketException): except (WebSocketDisconnect, WebSocketException):
print("Websocket %r disconnected.", ws)
break break
finally: finally:
queue.task_done() queue.task_done()