bambu_ftp.py 120 KB

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