test_forget_printer.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276
  1. """What Bambuddy keeps per printer id goes when the printer is deleted.
  2. SQLite used to give a deleted printer's id to the next printer created, which
  3. inherited it all: the old print's owner (its prints passed the kill switch and
  4. were billed to that user), the plate-clear gate, pending notifications, the old
  5. camera feed, the old printer's plate-detection references. Ids are no longer
  6. reused, but nothing kept for a printer that is gone should stay.
  7. """
  8. import ast
  9. import asyncio
  10. from pathlib import Path
  11. import pytest
  12. from backend.app import main
  13. pytestmark = pytest.mark.asyncio
  14. GONE, KEPT = 5, 6
  15. # Module-level maps in main.py that are not keyed by a printer, or are kept on
  16. # purpose. Anything else main.py adds must be forgotten with the printer.
  17. NOT_FORGOTTEN = {
  18. "_print_ams_mappings": "keyed by archive (dropped with the printer's expected/active prints)",
  19. "_print_cost_center_ids": "keyed by archive (dropped with the printer's expected/active prints)",
  20. "_print_plate_ids": "keyed by archive (dropped with the printer's expected/active prints)",
  21. "_ams_assignment_locks": "a lock carries nothing over; popping one a task holds would let a second be made",
  22. "_fallback_recovery_locks": "a lock carries nothing over (see its comment on popping)",
  23. "_HMS_FAILURE_REASONS": "constant",
  24. "_ACTIVE_PRINT_STATES": "constant",
  25. "_SENSOR_TARGET_KEYS": "constant",
  26. "PUBLIC_API_ROUTES": "constant",
  27. "_HTML_CACHE_HEADERS": "constant",
  28. }
  29. def _module_maps() -> set[str]:
  30. """Names of main.py's module-level dicts and sets."""
  31. tree = ast.parse(Path(main.__file__).read_text())
  32. names = set()
  33. for node in tree.body:
  34. if isinstance(node, ast.AnnAssign) and isinstance(node.target, ast.Name):
  35. kind = ast.unparse(node.annotation)
  36. if kind.startswith(("dict", "set")):
  37. names.add(node.target.id)
  38. elif isinstance(node, ast.Assign) and len(node.targets) == 1 and isinstance(node.targets[0], ast.Name):
  39. if isinstance(node.value, (ast.Dict, ast.Set)):
  40. names.add(node.targets[0].id)
  41. return names
  42. def _sleeper() -> asyncio.Task:
  43. return asyncio.ensure_future(asyncio.sleep(3600))
  44. def _entries(printer_id: int) -> dict[str, tuple]:
  45. """For each forgotten map: (key, value) for this printer."""
  46. return {
  47. "_active_prints": ((printer_id, "cube.3mf"), 100 + printer_id),
  48. "_expected_prints": ((printer_id, "cube.3mf"), 200 + printer_id),
  49. "_expected_print_creators": ((printer_id, "cube.3mf"), 1),
  50. "_expected_print_registered_at": ((printer_id, "cube.3mf"), 1.0),
  51. "_stage22_finish_frames": (printer_id, b"jpg"),
  52. "_stage22_finish_in_flight": (printer_id, asyncio.Event()),
  53. "_inprint_frame_bank": (printer_id, b"jpg"),
  54. "_inprint_frame_bank_ts": (printer_id, 1.0),
  55. "_printer_reconciled_since_connect": (printer_id, True),
  56. "_printer_kprofiles_primed_since_connect": (printer_id, True),
  57. "_last_progress_milestone": (printer_id, 50),
  58. "_first_layer_notified": (printer_id, True),
  59. "_unauthorized_print_kill_sent": (printer_id, None),
  60. "_kill_switch_notification_tasks": (printer_id, _sleeper()),
  61. "_notified_hms_errors": (printer_id, {"0300_0001": 1.0}),
  62. "_hms_print_state": (printer_id, "RUNNING"),
  63. "_hms_forget_when_gone": (printer_id, {"0300_0001"}),
  64. "_timelapse_baselines": (printer_id, {"video.mp4"}),
  65. "_bed_cool_waiters": (printer_id, {"threshold": 35.0, "filename": "cube", "registered_at": 1.0}),
  66. "_user_stopped_printers": (printer_id, None),
  67. "_printer_last_connected": (printer_id, True),
  68. "_printer_offline_published": (printer_id, None),
  69. "_printer_offline_notify_tasks": (printer_id, _sleeper()),
  70. "_unknown_tag_last_broadcast": (printer_id, {(0, 0): ("uid", "x")}),
  71. "_last_status_broadcast": (printer_id, "hash"),
  72. "_nozzle_count_updated": (printer_id, None),
  73. "_fallback_3mf_retry_tasks": (printer_id, _sleeper()),
  74. "_connection_watchdog_last_attempt": (printer_id, 1.0),
  75. "_ams_index_only_logged": ((printer_id, 0), None),
  76. "_ams_alarm_cooldown": (f"{printer_id}:0:humidity", None),
  77. }
  78. def _put(name: str, key, value) -> None:
  79. target = getattr(main, name)
  80. if isinstance(target, set):
  81. target.add(key)
  82. else:
  83. target[key] = value
  84. def _has(name: str, key) -> bool:
  85. return key in getattr(main, name)
  86. async def test_every_printer_keyed_map_in_main_is_forgotten():
  87. covered = set(_entries(GONE))
  88. unclassified = _module_maps() - covered - set(NOT_FORGOTTEN)
  89. assert not unclassified, (
  90. f"main.py maps neither forgotten with a deleted printer nor listed in NOT_FORGOTTEN: {sorted(unclassified)}"
  91. )
  92. async def test_forget_printer_clears_main_and_keeps_other_printers():
  93. gone, kept = _entries(GONE), _entries(KEPT)
  94. for name in gone:
  95. _put(name, *gone[name])
  96. _put(name, *kept[name])
  97. main._print_ams_mappings[100 + GONE] = [0]
  98. main._print_cost_center_ids[200 + GONE] = 1
  99. main._print_plate_ids[200 + GONE] = 2
  100. pending = {name: gone[name][1] for name in ("_printer_offline_notify_tasks", "_fallback_3mf_retry_tasks")}
  101. try:
  102. await main.forget_printer(GONE)
  103. left = [name for name in gone if _has(name, gone[name][0])]
  104. assert left == []
  105. lost = [name for name in kept if not _has(name, kept[name][0])]
  106. assert lost == []
  107. assert 100 + GONE not in main._print_ams_mappings
  108. assert 200 + GONE not in main._print_cost_center_ids
  109. assert 200 + GONE not in main._print_plate_ids
  110. await asyncio.sleep(0)
  111. assert all(task.cancelled() for task in pending.values())
  112. finally:
  113. for entries in (gone, kept):
  114. for name, (key, value) in entries.items():
  115. target = getattr(main, name)
  116. if isinstance(target, set):
  117. target.discard(key)
  118. else:
  119. target.pop(key, None)
  120. if isinstance(value, asyncio.Task):
  121. value.cancel()
  122. async def test_forget_printer_clears_the_services():
  123. from backend.app.api.routes import camera
  124. from backend.app.services import (
  125. bambu_ftp,
  126. kprofile_drift,
  127. layer_timelapse,
  128. obico_detection,
  129. print_dispatch_context,
  130. usage_tracker,
  131. )
  132. from backend.app.services.printer_manager import printer_manager
  133. printer_manager._current_print_user[GONE] = {"user_id": 1, "username": "alice"}
  134. printer_manager._awaiting_plate_clear.add(GONE)
  135. printer_manager._last_trays[GONE] = {"ams": []}
  136. print_dispatch_context.mark_pending(GONE)
  137. kprofile_drift.note_slot_configured(GONE, 0, 0, -1)
  138. kprofile_drift._watches[(GONE, 0, 1)] = kprofile_drift._SlotWatch()
  139. layer_timelapse._active_sessions[GONE] = type("S", (), {"cleanup": lambda self: None})()
  140. usage_tracker._active_sessions[GONE] = object()
  141. service = obico_detection.obico_detection_service
  142. for attr in ("_states", "_state_keys", "_last_class", "_errors", "_action_fired"):
  143. getattr(service, attr)[GONE] = object()
  144. bambu_ftp._threemf_path_cache[(GONE, "cube")] = Path("/nonexistent/cube.3mf")
  145. camera._last_frames[GONE] = b"jpg"
  146. camera._last_frame_times[GONE] = 1.0
  147. camera._stream_start_times[GONE] = 1.0
  148. camera._active_external_streams[GONE] = 1
  149. from backend.app.api.routes import printers
  150. printers._cover_cache[GONE] = {("Cube", "front"): b"png"}
  151. printers._cover_404_cache[GONE] = {}
  152. await main.forget_printer(GONE)
  153. assert GONE not in printer_manager._current_print_user
  154. assert GONE not in printer_manager._awaiting_plate_clear
  155. assert GONE not in printer_manager._last_trays
  156. assert not print_dispatch_context.adopt(GONE)
  157. assert (GONE, 0, 0) not in kprofile_drift._default_chosen
  158. assert (GONE, 0, 1) not in kprofile_drift._watches
  159. assert GONE not in layer_timelapse._active_sessions
  160. assert GONE not in usage_tracker._active_sessions
  161. for attr in ("_states", "_state_keys", "_last_class", "_errors", "_action_fired"):
  162. assert GONE not in getattr(service, attr), attr
  163. assert (GONE, "cube") not in bambu_ftp._threemf_path_cache
  164. assert GONE not in camera._last_frames
  165. assert GONE not in camera._last_frame_times
  166. assert GONE not in camera._stream_start_times
  167. assert GONE not in camera._active_external_streams
  168. assert GONE not in printers._cover_cache
  169. assert GONE not in printers._cover_404_cache
  170. async def test_the_plate_references_of_a_printer_go(tmp_path, monkeypatch):
  171. from backend.app.services import plate_detection
  172. monkeypatch.setattr(plate_detection, "_get_calibration_dir", lambda: tmp_path)
  173. for printer_id in (GONE, KEPT, 55):
  174. (tmp_path / f"printer_{printer_id}_ref_0.jpg").write_bytes(b"jpg")
  175. (tmp_path / f"printer_{printer_id}_metadata.json").write_text("{}")
  176. plate_detection.remove_printer_references(GONE)
  177. assert sorted(p.name for p in tmp_path.iterdir()) == [
  178. "printer_55_metadata.json",
  179. "printer_55_ref_0.jpg",
  180. f"printer_{KEPT}_metadata.json",
  181. f"printer_{KEPT}_ref_0.jpg",
  182. ]
  183. async def test_the_scheduler_and_live_activities_forget_it():
  184. from backend.app.services.notify_live_activities import notify_live_activities
  185. from backend.app.services.print_scheduler import scheduler
  186. scheduler._upload_backoff[GONE] = 1e12
  187. scheduler._upload_refusals[GONE] = 6
  188. scheduler._upload_refusal_notified.add(GONE)
  189. scheduler._wake_failures[GONE] = 1e12
  190. scheduler._dispatch_holds[GONE] = (1.0, "IDLE", None)
  191. scheduler._auto_dry_units[(GONE, 0)] = {}
  192. for attr in ("_snapshots", "_new_fallbacks", "_started_at", "_progress_resets"):
  193. getattr(notify_live_activities, attr)[GONE] = object()
  194. notify_live_activities._wake.clear()
  195. await main.forget_printer(GONE)
  196. assert GONE not in scheduler._upload_backoff
  197. assert GONE not in scheduler._upload_refusals
  198. assert GONE not in scheduler._upload_refusal_notified
  199. assert GONE not in scheduler._wake_failures
  200. assert GONE not in scheduler._dispatch_holds
  201. assert (GONE, 0) not in scheduler._auto_dry_units
  202. for attr in ("_snapshots", "_new_fallbacks", "_started_at", "_progress_resets"):
  203. assert GONE not in getattr(notify_live_activities, attr), attr
  204. # Its tiles are ended at once (the printer is gone), before a new one takes the id.
  205. assert notify_live_activities._wake.is_set()
  206. @pytest.mark.parametrize("ml_fails", [False, True])
  207. async def test_an_obico_check_in_flight_when_the_printer_goes_ends_quietly(ml_fails):
  208. """The check waits up to 30 s for the ML server. A KeyError there stopped the
  209. poll for every printer; an error written back stuck to the next printer given the id."""
  210. from unittest.mock import AsyncMock, MagicMock, patch
  211. from httpx import Request, Response
  212. from backend.app.services.obico_detection import ObicoDetectionService
  213. service = ObicoDetectionService()
  214. async def ml_call(url, **_kwargs):
  215. service.forget_printer(GONE) # deleted meanwhile
  216. if ml_fails:
  217. raise OSError("ML server gone")
  218. return Response(200, json={"detections": []}, request=Request("GET", url))
  219. client = MagicMock()
  220. client.get = AsyncMock(side_effect=ml_call)
  221. client.__aenter__ = AsyncMock(return_value=client)
  222. client.__aexit__ = AsyncMock(return_value=False)
  223. settings = {"sensitivity": "medium", "snapshot_base_url": "http://b", "ml_url": "http://o", "action": "notify"}
  224. with (
  225. patch("backend.app.services.obico_detection.httpx.AsyncClient", return_value=client),
  226. patch.object(service, "_capture_frame", new=AsyncMock(return_value=b"\xff\xd8jpg\xff\xd9")),
  227. ):
  228. await service._check_printer(GONE, MagicMock(state="RUNNING", task_name="job", subtask_name=""), settings)
  229. for attr in ("_states", "_state_keys", "_last_class", "_errors", "_action_fired"):
  230. assert GONE not in getattr(service, attr), attr
  231. assert service._last_error is None