bambu_ftp.py 50 KB

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