bambu_ftp.py 114 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551
  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. # When the control socket to the printer was opened, so the close log
  467. # can say how long the session was held (#3009).
  468. self._connected_at: float | None = None
  469. def _is_a1_model(self) -> bool:
  470. """Check if this is an A1 series printer."""
  471. if not self.printer_model:
  472. return False
  473. return self.printer_model in self.A1_MODELS
  474. def _get_cached_mode(self) -> str | None:
  475. """Get cached FTP mode for this printer."""
  476. return self._mode_cache.get(self.ip_address)
  477. @classmethod
  478. def cache_mode(cls, ip_address: str, mode: str):
  479. """Cache the working FTP mode for a printer."""
  480. cls._mode_cache[ip_address] = mode
  481. logger.info("FTP mode cached for %s: %s", ip_address, mode)
  482. def _should_use_prot_c(self) -> bool:
  483. """Determine if we should use prot_c (clear) mode."""
  484. # If explicitly forced, use prot_c
  485. if self.force_prot_c:
  486. return True
  487. # Check cache first
  488. cached = self._get_cached_mode()
  489. if cached:
  490. return cached == "prot_c"
  491. # Default: try prot_p first (will fall back if needed)
  492. return False
  493. @classmethod
  494. def handshake_blocked(cls, ip_address: str) -> bool:
  495. """True while *ip_address* is inside its post-handshake-failure cool-off.
  496. Public so a caller sweeping many candidate paths can stop after the
  497. first one rather than walking the rest against a printer that cannot
  498. complete a TLS handshake (#2780).
  499. """
  500. deadline = cls._handshake_blocked_until.get(ip_address)
  501. if deadline is None:
  502. return False
  503. if time.monotonic() >= deadline:
  504. # Drop it on the way past rather than leaving an entry per printer
  505. # this process has ever failed against.
  506. del cls._handshake_blocked_until[ip_address]
  507. cls._handshake_skip_logged.pop(ip_address, None)
  508. return False
  509. return True
  510. def connect(self) -> bool:
  511. """Connect to the printer FTP server (implicit FTPS on port 990).
  512. Returns False without touching the network while the printer is inside
  513. the cool-off a previous TLS handshake failure opened (#2780) -- unless
  514. this client was built with ``respect_handshake_cooloff=False``.
  515. """
  516. self.last_failure = None
  517. if self.respect_handshake_cooloff and self.handshake_blocked(self.ip_address):
  518. # WARNING, not DEBUG. This is the one connect() failure path that
  519. # reported without its cause, so at default log level four
  520. # reason-free "FTP connection failed" lines two seconds apart gave
  521. # no hint that nothing had been sent (#2898). Every caller reaching
  522. # here is already gated by handshake_blocked() at its own sweep
  523. # boundary, so this costs about one line per print, not a flood.
  524. deadline = self._handshake_blocked_until.get(self.ip_address)
  525. remaining = max(0.0, deadline - time.monotonic()) if deadline is not None else 0.0
  526. if deadline is not None and self._handshake_skip_logged.get(self.ip_address) != deadline:
  527. self._handshake_skip_logged[self.ip_address] = deadline
  528. logger.warning(
  529. "FTP connect to %s not attempted: its FTPS handshake failed recently and it is "
  530. "cooling off for another %.0fs. Nothing was sent to the printer.",
  531. self.ip_address,
  532. remaining,
  533. )
  534. else:
  535. # Said once already for this cool-off. Repeating it per candidate
  536. # path is the log flood #2780 set out to stop -- a download-zip
  537. # of 200 files would print the same sentence 200 times.
  538. logger.debug(
  539. "FTP connect to %s skipped: still cooling off for another %.0fs",
  540. self.ip_address,
  541. remaining,
  542. )
  543. self.last_failure = FtpFailure(
  544. FtpFailureKind.COOLOFF,
  545. f"cooling off for another {remaining:.0f}s after a recent FTPS handshake failure",
  546. )
  547. return False
  548. try:
  549. use_prot_c = self._should_use_prot_c()
  550. from backend.app.services.ftp_profiles import get_ftp_profile
  551. profile = get_ftp_profile(self.printer_model)
  552. logger.debug(
  553. f"FTP connecting to {self.ip_address}:{self.FTP_PORT} "
  554. f"(timeout={self.timeout}s, model={self.printer_model}, prot_c={use_prot_c}, "
  555. f"cap_tls_v1_2={profile.cap_tls_v1_2})"
  556. )
  557. self._ftp = ImplicitFTP_TLS(
  558. skip_session_reuse=use_prot_c,
  559. cap_tls_v1_2=profile.cap_tls_v1_2,
  560. )
  561. self._ftp.connect(self.ip_address, self.FTP_PORT, timeout=self.timeout)
  562. # Stamped here rather than after login: the socket exists from this
  563. # point on, and a session that dies during login is exactly the one
  564. # whose lifetime someone reading the log wants accounted for.
  565. self._connected_at = time.monotonic()
  566. logger.debug("FTP connected, logging in as bblp")
  567. self._ftp.login("bblp", self.access_code)
  568. if use_prot_c:
  569. # Use clear (unencrypted) data channel
  570. logger.debug("FTP logged in, setting prot_c (clear) and passive mode")
  571. self._ftp.prot_c()
  572. else:
  573. # Use protected (encrypted) data channel with session reuse
  574. logger.debug("FTP logged in, setting prot_p (protected) and passive mode")
  575. self._ftp.prot_p()
  576. self._ftp.set_pasv(True)
  577. # Log welcome message for debugging
  578. if hasattr(self._ftp, "welcome") and self._ftp.welcome:
  579. logger.debug("FTP server welcome: %s", self._ftp.welcome)
  580. logger.info(
  581. f"FTP connected successfully to {self.ip_address} (model={self.printer_model}, prot_c={use_prot_c})"
  582. )
  583. return True
  584. except ftplib.error_perm as e:
  585. logger.warning("FTP connection permission error to %s: %s", self.ip_address, e)
  586. self.last_failure = FtpFailure(FtpFailureKind.AUTH, str(e), _ftp_reply_code(e))
  587. self._abandon_connection("login rejected")
  588. return False
  589. except TimeoutError as e:
  590. logger.warning("FTP connection timed out to %s: %s", self.ip_address, e)
  591. self.last_failure = FtpFailure(FtpFailureKind.TIMEOUT, str(e))
  592. self._abandon_connection("connect timed out")
  593. return False
  594. except ssl.SSLError as e:
  595. # Not a transient failure and not something another path or another
  596. # retry can route around: the printer's file service answered port
  597. # 990 with something that isn't TLS. Say so once and stop knocking
  598. # for a while (#2780).
  599. #
  600. # Deliberately no advice about what to do. This message used to
  601. # tell the operator to restart the printer; #2780's reporter did
  602. # that twice, to no effect, and a single manual connect to the
  603. # same printer completes a clean handshake. We do not yet know the
  604. # trigger, so stating the observation and stopping there beats
  605. # sending people to do the one thing already known not to work.
  606. logger.warning(
  607. "FTP SSL error connecting to %s: %s — the printer answered port %s with something "
  608. "that is not TLS, so print files, covers and timelapses cannot be fetched from it. "
  609. "Pausing FTP to this printer for %.0fs.",
  610. self.ip_address,
  611. e,
  612. self.FTP_PORT,
  613. _HANDSHAKE_COOLOFF_SECONDS,
  614. )
  615. # Close the dead socket before asking this printer for anything
  616. # else. The probe below opens a second connection, and the leading
  617. # theory for this failure is a printer out of connection slots --
  618. # holding a failed handshake open across that is the exact thing
  619. # #2780's cleanup was added to stop. Idempotent, so the call that
  620. # used to sit at the end of this branch simply moved up.
  621. self._abandon_connection("TLS handshake failed")
  622. # Ask the printer what it actually said, once per cool-off window.
  623. # Checked before the deadline below is written, so a live entry here
  624. # means an earlier failure already opened this window and already
  625. # asked -- which keeps a dispatch that ignores the cool-off from
  626. # probing on each of its four attempts.
  627. detail = str(e)
  628. if getattr(e, "reason", None) == "WRONG_VERSION_NUMBER" and not self.handshake_blocked(self.ip_address):
  629. reply = _read_cleartext_reply(self.ip_address, self.FTP_PORT)
  630. if reply:
  631. logger.warning(
  632. "Printer %s answered port %s in cleartext with: %s — that is what the TLS "
  633. "handshake read as a malformed record. Please include this line if you report it.",
  634. self.ip_address,
  635. self.FTP_PORT,
  636. reply,
  637. )
  638. detail = f"{e} (printer answered in cleartext: {reply})"
  639. else:
  640. logger.warning(
  641. "Printer %s sent nothing readable in cleartext on port %s, so its file service "
  642. "was speaking TLS again by the time we asked — the refusal was momentary.",
  643. self.ip_address,
  644. self.FTP_PORT,
  645. )
  646. self._handshake_blocked_until[self.ip_address] = time.monotonic() + _HANDSHAKE_COOLOFF_SECONDS
  647. self.last_failure = FtpFailure(FtpFailureKind.HANDSHAKE, detail)
  648. return False
  649. except (OSError, ftplib.Error) as e:
  650. logger.warning("FTP connection failed to %s: %s (type: %s)", self.ip_address, e, type(e).__name__)
  651. self.last_failure = FtpFailure(FtpFailureKind.NETWORK, str(e), _ftp_reply_code(e))
  652. self._abandon_connection("connect failed")
  653. return False
  654. def _held_for(self) -> str:
  655. """How long the control socket has been open, for the close log.
  656. "unknown" when :meth:`connect` never got as far as opening one -- the
  657. cool-off skip and a DNS/refused failure both land in
  658. :meth:`_abandon_connection` without a socket ever existing.
  659. """
  660. if self._connected_at is None:
  661. return "unknown"
  662. return f"{time.monotonic() - self._connected_at:.1f}s"
  663. def _abandon_connection(self, reason: str = "connection never became usable") -> None:
  664. """Drop a connection that never became usable, closing its socket.
  665. Every failure path in :meth:`connect` used to clear ``self._ftp`` and
  666. nothing else, leaving a connected socket for the garbage collector.
  667. That is survivable once; it is not survivable at this volume. A single
  668. print used to walk ~110 candidate paths, so a printer refusing FTPS
  669. got ~110 sockets opened and abandoned in a couple of minutes, and one
  670. support bundle recorded 1813 of them in a day (#2780). If the refusal
  671. is the printer running out of connection slots -- which fits the
  672. evidence better than a wedged service, since a single manual connect
  673. to the same printer succeeds -- then abandoning sockets is not just
  674. untidy, it is what keeps the printer refusing.
  675. Uses ``close()`` rather than ``quit()``: QUIT is a command, and there
  676. is no working control channel to send it on.
  677. """
  678. ftp = self._ftp
  679. self._ftp = None
  680. held = self._held_for()
  681. self._connected_at = None
  682. if ftp is None:
  683. return
  684. try:
  685. ftp.close()
  686. except (OSError, ftplib.Error, EOFError):
  687. pass # Best-effort; the socket may already be gone
  688. # See the note in ``disconnect``: every session that opens a socket
  689. # says how it closed, so the log carries matched pairs (#3009).
  690. logger.debug(
  691. "FTP session to %s closed without QUIT (%s), held %s",
  692. self.ip_address,
  693. reason,
  694. held,
  695. )
  696. def disconnect(self):
  697. """Disconnect from the FTP server."""
  698. if self._ftp:
  699. held = self._held_for()
  700. try:
  701. self._ftp.quit()
  702. except (OSError, ftplib.Error, EOFError) as e:
  703. # ``quit()`` sends QUIT and only then closes; when the send
  704. # raises, ftplib never reaches its own close and the socket
  705. # stays open. Close it here rather than leaving it to the GC.
  706. self._abandon_connection(f"QUIT failed: {e}")
  707. else:
  708. # One line per session, at DEBUG. Neither this method nor
  709. # ``_abandon_connection`` used to log anything at any level, so
  710. # a session closed cleanly and a socket genuinely left open
  711. # produced identical logs -- nothing. #3009 read that silence
  712. # after a print as proof the connections were never closed, and
  713. # nothing in the log could have shown otherwise. Now every
  714. # connect has a matching close, so the next person can settle it
  715. # from a support bundle instead of by inference.
  716. logger.debug(
  717. "FTP session to %s closed after QUIT, held %s",
  718. self.ip_address,
  719. held,
  720. )
  721. self._ftp = None
  722. self._connected_at = None
  723. def list_files(self, path: str = "/", *, raise_on_error: bool = False) -> list[dict]:
  724. """List files in a directory."""
  725. if not self._ftp:
  726. return []
  727. files = []
  728. try:
  729. self._ftp.cwd(path)
  730. items = []
  731. self._ftp.retrlines("LIST", items.append)
  732. for item in items:
  733. parts = item.split()
  734. if len(parts) >= 9:
  735. name = " ".join(parts[8:])
  736. is_dir = item.startswith("d")
  737. size = int(parts[4]) if not is_dir else 0
  738. # Parse modification time from FTP listing
  739. # Format: "Nov 30 10:15" or "Nov 30 2024"
  740. mtime = None
  741. try:
  742. from datetime import datetime
  743. month = parts[5]
  744. day = parts[6]
  745. time_or_year = parts[7]
  746. # Determine if it's time (HH:MM) or year
  747. if ":" in time_or_year:
  748. # Recent file: "Nov 30 10:15" - assume current year
  749. year = datetime.now().year
  750. time_str = f"{month} {day} {year} {time_or_year}"
  751. mtime = datetime.strptime(time_str, "%b %d %Y %H:%M")
  752. # If parsed date is in the future, use last year
  753. if mtime > datetime.now():
  754. mtime = mtime.replace(year=year - 1)
  755. else:
  756. # Older file: "Nov 30 2024" - no time, just date
  757. time_str = f"{month} {day} {time_or_year}"
  758. mtime = datetime.strptime(time_str, "%b %d %Y")
  759. except (ValueError, IndexError):
  760. pass # Non-critical: mtime parsing is best-effort; file entry works without it
  761. file_entry = {
  762. "name": name,
  763. "is_directory": is_dir,
  764. "size": size,
  765. "path": f"{path.rstrip('/')}/{name}",
  766. }
  767. if mtime:
  768. file_entry["mtime"] = mtime
  769. files.append(file_entry)
  770. logger.debug("Listed %s files in %s", len(files), path)
  771. except (OSError, ftplib.Error) as e:
  772. logger.info("FTP list_files failed for %s: %s", path, e)
  773. if raise_on_error:
  774. raise
  775. return files
  776. def download_file(self, remote_path: str, expected_size: int | None = None) -> bytes | None:
  777. """Download a file from the printer.
  778. ``expected_size`` is the byte count the directory listing reported for
  779. this file. Pass it whenever a short read must not be mistaken for a
  780. successful download: an FTPS data connection that closes early does
  781. not always raise, so ``retrbinary`` can hand back a partial buffer that
  782. looks like a perfectly good file to everything downstream. That is
  783. tolerable when the printer keeps its copy, and not tolerable when the
  784. caller goes on to delete the source (#2704).
  785. A zero-byte result is always treated as a failure, matching
  786. :meth:`download_to_file` — no caller has a use for an empty file.
  787. """
  788. if not self._ftp:
  789. return None
  790. try:
  791. buffer = BytesIO()
  792. self._ftp.retrbinary(f"RETR {remote_path}", buffer.write)
  793. data = buffer.getvalue()
  794. except (OSError, ftplib.Error):
  795. return None
  796. if not data:
  797. logger.warning("FTP download returned 0 bytes for %s", remote_path)
  798. return None
  799. if expected_size is not None and len(data) != expected_size:
  800. logger.warning(
  801. "FTP download of %s is short: got %s bytes, listing reported %s — treating as failed",
  802. remote_path,
  803. len(data),
  804. expected_size,
  805. )
  806. return None
  807. return data
  808. def download_to_file(
  809. self,
  810. remote_path: str,
  811. local_path: Path,
  812. *,
  813. expected_size: int | None = None,
  814. max_bytes: int | None = None,
  815. cancel_event: threading.Event | None = None,
  816. min_free_bytes: int | None = None,
  817. size_callback: Callable[[int], None] | None = None,
  818. ) -> bool:
  819. """Download a file with cooperative cancellation and byte bounds.
  820. ``size_callback`` is handed the size the printer reported for this file,
  821. once, before the transfer starts. The async wrappers use it to grow a
  822. whole-transfer deadline that was set before anyone knew how big the file
  823. was (#2957); it must not raise.
  824. """
  825. if not self._ftp:
  826. logger.warning("download_to_file called but FTP not connected")
  827. return False
  828. try:
  829. local_path.parent.mkdir(parents=True, exist_ok=True)
  830. # SIZE is the printer's own current view of the file and is more
  831. # trustworthy than a browser round-tripped listing hint. Some
  832. # firmware does not implement SIZE, so retain expected_size as a
  833. # compatibility fallback when the command is unavailable.
  834. try:
  835. server_size = self._ftp.size(remote_path)
  836. except (OSError, ftplib.Error):
  837. server_size = None
  838. authoritative_size = server_size if server_size is not None and server_size >= 0 else expected_size
  839. if max_bytes is not None and authoritative_size is not None and authoritative_size > max_bytes:
  840. raise DownloadLimitExceeded(remote_path)
  841. if min_free_bytes is not None and authoritative_size is not None:
  842. if shutil.disk_usage(local_path.parent).free < min_free_bytes + authoritative_size:
  843. raise DownloadInsufficientSpace(remote_path)
  844. if size_callback is not None and authoritative_size is not None and authoritative_size > 0:
  845. size_callback(authoritative_size)
  846. with open(local_path, "wb") as f:
  847. written = 0
  848. # retrbinary hands over 8 KiB at a time, so checking the volume
  849. # on every callback is ~30k statvfs calls per 250 MB chunk for a
  850. # reserve measured in hundreds of megabytes. Sampling every few
  851. # MB cannot overshoot it by more than one interval.
  852. free_check_interval = 8 * 1024 * 1024
  853. next_free_check = 0
  854. def _write(chunk: bytes) -> None:
  855. nonlocal written, next_free_check
  856. if cancel_event is not None and cancel_event.is_set():
  857. raise DownloadCancelled(remote_path)
  858. if max_bytes is not None and written + len(chunk) > max_bytes:
  859. raise DownloadLimitExceeded(remote_path)
  860. if min_free_bytes is not None and written >= next_free_check:
  861. next_free_check = written + free_check_interval
  862. if shutil.disk_usage(local_path.parent).free < min_free_bytes + free_check_interval:
  863. raise DownloadInsufficientSpace(remote_path)
  864. f.write(chunk)
  865. written += len(chunk)
  866. self._ftp.retrbinary(f"RETR {remote_path}", _write)
  867. f.flush()
  868. os.fsync(f.fileno())
  869. file_size = local_path.stat().st_size if local_path.exists() else 0
  870. if file_size == 0:
  871. logger.warning("FTP download returned 0 bytes for %s", remote_path)
  872. if local_path.exists():
  873. local_path.unlink()
  874. return False
  875. if authoritative_size is not None and file_size != authoritative_size:
  876. logger.warning(
  877. "FTP download of %s is short: got %s bytes, listing reported %s — treating as failed",
  878. remote_path,
  879. file_size,
  880. authoritative_size,
  881. )
  882. local_path.unlink(missing_ok=True)
  883. return False
  884. logger.info("Successfully downloaded %s to %s (%s bytes)", remote_path, local_path, file_size)
  885. return True
  886. except (OSError, ftplib.Error, DownloadCancelled, DownloadLimitExceeded, DownloadInsufficientSpace) as e:
  887. # Clean up partial file if it exists
  888. if local_path.exists():
  889. try:
  890. local_path.unlink()
  891. except OSError:
  892. pass # Best-effort partial file cleanup; not critical if removal fails
  893. # 550 means the file is not at this path. Surface as a sentinel so
  894. # with_ftp_retry can abandon this path immediately and the caller
  895. # can advance to the next candidate instead of retrying 11× at
  896. # 30s intervals (the pattern that cost #972's reporter ~48min).
  897. if isinstance(e, (DownloadCancelled, DownloadLimitExceeded, DownloadInsufficientSpace)):
  898. raise
  899. if isinstance(e, ftplib.error_perm) and str(e).startswith("550"):
  900. logger.info("FTP download failed for %s: %s (not on printer)", remote_path, e)
  901. raise FileNotOnPrinterError(f"{remote_path}: {e}") from e
  902. # Log at INFO level so we can see failures in normal logs
  903. logger.info("FTP download failed for %s: %s", remote_path, e)
  904. return False
  905. def diagnose_storage(self) -> dict:
  906. """Run storage diagnostics and return results. For debugging upload issues."""
  907. results = {
  908. "connected": self._ftp is not None,
  909. "can_list_root": False,
  910. "root_files": [],
  911. "can_list_cache": False,
  912. "storage_info": None,
  913. "pwd": None,
  914. "errors": [],
  915. }
  916. if not self._ftp:
  917. results["errors"].append("FTP not connected")
  918. return results
  919. # Try to get current directory
  920. try:
  921. results["pwd"] = self._ftp.pwd()
  922. logger.debug("FTP current directory: %s", results["pwd"])
  923. except (OSError, ftplib.Error) as e:
  924. results["errors"].append(f"PWD failed: {e}")
  925. logger.debug("FTP PWD failed: %s", e)
  926. # Try to list root directory
  927. try:
  928. self._ftp.cwd("/")
  929. items = []
  930. self._ftp.retrlines("LIST", items.append)
  931. results["can_list_root"] = True
  932. results["root_files"] = items[:10] # First 10 entries
  933. logger.debug("FTP root listing (%s items): %s", len(items), items[:5])
  934. except (OSError, ftplib.Error) as e:
  935. results["errors"].append(f"LIST / failed: {e}")
  936. logger.debug("FTP LIST / failed: %s", e)
  937. # Try to list /cache (should exist on all printers)
  938. try:
  939. self._ftp.cwd("/cache")
  940. items = []
  941. self._ftp.retrlines("LIST", items.append)
  942. results["can_list_cache"] = True
  943. logger.debug("FTP /cache listing: %s items", len(items))
  944. except (OSError, ftplib.Error) as e:
  945. results["errors"].append(f"LIST /cache failed: {e}")
  946. logger.debug("FTP LIST /cache failed: %s", e)
  947. # Try to get storage info
  948. try:
  949. results["storage_info"] = self.get_storage_info()
  950. logger.debug("FTP storage info: %s", results["storage_info"])
  951. except (OSError, ftplib.Error) as e:
  952. results["errors"].append(f"Storage info failed: {e}")
  953. return results
  954. def upload_file(
  955. self,
  956. local_path: Path,
  957. remote_path: str,
  958. progress_callback: Callable[[int, int], None] | None = None,
  959. ) -> bool:
  960. """Upload a file to the printer with optional progress callback."""
  961. self.last_failure = None
  962. if not self._ftp:
  963. logger.warning("upload_file: FTP not connected")
  964. self.last_failure = FtpFailure(FtpFailureKind.UNKNOWN, "no FTP connection")
  965. return False
  966. try:
  967. file_size = local_path.stat().st_size if local_path.exists() else 0
  968. logger.info("FTP uploading %s (%s bytes) to %s", local_path, file_size, remote_path)
  969. uploaded = 0
  970. callback_exception: Exception | None = None
  971. # Use manual transfer instead of storbinary() for A1 compatibility
  972. # A1 printers have issues with storbinary's voidresp() hanging after transfer
  973. with open(local_path, "rb") as f:
  974. logger.debug("FTP STOR command starting for %s", remote_path)
  975. t0 = time.monotonic()
  976. conn = self._ftp.transfercmd(f"STOR {remote_path}")
  977. logger.info(
  978. "FTP data channel ready in %.1fs (PASV + TLS handshake)",
  979. time.monotonic() - t0,
  980. )
  981. # Set explicit socket options for reliable transfer
  982. conn.setblocking(True)
  983. conn.settimeout(self.timeout)
  984. try:
  985. while True:
  986. chunk = f.read(self.CHUNK_SIZE)
  987. if not chunk:
  988. logger.debug("FTP upload: final chunk reached")
  989. break
  990. conn.sendall(chunk)
  991. uploaded += len(chunk)
  992. logger.debug("FTP upload progress: %s/%s bytes", uploaded, file_size)
  993. if progress_callback:
  994. try:
  995. progress_callback(uploaded, file_size)
  996. except Exception as e:
  997. callback_exception = e
  998. logger.info(
  999. "FTP upload callback requested stop for %s at %s/%s bytes: %s",
  1000. remote_path,
  1001. uploaded,
  1002. file_size,
  1003. e,
  1004. )
  1005. break
  1006. except OSError as e:
  1007. logger.error("FTP connection lost during upload: %s", e)
  1008. raise
  1009. finally:
  1010. try:
  1011. conn.close()
  1012. except OSError:
  1013. pass
  1014. # Wait for the server's 226 "Transfer complete" response to confirm
  1015. # the file has been flushed to the SD card. Without this, the printer
  1016. # may try to read an incomplete file when the print command is sent,
  1017. # causing 0500-C010 "MicroSD Card read/write exception" errors.
  1018. # See: https://bugs.python.org/issue25458 (ftplib response desync)
  1019. try:
  1020. old_timeout = self._ftp.sock.gettimeout()
  1021. # Use a generous timeout — H2D printers can take 30+ seconds
  1022. # to send the 226 after the data channel closes.
  1023. self._ftp.sock.settimeout(max(self.timeout, 60))
  1024. try:
  1025. resp = self._ftp.voidresp()
  1026. logger.info("FTP STOR confirmed for %s: %s", remote_path, resp.strip())
  1027. finally:
  1028. self._ftp.sock.settimeout(old_timeout)
  1029. except ftplib.Error as e:
  1030. # Some P2S firmware revisions return ftplib.Error (e.g. 426
  1031. # "Failure reading network stream") on voidresp() even when
  1032. # the file landed fully on the SD card — the TLS data
  1033. # channel close races the 226 confirmation (#1417 follow-up).
  1034. # Verify via SIZE: if the server-side file size matches what
  1035. # we just uploaded, the file is intact and we proceed with
  1036. # a warning. If not — or SIZE itself fails — the transfer
  1037. # was genuinely truncated and we must fail so the print
  1038. # command doesn't go out for a partial 3MF (the original
  1039. # reason this catch was tightened in the previous round).
  1040. try:
  1041. server_size = self._ftp.size(remote_path)
  1042. except (OSError, ftplib.Error) as size_err:
  1043. logger.debug("Post-error SIZE check failed: %s", size_err)
  1044. server_size = None
  1045. if server_size is not None and server_size == file_size:
  1046. # INFO, not WARNING: a 426 whose bytes verify is the normal
  1047. # way Bambu FTPS ends a transfer, not a fault. It fired 54
  1048. # times in one support bundle and every one was followed by
  1049. # a completed upload, which buried the 26 handshake failures
  1050. # in the same log that actually cost the user two prints
  1051. # (#2987). The unverified branch below is still an error.
  1052. logger.info(
  1053. "FTP STOR returned %s for %s but file is intact on the "
  1054. "printer (%s bytes match) — proceeding: %s",
  1055. type(e).__name__,
  1056. remote_path,
  1057. file_size,
  1058. e,
  1059. )
  1060. else:
  1061. logger.error(
  1062. "FTP STOR rejected by printer for %s: %s (%s); server size=%s expected=%s",
  1063. remote_path,
  1064. e,
  1065. type(e).__name__,
  1066. server_size,
  1067. file_size,
  1068. )
  1069. raise
  1070. except Exception as e:
  1071. # Timeout or socket-level error reading 226 — the data was sent
  1072. # on our side and the printer may still have written the file.
  1073. # H2D can take 30+ seconds to send 226 after the data channel
  1074. # closes, so we proceed with a warning rather than failing here.
  1075. logger.warning(
  1076. "FTP STOR confirmation not received for %s (proceeding): %s (%s)",
  1077. remote_path,
  1078. e,
  1079. type(e).__name__,
  1080. )
  1081. if callback_exception is not None:
  1082. cleanup_result: DeleteResult = DeleteResult.FAILED
  1083. try:
  1084. cleanup_result = self.delete_file(remote_path)
  1085. except Exception as cleanup_error:
  1086. logger.warning("FTP cancel cleanup failed for %s: %s", remote_path, cleanup_error)
  1087. # NOT_FOUND is success here — the partial file is gone (printer
  1088. # may have already swept on cancel), which is the goal.
  1089. if cleanup_result in (DeleteResult.DELETED, DeleteResult.NOT_FOUND):
  1090. logger.info("FTP cancel cleanup succeeded for %s (%s)", remote_path, cleanup_result.value)
  1091. raise callback_exception
  1092. raise RuntimeError(
  1093. f"Upload cancelled but failed to remove partial file {remote_path} from printer"
  1094. ) from callback_exception
  1095. elapsed = time.monotonic() - t0
  1096. speed_kbs = (file_size / 1024) / elapsed if elapsed > 0 else 0
  1097. logger.info(
  1098. "FTP upload complete: %s (%s bytes in %.1fs, %.0f KB/s)",
  1099. remote_path,
  1100. file_size,
  1101. elapsed,
  1102. speed_kbs,
  1103. )
  1104. return True
  1105. except ftplib.error_perm as e:
  1106. # Permanent FTP error (4xx/5xx response)
  1107. error_code = str(e)[:3] if str(e) else "unknown"
  1108. logger.error("FTP upload failed for %s: %s (error code: %s)", remote_path, e, error_code)
  1109. # 553 and 552 are the printer telling us about its own storage --
  1110. # the one case where advice about the card is worth giving, and
  1111. # the case the dispatch's blanket SD-card message was written for
  1112. # before it was applied to every failure alike (#2899).
  1113. if error_code == "553":
  1114. logger.error(
  1115. "FTP 553 error - Could not create file. Possible causes: "
  1116. "1) No SD card inserted, 2) SD card full, 3) SD card not formatted correctly (needs FAT32/exFAT), "
  1117. "4) Printer busy/not ready, 5) File path issue"
  1118. )
  1119. kind = FtpFailureKind.STORAGE
  1120. elif error_code == "550":
  1121. logger.error("FTP 550 error - File/directory not found or permission denied")
  1122. kind = FtpFailureKind.NOT_FOUND
  1123. elif error_code == "552":
  1124. logger.error("FTP 552 error - Storage quota exceeded (SD card full?)")
  1125. kind = FtpFailureKind.STORAGE
  1126. else:
  1127. kind = FtpFailureKind.UNKNOWN
  1128. self.last_failure = FtpFailure(kind, str(e), _ftp_reply_code(e))
  1129. return False
  1130. except (OSError, ftplib.Error) as e:
  1131. logger.error("FTP upload failed for %s: %s (type: %s)", remote_path, e, type(e).__name__)
  1132. self.last_failure = FtpFailure(FtpFailureKind.NETWORK, str(e), _ftp_reply_code(e))
  1133. return False
  1134. def upload_bytes(self, data: bytes, remote_path: str) -> bool:
  1135. """Upload bytes to the printer."""
  1136. if not self._ftp:
  1137. return False
  1138. try:
  1139. # Use manual transfer instead of storbinary() for A1 compatibility
  1140. conn = self._ftp.transfercmd(f"STOR {remote_path}")
  1141. conn.setblocking(True)
  1142. conn.settimeout(self.timeout)
  1143. try:
  1144. # Send data in chunks
  1145. offset = 0
  1146. while offset < len(data):
  1147. chunk = data[offset : offset + self.CHUNK_SIZE]
  1148. conn.sendall(chunk)
  1149. offset += len(chunk)
  1150. except OSError as e:
  1151. logger.error("FTP connection lost during upload_bytes: %s", e)
  1152. raise
  1153. finally:
  1154. try:
  1155. conn.close()
  1156. except OSError:
  1157. pass
  1158. # Wait for 226 confirmation (see upload_file for rationale).
  1159. # ftplib.Error subclasses (e.g. 426 error_temp) mean the server
  1160. # rejected the transfer and the file is partial — fail. Other
  1161. # exceptions (timeout, socket-level) are tolerated as in upload_file.
  1162. try:
  1163. old_timeout = self._ftp.sock.gettimeout()
  1164. self._ftp.sock.settimeout(max(self.timeout, 60))
  1165. try:
  1166. self._ftp.voidresp()
  1167. finally:
  1168. self._ftp.sock.settimeout(old_timeout)
  1169. except ftplib.Error as e:
  1170. # Same SIZE-verify path as upload_file (#1417 follow-up):
  1171. # tolerate a transient 426 if the bytes are actually on the
  1172. # printer, fail loudly if they aren't.
  1173. try:
  1174. server_size = self._ftp.size(remote_path)
  1175. except (OSError, ftplib.Error) as size_err:
  1176. logger.debug("Post-error SIZE check failed: %s", size_err)
  1177. server_size = None
  1178. if server_size is not None and server_size == len(data):
  1179. # INFO for the same reason as upload_file above (#2987).
  1180. logger.info(
  1181. "FTP STOR returned %s for %s but file is intact on the "
  1182. "printer (%s bytes match) — proceeding: %s",
  1183. type(e).__name__,
  1184. remote_path,
  1185. len(data),
  1186. e,
  1187. )
  1188. else:
  1189. logger.error(
  1190. "FTP STOR rejected by printer for %s: %s (%s); server size=%s expected=%s",
  1191. remote_path,
  1192. e,
  1193. type(e).__name__,
  1194. server_size,
  1195. len(data),
  1196. )
  1197. return False
  1198. except Exception:
  1199. pass # Timeout / socket-level — proceed, data was sent.
  1200. return True
  1201. except (OSError, ftplib.Error):
  1202. return False
  1203. def delete_file(self, remote_path: str) -> DeleteResult:
  1204. """Delete a file from the printer.
  1205. Returns :class:`DeleteResult` distinguishing the file-not-found case
  1206. (550) from network / auth / transient FTP failure. Callers that just
  1207. want "did it work" should check ``result == DeleteResult.DELETED``.
  1208. """
  1209. if not self._ftp:
  1210. return DeleteResult.FAILED
  1211. try:
  1212. self._ftp.delete(remote_path)
  1213. return DeleteResult.DELETED
  1214. except ftplib.error_perm as e:
  1215. if str(e).startswith("550"):
  1216. logger.debug("FTP delete: %s not on printer (550)", remote_path)
  1217. return DeleteResult.NOT_FOUND
  1218. logger.warning("Failed to delete %s: %s", remote_path, e)
  1219. return DeleteResult.FAILED
  1220. except (OSError, ftplib.Error) as e:
  1221. logger.warning("Failed to delete %s: %s", remote_path, e)
  1222. return DeleteResult.FAILED
  1223. def get_file_size(self, remote_path: str) -> int | None:
  1224. """Get the size of a file."""
  1225. if not self._ftp:
  1226. return None
  1227. try:
  1228. return self._ftp.size(remote_path)
  1229. except (OSError, ftplib.Error):
  1230. return None
  1231. def get_storage_info(self) -> dict | None:
  1232. """Get storage information from the printer."""
  1233. if not self._ftp:
  1234. return None
  1235. result = {}
  1236. # Try AVBL command (available space) - some FTP servers support this
  1237. try:
  1238. response = self._ftp.sendcmd("AVBL")
  1239. logger.debug("AVBL response: %s", response)
  1240. # Response format: "213 <bytes available>"
  1241. if response.startswith("213"):
  1242. parts = response.split()
  1243. if len(parts) >= 2:
  1244. result["free_bytes"] = int(parts[1])
  1245. except (OSError, ftplib.Error) as e:
  1246. logger.debug("AVBL command not supported: %s", e)
  1247. # Try STAT command as fallback
  1248. try:
  1249. response = self._ftp.sendcmd("STAT")
  1250. logger.debug("STAT response: %s", response)
  1251. except (OSError, ftplib.Error):
  1252. pass # Both AVBL and STAT unsupported; storage info will rely on directory scan
  1253. # Calculate used space by listing root directories
  1254. try:
  1255. total_used = 0
  1256. dirs_to_scan = ["/cache", "/timelapse", "/model", "/data", "/data/Metadata", "/"]
  1257. for dir_path in dirs_to_scan:
  1258. try:
  1259. self._ftp.cwd(dir_path)
  1260. items = []
  1261. self._ftp.retrlines("LIST", items.append)
  1262. for item in items:
  1263. parts = item.split()
  1264. if len(parts) >= 5 and not item.startswith("d"):
  1265. try:
  1266. total_used += int(parts[4])
  1267. except ValueError:
  1268. pass # Skip entries with non-numeric size fields
  1269. except (OSError, ftplib.Error):
  1270. pass # Directory may not exist on this printer model; skip it
  1271. result["used_bytes"] = total_used
  1272. except (OSError, ftplib.Error):
  1273. pass # Storage scan failed; return whatever info was collected above
  1274. return result if result else None
  1275. def describe_upload_failure(failure: FtpFailure | None) -> str:
  1276. """One sentence for the operator, chosen from what actually went wrong.
  1277. Every upload failure used to get the same one: "Failed to upload file to
  1278. printer. Check if SD card is inserted and properly formatted
  1279. (FAT32/exFAT)." #2899's reporter got that after a TLS handshake failure and
  1280. restarted the printer, which could not have helped -- the handshake never
  1281. reached the printer's filesystem, and the state that produced it lives in
  1282. Bambuddy's own memory. #2780 had already removed advice from this failure's
  1283. *log* line for the same reason; it survived in the string people read.
  1284. So the card is named only where the printer itself raised storage, and
  1285. where nothing here can say more, this says so and points at the log rather
  1286. than picking a plausible cause. A wrong instruction costs more than a
  1287. vague one: it sends someone to work on hardware that is fine.
  1288. """
  1289. if failure is None:
  1290. return (
  1291. "Could not upload the file to the printer. See the server log for the reason — "
  1292. "it records what the printer's file service said."
  1293. )
  1294. if failure.kind is FtpFailureKind.STORAGE:
  1295. return (
  1296. f"The printer refused to store the file ({failure.code or 'storage error'}). Check that its SD card "
  1297. "is inserted, has space free, and is formatted FAT32 or exFAT."
  1298. )
  1299. if failure.kind is FtpFailureKind.HANDSHAKE:
  1300. return (
  1301. "The printer's file service answered, but not with TLS, so no file could be sent to it. "
  1302. "Its SD card is not involved. This usually clears by itself; if it does not, power-cycling "
  1303. "the printer has not been found to help either, so please report it."
  1304. )
  1305. if failure.kind is FtpFailureKind.COOLOFF:
  1306. return (
  1307. "Bambuddy is holding off from this printer's file service after a recent failed TLS handshake, "
  1308. "so the file was not sent. This clears on its own within a few minutes."
  1309. )
  1310. if failure.kind is FtpFailureKind.AUTH:
  1311. return (
  1312. "The printer refused the file transfer connection. If the printer's access code changed, "
  1313. "update it on Bambuddy's Printers page."
  1314. )
  1315. if failure.kind is FtpFailureKind.TIMEOUT:
  1316. return (
  1317. "The printer's file service did not respond in time, so the file was not sent. "
  1318. "Check that the printer is on the network and reachable."
  1319. )
  1320. if failure.kind is FtpFailureKind.NOT_FOUND:
  1321. return (
  1322. "The printer rejected the upload path (550). See the server log — this is a Bambuddy-side "
  1323. "problem, not something to fix on the printer."
  1324. )
  1325. return (
  1326. "Could not upload the file to the printer. See the server log for the reason — "
  1327. "it records what the printer's file service said."
  1328. )
  1329. def ftps_handshake_blocked(ip_address: str) -> bool:
  1330. """True while this printer's FTPS handshake cool-off is still running.
  1331. Callers that walk a list of candidate paths use this to give up on the
  1332. remaining candidates: the failure is at the transport, below any path, so
  1333. every one of them would fail identically (#2780).
  1334. """
  1335. return BambuFTPClient.handshake_blocked(ip_address)
  1336. # Shared 3MF download cache (#972).
  1337. #
  1338. # Both the cover thumbnail endpoint (api/routes/printers.py) and the archive
  1339. # metadata flow (main.py) fetch the same 3MF file over FTP during a print.
  1340. # On slow / contended links (A1 Wi-Fi, large files) the duplicate transfers
  1341. # compete for the printer's single FTP socket and trigger 425 "can't open
  1342. # data channel" errors, feeding back into cause-2's retry storm.
  1343. #
  1344. # This cache stores the local path of a successfully-downloaded 3MF keyed
  1345. # by (printer_id, normalized_name). Whichever flow downloads first populates
  1346. # the cache; the other flow reuses the file read-only. Evicted on print
  1347. # completion so a later print with the same name re-downloads fresh bytes.
  1348. _threemf_path_cache: dict[tuple[int, str], Path] = {}
  1349. def normalize_3mf_name(name: str) -> str:
  1350. """Collapse various 3MF filename variants to a cache key.
  1351. Bambu tooling produces names as bare subtask ("Part"), with .3mf, with
  1352. .gcode.3mf, or (Studio-normalized) with spaces → underscores. All of
  1353. these refer to the same print job on the same printer, so they must
  1354. hash to the same cache key.
  1355. """
  1356. # Lowercase first so .3MF / .GCODE.3MF variants strip cleanly — a
  1357. # real-world case since Windows-side tooling sometimes uppercases
  1358. # extensions.
  1359. cleaned = name.strip().lower().replace(".gcode.3mf", "").replace(".gcode", "").replace(".3mf", "")
  1360. return cleaned.replace(" ", "_")
  1361. def cache_3mf_download(printer_id: int, name: str, local_path: Path) -> None:
  1362. """Record a successfully-downloaded 3MF so a sibling flow can reuse it."""
  1363. _threemf_path_cache[(printer_id, normalize_3mf_name(name))] = local_path
  1364. def get_cached_3mf(printer_id: int, name: str) -> Path | None:
  1365. """Return a cached 3MF path for this printer/name if the file still exists."""
  1366. key = (printer_id, normalize_3mf_name(name))
  1367. cached = _threemf_path_cache.get(key)
  1368. if cached and cached.exists() and cached.stat().st_size > 0:
  1369. return cached
  1370. # Evict dead entry — the file was cleaned up (temp dir clean, manual
  1371. # deletion, restart) so the cache value is no longer usable.
  1372. if cached:
  1373. _threemf_path_cache.pop(key, None)
  1374. return None
  1375. def clear_3mf_cache(printer_id: int | None = None, delete_files: bool = True) -> None:
  1376. """Drop cache entries for one printer (or all with None).
  1377. When ``delete_files`` is True (default) the on-disk 3MF is removed as well
  1378. — called from on_print_complete so temp files don't accumulate across
  1379. prints. Tests that want to inspect the cache contents disable this.
  1380. Only paths inside ``archive_dir/temp`` are unlinked. The dispatch sites
  1381. added in #1166 also cache the live archive copy and library file bytes
  1382. so /cover can skip FTP — those are *user data*, never the cache's to
  1383. delete. Pre-fix this branch silently removed archive 3mfs on every print
  1384. completion (#1212 + private reports of "file disappeared overnight").
  1385. """
  1386. from backend.app.core.config import settings as _config_settings
  1387. temp_root = _config_settings.archive_dir / "temp"
  1388. def _is_temp_path(path: Path) -> bool:
  1389. try:
  1390. return path.is_relative_to(temp_root)
  1391. except (OSError, ValueError):
  1392. return False
  1393. def _maybe_unlink(path: Path) -> None:
  1394. if not delete_files or not path.exists():
  1395. return
  1396. if not _is_temp_path(path):
  1397. return
  1398. try:
  1399. path.unlink()
  1400. except OSError as exc:
  1401. logger.debug("3MF cache cleanup skipped %s: %s", path, exc)
  1402. if printer_id is None:
  1403. for path in list(_threemf_path_cache.values()):
  1404. _maybe_unlink(path)
  1405. _threemf_path_cache.clear()
  1406. return
  1407. for key in [k for k in _threemf_path_cache if k[0] == printer_id]:
  1408. _maybe_unlink(_threemf_path_cache[key])
  1409. _threemf_path_cache.pop(key, None)
  1410. async def download_file_async(
  1411. ip_address: str,
  1412. access_code: str,
  1413. remote_path: str,
  1414. local_path: Path,
  1415. timeout: float = 60.0,
  1416. socket_timeout: float | None = None,
  1417. printer_model: str | None = None,
  1418. expected_size: int | None = None,
  1419. max_bytes: int | None = None,
  1420. cancel_event: threading.Event | None = None,
  1421. min_free_bytes: int | None = None,
  1422. serialize: bool = True,
  1423. ) -> bool:
  1424. """Async wrapper for downloading a file with timeout.
  1425. For A1/A1 Mini printers, automatically tries prot_p first, then falls back
  1426. to prot_c if the download fails. The working mode is cached for future operations.
  1427. ``timeout`` bounds the wait for a *result*, not the call: when it expires
  1428. this waits for the FTP worker thread to unwind before returning, because
  1429. the thread owns ``local_path`` until it does and a caller that came back
  1430. early would delete a file still being written. That wait is bounded by the
  1431. socket timeout, so pass ``socket_timeout`` on any path that must not block
  1432. indefinitely -- every caller here does.
  1433. Args:
  1434. ip_address: Printer IP address
  1435. access_code: Printer access code
  1436. remote_path: Remote file path on printer
  1437. local_path: Local path to save file
  1438. timeout: Overall operation timeout (asyncio)
  1439. socket_timeout: FTP socket timeout for slow connections (e.g., A1 printers)
  1440. printer_model: Printer model for A1-specific workarounds
  1441. serialize: take this printer's download gate for the transfer (#2957).
  1442. Pass False from a path that must neither queue behind another
  1443. download nor make one queue behind it -- the printer file browser
  1444. is both, and says so: a preview must not wait out somebody else's
  1445. ten-gigabyte selection, and that selection must not hold the printer
  1446. for the twenty minutes it legitimately takes.
  1447. """
  1448. loop = asyncio.get_event_loop()
  1449. is_a1 = printer_model in BambuFTPClient.A1_MODELS if printer_model else False
  1450. # Per-attempt completion state: asyncio.wait_for cannot cancel
  1451. # run_in_executor threads, so on timeout the executor may still complete
  1452. # the download after we stop waiting. The thread flips `success` to True
  1453. # ONLY after the file is fully written — a post-timeout check lets us
  1454. # salvage the download without mistaking an in-progress partial write
  1455. # for a completed one. Each attempt gets its own dict and event so a
  1456. # zombie from an earlier attempt can't flip the flag for a later one.
  1457. # The event is set in `_download`'s finally block so the post-timeout
  1458. # path can wait for genuine thread completion instead of a fixed sleep.
  1459. class _CombinedCancelEvent:
  1460. def __init__(self, attempt_event: threading.Event):
  1461. self._attempt_event = attempt_event
  1462. def is_set(self) -> bool:
  1463. return self._attempt_event.is_set() or (cancel_event is not None and cancel_event.is_set())
  1464. def _download(
  1465. force_prot_c: bool,
  1466. completion: dict,
  1467. done: threading.Event,
  1468. attempt_cancel: threading.Event,
  1469. ) -> bool:
  1470. mode_str = "prot_c" if force_prot_c else "prot_p"
  1471. try:
  1472. combined_cancel = _CombinedCancelEvent(attempt_cancel)
  1473. if combined_cancel.is_set():
  1474. raise DownloadCancelled(remote_path)
  1475. client = BambuFTPClient(
  1476. ip_address,
  1477. access_code,
  1478. timeout=socket_timeout,
  1479. printer_model=printer_model,
  1480. force_prot_c=force_prot_c,
  1481. )
  1482. if client.connect():
  1483. try:
  1484. result = client.download_to_file(
  1485. remote_path,
  1486. local_path,
  1487. expected_size=expected_size,
  1488. max_bytes=max_bytes,
  1489. cancel_event=combined_cancel,
  1490. min_free_bytes=min_free_bytes,
  1491. size_callback=lambda n: completion.__setitem__("size", n),
  1492. )
  1493. if result:
  1494. BambuFTPClient.cache_mode(ip_address, mode_str)
  1495. completion["success"] = True
  1496. return result
  1497. finally:
  1498. client.disconnect()
  1499. return False
  1500. finally:
  1501. done.set()
  1502. async def _run(force_prot_c: bool) -> bool:
  1503. completion = {"success": False}
  1504. done = threading.Event()
  1505. attempt_cancel = threading.Event()
  1506. worker = loop.run_in_executor(_ftp_executor, _download, force_prot_c, completion, done, attempt_cancel)
  1507. # What this attempt was actually allowed, for the log lines below: the
  1508. # size-derived extension moves it after the fact.
  1509. allowed = timeout
  1510. extended = False
  1511. try:
  1512. try:
  1513. return await asyncio.wait_for(asyncio.shield(worker), timeout=timeout)
  1514. except TimeoutError:
  1515. # The deadline was set before anyone knew the file's size. Now
  1516. # the printer has told us, so give a transfer that is genuinely
  1517. # under way the time that size needs (#2957). Re-raises into the
  1518. # handler below when the size is unknown or already covered.
  1519. extension = _download_extension(completion.get("size"), timeout)
  1520. if extension <= 0:
  1521. raise
  1522. logger.info(
  1523. "FTP download of %s passed its %ss deadline but the printer reports %s bytes — "
  1524. "allowing %.0fs more rather than declaring a slow transfer dead (#2957)",
  1525. remote_path,
  1526. timeout,
  1527. completion.get("size"),
  1528. extension,
  1529. )
  1530. allowed = timeout + extension
  1531. extended = True
  1532. return await asyncio.wait_for(asyncio.shield(worker), timeout=extension)
  1533. except asyncio.CancelledError:
  1534. # Cancelling an asyncio Future cannot stop its executor thread. Set
  1535. # the callback-visible flag and do not let the caller unlink the
  1536. # staging file until the worker has genuinely unwound.
  1537. attempt_cancel.set()
  1538. try:
  1539. await asyncio.shield(worker)
  1540. except (DownloadCancelled, OSError, ftplib.Error):
  1541. pass
  1542. raise
  1543. except TimeoutError:
  1544. # Slow WiFi links commonly overshoot ftp_timeout by 10–30 s without
  1545. # actually being stuck, so starting attempt 2 now would just contend
  1546. # with the still-progressing RETR on attempt 1 and produce the
  1547. # zombie-write race reported in #1014 (file landed on disk minutes
  1548. # after the retry loop had already given up). Wait for the worker
  1549. # thread to genuinely finish — capped at 30 s so a truly stuck
  1550. # connection can't stall a whole attempt indefinitely, with a 0.5 s
  1551. # floor so artificially small test timeouts still give zombies a
  1552. # realistic window to finish.
  1553. grace = max(min(timeout, 30.0), 0.5)
  1554. # Deliberately the DEFAULT executor, not `_ftp_executor`: this thread
  1555. # blocks waiting on `_download`, which is itself an `_ftp_executor`
  1556. # worker. Parking waiters in the same bounded pool as the workers they
  1557. # wait for is how you build a deadlock — with enough concurrent
  1558. # timeouts the waiters would occupy every slot and the downloads they
  1559. # are waiting for could never be scheduled.
  1560. attempt_cancel.set()
  1561. await loop.run_in_executor(None, done.wait, grace)
  1562. # Wait for the thread either way. If the grace period was enough it
  1563. # returns at once; if it was not, the blocking socket still has to
  1564. # reach its own timeout, and returning before it does would let the
  1565. # caller unlink a file the executor is still writing.
  1566. try:
  1567. await asyncio.shield(worker)
  1568. except (DownloadCancelled, OSError, ftplib.Error):
  1569. pass
  1570. if completion["success"] and local_path.exists() and local_path.stat().st_size > 0:
  1571. logger.info(
  1572. "FTP download wait_for timed out after %ss for %s, but thread completed within %ss grace (%s bytes) — salvaging",
  1573. allowed,
  1574. remote_path,
  1575. grace,
  1576. local_path.stat().st_size,
  1577. )
  1578. return True
  1579. if extended:
  1580. # The transfer had already been given the time its own reported
  1581. # size needs. Retrying spends that again to learn the same
  1582. # thing, so say so rather than reporting an ordinary miss.
  1583. logger.warning(
  1584. "FTP download of %s did not finish inside the %ss its size bought it (plus %ss grace)",
  1585. remote_path,
  1586. allowed,
  1587. grace,
  1588. )
  1589. raise DownloadDeadlineExceeded(remote_path)
  1590. logger.warning(
  1591. "FTP download timed out after %ss (plus %ss grace) for %s",
  1592. allowed,
  1593. grace,
  1594. remote_path,
  1595. )
  1596. return False
  1597. # Check if we have a cached mode for this printer
  1598. cached_mode = BambuFTPClient._mode_cache.get(ip_address)
  1599. # The gate spans the prot_c fallback too: those are two attempts at one
  1600. # transfer, and letting go between them would hand the printer to a waiter
  1601. # mid-download (#2957).
  1602. async with _serialized_download(ip_address, f"a download of {remote_path}", enabled=serialize):
  1603. if cached_mode:
  1604. force_prot_c = cached_mode == "prot_c"
  1605. return await _run(force_prot_c)
  1606. # No cached mode - try prot_p first
  1607. if await _run(False):
  1608. return True
  1609. # Download failed - for A1 models, try prot_c fallback
  1610. if is_a1:
  1611. logger.info("FTP download failed with prot_p for A1 model, trying prot_c fallback...")
  1612. return await _run(True)
  1613. return False
  1614. async def download_file_try_paths_async(
  1615. ip_address: str,
  1616. access_code: str,
  1617. remote_paths: list[str],
  1618. local_path: Path,
  1619. socket_timeout: float | None = None,
  1620. printer_model: str | None = None,
  1621. timeout: float = 90.0,
  1622. ) -> str | None:
  1623. """Try downloading a file from multiple paths using a single connection.
  1624. Returns the path that served the file, or ``None``. The path rather than a
  1625. bare flag because the caller usually cannot tell afterwards which candidate
  1626. hit, and on a printer that keeps uploads around for weeks that is the
  1627. difference between a diagnosable stale-copy match and an invisible one
  1628. (#1820). Callers testing it for truth are unaffected: a served path is
  1629. always a non-empty string.
  1630. Args:
  1631. socket_timeout: FTP socket timeout for slow connections (e.g., A1 printers)
  1632. printer_model: Printer model for A1-specific workarounds
  1633. timeout: overall async cap. The per-socket timeout only bounds an
  1634. in-flight worker; it does NOT bound how long this coroutine waits
  1635. for a free slot in the fixed-size ``_ftp_executor``. On a large
  1636. farm where offline printers keep every worker busy on dead
  1637. connects, that queue wait is otherwise unbounded — and any caller
  1638. holding a DB connection while awaiting this would pin it until the
  1639. pool is exhausted (#2572). The cap converts that into a bounded
  1640. wait; the worker is then cancelled and waited out rather than
  1641. orphaned (#2957), so a DB-holding caller's worst case is the gate
  1642. wait plus this cap plus one unwind -- still bounded, and the
  1643. orphaned worker no longer keeps the printer's socket after it.
  1644. """
  1645. loop = asyncio.get_event_loop()
  1646. # An executor thread cannot be cancelled, so the cap alone used to leave a
  1647. # worker walking the remaining paths -- still holding the printer's FTP
  1648. # socket -- long after this coroutine had given up on it. A reporter's log
  1649. # shows one of those still going as the archive flow's own download landed,
  1650. # two Bambuddy transfers deep into a P1S that was mid-print (#2957). The
  1651. # flag stops it at the next chunk instead.
  1652. cancel = threading.Event()
  1653. done = threading.Event()
  1654. def _download():
  1655. try:
  1656. client = BambuFTPClient(ip_address, access_code, timeout=socket_timeout, printer_model=printer_model)
  1657. if not client.connect():
  1658. return None
  1659. try:
  1660. # FileNotOnPrinterError signals "try the next path", not "give up" —
  1661. # this function's whole purpose is to walk a list of candidates
  1662. # over one connection. Only a real transport error should bubble.
  1663. for remote_path in remote_paths:
  1664. if cancel.is_set():
  1665. return None
  1666. try:
  1667. if client.download_to_file(remote_path, local_path, cancel_event=cancel):
  1668. return remote_path
  1669. except FileNotOnPrinterError:
  1670. continue
  1671. except DownloadCancelled:
  1672. return None
  1673. return None
  1674. finally:
  1675. client.disconnect()
  1676. finally:
  1677. done.set()
  1678. async with _serialized_download(ip_address, f"a {len(remote_paths)}-path lookup"):
  1679. worker = loop.run_in_executor(_ftp_executor, _download)
  1680. try:
  1681. return await asyncio.wait_for(asyncio.shield(worker), timeout=timeout)
  1682. except asyncio.CancelledError:
  1683. # The caller is going away and should not be made to wait, but the
  1684. # worker must not keep the printer to itself either.
  1685. cancel.set()
  1686. _discard_worker_outcome(worker)
  1687. raise
  1688. except TimeoutError:
  1689. logger.warning("FTP download_try_paths exceeded its %ss cap for %s (#2572)", timeout, ip_address)
  1690. cancel.set()
  1691. # Do not hand the printer to the next download while this worker is
  1692. # still on its socket. The DEFAULT executor, never ``_ftp_executor``:
  1693. # parking a waiter in the same bounded pool as the worker it waits
  1694. # for is how a deadlock gets built.
  1695. await loop.run_in_executor(None, done.wait, _DOWNLOAD_UNWIND_SECONDS)
  1696. _discard_worker_outcome(worker)
  1697. return None
  1698. def _upload_deadline(local_path: Path) -> float:
  1699. """Derive an upload deadline from the file size (#2529).
  1700. See ``_UPLOAD_FLOOR_BYTES_PER_SEC``. An unstat-able file falls back to the
  1701. floor timeout — ``upload_file`` will fail on the open() anyway.
  1702. """
  1703. try:
  1704. size = local_path.stat().st_size
  1705. except OSError:
  1706. return _UPLOAD_MIN_TIMEOUT
  1707. return max(_UPLOAD_MIN_TIMEOUT, size / _UPLOAD_FLOOR_BYTES_PER_SEC)
  1708. # One upload at a time per printer. Two concurrent STOR commands for the same
  1709. # remote path leave a corrupt file on the SD card, and the printer reads as
  1710. # flaky rather than busy (#2529). Held for the duration of a transfer, so a
  1711. # second dispatch to the same printer queues behind the first instead of racing
  1712. # it. Keyed per event loop: an asyncio.Lock binds to the loop that first awaits
  1713. # it, and the test suite runs each case on a fresh loop.
  1714. _upload_locks: weakref.WeakKeyDictionary[asyncio.AbstractEventLoop, dict[str, asyncio.Lock]] = (
  1715. weakref.WeakKeyDictionary()
  1716. )
  1717. def _upload_lock(loop: asyncio.AbstractEventLoop, ip_address: str) -> asyncio.Lock:
  1718. per_loop = _upload_locks.setdefault(loop, {})
  1719. lock = per_loop.get(ip_address)
  1720. if lock is None:
  1721. lock = asyncio.Lock()
  1722. per_loop[ip_address] = lock
  1723. return lock
  1724. async def upload_file_async(
  1725. ip_address: str,
  1726. access_code: str,
  1727. local_path: Path,
  1728. remote_path: str,
  1729. timeout: float | None = None,
  1730. progress_callback: Callable[[int, int], None] | None = None,
  1731. socket_timeout: float | None = None,
  1732. printer_model: str | None = None,
  1733. respect_handshake_cooloff: bool = True,
  1734. failure: FtpFailureReport | None = None,
  1735. ) -> bool:
  1736. """Async wrapper for uploading a file with timeout and progress callback.
  1737. For A1/A1 Mini printers, automatically tries prot_p first, then falls back
  1738. to prot_c if the upload fails. The working mode is cached for future uploads.
  1739. Args:
  1740. ip_address: Printer IP address
  1741. access_code: Printer access code
  1742. local_path: Local file path to upload
  1743. remote_path: Remote path on printer
  1744. timeout: Overall deadline. ``None`` (the default) derives it from the
  1745. file size — see ``_upload_deadline``. A caller that passes a number
  1746. gets exactly that, which is what the tests rely on.
  1747. progress_callback: Optional callback for progress updates
  1748. socket_timeout: FTP socket timeout for slow connections (e.g., A1 printers)
  1749. printer_model: Printer model for A1-specific workarounds
  1750. respect_handshake_cooloff: see ``BambuFTPClient.__init__``. False for a
  1751. user-initiated upload, whose attempts are bounded and were being
  1752. spent against a cool-off that outlives them (#2898).
  1753. failure: caller-owned slot filled in with why the upload failed, so the
  1754. caller can say something true about it instead of guessing (#2899).
  1755. Passed through ``with_ftp_retry`` unchanged, so it ends up holding
  1756. the last attempt's reason -- which is the one that decided the
  1757. outcome.
  1758. """
  1759. loop = asyncio.get_event_loop()
  1760. is_a1 = printer_model in BambuFTPClient.A1_MODELS if printer_model else False
  1761. deadline = _upload_deadline(local_path) if timeout is None else timeout
  1762. # Set when the deadline expires. The worker checks it once per chunk.
  1763. cancel = threading.Event()
  1764. def _guarded_progress(uploaded: int, total: int) -> None:
  1765. if cancel.is_set():
  1766. raise UploadCancelled(f"upload of {remote_path} exceeded its {deadline:.0f}s deadline")
  1767. if progress_callback:
  1768. progress_callback(uploaded, total)
  1769. def _upload(force_prot_c: bool = False) -> bool:
  1770. mode_str = "prot_c" if force_prot_c else "prot_p"
  1771. logger.info(
  1772. f"FTP connecting to {ip_address} for upload (model={printer_model}, "
  1773. f"mode={mode_str}, socket_timeout={socket_timeout}s, deadline={deadline:.0f}s)..."
  1774. )
  1775. client = BambuFTPClient(
  1776. ip_address,
  1777. access_code,
  1778. timeout=socket_timeout,
  1779. printer_model=printer_model,
  1780. force_prot_c=force_prot_c,
  1781. respect_handshake_cooloff=respect_handshake_cooloff,
  1782. )
  1783. try:
  1784. if client.connect():
  1785. logger.info("FTP connected to %s", ip_address)
  1786. try:
  1787. result = client.upload_file(local_path, remote_path, _guarded_progress)
  1788. if result:
  1789. # Cache the working mode
  1790. BambuFTPClient.cache_mode(ip_address, mode_str)
  1791. return result
  1792. finally:
  1793. client.disconnect()
  1794. logger.warning("FTP connection failed to %s", ip_address)
  1795. return False
  1796. finally:
  1797. # In a finally so a transfer that leaves by raising -- a cancelled
  1798. # upload, a re-raised STOR rejection -- still reports what the
  1799. # client recorded on its way out.
  1800. if failure is not None and client.last_failure is not None:
  1801. failure.failure = client.last_failure
  1802. async def _attempt(force_prot_c: bool) -> bool:
  1803. """Run one upload attempt, and make a timeout actually stop the transfer.
  1804. ``asyncio.wait_for`` cancels the *future*, never the executor thread
  1805. behind it. Before #2529 a slow-but-healthy upload that overran the
  1806. deadline left that thread streaming: it kept pushing bytes, kept firing
  1807. the progress callback, and the retry above put a *second* STOR of the
  1808. same file onto the same printer. The reporter's 96 MB job ran four
  1809. concurrent transfers and never landed. So on timeout we signal the
  1810. worker (it raises ``UploadCancelled`` from the progress callback, which
  1811. breaks the send loop and deletes the partial file) and wait for it to
  1812. actually go.
  1813. """
  1814. fut = loop.run_in_executor(_ftp_executor, lambda: _upload(force_prot_c))
  1815. try:
  1816. return await asyncio.wait_for(asyncio.shield(fut), timeout=deadline)
  1817. except TimeoutError:
  1818. cancel.set()
  1819. logger.warning(
  1820. "FTP upload of %s exceeded its %.0fs deadline — cancelling the transfer",
  1821. remote_path,
  1822. deadline,
  1823. )
  1824. try:
  1825. await asyncio.wait_for(asyncio.shield(fut), timeout=_UPLOAD_CANCEL_GRACE)
  1826. except UploadCancelled:
  1827. logger.info("FTP upload of %s cancelled; partial file removed from the printer", remote_path)
  1828. except TimeoutError:
  1829. # The thread is wedged somewhere that never reaches the callback
  1830. # (a blocked sendall, say). Nothing more we can do from here —
  1831. # but consume the eventual result so asyncio doesn't log the
  1832. # future's exception as unretrieved when it is garbage-collected.
  1833. logger.error(
  1834. "FTP upload thread for %s did not stop within %.0fs of the cancel signal",
  1835. remote_path,
  1836. _UPLOAD_CANCEL_GRACE,
  1837. )
  1838. fut.add_done_callback(_swallow_future_result)
  1839. except Exception as e:
  1840. logger.warning("FTP upload of %s errored while cancelling: %s", remote_path, e)
  1841. # Raise rather than return False: a deadline expiry means the link
  1842. # sustained less than the floor rate for the whole transfer, and a
  1843. # retry would only spend another full deadline finding that out
  1844. # again — with check_queue serialized, four of those block the
  1845. # entire print queue for hours. ``with_ftp_retry`` never retries it.
  1846. raise UploadCancelled(
  1847. f"Upload of {remote_path} to {ip_address} exceeded its {deadline:.0f}s deadline "
  1848. f"(link sustained less than {_UPLOAD_FLOOR_BYTES_PER_SEC // 1024} KB/s)"
  1849. ) from None
  1850. async with _upload_lock(loop, ip_address):
  1851. # Check if we have a cached mode for this printer
  1852. cached_mode = BambuFTPClient._mode_cache.get(ip_address)
  1853. if cached_mode:
  1854. # Use cached mode
  1855. return await _attempt(cached_mode == "prot_c")
  1856. # No cached mode - try prot_p first
  1857. if await _attempt(False):
  1858. return True
  1859. # Upload failed - for A1 models, try prot_c fallback
  1860. if is_a1:
  1861. logger.info("FTP upload failed with prot_p for A1 model, trying prot_c fallback...")
  1862. return await _attempt(True)
  1863. return False
  1864. def _swallow_future_result(fut: asyncio.Future) -> None:
  1865. """Retrieve a future's exception so asyncio doesn't log it as unhandled."""
  1866. if not fut.cancelled():
  1867. fut.exception()
  1868. async def list_files_async(
  1869. ip_address: str,
  1870. access_code: str,
  1871. path: str = "/",
  1872. timeout: float = 30.0,
  1873. socket_timeout: float | None = None,
  1874. printer_model: str | None = None,
  1875. ) -> list[dict]:
  1876. """Async wrapper for listing files with timeout.
  1877. Args:
  1878. socket_timeout: FTP socket timeout for slow connections (e.g., A1 printers)
  1879. printer_model: Printer model for A1-specific workarounds
  1880. """
  1881. loop = asyncio.get_event_loop()
  1882. def _list():
  1883. client = BambuFTPClient(ip_address, access_code, timeout=socket_timeout, printer_model=printer_model)
  1884. if client.connect():
  1885. try:
  1886. return client.list_files(path)
  1887. finally:
  1888. client.disconnect()
  1889. return []
  1890. try:
  1891. return await asyncio.wait_for(loop.run_in_executor(_ftp_executor, _list), timeout=timeout)
  1892. except TimeoutError:
  1893. logger.warning("FTP list_files timed out after %ss for %s", timeout, path)
  1894. return []
  1895. async def list_files_result_async(
  1896. ip_address: str,
  1897. access_code: str,
  1898. path: str = "/",
  1899. timeout: float = 30.0,
  1900. socket_timeout: float | None = None,
  1901. printer_model: str | None = None,
  1902. ) -> FileListResult:
  1903. """List a directory without collapsing transport failure into empty."""
  1904. loop = asyncio.get_event_loop()
  1905. def _list() -> FileListResult:
  1906. client = BambuFTPClient(ip_address, access_code, timeout=socket_timeout, printer_model=printer_model)
  1907. if not client.connect():
  1908. return FileListResult(files=[], available=False)
  1909. try:
  1910. return FileListResult(files=client.list_files(path, raise_on_error=True), available=True)
  1911. except (OSError, ftplib.Error):
  1912. return FileListResult(files=[], available=False)
  1913. finally:
  1914. client.disconnect()
  1915. try:
  1916. return await asyncio.wait_for(loop.run_in_executor(_ftp_executor, _list), timeout=timeout)
  1917. except TimeoutError:
  1918. logger.warning("FTP list_files timed out after %ss for %s", timeout, path)
  1919. return FileListResult(files=[], available=False)
  1920. async def find_remote_file_async(
  1921. ip_address: str,
  1922. access_code: str,
  1923. remote_paths: list[str],
  1924. timeout: float = 30.0,
  1925. socket_timeout: float | None = None,
  1926. printer_model: str | None = None,
  1927. ) -> str | None:
  1928. """First of *remote_paths* the printer actually has, or None.
  1929. Answers "is this file there?" without fetching it, over a single
  1930. connection: one listing per distinct directory, reused across the
  1931. candidates that share it, and stops at the first hit. Written for the
  1932. connection diagnostic (#2856), which needs the answer for a file that can
  1933. be tens of megabytes and has no use for its contents.
  1934. Listing rather than ``SIZE``: LIST is what every Bambu firmware here is
  1935. known to answer, and a ``SIZE`` the server simply does not implement would
  1936. read as "the file is missing".
  1937. """
  1938. loop = asyncio.get_event_loop()
  1939. def _find() -> str | None:
  1940. client = BambuFTPClient(ip_address, access_code, timeout=socket_timeout, printer_model=printer_model)
  1941. if not client.connect():
  1942. return None
  1943. try:
  1944. listed: dict[str, set[str]] = {}
  1945. for remote_path in remote_paths:
  1946. directory, _, name = remote_path.rpartition("/")
  1947. directory = directory or "/"
  1948. if directory not in listed:
  1949. listed[directory] = {
  1950. entry.get("name") for entry in client.list_files(directory) if not entry.get("is_directory")
  1951. }
  1952. if name in listed[directory]:
  1953. return remote_path
  1954. return None
  1955. finally:
  1956. client.disconnect()
  1957. try:
  1958. return await asyncio.wait_for(loop.run_in_executor(_ftp_executor, _find), timeout=timeout)
  1959. except TimeoutError:
  1960. logger.warning("FTP find_remote_file timed out after %ss on %s", timeout, ip_address)
  1961. return None
  1962. async def delete_file_async(
  1963. ip_address: str,
  1964. access_code: str,
  1965. remote_path: str,
  1966. socket_timeout: float | None = None,
  1967. printer_model: str | None = None,
  1968. timeout: float = 60.0,
  1969. respect_handshake_cooloff: bool = True,
  1970. ) -> DeleteResult:
  1971. """Async wrapper for deleting a file.
  1972. Returns :class:`DeleteResult` so callers can distinguish ``NOT_FOUND``
  1973. (550 — file isn't on the printer, no retry value) from ``FAILED``
  1974. (network / auth / transient — worth retrying or surfacing).
  1975. Args:
  1976. socket_timeout: FTP socket timeout for slow connections (e.g., A1 printers)
  1977. printer_model: Printer model for A1-specific workarounds
  1978. timeout: overall async cap so a saturated ``_ftp_executor`` can't pin
  1979. the caller (and any DB connection it holds) indefinitely (#2572).
  1980. respect_handshake_cooloff: see ``BambuFTPClient.__init__``. The delete
  1981. that clears the way for a dispatch shares the upload's exemption --
  1982. it is one connection, and in #2898's trace it is the one that armed
  1983. the cool-off the upload then spent all four attempts against.
  1984. """
  1985. loop = asyncio.get_event_loop()
  1986. def _delete() -> DeleteResult:
  1987. client = BambuFTPClient(
  1988. ip_address,
  1989. access_code,
  1990. timeout=socket_timeout,
  1991. printer_model=printer_model,
  1992. respect_handshake_cooloff=respect_handshake_cooloff,
  1993. )
  1994. if client.connect():
  1995. try:
  1996. return client.delete_file(remote_path)
  1997. finally:
  1998. client.disconnect()
  1999. return DeleteResult.FAILED
  2000. try:
  2001. return await asyncio.wait_for(loop.run_in_executor(_ftp_executor, _delete), timeout=timeout)
  2002. except TimeoutError:
  2003. logger.warning("FTP delete_file exceeded its %ss cap for %s (#2572)", timeout, ip_address)
  2004. return DeleteResult.FAILED
  2005. async def download_file_bytes_async(
  2006. ip_address: str,
  2007. access_code: str,
  2008. remote_path: str,
  2009. socket_timeout: float | None = None,
  2010. printer_model: str | None = None,
  2011. timeout: float = 300.0,
  2012. expected_size: int | None = None,
  2013. ) -> bytes | None:
  2014. """Async wrapper for downloading file as bytes.
  2015. Args:
  2016. socket_timeout: FTP socket timeout for slow connections (e.g., A1 printers)
  2017. printer_model: Printer model for A1-specific workarounds
  2018. timeout: overall async cap so a saturated ``_ftp_executor`` can't pin
  2019. the caller (and any DB connection it holds) indefinitely (#2572).
  2020. Generous by default because this pulls whole files (timelapse
  2021. video, gcode) which can legitimately take minutes over slow Wi-Fi —
  2022. the cap only guards against a permanently-starved pool, not a
  2023. slow-but-progressing transfer.
  2024. expected_size: size from the directory listing; a mismatch fails the
  2025. download instead of returning a truncated file. See
  2026. :meth:`BambuFTPClient.download_file`.
  2027. """
  2028. loop = asyncio.get_event_loop()
  2029. def _download():
  2030. client = BambuFTPClient(ip_address, access_code, timeout=socket_timeout, printer_model=printer_model)
  2031. if client.connect():
  2032. try:
  2033. return client.download_file(remote_path, expected_size=expected_size)
  2034. finally:
  2035. client.disconnect()
  2036. return None
  2037. try:
  2038. return await asyncio.wait_for(loop.run_in_executor(_ftp_executor, _download), timeout=timeout)
  2039. except TimeoutError:
  2040. logger.warning("FTP download_bytes exceeded its %ss cap for %s (#2572)", timeout, ip_address)
  2041. return None
  2042. async def remote_file_settled(
  2043. ip_address: str,
  2044. access_code: str,
  2045. remote_path: str,
  2046. downloaded_bytes: int,
  2047. *,
  2048. printer_model: str | None = None,
  2049. ) -> bool:
  2050. """Confirm the printer has finished writing the file we just downloaded.
  2051. Matching the download against the size from the directory listing proves we
  2052. received what the listing *said*, not that the file was *finished*. The
  2053. timelapse scan's first look happens seconds after the print ends, which is
  2054. exactly when the printer is writing the video — so a file still growing can
  2055. be listed at a partial size, served at that size, and pass the length check
  2056. as a complete video (#2704).
  2057. That was survivable while the printer kept its copy. It isn't now that a
  2058. successful attach deletes the source, so re-list afterwards: if the file has
  2059. grown, what we hold is a prefix and the caller should discard it and try
  2060. again on the next round.
  2061. Returns True when the remote file can no longer differ from what we hold —
  2062. the size still matches, or the file is gone from the listing entirely and
  2063. so cannot grow any further. Returns False when it has changed size, and on
  2064. a listing failure, because "we could not check" must not read as "safe to
  2065. delete".
  2066. """
  2067. directory, _, name = remote_path.rpartition("/")
  2068. files = await list_files_async(ip_address, access_code, directory or "/", printer_model=printer_model)
  2069. if not files:
  2070. logger.warning("[TIMELAPSE] Could not re-list %s to confirm %s is complete", directory or "/", name)
  2071. return False
  2072. for f in files:
  2073. if f.get("name") == name:
  2074. size = f.get("size")
  2075. if size == downloaded_bytes:
  2076. return True
  2077. logger.info(
  2078. "[TIMELAPSE] %s is still being written (%s bytes now, %s when downloaded) — will retry",
  2079. name,
  2080. size,
  2081. downloaded_bytes,
  2082. )
  2083. return False
  2084. # Vanished between the download and now. Nothing left that could grow, and
  2085. # nothing left to delete either.
  2086. logger.debug("[TIMELAPSE] %s is no longer on the printer after download", name)
  2087. return True
  2088. async def delete_archived_timelapse(
  2089. ip_address: str,
  2090. access_code: str,
  2091. remote_path: str,
  2092. *,
  2093. verified: bool,
  2094. printer_model: str | None = None,
  2095. printer_name: str = "",
  2096. ) -> bool:
  2097. """Remove a timelapse from the printer once it is safely in the archive.
  2098. Call this only after the attach succeeded (#2704). Keeping ``/timelapse``
  2099. down to just the unclaimed videos is what makes the snapshot diff
  2100. unambiguous rather than merely usually-right, and it stops P1S cards
  2101. filling with AVIs.
  2102. ``verified`` must say whether the downloaded byte count was checked against
  2103. the size the directory listing reported. It is required rather than
  2104. defaulted because this is the one irreversible step in the flow: an FTPS
  2105. data connection that closes early does not always raise, so an unverified
  2106. transfer can be a partial file that looks complete, and deleting the source
  2107. would then destroy the only good copy. The check lives here rather than at
  2108. each call site so no future caller can omit it.
  2109. Best-effort otherwise: a printer that refuses the delete keeps its copy, the
  2110. diff still excludes that filename next time because it is attached to an
  2111. archive, and nothing else in the flow cares. Returns True only on an actual
  2112. delete or a 550 (already gone).
  2113. """
  2114. if not verified:
  2115. logger.warning(
  2116. "[TIMELAPSE] Not deleting %s from printer %s: the download was never size-checked",
  2117. remote_path,
  2118. printer_name,
  2119. )
  2120. return False
  2121. for attempt in range(1, 4):
  2122. try:
  2123. result = await delete_file_async(ip_address, access_code, remote_path, printer_model=printer_model)
  2124. except Exception as e:
  2125. result = DeleteResult.FAILED
  2126. logger.warning("[TIMELAPSE] Delete attempt %d/3 raised for %s: %s", attempt, remote_path, e)
  2127. if result == DeleteResult.DELETED:
  2128. logger.info("[TIMELAPSE] Deleted %s from printer %s after archiving", remote_path, printer_name)
  2129. return True
  2130. if result == DeleteResult.NOT_FOUND:
  2131. # 550 never recovers by waiting — the printer already cleaned up.
  2132. logger.debug("[TIMELAPSE] %s already gone from printer %s", remote_path, printer_name)
  2133. return True
  2134. if attempt < 3:
  2135. await asyncio.sleep(2)
  2136. logger.warning(
  2137. "[TIMELAPSE] Could not delete %s from printer %s (it stays on the card; the archive copy is unaffected)",
  2138. remote_path,
  2139. printer_name,
  2140. )
  2141. return False
  2142. async def get_storage_info_async(
  2143. ip_address: str,
  2144. access_code: str,
  2145. socket_timeout: float | None = None,
  2146. printer_model: str | None = None,
  2147. timeout: float = 60.0,
  2148. ) -> dict | None:
  2149. """Async wrapper for getting storage info.
  2150. Args:
  2151. socket_timeout: FTP socket timeout for slow connections (e.g., A1 printers)
  2152. printer_model: Printer model for A1-specific workarounds
  2153. timeout: overall async cap so a saturated ``_ftp_executor`` can't pin
  2154. the caller (and any DB connection it holds) indefinitely (#2572).
  2155. """
  2156. loop = asyncio.get_event_loop()
  2157. def _get_storage():
  2158. client = BambuFTPClient(ip_address, access_code, timeout=socket_timeout, printer_model=printer_model)
  2159. if client.connect():
  2160. try:
  2161. return client.get_storage_info()
  2162. finally:
  2163. client.disconnect()
  2164. return None
  2165. try:
  2166. return await asyncio.wait_for(loop.run_in_executor(_ftp_executor, _get_storage), timeout=timeout)
  2167. except TimeoutError:
  2168. logger.warning("FTP get_storage_info exceeded its %ss cap for %s (#2572)", timeout, ip_address)
  2169. return None
  2170. async def get_ftp_retry_settings() -> tuple[bool, int, float, float]:
  2171. """Get FTP retry settings from database.
  2172. Returns:
  2173. Tuple of (retry_enabled, retry_count, retry_delay, timeout)
  2174. """
  2175. from backend.app.api.routes.settings import get_setting
  2176. from backend.app.core.database import async_session
  2177. async with async_session() as db:
  2178. enabled = (await get_setting(db, "ftp_retry_enabled") or "true") == "true"
  2179. count = int(await get_setting(db, "ftp_retry_count") or "3")
  2180. delay = float(await get_setting(db, "ftp_retry_delay") or "2")
  2181. timeout = float(await get_setting(db, "ftp_timeout") or "30")
  2182. return enabled, count, delay, timeout
  2183. async def with_ftp_retry(
  2184. operation: Callable[..., Awaitable[T]],
  2185. *args,
  2186. max_retries: int = 3,
  2187. retry_delay: float = 2.0,
  2188. operation_name: str = "FTP operation",
  2189. non_retry_exceptions: tuple[type[BaseException], ...] = (),
  2190. cooloff_ip: str | None = None,
  2191. **kwargs,
  2192. ) -> T | None:
  2193. """Execute FTP operation with retry logic.
  2194. Args:
  2195. operation: Async function to execute
  2196. *args: Positional arguments for the operation
  2197. max_retries: Number of retry attempts (default: 3)
  2198. retry_delay: Seconds to wait between retries (default: 2.0)
  2199. operation_name: Name for logging purposes
  2200. non_retry_exceptions: Exception types that should immediately abort retries
  2201. cooloff_ip: printer IP whose FTPS handshake cool-off should end the loop
  2202. early. Pass it from any caller that respects the cool-off; leave it
  2203. unset for one that opted out, or the loop would stop on a gate its
  2204. own attempts are ignoring (#2898).
  2205. **kwargs: Keyword arguments for the operation
  2206. Returns:
  2207. Result of the operation, or None if all attempts fail
  2208. ``UploadCancelled`` is never retried, whatever the caller passes: it means
  2209. the transfer overran its size-derived deadline, so a retry would spend
  2210. another full deadline reaching the same conclusion (#2529).
  2211. ``DownloadDeadlineExceeded`` is the same thing in the other direction
  2212. (#2957) and is treated the same way.
  2213. """
  2214. last_error = None
  2215. attempts_made = 0
  2216. for attempt in range(max_retries + 1):
  2217. attempts_made = attempt + 1
  2218. try:
  2219. result = await operation(*args, **kwargs)
  2220. # Check for "falsy" success indicators
  2221. if result not in (False, None, []):
  2222. if attempt > 0:
  2223. logger.info("%s succeeded on attempt %s/%s", operation_name, attempt + 1, max_retries + 1)
  2224. return result
  2225. # Operation returned failure indicator
  2226. if attempt > 0:
  2227. logger.info("%s attempt %s/%s returned failure", operation_name, attempt + 1, max_retries + 1)
  2228. except (UploadCancelled, DownloadDeadlineExceeded):
  2229. raise
  2230. except Exception as e:
  2231. if non_retry_exceptions and isinstance(e, non_retry_exceptions):
  2232. raise
  2233. last_error = e
  2234. logger.warning("%s attempt %s/%s failed: %s", operation_name, attempt + 1, max_retries + 1, e)
  2235. # Don't wait after the last attempt
  2236. if attempt < max_retries:
  2237. # A cool-off outlasts this loop by two orders of magnitude, so once
  2238. # it is armed every remaining attempt returns False without opening
  2239. # a socket. Spending them anyway bought nothing and cost the caller
  2240. # `max_retries * retry_delay` seconds of sleeping, then reported the
  2241. # failure with the wrong reason (#2898).
  2242. if cooloff_ip and ftps_handshake_blocked(cooloff_ip):
  2243. logger.warning(
  2244. "%s: stopping after attempt %s/%s — %s is inside its FTPS handshake cool-off, "
  2245. "so the remaining attempts would not reach it",
  2246. operation_name,
  2247. attempt + 1,
  2248. max_retries + 1,
  2249. cooloff_ip,
  2250. )
  2251. break
  2252. logger.info("%s will retry in %ss...", operation_name, retry_delay)
  2253. await asyncio.sleep(retry_delay)
  2254. # attempts_made, not max_retries + 1: the loop can stop early on a cool-off,
  2255. # and reporting attempts that were never made is how #2898 read as a network
  2256. # problem when nothing had gone near the network.
  2257. logger.error("%s failed after %s attempts", operation_name, attempts_made)
  2258. if last_error:
  2259. logger.debug("Last error: %s", last_error)
  2260. return None