test_printer_kill_switch.py 18 KB

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