slicer_presets.py 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574
  1. """Unified slicer-preset listing for the SliceModal (#wiki / Cloud-aware presets).
  2. Returns the printer/process/filament options grouped by source tier in
  3. priority order — cloud (per-user, live-fetched) > local (DB-backed
  4. imports) > standard (slicer-bundled stock fallback). Name-based dedup is
  5. applied so a preset that exists in multiple tiers only appears in the
  6. highest-priority one. Cloud failure modes (signed out / expired / network)
  7. are surfaced via a status field so the modal can render a precise banner
  8. without faking an "ok with empty list" response.
  9. """
  10. from __future__ import annotations
  11. import hashlib
  12. import json
  13. import logging
  14. import time
  15. from fastapi import APIRouter, Depends, HTTPException, Query
  16. from sqlalchemy import select
  17. from sqlalchemy.ext.asyncio import AsyncSession
  18. from backend.app.api.routes.cloud import get_stored_token, resolve_api_key_cloud_owner
  19. from backend.app.api.routes.orca_cloud import (
  20. _ORCA_TYPE_TO_BAMBU,
  21. _build_authenticated_service as _build_orca_service,
  22. _load_credentials as _load_orca_credentials,
  23. )
  24. from backend.app.core.auth import RequirePermissionIfAuthEnabled, require_ownership_permission
  25. from backend.app.core.config import settings as app_settings
  26. from backend.app.core.database import get_db
  27. from backend.app.core.permissions import Permission
  28. from backend.app.models.local_preset import LocalPreset
  29. from backend.app.models.user import User
  30. from backend.app.schemas.slicer_presets import (
  31. UnifiedPreset,
  32. UnifiedPresetsBySlot,
  33. UnifiedPresetsResponse,
  34. )
  35. from backend.app.services.bambu_cloud import (
  36. BambuCloudAuthError,
  37. BambuCloudError,
  38. BambuCloudService,
  39. )
  40. from backend.app.services.orca_cloud import (
  41. OrcaCloudAuthError,
  42. OrcaCloudError,
  43. )
  44. from backend.app.services.slicer_api import (
  45. SlicerApiError,
  46. SlicerApiService,
  47. )
  48. from backend.app.utils.printer_models import PRINTER_MODEL_MAP
  49. logger = logging.getLogger(__name__)
  50. router = APIRouter(prefix="/slicer", tags=["Slicer Presets"])
  51. # In-process cache for the bundled-profile list. The slicer sidecar walks a
  52. # read-only filesystem inside its own container, so the list only changes
  53. # across sidecar rebuilds — a long TTL is safe and avoids a sidecar round-trip
  54. # on every modal open. Per-user cache is unnecessary because bundled profiles
  55. # are global.
  56. _BUNDLED_TTL_S = 3600.0
  57. _bundled_cache: tuple[float, dict[str, list[UnifiedPreset]]] | None = None
  58. # Per-user cache for the cloud preset list. Cache key is (user_id, token_hash):
  59. # keying on the token hash means a logout/login or token-change automatically
  60. # invalidates the entry without needing the cloud-auth route handlers to call
  61. # back into this module. 5 minutes balances "users see their freshly-saved
  62. # presets quickly" against "a busy install doesn't hit the cloud once per
  63. # modal open per user".
  64. _CLOUD_TTL_S = 300.0
  65. _cloud_cache: dict[tuple[int, str], tuple[float, dict[str, list[UnifiedPreset]]]] = {}
  66. # Same shape for Orca Cloud — keyed on (user_id, access_token-fingerprint).
  67. _orca_cloud_cache: dict[tuple[int, str], tuple[float, dict[str, list[UnifiedPreset]]]] = {}
  68. def _token_fingerprint(token: str) -> str:
  69. """Short stable hash of the cloud token for use as a cache-key component.
  70. Storing only the hash means we can safely keep multiple per-(user, token)
  71. entries without leaking the token via the in-process dict."""
  72. return hashlib.sha256(token.encode("utf-8")).hexdigest()[:16]
  73. _CLOUD_TYPE_TO_SLOT = {
  74. "filament": "filament",
  75. "printer": "printer",
  76. "print": "process", # Bambu Cloud calls process presets "print"
  77. }
  78. def _empty_slots() -> dict[str, list[UnifiedPreset]]:
  79. return {"printer": [], "process": [], "filament": []}
  80. async def _fetch_cloud_presets(
  81. db: AsyncSession, user: User | None, *, refresh: bool = False
  82. ) -> tuple[dict[str, list[UnifiedPreset]], str]:
  83. """Return (slots, cloud_status). Slots are empty when cloud_status != 'ok'.
  84. Defence-in-depth: even if a stored cloud_token survived a permission
  85. revocation (admin reset, legacy state), users without ``CLOUD_AUTH`` are
  86. treated as not-authenticated for this endpoint — the cloud tier never
  87. surfaces for them. This keeps the per-tier visibility consistent with the
  88. /cloud/* endpoint suite that already gates on CLOUD_AUTH.
  89. ``refresh=True`` skips the in-process cache for this call (used by the
  90. SliceModal's manual Refresh button so a user who just deleted a preset
  91. in Bambu Studio / Handy can pick up the change without waiting for the
  92. 5-minute TTL to expire). The fresh result is still written back to the
  93. cache so subsequent non-refresh callers benefit.
  94. """
  95. if user is not None and not user.has_permission(Permission.CLOUD_AUTH.value):
  96. return _empty_slots(), "not_authenticated"
  97. token, _email, region = await get_stored_token(db, user)
  98. if not token:
  99. return _empty_slots(), "not_authenticated"
  100. user_key = user.id if user is not None else 0
  101. cache_key = (user_key, _token_fingerprint(token))
  102. now = time.monotonic()
  103. if not refresh:
  104. cached = _cloud_cache.get(cache_key)
  105. if cached and now - cached[0] < _CLOUD_TTL_S:
  106. return cached[1], "ok"
  107. cloud = BambuCloudService(region=region)
  108. cloud.set_token(token)
  109. try:
  110. try:
  111. raw = await cloud.get_slicer_settings()
  112. except BambuCloudAuthError:
  113. # Don't clear the token here — the cloud-status endpoint owns that
  114. # lifecycle. Just report expired so the UI can prompt re-auth.
  115. return _empty_slots(), "expired"
  116. except BambuCloudError as e:
  117. logger.warning("Cloud preset fetch failed for user %s: %s", user_key, e)
  118. return _empty_slots(), "unreachable"
  119. except Exception as e: # noqa: BLE001 — defensive: never crash the modal
  120. logger.warning("Cloud preset fetch unexpected error for user %s: %s", user_key, e)
  121. return _empty_slots(), "unreachable"
  122. slots = _empty_slots()
  123. for cloud_type, slot in _CLOUD_TYPE_TO_SLOT.items():
  124. type_data = raw.get(cloud_type, {})
  125. # The cloud splits presets into "private" (the user's own) and "public"
  126. # (Bambu's stock cloud presets). Both are valid choices — surface them
  127. # in the natural order private → public so a user's customisations
  128. # appear above the stock entries with the same names. Stock entries
  129. # that share names with private ones get deduped out within the cloud
  130. # tier itself.
  131. seen_names: set[str] = set()
  132. for entry in type_data.get("private", []) + type_data.get("public", []):
  133. name = entry.get("name")
  134. setting_id = entry.get("setting_id") or entry.get("id")
  135. if not name or not setting_id or name in seen_names:
  136. continue
  137. seen_names.add(name)
  138. slots[slot].append(UnifiedPreset(id=setting_id, name=name, source="cloud"))
  139. # Cloud filament presets carry no metadata in this response on
  140. # purpose: the per-preset detail endpoint
  141. # (/v1/iot-service/api/slicer/setting/{id}) is rate-limited at roughly
  142. # 10/sec per token, so fetching N filament presets to enrich them
  143. # one-by-one trips Bambu's limiter and returns 429 on every request
  144. # for users with large preset libraries (#1150 follow-up).
  145. #
  146. # The metadata-enrich pass (see _enrich_cloud_metadata) compensates:
  147. # a Bambu Cloud entry without its own filament_type/colour inherits
  148. # those values from a same-named local / orca_cloud / standard entry
  149. # so it can still score for type/colour matches in pickFilamentForSlot.
  150. _cloud_cache[cache_key] = (now, slots)
  151. return slots, "ok"
  152. finally:
  153. await cloud.close()
  154. async def _fetch_orca_cloud_presets(
  155. db: AsyncSession, user: User | None, *, refresh: bool = False
  156. ) -> tuple[dict[str, list[UnifiedPreset]], str]:
  157. """Mirror of :func:`_fetch_cloud_presets` but for Orca Cloud. Same status
  158. vocabulary (``ok`` / ``not_authenticated`` / ``expired`` / ``unreachable``),
  159. same caching shape, same defence-in-depth permission gate
  160. (``orca_cloud:auth`` rather than ``cloud:auth``).
  161. Filament metadata (``filament_type`` / ``filament_colour``) is extracted
  162. from the profile's inline ``content`` dict — unlike Bambu Cloud where
  163. we'd have to fetch each setting separately and hit a rate limit, Orca's
  164. ``/sync/pull`` already returns full content per profile, so the metadata
  165. enrichment is free here.
  166. """
  167. if user is not None and not user.has_permission(Permission.ORCA_CLOUD_AUTH.value):
  168. return _empty_slots(), "not_authenticated"
  169. creds = await _load_orca_credentials(db, user)
  170. if not creds.token:
  171. return _empty_slots(), "not_authenticated"
  172. user_key = user.id if user is not None else 0
  173. cache_key = (user_key, _token_fingerprint(creds.token))
  174. now = time.monotonic()
  175. if not refresh:
  176. cached = _orca_cloud_cache.get(cache_key)
  177. if cached and now - cached[0] < _CLOUD_TTL_S:
  178. return cached[1], "ok"
  179. try:
  180. svc = await _build_orca_service(db, user)
  181. except HTTPException as e:
  182. # ``_build_orca_service`` raises 401 when the token is missing,
  183. # the refresh-token rotation failed, or the JIT refresh hit Orca's
  184. # backend and got rejected; 502 when Orca is unreachable. Translate
  185. # to the status vocabulary the SliceModal expects.
  186. if e.status_code == 401:
  187. return _empty_slots(), "expired"
  188. return _empty_slots(), "unreachable"
  189. try:
  190. try:
  191. raw_profiles = await svc.list_profiles()
  192. except OrcaCloudAuthError:
  193. return _empty_slots(), "expired"
  194. except OrcaCloudError as e:
  195. logger.warning("Orca Cloud preset fetch failed for user %s: %s", user_key, e)
  196. return _empty_slots(), "unreachable"
  197. except Exception as e: # noqa: BLE001 — defensive: never crash the modal
  198. logger.warning("Orca Cloud preset fetch unexpected error for user %s: %s", user_key, e)
  199. return _empty_slots(), "unreachable"
  200. slots = _empty_slots()
  201. for entry in raw_profiles:
  202. content = entry.get("content") if isinstance(entry, dict) else None
  203. if not isinstance(content, dict):
  204. continue
  205. slot = _ORCA_TYPE_TO_BAMBU.get(str(content.get("type", "")))
  206. if slot is None:
  207. continue
  208. preset_id = entry.get("id")
  209. name = entry.get("name") or preset_id
  210. if not preset_id or not name:
  211. continue
  212. filament_type: str | None = None
  213. filament_colour: str | None = None
  214. if slot == "filament":
  215. # Bambu/Orca filament profiles store these as single-element
  216. # arrays (the historical multi-extruder shape). Extract the
  217. # first non-empty element for both.
  218. ft = content.get("filament_type")
  219. if isinstance(ft, list) and ft and isinstance(ft[0], str):
  220. filament_type = ft[0]
  221. elif isinstance(ft, str):
  222. filament_type = ft
  223. fc = content.get("default_filament_colour")
  224. if isinstance(fc, list) and fc and isinstance(fc[0], str):
  225. filament_colour = fc[0]
  226. elif isinstance(fc, str):
  227. filament_colour = fc
  228. slots[slot].append(
  229. UnifiedPreset(
  230. id=str(preset_id),
  231. name=str(name),
  232. source="orca_cloud",
  233. filament_type=filament_type,
  234. filament_colour=filament_colour,
  235. )
  236. )
  237. _orca_cloud_cache[cache_key] = (now, slots)
  238. return slots, "ok"
  239. finally:
  240. await svc.close()
  241. async def _fetch_local_presets(db: AsyncSession) -> dict[str, list[UnifiedPreset]]:
  242. """Local imports — no caching needed, single indexed DB read."""
  243. result = await db.execute(select(LocalPreset).order_by(LocalPreset.name))
  244. presets = result.scalars().all()
  245. slots = _empty_slots()
  246. type_to_slot = {"filament": "filament", "printer": "printer", "process": "process"}
  247. for p in presets:
  248. slot = type_to_slot.get(p.preset_type)
  249. if slot is None:
  250. continue
  251. preset = UnifiedPreset(id=str(p.id), name=p.name, source="local")
  252. if slot == "filament":
  253. preset.filament_type, preset.filament_colour = _parse_filament_metadata(p.setting)
  254. if slot in ("process", "filament"):
  255. # Precise compatibility link — the slicer's own compatible_printers
  256. # list, captured at import time. Lets the SliceModal filter the
  257. # process / filament dropdowns by the selected printer without
  258. # falling back to the uploaded-bundle index.
  259. preset.compatible_printers = _parse_compatible_printers(p.compatible_printers)
  260. slots[slot].append(preset)
  261. return slots
  262. def _parse_compatible_printers(raw: str | None) -> list[str] | None:
  263. """``LocalPreset.compatible_printers`` stores a JSON array of printer-preset
  264. names. Return the parsed list, or ``None`` on missing / malformed data so
  265. the SliceModal falls back to the uploaded-bundle index for that preset."""
  266. if not raw:
  267. return None
  268. try:
  269. data = json.loads(raw)
  270. except (ValueError, TypeError):
  271. return None
  272. if not isinstance(data, list):
  273. return None
  274. names = [s for s in data if isinstance(s, str) and s.strip()]
  275. return names or None
  276. def _parse_filament_metadata(setting_json: str | None) -> tuple[str | None, str | None]:
  277. """Extract first-slot ``filament_type`` and ``filament_colour`` from a
  278. stored preset JSON. OrcaSlicer stores both as arrays (per-extruder) — we
  279. take the first entry since pre-pick matching is one-slot-at-a-time.
  280. Defensive parse: any error returns (None, None) so a corrupt row never
  281. breaks the listing."""
  282. if not setting_json:
  283. return None, None
  284. try:
  285. data = json.loads(setting_json)
  286. except (ValueError, TypeError):
  287. return None, None
  288. if not isinstance(data, dict):
  289. return None, None
  290. return _first_scalar(data.get("filament_type")), _first_scalar(data.get("filament_colour"))
  291. def _first_scalar(value: object) -> str | None:
  292. if isinstance(value, list) and value:
  293. return value[0] if isinstance(value[0], str) else None
  294. if isinstance(value, str) and value:
  295. return value
  296. return None
  297. async def _fetch_bundled_presets(db: AsyncSession, *, refresh: bool = False) -> dict[str, list[UnifiedPreset]]:
  298. """Standard slicer-bundled profiles via the sidecar's /profiles/bundled.
  299. ``refresh=True`` skips the in-process cache; see _fetch_cloud_presets for
  300. the same shape and rationale.
  301. """
  302. global _bundled_cache
  303. now = time.monotonic()
  304. if not refresh and _bundled_cache and now - _bundled_cache[0] < _BUNDLED_TTL_S:
  305. return _bundled_cache[1]
  306. api_url = await _resolve_slicer_api_url(db)
  307. if not api_url:
  308. # No sidecar configured at all — return empty rather than caching, so
  309. # users who configure one mid-session see results on next open.
  310. return _empty_slots()
  311. try:
  312. async with SlicerApiService(base_url=api_url) as svc:
  313. raw = await svc.list_bundled_profiles()
  314. except SlicerApiError as e:
  315. logger.info("Bundled preset fetch from sidecar at %s failed: %s", api_url, e)
  316. return _empty_slots()
  317. except Exception as e: # noqa: BLE001 — never break the modal on sidecar issues
  318. logger.warning("Bundled preset fetch unexpected error: %s", e)
  319. return _empty_slots()
  320. slots = _empty_slots()
  321. for slot in ("printer", "process", "filament"):
  322. for entry in raw.get(slot, []) or []:
  323. name = entry.get("name")
  324. if not name:
  325. continue
  326. # Bundled presets are addressed by name (the slicer resolves them
  327. # by name during the `inherits:` walk), so name doubles as id.
  328. extra: dict[str, str | None] = {}
  329. if slot == "filament":
  330. extra["filament_type"] = entry.get("filament_type")
  331. extra["filament_colour"] = entry.get("filament_colour")
  332. slots[slot].append(
  333. UnifiedPreset(id=name, name=name, source="standard", **extra),
  334. )
  335. _bundled_cache = (now, slots)
  336. return slots
  337. async def _resolve_slicer_api_url(db: AsyncSession) -> str | None:
  338. """Pick the sidecar URL the bundled-listing fetch should hit.
  339. Mirrors the slice route's resolution at ``library.py:_run_slicer_with_fallback``:
  340. the user's ``preferred_slicer`` setting decides which sidecar Bambuddy
  341. talks to, and the per-install URL setting overrides the env default.
  342. A user who prefers Bambu Studio gets the *bambu-studio-api* sidecar's
  343. bundled list; a user who prefers OrcaSlicer gets the *orca-slicer-api*
  344. sidecar's bundled list. Without this branch the listing would always
  345. hit OrcaSlicer (port 3003) even for BambuStudio installs (port 3001),
  346. leaving the Standard tier permanently empty for them.
  347. """
  348. from backend.app.api.routes.settings import get_setting
  349. preferred = (await get_setting(db, "preferred_slicer")) or "bambu_studio"
  350. if preferred == "orcaslicer":
  351. configured = await get_setting(db, "orcaslicer_api_url")
  352. url = (configured or app_settings.slicer_api_url).strip()
  353. elif preferred == "bambu_studio":
  354. configured = await get_setting(db, "bambu_studio_api_url")
  355. url = (configured or app_settings.bambu_studio_api_url).strip()
  356. else:
  357. # Unknown preference — return None so the bundled tier is empty
  358. # rather than crashing the modal. The slice route raises 400 here;
  359. # we degrade silently because the modal's listing is informational.
  360. logger.warning("Unknown preferred_slicer setting: %r — bundled tier disabled", preferred)
  361. return None
  362. return url or None
  363. def _enrich_cloud_metadata(
  364. orca_cloud: dict[str, list[UnifiedPreset]],
  365. cloud: dict[str, list[UnifiedPreset]],
  366. local: dict[str, list[UnifiedPreset]],
  367. standard: dict[str, list[UnifiedPreset]],
  368. ) -> tuple[
  369. dict[str, list[UnifiedPreset]],
  370. dict[str, list[UnifiedPreset]],
  371. dict[str, list[UnifiedPreset]],
  372. dict[str, list[UnifiedPreset]],
  373. ]:
  374. """Backfill Bambu Cloud filament metadata; do NOT dedup tiers.
  375. Every tier surfaces its full list — a name that exists in both ``local``
  376. and ``orca_cloud`` shows up in BOTH dropdown groups so the user can pick
  377. either source. Tier ORDER (``local > orca_cloud > cloud > standard``)
  378. is communicated by the SliceModal's group rendering and by the
  379. name-collision fallback in ``findPresetByName``; this function does not
  380. enforce it.
  381. Filament metadata merge: a Bambu Cloud entry without its own
  382. ``filament_type`` / ``filament_colour`` (Bambu Cloud doesn't surface
  383. these in the list response for rate-limiting reasons — see
  384. :func:`_fetch_cloud_presets`) inherits values from a same-named entry
  385. in ``local`` / ``orca_cloud`` / ``standard``. This is the only reason
  386. this function exists post-#1712 — without the enrich the Bambu Cloud
  387. tier can't score in ``pickFilamentForSlot``.
  388. """
  389. # Build a name → metadata lookup from the tiers that carry it (local,
  390. # orca_cloud, standard). Bambu cloud is intentionally skipped — it
  391. # doesn't populate filament_type/colour in the list response. Take
  392. # whichever non-empty entry shows up first.
  393. metadata_by_name: dict[str, tuple[str | None, str | None]] = {}
  394. for tier in (local, orca_cloud, standard):
  395. for p in tier["filament"]:
  396. if p.name in metadata_by_name:
  397. continue
  398. if p.filament_type or p.filament_colour:
  399. metadata_by_name[p.name] = (p.filament_type, p.filament_colour)
  400. # Backfill Bambu Cloud entries that don't have their own metadata.
  401. for p in cloud["filament"]:
  402. if (p.filament_type is None or p.filament_colour is None) and p.name in metadata_by_name:
  403. t, c = metadata_by_name[p.name]
  404. if p.filament_type is None and t is not None:
  405. p.filament_type = t
  406. if p.filament_colour is None and c is not None:
  407. p.filament_colour = c
  408. return orca_cloud, cloud, local, standard
  409. @router.get("/printer-models")
  410. def list_printer_models() -> dict[str, str]:
  411. """Canonical Bambu printer-model registry, surfaced for the SliceModal.
  412. Returns the backend's ``PRINTER_MODEL_MAP`` unmodified: keys are the long
  413. "Bambu Lab <model>" form that appears in 3MF metadata and in slicer
  414. printer-preset names, values are the normalized short codes used in
  415. BambuStudio's `@BBL <code>` cloud-preset filenames. The frontend uses this
  416. mapping to classify cloud / standard presets against the selected printer
  417. when no slicer bundle has been uploaded that covers the preset (#1325
  418. follow-up) - avoiding a second, manually-maintained model table on the
  419. frontend. No auth gate: this is a static reference dictionary, not
  420. user data.
  421. """
  422. return dict(PRINTER_MODEL_MAP)
  423. @router.get("/presets", response_model=UnifiedPresetsResponse)
  424. async def list_unified_presets(
  425. db: AsyncSession = Depends(get_db),
  426. current_user: User | None = RequirePermissionIfAuthEnabled(Permission.LIBRARY_UPLOAD),
  427. api_key_cloud_owner: User | None = Depends(resolve_api_key_cloud_owner),
  428. refresh: bool = Query(
  429. False,
  430. description=(
  431. "Bypass the in-process cloud and bundled-preset caches for this "
  432. "request. The SliceModal's Refresh button sets this so users who "
  433. "deleted a preset in Bambu Studio or Bambu Handy don't have to "
  434. "wait for the 5-minute cloud-cache TTL to expire."
  435. ),
  436. ),
  437. ) -> UnifiedPresetsResponse:
  438. """List slicer presets across cloud / local / standard tiers, deduped by name.
  439. Drives the SliceModal preset dropdowns. Permission gate matches the
  440. slice action itself (``LIBRARY_UPLOAD``) so any user who can slice can
  441. see the preset options for the dialog. The cloud branch is independently
  442. gated on ``CLOUD_AUTH`` inside ``_fetch_cloud_presets`` so a user with
  443. only ``LIBRARY_UPLOAD`` doesn't see cloud presets they shouldn't have
  444. access to.
  445. API-keyed callers (which return None from ``current_user``) get the
  446. owner User via ``resolve_api_key_cloud_owner`` when the key has the
  447. cloud-access scope, so the cloud tier surfaces correctly for them
  448. too — matching the slice route (#1182 follow-up).
  449. """
  450. cloud_token_user = current_user or api_key_cloud_owner
  451. orca_cloud, orca_cloud_status = await _fetch_orca_cloud_presets(db, cloud_token_user, refresh=refresh)
  452. cloud, cloud_status = await _fetch_cloud_presets(db, cloud_token_user, refresh=refresh)
  453. local = await _fetch_local_presets(db)
  454. standard = await _fetch_bundled_presets(db, refresh=refresh)
  455. orca_cloud, cloud, local, standard = _enrich_cloud_metadata(orca_cloud, cloud, local, standard)
  456. return UnifiedPresetsResponse(
  457. orca_cloud=UnifiedPresetsBySlot(**orca_cloud),
  458. cloud=UnifiedPresetsBySlot(**cloud),
  459. local=UnifiedPresetsBySlot(**local),
  460. standard=UnifiedPresetsBySlot(**standard),
  461. cloud_status=cloud_status,
  462. orca_cloud_status=orca_cloud_status,
  463. )
  464. @router.get("/preview-progress/{request_id}")
  465. async def get_preview_slice_progress(
  466. request_id: str,
  467. db: AsyncSession = Depends(get_db),
  468. _: tuple[User | None, bool] = Depends(
  469. require_ownership_permission(
  470. Permission.LIBRARY_READ_ALL,
  471. Permission.LIBRARY_READ_OWN,
  472. )
  473. ),
  474. ):
  475. """Proxy to the sidecar's ``GET /slice/progress/:requestId``.
  476. The SliceModal's filament-requirements call kicks off a real preview
  477. slice on the sidecar to discover which AMS slots the picked plate
  478. actually consumes. That HTTP call holds open for the full slice
  479. duration (multi-second to multi-minute on complex models), and the
  480. browser can't reach the sidecar directly thanks to the same-origin
  481. policy + the sidecar's CORS allowlist. This endpoint forwards the
  482. poll so the modal's inline spinner can show "Generating G-code (45%)"
  483. instead of an opaque elapsed-time counter while the preview runs.
  484. Returns the sidecar's snapshot verbatim, or 404 when the request_id
  485. is unknown / completed and grace-window-expired.
  486. """
  487. import httpx
  488. api_url = await _resolve_slicer_api_url(db)
  489. if not api_url:
  490. raise HTTPException(status_code=503, detail="No slicer sidecar configured")
  491. url = f"{api_url}/slice/progress/{request_id}"
  492. try:
  493. async with httpx.AsyncClient(timeout=5.0) as client:
  494. response = await client.get(url)
  495. except httpx.RequestError:
  496. # Sidecar unreachable: surface as 503 instead of 500 so the
  497. # frontend's poller can keep trying without flagging a hard error.
  498. raise HTTPException(status_code=503, detail="Slicer sidecar unreachable") from None
  499. if response.status_code == 404:
  500. raise HTTPException(status_code=404, detail="Progress unavailable")
  501. return response.json()