test_bambu_ftp.py 75 KB

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