preset_resolver.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276
  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. if isinstance(payload, dict):
  146. # Bambu Cloud labels presets with `type: "printer"` / `"print"` /
  147. # `"filament"`, but the BS / Orca CLI's `--load-settings` parser only
  148. # accepts `"machine"` / `"process"` / `"filament"`. Without this
  149. # rewrite the CLI exits -5 with `operator(): unknown config type`
  150. # and the sidecar surfaces a generic "The input preset file is
  151. # invalid and can not be parsed" — see preset_resolver header
  152. # comment for the silent-fail history. `from` gets the same
  153. # treatment: Bambu Cloud's filament details routinely arrive with
  154. # `from: ""` (or no `from` at all) and the CLI rejects either with
  155. # `operator(): ... from unsupported` (same -5 exit). The standard
  156. # tier already pins `from: "system"` for exactly this reason; the
  157. # cloud tier needs the same pin because it lands at the same `--load-
  158. # settings` parser. The sidecar's `normalizeFromField` only rewrites
  159. # the `"User"` / `"System"` casings, not empty / missing values.
  160. payload = {**payload, "type": _SLOT_TO_PROFILE_TYPE[slot], "from": "system"}
  161. return json.dumps(payload)
  162. async def _resolve_orca_cloud(db: AsyncSession, user: User | None, ref: PresetRef, slot: str) -> str:
  163. """Fetch a single profile from Orca Cloud and return its content JSON.
  164. The route-layer service builder handles JIT token refresh and stale-credential
  165. cleanup, so any exception here means a genuine fetch / network / not-found
  166. problem — never a "stale token" situation the caller could retry through.
  167. Permission gate matches the rest of the Orca Cloud surface so a user with
  168. ``LIBRARY_UPLOAD`` but no ``ORCA_CLOUD_AUTH`` cannot slice using cloud
  169. profiles even if their stored token survived a permission revocation.
  170. """
  171. if user is not None and not user.has_permission(Permission.ORCA_CLOUD_AUTH.value):
  172. raise HTTPException(
  173. status_code=403,
  174. detail=f"Orca Cloud presets require the orca_cloud:auth permission ({slot})",
  175. )
  176. try:
  177. svc = await _build_orca_service(db, user)
  178. except HTTPException:
  179. # Builder already produces the right user-facing error (401 not
  180. # connected, 401 session refresh failed, 502 unreachable).
  181. raise
  182. try:
  183. profile = await svc.get_profile(ref.id)
  184. except OrcaCloudAuthError as e:
  185. raise HTTPException(
  186. status_code=401,
  187. detail=f"Orca Cloud session expired while fetching {slot} preset. Sign in again and retry.",
  188. ) from e
  189. except OrcaCloudError as e:
  190. if "not found" in str(e).lower():
  191. raise HTTPException(
  192. status_code=400,
  193. detail=f"Orca Cloud {slot} preset {ref.id!r} not found.",
  194. ) from e
  195. raise HTTPException(
  196. status_code=502,
  197. detail=f"Orca Cloud unreachable while fetching {slot} preset: {e}",
  198. ) from e
  199. finally:
  200. await svc.close()
  201. # ``profile`` is the ProfileUpsert shape — the inner ``content`` is the
  202. # actual slicer-format JSON. Fall back to forwarding the wrapper if the
  203. # shape doesn't match what we expect (defensive, in case Orca evolves
  204. # the wire format).
  205. content = profile.get("content") if isinstance(profile, dict) else None
  206. if not isinstance(content, dict):
  207. logger.info(
  208. "Orca Cloud preset %r for %s returned unexpected shape, forwarding raw payload",
  209. ref.id,
  210. slot,
  211. )
  212. content = profile
  213. if isinstance(content, dict):
  214. # Orca natively uses `machine` / `process` / `filament` for `type`,
  215. # which is what the CLI wants — but Bambu-imported profiles synced
  216. # through Orca Cloud can carry `printer` / `print` instead, and the
  217. # CLI's `--load-settings` parser rejects those the same way it does
  218. # for the Bambu Cloud tier. Force the slot-appropriate value so the
  219. # source tier doesn't decide whether slicing works. `from` gets the
  220. # same forced pin to `"system"` for the same reason — see the
  221. # Bambu Cloud branch above.
  222. content = {**content, "type": _SLOT_TO_PROFILE_TYPE[slot], "from": "system"}
  223. return json.dumps(content)
  224. def _resolve_standard(ref: PresetRef, slot: str) -> str:
  225. """Build a minimal `{name, inherits, from, type}` stub. The sidecar's
  226. resolver walks `BUNDLED_PROFILES_PATH/<category>/<name>.json` and merges,
  227. yielding the full bundled preset without us round-tripping the content
  228. through Bambuddy."""
  229. if slot not in _SLOT_TO_BUNDLED_CATEGORY:
  230. raise HTTPException(status_code=400, detail=f"Unknown slot for standard preset: {slot!r}")
  231. return json.dumps(
  232. {
  233. # `name` must be set so the sidecar's compatibility checks see a
  234. # populated value. Reusing the bundled name keeps the resolved
  235. # profile's identity consistent with what the user picked.
  236. "name": ref.id,
  237. "inherits": ref.id,
  238. # `from: "system"` skips the User/system compatibility rejection
  239. # the resolver was designed to fix for OrcaSlicer GUI exports —
  240. # we never want a bundled preset to be treated as User-authored.
  241. "from": "system",
  242. # `type` is required by the CLI's --load-settings parser — see
  243. # _SLOT_TO_PROFILE_TYPE above for the silent-failure mode.
  244. "type": _SLOT_TO_PROFILE_TYPE[slot],
  245. }
  246. )