websocket.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316
  1. import asyncio
  2. import json
  3. import logging
  4. from typing import Any
  5. from fastapi import WebSocket
  6. logger = logging.getLogger(__name__)
  7. def _message_printer_id(message: dict[str, Any]) -> int | None:
  8. """The printer a broadcast is about, if any: top-level or inside ``data``."""
  9. printer_id = message.get("printer_id")
  10. if printer_id is None:
  11. data = message.get("data")
  12. if isinstance(data, dict):
  13. printer_id = data.get("printer_id")
  14. return printer_id if isinstance(printer_id, int) else None
  15. def _may_receive(connection: WebSocket, printer_id: int | None) -> bool:
  16. """Whether ``connection``'s printer scope (#1727) covers ``printer_id``.
  17. The scope is stamped on the socket at connect (``routes/websocket.py``).
  18. A socket without one is refused anything printer-bound, so a connection
  19. that slipped past the stamping can't receive every printer's events.
  20. """
  21. if printer_id is None:
  22. return True
  23. scope = getattr(connection.state, "bambuddy_printer_scope", None)
  24. return scope is not None and scope.allows(printer_id)
  25. class ConnectionManager:
  26. """Manages WebSocket connections and broadcasts."""
  27. def __init__(self):
  28. self.active_connections: list[WebSocket] = []
  29. self._lock = asyncio.Lock()
  30. async def connect(self, websocket: WebSocket):
  31. """Accept a new WebSocket connection."""
  32. await websocket.accept()
  33. async with self._lock:
  34. self.active_connections.append(websocket)
  35. async def disconnect(self, websocket: WebSocket):
  36. """Remove a WebSocket connection."""
  37. async with self._lock:
  38. if websocket in self.active_connections:
  39. self.active_connections.remove(websocket)
  40. async def broadcast(self, message: dict[str, Any]):
  41. """Broadcast a message to all connected clients."""
  42. if not self.active_connections:
  43. return
  44. data = json.dumps(message)
  45. printer_id = _message_printer_id(message)
  46. async with self._lock:
  47. disconnected = []
  48. for connection in self.active_connections:
  49. if not _may_receive(connection, printer_id):
  50. continue
  51. try:
  52. await connection.send_text(data)
  53. except Exception:
  54. disconnected.append(connection)
  55. # Clean up disconnected clients
  56. for conn in disconnected:
  57. if conn in self.active_connections:
  58. self.active_connections.remove(conn)
  59. async def broadcast_to_user(self, user_id: int | None, message: dict[str, Any]):
  60. """Send a message to every connection authenticated as the given user.
  61. When ``user_id`` is None the message fans out to all connections —
  62. this is the auth-disabled single-user path, where neither the queue
  63. item's ``created_by_id`` nor the WS principal is set, and the
  64. existing fan-out semantics are exactly what the user wants.
  65. Per-user routing reads ``websocket.state.bambuddy_principal_user_id``
  66. stamped at connect time (``routes/websocket.py``). Connections
  67. without a stamped id are skipped on the targeted path so an
  68. anonymous reader never receives another user's dispatch toast.
  69. """
  70. if user_id is None:
  71. await self.broadcast(message)
  72. return
  73. if not self.active_connections:
  74. return
  75. data = json.dumps(message)
  76. printer_id = _message_printer_id(message)
  77. async with self._lock:
  78. disconnected = []
  79. for connection in self.active_connections:
  80. conn_uid = getattr(connection.state, "bambuddy_principal_user_id", None)
  81. if conn_uid != user_id or not _may_receive(connection, printer_id):
  82. continue
  83. try:
  84. await connection.send_text(data)
  85. except Exception:
  86. disconnected.append(connection)
  87. for conn in disconnected:
  88. if conn in self.active_connections:
  89. self.active_connections.remove(conn)
  90. async def close_user(self, user_id: int):
  91. """Close a deleted user's sockets, which would otherwise keep receiving
  92. the messages of whoever is given their id next."""
  93. async with self._lock:
  94. theirs = [
  95. c for c in self.active_connections if getattr(c.state, "bambuddy_principal_user_id", None) == user_id
  96. ]
  97. for connection in theirs:
  98. self.active_connections.remove(connection)
  99. for connection in theirs:
  100. try:
  101. await connection.close(code=4401)
  102. except Exception: # noqa: BLE001 -- already gone
  103. pass
  104. async def refresh_printer_scopes(self):
  105. """Recompute every connection's printer scope (#1727).
  106. Called after an admin changes which printers a group may see, or who
  107. is in a group, so open dashboards stop (or start) receiving those
  108. printers' events without a reconnect.
  109. """
  110. from backend.app.core.auth import is_auth_enabled, principal_printer_scope
  111. from backend.app.core.database import async_session
  112. from backend.app.core.printer_scope import ALL_PRINTERS, PrinterScope
  113. async with self._lock:
  114. connections = list(self.active_connections)
  115. if not connections:
  116. return
  117. try:
  118. async with async_session() as db:
  119. auth_enabled = await is_auth_enabled(db)
  120. for connection in connections:
  121. if not auth_enabled:
  122. connection.state.bambuddy_printer_scope = ALL_PRINTERS
  123. continue
  124. username, api_key_id = getattr(connection.state, "bambuddy_scope_principal", (None, None))
  125. connection.state.bambuddy_printer_scope = await principal_printer_scope(db, username, api_key_id)
  126. except Exception: # SEC-AUTH-EXC: refresh failed → fail closed (empty scope, then disconnect to re-auth)
  127. # The old scopes may be wider than what was just granted, so they
  128. # can't be kept. Drop every socket to no printers and close it with
  129. # the "unauthorised" code: the SPA mints a new token and reconnects,
  130. # and its scope is worked out afresh at connect.
  131. logger.warning("WebSocket printer scope refresh failed; disconnecting clients", exc_info=True)
  132. for connection in connections:
  133. connection.state.bambuddy_printer_scope = PrinterScope(frozenset())
  134. try:
  135. await connection.close(code=4401)
  136. except Exception: # noqa: BLE001 -- already gone; disconnect() cleans it up
  137. pass
  138. async def send_printer_status(self, printer_id: int, status: dict):
  139. """Send printer status update to all clients."""
  140. await self.broadcast(
  141. {
  142. "type": "printer_status",
  143. "printer_id": printer_id,
  144. "data": status,
  145. }
  146. )
  147. async def send_print_start(self, printer_id: int, data: dict):
  148. """Notify clients that a print has started."""
  149. await self.broadcast(
  150. {
  151. "type": "print_start",
  152. "printer_id": printer_id,
  153. "data": data,
  154. }
  155. )
  156. async def send_print_complete(self, printer_id: int, data: dict):
  157. """Notify clients that a print has completed."""
  158. await self.broadcast(
  159. {
  160. "type": "print_complete",
  161. "printer_id": printer_id,
  162. "data": data,
  163. }
  164. )
  165. async def send_print_confirm_request(self, printer_id: int, data: dict):
  166. """Ask connected clients for a post-print outcome verdict (#1898)."""
  167. await self.broadcast(
  168. {
  169. "type": "print_confirm_request",
  170. "printer_id": printer_id,
  171. "data": data,
  172. }
  173. )
  174. async def send_archive_created(self, archive: dict):
  175. """Notify clients that a new archive was created."""
  176. await self.broadcast(
  177. {
  178. "type": "archive_created",
  179. "data": archive,
  180. }
  181. )
  182. async def send_archive_updated(self, archive: dict):
  183. """Notify clients that an archive was updated."""
  184. await self.broadcast(
  185. {
  186. "type": "archive_updated",
  187. "data": archive,
  188. }
  189. )
  190. async def send_queue_item_uploading(
  191. self,
  192. user_id: int | None,
  193. queue_item_id: int,
  194. printer_id: int,
  195. printer_name: str | None,
  196. file_name: str,
  197. total_bytes: int,
  198. ):
  199. """Toast trigger: scheduler picked the item up, FTP upload starts."""
  200. await self.broadcast_to_user(
  201. user_id,
  202. {
  203. "type": "queue_item_uploading",
  204. "queue_item_id": queue_item_id,
  205. "printer_id": printer_id,
  206. "printer_name": printer_name,
  207. "file_name": file_name,
  208. "total_bytes": total_bytes,
  209. },
  210. )
  211. async def send_queue_item_upload_progress(
  212. self,
  213. user_id: int | None,
  214. queue_item_id: int,
  215. bytes_transferred: int,
  216. total_bytes: int,
  217. ):
  218. """Toast update: throttled byte-level progress during the FTP upload."""
  219. pct = int(round(100 * bytes_transferred / total_bytes)) if total_bytes else 0
  220. await self.broadcast_to_user(
  221. user_id,
  222. {
  223. "type": "queue_item_upload_progress",
  224. "queue_item_id": queue_item_id,
  225. "bytes_transferred": bytes_transferred,
  226. "total_bytes": total_bytes,
  227. "pct": pct,
  228. },
  229. )
  230. async def send_queue_item_acked(
  231. self,
  232. user_id: int | None,
  233. queue_item_id: int,
  234. printer_id: int,
  235. ):
  236. """Toast trigger: watchdog confirmed the printer transitioned out of pre_state."""
  237. await self.broadcast_to_user(
  238. user_id,
  239. {
  240. "type": "queue_item_acked",
  241. "queue_item_id": queue_item_id,
  242. "printer_id": printer_id,
  243. },
  244. )
  245. async def send_queue_item_failed(
  246. self,
  247. user_id: int | None,
  248. queue_item_id: int,
  249. printer_id: int | None,
  250. reason: str,
  251. ):
  252. """Toast trigger: dispatch failed at any stage. Toast turns red, auto-dismisses."""
  253. await self.broadcast_to_user(
  254. user_id,
  255. {
  256. "type": "queue_item_failed",
  257. "queue_item_id": queue_item_id,
  258. "printer_id": printer_id,
  259. "reason": reason,
  260. },
  261. )
  262. async def send_missing_spool_assignment(
  263. self,
  264. printer_id: int,
  265. printer_name: str,
  266. missing_slots: list[dict[str, str]],
  267. ):
  268. """Notify clients that a print started with missing spool assignments."""
  269. await self.broadcast(
  270. {
  271. "type": "missing_spool_assignment",
  272. "printer_id": printer_id,
  273. "printer_name": printer_name,
  274. "missing_slots": missing_slots,
  275. }
  276. )
  277. # Global connection manager
  278. ws_manager = ConnectionManager()