preset_resolver.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287
  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.orca_cloud import _build_authenticated_service as _build_orca_service
  26. from backend.app.core.auth import is_auth_enabled
  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.bambu_cloud_credentials import get_stored_token
  37. from backend.app.services.orca_cloud import OrcaCloudAuthError, OrcaCloudError
  38. logger = logging.getLogger(__name__)
  39. _SLOT_TO_BUNDLED_CATEGORY = {
  40. "printer": "machine",
  41. "process": "process",
  42. "filament": "filament",
  43. }
  44. # The CLI's --load-settings parser uses the JSON's `type` field to decide
  45. # how to interpret each file (machine/process/filament). Without it the
  46. # CLI logs `operator(): unknown config type ... in load-settings`,
  47. # writes `error_string: "The input preset file is invalid and can not be
  48. # parsed.", return_code: -5` to result.json, and exits 0 — which the
  49. # Node sidecar's child_process treats as silent success producing no
  50. # output, then bubbles up as a generic "Failed to slice the model" 5xx.
  51. # Bambuddy then falls back to the embedded-settings path for every 3MF
  52. # slice, silently using whatever printer the source file was originally
  53. # bound to. Setting `type` correctly per slot fixes the silent fallback.
  54. _SLOT_TO_PROFILE_TYPE = {
  55. "printer": "machine",
  56. "process": "process",
  57. "filament": "filament",
  58. }
  59. async def resolve_preset_ref(
  60. db: AsyncSession,
  61. user: User | None,
  62. ref: PresetRef,
  63. slot: str,
  64. ) -> str:
  65. """Return the JSON-string content for `ref` so the sidecar can ingest it.
  66. `slot` is one of ``"printer"`` / ``"process"`` / ``"filament"``; it's
  67. only used to generate friendly error messages and to pick the bundled
  68. category for the standard tier.
  69. Raises ``HTTPException`` for any caller-facing error (invalid id, wrong
  70. preset type, cloud auth failure, network error fetching cloud detail).
  71. """
  72. if ref.source == "local":
  73. return await _resolve_local(db, ref, slot)
  74. if ref.source == "cloud":
  75. return await _resolve_cloud(db, user, ref, slot)
  76. if ref.source == "orca_cloud":
  77. return await _resolve_orca_cloud(db, user, ref, slot)
  78. if ref.source == "standard":
  79. return _resolve_standard(ref, slot)
  80. raise HTTPException(
  81. status_code=400,
  82. detail=f"Unknown preset source for {slot}: {ref.source!r}",
  83. )
  84. async def _resolve_local(db: AsyncSession, ref: PresetRef, slot: str) -> str:
  85. try:
  86. local_id = int(ref.id)
  87. except (ValueError, TypeError):
  88. raise HTTPException(status_code=400, detail=f"Invalid local preset id for {slot}: {ref.id!r}") from None
  89. preset = await db.get(LocalPreset, local_id)
  90. if preset is None or preset.preset_type != slot:
  91. raise HTTPException(
  92. status_code=400,
  93. detail=f"Invalid {slot} preset id (expected preset_type='{slot}')",
  94. )
  95. return preset.setting
  96. # The sign-in stored without a user belongs to an install with auth off. With
  97. # auth on, a caller without a user (an API key without Allow Cloud Access)
  98. # has no cloud sign-in of its own and must not borrow that one.
  99. _NO_CLOUD_IDENTITY = "{cloud} presets need a signed-in user or an API key with Allow Cloud Access ({slot})"
  100. async def _resolve_cloud(db: AsyncSession, user: User | None, ref: PresetRef, slot: str) -> str:
  101. """Fetch a single cloud preset detail. Permission gate matches the
  102. rest of the cloud surface (`CLOUD_AUTH`) so a user with `LIBRARY_UPLOAD`
  103. but no `CLOUD_AUTH` can't slice using cloud presets even if their
  104. ``User.cloud_token`` survived a permission revocation."""
  105. if user is not None and not user.has_permission(Permission.CLOUD_AUTH.value):
  106. raise HTTPException(
  107. status_code=403,
  108. detail=f"Cloud presets require the cloud:auth permission ({slot})",
  109. )
  110. if user is None and await is_auth_enabled(db):
  111. raise HTTPException(status_code=403, detail=_NO_CLOUD_IDENTITY.format(cloud="Bambu Cloud", slot=slot))
  112. token, _email, region = await get_stored_token(db, user)
  113. if not token:
  114. raise HTTPException(
  115. status_code=400,
  116. detail=(
  117. f"Cloud preset selected for {slot}, but no Bambu Cloud session is "
  118. "stored. Sign in to Bambu Cloud and retry."
  119. ),
  120. )
  121. cloud = BambuCloudService(region=region)
  122. cloud.set_token(token)
  123. try:
  124. detail = await cloud.get_setting_detail(ref.id)
  125. except BambuCloudAuthError:
  126. raise HTTPException(
  127. status_code=401,
  128. detail=(f"Bambu Cloud session expired while fetching {slot} preset. Sign in again and retry."),
  129. ) from None
  130. except BambuCloudError as e:
  131. raise HTTPException(
  132. status_code=502,
  133. detail=f"Bambu Cloud unreachable while fetching {slot} preset: {e}",
  134. ) from e
  135. finally:
  136. await cloud.close()
  137. # `get_setting_detail` returns the wrapper envelope; the actual preset
  138. # JSON lives under `.setting`. The sidecar wants the preset content, not
  139. # the envelope.
  140. payload = detail.get("setting") if isinstance(detail, dict) else None
  141. if not isinstance(payload, dict):
  142. # Some endpoints return the preset at the top level instead of
  143. # nested under `setting`. Fall back to the whole response in that
  144. # case rather than failing — the sidecar will reject it cleanly if
  145. # the shape is genuinely wrong, and we log the unusual response.
  146. logger.info(
  147. "Cloud preset %r for %s returned unexpected shape, forwarding raw payload",
  148. ref.id,
  149. slot,
  150. )
  151. payload = detail
  152. if isinstance(payload, dict):
  153. # Bambu Cloud labels presets with `type: "printer"` / `"print"` /
  154. # `"filament"`, but the BS / Orca CLI's `--load-settings` parser only
  155. # accepts `"machine"` / `"process"` / `"filament"`. Without this
  156. # rewrite the CLI exits -5 with `operator(): unknown config type`
  157. # and the sidecar surfaces a generic "The input preset file is
  158. # invalid and can not be parsed" — see preset_resolver header
  159. # comment for the silent-fail history. `from` gets the same
  160. # treatment: Bambu Cloud's filament details routinely arrive with
  161. # `from: ""` (or no `from` at all) and the CLI rejects either with
  162. # `operator(): ... from unsupported` (same -5 exit). The standard
  163. # tier already pins `from: "system"` for exactly this reason; the
  164. # cloud tier needs the same pin because it lands at the same `--load-
  165. # settings` parser. The sidecar's `normalizeFromField` only rewrites
  166. # the `"User"` / `"System"` casings, not empty / missing values.
  167. payload = {**payload, "type": _SLOT_TO_PROFILE_TYPE[slot], "from": "system"}
  168. return json.dumps(payload)
  169. async def _resolve_orca_cloud(db: AsyncSession, user: User | None, ref: PresetRef, slot: str) -> str:
  170. """Fetch a single profile from Orca Cloud and return its content JSON.
  171. The route-layer service builder handles JIT token refresh and stale-credential
  172. cleanup, so any exception here means a genuine fetch / network / not-found
  173. problem — never a "stale token" situation the caller could retry through.
  174. Permission gate matches the rest of the Orca Cloud surface so a user with
  175. ``LIBRARY_UPLOAD`` but no ``ORCA_CLOUD_AUTH`` cannot slice using cloud
  176. profiles even if their stored token survived a permission revocation.
  177. """
  178. if user is not None and not user.has_permission(Permission.ORCA_CLOUD_AUTH.value):
  179. raise HTTPException(
  180. status_code=403,
  181. detail=f"Orca Cloud presets require the orca_cloud:auth permission ({slot})",
  182. )
  183. if user is None and await is_auth_enabled(db):
  184. raise HTTPException(status_code=403, detail=_NO_CLOUD_IDENTITY.format(cloud="Orca Cloud", slot=slot))
  185. try:
  186. svc = await _build_orca_service(db, user)
  187. except HTTPException:
  188. # Builder already produces the right user-facing error (401 not
  189. # connected, 401 session refresh failed, 502 unreachable).
  190. raise
  191. try:
  192. profile = await svc.get_profile(ref.id)
  193. except OrcaCloudAuthError as e:
  194. raise HTTPException(
  195. status_code=401,
  196. detail=f"Orca Cloud session expired while fetching {slot} preset. Sign in again and retry.",
  197. ) from e
  198. except OrcaCloudError as e:
  199. if "not found" in str(e).lower():
  200. raise HTTPException(
  201. status_code=400,
  202. detail=f"Orca Cloud {slot} preset {ref.id!r} not found.",
  203. ) from e
  204. raise HTTPException(
  205. status_code=502,
  206. detail=f"Orca Cloud unreachable while fetching {slot} preset: {e}",
  207. ) from e
  208. finally:
  209. await svc.close()
  210. # ``profile`` is the ProfileUpsert shape — the inner ``content`` is the
  211. # actual slicer-format JSON. Fall back to forwarding the wrapper if the
  212. # shape doesn't match what we expect (defensive, in case Orca evolves
  213. # the wire format).
  214. content = profile.get("content") if isinstance(profile, dict) else None
  215. if not isinstance(content, dict):
  216. logger.info(
  217. "Orca Cloud preset %r for %s returned unexpected shape, forwarding raw payload",
  218. ref.id,
  219. slot,
  220. )
  221. content = profile
  222. if isinstance(content, dict):
  223. # Orca natively uses `machine` / `process` / `filament` for `type`,
  224. # which is what the CLI wants — but Bambu-imported profiles synced
  225. # through Orca Cloud can carry `printer` / `print` instead, and the
  226. # CLI's `--load-settings` parser rejects those the same way it does
  227. # for the Bambu Cloud tier. Force the slot-appropriate value so the
  228. # source tier doesn't decide whether slicing works. `from` gets the
  229. # same forced pin to `"system"` for the same reason — see the
  230. # Bambu Cloud branch above.
  231. content = {**content, "type": _SLOT_TO_PROFILE_TYPE[slot], "from": "system"}
  232. return json.dumps(content)
  233. def _resolve_standard(ref: PresetRef, slot: str) -> str:
  234. """Build a minimal `{name, inherits, from, type}` stub. The sidecar's
  235. resolver walks `BUNDLED_PROFILES_PATH/<category>/<name>.json` and merges,
  236. yielding the full bundled preset without us round-tripping the content
  237. through Bambuddy."""
  238. if slot not in _SLOT_TO_BUNDLED_CATEGORY:
  239. raise HTTPException(status_code=400, detail=f"Unknown slot for standard preset: {slot!r}")
  240. return json.dumps(
  241. {
  242. # `name` must be set so the sidecar's compatibility checks see a
  243. # populated value. Reusing the bundled name keeps the resolved
  244. # profile's identity consistent with what the user picked.
  245. "name": ref.id,
  246. "inherits": ref.id,
  247. # `from: "system"` skips the User/system compatibility rejection
  248. # the resolver was designed to fix for OrcaSlicer GUI exports —
  249. # we never want a bundled preset to be treated as User-authored.
  250. "from": "system",
  251. # `type` is required by the CLI's --load-settings parser — see
  252. # _SLOT_TO_PROFILE_TYPE above for the silent-failure mode.
  253. "type": _SLOT_TO_PROFILE_TYPE[slot],
  254. }
  255. )