slicer_api.py 37 KB

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