bambu_ftp.py 121 KB

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