test_bambu_ftp.py 77 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920
  1. """Comprehensive FTP test suite for BambuFTPClient.
  2. Tests against a real mock implicit FTPS server, covering:
  3. - Connection (auth, SSL modes, timeout, caching)
  4. - File listing
  5. - Download (bytes, to_file, 0-byte regression)
  6. - Upload (chunked transfer, progress, error codes)
  7. - Delete
  8. - File size
  9. - Storage info (AVBL, directory scan, diagnose_storage)
  10. - Model-specific behavior (X1C prot_p, A1 prot_c fallback)
  11. - Async wrappers
  12. - Failure injection scenarios (regressions for 0.1.8 bugs)
  13. """
  14. import asyncio
  15. import logging
  16. import socket
  17. import threading
  18. import time
  19. from pathlib import Path
  20. import pytest
  21. from backend.app.services import bambu_ftp
  22. from backend.app.services.bambu_ftp import (
  23. BambuFTPClient,
  24. FileNotOnPrinterError,
  25. cache_3mf_download,
  26. clear_3mf_cache,
  27. delete_file_async,
  28. download_file_async,
  29. download_file_try_paths_async,
  30. get_cached_3mf,
  31. list_files_async,
  32. normalize_3mf_name,
  33. upload_file_async,
  34. with_ftp_retry,
  35. )
  36. # Brief delay to allow pyftpdlib to flush uploaded files to disk.
  37. # Needed because upload_file() skips voidresp() for all models,
  38. # so the server may still be processing the data channel close event.
  39. _UPLOAD_FLUSH_DELAY = 0.3
  40. # ---------------------------------------------------------------------------
  41. # TestConnection
  42. # ---------------------------------------------------------------------------
  43. class TestConnection:
  44. """Tests for FTP connect/disconnect behavior."""
  45. def test_connect_success(self, ftp_client_factory):
  46. """Successful implicit FTPS connection and login."""
  47. client = ftp_client_factory()
  48. assert client.connect() is True
  49. client.disconnect()
  50. def test_connect_wrong_access_code(self, ftp_client_factory):
  51. """Wrong access code returns False."""
  52. client = ftp_client_factory(access_code="wrongcode")
  53. assert client.connect() is False
  54. def test_connect_unreachable_host(self, ftp_server):
  55. """Unreachable host returns False."""
  56. client = BambuFTPClient(
  57. ip_address="192.0.2.1", # TEST-NET, guaranteed unreachable
  58. access_code="12345678",
  59. timeout=1.0,
  60. printer_model="X1C",
  61. )
  62. client.FTP_PORT = ftp_server.port
  63. assert client.connect() is False
  64. def test_connect_timeout(self, ftp_server):
  65. """Very short timeout triggers timeout error."""
  66. client = BambuFTPClient(
  67. ip_address="192.0.2.1",
  68. access_code="12345678",
  69. timeout=0.001, # Extremely short
  70. printer_model="X1C",
  71. )
  72. client.FTP_PORT = ftp_server.port
  73. assert client.connect() is False
  74. def test_disconnect_clean(self, ftp_client_factory):
  75. """Clean disconnect after successful connect."""
  76. client = ftp_client_factory()
  77. client.connect()
  78. client.disconnect()
  79. assert client._ftp is None
  80. def test_disconnect_without_connect(self, ftp_client_factory):
  81. """Disconnect without connect does not raise."""
  82. client = ftp_client_factory()
  83. client.disconnect() # Should not raise
  84. assert client._ftp is None
  85. def test_x1c_uses_prot_p(self, ftp_client_factory):
  86. """X1C model connects with prot_p (protected data channel)."""
  87. client = ftp_client_factory(printer_model="X1C")
  88. assert client.connect() is True
  89. assert client._should_use_prot_c() is False
  90. client.disconnect()
  91. def test_a1_defaults_prot_p(self, ftp_client_factory):
  92. """A1 model defaults to prot_p when no cache exists."""
  93. client = ftp_client_factory(printer_model="A1")
  94. assert client._should_use_prot_c() is False
  95. assert client.connect() is True
  96. client.disconnect()
  97. def test_a1_force_prot_c(self, ftp_client_factory):
  98. """A1 model with force_prot_c uses clear data channel."""
  99. client = ftp_client_factory(printer_model="A1", force_prot_c=True)
  100. assert client._should_use_prot_c() is True
  101. assert client.connect() is True
  102. client.disconnect()
  103. def test_cached_mode_respected(self, ftp_client_factory):
  104. """Cached mode is used on subsequent connections."""
  105. BambuFTPClient.cache_mode("127.0.0.1", "prot_c")
  106. client = ftp_client_factory(printer_model="A1")
  107. assert client._should_use_prot_c() is True
  108. assert client.connect() is True
  109. client.disconnect()
  110. # ---------------------------------------------------------------------------
  111. # TestDisconnectServerGone — isolated class because server.stop() calls
  112. # close_all() which nukes all asyncore sockets globally.
  113. # ---------------------------------------------------------------------------
  114. class TestDisconnectServerGone:
  115. """Test disconnect behavior when the server has stopped."""
  116. def test_disconnect_after_server_gone(self, ftp_certs, tmp_path):
  117. """Disconnect after server has stopped does not raise.
  118. disconnect() catches OSError, ftplib.Error, and EOFError so that
  119. best-effort cleanup never propagates exceptions to the caller.
  120. """
  121. from backend.tests.unit.services.mock_ftp_server import (
  122. MockBambuFTPServer,
  123. )
  124. from .conftest import _find_free_port
  125. cert_path, key_path = ftp_certs
  126. port = _find_free_port()
  127. server = MockBambuFTPServer("127.0.0.1", port, str(tmp_path), cert_path, key_path)
  128. server.start()
  129. client = BambuFTPClient("127.0.0.1", "12345678", timeout=5.0)
  130. client.FTP_PORT = port
  131. client.connect()
  132. server.stop()
  133. # Should not raise — disconnect() catches all connection errors
  134. client.disconnect()
  135. assert client._ftp is None
  136. # ---------------------------------------------------------------------------
  137. # TestListFiles
  138. # ---------------------------------------------------------------------------
  139. class TestListFiles:
  140. """Tests for directory listing."""
  141. def test_list_empty_directory(self, ftp_client_factory):
  142. """Listing an empty directory returns empty list."""
  143. client = ftp_client_factory()
  144. client.connect()
  145. files = client.list_files("/cache")
  146. assert files == []
  147. client.disconnect()
  148. def test_list_directory_with_files(self, ftp_client_factory, ftp_server):
  149. """Files in directory are listed correctly."""
  150. ftp_server.add_file("cache/test.3mf", b"x" * 1024)
  151. ftp_server.add_file("cache/test2.gcode", b"y" * 512)
  152. client = ftp_client_factory()
  153. client.connect()
  154. files = client.list_files("/cache")
  155. names = {f["name"] for f in files}
  156. assert "test.3mf" in names
  157. assert "test2.gcode" in names
  158. client.disconnect()
  159. def test_directories_marked(self, ftp_client_factory, ftp_server):
  160. """Subdirectories are identified with is_directory=True."""
  161. ftp_server.add_directory("model/subdir")
  162. client = ftp_client_factory()
  163. client.connect()
  164. files = client.list_files("/model")
  165. dirs = [f for f in files if f["is_directory"]]
  166. assert len(dirs) >= 1
  167. assert dirs[0]["name"] == "subdir"
  168. client.disconnect()
  169. def test_nonexistent_path_returns_empty(self, ftp_client_factory):
  170. """Listing a nonexistent path returns empty list."""
  171. client = ftp_client_factory()
  172. client.connect()
  173. files = client.list_files("/nonexistent/path")
  174. assert files == []
  175. client.disconnect()
  176. def test_file_sizes_and_paths(self, ftp_client_factory, ftp_server):
  177. """File sizes and full paths are parsed correctly."""
  178. ftp_server.add_file("cache/sized.bin", b"a" * 2048)
  179. client = ftp_client_factory()
  180. client.connect()
  181. files = client.list_files("/cache")
  182. sized = [f for f in files if f["name"] == "sized.bin"]
  183. assert len(sized) == 1
  184. assert sized[0]["size"] == 2048
  185. assert sized[0]["path"] == "/cache/sized.bin"
  186. client.disconnect()
  187. # ---------------------------------------------------------------------------
  188. # TestDownload
  189. # ---------------------------------------------------------------------------
  190. class TestDownload:
  191. """Tests for file download operations."""
  192. def test_download_file_returns_bytes(self, ftp_client_factory, ftp_server):
  193. """download_file() returns file content as bytes."""
  194. content = b"Hello FTP World!"
  195. ftp_server.add_file("cache/hello.txt", content)
  196. client = ftp_client_factory()
  197. client.connect()
  198. result = client.download_file("/cache/hello.txt")
  199. assert result == content
  200. client.disconnect()
  201. def test_download_file_missing(self, ftp_client_factory):
  202. """download_file() returns None for missing file."""
  203. client = ftp_client_factory()
  204. client.connect()
  205. result = client.download_file("/cache/does_not_exist.txt")
  206. assert result is None
  207. client.disconnect()
  208. def test_download_to_file_writes_to_disk(self, ftp_client_factory, ftp_server, tmp_path):
  209. """download_to_file() writes content to local filesystem."""
  210. content = b"Downloaded content"
  211. ftp_server.add_file("cache/dl.bin", content)
  212. local = tmp_path / "output" / "dl.bin"
  213. client = ftp_client_factory()
  214. client.connect()
  215. result = client.download_to_file("/cache/dl.bin", local)
  216. assert result is True
  217. assert local.read_bytes() == content
  218. client.disconnect()
  219. def test_download_to_file_creates_parent_dirs(self, ftp_client_factory, ftp_server, tmp_path):
  220. """download_to_file() creates parent directories automatically."""
  221. ftp_server.add_file("cache/nested.txt", b"nested content")
  222. local = tmp_path / "deep" / "nested" / "path" / "nested.txt"
  223. client = ftp_client_factory()
  224. client.connect()
  225. result = client.download_to_file("/cache/nested.txt", local)
  226. assert result is True
  227. assert local.exists()
  228. client.disconnect()
  229. def test_zero_byte_download_returns_false(self, ftp_client_factory, ftp_server, tmp_path):
  230. """0-byte download returns False and cleans up (regression test)."""
  231. ftp_server.add_file("cache/empty.bin", b"")
  232. local = tmp_path / "empty.bin"
  233. client = ftp_client_factory()
  234. client.connect()
  235. result = client.download_to_file("/cache/empty.bin", local)
  236. assert result is False
  237. assert not local.exists()
  238. client.disconnect()
  239. def test_download_to_file_prefers_fresh_server_size_over_stale_client_hint(
  240. self, ftp_client_factory, ftp_server, tmp_path
  241. ):
  242. """The immediate printer SIZE result overrides a stale browser hint."""
  243. ftp_server.add_file("cache/short.bin", b"short")
  244. local = tmp_path / "short.bin"
  245. client = ftp_client_factory()
  246. client.connect()
  247. try:
  248. assert client.download_to_file("/cache/short.bin", local, expected_size=100) is True
  249. assert local.read_bytes() == b"short"
  250. finally:
  251. client.disconnect()
  252. def test_download_to_file_enforces_actual_byte_limit(self, ftp_client_factory, ftp_server, tmp_path):
  253. """Untrusted size hints cannot let a transfer exceed the server-side cap."""
  254. ftp_server.add_file("cache/oversize.bin", b"too large")
  255. local = tmp_path / "oversize.bin"
  256. client = ftp_client_factory()
  257. client.connect()
  258. try:
  259. with pytest.raises(bambu_ftp.DownloadLimitExceeded):
  260. client.download_to_file("/cache/oversize.bin", local, max_bytes=3)
  261. assert not local.exists()
  262. finally:
  263. client.disconnect()
  264. def test_download_to_file_uses_server_size_when_client_hint_is_omitted(self, tmp_path):
  265. """A clean short RETR is rejected using SIZE, without trusting a caller hint."""
  266. local = tmp_path / "server-sized.bin"
  267. client = BambuFTPClient("127.0.0.1", "12345678")
  268. class FakeFTP:
  269. def size(self, _remote_path):
  270. return 100
  271. def retrbinary(self, _command, callback):
  272. callback(b"short")
  273. client._ftp = FakeFTP()
  274. assert client.download_to_file("/cache/server-sized.bin", local) is False
  275. assert not local.exists()
  276. def test_download_to_file_falls_back_to_client_hint_when_size_is_unsupported(self, tmp_path):
  277. local = tmp_path / "hint-sized.bin"
  278. client = BambuFTPClient("127.0.0.1", "12345678")
  279. class FakeFTP:
  280. def size(self, _remote_path):
  281. raise bambu_ftp.ftplib.error_perm("502 SIZE unsupported")
  282. def retrbinary(self, _command, callback):
  283. callback(b"short")
  284. client._ftp = FakeFTP()
  285. assert client.download_to_file("/cache/hint-sized.bin", local, expected_size=100) is False
  286. assert not local.exists()
  287. def test_download_to_file_missing_raises_not_on_printer(self, ftp_client_factory, tmp_path):
  288. """Missing file raises FileNotOnPrinterError so callers can short-circuit
  289. the retry loop — 550 means the file isn't there and retrying won't help."""
  290. from backend.app.services.bambu_ftp import FileNotOnPrinterError
  291. local = tmp_path / "missing.bin"
  292. client = ftp_client_factory()
  293. client.connect()
  294. try:
  295. with pytest.raises(FileNotOnPrinterError):
  296. client.download_to_file("/cache/no_such_file.bin", local)
  297. finally:
  298. client.disconnect()
  299. def test_download_large_file(self, ftp_client_factory, ftp_server):
  300. """Large file download (>1MB) works correctly."""
  301. large_content = b"X" * (1024 * 1024 + 500) # ~1MB + 500 bytes
  302. ftp_server.add_file("cache/large.bin", large_content)
  303. client = ftp_client_factory()
  304. client.connect()
  305. result = client.download_file("/cache/large.bin")
  306. assert result == large_content
  307. client.disconnect()
  308. def test_download_not_connected(self):
  309. """download_file() returns None when not connected."""
  310. client = BambuFTPClient("127.0.0.1", "12345678")
  311. assert client.download_file("/cache/test.bin") is None
  312. # ---------------------------------------------------------------------------
  313. # TestUpload
  314. # ---------------------------------------------------------------------------
  315. class TestUpload:
  316. """Tests for file upload operations."""
  317. def test_upload_success(self, ftp_client_factory, ftp_server, tmp_path):
  318. """Successful upload via transfercmd (not storbinary)."""
  319. content = b"Upload test content"
  320. local = tmp_path / "upload.3mf"
  321. local.write_bytes(content)
  322. client = ftp_client_factory()
  323. client.connect()
  324. result = client.upload_file(local, "/cache/upload.3mf")
  325. assert result is True
  326. client.disconnect()
  327. # Verify via fresh connection (upload_file skips voidresp() for all
  328. # models, so the original session can't be reused for download)
  329. time.sleep(_UPLOAD_FLUSH_DELAY)
  330. client2 = ftp_client_factory()
  331. client2.connect()
  332. downloaded = client2.download_file("/cache/upload.3mf")
  333. assert downloaded == content
  334. client2.disconnect()
  335. def test_upload_progress_callback(self, ftp_client_factory, ftp_server, tmp_path):
  336. """Progress callback receives updates during upload."""
  337. content = b"P" * 2048
  338. local = tmp_path / "progress.bin"
  339. local.write_bytes(content)
  340. progress_calls = []
  341. def on_progress(uploaded, total):
  342. progress_calls.append((uploaded, total))
  343. client = ftp_client_factory()
  344. client.connect()
  345. client.upload_file(local, "/cache/progress.bin", on_progress)
  346. assert len(progress_calls) >= 1
  347. # Last call should report full file uploaded
  348. assert progress_calls[-1][0] == len(content)
  349. assert progress_calls[-1][1] == len(content)
  350. client.disconnect()
  351. def test_upload_not_connected(self, tmp_path):
  352. """Upload when not connected returns False."""
  353. local = tmp_path / "test.bin"
  354. local.write_bytes(b"data")
  355. client = BambuFTPClient("127.0.0.1", "12345678")
  356. assert client.upload_file(local, "/cache/test.bin") is False
  357. def test_upload_553_no_sd_card(self, ftp_client_factory, ftp_server, tmp_path):
  358. """553 error (no SD card) returns False."""
  359. ftp_server.inject_failure("STOR", 553, "Could not create file.")
  360. local = tmp_path / "test.bin"
  361. local.write_bytes(b"data")
  362. client = ftp_client_factory()
  363. client.connect()
  364. result = client.upload_file(local, "/cache/test.bin")
  365. assert result is False
  366. client.disconnect()
  367. def test_upload_550_permission_denied(self, ftp_client_factory, ftp_server, tmp_path):
  368. """550 error (permission denied) returns False."""
  369. ftp_server.inject_failure("STOR", 550, "Permission denied.")
  370. local = tmp_path / "test.bin"
  371. local.write_bytes(b"data")
  372. client = ftp_client_factory()
  373. client.connect()
  374. result = client.upload_file(local, "/cache/test.bin")
  375. assert result is False
  376. client.disconnect()
  377. def test_upload_552_storage_full(self, ftp_client_factory, ftp_server, tmp_path):
  378. """552 error (storage full) returns False."""
  379. ftp_server.inject_failure("STOR", 552, "Storage quota exceeded.")
  380. local = tmp_path / "test.bin"
  381. local.write_bytes(b"data")
  382. client = ftp_client_factory()
  383. client.connect()
  384. result = client.upload_file(local, "/cache/test.bin")
  385. assert result is False
  386. client.disconnect()
  387. def test_upload_426_with_intact_file_proceeds(self, ftp_client_factory, ftp_server, tmp_path):
  388. """Some P2S firmware revisions return 426 on voidresp() even when the
  389. file landed fully (TLS data-channel close races the 226). #1417
  390. follow-up — verify via SIZE: when server size matches, proceed with
  391. a warning instead of failing the dispatch.
  392. Pre-#1417 the catch raised unconditionally and the reporter saw 11
  393. retries fail in a row even though every upload was actually
  394. succeeding on the printer side (v0.2.4.1 worked because the prior
  395. proceed-with-warning branch tolerated the noise).
  396. """
  397. import ftplib # nosec B402 — tests need the real ftplib to construct mock 426 responses
  398. local = tmp_path / "test.bin"
  399. local.write_bytes(b"data" * 256) # 1024 bytes
  400. client = ftp_client_factory()
  401. client.connect()
  402. def raise_426():
  403. raise ftplib.error_temp("426 Failure reading network stream.")
  404. def fake_size(_path):
  405. # Real P2S firmware: voidresp returns 426 but the file IS on
  406. # the SD card at its full size. Mock can't reproduce both
  407. # halves naturally because pyftpdlib only flushes on a clean
  408. # voidresp, so we inject SIZE explicitly to model the
  409. # printer-side state the user observes.
  410. return 1024
  411. client._ftp.voidresp = raise_426
  412. client._ftp.size = fake_size
  413. result = client.upload_file(local, "/cache/test.bin")
  414. assert result is True, "intact file (SIZE match) tolerates 426 noise"
  415. client.disconnect()
  416. def test_upload_426_with_intact_file_logs_at_info_not_warning(
  417. self, ftp_client_factory, ftp_server, tmp_path, caplog
  418. ):
  419. """A verified-intact 426 is how Bambu FTPS normally ends a transfer,
  420. not a fault, so it must not be a WARNING (#2987).
  421. It fired 54 times in one support bundle, every one followed by a
  422. completed upload, and buried the 26 TLS handshake failures in the same
  423. log that actually cost the reporter two prints. The truncated case below
  424. is still an error -- this only moves the one we have already verified.
  425. """
  426. import ftplib # nosec B402 — tests need the real ftplib to construct mock 426 responses
  427. import logging
  428. local = tmp_path / "test.bin"
  429. local.write_bytes(b"data" * 256) # 1024 bytes
  430. client = ftp_client_factory()
  431. client.connect()
  432. def raise_426():
  433. raise ftplib.error_temp("426 Failure reading network stream.")
  434. client._ftp.voidresp = raise_426
  435. client._ftp.size = lambda _path: 1024
  436. with caplog.at_level(logging.INFO, logger="backend.app.services.bambu_ftp"):
  437. assert client.upload_file(local, "/cache/test.bin") is True
  438. client.disconnect()
  439. intact = [r for r in caplog.records if "file is intact on the" in r.getMessage()]
  440. assert intact, "the proceed path must still say why it proceeded"
  441. assert [r.levelno for r in intact] == [logging.INFO] * len(intact)
  442. def test_upload_426_with_truncated_file_still_logs_an_error(self, ftp_client_factory, ftp_server, tmp_path, caplog):
  443. """The half that must stay loud: bytes that did not verify."""
  444. import ftplib # nosec B402 — tests need the real ftplib to construct mock 426 responses
  445. import logging
  446. local = tmp_path / "test.bin"
  447. local.write_bytes(b"data" * 256)
  448. client = ftp_client_factory()
  449. client.connect()
  450. def raise_426():
  451. raise ftplib.error_temp("426 Failure reading network stream.")
  452. client._ftp.voidresp = raise_426
  453. client._ftp.size = lambda _path: 100
  454. with caplog.at_level(logging.INFO, logger="backend.app.services.bambu_ftp"):
  455. assert client.upload_file(local, "/cache/test.bin") is False
  456. client.disconnect()
  457. rejected = [r for r in caplog.records if "rejected by printer" in r.getMessage()]
  458. assert rejected and all(r.levelno == logging.ERROR for r in rejected)
  459. def test_upload_426_with_truncated_file_returns_false(self, ftp_client_factory, ftp_server, tmp_path):
  460. """The original #1401 fix is preserved: when SIZE confirms the file
  461. isn't on the server at full size (or SIZE itself fails), the upload
  462. must fail so the dispatcher doesn't send a print command for a
  463. partial 3MF."""
  464. import ftplib # nosec B402 — tests need the real ftplib to construct mock 426 responses
  465. local = tmp_path / "test.bin"
  466. local.write_bytes(b"data" * 256)
  467. client = ftp_client_factory()
  468. client.connect()
  469. def raise_426():
  470. raise ftplib.error_temp("426 Failure reading network stream.")
  471. # Make SIZE report a smaller value — file is genuinely truncated.
  472. def fake_size(_path):
  473. return 100
  474. client._ftp.voidresp = raise_426
  475. client._ftp.size = fake_size
  476. result = client.upload_file(local, "/cache/test.bin")
  477. assert result is False, "truncated file (SIZE mismatch) must fail"
  478. client.disconnect()
  479. def test_upload_426_with_size_check_failing_returns_false(self, ftp_client_factory, ftp_server, tmp_path):
  480. """If SIZE itself fails (e.g. server too broken to answer), assume
  481. the worst and fail — better a retry than a print on a partial file.
  482. """
  483. import ftplib # nosec B402 — tests need the real ftplib to construct mock 426 responses
  484. local = tmp_path / "test.bin"
  485. local.write_bytes(b"data" * 256)
  486. client = ftp_client_factory()
  487. client.connect()
  488. def raise_426():
  489. raise ftplib.error_temp("426 Failure reading network stream.")
  490. def raise_size(_path):
  491. raise ftplib.error_perm("550 File not found.")
  492. client._ftp.voidresp = raise_426
  493. client._ftp.size = raise_size
  494. result = client.upload_file(local, "/cache/test.bin")
  495. assert result is False
  496. client.disconnect()
  497. def test_upload_bytes_426_with_intact_file_proceeds(self, ftp_client_factory, ftp_server):
  498. """upload_bytes() mirrors the same SIZE-verify logic as upload_file."""
  499. import ftplib # nosec B402 — tests need the real ftplib to construct mock 426 responses
  500. client = ftp_client_factory()
  501. client.connect()
  502. data = b"x" * 1024
  503. def raise_426():
  504. raise ftplib.error_temp("426 Failure reading network stream.")
  505. def fake_size(_path):
  506. return 1024 # printer-side file matches expected size
  507. client._ftp.voidresp = raise_426
  508. client._ftp.size = fake_size
  509. result = client.upload_bytes(data, "/cache/bytes.bin")
  510. assert result is True
  511. client.disconnect()
  512. def test_upload_bytes_426_with_truncated_file_returns_false(self, ftp_client_factory, ftp_server):
  513. """The truncated branch for upload_bytes()."""
  514. import ftplib # nosec B402 — tests need the real ftplib to construct mock 426 responses
  515. client = ftp_client_factory()
  516. client.connect()
  517. data = b"x" * 1024
  518. def raise_426():
  519. raise ftplib.error_temp("426 Failure reading network stream.")
  520. def fake_size(_path):
  521. return 100
  522. client._ftp.voidresp = raise_426
  523. client._ftp.size = fake_size
  524. result = client.upload_bytes(data, "/cache/bytes.bin")
  525. assert result is False
  526. client.disconnect()
  527. def test_upload_bytes_success(self, ftp_client_factory, ftp_server):
  528. """upload_bytes() writes data to server."""
  529. data = b"Bytes upload content"
  530. client = ftp_client_factory()
  531. client.connect()
  532. result = client.upload_bytes(data, "/cache/bytes.bin")
  533. assert result is True
  534. client.disconnect()
  535. # Verify via fresh connection
  536. time.sleep(_UPLOAD_FLUSH_DELAY)
  537. client2 = ftp_client_factory()
  538. client2.connect()
  539. downloaded = client2.download_file("/cache/bytes.bin")
  540. assert downloaded == data
  541. client2.disconnect()
  542. def test_upload_bytes_failure(self, ftp_client_factory, ftp_server):
  543. """upload_bytes() returns False on STOR failure."""
  544. ftp_server.inject_failure("STOR", 553, "No space.")
  545. client = ftp_client_factory()
  546. client.connect()
  547. result = client.upload_bytes(b"data", "/cache/fail.bin")
  548. assert result is False
  549. client.disconnect()
  550. def test_upload_large_chunked(self, ftp_client_factory, ftp_server, tmp_path):
  551. """Large file upload in chunks completes without error.
  552. Uses 2.5MB to trigger multiple chunks with 64KB CHUNK_SIZE.
  553. Content verification skipped because upload_file() skips
  554. voidresp() for all models, so the server may still be flushing
  555. when we check. The upload result=True confirms the client sent
  556. all chunks without error.
  557. """
  558. content = b"C" * (1024 * 1024 * 2 + 512 * 1024)
  559. local = tmp_path / "large.bin"
  560. local.write_bytes(content)
  561. progress_calls = []
  562. def on_progress(uploaded, total):
  563. progress_calls.append((uploaded, total))
  564. client = ftp_client_factory()
  565. client.connect()
  566. result = client.upload_file(local, "/cache/large.bin", on_progress)
  567. assert result is True
  568. # Verify many chunks were sent (2.5MB / 64KB = 40 chunks)
  569. assert len(progress_calls) >= 38
  570. assert progress_calls[-1][0] == len(content)
  571. client.disconnect()
  572. # ---------------------------------------------------------------------------
  573. # TestDelete
  574. # ---------------------------------------------------------------------------
  575. class TestDelete:
  576. """Tests for file deletion."""
  577. def test_delete_success(self, ftp_client_factory, ftp_server):
  578. """Successful file deletion."""
  579. from backend.app.services.bambu_ftp import DeleteResult
  580. ftp_server.add_file("cache/to_delete.bin", b"delete me")
  581. client = ftp_client_factory()
  582. client.connect()
  583. result = client.delete_file("/cache/to_delete.bin")
  584. assert result == DeleteResult.DELETED
  585. assert not ftp_server.file_exists("cache/to_delete.bin")
  586. client.disconnect()
  587. def test_delete_not_found(self, ftp_client_factory):
  588. """Deleting a nonexistent file returns NOT_FOUND (550, #1721)."""
  589. from backend.app.services.bambu_ftp import DeleteResult
  590. client = ftp_client_factory()
  591. client.connect()
  592. result = client.delete_file("/cache/no_such_file.bin")
  593. assert result == DeleteResult.NOT_FOUND
  594. client.disconnect()
  595. def test_delete_not_connected(self):
  596. """Delete when not connected returns FAILED."""
  597. from backend.app.services.bambu_ftp import DeleteResult
  598. client = BambuFTPClient("127.0.0.1", "12345678")
  599. assert client.delete_file("/cache/test.bin") == DeleteResult.FAILED
  600. # ---------------------------------------------------------------------------
  601. # TestFileSize
  602. # ---------------------------------------------------------------------------
  603. class TestFileSize:
  604. """Tests for get_file_size."""
  605. def test_file_size_correct(self, ftp_client_factory, ftp_server):
  606. """Returns correct file size."""
  607. ftp_server.add_file("cache/sized.bin", b"a" * 4096)
  608. client = ftp_client_factory()
  609. client.connect()
  610. size = client.get_file_size("/cache/sized.bin")
  611. assert size == 4096
  612. client.disconnect()
  613. def test_file_size_missing(self, ftp_client_factory):
  614. """Returns None for missing file."""
  615. client = ftp_client_factory()
  616. client.connect()
  617. size = client.get_file_size("/cache/no_file.bin")
  618. assert size is None
  619. client.disconnect()
  620. def test_file_size_not_connected(self):
  621. """Returns None when not connected."""
  622. client = BambuFTPClient("127.0.0.1", "12345678")
  623. assert client.get_file_size("/cache/test.bin") is None
  624. # ---------------------------------------------------------------------------
  625. # TestStorageInfo
  626. # ---------------------------------------------------------------------------
  627. class TestStorageInfo:
  628. """Tests for storage info and diagnostics."""
  629. def test_avbl_parsed(self, ftp_client_factory, ftp_server):
  630. """AVBL response is parsed for free_bytes."""
  631. ftp_server.set_avbl_bytes(5000000000)
  632. client = ftp_client_factory()
  633. client.connect()
  634. info = client.get_storage_info()
  635. assert info is not None
  636. assert info["free_bytes"] == 5000000000
  637. client.disconnect()
  638. def test_used_bytes_from_scan(self, ftp_client_factory, ftp_server):
  639. """used_bytes calculated from directory scan."""
  640. ftp_server.add_file("cache/file1.bin", b"a" * 1000)
  641. ftp_server.add_file("cache/file2.bin", b"b" * 2000)
  642. client = ftp_client_factory()
  643. client.connect()
  644. info = client.get_storage_info()
  645. assert info is not None
  646. assert info["used_bytes"] >= 3000 # At least these two files
  647. client.disconnect()
  648. def test_storage_info_not_connected(self):
  649. """Returns None when not connected."""
  650. client = BambuFTPClient("127.0.0.1", "12345678")
  651. assert client.get_storage_info() is None
  652. def test_diagnose_storage_success(self, ftp_client_factory, ftp_server):
  653. """diagnose_storage() returns connected=True with working diagnostics."""
  654. client = ftp_client_factory()
  655. client.connect()
  656. diag = client.diagnose_storage()
  657. assert diag["connected"] is True
  658. assert diag["can_list_root"] is True
  659. assert diag["can_list_cache"] is True
  660. assert diag["pwd"] is not None
  661. assert diag["storage_info"] is not None
  662. client.disconnect()
  663. def test_diagnose_storage_not_connected(self):
  664. """diagnose_storage() reports not connected."""
  665. client = BambuFTPClient("127.0.0.1", "12345678")
  666. diag = client.diagnose_storage()
  667. assert diag["connected"] is False
  668. assert "FTP not connected" in diag["errors"]
  669. # ---------------------------------------------------------------------------
  670. # TestModelSpecificBehavior
  671. # ---------------------------------------------------------------------------
  672. class TestModelSpecificBehavior:
  673. """Tests for printer model-specific FTP behavior."""
  674. def test_x1c_upload(self, ftp_client_factory, ftp_server, tmp_path):
  675. """X1C upload with session reuse succeeds."""
  676. content = b"X1C upload data"
  677. local = tmp_path / "x1c.3mf"
  678. local.write_bytes(content)
  679. client = ftp_client_factory(printer_model="X1C")
  680. client.connect()
  681. result = client.upload_file(local, "/cache/x1c.3mf")
  682. assert result is True
  683. client.disconnect()
  684. # Verify via fresh connection
  685. time.sleep(_UPLOAD_FLUSH_DELAY)
  686. client2 = ftp_client_factory(printer_model="X1C")
  687. client2.connect()
  688. downloaded = client2.download_file("/cache/x1c.3mf")
  689. assert downloaded == content
  690. client2.disconnect()
  691. def test_a1_upload_prot_c(self, ftp_client_factory, ftp_server, tmp_path):
  692. """A1 model upload with prot_c succeeds."""
  693. content = b"A1 upload data"
  694. local = tmp_path / "a1.3mf"
  695. local.write_bytes(content)
  696. client = ftp_client_factory(printer_model="A1", force_prot_c=True)
  697. client.connect()
  698. result = client.upload_file(local, "/cache/a1.3mf")
  699. assert result is True
  700. client.disconnect()
  701. # Verify via fresh connection
  702. time.sleep(_UPLOAD_FLUSH_DELAY)
  703. client2 = ftp_client_factory(printer_model="A1", force_prot_c=True)
  704. client2.connect()
  705. downloaded = client2.download_file("/cache/a1.3mf")
  706. assert downloaded == content
  707. client2.disconnect()
  708. def test_a1_mini_upload(self, ftp_client_factory, ftp_server, tmp_path):
  709. """A1 Mini model upload succeeds."""
  710. content = b"A1 Mini data"
  711. local = tmp_path / "a1mini.3mf"
  712. local.write_bytes(content)
  713. client = ftp_client_factory(printer_model="A1 Mini", force_prot_c=True)
  714. client.connect()
  715. result = client.upload_file(local, "/cache/a1mini.3mf")
  716. assert result is True
  717. client.disconnect()
  718. def test_p1s_upload(self, ftp_client_factory, ftp_server, tmp_path):
  719. """P1S model upload with session reuse succeeds."""
  720. content = b"P1S upload data"
  721. local = tmp_path / "p1s.3mf"
  722. local.write_bytes(content)
  723. client = ftp_client_factory(printer_model="P1S")
  724. client.connect()
  725. result = client.upload_file(local, "/cache/p1s.3mf")
  726. assert result is True
  727. client.disconnect()
  728. def test_unknown_model_defaults_prot_p(self, ftp_client_factory):
  729. """Unknown model defaults to prot_p."""
  730. client = ftp_client_factory(printer_model="FuturePrinter3000")
  731. assert client._is_a1_model() is False
  732. assert client._should_use_prot_c() is False
  733. assert client.connect() is True
  734. client.disconnect()
  735. def test_mode_cache_persists_and_clears(self, ftp_client_factory):
  736. """Mode cache works within a test and clears between tests."""
  737. # Cache should be empty at start (autouse fixture clears it)
  738. assert BambuFTPClient._mode_cache == {}
  739. # Connect and cache a mode
  740. BambuFTPClient.cache_mode("127.0.0.1", "prot_p")
  741. assert BambuFTPClient._mode_cache["127.0.0.1"] == "prot_p"
  742. # New client for same IP uses cached mode
  743. client = ftp_client_factory(printer_model="A1")
  744. assert client._get_cached_mode() == "prot_p"
  745. assert client._should_use_prot_c() is False
  746. client.disconnect()
  747. # ---------------------------------------------------------------------------
  748. # TestAsyncWrappers
  749. # ---------------------------------------------------------------------------
  750. class TestAsyncWrappers:
  751. """Tests for async wrapper functions using patch_ftp_port fixture."""
  752. @pytest.mark.asyncio
  753. async def test_upload_file_async_success(self, patch_ftp_port, tmp_path):
  754. """upload_file_async succeeds for X1C."""
  755. content = b"async upload"
  756. local = tmp_path / "async_up.3mf"
  757. local.write_bytes(content)
  758. result = await upload_file_async(
  759. "127.0.0.1",
  760. "12345678",
  761. local,
  762. "/cache/async_up.3mf",
  763. timeout=30.0,
  764. printer_model="X1C",
  765. )
  766. assert result is True
  767. @pytest.mark.asyncio
  768. async def test_upload_file_async_a1_fallback(self, patch_ftp_port, tmp_path):
  769. """upload_file_async tries prot_p then falls back to prot_c for A1."""
  770. content = b"a1 async upload"
  771. local = tmp_path / "a1_async.3mf"
  772. local.write_bytes(content)
  773. # For A1 models, if prot_p succeeds we get True.
  774. # If prot_p fails, it tries prot_c. Either way should succeed
  775. # against our mock server which accepts both.
  776. result = await upload_file_async(
  777. "127.0.0.1",
  778. "12345678",
  779. local,
  780. "/cache/a1_async.3mf",
  781. timeout=30.0,
  782. printer_model="A1",
  783. )
  784. assert result is True
  785. @pytest.mark.asyncio
  786. async def test_download_file_async_success(self, patch_ftp_port, tmp_path):
  787. """download_file_async succeeds."""
  788. server = patch_ftp_port
  789. content = b"async download content"
  790. server.add_file("cache/async_dl.bin", content)
  791. local = tmp_path / "async_dl.bin"
  792. result = await download_file_async(
  793. "127.0.0.1",
  794. "12345678",
  795. "/cache/async_dl.bin",
  796. local,
  797. timeout=30.0,
  798. printer_model="X1C",
  799. )
  800. assert result is True
  801. assert local.read_bytes() == content
  802. @pytest.mark.asyncio
  803. async def test_download_file_async_a1_fallback(self, patch_ftp_port, tmp_path):
  804. """download_file_async falls back for A1 models."""
  805. server = patch_ftp_port
  806. server.add_file("cache/a1_dl.bin", b"a1 data")
  807. local = tmp_path / "a1_dl.bin"
  808. result = await download_file_async(
  809. "127.0.0.1",
  810. "12345678",
  811. "/cache/a1_dl.bin",
  812. local,
  813. timeout=30.0,
  814. printer_model="A1",
  815. )
  816. assert result is True
  817. @pytest.mark.asyncio
  818. async def test_download_file_async_timeout_salvages_completed_zombie(self, tmp_path, monkeypatch):
  819. """Executor thread that completes after wait_for timeout is salvaged.
  820. asyncio.wait_for cannot cancel run_in_executor threads, so the FTP
  821. download may still complete after we give up waiting. If the thread
  822. genuinely finished (signalled via completion["success"] and the file
  823. is on disk), download_file_async should return True rather than False.
  824. Regression for #972: A1 user with 14 MB 3MF hit the hardcoded 60s
  825. timeout, but the download thread finished ~45s later. The successful
  826. file was written to disk but the async wrapper returned False, so the
  827. archive was created as a fallback with no 3MF data.
  828. """
  829. from backend.app.services import bambu_ftp
  830. # Clear mode cache so prot_p path is exercised.
  831. bambu_ftp.BambuFTPClient._mode_cache.pop("127.0.0.1", None)
  832. local = tmp_path / "zombie.bin"
  833. expected_content = b"late arrival but complete"
  834. class FakeClient:
  835. """Connects instantly, download_to_file sleeps past wait_for's
  836. timeout then writes the file and returns True."""
  837. def __init__(self, *args, **kwargs):
  838. pass
  839. def connect(self):
  840. return True
  841. def download_to_file(self, remote_path, local_path, **_kwargs):
  842. time.sleep(0.4) # longer than wait_for timeout=0.1
  843. local_path.write_bytes(expected_content)
  844. return True
  845. def disconnect(self):
  846. pass
  847. monkeypatch.setattr(bambu_ftp, "BambuFTPClient", FakeClient)
  848. monkeypatch.setattr(FakeClient, "_mode_cache", {}, raising=False)
  849. monkeypatch.setattr(FakeClient, "A1_MODELS", {"A1"}, raising=False)
  850. def _noop_cache(ip, mode):
  851. pass
  852. monkeypatch.setattr(FakeClient, "cache_mode", staticmethod(_noop_cache), raising=False)
  853. result = await download_file_async(
  854. "127.0.0.1",
  855. "12345678",
  856. "/cache/zombie.bin",
  857. local,
  858. timeout=0.1,
  859. printer_model="X1C",
  860. )
  861. assert result is True
  862. assert local.read_bytes() == expected_content
  863. @pytest.mark.asyncio
  864. async def test_download_file_async_timeout_no_salvage_when_incomplete(self, tmp_path, monkeypatch):
  865. """Timeout returns False when thread has not signalled success.
  866. A partial file on disk (mid-retrbinary) must NOT be mistaken for a
  867. completed download — only the thread's explicit success flag permits
  868. salvage.
  869. """
  870. from backend.app.services import bambu_ftp
  871. bambu_ftp.BambuFTPClient._mode_cache.pop("127.0.0.1", None)
  872. local = tmp_path / "partial.bin"
  873. class FakeClient:
  874. def __init__(self, *args, **kwargs):
  875. pass
  876. def connect(self):
  877. return True
  878. def download_to_file(self, remote_path, local_path, **kwargs):
  879. # Simulate an in-progress partial write that never completes
  880. # until the async timeout asks the worker to unwind.
  881. local_path.write_bytes(b"partial...")
  882. while not kwargs["cancel_event"].is_set():
  883. time.sleep(0.01)
  884. local_path.unlink(missing_ok=True)
  885. raise bambu_ftp.DownloadCancelled(remote_path)
  886. def disconnect(self):
  887. pass
  888. monkeypatch.setattr(bambu_ftp, "BambuFTPClient", FakeClient)
  889. monkeypatch.setattr(FakeClient, "_mode_cache", {}, raising=False)
  890. monkeypatch.setattr(FakeClient, "A1_MODELS", set(), raising=False)
  891. monkeypatch.setattr(FakeClient, "cache_mode", staticmethod(lambda ip, mode: None), raising=False)
  892. result = await download_file_async(
  893. "127.0.0.1",
  894. "12345678",
  895. "/cache/partial.bin",
  896. local,
  897. timeout=0.1,
  898. printer_model="X1C",
  899. )
  900. assert result is False
  901. @pytest.mark.asyncio
  902. async def test_download_file_async_timeout_waits_for_slow_zombie(self, tmp_path, monkeypatch):
  903. """A zombie that completes within the 30s grace window is salvaged.
  904. Regression for #1014: on slow WiFi, download_to_file can overshoot the
  905. user's ftp_timeout by 10–30 s without being stuck. The old fixed 0.5 s
  906. post-timeout sleep was too short — it gave up and started attempt 2
  907. while attempt 1's zombie thread kept running, and by the time the zombie
  908. wrote the file to disk with a success flag, attempt 2 had already
  909. reported failure (its own completion dict was still False). The async
  910. wrapper now waits up to min(timeout, 30 s) for the worker thread to
  911. finish before returning, so a slow-but-progressing download salvages.
  912. """
  913. from backend.app.services import bambu_ftp
  914. bambu_ftp.BambuFTPClient._mode_cache.pop("127.0.0.1", None)
  915. local = tmp_path / "slow_zombie.bin"
  916. expected_content = b"finished during grace window"
  917. class FakeClient:
  918. """Mimics a slow FTP: wait_for gives up at 1.0 s but RETR takes
  919. 1.5 s total. Old 0.5 s fixed sleep would have bailed (0.5 < 0.5
  920. extra); new grace = max(min(1.0, 30), 0.5) = 1.0 s covers the
  921. remaining 0.5 s so salvage succeeds."""
  922. def __init__(self, *args, **kwargs):
  923. pass
  924. def connect(self):
  925. return True
  926. def download_to_file(self, remote_path, local_path, **_kwargs):
  927. time.sleep(1.5) # wait_for times out at 1.0 s; zombie finishes 0.5 s later
  928. local_path.write_bytes(expected_content)
  929. return True
  930. def disconnect(self):
  931. pass
  932. monkeypatch.setattr(bambu_ftp, "BambuFTPClient", FakeClient)
  933. monkeypatch.setattr(FakeClient, "_mode_cache", {}, raising=False)
  934. monkeypatch.setattr(FakeClient, "A1_MODELS", set(), raising=False)
  935. monkeypatch.setattr(FakeClient, "cache_mode", staticmethod(lambda ip, mode: None), raising=False)
  936. result = await download_file_async(
  937. "127.0.0.1",
  938. "12345678",
  939. "/cache/slow_zombie.bin",
  940. local,
  941. timeout=1.0,
  942. printer_model="X1C",
  943. )
  944. assert result is True
  945. assert local.read_bytes() == expected_content
  946. @pytest.mark.asyncio
  947. async def test_download_file_async_cancellation_waits_for_worker_cleanup(self, tmp_path, monkeypatch):
  948. """Task cancellation returns only after the FTP worker has unwound."""
  949. from backend.app.services import bambu_ftp
  950. bambu_ftp.BambuFTPClient._mode_cache.pop("127.0.0.1", None)
  951. local = tmp_path / "cancelled.bin"
  952. started = threading.Event()
  953. finished = threading.Event()
  954. class FakeClient:
  955. def __init__(self, *args, **kwargs):
  956. pass
  957. def connect(self):
  958. return True
  959. def download_to_file(self, remote_path, local_path, **kwargs):
  960. local_path.write_bytes(b"partial")
  961. started.set()
  962. try:
  963. while not kwargs["cancel_event"].is_set():
  964. time.sleep(0.01)
  965. local_path.unlink(missing_ok=True)
  966. raise bambu_ftp.DownloadCancelled(remote_path)
  967. finally:
  968. finished.set()
  969. def disconnect(self):
  970. pass
  971. monkeypatch.setattr(bambu_ftp, "BambuFTPClient", FakeClient)
  972. monkeypatch.setattr(FakeClient, "_mode_cache", {}, raising=False)
  973. monkeypatch.setattr(FakeClient, "A1_MODELS", set(), raising=False)
  974. monkeypatch.setattr(FakeClient, "cache_mode", staticmethod(lambda ip, mode: None), raising=False)
  975. task = asyncio.create_task(
  976. download_file_async(
  977. "127.0.0.1",
  978. "12345678",
  979. "/cache/cancelled.bin",
  980. local,
  981. timeout=30.0,
  982. printer_model="X1C",
  983. )
  984. )
  985. assert await asyncio.to_thread(started.wait, 1.0)
  986. task.cancel()
  987. with pytest.raises(asyncio.CancelledError):
  988. await task
  989. assert finished.is_set()
  990. assert not local.exists()
  991. @pytest.mark.asyncio
  992. async def test_download_file_try_paths_first_succeeds(self, patch_ftp_port, tmp_path):
  993. """download_file_try_paths_async succeeds on first path."""
  994. server = patch_ftp_port
  995. server.add_file("cache/try1.bin", b"first path")
  996. local = tmp_path / "try.bin"
  997. result = await download_file_try_paths_async(
  998. "127.0.0.1",
  999. "12345678",
  1000. ["/cache/try1.bin", "/cache/try2.bin"],
  1001. local,
  1002. printer_model="X1C",
  1003. )
  1004. # The path, not a flag: the caller logs which candidate served the file
  1005. # so a stale same-named copy is diagnosable (#1820).
  1006. assert result == "/cache/try1.bin"
  1007. assert local.read_bytes() == b"first path"
  1008. @pytest.mark.asyncio
  1009. async def test_download_file_try_paths_fallback(self, patch_ftp_port, tmp_path):
  1010. """download_file_try_paths_async falls back to second path."""
  1011. server = patch_ftp_port
  1012. server.add_file("cache/second.bin", b"second path")
  1013. local = tmp_path / "fallback.bin"
  1014. result = await download_file_try_paths_async(
  1015. "127.0.0.1",
  1016. "12345678",
  1017. ["/cache/missing.bin", "/cache/second.bin"],
  1018. local,
  1019. printer_model="X1C",
  1020. )
  1021. assert result == "/cache/second.bin"
  1022. assert local.read_bytes() == b"second path"
  1023. @pytest.mark.asyncio
  1024. async def test_list_files_async_success(self, patch_ftp_port):
  1025. """list_files_async returns file list."""
  1026. server = patch_ftp_port
  1027. server.add_file("cache/listed.bin", b"data")
  1028. result = await list_files_async(
  1029. "127.0.0.1",
  1030. "12345678",
  1031. "/cache",
  1032. timeout=30.0,
  1033. printer_model="X1C",
  1034. )
  1035. names = {f["name"] for f in result}
  1036. assert "listed.bin" in names
  1037. @pytest.mark.asyncio
  1038. async def test_delete_file_async_success(self, patch_ftp_port):
  1039. """delete_file_async deletes a file."""
  1040. from backend.app.services.bambu_ftp import DeleteResult
  1041. server = patch_ftp_port
  1042. server.add_file("cache/to_async_del.bin", b"delete me")
  1043. result = await delete_file_async(
  1044. "127.0.0.1",
  1045. "12345678",
  1046. "/cache/to_async_del.bin",
  1047. printer_model="X1C",
  1048. )
  1049. assert result == DeleteResult.DELETED
  1050. assert not server.file_exists("cache/to_async_del.bin")
  1051. @pytest.mark.asyncio
  1052. async def test_delete_file_async_not_found(self, patch_ftp_port):
  1053. """delete_file_async distinguishes 550 from real failure (#1721)."""
  1054. from backend.app.services.bambu_ftp import DeleteResult
  1055. result = await delete_file_async(
  1056. "127.0.0.1",
  1057. "12345678",
  1058. "/cache/never_existed.bin",
  1059. printer_model="X1C",
  1060. )
  1061. assert result == DeleteResult.NOT_FOUND
  1062. # ---------------------------------------------------------------------------
  1063. # TestFailureScenarios
  1064. # ---------------------------------------------------------------------------
  1065. class TestFailureScenarios:
  1066. """Regression tests for known FTP failure modes."""
  1067. def test_550_caught_by_broad_except(self, ftp_client_factory, ftp_server, tmp_path):
  1068. """550 error_perm is caught by (OSError, ftplib.Error) handler.
  1069. Regression: error_perm is a subclass of ftplib.Error, so the
  1070. broad except clause in upload_file catches it correctly.
  1071. """
  1072. ftp_server.inject_failure("STOR", 550, "Permission denied.")
  1073. local = tmp_path / "test.bin"
  1074. local.write_bytes(b"data")
  1075. client = ftp_client_factory()
  1076. client.connect()
  1077. result = client.upload_file(local, "/cache/test.bin")
  1078. assert result is False
  1079. client.disconnect()
  1080. def test_zero_byte_download_detected(self, ftp_client_factory, ftp_server, tmp_path):
  1081. """0-byte download is detected and file is cleaned up.
  1082. Regression: Prior to fix, 0-byte downloads were reported as success.
  1083. """
  1084. ftp_server.add_file("cache/zero.bin", b"")
  1085. local = tmp_path / "zero.bin"
  1086. client = ftp_client_factory()
  1087. client.connect()
  1088. result = client.download_to_file("/cache/zero.bin", local)
  1089. assert result is False
  1090. assert not local.exists()
  1091. client.disconnect()
  1092. def test_connection_refused_handled(self):
  1093. """Connection refused is handled gracefully."""
  1094. client = BambuFTPClient("127.0.0.1", "12345678", timeout=2.0)
  1095. client.FTP_PORT = 1 # Almost certainly not listening
  1096. assert client.connect() is False
  1097. def test_auth_failure_530(self, ftp_client_factory, ftp_server):
  1098. """530 authentication failure returns False."""
  1099. ftp_server.inject_failure("PASS", 530, "Login incorrect.")
  1100. client = ftp_client_factory()
  1101. result = client.connect()
  1102. assert result is False
  1103. def test_retr_550_handled(self, ftp_client_factory, ftp_server):
  1104. """RETR 550 (file not found) returns None."""
  1105. ftp_server.inject_failure("RETR", 550, "File not found.")
  1106. ftp_server.add_file("cache/exists.bin", b"data")
  1107. client = ftp_client_factory()
  1108. client.connect()
  1109. result = client.download_file("/cache/exists.bin")
  1110. assert result is None
  1111. client.disconnect()
  1112. def test_cwd_550_handled(self, ftp_client_factory, ftp_server):
  1113. """CWD 550 is handled in list_files."""
  1114. ftp_server.inject_failure("CWD", 550, "Directory not found.")
  1115. client = ftp_client_factory()
  1116. client.connect()
  1117. result = client.list_files("/nonexistent")
  1118. assert result == []
  1119. client.disconnect()
  1120. def test_stor_553_handled(self, ftp_client_factory, ftp_server, tmp_path):
  1121. """STOR 553 (no SD card) handled gracefully."""
  1122. ftp_server.inject_failure("STOR", 553, "Could not create file.")
  1123. local = tmp_path / "test.bin"
  1124. local.write_bytes(b"test")
  1125. client = ftp_client_factory()
  1126. client.connect()
  1127. result = client.upload_file(local, "/cache/test.bin")
  1128. assert result is False
  1129. client.disconnect()
  1130. def test_diagnose_storage_cwd_failure_doesnt_propagate(self, ftp_client_factory, ftp_server):
  1131. """diagnose_storage CWD failure doesn't crash the whole operation.
  1132. Regression: diagnose_storage() was called in the upload path and
  1133. a CWD failure would propagate and crash the upload.
  1134. """
  1135. ftp_server.inject_failure("CWD", 550, "No such directory.", count=2)
  1136. client = ftp_client_factory()
  1137. client.connect()
  1138. diag = client.diagnose_storage()
  1139. # Should still return results (with errors noted)
  1140. assert diag["connected"] is True
  1141. assert len(diag["errors"]) > 0
  1142. client.disconnect()
  1143. def test_failure_injection_count_decrements(self, ftp_client_factory, ftp_server):
  1144. """Failure injection with count decrements and eventually succeeds."""
  1145. ftp_server.add_file("cache/retry.bin", b"data after retry")
  1146. ftp_server.inject_failure("RETR", 550, "Temporary error.", count=1)
  1147. client = ftp_client_factory()
  1148. client.connect()
  1149. # First attempt fails
  1150. result1 = client.download_file("/cache/retry.bin")
  1151. assert result1 is None
  1152. # Second attempt succeeds (failure count exhausted)
  1153. result2 = client.download_file("/cache/retry.bin")
  1154. assert result2 == b"data after retry"
  1155. client.disconnect()
  1156. def test_upload_skips_voidresp(self, ftp_client_factory, ftp_server, tmp_path):
  1157. """Upload returns True without calling voidresp() for any model.
  1158. voidresp() is skipped for all models: A1 printers hang on it,
  1159. H2D printers delay the 226 response by 30+ seconds, and X1C/P1S
  1160. gain nothing from waiting. The file is on the SD card once
  1161. sendall() returns.
  1162. """
  1163. content = b"voidresp test data"
  1164. local = tmp_path / "voidresp_test.3mf"
  1165. local.write_bytes(content)
  1166. for model in ("X1C", "A1", "H2D", None):
  1167. client = ftp_client_factory(printer_model=model)
  1168. client.connect()
  1169. result = client.upload_file(local, "/cache/voidresp_test.3mf")
  1170. assert result is True, f"Upload failed for model={model}"
  1171. client.disconnect()
  1172. # Verify the file is actually on the server
  1173. time.sleep(_UPLOAD_FLUSH_DELAY)
  1174. client2 = ftp_client_factory()
  1175. client2.connect()
  1176. downloaded = client2.download_file("/cache/voidresp_test.3mf")
  1177. assert downloaded == content, f"Content mismatch for model={model}"
  1178. client2.disconnect()
  1179. # ---------------------------------------------------------------------------
  1180. # Short-circuit retries on 550 (#972)
  1181. # ---------------------------------------------------------------------------
  1182. class TestFileNotOnPrinterShortCircuit:
  1183. """FileNotOnPrinterError must bypass the retry budget.
  1184. Before this fix, a 3MF path that wasn't on the printer (550) cost
  1185. `ftp_retry_count + 1` attempts × `ftp_retry_delay` seconds per candidate
  1186. path. With ftp_retry_count=10 and four candidate paths, that's ~22 min
  1187. of dead retries before the real path is tried. #972 in the wild showed
  1188. 48 min of retrying paths that didn't exist.
  1189. """
  1190. async def test_with_ftp_retry_propagates_file_not_on_printer_without_retrying(self):
  1191. """with_ftp_retry raises FileNotOnPrinterError on first attempt.
  1192. Verifies non_retry_exceptions short-circuits before the retry loop
  1193. has a chance to sleep and try again.
  1194. """
  1195. attempts = {"n": 0}
  1196. async def always_missing(*_args, **_kwargs):
  1197. attempts["n"] += 1
  1198. raise FileNotOnPrinterError("/cache/absent.3mf: 550")
  1199. with pytest.raises(FileNotOnPrinterError):
  1200. await with_ftp_retry(
  1201. always_missing,
  1202. max_retries=10,
  1203. retry_delay=0.01,
  1204. operation_name="test 550 short-circuit",
  1205. non_retry_exceptions=(FileNotOnPrinterError,),
  1206. )
  1207. assert attempts["n"] == 1, "550 must not trigger any retry"
  1208. async def test_with_ftp_retry_still_retries_transient_errors(self):
  1209. """Non-550 exceptions continue to retry up to max_retries + 1."""
  1210. attempts = {"n": 0}
  1211. async def flaky(*_args, **_kwargs):
  1212. attempts["n"] += 1
  1213. raise TimeoutError("transient")
  1214. result = await with_ftp_retry(
  1215. flaky,
  1216. max_retries=2,
  1217. retry_delay=0.01,
  1218. operation_name="test transient retries",
  1219. non_retry_exceptions=(FileNotOnPrinterError,),
  1220. )
  1221. assert result is None
  1222. assert attempts["n"] == 3, "Transient errors should retry to exhaustion"
  1223. def test_download_to_file_raises_on_missing_path(self, ftp_client_factory, tmp_path):
  1224. """download_to_file surfaces 550 as FileNotOnPrinterError end-to-end
  1225. against the real mock FTPS server, not just a hand-rolled mock."""
  1226. local = tmp_path / "never_downloaded.3mf"
  1227. client = ftp_client_factory()
  1228. client.connect()
  1229. try:
  1230. with pytest.raises(FileNotOnPrinterError):
  1231. client.download_to_file("/cache/does_not_exist.3mf", local)
  1232. finally:
  1233. client.disconnect()
  1234. assert not local.exists(), "Partial file must be cleaned up on 550"
  1235. # ---------------------------------------------------------------------------
  1236. # 3MF download cache (#972)
  1237. # ---------------------------------------------------------------------------
  1238. class TestThreeMFCache:
  1239. """Cover endpoint and archive flow share downloaded 3MF bytes via this
  1240. cache. Tests isolate themselves with clear_3mf_cache(delete_files=False)
  1241. so they don't clobber each other."""
  1242. def setup_method(self):
  1243. clear_3mf_cache(delete_files=False)
  1244. def teardown_method(self):
  1245. clear_3mf_cache(delete_files=False)
  1246. def test_normalize_collapses_filename_variants(self):
  1247. """Bambu names vary (.3mf, .gcode.3mf, with spaces) — they all map
  1248. to the same cache slot so both flows agree on the key."""
  1249. canonical = normalize_3mf_name("Broly_Legendary.gcode.3mf")
  1250. assert normalize_3mf_name("Broly_Legendary.3mf") == canonical
  1251. assert normalize_3mf_name("Broly_Legendary") == canonical
  1252. # Bambu Studio rewrites spaces to underscores on upload — treat as equal
  1253. assert normalize_3mf_name("Broly Legendary") == canonical
  1254. # Case is also collapsed so keys match across capitalizations
  1255. assert normalize_3mf_name("BROLY_LEGENDARY.3MF") == canonical
  1256. def test_cache_hit_returns_stored_path(self, tmp_path):
  1257. """get_cached_3mf returns the same Path that was put in."""
  1258. f = tmp_path / "Broly.gcode.3mf"
  1259. f.write_bytes(b"fake 3mf content")
  1260. cache_3mf_download(1, "Broly.gcode.3mf", f)
  1261. assert get_cached_3mf(1, "Broly.gcode.3mf") == f
  1262. def test_cache_lookup_uses_normalized_name(self, tmp_path):
  1263. """Caching under .gcode.3mf and querying with bare name still hits."""
  1264. f = tmp_path / "Broly.gcode.3mf"
  1265. f.write_bytes(b"x")
  1266. cache_3mf_download(1, "Broly.gcode.3mf", f)
  1267. assert get_cached_3mf(1, "Broly.3mf") == f
  1268. assert get_cached_3mf(1, "Broly") == f
  1269. def test_cache_miss_on_different_printer(self, tmp_path):
  1270. """Printer id is part of the key — two printers never collide."""
  1271. f = tmp_path / "A.3mf"
  1272. f.write_bytes(b"x")
  1273. cache_3mf_download(1, "A.3mf", f)
  1274. assert get_cached_3mf(2, "A.3mf") is None
  1275. def test_cache_evicts_when_file_deleted(self, tmp_path):
  1276. """Stale entry (file gone) returns None and is dropped from the dict."""
  1277. f = tmp_path / "A.3mf"
  1278. f.write_bytes(b"x")
  1279. cache_3mf_download(1, "A.3mf", f)
  1280. f.unlink()
  1281. assert get_cached_3mf(1, "A.3mf") is None
  1282. # Re-populating after eviction works — no ghost entries remain.
  1283. f.write_bytes(b"y")
  1284. cache_3mf_download(1, "A.3mf", f)
  1285. assert get_cached_3mf(1, "A.3mf") == f
  1286. def test_clear_by_printer_scoped(self, tmp_path, monkeypatch):
  1287. """Clearing one printer leaves the other untouched."""
  1288. from backend.app.core import config as _config
  1289. monkeypatch.setattr(_config.settings, "archive_dir", tmp_path)
  1290. temp_dir = tmp_path / "temp"
  1291. temp_dir.mkdir()
  1292. f1 = temp_dir / "one.3mf"
  1293. f1.write_bytes(b"1")
  1294. f2 = temp_dir / "two.3mf"
  1295. f2.write_bytes(b"2")
  1296. cache_3mf_download(1, "one.3mf", f1)
  1297. cache_3mf_download(2, "two.3mf", f2)
  1298. clear_3mf_cache(1)
  1299. assert get_cached_3mf(1, "one.3mf") is None
  1300. assert get_cached_3mf(2, "two.3mf") == f2
  1301. # clear_3mf_cache defaulted to delete_files=True, so the temp file is gone
  1302. assert not f1.exists()
  1303. assert f2.exists()
  1304. def test_clear_without_deleting_files(self, tmp_path, monkeypatch):
  1305. """delete_files=False leaves files on disk — used by tests."""
  1306. from backend.app.core import config as _config
  1307. monkeypatch.setattr(_config.settings, "archive_dir", tmp_path)
  1308. temp_dir = tmp_path / "temp"
  1309. temp_dir.mkdir()
  1310. f = temp_dir / "keep.3mf"
  1311. f.write_bytes(b"x")
  1312. cache_3mf_download(1, "keep.3mf", f)
  1313. clear_3mf_cache(1, delete_files=False)
  1314. assert get_cached_3mf(1, "keep.3mf") is None
  1315. assert f.exists()
  1316. def test_clear_does_not_delete_persistent_files(self, tmp_path, monkeypatch):
  1317. """Regression for #1212 / "file disappeared overnight" reports.
  1318. Dispatch sites added in #1166 cache the live archive copy and library
  1319. file bytes — paths outside ``archive_dir/temp`` — so /cover can skip
  1320. FTP. Those files are user data; the cache cleanup must never unlink
  1321. them. Pre-fix, ``clear_3mf_cache(printer_id, delete_files=True)`` ran
  1322. on every ``on_print_complete`` and silently destroyed them, leaving a
  1323. DB row whose ``file_path`` pointed at nothing — breaking Reprint and
  1324. View G-code with a 404.
  1325. """
  1326. from backend.app.core import config as _config
  1327. monkeypatch.setattr(_config.settings, "archive_dir", tmp_path / "archive")
  1328. (tmp_path / "archive" / "temp").mkdir(parents=True)
  1329. archive_file = tmp_path / "archive" / "1" / "20260504_wallhooks" / "wallhooks.gcode.3mf"
  1330. archive_file.parent.mkdir(parents=True)
  1331. archive_file.write_bytes(b"archive bytes")
  1332. library_file = tmp_path / "library_files" / "abcd.3mf"
  1333. library_file.parent.mkdir(parents=True)
  1334. library_file.write_bytes(b"library bytes")
  1335. temp_file = tmp_path / "archive" / "temp" / "cover_1_x.3mf"
  1336. temp_file.write_bytes(b"temp bytes")
  1337. cache_3mf_download(1, "wallhooks.gcode.3mf", archive_file)
  1338. cache_3mf_download(1, "library.3mf", library_file)
  1339. cache_3mf_download(1, "cover_1_x.3mf", temp_file)
  1340. clear_3mf_cache(1)
  1341. # All three cache entries are dropped from the dict.
  1342. assert get_cached_3mf(1, "wallhooks.gcode.3mf") is None
  1343. assert get_cached_3mf(1, "library.3mf") is None
  1344. assert get_cached_3mf(1, "cover_1_x.3mf") is None
  1345. # But only the temp file is unlinked — user data survives.
  1346. assert archive_file.exists(), "archive 3mf must not be deleted by cache cleanup"
  1347. assert library_file.exists(), "library 3mf must not be deleted by cache cleanup"
  1348. assert not temp_file.exists(), "temp file should still be cleaned up"
  1349. @pytest.fixture
  1350. def slow_upload_client(monkeypatch):
  1351. """Replace BambuFTPClient with a fake whose upload streams slowly.
  1352. Mirrors the real client's contract for the bits that matter here: it fires
  1353. the progress callback once per chunk and treats a callback exception as
  1354. "stop now" — break out of the send loop, drop the partial file, re-raise.
  1355. The returned dict lets a test see what the worker thread actually did,
  1356. which is the whole point: the #2529 ghost transfer was invisible from the
  1357. event loop's side.
  1358. """
  1359. state = {
  1360. "attempts": 0,
  1361. "concurrent": 0,
  1362. "max_concurrent": 0,
  1363. "completed": False,
  1364. "cancelled": False,
  1365. "deleted": [],
  1366. "chunks": 20,
  1367. "chunk_delay": 0.05,
  1368. }
  1369. lock = threading.Lock()
  1370. class FakeClient:
  1371. def __init__(self, *args, **kwargs):
  1372. pass
  1373. def connect(self):
  1374. return True
  1375. def upload_file(self, local_path, remote_path, progress_callback=None):
  1376. with lock:
  1377. state["attempts"] += 1
  1378. state["concurrent"] += 1
  1379. state["max_concurrent"] = max(state["max_concurrent"], state["concurrent"])
  1380. try:
  1381. total = state["chunks"]
  1382. for sent in range(1, total + 1):
  1383. time.sleep(state["chunk_delay"])
  1384. if progress_callback:
  1385. try:
  1386. progress_callback(sent, total)
  1387. except Exception:
  1388. state["cancelled"] = True
  1389. state["deleted"].append(remote_path)
  1390. raise
  1391. state["completed"] = True
  1392. return True
  1393. finally:
  1394. with lock:
  1395. state["concurrent"] -= 1
  1396. def disconnect(self):
  1397. pass
  1398. monkeypatch.setattr(bambu_ftp, "BambuFTPClient", FakeClient)
  1399. monkeypatch.setattr(FakeClient, "_mode_cache", {}, raising=False)
  1400. monkeypatch.setattr(FakeClient, "A1_MODELS", ("A1", "A1 Mini"), raising=False)
  1401. monkeypatch.setattr(FakeClient, "cache_mode", staticmethod(lambda ip, mode: None), raising=False)
  1402. return state
  1403. # ---------------------------------------------------------------------------
  1404. # TestUploadDeadline (#2529)
  1405. # ---------------------------------------------------------------------------
  1406. class TestUploadDeadline:
  1407. """The upload deadline must be size-aware, and must actually stop the transfer.
  1408. Regression for #2529: a 96 MB 3MF to an A1 over WiFi sustains ~75 KB/s and
  1409. needs ~20 minutes. The old flat 600 s wall-clock cap declared it dead at
  1410. ~70 MB, `asyncio.wait_for` cancelled the *future* but not the executor
  1411. thread — which kept streaming — and `with_ftp_retry` then started a second
  1412. STOR of the same file onto the same printer. The reporter's video shows two
  1413. transfers of the same job climbing in parallel (2% and 72%), and the print
  1414. never landed.
  1415. """
  1416. def test_deadline_scales_with_file_size(self, tmp_path):
  1417. """A big file gets proportionally longer, a small one gets the floor."""
  1418. small = tmp_path / "small.3mf"
  1419. small.write_bytes(b"x" * 1024)
  1420. assert bambu_ftp._upload_deadline(small) == bambu_ftp._UPLOAD_MIN_TIMEOUT
  1421. # The reporter's file. At the 25 KB/s floor rate, 96 MB is ~64 minutes —
  1422. # far above the 600 s that killed it at 72%.
  1423. big = tmp_path / "big.3mf"
  1424. big.write_bytes(b"x" * (96 * 1024 * 1024))
  1425. deadline = bambu_ftp._upload_deadline(big)
  1426. assert deadline > bambu_ftp._UPLOAD_MIN_TIMEOUT
  1427. assert deadline == pytest.approx((96 * 1024 * 1024) / bambu_ftp._UPLOAD_FLOOR_BYTES_PER_SEC)
  1428. def test_deadline_falls_back_to_floor_for_unstatable_file(self, tmp_path):
  1429. assert bambu_ftp._upload_deadline(tmp_path / "nope.3mf") == bambu_ftp._UPLOAD_MIN_TIMEOUT
  1430. @pytest.mark.asyncio
  1431. async def test_timeout_stops_the_worker_thread(self, tmp_path, monkeypatch, slow_upload_client):
  1432. """The transfer stops when the deadline expires, instead of streaming on.
  1433. Mutation check: drop the `cancel.set()` in upload_file_async and the
  1434. worker runs to completion, which is exactly the ghost transfer #2529
  1435. reported.
  1436. """
  1437. state = slow_upload_client
  1438. local = tmp_path / "slow.3mf"
  1439. local.write_bytes(b"x" * 4096)
  1440. with pytest.raises(bambu_ftp.UploadCancelled):
  1441. await upload_file_async("127.0.0.1", "12345678", local, "/cache/slow.3mf", timeout=0.2, printer_model="X1C")
  1442. # The worker noticed the cancel and unwound — it did not run to the end.
  1443. await asyncio.sleep(0.5)
  1444. assert state["cancelled"] is True
  1445. assert state["completed"] is False
  1446. # And it cleaned the partial file off the printer on its way out.
  1447. assert state["deleted"] == ["/cache/slow.3mf"]
  1448. @pytest.mark.asyncio
  1449. async def test_timeout_is_not_retried(self, tmp_path, monkeypatch, slow_upload_client):
  1450. """with_ftp_retry must not start a second transfer after a deadline expiry.
  1451. This is the bug the reporter filmed: attempt 2 began while attempt 1 was
  1452. still sending. One attempt, then a hard failure.
  1453. """
  1454. state = slow_upload_client
  1455. local = tmp_path / "slow.3mf"
  1456. local.write_bytes(b"x" * 4096)
  1457. with pytest.raises(bambu_ftp.UploadCancelled):
  1458. await with_ftp_retry(
  1459. upload_file_async,
  1460. "127.0.0.1",
  1461. "12345678",
  1462. local,
  1463. "/cache/slow.3mf",
  1464. timeout=0.2,
  1465. printer_model="X1C",
  1466. max_retries=3,
  1467. retry_delay=0,
  1468. )
  1469. assert state["attempts"] == 1, "a timed-out upload must not be retried"
  1470. @pytest.mark.asyncio
  1471. async def test_uploads_to_one_printer_are_serialized(self, tmp_path, monkeypatch, slow_upload_client):
  1472. """Two dispatches to the same printer queue up; they never overlap.
  1473. Concurrent STORs of the same remote path leave a corrupt file on the SD
  1474. card and make the printer look like it has a flaky network.
  1475. """
  1476. state = slow_upload_client
  1477. state["chunk_delay"] = 0.05
  1478. local = tmp_path / "slow.3mf"
  1479. local.write_bytes(b"x" * 4096)
  1480. async def _dispatch(name: str) -> bool:
  1481. return await upload_file_async(
  1482. "127.0.0.1", "12345678", local, f"/cache/{name}.3mf", timeout=30.0, printer_model="X1C"
  1483. )
  1484. results = await asyncio.gather(_dispatch("a"), _dispatch("b"))
  1485. assert results == [True, True]
  1486. assert state["attempts"] == 2
  1487. assert state["max_concurrent"] == 1, "two uploads ran against the same printer at once"
  1488. def test_progress_callback_raising_deletes_the_partial_file(self, ftp_client_factory, ftp_root, tmp_path):
  1489. """The cancel path in the real client removes what it already wrote.
  1490. This is the mechanism the deadline now hangs off, exercised end to end
  1491. against the mock FTPS server rather than a fake.
  1492. """
  1493. client = ftp_client_factory()
  1494. assert client.connect() is True
  1495. try:
  1496. local = tmp_path / "cancelme.3mf"
  1497. # Two chunks, so the callback fires while there is a partial file.
  1498. local.write_bytes(b"x" * (BambuFTPClient.CHUNK_SIZE * 2))
  1499. def _stop_after_first_chunk(uploaded: int, total: int) -> None:
  1500. raise bambu_ftp.UploadCancelled("stop")
  1501. with pytest.raises(bambu_ftp.UploadCancelled):
  1502. client.upload_file(local, "/cancelme.3mf", _stop_after_first_chunk)
  1503. finally:
  1504. client.disconnect()
  1505. time.sleep(_UPLOAD_FLUSH_DELAY)
  1506. assert not (Path(ftp_root) / "cancelme.3mf").exists(), "partial file left on the printer"
  1507. # ---------------------------------------------------------------------------
  1508. # TestHandshakeCoolOff
  1509. # ---------------------------------------------------------------------------
  1510. class _PlaintextServer:
  1511. """A socket that accepts on 990 and answers in plaintext, not TLS.
  1512. This is what #2780's printers do once their file service wedges: the TCP
  1513. connect succeeds, so a port probe reports the printer as healthy, and then
  1514. the implicit-FTPS handshake dies on ``WRONG_VERSION_NUMBER`` because the
  1515. first bytes back are an FTP banner rather than a TLS record.
  1516. """
  1517. def __init__(self):
  1518. self._sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  1519. self._sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
  1520. self._sock.bind(("127.0.0.1", 0))
  1521. self._sock.listen(8)
  1522. self.port = self._sock.getsockname()[1]
  1523. self.accepts = 0
  1524. self._stop = threading.Event()
  1525. self._thread = threading.Thread(target=self._serve, daemon=True)
  1526. self._thread.start()
  1527. def _serve(self):
  1528. while not self._stop.is_set():
  1529. try:
  1530. conn, _addr = self._sock.accept()
  1531. except OSError:
  1532. return
  1533. self.accepts += 1
  1534. try:
  1535. conn.sendall(b"220 Welcome to the printer.\r\n")
  1536. except OSError:
  1537. pass
  1538. finally:
  1539. conn.close()
  1540. def stop(self):
  1541. self._stop.set()
  1542. self._sock.close()
  1543. self._thread.join(timeout=2)
  1544. @pytest.fixture()
  1545. def plaintext_server():
  1546. server = _PlaintextServer()
  1547. yield server
  1548. server.stop()
  1549. class TestHandshakeCoolOff:
  1550. """A wedged file service must be contacted once, not hundreds of times.
  1551. #2780: an X2D served clean FTPS for five days, flipped, and then failed
  1552. every handshake for eight more. Because each candidate path opened its own
  1553. connection, one reporter's log carried 3511 identical handshake failures.
  1554. """
  1555. def _client(self, server, ip="127.0.0.1"):
  1556. client = BambuFTPClient(ip, "12345678", timeout=5.0, printer_model="P2S")
  1557. client.FTP_PORT = server.port
  1558. return client
  1559. def test_plaintext_answer_on_990_blocks_the_printer(self, plaintext_server, caplog):
  1560. client = self._client(plaintext_server)
  1561. with caplog.at_level(logging.WARNING, logger="backend.app.services.bambu_ftp"):
  1562. assert client.connect() is False
  1563. assert bambu_ftp.ftps_handshake_blocked("127.0.0.1") is True
  1564. messages = [r.getMessage() for r in caplog.records]
  1565. assert any("WRONG_VERSION_NUMBER" in m for m in messages)
  1566. # The warning has to say more than the error: the port is open, so
  1567. # "unblock port 990" is the wrong reading and the operator needs to
  1568. # know what it actually costs them.
  1569. assert any("covers and timelapses cannot be fetched" in m for m in messages)
  1570. # It must NOT prescribe a restart. It used to, and #2780's reporter
  1571. # power-cycled both affected printers with no effect while a single
  1572. # manual connection to the same printers completed a clean handshake.
  1573. # Naming a remedy that is known not to work is worse than naming none.
  1574. assert not any("restart" in m.lower() for m in messages)
  1575. def test_blocked_printer_is_not_contacted_again(self, plaintext_server):
  1576. self._client(plaintext_server).connect()
  1577. # Two, not one: the failed handshake, then one cleartext read asking
  1578. # what the printer actually answered with (#2780). That read is the
  1579. # whole diagnosis and it happens once per cool-off, so the promise
  1580. # this test exists for -- contacted a couple of times, not ~110 --
  1581. # still holds.
  1582. assert plaintext_server.accepts == 2
  1583. for _ in range(5):
  1584. assert self._client(plaintext_server).connect() is False
  1585. # Still two: the cool-off answered without opening a socket, and it
  1586. # gates the probe as well as the handshake.
  1587. assert plaintext_server.accepts == 2
  1588. def test_cooloff_expiry_lets_the_printer_be_retried(self, plaintext_server, monkeypatch):
  1589. monkeypatch.setattr(bambu_ftp, "_HANDSHAKE_COOLOFF_SECONDS", 0.0)
  1590. self._client(plaintext_server).connect()
  1591. assert bambu_ftp.ftps_handshake_blocked("127.0.0.1") is False
  1592. assert self._client(plaintext_server).connect() is False
  1593. # Two handshakes and a cleartext probe on each. A zero-length cool-off
  1594. # is what makes the probe repeat -- it is gated on the window being
  1595. # already open, and here there is never a window. At the real 300s it
  1596. # runs once, which `test_blocked_printer_is_not_contacted_again` pins.
  1597. assert plaintext_server.accepts == 4
  1598. def test_block_is_per_printer(self, plaintext_server):
  1599. self._client(plaintext_server).connect()
  1600. assert bambu_ftp.ftps_handshake_blocked("127.0.0.1") is True
  1601. # A second printer that never failed must stay reachable.
  1602. assert bambu_ftp.ftps_handshake_blocked("192.0.2.77") is False
  1603. def test_expired_block_lets_a_recovered_printer_straight_back_in(self, ftp_client_factory):
  1604. """A power-cycled printer is picked up on the next print, not held out.
  1605. The expired entry is also dropped, so the map holds one key per
  1606. currently-wedged printer rather than one per printer this process has
  1607. ever failed against.
  1608. """
  1609. BambuFTPClient._handshake_blocked_until["127.0.0.1"] = time.monotonic() - 1
  1610. client = ftp_client_factory()
  1611. assert client.connect() is True
  1612. client.disconnect()
  1613. assert BambuFTPClient._handshake_blocked_until == {}