test_connection_watchdog.py 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157
  1. """Tests for the dead-MQTT-session watchdog (#2732).
  2. ``check_staleness()`` guards the "connected but silent" session and returns
  3. immediately once ``state.connected`` is False — from there, paho's own
  4. auto-reconnect is the only thing still watching. The #2732 bundle shows what
  5. happens when that stops making progress: a P1S dropped on a keep-alive timeout
  6. at 02:19 and did not reconnect until 11:24, nine hours offline with the UI open
  7. throughout.
  8. This watchdog is the backstop. The rules it has to keep are narrow on purpose —
  9. it must not interfere with a session that is recovering on its own, and it must
  10. not churn clients for printers that are simply switched off.
  11. """
  12. import time
  13. from types import SimpleNamespace
  14. from unittest.mock import AsyncMock, MagicMock, patch
  15. import pytest
  16. from backend.app.main import (
  17. CONNECTION_WATCHDOG_OFFLINE_GRACE,
  18. CONNECTION_WATCHDOG_RETRY_INTERVAL,
  19. _connection_watchdog_last_attempt,
  20. _recover_dead_printer_sessions,
  21. )
  22. def _client(*, connected: bool, last_message_age: float | None, ip: str = "192.168.1.100"):
  23. """Stand-in for BambuMQTTClient with only the fields the watchdog reads."""
  24. return SimpleNamespace(
  25. state=SimpleNamespace(connected=connected),
  26. _last_message_time=0.0 if last_message_age is None else time.time() - last_message_age,
  27. ip_address=ip,
  28. last_connect_error=None,
  29. force_reconnect_stale_session=MagicMock(),
  30. )
  31. async def _sweep(clients: dict, *, port_open: bool = True):
  32. with (
  33. patch("backend.app.main.printer_manager._clients", clients),
  34. patch("backend.app.services.printer_diagnostic.check_port", AsyncMock(return_value=port_open)),
  35. ):
  36. return await _recover_dead_printer_sessions()
  37. @pytest.fixture(autouse=True)
  38. def _clear_cooldowns():
  39. _connection_watchdog_last_attempt.clear()
  40. yield
  41. _connection_watchdog_last_attempt.clear()
  42. class TestRebuildsDeadSessions:
  43. @pytest.mark.asyncio
  44. async def test_rebuilds_a_long_dead_session(self):
  45. """The #2732 case: offline for hours, printer answering the whole time."""
  46. client = _client(connected=False, last_message_age=32718.0)
  47. assert await _sweep({1: client}) == 1
  48. client.force_reconnect_stale_session.assert_called_once()
  49. @pytest.mark.asyncio
  50. async def test_reconnect_reason_names_the_duration(self):
  51. client = _client(connected=False, last_message_age=32718.0)
  52. await _sweep({1: client})
  53. assert "32718" in client.force_reconnect_stale_session.call_args.args[0]
  54. @pytest.mark.asyncio
  55. async def test_sweeps_every_printer_in_the_farm(self):
  56. clients = {i: _client(connected=False, last_message_age=9999.0) for i in range(1, 4)}
  57. assert await _sweep(clients) == 3
  58. class TestLeavesHealthyAndRecoveringSessionsAlone:
  59. @pytest.mark.asyncio
  60. async def test_connected_printer_is_untouched(self):
  61. client = _client(connected=True, last_message_age=99999.0)
  62. assert await _sweep({1: client}) == 0
  63. client.force_reconnect_stale_session.assert_not_called()
  64. @pytest.mark.asyncio
  65. async def test_inside_the_grace_period_paho_keeps_the_job(self):
  66. """Below the grace window a reconnect may well be in flight; interrupting
  67. it would turn a self-healing blip into a forced session rebuild."""
  68. client = _client(connected=False, last_message_age=CONNECTION_WATCHDOG_OFFLINE_GRACE - 30)
  69. assert await _sweep({1: client}) == 0
  70. client.force_reconnect_stale_session.assert_not_called()
  71. @pytest.mark.asyncio
  72. async def test_a_client_that_never_had_a_session_is_left_to_paho(self):
  73. """No inbound message ever means this is the initial connect, where
  74. retrying is both correct and the only thing to do."""
  75. client = _client(connected=False, last_message_age=None)
  76. assert await _sweep({1: client}) == 0
  77. client.force_reconnect_stale_session.assert_not_called()
  78. @pytest.mark.asyncio
  79. async def test_reconnecting_clears_the_cooldown(self):
  80. """A printer that comes back must not carry a stale cooldown into its
  81. next outage."""
  82. client = _client(connected=False, last_message_age=9999.0)
  83. await _sweep({1: client})
  84. assert 1 in _connection_watchdog_last_attempt
  85. client.state.connected = True
  86. await _sweep({1: client})
  87. assert 1 not in _connection_watchdog_last_attempt
  88. class TestUnreachablePrinters:
  89. @pytest.mark.asyncio
  90. async def test_switched_off_printer_is_not_rebuilt(self):
  91. """Rebuilding a client against a host that isn't answering achieves
  92. nothing and would log a warning per printer all night."""
  93. client = _client(connected=False, last_message_age=9999.0)
  94. assert await _sweep({1: client}, port_open=False) == 0
  95. client.force_reconnect_stale_session.assert_not_called()
  96. @pytest.mark.asyncio
  97. async def test_unreachable_printer_still_takes_the_cooldown(self):
  98. """Otherwise every sweep re-probes the port of every dead printer."""
  99. client = _client(connected=False, last_message_age=9999.0)
  100. await _sweep({1: client}, port_open=False)
  101. assert 1 in _connection_watchdog_last_attempt
  102. class TestRetryInterval:
  103. @pytest.mark.asyncio
  104. async def test_does_not_rebuild_again_within_the_interval(self):
  105. client = _client(connected=False, last_message_age=9999.0)
  106. assert await _sweep({1: client}) == 1
  107. assert await _sweep({1: client}) == 0
  108. client.force_reconnect_stale_session.assert_called_once()
  109. @pytest.mark.asyncio
  110. async def test_retries_once_the_interval_has_passed(self):
  111. client = _client(connected=False, last_message_age=9999.0)
  112. await _sweep({1: client})
  113. _connection_watchdog_last_attempt[1] -= CONNECTION_WATCHDOG_RETRY_INTERVAL + 1
  114. assert await _sweep({1: client}) == 1
  115. assert client.force_reconnect_stale_session.call_count == 2
  116. class TestSweepIsFaultTolerant:
  117. @pytest.mark.asyncio
  118. async def test_one_broken_client_does_not_stop_the_others(self):
  119. """A farm sweep that aborts on the first bad client would leave every
  120. printer after it unrecovered."""
  121. bad = _client(connected=False, last_message_age=9999.0)
  122. bad.force_reconnect_stale_session.side_effect = RuntimeError("boom")
  123. good = _client(connected=False, last_message_age=9999.0)
  124. assert await _sweep({1: bad, 2: good}) == 2
  125. good.force_reconnect_stale_session.assert_called_once()