bambu_ftp.py 50 KB

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