preset_resolver.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250
  1. """Resolve a `PresetRef` (source + id) to the JSON-string content the
  2. slicer-api sidecar's `/slice` endpoint expects.
  3. Three sources, three paths:
  4. - **local** — read ``LocalPreset.setting`` from the DB. Existing pre-PR
  5. behaviour for the slicer integration; preserved verbatim
  6. so clients still sending bare integer ids see no change.
  7. - **cloud** — fetch ``BambuCloudService.get_setting_detail(id)`` for the
  8. caller's stored cloud token. Result is the full slicer-shape
  9. preset JSON the sidecar can ingest directly.
  10. - **standard** — emit a stub ``{inherits: <name>, from: "system"}``. The
  11. sidecar's `bambuddy/profile-resolver` branch already walks
  12. ``inherits:`` against ``BUNDLED_PROFILES_PATH/<category>/<name>.json``
  13. during ``materializeProfile`` and merges parent-then-child,
  14. so the stub flattens out to the bundled content with no
  15. round-trip needed for the JSON itself.
  16. All three return the JSON as a *string* because that's what
  17. ``SlicerApiService.slice_with_profiles`` accepts as
  18. ``printer_profile_json`` etc. — the sidecar parses it once.
  19. """
  20. from __future__ import annotations
  21. import json
  22. import logging
  23. from fastapi import HTTPException
  24. from sqlalchemy.ext.asyncio import AsyncSession
  25. from backend.app.api.routes.cloud import get_stored_token
  26. from backend.app.api.routes.orca_cloud import _build_authenticated_service as _build_orca_service
  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 import PresetRef
  31. from backend.app.services.bambu_cloud import (
  32. BambuCloudAuthError,
  33. BambuCloudError,
  34. BambuCloudService,
  35. )
  36. from backend.app.services.orca_cloud import OrcaCloudAuthError, OrcaCloudError
  37. logger = logging.getLogger(__name__)
  38. _SLOT_TO_BUNDLED_CATEGORY = {
  39. "printer": "machine",
  40. "process": "process",
  41. "filament": "filament",
  42. }
  43. # The CLI's --load-settings parser uses the JSON's `type` field to decide
  44. # how to interpret each file (machine/process/filament). Without it the
  45. # CLI logs `operator(): unknown config type ... in load-settings`,
  46. # writes `error_string: "The input preset file is invalid and can not be
  47. # parsed.", return_code: -5` to result.json, and exits 0 — which the
  48. # Node sidecar's child_process treats as silent success producing no
  49. # output, then bubbles up as a generic "Failed to slice the model" 5xx.
  50. # Bambuddy then falls back to the embedded-settings path for every 3MF
  51. # slice, silently using whatever printer the source file was originally
  52. # bound to. Setting `type` correctly per slot fixes the silent fallback.
  53. _SLOT_TO_PROFILE_TYPE = {
  54. "printer": "machine",
  55. "process": "process",
  56. "filament": "filament",
  57. }
  58. async def resolve_preset_ref(
  59. db: AsyncSession,
  60. user: User | None,
  61. ref: PresetRef,
  62. slot: str,
  63. ) -> str:
  64. """Return the JSON-string content for `ref` so the sidecar can ingest it.
  65. `slot` is one of ``"printer"`` / ``"process"`` / ``"filament"``; it's
  66. only used to generate friendly error messages and to pick the bundled
  67. category for the standard tier.
  68. Raises ``HTTPException`` for any caller-facing error (invalid id, wrong
  69. preset type, cloud auth failure, network error fetching cloud detail).
  70. """
  71. if ref.source == "local":
  72. return await _resolve_local(db, ref, slot)
  73. if ref.source == "cloud":
  74. return await _resolve_cloud(db, user, ref, slot)
  75. if ref.source == "orca_cloud":
  76. return await _resolve_orca_cloud(db, user, ref, slot)
  77. if ref.source == "standard":
  78. return _resolve_standard(ref, slot)
  79. raise HTTPException(
  80. status_code=400,
  81. detail=f"Unknown preset source for {slot}: {ref.source!r}",
  82. )
  83. async def _resolve_local(db: AsyncSession, ref: PresetRef, slot: str) -> str:
  84. try:
  85. local_id = int(ref.id)
  86. except (ValueError, TypeError):
  87. raise HTTPException(status_code=400, detail=f"Invalid local preset id for {slot}: {ref.id!r}") from None
  88. preset = await db.get(LocalPreset, local_id)
  89. if preset is None or preset.preset_type != slot:
  90. raise HTTPException(
  91. status_code=400,
  92. detail=f"Invalid {slot} preset id (expected preset_type='{slot}')",
  93. )
  94. return preset.setting
  95. async def _resolve_cloud(db: AsyncSession, user: User | None, ref: PresetRef, slot: str) -> str:
  96. """Fetch a single cloud preset detail. Permission gate matches the
  97. rest of the cloud surface (`CLOUD_AUTH`) so a user with `LIBRARY_UPLOAD`
  98. but no `CLOUD_AUTH` can't slice using cloud presets even if their
  99. ``User.cloud_token`` survived a permission revocation."""
  100. if user is not None and not user.has_permission(Permission.CLOUD_AUTH.value):
  101. raise HTTPException(
  102. status_code=403,
  103. detail=f"Cloud presets require the cloud:auth permission ({slot})",
  104. )
  105. token, _email, region = await get_stored_token(db, user)
  106. if not token:
  107. raise HTTPException(
  108. status_code=400,
  109. detail=(
  110. f"Cloud preset selected for {slot}, but no Bambu Cloud session is "
  111. "stored. Sign in to Bambu Cloud and retry."
  112. ),
  113. )
  114. cloud = BambuCloudService(region=region)
  115. cloud.set_token(token)
  116. try:
  117. detail = await cloud.get_setting_detail(ref.id)
  118. except BambuCloudAuthError:
  119. raise HTTPException(
  120. status_code=401,
  121. detail=(f"Bambu Cloud session expired while fetching {slot} preset. Sign in again and retry."),
  122. ) from None
  123. except BambuCloudError as e:
  124. raise HTTPException(
  125. status_code=502,
  126. detail=f"Bambu Cloud unreachable while fetching {slot} preset: {e}",
  127. ) from e
  128. finally:
  129. await cloud.close()
  130. # `get_setting_detail` returns the wrapper envelope; the actual preset
  131. # JSON lives under `.setting`. The sidecar wants the preset content, not
  132. # the envelope.
  133. payload = detail.get("setting") if isinstance(detail, dict) else None
  134. if not isinstance(payload, dict):
  135. # Some endpoints return the preset at the top level instead of
  136. # nested under `setting`. Fall back to the whole response in that
  137. # case rather than failing — the sidecar will reject it cleanly if
  138. # the shape is genuinely wrong, and we log the unusual response.
  139. logger.info(
  140. "Cloud preset %r for %s returned unexpected shape, forwarding raw payload",
  141. ref.id,
  142. slot,
  143. )
  144. payload = detail
  145. return json.dumps(payload)
  146. async def _resolve_orca_cloud(db: AsyncSession, user: User | None, ref: PresetRef, slot: str) -> str:
  147. """Fetch a single profile from Orca Cloud and return its content JSON.
  148. The route-layer service builder handles JIT token refresh and stale-credential
  149. cleanup, so any exception here means a genuine fetch / network / not-found
  150. problem — never a "stale token" situation the caller could retry through.
  151. Permission gate matches the rest of the Orca Cloud surface so a user with
  152. ``LIBRARY_UPLOAD`` but no ``ORCA_CLOUD_AUTH`` cannot slice using cloud
  153. profiles even if their stored token survived a permission revocation.
  154. """
  155. if user is not None and not user.has_permission(Permission.ORCA_CLOUD_AUTH.value):
  156. raise HTTPException(
  157. status_code=403,
  158. detail=f"Orca Cloud presets require the orca_cloud:auth permission ({slot})",
  159. )
  160. try:
  161. svc = await _build_orca_service(db, user)
  162. except HTTPException:
  163. # Builder already produces the right user-facing error (401 not
  164. # connected, 401 session refresh failed, 502 unreachable).
  165. raise
  166. try:
  167. profile = await svc.get_profile(ref.id)
  168. except OrcaCloudAuthError as e:
  169. raise HTTPException(
  170. status_code=401,
  171. detail=f"Orca Cloud session expired while fetching {slot} preset. Sign in again and retry.",
  172. ) from e
  173. except OrcaCloudError as e:
  174. if "not found" in str(e).lower():
  175. raise HTTPException(
  176. status_code=400,
  177. detail=f"Orca Cloud {slot} preset {ref.id!r} not found.",
  178. ) from e
  179. raise HTTPException(
  180. status_code=502,
  181. detail=f"Orca Cloud unreachable while fetching {slot} preset: {e}",
  182. ) from e
  183. finally:
  184. await svc.close()
  185. # ``profile`` is the ProfileUpsert shape — the inner ``content`` is the
  186. # actual slicer-format JSON. Fall back to forwarding the wrapper if the
  187. # shape doesn't match what we expect (defensive, in case Orca evolves
  188. # the wire format).
  189. content = profile.get("content") if isinstance(profile, dict) else None
  190. if not isinstance(content, dict):
  191. logger.info(
  192. "Orca Cloud preset %r for %s returned unexpected shape, forwarding raw payload",
  193. ref.id,
  194. slot,
  195. )
  196. content = profile
  197. return json.dumps(content)
  198. def _resolve_standard(ref: PresetRef, slot: str) -> str:
  199. """Build a minimal `{name, inherits, from, type}` stub. The sidecar's
  200. resolver walks `BUNDLED_PROFILES_PATH/<category>/<name>.json` and merges,
  201. yielding the full bundled preset without us round-tripping the content
  202. through Bambuddy."""
  203. if slot not in _SLOT_TO_BUNDLED_CATEGORY:
  204. raise HTTPException(status_code=400, detail=f"Unknown slot for standard preset: {slot!r}")
  205. return json.dumps(
  206. {
  207. # `name` must be set so the sidecar's compatibility checks see a
  208. # populated value. Reusing the bundled name keeps the resolved
  209. # profile's identity consistent with what the user picked.
  210. "name": ref.id,
  211. "inherits": ref.id,
  212. # `from: "system"` skips the User/system compatibility rejection
  213. # the resolver was designed to fix for OrcaSlicer GUI exports —
  214. # we never want a bundled preset to be treated as User-authored.
  215. "from": "system",
  216. # `type` is required by the CLI's --load-settings parser — see
  217. # _SLOT_TO_PROFILE_TYPE above for the silent-failure mode.
  218. "type": _SLOT_TO_PROFILE_TYPE[slot],
  219. }
  220. )