bambu_ftp.py 61 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441
  1. import asyncio
  2. import ftplib # nosec B402
  3. import logging
  4. import os
  5. import socket
  6. import ssl
  7. import threading
  8. import time
  9. import weakref
  10. from collections.abc import Awaitable, Callable
  11. from concurrent.futures import ThreadPoolExecutor
  12. from enum import Enum
  13. from ftplib import FTP, FTP_TLS # nosec B402
  14. from io import BytesIO
  15. from pathlib import Path
  16. from typing import TypeVar
  17. logger = logging.getLogger(__name__)
  18. T = TypeVar("T")
  19. # Every FTP call below is blocking ftplib work handed to a thread. They used to
  20. # run on asyncio's *default* executor, which is sized min(32, cpu_count + 4) —
  21. # six threads on a 2-core NAS — and is shared with every other ``to_thread`` /
  22. # ``run_in_executor`` caller in the app. That was survivable only because the
  23. # scheduler uploaded to exactly one printer at a time. Dispatching to several
  24. # printers at once (#2555) would park one thread per in-flight upload for
  25. # minutes at a stretch (a 41 MB 3MF at the ~150 KB/s a Bambu printer sustains
  26. # takes ~4 min), starving the default pool and stalling unrelated work.
  27. #
  28. # A dedicated pool keeps that blast radius inside the FTP layer: the scheduler's
  29. # own concurrency cap is what limits parallel uploads, and it can never exhaust
  30. # the executor everything else depends on. Threads are created lazily, so an
  31. # idle pool costs nothing.
  32. #
  33. # Sized well above `queue_max_concurrent_uploads` (max 16), because uploads are
  34. # not the only traffic here: SD browsing, timelapse/recording listing, cover
  35. # downloads, deletes and storage checks all run through this pool too, and on a
  36. # farm they fan out across every printer at once. The pool's work queue is
  37. # unbounded, so exceeding it does not fail — it queues. But `asyncio.wait_for`
  38. # starts its clock at submission, not at thread start, so a task that sits in the
  39. # queue can burn its whole timeout without ever running, and `list_files_async`
  40. # reports a timeout as an empty listing — a silent "this printer has no files".
  41. # Keep the headroom.
  42. _FTP_MAX_WORKERS = 48
  43. _ftp_executor = ThreadPoolExecutor(max_workers=_FTP_MAX_WORKERS, thread_name_prefix="bambu-ftp")
  44. # Overall upload deadline (#2529). A flat wall-clock cap punishes big files on
  45. # slow links rather than catching broken ones: a 96 MB 3MF at the ~75 KB/s an A1
  46. # sustains over WiFi legitimately needs ~20 minutes, and the old flat 600 s
  47. # declared it dead at ~70 MB. The deadline is therefore derived from the file
  48. # size against a deliberately pessimistic floor rate. This is a backstop, not the
  49. # failure detector — a link that has actually died is caught within
  50. # ``socket_timeout`` by the blocking ``sendall``, long before this fires.
  51. _UPLOAD_FLOOR_BYTES_PER_SEC = 25 * 1024
  52. _UPLOAD_MIN_TIMEOUT = 600.0
  53. # How long to give the worker thread to notice the cancel flag, unwind, and
  54. # delete its partial file. It checks the flag once per CHUNK_SIZE, so on a link
  55. # slow enough to have hit the deadline this is one chunk plus the delete.
  56. _UPLOAD_CANCEL_GRACE = 60.0
  57. class UploadCancelled(Exception):
  58. """Raised inside the upload worker to abort an in-flight transfer.
  59. ``upload_file`` treats any exception from its progress callback as "stop
  60. now": it breaks out of the send loop, deletes the partial file from the
  61. printer, and re-raises. That is the only way to stop a transfer — an
  62. executor thread cannot be cancelled from the event loop, so a bare
  63. ``asyncio.wait_for`` leaves it streaming (see ``upload_file_async``).
  64. """
  65. class DeleteResult(Enum):
  66. """Outcome of an FTP delete attempt.
  67. Distinguishes "file isn't on the printer" (550, recovery impossible by
  68. retrying) from "delete failed for some other reason" (network, auth,
  69. transient FTP error — worth retrying). The post-print SD-card cleanup in
  70. main.py used to flatten both into ``False`` and log a "may linger" WARNING
  71. on every successful print where the printer self-cleaned its SD card
  72. before our cleanup ran (#1721 reporter's A1).
  73. """
  74. DELETED = "deleted"
  75. NOT_FOUND = "not_found"
  76. FAILED = "failed"
  77. class FileNotOnPrinterError(Exception):
  78. """Raised when a remote FTP path returns 550 (file not found).
  79. 550 means the file does not exist at that path — retrying the same path
  80. will never succeed. Callers use this sentinel with with_ftp_retry's
  81. non_retry_exceptions to immediately move on to the next candidate path
  82. instead of burning the full retry budget (up to 11 × 30s per path) on
  83. a lookup that cannot recover.
  84. """
  85. class ImplicitFTP_TLS(FTP_TLS):
  86. """FTP_TLS subclass for implicit FTPS (port 990) with model-specific SSL handling.
  87. X1C/P1S printers (vsFTPd) require SSL with session reuse on the data channel.
  88. A1/A1 Mini printers have issues with SSL on the data channel entirely and
  89. timeout waiting for transfer completion. Set skip_session_reuse=True for A1
  90. printers to skip SSL on the data channel (control channel remains encrypted).
  91. Optionally caps the SSL context's maximum TLS version to v1.2 (P2S firmware
  92. 01.02.00.00 needs this — see :mod:`ftp_profiles` and #1401).
  93. """
  94. def __init__(self, *args, skip_session_reuse: bool = False, cap_tls_v1_2: bool = False, **kwargs):
  95. super().__init__(*args, **kwargs)
  96. self._sock = None
  97. self.skip_session_reuse = skip_session_reuse
  98. self.ssl_context = ssl.create_default_context()
  99. self.ssl_context.check_hostname = False
  100. self.ssl_context.verify_mode = ssl.CERT_NONE
  101. # ``create_default_context()`` does NOT guarantee a protocol floor: it
  102. # leaves ``minimum_version`` at ``MINIMUM_SUPPORTED``, and what that
  103. # resolves to is a property of the OpenSSL build, not of this code.
  104. # Measured on identical OpenSSL 3.5.6: python:3.13-slim-trixie (our
  105. # Docker base) reports TLSv1_2, a bare-metal venv reports
  106. # MINIMUM_SUPPORTED. Docker users have therefore always been floored at
  107. # 1.2 — every Bambu model is reachable under that floor — while
  108. # bare-metal and appliance installs could silently negotiate TLS 1.0.
  109. # State the floor rather than inheriting it.
  110. self.ssl_context.minimum_version = ssl.TLSVersion.TLSv1_2
  111. if cap_tls_v1_2:
  112. # With the floor above this pins the connection to exactly TLS 1.2.
  113. self.ssl_context.maximum_version = ssl.TLSVersion.TLSv1_2
  114. def connect(self, host="", port=990, timeout=-999, source_address=None):
  115. """Connect to host, wrapping socket in TLS immediately (implicit FTPS)."""
  116. if host:
  117. self.host = host
  118. if port > 0:
  119. self.port = port
  120. if timeout != -999:
  121. self.timeout = timeout
  122. if source_address:
  123. self.source_address = source_address
  124. # Create and wrap socket immediately (implicit TLS)
  125. self.sock = socket.create_connection((self.host, self.port), self.timeout, source_address=self.source_address)
  126. self.sock = self.ssl_context.wrap_socket(self.sock, server_hostname=self.host)
  127. self.af = self.sock.family
  128. self.file = self.sock.makefile("r", encoding=self.encoding)
  129. self.welcome = self.getresp()
  130. return self.welcome
  131. def ntransfercmd(self, cmd, rest=None):
  132. """Override to wrap data connection in SSL for X1C/P1S only.
  133. X1C/P1S printers (vsFTPd) require SSL session reuse on the data channel.
  134. A1/A1 Mini printers have issues with SSL on the data channel entirely -
  135. they timeout waiting for the transfer completion response. For A1, we
  136. skip SSL wrapping on the data channel (control channel remains encrypted).
  137. """
  138. conn, size = FTP.ntransfercmd(self, cmd, rest)
  139. if self._prot_p and not self.skip_session_reuse:
  140. # X1C/P1S: Wrap data channel with SSL session reuse (required by vsFTPd)
  141. conn = self.ssl_context.wrap_socket(
  142. conn,
  143. server_hostname=self.host,
  144. session=self.sock.session,
  145. )
  146. # A1/A1 Mini (skip_session_reuse=True): Don't wrap data channel in SSL
  147. # The control channel remains encrypted via implicit FTPS
  148. return conn, size
  149. class BambuFTPClient:
  150. """FTP client for retrieving files from Bambu Lab printers."""
  151. FTP_PORT = 990
  152. # Default timeout in seconds (increased for A1 printers)
  153. DEFAULT_TIMEOUT = 30
  154. # Models that may need SSL mode fallback (try prot_p first, fall back to prot_c)
  155. # These models have varying FTP SSL behavior depending on firmware version
  156. A1_MODELS = ("A1", "A1 Mini")
  157. # Chunk size for manual upload transfer (64KB)
  158. # Smaller chunks provide smoother progress reporting — at typical printer FTP
  159. # speeds (~50-100KB/s) this gives a progress update roughly every second.
  160. CHUNK_SIZE = 64 * 1024
  161. # Cache for working FTP modes per printer IP
  162. # Maps IP -> "prot_p" or "prot_c"
  163. _mode_cache: dict[str, str] = {}
  164. def __init__(
  165. self,
  166. ip_address: str,
  167. access_code: str,
  168. timeout: float | None = None,
  169. printer_model: str | None = None,
  170. force_prot_c: bool = False,
  171. ):
  172. self.ip_address = ip_address
  173. self.access_code = access_code
  174. self.timeout = timeout if timeout is not None else self.DEFAULT_TIMEOUT
  175. self.printer_model = printer_model
  176. self.force_prot_c = force_prot_c
  177. self._ftp: ImplicitFTP_TLS | None = None
  178. def _is_a1_model(self) -> bool:
  179. """Check if this is an A1 series printer."""
  180. if not self.printer_model:
  181. return False
  182. return self.printer_model in self.A1_MODELS
  183. def _get_cached_mode(self) -> str | None:
  184. """Get cached FTP mode for this printer."""
  185. return self._mode_cache.get(self.ip_address)
  186. @classmethod
  187. def cache_mode(cls, ip_address: str, mode: str):
  188. """Cache the working FTP mode for a printer."""
  189. cls._mode_cache[ip_address] = mode
  190. logger.info("FTP mode cached for %s: %s", ip_address, mode)
  191. def _should_use_prot_c(self) -> bool:
  192. """Determine if we should use prot_c (clear) mode."""
  193. # If explicitly forced, use prot_c
  194. if self.force_prot_c:
  195. return True
  196. # Check cache first
  197. cached = self._get_cached_mode()
  198. if cached:
  199. return cached == "prot_c"
  200. # Default: try prot_p first (will fall back if needed)
  201. return False
  202. def connect(self) -> bool:
  203. """Connect to the printer FTP server (implicit FTPS on port 990)."""
  204. try:
  205. use_prot_c = self._should_use_prot_c()
  206. from backend.app.services.ftp_profiles import get_ftp_profile
  207. profile = get_ftp_profile(self.printer_model)
  208. logger.debug(
  209. f"FTP connecting to {self.ip_address}:{self.FTP_PORT} "
  210. f"(timeout={self.timeout}s, model={self.printer_model}, prot_c={use_prot_c}, "
  211. f"cap_tls_v1_2={profile.cap_tls_v1_2})"
  212. )
  213. self._ftp = ImplicitFTP_TLS(
  214. skip_session_reuse=use_prot_c,
  215. cap_tls_v1_2=profile.cap_tls_v1_2,
  216. )
  217. self._ftp.connect(self.ip_address, self.FTP_PORT, timeout=self.timeout)
  218. logger.debug("FTP connected, logging in as bblp")
  219. self._ftp.login("bblp", self.access_code)
  220. if use_prot_c:
  221. # Use clear (unencrypted) data channel
  222. logger.debug("FTP logged in, setting prot_c (clear) and passive mode")
  223. self._ftp.prot_c()
  224. else:
  225. # Use protected (encrypted) data channel with session reuse
  226. logger.debug("FTP logged in, setting prot_p (protected) and passive mode")
  227. self._ftp.prot_p()
  228. self._ftp.set_pasv(True)
  229. # Log welcome message for debugging
  230. if hasattr(self._ftp, "welcome") and self._ftp.welcome:
  231. logger.debug("FTP server welcome: %s", self._ftp.welcome)
  232. logger.info(
  233. f"FTP connected successfully to {self.ip_address} (model={self.printer_model}, prot_c={use_prot_c})"
  234. )
  235. return True
  236. except ftplib.error_perm as e:
  237. logger.warning("FTP connection permission error to %s: %s", self.ip_address, e)
  238. self._ftp = None
  239. return False
  240. except TimeoutError as e:
  241. logger.warning("FTP connection timed out to %s: %s", self.ip_address, e)
  242. self._ftp = None
  243. return False
  244. except ssl.SSLError as e:
  245. logger.warning("FTP SSL error connecting to %s: %s", self.ip_address, e)
  246. self._ftp = None
  247. return False
  248. except (OSError, ftplib.Error) as e:
  249. logger.warning("FTP connection failed to %s: %s (type: %s)", self.ip_address, e, type(e).__name__)
  250. self._ftp = None
  251. return False
  252. def disconnect(self):
  253. """Disconnect from the FTP server."""
  254. if self._ftp:
  255. try:
  256. self._ftp.quit()
  257. except (OSError, ftplib.Error, EOFError):
  258. pass # Best-effort FTP cleanup; connection may already be closed
  259. self._ftp = None
  260. def list_files(self, path: str = "/") -> list[dict]:
  261. """List files in a directory."""
  262. if not self._ftp:
  263. return []
  264. files = []
  265. try:
  266. self._ftp.cwd(path)
  267. items = []
  268. self._ftp.retrlines("LIST", items.append)
  269. for item in items:
  270. parts = item.split()
  271. if len(parts) >= 9:
  272. name = " ".join(parts[8:])
  273. is_dir = item.startswith("d")
  274. size = int(parts[4]) if not is_dir else 0
  275. # Parse modification time from FTP listing
  276. # Format: "Nov 30 10:15" or "Nov 30 2024"
  277. mtime = None
  278. try:
  279. from datetime import datetime
  280. month = parts[5]
  281. day = parts[6]
  282. time_or_year = parts[7]
  283. # Determine if it's time (HH:MM) or year
  284. if ":" in time_or_year:
  285. # Recent file: "Nov 30 10:15" - assume current year
  286. year = datetime.now().year
  287. time_str = f"{month} {day} {year} {time_or_year}"
  288. mtime = datetime.strptime(time_str, "%b %d %Y %H:%M")
  289. # If parsed date is in the future, use last year
  290. if mtime > datetime.now():
  291. mtime = mtime.replace(year=year - 1)
  292. else:
  293. # Older file: "Nov 30 2024" - no time, just date
  294. time_str = f"{month} {day} {time_or_year}"
  295. mtime = datetime.strptime(time_str, "%b %d %Y")
  296. except (ValueError, IndexError):
  297. pass # Non-critical: mtime parsing is best-effort; file entry works without it
  298. file_entry = {
  299. "name": name,
  300. "is_directory": is_dir,
  301. "size": size,
  302. "path": f"{path.rstrip('/')}/{name}",
  303. }
  304. if mtime:
  305. file_entry["mtime"] = mtime
  306. files.append(file_entry)
  307. logger.debug("Listed %s files in %s", len(files), path)
  308. except (OSError, ftplib.Error) as e:
  309. logger.info("FTP list_files failed for %s: %s", path, e)
  310. return files
  311. def download_file(self, remote_path: str) -> bytes | None:
  312. """Download a file from the printer."""
  313. if not self._ftp:
  314. return None
  315. try:
  316. buffer = BytesIO()
  317. self._ftp.retrbinary(f"RETR {remote_path}", buffer.write)
  318. return buffer.getvalue()
  319. except (OSError, ftplib.Error):
  320. return None
  321. def download_to_file(self, remote_path: str, local_path: Path) -> bool:
  322. """Download a file from the printer to local filesystem."""
  323. if not self._ftp:
  324. logger.warning("download_to_file called but FTP not connected")
  325. return False
  326. try:
  327. local_path.parent.mkdir(parents=True, exist_ok=True)
  328. with open(local_path, "wb") as f:
  329. self._ftp.retrbinary(f"RETR {remote_path}", f.write)
  330. f.flush()
  331. os.fsync(f.fileno())
  332. file_size = local_path.stat().st_size if local_path.exists() else 0
  333. if file_size == 0:
  334. logger.warning("FTP download returned 0 bytes for %s", remote_path)
  335. if local_path.exists():
  336. local_path.unlink()
  337. return False
  338. logger.info("Successfully downloaded %s to %s (%s bytes)", remote_path, local_path, file_size)
  339. return True
  340. except (OSError, ftplib.Error) as e:
  341. # Clean up partial file if it exists
  342. if local_path.exists():
  343. try:
  344. local_path.unlink()
  345. except OSError:
  346. pass # Best-effort partial file cleanup; not critical if removal fails
  347. # 550 means the file is not at this path. Surface as a sentinel so
  348. # with_ftp_retry can abandon this path immediately and the caller
  349. # can advance to the next candidate instead of retrying 11× at
  350. # 30s intervals (the pattern that cost #972's reporter ~48min).
  351. if isinstance(e, ftplib.error_perm) and str(e).startswith("550"):
  352. logger.info("FTP download failed for %s: %s (not on printer)", remote_path, e)
  353. raise FileNotOnPrinterError(f"{remote_path}: {e}") from e
  354. # Log at INFO level so we can see failures in normal logs
  355. logger.info("FTP download failed for %s: %s", remote_path, e)
  356. return False
  357. def diagnose_storage(self) -> dict:
  358. """Run storage diagnostics and return results. For debugging upload issues."""
  359. results = {
  360. "connected": self._ftp is not None,
  361. "can_list_root": False,
  362. "root_files": [],
  363. "can_list_cache": False,
  364. "storage_info": None,
  365. "pwd": None,
  366. "errors": [],
  367. }
  368. if not self._ftp:
  369. results["errors"].append("FTP not connected")
  370. return results
  371. # Try to get current directory
  372. try:
  373. results["pwd"] = self._ftp.pwd()
  374. logger.debug("FTP current directory: %s", results["pwd"])
  375. except (OSError, ftplib.Error) as e:
  376. results["errors"].append(f"PWD failed: {e}")
  377. logger.debug("FTP PWD failed: %s", e)
  378. # Try to list root directory
  379. try:
  380. self._ftp.cwd("/")
  381. items = []
  382. self._ftp.retrlines("LIST", items.append)
  383. results["can_list_root"] = True
  384. results["root_files"] = items[:10] # First 10 entries
  385. logger.debug("FTP root listing (%s items): %s", len(items), items[:5])
  386. except (OSError, ftplib.Error) as e:
  387. results["errors"].append(f"LIST / failed: {e}")
  388. logger.debug("FTP LIST / failed: %s", e)
  389. # Try to list /cache (should exist on all printers)
  390. try:
  391. self._ftp.cwd("/cache")
  392. items = []
  393. self._ftp.retrlines("LIST", items.append)
  394. results["can_list_cache"] = True
  395. logger.debug("FTP /cache listing: %s items", len(items))
  396. except (OSError, ftplib.Error) as e:
  397. results["errors"].append(f"LIST /cache failed: {e}")
  398. logger.debug("FTP LIST /cache failed: %s", e)
  399. # Try to get storage info
  400. try:
  401. results["storage_info"] = self.get_storage_info()
  402. logger.debug("FTP storage info: %s", results["storage_info"])
  403. except (OSError, ftplib.Error) as e:
  404. results["errors"].append(f"Storage info failed: {e}")
  405. return results
  406. def upload_file(
  407. self,
  408. local_path: Path,
  409. remote_path: str,
  410. progress_callback: Callable[[int, int], None] | None = None,
  411. ) -> bool:
  412. """Upload a file to the printer with optional progress callback."""
  413. if not self._ftp:
  414. logger.warning("upload_file: FTP not connected")
  415. return False
  416. try:
  417. file_size = local_path.stat().st_size if local_path.exists() else 0
  418. logger.info("FTP uploading %s (%s bytes) to %s", local_path, file_size, remote_path)
  419. uploaded = 0
  420. callback_exception: Exception | None = None
  421. # Use manual transfer instead of storbinary() for A1 compatibility
  422. # A1 printers have issues with storbinary's voidresp() hanging after transfer
  423. with open(local_path, "rb") as f:
  424. logger.debug("FTP STOR command starting for %s", remote_path)
  425. t0 = time.monotonic()
  426. conn = self._ftp.transfercmd(f"STOR {remote_path}")
  427. logger.info(
  428. "FTP data channel ready in %.1fs (PASV + TLS handshake)",
  429. time.monotonic() - t0,
  430. )
  431. # Set explicit socket options for reliable transfer
  432. conn.setblocking(True)
  433. conn.settimeout(self.timeout)
  434. try:
  435. while True:
  436. chunk = f.read(self.CHUNK_SIZE)
  437. if not chunk:
  438. logger.debug("FTP upload: final chunk reached")
  439. break
  440. conn.sendall(chunk)
  441. uploaded += len(chunk)
  442. logger.debug("FTP upload progress: %s/%s bytes", uploaded, file_size)
  443. if progress_callback:
  444. try:
  445. progress_callback(uploaded, file_size)
  446. except Exception as e:
  447. callback_exception = e
  448. logger.info(
  449. "FTP upload callback requested stop for %s at %s/%s bytes: %s",
  450. remote_path,
  451. uploaded,
  452. file_size,
  453. e,
  454. )
  455. break
  456. except OSError as e:
  457. logger.error("FTP connection lost during upload: %s", e)
  458. raise
  459. finally:
  460. try:
  461. conn.close()
  462. except OSError:
  463. pass
  464. # Wait for the server's 226 "Transfer complete" response to confirm
  465. # the file has been flushed to the SD card. Without this, the printer
  466. # may try to read an incomplete file when the print command is sent,
  467. # causing 0500-C010 "MicroSD Card read/write exception" errors.
  468. # See: https://bugs.python.org/issue25458 (ftplib response desync)
  469. try:
  470. old_timeout = self._ftp.sock.gettimeout()
  471. # Use a generous timeout — H2D printers can take 30+ seconds
  472. # to send the 226 after the data channel closes.
  473. self._ftp.sock.settimeout(max(self.timeout, 60))
  474. try:
  475. resp = self._ftp.voidresp()
  476. logger.info("FTP STOR confirmed for %s: %s", remote_path, resp.strip())
  477. finally:
  478. self._ftp.sock.settimeout(old_timeout)
  479. except ftplib.Error as e:
  480. # Some P2S firmware revisions return ftplib.Error (e.g. 426
  481. # "Failure reading network stream") on voidresp() even when
  482. # the file landed fully on the SD card — the TLS data
  483. # channel close races the 226 confirmation (#1417 follow-up).
  484. # Verify via SIZE: if the server-side file size matches what
  485. # we just uploaded, the file is intact and we proceed with
  486. # a warning. If not — or SIZE itself fails — the transfer
  487. # was genuinely truncated and we must fail so the print
  488. # command doesn't go out for a partial 3MF (the original
  489. # reason this catch was tightened in the previous round).
  490. try:
  491. server_size = self._ftp.size(remote_path)
  492. except (OSError, ftplib.Error) as size_err:
  493. logger.debug("Post-error SIZE check failed: %s", size_err)
  494. server_size = None
  495. if server_size is not None and server_size == file_size:
  496. logger.warning(
  497. "FTP STOR returned %s for %s but file is intact on the "
  498. "printer (%s bytes match) — proceeding: %s",
  499. type(e).__name__,
  500. remote_path,
  501. file_size,
  502. e,
  503. )
  504. else:
  505. logger.error(
  506. "FTP STOR rejected by printer for %s: %s (%s); server size=%s expected=%s",
  507. remote_path,
  508. e,
  509. type(e).__name__,
  510. server_size,
  511. file_size,
  512. )
  513. raise
  514. except Exception as e:
  515. # Timeout or socket-level error reading 226 — the data was sent
  516. # on our side and the printer may still have written the file.
  517. # H2D can take 30+ seconds to send 226 after the data channel
  518. # closes, so we proceed with a warning rather than failing here.
  519. logger.warning(
  520. "FTP STOR confirmation not received for %s (proceeding): %s (%s)",
  521. remote_path,
  522. e,
  523. type(e).__name__,
  524. )
  525. if callback_exception is not None:
  526. cleanup_result: DeleteResult = DeleteResult.FAILED
  527. try:
  528. cleanup_result = self.delete_file(remote_path)
  529. except Exception as cleanup_error:
  530. logger.warning("FTP cancel cleanup failed for %s: %s", remote_path, cleanup_error)
  531. # NOT_FOUND is success here — the partial file is gone (printer
  532. # may have already swept on cancel), which is the goal.
  533. if cleanup_result in (DeleteResult.DELETED, DeleteResult.NOT_FOUND):
  534. logger.info("FTP cancel cleanup succeeded for %s (%s)", remote_path, cleanup_result.value)
  535. raise callback_exception
  536. raise RuntimeError(
  537. f"Upload cancelled but failed to remove partial file {remote_path} from printer"
  538. ) from callback_exception
  539. elapsed = time.monotonic() - t0
  540. speed_kbs = (file_size / 1024) / elapsed if elapsed > 0 else 0
  541. logger.info(
  542. "FTP upload complete: %s (%s bytes in %.1fs, %.0f KB/s)",
  543. remote_path,
  544. file_size,
  545. elapsed,
  546. speed_kbs,
  547. )
  548. return True
  549. except ftplib.error_perm as e:
  550. # Permanent FTP error (4xx/5xx response)
  551. error_code = str(e)[:3] if str(e) else "unknown"
  552. logger.error("FTP upload failed for %s: %s (error code: %s)", remote_path, e, error_code)
  553. if error_code == "553":
  554. logger.error(
  555. "FTP 553 error - Could not create file. Possible causes: "
  556. "1) No SD card inserted, 2) SD card full, 3) SD card not formatted correctly (needs FAT32/exFAT), "
  557. "4) Printer busy/not ready, 5) File path issue"
  558. )
  559. elif error_code == "550":
  560. logger.error("FTP 550 error - File/directory not found or permission denied")
  561. elif error_code == "552":
  562. logger.error("FTP 552 error - Storage quota exceeded (SD card full?)")
  563. return False
  564. except (OSError, ftplib.Error) as e:
  565. logger.error("FTP upload failed for %s: %s (type: %s)", remote_path, e, type(e).__name__)
  566. return False
  567. def upload_bytes(self, data: bytes, remote_path: str) -> bool:
  568. """Upload bytes to the printer."""
  569. if not self._ftp:
  570. return False
  571. try:
  572. # Use manual transfer instead of storbinary() for A1 compatibility
  573. conn = self._ftp.transfercmd(f"STOR {remote_path}")
  574. conn.setblocking(True)
  575. conn.settimeout(self.timeout)
  576. try:
  577. # Send data in chunks
  578. offset = 0
  579. while offset < len(data):
  580. chunk = data[offset : offset + self.CHUNK_SIZE]
  581. conn.sendall(chunk)
  582. offset += len(chunk)
  583. except OSError as e:
  584. logger.error("FTP connection lost during upload_bytes: %s", e)
  585. raise
  586. finally:
  587. try:
  588. conn.close()
  589. except OSError:
  590. pass
  591. # Wait for 226 confirmation (see upload_file for rationale).
  592. # ftplib.Error subclasses (e.g. 426 error_temp) mean the server
  593. # rejected the transfer and the file is partial — fail. Other
  594. # exceptions (timeout, socket-level) are tolerated as in upload_file.
  595. try:
  596. old_timeout = self._ftp.sock.gettimeout()
  597. self._ftp.sock.settimeout(max(self.timeout, 60))
  598. try:
  599. self._ftp.voidresp()
  600. finally:
  601. self._ftp.sock.settimeout(old_timeout)
  602. except ftplib.Error as e:
  603. # Same SIZE-verify path as upload_file (#1417 follow-up):
  604. # tolerate a transient 426 if the bytes are actually on the
  605. # printer, fail loudly if they aren't.
  606. try:
  607. server_size = self._ftp.size(remote_path)
  608. except (OSError, ftplib.Error) as size_err:
  609. logger.debug("Post-error SIZE check failed: %s", size_err)
  610. server_size = None
  611. if server_size is not None and server_size == len(data):
  612. logger.warning(
  613. "FTP STOR returned %s for %s but file is intact on the "
  614. "printer (%s bytes match) — proceeding: %s",
  615. type(e).__name__,
  616. remote_path,
  617. len(data),
  618. e,
  619. )
  620. else:
  621. logger.error(
  622. "FTP STOR rejected by printer for %s: %s (%s); server size=%s expected=%s",
  623. remote_path,
  624. e,
  625. type(e).__name__,
  626. server_size,
  627. len(data),
  628. )
  629. return False
  630. except Exception:
  631. pass # Timeout / socket-level — proceed, data was sent.
  632. return True
  633. except (OSError, ftplib.Error):
  634. return False
  635. def delete_file(self, remote_path: str) -> DeleteResult:
  636. """Delete a file from the printer.
  637. Returns :class:`DeleteResult` distinguishing the file-not-found case
  638. (550) from network / auth / transient FTP failure. Callers that just
  639. want "did it work" should check ``result == DeleteResult.DELETED``.
  640. """
  641. if not self._ftp:
  642. return DeleteResult.FAILED
  643. try:
  644. self._ftp.delete(remote_path)
  645. return DeleteResult.DELETED
  646. except ftplib.error_perm as e:
  647. if str(e).startswith("550"):
  648. logger.debug("FTP delete: %s not on printer (550)", remote_path)
  649. return DeleteResult.NOT_FOUND
  650. logger.warning("Failed to delete %s: %s", remote_path, e)
  651. return DeleteResult.FAILED
  652. except (OSError, ftplib.Error) as e:
  653. logger.warning("Failed to delete %s: %s", remote_path, e)
  654. return DeleteResult.FAILED
  655. def get_file_size(self, remote_path: str) -> int | None:
  656. """Get the size of a file."""
  657. if not self._ftp:
  658. return None
  659. try:
  660. return self._ftp.size(remote_path)
  661. except (OSError, ftplib.Error):
  662. return None
  663. def get_storage_info(self) -> dict | None:
  664. """Get storage information from the printer."""
  665. if not self._ftp:
  666. return None
  667. result = {}
  668. # Try AVBL command (available space) - some FTP servers support this
  669. try:
  670. response = self._ftp.sendcmd("AVBL")
  671. logger.debug("AVBL response: %s", response)
  672. # Response format: "213 <bytes available>"
  673. if response.startswith("213"):
  674. parts = response.split()
  675. if len(parts) >= 2:
  676. result["free_bytes"] = int(parts[1])
  677. except (OSError, ftplib.Error) as e:
  678. logger.debug("AVBL command not supported: %s", e)
  679. # Try STAT command as fallback
  680. try:
  681. response = self._ftp.sendcmd("STAT")
  682. logger.debug("STAT response: %s", response)
  683. except (OSError, ftplib.Error):
  684. pass # Both AVBL and STAT unsupported; storage info will rely on directory scan
  685. # Calculate used space by listing root directories
  686. try:
  687. total_used = 0
  688. dirs_to_scan = ["/cache", "/timelapse", "/model", "/data", "/data/Metadata", "/"]
  689. for dir_path in dirs_to_scan:
  690. try:
  691. self._ftp.cwd(dir_path)
  692. items = []
  693. self._ftp.retrlines("LIST", items.append)
  694. for item in items:
  695. parts = item.split()
  696. if len(parts) >= 5 and not item.startswith("d"):
  697. try:
  698. total_used += int(parts[4])
  699. except ValueError:
  700. pass # Skip entries with non-numeric size fields
  701. except (OSError, ftplib.Error):
  702. pass # Directory may not exist on this printer model; skip it
  703. result["used_bytes"] = total_used
  704. except (OSError, ftplib.Error):
  705. pass # Storage scan failed; return whatever info was collected above
  706. return result if result else None
  707. # Shared 3MF download cache (#972).
  708. #
  709. # Both the cover thumbnail endpoint (api/routes/printers.py) and the archive
  710. # metadata flow (main.py) fetch the same 3MF file over FTP during a print.
  711. # On slow / contended links (A1 Wi-Fi, large files) the duplicate transfers
  712. # compete for the printer's single FTP socket and trigger 425 "can't open
  713. # data channel" errors, feeding back into cause-2's retry storm.
  714. #
  715. # This cache stores the local path of a successfully-downloaded 3MF keyed
  716. # by (printer_id, normalized_name). Whichever flow downloads first populates
  717. # the cache; the other flow reuses the file read-only. Evicted on print
  718. # completion so a later print with the same name re-downloads fresh bytes.
  719. _threemf_path_cache: dict[tuple[int, str], Path] = {}
  720. def normalize_3mf_name(name: str) -> str:
  721. """Collapse various 3MF filename variants to a cache key.
  722. Bambu tooling produces names as bare subtask ("Part"), with .3mf, with
  723. .gcode.3mf, or (Studio-normalized) with spaces → underscores. All of
  724. these refer to the same print job on the same printer, so they must
  725. hash to the same cache key.
  726. """
  727. # Lowercase first so .3MF / .GCODE.3MF variants strip cleanly — a
  728. # real-world case since Windows-side tooling sometimes uppercases
  729. # extensions.
  730. cleaned = name.strip().lower().replace(".gcode.3mf", "").replace(".gcode", "").replace(".3mf", "")
  731. return cleaned.replace(" ", "_")
  732. def cache_3mf_download(printer_id: int, name: str, local_path: Path) -> None:
  733. """Record a successfully-downloaded 3MF so a sibling flow can reuse it."""
  734. _threemf_path_cache[(printer_id, normalize_3mf_name(name))] = local_path
  735. def get_cached_3mf(printer_id: int, name: str) -> Path | None:
  736. """Return a cached 3MF path for this printer/name if the file still exists."""
  737. key = (printer_id, normalize_3mf_name(name))
  738. cached = _threemf_path_cache.get(key)
  739. if cached and cached.exists() and cached.stat().st_size > 0:
  740. return cached
  741. # Evict dead entry — the file was cleaned up (temp dir clean, manual
  742. # deletion, restart) so the cache value is no longer usable.
  743. if cached:
  744. _threemf_path_cache.pop(key, None)
  745. return None
  746. def clear_3mf_cache(printer_id: int | None = None, delete_files: bool = True) -> None:
  747. """Drop cache entries for one printer (or all with None).
  748. When ``delete_files`` is True (default) the on-disk 3MF is removed as well
  749. — called from on_print_complete so temp files don't accumulate across
  750. prints. Tests that want to inspect the cache contents disable this.
  751. Only paths inside ``archive_dir/temp`` are unlinked. The dispatch sites
  752. added in #1166 also cache the live archive copy and library file bytes
  753. so /cover can skip FTP — those are *user data*, never the cache's to
  754. delete. Pre-fix this branch silently removed archive 3mfs on every print
  755. completion (#1212 + private reports of "file disappeared overnight").
  756. """
  757. from backend.app.core.config import settings as _config_settings
  758. temp_root = _config_settings.archive_dir / "temp"
  759. def _is_temp_path(path: Path) -> bool:
  760. try:
  761. return path.is_relative_to(temp_root)
  762. except (OSError, ValueError):
  763. return False
  764. def _maybe_unlink(path: Path) -> None:
  765. if not delete_files or not path.exists():
  766. return
  767. if not _is_temp_path(path):
  768. return
  769. try:
  770. path.unlink()
  771. except OSError as exc:
  772. logger.debug("3MF cache cleanup skipped %s: %s", path, exc)
  773. if printer_id is None:
  774. for path in list(_threemf_path_cache.values()):
  775. _maybe_unlink(path)
  776. _threemf_path_cache.clear()
  777. return
  778. for key in [k for k in _threemf_path_cache if k[0] == printer_id]:
  779. _maybe_unlink(_threemf_path_cache[key])
  780. _threemf_path_cache.pop(key, None)
  781. async def download_file_async(
  782. ip_address: str,
  783. access_code: str,
  784. remote_path: str,
  785. local_path: Path,
  786. timeout: float = 60.0,
  787. socket_timeout: float | None = None,
  788. printer_model: str | None = None,
  789. ) -> bool:
  790. """Async wrapper for downloading a file with timeout.
  791. For A1/A1 Mini printers, automatically tries prot_p first, then falls back
  792. to prot_c if the download fails. The working mode is cached for future operations.
  793. Args:
  794. ip_address: Printer IP address
  795. access_code: Printer access code
  796. remote_path: Remote file path on printer
  797. local_path: Local path to save file
  798. timeout: Overall operation timeout (asyncio)
  799. socket_timeout: FTP socket timeout for slow connections (e.g., A1 printers)
  800. printer_model: Printer model for A1-specific workarounds
  801. """
  802. loop = asyncio.get_event_loop()
  803. is_a1 = printer_model in BambuFTPClient.A1_MODELS if printer_model else False
  804. # Per-attempt completion state: asyncio.wait_for cannot cancel
  805. # run_in_executor threads, so on timeout the executor may still complete
  806. # the download after we stop waiting. The thread flips `success` to True
  807. # ONLY after the file is fully written — a post-timeout check lets us
  808. # salvage the download without mistaking an in-progress partial write
  809. # for a completed one. Each attempt gets its own dict and event so a
  810. # zombie from an earlier attempt can't flip the flag for a later one.
  811. # The event is set in `_download`'s finally block so the post-timeout
  812. # path can wait for genuine thread completion instead of a fixed sleep.
  813. def _download(force_prot_c: bool, completion: dict, done: threading.Event) -> bool:
  814. mode_str = "prot_c" if force_prot_c else "prot_p"
  815. try:
  816. client = BambuFTPClient(
  817. ip_address,
  818. access_code,
  819. timeout=socket_timeout,
  820. printer_model=printer_model,
  821. force_prot_c=force_prot_c,
  822. )
  823. if client.connect():
  824. try:
  825. result = client.download_to_file(remote_path, local_path)
  826. if result:
  827. BambuFTPClient.cache_mode(ip_address, mode_str)
  828. completion["success"] = True
  829. return result
  830. finally:
  831. client.disconnect()
  832. return False
  833. finally:
  834. done.set()
  835. async def _run(force_prot_c: bool) -> bool:
  836. completion = {"success": False}
  837. done = threading.Event()
  838. try:
  839. return await asyncio.wait_for(
  840. loop.run_in_executor(_ftp_executor, _download, force_prot_c, completion, done), timeout=timeout
  841. )
  842. except TimeoutError:
  843. # Slow WiFi links commonly overshoot ftp_timeout by 10–30 s without
  844. # actually being stuck, so starting attempt 2 now would just contend
  845. # with the still-progressing RETR on attempt 1 and produce the
  846. # zombie-write race reported in #1014 (file landed on disk minutes
  847. # after the retry loop had already given up). Wait for the worker
  848. # thread to genuinely finish — capped at 30 s so a truly stuck
  849. # connection can't stall a whole attempt indefinitely, with a 0.5 s
  850. # floor so artificially small test timeouts still give zombies a
  851. # realistic window to finish.
  852. grace = max(min(timeout, 30.0), 0.5)
  853. # Deliberately the DEFAULT executor, not `_ftp_executor`: this thread
  854. # blocks waiting on `_download`, which is itself an `_ftp_executor`
  855. # worker. Parking waiters in the same bounded pool as the workers they
  856. # wait for is how you build a deadlock — with enough concurrent
  857. # timeouts the waiters would occupy every slot and the downloads they
  858. # are waiting for could never be scheduled.
  859. await loop.run_in_executor(None, done.wait, grace)
  860. if completion["success"] and local_path.exists() and local_path.stat().st_size > 0:
  861. logger.info(
  862. "FTP download wait_for timed out after %ss for %s, but thread completed within %ss grace (%s bytes) — salvaging",
  863. timeout,
  864. remote_path,
  865. grace,
  866. local_path.stat().st_size,
  867. )
  868. return True
  869. logger.warning(
  870. "FTP download timed out after %ss (plus %ss grace) for %s",
  871. timeout,
  872. grace,
  873. remote_path,
  874. )
  875. return False
  876. # Check if we have a cached mode for this printer
  877. cached_mode = BambuFTPClient._mode_cache.get(ip_address)
  878. if cached_mode:
  879. force_prot_c = cached_mode == "prot_c"
  880. return await _run(force_prot_c)
  881. # No cached mode - try prot_p first
  882. if await _run(False):
  883. return True
  884. # Download failed - for A1 models, try prot_c fallback
  885. if is_a1:
  886. logger.info("FTP download failed with prot_p for A1 model, trying prot_c fallback...")
  887. return await _run(True)
  888. return False
  889. async def download_file_try_paths_async(
  890. ip_address: str,
  891. access_code: str,
  892. remote_paths: list[str],
  893. local_path: Path,
  894. socket_timeout: float | None = None,
  895. printer_model: str | None = None,
  896. timeout: float = 90.0,
  897. ) -> bool:
  898. """Try downloading a file from multiple paths using a single connection.
  899. Args:
  900. socket_timeout: FTP socket timeout for slow connections (e.g., A1 printers)
  901. printer_model: Printer model for A1-specific workarounds
  902. timeout: overall async cap. The per-socket timeout only bounds an
  903. in-flight worker; it does NOT bound how long this coroutine waits
  904. for a free slot in the fixed-size ``_ftp_executor``. On a large
  905. farm where offline printers keep every worker busy on dead
  906. connects, that queue wait is otherwise unbounded — and any caller
  907. holding a DB connection while awaiting this would pin it until the
  908. pool is exhausted (#2572). The cap converts that into a bounded
  909. wait; the orphaned worker finishes and its result is discarded.
  910. """
  911. loop = asyncio.get_event_loop()
  912. def _download():
  913. client = BambuFTPClient(ip_address, access_code, timeout=socket_timeout, printer_model=printer_model)
  914. if not client.connect():
  915. return False
  916. try:
  917. # FileNotOnPrinterError signals "try the next path", not "give up" —
  918. # this function's whole purpose is to walk a list of candidates
  919. # over one connection. Only a real transport error should bubble.
  920. for remote_path in remote_paths:
  921. try:
  922. if client.download_to_file(remote_path, local_path):
  923. return True
  924. except FileNotOnPrinterError:
  925. continue
  926. return False
  927. finally:
  928. client.disconnect()
  929. try:
  930. return await asyncio.wait_for(loop.run_in_executor(_ftp_executor, _download), timeout=timeout)
  931. except TimeoutError:
  932. logger.warning("FTP download_try_paths exceeded its %ss cap for %s (#2572)", timeout, ip_address)
  933. return False
  934. def _upload_deadline(local_path: Path) -> float:
  935. """Derive an upload deadline from the file size (#2529).
  936. See ``_UPLOAD_FLOOR_BYTES_PER_SEC``. An unstat-able file falls back to the
  937. floor timeout — ``upload_file`` will fail on the open() anyway.
  938. """
  939. try:
  940. size = local_path.stat().st_size
  941. except OSError:
  942. return _UPLOAD_MIN_TIMEOUT
  943. return max(_UPLOAD_MIN_TIMEOUT, size / _UPLOAD_FLOOR_BYTES_PER_SEC)
  944. # One upload at a time per printer. Two concurrent STOR commands for the same
  945. # remote path leave a corrupt file on the SD card, and the printer reads as
  946. # flaky rather than busy (#2529). Held for the duration of a transfer, so a
  947. # second dispatch to the same printer queues behind the first instead of racing
  948. # it. Keyed per event loop: an asyncio.Lock binds to the loop that first awaits
  949. # it, and the test suite runs each case on a fresh loop.
  950. _upload_locks: weakref.WeakKeyDictionary[asyncio.AbstractEventLoop, dict[str, asyncio.Lock]] = (
  951. weakref.WeakKeyDictionary()
  952. )
  953. def _upload_lock(loop: asyncio.AbstractEventLoop, ip_address: str) -> asyncio.Lock:
  954. per_loop = _upload_locks.setdefault(loop, {})
  955. lock = per_loop.get(ip_address)
  956. if lock is None:
  957. lock = asyncio.Lock()
  958. per_loop[ip_address] = lock
  959. return lock
  960. async def upload_file_async(
  961. ip_address: str,
  962. access_code: str,
  963. local_path: Path,
  964. remote_path: str,
  965. timeout: float | None = None,
  966. progress_callback: Callable[[int, int], None] | None = None,
  967. socket_timeout: float | None = None,
  968. printer_model: str | None = None,
  969. ) -> bool:
  970. """Async wrapper for uploading a file with timeout and progress callback.
  971. For A1/A1 Mini printers, automatically tries prot_p first, then falls back
  972. to prot_c if the upload fails. The working mode is cached for future uploads.
  973. Args:
  974. ip_address: Printer IP address
  975. access_code: Printer access code
  976. local_path: Local file path to upload
  977. remote_path: Remote path on printer
  978. timeout: Overall deadline. ``None`` (the default) derives it from the
  979. file size — see ``_upload_deadline``. A caller that passes a number
  980. gets exactly that, which is what the tests rely on.
  981. progress_callback: Optional callback for progress updates
  982. socket_timeout: FTP socket timeout for slow connections (e.g., A1 printers)
  983. printer_model: Printer model for A1-specific workarounds
  984. """
  985. loop = asyncio.get_event_loop()
  986. is_a1 = printer_model in BambuFTPClient.A1_MODELS if printer_model else False
  987. deadline = _upload_deadline(local_path) if timeout is None else timeout
  988. # Set when the deadline expires. The worker checks it once per chunk.
  989. cancel = threading.Event()
  990. def _guarded_progress(uploaded: int, total: int) -> None:
  991. if cancel.is_set():
  992. raise UploadCancelled(f"upload of {remote_path} exceeded its {deadline:.0f}s deadline")
  993. if progress_callback:
  994. progress_callback(uploaded, total)
  995. def _upload(force_prot_c: bool = False) -> bool:
  996. mode_str = "prot_c" if force_prot_c else "prot_p"
  997. logger.info(
  998. f"FTP connecting to {ip_address} for upload (model={printer_model}, "
  999. f"mode={mode_str}, socket_timeout={socket_timeout}s, deadline={deadline:.0f}s)..."
  1000. )
  1001. client = BambuFTPClient(
  1002. ip_address, access_code, timeout=socket_timeout, printer_model=printer_model, force_prot_c=force_prot_c
  1003. )
  1004. if client.connect():
  1005. logger.info("FTP connected to %s", ip_address)
  1006. try:
  1007. result = client.upload_file(local_path, remote_path, _guarded_progress)
  1008. if result:
  1009. # Cache the working mode
  1010. BambuFTPClient.cache_mode(ip_address, mode_str)
  1011. return result
  1012. finally:
  1013. client.disconnect()
  1014. logger.warning("FTP connection failed to %s", ip_address)
  1015. return False
  1016. async def _attempt(force_prot_c: bool) -> bool:
  1017. """Run one upload attempt, and make a timeout actually stop the transfer.
  1018. ``asyncio.wait_for`` cancels the *future*, never the executor thread
  1019. behind it. Before #2529 a slow-but-healthy upload that overran the
  1020. deadline left that thread streaming: it kept pushing bytes, kept firing
  1021. the progress callback, and the retry above put a *second* STOR of the
  1022. same file onto the same printer. The reporter's 96 MB job ran four
  1023. concurrent transfers and never landed. So on timeout we signal the
  1024. worker (it raises ``UploadCancelled`` from the progress callback, which
  1025. breaks the send loop and deletes the partial file) and wait for it to
  1026. actually go.
  1027. """
  1028. fut = loop.run_in_executor(_ftp_executor, lambda: _upload(force_prot_c))
  1029. try:
  1030. return await asyncio.wait_for(asyncio.shield(fut), timeout=deadline)
  1031. except TimeoutError:
  1032. cancel.set()
  1033. logger.warning(
  1034. "FTP upload of %s exceeded its %.0fs deadline — cancelling the transfer",
  1035. remote_path,
  1036. deadline,
  1037. )
  1038. try:
  1039. await asyncio.wait_for(asyncio.shield(fut), timeout=_UPLOAD_CANCEL_GRACE)
  1040. except UploadCancelled:
  1041. logger.info("FTP upload of %s cancelled; partial file removed from the printer", remote_path)
  1042. except TimeoutError:
  1043. # The thread is wedged somewhere that never reaches the callback
  1044. # (a blocked sendall, say). Nothing more we can do from here —
  1045. # but consume the eventual result so asyncio doesn't log the
  1046. # future's exception as unretrieved when it is garbage-collected.
  1047. logger.error(
  1048. "FTP upload thread for %s did not stop within %.0fs of the cancel signal",
  1049. remote_path,
  1050. _UPLOAD_CANCEL_GRACE,
  1051. )
  1052. fut.add_done_callback(_swallow_future_result)
  1053. except Exception as e:
  1054. logger.warning("FTP upload of %s errored while cancelling: %s", remote_path, e)
  1055. # Raise rather than return False: a deadline expiry means the link
  1056. # sustained less than the floor rate for the whole transfer, and a
  1057. # retry would only spend another full deadline finding that out
  1058. # again — with check_queue serialized, four of those block the
  1059. # entire print queue for hours. ``with_ftp_retry`` never retries it.
  1060. raise UploadCancelled(
  1061. f"Upload of {remote_path} to {ip_address} exceeded its {deadline:.0f}s deadline "
  1062. f"(link sustained less than {_UPLOAD_FLOOR_BYTES_PER_SEC // 1024} KB/s)"
  1063. ) from None
  1064. async with _upload_lock(loop, ip_address):
  1065. # Check if we have a cached mode for this printer
  1066. cached_mode = BambuFTPClient._mode_cache.get(ip_address)
  1067. if cached_mode:
  1068. # Use cached mode
  1069. return await _attempt(cached_mode == "prot_c")
  1070. # No cached mode - try prot_p first
  1071. if await _attempt(False):
  1072. return True
  1073. # Upload failed - for A1 models, try prot_c fallback
  1074. if is_a1:
  1075. logger.info("FTP upload failed with prot_p for A1 model, trying prot_c fallback...")
  1076. return await _attempt(True)
  1077. return False
  1078. def _swallow_future_result(fut: asyncio.Future) -> None:
  1079. """Retrieve a future's exception so asyncio doesn't log it as unhandled."""
  1080. if not fut.cancelled():
  1081. fut.exception()
  1082. async def list_files_async(
  1083. ip_address: str,
  1084. access_code: str,
  1085. path: str = "/",
  1086. timeout: float = 30.0,
  1087. socket_timeout: float | None = None,
  1088. printer_model: str | None = None,
  1089. ) -> list[dict]:
  1090. """Async wrapper for listing files with timeout.
  1091. Args:
  1092. socket_timeout: FTP socket timeout for slow connections (e.g., A1 printers)
  1093. printer_model: Printer model for A1-specific workarounds
  1094. """
  1095. loop = asyncio.get_event_loop()
  1096. def _list():
  1097. client = BambuFTPClient(ip_address, access_code, timeout=socket_timeout, printer_model=printer_model)
  1098. if client.connect():
  1099. try:
  1100. return client.list_files(path)
  1101. finally:
  1102. client.disconnect()
  1103. return []
  1104. try:
  1105. return await asyncio.wait_for(loop.run_in_executor(_ftp_executor, _list), timeout=timeout)
  1106. except TimeoutError:
  1107. logger.warning("FTP list_files timed out after %ss for %s", timeout, path)
  1108. return []
  1109. async def delete_file_async(
  1110. ip_address: str,
  1111. access_code: str,
  1112. remote_path: str,
  1113. socket_timeout: float | None = None,
  1114. printer_model: str | None = None,
  1115. timeout: float = 60.0,
  1116. ) -> DeleteResult:
  1117. """Async wrapper for deleting a file.
  1118. Returns :class:`DeleteResult` so callers can distinguish ``NOT_FOUND``
  1119. (550 — file isn't on the printer, no retry value) from ``FAILED``
  1120. (network / auth / transient — worth retrying or surfacing).
  1121. Args:
  1122. socket_timeout: FTP socket timeout for slow connections (e.g., A1 printers)
  1123. printer_model: Printer model for A1-specific workarounds
  1124. timeout: overall async cap so a saturated ``_ftp_executor`` can't pin
  1125. the caller (and any DB connection it holds) indefinitely (#2572).
  1126. """
  1127. loop = asyncio.get_event_loop()
  1128. def _delete() -> DeleteResult:
  1129. client = BambuFTPClient(ip_address, access_code, timeout=socket_timeout, printer_model=printer_model)
  1130. if client.connect():
  1131. try:
  1132. return client.delete_file(remote_path)
  1133. finally:
  1134. client.disconnect()
  1135. return DeleteResult.FAILED
  1136. try:
  1137. return await asyncio.wait_for(loop.run_in_executor(_ftp_executor, _delete), timeout=timeout)
  1138. except TimeoutError:
  1139. logger.warning("FTP delete_file exceeded its %ss cap for %s (#2572)", timeout, ip_address)
  1140. return DeleteResult.FAILED
  1141. async def download_file_bytes_async(
  1142. ip_address: str,
  1143. access_code: str,
  1144. remote_path: str,
  1145. socket_timeout: float | None = None,
  1146. printer_model: str | None = None,
  1147. timeout: float = 300.0,
  1148. ) -> bytes | None:
  1149. """Async wrapper for downloading file as bytes.
  1150. Args:
  1151. socket_timeout: FTP socket timeout for slow connections (e.g., A1 printers)
  1152. printer_model: Printer model for A1-specific workarounds
  1153. timeout: overall async cap so a saturated ``_ftp_executor`` can't pin
  1154. the caller (and any DB connection it holds) indefinitely (#2572).
  1155. Generous by default because this pulls whole files (timelapse
  1156. video, gcode) which can legitimately take minutes over slow Wi-Fi —
  1157. the cap only guards against a permanently-starved pool, not a
  1158. slow-but-progressing transfer.
  1159. """
  1160. loop = asyncio.get_event_loop()
  1161. def _download():
  1162. client = BambuFTPClient(ip_address, access_code, timeout=socket_timeout, printer_model=printer_model)
  1163. if client.connect():
  1164. try:
  1165. return client.download_file(remote_path)
  1166. finally:
  1167. client.disconnect()
  1168. return None
  1169. try:
  1170. return await asyncio.wait_for(loop.run_in_executor(_ftp_executor, _download), timeout=timeout)
  1171. except TimeoutError:
  1172. logger.warning("FTP download_bytes exceeded its %ss cap for %s (#2572)", timeout, ip_address)
  1173. return None
  1174. async def get_storage_info_async(
  1175. ip_address: str,
  1176. access_code: str,
  1177. socket_timeout: float | None = None,
  1178. printer_model: str | None = None,
  1179. timeout: float = 60.0,
  1180. ) -> dict | None:
  1181. """Async wrapper for getting storage info.
  1182. Args:
  1183. socket_timeout: FTP socket timeout for slow connections (e.g., A1 printers)
  1184. printer_model: Printer model for A1-specific workarounds
  1185. timeout: overall async cap so a saturated ``_ftp_executor`` can't pin
  1186. the caller (and any DB connection it holds) indefinitely (#2572).
  1187. """
  1188. loop = asyncio.get_event_loop()
  1189. def _get_storage():
  1190. client = BambuFTPClient(ip_address, access_code, timeout=socket_timeout, printer_model=printer_model)
  1191. if client.connect():
  1192. try:
  1193. return client.get_storage_info()
  1194. finally:
  1195. client.disconnect()
  1196. return None
  1197. try:
  1198. return await asyncio.wait_for(loop.run_in_executor(_ftp_executor, _get_storage), timeout=timeout)
  1199. except TimeoutError:
  1200. logger.warning("FTP get_storage_info exceeded its %ss cap for %s (#2572)", timeout, ip_address)
  1201. return None
  1202. async def get_ftp_retry_settings() -> tuple[bool, int, float, float]:
  1203. """Get FTP retry settings from database.
  1204. Returns:
  1205. Tuple of (retry_enabled, retry_count, retry_delay, timeout)
  1206. """
  1207. from backend.app.api.routes.settings import get_setting
  1208. from backend.app.core.database import async_session
  1209. async with async_session() as db:
  1210. enabled = (await get_setting(db, "ftp_retry_enabled") or "true") == "true"
  1211. count = int(await get_setting(db, "ftp_retry_count") or "3")
  1212. delay = float(await get_setting(db, "ftp_retry_delay") or "2")
  1213. timeout = float(await get_setting(db, "ftp_timeout") or "30")
  1214. return enabled, count, delay, timeout
  1215. async def with_ftp_retry(
  1216. operation: Callable[..., Awaitable[T]],
  1217. *args,
  1218. max_retries: int = 3,
  1219. retry_delay: float = 2.0,
  1220. operation_name: str = "FTP operation",
  1221. non_retry_exceptions: tuple[type[BaseException], ...] = (),
  1222. **kwargs,
  1223. ) -> T | None:
  1224. """Execute FTP operation with retry logic.
  1225. Args:
  1226. operation: Async function to execute
  1227. *args: Positional arguments for the operation
  1228. max_retries: Number of retry attempts (default: 3)
  1229. retry_delay: Seconds to wait between retries (default: 2.0)
  1230. operation_name: Name for logging purposes
  1231. non_retry_exceptions: Exception types that should immediately abort retries
  1232. **kwargs: Keyword arguments for the operation
  1233. Returns:
  1234. Result of the operation, or None if all attempts fail
  1235. ``UploadCancelled`` is never retried, whatever the caller passes: it means
  1236. the transfer overran its size-derived deadline, so a retry would spend
  1237. another full deadline reaching the same conclusion (#2529).
  1238. """
  1239. last_error = None
  1240. for attempt in range(max_retries + 1):
  1241. try:
  1242. result = await operation(*args, **kwargs)
  1243. # Check for "falsy" success indicators
  1244. if result not in (False, None, []):
  1245. if attempt > 0:
  1246. logger.info("%s succeeded on attempt %s/%s", operation_name, attempt + 1, max_retries + 1)
  1247. return result
  1248. # Operation returned failure indicator
  1249. if attempt > 0:
  1250. logger.info("%s attempt %s/%s returned failure", operation_name, attempt + 1, max_retries + 1)
  1251. except UploadCancelled:
  1252. raise
  1253. except Exception as e:
  1254. if non_retry_exceptions and isinstance(e, non_retry_exceptions):
  1255. raise
  1256. last_error = e
  1257. logger.warning("%s attempt %s/%s failed: %s", operation_name, attempt + 1, max_retries + 1, e)
  1258. # Don't wait after the last attempt
  1259. if attempt < max_retries:
  1260. logger.info("%s will retry in %ss...", operation_name, retry_delay)
  1261. await asyncio.sleep(retry_delay)
  1262. logger.error("%s failed after %s attempts", operation_name, max_retries + 1)
  1263. if last_error:
  1264. logger.debug("Last error: %s", last_error)
  1265. return None