slicer_api.py 30 KB

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