bambu_ftp.py 100 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260
  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. # INFO, not WARNING: a 426 whose bytes verify is the normal
  866. # way Bambu FTPS ends a transfer, not a fault. It fired 54
  867. # times in one support bundle and every one was followed by
  868. # a completed upload, which buried the 26 handshake failures
  869. # in the same log that actually cost the user two prints
  870. # (#2987). The unverified branch below is still an error.
  871. logger.info(
  872. "FTP STOR returned %s for %s but file is intact on the "
  873. "printer (%s bytes match) — proceeding: %s",
  874. type(e).__name__,
  875. remote_path,
  876. file_size,
  877. e,
  878. )
  879. else:
  880. logger.error(
  881. "FTP STOR rejected by printer for %s: %s (%s); server size=%s expected=%s",
  882. remote_path,
  883. e,
  884. type(e).__name__,
  885. server_size,
  886. file_size,
  887. )
  888. raise
  889. except Exception as e:
  890. # Timeout or socket-level error reading 226 — the data was sent
  891. # on our side and the printer may still have written the file.
  892. # H2D can take 30+ seconds to send 226 after the data channel
  893. # closes, so we proceed with a warning rather than failing here.
  894. logger.warning(
  895. "FTP STOR confirmation not received for %s (proceeding): %s (%s)",
  896. remote_path,
  897. e,
  898. type(e).__name__,
  899. )
  900. if callback_exception is not None:
  901. cleanup_result: DeleteResult = DeleteResult.FAILED
  902. try:
  903. cleanup_result = self.delete_file(remote_path)
  904. except Exception as cleanup_error:
  905. logger.warning("FTP cancel cleanup failed for %s: %s", remote_path, cleanup_error)
  906. # NOT_FOUND is success here — the partial file is gone (printer
  907. # may have already swept on cancel), which is the goal.
  908. if cleanup_result in (DeleteResult.DELETED, DeleteResult.NOT_FOUND):
  909. logger.info("FTP cancel cleanup succeeded for %s (%s)", remote_path, cleanup_result.value)
  910. raise callback_exception
  911. raise RuntimeError(
  912. f"Upload cancelled but failed to remove partial file {remote_path} from printer"
  913. ) from callback_exception
  914. elapsed = time.monotonic() - t0
  915. speed_kbs = (file_size / 1024) / elapsed if elapsed > 0 else 0
  916. logger.info(
  917. "FTP upload complete: %s (%s bytes in %.1fs, %.0f KB/s)",
  918. remote_path,
  919. file_size,
  920. elapsed,
  921. speed_kbs,
  922. )
  923. return True
  924. except ftplib.error_perm as e:
  925. # Permanent FTP error (4xx/5xx response)
  926. error_code = str(e)[:3] if str(e) else "unknown"
  927. logger.error("FTP upload failed for %s: %s (error code: %s)", remote_path, e, error_code)
  928. # 553 and 552 are the printer telling us about its own storage --
  929. # the one case where advice about the card is worth giving, and
  930. # the case the dispatch's blanket SD-card message was written for
  931. # before it was applied to every failure alike (#2899).
  932. if error_code == "553":
  933. logger.error(
  934. "FTP 553 error - Could not create file. Possible causes: "
  935. "1) No SD card inserted, 2) SD card full, 3) SD card not formatted correctly (needs FAT32/exFAT), "
  936. "4) Printer busy/not ready, 5) File path issue"
  937. )
  938. kind = FtpFailureKind.STORAGE
  939. elif error_code == "550":
  940. logger.error("FTP 550 error - File/directory not found or permission denied")
  941. kind = FtpFailureKind.NOT_FOUND
  942. elif error_code == "552":
  943. logger.error("FTP 552 error - Storage quota exceeded (SD card full?)")
  944. kind = FtpFailureKind.STORAGE
  945. else:
  946. kind = FtpFailureKind.UNKNOWN
  947. self.last_failure = FtpFailure(kind, str(e), _ftp_reply_code(e))
  948. return False
  949. except (OSError, ftplib.Error) as e:
  950. logger.error("FTP upload failed for %s: %s (type: %s)", remote_path, e, type(e).__name__)
  951. self.last_failure = FtpFailure(FtpFailureKind.NETWORK, str(e), _ftp_reply_code(e))
  952. return False
  953. def upload_bytes(self, data: bytes, remote_path: str) -> bool:
  954. """Upload bytes to the printer."""
  955. if not self._ftp:
  956. return False
  957. try:
  958. # Use manual transfer instead of storbinary() for A1 compatibility
  959. conn = self._ftp.transfercmd(f"STOR {remote_path}")
  960. conn.setblocking(True)
  961. conn.settimeout(self.timeout)
  962. try:
  963. # Send data in chunks
  964. offset = 0
  965. while offset < len(data):
  966. chunk = data[offset : offset + self.CHUNK_SIZE]
  967. conn.sendall(chunk)
  968. offset += len(chunk)
  969. except OSError as e:
  970. logger.error("FTP connection lost during upload_bytes: %s", e)
  971. raise
  972. finally:
  973. try:
  974. conn.close()
  975. except OSError:
  976. pass
  977. # Wait for 226 confirmation (see upload_file for rationale).
  978. # ftplib.Error subclasses (e.g. 426 error_temp) mean the server
  979. # rejected the transfer and the file is partial — fail. Other
  980. # exceptions (timeout, socket-level) are tolerated as in upload_file.
  981. try:
  982. old_timeout = self._ftp.sock.gettimeout()
  983. self._ftp.sock.settimeout(max(self.timeout, 60))
  984. try:
  985. self._ftp.voidresp()
  986. finally:
  987. self._ftp.sock.settimeout(old_timeout)
  988. except ftplib.Error as e:
  989. # Same SIZE-verify path as upload_file (#1417 follow-up):
  990. # tolerate a transient 426 if the bytes are actually on the
  991. # printer, fail loudly if they aren't.
  992. try:
  993. server_size = self._ftp.size(remote_path)
  994. except (OSError, ftplib.Error) as size_err:
  995. logger.debug("Post-error SIZE check failed: %s", size_err)
  996. server_size = None
  997. if server_size is not None and server_size == len(data):
  998. # INFO for the same reason as upload_file above (#2987).
  999. logger.info(
  1000. "FTP STOR returned %s for %s but file is intact on the "
  1001. "printer (%s bytes match) — proceeding: %s",
  1002. type(e).__name__,
  1003. remote_path,
  1004. len(data),
  1005. e,
  1006. )
  1007. else:
  1008. logger.error(
  1009. "FTP STOR rejected by printer for %s: %s (%s); server size=%s expected=%s",
  1010. remote_path,
  1011. e,
  1012. type(e).__name__,
  1013. server_size,
  1014. len(data),
  1015. )
  1016. return False
  1017. except Exception:
  1018. pass # Timeout / socket-level — proceed, data was sent.
  1019. return True
  1020. except (OSError, ftplib.Error):
  1021. return False
  1022. def delete_file(self, remote_path: str) -> DeleteResult:
  1023. """Delete a file from the printer.
  1024. Returns :class:`DeleteResult` distinguishing the file-not-found case
  1025. (550) from network / auth / transient FTP failure. Callers that just
  1026. want "did it work" should check ``result == DeleteResult.DELETED``.
  1027. """
  1028. if not self._ftp:
  1029. return DeleteResult.FAILED
  1030. try:
  1031. self._ftp.delete(remote_path)
  1032. return DeleteResult.DELETED
  1033. except ftplib.error_perm as e:
  1034. if str(e).startswith("550"):
  1035. logger.debug("FTP delete: %s not on printer (550)", remote_path)
  1036. return DeleteResult.NOT_FOUND
  1037. logger.warning("Failed to delete %s: %s", remote_path, e)
  1038. return DeleteResult.FAILED
  1039. except (OSError, ftplib.Error) as e:
  1040. logger.warning("Failed to delete %s: %s", remote_path, e)
  1041. return DeleteResult.FAILED
  1042. def get_file_size(self, remote_path: str) -> int | None:
  1043. """Get the size of a file."""
  1044. if not self._ftp:
  1045. return None
  1046. try:
  1047. return self._ftp.size(remote_path)
  1048. except (OSError, ftplib.Error):
  1049. return None
  1050. def get_storage_info(self) -> dict | None:
  1051. """Get storage information from the printer."""
  1052. if not self._ftp:
  1053. return None
  1054. result = {}
  1055. # Try AVBL command (available space) - some FTP servers support this
  1056. try:
  1057. response = self._ftp.sendcmd("AVBL")
  1058. logger.debug("AVBL response: %s", response)
  1059. # Response format: "213 <bytes available>"
  1060. if response.startswith("213"):
  1061. parts = response.split()
  1062. if len(parts) >= 2:
  1063. result["free_bytes"] = int(parts[1])
  1064. except (OSError, ftplib.Error) as e:
  1065. logger.debug("AVBL command not supported: %s", e)
  1066. # Try STAT command as fallback
  1067. try:
  1068. response = self._ftp.sendcmd("STAT")
  1069. logger.debug("STAT response: %s", response)
  1070. except (OSError, ftplib.Error):
  1071. pass # Both AVBL and STAT unsupported; storage info will rely on directory scan
  1072. # Calculate used space by listing root directories
  1073. try:
  1074. total_used = 0
  1075. dirs_to_scan = ["/cache", "/timelapse", "/model", "/data", "/data/Metadata", "/"]
  1076. for dir_path in dirs_to_scan:
  1077. try:
  1078. self._ftp.cwd(dir_path)
  1079. items = []
  1080. self._ftp.retrlines("LIST", items.append)
  1081. for item in items:
  1082. parts = item.split()
  1083. if len(parts) >= 5 and not item.startswith("d"):
  1084. try:
  1085. total_used += int(parts[4])
  1086. except ValueError:
  1087. pass # Skip entries with non-numeric size fields
  1088. except (OSError, ftplib.Error):
  1089. pass # Directory may not exist on this printer model; skip it
  1090. result["used_bytes"] = total_used
  1091. except (OSError, ftplib.Error):
  1092. pass # Storage scan failed; return whatever info was collected above
  1093. return result if result else None
  1094. def describe_upload_failure(failure: FtpFailure | None) -> str:
  1095. """One sentence for the operator, chosen from what actually went wrong.
  1096. Every upload failure used to get the same one: "Failed to upload file to
  1097. printer. Check if SD card is inserted and properly formatted
  1098. (FAT32/exFAT)." #2899's reporter got that after a TLS handshake failure and
  1099. restarted the printer, which could not have helped -- the handshake never
  1100. reached the printer's filesystem, and the state that produced it lives in
  1101. Bambuddy's own memory. #2780 had already removed advice from this failure's
  1102. *log* line for the same reason; it survived in the string people read.
  1103. So the card is named only where the printer itself raised storage, and
  1104. where nothing here can say more, this says so and points at the log rather
  1105. than picking a plausible cause. A wrong instruction costs more than a
  1106. vague one: it sends someone to work on hardware that is fine.
  1107. """
  1108. if failure is None:
  1109. return (
  1110. "Could not upload the file to the printer. See the server log for the reason — "
  1111. "it records what the printer's file service said."
  1112. )
  1113. if failure.kind is FtpFailureKind.STORAGE:
  1114. return (
  1115. f"The printer refused to store the file ({failure.code or 'storage error'}). Check that its SD card "
  1116. "is inserted, has space free, and is formatted FAT32 or exFAT."
  1117. )
  1118. if failure.kind is FtpFailureKind.HANDSHAKE:
  1119. return (
  1120. "The printer's file service answered, but not with TLS, so no file could be sent to it. "
  1121. "Its SD card is not involved. This usually clears by itself; if it does not, power-cycling "
  1122. "the printer has not been found to help either, so please report it."
  1123. )
  1124. if failure.kind is FtpFailureKind.COOLOFF:
  1125. return (
  1126. "Bambuddy is holding off from this printer's file service after a recent failed TLS handshake, "
  1127. "so the file was not sent. This clears on its own within a few minutes."
  1128. )
  1129. if failure.kind is FtpFailureKind.AUTH:
  1130. return (
  1131. "The printer refused the file transfer connection. If the printer's access code changed, "
  1132. "update it on Bambuddy's Printers page."
  1133. )
  1134. if failure.kind is FtpFailureKind.TIMEOUT:
  1135. return (
  1136. "The printer's file service did not respond in time, so the file was not sent. "
  1137. "Check that the printer is on the network and reachable."
  1138. )
  1139. if failure.kind is FtpFailureKind.NOT_FOUND:
  1140. return (
  1141. "The printer rejected the upload path (550). See the server log — this is a Bambuddy-side "
  1142. "problem, not something to fix on the printer."
  1143. )
  1144. return (
  1145. "Could not upload the file to the printer. See the server log for the reason — "
  1146. "it records what the printer's file service said."
  1147. )
  1148. def ftps_handshake_blocked(ip_address: str) -> bool:
  1149. """True while this printer's FTPS handshake cool-off is still running.
  1150. Callers that walk a list of candidate paths use this to give up on the
  1151. remaining candidates: the failure is at the transport, below any path, so
  1152. every one of them would fail identically (#2780).
  1153. """
  1154. return BambuFTPClient.handshake_blocked(ip_address)
  1155. # Shared 3MF download cache (#972).
  1156. #
  1157. # Both the cover thumbnail endpoint (api/routes/printers.py) and the archive
  1158. # metadata flow (main.py) fetch the same 3MF file over FTP during a print.
  1159. # On slow / contended links (A1 Wi-Fi, large files) the duplicate transfers
  1160. # compete for the printer's single FTP socket and trigger 425 "can't open
  1161. # data channel" errors, feeding back into cause-2's retry storm.
  1162. #
  1163. # This cache stores the local path of a successfully-downloaded 3MF keyed
  1164. # by (printer_id, normalized_name). Whichever flow downloads first populates
  1165. # the cache; the other flow reuses the file read-only. Evicted on print
  1166. # completion so a later print with the same name re-downloads fresh bytes.
  1167. _threemf_path_cache: dict[tuple[int, str], Path] = {}
  1168. def normalize_3mf_name(name: str) -> str:
  1169. """Collapse various 3MF filename variants to a cache key.
  1170. Bambu tooling produces names as bare subtask ("Part"), with .3mf, with
  1171. .gcode.3mf, or (Studio-normalized) with spaces → underscores. All of
  1172. these refer to the same print job on the same printer, so they must
  1173. hash to the same cache key.
  1174. """
  1175. # Lowercase first so .3MF / .GCODE.3MF variants strip cleanly — a
  1176. # real-world case since Windows-side tooling sometimes uppercases
  1177. # extensions.
  1178. cleaned = name.strip().lower().replace(".gcode.3mf", "").replace(".gcode", "").replace(".3mf", "")
  1179. return cleaned.replace(" ", "_")
  1180. def cache_3mf_download(printer_id: int, name: str, local_path: Path) -> None:
  1181. """Record a successfully-downloaded 3MF so a sibling flow can reuse it."""
  1182. _threemf_path_cache[(printer_id, normalize_3mf_name(name))] = local_path
  1183. def get_cached_3mf(printer_id: int, name: str) -> Path | None:
  1184. """Return a cached 3MF path for this printer/name if the file still exists."""
  1185. key = (printer_id, normalize_3mf_name(name))
  1186. cached = _threemf_path_cache.get(key)
  1187. if cached and cached.exists() and cached.stat().st_size > 0:
  1188. return cached
  1189. # Evict dead entry — the file was cleaned up (temp dir clean, manual
  1190. # deletion, restart) so the cache value is no longer usable.
  1191. if cached:
  1192. _threemf_path_cache.pop(key, None)
  1193. return None
  1194. def clear_3mf_cache(printer_id: int | None = None, delete_files: bool = True) -> None:
  1195. """Drop cache entries for one printer (or all with None).
  1196. When ``delete_files`` is True (default) the on-disk 3MF is removed as well
  1197. — called from on_print_complete so temp files don't accumulate across
  1198. prints. Tests that want to inspect the cache contents disable this.
  1199. Only paths inside ``archive_dir/temp`` are unlinked. The dispatch sites
  1200. added in #1166 also cache the live archive copy and library file bytes
  1201. so /cover can skip FTP — those are *user data*, never the cache's to
  1202. delete. Pre-fix this branch silently removed archive 3mfs on every print
  1203. completion (#1212 + private reports of "file disappeared overnight").
  1204. """
  1205. from backend.app.core.config import settings as _config_settings
  1206. temp_root = _config_settings.archive_dir / "temp"
  1207. def _is_temp_path(path: Path) -> bool:
  1208. try:
  1209. return path.is_relative_to(temp_root)
  1210. except (OSError, ValueError):
  1211. return False
  1212. def _maybe_unlink(path: Path) -> None:
  1213. if not delete_files or not path.exists():
  1214. return
  1215. if not _is_temp_path(path):
  1216. return
  1217. try:
  1218. path.unlink()
  1219. except OSError as exc:
  1220. logger.debug("3MF cache cleanup skipped %s: %s", path, exc)
  1221. if printer_id is None:
  1222. for path in list(_threemf_path_cache.values()):
  1223. _maybe_unlink(path)
  1224. _threemf_path_cache.clear()
  1225. return
  1226. for key in [k for k in _threemf_path_cache if k[0] == printer_id]:
  1227. _maybe_unlink(_threemf_path_cache[key])
  1228. _threemf_path_cache.pop(key, None)
  1229. async def download_file_async(
  1230. ip_address: str,
  1231. access_code: str,
  1232. remote_path: str,
  1233. local_path: Path,
  1234. timeout: float = 60.0,
  1235. socket_timeout: float | None = None,
  1236. printer_model: str | None = None,
  1237. expected_size: int | None = None,
  1238. max_bytes: int | None = None,
  1239. cancel_event: threading.Event | None = None,
  1240. min_free_bytes: int | None = None,
  1241. ) -> bool:
  1242. """Async wrapper for downloading a file with timeout.
  1243. For A1/A1 Mini printers, automatically tries prot_p first, then falls back
  1244. to prot_c if the download fails. The working mode is cached for future operations.
  1245. ``timeout`` bounds the wait for a *result*, not the call: when it expires
  1246. this waits for the FTP worker thread to unwind before returning, because
  1247. the thread owns ``local_path`` until it does and a caller that came back
  1248. early would delete a file still being written. That wait is bounded by the
  1249. socket timeout, so pass ``socket_timeout`` on any path that must not block
  1250. indefinitely -- every caller here does.
  1251. Args:
  1252. ip_address: Printer IP address
  1253. access_code: Printer access code
  1254. remote_path: Remote file path on printer
  1255. local_path: Local path to save file
  1256. timeout: Overall operation timeout (asyncio)
  1257. socket_timeout: FTP socket timeout for slow connections (e.g., A1 printers)
  1258. printer_model: Printer model for A1-specific workarounds
  1259. """
  1260. loop = asyncio.get_event_loop()
  1261. is_a1 = printer_model in BambuFTPClient.A1_MODELS if printer_model else False
  1262. # Per-attempt completion state: asyncio.wait_for cannot cancel
  1263. # run_in_executor threads, so on timeout the executor may still complete
  1264. # the download after we stop waiting. The thread flips `success` to True
  1265. # ONLY after the file is fully written — a post-timeout check lets us
  1266. # salvage the download without mistaking an in-progress partial write
  1267. # for a completed one. Each attempt gets its own dict and event so a
  1268. # zombie from an earlier attempt can't flip the flag for a later one.
  1269. # The event is set in `_download`'s finally block so the post-timeout
  1270. # path can wait for genuine thread completion instead of a fixed sleep.
  1271. class _CombinedCancelEvent:
  1272. def __init__(self, attempt_event: threading.Event):
  1273. self._attempt_event = attempt_event
  1274. def is_set(self) -> bool:
  1275. return self._attempt_event.is_set() or (cancel_event is not None and cancel_event.is_set())
  1276. def _download(
  1277. force_prot_c: bool,
  1278. completion: dict,
  1279. done: threading.Event,
  1280. attempt_cancel: threading.Event,
  1281. ) -> bool:
  1282. mode_str = "prot_c" if force_prot_c else "prot_p"
  1283. try:
  1284. combined_cancel = _CombinedCancelEvent(attempt_cancel)
  1285. if combined_cancel.is_set():
  1286. raise DownloadCancelled(remote_path)
  1287. client = BambuFTPClient(
  1288. ip_address,
  1289. access_code,
  1290. timeout=socket_timeout,
  1291. printer_model=printer_model,
  1292. force_prot_c=force_prot_c,
  1293. )
  1294. if client.connect():
  1295. try:
  1296. result = client.download_to_file(
  1297. remote_path,
  1298. local_path,
  1299. expected_size=expected_size,
  1300. max_bytes=max_bytes,
  1301. cancel_event=combined_cancel,
  1302. min_free_bytes=min_free_bytes,
  1303. )
  1304. if result:
  1305. BambuFTPClient.cache_mode(ip_address, mode_str)
  1306. completion["success"] = True
  1307. return result
  1308. finally:
  1309. client.disconnect()
  1310. return False
  1311. finally:
  1312. done.set()
  1313. async def _run(force_prot_c: bool) -> bool:
  1314. completion = {"success": False}
  1315. done = threading.Event()
  1316. attempt_cancel = threading.Event()
  1317. worker = loop.run_in_executor(_ftp_executor, _download, force_prot_c, completion, done, attempt_cancel)
  1318. try:
  1319. return await asyncio.wait_for(asyncio.shield(worker), timeout=timeout)
  1320. except asyncio.CancelledError:
  1321. # Cancelling an asyncio Future cannot stop its executor thread. Set
  1322. # the callback-visible flag and do not let the caller unlink the
  1323. # staging file until the worker has genuinely unwound.
  1324. attempt_cancel.set()
  1325. try:
  1326. await asyncio.shield(worker)
  1327. except (DownloadCancelled, OSError, ftplib.Error):
  1328. pass
  1329. raise
  1330. except TimeoutError:
  1331. # Slow WiFi links commonly overshoot ftp_timeout by 10–30 s without
  1332. # actually being stuck, so starting attempt 2 now would just contend
  1333. # with the still-progressing RETR on attempt 1 and produce the
  1334. # zombie-write race reported in #1014 (file landed on disk minutes
  1335. # after the retry loop had already given up). Wait for the worker
  1336. # thread to genuinely finish — capped at 30 s so a truly stuck
  1337. # connection can't stall a whole attempt indefinitely, with a 0.5 s
  1338. # floor so artificially small test timeouts still give zombies a
  1339. # realistic window to finish.
  1340. grace = max(min(timeout, 30.0), 0.5)
  1341. # Deliberately the DEFAULT executor, not `_ftp_executor`: this thread
  1342. # blocks waiting on `_download`, which is itself an `_ftp_executor`
  1343. # worker. Parking waiters in the same bounded pool as the workers they
  1344. # wait for is how you build a deadlock — with enough concurrent
  1345. # timeouts the waiters would occupy every slot and the downloads they
  1346. # are waiting for could never be scheduled.
  1347. attempt_cancel.set()
  1348. await loop.run_in_executor(None, done.wait, grace)
  1349. # Wait for the thread either way. If the grace period was enough it
  1350. # returns at once; if it was not, the blocking socket still has to
  1351. # reach its own timeout, and returning before it does would let the
  1352. # caller unlink a file the executor is still writing.
  1353. try:
  1354. await asyncio.shield(worker)
  1355. except (DownloadCancelled, OSError, ftplib.Error):
  1356. pass
  1357. if completion["success"] and local_path.exists() and local_path.stat().st_size > 0:
  1358. logger.info(
  1359. "FTP download wait_for timed out after %ss for %s, but thread completed within %ss grace (%s bytes) — salvaging",
  1360. timeout,
  1361. remote_path,
  1362. grace,
  1363. local_path.stat().st_size,
  1364. )
  1365. return True
  1366. logger.warning(
  1367. "FTP download timed out after %ss (plus %ss grace) for %s",
  1368. timeout,
  1369. grace,
  1370. remote_path,
  1371. )
  1372. return False
  1373. # Check if we have a cached mode for this printer
  1374. cached_mode = BambuFTPClient._mode_cache.get(ip_address)
  1375. if cached_mode:
  1376. force_prot_c = cached_mode == "prot_c"
  1377. return await _run(force_prot_c)
  1378. # No cached mode - try prot_p first
  1379. if await _run(False):
  1380. return True
  1381. # Download failed - for A1 models, try prot_c fallback
  1382. if is_a1:
  1383. logger.info("FTP download failed with prot_p for A1 model, trying prot_c fallback...")
  1384. return await _run(True)
  1385. return False
  1386. async def download_file_try_paths_async(
  1387. ip_address: str,
  1388. access_code: str,
  1389. remote_paths: list[str],
  1390. local_path: Path,
  1391. socket_timeout: float | None = None,
  1392. printer_model: str | None = None,
  1393. timeout: float = 90.0,
  1394. ) -> str | None:
  1395. """Try downloading a file from multiple paths using a single connection.
  1396. Returns the path that served the file, or ``None``. The path rather than a
  1397. bare flag because the caller usually cannot tell afterwards which candidate
  1398. hit, and on a printer that keeps uploads around for weeks that is the
  1399. difference between a diagnosable stale-copy match and an invisible one
  1400. (#1820). Callers testing it for truth are unaffected: a served path is
  1401. always a non-empty string.
  1402. Args:
  1403. socket_timeout: FTP socket timeout for slow connections (e.g., A1 printers)
  1404. printer_model: Printer model for A1-specific workarounds
  1405. timeout: overall async cap. The per-socket timeout only bounds an
  1406. in-flight worker; it does NOT bound how long this coroutine waits
  1407. for a free slot in the fixed-size ``_ftp_executor``. On a large
  1408. farm where offline printers keep every worker busy on dead
  1409. connects, that queue wait is otherwise unbounded — and any caller
  1410. holding a DB connection while awaiting this would pin it until the
  1411. pool is exhausted (#2572). The cap converts that into a bounded
  1412. wait; the orphaned worker finishes and its result is discarded.
  1413. """
  1414. loop = asyncio.get_event_loop()
  1415. def _download():
  1416. client = BambuFTPClient(ip_address, access_code, timeout=socket_timeout, printer_model=printer_model)
  1417. if not client.connect():
  1418. return None
  1419. try:
  1420. # FileNotOnPrinterError signals "try the next path", not "give up" —
  1421. # this function's whole purpose is to walk a list of candidates
  1422. # over one connection. Only a real transport error should bubble.
  1423. for remote_path in remote_paths:
  1424. try:
  1425. if client.download_to_file(remote_path, local_path):
  1426. return remote_path
  1427. except FileNotOnPrinterError:
  1428. continue
  1429. return None
  1430. finally:
  1431. client.disconnect()
  1432. try:
  1433. return await asyncio.wait_for(loop.run_in_executor(_ftp_executor, _download), timeout=timeout)
  1434. except TimeoutError:
  1435. logger.warning("FTP download_try_paths exceeded its %ss cap for %s (#2572)", timeout, ip_address)
  1436. return None
  1437. def _upload_deadline(local_path: Path) -> float:
  1438. """Derive an upload deadline from the file size (#2529).
  1439. See ``_UPLOAD_FLOOR_BYTES_PER_SEC``. An unstat-able file falls back to the
  1440. floor timeout — ``upload_file`` will fail on the open() anyway.
  1441. """
  1442. try:
  1443. size = local_path.stat().st_size
  1444. except OSError:
  1445. return _UPLOAD_MIN_TIMEOUT
  1446. return max(_UPLOAD_MIN_TIMEOUT, size / _UPLOAD_FLOOR_BYTES_PER_SEC)
  1447. # One upload at a time per printer. Two concurrent STOR commands for the same
  1448. # remote path leave a corrupt file on the SD card, and the printer reads as
  1449. # flaky rather than busy (#2529). Held for the duration of a transfer, so a
  1450. # second dispatch to the same printer queues behind the first instead of racing
  1451. # it. Keyed per event loop: an asyncio.Lock binds to the loop that first awaits
  1452. # it, and the test suite runs each case on a fresh loop.
  1453. _upload_locks: weakref.WeakKeyDictionary[asyncio.AbstractEventLoop, dict[str, asyncio.Lock]] = (
  1454. weakref.WeakKeyDictionary()
  1455. )
  1456. def _upload_lock(loop: asyncio.AbstractEventLoop, ip_address: str) -> asyncio.Lock:
  1457. per_loop = _upload_locks.setdefault(loop, {})
  1458. lock = per_loop.get(ip_address)
  1459. if lock is None:
  1460. lock = asyncio.Lock()
  1461. per_loop[ip_address] = lock
  1462. return lock
  1463. async def upload_file_async(
  1464. ip_address: str,
  1465. access_code: str,
  1466. local_path: Path,
  1467. remote_path: str,
  1468. timeout: float | None = None,
  1469. progress_callback: Callable[[int, int], None] | None = None,
  1470. socket_timeout: float | None = None,
  1471. printer_model: str | None = None,
  1472. respect_handshake_cooloff: bool = True,
  1473. failure: FtpFailureReport | None = None,
  1474. ) -> bool:
  1475. """Async wrapper for uploading a file with timeout and progress callback.
  1476. For A1/A1 Mini printers, automatically tries prot_p first, then falls back
  1477. to prot_c if the upload fails. The working mode is cached for future uploads.
  1478. Args:
  1479. ip_address: Printer IP address
  1480. access_code: Printer access code
  1481. local_path: Local file path to upload
  1482. remote_path: Remote path on printer
  1483. timeout: Overall deadline. ``None`` (the default) derives it from the
  1484. file size — see ``_upload_deadline``. A caller that passes a number
  1485. gets exactly that, which is what the tests rely on.
  1486. progress_callback: Optional callback for progress updates
  1487. socket_timeout: FTP socket timeout for slow connections (e.g., A1 printers)
  1488. printer_model: Printer model for A1-specific workarounds
  1489. respect_handshake_cooloff: see ``BambuFTPClient.__init__``. False for a
  1490. user-initiated upload, whose attempts are bounded and were being
  1491. spent against a cool-off that outlives them (#2898).
  1492. failure: caller-owned slot filled in with why the upload failed, so the
  1493. caller can say something true about it instead of guessing (#2899).
  1494. Passed through ``with_ftp_retry`` unchanged, so it ends up holding
  1495. the last attempt's reason -- which is the one that decided the
  1496. outcome.
  1497. """
  1498. loop = asyncio.get_event_loop()
  1499. is_a1 = printer_model in BambuFTPClient.A1_MODELS if printer_model else False
  1500. deadline = _upload_deadline(local_path) if timeout is None else timeout
  1501. # Set when the deadline expires. The worker checks it once per chunk.
  1502. cancel = threading.Event()
  1503. def _guarded_progress(uploaded: int, total: int) -> None:
  1504. if cancel.is_set():
  1505. raise UploadCancelled(f"upload of {remote_path} exceeded its {deadline:.0f}s deadline")
  1506. if progress_callback:
  1507. progress_callback(uploaded, total)
  1508. def _upload(force_prot_c: bool = False) -> bool:
  1509. mode_str = "prot_c" if force_prot_c else "prot_p"
  1510. logger.info(
  1511. f"FTP connecting to {ip_address} for upload (model={printer_model}, "
  1512. f"mode={mode_str}, socket_timeout={socket_timeout}s, deadline={deadline:.0f}s)..."
  1513. )
  1514. client = BambuFTPClient(
  1515. ip_address,
  1516. access_code,
  1517. timeout=socket_timeout,
  1518. printer_model=printer_model,
  1519. force_prot_c=force_prot_c,
  1520. respect_handshake_cooloff=respect_handshake_cooloff,
  1521. )
  1522. try:
  1523. if client.connect():
  1524. logger.info("FTP connected to %s", ip_address)
  1525. try:
  1526. result = client.upload_file(local_path, remote_path, _guarded_progress)
  1527. if result:
  1528. # Cache the working mode
  1529. BambuFTPClient.cache_mode(ip_address, mode_str)
  1530. return result
  1531. finally:
  1532. client.disconnect()
  1533. logger.warning("FTP connection failed to %s", ip_address)
  1534. return False
  1535. finally:
  1536. # In a finally so a transfer that leaves by raising -- a cancelled
  1537. # upload, a re-raised STOR rejection -- still reports what the
  1538. # client recorded on its way out.
  1539. if failure is not None and client.last_failure is not None:
  1540. failure.failure = client.last_failure
  1541. async def _attempt(force_prot_c: bool) -> bool:
  1542. """Run one upload attempt, and make a timeout actually stop the transfer.
  1543. ``asyncio.wait_for`` cancels the *future*, never the executor thread
  1544. behind it. Before #2529 a slow-but-healthy upload that overran the
  1545. deadline left that thread streaming: it kept pushing bytes, kept firing
  1546. the progress callback, and the retry above put a *second* STOR of the
  1547. same file onto the same printer. The reporter's 96 MB job ran four
  1548. concurrent transfers and never landed. So on timeout we signal the
  1549. worker (it raises ``UploadCancelled`` from the progress callback, which
  1550. breaks the send loop and deletes the partial file) and wait for it to
  1551. actually go.
  1552. """
  1553. fut = loop.run_in_executor(_ftp_executor, lambda: _upload(force_prot_c))
  1554. try:
  1555. return await asyncio.wait_for(asyncio.shield(fut), timeout=deadline)
  1556. except TimeoutError:
  1557. cancel.set()
  1558. logger.warning(
  1559. "FTP upload of %s exceeded its %.0fs deadline — cancelling the transfer",
  1560. remote_path,
  1561. deadline,
  1562. )
  1563. try:
  1564. await asyncio.wait_for(asyncio.shield(fut), timeout=_UPLOAD_CANCEL_GRACE)
  1565. except UploadCancelled:
  1566. logger.info("FTP upload of %s cancelled; partial file removed from the printer", remote_path)
  1567. except TimeoutError:
  1568. # The thread is wedged somewhere that never reaches the callback
  1569. # (a blocked sendall, say). Nothing more we can do from here —
  1570. # but consume the eventual result so asyncio doesn't log the
  1571. # future's exception as unretrieved when it is garbage-collected.
  1572. logger.error(
  1573. "FTP upload thread for %s did not stop within %.0fs of the cancel signal",
  1574. remote_path,
  1575. _UPLOAD_CANCEL_GRACE,
  1576. )
  1577. fut.add_done_callback(_swallow_future_result)
  1578. except Exception as e:
  1579. logger.warning("FTP upload of %s errored while cancelling: %s", remote_path, e)
  1580. # Raise rather than return False: a deadline expiry means the link
  1581. # sustained less than the floor rate for the whole transfer, and a
  1582. # retry would only spend another full deadline finding that out
  1583. # again — with check_queue serialized, four of those block the
  1584. # entire print queue for hours. ``with_ftp_retry`` never retries it.
  1585. raise UploadCancelled(
  1586. f"Upload of {remote_path} to {ip_address} exceeded its {deadline:.0f}s deadline "
  1587. f"(link sustained less than {_UPLOAD_FLOOR_BYTES_PER_SEC // 1024} KB/s)"
  1588. ) from None
  1589. async with _upload_lock(loop, ip_address):
  1590. # Check if we have a cached mode for this printer
  1591. cached_mode = BambuFTPClient._mode_cache.get(ip_address)
  1592. if cached_mode:
  1593. # Use cached mode
  1594. return await _attempt(cached_mode == "prot_c")
  1595. # No cached mode - try prot_p first
  1596. if await _attempt(False):
  1597. return True
  1598. # Upload failed - for A1 models, try prot_c fallback
  1599. if is_a1:
  1600. logger.info("FTP upload failed with prot_p for A1 model, trying prot_c fallback...")
  1601. return await _attempt(True)
  1602. return False
  1603. def _swallow_future_result(fut: asyncio.Future) -> None:
  1604. """Retrieve a future's exception so asyncio doesn't log it as unhandled."""
  1605. if not fut.cancelled():
  1606. fut.exception()
  1607. async def list_files_async(
  1608. ip_address: str,
  1609. access_code: str,
  1610. path: str = "/",
  1611. timeout: float = 30.0,
  1612. socket_timeout: float | None = None,
  1613. printer_model: str | None = None,
  1614. ) -> list[dict]:
  1615. """Async wrapper for listing files with timeout.
  1616. Args:
  1617. socket_timeout: FTP socket timeout for slow connections (e.g., A1 printers)
  1618. printer_model: Printer model for A1-specific workarounds
  1619. """
  1620. loop = asyncio.get_event_loop()
  1621. def _list():
  1622. client = BambuFTPClient(ip_address, access_code, timeout=socket_timeout, printer_model=printer_model)
  1623. if client.connect():
  1624. try:
  1625. return client.list_files(path)
  1626. finally:
  1627. client.disconnect()
  1628. return []
  1629. try:
  1630. return await asyncio.wait_for(loop.run_in_executor(_ftp_executor, _list), timeout=timeout)
  1631. except TimeoutError:
  1632. logger.warning("FTP list_files timed out after %ss for %s", timeout, path)
  1633. return []
  1634. async def list_files_result_async(
  1635. ip_address: str,
  1636. access_code: str,
  1637. path: str = "/",
  1638. timeout: float = 30.0,
  1639. socket_timeout: float | None = None,
  1640. printer_model: str | None = None,
  1641. ) -> FileListResult:
  1642. """List a directory without collapsing transport failure into empty."""
  1643. loop = asyncio.get_event_loop()
  1644. def _list() -> FileListResult:
  1645. client = BambuFTPClient(ip_address, access_code, timeout=socket_timeout, printer_model=printer_model)
  1646. if not client.connect():
  1647. return FileListResult(files=[], available=False)
  1648. try:
  1649. return FileListResult(files=client.list_files(path, raise_on_error=True), available=True)
  1650. except (OSError, ftplib.Error):
  1651. return FileListResult(files=[], available=False)
  1652. finally:
  1653. client.disconnect()
  1654. try:
  1655. return await asyncio.wait_for(loop.run_in_executor(_ftp_executor, _list), timeout=timeout)
  1656. except TimeoutError:
  1657. logger.warning("FTP list_files timed out after %ss for %s", timeout, path)
  1658. return FileListResult(files=[], available=False)
  1659. async def find_remote_file_async(
  1660. ip_address: str,
  1661. access_code: str,
  1662. remote_paths: list[str],
  1663. timeout: float = 30.0,
  1664. socket_timeout: float | None = None,
  1665. printer_model: str | None = None,
  1666. ) -> str | None:
  1667. """First of *remote_paths* the printer actually has, or None.
  1668. Answers "is this file there?" without fetching it, over a single
  1669. connection: one listing per distinct directory, reused across the
  1670. candidates that share it, and stops at the first hit. Written for the
  1671. connection diagnostic (#2856), which needs the answer for a file that can
  1672. be tens of megabytes and has no use for its contents.
  1673. Listing rather than ``SIZE``: LIST is what every Bambu firmware here is
  1674. known to answer, and a ``SIZE`` the server simply does not implement would
  1675. read as "the file is missing".
  1676. """
  1677. loop = asyncio.get_event_loop()
  1678. def _find() -> str | None:
  1679. client = BambuFTPClient(ip_address, access_code, timeout=socket_timeout, printer_model=printer_model)
  1680. if not client.connect():
  1681. return None
  1682. try:
  1683. listed: dict[str, set[str]] = {}
  1684. for remote_path in remote_paths:
  1685. directory, _, name = remote_path.rpartition("/")
  1686. directory = directory or "/"
  1687. if directory not in listed:
  1688. listed[directory] = {
  1689. entry.get("name") for entry in client.list_files(directory) if not entry.get("is_directory")
  1690. }
  1691. if name in listed[directory]:
  1692. return remote_path
  1693. return None
  1694. finally:
  1695. client.disconnect()
  1696. try:
  1697. return await asyncio.wait_for(loop.run_in_executor(_ftp_executor, _find), timeout=timeout)
  1698. except TimeoutError:
  1699. logger.warning("FTP find_remote_file timed out after %ss on %s", timeout, ip_address)
  1700. return None
  1701. async def delete_file_async(
  1702. ip_address: str,
  1703. access_code: str,
  1704. remote_path: str,
  1705. socket_timeout: float | None = None,
  1706. printer_model: str | None = None,
  1707. timeout: float = 60.0,
  1708. respect_handshake_cooloff: bool = True,
  1709. ) -> DeleteResult:
  1710. """Async wrapper for deleting a file.
  1711. Returns :class:`DeleteResult` so callers can distinguish ``NOT_FOUND``
  1712. (550 — file isn't on the printer, no retry value) from ``FAILED``
  1713. (network / auth / transient — worth retrying or surfacing).
  1714. Args:
  1715. socket_timeout: FTP socket timeout for slow connections (e.g., A1 printers)
  1716. printer_model: Printer model for A1-specific workarounds
  1717. timeout: overall async cap so a saturated ``_ftp_executor`` can't pin
  1718. the caller (and any DB connection it holds) indefinitely (#2572).
  1719. respect_handshake_cooloff: see ``BambuFTPClient.__init__``. The delete
  1720. that clears the way for a dispatch shares the upload's exemption --
  1721. it is one connection, and in #2898's trace it is the one that armed
  1722. the cool-off the upload then spent all four attempts against.
  1723. """
  1724. loop = asyncio.get_event_loop()
  1725. def _delete() -> DeleteResult:
  1726. client = BambuFTPClient(
  1727. ip_address,
  1728. access_code,
  1729. timeout=socket_timeout,
  1730. printer_model=printer_model,
  1731. respect_handshake_cooloff=respect_handshake_cooloff,
  1732. )
  1733. if client.connect():
  1734. try:
  1735. return client.delete_file(remote_path)
  1736. finally:
  1737. client.disconnect()
  1738. return DeleteResult.FAILED
  1739. try:
  1740. return await asyncio.wait_for(loop.run_in_executor(_ftp_executor, _delete), timeout=timeout)
  1741. except TimeoutError:
  1742. logger.warning("FTP delete_file exceeded its %ss cap for %s (#2572)", timeout, ip_address)
  1743. return DeleteResult.FAILED
  1744. async def download_file_bytes_async(
  1745. ip_address: str,
  1746. access_code: str,
  1747. remote_path: str,
  1748. socket_timeout: float | None = None,
  1749. printer_model: str | None = None,
  1750. timeout: float = 300.0,
  1751. expected_size: int | None = None,
  1752. ) -> bytes | None:
  1753. """Async wrapper for downloading file as bytes.
  1754. Args:
  1755. socket_timeout: FTP socket timeout for slow connections (e.g., A1 printers)
  1756. printer_model: Printer model for A1-specific workarounds
  1757. timeout: overall async cap so a saturated ``_ftp_executor`` can't pin
  1758. the caller (and any DB connection it holds) indefinitely (#2572).
  1759. Generous by default because this pulls whole files (timelapse
  1760. video, gcode) which can legitimately take minutes over slow Wi-Fi —
  1761. the cap only guards against a permanently-starved pool, not a
  1762. slow-but-progressing transfer.
  1763. expected_size: size from the directory listing; a mismatch fails the
  1764. download instead of returning a truncated file. See
  1765. :meth:`BambuFTPClient.download_file`.
  1766. """
  1767. loop = asyncio.get_event_loop()
  1768. def _download():
  1769. client = BambuFTPClient(ip_address, access_code, timeout=socket_timeout, printer_model=printer_model)
  1770. if client.connect():
  1771. try:
  1772. return client.download_file(remote_path, expected_size=expected_size)
  1773. finally:
  1774. client.disconnect()
  1775. return None
  1776. try:
  1777. return await asyncio.wait_for(loop.run_in_executor(_ftp_executor, _download), timeout=timeout)
  1778. except TimeoutError:
  1779. logger.warning("FTP download_bytes exceeded its %ss cap for %s (#2572)", timeout, ip_address)
  1780. return None
  1781. async def remote_file_settled(
  1782. ip_address: str,
  1783. access_code: str,
  1784. remote_path: str,
  1785. downloaded_bytes: int,
  1786. *,
  1787. printer_model: str | None = None,
  1788. ) -> bool:
  1789. """Confirm the printer has finished writing the file we just downloaded.
  1790. Matching the download against the size from the directory listing proves we
  1791. received what the listing *said*, not that the file was *finished*. The
  1792. timelapse scan's first look happens seconds after the print ends, which is
  1793. exactly when the printer is writing the video — so a file still growing can
  1794. be listed at a partial size, served at that size, and pass the length check
  1795. as a complete video (#2704).
  1796. That was survivable while the printer kept its copy. It isn't now that a
  1797. successful attach deletes the source, so re-list afterwards: if the file has
  1798. grown, what we hold is a prefix and the caller should discard it and try
  1799. again on the next round.
  1800. Returns True when the remote file can no longer differ from what we hold —
  1801. the size still matches, or the file is gone from the listing entirely and
  1802. so cannot grow any further. Returns False when it has changed size, and on
  1803. a listing failure, because "we could not check" must not read as "safe to
  1804. delete".
  1805. """
  1806. directory, _, name = remote_path.rpartition("/")
  1807. files = await list_files_async(ip_address, access_code, directory or "/", printer_model=printer_model)
  1808. if not files:
  1809. logger.warning("[TIMELAPSE] Could not re-list %s to confirm %s is complete", directory or "/", name)
  1810. return False
  1811. for f in files:
  1812. if f.get("name") == name:
  1813. size = f.get("size")
  1814. if size == downloaded_bytes:
  1815. return True
  1816. logger.info(
  1817. "[TIMELAPSE] %s is still being written (%s bytes now, %s when downloaded) — will retry",
  1818. name,
  1819. size,
  1820. downloaded_bytes,
  1821. )
  1822. return False
  1823. # Vanished between the download and now. Nothing left that could grow, and
  1824. # nothing left to delete either.
  1825. logger.debug("[TIMELAPSE] %s is no longer on the printer after download", name)
  1826. return True
  1827. async def delete_archived_timelapse(
  1828. ip_address: str,
  1829. access_code: str,
  1830. remote_path: str,
  1831. *,
  1832. verified: bool,
  1833. printer_model: str | None = None,
  1834. printer_name: str = "",
  1835. ) -> bool:
  1836. """Remove a timelapse from the printer once it is safely in the archive.
  1837. Call this only after the attach succeeded (#2704). Keeping ``/timelapse``
  1838. down to just the unclaimed videos is what makes the snapshot diff
  1839. unambiguous rather than merely usually-right, and it stops P1S cards
  1840. filling with AVIs.
  1841. ``verified`` must say whether the downloaded byte count was checked against
  1842. the size the directory listing reported. It is required rather than
  1843. defaulted because this is the one irreversible step in the flow: an FTPS
  1844. data connection that closes early does not always raise, so an unverified
  1845. transfer can be a partial file that looks complete, and deleting the source
  1846. would then destroy the only good copy. The check lives here rather than at
  1847. each call site so no future caller can omit it.
  1848. Best-effort otherwise: a printer that refuses the delete keeps its copy, the
  1849. diff still excludes that filename next time because it is attached to an
  1850. archive, and nothing else in the flow cares. Returns True only on an actual
  1851. delete or a 550 (already gone).
  1852. """
  1853. if not verified:
  1854. logger.warning(
  1855. "[TIMELAPSE] Not deleting %s from printer %s: the download was never size-checked",
  1856. remote_path,
  1857. printer_name,
  1858. )
  1859. return False
  1860. for attempt in range(1, 4):
  1861. try:
  1862. result = await delete_file_async(ip_address, access_code, remote_path, printer_model=printer_model)
  1863. except Exception as e:
  1864. result = DeleteResult.FAILED
  1865. logger.warning("[TIMELAPSE] Delete attempt %d/3 raised for %s: %s", attempt, remote_path, e)
  1866. if result == DeleteResult.DELETED:
  1867. logger.info("[TIMELAPSE] Deleted %s from printer %s after archiving", remote_path, printer_name)
  1868. return True
  1869. if result == DeleteResult.NOT_FOUND:
  1870. # 550 never recovers by waiting — the printer already cleaned up.
  1871. logger.debug("[TIMELAPSE] %s already gone from printer %s", remote_path, printer_name)
  1872. return True
  1873. if attempt < 3:
  1874. await asyncio.sleep(2)
  1875. logger.warning(
  1876. "[TIMELAPSE] Could not delete %s from printer %s (it stays on the card; the archive copy is unaffected)",
  1877. remote_path,
  1878. printer_name,
  1879. )
  1880. return False
  1881. async def get_storage_info_async(
  1882. ip_address: str,
  1883. access_code: str,
  1884. socket_timeout: float | None = None,
  1885. printer_model: str | None = None,
  1886. timeout: float = 60.0,
  1887. ) -> dict | None:
  1888. """Async wrapper for getting storage info.
  1889. Args:
  1890. socket_timeout: FTP socket timeout for slow connections (e.g., A1 printers)
  1891. printer_model: Printer model for A1-specific workarounds
  1892. timeout: overall async cap so a saturated ``_ftp_executor`` can't pin
  1893. the caller (and any DB connection it holds) indefinitely (#2572).
  1894. """
  1895. loop = asyncio.get_event_loop()
  1896. def _get_storage():
  1897. client = BambuFTPClient(ip_address, access_code, timeout=socket_timeout, printer_model=printer_model)
  1898. if client.connect():
  1899. try:
  1900. return client.get_storage_info()
  1901. finally:
  1902. client.disconnect()
  1903. return None
  1904. try:
  1905. return await asyncio.wait_for(loop.run_in_executor(_ftp_executor, _get_storage), timeout=timeout)
  1906. except TimeoutError:
  1907. logger.warning("FTP get_storage_info exceeded its %ss cap for %s (#2572)", timeout, ip_address)
  1908. return None
  1909. async def get_ftp_retry_settings() -> tuple[bool, int, float, float]:
  1910. """Get FTP retry settings from database.
  1911. Returns:
  1912. Tuple of (retry_enabled, retry_count, retry_delay, timeout)
  1913. """
  1914. from backend.app.api.routes.settings import get_setting
  1915. from backend.app.core.database import async_session
  1916. async with async_session() as db:
  1917. enabled = (await get_setting(db, "ftp_retry_enabled") or "true") == "true"
  1918. count = int(await get_setting(db, "ftp_retry_count") or "3")
  1919. delay = float(await get_setting(db, "ftp_retry_delay") or "2")
  1920. timeout = float(await get_setting(db, "ftp_timeout") or "30")
  1921. return enabled, count, delay, timeout
  1922. async def with_ftp_retry(
  1923. operation: Callable[..., Awaitable[T]],
  1924. *args,
  1925. max_retries: int = 3,
  1926. retry_delay: float = 2.0,
  1927. operation_name: str = "FTP operation",
  1928. non_retry_exceptions: tuple[type[BaseException], ...] = (),
  1929. cooloff_ip: str | None = None,
  1930. **kwargs,
  1931. ) -> T | None:
  1932. """Execute FTP operation with retry logic.
  1933. Args:
  1934. operation: Async function to execute
  1935. *args: Positional arguments for the operation
  1936. max_retries: Number of retry attempts (default: 3)
  1937. retry_delay: Seconds to wait between retries (default: 2.0)
  1938. operation_name: Name for logging purposes
  1939. non_retry_exceptions: Exception types that should immediately abort retries
  1940. cooloff_ip: printer IP whose FTPS handshake cool-off should end the loop
  1941. early. Pass it from any caller that respects the cool-off; leave it
  1942. unset for one that opted out, or the loop would stop on a gate its
  1943. own attempts are ignoring (#2898).
  1944. **kwargs: Keyword arguments for the operation
  1945. Returns:
  1946. Result of the operation, or None if all attempts fail
  1947. ``UploadCancelled`` is never retried, whatever the caller passes: it means
  1948. the transfer overran its size-derived deadline, so a retry would spend
  1949. another full deadline reaching the same conclusion (#2529).
  1950. """
  1951. last_error = None
  1952. attempts_made = 0
  1953. for attempt in range(max_retries + 1):
  1954. attempts_made = attempt + 1
  1955. try:
  1956. result = await operation(*args, **kwargs)
  1957. # Check for "falsy" success indicators
  1958. if result not in (False, None, []):
  1959. if attempt > 0:
  1960. logger.info("%s succeeded on attempt %s/%s", operation_name, attempt + 1, max_retries + 1)
  1961. return result
  1962. # Operation returned failure indicator
  1963. if attempt > 0:
  1964. logger.info("%s attempt %s/%s returned failure", operation_name, attempt + 1, max_retries + 1)
  1965. except UploadCancelled:
  1966. raise
  1967. except Exception as e:
  1968. if non_retry_exceptions and isinstance(e, non_retry_exceptions):
  1969. raise
  1970. last_error = e
  1971. logger.warning("%s attempt %s/%s failed: %s", operation_name, attempt + 1, max_retries + 1, e)
  1972. # Don't wait after the last attempt
  1973. if attempt < max_retries:
  1974. # A cool-off outlasts this loop by two orders of magnitude, so once
  1975. # it is armed every remaining attempt returns False without opening
  1976. # a socket. Spending them anyway bought nothing and cost the caller
  1977. # `max_retries * retry_delay` seconds of sleeping, then reported the
  1978. # failure with the wrong reason (#2898).
  1979. if cooloff_ip and ftps_handshake_blocked(cooloff_ip):
  1980. logger.warning(
  1981. "%s: stopping after attempt %s/%s — %s is inside its FTPS handshake cool-off, "
  1982. "so the remaining attempts would not reach it",
  1983. operation_name,
  1984. attempt + 1,
  1985. max_retries + 1,
  1986. cooloff_ip,
  1987. )
  1988. break
  1989. logger.info("%s will retry in %ss...", operation_name, retry_delay)
  1990. await asyncio.sleep(retry_delay)
  1991. # attempts_made, not max_retries + 1: the loop can stop early on a cool-off,
  1992. # and reporting attempts that were never made is how #2898 read as a network
  1993. # problem when nothing had gone near the network.
  1994. logger.error("%s failed after %s attempts", operation_name, attempts_made)
  1995. if last_error:
  1996. logger.debug("Last error: %s", last_error)
  1997. return None