bambu_ftp.py 126 KB

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