test_printer_kill_switch.py 19 KB

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