websocket.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343
  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. await self._close(lambda c: getattr(c.state, "bambuddy_principal_user_id", None) == user_id)
  94. async def close_api_keys(self, key_ids):
  95. """Close the sockets opened with deleted API keys. Their scope is looked
  96. up by key id on every refresh: SQLite gives the id to the next key."""
  97. key_ids = set(key_ids)
  98. await self._close(lambda c: getattr(c.state, "bambuddy_scope_principal", (None, None))[1] in key_ids)
  99. async def _close(self, matches):
  100. async with self._lock:
  101. theirs = [c for c in self.active_connections if matches(c)]
  102. for connection in theirs:
  103. self.active_connections.remove(connection)
  104. for connection in theirs:
  105. try:
  106. await connection.close(code=4401)
  107. except Exception: # noqa: BLE001 -- already gone
  108. pass
  109. async def refresh_printer_scopes(self):
  110. """Recompute every connection's printer scope (#1727).
  111. Called after an admin changes which printers a group may see, or who
  112. is in a group, so open dashboards stop (or start) receiving those
  113. printers' events without a reconnect.
  114. """
  115. from backend.app.core.auth import is_auth_enabled, principal_printer_scope
  116. from backend.app.core.database import async_session
  117. from backend.app.core.printer_scope import ALL_PRINTERS, PrinterScope
  118. async with self._lock:
  119. connections = list(self.active_connections)
  120. if not connections:
  121. return
  122. from sqlalchemy import select
  123. from backend.app.models.api_key import APIKey
  124. orphaned = []
  125. try:
  126. async with async_session() as db:
  127. auth_enabled = await is_auth_enabled(db)
  128. for connection in connections:
  129. if not auth_enabled:
  130. connection.state.bambuddy_printer_scope = ALL_PRINTERS
  131. continue
  132. username, api_key_id = getattr(connection.state, "bambuddy_scope_principal", (None, None))
  133. if api_key_id is not None:
  134. # The key is looked up by id, which SQLite gives to the
  135. # next key created: a socket whose key is gone, or whose
  136. # id another key now has, is closed, not re-scoped (a key
  137. # rotated from the command line, which can't close it).
  138. prefix = (
  139. await db.execute(select(APIKey.key_prefix).where(APIKey.id == api_key_id))
  140. ).scalar_one_or_none()
  141. if prefix is None or prefix != getattr(connection.state, "bambuddy_api_key_prefix", prefix):
  142. connection.state.bambuddy_printer_scope = PrinterScope(frozenset())
  143. orphaned.append(connection)
  144. continue
  145. connection.state.bambuddy_printer_scope = await principal_printer_scope(db, username, api_key_id)
  146. except Exception: # SEC-AUTH-EXC: refresh failed → fail closed (empty scope, then disconnect to re-auth)
  147. # The old scopes may be wider than what was just granted, so they
  148. # can't be kept. Drop every socket to no printers and close it with
  149. # the "unauthorised" code: the SPA mints a new token and reconnects,
  150. # and its scope is worked out afresh at connect.
  151. logger.warning("WebSocket printer scope refresh failed; disconnecting clients", exc_info=True)
  152. for connection in connections:
  153. connection.state.bambuddy_printer_scope = PrinterScope(frozenset())
  154. try:
  155. await connection.close(code=4401)
  156. except Exception: # noqa: BLE001 -- already gone; disconnect() cleans it up
  157. pass
  158. return
  159. if orphaned:
  160. await self._close(lambda c: c in orphaned)
  161. async def send_printer_status(self, printer_id: int, status: dict):
  162. """Send printer status update to all clients."""
  163. await self.broadcast(
  164. {
  165. "type": "printer_status",
  166. "printer_id": printer_id,
  167. "data": status,
  168. }
  169. )
  170. async def send_print_start(self, printer_id: int, data: dict):
  171. """Notify clients that a print has started."""
  172. await self.broadcast(
  173. {
  174. "type": "print_start",
  175. "printer_id": printer_id,
  176. "data": data,
  177. }
  178. )
  179. async def send_print_complete(self, printer_id: int, data: dict):
  180. """Notify clients that a print has completed."""
  181. await self.broadcast(
  182. {
  183. "type": "print_complete",
  184. "printer_id": printer_id,
  185. "data": data,
  186. }
  187. )
  188. async def send_print_confirm_request(self, printer_id: int, data: dict):
  189. """Ask connected clients for a post-print outcome verdict (#1898)."""
  190. await self.broadcast(
  191. {
  192. "type": "print_confirm_request",
  193. "printer_id": printer_id,
  194. "data": data,
  195. }
  196. )
  197. async def send_archive_created(self, archive: dict):
  198. """Notify clients that a new archive was created."""
  199. await self.broadcast(
  200. {
  201. "type": "archive_created",
  202. "data": archive,
  203. }
  204. )
  205. async def send_archive_updated(self, archive: dict):
  206. """Notify clients that an archive was updated."""
  207. await self.broadcast(
  208. {
  209. "type": "archive_updated",
  210. "data": archive,
  211. }
  212. )
  213. async def send_queue_item_uploading(
  214. self,
  215. user_id: int | None,
  216. queue_item_id: int,
  217. printer_id: int,
  218. printer_name: str | None,
  219. file_name: str,
  220. total_bytes: int,
  221. ):
  222. """Toast trigger: scheduler picked the item up, FTP upload starts."""
  223. await self.broadcast_to_user(
  224. user_id,
  225. {
  226. "type": "queue_item_uploading",
  227. "queue_item_id": queue_item_id,
  228. "printer_id": printer_id,
  229. "printer_name": printer_name,
  230. "file_name": file_name,
  231. "total_bytes": total_bytes,
  232. },
  233. )
  234. async def send_queue_item_upload_progress(
  235. self,
  236. user_id: int | None,
  237. queue_item_id: int,
  238. bytes_transferred: int,
  239. total_bytes: int,
  240. ):
  241. """Toast update: throttled byte-level progress during the FTP upload."""
  242. pct = int(round(100 * bytes_transferred / total_bytes)) if total_bytes else 0
  243. await self.broadcast_to_user(
  244. user_id,
  245. {
  246. "type": "queue_item_upload_progress",
  247. "queue_item_id": queue_item_id,
  248. "bytes_transferred": bytes_transferred,
  249. "total_bytes": total_bytes,
  250. "pct": pct,
  251. },
  252. )
  253. async def send_queue_item_acked(
  254. self,
  255. user_id: int | None,
  256. queue_item_id: int,
  257. printer_id: int,
  258. ):
  259. """Toast trigger: watchdog confirmed the printer transitioned out of pre_state."""
  260. await self.broadcast_to_user(
  261. user_id,
  262. {
  263. "type": "queue_item_acked",
  264. "queue_item_id": queue_item_id,
  265. "printer_id": printer_id,
  266. },
  267. )
  268. async def send_queue_item_failed(
  269. self,
  270. user_id: int | None,
  271. queue_item_id: int,
  272. printer_id: int | None,
  273. reason: str,
  274. ):
  275. """Toast trigger: dispatch failed at any stage. Toast turns red, auto-dismisses."""
  276. await self.broadcast_to_user(
  277. user_id,
  278. {
  279. "type": "queue_item_failed",
  280. "queue_item_id": queue_item_id,
  281. "printer_id": printer_id,
  282. "reason": reason,
  283. },
  284. )
  285. async def send_missing_spool_assignment(
  286. self,
  287. printer_id: int,
  288. printer_name: str,
  289. missing_slots: list[dict[str, str]],
  290. ):
  291. """Notify clients that a print started with missing spool assignments."""
  292. await self.broadcast(
  293. {
  294. "type": "missing_spool_assignment",
  295. "printer_id": printer_id,
  296. "printer_name": printer_name,
  297. "missing_slots": missing_slots,
  298. }
  299. )
  300. # Global connection manager
  301. ws_manager = ConnectionManager()