bambu_ftp.py 125 KB

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