background_dispatch.py 47 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100
  1. """Background dispatch for print/reprint jobs.
  2. This service is separate from the app's print queue feature. It exists only to
  3. decouple "send/start print" operations (FTP upload + start command) from API
  4. request latency so the UI can continue immediately after dispatch.
  5. """
  6. from __future__ import annotations
  7. import asyncio
  8. import logging
  9. import time
  10. import zipfile
  11. from collections import deque
  12. from dataclasses import dataclass, field
  13. from pathlib import Path
  14. from typing import Any, Literal
  15. from sqlalchemy import select
  16. from backend.app.core.config import settings
  17. from backend.app.core.database import async_session
  18. from backend.app.core.tasks import spawn_background_task
  19. from backend.app.core.websocket import ws_manager
  20. from backend.app.models.library import LibraryFile
  21. from backend.app.models.printer import Printer
  22. from backend.app.services.archive import ArchiveService
  23. from backend.app.services.bambu_ftp import (
  24. cache_3mf_download,
  25. delete_file_async,
  26. get_ftp_retry_settings,
  27. upload_file_async,
  28. with_ftp_retry,
  29. )
  30. from backend.app.services.printer_manager import printer_manager
  31. from backend.app.utils.filename import derive_remote_filename
  32. logger = logging.getLogger(__name__)
  33. # Bambu firmware states that mean the project_file has actually been accepted
  34. # and the printer is now processing / running / paused mid-print. Used by the
  35. # direct-dispatch verifier (#1370): a transition into one of these states means
  36. # the print landed, anything else (e.g. FINISH -> IDLE after the user dismisses
  37. # a post-print prompt) is NOT a valid "command landed" signal even though the
  38. # state value did change. Mirrors the same constant in print_scheduler.py —
  39. # kept duplicated rather than imported to avoid coupling the two services and
  40. # to keep the value at the point of use.
  41. _ACTIVE_PRINT_STATES: frozenset[str] = frozenset({"PREPARE", "SLICING", "RUNNING", "PAUSE"})
  42. class DispatchJobCancelled(Exception):
  43. """Raised when a dispatch job is cancelled by the user."""
  44. class DispatchEnqueueRejected(Exception):
  45. """Raised when a dispatch job should not be accepted."""
  46. @dataclass(slots=True)
  47. class PrintDispatchJob:
  48. id: int
  49. kind: Literal["reprint_archive", "print_library_file"]
  50. source_id: int
  51. source_name: str
  52. printer_id: int
  53. printer_name: str
  54. options: dict[str, Any] = field(default_factory=dict)
  55. requested_by_user_id: int | None = None
  56. requested_by_username: str | None = None
  57. project_id: int | None = None
  58. cleanup_library_after_dispatch: bool = False
  59. @dataclass(slots=True)
  60. class ActiveDispatchState:
  61. job: PrintDispatchJob
  62. message: str
  63. upload_bytes: int | None = None
  64. upload_total_bytes: int | None = None
  65. class BackgroundDispatchService:
  66. def __init__(self):
  67. self._queued_jobs: deque[PrintDispatchJob] = deque()
  68. self._dispatcher_task: asyncio.Task | None = None
  69. self._running_tasks: dict[int, asyncio.Task] = {}
  70. self._lock = asyncio.Lock()
  71. self._job_event = asyncio.Event()
  72. self._next_job_id = 1
  73. self._active_jobs: dict[int, ActiveDispatchState] = {}
  74. self._cancel_requested_job_ids: set[int] = set()
  75. # Progress for the current "batch" (since queue became non-empty)
  76. self._batch_total = 0
  77. self._batch_completed = 0
  78. self._batch_failed = 0
  79. @staticmethod
  80. def _printer_is_busy_printing(printer_id: int) -> bool:
  81. state = printer_manager.get_status(printer_id)
  82. if not state:
  83. return False
  84. return state.state in ("RUNNING", "PAUSE", "PAUSED") and bool(state.gcode_file)
  85. async def start(self):
  86. async with self._lock:
  87. if self._dispatcher_task and not self._dispatcher_task.done():
  88. return
  89. self._dispatcher_task = asyncio.create_task(self._dispatcher_loop(), name="background-dispatch-dispatcher")
  90. logger.info("Background dispatch dispatcher started")
  91. async def stop(self):
  92. dispatcher: asyncio.Task | None = None
  93. running_tasks: list[asyncio.Task] = []
  94. async with self._lock:
  95. dispatcher = self._dispatcher_task
  96. self._dispatcher_task = None
  97. running_tasks = list(self._running_tasks.values())
  98. self._running_tasks.clear()
  99. self._active_jobs.clear()
  100. self._queued_jobs.clear()
  101. self._cancel_requested_job_ids.clear()
  102. self._job_event.set()
  103. if dispatcher:
  104. dispatcher.cancel()
  105. for task in running_tasks:
  106. task.cancel()
  107. if dispatcher:
  108. try:
  109. await dispatcher
  110. except asyncio.CancelledError:
  111. pass
  112. if running_tasks:
  113. await asyncio.gather(*running_tasks, return_exceptions=True)
  114. logger.info("Background dispatch dispatcher stopped")
  115. async def dispatch_reprint_archive(
  116. self,
  117. *,
  118. archive_id: int,
  119. archive_name: str,
  120. printer_id: int,
  121. printer_name: str,
  122. options: dict[str, Any],
  123. requested_by_user_id: int | None,
  124. requested_by_username: str | None,
  125. ) -> dict[str, Any]:
  126. return await self._dispatch(
  127. kind="reprint_archive",
  128. source_id=archive_id,
  129. source_name=archive_name,
  130. printer_id=printer_id,
  131. printer_name=printer_name,
  132. options=options,
  133. requested_by_user_id=requested_by_user_id,
  134. requested_by_username=requested_by_username,
  135. )
  136. async def get_state(self) -> dict[str, Any]:
  137. """Get current dispatch queue state snapshot for newly connected clients."""
  138. async with self._lock:
  139. return self._build_state_payload_unlocked()
  140. async def dispatch_print_library_file(
  141. self,
  142. *,
  143. file_id: int,
  144. filename: str,
  145. printer_id: int,
  146. printer_name: str,
  147. options: dict[str, Any],
  148. requested_by_user_id: int | None,
  149. requested_by_username: str | None,
  150. project_id: int | None = None,
  151. cleanup_library_after_dispatch: bool = False,
  152. ) -> dict[str, Any]:
  153. return await self._dispatch(
  154. kind="print_library_file",
  155. source_id=file_id,
  156. source_name=filename,
  157. printer_id=printer_id,
  158. printer_name=printer_name,
  159. options=options,
  160. requested_by_user_id=requested_by_user_id,
  161. requested_by_username=requested_by_username,
  162. project_id=project_id,
  163. cleanup_library_after_dispatch=cleanup_library_after_dispatch,
  164. )
  165. async def cancel_job(self, job_id: int) -> dict[str, Any]:
  166. """Cancel a queued dispatch job.
  167. Queued jobs are removed immediately. Active jobs are cancelled
  168. cooperatively and will stop at the next cancellation checkpoint.
  169. """
  170. async with self._lock:
  171. # Check active jobs first
  172. active_state = self._active_jobs.get(job_id)
  173. if active_state is not None:
  174. logger.info("Cancel requested for active dispatch job %s", job_id)
  175. self._cancel_requested_job_ids.add(job_id)
  176. active_job = active_state.job
  177. payload = self._build_state_payload_unlocked(
  178. recent_event={
  179. "status": "cancelling",
  180. "job_id": active_job.id,
  181. "source_name": active_job.source_name,
  182. "printer_id": active_job.printer_id,
  183. "printer_name": active_job.printer_name,
  184. "message": "Cancelling current dispatch...",
  185. }
  186. )
  187. result = {
  188. "cancelled": True,
  189. "pending": True,
  190. "job_id": active_job.id,
  191. "source_name": active_job.source_name,
  192. "printer_id": active_job.printer_id,
  193. "printer_name": active_job.printer_name,
  194. }
  195. await ws_manager.broadcast({"type": "background_dispatch", "data": payload})
  196. return result
  197. # Check queued jobs
  198. cancelled_job: PrintDispatchJob | None = None
  199. for job in self._queued_jobs:
  200. if job.id == job_id:
  201. cancelled_job = job
  202. break
  203. if not cancelled_job:
  204. logger.info("Cancel requested for unknown dispatch job %s", job_id)
  205. return {"cancelled": False, "reason": "not_found"}
  206. self._queued_jobs.remove(cancelled_job)
  207. logger.info("Cancelled queued dispatch job %s", cancelled_job.id)
  208. self._batch_total = max(0, self._batch_total - 1)
  209. if self._batch_total == 0 and len(self._queued_jobs) == 0 and len(self._active_jobs) == 0:
  210. self._batch_completed = 0
  211. self._batch_failed = 0
  212. payload = self._build_state_payload_unlocked(
  213. recent_event={
  214. "status": "cancelled",
  215. "job_id": cancelled_job.id,
  216. "source_name": cancelled_job.source_name,
  217. "printer_id": cancelled_job.printer_id,
  218. "printer_name": cancelled_job.printer_name,
  219. "message": "Cancelled from queue",
  220. }
  221. )
  222. await ws_manager.broadcast({"type": "background_dispatch", "data": payload})
  223. return {
  224. "cancelled": True,
  225. "pending": False,
  226. "job_id": cancelled_job.id,
  227. "source_name": cancelled_job.source_name,
  228. "printer_id": cancelled_job.printer_id,
  229. "printer_name": cancelled_job.printer_name,
  230. }
  231. async def _dispatch(
  232. self,
  233. *,
  234. kind: Literal["reprint_archive", "print_library_file"],
  235. source_id: int,
  236. source_name: str,
  237. printer_id: int,
  238. printer_name: str,
  239. options: dict[str, Any],
  240. requested_by_user_id: int | None,
  241. requested_by_username: str | None,
  242. project_id: int | None = None,
  243. cleanup_library_after_dispatch: bool = False,
  244. ) -> dict[str, Any]:
  245. async with self._lock:
  246. has_pending_for_printer = any(job.printer_id == printer_id for job in self._queued_jobs)
  247. has_active_for_printer = any(active.job.printer_id == printer_id for active in self._active_jobs.values())
  248. if has_pending_for_printer or has_active_for_printer:
  249. raise DispatchEnqueueRejected(f"Printer {printer_name} already has a background dispatch in progress")
  250. if self._printer_is_busy_printing(printer_id):
  251. raise DispatchEnqueueRejected(f"Printer {printer_name} is currently busy printing")
  252. dispatch_position = len(self._queued_jobs) + len(self._active_jobs) + 1
  253. job = PrintDispatchJob(
  254. id=self._next_job_id,
  255. kind=kind,
  256. source_id=source_id,
  257. source_name=source_name,
  258. printer_id=printer_id,
  259. printer_name=printer_name,
  260. options=options,
  261. requested_by_user_id=requested_by_user_id,
  262. requested_by_username=requested_by_username,
  263. project_id=project_id,
  264. cleanup_library_after_dispatch=cleanup_library_after_dispatch,
  265. )
  266. self._next_job_id += 1
  267. self._batch_total += 1
  268. self._queued_jobs.append(job)
  269. self._job_event.set()
  270. payload = self._build_state_payload_unlocked(
  271. recent_event={
  272. "status": "dispatched",
  273. "job_id": job.id,
  274. "source_name": source_name,
  275. "printer_id": printer_id,
  276. "printer_name": printer_name,
  277. "message": f"Dispatched to {printer_name}",
  278. }
  279. )
  280. await ws_manager.broadcast({"type": "background_dispatch", "data": payload})
  281. return {
  282. "dispatch_job_id": job.id,
  283. "dispatch_position": dispatch_position,
  284. "status": "dispatched",
  285. "printer_id": printer_id,
  286. "source_id": source_id,
  287. "source_name": source_name,
  288. }
  289. async def _dispatcher_loop(self):
  290. while True:
  291. await self._job_event.wait()
  292. self._job_event.clear()
  293. while True:
  294. payload: dict[str, Any] | None = None
  295. job_to_start: PrintDispatchJob | None = None
  296. async with self._lock:
  297. busy_printer_ids = {state.job.printer_id for state in self._active_jobs.values()}
  298. start_index = next(
  299. (
  300. idx
  301. for idx, queued_job in enumerate(self._queued_jobs)
  302. if queued_job.printer_id not in busy_printer_ids
  303. ),
  304. None,
  305. )
  306. if start_index is None:
  307. break
  308. job_to_start = self._queued_jobs[start_index]
  309. del self._queued_jobs[start_index]
  310. self._active_jobs[job_to_start.id] = ActiveDispatchState(
  311. job=job_to_start,
  312. message="Preparing background dispatch...",
  313. )
  314. task = asyncio.create_task(
  315. self._run_active_job(job_to_start), name=f"background-dispatch-job-{job_to_start.id}"
  316. )
  317. self._running_tasks[job_to_start.id] = task
  318. payload = self._build_state_payload_unlocked(
  319. recent_event={
  320. "status": "processing",
  321. "job_id": job_to_start.id,
  322. "source_name": job_to_start.source_name,
  323. "printer_id": job_to_start.printer_id,
  324. "printer_name": job_to_start.printer_name,
  325. "message": "Preparing background dispatch...",
  326. }
  327. )
  328. if payload:
  329. await ws_manager.broadcast({"type": "background_dispatch", "data": payload})
  330. async def _run_active_job(self, job: PrintDispatchJob):
  331. try:
  332. await self._process_job(job)
  333. await self._mark_job_finished(job, failed=False, message="Background dispatch complete")
  334. except DispatchJobCancelled:
  335. await self._mark_job_cancelled(job)
  336. except asyncio.CancelledError:
  337. raise
  338. except Exception as e:
  339. logger.error("Background dispatch job %s failed: %s", job.id, e, exc_info=True)
  340. await self._mark_job_finished(job, failed=True, message=str(e))
  341. finally:
  342. self._job_event.set()
  343. async def _set_active_message(self, job: PrintDispatchJob, message: str):
  344. async with self._lock:
  345. active = self._active_jobs.get(job.id)
  346. if not active:
  347. return
  348. active.message = message
  349. payload = self._build_state_payload_unlocked(
  350. recent_event={
  351. "status": "processing",
  352. "job_id": active.job.id,
  353. "source_name": active.job.source_name,
  354. "printer_id": active.job.printer_id,
  355. "printer_name": active.job.printer_name,
  356. "message": message,
  357. }
  358. )
  359. await ws_manager.broadcast({"type": "background_dispatch", "data": payload})
  360. async def _set_active_upload_progress(self, job: PrintDispatchJob, uploaded: int, total: int):
  361. async with self._lock:
  362. active = self._active_jobs.get(job.id)
  363. if not active:
  364. return
  365. active.upload_bytes = max(0, int(uploaded))
  366. active.upload_total_bytes = max(0, int(total))
  367. payload = self._build_state_payload_unlocked(
  368. recent_event={
  369. "status": "processing",
  370. "job_id": active.job.id,
  371. "source_name": active.job.source_name,
  372. "printer_id": active.job.printer_id,
  373. "printer_name": active.job.printer_name,
  374. "message": active.message,
  375. }
  376. )
  377. await ws_manager.broadcast({"type": "background_dispatch", "data": payload})
  378. async def _mark_job_finished(self, job: PrintDispatchJob, *, failed: bool, message: str):
  379. async with self._lock:
  380. if failed:
  381. self._batch_failed += 1
  382. else:
  383. self._batch_completed += 1
  384. self._active_jobs.pop(job.id, None)
  385. self._running_tasks.pop(job.id, None)
  386. self._cancel_requested_job_ids.discard(job.id)
  387. payload = self._build_state_payload_unlocked(
  388. recent_event={
  389. "status": "failed" if failed else "completed",
  390. "job_id": job.id,
  391. "source_name": job.source_name,
  392. "printer_id": job.printer_id,
  393. "printer_name": job.printer_name,
  394. "message": message,
  395. }
  396. )
  397. should_reset_batch = len(self._queued_jobs) == 0 and len(self._active_jobs) == 0
  398. await ws_manager.broadcast({"type": "background_dispatch", "data": payload})
  399. if should_reset_batch:
  400. async with self._lock:
  401. if len(self._queued_jobs) == 0 and len(self._active_jobs) == 0:
  402. self._batch_total = 0
  403. self._batch_completed = 0
  404. self._batch_failed = 0
  405. async def _mark_job_cancelled(self, job: PrintDispatchJob):
  406. async with self._lock:
  407. self._active_jobs.pop(job.id, None)
  408. self._running_tasks.pop(job.id, None)
  409. self._cancel_requested_job_ids.discard(job.id)
  410. self._batch_total = max(0, self._batch_total - 1)
  411. if self._batch_total == 0 and len(self._queued_jobs) == 0 and len(self._active_jobs) == 0:
  412. self._batch_completed = 0
  413. self._batch_failed = 0
  414. payload = self._build_state_payload_unlocked(
  415. recent_event={
  416. "status": "cancelled",
  417. "job_id": job.id,
  418. "source_name": job.source_name,
  419. "printer_id": job.printer_id,
  420. "printer_name": job.printer_name,
  421. "message": "Cancelled during dispatch",
  422. }
  423. )
  424. await ws_manager.broadcast({"type": "background_dispatch", "data": payload})
  425. def _is_cancel_requested(self, job_id: int) -> bool:
  426. return job_id in self._cancel_requested_job_ids
  427. def _raise_if_cancel_requested(self, job: PrintDispatchJob):
  428. if self._is_cancel_requested(job.id):
  429. raise DispatchJobCancelled(f"Dispatch job {job.id} cancelled")
  430. def _build_state_payload_unlocked(self, recent_event: dict[str, Any] | None = None) -> dict[str, Any]:
  431. processing = len(self._active_jobs)
  432. dispatched = len(self._queued_jobs)
  433. dispatched_jobs = [
  434. {
  435. "job_id": job.id,
  436. "kind": job.kind,
  437. "source_id": job.source_id,
  438. "source_name": job.source_name,
  439. "printer_id": job.printer_id,
  440. "printer_name": job.printer_name,
  441. }
  442. for job in list(self._queued_jobs)
  443. ]
  444. active_jobs: list[dict[str, Any]] = []
  445. for active in self._active_jobs.values():
  446. upload_progress_pct = None
  447. if active.upload_total_bytes and active.upload_total_bytes > 0 and active.upload_bytes is not None:
  448. upload_progress_pct = round(
  449. max(0.0, min(100.0, (active.upload_bytes / active.upload_total_bytes) * 100.0)), 1
  450. )
  451. active_jobs.append(
  452. {
  453. "job_id": active.job.id,
  454. "kind": active.job.kind,
  455. "source_id": active.job.source_id,
  456. "source_name": active.job.source_name,
  457. "printer_id": active.job.printer_id,
  458. "printer_name": active.job.printer_name,
  459. "message": active.message,
  460. "upload_bytes": active.upload_bytes,
  461. "upload_total_bytes": active.upload_total_bytes,
  462. "upload_progress_pct": upload_progress_pct,
  463. }
  464. )
  465. active_jobs.sort(key=lambda item: int(item["job_id"]))
  466. active_job = active_jobs[0] if active_jobs else None
  467. return {
  468. "total": self._batch_total,
  469. "dispatched": dispatched,
  470. "processing": processing,
  471. "completed": self._batch_completed,
  472. "failed": self._batch_failed,
  473. "dispatched_jobs": dispatched_jobs,
  474. "active_jobs": active_jobs,
  475. "active_job": active_job,
  476. "recent_event": recent_event,
  477. }
  478. async def _process_job(self, job: PrintDispatchJob):
  479. if job.kind == "reprint_archive":
  480. await self._run_reprint_archive(job)
  481. return
  482. if job.kind == "print_library_file":
  483. await self._run_print_library_file(job)
  484. return
  485. raise RuntimeError(f"Unknown dispatch job kind: {job.kind}")
  486. async def _run_reprint_archive(self, job: PrintDispatchJob):
  487. from backend.app.main import register_expected_print
  488. async with async_session() as db:
  489. service = ArchiveService(db)
  490. archive = await service.get_archive(job.source_id)
  491. if not archive:
  492. raise RuntimeError("Archive not found")
  493. printer = await db.scalar(select(Printer).where(Printer.id == job.printer_id))
  494. if not printer:
  495. raise RuntimeError("Printer not found")
  496. printer_name = printer.name
  497. printer_ip = printer.ip_address
  498. printer_access_code = printer.access_code
  499. printer_model = printer.model
  500. archive_filename = archive.filename
  501. if not printer_manager.is_connected(job.printer_id):
  502. raise RuntimeError("Printer is not connected")
  503. file_path = settings.base_dir / archive.file_path
  504. if not file_path.exists():
  505. raise RuntimeError("Archive file not found")
  506. remote_filename = derive_remote_filename(archive.filename)
  507. remote_path = f"/{remote_filename}"
  508. ftp_retry_enabled, ftp_retry_count, ftp_retry_delay, ftp_timeout = await get_ftp_retry_settings()
  509. self._raise_if_cancel_requested(job)
  510. await self._set_active_message(job, f"Preparing upload to {printer_name}...")
  511. await delete_file_async(
  512. printer_ip,
  513. printer_access_code,
  514. remote_path,
  515. socket_timeout=ftp_timeout,
  516. printer_model=printer_model,
  517. )
  518. self._raise_if_cancel_requested(job)
  519. try:
  520. await self._set_active_message(job, f"Uploading {archive_filename} to {printer_name}...")
  521. loop = asyncio.get_running_loop()
  522. progress_state = {"last_emit": 0.0, "last_bytes": 0}
  523. def upload_progress_callback(uploaded: int, total: int):
  524. if self._is_cancel_requested(job.id):
  525. raise DispatchJobCancelled(f"Dispatch job {job.id} cancelled during upload")
  526. now = time.monotonic()
  527. should_emit = (
  528. uploaded >= total
  529. or now - progress_state["last_emit"] >= 0.2
  530. or uploaded - progress_state["last_bytes"] >= 256 * 1024
  531. )
  532. if should_emit:
  533. progress_state["last_emit"] = now
  534. progress_state["last_bytes"] = uploaded
  535. loop.call_soon_threadsafe(
  536. lambda u=uploaded, t=total: spawn_background_task(
  537. self._set_active_upload_progress(job, u, t),
  538. name=f"upload-progress-{job.id}",
  539. )
  540. )
  541. if ftp_retry_enabled:
  542. uploaded = await with_ftp_retry(
  543. upload_file_async,
  544. printer_ip,
  545. printer_access_code,
  546. file_path,
  547. remote_path,
  548. progress_callback=upload_progress_callback,
  549. socket_timeout=ftp_timeout,
  550. printer_model=printer_model,
  551. max_retries=ftp_retry_count,
  552. retry_delay=ftp_retry_delay,
  553. operation_name=f"Upload for reprint to {printer_name}",
  554. non_retry_exceptions=(DispatchJobCancelled,),
  555. )
  556. else:
  557. uploaded = await upload_file_async(
  558. printer_ip,
  559. printer_access_code,
  560. file_path,
  561. remote_path,
  562. progress_callback=upload_progress_callback,
  563. socket_timeout=ftp_timeout,
  564. printer_model=printer_model,
  565. )
  566. if uploaded:
  567. await self._set_active_upload_progress(job, 1, 1)
  568. if not uploaded:
  569. raise RuntimeError(
  570. "Failed to upload file to printer. Check if SD card is inserted and properly formatted (FAT32/exFAT)."
  571. )
  572. # Resolve plate_id before register so usage tracking can scope the
  573. # 3MF parse to the dispatched plate at print-start (#1697). Pure
  574. # transform of file_path + options, safe to reorder.
  575. plate_id = self._resolve_plate_id(file_path, job.options.get("plate_id"))
  576. register_expected_print(
  577. job.printer_id,
  578. remote_filename,
  579. job.source_id,
  580. ams_mapping=job.options.get("ams_mapping"),
  581. plate_id=plate_id,
  582. )
  583. self._raise_if_cancel_requested(job)
  584. effective_timelapse = bool(job.options.get("timelapse", False))
  585. await self._set_active_message(job, f"Starting print on {printer_name}...")
  586. started = printer_manager.start_print(
  587. job.printer_id,
  588. remote_filename,
  589. plate_id,
  590. ams_mapping=job.options.get("ams_mapping"),
  591. timelapse=effective_timelapse,
  592. bed_levelling=job.options.get("bed_levelling", True),
  593. flow_cali=job.options.get("flow_cali", False),
  594. vibration_cali=job.options.get("vibration_cali", True),
  595. layer_inspect=job.options.get("layer_inspect", False),
  596. use_ams=job.options.get("use_ams", True),
  597. nozzle_offset_cali=job.options.get("nozzle_offset_cali", False),
  598. )
  599. if not started:
  600. await self._cleanup_sd_card_file(
  601. printer_ip,
  602. printer_access_code,
  603. remote_path,
  604. printer_model,
  605. )
  606. raise RuntimeError("Failed to start print")
  607. # Register the archive's local 3MF in the cover-cache so the
  608. # /cover endpoint can skip FTP — we already have the file on
  609. # disk, no need to refetch 36 MB from a printer whose FTP is
  610. # busy serving the active print (#1166 follow-up).
  611. cache_3mf_download(job.printer_id, remote_filename, file_path)
  612. # Wait for the printer to actually pick up the command before
  613. # marking the dispatch job complete (#1042). MQTT-publish success
  614. # only proves the command queued locally; the printer can still
  615. # reject it (HMS error pending, half-broken session, SD card
  616. # missing) and never transition. Until #1042 this watchdog was
  617. # fire-and-forget — the job was reported successful and the
  618. # user had no signal that the print never started. The uploaded
  619. # file is intentionally left on the printer's SD card on
  620. # timeout: the next dispatch will overwrite it via the existing
  621. # delete-then-upload step, and the printer may still be in the
  622. # middle of reading it if it picked up just past the timeout.
  623. pre_status = printer_manager.get_status(job.printer_id)
  624. pre_state = getattr(pre_status, "state", None) if pre_status else None
  625. pre_subtask_id = getattr(pre_status, "subtask_id", None) if pre_status else None
  626. pre_gcode_file = getattr(pre_status, "gcode_file", None) if pre_status else None
  627. if pre_state:
  628. await self._set_active_message(job, f"Waiting for {printer_name} to acknowledge print...")
  629. transitioned = await self._verify_print_response(
  630. job.printer_id,
  631. printer_name,
  632. pre_state,
  633. pre_subtask_id=pre_subtask_id,
  634. pre_gcode_file=pre_gcode_file,
  635. )
  636. if not transitioned:
  637. raise RuntimeError(
  638. f"Printer did not acknowledge print command — state still {pre_state}. "
  639. f"Check the printer for a pending error (HMS code, plate-clear prompt, "
  640. f"SD card) and try again."
  641. )
  642. if job.requested_by_user_id and job.requested_by_username:
  643. printer_manager.set_current_print_user(
  644. job.printer_id,
  645. job.requested_by_user_id,
  646. job.requested_by_username,
  647. )
  648. except DispatchJobCancelled:
  649. await self._set_active_message(job, f"Cancelled upload on {printer_name}.")
  650. raise
  651. async def _run_print_library_file(self, job: PrintDispatchJob):
  652. from backend.app.main import register_expected_print
  653. async with async_session() as db:
  654. lib_file = await db.scalar(LibraryFile.active().where(LibraryFile.id == job.source_id))
  655. if not lib_file:
  656. raise RuntimeError("File not found")
  657. if not self._is_sliced_file(lib_file.filename):
  658. raise RuntimeError("Not a sliced file. Only .gcode or .gcode.3mf files can be printed.")
  659. file_path = Path(settings.base_dir) / lib_file.file_path
  660. if not file_path.exists():
  661. raise RuntimeError("File not found on disk")
  662. printer = await db.scalar(select(Printer).where(Printer.id == job.printer_id))
  663. if not printer:
  664. raise RuntimeError("Printer not found")
  665. printer_name = printer.name
  666. printer_ip = printer.ip_address
  667. printer_access_code = printer.access_code
  668. printer_model = printer.model
  669. library_filename = lib_file.filename
  670. if not printer_manager.is_connected(job.printer_id):
  671. raise RuntimeError("Printer is not connected")
  672. await self._set_active_message(job, f"Creating archive for {lib_file.filename}...")
  673. archive_service = ArchiveService(db)
  674. archive = await archive_service.archive_print(
  675. printer_id=job.printer_id,
  676. source_file=file_path,
  677. original_filename=lib_file.filename,
  678. project_id=job.project_id,
  679. created_by_id=job.requested_by_user_id,
  680. )
  681. if not archive:
  682. raise RuntimeError("Failed to create archive")
  683. await db.flush()
  684. remote_filename = derive_remote_filename(lib_file.filename)
  685. remote_path = f"/{remote_filename}"
  686. ftp_retry_enabled, ftp_retry_count, ftp_retry_delay, ftp_timeout = await get_ftp_retry_settings()
  687. self._raise_if_cancel_requested(job)
  688. await self._set_active_message(job, f"Preparing upload to {printer_name}...")
  689. await delete_file_async(
  690. printer_ip,
  691. printer_access_code,
  692. remote_path,
  693. socket_timeout=ftp_timeout,
  694. printer_model=printer_model,
  695. )
  696. self._raise_if_cancel_requested(job)
  697. try:
  698. await self._set_active_message(job, f"Uploading {library_filename} to {printer_name}...")
  699. loop = asyncio.get_running_loop()
  700. progress_state = {"last_emit": 0.0, "last_bytes": 0}
  701. def upload_progress_callback(uploaded: int, total: int):
  702. if self._is_cancel_requested(job.id):
  703. raise DispatchJobCancelled(f"Dispatch job {job.id} cancelled during upload")
  704. now = time.monotonic()
  705. should_emit = (
  706. uploaded >= total
  707. or now - progress_state["last_emit"] >= 0.2
  708. or uploaded - progress_state["last_bytes"] >= 256 * 1024
  709. )
  710. if should_emit:
  711. progress_state["last_emit"] = now
  712. progress_state["last_bytes"] = uploaded
  713. loop.call_soon_threadsafe(
  714. lambda u=uploaded, t=total: spawn_background_task(
  715. self._set_active_upload_progress(job, u, t),
  716. name=f"upload-progress-{job.id}",
  717. )
  718. )
  719. if ftp_retry_enabled:
  720. uploaded = await with_ftp_retry(
  721. upload_file_async,
  722. printer_ip,
  723. printer_access_code,
  724. file_path,
  725. remote_path,
  726. progress_callback=upload_progress_callback,
  727. socket_timeout=ftp_timeout,
  728. printer_model=printer_model,
  729. max_retries=ftp_retry_count,
  730. retry_delay=ftp_retry_delay,
  731. operation_name=f"Upload for print to {printer_name}",
  732. non_retry_exceptions=(DispatchJobCancelled,),
  733. )
  734. else:
  735. uploaded = await upload_file_async(
  736. printer_ip,
  737. printer_access_code,
  738. file_path,
  739. remote_path,
  740. progress_callback=upload_progress_callback,
  741. socket_timeout=ftp_timeout,
  742. printer_model=printer_model,
  743. )
  744. if uploaded:
  745. await self._set_active_upload_progress(job, 1, 1)
  746. if not uploaded:
  747. await db.rollback()
  748. raise RuntimeError(
  749. "Failed to upload file to printer. Check if SD card is inserted and properly formatted (FAT32/exFAT)."
  750. )
  751. # Resolve plate_id before register so usage tracking can scope the
  752. # 3MF parse to the dispatched plate at print-start (#1697).
  753. plate_id = self._resolve_plate_id(file_path, job.options.get("plate_id"))
  754. register_expected_print(
  755. job.printer_id,
  756. remote_filename,
  757. archive.id,
  758. ams_mapping=job.options.get("ams_mapping"),
  759. plate_id=plate_id,
  760. )
  761. self._raise_if_cancel_requested(job)
  762. effective_timelapse = bool(job.options.get("timelapse", False))
  763. await self._set_active_message(job, f"Starting print on {printer_name}...")
  764. started = printer_manager.start_print(
  765. job.printer_id,
  766. remote_filename,
  767. plate_id,
  768. ams_mapping=job.options.get("ams_mapping"),
  769. timelapse=effective_timelapse,
  770. bed_levelling=job.options.get("bed_levelling", True),
  771. flow_cali=job.options.get("flow_cali", False),
  772. vibration_cali=job.options.get("vibration_cali", True),
  773. layer_inspect=job.options.get("layer_inspect", False),
  774. use_ams=job.options.get("use_ams", True),
  775. nozzle_offset_cali=job.options.get("nozzle_offset_cali", False),
  776. )
  777. if not started:
  778. await self._cleanup_sd_card_file(
  779. printer_ip,
  780. printer_access_code,
  781. remote_path,
  782. printer_model,
  783. )
  784. await db.rollback()
  785. raise RuntimeError("Failed to start print")
  786. # Same as the archive path: register the library file's local
  787. # 3MF in the cover-cache so /cover skips FTP (#1166 follow-up).
  788. cache_3mf_download(job.printer_id, remote_filename, file_path)
  789. # See _run_reprint_archive for rationale (#1042). On timeout
  790. # also rolls back the freshly-created archive so the library
  791. # flow doesn't leave behind a phantom row for a print that
  792. # never started.
  793. pre_status = printer_manager.get_status(job.printer_id)
  794. pre_state = getattr(pre_status, "state", None) if pre_status else None
  795. pre_subtask_id = getattr(pre_status, "subtask_id", None) if pre_status else None
  796. pre_gcode_file = getattr(pre_status, "gcode_file", None) if pre_status else None
  797. if pre_state:
  798. await self._set_active_message(job, f"Waiting for {printer_name} to acknowledge print...")
  799. transitioned = await self._verify_print_response(
  800. job.printer_id,
  801. printer_name,
  802. pre_state,
  803. pre_subtask_id=pre_subtask_id,
  804. pre_gcode_file=pre_gcode_file,
  805. )
  806. if not transitioned:
  807. await db.rollback()
  808. raise RuntimeError(
  809. f"Printer did not acknowledge print command — state still {pre_state}. "
  810. f"Check the printer for a pending error (HMS code, plate-clear prompt, "
  811. f"SD card) and try again."
  812. )
  813. if job.requested_by_user_id and job.requested_by_username:
  814. printer_manager.set_current_print_user(
  815. job.printer_id,
  816. job.requested_by_user_id,
  817. job.requested_by_username,
  818. )
  819. # Direct-Print flow only: archive_print copies, so deleting the
  820. # transient library row + files here leaves archive intact. Disk
  821. # deletes run only after commit so a rollback leaves no orphan.
  822. cleanup_disk_paths: list[Path] = []
  823. if job.cleanup_library_after_dispatch and not lib_file.is_external:
  824. cleanup_disk_paths.append(file_path)
  825. if lib_file.thumbnail_path:
  826. thumb_path = Path(lib_file.thumbnail_path)
  827. if not thumb_path.is_absolute():
  828. thumb_path = Path(settings.base_dir) / lib_file.thumbnail_path
  829. cleanup_disk_paths.append(thumb_path)
  830. await db.delete(lib_file)
  831. await db.commit()
  832. for cleanup_path in cleanup_disk_paths:
  833. try:
  834. if cleanup_path.exists():
  835. cleanup_path.unlink()
  836. except OSError as cleanup_err:
  837. logger.warning("Failed to delete transient library file %s: %s", cleanup_path, cleanup_err)
  838. except DispatchJobCancelled:
  839. await db.rollback()
  840. await self._set_active_message(job, f"Cancelled upload on {printer_name}.")
  841. raise
  842. @staticmethod
  843. async def _verify_print_response(
  844. printer_id: int,
  845. printer_name: str,
  846. pre_state: str,
  847. pre_subtask_id: str | None = None,
  848. pre_gcode_file: str | None = None,
  849. timeout: float = 90.0,
  850. poll_interval: float = 3.0,
  851. ) -> bool:
  852. """Wait for the printer to acknowledge a print command.
  853. Returns True if the printer transitioned (state advanced past pre_state
  854. or subtask_id advanced past pre_subtask_id). Returns False on timeout —
  855. in that case logs a warning and forces an MQTT reconnect, mirroring the
  856. queue-side watchdog (`_watchdog_print_start`). Caller is responsible
  857. for surfacing the False result to the user (typically by raising so the
  858. dispatch job is marked failed).
  859. Both transition signals are checked because H2D can sit at FINISH for
  860. ~50 s after accepting `project_file` before flipping to PREPARE; the
  861. printer echoes our per-dispatch identity back as `subtask_id` on
  862. `push_status` first, so a subtask_id change is a definitive "command
  863. landed" signal even while state is still FINISH (#1078).
  864. """
  865. deadline = time.monotonic() + timeout
  866. last_status = None
  867. while time.monotonic() < deadline:
  868. await asyncio.sleep(poll_interval)
  869. state = printer_manager.get_status(printer_id)
  870. if not state:
  871. # Printer momentarily not reporting — could be a brief MQTT
  872. # disconnect mid-window. Keep polling rather than declaring
  873. # failure on the first missed tick; the printer may reconnect
  874. # within the remaining timeout and still surface a transition.
  875. continue
  876. last_status = state
  877. if state.state in _ACTIVE_PRINT_STATES:
  878. # Printer is actively processing the job. We do NOT accept
  879. # arbitrary state transitions: a printer going FINISH -> IDLE
  880. # (user dismissed the post-print prompt without accepting our
  881. # project_file) would otherwise look like "command landed"
  882. # and the dispatch job would be marked successful even though
  883. # no print is running (#1370).
  884. return True
  885. if pre_subtask_id is not None and state.subtask_id is not None and state.subtask_id != pre_subtask_id:
  886. # Printer picked up the job (subtask_id advanced). H2D can
  887. # sit at FINISH for ~50 s after accepting project_file before
  888. # transitioning to PREPARE, but the subtask_id flips to our
  889. # submission_id almost immediately (#1078).
  890. return True
  891. logger.warning(
  892. "Printer %s (%d) did not respond to print command within %.0fs "
  893. "(state still %s, subtask_id still %s) — printer may need restart",
  894. printer_name,
  895. printer_id,
  896. timeout,
  897. pre_state,
  898. pre_subtask_id,
  899. )
  900. # Distinguish #1150 (slow parse) from #887/#936 (half-broken session)
  901. # via gcode_file: if the printer is now showing a different file than
  902. # before dispatch, the project_file command landed and the printer is
  903. # parsing — a forced reconnect mid-parse causes 0500_4003. If
  904. # gcode_file is unchanged, the publish was silently swallowed and the
  905. # original #936 recovery (force_reconnect → fresh client_id) is what
  906. # we want. Caveat: in the rare retry-same-file-after-timeout case the
  907. # printer's gcode_file looks identical before and after the publish
  908. # lands, so a slow parse on retry-same-file still falls through to the
  909. # reconnect (and the original 0500_4003) — accepted to avoid breaking
  910. # the half-broken-session recovery path.
  911. client = printer_manager.get_client(printer_id)
  912. current_gcode_file = getattr(last_status, "gcode_file", None) if last_status else None
  913. publish_landed = current_gcode_file is not None and current_gcode_file != pre_gcode_file
  914. if publish_landed:
  915. logger.warning(
  916. "Printer %s (%d) gcode_file changed to %r (was %r) — printer "
  917. "received the command and is parsing slowly. Skipping forced "
  918. "MQTT reconnect to avoid 0500_4003 mid-parse (#1150).",
  919. printer_name,
  920. printer_id,
  921. current_gcode_file,
  922. pre_gcode_file,
  923. )
  924. elif client and hasattr(client, "force_reconnect_stale_session"):
  925. client.force_reconnect_stale_session(
  926. f"print command unacknowledged after {timeout:.0f}s "
  927. f"(state still {pre_state}, gcode_file {current_gcode_file!r})"
  928. )
  929. return False
  930. @staticmethod
  931. async def _cleanup_sd_card_file(
  932. printer_ip: str,
  933. access_code: str,
  934. remote_path: str,
  935. printer_model: str | None,
  936. ):
  937. """Best-effort delete of uploaded file from printer SD card."""
  938. try:
  939. await delete_file_async(printer_ip, access_code, remote_path, printer_model=printer_model)
  940. except Exception:
  941. pass # Best-effort — don't fail the error handler
  942. @staticmethod
  943. def _resolve_plate_id(file_path: Path, requested_plate_id: int | None) -> int:
  944. if requested_plate_id is not None:
  945. return requested_plate_id
  946. plate_id = 1
  947. try:
  948. with zipfile.ZipFile(file_path, "r") as zf:
  949. for name in zf.namelist():
  950. if name.startswith("Metadata/plate_") and name.endswith(".gcode"):
  951. plate_str = name[15:-6]
  952. plate_id = int(plate_str)
  953. break
  954. except (ValueError, zipfile.BadZipFile, OSError):
  955. pass
  956. return plate_id
  957. @staticmethod
  958. def _is_sliced_file(filename: str) -> bool:
  959. lower = filename.lower()
  960. return lower.endswith(".gcode") or lower.endswith(".gcode.3mf")
  961. background_dispatch = BackgroundDispatchService()