bambu_ftp.py 99 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253
  1. import asyncio
  2. import ftplib # nosec B402
  3. import logging
  4. import os
  5. import shutil
  6. import socket
  7. import ssl
  8. import threading
  9. import time
  10. import weakref
  11. from collections.abc import Awaitable, Callable
  12. from concurrent.futures import ThreadPoolExecutor
  13. from dataclasses import dataclass
  14. from enum import Enum
  15. from ftplib import FTP, FTP_TLS # nosec B402
  16. from io import BytesIO
  17. from pathlib import Path
  18. from typing import TypeVar
  19. logger = logging.getLogger(__name__)
  20. T = TypeVar("T")
  21. # Every FTP call below is blocking ftplib work handed to a thread. They used to
  22. # run on asyncio's *default* executor, which is sized min(32, cpu_count + 4) —
  23. # six threads on a 2-core NAS — and is shared with every other ``to_thread`` /
  24. # ``run_in_executor`` caller in the app. That was survivable only because the
  25. # scheduler uploaded to exactly one printer at a time. Dispatching to several
  26. # printers at once (#2555) would park one thread per in-flight upload for
  27. # minutes at a stretch (a 41 MB 3MF at the ~150 KB/s a Bambu printer sustains
  28. # takes ~4 min), starving the default pool and stalling unrelated work.
  29. #
  30. # A dedicated pool keeps that blast radius inside the FTP layer: the scheduler's
  31. # own concurrency cap is what limits parallel uploads, and it can never exhaust
  32. # the executor everything else depends on. Threads are created lazily, so an
  33. # idle pool costs nothing.
  34. #
  35. # Sized well above `queue_max_concurrent_uploads` (max 16), because uploads are
  36. # not the only traffic here: SD browsing, timelapse/recording listing, cover
  37. # downloads, deletes and storage checks all run through this pool too, and on a
  38. # farm they fan out across every printer at once. The pool's work queue is
  39. # unbounded, so exceeding it does not fail — it queues. But `asyncio.wait_for`
  40. # starts its clock at submission, not at thread start, so a task that sits in the
  41. # queue can burn its whole timeout without ever running, and `list_files_async`
  42. # reports a timeout as an empty listing — a silent "this printer has no files".
  43. # Keep the headroom.
  44. _FTP_MAX_WORKERS = 48
  45. _ftp_executor = ThreadPoolExecutor(max_workers=_FTP_MAX_WORKERS, thread_name_prefix="bambu-ftp")
  46. # Overall upload deadline (#2529). A flat wall-clock cap punishes big files on
  47. # slow links rather than catching broken ones: a 96 MB 3MF at the ~75 KB/s an A1
  48. # sustains over WiFi legitimately needs ~20 minutes, and the old flat 600 s
  49. # declared it dead at ~70 MB. The deadline is therefore derived from the file
  50. # size against a deliberately pessimistic floor rate. This is a backstop, not the
  51. # failure detector — a link that has actually died is caught within
  52. # ``socket_timeout`` by the blocking ``sendall``, long before this fires.
  53. _UPLOAD_FLOOR_BYTES_PER_SEC = 25 * 1024
  54. _UPLOAD_MIN_TIMEOUT = 600.0
  55. # How long to give the worker thread to notice the cancel flag, unwind, and
  56. # delete its partial file. It checks the flag once per CHUNK_SIZE, so on a link
  57. # slow enough to have hit the deadline this is one chunk plus the delete.
  58. _UPLOAD_CANCEL_GRACE = 60.0
  59. class UploadCancelled(Exception):
  60. """Raised inside the upload worker to abort an in-flight transfer.
  61. ``upload_file`` treats any exception from its progress callback as "stop
  62. now": it breaks out of the send loop, deletes the partial file from the
  63. printer, and re-raises. That is the only way to stop a transfer — an
  64. executor thread cannot be cancelled from the event loop, so a bare
  65. ``asyncio.wait_for`` leaves it streaming (see ``upload_file_async``).
  66. """
  67. class DownloadCancelled(Exception):
  68. """Raised in an FTP callback to stop a disk-backed download cooperatively."""
  69. class DownloadLimitExceeded(Exception):
  70. """Raised before an FTP callback writes beyond its caller-supplied limit."""
  71. class DownloadInsufficientSpace(Exception):
  72. """Raised before an FTP callback consumes the application's disk reserve."""
  73. @dataclass(frozen=True)
  74. class FileListResult:
  75. """A directory listing that distinguishes empty from unreachable."""
  76. files: list[dict]
  77. available: bool
  78. class DeleteResult(Enum):
  79. """Outcome of an FTP delete attempt.
  80. Distinguishes "file isn't on the printer" (550, recovery impossible by
  81. retrying) from "delete failed for some other reason" (network, auth,
  82. transient FTP error — worth retrying). The post-print SD-card cleanup in
  83. main.py used to flatten both into ``False`` and log a "may linger" WARNING
  84. on every successful print where the printer self-cleaned its SD card
  85. before our cleanup ran (#1721 reporter's A1).
  86. """
  87. DELETED = "deleted"
  88. NOT_FOUND = "not_found"
  89. FAILED = "failed"
  90. # How long to stop opening FTPS connections to a printer after its TLS
  91. # handshake failed (#2780).
  92. #
  93. # ``WRONG_VERSION_NUMBER`` on port 990 means the printer answered with
  94. # something that is not a TLS record at all, so no path, retry or SSL option
  95. # gets further. Two support bundles show that state lasting for days: one X2D
  96. # served clean FTPS for five days, flipped on 2026-07-19, and then failed every
  97. # single handshake for the next eight (zero successes, 3511 failures).
  98. #
  99. # What it is NOT is a wedged file service, which is what this comment used to
  100. # claim. #2780's reporter power-cycled both affected printers and the state
  101. # survived it, and ``openssl s_client`` against the same port completes a clean
  102. # handshake and returns a valid certificate while Bambuddy is failing. The
  103. # leading theory is now a connection-count refusal — vsFTPd answers one in
  104. # cleartext, which is exactly this error to an implicit-TLS client, and answers
  105. # the global limit by accepting and never speaking, which is the handshake
  106. # timeout we also see. Unproven: confirming it needs a capture taken while a
  107. # printer is in the failing state.
  108. #
  109. # Without a gate every candidate path re-runs the same doomed handshake: the
  110. # 3MF lookup alone walks 6 filename variants x 5 directories x 4 retries, and
  111. # the cover and timelapse scans run their own sweeps on top. That is where
  112. # those thousands of failures come from — one wedged printer, hammered.
  113. #
  114. # Five minutes is short enough that a power-cycled printer is picked up on the
  115. # next print (and any successful connect clears the gate immediately), long
  116. # enough that a wedged one is contacted twice an hour instead of hundreds of
  117. # times a minute.
  118. _HANDSHAKE_COOLOFF_SECONDS = 300.0
  119. # How long to wait for a printer to say something in cleartext on the TLS port.
  120. # The failing case answers immediately -- the banner is the first thing a
  121. # vsFTPd refusal sends -- so this only ever elapses in full when the service has
  122. # gone back to speaking TLS and is waiting for a ClientHello that will not come.
  123. _CLEARTEXT_PROBE_TIMEOUT = 2.0
  124. def _read_cleartext_reply(ip_address: str, port: int) -> str | None:
  125. """Read what a printer answers the TLS port with, when it is not TLS.
  126. ``WRONG_VERSION_NUMBER`` means the peer's first bytes were not a TLS
  127. record -- measured, not inferred: a cleartext ``421`` banner reproduces
  128. that exact error and message, while a genuine version mismatch produces
  129. ``TLSV1_ALERT_PROTOCOL_VERSION`` instead (#2780).
  130. What it does not say is *which* cleartext message, and that is the part
  131. that would identify the fault. OpenSSL has already consumed those bytes by
  132. the time the error surfaces, so this opens one plain connection and reads
  133. them directly. Answering it from the reporter's own printers beats waiting
  134. on a packet capture from the one farm that can take one.
  135. Returns the reply, or None when the printer said nothing readable -- which
  136. is itself informative: a healthy implicit-FTPS service sends nothing until
  137. it has a ClientHello, so silence means the fault had already passed.
  138. """
  139. sock = None
  140. # One budget for connect *and* read. Given a timeout each, a printer that
  141. # is slow to accept would then get the full read window on top of it, and
  142. # the wait this adds to a failed connect would be double what it says.
  143. deadline = time.monotonic() + _CLEARTEXT_PROBE_TIMEOUT
  144. try:
  145. sock = socket.create_connection((ip_address, port), _CLEARTEXT_PROBE_TIMEOUT)
  146. sock.settimeout(max(0.05, deadline - time.monotonic()))
  147. # One read. A refusal is a single short line; anything longer is not
  148. # the thing being looked for, and this must not become a transfer.
  149. raw = sock.recv(256)
  150. except OSError as e:
  151. # Refused or reset is a different fact from "answered in cleartext",
  152. # and worth having in the log rather than flattened into silence.
  153. logger.debug("Cleartext probe of %s:%s could not connect: %s", ip_address, port, e)
  154. return None
  155. finally:
  156. if sock is not None:
  157. try:
  158. sock.close()
  159. except OSError:
  160. pass
  161. if not raw:
  162. return None
  163. # latin-1 cannot fail, and an FTP reply line is ASCII in practice. Control
  164. # characters are stripped so a stray byte cannot mangle the log line.
  165. text = raw.decode("latin-1").strip()
  166. return "".join(c for c in text if c.isprintable()) or None
  167. def _ftp_reply_code(error: BaseException) -> str | None:
  168. """The three-digit reply code an ftplib error carries, if it carries one.
  169. ``ftplib`` puts the server's whole reply line in the exception message, so
  170. the code is the first token: "553 Could not create file." Anything that is
  171. not three digits (an ``OSError``, a library-side message) has no code, and
  172. saying so beats inventing one.
  173. """
  174. head = str(error)[:3]
  175. return head if head.isdigit() else None
  176. class FtpFailureKind(Enum):
  177. """Why an FTP operation failed, at the granularity the client can tell.
  178. ``connect`` and ``upload_file`` already separate every one of these -- each
  179. has its own log line, and 553 even gets a spelled-out list of storage
  180. causes -- and then both returned a bare ``False``. So the dispatch that
  181. reports the failure to the operator had nothing to go on, and used one
  182. string for all of them: "check if SD card is inserted and properly
  183. formatted". #2899's reporter acted on that after a TLS handshake failure
  184. and restarted the printer, which could not have helped: the handshake never
  185. got near the printer's filesystem.
  186. """
  187. COOLOFF = "cooloff" # skipped without contacting the printer (#2780)
  188. HANDSHAKE = "handshake" # port 990 answered with something that is not TLS
  189. AUTH = "auth" # permanent refusal, typically a rejected access code
  190. TIMEOUT = "timeout"
  191. STORAGE = "storage" # 553/552 -- the case the SD-card advice was written for
  192. NOT_FOUND = "not_found" # 550
  193. NETWORK = "network" # socket dropped, or an FTP error with no clearer reading
  194. UNKNOWN = "unknown"
  195. @dataclass(frozen=True)
  196. class FtpFailure:
  197. """What went wrong, kept next to the log line that already said it."""
  198. kind: FtpFailureKind
  199. detail: str
  200. code: str | None = None # FTP reply code where the server gave one
  201. @dataclass
  202. class FtpFailureReport:
  203. """A slot the *caller* owns for the reason its upload failed.
  204. Deliberately not a per-IP dict on the client, the way ``_mode_cache`` and
  205. ``_handshake_blocked_until`` are. Those describe a printer, and are
  206. correct to share. This describes one operation, and a background timelapse
  207. fetch running beside a dispatch would overwrite the dispatch's reason with
  208. its own -- reporting the wrong cause with total confidence, which is the
  209. bug being fixed rather than a new way to hit it (#2899).
  210. """
  211. failure: FtpFailure | None = None
  212. class FileNotOnPrinterError(Exception):
  213. """Raised when a remote FTP path returns 550 (file not found).
  214. 550 means the file does not exist at that path — retrying the same path
  215. will never succeed. Callers use this sentinel with with_ftp_retry's
  216. non_retry_exceptions to immediately move on to the next candidate path
  217. instead of burning the full retry budget (up to 11 × 30s per path) on
  218. a lookup that cannot recover.
  219. """
  220. class ImplicitFTP_TLS(FTP_TLS):
  221. """FTP_TLS subclass for implicit FTPS (port 990) with model-specific SSL handling.
  222. X1C/P1S printers (vsFTPd) require SSL with session reuse on the data channel.
  223. A1/A1 Mini printers have issues with SSL on the data channel entirely and
  224. timeout waiting for transfer completion. Set skip_session_reuse=True for A1
  225. printers to skip SSL on the data channel (control channel remains encrypted).
  226. Optionally caps the SSL context's maximum TLS version to v1.2 (P2S firmware
  227. 01.02.00.00 needs this — see :mod:`ftp_profiles` and #1401).
  228. """
  229. def __init__(self, *args, skip_session_reuse: bool = False, cap_tls_v1_2: bool = False, **kwargs):
  230. super().__init__(*args, **kwargs)
  231. self._sock = None
  232. self.skip_session_reuse = skip_session_reuse
  233. self.ssl_context = ssl.create_default_context()
  234. self.ssl_context.check_hostname = False
  235. self.ssl_context.verify_mode = ssl.CERT_NONE
  236. # ``create_default_context()`` does NOT guarantee a protocol floor: it
  237. # leaves ``minimum_version`` at ``MINIMUM_SUPPORTED``, and what that
  238. # resolves to is a property of the OpenSSL build, not of this code.
  239. # Measured on identical OpenSSL 3.5.6: python:3.13-slim-trixie (our
  240. # Docker base) reports TLSv1_2, a bare-metal venv reports
  241. # MINIMUM_SUPPORTED. Docker users have therefore always been floored at
  242. # 1.2 — every Bambu model is reachable under that floor — while
  243. # bare-metal and appliance installs could silently negotiate TLS 1.0.
  244. # State the floor rather than inheriting it.
  245. self.ssl_context.minimum_version = ssl.TLSVersion.TLSv1_2
  246. if cap_tls_v1_2:
  247. # With the floor above this pins the connection to exactly TLS 1.2.
  248. self.ssl_context.maximum_version = ssl.TLSVersion.TLSv1_2
  249. def connect(self, host="", port=990, timeout=-999, source_address=None):
  250. """Connect to host, wrapping socket in TLS immediately (implicit FTPS)."""
  251. if host:
  252. self.host = host
  253. if port > 0:
  254. self.port = port
  255. if timeout != -999:
  256. self.timeout = timeout
  257. if source_address:
  258. self.source_address = source_address
  259. # Create and wrap socket immediately (implicit TLS)
  260. self.sock = socket.create_connection((self.host, self.port), self.timeout, source_address=self.source_address)
  261. self.sock = self.ssl_context.wrap_socket(self.sock, server_hostname=self.host)
  262. self.af = self.sock.family
  263. self.file = self.sock.makefile("r", encoding=self.encoding)
  264. self.welcome = self.getresp()
  265. return self.welcome
  266. def ntransfercmd(self, cmd, rest=None):
  267. """Override to wrap data connection in SSL for X1C/P1S only.
  268. X1C/P1S printers (vsFTPd) require SSL session reuse on the data channel.
  269. A1/A1 Mini printers have issues with SSL on the data channel entirely -
  270. they timeout waiting for the transfer completion response. For A1, we
  271. skip SSL wrapping on the data channel (control channel remains encrypted).
  272. """
  273. conn, size = FTP.ntransfercmd(self, cmd, rest)
  274. if self._prot_p and not self.skip_session_reuse:
  275. # X1C/P1S: Wrap data channel with SSL session reuse (required by vsFTPd)
  276. conn = self.ssl_context.wrap_socket(
  277. conn,
  278. server_hostname=self.host,
  279. session=self.sock.session,
  280. )
  281. # A1/A1 Mini (skip_session_reuse=True): Don't wrap data channel in SSL
  282. # The control channel remains encrypted via implicit FTPS
  283. return conn, size
  284. class BambuFTPClient:
  285. """FTP client for retrieving files from Bambu Lab printers."""
  286. FTP_PORT = 990
  287. # Default timeout in seconds (increased for A1 printers)
  288. DEFAULT_TIMEOUT = 30
  289. # Models that may need SSL mode fallback (try prot_p first, fall back to prot_c)
  290. # These models have varying FTP SSL behavior depending on firmware version
  291. A1_MODELS = ("A1", "A1 Mini")
  292. # Chunk size for manual upload transfer (64KB)
  293. # Smaller chunks provide smoother progress reporting — at typical printer FTP
  294. # speeds (~50-100KB/s) this gives a progress update roughly every second.
  295. CHUNK_SIZE = 64 * 1024
  296. # Cache for working FTP modes per printer IP
  297. # Maps IP -> "prot_p" or "prot_c"
  298. _mode_cache: dict[str, str] = {}
  299. # Printers whose FTPS handshake just failed, mapped to the monotonic time
  300. # their cool-off expires. See ``_HANDSHAKE_COOLOFF_SECONDS``.
  301. _handshake_blocked_until: dict[str, float] = {}
  302. # Which cool-off deadline each printer's "not attempted" warning was last
  303. # logged for, so the warning is said once per cool-off. See ``connect``.
  304. _handshake_skip_logged: dict[str, float] = {}
  305. def __init__(
  306. self,
  307. ip_address: str,
  308. access_code: str,
  309. timeout: float | None = None,
  310. printer_model: str | None = None,
  311. force_prot_c: bool = False,
  312. respect_handshake_cooloff: bool = True,
  313. ):
  314. """Set ``respect_handshake_cooloff=False`` for bounded, user-initiated work.
  315. The cool-off exists to stop an unbounded sweep re-running one doomed
  316. handshake a hundred times over (#2780). Dispatching a print is not
  317. that: it is one delete plus at most four upload attempts, with someone
  318. waiting on the result. Sharing the sweep's gate cost those attempts
  319. their whole retry budget, and failed every further job queued for that
  320. printer for the rest of the 300s window (#2898).
  321. Leave it at the default everywhere else. Opting out is only defensible
  322. because the caller's own connection count is bounded and small.
  323. """
  324. self.ip_address = ip_address
  325. self.access_code = access_code
  326. self.timeout = timeout if timeout is not None else self.DEFAULT_TIMEOUT
  327. self.printer_model = printer_model
  328. self.force_prot_c = force_prot_c
  329. self.respect_handshake_cooloff = respect_handshake_cooloff
  330. # Why the last connect/upload on this client failed, for a caller that
  331. # only gets a bool back (#2899). Per instance, so it describes one
  332. # operation and cannot be overwritten by work against another printer.
  333. self.last_failure: FtpFailure | None = None
  334. self._ftp: ImplicitFTP_TLS | None = None
  335. def _is_a1_model(self) -> bool:
  336. """Check if this is an A1 series printer."""
  337. if not self.printer_model:
  338. return False
  339. return self.printer_model in self.A1_MODELS
  340. def _get_cached_mode(self) -> str | None:
  341. """Get cached FTP mode for this printer."""
  342. return self._mode_cache.get(self.ip_address)
  343. @classmethod
  344. def cache_mode(cls, ip_address: str, mode: str):
  345. """Cache the working FTP mode for a printer."""
  346. cls._mode_cache[ip_address] = mode
  347. logger.info("FTP mode cached for %s: %s", ip_address, mode)
  348. def _should_use_prot_c(self) -> bool:
  349. """Determine if we should use prot_c (clear) mode."""
  350. # If explicitly forced, use prot_c
  351. if self.force_prot_c:
  352. return True
  353. # Check cache first
  354. cached = self._get_cached_mode()
  355. if cached:
  356. return cached == "prot_c"
  357. # Default: try prot_p first (will fall back if needed)
  358. return False
  359. @classmethod
  360. def handshake_blocked(cls, ip_address: str) -> bool:
  361. """True while *ip_address* is inside its post-handshake-failure cool-off.
  362. Public so a caller sweeping many candidate paths can stop after the
  363. first one rather than walking the rest against a printer that cannot
  364. complete a TLS handshake (#2780).
  365. """
  366. deadline = cls._handshake_blocked_until.get(ip_address)
  367. if deadline is None:
  368. return False
  369. if time.monotonic() >= deadline:
  370. # Drop it on the way past rather than leaving an entry per printer
  371. # this process has ever failed against.
  372. del cls._handshake_blocked_until[ip_address]
  373. cls._handshake_skip_logged.pop(ip_address, None)
  374. return False
  375. return True
  376. def connect(self) -> bool:
  377. """Connect to the printer FTP server (implicit FTPS on port 990).
  378. Returns False without touching the network while the printer is inside
  379. the cool-off a previous TLS handshake failure opened (#2780) -- unless
  380. this client was built with ``respect_handshake_cooloff=False``.
  381. """
  382. self.last_failure = None
  383. if self.respect_handshake_cooloff and self.handshake_blocked(self.ip_address):
  384. # WARNING, not DEBUG. This is the one connect() failure path that
  385. # reported without its cause, so at default log level four
  386. # reason-free "FTP connection failed" lines two seconds apart gave
  387. # no hint that nothing had been sent (#2898). Every caller reaching
  388. # here is already gated by handshake_blocked() at its own sweep
  389. # boundary, so this costs about one line per print, not a flood.
  390. deadline = self._handshake_blocked_until.get(self.ip_address)
  391. remaining = max(0.0, deadline - time.monotonic()) if deadline is not None else 0.0
  392. if deadline is not None and self._handshake_skip_logged.get(self.ip_address) != deadline:
  393. self._handshake_skip_logged[self.ip_address] = deadline
  394. logger.warning(
  395. "FTP connect to %s not attempted: its FTPS handshake failed recently and it is "
  396. "cooling off for another %.0fs. Nothing was sent to the printer.",
  397. self.ip_address,
  398. remaining,
  399. )
  400. else:
  401. # Said once already for this cool-off. Repeating it per candidate
  402. # path is the log flood #2780 set out to stop -- a download-zip
  403. # of 200 files would print the same sentence 200 times.
  404. logger.debug(
  405. "FTP connect to %s skipped: still cooling off for another %.0fs",
  406. self.ip_address,
  407. remaining,
  408. )
  409. self.last_failure = FtpFailure(
  410. FtpFailureKind.COOLOFF,
  411. f"cooling off for another {remaining:.0f}s after a recent FTPS handshake failure",
  412. )
  413. return False
  414. try:
  415. use_prot_c = self._should_use_prot_c()
  416. from backend.app.services.ftp_profiles import get_ftp_profile
  417. profile = get_ftp_profile(self.printer_model)
  418. logger.debug(
  419. f"FTP connecting to {self.ip_address}:{self.FTP_PORT} "
  420. f"(timeout={self.timeout}s, model={self.printer_model}, prot_c={use_prot_c}, "
  421. f"cap_tls_v1_2={profile.cap_tls_v1_2})"
  422. )
  423. self._ftp = ImplicitFTP_TLS(
  424. skip_session_reuse=use_prot_c,
  425. cap_tls_v1_2=profile.cap_tls_v1_2,
  426. )
  427. self._ftp.connect(self.ip_address, self.FTP_PORT, timeout=self.timeout)
  428. logger.debug("FTP connected, logging in as bblp")
  429. self._ftp.login("bblp", self.access_code)
  430. if use_prot_c:
  431. # Use clear (unencrypted) data channel
  432. logger.debug("FTP logged in, setting prot_c (clear) and passive mode")
  433. self._ftp.prot_c()
  434. else:
  435. # Use protected (encrypted) data channel with session reuse
  436. logger.debug("FTP logged in, setting prot_p (protected) and passive mode")
  437. self._ftp.prot_p()
  438. self._ftp.set_pasv(True)
  439. # Log welcome message for debugging
  440. if hasattr(self._ftp, "welcome") and self._ftp.welcome:
  441. logger.debug("FTP server welcome: %s", self._ftp.welcome)
  442. logger.info(
  443. f"FTP connected successfully to {self.ip_address} (model={self.printer_model}, prot_c={use_prot_c})"
  444. )
  445. return True
  446. except ftplib.error_perm as e:
  447. logger.warning("FTP connection permission error to %s: %s", self.ip_address, e)
  448. self.last_failure = FtpFailure(FtpFailureKind.AUTH, str(e), _ftp_reply_code(e))
  449. self._abandon_connection()
  450. return False
  451. except TimeoutError as e:
  452. logger.warning("FTP connection timed out to %s: %s", self.ip_address, e)
  453. self.last_failure = FtpFailure(FtpFailureKind.TIMEOUT, str(e))
  454. self._abandon_connection()
  455. return False
  456. except ssl.SSLError as e:
  457. # Not a transient failure and not something another path or another
  458. # retry can route around: the printer's file service answered port
  459. # 990 with something that isn't TLS. Say so once and stop knocking
  460. # for a while (#2780).
  461. #
  462. # Deliberately no advice about what to do. This message used to
  463. # tell the operator to restart the printer; #2780's reporter did
  464. # that twice, to no effect, and a single manual connect to the
  465. # same printer completes a clean handshake. We do not yet know the
  466. # trigger, so stating the observation and stopping there beats
  467. # sending people to do the one thing already known not to work.
  468. logger.warning(
  469. "FTP SSL error connecting to %s: %s — the printer answered port %s with something "
  470. "that is not TLS, so print files, covers and timelapses cannot be fetched from it. "
  471. "Pausing FTP to this printer for %.0fs.",
  472. self.ip_address,
  473. e,
  474. self.FTP_PORT,
  475. _HANDSHAKE_COOLOFF_SECONDS,
  476. )
  477. # Close the dead socket before asking this printer for anything
  478. # else. The probe below opens a second connection, and the leading
  479. # theory for this failure is a printer out of connection slots --
  480. # holding a failed handshake open across that is the exact thing
  481. # #2780's cleanup was added to stop. Idempotent, so the call that
  482. # used to sit at the end of this branch simply moved up.
  483. self._abandon_connection()
  484. # Ask the printer what it actually said, once per cool-off window.
  485. # Checked before the deadline below is written, so a live entry here
  486. # means an earlier failure already opened this window and already
  487. # asked -- which keeps a dispatch that ignores the cool-off from
  488. # probing on each of its four attempts.
  489. detail = str(e)
  490. if getattr(e, "reason", None) == "WRONG_VERSION_NUMBER" and not self.handshake_blocked(self.ip_address):
  491. reply = _read_cleartext_reply(self.ip_address, self.FTP_PORT)
  492. if reply:
  493. logger.warning(
  494. "Printer %s answered port %s in cleartext with: %s — that is what the TLS "
  495. "handshake read as a malformed record. Please include this line if you report it.",
  496. self.ip_address,
  497. self.FTP_PORT,
  498. reply,
  499. )
  500. detail = f"{e} (printer answered in cleartext: {reply})"
  501. else:
  502. logger.warning(
  503. "Printer %s sent nothing readable in cleartext on port %s, so its file service "
  504. "was speaking TLS again by the time we asked — the refusal was momentary.",
  505. self.ip_address,
  506. self.FTP_PORT,
  507. )
  508. self._handshake_blocked_until[self.ip_address] = time.monotonic() + _HANDSHAKE_COOLOFF_SECONDS
  509. self.last_failure = FtpFailure(FtpFailureKind.HANDSHAKE, detail)
  510. return False
  511. except (OSError, ftplib.Error) as e:
  512. logger.warning("FTP connection failed to %s: %s (type: %s)", self.ip_address, e, type(e).__name__)
  513. self.last_failure = FtpFailure(FtpFailureKind.NETWORK, str(e), _ftp_reply_code(e))
  514. self._abandon_connection()
  515. return False
  516. def _abandon_connection(self) -> None:
  517. """Drop a connection that never became usable, closing its socket.
  518. Every failure path in :meth:`connect` used to clear ``self._ftp`` and
  519. nothing else, leaving a connected socket for the garbage collector.
  520. That is survivable once; it is not survivable at this volume. A single
  521. print used to walk ~110 candidate paths, so a printer refusing FTPS
  522. got ~110 sockets opened and abandoned in a couple of minutes, and one
  523. support bundle recorded 1813 of them in a day (#2780). If the refusal
  524. is the printer running out of connection slots -- which fits the
  525. evidence better than a wedged service, since a single manual connect
  526. to the same printer succeeds -- then abandoning sockets is not just
  527. untidy, it is what keeps the printer refusing.
  528. Uses ``close()`` rather than ``quit()``: QUIT is a command, and there
  529. is no working control channel to send it on.
  530. """
  531. ftp = self._ftp
  532. self._ftp = None
  533. if ftp is None:
  534. return
  535. try:
  536. ftp.close()
  537. except (OSError, ftplib.Error, EOFError):
  538. pass # Best-effort; the socket may already be gone
  539. def disconnect(self):
  540. """Disconnect from the FTP server."""
  541. if self._ftp:
  542. try:
  543. self._ftp.quit()
  544. except (OSError, ftplib.Error, EOFError):
  545. # ``quit()`` sends QUIT and only then closes; when the send
  546. # raises, ftplib never reaches its own close and the socket
  547. # stays open. Close it here rather than leaving it to the GC.
  548. self._abandon_connection()
  549. self._ftp = None
  550. def list_files(self, path: str = "/", *, raise_on_error: bool = False) -> list[dict]:
  551. """List files in a directory."""
  552. if not self._ftp:
  553. return []
  554. files = []
  555. try:
  556. self._ftp.cwd(path)
  557. items = []
  558. self._ftp.retrlines("LIST", items.append)
  559. for item in items:
  560. parts = item.split()
  561. if len(parts) >= 9:
  562. name = " ".join(parts[8:])
  563. is_dir = item.startswith("d")
  564. size = int(parts[4]) if not is_dir else 0
  565. # Parse modification time from FTP listing
  566. # Format: "Nov 30 10:15" or "Nov 30 2024"
  567. mtime = None
  568. try:
  569. from datetime import datetime
  570. month = parts[5]
  571. day = parts[6]
  572. time_or_year = parts[7]
  573. # Determine if it's time (HH:MM) or year
  574. if ":" in time_or_year:
  575. # Recent file: "Nov 30 10:15" - assume current year
  576. year = datetime.now().year
  577. time_str = f"{month} {day} {year} {time_or_year}"
  578. mtime = datetime.strptime(time_str, "%b %d %Y %H:%M")
  579. # If parsed date is in the future, use last year
  580. if mtime > datetime.now():
  581. mtime = mtime.replace(year=year - 1)
  582. else:
  583. # Older file: "Nov 30 2024" - no time, just date
  584. time_str = f"{month} {day} {time_or_year}"
  585. mtime = datetime.strptime(time_str, "%b %d %Y")
  586. except (ValueError, IndexError):
  587. pass # Non-critical: mtime parsing is best-effort; file entry works without it
  588. file_entry = {
  589. "name": name,
  590. "is_directory": is_dir,
  591. "size": size,
  592. "path": f"{path.rstrip('/')}/{name}",
  593. }
  594. if mtime:
  595. file_entry["mtime"] = mtime
  596. files.append(file_entry)
  597. logger.debug("Listed %s files in %s", len(files), path)
  598. except (OSError, ftplib.Error) as e:
  599. logger.info("FTP list_files failed for %s: %s", path, e)
  600. if raise_on_error:
  601. raise
  602. return files
  603. def download_file(self, remote_path: str, expected_size: int | None = None) -> bytes | None:
  604. """Download a file from the printer.
  605. ``expected_size`` is the byte count the directory listing reported for
  606. this file. Pass it whenever a short read must not be mistaken for a
  607. successful download: an FTPS data connection that closes early does
  608. not always raise, so ``retrbinary`` can hand back a partial buffer that
  609. looks like a perfectly good file to everything downstream. That is
  610. tolerable when the printer keeps its copy, and not tolerable when the
  611. caller goes on to delete the source (#2704).
  612. A zero-byte result is always treated as a failure, matching
  613. :meth:`download_to_file` — no caller has a use for an empty file.
  614. """
  615. if not self._ftp:
  616. return None
  617. try:
  618. buffer = BytesIO()
  619. self._ftp.retrbinary(f"RETR {remote_path}", buffer.write)
  620. data = buffer.getvalue()
  621. except (OSError, ftplib.Error):
  622. return None
  623. if not data:
  624. logger.warning("FTP download returned 0 bytes for %s", remote_path)
  625. return None
  626. if expected_size is not None and len(data) != expected_size:
  627. logger.warning(
  628. "FTP download of %s is short: got %s bytes, listing reported %s — treating as failed",
  629. remote_path,
  630. len(data),
  631. expected_size,
  632. )
  633. return None
  634. return data
  635. def download_to_file(
  636. self,
  637. remote_path: str,
  638. local_path: Path,
  639. *,
  640. expected_size: int | None = None,
  641. max_bytes: int | None = None,
  642. cancel_event: threading.Event | None = None,
  643. min_free_bytes: int | None = None,
  644. ) -> bool:
  645. """Download a file with cooperative cancellation and byte bounds."""
  646. if not self._ftp:
  647. logger.warning("download_to_file called but FTP not connected")
  648. return False
  649. try:
  650. local_path.parent.mkdir(parents=True, exist_ok=True)
  651. # SIZE is the printer's own current view of the file and is more
  652. # trustworthy than a browser round-tripped listing hint. Some
  653. # firmware does not implement SIZE, so retain expected_size as a
  654. # compatibility fallback when the command is unavailable.
  655. try:
  656. server_size = self._ftp.size(remote_path)
  657. except (OSError, ftplib.Error):
  658. server_size = None
  659. authoritative_size = server_size if server_size is not None and server_size >= 0 else expected_size
  660. if max_bytes is not None and authoritative_size is not None and authoritative_size > max_bytes:
  661. raise DownloadLimitExceeded(remote_path)
  662. if min_free_bytes is not None and authoritative_size is not None:
  663. if shutil.disk_usage(local_path.parent).free < min_free_bytes + authoritative_size:
  664. raise DownloadInsufficientSpace(remote_path)
  665. with open(local_path, "wb") as f:
  666. written = 0
  667. # retrbinary hands over 8 KiB at a time, so checking the volume
  668. # on every callback is ~30k statvfs calls per 250 MB chunk for a
  669. # reserve measured in hundreds of megabytes. Sampling every few
  670. # MB cannot overshoot it by more than one interval.
  671. free_check_interval = 8 * 1024 * 1024
  672. next_free_check = 0
  673. def _write(chunk: bytes) -> None:
  674. nonlocal written, next_free_check
  675. if cancel_event is not None and cancel_event.is_set():
  676. raise DownloadCancelled(remote_path)
  677. if max_bytes is not None and written + len(chunk) > max_bytes:
  678. raise DownloadLimitExceeded(remote_path)
  679. if min_free_bytes is not None and written >= next_free_check:
  680. next_free_check = written + free_check_interval
  681. if shutil.disk_usage(local_path.parent).free < min_free_bytes + free_check_interval:
  682. raise DownloadInsufficientSpace(remote_path)
  683. f.write(chunk)
  684. written += len(chunk)
  685. self._ftp.retrbinary(f"RETR {remote_path}", _write)
  686. f.flush()
  687. os.fsync(f.fileno())
  688. file_size = local_path.stat().st_size if local_path.exists() else 0
  689. if file_size == 0:
  690. logger.warning("FTP download returned 0 bytes for %s", remote_path)
  691. if local_path.exists():
  692. local_path.unlink()
  693. return False
  694. if authoritative_size is not None and file_size != authoritative_size:
  695. logger.warning(
  696. "FTP download of %s is short: got %s bytes, listing reported %s — treating as failed",
  697. remote_path,
  698. file_size,
  699. authoritative_size,
  700. )
  701. local_path.unlink(missing_ok=True)
  702. return False
  703. logger.info("Successfully downloaded %s to %s (%s bytes)", remote_path, local_path, file_size)
  704. return True
  705. except (OSError, ftplib.Error, DownloadCancelled, DownloadLimitExceeded, DownloadInsufficientSpace) as e:
  706. # Clean up partial file if it exists
  707. if local_path.exists():
  708. try:
  709. local_path.unlink()
  710. except OSError:
  711. pass # Best-effort partial file cleanup; not critical if removal fails
  712. # 550 means the file is not at this path. Surface as a sentinel so
  713. # with_ftp_retry can abandon this path immediately and the caller
  714. # can advance to the next candidate instead of retrying 11× at
  715. # 30s intervals (the pattern that cost #972's reporter ~48min).
  716. if isinstance(e, (DownloadCancelled, DownloadLimitExceeded, DownloadInsufficientSpace)):
  717. raise
  718. if isinstance(e, ftplib.error_perm) and str(e).startswith("550"):
  719. logger.info("FTP download failed for %s: %s (not on printer)", remote_path, e)
  720. raise FileNotOnPrinterError(f"{remote_path}: {e}") from e
  721. # Log at INFO level so we can see failures in normal logs
  722. logger.info("FTP download failed for %s: %s", remote_path, e)
  723. return False
  724. def diagnose_storage(self) -> dict:
  725. """Run storage diagnostics and return results. For debugging upload issues."""
  726. results = {
  727. "connected": self._ftp is not None,
  728. "can_list_root": False,
  729. "root_files": [],
  730. "can_list_cache": False,
  731. "storage_info": None,
  732. "pwd": None,
  733. "errors": [],
  734. }
  735. if not self._ftp:
  736. results["errors"].append("FTP not connected")
  737. return results
  738. # Try to get current directory
  739. try:
  740. results["pwd"] = self._ftp.pwd()
  741. logger.debug("FTP current directory: %s", results["pwd"])
  742. except (OSError, ftplib.Error) as e:
  743. results["errors"].append(f"PWD failed: {e}")
  744. logger.debug("FTP PWD failed: %s", e)
  745. # Try to list root directory
  746. try:
  747. self._ftp.cwd("/")
  748. items = []
  749. self._ftp.retrlines("LIST", items.append)
  750. results["can_list_root"] = True
  751. results["root_files"] = items[:10] # First 10 entries
  752. logger.debug("FTP root listing (%s items): %s", len(items), items[:5])
  753. except (OSError, ftplib.Error) as e:
  754. results["errors"].append(f"LIST / failed: {e}")
  755. logger.debug("FTP LIST / failed: %s", e)
  756. # Try to list /cache (should exist on all printers)
  757. try:
  758. self._ftp.cwd("/cache")
  759. items = []
  760. self._ftp.retrlines("LIST", items.append)
  761. results["can_list_cache"] = True
  762. logger.debug("FTP /cache listing: %s items", len(items))
  763. except (OSError, ftplib.Error) as e:
  764. results["errors"].append(f"LIST /cache failed: {e}")
  765. logger.debug("FTP LIST /cache failed: %s", e)
  766. # Try to get storage info
  767. try:
  768. results["storage_info"] = self.get_storage_info()
  769. logger.debug("FTP storage info: %s", results["storage_info"])
  770. except (OSError, ftplib.Error) as e:
  771. results["errors"].append(f"Storage info failed: {e}")
  772. return results
  773. def upload_file(
  774. self,
  775. local_path: Path,
  776. remote_path: str,
  777. progress_callback: Callable[[int, int], None] | None = None,
  778. ) -> bool:
  779. """Upload a file to the printer with optional progress callback."""
  780. self.last_failure = None
  781. if not self._ftp:
  782. logger.warning("upload_file: FTP not connected")
  783. self.last_failure = FtpFailure(FtpFailureKind.UNKNOWN, "no FTP connection")
  784. return False
  785. try:
  786. file_size = local_path.stat().st_size if local_path.exists() else 0
  787. logger.info("FTP uploading %s (%s bytes) to %s", local_path, file_size, remote_path)
  788. uploaded = 0
  789. callback_exception: Exception | None = None
  790. # Use manual transfer instead of storbinary() for A1 compatibility
  791. # A1 printers have issues with storbinary's voidresp() hanging after transfer
  792. with open(local_path, "rb") as f:
  793. logger.debug("FTP STOR command starting for %s", remote_path)
  794. t0 = time.monotonic()
  795. conn = self._ftp.transfercmd(f"STOR {remote_path}")
  796. logger.info(
  797. "FTP data channel ready in %.1fs (PASV + TLS handshake)",
  798. time.monotonic() - t0,
  799. )
  800. # Set explicit socket options for reliable transfer
  801. conn.setblocking(True)
  802. conn.settimeout(self.timeout)
  803. try:
  804. while True:
  805. chunk = f.read(self.CHUNK_SIZE)
  806. if not chunk:
  807. logger.debug("FTP upload: final chunk reached")
  808. break
  809. conn.sendall(chunk)
  810. uploaded += len(chunk)
  811. logger.debug("FTP upload progress: %s/%s bytes", uploaded, file_size)
  812. if progress_callback:
  813. try:
  814. progress_callback(uploaded, file_size)
  815. except Exception as e:
  816. callback_exception = e
  817. logger.info(
  818. "FTP upload callback requested stop for %s at %s/%s bytes: %s",
  819. remote_path,
  820. uploaded,
  821. file_size,
  822. e,
  823. )
  824. break
  825. except OSError as e:
  826. logger.error("FTP connection lost during upload: %s", e)
  827. raise
  828. finally:
  829. try:
  830. conn.close()
  831. except OSError:
  832. pass
  833. # Wait for the server's 226 "Transfer complete" response to confirm
  834. # the file has been flushed to the SD card. Without this, the printer
  835. # may try to read an incomplete file when the print command is sent,
  836. # causing 0500-C010 "MicroSD Card read/write exception" errors.
  837. # See: https://bugs.python.org/issue25458 (ftplib response desync)
  838. try:
  839. old_timeout = self._ftp.sock.gettimeout()
  840. # Use a generous timeout — H2D printers can take 30+ seconds
  841. # to send the 226 after the data channel closes.
  842. self._ftp.sock.settimeout(max(self.timeout, 60))
  843. try:
  844. resp = self._ftp.voidresp()
  845. logger.info("FTP STOR confirmed for %s: %s", remote_path, resp.strip())
  846. finally:
  847. self._ftp.sock.settimeout(old_timeout)
  848. except ftplib.Error as e:
  849. # Some P2S firmware revisions return ftplib.Error (e.g. 426
  850. # "Failure reading network stream") on voidresp() even when
  851. # the file landed fully on the SD card — the TLS data
  852. # channel close races the 226 confirmation (#1417 follow-up).
  853. # Verify via SIZE: if the server-side file size matches what
  854. # we just uploaded, the file is intact and we proceed with
  855. # a warning. If not — or SIZE itself fails — the transfer
  856. # was genuinely truncated and we must fail so the print
  857. # command doesn't go out for a partial 3MF (the original
  858. # reason this catch was tightened in the previous round).
  859. try:
  860. server_size = self._ftp.size(remote_path)
  861. except (OSError, ftplib.Error) as size_err:
  862. logger.debug("Post-error SIZE check failed: %s", size_err)
  863. server_size = None
  864. if server_size is not None and server_size == file_size:
  865. logger.warning(
  866. "FTP STOR returned %s for %s but file is intact on the "
  867. "printer (%s bytes match) — proceeding: %s",
  868. type(e).__name__,
  869. remote_path,
  870. file_size,
  871. e,
  872. )
  873. else:
  874. logger.error(
  875. "FTP STOR rejected by printer for %s: %s (%s); server size=%s expected=%s",
  876. remote_path,
  877. e,
  878. type(e).__name__,
  879. server_size,
  880. file_size,
  881. )
  882. raise
  883. except Exception as e:
  884. # Timeout or socket-level error reading 226 — the data was sent
  885. # on our side and the printer may still have written the file.
  886. # H2D can take 30+ seconds to send 226 after the data channel
  887. # closes, so we proceed with a warning rather than failing here.
  888. logger.warning(
  889. "FTP STOR confirmation not received for %s (proceeding): %s (%s)",
  890. remote_path,
  891. e,
  892. type(e).__name__,
  893. )
  894. if callback_exception is not None:
  895. cleanup_result: DeleteResult = DeleteResult.FAILED
  896. try:
  897. cleanup_result = self.delete_file(remote_path)
  898. except Exception as cleanup_error:
  899. logger.warning("FTP cancel cleanup failed for %s: %s", remote_path, cleanup_error)
  900. # NOT_FOUND is success here — the partial file is gone (printer
  901. # may have already swept on cancel), which is the goal.
  902. if cleanup_result in (DeleteResult.DELETED, DeleteResult.NOT_FOUND):
  903. logger.info("FTP cancel cleanup succeeded for %s (%s)", remote_path, cleanup_result.value)
  904. raise callback_exception
  905. raise RuntimeError(
  906. f"Upload cancelled but failed to remove partial file {remote_path} from printer"
  907. ) from callback_exception
  908. elapsed = time.monotonic() - t0
  909. speed_kbs = (file_size / 1024) / elapsed if elapsed > 0 else 0
  910. logger.info(
  911. "FTP upload complete: %s (%s bytes in %.1fs, %.0f KB/s)",
  912. remote_path,
  913. file_size,
  914. elapsed,
  915. speed_kbs,
  916. )
  917. return True
  918. except ftplib.error_perm as e:
  919. # Permanent FTP error (4xx/5xx response)
  920. error_code = str(e)[:3] if str(e) else "unknown"
  921. logger.error("FTP upload failed for %s: %s (error code: %s)", remote_path, e, error_code)
  922. # 553 and 552 are the printer telling us about its own storage --
  923. # the one case where advice about the card is worth giving, and
  924. # the case the dispatch's blanket SD-card message was written for
  925. # before it was applied to every failure alike (#2899).
  926. if error_code == "553":
  927. logger.error(
  928. "FTP 553 error - Could not create file. Possible causes: "
  929. "1) No SD card inserted, 2) SD card full, 3) SD card not formatted correctly (needs FAT32/exFAT), "
  930. "4) Printer busy/not ready, 5) File path issue"
  931. )
  932. kind = FtpFailureKind.STORAGE
  933. elif error_code == "550":
  934. logger.error("FTP 550 error - File/directory not found or permission denied")
  935. kind = FtpFailureKind.NOT_FOUND
  936. elif error_code == "552":
  937. logger.error("FTP 552 error - Storage quota exceeded (SD card full?)")
  938. kind = FtpFailureKind.STORAGE
  939. else:
  940. kind = FtpFailureKind.UNKNOWN
  941. self.last_failure = FtpFailure(kind, str(e), _ftp_reply_code(e))
  942. return False
  943. except (OSError, ftplib.Error) as e:
  944. logger.error("FTP upload failed for %s: %s (type: %s)", remote_path, e, type(e).__name__)
  945. self.last_failure = FtpFailure(FtpFailureKind.NETWORK, str(e), _ftp_reply_code(e))
  946. return False
  947. def upload_bytes(self, data: bytes, remote_path: str) -> bool:
  948. """Upload bytes to the printer."""
  949. if not self._ftp:
  950. return False
  951. try:
  952. # Use manual transfer instead of storbinary() for A1 compatibility
  953. conn = self._ftp.transfercmd(f"STOR {remote_path}")
  954. conn.setblocking(True)
  955. conn.settimeout(self.timeout)
  956. try:
  957. # Send data in chunks
  958. offset = 0
  959. while offset < len(data):
  960. chunk = data[offset : offset + self.CHUNK_SIZE]
  961. conn.sendall(chunk)
  962. offset += len(chunk)
  963. except OSError as e:
  964. logger.error("FTP connection lost during upload_bytes: %s", e)
  965. raise
  966. finally:
  967. try:
  968. conn.close()
  969. except OSError:
  970. pass
  971. # Wait for 226 confirmation (see upload_file for rationale).
  972. # ftplib.Error subclasses (e.g. 426 error_temp) mean the server
  973. # rejected the transfer and the file is partial — fail. Other
  974. # exceptions (timeout, socket-level) are tolerated as in upload_file.
  975. try:
  976. old_timeout = self._ftp.sock.gettimeout()
  977. self._ftp.sock.settimeout(max(self.timeout, 60))
  978. try:
  979. self._ftp.voidresp()
  980. finally:
  981. self._ftp.sock.settimeout(old_timeout)
  982. except ftplib.Error as e:
  983. # Same SIZE-verify path as upload_file (#1417 follow-up):
  984. # tolerate a transient 426 if the bytes are actually on the
  985. # printer, fail loudly if they aren't.
  986. try:
  987. server_size = self._ftp.size(remote_path)
  988. except (OSError, ftplib.Error) as size_err:
  989. logger.debug("Post-error SIZE check failed: %s", size_err)
  990. server_size = None
  991. if server_size is not None and server_size == len(data):
  992. logger.warning(
  993. "FTP STOR returned %s for %s but file is intact on the "
  994. "printer (%s bytes match) — proceeding: %s",
  995. type(e).__name__,
  996. remote_path,
  997. len(data),
  998. e,
  999. )
  1000. else:
  1001. logger.error(
  1002. "FTP STOR rejected by printer for %s: %s (%s); server size=%s expected=%s",
  1003. remote_path,
  1004. e,
  1005. type(e).__name__,
  1006. server_size,
  1007. len(data),
  1008. )
  1009. return False
  1010. except Exception:
  1011. pass # Timeout / socket-level — proceed, data was sent.
  1012. return True
  1013. except (OSError, ftplib.Error):
  1014. return False
  1015. def delete_file(self, remote_path: str) -> DeleteResult:
  1016. """Delete a file from the printer.
  1017. Returns :class:`DeleteResult` distinguishing the file-not-found case
  1018. (550) from network / auth / transient FTP failure. Callers that just
  1019. want "did it work" should check ``result == DeleteResult.DELETED``.
  1020. """
  1021. if not self._ftp:
  1022. return DeleteResult.FAILED
  1023. try:
  1024. self._ftp.delete(remote_path)
  1025. return DeleteResult.DELETED
  1026. except ftplib.error_perm as e:
  1027. if str(e).startswith("550"):
  1028. logger.debug("FTP delete: %s not on printer (550)", remote_path)
  1029. return DeleteResult.NOT_FOUND
  1030. logger.warning("Failed to delete %s: %s", remote_path, e)
  1031. return DeleteResult.FAILED
  1032. except (OSError, ftplib.Error) as e:
  1033. logger.warning("Failed to delete %s: %s", remote_path, e)
  1034. return DeleteResult.FAILED
  1035. def get_file_size(self, remote_path: str) -> int | None:
  1036. """Get the size of a file."""
  1037. if not self._ftp:
  1038. return None
  1039. try:
  1040. return self._ftp.size(remote_path)
  1041. except (OSError, ftplib.Error):
  1042. return None
  1043. def get_storage_info(self) -> dict | None:
  1044. """Get storage information from the printer."""
  1045. if not self._ftp:
  1046. return None
  1047. result = {}
  1048. # Try AVBL command (available space) - some FTP servers support this
  1049. try:
  1050. response = self._ftp.sendcmd("AVBL")
  1051. logger.debug("AVBL response: %s", response)
  1052. # Response format: "213 <bytes available>"
  1053. if response.startswith("213"):
  1054. parts = response.split()
  1055. if len(parts) >= 2:
  1056. result["free_bytes"] = int(parts[1])
  1057. except (OSError, ftplib.Error) as e:
  1058. logger.debug("AVBL command not supported: %s", e)
  1059. # Try STAT command as fallback
  1060. try:
  1061. response = self._ftp.sendcmd("STAT")
  1062. logger.debug("STAT response: %s", response)
  1063. except (OSError, ftplib.Error):
  1064. pass # Both AVBL and STAT unsupported; storage info will rely on directory scan
  1065. # Calculate used space by listing root directories
  1066. try:
  1067. total_used = 0
  1068. dirs_to_scan = ["/cache", "/timelapse", "/model", "/data", "/data/Metadata", "/"]
  1069. for dir_path in dirs_to_scan:
  1070. try:
  1071. self._ftp.cwd(dir_path)
  1072. items = []
  1073. self._ftp.retrlines("LIST", items.append)
  1074. for item in items:
  1075. parts = item.split()
  1076. if len(parts) >= 5 and not item.startswith("d"):
  1077. try:
  1078. total_used += int(parts[4])
  1079. except ValueError:
  1080. pass # Skip entries with non-numeric size fields
  1081. except (OSError, ftplib.Error):
  1082. pass # Directory may not exist on this printer model; skip it
  1083. result["used_bytes"] = total_used
  1084. except (OSError, ftplib.Error):
  1085. pass # Storage scan failed; return whatever info was collected above
  1086. return result if result else None
  1087. def describe_upload_failure(failure: FtpFailure | None) -> str:
  1088. """One sentence for the operator, chosen from what actually went wrong.
  1089. Every upload failure used to get the same one: "Failed to upload file to
  1090. printer. Check if SD card is inserted and properly formatted
  1091. (FAT32/exFAT)." #2899's reporter got that after a TLS handshake failure and
  1092. restarted the printer, which could not have helped -- the handshake never
  1093. reached the printer's filesystem, and the state that produced it lives in
  1094. Bambuddy's own memory. #2780 had already removed advice from this failure's
  1095. *log* line for the same reason; it survived in the string people read.
  1096. So the card is named only where the printer itself raised storage, and
  1097. where nothing here can say more, this says so and points at the log rather
  1098. than picking a plausible cause. A wrong instruction costs more than a
  1099. vague one: it sends someone to work on hardware that is fine.
  1100. """
  1101. if failure is None:
  1102. return (
  1103. "Could not upload the file to the printer. See the server log for the reason — "
  1104. "it records what the printer's file service said."
  1105. )
  1106. if failure.kind is FtpFailureKind.STORAGE:
  1107. return (
  1108. f"The printer refused to store the file ({failure.code or 'storage error'}). Check that its SD card "
  1109. "is inserted, has space free, and is formatted FAT32 or exFAT."
  1110. )
  1111. if failure.kind is FtpFailureKind.HANDSHAKE:
  1112. return (
  1113. "The printer's file service answered, but not with TLS, so no file could be sent to it. "
  1114. "Its SD card is not involved. This usually clears by itself; if it does not, power-cycling "
  1115. "the printer has not been found to help either, so please report it."
  1116. )
  1117. if failure.kind is FtpFailureKind.COOLOFF:
  1118. return (
  1119. "Bambuddy is holding off from this printer's file service after a recent failed TLS handshake, "
  1120. "so the file was not sent. This clears on its own within a few minutes."
  1121. )
  1122. if failure.kind is FtpFailureKind.AUTH:
  1123. return (
  1124. "The printer refused the file transfer connection. If the printer's access code changed, "
  1125. "update it on Bambuddy's Printers page."
  1126. )
  1127. if failure.kind is FtpFailureKind.TIMEOUT:
  1128. return (
  1129. "The printer's file service did not respond in time, so the file was not sent. "
  1130. "Check that the printer is on the network and reachable."
  1131. )
  1132. if failure.kind is FtpFailureKind.NOT_FOUND:
  1133. return (
  1134. "The printer rejected the upload path (550). See the server log — this is a Bambuddy-side "
  1135. "problem, not something to fix on the printer."
  1136. )
  1137. return (
  1138. "Could not upload the file to the printer. See the server log for the reason — "
  1139. "it records what the printer's file service said."
  1140. )
  1141. def ftps_handshake_blocked(ip_address: str) -> bool:
  1142. """True while this printer's FTPS handshake cool-off is still running.
  1143. Callers that walk a list of candidate paths use this to give up on the
  1144. remaining candidates: the failure is at the transport, below any path, so
  1145. every one of them would fail identically (#2780).
  1146. """
  1147. return BambuFTPClient.handshake_blocked(ip_address)
  1148. # Shared 3MF download cache (#972).
  1149. #
  1150. # Both the cover thumbnail endpoint (api/routes/printers.py) and the archive
  1151. # metadata flow (main.py) fetch the same 3MF file over FTP during a print.
  1152. # On slow / contended links (A1 Wi-Fi, large files) the duplicate transfers
  1153. # compete for the printer's single FTP socket and trigger 425 "can't open
  1154. # data channel" errors, feeding back into cause-2's retry storm.
  1155. #
  1156. # This cache stores the local path of a successfully-downloaded 3MF keyed
  1157. # by (printer_id, normalized_name). Whichever flow downloads first populates
  1158. # the cache; the other flow reuses the file read-only. Evicted on print
  1159. # completion so a later print with the same name re-downloads fresh bytes.
  1160. _threemf_path_cache: dict[tuple[int, str], Path] = {}
  1161. def normalize_3mf_name(name: str) -> str:
  1162. """Collapse various 3MF filename variants to a cache key.
  1163. Bambu tooling produces names as bare subtask ("Part"), with .3mf, with
  1164. .gcode.3mf, or (Studio-normalized) with spaces → underscores. All of
  1165. these refer to the same print job on the same printer, so they must
  1166. hash to the same cache key.
  1167. """
  1168. # Lowercase first so .3MF / .GCODE.3MF variants strip cleanly — a
  1169. # real-world case since Windows-side tooling sometimes uppercases
  1170. # extensions.
  1171. cleaned = name.strip().lower().replace(".gcode.3mf", "").replace(".gcode", "").replace(".3mf", "")
  1172. return cleaned.replace(" ", "_")
  1173. def cache_3mf_download(printer_id: int, name: str, local_path: Path) -> None:
  1174. """Record a successfully-downloaded 3MF so a sibling flow can reuse it."""
  1175. _threemf_path_cache[(printer_id, normalize_3mf_name(name))] = local_path
  1176. def get_cached_3mf(printer_id: int, name: str) -> Path | None:
  1177. """Return a cached 3MF path for this printer/name if the file still exists."""
  1178. key = (printer_id, normalize_3mf_name(name))
  1179. cached = _threemf_path_cache.get(key)
  1180. if cached and cached.exists() and cached.stat().st_size > 0:
  1181. return cached
  1182. # Evict dead entry — the file was cleaned up (temp dir clean, manual
  1183. # deletion, restart) so the cache value is no longer usable.
  1184. if cached:
  1185. _threemf_path_cache.pop(key, None)
  1186. return None
  1187. def clear_3mf_cache(printer_id: int | None = None, delete_files: bool = True) -> None:
  1188. """Drop cache entries for one printer (or all with None).
  1189. When ``delete_files`` is True (default) the on-disk 3MF is removed as well
  1190. — called from on_print_complete so temp files don't accumulate across
  1191. prints. Tests that want to inspect the cache contents disable this.
  1192. Only paths inside ``archive_dir/temp`` are unlinked. The dispatch sites
  1193. added in #1166 also cache the live archive copy and library file bytes
  1194. so /cover can skip FTP — those are *user data*, never the cache's to
  1195. delete. Pre-fix this branch silently removed archive 3mfs on every print
  1196. completion (#1212 + private reports of "file disappeared overnight").
  1197. """
  1198. from backend.app.core.config import settings as _config_settings
  1199. temp_root = _config_settings.archive_dir / "temp"
  1200. def _is_temp_path(path: Path) -> bool:
  1201. try:
  1202. return path.is_relative_to(temp_root)
  1203. except (OSError, ValueError):
  1204. return False
  1205. def _maybe_unlink(path: Path) -> None:
  1206. if not delete_files or not path.exists():
  1207. return
  1208. if not _is_temp_path(path):
  1209. return
  1210. try:
  1211. path.unlink()
  1212. except OSError as exc:
  1213. logger.debug("3MF cache cleanup skipped %s: %s", path, exc)
  1214. if printer_id is None:
  1215. for path in list(_threemf_path_cache.values()):
  1216. _maybe_unlink(path)
  1217. _threemf_path_cache.clear()
  1218. return
  1219. for key in [k for k in _threemf_path_cache if k[0] == printer_id]:
  1220. _maybe_unlink(_threemf_path_cache[key])
  1221. _threemf_path_cache.pop(key, None)
  1222. async def download_file_async(
  1223. ip_address: str,
  1224. access_code: str,
  1225. remote_path: str,
  1226. local_path: Path,
  1227. timeout: float = 60.0,
  1228. socket_timeout: float | None = None,
  1229. printer_model: str | None = None,
  1230. expected_size: int | None = None,
  1231. max_bytes: int | None = None,
  1232. cancel_event: threading.Event | None = None,
  1233. min_free_bytes: int | None = None,
  1234. ) -> bool:
  1235. """Async wrapper for downloading a file with timeout.
  1236. For A1/A1 Mini printers, automatically tries prot_p first, then falls back
  1237. to prot_c if the download fails. The working mode is cached for future operations.
  1238. ``timeout`` bounds the wait for a *result*, not the call: when it expires
  1239. this waits for the FTP worker thread to unwind before returning, because
  1240. the thread owns ``local_path`` until it does and a caller that came back
  1241. early would delete a file still being written. That wait is bounded by the
  1242. socket timeout, so pass ``socket_timeout`` on any path that must not block
  1243. indefinitely -- every caller here does.
  1244. Args:
  1245. ip_address: Printer IP address
  1246. access_code: Printer access code
  1247. remote_path: Remote file path on printer
  1248. local_path: Local path to save file
  1249. timeout: Overall operation timeout (asyncio)
  1250. socket_timeout: FTP socket timeout for slow connections (e.g., A1 printers)
  1251. printer_model: Printer model for A1-specific workarounds
  1252. """
  1253. loop = asyncio.get_event_loop()
  1254. is_a1 = printer_model in BambuFTPClient.A1_MODELS if printer_model else False
  1255. # Per-attempt completion state: asyncio.wait_for cannot cancel
  1256. # run_in_executor threads, so on timeout the executor may still complete
  1257. # the download after we stop waiting. The thread flips `success` to True
  1258. # ONLY after the file is fully written — a post-timeout check lets us
  1259. # salvage the download without mistaking an in-progress partial write
  1260. # for a completed one. Each attempt gets its own dict and event so a
  1261. # zombie from an earlier attempt can't flip the flag for a later one.
  1262. # The event is set in `_download`'s finally block so the post-timeout
  1263. # path can wait for genuine thread completion instead of a fixed sleep.
  1264. class _CombinedCancelEvent:
  1265. def __init__(self, attempt_event: threading.Event):
  1266. self._attempt_event = attempt_event
  1267. def is_set(self) -> bool:
  1268. return self._attempt_event.is_set() or (cancel_event is not None and cancel_event.is_set())
  1269. def _download(
  1270. force_prot_c: bool,
  1271. completion: dict,
  1272. done: threading.Event,
  1273. attempt_cancel: threading.Event,
  1274. ) -> bool:
  1275. mode_str = "prot_c" if force_prot_c else "prot_p"
  1276. try:
  1277. combined_cancel = _CombinedCancelEvent(attempt_cancel)
  1278. if combined_cancel.is_set():
  1279. raise DownloadCancelled(remote_path)
  1280. client = BambuFTPClient(
  1281. ip_address,
  1282. access_code,
  1283. timeout=socket_timeout,
  1284. printer_model=printer_model,
  1285. force_prot_c=force_prot_c,
  1286. )
  1287. if client.connect():
  1288. try:
  1289. result = client.download_to_file(
  1290. remote_path,
  1291. local_path,
  1292. expected_size=expected_size,
  1293. max_bytes=max_bytes,
  1294. cancel_event=combined_cancel,
  1295. min_free_bytes=min_free_bytes,
  1296. )
  1297. if result:
  1298. BambuFTPClient.cache_mode(ip_address, mode_str)
  1299. completion["success"] = True
  1300. return result
  1301. finally:
  1302. client.disconnect()
  1303. return False
  1304. finally:
  1305. done.set()
  1306. async def _run(force_prot_c: bool) -> bool:
  1307. completion = {"success": False}
  1308. done = threading.Event()
  1309. attempt_cancel = threading.Event()
  1310. worker = loop.run_in_executor(_ftp_executor, _download, force_prot_c, completion, done, attempt_cancel)
  1311. try:
  1312. return await asyncio.wait_for(asyncio.shield(worker), timeout=timeout)
  1313. except asyncio.CancelledError:
  1314. # Cancelling an asyncio Future cannot stop its executor thread. Set
  1315. # the callback-visible flag and do not let the caller unlink the
  1316. # staging file until the worker has genuinely unwound.
  1317. attempt_cancel.set()
  1318. try:
  1319. await asyncio.shield(worker)
  1320. except (DownloadCancelled, OSError, ftplib.Error):
  1321. pass
  1322. raise
  1323. except TimeoutError:
  1324. # Slow WiFi links commonly overshoot ftp_timeout by 10–30 s without
  1325. # actually being stuck, so starting attempt 2 now would just contend
  1326. # with the still-progressing RETR on attempt 1 and produce the
  1327. # zombie-write race reported in #1014 (file landed on disk minutes
  1328. # after the retry loop had already given up). Wait for the worker
  1329. # thread to genuinely finish — capped at 30 s so a truly stuck
  1330. # connection can't stall a whole attempt indefinitely, with a 0.5 s
  1331. # floor so artificially small test timeouts still give zombies a
  1332. # realistic window to finish.
  1333. grace = max(min(timeout, 30.0), 0.5)
  1334. # Deliberately the DEFAULT executor, not `_ftp_executor`: this thread
  1335. # blocks waiting on `_download`, which is itself an `_ftp_executor`
  1336. # worker. Parking waiters in the same bounded pool as the workers they
  1337. # wait for is how you build a deadlock — with enough concurrent
  1338. # timeouts the waiters would occupy every slot and the downloads they
  1339. # are waiting for could never be scheduled.
  1340. attempt_cancel.set()
  1341. await loop.run_in_executor(None, done.wait, grace)
  1342. # Wait for the thread either way. If the grace period was enough it
  1343. # returns at once; if it was not, the blocking socket still has to
  1344. # reach its own timeout, and returning before it does would let the
  1345. # caller unlink a file the executor is still writing.
  1346. try:
  1347. await asyncio.shield(worker)
  1348. except (DownloadCancelled, OSError, ftplib.Error):
  1349. pass
  1350. if completion["success"] and local_path.exists() and local_path.stat().st_size > 0:
  1351. logger.info(
  1352. "FTP download wait_for timed out after %ss for %s, but thread completed within %ss grace (%s bytes) — salvaging",
  1353. timeout,
  1354. remote_path,
  1355. grace,
  1356. local_path.stat().st_size,
  1357. )
  1358. return True
  1359. logger.warning(
  1360. "FTP download timed out after %ss (plus %ss grace) for %s",
  1361. timeout,
  1362. grace,
  1363. remote_path,
  1364. )
  1365. return False
  1366. # Check if we have a cached mode for this printer
  1367. cached_mode = BambuFTPClient._mode_cache.get(ip_address)
  1368. if cached_mode:
  1369. force_prot_c = cached_mode == "prot_c"
  1370. return await _run(force_prot_c)
  1371. # No cached mode - try prot_p first
  1372. if await _run(False):
  1373. return True
  1374. # Download failed - for A1 models, try prot_c fallback
  1375. if is_a1:
  1376. logger.info("FTP download failed with prot_p for A1 model, trying prot_c fallback...")
  1377. return await _run(True)
  1378. return False
  1379. async def download_file_try_paths_async(
  1380. ip_address: str,
  1381. access_code: str,
  1382. remote_paths: list[str],
  1383. local_path: Path,
  1384. socket_timeout: float | None = None,
  1385. printer_model: str | None = None,
  1386. timeout: float = 90.0,
  1387. ) -> str | None:
  1388. """Try downloading a file from multiple paths using a single connection.
  1389. Returns the path that served the file, or ``None``. The path rather than a
  1390. bare flag because the caller usually cannot tell afterwards which candidate
  1391. hit, and on a printer that keeps uploads around for weeks that is the
  1392. difference between a diagnosable stale-copy match and an invisible one
  1393. (#1820). Callers testing it for truth are unaffected: a served path is
  1394. always a non-empty string.
  1395. Args:
  1396. socket_timeout: FTP socket timeout for slow connections (e.g., A1 printers)
  1397. printer_model: Printer model for A1-specific workarounds
  1398. timeout: overall async cap. The per-socket timeout only bounds an
  1399. in-flight worker; it does NOT bound how long this coroutine waits
  1400. for a free slot in the fixed-size ``_ftp_executor``. On a large
  1401. farm where offline printers keep every worker busy on dead
  1402. connects, that queue wait is otherwise unbounded — and any caller
  1403. holding a DB connection while awaiting this would pin it until the
  1404. pool is exhausted (#2572). The cap converts that into a bounded
  1405. wait; the orphaned worker finishes and its result is discarded.
  1406. """
  1407. loop = asyncio.get_event_loop()
  1408. def _download():
  1409. client = BambuFTPClient(ip_address, access_code, timeout=socket_timeout, printer_model=printer_model)
  1410. if not client.connect():
  1411. return None
  1412. try:
  1413. # FileNotOnPrinterError signals "try the next path", not "give up" —
  1414. # this function's whole purpose is to walk a list of candidates
  1415. # over one connection. Only a real transport error should bubble.
  1416. for remote_path in remote_paths:
  1417. try:
  1418. if client.download_to_file(remote_path, local_path):
  1419. return remote_path
  1420. except FileNotOnPrinterError:
  1421. continue
  1422. return None
  1423. finally:
  1424. client.disconnect()
  1425. try:
  1426. return await asyncio.wait_for(loop.run_in_executor(_ftp_executor, _download), timeout=timeout)
  1427. except TimeoutError:
  1428. logger.warning("FTP download_try_paths exceeded its %ss cap for %s (#2572)", timeout, ip_address)
  1429. return None
  1430. def _upload_deadline(local_path: Path) -> float:
  1431. """Derive an upload deadline from the file size (#2529).
  1432. See ``_UPLOAD_FLOOR_BYTES_PER_SEC``. An unstat-able file falls back to the
  1433. floor timeout — ``upload_file`` will fail on the open() anyway.
  1434. """
  1435. try:
  1436. size = local_path.stat().st_size
  1437. except OSError:
  1438. return _UPLOAD_MIN_TIMEOUT
  1439. return max(_UPLOAD_MIN_TIMEOUT, size / _UPLOAD_FLOOR_BYTES_PER_SEC)
  1440. # One upload at a time per printer. Two concurrent STOR commands for the same
  1441. # remote path leave a corrupt file on the SD card, and the printer reads as
  1442. # flaky rather than busy (#2529). Held for the duration of a transfer, so a
  1443. # second dispatch to the same printer queues behind the first instead of racing
  1444. # it. Keyed per event loop: an asyncio.Lock binds to the loop that first awaits
  1445. # it, and the test suite runs each case on a fresh loop.
  1446. _upload_locks: weakref.WeakKeyDictionary[asyncio.AbstractEventLoop, dict[str, asyncio.Lock]] = (
  1447. weakref.WeakKeyDictionary()
  1448. )
  1449. def _upload_lock(loop: asyncio.AbstractEventLoop, ip_address: str) -> asyncio.Lock:
  1450. per_loop = _upload_locks.setdefault(loop, {})
  1451. lock = per_loop.get(ip_address)
  1452. if lock is None:
  1453. lock = asyncio.Lock()
  1454. per_loop[ip_address] = lock
  1455. return lock
  1456. async def upload_file_async(
  1457. ip_address: str,
  1458. access_code: str,
  1459. local_path: Path,
  1460. remote_path: str,
  1461. timeout: float | None = None,
  1462. progress_callback: Callable[[int, int], None] | None = None,
  1463. socket_timeout: float | None = None,
  1464. printer_model: str | None = None,
  1465. respect_handshake_cooloff: bool = True,
  1466. failure: FtpFailureReport | None = None,
  1467. ) -> bool:
  1468. """Async wrapper for uploading a file with timeout and progress callback.
  1469. For A1/A1 Mini printers, automatically tries prot_p first, then falls back
  1470. to prot_c if the upload fails. The working mode is cached for future uploads.
  1471. Args:
  1472. ip_address: Printer IP address
  1473. access_code: Printer access code
  1474. local_path: Local file path to upload
  1475. remote_path: Remote path on printer
  1476. timeout: Overall deadline. ``None`` (the default) derives it from the
  1477. file size — see ``_upload_deadline``. A caller that passes a number
  1478. gets exactly that, which is what the tests rely on.
  1479. progress_callback: Optional callback for progress updates
  1480. socket_timeout: FTP socket timeout for slow connections (e.g., A1 printers)
  1481. printer_model: Printer model for A1-specific workarounds
  1482. respect_handshake_cooloff: see ``BambuFTPClient.__init__``. False for a
  1483. user-initiated upload, whose attempts are bounded and were being
  1484. spent against a cool-off that outlives them (#2898).
  1485. failure: caller-owned slot filled in with why the upload failed, so the
  1486. caller can say something true about it instead of guessing (#2899).
  1487. Passed through ``with_ftp_retry`` unchanged, so it ends up holding
  1488. the last attempt's reason -- which is the one that decided the
  1489. outcome.
  1490. """
  1491. loop = asyncio.get_event_loop()
  1492. is_a1 = printer_model in BambuFTPClient.A1_MODELS if printer_model else False
  1493. deadline = _upload_deadline(local_path) if timeout is None else timeout
  1494. # Set when the deadline expires. The worker checks it once per chunk.
  1495. cancel = threading.Event()
  1496. def _guarded_progress(uploaded: int, total: int) -> None:
  1497. if cancel.is_set():
  1498. raise UploadCancelled(f"upload of {remote_path} exceeded its {deadline:.0f}s deadline")
  1499. if progress_callback:
  1500. progress_callback(uploaded, total)
  1501. def _upload(force_prot_c: bool = False) -> bool:
  1502. mode_str = "prot_c" if force_prot_c else "prot_p"
  1503. logger.info(
  1504. f"FTP connecting to {ip_address} for upload (model={printer_model}, "
  1505. f"mode={mode_str}, socket_timeout={socket_timeout}s, deadline={deadline:.0f}s)..."
  1506. )
  1507. client = BambuFTPClient(
  1508. ip_address,
  1509. access_code,
  1510. timeout=socket_timeout,
  1511. printer_model=printer_model,
  1512. force_prot_c=force_prot_c,
  1513. respect_handshake_cooloff=respect_handshake_cooloff,
  1514. )
  1515. try:
  1516. if client.connect():
  1517. logger.info("FTP connected to %s", ip_address)
  1518. try:
  1519. result = client.upload_file(local_path, remote_path, _guarded_progress)
  1520. if result:
  1521. # Cache the working mode
  1522. BambuFTPClient.cache_mode(ip_address, mode_str)
  1523. return result
  1524. finally:
  1525. client.disconnect()
  1526. logger.warning("FTP connection failed to %s", ip_address)
  1527. return False
  1528. finally:
  1529. # In a finally so a transfer that leaves by raising -- a cancelled
  1530. # upload, a re-raised STOR rejection -- still reports what the
  1531. # client recorded on its way out.
  1532. if failure is not None and client.last_failure is not None:
  1533. failure.failure = client.last_failure
  1534. async def _attempt(force_prot_c: bool) -> bool:
  1535. """Run one upload attempt, and make a timeout actually stop the transfer.
  1536. ``asyncio.wait_for`` cancels the *future*, never the executor thread
  1537. behind it. Before #2529 a slow-but-healthy upload that overran the
  1538. deadline left that thread streaming: it kept pushing bytes, kept firing
  1539. the progress callback, and the retry above put a *second* STOR of the
  1540. same file onto the same printer. The reporter's 96 MB job ran four
  1541. concurrent transfers and never landed. So on timeout we signal the
  1542. worker (it raises ``UploadCancelled`` from the progress callback, which
  1543. breaks the send loop and deletes the partial file) and wait for it to
  1544. actually go.
  1545. """
  1546. fut = loop.run_in_executor(_ftp_executor, lambda: _upload(force_prot_c))
  1547. try:
  1548. return await asyncio.wait_for(asyncio.shield(fut), timeout=deadline)
  1549. except TimeoutError:
  1550. cancel.set()
  1551. logger.warning(
  1552. "FTP upload of %s exceeded its %.0fs deadline — cancelling the transfer",
  1553. remote_path,
  1554. deadline,
  1555. )
  1556. try:
  1557. await asyncio.wait_for(asyncio.shield(fut), timeout=_UPLOAD_CANCEL_GRACE)
  1558. except UploadCancelled:
  1559. logger.info("FTP upload of %s cancelled; partial file removed from the printer", remote_path)
  1560. except TimeoutError:
  1561. # The thread is wedged somewhere that never reaches the callback
  1562. # (a blocked sendall, say). Nothing more we can do from here —
  1563. # but consume the eventual result so asyncio doesn't log the
  1564. # future's exception as unretrieved when it is garbage-collected.
  1565. logger.error(
  1566. "FTP upload thread for %s did not stop within %.0fs of the cancel signal",
  1567. remote_path,
  1568. _UPLOAD_CANCEL_GRACE,
  1569. )
  1570. fut.add_done_callback(_swallow_future_result)
  1571. except Exception as e:
  1572. logger.warning("FTP upload of %s errored while cancelling: %s", remote_path, e)
  1573. # Raise rather than return False: a deadline expiry means the link
  1574. # sustained less than the floor rate for the whole transfer, and a
  1575. # retry would only spend another full deadline finding that out
  1576. # again — with check_queue serialized, four of those block the
  1577. # entire print queue for hours. ``with_ftp_retry`` never retries it.
  1578. raise UploadCancelled(
  1579. f"Upload of {remote_path} to {ip_address} exceeded its {deadline:.0f}s deadline "
  1580. f"(link sustained less than {_UPLOAD_FLOOR_BYTES_PER_SEC // 1024} KB/s)"
  1581. ) from None
  1582. async with _upload_lock(loop, ip_address):
  1583. # Check if we have a cached mode for this printer
  1584. cached_mode = BambuFTPClient._mode_cache.get(ip_address)
  1585. if cached_mode:
  1586. # Use cached mode
  1587. return await _attempt(cached_mode == "prot_c")
  1588. # No cached mode - try prot_p first
  1589. if await _attempt(False):
  1590. return True
  1591. # Upload failed - for A1 models, try prot_c fallback
  1592. if is_a1:
  1593. logger.info("FTP upload failed with prot_p for A1 model, trying prot_c fallback...")
  1594. return await _attempt(True)
  1595. return False
  1596. def _swallow_future_result(fut: asyncio.Future) -> None:
  1597. """Retrieve a future's exception so asyncio doesn't log it as unhandled."""
  1598. if not fut.cancelled():
  1599. fut.exception()
  1600. async def list_files_async(
  1601. ip_address: str,
  1602. access_code: str,
  1603. path: str = "/",
  1604. timeout: float = 30.0,
  1605. socket_timeout: float | None = None,
  1606. printer_model: str | None = None,
  1607. ) -> list[dict]:
  1608. """Async wrapper for listing files with timeout.
  1609. Args:
  1610. socket_timeout: FTP socket timeout for slow connections (e.g., A1 printers)
  1611. printer_model: Printer model for A1-specific workarounds
  1612. """
  1613. loop = asyncio.get_event_loop()
  1614. def _list():
  1615. client = BambuFTPClient(ip_address, access_code, timeout=socket_timeout, printer_model=printer_model)
  1616. if client.connect():
  1617. try:
  1618. return client.list_files(path)
  1619. finally:
  1620. client.disconnect()
  1621. return []
  1622. try:
  1623. return await asyncio.wait_for(loop.run_in_executor(_ftp_executor, _list), timeout=timeout)
  1624. except TimeoutError:
  1625. logger.warning("FTP list_files timed out after %ss for %s", timeout, path)
  1626. return []
  1627. async def list_files_result_async(
  1628. ip_address: str,
  1629. access_code: str,
  1630. path: str = "/",
  1631. timeout: float = 30.0,
  1632. socket_timeout: float | None = None,
  1633. printer_model: str | None = None,
  1634. ) -> FileListResult:
  1635. """List a directory without collapsing transport failure into empty."""
  1636. loop = asyncio.get_event_loop()
  1637. def _list() -> FileListResult:
  1638. client = BambuFTPClient(ip_address, access_code, timeout=socket_timeout, printer_model=printer_model)
  1639. if not client.connect():
  1640. return FileListResult(files=[], available=False)
  1641. try:
  1642. return FileListResult(files=client.list_files(path, raise_on_error=True), available=True)
  1643. except (OSError, ftplib.Error):
  1644. return FileListResult(files=[], available=False)
  1645. finally:
  1646. client.disconnect()
  1647. try:
  1648. return await asyncio.wait_for(loop.run_in_executor(_ftp_executor, _list), timeout=timeout)
  1649. except TimeoutError:
  1650. logger.warning("FTP list_files timed out after %ss for %s", timeout, path)
  1651. return FileListResult(files=[], available=False)
  1652. async def find_remote_file_async(
  1653. ip_address: str,
  1654. access_code: str,
  1655. remote_paths: list[str],
  1656. timeout: float = 30.0,
  1657. socket_timeout: float | None = None,
  1658. printer_model: str | None = None,
  1659. ) -> str | None:
  1660. """First of *remote_paths* the printer actually has, or None.
  1661. Answers "is this file there?" without fetching it, over a single
  1662. connection: one listing per distinct directory, reused across the
  1663. candidates that share it, and stops at the first hit. Written for the
  1664. connection diagnostic (#2856), which needs the answer for a file that can
  1665. be tens of megabytes and has no use for its contents.
  1666. Listing rather than ``SIZE``: LIST is what every Bambu firmware here is
  1667. known to answer, and a ``SIZE`` the server simply does not implement would
  1668. read as "the file is missing".
  1669. """
  1670. loop = asyncio.get_event_loop()
  1671. def _find() -> str | None:
  1672. client = BambuFTPClient(ip_address, access_code, timeout=socket_timeout, printer_model=printer_model)
  1673. if not client.connect():
  1674. return None
  1675. try:
  1676. listed: dict[str, set[str]] = {}
  1677. for remote_path in remote_paths:
  1678. directory, _, name = remote_path.rpartition("/")
  1679. directory = directory or "/"
  1680. if directory not in listed:
  1681. listed[directory] = {
  1682. entry.get("name") for entry in client.list_files(directory) if not entry.get("is_directory")
  1683. }
  1684. if name in listed[directory]:
  1685. return remote_path
  1686. return None
  1687. finally:
  1688. client.disconnect()
  1689. try:
  1690. return await asyncio.wait_for(loop.run_in_executor(_ftp_executor, _find), timeout=timeout)
  1691. except TimeoutError:
  1692. logger.warning("FTP find_remote_file timed out after %ss on %s", timeout, ip_address)
  1693. return None
  1694. async def delete_file_async(
  1695. ip_address: str,
  1696. access_code: str,
  1697. remote_path: str,
  1698. socket_timeout: float | None = None,
  1699. printer_model: str | None = None,
  1700. timeout: float = 60.0,
  1701. respect_handshake_cooloff: bool = True,
  1702. ) -> DeleteResult:
  1703. """Async wrapper for deleting a file.
  1704. Returns :class:`DeleteResult` so callers can distinguish ``NOT_FOUND``
  1705. (550 — file isn't on the printer, no retry value) from ``FAILED``
  1706. (network / auth / transient — worth retrying or surfacing).
  1707. Args:
  1708. socket_timeout: FTP socket timeout for slow connections (e.g., A1 printers)
  1709. printer_model: Printer model for A1-specific workarounds
  1710. timeout: overall async cap so a saturated ``_ftp_executor`` can't pin
  1711. the caller (and any DB connection it holds) indefinitely (#2572).
  1712. respect_handshake_cooloff: see ``BambuFTPClient.__init__``. The delete
  1713. that clears the way for a dispatch shares the upload's exemption --
  1714. it is one connection, and in #2898's trace it is the one that armed
  1715. the cool-off the upload then spent all four attempts against.
  1716. """
  1717. loop = asyncio.get_event_loop()
  1718. def _delete() -> DeleteResult:
  1719. client = BambuFTPClient(
  1720. ip_address,
  1721. access_code,
  1722. timeout=socket_timeout,
  1723. printer_model=printer_model,
  1724. respect_handshake_cooloff=respect_handshake_cooloff,
  1725. )
  1726. if client.connect():
  1727. try:
  1728. return client.delete_file(remote_path)
  1729. finally:
  1730. client.disconnect()
  1731. return DeleteResult.FAILED
  1732. try:
  1733. return await asyncio.wait_for(loop.run_in_executor(_ftp_executor, _delete), timeout=timeout)
  1734. except TimeoutError:
  1735. logger.warning("FTP delete_file exceeded its %ss cap for %s (#2572)", timeout, ip_address)
  1736. return DeleteResult.FAILED
  1737. async def download_file_bytes_async(
  1738. ip_address: str,
  1739. access_code: str,
  1740. remote_path: str,
  1741. socket_timeout: float | None = None,
  1742. printer_model: str | None = None,
  1743. timeout: float = 300.0,
  1744. expected_size: int | None = None,
  1745. ) -> bytes | None:
  1746. """Async wrapper for downloading file as bytes.
  1747. Args:
  1748. socket_timeout: FTP socket timeout for slow connections (e.g., A1 printers)
  1749. printer_model: Printer model for A1-specific workarounds
  1750. timeout: overall async cap so a saturated ``_ftp_executor`` can't pin
  1751. the caller (and any DB connection it holds) indefinitely (#2572).
  1752. Generous by default because this pulls whole files (timelapse
  1753. video, gcode) which can legitimately take minutes over slow Wi-Fi —
  1754. the cap only guards against a permanently-starved pool, not a
  1755. slow-but-progressing transfer.
  1756. expected_size: size from the directory listing; a mismatch fails the
  1757. download instead of returning a truncated file. See
  1758. :meth:`BambuFTPClient.download_file`.
  1759. """
  1760. loop = asyncio.get_event_loop()
  1761. def _download():
  1762. client = BambuFTPClient(ip_address, access_code, timeout=socket_timeout, printer_model=printer_model)
  1763. if client.connect():
  1764. try:
  1765. return client.download_file(remote_path, expected_size=expected_size)
  1766. finally:
  1767. client.disconnect()
  1768. return None
  1769. try:
  1770. return await asyncio.wait_for(loop.run_in_executor(_ftp_executor, _download), timeout=timeout)
  1771. except TimeoutError:
  1772. logger.warning("FTP download_bytes exceeded its %ss cap for %s (#2572)", timeout, ip_address)
  1773. return None
  1774. async def remote_file_settled(
  1775. ip_address: str,
  1776. access_code: str,
  1777. remote_path: str,
  1778. downloaded_bytes: int,
  1779. *,
  1780. printer_model: str | None = None,
  1781. ) -> bool:
  1782. """Confirm the printer has finished writing the file we just downloaded.
  1783. Matching the download against the size from the directory listing proves we
  1784. received what the listing *said*, not that the file was *finished*. The
  1785. timelapse scan's first look happens seconds after the print ends, which is
  1786. exactly when the printer is writing the video — so a file still growing can
  1787. be listed at a partial size, served at that size, and pass the length check
  1788. as a complete video (#2704).
  1789. That was survivable while the printer kept its copy. It isn't now that a
  1790. successful attach deletes the source, so re-list afterwards: if the file has
  1791. grown, what we hold is a prefix and the caller should discard it and try
  1792. again on the next round.
  1793. Returns True when the remote file can no longer differ from what we hold —
  1794. the size still matches, or the file is gone from the listing entirely and
  1795. so cannot grow any further. Returns False when it has changed size, and on
  1796. a listing failure, because "we could not check" must not read as "safe to
  1797. delete".
  1798. """
  1799. directory, _, name = remote_path.rpartition("/")
  1800. files = await list_files_async(ip_address, access_code, directory or "/", printer_model=printer_model)
  1801. if not files:
  1802. logger.warning("[TIMELAPSE] Could not re-list %s to confirm %s is complete", directory or "/", name)
  1803. return False
  1804. for f in files:
  1805. if f.get("name") == name:
  1806. size = f.get("size")
  1807. if size == downloaded_bytes:
  1808. return True
  1809. logger.info(
  1810. "[TIMELAPSE] %s is still being written (%s bytes now, %s when downloaded) — will retry",
  1811. name,
  1812. size,
  1813. downloaded_bytes,
  1814. )
  1815. return False
  1816. # Vanished between the download and now. Nothing left that could grow, and
  1817. # nothing left to delete either.
  1818. logger.debug("[TIMELAPSE] %s is no longer on the printer after download", name)
  1819. return True
  1820. async def delete_archived_timelapse(
  1821. ip_address: str,
  1822. access_code: str,
  1823. remote_path: str,
  1824. *,
  1825. verified: bool,
  1826. printer_model: str | None = None,
  1827. printer_name: str = "",
  1828. ) -> bool:
  1829. """Remove a timelapse from the printer once it is safely in the archive.
  1830. Call this only after the attach succeeded (#2704). Keeping ``/timelapse``
  1831. down to just the unclaimed videos is what makes the snapshot diff
  1832. unambiguous rather than merely usually-right, and it stops P1S cards
  1833. filling with AVIs.
  1834. ``verified`` must say whether the downloaded byte count was checked against
  1835. the size the directory listing reported. It is required rather than
  1836. defaulted because this is the one irreversible step in the flow: an FTPS
  1837. data connection that closes early does not always raise, so an unverified
  1838. transfer can be a partial file that looks complete, and deleting the source
  1839. would then destroy the only good copy. The check lives here rather than at
  1840. each call site so no future caller can omit it.
  1841. Best-effort otherwise: a printer that refuses the delete keeps its copy, the
  1842. diff still excludes that filename next time because it is attached to an
  1843. archive, and nothing else in the flow cares. Returns True only on an actual
  1844. delete or a 550 (already gone).
  1845. """
  1846. if not verified:
  1847. logger.warning(
  1848. "[TIMELAPSE] Not deleting %s from printer %s: the download was never size-checked",
  1849. remote_path,
  1850. printer_name,
  1851. )
  1852. return False
  1853. for attempt in range(1, 4):
  1854. try:
  1855. result = await delete_file_async(ip_address, access_code, remote_path, printer_model=printer_model)
  1856. except Exception as e:
  1857. result = DeleteResult.FAILED
  1858. logger.warning("[TIMELAPSE] Delete attempt %d/3 raised for %s: %s", attempt, remote_path, e)
  1859. if result == DeleteResult.DELETED:
  1860. logger.info("[TIMELAPSE] Deleted %s from printer %s after archiving", remote_path, printer_name)
  1861. return True
  1862. if result == DeleteResult.NOT_FOUND:
  1863. # 550 never recovers by waiting — the printer already cleaned up.
  1864. logger.debug("[TIMELAPSE] %s already gone from printer %s", remote_path, printer_name)
  1865. return True
  1866. if attempt < 3:
  1867. await asyncio.sleep(2)
  1868. logger.warning(
  1869. "[TIMELAPSE] Could not delete %s from printer %s (it stays on the card; the archive copy is unaffected)",
  1870. remote_path,
  1871. printer_name,
  1872. )
  1873. return False
  1874. async def get_storage_info_async(
  1875. ip_address: str,
  1876. access_code: str,
  1877. socket_timeout: float | None = None,
  1878. printer_model: str | None = None,
  1879. timeout: float = 60.0,
  1880. ) -> dict | None:
  1881. """Async wrapper for getting storage info.
  1882. Args:
  1883. socket_timeout: FTP socket timeout for slow connections (e.g., A1 printers)
  1884. printer_model: Printer model for A1-specific workarounds
  1885. timeout: overall async cap so a saturated ``_ftp_executor`` can't pin
  1886. the caller (and any DB connection it holds) indefinitely (#2572).
  1887. """
  1888. loop = asyncio.get_event_loop()
  1889. def _get_storage():
  1890. client = BambuFTPClient(ip_address, access_code, timeout=socket_timeout, printer_model=printer_model)
  1891. if client.connect():
  1892. try:
  1893. return client.get_storage_info()
  1894. finally:
  1895. client.disconnect()
  1896. return None
  1897. try:
  1898. return await asyncio.wait_for(loop.run_in_executor(_ftp_executor, _get_storage), timeout=timeout)
  1899. except TimeoutError:
  1900. logger.warning("FTP get_storage_info exceeded its %ss cap for %s (#2572)", timeout, ip_address)
  1901. return None
  1902. async def get_ftp_retry_settings() -> tuple[bool, int, float, float]:
  1903. """Get FTP retry settings from database.
  1904. Returns:
  1905. Tuple of (retry_enabled, retry_count, retry_delay, timeout)
  1906. """
  1907. from backend.app.api.routes.settings import get_setting
  1908. from backend.app.core.database import async_session
  1909. async with async_session() as db:
  1910. enabled = (await get_setting(db, "ftp_retry_enabled") or "true") == "true"
  1911. count = int(await get_setting(db, "ftp_retry_count") or "3")
  1912. delay = float(await get_setting(db, "ftp_retry_delay") or "2")
  1913. timeout = float(await get_setting(db, "ftp_timeout") or "30")
  1914. return enabled, count, delay, timeout
  1915. async def with_ftp_retry(
  1916. operation: Callable[..., Awaitable[T]],
  1917. *args,
  1918. max_retries: int = 3,
  1919. retry_delay: float = 2.0,
  1920. operation_name: str = "FTP operation",
  1921. non_retry_exceptions: tuple[type[BaseException], ...] = (),
  1922. cooloff_ip: str | None = None,
  1923. **kwargs,
  1924. ) -> T | None:
  1925. """Execute FTP operation with retry logic.
  1926. Args:
  1927. operation: Async function to execute
  1928. *args: Positional arguments for the operation
  1929. max_retries: Number of retry attempts (default: 3)
  1930. retry_delay: Seconds to wait between retries (default: 2.0)
  1931. operation_name: Name for logging purposes
  1932. non_retry_exceptions: Exception types that should immediately abort retries
  1933. cooloff_ip: printer IP whose FTPS handshake cool-off should end the loop
  1934. early. Pass it from any caller that respects the cool-off; leave it
  1935. unset for one that opted out, or the loop would stop on a gate its
  1936. own attempts are ignoring (#2898).
  1937. **kwargs: Keyword arguments for the operation
  1938. Returns:
  1939. Result of the operation, or None if all attempts fail
  1940. ``UploadCancelled`` is never retried, whatever the caller passes: it means
  1941. the transfer overran its size-derived deadline, so a retry would spend
  1942. another full deadline reaching the same conclusion (#2529).
  1943. """
  1944. last_error = None
  1945. attempts_made = 0
  1946. for attempt in range(max_retries + 1):
  1947. attempts_made = attempt + 1
  1948. try:
  1949. result = await operation(*args, **kwargs)
  1950. # Check for "falsy" success indicators
  1951. if result not in (False, None, []):
  1952. if attempt > 0:
  1953. logger.info("%s succeeded on attempt %s/%s", operation_name, attempt + 1, max_retries + 1)
  1954. return result
  1955. # Operation returned failure indicator
  1956. if attempt > 0:
  1957. logger.info("%s attempt %s/%s returned failure", operation_name, attempt + 1, max_retries + 1)
  1958. except UploadCancelled:
  1959. raise
  1960. except Exception as e:
  1961. if non_retry_exceptions and isinstance(e, non_retry_exceptions):
  1962. raise
  1963. last_error = e
  1964. logger.warning("%s attempt %s/%s failed: %s", operation_name, attempt + 1, max_retries + 1, e)
  1965. # Don't wait after the last attempt
  1966. if attempt < max_retries:
  1967. # A cool-off outlasts this loop by two orders of magnitude, so once
  1968. # it is armed every remaining attempt returns False without opening
  1969. # a socket. Spending them anyway bought nothing and cost the caller
  1970. # `max_retries * retry_delay` seconds of sleeping, then reported the
  1971. # failure with the wrong reason (#2898).
  1972. if cooloff_ip and ftps_handshake_blocked(cooloff_ip):
  1973. logger.warning(
  1974. "%s: stopping after attempt %s/%s — %s is inside its FTPS handshake cool-off, "
  1975. "so the remaining attempts would not reach it",
  1976. operation_name,
  1977. attempt + 1,
  1978. max_retries + 1,
  1979. cooloff_ip,
  1980. )
  1981. break
  1982. logger.info("%s will retry in %ss...", operation_name, retry_delay)
  1983. await asyncio.sleep(retry_delay)
  1984. # attempts_made, not max_retries + 1: the loop can stop early on a cool-off,
  1985. # and reporting attempts that were never made is how #2898 read as a network
  1986. # problem when nothing had gone near the network.
  1987. logger.error("%s failed after %s attempts", operation_name, attempts_made)
  1988. if last_error:
  1989. logger.debug("Last error: %s", last_error)
  1990. return None