test_bambu_ftp.py 74 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864
  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_truncated_file_returns_false(self, ftp_client_factory, ftp_server, tmp_path):
  417. """The original #1401 fix is preserved: when SIZE confirms the file
  418. isn't on the server at full size (or SIZE itself fails), the upload
  419. must fail so the dispatcher doesn't send a print command for a
  420. partial 3MF."""
  421. import ftplib # nosec B402 — tests need the real ftplib to construct mock 426 responses
  422. local = tmp_path / "test.bin"
  423. local.write_bytes(b"data" * 256)
  424. client = ftp_client_factory()
  425. client.connect()
  426. def raise_426():
  427. raise ftplib.error_temp("426 Failure reading network stream.")
  428. # Make SIZE report a smaller value — file is genuinely truncated.
  429. def fake_size(_path):
  430. return 100
  431. client._ftp.voidresp = raise_426
  432. client._ftp.size = fake_size
  433. result = client.upload_file(local, "/cache/test.bin")
  434. assert result is False, "truncated file (SIZE mismatch) must fail"
  435. client.disconnect()
  436. def test_upload_426_with_size_check_failing_returns_false(self, ftp_client_factory, ftp_server, tmp_path):
  437. """If SIZE itself fails (e.g. server too broken to answer), assume
  438. the worst and fail — better a retry than a print on a partial file.
  439. """
  440. import ftplib # nosec B402 — tests need the real ftplib to construct mock 426 responses
  441. local = tmp_path / "test.bin"
  442. local.write_bytes(b"data" * 256)
  443. client = ftp_client_factory()
  444. client.connect()
  445. def raise_426():
  446. raise ftplib.error_temp("426 Failure reading network stream.")
  447. def raise_size(_path):
  448. raise ftplib.error_perm("550 File not found.")
  449. client._ftp.voidresp = raise_426
  450. client._ftp.size = raise_size
  451. result = client.upload_file(local, "/cache/test.bin")
  452. assert result is False
  453. client.disconnect()
  454. def test_upload_bytes_426_with_intact_file_proceeds(self, ftp_client_factory, ftp_server):
  455. """upload_bytes() mirrors the same SIZE-verify logic as upload_file."""
  456. import ftplib # nosec B402 — tests need the real ftplib to construct mock 426 responses
  457. client = ftp_client_factory()
  458. client.connect()
  459. data = b"x" * 1024
  460. def raise_426():
  461. raise ftplib.error_temp("426 Failure reading network stream.")
  462. def fake_size(_path):
  463. return 1024 # printer-side file matches expected size
  464. client._ftp.voidresp = raise_426
  465. client._ftp.size = fake_size
  466. result = client.upload_bytes(data, "/cache/bytes.bin")
  467. assert result is True
  468. client.disconnect()
  469. def test_upload_bytes_426_with_truncated_file_returns_false(self, ftp_client_factory, ftp_server):
  470. """The truncated branch for upload_bytes()."""
  471. import ftplib # nosec B402 — tests need the real ftplib to construct mock 426 responses
  472. client = ftp_client_factory()
  473. client.connect()
  474. data = b"x" * 1024
  475. def raise_426():
  476. raise ftplib.error_temp("426 Failure reading network stream.")
  477. def fake_size(_path):
  478. return 100
  479. client._ftp.voidresp = raise_426
  480. client._ftp.size = fake_size
  481. result = client.upload_bytes(data, "/cache/bytes.bin")
  482. assert result is False
  483. client.disconnect()
  484. def test_upload_bytes_success(self, ftp_client_factory, ftp_server):
  485. """upload_bytes() writes data to server."""
  486. data = b"Bytes upload content"
  487. client = ftp_client_factory()
  488. client.connect()
  489. result = client.upload_bytes(data, "/cache/bytes.bin")
  490. assert result is True
  491. client.disconnect()
  492. # Verify via fresh connection
  493. time.sleep(_UPLOAD_FLUSH_DELAY)
  494. client2 = ftp_client_factory()
  495. client2.connect()
  496. downloaded = client2.download_file("/cache/bytes.bin")
  497. assert downloaded == data
  498. client2.disconnect()
  499. def test_upload_bytes_failure(self, ftp_client_factory, ftp_server):
  500. """upload_bytes() returns False on STOR failure."""
  501. ftp_server.inject_failure("STOR", 553, "No space.")
  502. client = ftp_client_factory()
  503. client.connect()
  504. result = client.upload_bytes(b"data", "/cache/fail.bin")
  505. assert result is False
  506. client.disconnect()
  507. def test_upload_large_chunked(self, ftp_client_factory, ftp_server, tmp_path):
  508. """Large file upload in chunks completes without error.
  509. Uses 2.5MB to trigger multiple chunks with 64KB CHUNK_SIZE.
  510. Content verification skipped because upload_file() skips
  511. voidresp() for all models, so the server may still be flushing
  512. when we check. The upload result=True confirms the client sent
  513. all chunks without error.
  514. """
  515. content = b"C" * (1024 * 1024 * 2 + 512 * 1024)
  516. local = tmp_path / "large.bin"
  517. local.write_bytes(content)
  518. progress_calls = []
  519. def on_progress(uploaded, total):
  520. progress_calls.append((uploaded, total))
  521. client = ftp_client_factory()
  522. client.connect()
  523. result = client.upload_file(local, "/cache/large.bin", on_progress)
  524. assert result is True
  525. # Verify many chunks were sent (2.5MB / 64KB = 40 chunks)
  526. assert len(progress_calls) >= 38
  527. assert progress_calls[-1][0] == len(content)
  528. client.disconnect()
  529. # ---------------------------------------------------------------------------
  530. # TestDelete
  531. # ---------------------------------------------------------------------------
  532. class TestDelete:
  533. """Tests for file deletion."""
  534. def test_delete_success(self, ftp_client_factory, ftp_server):
  535. """Successful file deletion."""
  536. from backend.app.services.bambu_ftp import DeleteResult
  537. ftp_server.add_file("cache/to_delete.bin", b"delete me")
  538. client = ftp_client_factory()
  539. client.connect()
  540. result = client.delete_file("/cache/to_delete.bin")
  541. assert result == DeleteResult.DELETED
  542. assert not ftp_server.file_exists("cache/to_delete.bin")
  543. client.disconnect()
  544. def test_delete_not_found(self, ftp_client_factory):
  545. """Deleting a nonexistent file returns NOT_FOUND (550, #1721)."""
  546. from backend.app.services.bambu_ftp import DeleteResult
  547. client = ftp_client_factory()
  548. client.connect()
  549. result = client.delete_file("/cache/no_such_file.bin")
  550. assert result == DeleteResult.NOT_FOUND
  551. client.disconnect()
  552. def test_delete_not_connected(self):
  553. """Delete when not connected returns FAILED."""
  554. from backend.app.services.bambu_ftp import DeleteResult
  555. client = BambuFTPClient("127.0.0.1", "12345678")
  556. assert client.delete_file("/cache/test.bin") == DeleteResult.FAILED
  557. # ---------------------------------------------------------------------------
  558. # TestFileSize
  559. # ---------------------------------------------------------------------------
  560. class TestFileSize:
  561. """Tests for get_file_size."""
  562. def test_file_size_correct(self, ftp_client_factory, ftp_server):
  563. """Returns correct file size."""
  564. ftp_server.add_file("cache/sized.bin", b"a" * 4096)
  565. client = ftp_client_factory()
  566. client.connect()
  567. size = client.get_file_size("/cache/sized.bin")
  568. assert size == 4096
  569. client.disconnect()
  570. def test_file_size_missing(self, ftp_client_factory):
  571. """Returns None for missing file."""
  572. client = ftp_client_factory()
  573. client.connect()
  574. size = client.get_file_size("/cache/no_file.bin")
  575. assert size is None
  576. client.disconnect()
  577. def test_file_size_not_connected(self):
  578. """Returns None when not connected."""
  579. client = BambuFTPClient("127.0.0.1", "12345678")
  580. assert client.get_file_size("/cache/test.bin") is None
  581. # ---------------------------------------------------------------------------
  582. # TestStorageInfo
  583. # ---------------------------------------------------------------------------
  584. class TestStorageInfo:
  585. """Tests for storage info and diagnostics."""
  586. def test_avbl_parsed(self, ftp_client_factory, ftp_server):
  587. """AVBL response is parsed for free_bytes."""
  588. ftp_server.set_avbl_bytes(5000000000)
  589. client = ftp_client_factory()
  590. client.connect()
  591. info = client.get_storage_info()
  592. assert info is not None
  593. assert info["free_bytes"] == 5000000000
  594. client.disconnect()
  595. def test_used_bytes_from_scan(self, ftp_client_factory, ftp_server):
  596. """used_bytes calculated from directory scan."""
  597. ftp_server.add_file("cache/file1.bin", b"a" * 1000)
  598. ftp_server.add_file("cache/file2.bin", b"b" * 2000)
  599. client = ftp_client_factory()
  600. client.connect()
  601. info = client.get_storage_info()
  602. assert info is not None
  603. assert info["used_bytes"] >= 3000 # At least these two files
  604. client.disconnect()
  605. def test_storage_info_not_connected(self):
  606. """Returns None when not connected."""
  607. client = BambuFTPClient("127.0.0.1", "12345678")
  608. assert client.get_storage_info() is None
  609. def test_diagnose_storage_success(self, ftp_client_factory, ftp_server):
  610. """diagnose_storage() returns connected=True with working diagnostics."""
  611. client = ftp_client_factory()
  612. client.connect()
  613. diag = client.diagnose_storage()
  614. assert diag["connected"] is True
  615. assert diag["can_list_root"] is True
  616. assert diag["can_list_cache"] is True
  617. assert diag["pwd"] is not None
  618. assert diag["storage_info"] is not None
  619. client.disconnect()
  620. def test_diagnose_storage_not_connected(self):
  621. """diagnose_storage() reports not connected."""
  622. client = BambuFTPClient("127.0.0.1", "12345678")
  623. diag = client.diagnose_storage()
  624. assert diag["connected"] is False
  625. assert "FTP not connected" in diag["errors"]
  626. # ---------------------------------------------------------------------------
  627. # TestModelSpecificBehavior
  628. # ---------------------------------------------------------------------------
  629. class TestModelSpecificBehavior:
  630. """Tests for printer model-specific FTP behavior."""
  631. def test_x1c_upload(self, ftp_client_factory, ftp_server, tmp_path):
  632. """X1C upload with session reuse succeeds."""
  633. content = b"X1C upload data"
  634. local = tmp_path / "x1c.3mf"
  635. local.write_bytes(content)
  636. client = ftp_client_factory(printer_model="X1C")
  637. client.connect()
  638. result = client.upload_file(local, "/cache/x1c.3mf")
  639. assert result is True
  640. client.disconnect()
  641. # Verify via fresh connection
  642. time.sleep(_UPLOAD_FLUSH_DELAY)
  643. client2 = ftp_client_factory(printer_model="X1C")
  644. client2.connect()
  645. downloaded = client2.download_file("/cache/x1c.3mf")
  646. assert downloaded == content
  647. client2.disconnect()
  648. def test_a1_upload_prot_c(self, ftp_client_factory, ftp_server, tmp_path):
  649. """A1 model upload with prot_c succeeds."""
  650. content = b"A1 upload data"
  651. local = tmp_path / "a1.3mf"
  652. local.write_bytes(content)
  653. client = ftp_client_factory(printer_model="A1", force_prot_c=True)
  654. client.connect()
  655. result = client.upload_file(local, "/cache/a1.3mf")
  656. assert result is True
  657. client.disconnect()
  658. # Verify via fresh connection
  659. time.sleep(_UPLOAD_FLUSH_DELAY)
  660. client2 = ftp_client_factory(printer_model="A1", force_prot_c=True)
  661. client2.connect()
  662. downloaded = client2.download_file("/cache/a1.3mf")
  663. assert downloaded == content
  664. client2.disconnect()
  665. def test_a1_mini_upload(self, ftp_client_factory, ftp_server, tmp_path):
  666. """A1 Mini model upload succeeds."""
  667. content = b"A1 Mini data"
  668. local = tmp_path / "a1mini.3mf"
  669. local.write_bytes(content)
  670. client = ftp_client_factory(printer_model="A1 Mini", force_prot_c=True)
  671. client.connect()
  672. result = client.upload_file(local, "/cache/a1mini.3mf")
  673. assert result is True
  674. client.disconnect()
  675. def test_p1s_upload(self, ftp_client_factory, ftp_server, tmp_path):
  676. """P1S model upload with session reuse succeeds."""
  677. content = b"P1S upload data"
  678. local = tmp_path / "p1s.3mf"
  679. local.write_bytes(content)
  680. client = ftp_client_factory(printer_model="P1S")
  681. client.connect()
  682. result = client.upload_file(local, "/cache/p1s.3mf")
  683. assert result is True
  684. client.disconnect()
  685. def test_unknown_model_defaults_prot_p(self, ftp_client_factory):
  686. """Unknown model defaults to prot_p."""
  687. client = ftp_client_factory(printer_model="FuturePrinter3000")
  688. assert client._is_a1_model() is False
  689. assert client._should_use_prot_c() is False
  690. assert client.connect() is True
  691. client.disconnect()
  692. def test_mode_cache_persists_and_clears(self, ftp_client_factory):
  693. """Mode cache works within a test and clears between tests."""
  694. # Cache should be empty at start (autouse fixture clears it)
  695. assert BambuFTPClient._mode_cache == {}
  696. # Connect and cache a mode
  697. BambuFTPClient.cache_mode("127.0.0.1", "prot_p")
  698. assert BambuFTPClient._mode_cache["127.0.0.1"] == "prot_p"
  699. # New client for same IP uses cached mode
  700. client = ftp_client_factory(printer_model="A1")
  701. assert client._get_cached_mode() == "prot_p"
  702. assert client._should_use_prot_c() is False
  703. client.disconnect()
  704. # ---------------------------------------------------------------------------
  705. # TestAsyncWrappers
  706. # ---------------------------------------------------------------------------
  707. class TestAsyncWrappers:
  708. """Tests for async wrapper functions using patch_ftp_port fixture."""
  709. @pytest.mark.asyncio
  710. async def test_upload_file_async_success(self, patch_ftp_port, tmp_path):
  711. """upload_file_async succeeds for X1C."""
  712. content = b"async upload"
  713. local = tmp_path / "async_up.3mf"
  714. local.write_bytes(content)
  715. result = await upload_file_async(
  716. "127.0.0.1",
  717. "12345678",
  718. local,
  719. "/cache/async_up.3mf",
  720. timeout=30.0,
  721. printer_model="X1C",
  722. )
  723. assert result is True
  724. @pytest.mark.asyncio
  725. async def test_upload_file_async_a1_fallback(self, patch_ftp_port, tmp_path):
  726. """upload_file_async tries prot_p then falls back to prot_c for A1."""
  727. content = b"a1 async upload"
  728. local = tmp_path / "a1_async.3mf"
  729. local.write_bytes(content)
  730. # For A1 models, if prot_p succeeds we get True.
  731. # If prot_p fails, it tries prot_c. Either way should succeed
  732. # against our mock server which accepts both.
  733. result = await upload_file_async(
  734. "127.0.0.1",
  735. "12345678",
  736. local,
  737. "/cache/a1_async.3mf",
  738. timeout=30.0,
  739. printer_model="A1",
  740. )
  741. assert result is True
  742. @pytest.mark.asyncio
  743. async def test_download_file_async_success(self, patch_ftp_port, tmp_path):
  744. """download_file_async succeeds."""
  745. server = patch_ftp_port
  746. content = b"async download content"
  747. server.add_file("cache/async_dl.bin", content)
  748. local = tmp_path / "async_dl.bin"
  749. result = await download_file_async(
  750. "127.0.0.1",
  751. "12345678",
  752. "/cache/async_dl.bin",
  753. local,
  754. timeout=30.0,
  755. printer_model="X1C",
  756. )
  757. assert result is True
  758. assert local.read_bytes() == content
  759. @pytest.mark.asyncio
  760. async def test_download_file_async_a1_fallback(self, patch_ftp_port, tmp_path):
  761. """download_file_async falls back for A1 models."""
  762. server = patch_ftp_port
  763. server.add_file("cache/a1_dl.bin", b"a1 data")
  764. local = tmp_path / "a1_dl.bin"
  765. result = await download_file_async(
  766. "127.0.0.1",
  767. "12345678",
  768. "/cache/a1_dl.bin",
  769. local,
  770. timeout=30.0,
  771. printer_model="A1",
  772. )
  773. assert result is True
  774. @pytest.mark.asyncio
  775. async def test_download_file_async_timeout_salvages_completed_zombie(self, tmp_path, monkeypatch):
  776. """Executor thread that completes after wait_for timeout is salvaged.
  777. asyncio.wait_for cannot cancel run_in_executor threads, so the FTP
  778. download may still complete after we give up waiting. If the thread
  779. genuinely finished (signalled via completion["success"] and the file
  780. is on disk), download_file_async should return True rather than False.
  781. Regression for #972: A1 user with 14 MB 3MF hit the hardcoded 60s
  782. timeout, but the download thread finished ~45s later. The successful
  783. file was written to disk but the async wrapper returned False, so the
  784. archive was created as a fallback with no 3MF data.
  785. """
  786. from backend.app.services import bambu_ftp
  787. # Clear mode cache so prot_p path is exercised.
  788. bambu_ftp.BambuFTPClient._mode_cache.pop("127.0.0.1", None)
  789. local = tmp_path / "zombie.bin"
  790. expected_content = b"late arrival but complete"
  791. class FakeClient:
  792. """Connects instantly, download_to_file sleeps past wait_for's
  793. timeout then writes the file and returns True."""
  794. def __init__(self, *args, **kwargs):
  795. pass
  796. def connect(self):
  797. return True
  798. def download_to_file(self, remote_path, local_path, **_kwargs):
  799. time.sleep(0.4) # longer than wait_for timeout=0.1
  800. local_path.write_bytes(expected_content)
  801. return True
  802. def disconnect(self):
  803. pass
  804. monkeypatch.setattr(bambu_ftp, "BambuFTPClient", FakeClient)
  805. monkeypatch.setattr(FakeClient, "_mode_cache", {}, raising=False)
  806. monkeypatch.setattr(FakeClient, "A1_MODELS", {"A1"}, raising=False)
  807. def _noop_cache(ip, mode):
  808. pass
  809. monkeypatch.setattr(FakeClient, "cache_mode", staticmethod(_noop_cache), raising=False)
  810. result = await download_file_async(
  811. "127.0.0.1",
  812. "12345678",
  813. "/cache/zombie.bin",
  814. local,
  815. timeout=0.1,
  816. printer_model="X1C",
  817. )
  818. assert result is True
  819. assert local.read_bytes() == expected_content
  820. @pytest.mark.asyncio
  821. async def test_download_file_async_timeout_no_salvage_when_incomplete(self, tmp_path, monkeypatch):
  822. """Timeout returns False when thread has not signalled success.
  823. A partial file on disk (mid-retrbinary) must NOT be mistaken for a
  824. completed download — only the thread's explicit success flag permits
  825. salvage.
  826. """
  827. from backend.app.services import bambu_ftp
  828. bambu_ftp.BambuFTPClient._mode_cache.pop("127.0.0.1", None)
  829. local = tmp_path / "partial.bin"
  830. class FakeClient:
  831. def __init__(self, *args, **kwargs):
  832. pass
  833. def connect(self):
  834. return True
  835. def download_to_file(self, remote_path, local_path, **kwargs):
  836. # Simulate an in-progress partial write that never completes
  837. # until the async timeout asks the worker to unwind.
  838. local_path.write_bytes(b"partial...")
  839. while not kwargs["cancel_event"].is_set():
  840. time.sleep(0.01)
  841. local_path.unlink(missing_ok=True)
  842. raise bambu_ftp.DownloadCancelled(remote_path)
  843. def disconnect(self):
  844. pass
  845. monkeypatch.setattr(bambu_ftp, "BambuFTPClient", FakeClient)
  846. monkeypatch.setattr(FakeClient, "_mode_cache", {}, raising=False)
  847. monkeypatch.setattr(FakeClient, "A1_MODELS", set(), raising=False)
  848. monkeypatch.setattr(FakeClient, "cache_mode", staticmethod(lambda ip, mode: None), raising=False)
  849. result = await download_file_async(
  850. "127.0.0.1",
  851. "12345678",
  852. "/cache/partial.bin",
  853. local,
  854. timeout=0.1,
  855. printer_model="X1C",
  856. )
  857. assert result is False
  858. @pytest.mark.asyncio
  859. async def test_download_file_async_timeout_waits_for_slow_zombie(self, tmp_path, monkeypatch):
  860. """A zombie that completes within the 30s grace window is salvaged.
  861. Regression for #1014: on slow WiFi, download_to_file can overshoot the
  862. user's ftp_timeout by 10–30 s without being stuck. The old fixed 0.5 s
  863. post-timeout sleep was too short — it gave up and started attempt 2
  864. while attempt 1's zombie thread kept running, and by the time the zombie
  865. wrote the file to disk with a success flag, attempt 2 had already
  866. reported failure (its own completion dict was still False). The async
  867. wrapper now waits up to min(timeout, 30 s) for the worker thread to
  868. finish before returning, so a slow-but-progressing download salvages.
  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 / "slow_zombie.bin"
  873. expected_content = b"finished during grace window"
  874. class FakeClient:
  875. """Mimics a slow FTP: wait_for gives up at 1.0 s but RETR takes
  876. 1.5 s total. Old 0.5 s fixed sleep would have bailed (0.5 < 0.5
  877. extra); new grace = max(min(1.0, 30), 0.5) = 1.0 s covers the
  878. remaining 0.5 s so salvage succeeds."""
  879. def __init__(self, *args, **kwargs):
  880. pass
  881. def connect(self):
  882. return True
  883. def download_to_file(self, remote_path, local_path, **_kwargs):
  884. time.sleep(1.5) # wait_for times out at 1.0 s; zombie finishes 0.5 s later
  885. local_path.write_bytes(expected_content)
  886. return True
  887. def disconnect(self):
  888. pass
  889. monkeypatch.setattr(bambu_ftp, "BambuFTPClient", FakeClient)
  890. monkeypatch.setattr(FakeClient, "_mode_cache", {}, raising=False)
  891. monkeypatch.setattr(FakeClient, "A1_MODELS", set(), raising=False)
  892. monkeypatch.setattr(FakeClient, "cache_mode", staticmethod(lambda ip, mode: None), raising=False)
  893. result = await download_file_async(
  894. "127.0.0.1",
  895. "12345678",
  896. "/cache/slow_zombie.bin",
  897. local,
  898. timeout=1.0,
  899. printer_model="X1C",
  900. )
  901. assert result is True
  902. assert local.read_bytes() == expected_content
  903. @pytest.mark.asyncio
  904. async def test_download_file_async_cancellation_waits_for_worker_cleanup(self, tmp_path, monkeypatch):
  905. """Task cancellation returns only after the FTP worker has unwound."""
  906. from backend.app.services import bambu_ftp
  907. bambu_ftp.BambuFTPClient._mode_cache.pop("127.0.0.1", None)
  908. local = tmp_path / "cancelled.bin"
  909. started = threading.Event()
  910. finished = threading.Event()
  911. class FakeClient:
  912. def __init__(self, *args, **kwargs):
  913. pass
  914. def connect(self):
  915. return True
  916. def download_to_file(self, remote_path, local_path, **kwargs):
  917. local_path.write_bytes(b"partial")
  918. started.set()
  919. try:
  920. while not kwargs["cancel_event"].is_set():
  921. time.sleep(0.01)
  922. local_path.unlink(missing_ok=True)
  923. raise bambu_ftp.DownloadCancelled(remote_path)
  924. finally:
  925. finished.set()
  926. def disconnect(self):
  927. pass
  928. monkeypatch.setattr(bambu_ftp, "BambuFTPClient", FakeClient)
  929. monkeypatch.setattr(FakeClient, "_mode_cache", {}, raising=False)
  930. monkeypatch.setattr(FakeClient, "A1_MODELS", set(), raising=False)
  931. monkeypatch.setattr(FakeClient, "cache_mode", staticmethod(lambda ip, mode: None), raising=False)
  932. task = asyncio.create_task(
  933. download_file_async(
  934. "127.0.0.1",
  935. "12345678",
  936. "/cache/cancelled.bin",
  937. local,
  938. timeout=30.0,
  939. printer_model="X1C",
  940. )
  941. )
  942. assert await asyncio.to_thread(started.wait, 1.0)
  943. task.cancel()
  944. with pytest.raises(asyncio.CancelledError):
  945. await task
  946. assert finished.is_set()
  947. assert not local.exists()
  948. @pytest.mark.asyncio
  949. async def test_download_file_try_paths_first_succeeds(self, patch_ftp_port, tmp_path):
  950. """download_file_try_paths_async succeeds on first path."""
  951. server = patch_ftp_port
  952. server.add_file("cache/try1.bin", b"first path")
  953. local = tmp_path / "try.bin"
  954. result = await download_file_try_paths_async(
  955. "127.0.0.1",
  956. "12345678",
  957. ["/cache/try1.bin", "/cache/try2.bin"],
  958. local,
  959. printer_model="X1C",
  960. )
  961. # The path, not a flag: the caller logs which candidate served the file
  962. # so a stale same-named copy is diagnosable (#1820).
  963. assert result == "/cache/try1.bin"
  964. assert local.read_bytes() == b"first path"
  965. @pytest.mark.asyncio
  966. async def test_download_file_try_paths_fallback(self, patch_ftp_port, tmp_path):
  967. """download_file_try_paths_async falls back to second path."""
  968. server = patch_ftp_port
  969. server.add_file("cache/second.bin", b"second path")
  970. local = tmp_path / "fallback.bin"
  971. result = await download_file_try_paths_async(
  972. "127.0.0.1",
  973. "12345678",
  974. ["/cache/missing.bin", "/cache/second.bin"],
  975. local,
  976. printer_model="X1C",
  977. )
  978. assert result == "/cache/second.bin"
  979. assert local.read_bytes() == b"second path"
  980. @pytest.mark.asyncio
  981. async def test_list_files_async_success(self, patch_ftp_port):
  982. """list_files_async returns file list."""
  983. server = patch_ftp_port
  984. server.add_file("cache/listed.bin", b"data")
  985. result = await list_files_async(
  986. "127.0.0.1",
  987. "12345678",
  988. "/cache",
  989. timeout=30.0,
  990. printer_model="X1C",
  991. )
  992. names = {f["name"] for f in result}
  993. assert "listed.bin" in names
  994. @pytest.mark.asyncio
  995. async def test_delete_file_async_success(self, patch_ftp_port):
  996. """delete_file_async deletes a file."""
  997. from backend.app.services.bambu_ftp import DeleteResult
  998. server = patch_ftp_port
  999. server.add_file("cache/to_async_del.bin", b"delete me")
  1000. result = await delete_file_async(
  1001. "127.0.0.1",
  1002. "12345678",
  1003. "/cache/to_async_del.bin",
  1004. printer_model="X1C",
  1005. )
  1006. assert result == DeleteResult.DELETED
  1007. assert not server.file_exists("cache/to_async_del.bin")
  1008. @pytest.mark.asyncio
  1009. async def test_delete_file_async_not_found(self, patch_ftp_port):
  1010. """delete_file_async distinguishes 550 from real failure (#1721)."""
  1011. from backend.app.services.bambu_ftp import DeleteResult
  1012. result = await delete_file_async(
  1013. "127.0.0.1",
  1014. "12345678",
  1015. "/cache/never_existed.bin",
  1016. printer_model="X1C",
  1017. )
  1018. assert result == DeleteResult.NOT_FOUND
  1019. # ---------------------------------------------------------------------------
  1020. # TestFailureScenarios
  1021. # ---------------------------------------------------------------------------
  1022. class TestFailureScenarios:
  1023. """Regression tests for known FTP failure modes."""
  1024. def test_550_caught_by_broad_except(self, ftp_client_factory, ftp_server, tmp_path):
  1025. """550 error_perm is caught by (OSError, ftplib.Error) handler.
  1026. Regression: error_perm is a subclass of ftplib.Error, so the
  1027. broad except clause in upload_file catches it correctly.
  1028. """
  1029. ftp_server.inject_failure("STOR", 550, "Permission denied.")
  1030. local = tmp_path / "test.bin"
  1031. local.write_bytes(b"data")
  1032. client = ftp_client_factory()
  1033. client.connect()
  1034. result = client.upload_file(local, "/cache/test.bin")
  1035. assert result is False
  1036. client.disconnect()
  1037. def test_zero_byte_download_detected(self, ftp_client_factory, ftp_server, tmp_path):
  1038. """0-byte download is detected and file is cleaned up.
  1039. Regression: Prior to fix, 0-byte downloads were reported as success.
  1040. """
  1041. ftp_server.add_file("cache/zero.bin", b"")
  1042. local = tmp_path / "zero.bin"
  1043. client = ftp_client_factory()
  1044. client.connect()
  1045. result = client.download_to_file("/cache/zero.bin", local)
  1046. assert result is False
  1047. assert not local.exists()
  1048. client.disconnect()
  1049. def test_connection_refused_handled(self):
  1050. """Connection refused is handled gracefully."""
  1051. client = BambuFTPClient("127.0.0.1", "12345678", timeout=2.0)
  1052. client.FTP_PORT = 1 # Almost certainly not listening
  1053. assert client.connect() is False
  1054. def test_auth_failure_530(self, ftp_client_factory, ftp_server):
  1055. """530 authentication failure returns False."""
  1056. ftp_server.inject_failure("PASS", 530, "Login incorrect.")
  1057. client = ftp_client_factory()
  1058. result = client.connect()
  1059. assert result is False
  1060. def test_retr_550_handled(self, ftp_client_factory, ftp_server):
  1061. """RETR 550 (file not found) returns None."""
  1062. ftp_server.inject_failure("RETR", 550, "File not found.")
  1063. ftp_server.add_file("cache/exists.bin", b"data")
  1064. client = ftp_client_factory()
  1065. client.connect()
  1066. result = client.download_file("/cache/exists.bin")
  1067. assert result is None
  1068. client.disconnect()
  1069. def test_cwd_550_handled(self, ftp_client_factory, ftp_server):
  1070. """CWD 550 is handled in list_files."""
  1071. ftp_server.inject_failure("CWD", 550, "Directory not found.")
  1072. client = ftp_client_factory()
  1073. client.connect()
  1074. result = client.list_files("/nonexistent")
  1075. assert result == []
  1076. client.disconnect()
  1077. def test_stor_553_handled(self, ftp_client_factory, ftp_server, tmp_path):
  1078. """STOR 553 (no SD card) handled gracefully."""
  1079. ftp_server.inject_failure("STOR", 553, "Could not create file.")
  1080. local = tmp_path / "test.bin"
  1081. local.write_bytes(b"test")
  1082. client = ftp_client_factory()
  1083. client.connect()
  1084. result = client.upload_file(local, "/cache/test.bin")
  1085. assert result is False
  1086. client.disconnect()
  1087. def test_diagnose_storage_cwd_failure_doesnt_propagate(self, ftp_client_factory, ftp_server):
  1088. """diagnose_storage CWD failure doesn't crash the whole operation.
  1089. Regression: diagnose_storage() was called in the upload path and
  1090. a CWD failure would propagate and crash the upload.
  1091. """
  1092. ftp_server.inject_failure("CWD", 550, "No such directory.", count=2)
  1093. client = ftp_client_factory()
  1094. client.connect()
  1095. diag = client.diagnose_storage()
  1096. # Should still return results (with errors noted)
  1097. assert diag["connected"] is True
  1098. assert len(diag["errors"]) > 0
  1099. client.disconnect()
  1100. def test_failure_injection_count_decrements(self, ftp_client_factory, ftp_server):
  1101. """Failure injection with count decrements and eventually succeeds."""
  1102. ftp_server.add_file("cache/retry.bin", b"data after retry")
  1103. ftp_server.inject_failure("RETR", 550, "Temporary error.", count=1)
  1104. client = ftp_client_factory()
  1105. client.connect()
  1106. # First attempt fails
  1107. result1 = client.download_file("/cache/retry.bin")
  1108. assert result1 is None
  1109. # Second attempt succeeds (failure count exhausted)
  1110. result2 = client.download_file("/cache/retry.bin")
  1111. assert result2 == b"data after retry"
  1112. client.disconnect()
  1113. def test_upload_skips_voidresp(self, ftp_client_factory, ftp_server, tmp_path):
  1114. """Upload returns True without calling voidresp() for any model.
  1115. voidresp() is skipped for all models: A1 printers hang on it,
  1116. H2D printers delay the 226 response by 30+ seconds, and X1C/P1S
  1117. gain nothing from waiting. The file is on the SD card once
  1118. sendall() returns.
  1119. """
  1120. content = b"voidresp test data"
  1121. local = tmp_path / "voidresp_test.3mf"
  1122. local.write_bytes(content)
  1123. for model in ("X1C", "A1", "H2D", None):
  1124. client = ftp_client_factory(printer_model=model)
  1125. client.connect()
  1126. result = client.upload_file(local, "/cache/voidresp_test.3mf")
  1127. assert result is True, f"Upload failed for model={model}"
  1128. client.disconnect()
  1129. # Verify the file is actually on the server
  1130. time.sleep(_UPLOAD_FLUSH_DELAY)
  1131. client2 = ftp_client_factory()
  1132. client2.connect()
  1133. downloaded = client2.download_file("/cache/voidresp_test.3mf")
  1134. assert downloaded == content, f"Content mismatch for model={model}"
  1135. client2.disconnect()
  1136. # ---------------------------------------------------------------------------
  1137. # Short-circuit retries on 550 (#972)
  1138. # ---------------------------------------------------------------------------
  1139. class TestFileNotOnPrinterShortCircuit:
  1140. """FileNotOnPrinterError must bypass the retry budget.
  1141. Before this fix, a 3MF path that wasn't on the printer (550) cost
  1142. `ftp_retry_count + 1` attempts × `ftp_retry_delay` seconds per candidate
  1143. path. With ftp_retry_count=10 and four candidate paths, that's ~22 min
  1144. of dead retries before the real path is tried. #972 in the wild showed
  1145. 48 min of retrying paths that didn't exist.
  1146. """
  1147. async def test_with_ftp_retry_propagates_file_not_on_printer_without_retrying(self):
  1148. """with_ftp_retry raises FileNotOnPrinterError on first attempt.
  1149. Verifies non_retry_exceptions short-circuits before the retry loop
  1150. has a chance to sleep and try again.
  1151. """
  1152. attempts = {"n": 0}
  1153. async def always_missing(*_args, **_kwargs):
  1154. attempts["n"] += 1
  1155. raise FileNotOnPrinterError("/cache/absent.3mf: 550")
  1156. with pytest.raises(FileNotOnPrinterError):
  1157. await with_ftp_retry(
  1158. always_missing,
  1159. max_retries=10,
  1160. retry_delay=0.01,
  1161. operation_name="test 550 short-circuit",
  1162. non_retry_exceptions=(FileNotOnPrinterError,),
  1163. )
  1164. assert attempts["n"] == 1, "550 must not trigger any retry"
  1165. async def test_with_ftp_retry_still_retries_transient_errors(self):
  1166. """Non-550 exceptions continue to retry up to max_retries + 1."""
  1167. attempts = {"n": 0}
  1168. async def flaky(*_args, **_kwargs):
  1169. attempts["n"] += 1
  1170. raise TimeoutError("transient")
  1171. result = await with_ftp_retry(
  1172. flaky,
  1173. max_retries=2,
  1174. retry_delay=0.01,
  1175. operation_name="test transient retries",
  1176. non_retry_exceptions=(FileNotOnPrinterError,),
  1177. )
  1178. assert result is None
  1179. assert attempts["n"] == 3, "Transient errors should retry to exhaustion"
  1180. def test_download_to_file_raises_on_missing_path(self, ftp_client_factory, tmp_path):
  1181. """download_to_file surfaces 550 as FileNotOnPrinterError end-to-end
  1182. against the real mock FTPS server, not just a hand-rolled mock."""
  1183. local = tmp_path / "never_downloaded.3mf"
  1184. client = ftp_client_factory()
  1185. client.connect()
  1186. try:
  1187. with pytest.raises(FileNotOnPrinterError):
  1188. client.download_to_file("/cache/does_not_exist.3mf", local)
  1189. finally:
  1190. client.disconnect()
  1191. assert not local.exists(), "Partial file must be cleaned up on 550"
  1192. # ---------------------------------------------------------------------------
  1193. # 3MF download cache (#972)
  1194. # ---------------------------------------------------------------------------
  1195. class TestThreeMFCache:
  1196. """Cover endpoint and archive flow share downloaded 3MF bytes via this
  1197. cache. Tests isolate themselves with clear_3mf_cache(delete_files=False)
  1198. so they don't clobber each other."""
  1199. def setup_method(self):
  1200. clear_3mf_cache(delete_files=False)
  1201. def teardown_method(self):
  1202. clear_3mf_cache(delete_files=False)
  1203. def test_normalize_collapses_filename_variants(self):
  1204. """Bambu names vary (.3mf, .gcode.3mf, with spaces) — they all map
  1205. to the same cache slot so both flows agree on the key."""
  1206. canonical = normalize_3mf_name("Broly_Legendary.gcode.3mf")
  1207. assert normalize_3mf_name("Broly_Legendary.3mf") == canonical
  1208. assert normalize_3mf_name("Broly_Legendary") == canonical
  1209. # Bambu Studio rewrites spaces to underscores on upload — treat as equal
  1210. assert normalize_3mf_name("Broly Legendary") == canonical
  1211. # Case is also collapsed so keys match across capitalizations
  1212. assert normalize_3mf_name("BROLY_LEGENDARY.3MF") == canonical
  1213. def test_cache_hit_returns_stored_path(self, tmp_path):
  1214. """get_cached_3mf returns the same Path that was put in."""
  1215. f = tmp_path / "Broly.gcode.3mf"
  1216. f.write_bytes(b"fake 3mf content")
  1217. cache_3mf_download(1, "Broly.gcode.3mf", f)
  1218. assert get_cached_3mf(1, "Broly.gcode.3mf") == f
  1219. def test_cache_lookup_uses_normalized_name(self, tmp_path):
  1220. """Caching under .gcode.3mf and querying with bare name still hits."""
  1221. f = tmp_path / "Broly.gcode.3mf"
  1222. f.write_bytes(b"x")
  1223. cache_3mf_download(1, "Broly.gcode.3mf", f)
  1224. assert get_cached_3mf(1, "Broly.3mf") == f
  1225. assert get_cached_3mf(1, "Broly") == f
  1226. def test_cache_miss_on_different_printer(self, tmp_path):
  1227. """Printer id is part of the key — two printers never collide."""
  1228. f = tmp_path / "A.3mf"
  1229. f.write_bytes(b"x")
  1230. cache_3mf_download(1, "A.3mf", f)
  1231. assert get_cached_3mf(2, "A.3mf") is None
  1232. def test_cache_evicts_when_file_deleted(self, tmp_path):
  1233. """Stale entry (file gone) returns None and is dropped from the dict."""
  1234. f = tmp_path / "A.3mf"
  1235. f.write_bytes(b"x")
  1236. cache_3mf_download(1, "A.3mf", f)
  1237. f.unlink()
  1238. assert get_cached_3mf(1, "A.3mf") is None
  1239. # Re-populating after eviction works — no ghost entries remain.
  1240. f.write_bytes(b"y")
  1241. cache_3mf_download(1, "A.3mf", f)
  1242. assert get_cached_3mf(1, "A.3mf") == f
  1243. def test_clear_by_printer_scoped(self, tmp_path, monkeypatch):
  1244. """Clearing one printer leaves the other untouched."""
  1245. from backend.app.core import config as _config
  1246. monkeypatch.setattr(_config.settings, "archive_dir", tmp_path)
  1247. temp_dir = tmp_path / "temp"
  1248. temp_dir.mkdir()
  1249. f1 = temp_dir / "one.3mf"
  1250. f1.write_bytes(b"1")
  1251. f2 = temp_dir / "two.3mf"
  1252. f2.write_bytes(b"2")
  1253. cache_3mf_download(1, "one.3mf", f1)
  1254. cache_3mf_download(2, "two.3mf", f2)
  1255. clear_3mf_cache(1)
  1256. assert get_cached_3mf(1, "one.3mf") is None
  1257. assert get_cached_3mf(2, "two.3mf") == f2
  1258. # clear_3mf_cache defaulted to delete_files=True, so the temp file is gone
  1259. assert not f1.exists()
  1260. assert f2.exists()
  1261. def test_clear_without_deleting_files(self, tmp_path, monkeypatch):
  1262. """delete_files=False leaves files on disk — used by tests."""
  1263. from backend.app.core import config as _config
  1264. monkeypatch.setattr(_config.settings, "archive_dir", tmp_path)
  1265. temp_dir = tmp_path / "temp"
  1266. temp_dir.mkdir()
  1267. f = temp_dir / "keep.3mf"
  1268. f.write_bytes(b"x")
  1269. cache_3mf_download(1, "keep.3mf", f)
  1270. clear_3mf_cache(1, delete_files=False)
  1271. assert get_cached_3mf(1, "keep.3mf") is None
  1272. assert f.exists()
  1273. def test_clear_does_not_delete_persistent_files(self, tmp_path, monkeypatch):
  1274. """Regression for #1212 / "file disappeared overnight" reports.
  1275. Dispatch sites added in #1166 cache the live archive copy and library
  1276. file bytes — paths outside ``archive_dir/temp`` — so /cover can skip
  1277. FTP. Those files are user data; the cache cleanup must never unlink
  1278. them. Pre-fix, ``clear_3mf_cache(printer_id, delete_files=True)`` ran
  1279. on every ``on_print_complete`` and silently destroyed them, leaving a
  1280. DB row whose ``file_path`` pointed at nothing — breaking Reprint and
  1281. View G-code with a 404.
  1282. """
  1283. from backend.app.core import config as _config
  1284. monkeypatch.setattr(_config.settings, "archive_dir", tmp_path / "archive")
  1285. (tmp_path / "archive" / "temp").mkdir(parents=True)
  1286. archive_file = tmp_path / "archive" / "1" / "20260504_wallhooks" / "wallhooks.gcode.3mf"
  1287. archive_file.parent.mkdir(parents=True)
  1288. archive_file.write_bytes(b"archive bytes")
  1289. library_file = tmp_path / "library_files" / "abcd.3mf"
  1290. library_file.parent.mkdir(parents=True)
  1291. library_file.write_bytes(b"library bytes")
  1292. temp_file = tmp_path / "archive" / "temp" / "cover_1_x.3mf"
  1293. temp_file.write_bytes(b"temp bytes")
  1294. cache_3mf_download(1, "wallhooks.gcode.3mf", archive_file)
  1295. cache_3mf_download(1, "library.3mf", library_file)
  1296. cache_3mf_download(1, "cover_1_x.3mf", temp_file)
  1297. clear_3mf_cache(1)
  1298. # All three cache entries are dropped from the dict.
  1299. assert get_cached_3mf(1, "wallhooks.gcode.3mf") is None
  1300. assert get_cached_3mf(1, "library.3mf") is None
  1301. assert get_cached_3mf(1, "cover_1_x.3mf") is None
  1302. # But only the temp file is unlinked — user data survives.
  1303. assert archive_file.exists(), "archive 3mf must not be deleted by cache cleanup"
  1304. assert library_file.exists(), "library 3mf must not be deleted by cache cleanup"
  1305. assert not temp_file.exists(), "temp file should still be cleaned up"
  1306. @pytest.fixture
  1307. def slow_upload_client(monkeypatch):
  1308. """Replace BambuFTPClient with a fake whose upload streams slowly.
  1309. Mirrors the real client's contract for the bits that matter here: it fires
  1310. the progress callback once per chunk and treats a callback exception as
  1311. "stop now" — break out of the send loop, drop the partial file, re-raise.
  1312. The returned dict lets a test see what the worker thread actually did,
  1313. which is the whole point: the #2529 ghost transfer was invisible from the
  1314. event loop's side.
  1315. """
  1316. state = {
  1317. "attempts": 0,
  1318. "concurrent": 0,
  1319. "max_concurrent": 0,
  1320. "completed": False,
  1321. "cancelled": False,
  1322. "deleted": [],
  1323. "chunks": 20,
  1324. "chunk_delay": 0.05,
  1325. }
  1326. lock = threading.Lock()
  1327. class FakeClient:
  1328. def __init__(self, *args, **kwargs):
  1329. pass
  1330. def connect(self):
  1331. return True
  1332. def upload_file(self, local_path, remote_path, progress_callback=None):
  1333. with lock:
  1334. state["attempts"] += 1
  1335. state["concurrent"] += 1
  1336. state["max_concurrent"] = max(state["max_concurrent"], state["concurrent"])
  1337. try:
  1338. total = state["chunks"]
  1339. for sent in range(1, total + 1):
  1340. time.sleep(state["chunk_delay"])
  1341. if progress_callback:
  1342. try:
  1343. progress_callback(sent, total)
  1344. except Exception:
  1345. state["cancelled"] = True
  1346. state["deleted"].append(remote_path)
  1347. raise
  1348. state["completed"] = True
  1349. return True
  1350. finally:
  1351. with lock:
  1352. state["concurrent"] -= 1
  1353. def disconnect(self):
  1354. pass
  1355. monkeypatch.setattr(bambu_ftp, "BambuFTPClient", FakeClient)
  1356. monkeypatch.setattr(FakeClient, "_mode_cache", {}, raising=False)
  1357. monkeypatch.setattr(FakeClient, "A1_MODELS", ("A1", "A1 Mini"), raising=False)
  1358. monkeypatch.setattr(FakeClient, "cache_mode", staticmethod(lambda ip, mode: None), raising=False)
  1359. return state
  1360. # ---------------------------------------------------------------------------
  1361. # TestUploadDeadline (#2529)
  1362. # ---------------------------------------------------------------------------
  1363. class TestUploadDeadline:
  1364. """The upload deadline must be size-aware, and must actually stop the transfer.
  1365. Regression for #2529: a 96 MB 3MF to an A1 over WiFi sustains ~75 KB/s and
  1366. needs ~20 minutes. The old flat 600 s wall-clock cap declared it dead at
  1367. ~70 MB, `asyncio.wait_for` cancelled the *future* but not the executor
  1368. thread — which kept streaming — and `with_ftp_retry` then started a second
  1369. STOR of the same file onto the same printer. The reporter's video shows two
  1370. transfers of the same job climbing in parallel (2% and 72%), and the print
  1371. never landed.
  1372. """
  1373. def test_deadline_scales_with_file_size(self, tmp_path):
  1374. """A big file gets proportionally longer, a small one gets the floor."""
  1375. small = tmp_path / "small.3mf"
  1376. small.write_bytes(b"x" * 1024)
  1377. assert bambu_ftp._upload_deadline(small) == bambu_ftp._UPLOAD_MIN_TIMEOUT
  1378. # The reporter's file. At the 25 KB/s floor rate, 96 MB is ~64 minutes —
  1379. # far above the 600 s that killed it at 72%.
  1380. big = tmp_path / "big.3mf"
  1381. big.write_bytes(b"x" * (96 * 1024 * 1024))
  1382. deadline = bambu_ftp._upload_deadline(big)
  1383. assert deadline > bambu_ftp._UPLOAD_MIN_TIMEOUT
  1384. assert deadline == pytest.approx((96 * 1024 * 1024) / bambu_ftp._UPLOAD_FLOOR_BYTES_PER_SEC)
  1385. def test_deadline_falls_back_to_floor_for_unstatable_file(self, tmp_path):
  1386. assert bambu_ftp._upload_deadline(tmp_path / "nope.3mf") == bambu_ftp._UPLOAD_MIN_TIMEOUT
  1387. @pytest.mark.asyncio
  1388. async def test_timeout_stops_the_worker_thread(self, tmp_path, monkeypatch, slow_upload_client):
  1389. """The transfer stops when the deadline expires, instead of streaming on.
  1390. Mutation check: drop the `cancel.set()` in upload_file_async and the
  1391. worker runs to completion, which is exactly the ghost transfer #2529
  1392. reported.
  1393. """
  1394. state = slow_upload_client
  1395. local = tmp_path / "slow.3mf"
  1396. local.write_bytes(b"x" * 4096)
  1397. with pytest.raises(bambu_ftp.UploadCancelled):
  1398. await upload_file_async("127.0.0.1", "12345678", local, "/cache/slow.3mf", timeout=0.2, printer_model="X1C")
  1399. # The worker noticed the cancel and unwound — it did not run to the end.
  1400. await asyncio.sleep(0.5)
  1401. assert state["cancelled"] is True
  1402. assert state["completed"] is False
  1403. # And it cleaned the partial file off the printer on its way out.
  1404. assert state["deleted"] == ["/cache/slow.3mf"]
  1405. @pytest.mark.asyncio
  1406. async def test_timeout_is_not_retried(self, tmp_path, monkeypatch, slow_upload_client):
  1407. """with_ftp_retry must not start a second transfer after a deadline expiry.
  1408. This is the bug the reporter filmed: attempt 2 began while attempt 1 was
  1409. still sending. One attempt, then a hard failure.
  1410. """
  1411. state = slow_upload_client
  1412. local = tmp_path / "slow.3mf"
  1413. local.write_bytes(b"x" * 4096)
  1414. with pytest.raises(bambu_ftp.UploadCancelled):
  1415. await with_ftp_retry(
  1416. upload_file_async,
  1417. "127.0.0.1",
  1418. "12345678",
  1419. local,
  1420. "/cache/slow.3mf",
  1421. timeout=0.2,
  1422. printer_model="X1C",
  1423. max_retries=3,
  1424. retry_delay=0,
  1425. )
  1426. assert state["attempts"] == 1, "a timed-out upload must not be retried"
  1427. @pytest.mark.asyncio
  1428. async def test_uploads_to_one_printer_are_serialized(self, tmp_path, monkeypatch, slow_upload_client):
  1429. """Two dispatches to the same printer queue up; they never overlap.
  1430. Concurrent STORs of the same remote path leave a corrupt file on the SD
  1431. card and make the printer look like it has a flaky network.
  1432. """
  1433. state = slow_upload_client
  1434. state["chunk_delay"] = 0.05
  1435. local = tmp_path / "slow.3mf"
  1436. local.write_bytes(b"x" * 4096)
  1437. async def _dispatch(name: str) -> bool:
  1438. return await upload_file_async(
  1439. "127.0.0.1", "12345678", local, f"/cache/{name}.3mf", timeout=30.0, printer_model="X1C"
  1440. )
  1441. results = await asyncio.gather(_dispatch("a"), _dispatch("b"))
  1442. assert results == [True, True]
  1443. assert state["attempts"] == 2
  1444. assert state["max_concurrent"] == 1, "two uploads ran against the same printer at once"
  1445. def test_progress_callback_raising_deletes_the_partial_file(self, ftp_client_factory, ftp_root, tmp_path):
  1446. """The cancel path in the real client removes what it already wrote.
  1447. This is the mechanism the deadline now hangs off, exercised end to end
  1448. against the mock FTPS server rather than a fake.
  1449. """
  1450. client = ftp_client_factory()
  1451. assert client.connect() is True
  1452. try:
  1453. local = tmp_path / "cancelme.3mf"
  1454. # Two chunks, so the callback fires while there is a partial file.
  1455. local.write_bytes(b"x" * (BambuFTPClient.CHUNK_SIZE * 2))
  1456. def _stop_after_first_chunk(uploaded: int, total: int) -> None:
  1457. raise bambu_ftp.UploadCancelled("stop")
  1458. with pytest.raises(bambu_ftp.UploadCancelled):
  1459. client.upload_file(local, "/cancelme.3mf", _stop_after_first_chunk)
  1460. finally:
  1461. client.disconnect()
  1462. time.sleep(_UPLOAD_FLUSH_DELAY)
  1463. assert not (Path(ftp_root) / "cancelme.3mf").exists(), "partial file left on the printer"
  1464. # ---------------------------------------------------------------------------
  1465. # TestHandshakeCoolOff
  1466. # ---------------------------------------------------------------------------
  1467. class _PlaintextServer:
  1468. """A socket that accepts on 990 and answers in plaintext, not TLS.
  1469. This is what #2780's printers do once their file service wedges: the TCP
  1470. connect succeeds, so a port probe reports the printer as healthy, and then
  1471. the implicit-FTPS handshake dies on ``WRONG_VERSION_NUMBER`` because the
  1472. first bytes back are an FTP banner rather than a TLS record.
  1473. """
  1474. def __init__(self):
  1475. self._sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  1476. self._sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
  1477. self._sock.bind(("127.0.0.1", 0))
  1478. self._sock.listen(8)
  1479. self.port = self._sock.getsockname()[1]
  1480. self.accepts = 0
  1481. self._stop = threading.Event()
  1482. self._thread = threading.Thread(target=self._serve, daemon=True)
  1483. self._thread.start()
  1484. def _serve(self):
  1485. while not self._stop.is_set():
  1486. try:
  1487. conn, _addr = self._sock.accept()
  1488. except OSError:
  1489. return
  1490. self.accepts += 1
  1491. try:
  1492. conn.sendall(b"220 Welcome to the printer.\r\n")
  1493. except OSError:
  1494. pass
  1495. finally:
  1496. conn.close()
  1497. def stop(self):
  1498. self._stop.set()
  1499. self._sock.close()
  1500. self._thread.join(timeout=2)
  1501. @pytest.fixture()
  1502. def plaintext_server():
  1503. server = _PlaintextServer()
  1504. yield server
  1505. server.stop()
  1506. class TestHandshakeCoolOff:
  1507. """A wedged file service must be contacted once, not hundreds of times.
  1508. #2780: an X2D served clean FTPS for five days, flipped, and then failed
  1509. every handshake for eight more. Because each candidate path opened its own
  1510. connection, one reporter's log carried 3511 identical handshake failures.
  1511. """
  1512. def _client(self, server, ip="127.0.0.1"):
  1513. client = BambuFTPClient(ip, "12345678", timeout=5.0, printer_model="P2S")
  1514. client.FTP_PORT = server.port
  1515. return client
  1516. def test_plaintext_answer_on_990_blocks_the_printer(self, plaintext_server, caplog):
  1517. client = self._client(plaintext_server)
  1518. with caplog.at_level(logging.WARNING, logger="backend.app.services.bambu_ftp"):
  1519. assert client.connect() is False
  1520. assert bambu_ftp.ftps_handshake_blocked("127.0.0.1") is True
  1521. messages = [r.getMessage() for r in caplog.records]
  1522. assert any("WRONG_VERSION_NUMBER" in m for m in messages)
  1523. # The warning has to say more than the error: the port is open, so
  1524. # "unblock port 990" is the wrong reading and the operator needs to
  1525. # know what it actually costs them.
  1526. assert any("covers and timelapses cannot be fetched" in m for m in messages)
  1527. # It must NOT prescribe a restart. It used to, and #2780's reporter
  1528. # power-cycled both affected printers with no effect while a single
  1529. # manual connection to the same printers completed a clean handshake.
  1530. # Naming a remedy that is known not to work is worse than naming none.
  1531. assert not any("restart" in m.lower() for m in messages)
  1532. def test_blocked_printer_is_not_contacted_again(self, plaintext_server):
  1533. self._client(plaintext_server).connect()
  1534. # Two, not one: the failed handshake, then one cleartext read asking
  1535. # what the printer actually answered with (#2780). That read is the
  1536. # whole diagnosis and it happens once per cool-off, so the promise
  1537. # this test exists for -- contacted a couple of times, not ~110 --
  1538. # still holds.
  1539. assert plaintext_server.accepts == 2
  1540. for _ in range(5):
  1541. assert self._client(plaintext_server).connect() is False
  1542. # Still two: the cool-off answered without opening a socket, and it
  1543. # gates the probe as well as the handshake.
  1544. assert plaintext_server.accepts == 2
  1545. def test_cooloff_expiry_lets_the_printer_be_retried(self, plaintext_server, monkeypatch):
  1546. monkeypatch.setattr(bambu_ftp, "_HANDSHAKE_COOLOFF_SECONDS", 0.0)
  1547. self._client(plaintext_server).connect()
  1548. assert bambu_ftp.ftps_handshake_blocked("127.0.0.1") is False
  1549. assert self._client(plaintext_server).connect() is False
  1550. # Two handshakes and a cleartext probe on each. A zero-length cool-off
  1551. # is what makes the probe repeat -- it is gated on the window being
  1552. # already open, and here there is never a window. At the real 300s it
  1553. # runs once, which `test_blocked_printer_is_not_contacted_again` pins.
  1554. assert plaintext_server.accepts == 4
  1555. def test_block_is_per_printer(self, plaintext_server):
  1556. self._client(plaintext_server).connect()
  1557. assert bambu_ftp.ftps_handshake_blocked("127.0.0.1") is True
  1558. # A second printer that never failed must stay reachable.
  1559. assert bambu_ftp.ftps_handshake_blocked("192.0.2.77") is False
  1560. def test_expired_block_lets_a_recovered_printer_straight_back_in(self, ftp_client_factory):
  1561. """A power-cycled printer is picked up on the next print, not held out.
  1562. The expired entry is also dropped, so the map holds one key per
  1563. currently-wedged printer rather than one per printer this process has
  1564. ever failed against.
  1565. """
  1566. BambuFTPClient._handshake_blocked_until["127.0.0.1"] = time.monotonic() - 1
  1567. client = ftp_client_factory()
  1568. assert client.connect() is True
  1569. client.disconnect()
  1570. assert BambuFTPClient._handshake_blocked_until == {}