test_printer_kill_switch.py 18 KB

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