bambu_ftp.py 112 KB

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