slicer_api.py 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707
  1. """HTTP client for an OrcaSlicer / BambuStudio API sidecar.
  2. Bambuddy stores user printer/process/filament profiles itself (cloud-synced
  3. or locally imported), so the slice flow always sends the model file plus an
  4. explicit JSON profile triplet to the sidecar's `/slice` endpoint. The sidecar
  5. shape mirrors `AFKFelix/orca-slicer-api` (multipart upload, `--load-settings`
  6. under the hood, response body is raw G-code or 3MF with metadata in the
  7. `X-Print-Time-Seconds` / `X-Filament-Used-G` / `X-Filament-Used-Mm` headers).
  8. """
  9. import asyncio
  10. import io
  11. import json
  12. import logging
  13. import time
  14. import zipfile
  15. from collections.abc import Callable
  16. from typing import NamedTuple
  17. import httpx
  18. logger = logging.getLogger(__name__)
  19. class SlicerApiError(Exception):
  20. """Base error from the slicer API sidecar."""
  21. class SlicerApiUnavailableError(SlicerApiError):
  22. """Sidecar is unreachable (connection error, no response)."""
  23. class SlicerApiServerError(SlicerApiError):
  24. """Sidecar responded with a 5xx — usually the wrapped slicer CLI exited
  25. non-zero (range-validation reject, segfault on complex models, etc.).
  26. Distinguished from `SlicerApiUnavailableError` so the caller can decide
  27. whether to retry with a different request shape (e.g. a 3MF embedded-
  28. settings fallback)."""
  29. class SlicerInputError(SlicerApiError):
  30. """Sidecar rejected the input as invalid (4xx)."""
  31. class SlicerTimeoutError(SlicerApiError):
  32. """We gave up waiting on a slice that never finished.
  33. Kept apart from ``SlicerApiUnavailableError`` because they call for
  34. opposite reactions and used to be reported as the same thing: an
  35. ``httpx.ReadTimeout`` is a subclass of ``RequestError``, so a slice that
  36. simply took a long time surfaced as "Slicer sidecar unreachable" — sending
  37. the reporter of #2730 off to check a sidecar that was reachable throughout
  38. and still slicing when we hung up on it.
  39. """
  40. class ResolvedProfile(NamedTuple):
  41. """A preset's effective values, or why they are unavailable.
  42. ``reason`` is one of ``ok`` / ``sidecar_outdated`` / ``sidecar_unavailable``
  43. / ``preset_unresolved``. It exists so the UI can say something actionable
  44. instead of one generic "could not read the values" for four causes.
  45. """
  46. values: dict | None
  47. reason: str
  48. class SliceResult(NamedTuple):
  49. """Result of a slice operation."""
  50. content: bytes
  51. print_time_seconds: int
  52. filament_used_g: float
  53. filament_used_mm: float
  54. _shared_http_client: httpx.AsyncClient | None = None
  55. # Fallback for callers that don't pass one (tests, and any path that runs
  56. # without a DB session to read the setting from). The user-facing value is
  57. # ``slicer_stall_timeout_minutes`` under Settings -> Workflow -> Slicer.
  58. DEFAULT_SLICE_STALL_TIMEOUT_SECONDS = 15 * 60.0
  59. # How often the progress poller ticks. Also the granularity of the stall check,
  60. # since a missed tick is what the stall clock is counting.
  61. _PROGRESS_POLL_INTERVAL = 1.0
  62. async def get_stall_timeout_seconds(db) -> float:
  63. """Read ``slicer_stall_timeout_minutes`` (Settings -> Workflow -> Slicer).
  64. Falls back to the default on anything unparseable rather than failing the
  65. slice — a bad settings row must not be the reason a print doesn't happen.
  66. """
  67. from backend.app.api.routes.settings import get_setting
  68. try:
  69. raw = await get_setting(db, "slicer_stall_timeout_minutes")
  70. except Exception:
  71. return DEFAULT_SLICE_STALL_TIMEOUT_SECONDS
  72. try:
  73. minutes = int(str(raw).strip())
  74. except (TypeError, ValueError):
  75. return DEFAULT_SLICE_STALL_TIMEOUT_SECONDS
  76. if minutes < 1:
  77. return DEFAULT_SLICE_STALL_TIMEOUT_SECONDS
  78. return float(minutes) * 60.0
  79. def _format_sidecar_error(response: httpx.Response) -> str:
  80. """Build a human-readable error string from a sidecar 4xx/5xx response.
  81. The sidecar's `AppError` middleware emits a JSON body of the shape
  82. ``{"message": "...", "details": "..."}``. Earlier versions of this
  83. client only read ``message``, which left every CLI failure surfaced
  84. as the generic ``Failed to slice the model`` because the *actual*
  85. CLI stderr / `error_string` lives in ``details``. Including both
  86. means ``bambuddy.log`` carries the real reason a slice rejected
  87. the supplied profiles instead of an unhelpful generic line.
  88. """
  89. try:
  90. payload = response.json()
  91. except Exception:
  92. return response.text[:500]
  93. if not isinstance(payload, dict):
  94. return str(payload)[:500]
  95. message = payload.get("message") or ""
  96. details = payload.get("details") or ""
  97. if message and details:
  98. return f"{message}: {details}"[:500]
  99. return (message or details or response.text)[:500]
  100. def _handle_slice_response(response: httpx.Response, *, export_3mf: bool) -> SliceResult:
  101. """Turn a sidecar ``/slice`` HTTP response into a validated ``SliceResult``.
  102. Shared by ``slice_with_profiles`` / ``slice_without_profiles`` so the status
  103. handling and output validation live in one place.
  104. Beyond the status check, this guards against the sidecar (or a reverse proxy
  105. in front of it) returning **HTTP 200 with a body that isn't a real slice**
  106. (#2671): a stock/misconfigured sidecar, a proxy interstitial or truncated
  107. response, or an OrcaSlicer/BambuStudio CLI crash that produces empty output.
  108. Without this check Bambuddy would store that tiny blob as a ``.gcode.3mf``,
  109. let it be queued, and FTP it to the printer — a silently-broken print. When
  110. a 3MF export was requested the body must be a valid ZIP (3MF container);
  111. anything else is treated as a sidecar failure.
  112. Raises:
  113. SlicerInputError: 4xx from the sidecar (bad input / proxy body limit).
  114. SlicerApiServerError: 5xx, or a 2xx whose body is not a valid 3MF.
  115. """
  116. if response.status_code == 413:
  117. # A 413 almost never comes from the slicer itself — it's a reverse proxy
  118. # (nginx/SWAG/Traefik) or a CDN capping the multipart upload (model +
  119. # profiles). Name the real fix so the user doesn't tweak the wrong layer.
  120. raise SlicerInputError(
  121. "The slice request was rejected as too large (HTTP 413). A reverse proxy "
  122. "in front of the slicer sidecar is capping the request body — raise "
  123. "'client_max_body_size' (nginx/SWAG) or the equivalent on the proxy that "
  124. "sits directly in front of the sidecar, then reload it. If the sidecar is "
  125. "behind Cloudflare, note its request-size cap."
  126. )
  127. if response.status_code >= 500:
  128. raise SlicerApiServerError(f"Slicer CLI failed ({response.status_code}): {_format_sidecar_error(response)}")
  129. if response.status_code >= 400:
  130. raise SlicerInputError(f"Slicer rejected input ({response.status_code}): {_format_sidecar_error(response)}")
  131. content = response.content
  132. if export_3mf and not zipfile.is_zipfile(io.BytesIO(content)):
  133. # 200 OK but the body is not a 3MF zip → the sidecar did not produce a
  134. # usable slice. Surface it loudly instead of persisting a corrupt file.
  135. detail = _format_sidecar_error(response) if len(content) <= 500 else ""
  136. raise SlicerApiServerError(
  137. f"Slicer sidecar returned HTTP {response.status_code} but the body is not a valid "
  138. f"3MF ({len(content)} bytes). This usually means a misconfigured sidecar, an "
  139. f"OrcaSlicer/BambuStudio CLI crash producing no output, or a reverse proxy returning "
  140. f"an error page or truncating the response — verify the sidecar URL and any proxy in "
  141. f"front of it." + (f" Body: {detail}" if detail else "")
  142. )
  143. return SliceResult(
  144. content=content,
  145. print_time_seconds=_safe_int(response.headers.get("x-print-time-seconds")),
  146. filament_used_g=_safe_float(response.headers.get("x-filament-used-g")),
  147. filament_used_mm=_safe_float(response.headers.get("x-filament-used-mm")),
  148. )
  149. def set_shared_http_client(client: httpx.AsyncClient | None) -> None:
  150. """Register an app-scoped client so per-request services can pool transport."""
  151. global _shared_http_client
  152. _shared_http_client = client
  153. def _guess_model_content_type(filename: str) -> str:
  154. lower = filename.lower()
  155. if lower.endswith(".stl"):
  156. return "model/stl"
  157. if lower.endswith(".3mf") or lower.endswith(".gcode.3mf"):
  158. return "model/3mf"
  159. if lower.endswith(".step") or lower.endswith(".stp"):
  160. return "model/step"
  161. return "application/octet-stream"
  162. class _Liveness:
  163. """Tracks when the slicer last showed a sign of life.
  164. ``deadline`` is what the slice waits against, and it moves forward on every
  165. genuine progress update. A slice therefore fails only after the configured
  166. window of *silence*, however long the whole thing has been running (#2730).
  167. ``progress_supported`` stays False for sidecars that never answer the
  168. progress endpoint. Those give us nothing to judge liveness by, so the caller
  169. treats the same window as a total-elapsed ceiling rather than pretending a
  170. stall can be detected.
  171. """
  172. def __init__(self, window_seconds: float, poll_interval: float = _PROGRESS_POLL_INTERVAL) -> None:
  173. # Liveness can only be observed as often as the poller ticks, so a
  174. # window shorter than a few ticks would expire in the gap between two
  175. # polls and fail every slice instantly, however healthy. The settings
  176. # schema already floors the user-facing value at a minute; this guards
  177. # the constructor, which tests and any future caller can pass anything.
  178. self.window_seconds = max(window_seconds, poll_interval * 3)
  179. self.progress_supported = False
  180. self.started_at = time.monotonic()
  181. self._last_alive = self.started_at
  182. def saw_progress_endpoint(self) -> None:
  183. self.progress_supported = True
  184. def mark_alive(self) -> None:
  185. self._last_alive = time.monotonic()
  186. @property
  187. def deadline(self) -> float:
  188. """Monotonic time at which we stop waiting."""
  189. base = self._last_alive if self.progress_supported else self.started_at
  190. return base + self.window_seconds
  191. def silent_for(self) -> float:
  192. return time.monotonic() - self._last_alive
  193. def elapsed(self) -> float:
  194. return time.monotonic() - self.started_at
  195. def timeout_message(self) -> str:
  196. minutes = self.window_seconds / 60
  197. if self.progress_supported:
  198. return (
  199. f"The slicer stopped reporting progress for {minutes:.0f} minutes "
  200. f"(slicing had been running for {self.elapsed() / 60:.0f} minutes). "
  201. "Raise 'Slicer stall timeout' under Settings -> Workflow -> Slicer if this model "
  202. "legitimately needs longer between progress updates."
  203. )
  204. return (
  205. f"Slicing did not finish within {minutes:.0f} minutes, and this sidecar does not "
  206. "report progress, so there was no way to tell a slow model from a stalled one. "
  207. "Raise 'Slicer stall timeout' under Settings -> Workflow -> Slicer, or update the "
  208. "sidecar to a version that reports progress."
  209. )
  210. class SlicerApiService:
  211. """Talks to an OrcaSlicer / BambuStudio API sidecar."""
  212. def __init__(
  213. self,
  214. base_url: str,
  215. *,
  216. client: httpx.AsyncClient | None = None,
  217. timeout_seconds: float = DEFAULT_SLICE_STALL_TIMEOUT_SECONDS,
  218. ) -> None:
  219. """``timeout_seconds`` bounds *silence*, not total slicing time (#2730).
  220. While a slice is running Bambuddy polls the sidecar's progress channel
  221. once a second, so it can tell a model that is merely slow from one that
  222. has stopped: the clock is reset by every progress update, and only runs
  223. out when the slicer has said nothing for this long. A heavy model that
  224. keeps reporting will run to completion however long it takes.
  225. Sidecars too old to report progress have no liveness signal to offer, so
  226. for those the same number bounds total elapsed time — the pre-#2730
  227. behaviour, but configurable and no longer five minutes flat.
  228. """
  229. self.base_url = base_url.rstrip("/")
  230. self.timeout_seconds = timeout_seconds
  231. # Instance-level so tests can compress the timing; production always
  232. # uses the module default.
  233. self.progress_poll_interval = _PROGRESS_POLL_INTERVAL
  234. if client is not None:
  235. self._client = client
  236. self._owns_client = False
  237. elif _shared_http_client is not None:
  238. self._client = _shared_http_client
  239. self._owns_client = False
  240. else:
  241. self._client = httpx.AsyncClient(timeout=timeout_seconds)
  242. self._owns_client = True
  243. async def close(self) -> None:
  244. if self._owns_client:
  245. await self._client.aclose()
  246. async def __aenter__(self) -> "SlicerApiService":
  247. return self
  248. async def __aexit__(self, *_: object) -> None:
  249. await self.close()
  250. async def health(self) -> dict:
  251. """GET /health — used to surface a clear "sidecar offline" error before
  252. accepting a slice request from the user."""
  253. try:
  254. response = await self._client.get(f"{self.base_url}/health", timeout=10.0)
  255. except httpx.RequestError as exc:
  256. raise SlicerApiUnavailableError(f"Slicer sidecar unreachable: {exc}") from exc
  257. if response.status_code >= 400:
  258. raise SlicerApiUnavailableError(f"Slicer sidecar /health returned {response.status_code}")
  259. return response.json()
  260. async def resolve_profile(self, profile_json: str, category: str) -> "ResolvedProfile":
  261. """POST /profiles/resolve — flatten a preset's ``inherits:`` chain.
  262. Returns the effective key/value map the slicer would actually use, so
  263. the slice modal's settings panel can show a preset's real values rather
  264. than the option schema's compiled-in defaults (a "Standard" pick is
  265. only a ``{inherits: ...}`` stub on our side; everything else it sets
  266. lives in the sidecar's bundled profiles).
  267. This deliberately asks the sidecar rather than resolving locally.
  268. Bambuddy has its own ``inherits:`` resolver in ``orca_profiles``, but it
  269. walks OrcaSlicer's *published* profile tree, which is not necessarily
  270. the one baked into the running sidecar image — values from it would look
  271. authoritative and could quietly disagree with what gets sliced.
  272. Returns a :class:`ResolvedProfile` whose ``reason`` distinguishes *why*
  273. values are missing. That matters more than it looks: the common case in
  274. practice is a sidecar older than this endpoint, because a Bambuddy
  275. install pulls ``SIDECAR_TAG:-latest`` independently of its own release
  276. channel. "Could not read the values" sends that user hunting; "your
  277. sidecar image is older than this feature" is a one-line fix. Genuine
  278. transport failures still raise.
  279. """
  280. try:
  281. payload = json.loads(profile_json)
  282. except json.JSONDecodeError:
  283. logger.warning("Cannot resolve %s preset: content is not valid JSON", category)
  284. return ResolvedProfile(None, "preset_unresolved")
  285. try:
  286. response = await self._client.post(
  287. f"{self.base_url}/profiles/resolve",
  288. json={"category": category, "profile": payload},
  289. timeout=15.0,
  290. )
  291. except httpx.RequestError as exc:
  292. raise SlicerApiUnavailableError(f"Slicer sidecar unreachable: {exc}") from exc
  293. if response.status_code == 404:
  294. # Sidecar predates the endpoint. Not an error, and specifically not
  295. # the same as a broken one — this is the case that has a fix the
  296. # user can act on.
  297. logger.info("Slicer sidecar has no /profiles/resolve; falling back to schema defaults")
  298. return ResolvedProfile(None, "sidecar_outdated")
  299. if response.status_code >= 400:
  300. logger.warning(
  301. "Slicer sidecar /profiles/resolve returned %s: %s",
  302. response.status_code,
  303. _format_sidecar_error(response),
  304. )
  305. return ResolvedProfile(None, "sidecar_unavailable")
  306. body = response.json()
  307. resolved = body.get("profile") if isinstance(body, dict) else None
  308. if not isinstance(resolved, dict):
  309. logger.warning("Slicer sidecar /profiles/resolve returned no profile object")
  310. return ResolvedProfile(None, "sidecar_unavailable")
  311. return ResolvedProfile(resolved, "ok")
  312. async def list_bundled_profiles(self) -> dict:
  313. """GET /profiles/bundled — return the slicer's stock profiles by slot.
  314. Powers the "Standard" tier of Bambuddy's SliceModal preset dropdowns.
  315. The sidecar walks the slicer's read-only `resources/profiles/BBL/`
  316. tree and returns ``{printer, process, filament}`` arrays of
  317. ``{name, base_id}`` (alphabetised, instantiable presets only — abstract
  318. bases like `fdm_filament_pla` are filtered out by the sidecar).
  319. Returns an empty-shaped dict when the sidecar is unreachable so the
  320. unified-presets endpoint can degrade to "no standard tier" without
  321. crashing the modal — cloud + local-imported profiles still render.
  322. """
  323. try:
  324. response = await self._client.get(f"{self.base_url}/profiles/bundled", timeout=10.0)
  325. except httpx.RequestError as exc:
  326. raise SlicerApiUnavailableError(f"Slicer sidecar unreachable: {exc}") from exc
  327. if response.status_code >= 400:
  328. raise SlicerApiUnavailableError(f"Slicer sidecar /profiles/bundled returned {response.status_code}")
  329. return response.json()
  330. async def _poll_progress(
  331. self,
  332. request_id: str,
  333. on_progress: Callable[[dict], None],
  334. *,
  335. liveness: "_Liveness | None" = None,
  336. ) -> None:
  337. """Poll the sidecar's progress endpoint at ~1Hz and forward each
  338. snapshot to ``on_progress``. Runs until cancelled.
  339. 4xx is NOT treated as terminal: the FIRST poll fires the moment
  340. the slice POST is sent, which can be milliseconds before the
  341. request actually lands on the sidecar and `progressStore.start()`
  342. runs — so a fresh request legitimately returns 404 for the first
  343. tick or two. Bailing on the first 404 (the original implementation)
  344. meant we'd quit before progress could ever arrive. The polling
  345. task is cancelled by the outer slice request anyway, so a
  346. sustained 404 (older sidecar without progress support, or post-
  347. slice grace expiry) just costs a few wasted GETs that the cancel
  348. will stop. Network errors and non-JSON 5xx are swallowed; the
  349. next tick retries.
  350. When ``liveness`` is supplied this doubles as the stall watchdog: every
  351. 200 carrying a *changed* payload marks the slicer alive, which is what
  352. keeps the slice's deadline moving (#2730). An unchanged payload
  353. deliberately does not count — the sidecar re-serves its last snapshot on
  354. every poll, so treating a repeat as progress would leave the watchdog
  355. unable to detect a stall at all.
  356. """
  357. url = f"{self.base_url}/slice/progress/{request_id}"
  358. last_payload: dict | None = None
  359. while True:
  360. try:
  361. response = await self._client.get(url, timeout=5.0)
  362. if response.status_code == 200:
  363. payload = response.json()
  364. if isinstance(payload, dict):
  365. if liveness is not None:
  366. liveness.saw_progress_endpoint()
  367. if payload != last_payload:
  368. liveness.mark_alive()
  369. last_payload = payload
  370. on_progress(payload)
  371. # 404 / other 4xx = no progress available (yet, or ever
  372. # for older sidecars). Keep polling — the outer slice
  373. # request will cancel this task on completion.
  374. except (httpx.RequestError, ValueError):
  375. # ValueError covers JSONDecodeError when the sidecar
  376. # returns a non-JSON 5xx. Don't crash the poller.
  377. pass
  378. try:
  379. await asyncio.sleep(self.progress_poll_interval)
  380. except asyncio.CancelledError:
  381. return
  382. async def _post_slice(
  383. self,
  384. *,
  385. files: list | dict,
  386. data: dict,
  387. request_id: str | None,
  388. on_progress: Callable[[dict], None] | None,
  389. ) -> httpx.Response:
  390. """POST /slice, supervised by the progress channel rather than a clock.
  391. Before #2730 this was a plain ``httpx`` call with a flat 300 s timeout on
  392. every phase. A genuinely heavy model — the reporter's was a MakerWorld
  393. model that Bambu Studio also took a long time over — hit the ceiling
  394. while it was still slicing perfectly happily, and because
  395. ``httpx.ReadTimeout`` is a ``RequestError`` it was reported as "Slicer
  396. sidecar unreachable". Meanwhile Bambuddy was polling the sidecar's
  397. progress endpoint once a second and could see the thing working.
  398. So the read timeout comes off the HTTP call and the poller supervises
  399. instead: the deadline is pushed forward by every progress update, and
  400. only a genuine silence ends the wait. Connect and pool keep short
  401. timeouts — a sidecar that won't accept the connection at all is
  402. unreachable, and should still say so quickly.
  403. """
  404. liveness = _Liveness(self.timeout_seconds, self.progress_poll_interval)
  405. # Poll whenever we have a request_id, even if the caller wants no
  406. # progress callbacks: the poll is what makes stall detection possible,
  407. # and one GET per second is cheaper than a wrongly-cancelled slice.
  408. progress_task: asyncio.Task | None = None
  409. if request_id is not None:
  410. progress_task = asyncio.create_task(
  411. self._poll_progress(request_id, on_progress or (lambda _payload: None), liveness=liveness),
  412. name=f"slicer-progress-{request_id}",
  413. )
  414. post_task = asyncio.create_task(
  415. self._client.post(
  416. f"{self.base_url}/slice",
  417. files=files,
  418. data=data,
  419. timeout=httpx.Timeout(connect=30.0, read=None, write=None, pool=30.0),
  420. ),
  421. name="slicer-slice-post",
  422. )
  423. try:
  424. while True:
  425. remaining = liveness.deadline - time.monotonic()
  426. if remaining <= 0:
  427. post_task.cancel()
  428. logger.warning(
  429. "Slice abandoned after %.0fs (silent for %.0fs, progress channel %s)",
  430. liveness.elapsed(),
  431. liveness.silent_for(),
  432. "available" if liveness.progress_supported else "unavailable",
  433. )
  434. raise SlicerTimeoutError(liveness.timeout_message())
  435. # Re-check at poll granularity so a progress update that lands
  436. # mid-wait extends the deadline promptly.
  437. done, _pending = await asyncio.wait({post_task}, timeout=min(remaining, self.progress_poll_interval))
  438. if post_task in done:
  439. break
  440. finally:
  441. if progress_task is not None:
  442. progress_task.cancel()
  443. # Await both so neither is left pending — a cancelled POST still
  444. # needs its connection released back to the pool.
  445. await asyncio.gather(post_task, progress_task or asyncio.sleep(0), return_exceptions=True)
  446. try:
  447. return post_task.result()
  448. except httpx.RequestError as exc:
  449. raise SlicerApiUnavailableError(f"Slicer sidecar unreachable: {exc}") from exc
  450. async def slice_with_profiles(
  451. self,
  452. *,
  453. model_bytes: bytes,
  454. model_filename: str,
  455. printer_profile_json: str,
  456. process_profile_json: str,
  457. filament_profile_jsons: list[str],
  458. plate: int | None = None,
  459. export_3mf: bool = False,
  460. arrange: bool = False,
  461. orient: bool = False,
  462. request_id: str | None = None,
  463. on_progress: Callable[[dict], None] | None = None,
  464. ) -> SliceResult:
  465. """POST /slice with model + printer/process/filament profiles.
  466. ``filament_profile_jsons`` is plate-slot-ordered: index 0 is the
  467. profile for slot 1, etc. Single-color callers pass a one-element
  468. list. Multiple ``filamentProfile`` parts are sent as a repeated form
  469. field — the sidecar's route declares ``maxCount: 16`` and the
  470. slicing service joins them as semicolon-separated
  471. ``--load-filaments`` for the OrcaSlicer / BambuStudio CLI.
  472. ``arrange`` forwards the sidecar's ``--arrange`` flag to BambuStudio.
  473. When True the slicer auto-repositions objects on the target bed,
  474. which Bambuddy uses for cross-nozzle-class re-slices (#1493) where
  475. the source's X1C-coordinate layout would otherwise drop into an H2D
  476. dead zone or trigger the multi-extruder geometry pipeline's polygon
  477. clipping crash. Default off so single-printer slices preserve the
  478. user's deliberate layout. Also settable per-slice by the user
  479. (#2548).
  480. ``orient`` forwards ``--orient``, the CLI's auto-orientation pass:
  481. the slicer scores candidate rotations (overhang area, contour,
  482. unprintability) and rotates each object onto the best one before
  483. slicing. User-driven only — nothing in Bambuddy turns it on by
  484. itself, since rotating a deliberately-laid-out model is not a
  485. change to make silently.
  486. ``request_id``: when supplied, the sidecar wires --pipe to a
  487. per-request FIFO and publishes structured JSON progress events to
  488. its in-memory ProgressStore under this id. Bambuddy's slice
  489. dispatch polls ``GET /slice/progress/{request_id}`` in parallel
  490. to drive the live-progress toast.
  491. Raises:
  492. SlicerInputError: 4xx from sidecar (caller-supplied input is bad).
  493. SlicerApiUnavailableError: connection error or 5xx from sidecar.
  494. """
  495. # httpx supports repeated multipart fields when files is a list of
  496. # tuples — using the dict form would silently overwrite duplicate
  497. # keys and ship only the last filament profile.
  498. files: list[tuple[str, tuple[str, bytes, str]]] = [
  499. ("file", (model_filename, model_bytes, _guess_model_content_type(model_filename))),
  500. ("printerProfile", ("printer.json", printer_profile_json.encode("utf-8"), "application/json")),
  501. ("presetProfile", ("preset.json", process_profile_json.encode("utf-8"), "application/json")),
  502. ]
  503. for idx, fjson in enumerate(filament_profile_jsons):
  504. files.append(
  505. (
  506. "filamentProfile",
  507. (f"filament_{idx + 1}.json", fjson.encode("utf-8"), "application/json"),
  508. )
  509. )
  510. data: dict[str, str] = {}
  511. if plate is not None:
  512. data["plate"] = str(plate)
  513. if export_3mf:
  514. data["exportType"] = "3mf"
  515. _add_layout_flags(data, arrange=arrange, orient=orient)
  516. if request_id is not None:
  517. data["requestId"] = request_id
  518. # When the caller supplied a request_id, kick off a parallel
  519. # poller that reads the sidecar's --pipe-fed progress endpoint
  520. # and surfaces structured updates via on_progress. Uses a
  521. # short-tick poll (1s) since the slicer emits stage changes
  522. # several times per minute on complex models.
  523. response = await self._post_slice(files=files, data=data, request_id=request_id, on_progress=on_progress)
  524. return _handle_slice_response(response, export_3mf=export_3mf)
  525. async def slice_without_profiles(
  526. self,
  527. *,
  528. model_bytes: bytes,
  529. model_filename: str,
  530. plate: int | None = None,
  531. export_3mf: bool = False,
  532. arrange: bool = False,
  533. orient: bool = False,
  534. request_id: str | None = None,
  535. on_progress: Callable[[dict], None] | None = None,
  536. ) -> SliceResult:
  537. """POST /slice with only the model file and no profile triplet.
  538. For 3MF inputs this lets the slicer fall back on the file's embedded
  539. `Metadata/project_settings.config`. Used as a fallback when
  540. `slice_with_profiles` triggers a CLI segfault or other 5xx —
  541. complex H2D / multi-extruder models hit upstream bugs in both the
  542. OrcaSlicer and BambuStudio CLIs when invoked via `--load-settings`.
  543. Also used by the SliceModal's per-plate filament discovery path:
  544. for an unsliced project file we run a real preview slice via the
  545. sidecar to find which AMS slots the picked plate consumes. The
  546. ``request_id`` parameter routes the sidecar's --pipe progress
  547. events to the ProgressStore so the modal's inline spinner +
  548. toast can show "Generating G-code (75%)" for that preview as
  549. well.
  550. ``arrange`` / ``orient`` mean the same as on
  551. ``slice_with_profiles``: they are CLI actions applied to the loaded
  552. geometry, independent of where the print config came from. Both
  553. paths accept them so a user's per-slice choice survives the
  554. embedded-settings route and the segfault fallback — the filament-
  555. discovery preview leaves them off, since moving objects there
  556. would change nothing about which slots the plate consumes.
  557. """
  558. files = {
  559. "file": (model_filename, model_bytes, _guess_model_content_type(model_filename)),
  560. }
  561. data: dict[str, str] = {}
  562. if plate is not None:
  563. data["plate"] = str(plate)
  564. if export_3mf:
  565. data["exportType"] = "3mf"
  566. _add_layout_flags(data, arrange=arrange, orient=orient)
  567. if request_id is not None:
  568. data["requestId"] = request_id
  569. # Same progress-poller wiring as slice_with_profiles. Used by the
  570. # SliceModal's preview slice (for filament discovery) AND the
  571. # embedded-settings fallback path triggered by an Orca/Bambu CLI
  572. # segfault on complex H2D models — both want to keep updating
  573. # the user's toast through the slow operation.
  574. response = await self._post_slice(files=files, data=data, request_id=request_id, on_progress=on_progress)
  575. return _handle_slice_response(response, export_3mf=export_3mf)
  576. def _add_layout_flags(data: dict[str, str], *, arrange: bool, orient: bool) -> None:
  577. """Set the sidecar's ``arrange`` / ``orient`` form fields, but only when on.
  578. The sidecar branches on ``settings.arrange !== undefined`` and forwards
  579. ``--arrange 1`` / ``--arrange 0`` accordingly — but multipart fields
  580. arrive as *strings*, and ``"false"`` is truthy in JavaScript. Sending
  581. ``"false"`` would therefore turn the flag ON. So an off flag is
  582. expressed by omitting the field entirely, which also keeps the wire
  583. payload of default-off callers byte-identical to before these
  584. parameters existed.
  585. """
  586. if arrange:
  587. data["arrange"] = "true"
  588. if orient:
  589. data["orient"] = "true"
  590. def _safe_int(value: str | None) -> int:
  591. if not value:
  592. return 0
  593. try:
  594. return int(float(value))
  595. except (TypeError, ValueError):
  596. return 0
  597. def _safe_float(value: str | None) -> float:
  598. if not value:
  599. return 0.0
  600. try:
  601. return float(value)
  602. except (TypeError, ValueError):
  603. return 0.0