virtual_printers.py 24 KB

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