virtual_printers.py 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571
  1. import logging
  2. from fastapi import APIRouter, Depends
  3. from fastapi.responses import JSONResponse
  4. from pydantic import BaseModel
  5. from sqlalchemy import select
  6. from sqlalchemy.ext.asyncio import AsyncSession
  7. from backend.app.core.auth import RequirePermissionIfAuthEnabled
  8. from backend.app.core.database import get_db
  9. from backend.app.core.permissions import Permission
  10. from backend.app.models.user import User
  11. from backend.app.schemas.virtual_printer import VPDiagnosticResult
  12. # Imported at module scope so tests can patch
  13. # backend.app.api.routes.virtual_printers.tailscale_service.
  14. from backend.app.services.virtual_printer.tailscale import tailscale_service
  15. logger = logging.getLogger(__name__)
  16. router = APIRouter(prefix="/virtual-printers", tags=["virtual-printers"])
  17. class TailscaleStatusResponse(BaseModel):
  18. available: bool
  19. fqdn: str
  20. hostname: str
  21. tailnet_name: str
  22. tailscale_ips: list[str]
  23. error: str | None
  24. class VirtualPrinterCreate(BaseModel):
  25. name: str = "Bambuddy"
  26. enabled: bool = False
  27. mode: str = "archive"
  28. model: str | None = None
  29. access_code: str | None = None
  30. target_printer_id: int | None = None
  31. auto_dispatch: bool = True
  32. queue_force_color_match: bool = False
  33. bind_ip: str | None = None
  34. remote_interface_ip: str | None = None
  35. class VirtualPrinterUpdate(BaseModel):
  36. name: str | None = None
  37. enabled: bool | None = None
  38. mode: str | None = None
  39. model: str | None = None
  40. access_code: str | None = None
  41. target_printer_id: int | None = None
  42. auto_dispatch: bool | None = None
  43. queue_force_color_match: bool | None = None
  44. bind_ip: str | None = None
  45. remote_interface_ip: str | None = None
  46. tailscale_disabled: bool | None = None
  47. def _resolve_printer_model(printer_model: str | None) -> str | None:
  48. """Map a printer's model (display name or SSDP code) to a valid VP SSDP model code.
  49. Printers store display names like 'X1C' while VPs need SSDP codes like 'BL-P001'.
  50. """
  51. if not printer_model:
  52. return None
  53. from backend.app.services.virtual_printer import VIRTUAL_PRINTER_MODELS
  54. from backend.app.services.virtual_printer.manager import DISPLAY_NAME_TO_MODEL_CODE
  55. # Already a valid SSDP model code
  56. if printer_model in VIRTUAL_PRINTER_MODELS:
  57. return printer_model
  58. # Map display name to SSDP code
  59. return DISPLAY_NAME_TO_MODEL_CODE.get(printer_model)
  60. def _vp_to_dict(vp, status: dict | None = None) -> dict:
  61. """Convert VirtualPrinter model to response dict."""
  62. from backend.app.services.virtual_printer import VIRTUAL_PRINTER_MODELS
  63. from backend.app.services.virtual_printer.manager import DEFAULT_VIRTUAL_PRINTER_MODEL, _get_serial_for_model
  64. model_code = vp.model or DEFAULT_VIRTUAL_PRINTER_MODEL
  65. serial = _get_serial_for_model(model_code, vp.serial_suffix)
  66. return {
  67. "id": vp.id,
  68. "name": vp.name,
  69. "enabled": vp.enabled,
  70. "mode": vp.mode,
  71. "model": model_code,
  72. "model_name": VIRTUAL_PRINTER_MODELS.get(model_code, model_code),
  73. "access_code_set": bool(vp.access_code),
  74. "serial": serial,
  75. "target_printer_id": vp.target_printer_id,
  76. "auto_dispatch": vp.auto_dispatch,
  77. "queue_force_color_match": vp.queue_force_color_match,
  78. "bind_ip": vp.bind_ip,
  79. "remote_interface_ip": vp.remote_interface_ip,
  80. "tailscale_disabled": vp.tailscale_disabled,
  81. "position": vp.position,
  82. "status": status or {"running": False, "pending_files": 0},
  83. }
  84. @router.get("")
  85. async def list_virtual_printers(
  86. db: AsyncSession = Depends(get_db),
  87. _: User | None = RequirePermissionIfAuthEnabled(Permission.SETTINGS_READ),
  88. ):
  89. """List all virtual printers with status."""
  90. from backend.app.models.virtual_printer import VirtualPrinter
  91. from backend.app.services.virtual_printer import VIRTUAL_PRINTER_MODELS, virtual_printer_manager
  92. result = await db.execute(select(VirtualPrinter).order_by(VirtualPrinter.position, VirtualPrinter.id))
  93. vps = result.scalars().all()
  94. printers = []
  95. for vp in vps:
  96. instance = virtual_printer_manager.get_instance(vp.id)
  97. status = instance.get_status() if instance else {"running": False, "pending_files": 0}
  98. printers.append(_vp_to_dict(vp, status))
  99. return {
  100. "printers": printers,
  101. "models": VIRTUAL_PRINTER_MODELS,
  102. }
  103. @router.post("")
  104. async def create_virtual_printer(
  105. body: VirtualPrinterCreate,
  106. db: AsyncSession = Depends(get_db),
  107. _: User | None = RequirePermissionIfAuthEnabled(Permission.SETTINGS_UPDATE),
  108. ):
  109. """Create a new virtual printer."""
  110. from backend.app.models.virtual_printer import VP_MODE_VALUES, VirtualPrinter, normalize_vp_mode
  111. from backend.app.services.virtual_printer import VIRTUAL_PRINTER_MODELS, virtual_printer_manager
  112. from backend.app.services.virtual_printer.manager import DEFAULT_VIRTUAL_PRINTER_MODEL
  113. # Accept both canonical and legacy wire values so older clients (forks /
  114. # mobile shortcuts / scripted setups) still work; normalize before write.
  115. body.mode = normalize_vp_mode(body.mode) or body.mode
  116. if body.mode not in VP_MODE_VALUES:
  117. return JSONResponse(status_code=400, content={"detail": "Invalid mode"})
  118. # Validate model
  119. if body.model and body.model not in VIRTUAL_PRINTER_MODELS:
  120. return JSONResponse(
  121. status_code=400,
  122. content={"detail": f"Invalid model. Must be one of: {', '.join(VIRTUAL_PRINTER_MODELS.keys())}"},
  123. )
  124. # Validate access code length
  125. if body.access_code and len(body.access_code) != 8:
  126. return JSONResponse(status_code=400, content={"detail": "Access code must be exactly 8 characters"})
  127. # Validation when enabling. Non-proxy VPs with a target printer derive
  128. # their access code from the target (the bridge forwards the slicer's
  129. # auth bytes through to the real printer, so the codes MUST match),
  130. # so a separately-supplied access_code isn't required in that case.
  131. if body.enabled:
  132. if not body.bind_ip:
  133. return JSONResponse(status_code=400, content={"detail": "Bind IP is required when enabling"})
  134. if body.mode == "proxy":
  135. if not body.target_printer_id:
  136. return JSONResponse(status_code=400, content={"detail": "Target printer is required for proxy mode"})
  137. else:
  138. if not body.access_code and not body.target_printer_id:
  139. return JSONResponse(status_code=400, content={"detail": "Access code is required when enabling"})
  140. # Validate proxy target printer exists
  141. target_printer = None
  142. if body.target_printer_id:
  143. from backend.app.models.printer import Printer
  144. result = await db.execute(select(Printer).where(Printer.id == body.target_printer_id))
  145. target_printer = result.scalar_one_or_none()
  146. if not target_printer:
  147. return JSONResponse(
  148. status_code=400, content={"detail": f"Printer with ID {body.target_printer_id} not found"}
  149. )
  150. # Validate bind_ip uniqueness (against all enabled VPs)
  151. if body.bind_ip:
  152. result = await db.execute(
  153. select(VirtualPrinter).where(
  154. VirtualPrinter.bind_ip == body.bind_ip,
  155. VirtualPrinter.enabled == True, # noqa: E712
  156. )
  157. )
  158. if result.scalar_one_or_none():
  159. return JSONResponse(status_code=400, content={"detail": f"Bind IP {body.bind_ip} is already in use"})
  160. # Force-inherit the access code from the target printer for non-proxy VPs.
  161. # The non-proxy bridge (Immediate / Review / Queue with a target set) forwards
  162. # the slicer's MQTT / RTSPS auth bytes through to the real printer, so any
  163. # value the user supplied here would silently break the bridge if it didn't
  164. # match the printer's code. The UI now renders the field read-only when a
  165. # target is set; this is the belt-and-braces backstop for any non-UI client.
  166. effective_access_code = body.access_code
  167. if body.mode != "proxy" and target_printer is not None:
  168. effective_access_code = target_printer.access_code
  169. # Generate next serial suffix
  170. result = await db.execute(select(VirtualPrinter.serial_suffix).order_by(VirtualPrinter.id.desc()))
  171. last_suffix = result.scalar()
  172. if last_suffix:
  173. try:
  174. next_num = int(last_suffix) + 1
  175. new_suffix = str(next_num).zfill(9)
  176. except ValueError:
  177. new_suffix = "391800002"
  178. else:
  179. new_suffix = "391800001"
  180. # Get next position
  181. result = await db.execute(select(VirtualPrinter.position).order_by(VirtualPrinter.position.desc()))
  182. last_pos = result.scalar()
  183. next_pos = (last_pos or 0) + 1
  184. vp = VirtualPrinter(
  185. name=body.name,
  186. enabled=body.enabled,
  187. mode=body.mode,
  188. model=body.model
  189. or _resolve_printer_model(target_printer.model if target_printer and body.mode == "proxy" else None)
  190. or DEFAULT_VIRTUAL_PRINTER_MODEL,
  191. access_code=effective_access_code,
  192. target_printer_id=body.target_printer_id,
  193. auto_dispatch=body.auto_dispatch,
  194. queue_force_color_match=body.queue_force_color_match,
  195. bind_ip=body.bind_ip,
  196. remote_interface_ip=body.remote_interface_ip,
  197. serial_suffix=new_suffix,
  198. position=next_pos,
  199. )
  200. db.add(vp)
  201. await db.commit()
  202. await db.refresh(vp)
  203. logger.info("Created virtual printer: %s (id=%d)", vp.name, vp.id)
  204. # Sync services if enabled
  205. if body.enabled:
  206. try:
  207. await virtual_printer_manager.sync_from_db()
  208. except Exception as e:
  209. logger.error("Failed to start virtual printer after create: %s", e)
  210. return _vp_to_dict(vp)
  211. @router.get("/tailscale-status", response_model=TailscaleStatusResponse)
  212. async def get_tailscale_status(
  213. _: User | None = RequirePermissionIfAuthEnabled(Permission.SETTINGS_READ),
  214. ) -> TailscaleStatusResponse:
  215. """Return current Tailscale availability and machine identity.
  216. Used by the frontend to indicate whether virtual printer TLS is backed
  217. by a trusted Let's Encrypt certificate or a self-signed CA.
  218. """
  219. status = await tailscale_service.get_status()
  220. return TailscaleStatusResponse(
  221. available=status.available,
  222. fqdn=status.fqdn,
  223. hostname=status.hostname,
  224. tailnet_name=status.tailnet_name,
  225. tailscale_ips=status.tailscale_ips,
  226. error=status.error,
  227. )
  228. @router.get("/ca-certificate")
  229. async def get_ca_certificate(
  230. _: User | None = RequirePermissionIfAuthEnabled(Permission.SETTINGS_READ),
  231. ):
  232. """Return the shared virtual-printer CA certificate (PEM) for slicer trust import.
  233. One CA is shared by every virtual printer — the user imports it into their
  234. slicer's trust store once. Only the public certificate is returned; the CA
  235. private key never leaves the backend.
  236. """
  237. from backend.app.services.virtual_printer import virtual_printer_manager
  238. try:
  239. return virtual_printer_manager.get_ca_certificate_info()
  240. except Exception as e:
  241. logger.error("Failed to obtain virtual printer CA certificate: %s", e)
  242. return JSONResponse(status_code=500, content={"detail": "Could not generate the CA certificate"})
  243. @router.get("/{vp_id}/diagnostic", response_model=VPDiagnosticResult)
  244. async def diagnose_virtual_printer(
  245. vp_id: int,
  246. db: AsyncSession = Depends(get_db),
  247. _: User | None = RequirePermissionIfAuthEnabled(Permission.SETTINGS_READ),
  248. ):
  249. """Run setup diagnostics for a virtual printer.
  250. Probes the VP's own bind IP and services so the user can self-diagnose the
  251. common "my virtual printer doesn't show up in the slicer" failures.
  252. """
  253. from backend.app.models.virtual_printer import VirtualPrinter
  254. from backend.app.services.virtual_printer import virtual_printer_manager
  255. from backend.app.services.virtual_printer.diagnostic import run_vp_diagnostic
  256. result = await db.execute(select(VirtualPrinter).where(VirtualPrinter.id == vp_id))
  257. vp = result.scalar_one_or_none()
  258. if not vp:
  259. return JSONResponse(status_code=404, content={"detail": "Virtual printer not found"})
  260. instance = virtual_printer_manager.get_instance(vp.id)
  261. return await run_vp_diagnostic(vp, instance)
  262. @router.get("/{vp_id}")
  263. async def get_virtual_printer(
  264. vp_id: int,
  265. db: AsyncSession = Depends(get_db),
  266. _: User | None = RequirePermissionIfAuthEnabled(Permission.SETTINGS_READ),
  267. ):
  268. """Get a single virtual printer with status."""
  269. from backend.app.models.virtual_printer import VirtualPrinter
  270. from backend.app.services.virtual_printer import virtual_printer_manager
  271. result = await db.execute(select(VirtualPrinter).where(VirtualPrinter.id == vp_id))
  272. vp = result.scalar_one_or_none()
  273. if not vp:
  274. return JSONResponse(status_code=404, content={"detail": "Virtual printer not found"})
  275. instance = virtual_printer_manager.get_instance(vp.id)
  276. status = instance.get_status() if instance else {"running": False, "pending_files": 0}
  277. return _vp_to_dict(vp, status)
  278. @router.put("/{vp_id}")
  279. async def update_virtual_printer(
  280. vp_id: int,
  281. body: VirtualPrinterUpdate,
  282. db: AsyncSession = Depends(get_db),
  283. _: User | None = RequirePermissionIfAuthEnabled(Permission.SETTINGS_UPDATE),
  284. ):
  285. """Update a virtual printer."""
  286. from backend.app.models.virtual_printer import VirtualPrinter
  287. from backend.app.services.virtual_printer import VIRTUAL_PRINTER_MODELS, virtual_printer_manager
  288. result = await db.execute(select(VirtualPrinter).where(VirtualPrinter.id == vp_id))
  289. vp = result.scalar_one_or_none()
  290. if not vp:
  291. return JSONResponse(status_code=404, content={"detail": "Virtual printer not found"})
  292. # Redact the access code before logging — model_dump otherwise includes
  293. # the plaintext value at DEBUG, violating the project no-secrets-in-logs
  294. # rule. Replace with a marker that still signals "the user changed it"
  295. # vs "the user didn't touch this field".
  296. _safe_body = body.model_dump(exclude_unset=True)
  297. if "access_code" in _safe_body:
  298. _safe_body["access_code"] = "***"
  299. logger.debug(
  300. "Update VP %d: body=%s, current state: mode=%s, enabled=%s, access_code_set=%s, bind_ip=%s, target=%s",
  301. vp_id,
  302. _safe_body,
  303. vp.mode,
  304. vp.enabled,
  305. bool(vp.access_code),
  306. vp.bind_ip,
  307. vp.target_printer_id,
  308. )
  309. # Apply updates
  310. if body.name is not None:
  311. vp.name = body.name
  312. if body.mode is not None:
  313. from backend.app.models.virtual_printer import VP_MODE_VALUES, normalize_vp_mode
  314. canonical_mode = normalize_vp_mode(body.mode) or body.mode
  315. if canonical_mode not in VP_MODE_VALUES:
  316. return JSONResponse(status_code=400, content={"detail": "Invalid mode"})
  317. vp.mode = canonical_mode
  318. if body.model is not None:
  319. if body.model not in VIRTUAL_PRINTER_MODELS:
  320. return JSONResponse(
  321. status_code=400,
  322. content={"detail": f"Invalid model. Must be one of: {', '.join(VIRTUAL_PRINTER_MODELS.keys())}"},
  323. )
  324. vp.model = body.model
  325. if body.access_code is not None:
  326. if body.access_code and len(body.access_code) != 8:
  327. return JSONResponse(status_code=400, content={"detail": "Access code must be exactly 8 characters"})
  328. vp.access_code = body.access_code
  329. if body.target_printer_id is not None:
  330. from backend.app.models.printer import Printer
  331. result = await db.execute(select(Printer).where(Printer.id == body.target_printer_id))
  332. target_printer = result.scalar_one_or_none()
  333. if not target_printer:
  334. return JSONResponse(
  335. status_code=400, content={"detail": f"Printer with ID {body.target_printer_id} not found"}
  336. )
  337. vp.target_printer_id = body.target_printer_id
  338. # Auto-inherit model from target printer in proxy mode (unless user explicitly set model)
  339. if body.model is None and vp.mode == "proxy" and target_printer.model:
  340. vp.model = _resolve_printer_model(target_printer.model) or target_printer.model
  341. if body.auto_dispatch is not None:
  342. vp.auto_dispatch = body.auto_dispatch
  343. if body.queue_force_color_match is not None:
  344. vp.queue_force_color_match = body.queue_force_color_match
  345. if body.bind_ip is not None:
  346. vp.bind_ip = body.bind_ip
  347. if body.remote_interface_ip is not None:
  348. vp.remote_interface_ip = body.remote_interface_ip
  349. if body.tailscale_disabled is not None:
  350. vp.tailscale_disabled = body.tailscale_disabled
  351. # Auto-inherit model when switching to proxy mode with existing target printer
  352. if body.mode == "proxy" and body.model is None and body.target_printer_id is None and vp.target_printer_id:
  353. from backend.app.models.printer import Printer as PrinterModel
  354. result = await db.execute(select(PrinterModel).where(PrinterModel.id == vp.target_printer_id))
  355. existing_target = result.scalar_one_or_none()
  356. if existing_target and existing_target.model:
  357. vp.model = _resolve_printer_model(existing_target.model) or existing_target.model
  358. # Force-inherit the access code from the target printer for non-proxy VPs.
  359. # See create_virtual_printer for the rationale: the bridge forwards slicer
  360. # auth bytes through, so the VP's code MUST equal the target's. This block
  361. # runs after every patch (whether or not access_code or target were in the
  362. # body), so changing the target also resyncs the code, and an explicit
  363. # access_code submitted alongside a target is silently overridden.
  364. if vp.mode != "proxy" and vp.target_printer_id is not None:
  365. from backend.app.models.printer import Printer as PrinterModelAC
  366. result = await db.execute(select(PrinterModelAC).where(PrinterModelAC.id == vp.target_printer_id))
  367. target_for_ac = result.scalar_one_or_none()
  368. if target_for_ac is not None and vp.access_code != target_for_ac.access_code:
  369. vp.access_code = target_for_ac.access_code
  370. # Determine final enabled state
  371. explicitly_enabling = body.enabled is True
  372. new_enabled = body.enabled if body.enabled is not None else vp.enabled
  373. effective_mode = vp.mode
  374. if explicitly_enabling:
  375. # User is explicitly toggling on — enforce all requirements
  376. if not vp.bind_ip:
  377. logger.warning("Update VP %d rejected: no bind_ip", vp_id)
  378. return JSONResponse(status_code=400, content={"detail": "Bind IP is required when enabling"})
  379. # Validate bind_ip uniqueness (against all enabled VPs)
  380. existing = await db.execute(
  381. select(VirtualPrinter).where(
  382. VirtualPrinter.bind_ip == vp.bind_ip,
  383. VirtualPrinter.id != vp_id,
  384. VirtualPrinter.enabled == True, # noqa: E712
  385. )
  386. )
  387. conflict = existing.scalar_one_or_none()
  388. if conflict:
  389. logger.warning(
  390. "Update VP %d rejected: bind_ip %s already in use by VP %d (enabled=%s, mode=%s)",
  391. vp_id,
  392. vp.bind_ip,
  393. conflict.id,
  394. conflict.enabled,
  395. conflict.mode,
  396. )
  397. return JSONResponse(
  398. status_code=400,
  399. content={"detail": f"Bind IP {vp.bind_ip} is already in use by '{conflict.name}'"},
  400. )
  401. if effective_mode == "proxy":
  402. if not vp.target_printer_id:
  403. logger.warning("Update VP %d rejected: no target_printer_id for proxy mode", vp_id)
  404. return JSONResponse(status_code=400, content={"detail": "Target printer is required for proxy mode"})
  405. else:
  406. if not vp.access_code:
  407. logger.warning(
  408. "Update VP %d rejected: no access_code for non-proxy enable (mode=%s)", vp_id, effective_mode
  409. )
  410. return JSONResponse(status_code=400, content={"detail": "Access code is required when enabling"})
  411. elif new_enabled and body.enabled is None:
  412. # VP is already enabled and user is changing other fields —
  413. # auto-disable if new state doesn't meet requirements
  414. if not vp.bind_ip:
  415. new_enabled = False
  416. elif effective_mode == "proxy":
  417. if not vp.target_printer_id:
  418. new_enabled = False
  419. else:
  420. if not vp.access_code:
  421. new_enabled = False
  422. vp.enabled = new_enabled
  423. await db.commit()
  424. await db.refresh(vp)
  425. logger.info("Updated virtual printer: %s (id=%d)", vp.name, vp.id)
  426. # Sync services
  427. try:
  428. await virtual_printer_manager.sync_from_db()
  429. except Exception as e:
  430. logger.error("Failed to sync virtual printers after update: %s", e)
  431. instance = virtual_printer_manager.get_instance(vp.id)
  432. status = instance.get_status() if instance else {"running": False, "pending_files": 0}
  433. return _vp_to_dict(vp, status)
  434. @router.delete("/{vp_id}")
  435. async def delete_virtual_printer(
  436. vp_id: int,
  437. db: AsyncSession = Depends(get_db),
  438. _: User | None = RequirePermissionIfAuthEnabled(Permission.SETTINGS_UPDATE),
  439. ):
  440. """Delete a virtual printer."""
  441. from sqlalchemy import delete as sql_delete
  442. from backend.app.models.virtual_printer import VirtualPrinter
  443. from backend.app.services.virtual_printer import virtual_printer_manager
  444. result = await db.execute(select(VirtualPrinter).where(VirtualPrinter.id == vp_id))
  445. vp = result.scalar_one_or_none()
  446. if not vp:
  447. return JSONResponse(status_code=404, content={"detail": "Virtual printer not found"})
  448. vp_name = vp.name
  449. # Stop instance if running
  450. await virtual_printer_manager.remove_instance(vp_id)
  451. # Mark any PendingUpload rows that referenced this VP's upload_dir as
  452. # discarded — without this the rows live on as phantom entries in
  453. # /pending-uploads/ pointing at file paths that no longer exist, and
  454. # the user only learns they're orphaned by trying to archive one and
  455. # getting a flip-to-discarded on file-missing.
  456. upload_prefix = str(virtual_printer_manager._base_dir / "uploads" / str(vp_id))
  457. try:
  458. from backend.app.models.pending_upload import PendingUpload
  459. stale = await db.execute(select(PendingUpload).where(PendingUpload.file_path.startswith(upload_prefix)))
  460. for pending in stale.scalars().all():
  461. pending.status = "discarded"
  462. await db.flush()
  463. except Exception as e:
  464. logger.error("Failed to discard orphan PendingUpload rows for VP %d: %s", vp_id, e)
  465. # Delete from DB
  466. await db.execute(sql_delete(VirtualPrinter).where(VirtualPrinter.id == vp_id))
  467. await db.commit()
  468. # Remove the on-disk upload directory after the DB commit succeeds, so
  469. # a crash between commit and rmtree only leaves orphan files (vs orphan
  470. # rows pointing at a now-missing tree).
  471. upload_dir = virtual_printer_manager._base_dir / "uploads" / str(vp_id)
  472. if upload_dir.exists():
  473. import shutil
  474. shutil.rmtree(upload_dir, ignore_errors=True)
  475. logger.info("Deleted virtual printer: %s (id=%d)", vp_name, vp_id)
  476. # Resync remaining services
  477. try:
  478. await virtual_printer_manager.sync_from_db()
  479. except Exception as e:
  480. logger.error("Failed to sync virtual printers after delete: %s", e)
  481. return {"detail": "Deleted", "id": vp_id}