bambu_ftp.py 88 KB

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