test_printer_kill_switch.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493
  1. from types import SimpleNamespace
  2. from unittest.mock import AsyncMock
  3. import pytest
  4. from backend.app import main as main_module
  5. @pytest.fixture(autouse=True)
  6. def clear_kill_switch_state():
  7. main_module._kill_switch_setting_cache = None
  8. main_module._unauthorized_print_kill_sent.clear()
  9. main_module._kill_switch_notification_tasks.clear()
  10. main_module._expected_prints.clear()
  11. main_module._active_prints.clear()
  12. main_module._expected_print_registered_at.clear()
  13. main_module._printer_reconciled_since_connect.clear()
  14. yield
  15. for task in main_module._kill_switch_notification_tasks.values():
  16. if not task.done():
  17. task.cancel()
  18. main_module._unauthorized_print_kill_sent.clear()
  19. main_module._kill_switch_notification_tasks.clear()
  20. main_module._expected_prints.clear()
  21. main_module._active_prints.clear()
  22. main_module._expected_print_registered_at.clear()
  23. main_module._printer_reconciled_since_connect.clear()
  24. main_module._kill_switch_setting_cache = None
  25. def test_gcode_3mf_status_filename_matches_registered_expected_print():
  26. state = SimpleNamespace(
  27. current_print=None,
  28. subtask_name="",
  29. gcode_file="foreign_job.gcode.3mf",
  30. )
  31. keys = main_module._build_status_print_keys(7, state)
  32. assert (7, "foreign_job.gcode.3mf") in keys
  33. assert (7, "foreign_job.gcode") in keys
  34. @pytest.mark.asyncio
  35. async def test_unauthorized_active_print_triggers_stop(monkeypatch):
  36. stop_calls: list[int] = []
  37. broadcast = AsyncMock()
  38. provider_notification = AsyncMock(return_value=True)
  39. async def fake_status(*args, **kwargs):
  40. return None
  41. async def kill_switch_enabled(_db):
  42. return True
  43. unauthorized = AsyncMock(return_value=False)
  44. monkeypatch.setattr(main_module.printer_manager, "get_current_print_user", lambda printer_id: None)
  45. monkeypatch.setattr(
  46. main_module.printer_manager, "stop_print", lambda printer_id: stop_calls.append(printer_id) or True
  47. )
  48. monkeypatch.setattr(main_module.printer_manager, "get_printer", lambda printer_id: None)
  49. monkeypatch.setattr(main_module.printer_manager, "get_model", lambda printer_id: None)
  50. monkeypatch.setattr(main_module, "printer_state_to_dict", lambda *args, **kwargs: {})
  51. monkeypatch.setattr(main_module.mqtt_relay, "on_printer_status", fake_status)
  52. monkeypatch.setattr(main_module.ws_manager, "send_printer_status", fake_status)
  53. monkeypatch.setattr(main_module.ws_manager, "broadcast", broadcast)
  54. monkeypatch.setattr(main_module, "_is_bambuddy_authorized_print", unauthorized)
  55. monkeypatch.setattr(main_module, "_send_kill_switch_provider_notification", provider_notification)
  56. monkeypatch.setattr("backend.app.services.finance_budget.is_printer_kill_switch_enabled", kill_switch_enabled)
  57. state = SimpleNamespace(
  58. connected=True,
  59. state="RUNNING",
  60. progress=0,
  61. remaining_time=0,
  62. layer_num=0,
  63. temperatures={},
  64. nozzles=[],
  65. raw_data={},
  66. stg_cur=0,
  67. # Real PrinterState always carries these; the status-broadcast dedup
  68. # key reads them so a Filament Track Switch rebind reaches the card.
  69. fila_switch=None,
  70. ams_switch_inlet={},
  71. cooling_fan_speed=None,
  72. big_fan1_speed=None,
  73. big_fan2_speed=None,
  74. chamber_light=False,
  75. active_extruder=0,
  76. tray_now=255,
  77. door_open=False,
  78. ams_filament_backup=False,
  79. current_print=None,
  80. subtask_name="foreign_job",
  81. subtask_id="external-task-1",
  82. gcode_file="foreign_job.gcode",
  83. )
  84. await main_module.on_printer_status_change(7, state)
  85. await main_module.on_printer_status_change(7, state)
  86. assert stop_calls == [7]
  87. unauthorized.assert_awaited_once()
  88. assert 7 in main_module._unauthorized_print_kill_sent
  89. broadcast.assert_awaited_once_with(
  90. {
  91. "type": "kill_switch_triggered",
  92. "printer_id": 7,
  93. "printer_name": "Printer 7",
  94. "filename": "foreign_job",
  95. "reason": "unauthorized_print",
  96. }
  97. )
  98. notification_task = main_module._kill_switch_notification_tasks[7]
  99. assert await notification_task is True
  100. provider_notification.assert_awaited_once_with(
  101. 7,
  102. "Printer 7",
  103. {
  104. "status": "stopped",
  105. "filename": "foreign_job.gcode",
  106. "subtask_name": "foreign_job",
  107. "progress": 0,
  108. "reason": "unauthorized_print",
  109. },
  110. )
  111. @pytest.mark.asyncio
  112. async def test_failed_immediate_notification_allows_completion_retry():
  113. task = main_module.spawn_background_task(_return_false(), name="test-kill-switch-notification-failure")
  114. assert await main_module._kill_switch_notification_already_sent(task) is False
  115. async def _return_false():
  116. return False
  117. @pytest.mark.asyncio
  118. async def test_bambuddy_authorized_print_is_not_stopped(monkeypatch):
  119. monkeypatch.setitem(main_module._expected_prints, (7, "foreign_job"), 123)
  120. stop_calls: list[int] = []
  121. async def fake_status(*args, **kwargs):
  122. return None
  123. kill_switch_enabled = AsyncMock(return_value=True)
  124. monkeypatch.setattr(main_module.printer_manager, "get_current_print_user", lambda printer_id: None)
  125. monkeypatch.setattr(
  126. main_module.printer_manager, "stop_print", lambda printer_id: stop_calls.append(printer_id) or True
  127. )
  128. monkeypatch.setattr(main_module.printer_manager, "get_printer", lambda printer_id: None)
  129. monkeypatch.setattr(main_module.printer_manager, "get_model", lambda printer_id: None)
  130. monkeypatch.setattr(main_module, "printer_state_to_dict", lambda *args, **kwargs: {})
  131. monkeypatch.setattr(main_module.mqtt_relay, "on_printer_status", fake_status)
  132. monkeypatch.setattr(main_module.ws_manager, "send_printer_status", fake_status)
  133. monkeypatch.setattr("backend.app.services.finance_budget.is_printer_kill_switch_enabled", kill_switch_enabled)
  134. state = SimpleNamespace(
  135. connected=True,
  136. state="RUNNING",
  137. progress=0,
  138. remaining_time=0,
  139. layer_num=0,
  140. temperatures={},
  141. nozzles=[],
  142. raw_data={},
  143. stg_cur=0,
  144. # Real PrinterState always carries these; the status-broadcast dedup
  145. # key reads them so a Filament Track Switch rebind reaches the card.
  146. fila_switch=None,
  147. ams_switch_inlet={},
  148. cooling_fan_speed=None,
  149. big_fan1_speed=None,
  150. big_fan2_speed=None,
  151. chamber_light=False,
  152. active_extruder=0,
  153. tray_now=255,
  154. door_open=False,
  155. ams_filament_backup=False,
  156. current_print=None,
  157. subtask_name="foreign_job",
  158. gcode_file="foreign_job.gcode",
  159. )
  160. await main_module.on_printer_status_change(7, state)
  161. assert stop_calls == []
  162. assert 7 not in main_module._unauthorized_print_kill_sent
  163. kill_switch_enabled.assert_not_awaited()
  164. @pytest.mark.asyncio
  165. async def test_kill_switch_setting_is_cached(monkeypatch):
  166. kill_switch_enabled = AsyncMock(return_value=True)
  167. class FakeSessionContext:
  168. async def __aenter__(self):
  169. return SimpleNamespace()
  170. async def __aexit__(self, *_args):
  171. return False
  172. monkeypatch.setattr(main_module, "async_session", FakeSessionContext)
  173. monkeypatch.setattr("backend.app.services.finance_budget.is_printer_kill_switch_enabled", kill_switch_enabled)
  174. assert await main_module._is_printer_kill_switch_enabled_cached() is True
  175. assert await main_module._is_printer_kill_switch_enabled_cached() is True
  176. kill_switch_enabled.assert_awaited_once()
  177. @pytest.mark.asyncio
  178. async def test_unauthorized_print_state_is_cleared_when_print_ends(monkeypatch):
  179. stop_calls: list[int] = []
  180. async def fake_status(*args, **kwargs):
  181. return None
  182. async def kill_switch_enabled(_db):
  183. return True
  184. async def unauthorized(*_args):
  185. return False
  186. monkeypatch.setattr(main_module.printer_manager, "get_current_print_user", lambda printer_id: None)
  187. monkeypatch.setattr(
  188. main_module.printer_manager, "stop_print", lambda printer_id: stop_calls.append(printer_id) or True
  189. )
  190. monkeypatch.setattr(main_module.printer_manager, "get_printer", lambda printer_id: None)
  191. monkeypatch.setattr(main_module.printer_manager, "get_model", lambda printer_id: None)
  192. monkeypatch.setattr(main_module, "printer_state_to_dict", lambda *args, **kwargs: {})
  193. monkeypatch.setattr(main_module.mqtt_relay, "on_printer_status", fake_status)
  194. monkeypatch.setattr(main_module.ws_manager, "send_printer_status", fake_status)
  195. monkeypatch.setattr(main_module, "_is_bambuddy_authorized_print", unauthorized)
  196. monkeypatch.setattr("backend.app.services.finance_budget.is_printer_kill_switch_enabled", kill_switch_enabled)
  197. active_state = SimpleNamespace(
  198. connected=True,
  199. state="RUNNING",
  200. progress=0,
  201. remaining_time=0,
  202. layer_num=0,
  203. temperatures={},
  204. nozzles=[],
  205. raw_data={},
  206. stg_cur=0,
  207. # Real PrinterState always carries these; the status-broadcast dedup
  208. # key reads them so a Filament Track Switch rebind reaches the card.
  209. fila_switch=None,
  210. ams_switch_inlet={},
  211. cooling_fan_speed=None,
  212. big_fan1_speed=None,
  213. big_fan2_speed=None,
  214. chamber_light=False,
  215. active_extruder=0,
  216. tray_now=255,
  217. door_open=False,
  218. ams_filament_backup=False,
  219. current_print=None,
  220. subtask_name="foreign_job",
  221. subtask_id="external-task-1",
  222. gcode_file="foreign_job.gcode",
  223. )
  224. idle_state = SimpleNamespace(
  225. connected=True,
  226. state="IDLE",
  227. progress=0,
  228. remaining_time=0,
  229. layer_num=0,
  230. temperatures={},
  231. nozzles=[],
  232. raw_data={},
  233. stg_cur=0,
  234. # Real PrinterState always carries these; the status-broadcast dedup
  235. # key reads them so a Filament Track Switch rebind reaches the card.
  236. fila_switch=None,
  237. ams_switch_inlet={},
  238. cooling_fan_speed=None,
  239. big_fan1_speed=None,
  240. big_fan2_speed=None,
  241. chamber_light=False,
  242. active_extruder=0,
  243. tray_now=255,
  244. door_open=False,
  245. ams_filament_backup=False,
  246. current_print=None,
  247. subtask_name="",
  248. subtask_id=None,
  249. gcode_file=None,
  250. )
  251. await main_module.on_printer_status_change(7, active_state)
  252. assert stop_calls == [7]
  253. assert 7 in main_module._unauthorized_print_kill_sent
  254. await main_module.on_printer_status_change(7, idle_state)
  255. assert 7 not in main_module._unauthorized_print_kill_sent
  256. @pytest.mark.asyncio
  257. @pytest.mark.parametrize("printer_state", ["RUNNING", "PAUSE"])
  258. async def test_persisted_print_is_authorized_after_restart(monkeypatch, printer_state):
  259. # billing_run_id is the marker the scheduler stamps on its own dispatches;
  260. # an archive without one proves only that Bambuddy watched the print.
  261. archive = SimpleNamespace(
  262. id=123,
  263. filename="owned_job.gcode.3mf",
  264. billing_run_id="d7c1f0b2-0000-4000-8000-000000000001",
  265. created_by_id=None,
  266. )
  267. query_result = SimpleNamespace(scalar_one_or_none=lambda: archive)
  268. db = SimpleNamespace(execute=AsyncMock(return_value=query_result))
  269. class FakeSessionContext:
  270. async def __aenter__(self):
  271. return db
  272. async def __aexit__(self, *_args):
  273. return False
  274. stop_calls: list[int] = []
  275. async def fake_status(*args, **kwargs):
  276. return None
  277. async def kill_switch_enabled(_db):
  278. return True
  279. def discard_background_task(coro, **_kwargs):
  280. coro.close()
  281. monkeypatch.setattr(main_module, "async_session", FakeSessionContext)
  282. monkeypatch.setattr(main_module, "spawn_background_task", discard_background_task)
  283. monkeypatch.setattr(main_module.printer_manager, "get_current_print_user", lambda printer_id: None)
  284. monkeypatch.setattr(
  285. main_module.printer_manager, "stop_print", lambda printer_id: stop_calls.append(printer_id) or True
  286. )
  287. monkeypatch.setattr(main_module.printer_manager, "get_printer", lambda printer_id: None)
  288. monkeypatch.setattr(main_module.printer_manager, "get_model", lambda printer_id: None)
  289. monkeypatch.setattr(main_module, "printer_state_to_dict", lambda *args, **kwargs: {})
  290. monkeypatch.setattr(main_module.mqtt_relay, "on_printer_status", fake_status)
  291. monkeypatch.setattr(main_module.ws_manager, "send_printer_status", fake_status)
  292. monkeypatch.setattr("backend.app.services.finance_budget.is_printer_kill_switch_enabled", kill_switch_enabled)
  293. state = SimpleNamespace(
  294. connected=True,
  295. state=printer_state,
  296. progress=42,
  297. remaining_time=600,
  298. layer_num=50,
  299. temperatures={},
  300. nozzles=[],
  301. raw_data={},
  302. stg_cur=0,
  303. # Real PrinterState always carries these; the status-broadcast dedup
  304. # key reads them so a Filament Track Switch rebind reaches the card.
  305. fila_switch=None,
  306. ams_switch_inlet={},
  307. cooling_fan_speed=None,
  308. big_fan1_speed=None,
  309. big_fan2_speed=None,
  310. chamber_light=False,
  311. active_extruder=0,
  312. tray_now=255,
  313. door_open=False,
  314. ams_filament_backup=False,
  315. current_print=None,
  316. subtask_name="owned_job",
  317. subtask_id="bambuddy-task-123",
  318. gcode_file="owned_job.gcode.3mf",
  319. )
  320. await main_module.on_printer_status_change(7, state)
  321. assert stop_calls == []
  322. assert (7, "owned_job.gcode.3mf") in main_module._active_prints
  323. assert main_module._active_prints[(7, "owned_job.gcode.3mf")] == 123
  324. assert 7 not in main_module._unauthorized_print_kill_sent
  325. @pytest.mark.asyncio
  326. async def test_kill_switch_defers_when_restart_identity_is_not_available(monkeypatch):
  327. state = SimpleNamespace(
  328. current_print=None,
  329. subtask_name="owned_job",
  330. subtask_id=None,
  331. gcode_file="owned_job.gcode.3mf",
  332. )
  333. db = SimpleNamespace(execute=AsyncMock())
  334. monkeypatch.setattr(main_module.printer_manager, "get_current_print_user", lambda printer_id: None)
  335. authorization = await main_module._is_bambuddy_authorized_print(7, state, db)
  336. assert authorization is None
  337. db.execute.assert_not_awaited()
  338. def _authorization_db(archive, dispatched_queue_item_id=None):
  339. """Fake session answering the two lookups `_is_bambuddy_authorized_print` makes."""
  340. query_result = SimpleNamespace(scalar_one_or_none=lambda: archive)
  341. return SimpleNamespace(
  342. execute=AsyncMock(return_value=query_result),
  343. scalar=AsyncMock(return_value=dispatched_queue_item_id),
  344. )
  345. def _running_state(subtask_id="external-task-9"):
  346. return SimpleNamespace(
  347. current_print=None,
  348. subtask_name="some_job",
  349. subtask_id=subtask_id,
  350. gcode_file="some_job.gcode.3mf",
  351. )
  352. @pytest.mark.asyncio
  353. async def test_archive_without_a_dispatch_marker_is_not_authorization(monkeypatch):
  354. """on_print_start archives prints started from Studio or Handy too.
  355. Those rows carry the same status and subtask_id as Bambuddy's own, so treating
  356. the row's existence as proof would switch the feature off a few seconds into
  357. every foreign print — as soon as the 3MF finished downloading.
  358. """
  359. monkeypatch.setattr(main_module.printer_manager, "get_current_print_user", lambda printer_id: None)
  360. observed_only = SimpleNamespace(
  361. id=55,
  362. filename="some_job.gcode.3mf",
  363. billing_run_id=None,
  364. created_by_id=None,
  365. )
  366. db = _authorization_db(observed_only, dispatched_queue_item_id=None)
  367. assert await main_module._is_bambuddy_authorized_print(9, _running_state(), db) is False
  368. assert (9, "some_job.gcode.3mf") not in main_module._active_prints
  369. @pytest.mark.asyncio
  370. @pytest.mark.parametrize(
  371. "marker",
  372. [
  373. {"billing_run_id": "9f0c2b6e-0000-4000-8000-00000000abcd", "created_by_id": None},
  374. {"billing_run_id": None, "created_by_id": 4},
  375. ],
  376. ids=["billing_run_id", "created_by_id"],
  377. )
  378. async def test_either_dispatch_marker_authorizes_after_a_restart(monkeypatch, marker):
  379. monkeypatch.setattr(main_module.printer_manager, "get_current_print_user", lambda printer_id: None)
  380. archive = SimpleNamespace(id=77, filename="some_job.gcode.3mf", **marker)
  381. db = _authorization_db(archive, dispatched_queue_item_id=None)
  382. assert await main_module._is_bambuddy_authorized_print(9, _running_state(), db) is True
  383. assert main_module._active_prints[(9, "some_job.gcode.3mf")] == 77
  384. # The fast path is rehydrated, so the queue is never consulted.
  385. db.scalar.assert_not_awaited()
  386. @pytest.mark.asyncio
  387. async def test_defers_while_bambuddy_has_a_job_running_on_that_printer(monkeypatch):
  388. """A library-file dispatch has no archive at send time, and the row created for
  389. it moments later by on_print_start carries neither marker. The queue row is the
  390. only durable trace, and it cannot be tied to a subtask_id — so it defers."""
  391. monkeypatch.setattr(main_module.printer_manager, "get_current_print_user", lambda printer_id: None)
  392. unmarked = SimpleNamespace(id=56, filename="some_job.gcode.3mf", billing_run_id=None, created_by_id=None)
  393. db = _authorization_db(unmarked, dispatched_queue_item_id=310)
  394. assert await main_module._is_bambuddy_authorized_print(9, _running_state(), db) is None
  395. # Deferring must not authorize the print for every later frame.
  396. assert (9, "some_job.gcode.3mf") not in main_module._active_prints
  397. @pytest.mark.asyncio
  398. async def test_defers_when_the_dispatch_has_not_been_archived_yet(monkeypatch):
  399. """Restart during the window between the MQTT send and the 3MF download."""
  400. monkeypatch.setattr(main_module.printer_manager, "get_current_print_user", lambda printer_id: None)
  401. db = _authorization_db(None, dispatched_queue_item_id=311)
  402. assert await main_module._is_bambuddy_authorized_print(9, _running_state(), db) is None
  403. @pytest.mark.asyncio
  404. async def test_foreign_print_with_no_archive_and_no_dispatch_is_unauthorized(monkeypatch):
  405. monkeypatch.setattr(main_module.printer_manager, "get_current_print_user", lambda printer_id: None)
  406. db = _authorization_db(None, dispatched_queue_item_id=None)
  407. assert await main_module._is_bambuddy_authorized_print(9, _running_state(), db) is False