Websocket sends: per-send timeout, parallel broadcast, heartbeat never dies

This commit is contained in:
2026-11-16 14:35:53 +01:00
parent e3605c48ec
commit eae125a469
+26 -18
View File
@@ -147,10 +147,23 @@ class Hub:
self.pending: dict[str, bool] = {}
async def send(self, ws: WebSocket, msg):
# a stalled peer (half-open tcp behind a proxy) must not block everyone else
try:
await ws.send_text(json.dumps(msg, ensure_ascii=False))
await asyncio.wait_for(ws.send_text(json.dumps(msg, ensure_ascii=False)), 5)
except Exception:
pass
self.drop(ws)
def drop(self, ws: WebSocket):
for group in self.screens.values():
group.pop(ws, None)
for group in self.admins.values():
group.discard(ws)
for group in self.voters.values():
for conns in group.values():
conns.discard(ws)
async def send_all(self, conns, msg):
await asyncio.gather(*[self.send(ws, msg) for ws in list(conns)])
def refresh(self, pid, voters=False):
"""debounced push of fresh state to admins + screens (+ every voter)"""
@@ -166,13 +179,9 @@ class Hub:
if not db.poll(pid):
return
if self.admins.get(pid):
st = admin_state(pid)
for ws in list(self.admins[pid]):
await self.send(ws, st)
await self.send_all(self.admins[pid], admin_state(pid))
if self.screens.get(pid):
st = screen_state(pid)
for ws in list(self.screens[pid]):
await self.send(ws, st)
await self.send_all(self.screens[pid], screen_state(pid))
if voters:
for vid in list(self.voters.get(pid, {})):
await self.push_voter(pid, vid)
@@ -185,9 +194,7 @@ class Hub:
v = db.one("SELECT * FROM voters WHERE id=?", vid)
if not v:
return
st = voter_state(pid, v)
for ws in list(conns):
await self.send(ws, st)
await self.send_all(conns, voter_state(pid, v))
def ensure_ticker(self, pid):
t = self.tickers.get(pid)
@@ -214,8 +221,7 @@ class Hub:
url = f"{base}/v/{pid}#{token}"
msg = {"type": "qr", "url": url, "modules": qr_modules(url), "slot": slot,
"interval_ms": iv, "valid_until": (slot + 1) * iv}
for ws in conns:
await self.send(ws, msg)
await self.send_all(conns, msg)
await asyncio.sleep(max(0.01, ((slot + 1) * iv - now_ms()) / 1000))
except asyncio.CancelledError:
pass
@@ -230,11 +236,13 @@ async def heartbeat():
# proxies (cloudflare ~100s) drop idle websockets, keep every socket chatty
while True:
await asyncio.sleep(25)
conns = [ws for group in hub.screens.values() for ws in group]
conns += [ws for group in hub.admins.values() for ws in group]
conns += [ws for group in hub.voters.values() for s in group.values() for ws in s]
for ws in conns:
await hub.send(ws, {"type": "ping"})
try:
conns = [ws for group in hub.screens.values() for ws in group]
conns += [ws for group in hub.admins.values() for ws in group]
conns += [ws for group in hub.voters.values() for s in group.values() for ws in s]
await hub.send_all(conns, {"type": "ping"})
except Exception:
log.exception("heartbeat")
async def body(request: Request) -> dict: