slicer_presets.py 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726
  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, File, HTTPException, Query, UploadFile
  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
  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. BundleNotFoundError,
  46. BundleSummary,
  47. SlicerApiError,
  48. SlicerApiService,
  49. SlicerApiUnavailableError,
  50. SlicerInputError,
  51. )
  52. from backend.app.utils.printer_models import PRINTER_MODEL_MAP
  53. logger = logging.getLogger(__name__)
  54. router = APIRouter(prefix="/slicer", tags=["Slicer Presets"])
  55. # In-process cache for the bundled-profile list. The slicer sidecar walks a
  56. # read-only filesystem inside its own container, so the list only changes
  57. # across sidecar rebuilds — a long TTL is safe and avoids a sidecar round-trip
  58. # on every modal open. Per-user cache is unnecessary because bundled profiles
  59. # are global.
  60. _BUNDLED_TTL_S = 3600.0
  61. _bundled_cache: tuple[float, dict[str, list[UnifiedPreset]]] | None = None
  62. # Per-user cache for the cloud preset list. Cache key is (user_id, token_hash):
  63. # keying on the token hash means a logout/login or token-change automatically
  64. # invalidates the entry without needing the cloud-auth route handlers to call
  65. # back into this module. 5 minutes balances "users see their freshly-saved
  66. # presets quickly" against "a busy install doesn't hit the cloud once per
  67. # modal open per user".
  68. _CLOUD_TTL_S = 300.0
  69. _cloud_cache: dict[tuple[int, str], tuple[float, dict[str, list[UnifiedPreset]]]] = {}
  70. # Same shape for Orca Cloud — keyed on (user_id, access_token-fingerprint).
  71. _orca_cloud_cache: dict[tuple[int, str], tuple[float, dict[str, list[UnifiedPreset]]]] = {}
  72. def _token_fingerprint(token: str) -> str:
  73. """Short stable hash of the cloud token for use as a cache-key component.
  74. Storing only the hash means we can safely keep multiple per-(user, token)
  75. entries without leaking the token via the in-process dict."""
  76. return hashlib.sha256(token.encode("utf-8")).hexdigest()[:16]
  77. _CLOUD_TYPE_TO_SLOT = {
  78. "filament": "filament",
  79. "printer": "printer",
  80. "print": "process", # Bambu Cloud calls process presets "print"
  81. }
  82. def _empty_slots() -> dict[str, list[UnifiedPreset]]:
  83. return {"printer": [], "process": [], "filament": []}
  84. async def _fetch_cloud_presets(
  85. db: AsyncSession, user: User | None, *, refresh: bool = False
  86. ) -> tuple[dict[str, list[UnifiedPreset]], str]:
  87. """Return (slots, cloud_status). Slots are empty when cloud_status != 'ok'.
  88. Defence-in-depth: even if a stored cloud_token survived a permission
  89. revocation (admin reset, legacy state), users without ``CLOUD_AUTH`` are
  90. treated as not-authenticated for this endpoint — the cloud tier never
  91. surfaces for them. This keeps the per-tier visibility consistent with the
  92. /cloud/* endpoint suite that already gates on CLOUD_AUTH.
  93. ``refresh=True`` skips the in-process cache for this call (used by the
  94. SliceModal's manual Refresh button so a user who just deleted a preset
  95. in Bambu Studio / Handy can pick up the change without waiting for the
  96. 5-minute TTL to expire). The fresh result is still written back to the
  97. cache so subsequent non-refresh callers benefit.
  98. """
  99. if user is not None and not user.has_permission(Permission.CLOUD_AUTH.value):
  100. return _empty_slots(), "not_authenticated"
  101. token, _email, region = await get_stored_token(db, user)
  102. if not token:
  103. return _empty_slots(), "not_authenticated"
  104. user_key = user.id if user is not None else 0
  105. cache_key = (user_key, _token_fingerprint(token))
  106. now = time.monotonic()
  107. if not refresh:
  108. cached = _cloud_cache.get(cache_key)
  109. if cached and now - cached[0] < _CLOUD_TTL_S:
  110. return cached[1], "ok"
  111. cloud = BambuCloudService(region=region)
  112. cloud.set_token(token)
  113. try:
  114. try:
  115. raw = await cloud.get_slicer_settings()
  116. except BambuCloudAuthError:
  117. # Don't clear the token here — the cloud-status endpoint owns that
  118. # lifecycle. Just report expired so the UI can prompt re-auth.
  119. return _empty_slots(), "expired"
  120. except BambuCloudError as e:
  121. logger.warning("Cloud preset fetch failed for user %s: %s", user_key, e)
  122. return _empty_slots(), "unreachable"
  123. except Exception as e: # noqa: BLE001 — defensive: never crash the modal
  124. logger.warning("Cloud preset fetch unexpected error for user %s: %s", user_key, e)
  125. return _empty_slots(), "unreachable"
  126. slots = _empty_slots()
  127. for cloud_type, slot in _CLOUD_TYPE_TO_SLOT.items():
  128. type_data = raw.get(cloud_type, {})
  129. # The cloud splits presets into "private" (the user's own) and "public"
  130. # (Bambu's stock cloud presets). Both are valid choices — surface them
  131. # in the natural order private → public so a user's customisations
  132. # appear above the stock entries with the same names. Stock entries
  133. # that share names with private ones get deduped out within the cloud
  134. # tier itself.
  135. seen_names: set[str] = set()
  136. for entry in type_data.get("private", []) + type_data.get("public", []):
  137. name = entry.get("name")
  138. setting_id = entry.get("setting_id") or entry.get("id")
  139. if not name or not setting_id or name in seen_names:
  140. continue
  141. seen_names.add(name)
  142. slots[slot].append(UnifiedPreset(id=setting_id, name=name, source="cloud"))
  143. # Cloud filament presets carry no metadata in this response on
  144. # purpose: the per-preset detail endpoint
  145. # (/v1/iot-service/api/slicer/setting/{id}) is rate-limited at roughly
  146. # 10/sec per token, so fetching N filament presets to enrich them
  147. # one-by-one trips Bambu's limiter and returns 429 on every request
  148. # for users with large preset libraries (#1150 follow-up).
  149. #
  150. # The metadata-enrich pass (see _enrich_cloud_metadata) compensates:
  151. # a Bambu Cloud entry without its own filament_type/colour inherits
  152. # those values from a same-named local / orca_cloud / standard entry
  153. # so it can still score for type/colour matches in pickFilamentForSlot.
  154. _cloud_cache[cache_key] = (now, slots)
  155. return slots, "ok"
  156. finally:
  157. await cloud.close()
  158. async def _fetch_orca_cloud_presets(
  159. db: AsyncSession, user: User | None, *, refresh: bool = False
  160. ) -> tuple[dict[str, list[UnifiedPreset]], str]:
  161. """Mirror of :func:`_fetch_cloud_presets` but for Orca Cloud. Same status
  162. vocabulary (``ok`` / ``not_authenticated`` / ``expired`` / ``unreachable``),
  163. same caching shape, same defence-in-depth permission gate
  164. (``orca_cloud:auth`` rather than ``cloud:auth``).
  165. Filament metadata (``filament_type`` / ``filament_colour``) is extracted
  166. from the profile's inline ``content`` dict — unlike Bambu Cloud where
  167. we'd have to fetch each setting separately and hit a rate limit, Orca's
  168. ``/sync/pull`` already returns full content per profile, so the metadata
  169. enrichment is free here.
  170. """
  171. if user is not None and not user.has_permission(Permission.ORCA_CLOUD_AUTH.value):
  172. return _empty_slots(), "not_authenticated"
  173. creds = await _load_orca_credentials(db, user)
  174. if not creds.token:
  175. return _empty_slots(), "not_authenticated"
  176. user_key = user.id if user is not None else 0
  177. cache_key = (user_key, _token_fingerprint(creds.token))
  178. now = time.monotonic()
  179. if not refresh:
  180. cached = _orca_cloud_cache.get(cache_key)
  181. if cached and now - cached[0] < _CLOUD_TTL_S:
  182. return cached[1], "ok"
  183. try:
  184. svc = await _build_orca_service(db, user)
  185. except HTTPException as e:
  186. # ``_build_orca_service`` raises 401 when the token is missing,
  187. # the refresh-token rotation failed, or the JIT refresh hit Orca's
  188. # backend and got rejected; 502 when Orca is unreachable. Translate
  189. # to the status vocabulary the SliceModal expects.
  190. if e.status_code == 401:
  191. return _empty_slots(), "expired"
  192. return _empty_slots(), "unreachable"
  193. try:
  194. try:
  195. raw_profiles = await svc.list_profiles()
  196. except OrcaCloudAuthError:
  197. return _empty_slots(), "expired"
  198. except OrcaCloudError as e:
  199. logger.warning("Orca Cloud preset fetch failed for user %s: %s", user_key, e)
  200. return _empty_slots(), "unreachable"
  201. except Exception as e: # noqa: BLE001 — defensive: never crash the modal
  202. logger.warning("Orca Cloud preset fetch unexpected error for user %s: %s", user_key, e)
  203. return _empty_slots(), "unreachable"
  204. slots = _empty_slots()
  205. for entry in raw_profiles:
  206. content = entry.get("content") if isinstance(entry, dict) else None
  207. if not isinstance(content, dict):
  208. continue
  209. slot = _ORCA_TYPE_TO_BAMBU.get(str(content.get("type", "")))
  210. if slot is None:
  211. continue
  212. preset_id = entry.get("id")
  213. name = entry.get("name") or preset_id
  214. if not preset_id or not name:
  215. continue
  216. filament_type: str | None = None
  217. filament_colour: str | None = None
  218. if slot == "filament":
  219. # Bambu/Orca filament profiles store these as single-element
  220. # arrays (the historical multi-extruder shape). Extract the
  221. # first non-empty element for both.
  222. ft = content.get("filament_type")
  223. if isinstance(ft, list) and ft and isinstance(ft[0], str):
  224. filament_type = ft[0]
  225. elif isinstance(ft, str):
  226. filament_type = ft
  227. fc = content.get("default_filament_colour")
  228. if isinstance(fc, list) and fc and isinstance(fc[0], str):
  229. filament_colour = fc[0]
  230. elif isinstance(fc, str):
  231. filament_colour = fc
  232. slots[slot].append(
  233. UnifiedPreset(
  234. id=str(preset_id),
  235. name=str(name),
  236. source="orca_cloud",
  237. filament_type=filament_type,
  238. filament_colour=filament_colour,
  239. )
  240. )
  241. _orca_cloud_cache[cache_key] = (now, slots)
  242. return slots, "ok"
  243. finally:
  244. await svc.close()
  245. async def _fetch_local_presets(db: AsyncSession) -> dict[str, list[UnifiedPreset]]:
  246. """Local imports — no caching needed, single indexed DB read."""
  247. result = await db.execute(select(LocalPreset).order_by(LocalPreset.name))
  248. presets = result.scalars().all()
  249. slots = _empty_slots()
  250. type_to_slot = {"filament": "filament", "printer": "printer", "process": "process"}
  251. for p in presets:
  252. slot = type_to_slot.get(p.preset_type)
  253. if slot is None:
  254. continue
  255. preset = UnifiedPreset(id=str(p.id), name=p.name, source="local")
  256. if slot == "filament":
  257. preset.filament_type, preset.filament_colour = _parse_filament_metadata(p.setting)
  258. if slot in ("process", "filament"):
  259. # Precise compatibility link — the slicer's own compatible_printers
  260. # list, captured at import time. Lets the SliceModal filter the
  261. # process / filament dropdowns by the selected printer without
  262. # falling back to the uploaded-bundle index.
  263. preset.compatible_printers = _parse_compatible_printers(p.compatible_printers)
  264. slots[slot].append(preset)
  265. return slots
  266. def _parse_compatible_printers(raw: str | None) -> list[str] | None:
  267. """``LocalPreset.compatible_printers`` stores a JSON array of printer-preset
  268. names. Return the parsed list, or ``None`` on missing / malformed data so
  269. the SliceModal falls back to the uploaded-bundle index for that preset."""
  270. if not raw:
  271. return None
  272. try:
  273. data = json.loads(raw)
  274. except (ValueError, TypeError):
  275. return None
  276. if not isinstance(data, list):
  277. return None
  278. names = [s for s in data if isinstance(s, str) and s.strip()]
  279. return names or None
  280. def _parse_filament_metadata(setting_json: str | None) -> tuple[str | None, str | None]:
  281. """Extract first-slot ``filament_type`` and ``filament_colour`` from a
  282. stored preset JSON. OrcaSlicer stores both as arrays (per-extruder) — we
  283. take the first entry since pre-pick matching is one-slot-at-a-time.
  284. Defensive parse: any error returns (None, None) so a corrupt row never
  285. breaks the listing."""
  286. if not setting_json:
  287. return None, None
  288. try:
  289. data = json.loads(setting_json)
  290. except (ValueError, TypeError):
  291. return None, None
  292. if not isinstance(data, dict):
  293. return None, None
  294. return _first_scalar(data.get("filament_type")), _first_scalar(data.get("filament_colour"))
  295. def _first_scalar(value: object) -> str | None:
  296. if isinstance(value, list) and value:
  297. return value[0] if isinstance(value[0], str) else None
  298. if isinstance(value, str) and value:
  299. return value
  300. return None
  301. async def _fetch_bundled_presets(db: AsyncSession, *, refresh: bool = False) -> dict[str, list[UnifiedPreset]]:
  302. """Standard slicer-bundled profiles via the sidecar's /profiles/bundled.
  303. ``refresh=True`` skips the in-process cache; see _fetch_cloud_presets for
  304. the same shape and rationale.
  305. """
  306. global _bundled_cache
  307. now = time.monotonic()
  308. if not refresh and _bundled_cache and now - _bundled_cache[0] < _BUNDLED_TTL_S:
  309. return _bundled_cache[1]
  310. api_url = await _resolve_slicer_api_url(db)
  311. if not api_url:
  312. # No sidecar configured at all — return empty rather than caching, so
  313. # users who configure one mid-session see results on next open.
  314. return _empty_slots()
  315. try:
  316. async with SlicerApiService(base_url=api_url) as svc:
  317. raw = await svc.list_bundled_profiles()
  318. except SlicerApiError as e:
  319. logger.info("Bundled preset fetch from sidecar at %s failed: %s", api_url, e)
  320. return _empty_slots()
  321. except Exception as e: # noqa: BLE001 — never break the modal on sidecar issues
  322. logger.warning("Bundled preset fetch unexpected error: %s", e)
  323. return _empty_slots()
  324. slots = _empty_slots()
  325. for slot in ("printer", "process", "filament"):
  326. for entry in raw.get(slot, []) or []:
  327. name = entry.get("name")
  328. if not name:
  329. continue
  330. # Bundled presets are addressed by name (the slicer resolves them
  331. # by name during the `inherits:` walk), so name doubles as id.
  332. extra: dict[str, str | None] = {}
  333. if slot == "filament":
  334. extra["filament_type"] = entry.get("filament_type")
  335. extra["filament_colour"] = entry.get("filament_colour")
  336. slots[slot].append(
  337. UnifiedPreset(id=name, name=name, source="standard", **extra),
  338. )
  339. _bundled_cache = (now, slots)
  340. return slots
  341. async def _resolve_slicer_api_url(db: AsyncSession) -> str | None:
  342. """Pick the sidecar URL the bundled-listing fetch should hit.
  343. Mirrors the slice route's resolution at ``library.py:_run_slicer_with_fallback``:
  344. the user's ``preferred_slicer`` setting decides which sidecar Bambuddy
  345. talks to, and the per-install URL setting overrides the env default.
  346. A user who prefers Bambu Studio gets the *bambu-studio-api* sidecar's
  347. bundled list; a user who prefers OrcaSlicer gets the *orca-slicer-api*
  348. sidecar's bundled list. Without this branch the listing would always
  349. hit OrcaSlicer (port 3003) even for BambuStudio installs (port 3001),
  350. leaving the Standard tier permanently empty for them.
  351. """
  352. from backend.app.api.routes.settings import get_setting
  353. preferred = (await get_setting(db, "preferred_slicer")) or "bambu_studio"
  354. if preferred == "orcaslicer":
  355. configured = await get_setting(db, "orcaslicer_api_url")
  356. url = (configured or app_settings.slicer_api_url).strip()
  357. elif preferred == "bambu_studio":
  358. configured = await get_setting(db, "bambu_studio_api_url")
  359. url = (configured or app_settings.bambu_studio_api_url).strip()
  360. else:
  361. # Unknown preference — return None so the bundled tier is empty
  362. # rather than crashing the modal. The slice route raises 400 here;
  363. # we degrade silently because the modal's listing is informational.
  364. logger.warning("Unknown preferred_slicer setting: %r — bundled tier disabled", preferred)
  365. return None
  366. return url or None
  367. def _enrich_cloud_metadata(
  368. orca_cloud: dict[str, list[UnifiedPreset]],
  369. cloud: dict[str, list[UnifiedPreset]],
  370. local: dict[str, list[UnifiedPreset]],
  371. standard: dict[str, list[UnifiedPreset]],
  372. ) -> tuple[
  373. dict[str, list[UnifiedPreset]],
  374. dict[str, list[UnifiedPreset]],
  375. dict[str, list[UnifiedPreset]],
  376. dict[str, list[UnifiedPreset]],
  377. ]:
  378. """Backfill Bambu Cloud filament metadata; do NOT dedup tiers.
  379. Every tier surfaces its full list — a name that exists in both ``local``
  380. and ``orca_cloud`` shows up in BOTH dropdown groups so the user can pick
  381. either source. Tier ORDER (``local > orca_cloud > cloud > standard``)
  382. is communicated by the SliceModal's group rendering and by the
  383. name-collision fallback in ``findPresetByName``; this function does not
  384. enforce it.
  385. Filament metadata merge: a Bambu Cloud entry without its own
  386. ``filament_type`` / ``filament_colour`` (Bambu Cloud doesn't surface
  387. these in the list response for rate-limiting reasons — see
  388. :func:`_fetch_cloud_presets`) inherits values from a same-named entry
  389. in ``local`` / ``orca_cloud`` / ``standard``. This is the only reason
  390. this function exists post-#1712 — without the enrich the Bambu Cloud
  391. tier can't score in ``pickFilamentForSlot``.
  392. """
  393. # Build a name → metadata lookup from the tiers that carry it (local,
  394. # orca_cloud, standard). Bambu cloud is intentionally skipped — it
  395. # doesn't populate filament_type/colour in the list response. Take
  396. # whichever non-empty entry shows up first.
  397. metadata_by_name: dict[str, tuple[str | None, str | None]] = {}
  398. for tier in (local, orca_cloud, standard):
  399. for p in tier["filament"]:
  400. if p.name in metadata_by_name:
  401. continue
  402. if p.filament_type or p.filament_colour:
  403. metadata_by_name[p.name] = (p.filament_type, p.filament_colour)
  404. # Backfill Bambu Cloud entries that don't have their own metadata.
  405. for p in cloud["filament"]:
  406. if (p.filament_type is None or p.filament_colour is None) and p.name in metadata_by_name:
  407. t, c = metadata_by_name[p.name]
  408. if p.filament_type is None and t is not None:
  409. p.filament_type = t
  410. if p.filament_colour is None and c is not None:
  411. p.filament_colour = c
  412. return orca_cloud, cloud, local, standard
  413. @router.get("/printer-models")
  414. def list_printer_models() -> dict[str, str]:
  415. """Canonical Bambu printer-model registry, surfaced for the SliceModal.
  416. Returns the backend's ``PRINTER_MODEL_MAP`` unmodified: keys are the long
  417. "Bambu Lab <model>" form that appears in 3MF metadata and in slicer
  418. printer-preset names, values are the normalized short codes used in
  419. BambuStudio's `@BBL <code>` cloud-preset filenames. The frontend uses this
  420. mapping to classify cloud / standard presets against the selected printer
  421. when no slicer bundle has been uploaded that covers the preset (#1325
  422. follow-up) - avoiding a second, manually-maintained model table on the
  423. frontend. No auth gate: this is a static reference dictionary, not
  424. user data.
  425. """
  426. return dict(PRINTER_MODEL_MAP)
  427. @router.get("/presets", response_model=UnifiedPresetsResponse)
  428. async def list_unified_presets(
  429. db: AsyncSession = Depends(get_db),
  430. current_user: User | None = RequirePermissionIfAuthEnabled(Permission.LIBRARY_UPLOAD),
  431. api_key_cloud_owner: User | None = Depends(resolve_api_key_cloud_owner),
  432. refresh: bool = Query(
  433. False,
  434. description=(
  435. "Bypass the in-process cloud and bundled-preset caches for this "
  436. "request. The SliceModal's Refresh button sets this so users who "
  437. "deleted a preset in Bambu Studio or Bambu Handy don't have to "
  438. "wait for the 5-minute cloud-cache TTL to expire."
  439. ),
  440. ),
  441. ) -> UnifiedPresetsResponse:
  442. """List slicer presets across cloud / local / standard tiers, deduped by name.
  443. Drives the SliceModal preset dropdowns. Permission gate matches the
  444. slice action itself (``LIBRARY_UPLOAD``) so any user who can slice can
  445. see the preset options for the dialog. The cloud branch is independently
  446. gated on ``CLOUD_AUTH`` inside ``_fetch_cloud_presets`` so a user with
  447. only ``LIBRARY_UPLOAD`` doesn't see cloud presets they shouldn't have
  448. access to.
  449. API-keyed callers (which return None from ``current_user``) get the
  450. owner User via ``resolve_api_key_cloud_owner`` when the key has the
  451. cloud-access scope, so the cloud tier surfaces correctly for them
  452. too — matching the slice route (#1182 follow-up).
  453. """
  454. cloud_token_user = current_user or api_key_cloud_owner
  455. orca_cloud, orca_cloud_status = await _fetch_orca_cloud_presets(db, cloud_token_user, refresh=refresh)
  456. cloud, cloud_status = await _fetch_cloud_presets(db, cloud_token_user, refresh=refresh)
  457. local = await _fetch_local_presets(db)
  458. standard = await _fetch_bundled_presets(db, refresh=refresh)
  459. orca_cloud, cloud, local, standard = _enrich_cloud_metadata(orca_cloud, cloud, local, standard)
  460. return UnifiedPresetsResponse(
  461. orca_cloud=UnifiedPresetsBySlot(**orca_cloud),
  462. cloud=UnifiedPresetsBySlot(**cloud),
  463. local=UnifiedPresetsBySlot(**local),
  464. standard=UnifiedPresetsBySlot(**standard),
  465. cloud_status=cloud_status,
  466. orca_cloud_status=orca_cloud_status,
  467. )
  468. def _bundle_summary_to_dict(b: BundleSummary) -> dict:
  469. """Serialize a BundleSummary for the JSON response. The frontend uses
  470. these arrays to populate the preset dropdowns when a user picks the
  471. bundle as the slice source.
  472. """
  473. return {
  474. "id": b.id,
  475. "printer_preset_name": b.printer_preset_name,
  476. "printer": b.printer,
  477. "process": b.process,
  478. "filament": b.filament,
  479. "version": b.version,
  480. }
  481. @router.post("/bundles", status_code=201)
  482. async def import_slicer_bundle(
  483. file: UploadFile = File(...),
  484. db: AsyncSession = Depends(get_db),
  485. _: User | None = RequirePermissionIfAuthEnabled(Permission.LIBRARY_UPLOAD),
  486. ):
  487. """Forward a BambuStudio Printer Preset Bundle (.bbscfg) to the sidecar.
  488. The user exports their printer's preset bundle from BambuStudio (File
  489. -> Export -> Export Preset Bundle, "Printer preset bundle" option).
  490. Uploading it here unpacks the bundle on the sidecar and exposes its
  491. inner printer / process / filament presets to subsequent slice
  492. requests via the bundle-id selector.
  493. Idempotent: re-uploading the same file yields the same id (sidecar
  494. hashes the zip content), so duplicate uploads collapse rather than
  495. accumulate.
  496. """
  497. api_url = await _resolve_slicer_api_url(db)
  498. if not api_url:
  499. raise HTTPException(status_code=503, detail="No slicer sidecar configured")
  500. # Multer on the sidecar caps bundle uploads at 50MB. We don't enforce
  501. # that here — let the sidecar's filter own the limit so it stays in
  502. # one place — but we do reject empty / huge files at the FastAPI
  503. # layer to avoid pointlessly streaming them to the sidecar first.
  504. contents = await file.read()
  505. if not contents:
  506. raise HTTPException(status_code=400, detail="Bundle file is empty")
  507. filename = file.filename or "bundle.bbscfg"
  508. try:
  509. async with SlicerApiService(base_url=api_url) as svc:
  510. summary = await svc.import_bundle(contents, filename=filename)
  511. except SlicerInputError as e:
  512. # Sidecar's 4xx — most likely a non-.bbscfg upload, a corrupt zip,
  513. # or a path-traversal entry that the manifest validator caught.
  514. # Log the detail so it lands in the support bundle: the FE-only
  515. # toast was leaving us blind during triage (#1312).
  516. logger.warning(
  517. "Bundle import rejected by sidecar (%s, %d bytes): %s",
  518. filename,
  519. len(contents),
  520. e,
  521. )
  522. raise HTTPException(status_code=400, detail=str(e)) from e
  523. except SlicerApiUnavailableError as e:
  524. logger.warning("Bundle import: sidecar unreachable (%s): %s", api_url, e)
  525. raise HTTPException(status_code=503, detail=str(e)) from e
  526. except SlicerApiError as e:
  527. logger.warning(
  528. "Bundle import: sidecar server error (%s, %d bytes): %s",
  529. filename,
  530. len(contents),
  531. e,
  532. )
  533. # 5xx from the sidecar's import path is rare — usually a disk
  534. # write failure inside DATA_PATH/bundles. 502 (bad gateway) is
  535. # closer to the truth than 500 here, since we're proxying.
  536. raise HTTPException(status_code=502, detail=str(e)) from e
  537. return _bundle_summary_to_dict(summary)
  538. @router.get("/bundles")
  539. async def list_slicer_bundles(
  540. db: AsyncSession = Depends(get_db),
  541. _: User | None = RequirePermissionIfAuthEnabled(Permission.LIBRARY_UPLOAD),
  542. ):
  543. """List every Printer Preset Bundle currently stored on the sidecar.
  544. Drives the SliceModal's "Bundle" tier and a Settings panel where
  545. users can review / delete imported bundles. Returns ``[]`` when the
  546. sidecar has no bundles imported yet.
  547. """
  548. api_url = await _resolve_slicer_api_url(db)
  549. if not api_url:
  550. # No sidecar configured: empty list rather than 503 so the modal
  551. # renders cleanly. Same shape as the bundled-presets fallback.
  552. return []
  553. try:
  554. async with SlicerApiService(base_url=api_url) as svc:
  555. bundles = await svc.list_bundles()
  556. except SlicerApiUnavailableError as e:
  557. # Sidecar offline: surface as 503 so the frontend can show a
  558. # banner. Differs from the bundled-tier behaviour because that
  559. # path also has cloud + local fallbacks; bundles is the only
  560. # source for its tier.
  561. raise HTTPException(status_code=503, detail=str(e)) from e
  562. except SlicerApiError as e:
  563. raise HTTPException(status_code=502, detail=str(e)) from e
  564. return [_bundle_summary_to_dict(b) for b in bundles]
  565. @router.get("/bundles/{bundle_id}")
  566. async def get_slicer_bundle(
  567. bundle_id: str,
  568. db: AsyncSession = Depends(get_db),
  569. _: User | None = RequirePermissionIfAuthEnabled(Permission.LIBRARY_UPLOAD),
  570. ):
  571. """Return one bundle by id. 404 if it doesn't exist on the sidecar."""
  572. api_url = await _resolve_slicer_api_url(db)
  573. if not api_url:
  574. raise HTTPException(status_code=503, detail="No slicer sidecar configured")
  575. try:
  576. async with SlicerApiService(base_url=api_url) as svc:
  577. summary = await svc.get_bundle(bundle_id)
  578. except BundleNotFoundError as e:
  579. raise HTTPException(status_code=404, detail=str(e)) from e
  580. except SlicerApiUnavailableError as e:
  581. raise HTTPException(status_code=503, detail=str(e)) from e
  582. except SlicerApiError as e:
  583. raise HTTPException(status_code=502, detail=str(e)) from e
  584. return _bundle_summary_to_dict(summary)
  585. @router.delete("/bundles/{bundle_id}", status_code=204)
  586. async def delete_slicer_bundle(
  587. bundle_id: str,
  588. db: AsyncSession = Depends(get_db),
  589. _: User | None = RequirePermissionIfAuthEnabled(Permission.LIBRARY_UPLOAD),
  590. ):
  591. """Remove a stored bundle from the sidecar. Future slice requests
  592. referencing this id will fail with 404 from the sidecar.
  593. """
  594. api_url = await _resolve_slicer_api_url(db)
  595. if not api_url:
  596. raise HTTPException(status_code=503, detail="No slicer sidecar configured")
  597. try:
  598. async with SlicerApiService(base_url=api_url) as svc:
  599. await svc.delete_bundle(bundle_id)
  600. except BundleNotFoundError as e:
  601. raise HTTPException(status_code=404, detail=str(e)) from e
  602. except SlicerApiUnavailableError as e:
  603. raise HTTPException(status_code=503, detail=str(e)) from e
  604. except SlicerApiError as e:
  605. raise HTTPException(status_code=502, detail=str(e)) from e
  606. @router.get("/preview-progress/{request_id}")
  607. async def get_preview_slice_progress(
  608. request_id: str,
  609. db: AsyncSession = Depends(get_db),
  610. _: User | None = RequirePermissionIfAuthEnabled(Permission.LIBRARY_READ),
  611. ):
  612. """Proxy to the sidecar's ``GET /slice/progress/:requestId``.
  613. The SliceModal's filament-requirements call kicks off a real preview
  614. slice on the sidecar to discover which AMS slots the picked plate
  615. actually consumes. That HTTP call holds open for the full slice
  616. duration (multi-second to multi-minute on complex models), and the
  617. browser can't reach the sidecar directly thanks to the same-origin
  618. policy + the sidecar's CORS allowlist. This endpoint forwards the
  619. poll so the modal's inline spinner can show "Generating G-code (45%)"
  620. instead of an opaque elapsed-time counter while the preview runs.
  621. Returns the sidecar's snapshot verbatim, or 404 when the request_id
  622. is unknown / completed and grace-window-expired.
  623. """
  624. import httpx
  625. api_url = await _resolve_slicer_api_url(db)
  626. if not api_url:
  627. raise HTTPException(status_code=503, detail="No slicer sidecar configured")
  628. url = f"{api_url}/slice/progress/{request_id}"
  629. try:
  630. async with httpx.AsyncClient(timeout=5.0) as client:
  631. response = await client.get(url)
  632. except httpx.RequestError:
  633. # Sidecar unreachable: surface as 503 instead of 500 so the
  634. # frontend's poller can keep trying without flagging a hard error.
  635. raise HTTPException(status_code=503, detail="Slicer sidecar unreachable") from None
  636. if response.status_code == 404:
  637. raise HTTPException(status_code=404, detail="Progress unavailable")
  638. return response.json()