Selaa lähdekoodia

Queue: a printer that reconnects is not held to its upload backoff (#3563)

- The backoff after a refused upload (up to an hour) ended only on its
  timer, so a printer fixed by a restart kept its jobs waiting, and only
  a Bambuddy restart sent them
- PrintScheduler.printer_reconnected(): a disconnected -> connected edge
  in on_printer_status_change ends the printer's backoff; the refusal
  count and notified text stay, so a printer that still refuses gets the
  next, longer wait and no second Job Waiting
- BambuFTPClient.clear_handshake_cooloff(): the reconnect also drops the
  FTP handshake cool-off from before it, which would fail the first try
- Not on Bambuddy's own start (no previous connection state)
- Tests: reconnect dispatches, still refusing doubles the wait, FTP
  cool-off per IP, the edge in main
maziggy 5 päivää sitten
vanhempi
sitoutus
8bd294eeff

+ 1 - 0
CHANGELOG.md

@@ -14,6 +14,7 @@ All notable changes to Bambuddy will be documented in this file.
 - **Choose which printer an "Any model" job takes (#2915, requested by @bryanmahin, contributed by @Keybored02 in #3547)** — Several printers of a model can take an "Any model" job, and the one with the fewest print hours always got it. **Settings > Workflow > Printer Order for Any-Model Jobs** now chooses: the fewest print hours (the default, as before), the most (use up the machines near replacement first), the printer idle the longest (by its last finished print; one that never printed goes first), or the printers' own priority, a number in **Edit Printer** (lowest first, none last). The order only ranks printers that can take the job: a busy, offline or filament-short printer is still passed over, and preferred colours still come first. Powering a printer on with an Auto Power On plug follows the same order.
 
 ### Fixed
+- **A printer that reconnects no longer waits out its upload backoff (#3563, reported by @Costyv95)** — When a printer's file service stops answering, Bambuddy sends it no jobs for a while, five minutes after the first refused upload and doubling up to an hour. Restarting the printer fixed its file service, but the queue still waited out the rest of that hour, and only restarting Bambuddy sent the job. A printer that reconnects is now tried again on the next pass, and the FTP cool-off from before the reconnect no longer blocks that try. If it still refuses, the next wait is the longer one and no second Job Waiting notification is sent. Wiki updated.
 - **Spoolman mode reads the subtype and colour from a filament named after its product (#3561, reported by @ARGACE)** — Spoolman has no subtype or colour-name field, so Bambuddy reads both from the filament's name, and it only understood names it writes itself ("PLA Matte"). A filament named "Matte Scarlet Red", "Silk+ Baby Blue" or "Gold - Basic PLA" got its whole name as the subtype and no colour, so the spool form left the colour blank. The finish words (Basic, Matte, Silk, HF, ...) are now the subtype and the rest of the name is the colour, wherever the material stands in it. Saving a spool also renamed its Spoolman filament to "material subtype" on every save; the name is now only rebuilt when the material or subtype is changed.
 - **Spool labels print Chinese, Japanese and Korean (#3560, reported by @mohan456-wqs)** — Since labels embed Liberation Sans (#3553), every character was drawn in that font, which has no Chinese, Japanese or Korean, so names in those languages came out as empty boxes in the PDF and in the preview. Installing fonts in the container could not help, because labels only use the fonts Bambuddy embeds. A character Liberation Sans lacks is now drawn in Droid Sans Fallback (Chinese and Japanese) or Noto Sans KR (Korean), and only the characters a label uses are embedded. Long names are shortened by their real printed width. These fonts have no bold or italic, so CJK text on a bold or italic line prints in regular weight.
 - **A slot set to a support filament is a support slot (#3559)** — BambuStudio puts a support filament into an AMS slot as **PLA-S** (or **PA-S**), and a plate sliced with one asks for that type. Bambuddy wrote plain **PLA** instead, whether the slot was set with **Configure**, by assigning a spool or by linking a Spoolman spool, so a slot holding Support For PLA was offered to every PLA part and to nothing that needed support. Support W and Support For PLA/PETG came out as PLA and PETG. Bambu's support filaments now get Bambu's type, and a third-party or user preset whose name says "Support" gets PLA-S or PA-S over PLA or PA. Slots set up before this keep PLA until they are configured again. The spool form's built-in list, shown when no other preset source is available, also had wrong filament ids for most entries (Bambu PLA-CF was filed under Support W); they now match Bambu's.

+ 6 - 0
backend/app/main.py

@@ -2320,6 +2320,12 @@ async def on_printer_status_change(printer_id: int, state: PrinterState):
                 name=f"printer-offline-notify-{printer_id}",
             )
     elif state.connected:
+        if prev_connected is False:
+            # A printer back from a dropped connection, often a restart, may
+            # take files again: don't hold it to an upload backoff from
+            # before (#3563). Not on Bambuddy's own start (no previous state).
+            client = printer_manager.get_client(printer_id)
+            print_scheduler.printer_reconnected(printer_id, client.ip_address if client else None)
         # Kept until the relay can actually send online: with its broker down
         # now, the next status update after the reconnect sends it.
         if printer_id in _printer_offline_published and mqtt_relay.enabled and mqtt_relay.connected:

+ 9 - 0
backend/app/services/bambu_ftp.py

@@ -705,6 +705,15 @@ class BambuFTPClient:
             return False
         return True
 
+    @classmethod
+    def clear_handshake_cooloff(cls, ip_address: str) -> None:
+        """End *ip_address*'s handshake cool-off early, for a printer that has
+        just reconnected (#3563): a cool-off from before a restart says nothing
+        about the printer now."""
+        cls._handshake_blocked_until.pop(ip_address, None)
+        cls._handshake_skip_logged.pop(ip_address, None)
+        cls._cleartext_reply.pop(ip_address, None)
+
     def _record_stall(self, what: str) -> None:
         if self.records_handshake_cooloff:
             _record_ftps_stall(self.ip_address, what)

+ 20 - 0
backend/app/services/print_scheduler.py

@@ -35,6 +35,7 @@ from backend.app.models.spool_assignment import SpoolAssignment
 from backend.app.models.spoolman_slot_assignment import SpoolmanSlotAssignment
 from backend.app.services import drying_preflight, kprofile_drift, print_dispatch_context, stock_forecast
 from backend.app.services.bambu_ftp import (
+    BambuFTPClient,
     FtpFailureKind,
     FtpFailureReport,
     UploadCancelled,
@@ -1765,6 +1766,25 @@ class PrintScheduler:
         for item_id in [i for i, sent in self._sent_unstarted_print.items() if sent[0] == printer_id]:
             del self._sent_unstarted_print[item_id]
 
+    def printer_reconnected(self, printer_id: int, ip_address: str | None) -> None:
+        """Let a printer that has just reconnected take an upload on the next pass (#3563).
+
+        A printer whose file service stopped answering is often fixed by a
+        restart, but its upload backoff ran on for up to an hour, and nothing
+        but the timer ended it. A reconnect ends the window. The refusal count
+        and the notified text stay: a printer that still refuses gets the next,
+        longer window and no second "job waiting", and a successful upload
+        resets them as before.
+
+        The FTP client's handshake cool-off for the printer goes too. It dates
+        from before the reconnect, and inside it the first retry would fail
+        without reaching the printer and count as another refusal.
+        """
+        if self._upload_backoff.pop(printer_id, None) is not None:
+            logger.info("Printer %s reconnected; retrying uploads to it without waiting for the backoff", printer_id)
+        if ip_address:
+            BambuFTPClient.clear_handshake_cooloff(ip_address)
+
     async def check_queue(self) -> bool:
         """Check for prints ready to start.
 

+ 129 - 0
backend/tests/unit/test_upload_backoff_reconnect_3563.py

@@ -0,0 +1,129 @@
+"""A printer that reconnects is not held to its upload backoff (#3563).
+
+An X2D's file service stopped finishing the TLS handshake, so every upload
+timed out and the backoff grew to an hour. Restarting the printer fixed it, but
+the queue kept waiting out the hour: only the timer ended the backoff, and only
+a Bambuddy restart, which forgets it, got the job going.
+"""
+
+import time
+from types import SimpleNamespace
+from unittest.mock import AsyncMock, MagicMock, patch
+
+import pytest
+
+from backend.app import main as main_module
+from backend.app.services.bambu_ftp import BambuFTPClient
+from backend.app.services.print_scheduler import UPLOAD_FAILURE_BACKOFF_SECONDS, PrintScheduler
+from backend.tests.unit.test_printer_offline_notification import _reset_edge_state, _spawn_patch, _state
+from backend.tests.unit.test_scheduler_upload_requeue_3210 import (
+    HANDSHAKE,
+    REFUSING_IP,
+    _item,
+    _remaining,
+    _scheduler,
+    _upload_refused_by,
+    farm,
+)
+
+__all__ = ["_reset_edge_state", "farm"]  # fixtures, used by name
+
+pytestmark = pytest.mark.unit
+
+
+class TestTheScheduler:
+    @pytest.mark.asyncio
+    async def test_a_reconnected_printer_gets_the_job_without_waiting(self, farm):
+        item_id = await farm.add_item(printer_id=farm.ids.refusing)
+        scheduler = PrintScheduler()
+        async with _scheduler(farm, _upload_refused_by(REFUSING_IP, HANDSHAKE), scheduler=scheduler):
+            await scheduler.check_queue()
+        assert farm.ids.refusing in scheduler._upload_backoff
+
+        scheduler.printer_reconnected(farm.ids.refusing, REFUSING_IP)
+
+        async with _scheduler(farm, AsyncMock(return_value=True), scheduler=scheduler):
+            await scheduler.check_queue()
+        assert (await _item(farm, item_id)).status == "printing"
+
+    @pytest.mark.asyncio
+    async def test_a_printer_that_still_refuses_gets_the_next_longer_wait_and_no_second_notice(self, farm):
+        await farm.add_item(printer_id=farm.ids.refusing)
+        refused = _upload_refused_by(REFUSING_IP, HANDSHAKE)
+        scheduler = PrintScheduler()
+        waiting = AsyncMock()
+        async with _scheduler(farm, refused, scheduler=scheduler, waiting_notify=waiting):
+            await scheduler.check_queue()
+
+        scheduler.printer_reconnected(farm.ids.refusing, REFUSING_IP)
+        async with _scheduler(farm, refused, scheduler=scheduler, waiting_notify=waiting):
+            await scheduler.check_queue()
+
+        assert _remaining(scheduler, farm.ids.refusing) == pytest.approx(2 * UPLOAD_FAILURE_BACKOFF_SECONDS, abs=5)
+        assert waiting.await_count == 1
+
+    def test_the_ftp_cool_off_from_before_the_reconnect_goes(self):
+        """Inside it the first retry would fail without reaching the printer."""
+        scheduler = PrintScheduler()
+        BambuFTPClient._handshake_blocked_until["10.0.0.50"] = time.monotonic() + 300
+        BambuFTPClient._handshake_blocked_until["10.0.0.51"] = time.monotonic() + 300
+        try:
+            scheduler.printer_reconnected(7, "10.0.0.50")
+
+            assert not BambuFTPClient.handshake_blocked("10.0.0.50")
+            assert BambuFTPClient.handshake_blocked("10.0.0.51")
+        finally:
+            BambuFTPClient._handshake_blocked_until.pop("10.0.0.50", None)
+            BambuFTPClient._handshake_blocked_until.pop("10.0.0.51", None)
+
+    def test_only_the_reconnected_printer_is_let_go(self):
+        scheduler = PrintScheduler()
+        scheduler._upload_backoff.update({1: time.monotonic() + 600, 2: time.monotonic() + 600})
+        scheduler._upload_refusals.update({1: 2, 2: 2})
+
+        scheduler.printer_reconnected(1, None)
+
+        assert 1 not in scheduler._upload_backoff
+        assert 2 in scheduler._upload_backoff
+        assert scheduler._upload_refusals == {1: 2, 2: 2}
+
+
+class TestTheReconnect:
+    @staticmethod
+    async def _status(*connected: bool) -> MagicMock:
+        """Feed the status handler these connection states; return the scheduler stand-in."""
+        ws_mgr = MagicMock()
+        ws_mgr.send_printer_status = AsyncMock()
+        relay = MagicMock()
+        relay.on_printer_status = AsyncMock()
+        relay.on_printer_online = AsyncMock()
+        pm = MagicMock()
+        pm.get_printer.return_value = SimpleNamespace(name="X2D", serial_number="SN1")
+        pm.get_model.return_value = ""
+        pm.is_awaiting_plate_clear.return_value = False
+        pm.get_client.return_value = SimpleNamespace(ip_address="10.0.0.8")
+        scheduler = MagicMock()
+        with (
+            patch("backend.app.main.ws_manager", ws_mgr),
+            patch("backend.app.main.mqtt_relay", relay),
+            patch("backend.app.main.printer_manager", pm),
+            patch("backend.app.main.print_scheduler", scheduler),
+            patch("backend.app.main._maybe_notify_printer_offline", new=AsyncMock()),
+            _spawn_patch(),
+            patch("backend.app.main.printer_state_to_dict", return_value={}),
+        ):
+            for c in connected:
+                await main_module.on_printer_status_change(1, _state(connected=c))
+        return scheduler
+
+    @pytest.mark.asyncio
+    async def test_a_printer_back_from_a_dropped_connection_is_let_go(self):
+        scheduler = await self._status(True, False, True)
+
+        scheduler.printer_reconnected.assert_called_once_with(1, "10.0.0.8")
+
+    @pytest.mark.asyncio
+    async def test_bambuddys_own_start_and_further_updates_are_no_reconnect(self):
+        scheduler = await self._status(True, True, True)
+
+        scheduler.printer_reconnected.assert_not_called()