bambu_ftp.py 73 KB

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