Files
WolfandClaude Opus 5.5 9d666d0937 Bring in pipeline, auth, deploy and docs from the boilerplate
roledesk is built on the boilerplate from here on: pipeline 2.0 (queue and
scheduler), auth (one password, sessions, passkeys), the deploy kit and its
docs, plus the coupling and packaging tests. Downstream copies, unedited.

Refreshed from boilerplate/d56949f7d0f6c0bfe5745478e09007bfad67ae87

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-23 12:29:16 +02:00

57 lines
2.0 KiB
Python

"""One message out to every connected socket.
Deliberately knows nothing about jobs. It holds sockets, sends dicts, and drops
the ones that have gone away — which is the whole of what a fan-out is, and is
the reason the next thing that wants to push (a tag landing, a transcript
finishing, another reader in another tab) can use this rather than grow a
second copy of it.
A dead socket is discovered by writing to it, not by asking: a browser tab that
was closed, slept or navigated away leaves a connection that looks open until
the send fails. So every failure is a removal, and `broadcast` never raises —
one stale subscriber must not cost the others their update.
"""
from __future__ import annotations
import logging
import asyncio
from typing import Any
from fastapi import WebSocket
log = logging.getLogger(__name__)
class Broadcaster:
def __init__(self) -> None:
self._subscribers: set[WebSocket] = set()
@property
def count(self) -> int:
return len(self._subscribers)
async def subscribe(self, ws: WebSocket, hello: dict[str, Any] | None = None) -> None:
"""Register an accepted socket, and send it the current state.
The immediate send matters: a client that connects mid-job would
otherwise see nothing at all until the next change, which for a long
job is a blank progress bar next to work that is visibly happening.
"""
self._subscribers.add(ws)
if hello is not None:
await self._send(ws, hello)
def unsubscribe(self, ws: WebSocket) -> None:
self._subscribers.discard(ws)
async def broadcast(self, message: dict[str, Any]) -> None:
await asyncio.gather(*(self._send(ws, message)
for ws in tuple(self._subscribers)))
async def _send(self, ws: WebSocket, message: dict[str, Any]) -> None:
try:
await asyncio.wait_for(ws.send_json(message), timeout=1.0)
except Exception:
self._subscribers.discard(ws)