Skip to content

Open-source manufacturing ERP, MES and QMS. Quoting, MRP, inventory, shop floor, quality and lot/serial traceability on one Postgres schema, with a REST API and MCP server. Self-host or use Carbon Cloud.

feat(cad): Rust assembler CAD pipeline — eager optimize, raw compaction, progressive viewer (#1148)

Sid1cce52f44aac
diff --git a/.ai/lessons.md b/.ai/lessons.md
index 66123ada61..df0629ee31 100644
--- a/.ai/lessons.md
+++ b/.ai/lessons.md
@@ -319,6 +319,25 @@ Format: `Context → Problem → Rule → Applies to`
**Applies to:** any change to `packages/database/supabase/functions/lib/seed.data.ts` per-company templates; `seed-company/index.ts`, `seed-dev.ts`.
+## meshopt vertex codec requires a stride that is a multiple of 4 — i16 VEC3 normals break it
+
+**Context:** `crates/optimize` quantizes normals to i16 (SHORT, normalized) to shrink the optimised GLB, encoding each attribute as its own `EXT_meshopt_compression` vertex buffer. An i16 VEC3 normal is 6 bytes, so the normal view was emitted with `byteStride: 6`. The GLB reparsed and round-tripped fine through the Rust `meshopt` decoder, and all crate tests passed.
+
+**Problem:** `meshopt_encodeVertexBuffer`/`decodeVertexBuffer` require the vertex size be a **multiple of 4** (`assert(vertex_size % 4 == 0)`); the Rust binding doesn't assert in release, so it emitted a 6-byte-stride stream that only its own decoder round-trips. The spec-compliant JS `MeshoptDecoder` (three.js / `three-stdlib`) rejects it with `Malformed buffer data: -2`, so the viewer showed a black screen — and because the failure is inside the decoder, no obvious app-level error surfaced. Positions (stride 12) and indices were fine; only the 6-byte normal stream broke.
+
+**Rule:** Any attribute encoded as a meshopt vertex buffer must have a stride divisible by 4. Pad i16 VEC3 normals to i16 VEC4 (8 bytes, 4th lane `0`) — the accessor stays VEC3 (reads x,y,z; the 8-byte stride skips the pad) and the constant pad lane compresses to ~nothing. Never trust "reparses + Rust-decoder round-trips" as proof a meshopt GLB is valid; validate against the spec JS decoder (`GLTFLoader.setMeshoptDecoder`). The regression test `quantized_normals_keep_meshopt_stride_multiple_of_four` asserts every `ATTRIBUTES` view stride is `% 4 == 0`.
+
+**Applies to:** `crates/optimize/src/lib.rs` (`ViewData`, the meshopt assemble path); any new quantized attribute type added to the optimiser; the `@carbon/viewer` `useAssembly` loader that consumes these GLBs.
+
+## Large text `.gltf` with an embedded base64 buffer can't be serde-parsed bounded — stream it into a GLB
+
+**Context:** The assembler optimises uploaded models. Text `.gltf` (the Onshape export shape) carries its single geometry buffer as a base64 `data:` URI. `optimize_gltf` did `serde_json::from_slice(gltf_bytes)` then base64-decoded the URI. GLB (`optimize_glb`) was already bounded — its BIN chunk is a `&[u8]` slice into the mmap.
+
+**Problem:** For a 1.73 GB `.gltf`, serde materialises the base64 as an owned ~1.73 GB `String`, then base64-decode allocates ~1.3 GB more — both live at once → ~3 GB peak. mmap doesn't help because serde copies the string out of the mapped bytes. The assembler failed with "source file exceeds the size limit" (a separate cap) and, once that was lifted, was on track to OOM on parse.
+
+**Rule:** Don't serde-parse a glTF whose buffer is a giant base64 data URI. Repack `.gltf` → `.glb` first with a **streaming** base64 decode: walk the JSON with `struson` (`transfer_to` copies the small structural fields verbatim, dropping the buffer's `uri`), then `next_string_reader()` the base64 value through `base64::read::DecoderReader` straight into the GLB BIN chunk on disk. Then mmap the `.glb` and use the already-bounded `optimize_glb` path — geometry never heaps. Verify decoded length == the buffer's declared `byteLength` (fail loud, never emit a corrupt GLB). `crates/optimize::gltf_to_glb` + `apps/assembler` `load_source` (`Format::Gltf` → repacked temp `.glb` → `Src::MappedTemp`).
+
+**Applies to:** `crates/optimize/src/lib.rs` (`gltf_to_glb`; `optimize_gltf` was removed), `apps/assembler/src/actions/optimize.rs` (`load_source`, `run_optimize` — every source is GLB now); any new large-text-JSON asset with an embedded base64 blob.
## Raw-SQL item fixtures break type-specific UI — Material items need a companion `material` row keyed by readableId
**Context:** Posting-flow verification created a type-`Material` item (RM-STEEL) with a raw `INSERT INTO "item"`. Interceptors auto-created `itemCost`/`itemReplenishment`/etc., so purchasing and posting worked. Later, selecting that material on a part's BOM (`/x/part/{id}/details?materialId=…`) crashed the whole page with "Not Found".
diff --git a/.ai/plans/2026-07-15-assembler-deployment-code.md b/.ai/plans/2026-07-15-assembler-deployment-code.md
new file mode 100644
index 0000000000..50891d1fd0
--- /dev/null
+++ b/.ai/plans/2026-07-15-assembler-deployment-code.md
@@ -0,0 +1,210 @@
+# Plan: Assembler code for ECS-service-default (Lambda as optional cost-mode)
+
+Date: 2026-07-15 (revised)
+Spec: `.ai/specs/2026-07-15-assembler-deployment.md`
+Scope: **code only** — Rust assembler + `@carbon/jobs` + Dockerfile. IaC (ECS
+service, ALB, autoscaling, VPC, SST/CI) is a downstream handoff.
+
+## Pivot (Sid, 2026-07-15)
+
+**Run the assembler as a standing ECS service** (the primary), async submit→poll
+over HTTP behind a load balancer. **Lambda stays available as an optional
+cost-mode** (scale-to-zero) if idle cost ever bites — but it is no longer the
+default. This **diverges from the spec's Lambda-default stance**; the spec needs a
+changelog update to record the flip (noted in Tasks).
+
+### Why this is *less* code, not more
+
+The assembler is **already a standing async HTTP service** and its job store is
+**already multi-replica-safe**:
+
+- `apps/assembler/src/jobs.rs` — `Backend::Redis` keeps job **status + pointers** in
+ Redis, and holds the pending late-mint artifact bytes in Redis under a short TTL
+ **"so ANY replica's poll can drain it"** (its own doc comment). `Backend::Memory`
+ is process-local (single-process/dev).
+- So with `ASSEMBLER_REDIS_URL` set, N replicas behind a round-robin LB Just Work:
+ submit lands on replica A, the poll can be served by replica B (status from Redis,
+ pending bytes from Redis). No sticky sessions, no refactor.
+- `packages/jobs/.../assembler-client.ts` already does submit→poll against
+ `ASSEMBLER_SERVICE_URL` with `internalizeStorageUrl` (no-op in prod). Pointing that
+ URL at the ECS load balancer is the whole integration change.
+
+The big sync/`run-job`/router refactor from the earlier draft was **only for Lambda**.
+It moves to an **optional** workstream, gated on cost.
+
+## Verified current state
+
+- `main.rs` — axum `/v1/{convert,optimize,plan}` (submit → 202), `/v1/jobs/:id`
+ (long-poll, drains late-mint via `X-Carbon-Upload-Urls`), `/v1/cache/invalidate`,
+ `/health`, `/v1` discovery. `main()` → tokio runtime → `serve()`.
+- `config.rs` — `max_concurrency` (semaphore), `shutdown_grace` (default 600 s),
+ `max_source_bytes` (0 = unlimited, set earlier), `redis_url` (Redis when set +
+ reachable, else Memory), TTLs, URL/SSRF policy (`require_https`/`verify_tls` off
+ under `ASSEMBLER_DEV_MODE`).
+- `actions/optimize.rs` — inline `run_optimize` (streaming glTF→GLB repack done;
+ bounded memory), a **size** ladder gate (`cannot_fit_budget`).
+- `Dockerfile` — static OCCT+Draco, `EXPOSE 8000`, `/health`, `USER assembler`.
+
+## Workstream A — ECS-service readiness (the real code work; small)
+
+- [ ] **Redis is the prod default.** No code change (env: `ASSEMBLER_REDIS_URL`
+ set). Add a **boot log line** that states the backend (`Redis`/`Memory`) and,
+ on Redis, **warn loudly if unset in a multi-replica context** — a Memory
+ backend behind an LB with >1 task silently breaks cross-replica polls. Confirm
+ `existing_active` / `set_pending` / late-mint all round-trip on Redis (they do
+ by design; add an integration test against a local redis).
+- [ ] **Graceful shutdown / SIGTERM drain.** Verify `serve()` installs a shutdown
+ signal handler (SIGTERM/SIGINT) with `axum::serve(...).with_graceful_shutdown`
+ that (a) stops accepting new work, (b) waits up to `shutdown_grace` for
+ in-flight jobs, then exits. **If not wired, add it.** This is what makes
+ rolling deploys + scale-in / (later) Spot drains lossless. Align
+ `stopTimeout` (IaC) with `shutdown_grace`.
+- [ ] **Concurrency / backpressure.** Confirm the `max_concurrency` semaphore returns
+ **429 + `Retry-After`** when full (so the LB/autoscaler sheds instead of OOM).
+ Default `max_concurrency` should track the task's vCPU (OCCT is CPU-bound);
+ document the `vCPU → max_concurrency` guidance.
+- [ ] **Autoscaling signal.** Prefer **CPU target-tracking** (no code). If queue-depth
+ scaling is wanted later, expose in-flight + pending counts on `/v1` discovery
+ (cheap) for a custom CloudWatch metric — optional, deferred.
+- [ ] **Health vs readiness.** `/health` exists (liveness). Confirm it returns
+ healthy only once the server is actually serving (post-bind); that doubles as
+ the LB target-group health check. A separate readiness gate is unnecessary
+ (stateless workers).
+
+## Workstream B — Per-job robustness / bounding (applies to any runtime)
+
+- [ ] **Memory bounding** — the streaming glTF→GLB repack (done) keeps geometry in an
+ mmap'd `/tmp` file off-heap. Confirm the optimiser working set fits the task's
+ RAM (4 vCPU / 16 GB tier); document the practical max input. jemalloc on linux
+ already curbs fragmentation.
+- [ ] **`/tmp` discipline** — temps (download + repacked glb) under `std::env::
+ temp_dir()`; prompt `remove_file` on done/error (present). On ECS the container
+ FS is ephemeral + sized by task storage — set the ephemeral/`/tmp` size in the
+ task-def (IaC) to fit `raw + repacked + output`.
+- [ ] **Time/size gates** — the size ladder exists. A **wall-clock budget** is
+ **not required** for an ECS service (no 15-min cap) — a long job just runs. Keep
+ it **optional**, only wired if the Lambda cost-mode (Workstream C) is enabled.
+- [ ] **SSRF/auth for prod** — `ASSEMBLER_ALLOWED_URL_HOSTS` set, `ASSEMBLER_DEV_MODE`
+ unset (https + TLS verify + private-IP default-deny — wired), bearer on every
+ non-`/health` route (present).
+
+## Workstream C — Optional Lambda cost-mode (deferred; only if idle cost bites)
+
+Everything from the earlier draft, kept but **not on the critical path**:
+
+- [ ] Sync execution via `X-Carbon-Sync: 1` + request-carried `upload_url` (inline
+ run + upload + return JSON), the `run-job` CLI (arg-dispatch in `main()`),
+ the **wall-clock time-budget gate** (the 900 s fit), Redis-off-on-Lambda, LWA
+ extension in the Dockerfile, and the TS **router** (size pre-route → Lambda
+ invoke-and-await → fallback to the ECS service).
+- [ ] The ECS **service** (Workstream A) is the fallback target for Lambda overflow —
+ no separate one-shot RunTask path needed once a standing service exists (a
+ simpler topology than the spec's Lambda+one-shot-ECS).
+
+Full detail preserved in the spec (`2026-07-15-assembler-deployment.md` P1/§Design);
+implement only when cost forces scale-to-zero.
+
+## Workstream D — Dockerfile / image
+
+- [ ] Confirm the standing-service image is complete: `EXPOSE 8000`, `/health`,
+ non-root, static OCCT/Draco, sane default `CMD` = the HTTP server. No LWA needed
+ for the ECS service (LWA is added only under Workstream C for Lambda).
+- [ ] `ASSEMBLER_BIND=0.0.0.0:8000` in the container so the LB/target group reaches it
+ (dev binds `127.0.0.1`).
+
+## Workstream E — TS job layer (minimal)
+
+- [ ] **No refactor.** Keep `submitAssemblerJob` + `pollAssemblerJobOnce`. The only
+ prod wiring: `ASSEMBLER_SERVICE_URL` = the ECS load-balancer URL,
+ `ASSEMBLER_SERVICE_API_KEY` = the bearer (both already in `@carbon/env`).
+ `internalizeStorageUrl` no-ops in prod. `model-optimize`/`assembly-convert`/
+ `assembly-plan` are unchanged.
+- [ ] (Only if Workstream C lands) add the `invokeAssembler` router.
+
+## Workstream G — Inngest job-layer hardening (for a standing service)
+
+A standing service **restarts on every deploy** and scales; the Inngest tasks must
+tolerate that. Grounded in the current code.
+
+- [ ] **Fix retry classification (bug).** `assembler-client.ts::submitAssemblerJob`
+ throws `NonRetriableError` on **every** non-429 status, so a **5xx during a
+ rolling deploy** fails the job permanently. Split it:
+ - **4xx** (bad input / permanent reject) → `NonRetriableError` (fail fast). ✓
+ - **5xx / connection refused / timeout** (outage / deploy / restart) → a **plain
+ `Error`** (retryable — Inngest retries after the service returns).
+ Shared client → fixes `model-optimize` + `assembly-convert` + `assembly-plan`
+ at once. Mirror in `pollAssemblerJobOnce` (a transient poll 5xx should retry,
+ not fail — it already throws a plain `Error`; keep it that way).
+- [ ] **Raise retries for deploy resilience.** `model-optimize` is `retries: 2`; a
+ rolling deploy can outlast 2 exponential backoffs. Bump to ~4–5 (and audit
+ convert/plan) so a job survives a deploy window. Idempotent by `jobId`
+ (`optimize-${modelUploadId}` + the assembler's `existing_active` + declared-hash
+ result cache), so extra retries just re-attach / hit the cache — never
+ double-compute.
+- [ ] **Align the wait budget with uncapped ECS jobs.** `MAX_OPTIMIZE_WAIT_MS = 15
+ min` was sized to the (old) Lambda-ish ceiling. On a standing service there is
+ **no cap** — a big job (e.g. the 1.73 GB glTF) can exceed 15 min, at which point
+ the Inngest poll loop **gives up while the service is still working and
+ uploads the artifact anyway** → row goes `Failed` despite a good GLB (state
+ mismatch). Raise `MAX_OPTIMIZE_WAIT_MS` to the real max (≈ `assembly-plan`'s 40
+ min, or derive from size); the Inngest budget is now the effective cap, so make
+ it generous. Audit `assembly-convert` similarly (`assembly-plan` already 40 min).
+- [ ] **Align concurrency with the service's capacity.** Inngest `model-optimize`
+ concurrency is `[{limit:4},{company:2}]`; the assembler caps in-flight via its
+ `max_concurrency` semaphore (per replica). Set Inngest global concurrency ≈
+ `replicas × max_concurrency` so it doesn't 429-storm a single replica (the
+ `BUSY_RETRIES` + `Retry-After` backoff is the safety net, but tuning avoids the
+ churn). Document the relationship; it's a deploy-time number.
+- [ ] **Dedup rapid re-triggers (optional).** `model-optimize` fires from several
+ call sites (upload, both drag routes, Part/Tool insert, the Retry route). The
+ assembler dedups server-side (`Idempotency-Key`), but two near-simultaneous
+ triggers still spawn two function runs that both attach + both persist. Consider
+ an Inngest `idempotency: "event.data.modelUploadId"` (windowed) to collapse them.
+- [ ] **Terminal-failure row status is already right** — `model-optimize` `onFailure`
+ → `optimizeStatus: "Failed"`, `assembly-plan` `onFailure` → `Failed`. Confirm
+ `assembly-convert` does the same so the viewer's Retry surfaces on every path.
+
+## Workstream F — Tests & verification
+
+- [ ] Rust: an integration test of the Redis backend cross-replica invariant —
+ `set_pending` on one `JobStore`, poll/finalize from a second `JobStore` sharing
+ the same redis (proves multi-replica polling). A graceful-shutdown test
+ (SIGTERM mid-job → in-flight completes, no new accepts).
+- [ ] `cargo test -p assembler`; image builds; run the container with a local redis +
+ 2 replicas behind a tiny round-robin proxy → submit on one, poll on the other →
+ success (the horizontal-scale proof).
+- [ ] TS: a `submitAssemblerJob` unit test asserting **5xx / connection error →
+ retryable throw**, **4xx → `NonRetriableError`** (the deploy-resilience fix).
+ Path still green (`pnpm --filter @carbon/jobs typecheck` + `test`).
+
+## Out of scope (downstream IaC)
+
+ECS **service** definition (desired count, rolling deploy), ALB + target group +
+health check, service-autoscaling policy (CPU target-tracking), VPC/subnets/SG, the
+Redis the service points at (existing `@carbon/kv` redis or an ElastiCache), SST/CI,
+GovCloud fan-out, ECR repos. This plan produces the **code + image** those consume.
+
+## Sequencing
+
+1. **A + B + D + E + G** — make the standing service production-solid (Redis-default
+ log, graceful drain, 429 backpressure, bind `0.0.0.0`, cross-replica test) **and**
+ the Inngest layer deploy-resilient (5xx-retryable, wait budget, retries). Small.
+ The retry-classification fix (G) is worth doing **now regardless of deployment** —
+ it's a latent bug the moment the dev/prod service ever restarts mid-job.
+2. Hand to IaC for the ECS service + ALB + autoscaling.
+3. **C (Lambda cost-mode)** — only if/when idle cost justifies the sync refactor.
+
+## Decisions (locked)
+
+- **Primary = standing ECS service**, async submit→poll, multi-replica via the
+ existing Redis job store. **Lambda = optional cost-mode**, deferred.
+- Update the deployment **spec's changelog** to record this flip from Lambda-default.
+
+## Risks
+
+| Risk | Mitigation |
+|---|---|
+| Memory backend behind an LB with >1 task → cross-replica poll misses | Redis is the prod default + a loud boot warn when Memory + scaled; cross-replica integration test |
+| Graceful drain not wired → rolling deploys drop in-flight jobs | verify/add `with_graceful_shutdown` + `shutdown_grace`; align `stopTimeout` |
+| Standing service = non-zero idle cost | accepted trade for simplicity; Lambda cost-mode (Workstream C) is the escape hatch |
+| Long/huge job on a small task → OOM | size the task tier (4 vCPU/16 GB); streaming repack (done) bounds memory; 429 backpressure sheds overload |
diff --git a/.ai/plans/2026-07-15-assembler-deployment.md b/.ai/plans/2026-07-15-assembler-deployment.md
new file mode 100644
index 0000000000..b421a601db
--- /dev/null
+++ b/.ai/plans/2026-07-15-assembler-deployment.md
@@ -0,0 +1,156 @@
+# Plan — Assembler Deployment (Lambda-default + ECS-Spot service overflow)
+
+Spec: `.ai/specs/2026-07-15-assembler-deployment.md`
+Runbook: `.ai/runs/2026-07-15-assembler-deployment.md` (create on execute)
+
+**Model (locked):** one image, two runtimes, **same default HTTP entrypoint**.
+**Lambda** (container image + LWA, **synchronous**) is the default; a **long-running
+ECS Fargate Spot _service_** (default-off, `desiredCount 0`, async submit→poll) is the
+overflow for jobs past Lambda's 15-min cap. **One shared deployment per environment**
+— commercial (Vercel) + GovCloud/ITAR — **NOT per-workspace** (Sid, 2026-07-15).
+Overflow model changed RunTask → service (Sid, 2026-07-17).
+
+**Gates:**
+- P1 (Lambda **sync handler** + router) — ✅ go-ahead granted + implemented (Sid
+ reviewed the spec, 2026-07-17). Default-off, so the live path is unchanged until P2.
+- P2+ (prod deploy) — needs AWS account/region + hostnames/certs; run by a human
+ (no creds in-session, no prod deploy without approval).
+
+Legend: `[ ]` todo · verify = command + expected.
+
+---
+
+## P0 — Image is Lambda- and ECS-runnable (decision-free code)
+
+- [ ] **T0.1 Create ECR repos out-of-band** — `carbon/assembler` + `carbon/occt` in
+ the target account/region (console/Terraform; nothing in-repo creates them).
+ *Verify:* `aws ecr describe-repositories --repository-names carbon/assembler carbon/occt`.
+- [x] **T0.2 CI: build + push the OCCT base** — new job (path-filter
+ `apps/assembler/occt.Dockerfile` or `workflow_dispatch`) builds it →
+ `carbon/occt:8.0.0-p1` → ECR. File: `.github/workflows/deploy.yml`.
+ *Verify:* image tag present in ECR.
+- [x] **T0.3 Dockerfile: add the Lambda Web Adapter** — in the runtime stage of
+ `apps/assembler/Dockerfile`:
+ `COPY --from=public.ecr.aws/awsguru/aws-lambda-adapter:0.9.1 /lambda-adapter /opt/extensions/lambda-adapter`
+ and `ENV AWS_LWA_PORT=8000` (LWA defaults 8080; assembler binds 8000).
+ *Verify:* `docker build -f apps/assembler/Dockerfile --build-arg OCCT_IMAGE=carbon-occt:8.0.0-p1 -t asm .` builds; `docker run -p 8000:8000 asm` → `curl localhost:8000/health` = `{"ok":true,...}`.
+- [x] **T0.4 Add a `run-job` CLI entrypoint** — `apps/assembler/src/main.rs`: if
+ `argv[1] == "run-job"`, read a job spec, spawn the action, `run_to_completion`,
+ print terminal JSON, exit. **Note (2026-07-17):** now that overflow is a standing
+ service, this CLI is **not** on either production path — retained only as an
+ optional batch/manual entrypoint. `run_to_completion` is reused by the P1 Lambda
+ sync handler. *Verify:* `assembler run-job '<spec>'` → artifact lands, exit 0.
+- [x] **T0.5 CI: build + push `carbon/assembler:${sha}`** — `docker/build-push-action`
+ (`context: .`, `file: apps/assembler/Dockerfile`, `--build-arg
+ OCCT_IMAGE=<ecr>/carbon/occt:8.0.0-p1`), **Trivy scan**, tags `:${sha}` + `:latest`.
+ Add `apps/assembler/**`,`crates/**` to `paths`. File: `.github/workflows/deploy.yml`.
+ *Verify:* push to a branch → tag in ECR, Trivy clean.
+
+## P1 — Lambda sync handler + router ⛳ needs go-ahead
+
+- [x] **T1.1 Sync HTTP branch** — `?sync` (bare/`=true`/`=1`) flag on all 4 create
+ routes: after `spawn` (or attaching to an already-running job), calls
+ `run::run_to_completion` inline with the request's `X-Carbon-Upload-Urls` and
+ returns the **terminal** `{ok, job}` (200) in one response; plain POST still
+ 202s. Added `CreateQuery`/`sync_flag`/`respond` in `apps/assembler/src/main.rs`.
+ The async `/v1/jobs` path is **unchanged** (ECS service's contract + local dev).
+ *Verify:* `cargo check`/`clippy -p assembler` clean; runtime (STEP→sync→upload)
+ verifies at deploy (needs storage + signed URLs).
+- [x] **T1.2 Time-budget gate** — optional wall-clock budget (`quality.time_budget_secs`
+ or `ASSEMBLER_OPTIMIZE_BUDGET_SECS`, default unbounded) → absolute `deadline`
+ in `optimize::spawn` (charges download+tessellation) → the ladder **skips to the
+ coarsest rung** once spent (finer skipped rungs would fail the size gate too and
+ only burn the window). Size invariant kept: no-fit still `cannot_fit_budget`.
+ Files: `apps/assembler/src/{config.rs, main.rs, actions/optimize.rs}`.
+ **convert has no ladder** (single-pass lossless — nodeIds/planner need full
+ geometry), so the gate is optimize-only. *Verify:* `cargo build`/`clippy` clean;
+ the skip-to-coarsest triggers on a real over-budget model at deploy.
+- [x] **T1.3 Job-layer router** — primitive + rewire both landed.
+ - [x] **Primitive** — `invokeAssemblerJobSync(action, jobId, body, uploadUrls)`
+ in `assembler-client.ts`: `POST /v1/{action}?sync`, upload URLs minted once up
+ front, terminal `{ok, job}` → `done`/`error`/`overflow` (runtime cut-off / busy
+ / 5xx → `overflow` for the router to fall back on).
+ - [x] **Router** — `runAssemblerJob(step, spec)` in `assembler-client.ts`:
+ sync-inline (Lambda, `preferSync` default) → on `overflow` re-dispatch async to
+ `ASSEMBLER_ECS_SERVICE_URL` (or fail→degrade if unset); else async submit→poll.
+ `submitAssemblerJob`/`pollAssemblerJobOnce`/`invokeAssemblerJobSync` gained a
+ `baseUrl?` override; new env `ASSEMBLER_ECS_SERVICE_URL` + `ASSEMBLER_SYNC_ENABLED`
+ (default false) in `@carbon/env`.
+ - [x] **Callers** — `model-optimize.ts` (optimize + compact) and
+ `assembly-convert.ts` routed through `runAssemblerJob`. **`assembly-plan.ts`
+ stays async by design** (routinely ~40 min > Lambda's 15-min cap; bespoke
+ `failJob`/inline-plan/re-motion logic) — it's the long-running case the ECS
+ service exists for.
+ **Default-off ⇒ zero behavior change**: with `ASSEMBLER_SYNC_ENABLED` unset,
+ every path is the current async submit→poll on the default base.
+ *Verify:* `@carbon/env` + `@carbon/jobs` typecheck green; biome clean.
+
+## P2 — Lambda (commercial / standalone) ⛳ needs AWS account/region + hostname
+
+> **Scaffolded** in `apps/assembler/sst.config.ts` (2026-07-17) — an **unvalidated
+> starting point**, NOT `sst deploy`-validated (no in-session AWS creds / `.sst`
+> types). Decisions are `DECISION:`-marked env placeholders. A human validates +
+> fills them at the deploy gate.
+
+- [~] **T2.1 SST/IaC: `aws.lambda.Function`** (packageType Image) — scaffolded:
+ `imageUri` = `carbon/assembler:${IMAGE_TAG}`, `memorySize: 10240`,
+ `timeout: 900`, `ephemeralStorage: 10240`, exec role (logs; ECR pull via
+ Lambda service + repo policy), shared `environment`. **Not** `sst.aws.Function`.
+ *Remaining:* deploy-validate the raw-provider shape.
+- [~] **T2.2 `aws.lambda.FunctionUrl`** — scaffolded `authorizationType: "NONE"`
+ (in-app bearer). *Remaining:* DECISION NONE vs `AWS_IAM`; hostname/cert/DNS.
+- [~] **T2.3 CI deploy step** — scaffolded as a **manual-only** `deploy` job in
+ `.github/workflows/assembler.yml` (gated on the `deploy` dispatch input; never
+ auto-fires on a main push). AWS creds + Pulumi 3.212.0 + `working-directory:
+ apps/assembler`, `IMAGE_TAG=${sha}`. The `sst deploy` command is a fail-loud
+ `exit 1` stub. *Remaining:* wire the sst toolchain for the standalone app + fill
+ the DECISION secrets, then replace the stub + (optionally) auto-run on main.
+- [ ] **T2.4 Consumer env** — commercial ERP/MES + Vercel get `ASSEMBLER_SERVICE_URL`
+ (Function URL) + `ASSEMBLER_SERVICE_API_KEY` + `ASSEMBLER_SYNC_ENABLED=true`.
+ *Verify (P2):* `curl …/health` 200; no bearer → 401; STEP fixture end-to-end.
+
+## P3 — ECS Spot service (default-off) ⛳ needs size-route threshold
+
+- [~] **T3.1 Cluster + long-running service** — scaffolded in the same
+ `sst.config.ts` behind `ASSEMBLER_ECS_ENABLED`: `sst.aws.Vpc` (no-NAT public
+ subnet) + `sst.aws.Cluster` + `addService` (4 vCPU/16 GB, `capacity: "spot"`,
+ ALB on `/health` port 8000, `scaling.min`≥1 when deployed). *Remaining:*
+ deploy-validate SST v3 `capacity`/`Vpc nat` options; hostname/cert.
+- [ ] **T3.2 Point the router at the service** — set `ASSEMBLER_ECS_SERVICE_URL` to
+ the ALB URL; the router's overflow branch already uses it (no RunTask code).
+ Enable by setting `ASSEMBLER_ECS_ENABLED=true`. *Verify (P3):* enabled → an
+ over-threshold / overflowed job routes to the service, completes (no 15-min
+ cap); induced Spot stop → service reschedules + Inngest retry (idempotent).
+ Disabled → job degrades, $0 billing.
+
+## P4 — GovCloud (shared, not per-workspace) ⛳ needs ITAR account
+
+- [ ] **T4.1** Replicate the P2/P3 stack once in the GovCloud account/region (Lambda +
+ default-off ECS-Spot service). No fan-out, no `workspaces` columns.
+- [ ] **T4.2** GovCloud ERP/MES get the GovCloud Function URL + key (single value).
+ *Verify (P4):* health + bearer + STEP end-to-end in GovCloud;
+ `assembler.itar.carbon.ms` resolves.
+
+---
+
+## Sequencing
+
+P0 → P1 (⛳) → P2 → P3, then P4. P0 is safe to start now. P1 is the crux (go-ahead).
+P2–P4 are IaC + prod, human-triggered at the approval gate.
+
+## Rollback (each deploy phase)
+
+Lambda: roll the alias/version back or `update-function-code` to prior `:sha`.
+ECS service: roll to the prior task-def revision, or `desiredCount 0` to disable.
+Consumers degrade to the poster tier — no data loss.
+
+## Open decisions for the approval gate
+
+- AWS account IDs + regions (commercial + GovCloud) and the hostnames + ACM certs
+ (Lambda Function URL + the service ALB).
+- Size-route threshold (Lambda→ECS service), e.g. ≥ 150 MB source or an estimated-tri
+ budget.
+- Lambda Function URL auth: in-app bearer (auth NONE) vs `AWS_IAM`.
+- ECS service task size (default 4 vCPU/16 GB) + `scaling` min/max; service ALB
+ internal vs public+bearer.
+- When to first enable the service (default-off until a real overflow complaint).
diff --git a/.ai/plans/2026-07-15-gltf-glb-streaming-repack.md b/.ai/plans/2026-07-15-gltf-glb-streaming-repack.md
new file mode 100644
index 0000000000..5243f0cfeb
--- /dev/null
+++ b/.ai/plans/2026-07-15-gltf-glb-streaming-repack.md
@@ -0,0 +1,179 @@
+# Plan: Streaming glTF→GLB repack (bounded-memory optimize for large text glTF)
+
+Date: 2026-07-15
+Area: `apps/assembler`, `crates/optimize` (Rust)
+Owner: assembler CAD pipeline
+
+## Problem
+
+A multi-GB **text `.gltf`** (Onshape export shape: single buffer as a base64
+data URI) OOMs / spikes the assembler during optimise. The 1.73 GB upload now
+downloads fine (internal-URL fix + source-size limit disabled), but the parse is
+not bounded.
+
+## Root cause (verified)
+
+`crates/optimize/src/lib.rs::optimize_gltf` (L155):
+
+```rust
+let mut root: json::Root = serde_json::from_slice(gltf_bytes) // materialises the
+ ... // ~1.73 GB base64 String
+let bin = base64::...STANDARD.decode(&uri.as_bytes()[comma+1..]) // + ~1.3 GB decoded Vec
+```
+
+serde owns the entire base64 data-URI as a `String`, then base64-decode allocates
+the geometry `Vec` — both live at once → **~3 GB peak** (the code comments on the
+"~1.3x base64 string").
+
+By contrast `optimize_glb` (L141) is **already bounded**: `Glb::from_slice` over
+the mmap gives `bin` as a **`&[u8]` slice into the mmap** — geometry stays on disk,
+never heaps. The assembler already mmaps glTF/GLB sources
+(`apps/assembler/src/actions/optimize.rs::load_source`, L294-300).
+
+## Design
+
+**Repack text `.gltf` → `.glb` with a streaming base64 decode, then reuse the
+already-bounded GLB path.** No general JSON-in-RAM parse; the only large field
+(the buffer's base64 URI) is streamed byte→byte into the GLB BIN chunk on disk.
+
+Two-pass over the mmap'd source (file-backed, second pass is page-cache-cheap):
+
+- **Pass 1** — walk the JSON with `struson`, copying every top-level member
+ **verbatim** via `JsonReader::transfer_to(writer)` **except** `buffers`, which is
+ rebuilt dropping each buffer's `uri` (GLB embeds the buffer, so it carries no
+ URI). Output: a small in-RAM GLB-ready JSON `Vec` + the buffer's `byteLength`.
+ Everything transferred is small (accessors/bufferViews/meshes/…); the base64 is
+ never materialised.
+- **Assemble** — write the GLB header + JSON chunk to `out`, then the BIN chunk
+ header. JSON size and `byteLength` are both known after Pass 1, so `out` needs no
+ seek (write-only).
+- **Pass 2** — walk again to `buffers[0].uri`, take `JsonReader::next_string_reader`
+ (streams the string, never buffers it), consume the `data:…;base64,` prefix up to
+ the first `,`, wrap the remainder in `base64::read::DecoderReader` (decodes on
+ read), and `io::copy` it into `out` (the BIN payload). Pad to 4 bytes with `0x00`.
+
+Peak memory = small structural JSON + the optimiser's own working set. The 1.3 GB
+geometry lives on disk in the temp `.glb`, mmap'd, and `optimize_glb` reads it as a
+borrowed slice — never heaped.
+
+### Why struson + base64 DecoderReader
+
+- `struson::reader::JsonReader::next_string_reader() -> impl Read` — streams a
+ string value without materialising it (the crux). Also `transfer_to(writer)`
+ (copy small values verbatim), forward walk (`begin_object`/`next_name`/`has_next`/
+ `end_object`, `begin_array`/`end_array`), `skip_value`. `JsonStreamReader::new(R:
+ Read)` over `Cursor(&mmap)`. `JsonStreamWriter` for the rewritten JSON.
+- `base64::read::DecoderReader` (base64 0.22, already a dep) — `Read` adapter that
+ base64-decodes incrementally. `io::copy(decoder, out)` streams, bounded.
+
+### GLB container format (write correctly)
+
+- Header (12 B): `b"glTF"` + `2u32_le` (version) + `total_len u32_le`.
+- Chunk: `chunkLen u32_le` + `chunkType(4)` + `chunkData[chunkLen]`. `chunkLen`
+ **includes** trailing padding; data is 4-byte aligned.
+- JSON chunk: type `b"JSON"`, pad with `0x20` (spaces).
+- BIN chunk: type `b"BIN\0"` (`[0x42,0x49,0x4E,0x00]`), pad with `0x00`.
+- `total_len = 12 + 8 + json_padded + 8 + bin_padded`.
+- `bufferView.byteOffset` are buffer-relative → unchanged (decoded bytes are
+ byte-identical to the original buffer); offsets stay valid.
+
+## Tasks
+
+### 1. Dependencies
+- [ ] `crates/optimize/Cargo.toml` — add `struson = "0.6"`.
+- [ ] `apps/assembler/Cargo.toml` — add `tempfile = "3"` (temp `.glb` to mmap).
+ (Confirm the source-download temp path can't be reused for the repacked glb;
+ it holds the raw `.gltf`. A sibling temp is needed.)
+
+### 2. `crates/optimize/src/lib.rs` — `gltf_to_glb`
+- [ ] Add `pub fn gltf_to_glb(gltf: &[u8], out: &mut impl std::io::Write) -> Result<(), OptimizeError>`.
+- [ ] Pass 1: `JsonStreamReader::new(Cursor::new(gltf))` + `JsonStreamWriter` into a
+ `Vec<u8>`. Walk the root object:
+ - member `"buffers"` → `begin_array`; for each buffer object copy every field via
+ `writer.name(n)? + reader.transfer_to(writer)?` **except** `"uri"` (call
+ `reader.skip_value()` / consume it — do NOT transfer). Capture `byteLength` of
+ buffer 0.
+ - any other member → `writer.name(n)? + reader.transfer_to(writer)?`.
+ - Guards (fail loud): exactly one buffer; buffer 0 has a `uri` starting `data:`
+ with `;base64,`. External `.bin` (uri not `data:`) or >1 buffer → `OptimizeError`
+ ("external .bin unsupported" / "multi-buffer glTF unsupported").
+- [ ] Compute `json_padded` (pad to 4 with `0x20`), `bin_len = byteLength`,
+ `bin_padded` (pad to 4 with `0x00`), `total`.
+- [ ] Write header + JSON chunk (bytes + space pad) + BIN chunk header to `out`.
+- [ ] Pass 2: fresh `JsonStreamReader` over `gltf`; navigate root→`buffers`→array→
+ buffer 0→`"uri"`; `next_string_reader()`; read bytes until first `,`
+ (prefix); wrap the rest in `base64::read::DecoderReader::new(reader,
+ &base64::engine::general_purpose::STANDARD)`; `let n = io::copy(&mut dec,
+ out)?`; assert `n == byteLength` (else `OptimizeError` — never emit a corrupt
+ GLB); write `bin_padded - bin_len` zero bytes.
+- [ ] Small navigation helper to reach `buffers[0].uri` (skip other members with
+ `skip_name`/`skip_value`).
+
+### 3. `crates/optimize/src/lib.rs` — retire `optimize_gltf`
+- [ ] Remove `optimize_gltf` (superseded — all glTF now repacked to GLB upstream of
+ the optimiser). Remove/repoint any test that called it.
+
+### 4. `apps/assembler/src/actions/optimize.rs` — wire the repack
+- [ ] Split the `Format::Glb | Format::Gltf` arm of `load_source`:
+ - `Format::Glb` → mmap the source directly (unchanged).
+ - `Format::Gltf` → mmap the `.gltf`; create a sibling temp `.glb`
+ (`tempfile::NamedTempFile`); `optimize::gltf_to_glb(&gltf_mmap, &mut
+ BufWriter::new(&mut tmp))`; flush; mmap the temp `.glb`; return it.
+- [ ] `Src` must keep the temp file alive for the mmap's lifetime. Add a variant
+ (e.g. `Src::MappedTemp(memmap2::Mmap, tempfile::TempPath)`) or hold the
+ `TempPath` beside the `Mmap`; update `Src::bytes()`.
+- [ ] `run_optimize`: every `Src` is now GLB (STEP→`build_triangle_glb`,
+ STL→`stl_to_glb`, GLB→mmap, glTF→repacked). Drop the `is_glb ? optimize_glb :
+ optimize_gltf` branch → always `optimize::optimize_glb`. Remove the `is_glb`
+ probe (or keep as a debug assert).
+- [ ] Update the module doc (L3): "mmapping a GLB (text glTF is repacked to GLB via
+ a streaming base64 decode first)".
+
+### 5. Tests
+- [ ] `crates/optimize` unit test `gltf_to_glb_repacks_embedded_base64`: build a
+ tiny `.gltf` (one triangle, buffer as base64 data URI) → `gltf_to_glb` → output
+ starts `b"glTF"`, is a valid GLB, and `optimize_glb` on it succeeds with the
+ mesh intact (positions round-trip).
+- [ ] `crates/optimize` test `gltf_to_glb_rejects_external_bin` (uri not `data:` →
+ `OptimizeError`).
+- [ ] Existing assembler format/loader tests still pass (STEP/STL/GLB unaffected).
+
+### 6. Docs
+- [ ] `crates/optimize/AGENTS.md` — note glTF is repacked to GLB (streaming base64)
+ before optimise; `optimize_gltf` removed, `gltf_to_glb` added.
+- [ ] `apps/assembler/AGENTS.md` — update the load path description if it mentions
+ glTF handling.
+- [ ] `.ai/lessons.md` — add: "large text glTF base64 buffers must be streamed
+ (struson `next_string_reader` + base64 `DecoderReader`), not serde-materialised
+ — a multi-GB data URI is ~3 GB peak otherwise."
+
+### 7. Verify + roll out
+- [ ] `cargo test -p optimize` (new + existing green).
+- [ ] `cargo build --release -p assembler`.
+- [ ] Restart the assembler (it runs `cargo run --release -p assembler`; recompiles
+ on next spawn — user restarts, not me).
+- [ ] Re-fire optimise on the 1.73 GB `.gltf` (viewer Retry / the model-optimize
+ event) → assembler RSS stays bounded (structural JSON + optimiser working set,
+ not ~3 GB), job → `Success`, GLB renders.
+
+## Notes / edge cases
+
+- Single embedded buffer only (the Onshape/GLB shape). External `.bin` and
+ multi-buffer glTF are explicitly rejected (they already were).
+- Data-URI media type varies (`application/octet-stream`, `gltf-buffer`, or empty) —
+ key on the first `,`, not the media type.
+- `byteLength` mismatch vs decoded byte count → hard error (fail loud; never store a
+ corrupt GLB). Aligns with the "verify + fail loud, no pray-it-works" rule.
+- Two mmaps briefly (source `.gltf` + temp `.glb`) — both file-backed, off RSS.
+- The disabled source-size limit (`ASSEMBLER_MAX_SOURCE_MB` default 0) stays; this
+ removes the reason it OOMs, not the cap.
+- The temp `.glb` roughly doubles transient disk (raw gltf + repacked glb). Cleaned
+ when `Src`/`TempPath` drops.
+
+## Out of scope
+
+- Having the exporter/browser emit GLB directly (would remove the repack entirely) —
+ separate upstream change; this keeps `.gltf` uploads working regardless.
+- Bounding the optimiser's own per-primitive working set (a separate concern from
+ the base64 parse).
+```
diff --git a/.ai/plans/2026-07-15-step-zstd-xbf-compaction.md b/.ai/plans/2026-07-15-step-zstd-xbf-compaction.md
new file mode 100644
index 0000000000..03bbdfaca5
--- /dev/null
+++ b/.ai/plans/2026-07-15-step-zstd-xbf-compaction.md
@@ -0,0 +1,99 @@
+# Retained-raw compaction: zstd + OCCT XBF
+
+> **STATUS: implemented** (2026-07-15). Both phases landed together (D2).
+> occt-bridge `step_to_xbf`/`read_xbf` (magic `BINFILE`), converter `build_tree`
+> content-sniff + `convert_xbf`, assembler transparent-zstd `download_hashed` +
+> `Format::Xbf` + `compact` action, `model-optimize.ts` compact step. XBF↔STEP
+> parity proven (`crates/converter/tests/xbf_parity.rs`). All Rust suites +
+> jobs/utils typecheck green.
+>
+> **Revision (same day):** default compaction changed to **all optimisable
+> uploads, any size, mode `zstd`, original format preserved** (`raw.<ext>.zst`) —
+> the user wanted every STEP compacted while staying a downloadable, openable
+> file. The `file+/preview` route zstd-decompresses `.zst` on download
+> (`node:zlib`). Compact path is FLAT (`${id}.step.zst`) so `modelIdFromPath`
+> still resolves; TTL prune excludes `.zst` (compacted raws are permanent).
+> `xbf` mode remains available in the `compact` action + full xbf read path, but
+> is **not used by default** (kept for a possible future "xbf for big hidden
+> raws" optimisation — those parse the full STEP on every plan today).
+> Pending: `generate:types` (optimizedSize), `db:migrate` + assembler redeploy.
+
+**Goal:** stop hoarding fat raw STEP. After eager optimise, replace the raw with a
+compact, lossless artifact that lazy planning + reoptimise can still consume. Two
+mechanisms, both requested: (1) transparent **zstd**, (2) OCCT **XBF** (XCAF binary
+document — B-rep + assembly tree + names + colors, smaller + faster to parse than
+ASCII STEP).
+
+Retained target evolves: `raw.step` → Phase 1 `raw.step.zst` → Phase 2 `raw.xbf.zst`.
+
+Nothing downstream changes contract: every action fetches its source through
+`http::download_hashed`, so transparent zstd + an xbf loader make `.zst` / `.xbf`
+sources "just work" for optimize, convert, plan, reoptimize.
+
+---
+
+## Phase 1 — zstd (no OCCT; ships the storage win)
+
+1. **Transparent zstd input** — `apps/assembler/src/http.rs` `download_hashed`:
+ sniff the zstd magic (`28 B5 2F FD`) on the first bytes; if present, stream the
+ body through a zstd decoder into the temp file. Hash the **decompressed** bytes
+ (content-hash cache key must track true geometry, not the container). Keep the
+ decompressed-size guard on the `written` counter (compressed `content_length`
+ can't gate it). Dep: `async-compression` (tokio + zstd feature).
+
+2. **`compress` action** — new `POST /v1/compress` (register in `actions/mod.rs`,
+ advertise in `GET /v1`): streaming download → zstd (level ~19) → streaming PUT to
+ a caller-supplied dest URL. No late-mint, no RAM buffer (pre-minted dest). Typed
+ errors like the others.
+
+3. **Wire into `packages/jobs/.../tasks/model-optimize.ts`** — after `persist`
+ (optimise Success), add `step.run("compact-raw")`: mint an upload URL for
+ `${companyId}/models/${modelUploadId}/raw.step.zst`, invoke assembler `compress`
+ (source = signed raw URL, dest = that URL), then set
+ `modelUpload.modelPath = raw.step.zst` and `.remove()` the original raw `.step`
+ from `temp-staging`. Only for OCCT/large formats; skip mesh/tiny + already-`.zst`.
+
+4. **Keep the big-raw TTL prune** (`scheduled/cleanup.ts`) as the **failure**
+ safety net — models whose optimise never succeeded never get compacted. Reword
+ the comment to say so.
+
+## Phase 2 — XBF (replaces STEP as retained artifact + planner input)
+
+5. **occt-bridge** (`crates/occt-bridge/src/occt.{h,cc}`, `lib.rs`): factor the
+ doc→`Tree` walk out of `read_step`; add cxx fns:
+ - `step_to_xbf(step_path, xbf_path) -> bool` — `STEPCAFControl_Reader` → doc →
+ `BinXCAFDrivers` document-storage write.
+ - `read_xbf(xbf_path, lin, ang) -> Tree` — `BinXCAFDrivers` retrieve → same walk.
+ build.rs already links all `TK*`; confirm `TKBinXCAF`/`TKBinL`/`TKBin` present in
+ the OCCT build (add to allowlist if the toolkit scan filters them).
+
+6. **converter** (`crates/converter`): `convert_xbf(path, lin, ang)` mirroring
+ `convert_step`, calling `read_xbf`. Planner `build_tree` accepts an xbf path.
+
+7. **assembler formats** (`formats.rs`): add `Format::Xbf` (loader `Occt`, `exact`,
+ `structured`); sniff the BinXCAF header magic; extend `SUPPORTED`/`ALL`/`from_name`.
+ `load_source` + convert route `Xbf → convert_xbf`.
+
+8. **`compress` → `compact` (Phase-2 form)**: for OCCT sources produce `.xbf`
+ (occt, whole-file — not streaming) then zstd → `.xbf.zst`. `model-optimize.ts`
+ compact step requests xbf mode and sets `modelPath = raw.xbf.zst`. STEP fully
+ retired from storage post-optimise; ASCII STEP only transient pre-optimise.
+
+## Verify
+
+- **Rust**: `cargo test -p optimize -p converter -p planner`; `cargo build -p assembler`.
+ New tests: zstd roundtrip through `download_hashed`; `read_xbf` vs `read_step`
+ `Tree` parity (nodeIds + geometryHash) on the shadow corpus (reuse the
+ byte-parity harness from the geometry rewrite).
+- **TS**: `turbo run typecheck --filter=@carbon/jobs --filter=erp`.
+- **Manual**: upload STEP → optimise → raw replaced by `.xbf.zst`; viewer preview
+ ok; "Generate Steps" (plan) runs off the compacted raw; reoptimise runs.
+
+## Decisions (locked)
+
+- **D1** standalone `compact` action (streaming download → xbf → zstd → streaming
+ upload; no RAM buffer). Not folded into optimize.
+- **D2** build Phase 1 + Phase 2 together, ship as one change. Retained artifact
+ goes straight to `raw.xbf.zst` (no interim `.step.zst` shipped).
+- **D3** hash decompressed bytes in `download_hashed` so the plan cache keys on
+ geometry regardless of container.
diff --git a/.ai/research/enterprise-iac-byoc-deployment.md b/.ai/research/enterprise-iac-byoc-deployment.md
index 5899275497..501ae300bf 100644
--- a/.ai/research/enterprise-iac-byoc-deployment.md
+++ b/.ai/research/enterprise-iac-byoc-deployment.md
@@ -123,6 +123,28 @@ Open question parked with the operator work: in-cluster Postgres (CloudNativePG
Phasing matters: Phase 1 is sellable on its own ("we deploy Carbon in your account"), and each phase de-risks the next.
+## 5b. Support-access plane (NetBird) — vendor-operated connectivity
+
+Decided 2026-07-18: BYOC deployments are **vendor-operated** ("Model B") — Carbon runs upgrades and carries the pager; the customer owns the account and the data. That requires a support-access path into customer VPCs that survives enterprise security review, without ever making the overlay an app dependency.
+
+**Control plane.** Decided 2026-07-18: **NetBird Cloud** (managed), not self-hosted. Rationale: zero control-plane ops while the team is small, and the cloud-only MSP feature is purpose-built for the Model B shape — multiple customer networks under one account with per-tenant switching. The data plane is end-to-end encrypted WireGuard either way; NetBird's cloud sees coordination metadata (peers, topology, connection events), never traffic. **Customers are never NetBird users** — they only contribute *peers* via setup keys; the only humans in the system are Carbon engineers. Delete the default allow-all policy on day one; every policy explicit. Escape hatches, kept open by NetBird being open source (BSD-3): a sovereignty-demanding deal runs `supportAccess: disabled` (SSM-only support), and a later wholesale move to a self-hosted control plane is re-registering peers, not a redesign. The ITAR/GovCloud install should be treated as supportAccess-disabled from day one — a third-party control plane holding connection metadata is unlikely to clear ITAR review; SSM is the support path there.
+
+**Customer side (part of the artifact set).** Two NetBird routing-peer containers (agent, `NET_ADMIN`) — an ECS service in phase 1, an operator-managed Deployment in phase 3 — registered with a per-customer setup key minted by the Carbon control plane. They advertise only the app subnets (or narrower resources), masquerade on, and dial **out** on 443 to the NetBird endpoints (documented in the egress allowlist alongside registry + telemetry). Security groups add a second gate: routing-peer SG → specific ports only. `CarbonInstall.supportAccess: enabled|disabled` scales the peers to zero — the customer's kill switch. ITAR/air-gap installs run permanently disabled; nothing in the stack depends on the overlay. SSM Session Manager via a customer-granted narrow IAM role remains the AWS-native parallel path for shell access; NetBird provides network reach (internal ALBs, DB, dashboards). Both audited.
+
+**Isolation model.** Per customer: a NetBird Network (v0.35+) with their VPC subnets as resources — resources are invisible to any peer until a policy explicitly grants access (zero-trust default; legacy network routes bypass ACLs unless configured, so use Networks, not routes). Groups: `eng-oncall`, plus a per-customer `access-{customer}` group used as both policy source and route-distribution group. No standing memberships.
+
+**Access workflow (time-boxed).**
+1. Engineer requests access to an install in the fleet dashboard (incident/ticket reference).
+2. Approval → control plane calls the NetBird API: adds the engineer to `access-{customer}` with a TTL.
+3. Routes and policy propagate in seconds; engineer reaches the internal ALB / observability endpoints over p2p WireGuard (Carbon-hosted relay as fallback).
+4. TTL expiry removes the membership; routes vanish. NetBird activity events are the audit trail; streaming into the customer's SIEM is a later enterprise option.
+
+**Overlapping CIDRs.** Customer VPC ranges will collide (10.0.0.0/16 is everyone's default). Routes are only distributed while a grant is active, so serial access is conflict-free; simultaneous overlapping grants fall back to client-side route selection (client ≥ 0.27.4). Transparent remapping is an open upstream feature (netbird#4664) — don't design around it. Bootstrap docs should nudge customers toward distinct CIDRs when they have flexibility.
+
+**Failure surface.** If the NetBird control plane is down: established tunnels keep working, new grants fail, and the customer stack is unaffected (the overlay is never in the app path). Run management with a Postgres backend, 2 tasks, backups. Setup keys revoke per customer (blocks new registrations); existing peers removable via API.
+
+**Dogfood path.** Carbon's own staging/prod accounts are customers #0 and #1 of this exact pattern (`access-staging`, `access-prod`). The GovCloud install's SSH access migrates to routing peer + SSM once edge-function baking lands (§4b already kills the SSH sync).
+
## 6. Gaps to close (found in the audit)
| Gap | Detail | Severity for BYOC |
@@ -139,7 +161,7 @@ Phasing matters: Phase 1 is sellable on its own ("we deploy Carbon in your accou
## 7. Open questions for Brad
1. ~~Data-tier ambition~~ — resolved: the extension audit is a phase-1 prerequisite; v1 ships on RDS Multi-AZ (§4b). EC2 + EBS remains only as the fallback if the audit slips a deal timeline.
-2. Who operates Phase 1 deployments — us (managed-in-their-account, needs cross-account role from day one) or the customer (pure Terraform handoff)?
+2. ~~Who operates Phase 1 deployments~~ — resolved (2026-07-18): **vendor-operated ("Model B")** — Carbon operates installs in the customer's account; support access via the self-hosted NetBird plane (§5b) + optional customer-granted SSM role.
3. Does any near-term deal require non-AWS (Azure/GCP)? If yes, that pulls the Helm-chart question forward; if no, AWS-only v1.
4. Blue/green for the app tier: adopt native ECS blue/green with bake/rollback as the default enterprise strategy, or keep plain rolling (current SST behavior)?
5. Is Inngest self-hosted (already proven in Swarm) the standard for enterprise, or does any deal tolerate Inngest Cloud egress?
@@ -148,4 +170,7 @@ Phasing matters: Phase 1 is sellable on its own ("we deploy Carbon in your accou
- ECS blue/green (built-in, July 2025): https://aws.amazon.com/blogs/aws/accelerate-safe-software-releases-with-new-built-in-blue-green-deployments-in-amazon-ecs/ ; https://docs.aws.amazon.com/AmazonECS/latest/developerguide/deployment-type-blue-green.html ; https://www.infoq.com/news/2025/07/aws-blue-green-ecs/
- Inngest self-hosting (external Postgres/Redis): https://www.inngest.com/docs/self-hosting
+- NetBird Networks / routing peers (zero-trust resource visibility): https://docs.netbird.io/manage/networks/how-routing-peers-work
+- NetBird overlapping routes (client-side selection): https://docs.netbird.io/manage/network-routes/overlapping-routes ; transparent remap upstream: https://github.com/netbirdio/netbird/issues/4664
+- NetBird self-hosted vs cloud (single-account mode; MSP is cloud-only): https://docs.netbird.io/about-netbird/self-hosted-vs-cloud ; https://forum.netbird.io/t/multi-tenant-question-regarding-users-with-the-same-email-domain/410
- In-repo: `sst.config.ts`, `ci/src/deploy.ts`, `ci/src/migrations.ts`, `contrib/deploying/simple-docker-caddy/docker-compose.prod.yml`, `.github/workflows/{deploy,supabase,functions,inngest}.yml`, `packages/env/src/index.ts`, extension grep over `packages/database/supabase/migrations/`
diff --git a/.ai/rules/environment-configuration.md b/.ai/rules/environment-configuration.md
index 1f72b30306..c5f90c8d9d 100644
--- a/.ai/rules/environment-configuration.md
+++ b/.ai/rules/environment-configuration.md
@@ -40,8 +40,14 @@ keys listed in `getBrowserEnv()` are exposed client-side.
Template is `.env.example`.
- `.env.local` — **generated by `crbn up`** (`packages/dev/src/commands/up.ts`);
"Do not edit by hand". Holds per-worktree ports, portless `*.dev` URLs,
- dev Supabase keys, Redis/Inngest dev settings, `DEV_BYPASS_EMAIL`. Vite /
- React Router auto-load it on top of `.env`, with `.env.local` overriding.
+ dev Supabase keys, Redis/Inngest dev settings, `DEV_BYPASS_EMAIL`,
+ `ASSEMBLER_SERVICE_URL`/`_API_KEY`. Vite / React Router auto-load it on top of
+ `.env`, with `.env.local` overriding.
+- **`#force` escape hatch** — end a line in `.env` with a `#force` comment
+ (e.g. `ASSEMBLER_SERVICE_URL=https://… #force`) and `writeEnv`
+ (`packages/dev/src/env.ts`) omits that key from the generated `.env.local`,
+ so the `.env` value wins. Survives regeneration (the marker lives in `.env`,
+ which crbn never writes). Use it to point a local stack at a remote service.
- Self-hosting? The Swarm stack does **not** use a prod `.env` for secrets — it
uses Docker Swarm secrets + non-secret `contrib/deploying/simple-docker-caddy/.env`.
See [contrib-deployment-swarm.md](contrib-deployment-swarm.md).
diff --git a/.ai/specs/2026-07-15-assembler-deployment.md b/.ai/specs/2026-07-15-assembler-deployment.md
new file mode 100644
index 0000000000..6f24195a84
--- /dev/null
+++ b/.ai/specs/2026-07-15-assembler-deployment.md
@@ -0,0 +1,307 @@
+# Assembler Service Deployment — Lambda-default + ECS-Spot service overflow
+
+> Status: design → ready for implementation (approval gate before any prod deploy)
+> Author: Claude (with Sid Rathi)
+> Date: 2026-07-15
+> Supersedes: `.ai/specs/2026-07-06-geometry-service-deployment.md` (Python-era,
+> two always-on Fargate services). Facts below fact-checked against AWS/SST docs
+> (July 2026).
+
+## TLDR
+
+Run the Rust assembler **serverless by default on AWS Lambda** (container image),
+and overflow jobs too big/long for Lambda's 15-min ceiling to a **long-running ECS
+Fargate Spot _service_** (the same image, default HTTP entrypoint). **One image, two
+runtimes.** Cheapest viable option (~$0 idle, ~$10–30/mo typical), needs **no scaling
+to manage** ("don't scale it until someone complains" → the service is **config-gated,
+desiredCount 0 / not deployed by default**; Lambda handles everything until a
+complaint bumps it up), and works in **GovCloud** — one strategy for both
+environments, one **shared** deployment each (Vercel-serving commercial +
+GovCloud/ITAR), **not** per-workspace. New feature; cost floor stays at zero.
+
+The trade — **smaller than the earlier one-shot-RunTask draft**: only the **Lambda
+path** needs the async→**synchronous** refactor (Lambda freezes after the response,
+so a spawned job must run inline). The **ECS service keeps the assembler's existing
+async submit→poll** — it's a warm HTTP backend, no refactor, no `run-job` CLI on the
+hot path. The compute (`run_optimize`/`convert`) already runs inline; the Lambda
+handler drains a spawned job with `run_to_completion` (already built) instead of
+returning 202.
+
+## Verified facts (AWS/SST docs, Jul 2026)
+
+- **Lambda**: container image ≤ **10 GB**; memory ≤ **10,240 MB**; timeout **900 s
+ (15 min, hard cap — not raisable)**; `/tmp` **512 MB–10,240 MB**. In **both
+ GovCloud regions** incl. container images + cross-account ECR.
+- **AWS Lambda Web Adapter (LWA)**: an extension that proxies the Lambda invoke →
+ your existing HTTP server, no code change. **Same image runs on Lambda, Fargate,
+ EC2, local.** Copy its binary to `/opt/extensions`; **default port 8080 → set
+ `AWS_LWA_PORT=8000`** (the assembler binds 8000).
+- **Fargate Spot**: 50–70% off; **2-min interruption warning** (EventBridge +
+ SIGTERM). Use **`capacityProviderStrategy` NOT `launchType`** (they conflict).
+ `stopTimeout ≤ 120 s` for graceful drain. An **ECS _service_ on FARGATE_SPOT
+ auto-reschedules** an interrupted task to hold `desiredCount` (unlike a one-shot
+ `RunTask`); the in-flight job on the killed task is lost → the caller (Inngest)
+ retries, and steady-state capacity self-heals.
+- **SST v3**: `sst.aws.Function` does **not** accept a prebuilt container image →
+ use raw **`aws.lambda.Function` `{ packageType: "Image", imageUri }`** inside
+ `run()` (SST v3 is Pulumi-based, so raw `aws.*` resources compose fine).
+
+## Already done (Rust rewrite)
+
+- Production Dockerfile (`apps/assembler/Dockerfile`, static OCCT+Draco, `EXPOSE
+ 8000`, `/health`) + cached OCCT base (`occt.Dockerfile`).
+- Redis job store (`ASSEMBLER_REDIS_URL`, Memory|Redis) — mostly moot in sync mode,
+ kept for the result cache.
+- `ASSEMBLER_SERVICE_URL`/`_API_KEY` in `@carbon/env`, consumed by the Inngest tasks.
+
+## Design
+
+### One image, two runtimes — same entrypoint both places
+
+The single `carbon/assembler:${sha}` image (built once) runs `serve()` (the axum HTTP
+app) as its default CMD **everywhere**:
+- **On Lambda** the **LWA extension** (`COPY --from=public.ecr.aws/awsguru/aws-lambda-adapter:0.9.1 /lambda-adapter /opt/extensions/lambda-adapter` + `ENV AWS_LWA_PORT=8000`) proxies the invoke → the same HTTP server, unchanged.
+- **On the ECS service** it's just the HTTP server behind an ALB — a normal warm backend.
+
+No per-runtime CMD switch on the hot path. The `run-job` CLI (`assembler run-job
+<spec.json>`) is retained only as an **optional batch/manual entrypoint** (cron,
+one-off reprocessing) — it is **not** used by either production path now that overflow
+is a standing service. `run_to_completion` (the drain-to-terminal helper it shares) is
+reused by the Lambda sync handler below.
+
+### Runtime A — Lambda (default)
+
+- `aws.lambda.Function` `{ packageType: "Image", imageUri, memorySize: 10240,
+ timeout: 900, ephemeralStorage: 10240, architectures: ["x86_64"] }` + a **Function
+ URL** (bearer-gated) or direct SDK `Invoke`.
+- **Synchronous execution**: the HTTP handler runs the whole job in-request
+ (download → tessellate → optimize → **upload to the caller-provided signed URL**
+ → return small JSON). The GLB never transits the response (late-mint upload), so
+ the 6 MB Function-URL response cap is a non-issue.
+- The **time-budget gate** (degrade quality until it fits ~12 min, mirroring the
+ size gate) keeps ~all jobs inside 900 s.
+- Auto-scales, **$0 idle**, GovCloud-capable. Cold start ~1–3 s after first pull
+ (fine — background job).
+
+### Runtime B — ECS Fargate Spot _service_ (overflow, config-gated)
+
+- A **long-running `aws.ecs.Service`** (Fargate, FARGATE_SPOT capacity provider)
+ running the same image's default HTTP CMD, behind an **ALB** (internal, or public +
+ bearer) at a stable URL. 4 vCPU/16 GB task tier for the big-job tier.
+- **Config-gated / default-off:** `desiredCount: 0` (or the service simply not
+ deployed) until a real overflow need appears — "don't scale until someone
+ complains." When enabled it runs **≥1 warm task**; the router uses it only when
+ `ASSEMBLER_ECS_SERVICE_URL` is configured, else overflow degrades (poster tier).
+- **Native async, no CLI, no RunTask:** the warm service handles jobs through the
+ assembler's existing **submit→poll** API (`POST /v1/optimize` → 202 → `GET
+ /v1/jobs/{id}?wait`) — the Redis/in-memory job store is used as originally
+ designed. No `run-job` orchestration.
+- `stopTimeout: 110` + SIGTERM drain. On Spot interruption the **service reschedules**
+ the task to hold `desiredCount`; the in-flight job is lost → the client's poll fails
+ → **Inngest retries** (idempotent, keyed by `modelUploadId` + the declared-hash
+ result cache). Steady-state capacity self-heals.
+- No 15-min ceiling — a service task runs as long as the job needs.
+
+### Router (`packages/jobs/.../tasks/model-optimize.ts`)
+
+1. **Pre-route by size** — source > threshold (e.g. > 150 MB, or estimated tris over
+ budget) → straight to the **ECS service** (async submit→poll) if
+ `ASSEMBLER_ECS_SERVICE_URL` set, else degrade.
+2. Else → **invoke Lambda** (sync), await the result.
+3. **Fallback** — Lambda returns "timed out / too large" (or the invoke times out) →
+ re-dispatch to the ECS service (or degrade if not enabled).
+Most jobs never touch ECS; when the service is off, overflow jobs degrade rather than
+run — an explicit, cheap default.
+
+### Job-layer changes (smaller than the RunTask draft)
+
+- `assembler-client.ts`: add **`invokeLambda(spec)`** (await the sync result) for the
+ default path. **Keep** `submitAssemblerJob` + `pollAssemblerJobOnce` — the ECS
+ service is a normal async assembler endpoint, just pointed at
+ `ASSEMBLER_ECS_SERVICE_URL`. No RunTask/STOPPED-wait code.
+- `model-optimize.ts` / `assembly-convert.ts` / `assembly-plan.ts`: call the router
+ (Lambda-sync default, ECS-async overflow).
+- Assembler: add the **sync HTTP handler** (spawn + `run_to_completion` inline,
+ return) for the Lambda path. The async `/v1/jobs` API is **retained as the ECS
+ service's primary contract** (and local dev), not a fallback.
+- The only net-new is the Lambda sync handler + the router; the async path stays.
+
+### Two environments — one **shared** assembler each (NOT per-workspace)
+
+**Decision (Sid, 2026-07-15): ITAR/GovCloud is NOT per-workspace.** So there is no
+`ci/src/deploy.ts` fan-out and **no new `workspaces` columns** for the assembler —
+Brad's per-workspace design is dropped. The service holds no tenant data at rest
+(files via signed URLs, Redis job records transient), so **one shared deployment per
+environment** serves all tenants in that environment:
+- **Commercial (Vercel-serving):** one Lambda + one (default-off) ECS service +
+ cluster in the shared commercial account; Lambda Function URL public + bearer at
+ `assembler.carbon.ms`; the service (when enabled) behind an ALB at
+ `assembler-svc.carbon.ms` (or internal).
+- **GovCloud (ITAR):** the **same** hybrid, one shared deployment in the GovCloud
+ account/region; internal or public URLs + bearer. `assembler.itar.carbon.ms`.
+
+Both are deployed on their **own cadence** (not through the workspace fan-out). ERP/MES
+in each environment get `ASSEMBLER_SERVICE_URL` (that env's Function URL) +
+`ASSEMBLER_SERVICE_API_KEY` from env/secrets — a single value per environment, not
+per workspace.
+
+## SST specifics
+
+- **Lambda:** raw `new aws.lambda.Function("Assembler", { packageType: "Image",
+ imageUri: <ecr>/carbon/assembler:${IMAGE_TAG}, memorySize: 10240, timeout: 900,
+ ephemeralStorage: { size: 10240 }, environment: { variables: { ASSEMBLER_*, … } },
+ role: <exec-role with ECR + logs + s3/signed-url + redis SG> })` + a
+ `aws.lambda.FunctionUrl` (auth `NONE` → bearer-gated in-app, or `AWS_IAM`).
+ **Not** `sst.aws.Function` (no prebuilt-image support).
+- **ECS overflow:** `sst.aws.Cluster` + `sst.aws.Service` (Fargate, 4 vCPU/16 GB,
+ FARGATE_SPOT capacity provider, `scaling: { min: 0/1, max: N }`, ALB on `/health`)
+ — **default `desiredCount: 0`** / gated behind a stage flag. A small VPC (public
+ subnet + SG, **no NAT**) or reuse the GovCloud VPC. No RunTask code — the router
+ hits the service URL over HTTP.
+- **ECR repos** `carbon/assembler` + `carbon/occt` created **out-of-band** (nothing
+ in-repo auto-creates them; same as `carbon/erp`).
+
+## CI
+
+- **OCCT base** (`apps/assembler/occt.Dockerfile` → `carbon/occt:8.0.0-p1`), built +
+ pushed once (path-filtered / manual).
+- **Assembler image**: `docker/build-push-action` with `context: .`,
+ `file: apps/assembler/Dockerfile`, `--build-arg OCCT_IMAGE=<ecr>/carbon/occt:8.0.0-p1`,
+ Trivy scan, push `carbon/assembler:${sha}`. Add `apps/assembler/**`,`crates/**` to
+ `paths`.
+- **Deploy**: update the Lambda image (`aws lambda update-function-code
+ --image-uri …:${sha}`) + (when the service is enabled) a new task-def revision +
+ service update. **One shared deployment per environment** on its own cadence — not
+ the workspace fan-out.
+
+## Security
+
+- **Auth** — bearer key on every non-`/health` route (Function URL auth `NONE` +
+ in-app key, or `AWS_IAM`). Callers: ERP/MES/Inngest with `ASSEMBLER_SERVICE_API_KEY`.
+- **SSRF** — `ASSEMBLER_ALLOWED_URL_HOSTS` set in prod (`ASSEMBLER_DEV_MODE` unset →
+ default-deny).
+- Least-priv IAM exec role; non-root already (`USER assembler`); Trivy scan;
+ SHA-pinned image.
+
+## Cost
+
+| | Monthly |
+|---|---|
+| **Lambda** (typical volume, sync jobs, $0 idle) | **~$10–30** |
+| ECS Spot service — **default off** (`desiredCount 0`) | **$0 standing** |
+| ECS Spot service — **when enabled** (ALB ~$16 + ≥1 Spot 4vCPU/16GB task) | **~$30–55** |
+| Two always-on Fargate services (the rejected plan) | ~$400–500 |
+
+Per Lambda job ≈ 10 GB × ~10 s × $0.0000167/GB-s ≈ **$0.0017** + request. Lambda path
+is scale-to-zero with no ALB/VPC/NAT. The service costs $0 until a complaint turns it
+on — the standing cost is opt-in, not the default.
+
+## Rollback
+
+- **Lambda:** publish versions/alias; roll the alias back to the prior version, or
+ `update-function-code` to the previous `:sha`. Instant.
+- **ECS service:** roll the service back to the prior task-def revision, or set
+ `desiredCount 0` to disable overflow entirely (Lambda-only).
+- Consumers degrade gracefully — a down assembler leaves models on the poster tier;
+ no data loss (raw + prior artifacts untouched).
+
+## Acceptance criteria
+
+- [ ] `carbon/occt` + `carbon/assembler:${sha}` in ECR; LWA extension present; Trivy
+ clean.
+- [ ] Lambda: STEP fixture via Function URL → optimize completes (artifact in
+ storage, row updated); no bearer → 401; a job that would exceed 12 min
+ degrades via the time gate and still returns ≤ 15 min.
+- [ ] Overflow: with the service enabled, a > threshold source routes to the ECS
+ service (async submit→poll, Spot), completes, no 15-min limit; a Spot
+ interruption → service reschedules + Inngest retry succeeds (idempotent).
+- [ ] Overflow default-off: with `ASSEMBLER_ECS_SERVICE_URL` unset / `desiredCount 0`,
+ an over-threshold job degrades to the poster tier (no crash), and no ECS task
+ or ALB is billing.
+- [ ] GovCloud: Lambda deployed; service present but default-off; missing config
+ skipped (log line); STEP end-to-end via Lambda in GovCloud.
+
+## Risks
+
+| Risk | Sev | Mitigation |
+|---|---|---|
+| Sync refactor scope | Low | Lambda-only (ECS keeps async submit→poll); `run_to_completion` already built; compute already inline |
+| Lambda 15-min on a huge job | Med | time-budget gate degrades to fit; ECS service overflow with no cap; size pre-route |
+| Spot interruption mid-job | Low | 2-min drain + service reschedule + Inngest idempotent retry |
+| Standing service cost creep | Low | default `desiredCount 0` / not deployed; opt-in only on a real complaint |
+| Cold start on first job after idle | Low | ~1–3 s, background job — acceptable |
+| SST can't do container Lambda natively | Low | raw `aws.lambda.Function` (packageType Image) — verified path |
+| ECR repos not auto-created | Low | create `carbon/assembler` + `carbon/occt` out-of-band (P0) |
+
+## Implementation phases
+
+**P0 — ECR + OCCT base + LWA in image.** Create `carbon/assembler`+`carbon/occt`
+repos; CI builds the OCCT base; add LWA extension + `AWS_LWA_PORT=8000` to the
+Dockerfile (default CMD stays the HTTP server). *(`run-job` CLI already built as an
+optional batch entrypoint.)* *Verify:* image runs the HTTP server locally.
+
+**P1 — Lambda sync handler + router.** Add the sync HTTP branch (spawn +
+`run_to_completion` inline, return) for the Lambda path; add `invokeLambda(spec)` to
+`assembler-client.ts` + the size/timeout router in `model-optimize.ts` (Lambda-sync
+default; ECS async via the existing `submitAssemblerJob`/`pollAssemblerJobOnce`
+pointed at `ASSEMBLER_ECS_SERVICE_URL`). *Verify:* local end-to-end via the sync path;
+overflow routes to the async path (stub) or degrades when unset.
+
+**P2 — Lambda (standalone).** `aws.lambda.Function` (packageType Image) + Function
+URL + IAM role + env; CI updates the image. Vercel env → `ASSEMBLER_SERVICE_URL`
+(Function URL) + key. *Verify:* acceptance rows for Lambda.
+
+**P3 — ECS Spot service (default-off).** `sst.aws.Cluster` + `sst.aws.Service`
+(4 vCPU/16 GB, FARGATE_SPOT, ALB, `desiredCount 0` behind a stage flag);
+public-subnet VPC (no NAT). Router uses `ASSEMBLER_ECS_SERVICE_URL` when set.
+*Verify:* enable → overflow + interruption-reschedule rows; disabled → degrade + $0.
+
+**P4 — GovCloud (shared).** Replicate the P2/P3 stack (Lambda + default-off ECS
+service) once in the GovCloud account/region — **no** fan-out, **no** `workspaces`
+columns. ERP/MES there get the GovCloud Function URL + key. *Verify:* health + bearer
++ STEP end-to-end in GovCloud.
+
+> **Approval gate:** no prod deploy until Sid confirms AWS account/region, the
+> standalone vs shared-GovCloud call, the size-route threshold, and the sync-refactor
+> go-ahead. This spec produces the code + IaC; a human triggers prod.
+
+## Changelog
+
+- 2026-07-18 — **async everywhere; the sync path is dead** (Sid, after staging
+ fights: org RCP denies anonymous Function URLs, Function URLs can't carry a
+ domain, CloudFront/APIGW cap long requests at 30–60s). New Lambda model:
+ create → 202 + **Event-type self-invocation** runs the job in its own 900s
+ window (`ASSEMBLER_DISPATCH=lambda`; LWA pass-through delivers the event to
+ `POST /events`, which reuses the CLI's `spawn_from_spec` + `run_to_completion`);
+ job state + hand-off live in the **shared Redis JobStore** (now TLS-capable for
+ Upstash), so any instance's poll answers. Artifacts upload **directly from the
+ worker** via upload URLs handed over at submit (X-Carbon-Upload-Urls on create;
+ long-expiry) — bytes never sit in Redis; per-poll late-mint stays as the
+ ECS/dev/retry path. Front door is now **API Gateway HTTP API** (~$0, TLS
+ built-in, custom domain later, only `/health` + `/v1/*` routed; every request
+ is short so the 30s cap never binds). Self-invoke is a hand-rolled SigV4 POST
+ (aws-sdk needs rustc 1.94 > workspace's 1.90); signing key verified against
+ AWS's documented example. TS: `runAssemblerJob` is now purely async
+ (submit passes upload URLs; sync client + `ASSEMBLER_SYNC_ENABLED` removed).
+ The `?sync` HTTP branch remains for dev/CLI convenience but is off the
+ production path. **New prod requirement: `ASSEMBLER_REDIS_URL` (serverless
+ Redis, e.g. Upstash) on the Lambda.**
+
+- 2026-07-15 — written. Pivoted from the two-always-on-Fargate-services draft to
+ **Lambda-default + ECS-Spot-RunTask overflow** (cheaper, no scaling, GovCloud-wide)
+ after fact-checking Lambda/LWA/Fargate-Spot/SST against AWS+SST docs. Not yet
+ implemented.
+- 2026-07-17 — overflow runtime changed from **one-shot `RunTask`** to a **long-running
+ ECS Fargate Spot _service_** (Sid). Same image, same default HTTP entrypoint on both
+ runtimes; the service handles jobs via the assembler's existing async submit→poll
+ (no `run-job` CLI on the hot path — kept only for batch). Net effect: the async→sync
+ refactor is now **Lambda-only** (smaller), the service is **config-gated/default-off**
+ to preserve $0 idle, and Spot interruptions **self-heal** via the service scheduler.
+- 2026-07-17 — **P0 + P1 implemented** (Sid reviewed + approved). P0: LWA in the
+ Dockerfile, `run-job` CLI (now batch-only), isolated `assembler.yml` CI. P1:
+ assembler `?sync` HTTP branch + wall-clock time-budget gate (`optimize` ladder) +
+ the job-layer router `runAssemblerJob` (Lambda-sync default / ECS-async overflow,
+ `ASSEMBLER_SYNC_ENABLED` default-off) wired into `model-optimize` + `assembly-convert`
+ (`assembly-plan` stays async by design). Verified: `cargo build`/`clippy`,
+ `@carbon/{env,jobs}` typecheck, biome. **Next: P2/P3 IaC** — gated on AWS
+ account/region + hostnames/certs + the size-route threshold.
diff --git a/.ai/specs/2026-07-15-assembler-model-pipeline.md b/.ai/specs/2026-07-15-assembler-model-pipeline.md
new file mode 100644
index 0000000000..10dd90b9cb
--- /dev/null
+++ b/.ai/specs/2026-07-15-assembler-model-pipeline.md
@@ -0,0 +1,249 @@
+# Assembler Model Pipeline — formats, optimize gates, storage, viewer
+
+> Status: design (open questions resolved 2026-07-15)
+> Author: Claude (with Sid Rathi)
+> Date: 2026-07-15
+> Related: PR #1092 (Onshape asset sync — to consolidate), `.ai/rules/workflow-edge-function.md`
+
+## TLDR
+
+The assembler (`apps/assembler`, `crates/*`) is the single home for CAD →
+web-viewable-model work. This spec locks its shape: an action-RPC `/v1` API with
+an **explicit format registry** + **content auto-detection** (`format: "auto"`
+via the `file-format` crate), a **hard size gate** on optimize output (simplify
+ladder until it fits the bucket, `cannot_fit_budget` if it can't), **snake_case**
+JSON in and out, a **staging + served bucket** storage model that respects a
+**50 MB served-bucket cap**, three artifact tiers (poster / preview / assembly),
+and a **performance-over-quality** default policy. Onshape PR #1092's Node
+gltfpack+Draco compressor is retired in favor of this optimizer.
+
+Carbon is a **viewer + animator**, not a CAM/inspection tool — precision lives in
+the CAD system. So aggressive lossy optimization is the correct default; the only
+things we must preserve are **assembly structure** (per-part `nodeId`s, for
+animation) and **silhouette at screen resolution**.
+
+## Current state (grounded)
+
+- **Optimizer** — `crates/optimize` (`optimize_glb`/`optimize_gltf`/`optimize_root`,
+ `Options`, `Codec` = None|Meshopt|Draco). meshopt weld/reorder/simplify + merge
+ same-material primitives + i16-normal quant; Draco via `crates/draco-bridge`.
+- **Tessellation / structure** — `crates/converter` (`convert::convert_step`) via
+ `crates/occt-bridge` (OCCT). Produces the **structured** GLB + `graph.json`
+ (nodeIds, unit, hierarchy) for the assembly viewer.
+- **Assembler actions** — `apps/assembler/src/actions/{convert,optimize,plan}.rs`.
+ `convert.rs:84` already has an `optimize_glb()` hook that runs
+ `optimize::optimize_glb` on the converted GLB when the `optimize` flag is set —
+ **this is where the structure-preserving "assembly tier" plugs in.**
+- **Format support today (implicit)** — `run_optimize` (`optimize.rs`) matches only
+ `step|stp` (OCCT tessellate) / `glb|gltf` (mmap); everything else →
+ `Err("unsupported format")`. Client `optimizableModelFormat` (`packages/utils`)
+ mirrors it by hand. Upload (`supportedModelTypes`) accepts **18** formats but
+ only **4** ever optimize — the gap this spec closes.
+- **Wire format today** — camelCase (`json!` responses in `convert.rs`/`plan.rs`/
+ `optimize.rs`: `componentCount`, `outputBytes`, `simplifyRatioUsed`, …).
+ Request structs default to snake. **Inconsistent** → standardize on snake_case.
+- **Jobs** — `packages/jobs/.../tasks/{assembly-convert,assembly-plan,model-optimize}.ts`
+ + shared `assembler-client.ts`. `model-optimize` triggered on every attach point
+ (upload, part/new, quote/rfq drag); derives format from the stored file; skips
+ non-mesh.
+- **Storage today** — one `private` bucket. Dev `FILE_SIZE_LIMIT` was 50 MiB (413'd
+ CAD uploads); raised in `docker-compose.dev.yml` / `config.toml`. **Prod bucket
+ cap is 50 MB** (the real constraint this spec designs around).
+
+## Design
+
+### Roles (what we keep vs derive)
+
+- **STEP / structured source** = kept, but **not** as a fidelity master — for
+ (a) re-deriving artifacts later, (b) users **downloading their original CAD
+ file** (a real ERP need). Precision is the CAD system's job.
+- **glTF / GLB** = the derived viewer format (triangulated, lossy, one-way).
+
+### Formats — explicit registry + auto-detect
+
+Single source of truth in the assembler; surfaced via `GET /v1`; the client reads
+it instead of hand-maintaining lists.
+
+| Format | loader | exact | structured | `/optimize` | `/convert` |
+|---|---|---|---|---|---|
+| step, stp | occt | ✓ | ✓ | ✓ | ✓ |
+| iges, brep | occt | ✓ | ✓ (iges weaker) | ✓ | ✓ |
+| glb, gltf | mesh | — | ✓ (scene graph) | ✓ | ✓ (extract graph) |
+| obj | mesh | — | partial (groups) | ✓ | ⚠️ shallow |
+| stl, ply, off | mesh | — | ✗ | ✓ | ✗ `no_structure` |
+
+- **Easy adds (mesh loaders, no OCCT):** STL first, then OBJ/PLY/OFF → parse →
+ build glTF → existing optimize.
+- **Auto-detect** — `format: "auto"` (or omit): **`file-format` crate** for
+ magic/content, plus our supplements: `.gltf` JSON check, binary-STL size formula
+ (`84 + N*50` — check *before* the ASCII `"solid"` prefix), extension fallback.
+ Sniff-verify even when a format is declared. Unknown → `ambiguous_format` /
+ `unsupported_format` (fail loud, never guess into OCCT).
+
+### Quality policy — performance first
+
+Defaults aggressive; the bar is "reads right on screen + animates smoothly."
+
+- **Target small, not the cap** — aim ~2–10 MB per preview; 50 MB is the safety
+ net, not the goal.
+- Coarse tessellation (high linear/angular deflection), **defeature** small
+ features (fillets/holes/chamfers/threads), per-part LOD (tiny→primitive).
+- **meshopt** default codec (GPU-fast decode) + zstd transport; **draco** only when
+ bandwidth-bound. Never stack the two (mutually exclusive per primitive).
+- **Preserve only:** per-part `nodeId`s (animation) + silhouette. Geometry
+ precision is expendable.
+- Optional per-model `high_fidelity` opt-in for hero parts.
+
+### The size gate (the core algorithm)
+
+```
+for rung in [full, 0.75, 0.5, 0.25, …]:
+ cand = optimize(mesh, codec, simplify=rung)
+ if cand.bytes <= max_bytes AND cand.render_weight <= max_render_weight_bytes:
+ return cand, rung
+return error("cannot_fit_budget") # never store an over-cap blob
+```
+
+Two caps: **file size** (storage/transfer) **and** decoded **render weight**
+(a small Draco file with a huge decoded mesh still hangs the viewer — #1092's
+lesson). Record `simplify_ratio_used` and surface it.
+
+### Artifact tiers (app orchestrates 3 focused actions)
+
+| Tier | Producer | Notes |
+|---|---|---|
+| **Poster** | `model-thumbnail` | instant paint; Onshape's render feeds it |
+| **Preview** | `/optimize` (meshopt, gated) | the 95% case; merges/flattens OK |
+| **Assembly** | `/convert` (structure-preserving optimize) | per-node simplify, **no cross-node merge**, keeps `nodeId`s + graph — the `convert.rs:84` hook, made structure-preserving |
+
+### Storage model
+
+- **`served`** bucket — per-bucket cap **50 MB**: poster, preview, assembly GLB,
+ graph. (Global `FILE_SIZE_LIMIT` stays high; `min(global, bucket)` enforces the
+ cap on `served` only.)
+- **`staging`** bucket — high limit, **TTL lifecycle** (orphan backstop): raw lands
+ here via the normal resumable browser→storage upload; the job reads it via signed
+ URL (no streaming through the assembler).
+- **`cold`** (optional) — cheap tier for manual raws worth re-deriving.
+- **Retention by provenance:** Onshape → source is Onshape, drop the raw (re-pull to
+ re-derive). Manual → keep raw if ≤50 MB (fits `served`, convert always possible);
+ else stage-and-drop (only genuinely-too-big models lose their lossless source).
+- After dropping a raw, point `modelPath` at the optimized artifact (don't dangle).
+
+### API (`/v1`, snake_case, `Authorization: Bearer`)
+
+Envelope `{ ok, job }` | `{ ok: false, error }`; job `{ id, action, status,
+result?, stats?, error? }`; status `queued|running|succeeded|failed|canceled`.
+Headers: `Idempotency-Key`, `X-Carbon-Upload-Urls` (late-mint), `Accept-Encoding:
+identity` bypasses zstd.
+
+- `GET /health` → `{ ok, version }`
+- `GET /v1` → discovery: `actions`, `input_formats` (loader/exact/structured),
+ `codecs`, `limits` (`max_output_bytes`, `max_source_bytes`, …).
+- `POST /v1/optimize` → `{ source:{url,format}, output:{path,codec,max_bytes,
+ max_render_weight_bytes}, quality:{simplify,auto_error,tolerance_mm,
+ quantize_normals,merge_primitives,weld,reorder} }` → 202 job. Result:
+ `{ detected_format, detected_via, outputs:{glb:{path,bytes,codec}} }` + stats
+ (`input/output_triangles`, `input/output_bytes`, `simplify_ratio_used`,
+ `render_weight_bytes`, `warnings`).
+- `POST /v1/convert` → `{ source, outputs:{glb,graph}, tessellation:{…},
+ quality:{defeature_below_mm,unify_faces,per_part_simplify,max_bytes,…} }` →
+ result `{ outputs:{glb,graph}, component_count, unit }`.
+- `POST /v1/plan` → `{ source, graph_url, output }`.
+- `GET /v1/jobs/{id}?wait=25` (long-poll), `POST /v1/jobs/{id}/cancel`,
+ `POST /v1/cache/invalidate` (`{ model_upload_id }` | `{ source_hash }`).
+
+**Error codes** (`error.code`): `unsupported_format`, `ambiguous_format`,
+`no_structure`, `source_too_large`, `tessellation_failed`, `optimize_failed`,
+`cannot_fit_budget`, `busy`, `invalid_input`, `not_found`, `unauthorized`.
+`unsupported_format` includes `supported: [...]`.
+
+### Onshape #1092 consolidation
+
+- Onshape attach → `trigger("model-optimize")` (same as other attach points).
+- **Delete** `onshape-compress-model.ts` + deps (`GLTFPACK_PATH` binary,
+ `draco3dgltf`, `@gltf-transform/*`). One optimizer.
+- Its Onshape-rendered thumbnail → the poster tier.
+- Merge viewers: keep `ModelPreview` (progressive tiers + WASM fallback), adopt
+ #1092's **explicit click-to-load** gate for large models.
+- Conflict files to reconcile on merge: `CadModel.tsx`, `shared.service.ts`,
+ `sales.service.ts`, `jobs/AGENTS.md`, the `$lineId.details.tsx` routes.
+
+## Implementation slices
+
+1. **Formats + auto-detect + STL + snake_case + gate** — registry enum + `file-format`
+ sniff + STL mesh loader; add `max_bytes`/`max_render_weight_bytes` gate +
+ simplify ladder + `cannot_fit_budget`; switch `json!` responses to snake_case +
+ `#[serde(rename_all="snake_case")]` on request structs; update TS readers.
+ Discovery lists it all. (First, highest value.)
+2. **Storage split** — `served` @ 50 MB per-bucket + `staging` w/ TTL; job reads raw
+ from `staging`; provenance field + retention rules; keep-raw-if-≤50 MB.
+3. **Assembly tier** — make `convert.rs:84` optimize structure-preserving
+ (per-node simplify, no cross-node merge) + defeature/unify/deflection knobs +
+ the same gate.
+4. **Viewer** — retire WASM-raw to last resort; poster + poll + meshopt tiers +
+ click-to-load gate (partly done in `ModelPreview`).
+5. **Onshape consolidation** — after #1092 lands (or rebase): swap its compressor
+ for `model-optimize`, delete deps, merge viewers.
+6. **IGES/BREP** — OCCT reader dispatch alongside `convert_step`.
+
+## GLB-always roadmap (decided 2026-07-18, Sid)
+
+**Doctrine: when the assembler is enabled, EVERY accepted upload format is
+optimised into GLB and the viewer uses that artifact.** The browser WASM raw
+tier stays exactly as built — the bridge for optimise-in-flight, assembler-off,
+and job-failure states — but is never the steady state for any format. Each
+format added server-side automatically demotes its WASM path to
+first-seconds-preview: the trigger derives format from the stored file
+(`optimizableModelFormat` widens in lockstep) and `model.reoptimize` backfills.
+
+Accepted-format coverage to build, in cost order:
+
+| Phase | Formats | Status |
+|---|---|---|
+| **F1** ✅ 2026-07-18 | iges, brep (OCCT readers, shared `doc_to_tree` walk) + obj, ply, off, bim (parsers → `build_triangle_glb`, `crates/optimize/src/ingest.rs`) | implemented; IGES/BREP runtime proof at staging (no hermetic fixtures) |
+| **F2** ✅ 2026-07-18 | 3mf (zip + build/components + 4x3 transforms), amf (XML, zip-unwrapped; constellations not applied) | implemented (zip 8 + quick-xml deps) |
+| **F3 (on demand)** | fbx, dae, 3ds, 3dm | each needs a real import dep (assimp binding / opennurbs) — only on customer evidence |
+
+ifc/fcstd stay out (dropped from the accept list 2026-07-18).
+
+## Open / deferred
+
+- Content-addressed dedup by `geometry_hash` (share artifacts across item revisions)
+ — noted, not scoped here.
+- Surfacing optimized size in **doc-list tables** (needs summary-view recreation) —
+ viewer badge is done; tables deferred.
+
+## Changelog
+
+- 2026-07-15 — spec written; decisions resolved in design thread.
+- 2026-07-15 — **slice 1 core implemented** (assembler + optimize crate):
+ - `crates/optimize::stl_to_glb` — binary + ASCII STL ingest → weldable GLB (2 tests).
+ - `apps/assembler/src/formats.rs` — explicit `Format` registry + `file-format`-backed
+ content auto-detect with supplements (gltf-JSON, binary-STL size formula, ext
+ fallback) + `resolve(auto|declared)` → typed `unsupported_format`/`ambiguous_format`
+ (4 tests).
+ - `optimize` action: format resolve + STL load + typed errors + **`cannot_fit_budget`**
+ (fails instead of storing an over-cap blob) + `detected_format`/`detected_via`;
+ request reshaped to `output`/`quality`, **snake_case** request + response; default
+ aggressive simplify ladder `[none,0.5,0.25,0.1]` + 50 MiB output / 400 MiB
+ render-weight default gates.
+ - `GET /v1` discovery: `input_formats` (loader/exact/structured) + `codecs` + snake_case
+ `limits` (incl. `max_output_bytes`, `max_render_weight_bytes`).
+ - HTTP error codes → snake_case (`invalid_input`/`unauthorized`/`not_found`).
+ - TS: `optimizableModelFormat` accepts `stl`; `model-optimize` sends `output.path`.
+ - **Remaining in slice 1** (deferred — orthogonal, needs a live convert test):
+ `convert`/`plan` action responses + request keys still camelCase (`componentCount`,
+ `linearDeflection`, `contentHash`, `planPath`, `pathSamples`, `nodeIds`) and their TS
+ readers (`assembly-convert.ts`/`assembly-plan.ts`) + `cache/invalidate`
+ (`modelUploadId` → `model_upload_id`). IGES/BREP/OBJ/PLY/OFF are detected + advertised
+ but their loaders error `unsupported_format` until slice 6 / mesh-loader follow-ups.
+- 2026-07-15 — **slice 2 foundation**: `temp-staging` storage bucket created
+ (`20260715150742_temp-staging-bucket.sql`) — high size limit (inherits the global
+ cap), private, company-scoped RLS mirroring the `private` model policies. `private`
+ is intentionally NOT yet capped to 50 MB (the lossless assembly-convert GLB exceeds
+ it for big assemblies until the slice-3 structure-preserving tier gates it).
+ **Remaining in slice 2**: route raw uploads to `temp-staging` (CadModel/PartForm/
+ drag + `model.upload`); job reads raw from `temp-staging`, writes the artifact to
+ `private`, drops the staged raw (keep-raw-if-≤50 MB in `private`); `provenance`
+ column + retention rules; scheduled TTL cleanup of staged orphans.
diff --git a/.github/workflows/assembler.yml b/.github/workflows/assembler.yml
new file mode 100644
index 0000000000..c3f78cf45a
--- /dev/null
+++ b/.github/workflows/assembler.yml
@@ -0,0 +1,180 @@
+name: Assembler Image
+
+# Isolated from deploy.yml so an assembler/crates change builds ONLY the
+# assembler image (and vice versa — erp/mes pushes never rebuild this).
+# Builds carbon/assembler:${sha} from apps/assembler/Dockerfile, which links the
+# prebuilt carbon/occt base (built here on demand — it's a ~30 min OCCT compile,
+# so it is NOT part of every run). The Lambda/ECS *deploy* is separate (P2/P3).
+#
+# Prereq: ECR repos carbon/assembler + carbon/occt exist (created out-of-band).
+
+on:
+ push:
+ branches:
+ - main
+ paths:
+ - "apps/assembler/**"
+ - "crates/**"
+ workflow_dispatch:
+ inputs:
+ build_occt_base:
+ description: "Also rebuild the carbon/occt base image (slow, ~30 min)"
+ type: boolean
+ default: false
+ deploy:
+ description: "Deploy the Lambda (+ optional ECS service) after building"
+ type: boolean
+ default: false
+ stage:
+ description: "SST stage to deploy (e.g. prod, govcloud)"
+ type: string
+ default: "prod"
+
+jobs:
+ occt-base:
+ name: OCCT base image
+ if: ${{ github.event_name == 'workflow_dispatch' && inputs.build_occt_base }}
+ runs-on: ubuntu-latest
+ steps:
+ - name: Checkout code
+ uses: actions/checkout@v4
+
+ - name: Configure AWS credentials
+ uses: aws-actions/configure-aws-credentials@v4
+ with:
+ aws-access-key-id: ${{ secrets.AWS_ACCESS_KEY_ID }}
+ aws-secret-access-key: ${{ secrets.AWS_SECRET_ACCESS_KEY }}
+ aws-region: ${{ secrets.AWS_REGION }}
+
+ - name: Login to Amazon ECR
+ id: login-ecr
+ uses: aws-actions/amazon-ecr-login@v2
+
+ - name: Set up Docker Buildx
+ uses: docker/setup-buildx-action@v3
+
+ - name: Build and push OCCT base
+ uses: docker/build-push-action@v5
+ with:
+ context: apps/assembler
+ file: apps/assembler/occt.Dockerfile
+ push: true
+ tags: ${{ steps.login-ecr.outputs.registry }}/carbon/occt:8.0.0-p1
+ cache-from: type=gha
+ cache-to: type=gha,mode=max
+ platforms: linux/amd64
+
+ build:
+ name: Build assembler image
+ # Disabled by default: the push trigger only fires once the repo variable
+ # ASSEMBLER_CI_ENABLED is set to 'true' (Settings -> Variables). Until the
+ # ECR repos + AWS secrets exist in the CI account, an automatic build on a
+ # main merge would just fail red. Manual workflow_dispatch always works —
+ # running it by hand is intentional.
+ if: github.event_name == 'workflow_dispatch' || vars.ASSEMBLER_CI_ENABLED == 'true'
+ runs-on: ubuntu-latest
+ steps:
+ - name: Checkout code
+ uses: actions/checkout@v4
+
+ - name: Configure AWS credentials
+ uses: aws-actions/configure-aws-credentials@v4
+ with:
+ aws-access-key-id: ${{ secrets.AWS_ACCESS_KEY_ID }}
+ aws-secret-access-key: ${{ secrets.AWS_SECRET_ACCESS_KEY }}
+ aws-region: ${{ secrets.AWS_REGION }}
+
+ - name: Login to Amazon ECR
+ id: login-ecr
+ uses: aws-actions/amazon-ecr-login@v2
+
+ - name: Set up Docker Buildx
+ uses: docker/setup-buildx-action@v3
+
+ # Context is the repo root (the cargo workspace spans crates/* + apps/assembler);
+ # the Dockerfile links the prebuilt OCCT base via the OCCT_IMAGE build-arg.
+ - name: Build and push assembler image
+ id: build
+ uses: docker/build-push-action@v5
+ with:
+ context: .
+ file: apps/assembler/Dockerfile
+ build-args: |
+ OCCT_IMAGE=${{ steps.login-ecr.outputs.registry }}/carbon/occt:8.0.0-p1
+ push: true
+ tags: |
+ ${{ steps.login-ecr.outputs.registry }}/carbon/assembler:latest
+ ${{ steps.login-ecr.outputs.registry }}/carbon/assembler:${{ github.sha }}
+ cache-from: type=gha
+ cache-to: type=gha,mode=max
+ platforms: linux/amd64
+
+ # Report-only for now (exit-code 0). Flip to '1' to fail the build on
+ # CRITICAL/HIGH once the base image's findings are triaged.
+ - name: Scan image (Trivy)
+ uses: aquasecurity/trivy-action@master
+ with:
+ image-ref: ${{ steps.login-ecr.outputs.registry }}/carbon/assembler:${{ github.sha }}
+ severity: CRITICAL,HIGH
+ ignore-unfixed: true
+ exit-code: "0"
+
+ # P2/P3 deploy — MANUAL ONLY, never auto-fires. Gated on the explicit `deploy`
+ # dispatch input so a main push only builds the image (above); the Lambda/ECS
+ # rollout happens when a human triggers it AFTER filling the DECISION: env in
+ # apps/assembler/sst.config.ts and adding the deploy secrets. This is an
+ # UNVALIDATED scaffold (see the sst.config.ts header) — validate against a
+ # throwaway stage first.
+ deploy:
+ name: Deploy assembler (Lambda + optional ECS service)
+ if: ${{ github.event_name == 'workflow_dispatch' && inputs.deploy }}
+ needs: build
+ runs-on: ubuntu-latest
+ env:
+ IMAGE_TAG: ${{ github.sha }}
+ steps:
+ - uses: actions/checkout@v4
+
+ - name: Configure AWS credentials
+ uses: aws-actions/configure-aws-credentials@v4
+ with:
+ aws-access-key-id: ${{ secrets.AWS_ACCESS_KEY_ID }}
+ aws-secret-access-key: ${{ secrets.AWS_SECRET_ACCESS_KEY }}
+ aws-region: ${{ secrets.AWS_REGION }}
+
+ - uses: pnpm/action-setup@v4
+ - uses: actions/setup-node@v4
+ with:
+ node-version: "22"
+ cache: pnpm
+
+ # SST v3 is Pulumi-based; pin the same engine version deploy.yml uses.
+ - name: Install compatible Pulumi version
+ run: |
+ curl -fsSL https://get.pulumi.com | sh -s -- --version 3.212.0
+ echo "$HOME/.pulumi/bin" >> $GITHUB_PATH
+
+ - name: Install dependencies
+ run: pnpm install --frozen-lockfile
+
+ # Deploys apps/assembler/sst.config.ts. The image was pushed by `build`
+ # above (carbon/assembler:${github.sha}); IMAGE_TAG points the Lambda + ECS
+ # task at it. Consumers' ASSEMBLER_SERVICE_URL / ASSEMBLER_ECS_SERVICE_URL /
+ # ASSEMBLER_SYNC_ENABLED are wired from the stack outputs after this runs.
+ - name: Deploy (sst)
+ working-directory: apps/assembler
+ env:
+ AWS_ACCOUNT_ID: ${{ secrets.AWS_ACCOUNT_ID }}
+ AWS_REGION: ${{ secrets.AWS_REGION }}
+ ASSEMBLER_SERVICE_API_KEY: ${{ secrets.ASSEMBLER_SERVICE_API_KEY }}
+ # DECISION: fill the rest from secrets before enabling —
+ # ASSEMBLER_ALLOWED_URL_HOSTS, ASSEMBLER_REDIS_URL,
+ # ASSEMBLER_ECS_ENABLED (default off), ASSEMBLER_SERVICE_HOSTNAME,
+ # ASSEMBLER_SERVICE_CERT_ARN, ASSEMBLER_ECS_MIN/MAX.
+ # TODO(P2/P3): the standalone SST app needs an sst toolchain in
+ # apps/assembler (or run via the root's sst). Wire the actual command once
+ # the toolchain + stage naming are settled.
+ run: |
+ echo "TODO: npx sst deploy --stage ${{ inputs.stage }}"
+ echo "Scaffold only — filling DECISION env + sst toolchain is the human deploy step."
+ exit 1
diff --git a/Cargo.lock b/Cargo.lock
index 394e90af89..73208bdb27 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -57,21 +57,43 @@ dependencies = [
name = "assembler"
version = "0.1.0"
dependencies = [
+ "async-compression",
"axum",
"bytes",
"converter",
"dashmap",
+ "file-format",
"futures-util",
+ "hex",
+ "hmac",
"lru",
+ "memmap2",
+ "optimize",
"planner",
"redis",
"reqwest",
"serde",
"serde_json",
+ "sha2",
+ "tempfile",
"tikv-jemallocator",
"tokio",
"tokio-util",
+ "tower-http",
"xxhash-rust",
+ "zstd",
+]
+
+[[package]]
+name = "async-compression"
+version = "0.4.42"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e79b3f8a79cccc2898f31920fc69f304859b3bd567490f75ebf51ae1c792a9ac"
+dependencies = [
+ "compression-codecs",
+ "compression-core",
+ "pin-project-lite",
+ "tokio",
]
[[package]]
@@ -193,6 +215,20 @@ name = "bytemuck"
version = "1.25.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c8efb64bd706a16a1bdde310ae86b351e4d21550d98d056f22f8a7f7a2183fec"
+dependencies = [
+ "bytemuck_derive",
+]
+
+[[package]]
+name = "bytemuck_derive"
+version = "1.11.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f65693059b6b9c588b9f62fed1cedbf0a8b805631457ea162d68f0de186f3de5"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn",
+]
[[package]]
name = "byteorder"
@@ -234,6 +270,8 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f5d6cac793997bd970000024b2934968efe83b382de4fdcf4fcb46b6ee4ad996"
dependencies = [
"find-msvc-tools",
+ "jobserver",
+ "libc",
"shlex",
]
@@ -320,6 +358,25 @@ dependencies = [
"tokio-util",
]
+[[package]]
+name = "compression-codecs"
+version = "0.4.38"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ce2548391e9c1929c21bf6aa2680af86fe4c1b33e6cea9ac1cfeec0bd11218cf"
+dependencies = [
+ "compression-core",
+ "flate2",
+ "memchr",
+ "zstd",
+ "zstd-safe",
+]
+
+[[package]]
+name = "compression-core"
+version = "0.4.32"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "cc14f565cf027a105f7a44ccf9e5b424348421a1d8952a8fc9d499d313107789"
+
[[package]]
name = "converter"
version = "0.1.0"
@@ -505,6 +562,7 @@ checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292"
dependencies = [
"block-buffer",
"crypto-common",
+ "subtle",
]
[[package]]
@@ -538,6 +596,25 @@ dependencies = [
"syn",
]
+[[package]]
+name = "draco-bridge"
+version = "0.1.0"
+dependencies = [
+ "cxx",
+ "cxx-build",
+]
+
+[[package]]
+name = "duplicate"
+version = "2.0.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8e92f10a49176cbffacaedabfaa11d51db1ea0f80a83c26e1873b43cd1742c24"
+dependencies = [
+ "heck",
+ "proc-macro2",
+ "proc-macro2-diagnostics",
+]
+
[[package]]
name = "either"
version = "1.16.0"
@@ -566,6 +643,12 @@ version = "2.4.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9f1f227452a390804cdb637b74a86990f2a7d7ba4b7d5693aac9b4dd6defd8d6"
+[[package]]
+name = "file-format"
+version = "0.26.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e7ef3d5e8ae27277c8285ac43ed153158178ef0f79567f32024ca8140a0c7cd8"
+
[[package]]
name = "filetime"
version = "0.2.29"
@@ -590,6 +673,16 @@ checksum = "843fba2746e448b37e26a819579957415c8cef339bf08564fe8b7ddbd959573c"
dependencies = [
"crc32fast",
"miniz_oxide",
+ "zlib-rs",
+]
+
+[[package]]
+name = "float-cmp"
+version = "0.10.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b09cf3155332e944990140d967ff5eceb70df778b34f77d8075db46e4704e6d8"
+dependencies = [
+ "num-traits",
]
[[package]]
@@ -739,6 +832,18 @@ dependencies = [
"wasm-bindgen",
]
+[[package]]
+name = "getrandom"
+version = "0.3.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "899def5c37c4fd7b2664648c28120ecec138e4d395b459e5ca34f9cce2dd77fd"
+dependencies = [
+ "cfg-if",
+ "libc",
+ "r-efi 5.3.0",
+ "wasip2",
+]
+
[[package]]
name = "getrandom"
version = "0.4.3"
@@ -748,7 +853,7 @@ dependencies = [
"cfg-if",
"js-sys",
"libc",
- "r-efi",
+ "r-efi 6.0.0",
"rand_core 0.10.1",
"wasm-bindgen",
]
@@ -812,12 +917,27 @@ version = "0.17.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a"
+[[package]]
+name = "heck"
+version = "0.5.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea"
+
[[package]]
name = "hex"
version = "0.4.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70"
+[[package]]
+name = "hmac"
+version = "0.12.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "6c49c37c09c17a53d937dfbb742eb3a961d65a994e6bcdcf37e7399d0cc8ab5e"
+dependencies = [
+ "digest",
+]
+
[[package]]
name = "http"
version = "1.4.2"
@@ -1063,6 +1183,16 @@ version = "1.0.18"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682"
+[[package]]
+name = "jobserver"
+version = "0.1.34"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9afb3de4395d6b3e67a780b6de64b51c978ecf11cb9a462c66be7d4ca9039d33"
+dependencies = [
+ "getrandom 0.3.4",
+ "libc",
+]
+
[[package]]
name = "js-sys"
version = "0.3.103"
@@ -1202,6 +1332,27 @@ version = "2.8.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98"
+[[package]]
+name = "memmap2"
+version = "0.9.11"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d1219ed1b7f229ee7104d281dd01d6802fe28bb6e95d292942c4daacdeb798c0"
+dependencies = [
+ "libc",
+]
+
+[[package]]
+name = "meshopt"
+version = "0.6.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e01e77ead21976b3a9f01ec1724f766923da74f0726364e2b0f425658935d71a"
+dependencies = [
+ "bitflags",
+ "cc",
+ "float-cmp",
+ "thiserror 2.0.18",
+]
+
[[package]]
name = "mime"
version = "0.3.17"
@@ -1446,6 +1597,22 @@ dependencies = [
"vcpkg",
]
+[[package]]
+name = "optimize"
+version = "0.1.0"
+dependencies = [
+ "base64",
+ "bytemuck",
+ "draco-bridge",
+ "gltf",
+ "memmap2",
+ "meshopt",
+ "quick-xml",
+ "serde_json",
+ "struson",
+ "zip",
+]
+
[[package]]
name = "parking_lot_core"
version = "0.9.12"
@@ -1545,6 +1712,27 @@ dependencies = [
"unicode-ident",
]
+[[package]]
+name = "proc-macro2-diagnostics"
+version = "0.10.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "af066a9c399a26e020ada66a034357a868728e72cd426f3adcd35f80d88d88c8"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn",
+ "version_check",
+]
+
+[[package]]
+name = "quick-xml"
+version = "0.41.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e660451e55124f798a69a5af3f49ccfbefbd41910eefd25caf2393e1f3473ec1"
+dependencies = [
+ "memchr",
+]
+
[[package]]
name = "quinn"
version = "0.11.11"
@@ -1610,6 +1798,12 @@ dependencies = [
"proc-macro2",
]
+[[package]]
+name = "r-efi"
+version = "5.3.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "69cdb34c158ceb288df11e18b4bd39de994f6657d83847bdffdbd7f346754b0f"
+
[[package]]
name = "r-efi"
version = "6.0.0"
@@ -1716,8 +1910,13 @@ dependencies = [
"num-bigint",
"percent-encoding",
"pin-project-lite",
+ "rustls",
+ "rustls-native-certs",
+ "rustls-pemfile",
+ "rustls-pki-types",
"ryu",
"tokio",
+ "tokio-rustls",
"tokio-util",
"url",
]
@@ -2066,6 +2265,17 @@ dependencies = [
"digest",
]
+[[package]]
+name = "sha2"
+version = "0.10.9"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283"
+dependencies = [
+ "cfg-if",
+ "cpufeatures 0.2.17",
+ "digest",
+]
+
[[package]]
name = "shlex"
version = "2.0.1"
@@ -2135,6 +2345,39 @@ version = "0.11.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f"
+[[package]]
+name = "strum"
+version = "0.26.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8fec0f0aef304996cf250b31b5a10dee7980c85da9d759361292b8bca5a18f06"
+dependencies = [
+ "strum_macros",
+]
+
+[[package]]
+name = "strum_macros"
+version = "0.26.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4c6bee85a5a24955dc440386795aa378cd9cf82acd5f764469152d2270e581be"
+dependencies = [
+ "heck",
+ "proc-macro2",
+ "quote",
+ "rustversion",
+ "syn",
+]
+
+[[package]]
+name = "struson"
+version = "0.6.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "18c68ef850864c0fa120c07a17d6369ec4df02a33cad4aa593e0e0566e031bda"
+dependencies = [
+ "duplicate",
+ "strum",
+ "thiserror 1.0.69",
+]
+
[[package]]
name = "subtle"
version = "2.6.1"
@@ -2363,12 +2606,16 @@ version = "0.6.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4cfcf7e2740e6fc6d4d688b4ef00650406bb94adf4731e43c096c3a19fe40840"
dependencies = [
+ "async-compression",
"bitflags",
"bytes",
+ "futures-core",
"futures-util",
"http",
"http-body",
"pin-project-lite",
+ "tokio",
+ "tokio-util",
"tower",
"tower-layer",
"tower-service",
@@ -2413,6 +2660,12 @@ version = "0.2.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e421abadd41a4225275504ea4d6566923418b7f05506fbc9c0fe86ba7396114b"
+[[package]]
+name = "typed-path"
+version = "0.12.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8e28f89b80c87b8fb0cf04ab448d5dd0dd0ade2f8891bae878de66a75a28600e"
+
[[package]]
name = "typenum"
version = "1.20.1"
@@ -2507,6 +2760,15 @@ version = "0.11.1+wasi-snapshot-preview1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b"
+[[package]]
+name = "wasip2"
+version = "1.0.2+wasi-0.2.9"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9517f9239f02c069db75e65f174b3da828fe5f5b945c4dd26bd25d89c03ebcf5"
+dependencies = [
+ "wit-bindgen",
+]
+
[[package]]
name = "wasm-bindgen"
version = "0.2.126"
@@ -2733,6 +2995,12 @@ version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec"
+[[package]]
+name = "wit-bindgen"
+version = "0.51.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d7249219f66ced02969388cf2bb044a09756a083d0fab1e566056b04d9fbcaa5"
+
[[package]]
name = "writeable"
version = "0.6.3"
@@ -2858,8 +3126,68 @@ dependencies = [
"syn",
]
+[[package]]
+name = "zip"
+version = "8.6.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "2d04a6b5381502aa6087c94c669499eb1602eb9c5e8198e534de571f7154809b"
+dependencies = [
+ "crc32fast",
+ "flate2",
+ "indexmap",
+ "memchr",
+ "typed-path",
+ "zopfli",
+]
+
+[[package]]
+name = "zlib-rs"
+version = "0.6.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b142a20ec14a91d5bc708c1dc21b080c550113d8aa77afa29635673a65dd02c5"
+
[[package]]
name = "zmij"
version = "1.0.21"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b8848ee67ecc8aedbaf3e4122217aff892639231befc6a1b58d29fff4c2cabaa"
+
+[[package]]
+name = "zopfli"
+version = "0.8.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f05cd8797d63865425ff89b5c4a48804f35ba0ce8d125800027ad6017d2b5249"
+dependencies = [
+ "bumpalo",
+ "crc32fast",
+ "log",
+ "simd-adler32",
+]
+
+[[package]]
+name = "zstd"
+version = "0.13.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e91ee311a569c327171651566e07972200e76fcfe2242a4fa446149a3881c08a"
+dependencies = [
+ "zstd-safe",
+]
+
+[[package]]
+name = "zstd-safe"
+version = "7.2.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8f49c4d5f0abb602a93fb8736af2a4f4dd9512e36f7f570d66e65ff867ed3b9d"
+dependencies = [
+ "zstd-sys",
+]
+
+[[package]]
+name = "zstd-sys"
+version = "2.0.16+zstd.1.5.7"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "91e19ebc2adc8f83e43039e79776e3fda8ca919132d68a1fed6a5faca2683748"
+dependencies = [
+ "cc",
+ "pkg-config",
+]
diff --git a/Cargo.toml b/Cargo.toml
index f9d8507220..95acef639c 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -15,7 +15,9 @@ debug = true
strip = false
[workspace.dependencies]
-gltf = { version = "1.4", default-features = false, features = ["extras", "names"] }
+gltf = { version = "1.4", default-features = false, features = ["extras", "names", "extensions"] }
+meshopt = "0.6"
+bytemuck = { version = "1", features = ["derive"] }
nalgebra = "0.33"
serde = { version = "1", features = ["derive"] }
serde_json = "1"
diff --git a/apps/assembler/AGENTS.md b/apps/assembler/AGENTS.md
index 798e5ea4bb..952d395000 100644
--- a/apps/assembler/AGENTS.md
+++ b/apps/assembler/AGENTS.md
@@ -143,11 +143,19 @@ and plan jobs, then force-exits after `ASSEMBLER_SHUTDOWN_GRACE_S`.
## Not yet done
-- **meshopt compression** — the converter serves an uncompressed (contract-valid)
- GLB. In-process `meshopt` + `EXT_meshopt_compression` is a follow-up.
- **CI + registry** — no workflow yet builds/publishes the `carbon-occt` base or
the `carbon-assembler` image, or deploys the container.
+## meshopt / Draco compression
+
+`meshopt` + `EXT_meshopt_compression` (and optional `KHR_draco_mesh_compression`)
+live in the **`/v1/optimize`** action (`crates/optimize`), NOT the converter. The
+**convert** action still serves an uncompressed, contract-valid, lossless GLB (it
+feeds the animated assembly viewer); optimise produces the separate compact
+preview GLB. Gotcha grounded in `crates/optimize`: the meshopt vertex codec
+requires every attribute stride be a multiple of 4 — i16 VEC3 normals are padded
+to i16 VEC4 (8 bytes), or the spec JS decoder rejects the output.
+
## Never
- Never swap the FCL/OCCT bridges for parry3d or a pure-Rust CAD lib — parity breaks.
diff --git a/apps/assembler/Cargo.toml b/apps/assembler/Cargo.toml
index 592805e3f6..0063a4745d 100644
--- a/apps/assembler/Cargo.toml
+++ b/apps/assembler/Cargo.toml
@@ -11,6 +11,7 @@ path = "src/main.rs"
[dependencies]
converter = { path = "../../crates/converter" }
planner = { path = "../../crates/planner" }
+optimize = { path = "../../crates/optimize" }
serde.workspace = true
serde_json.workspace = true
axum = "0.7"
@@ -21,8 +22,21 @@ bytes = "1"
lru = "0.12"
xxhash-rust = { version = "0.8", features = ["xxh3"] }
futures-util = "0.3"
-tokio-util = { version = "0.7", features = ["rt"] }
-redis = { version = "0.27", default-features = false, features = ["tokio-comp", "connection-manager"] }
+tokio-util = { version = "0.7", features = ["rt", "io"] }
+async-compression = { version = "0.4", features = ["tokio", "zstd"] }
+zstd = "0.13"
+redis = { version = "0.27", default-features = false, features = ["tokio-comp", "connection-manager", "tokio-rustls-comp"] }
+# Lambda self-invoke dispatch (ASSEMBLER_DISPATCH=lambda): one SigV4-signed POST
+# to the Lambda Invoke API (Event type). Hand-signed — the aws-sdk tree needs
+# rustc 1.94 (ours is 1.90) and is ~40 crates for a single call; creds come
+# straight from the Lambda runtime env.
+hmac = "0.12"
+sha2 = "0.10"
+hex = "0.4"
+tower-http = { version = "0.6", features = ["compression-zstd", "compression-gzip"] }
+memmap2 = "0.9"
+file-format = "0.26"
+tempfile = "3"
[target.'cfg(target_os = "linux")'.dependencies]
tikv-jemallocator = "0.6"
diff --git a/apps/assembler/Dockerfile b/apps/assembler/Dockerfile
index bbdac3eb85..3f24a028fd 100644
--- a/apps/assembler/Dockerfile
+++ b/apps/assembler/Dockerfile
@@ -27,14 +27,18 @@ FROM ${OCCT_IMAGE} AS occt
# Docker-layer cached; only rebuilt when the pinned versions below change.
FROM debian:bookworm-slim AS fcl
# SIMD baseline for the compiled GJK/EPA bits (the templated hot path is compiled
-# in the collision shim instead). x86-64-v3 = AVX2+FMA, the x86_64 Fargate fleet;
-# override for a different target arch (e.g. an arm64 image needs an -mcpu value).
-ARG MARCH=x86-64-v3
+# in the collision shim instead). Auto-derived from the build platform (buildx sets
+# TARGETARCH): x86-64-v3 (AVX2+FMA, the x86_64 Fargate fleet) for amd64, armv8.2-a
+# (Lambda Graviton2 / Neoverse-N1 baseline) for arm64. Override with
+# --build-arg MARCH=<value>.
+ARG TARGETARCH
+ARG MARCH
RUN apt-get update && apt-get install -y --no-install-recommends \
git cmake ninja-build g++ libeigen3-dev ca-certificates \
&& rm -rf /var/lib/apt/lists/*
# libccd — double precision (FCL requires it), static.
-RUN git clone --depth 1 --branch v2.1 https://github.com/danfis/libccd.git /ccd \
+RUN MARCH="${MARCH:-$( [ "$TARGETARCH" = arm64 ] && echo armv8.2-a || echo x86-64-v3 )}" \
+ && git clone --depth 1 --branch v2.1 https://github.com/danfis/libccd.git /ccd \
&& cmake -S /ccd -B /ccd/b -G Ninja -DCMAKE_BUILD_TYPE=Release \
-DCMAKE_INSTALL_PREFIX=/opt/fcl -DCMAKE_POSITION_INDEPENDENT_CODE=ON \
-DCMAKE_CXX_FLAGS_RELEASE="-O3 -march=${MARCH}" \
@@ -43,7 +47,8 @@ RUN git clone --depth 1 --branch v2.1 https://github.com/danfis/libccd.git /ccd
# FCL 0.7.0 — static, no octomap; finds ccd + Eigen under the same prefix.
# FCL ignores BUILD_SHARED_LIBS; its own FCL_STATIC_LIBRARY flag is what selects
# a static archive (verified: without it FCL builds libfcl.so regardless).
-RUN git clone --depth 1 --branch 0.7.0 https://github.com/flexible-collision-library/fcl.git /fcl \
+RUN MARCH="${MARCH:-$( [ "$TARGETARCH" = arm64 ] && echo armv8.2-a || echo x86-64-v3 )}" \
+ && git clone --depth 1 --branch 0.7.0 https://github.com/flexible-collision-library/fcl.git /fcl \
&& cmake -S /fcl -B /fcl/b -G Ninja -DCMAKE_BUILD_TYPE=Release \
-DCMAKE_INSTALL_PREFIX=/opt/fcl -DCMAKE_PREFIX_PATH=/opt/fcl \
-DCMAKE_POSITION_INDEPENDENT_CODE=ON \
@@ -51,6 +56,26 @@ RUN git clone --depth 1 --branch 0.7.0 https://github.com/flexible-collision-lib
-DFCL_STATIC_LIBRARY=ON -DFCL_WITH_OCTOMAP=OFF -DFCL_BUILD_TESTS=OFF \
&& cmake --build /fcl/b --target install
+# ---- static Draco (built from source; Debian/brew ship only shared) ----
+# KHR_draco_mesh_compression encoder for the optimise pipeline. Encoder-only
+# (transcoder off — we build the glTF ourselves in Rust), STATIC, so libdraco.a
+# links into the binary and the runtime image carries no draco .so. Draco vendors
+# its own deps, so no extra -dev packages. Docker-layer cached; rebuilt only when
+# the pinned version below changes.
+FROM debian:bookworm-slim AS draco
+ARG TARGETARCH
+ARG MARCH
+RUN apt-get update && apt-get install -y --no-install-recommends \
+ git cmake ninja-build g++ ca-certificates \
+ && rm -rf /var/lib/apt/lists/*
+RUN MARCH="${MARCH:-$( [ "$TARGETARCH" = arm64 ] && echo armv8.2-a || echo x86-64-v3 )}" \
+ && git clone --depth 1 --branch 1.5.7 https://github.com/google/draco.git /draco \
+ && cmake -S /draco -B /draco/b -G Ninja -DCMAKE_BUILD_TYPE=Release \
+ -DCMAKE_INSTALL_PREFIX=/opt/draco -DCMAKE_POSITION_INDEPENDENT_CODE=ON \
+ -DCMAKE_CXX_FLAGS_RELEASE="-O3 -march=${MARCH}" \
+ -DBUILD_SHARED_LIBS=OFF -DDRACO_TRANSCODER_SUPPORTED=OFF \
+ && cmake --build /draco/b --target install
+
# ---- Rust builder ----
FROM rust:1.90-bookworm AS build
# Eigen headers for the cxx shim; OpenBLAS/gfortran for the planner's BLAS.
@@ -60,6 +85,7 @@ RUN apt-get update && apt-get install -y --no-install-recommends \
&& rm -rf /var/lib/apt/lists/*
COPY --from=occt /opt/occt /opt/occt
COPY --from=fcl /opt/fcl /opt/fcl
+COPY --from=draco /opt/draco /opt/draco
WORKDIR /app
# Only the Rust workspace — not the whole monorepo (see Dockerfile.dockerignore).
COPY Cargo.toml Cargo.lock ./
@@ -68,16 +94,19 @@ COPY apps/assembler ./apps/assembler
# Point the cxx bridges at the static OCCT + static FCL/ccd (build.rs picks
# `static=` when it finds a .a at the prefix). Eigen headers from apt.
#
-# Build the x86_64 Fargate fleet for AVX2/FMA (x86-64-v3) so the planner's
-# collision-heavy loops and the Eigen/FCL math vectorize — matching the -march on
-# the C++ collision shim (crates/collision/build.rs). Conservative fleet baseline,
-# NOT target-cpu=native (which bakes the build box's ISA and SIGILLs on older
-# CPUs). Lives here (not .cargo/config.toml, which isn't copied into this build
-# context anyway) so it actually applies to the deploy target; env is
-# target-scoped, so cross-compiles/other arches are untouched.
+# Tune the Rust codegen per target: x86-64-v3 (AVX2/FMA) for the x86_64 Fargate
+# fleet, neoverse-n1 for arm64 (Lambda Graviton2) — so the planner's collision-heavy
+# loops and the Eigen/FCL math vectorize, matching the C++ -march above
+# (crates/collision/build.rs). Conservative baselines, NOT target-cpu=native (which
+# bakes the build box's ISA and SIGILLs on older CPUs). Both are target-triple
+# scoped, so only the one matching the build arch applies — the other is inert.
+# Lives here (not .cargo/config.toml, which isn't copied into this build context
+# anyway) so it actually applies to the deploy target.
ENV OCCT_PREFIX=/opt/occt OCCT_LINK=static \
FCL_PREFIX=/opt/fcl LIBCCD_PREFIX=/opt/fcl EIGEN_PREFIX=/usr OCTOMAP_PREFIX=/usr \
- CARGO_TARGET_X86_64_UNKNOWN_LINUX_GNU_RUSTFLAGS="-C target-cpu=x86-64-v3"
+ DRACO_PREFIX=/opt/draco \
+ CARGO_TARGET_X86_64_UNKNOWN_LINUX_GNU_RUSTFLAGS="-C target-cpu=x86-64-v3" \
+ CARGO_TARGET_AARCH64_UNKNOWN_LINUX_GNU_RUSTFLAGS="-C target-cpu=neoverse-n1"
# Cache mounts: the cargo registry and the target dir survive across builds,
# so a code-only change relinks instead of recompiling every dependency.
# The binary is copied out because cache mounts vanish after the RUN.
@@ -98,6 +127,15 @@ RUN apt-get update && apt-get install -y --no-install-recommends \
&& rm -rf /var/lib/apt/lists/* \
&& useradd --system --uid 1001 --create-home assembler
COPY --from=build /usr/local/bin/assembler /usr/local/bin/assembler
+# AWS Lambda Web Adapter — proxies a Lambda invoke to the HTTP server so the same
+# image runs unchanged on Lambda (default), and is inert on ECS/EC2/local. Point
+# it at our port (LWA defaults to 8080). Pin: verify against the latest release.
+COPY --from=public.ecr.aws/awsguru/aws-lambda-adapter:0.9.1 /lambda-adapter /opt/extensions/lambda-adapter
+# Both the app and the Lambda Web Adapter read PORT (LWA falls back to it).
+ENV PORT=8000
+# Non-HTTP (Event) invokes — the self-dispatch worker path — are POSTed by the
+# adapter to this app route instead of being translated as HTTP requests.
+ENV AWS_LWA_PASS_THROUGH_PATH=/events
USER assembler
EXPOSE 8000
HEALTHCHECK --interval=30s --timeout=3s --start-period=5s --retries=3 \
diff --git a/apps/assembler/package.json b/apps/assembler/package.json
new file mode 100644
index 0000000000..0c4105158e
--- /dev/null
+++ b/apps/assembler/package.json
@@ -0,0 +1,8 @@
+{
+ "name": "carbon-assembler-infra",
+ "private": true,
+ "description": "SST (Ion) infrastructure for the Rust assembler service. Deploy: `pnpm exec sst deploy --stage <stage>`. The Rust app itself is a cargo crate; this package only carries the IaC toolchain.",
+ "devDependencies": {
+ "sst": "4.6.9"
+ }
+}
diff --git a/apps/assembler/src/actions/compact.rs b/apps/assembler/src/actions/compact.rs
new file mode 100644
index 0000000000..027d1fd755
--- /dev/null
+++ b/apps/assembler/src/actions/compact.rs
@@ -0,0 +1,178 @@
+//! `compact` action — shrink the retained raw so lazy planning + reoptimise keep
+//! working without hoarding the fat upload. Two modes:
+//!
+//! - `xbf` (STEP sources): STEP → OCCT BinXCAF (`.xbf`, lossless B-rep +
+//! assembly tree + names + colors, already mm) → zstd. Far smaller and
+//! faster to parse than ASCII STEP; the planner/convert/optimize read
+//! it transparently (content-sniffed as `xbf`).
+//! - `zstd` (mesh sources: glTF/GLB/STL): plain zstd of the raw — nothing to
+//! re-topologise, but reoptimise still needs the bytes.
+//!
+//! Async job; the single compressed `raw` output is late-mint uploaded. The
+//! caller then repoints `modelUpload.modelPath` at it and deletes the fat
+//! original. `download_hashed` decompresses any `.zst` source transparently, so
+//! re-running compact on an already-compacted model is a no-op-safe passthrough.
+
+use crate::jobs::{Done, Output};
+use crate::{http, AppState};
+use serde_json::json;
+use std::sync::Arc;
+use std::time::Instant;
+
+#[derive(Clone, Copy, PartialEq, Eq)]
+pub enum Mode {
+ /// STEP → BinXCAF (`.xbf`) → zstd.
+ Xbf,
+ /// Raw bytes → zstd (mesh sources).
+ Zstd,
+}
+
+impl Mode {
+ pub fn from_str(s: &str) -> Option<Mode> {
+ match s.trim().to_ascii_lowercase().as_str() {
+ "xbf" => Some(Mode::Xbf),
+ "zstd" | "zst" => Some(Mode::Zstd),
+ _ => None,
+ }
+ }
+}
+
+pub struct CompactReq {
+ pub source_url: String,
+ pub mode: Mode,
+ /// Storage path recorded in the completion pointer (the app persists it and
+ /// repoints modelPath); the signed PUT URL is late-minted per poll, key `raw`.
+ pub raw_path: Option<String>,
+}
+
+/// zstd level for the retained artifact. Background job, so favour ratio, but
+/// not the glacial max — STEP/xbf/glTF text all compress well at this mid level.
+const ZSTD_LEVEL: i32 = 12;
+
+pub fn spawn(state: &AppState, job_id: &str, req: CompactReq) {
+ let jobs = state.jobs.clone();
+ let slots = Arc::clone(&state.slots);
+ let job_id = job_id.to_string();
+ tokio::spawn(async move {
+ let _permit = slots.acquire().await;
+ if jobs.is_canceled(&job_id).await {
+ return;
+ }
+ jobs.set_status(&job_id, "running").await;
+ eprintln!("[{job_id}] compact running");
+ let started = Instant::now();
+
+ let src = http::temp_path("src");
+ if let Err(e) = http::download_hashed(&req.source_url, &src, None).await {
+ let _ = tokio::fs::remove_file(&src).await;
+ eprintln!("[{job_id}] compact failed: source download: {}", e.message);
+ jobs.set_error(&job_id, &e.code, e.message).await;
+ return;
+ }
+ let src_str = src.to_string_lossy().to_string();
+ let mode = req.mode;
+ let level = ZSTD_LEVEL;
+
+ let res = tokio::task::spawn_blocking(move || compress(&src_str, mode, level)).await;
+ let _ = tokio::fs::remove_file(&src).await;
+
+ let out = match res {
+ Ok(Ok(o)) => o,
+ Ok(Err(e)) => {
+ eprintln!("[{job_id}] compact failed ({}): {}", e.code, e.message);
+ jobs.set_error(&job_id, e.code, e.message).await;
+ return;
+ }
+ Err(e) => {
+ let msg = format!("compact panicked: {e}");
+ eprintln!("[{job_id}] {msg}");
+ jobs.set_error(&job_id, "compact_failed", msg).await;
+ return;
+ }
+ };
+
+ let compact_ms = started.elapsed().as_millis() as i64;
+ eprintln!(
+ "[{job_id}] compact done: {} -> {} bytes ({}), {compact_ms}ms",
+ out.input_bytes,
+ out.bytes.len(),
+ out.kind,
+ );
+
+ let done = Done {
+ result: json!({
+ "kind": out.kind,
+ "outputs": { "raw": { "path": req.raw_path, "bytes": out.bytes.len() } },
+ }),
+ stats: json!({
+ "inputBytes": out.input_bytes,
+ "outputBytes": out.bytes.len(),
+ "compactMs": compact_ms,
+ }),
+ };
+ let outputs = vec![Output {
+ name: "raw".into(),
+ content_type: "application/zstd".into(),
+ bytes: out.bytes,
+ }];
+ jobs.finish(&job_id, outputs, done, None).await;
+ });
+}
+
+struct CompactErr {
+ code: &'static str,
+ message: String,
+}
+
+struct Compacted {
+ bytes: Vec<u8>,
+ input_bytes: u64,
+ kind: &'static str,
+}
+
+fn compress(src_path: &str, mode: Mode, level: i32) -> Result<Compacted, CompactErr> {
+ let input_bytes = std::fs::metadata(src_path).map(|m| m.len()).unwrap_or(0);
+ match mode {
+ Mode::Xbf => {
+ let xbf = http::temp_path("xbf");
+ let xbf_str = xbf.to_string_lossy().to_string();
+ let r = converter::convert::step_to_xbf(src_path, &xbf_str).map_err(|e| CompactErr {
+ code: "tessellation_failed",
+ message: e.message,
+ });
+ if let Err(e) = r {
+ let _ = std::fs::remove_file(&xbf);
+ return Err(e);
+ }
+ let bytes = zstd_file(&xbf_str, level).map_err(|e| CompactErr {
+ code: "compact_failed",
+ message: e,
+ });
+ let _ = std::fs::remove_file(&xbf);
+ Ok(Compacted {
+ bytes: bytes?,
+ input_bytes,
+ kind: "xbf",
+ })
+ }
+ Mode::Zstd => {
+ let bytes = zstd_file(src_path, level).map_err(|e| CompactErr {
+ code: "compact_failed",
+ message: e,
+ })?;
+ Ok(Compacted {
+ bytes,
+ input_bytes,
+ kind: "zstd",
+ })
+ }
+ }
+}
+
+/// Stream a file through zstd into an owned buffer (the compressed artifact is
+/// small — read is streaming, only the result is held).
+fn zstd_file(path: &str, level: i32) -> Result<Vec<u8>, String> {
+ let file = std::fs::File::open(path).map_err(|e| format!("open {path}: {e}"))?;
+ zstd::stream::encode_all(std::io::BufReader::new(file), level)
+ .map_err(|e| format!("zstd encode: {e}"))
+}
diff --git a/apps/assembler/src/actions/convert.rs b/apps/assembler/src/actions/convert.rs
new file mode 100644
index 0000000000..3874aa808d
--- /dev/null
+++ b/apps/assembler/src/actions/convert.rs
@@ -0,0 +1,228 @@
+//! `convert` action — STEP → GLB + graph.json. Async job: the caller long-polls
+//! and hands fresh signed upload URLs (`glb`, `graph`) per poll (late-mint). The
+//! in-process result cache still skips re-tessellation for repeated content; the
+//! artifacts are re-uploaded to each job's own paths.
+
+use crate::cache::{CachedConvert, ResultCache};
+use crate::jobs::{Done, Output};
+use crate::{config, http, progress, AppState};
+use serde_json::json;
+use std::sync::Arc;
+use std::time::Instant;
+
+/// Everything a convert task needs from the request.
+pub struct ConvertReq {
+ pub source_url: String,
+ /// Caller-declared content identity (storage etag); a hit skips the download.
+ pub declared_hash: Option<String>,
+ /// Storage paths recorded in the completion pointer (the app persists these);
+ /// the actual signed PUT URLs are late-minted per poll, keyed `glb`/`graph`.
+ pub glb_path: Option<String>,
+ pub graph_path: Option<String>,
+ pub lin: f64,
+ pub ang: f64,
+ /// Run meshopt geometry passes + EXT_meshopt encode on the GLB (default true).
+ pub optimize: bool,
+}
+
+pub fn spawn(state: &AppState, job_id: &str, req: ConvertReq) {
+ let jobs = state.jobs.clone();
+ let cache = Arc::clone(&state.cache);
+ let progress_store = state.progress.clone();
+ let slots = Arc::clone(&state.slots);
+ let job_id = job_id.to_string();
+ tokio::spawn(async move {
+ let _permit = slots.acquire().await;
+ if jobs.is_canceled(&job_id).await {
+ return;
+ }
+ jobs.set_status(&job_id, "running").await;
+ let tracker = progress_store.start(&job_id);
+ eprintln!("[{job_id}] convert running");
+ let started = Instant::now();
+
+ // Declared-hash pre-check: a hit skips the source download entirely.
+ if let Some(h) = &req.declared_hash {
+ let key = ResultCache::key_declared(h, req.lin, req.ang);
+ if let Some(entry) = cache.get(&key) {
+ tracker.progress.set_phase(progress::PHASE_UPLOAD);
+ complete(&jobs, &job_id, &req, entry, started, true).await;
+ return;
+ }
+ }
+
+ let tmp = http::temp_path("step");
+ let content_hash =
+ match http::download_hashed(&req.source_url, &tmp, Some(&tracker.progress)).await {
+ Ok(h) => h,
+ Err(e) => {
+ let _ = tokio::fs::remove_file(&tmp).await;
+ eprintln!("[{job_id}] convert failed: source download: {}", e.message);
+ jobs.set_error(&job_id, &e.code, e.message).await;
+ return;
+ }
+ };
+ tracker.progress.set_phase(progress::PHASE_CONVERT);
+
+ let key = match &req.declared_hash {
+ Some(h) => ResultCache::key_declared(h, req.lin, req.ang),
+ None => ResultCache::key(content_hash, req.lin, req.ang),
+ };
+ let entry = match cache.get(&key) {
+ Some(entry) => {
+ let _ = tokio::fs::remove_file(&tmp).await;
+ entry
+ }
+ None => {
+ let tmp_str = tmp.to_string_lossy().to_string();
+ let cache_ins = Arc::clone(&cache);
+ let (lin, ang, optimize) = (req.lin, req.ang, req.optimize);
+ let res = tokio::task::spawn_blocking(move || {
+ // Unit detection scans at most the first 32MB of STEP text.
+ let text = read_head_lossy(&tmp_str, 32 * 1024 * 1024)?;
+ converter::convert::convert_step(&tmp_str, &text, lin, ang).map(|conv| {
+ let glb = if optimize {
+ optimize_glb(conv.glb)
+ } else {
+ conv.glb
+ };
+ let entry = Arc::new(CachedConvert {
+ glb: glb.into(),
+ graph_bytes: serde_json::to_vec(&conv.graph).unwrap().into(),
+ component_count: conv.component_count,
+ triangles: conv.triangles,
+ unit: conv.graph["unit"].clone(),
+ });
+ cache_ins.insert(key, Arc::clone(&entry));
+ entry
+ })
+ })
+ .await;
+ let _ = tokio::fs::remove_file(&tmp).await;
+ match res {
+ Ok(Ok(entry)) => entry,
+ Ok(Err(e)) => {
+ let code = convert_code(&e);
+ eprintln!("[{job_id}] convert failed: {}", e.message);
+ jobs.set_error(&job_id, code, e.message).await;
+ return;
+ }
+ Err(e) => {
+ let msg = format!("convert panicked: {e}");
+ eprintln!("[{job_id}] {msg}");
+ jobs.set_error(&job_id, "TESSELLATION_FAILED", msg).await;
+ return;
+ }
+ }
+ }
+ };
+
+ tracker.progress.set_phase(progress::PHASE_UPLOAD);
+ complete(&jobs, &job_id, &req, entry, started, false).await;
+ });
+}
+
+/// Enforce the part-count limit, then hold the GLB + graph for late-mint upload.
+async fn complete(
+ jobs: &crate::jobs::JobStore,
+ job_id: &str,
+ req: &ConvertReq,
+ entry: Arc<CachedConvert>,
+ started: Instant,
+ was_hit: bool,
+) {
+ let mp = config::max_parts();
+ if entry.component_count > mp as i64 {
+ jobs.set_error(
+ job_id,
+ "LIMIT_EXCEEDED",
+ format!(
+ "assembly has {} part instances; the limit is {mp}",
+ entry.component_count
+ ),
+ )
+ .await;
+ return;
+ }
+
+ let convert_ms = started.elapsed().as_millis() as i64;
+ eprintln!(
+ "[{job_id}] convert computed: {} parts, {} triangles, {convert_ms}ms{}",
+ entry.component_count,
+ entry.triangles,
+ if was_hit { " (cache hit)" } else { "" }
+ );
+
+ let done = Done {
+ result: json!({
+ "componentCount": entry.component_count,
+ "unit": entry.unit,
+ "outputs": {
+ "glb": { "path": req.glb_path },
+ "graph": { "path": req.graph_path },
+ },
+ }),
+ stats: json!({ "convertMs": convert_ms, "meshTriangles": entry.triangles }),
+ };
+ let outputs = vec![
+ Output {
+ name: "glb".into(),
+ content_type: "model/gltf-binary".into(),
+ bytes: entry.glb.to_vec(),
+ },
+ Output {
+ name: "graph".into(),
+ content_type: "application/json".into(),
+ bytes: entry.graph_bytes.to_vec(),
+ },
+ ];
+ // Convert output paths are job-scoped, so no result-pointer cache (the bytes
+ // are cached in-process instead); artifacts always re-upload.
+ jobs.finish(job_id, outputs, done, None).await;
+}
+
+/// Meshopt geometry optimisation + EXT_meshopt encode on the convert output.
+/// Full fidelity (no simplify) — convert must not drop geometry the planner and
+/// nodeIds depend on. Best-effort: on any optimise error keep the plain,
+/// contract-valid GLB rather than failing the convert.
+fn optimize_glb(glb: Vec<u8>) -> Vec<u8> {
+ let opts = optimize::Options {
+ codec: optimize::Codec::Meshopt,
+ simplify: None,
+ ..Default::default()
+ };
+ match optimize::optimize_glb(&glb, &opts) {
+ Ok(res) => res.glb,
+ Err(e) => {
+ eprintln!(
+ "convert: meshopt optimise skipped ({}); serving plain GLB",
+ e
+ );
+ glb
+ }
+ }
+}
+
+/// Read at most `cap` bytes from the head of a file, lossy-decoded.
+fn read_head_lossy(path: &str, cap: usize) -> Result<String, converter::convert::ConvertError> {
+ use std::io::Read;
+ let file = std::fs::File::open(path).map_err(|e| {
+ converter::convert::ConvertError::new("READ_FAILED", format!("read temp: {e}"))
+ })?;
+ let mut buf = Vec::new();
+ file.take(cap as u64).read_to_end(&mut buf).map_err(|e| {
+ converter::convert::ConvertError::new("READ_FAILED", format!("read temp: {e}"))
+ })?;
+ Ok(String::from_utf8_lossy(&buf).into_owned())
+}
+
+fn convert_code(e: &converter::convert::ConvertError) -> &'static str {
+ match e.code.as_str() {
+ "READ_FAILED" => "READ_FAILED",
+ "INVALID_INPUT" => "INVALID_INPUT",
+ "LIMIT_EXCEEDED" => "LIMIT_EXCEEDED",
+ "BUSY" => "BUSY",
+ "UPLOAD_FAILED" => "UPLOAD_FAILED",
+ _ => "TESSELLATION_FAILED",
+ }
+}
diff --git a/apps/assembler/src/actions/mod.rs b/apps/assembler/src/actions/mod.rs
new file mode 100644
index 0000000000..7e7080cc95
--- /dev/null
+++ b/apps/assembler/src/actions/mod.rs
@@ -0,0 +1,9 @@
+//! Per-action compute tasks. Each `spawn` runs the action in a Tokio task that
+//! holds a concurrency slot and drives the shared `JobStore` lifecycle
+//! (running → uploading/done/error). The HTTP layer (`main.rs`) only parses the
+//! request and calls `spawn`; all compute + storage I/O lives here.
+
+pub mod compact;
+pub mod convert;
+pub mod optimize;
+pub mod plan;
diff --git a/apps/assembler/src/actions/optimize.rs b/apps/assembler/src/actions/optimize.rs
new file mode 100644
index 0000000000..e28309c323
--- /dev/null
+++ b/apps/assembler/src/actions/optimize.rs
@@ -0,0 +1,419 @@
+//! `optimize` action — any supported CAD/mesh input → optimised GLB. Resolves the
+//! source format (explicit or content auto-detected), loads it into a GLB
+//! (OCCT-tessellating B-rep, ingesting STL, mmapping a GLB, or repacking a text
+//! glTF to GLB via a streaming base64 decode), then runs the
+//! meshopt geometry passes + codec encode (via `crates/optimize`), walking a
+//! simplify ladder until the render-weight + output-size gates pass. Async job;
+//! late-mint uploads the single `glb` output. Fails loud with a typed error
+//! (`unsupported_format` / `ambiguous_format` / `tessellation_failed` /
+//! `cannot_fit_budget`) rather than storing an over-cap or wrong result.
+
+use crate::formats::{self, Format};
+use crate::jobs::{Done, Output};
+use crate::{http, AppState};
+use serde_json::json;
+use std::sync::Arc;
+use std::time::{Duration, Instant};
+
+pub struct OptimizeReq {
+ pub source_url: String,
+ /// Declared source format, or `"auto"` / empty to content-detect.
+ pub format: String,
+ /// Storage path recorded in the completion pointer (late-mint uploads here).
+ pub glb_path: Option<String>,
+ pub opts: Opts,
+}
+
+pub struct Opts {
+ pub codec: optimize::Codec,
+ /// Simplify rungs walked in order; the first passing the gates wins. `None` =
+ /// full fidelity. Default `[None]`.
+ pub ladder: Vec<Option<f32>>,
+ pub simplify_aggressive: bool,
+ pub weld: bool,
+ pub reorder: bool,
+ /// Quality/perf knob: max simplify error in mm (`None` = ratio-only).
+ pub tolerance: Option<f32>,
+ /// Auto-mode normalized error budget. `None` = lossless.
+ pub auto_error: Option<f32>,
+ /// Draco quantization bits (position, normal, texcoord) — Draco codec only.
+ pub draco_bits: (i32, i32, i32),
+ /// Quantize normals to i16 (none/meshopt codecs).
+ pub quantize_normals: bool,
+ /// Merge same-material primitives within a mesh.
+ pub merge_primitives: bool,
+ /// Decoded (render-weight) byte ceiling — the "packed" gate.
+ pub max_packed: usize,
+ /// Encoded output byte ceiling.
+ pub max_output: usize,
+ /// STEP/IGES tessellation deflection (ignored for mesh input).
+ pub lin: f64,
+ pub ang: f64,
+ /// Wall-clock budget for the simplify ladder (`quality.time_budget_secs`,
+ /// else auto: 720s on Lambda). `None` = unbounded. `spawn` turns this
+ /// into an absolute `deadline` relative to job start (so it also charges the
+ /// download + tessellation time already spent).
+ pub budget: Option<Duration>,
+ /// Absolute deadline computed in `spawn`; consumed by the ladder. Never set
+ /// from JSON.
+ pub deadline: Option<Instant>,
+}
+
+/// A typed action failure carrying the snake_case API error code.
+struct ActionErr {
+ code: &'static str,
+ message: String,
+}
+impl ActionErr {
+ fn new(code: &'static str, message: impl Into<String>) -> Self {
+ ActionErr {
+ code,
+ message: message.into(),
+ }
+ }
+}
+
+pub fn spawn(state: &AppState, job_id: &str, req: OptimizeReq) {
+ let jobs = state.jobs.clone();
+ let slots = Arc::clone(&state.slots);
+ let job_id = job_id.to_string();
+ tokio::spawn(async move {
+ let _permit = slots.acquire().await;
+ if jobs.is_canceled(&job_id).await {
+ return;
+ }
+ jobs.set_status(&job_id, "running").await;
+ eprintln!(
+ "[{job_id}] optimize running (codec={:?} format={})",
+ req.opts.codec, req.format
+ );
+ let started = Instant::now();
+
+ let tmp = http::temp_path("model");
+ if let Err(e) = http::download_hashed(&req.source_url, &tmp, None).await {
+ let _ = tokio::fs::remove_file(&tmp).await;
+ eprintln!("[{job_id}] optimize failed: source download: {}", e.message);
+ jobs.set_error(&job_id, &e.code, e.message).await;
+ return;
+ }
+ let tmp_str = tmp.to_string_lossy().to_string();
+ let declared = req.format.clone();
+ let ext = url_ext(&req.source_url);
+ let mut opts = req.opts;
+ // Charge the download + tessellation already spent against the budget.
+ opts.deadline = opts.budget.map(|b| started + b);
+
+ let res = tokio::task::spawn_blocking(move || {
+ run_optimize(&tmp_str, &declared, ext.as_deref(), &opts)
+ })
+ .await;
+ let _ = tokio::fs::remove_file(&tmp).await;
+
+ let outcome = match res {
+ Ok(Ok(o)) => o,
+ Ok(Err(e)) => {
+ eprintln!("[{job_id}] optimize failed ({}): {}", e.code, e.message);
+ jobs.set_error(&job_id, e.code, e.message).await;
+ return;
+ }
+ Err(e) => {
+ let msg = format!("optimize panicked: {e}");
+ eprintln!("[{job_id}] {msg}");
+ jobs.set_error(&job_id, "optimize_failed", msg).await;
+ return;
+ }
+ };
+
+ let optimise_ms = started.elapsed().as_millis() as i64;
+ eprintln!(
+ "[{job_id}] optimize done: {} ({} via) {} -> {} tris, {} -> {} bytes, ratio={:?}, {optimise_ms}ms",
+ outcome.detected_format,
+ outcome.detected_via,
+ outcome.stats.input_triangles,
+ outcome.stats.output_triangles,
+ outcome.stats.input_bytes,
+ outcome.glb.len(),
+ outcome.ratio,
+ );
+
+ let done = Done {
+ result: json!({
+ "detected_format": outcome.detected_format,
+ "detected_via": outcome.detected_via,
+ "outputs": {
+ "glb": {
+ "path": req.glb_path,
+ "bytes": outcome.glb.len(),
+ "codec": codec_name(outcome.codec),
+ }
+ },
+ "warnings": outcome.warnings,
+ }),
+ stats: json!({
+ "input_triangles": outcome.stats.input_triangles,
+ "output_triangles": outcome.stats.output_triangles,
+ "input_bytes": outcome.stats.input_bytes,
+ "output_bytes": outcome.glb.len(),
+ "render_weight_bytes": outcome.stats.decoded_bytes,
+ "simplify_ratio_used": outcome.ratio,
+ "optimise_ms": optimise_ms,
+ }),
+ };
+ let outputs = vec![Output {
+ name: "glb".into(),
+ content_type: "model/gltf-binary".into(),
+ bytes: outcome.glb,
+ }];
+ jobs.finish(&job_id, outputs, done, None).await;
+ });
+}
+
+struct Outcome {
+ glb: Vec<u8>,
+ stats: optimize::Stats,
+ codec: optimize::Codec,
+ ratio: Option<f32>,
+ warnings: Vec<String>,
+ detected_format: &'static str,
+ detected_via: &'static str,
+}
+
+/// GLB source bytes — an owned tessellation/STL-ingest, a memory-mapped uploaded
+/// GLB, or a memory-mapped repacked temp GLB (from a text glTF). All OS-paged, off
+/// the RSS.
+enum Src {
+ Owned(Vec<u8>),
+ Mapped(memmap2::Mmap),
+ /// Repacked temp `.glb` (from text glTF); the `TempPath` holds the file open
+ /// for the mmap's lifetime and deletes it on drop.
+ MappedTemp(memmap2::Mmap, #[allow(dead_code)] tempfile::TempPath),
+}
+impl Src {
+ fn bytes(&self) -> &[u8] {
+ match self {
+ Src::Owned(v) => v,
+ Src::Mapped(m) | Src::MappedTemp(m, _) => m,
+ }
+ }
+}
+
+/// Resolve the format, load the source into GLB bytes, then walk the simplify
+/// ladder — the first rung under both gates wins; if none fit, fail with
+/// `cannot_fit_budget` (never store an over-cap blob).
+fn run_optimize(
+ path: &str,
+ declared: &str,
+ ext: Option<&str>,
+ opts: &Opts,
+) -> Result<Outcome, ActionErr> {
+ let head = read_head_bytes(path, 512 * 1024).map_err(|e| ActionErr::new("invalid_input", e))?;
+ let size = std::fs::metadata(path).map(|m| m.len()).unwrap_or(0);
+
+ let (format, detected_via) = formats::resolve(declared, &head, size, ext)
+ .map_err(|e| ActionErr::new(e.code, e.message))?;
+ let detected_format = format.name();
+
+ let src = load_source(path, format, &head, opts)?;
+ let glb = src.bytes();
+ let input_bytes = glb.len();
+
+ let ladder = if opts.ladder.is_empty() {
+ vec![None]
+ } else {
+ opts.ladder.clone()
+ };
+
+ let mut best: Option<Outcome> = None;
+ let mut warnings: Vec<String> = Vec::new();
+ let mut i = 0;
+ while i < ladder.len() {
+ // Time-budget gate: if the wall-clock budget is spent and coarser rungs
+ // remain, jump straight to the coarsest. The skipped middle rungs are
+ // finer (larger output) than the coarsest, so if they'd fail the size gate
+ // the coarsest is the only one with a chance — running them first only
+ // burns the remaining window. Preserves the size invariant: a no-fit
+ // coarsest still fails `cannot_fit_budget` below (never stores over-cap).
+ if let Some(dl) = opts.deadline {
+ let last = ladder.len() - 1;
+ if i < last && Instant::now() >= dl {
+ warnings.push(format!(
+ "time budget spent after rung {:?}; skipping to coarsest rung {:?}",
+ ladder[i], ladder[last]
+ ));
+ i = last;
+ }
+ }
+ let rung = ladder[i];
+ let o = optimize::Options {
+ codec: opts.codec,
+ simplify: rung,
+ tolerance: opts.tolerance,
+ auto_error: opts.auto_error,
+ simplify_aggressive: opts.simplify_aggressive,
+ draco_bits: opts.draco_bits,
+ quantize_normals: opts.quantize_normals,
+ merge_primitives: opts.merge_primitives,
+ weld: opts.weld,
+ reorder: opts.reorder,
+ };
+ // Every source is GLB here (STEP/STL ingested to GLB, GLB mmap'd, text
+ // glTF repacked to GLB in load_source).
+ let mut res = optimize::optimize_glb(glb, &o)
+ .map_err(|e| ActionErr::new("optimize_failed", e.message))?;
+ res.stats.input_bytes = input_bytes;
+ let passes = res.stats.decoded_bytes <= opts.max_packed && res.glb.len() <= opts.max_output;
+ let outcome = Outcome {
+ glb: res.glb,
+ stats: res.stats,
+ codec: opts.codec,
+ ratio: rung,
+ warnings: Vec::new(),
+ detected_format,
+ detected_via,
+ };
+ if passes {
+ return Ok(outcome);
+ }
+ warnings.push(format!(
+ "rung {:?} over budget: render-weight {}B (max {}B), output {}B (max {}B)",
+ rung,
+ outcome.stats.decoded_bytes,
+ opts.max_packed,
+ outcome.glb.len(),
+ opts.max_output
+ ));
+ best = Some(outcome);
+ i += 1;
+ }
+
+ // Nothing fit the budget even at the most aggressive rung: fail loud rather
+ // than store an artifact the served bucket would reject.
+ let smallest = best.map(|o| o.glb.len()).unwrap_or(0);
+ Err(ActionErr::new(
+ "cannot_fit_budget",
+ format!(
+ "could not fit the size/render-weight budget (smallest {smallest}B, max {}B); tried rungs {:?}. {}",
+ opts.max_output,
+ opts.ladder,
+ warnings.join("; ")
+ ),
+ ))
+}
+
+/// Load the resolved format into GLB bytes.
+fn load_source(path: &str, format: Format, head: &[u8], opts: &Opts) -> Result<Src, ActionErr> {
+ match format {
+ Format::Step => {
+ let text = String::from_utf8_lossy(head).into_owned();
+ let glb = converter::convert::convert_step(path, &text, opts.lin, opts.ang)
+ .map_err(|e| ActionErr::new("tessellation_failed", e.message))?
+ .glb;
+ Ok(Src::Owned(glb))
+ }
+ Format::Xbf => {
+ // Compacted retained raw (BinXCAF). Geometry already mm; tessellate
+ // like STEP. Lets reoptimise run off the compacted source.
+ let glb = converter::convert::convert_xbf(path, opts.lin, opts.ang)
+ .map_err(|e| ActionErr::new("tessellation_failed", e.message))?
+ .glb;
+ Ok(Src::Owned(glb))
+ }
+ Format::Stl => {
+ let bytes =
+ std::fs::read(path).map_err(|e| ActionErr::new("invalid_input", e.to_string()))?;
+ let glb = optimize::stl_to_glb(&bytes)
+ .map_err(|e| ActionErr::new("optimize_failed", e.message))?;
+ Ok(Src::Owned(glb))
+ }
+ Format::Glb => {
+ let file = std::fs::File::open(path)
+ .map_err(|e| ActionErr::new("invalid_input", format!("open source: {e}")))?;
+ let map = unsafe { memmap2::Mmap::map(&file) }
+ .map_err(|e| ActionErr::new("invalid_input", format!("mmap source: {e}")))?;
+ Ok(Src::Mapped(map))
+ }
+ Format::Gltf => {
+ use std::io::Write as _;
+ // Repack text glTF → GLB with a streaming base64 decode, then mmap the
+ // GLB and run the bounded GLB path. A serde parse of a multi-GB glTF
+ // holds the base64 string + decoded bytes at once (~3× the file); this
+ // keeps peak memory off the geometry (it lives in the temp GLB on disk).
+ let file = std::fs::File::open(path)
+ .map_err(|e| ActionErr::new("invalid_input", format!("open source: {e}")))?;
+ let gltf = unsafe { memmap2::Mmap::map(&file) }
+ .map_err(|e| ActionErr::new("invalid_input", format!("mmap source: {e}")))?;
+ let mut tmp = tempfile::NamedTempFile::new()
+ .map_err(|e| ActionErr::new("invalid_input", format!("temp glb: {e}")))?;
+ {
+ let mut bw = std::io::BufWriter::new(&mut tmp);
+ optimize::gltf_to_glb(&gltf, &mut bw)
+ .map_err(|e| ActionErr::new("optimize_failed", e.message))?;
+ bw.flush().map_err(|e| {
+ ActionErr::new("optimize_failed", format!("flush temp glb: {e}"))
+ })?;
+ }
+ let temp_path = tmp.into_temp_path();
+ let glb_file = std::fs::File::open(&temp_path)
+ .map_err(|e| ActionErr::new("invalid_input", format!("open temp glb: {e}")))?;
+ let glb_map = unsafe { memmap2::Mmap::map(&glb_file) }
+ .map_err(|e| ActionErr::new("invalid_input", format!("mmap temp glb: {e}")))?;
+ Ok(Src::MappedTemp(glb_map, temp_path))
+ }
+ // Plain mesh formats: parse → triangle-soup GLB (the optimiser's weld
+ // pass reconstructs sharing) → the bounded GLB path.
+ Format::Obj | Format::Ply | Format::Off | Format::Bim | Format::ThreeMf | Format::Amf => {
+ let bytes =
+ std::fs::read(path).map_err(|e| ActionErr::new("invalid_input", e.to_string()))?;
+ let glb = match format {
+ Format::Obj => optimize::obj_to_glb(&bytes),
+ Format::Ply => optimize::ply_to_glb(&bytes),
+ Format::Off => optimize::off_to_glb(&bytes),
+ Format::Bim => optimize::bim_to_glb(&bytes),
+ Format::ThreeMf => optimize::threemf_to_glb(&bytes),
+ _ => optimize::amf_to_glb(&bytes),
+ }
+ .map_err(|e| ActionErr::new("invalid_input", e.message))?;
+ Ok(Src::Owned(glb))
+ }
+ // Exact B-rep sources tessellated by OCCT, same walk as STEP.
+ Format::Iges => {
+ let glb = converter::convert::convert_iges(path, opts.lin, opts.ang)
+ .map_err(|e| ActionErr::new("tessellation_failed", e.message))?
+ .glb;
+ Ok(Src::Owned(glb))
+ }
+ Format::Brep => {
+ let glb = converter::convert::convert_brep(path, opts.lin, opts.ang)
+ .map_err(|e| ActionErr::new("tessellation_failed", e.message))?
+ .glb;
+ Ok(Src::Owned(glb))
+ }
+ }
+}
+
+fn read_head_bytes(path: &str, cap: usize) -> Result<Vec<u8>, String> {
+ use std::io::Read;
+ let file = std::fs::File::open(path).map_err(|e| format!("read temp: {e}"))?;
+ let mut buf = Vec::new();
+ file.take(cap as u64)
+ .read_to_end(&mut buf)
+ .map_err(|e| format!("read temp: {e}"))?;
+ Ok(buf)
+}
+
+/// Filename extension hint from a (possibly signed) URL — the last-resort tiebreak
+/// for format detection. Strips the query string.
+fn url_ext(url: &str) -> Option<String> {
+ let path = url.split(['?', '#']).next().unwrap_or(url);
+ let name = path.rsplit('/').next().unwrap_or(path);
+ name.rsplit_once('.')
+ .map(|(_, ext)| ext.to_ascii_lowercase())
+}
+
+fn codec_name(c: optimize::Codec) -> &'static str {
+ match c {
+ optimize::Codec::None => "none",
+ optimize::Codec::Meshopt => "meshopt",
+ optimize::Codec::Draco => "draco",
+ }
+}
diff --git a/apps/assembler/src/actions/plan.rs b/apps/assembler/src/actions/plan.rs
new file mode 100644
index 0000000000..a26f7a1b3d
--- /dev/null
+++ b/apps/assembler/src/actions/plan.rs
@@ -0,0 +1,216 @@
+//! `plan` action — collision-free disassembly motion planning. Async: the job
+//! runs detached, the caller long-polls. On completion the plan.json is either
+//! late-mint uploaded (a `planPath` was given) or returned inline in the result.
+
+use crate::jobs::{opts_hash, Done, Output};
+use crate::{config, http, AppState};
+use planner::steps::PlanUnit;
+use serde_json::{json, Value};
+use std::sync::Arc;
+use std::time::Instant;
+
+/// Everything a plan task needs from the request.
+pub struct PlanReq {
+ pub source_url: String,
+ /// Storage path recorded in the completion pointer (what the app persists).
+ /// The plan.json is PUT here later via a per-poll signed URL (late-mint).
+ pub plan_path: Option<String>,
+ /// Scopes the content-hash result cache; None disables caching for this job.
+ pub model_upload_id: Option<String>,
+ pub options: Value,
+}
+
+pub fn spawn(state: &AppState, job_id: &str, req: PlanReq) {
+ let jobs = state.jobs.clone();
+ let slots = Arc::clone(&state.slots);
+ let job_id = job_id.to_string();
+ tokio::spawn(async move {
+ let _permit = slots.acquire().await;
+ if jobs.is_canceled(&job_id).await {
+ return;
+ }
+ jobs.set_status(&job_id, "running").await;
+ eprintln!("[{job_id}] plan running");
+ let started = Instant::now();
+
+ let tmp = http::temp_path("step");
+ let content_hash = match http::download_hashed(&req.source_url, &tmp, None).await {
+ Ok(h) => h,
+ Err(e) => {
+ let msg = e.message;
+ eprintln!("[{job_id}] plan failed: source download: {msg}");
+ let _ = tokio::fs::remove_file(&tmp).await;
+ jobs.set_error(&job_id, "READ_FAILED", msg).await;
+ return;
+ }
+ };
+ let opts_h = opts_hash(&req.options);
+
+ // Content-hash result cache: same model + same bytes + same options +
+ // same CODE_VERSION => reuse the prior plan's pointer, skip the compute.
+ if let Some(model) = &req.model_upload_id {
+ if let Some(done) = jobs.result_get(model, content_hash, opts_h).await {
+ let _ = tokio::fs::remove_file(&tmp).await;
+ eprintln!("[{job_id}] plan cache hit");
+ jobs.set_done(&job_id, done).await;
+ jobs.send_callback(&job_id).await;
+ return;
+ }
+ }
+
+ let tmp_str = tmp.to_string_lossy().to_string();
+ let (lin, ang, clearance, path_samples, units, sequence, tolerance) =
+ parse_options(&req.options);
+ let mp = config::max_parts();
+
+ let res = tokio::task::spawn_blocking(move || {
+ planner::steps::plan_step(
+ &tmp_str,
+ lin,
+ ang,
+ clearance,
+ path_samples,
+ Some(mp),
+ units,
+ sequence,
+ tolerance,
+ )
+ })
+ .await;
+ let _ = tokio::fs::remove_file(&tmp).await;
+
+ match res {
+ Ok(Ok(r)) => {
+ let plan_ms = started.elapsed().as_millis() as i64;
+ let stats = json!({
+ "planMs": plan_ms,
+ "tiers": r.tiers,
+ "warnings": r.warnings,
+ "verifiedCount": r.verified_count,
+ "componentCount": r.component_count,
+ "plannedCount": r.planned_count,
+ });
+ eprintln!(
+ "[{job_id}] plan computed: {} parts, {} planned, {plan_ms}ms",
+ r.component_count, r.planned_count
+ );
+ let cache = req
+ .model_upload_id
+ .as_ref()
+ .map(|m| (m.clone(), content_hash, opts_h));
+
+ match &req.plan_path {
+ // Offload: late-mint upload the plan.json.
+ Some(path) => {
+ let bytes = match serde_json::to_vec(&r.plan) {
+ Ok(b) => b,
+ Err(e) => {
+ jobs.set_error(
+ &job_id,
+ "TESSELLATION_FAILED",
+ format!("serialize plan: {e}"),
+ )
+ .await;
+ return;
+ }
+ };
+ let done = Done {
+ result: json!({
+ "planPath": path,
+ "componentCount": r.component_count,
+ "plannedCount": r.planned_count,
+ }),
+ stats,
+ };
+ let outputs = vec![Output {
+ name: "plan".into(),
+ content_type: "application/json".into(),
+ bytes,
+ }];
+ jobs.finish(&job_id, outputs, done, cache).await;
+ }
+ // Inline: return the plan in the result for the app to persist.
+ None => {
+ let done = Done {
+ result: json!({
+ "plan": r.plan,
+ "componentCount": r.component_count,
+ "plannedCount": r.planned_count,
+ }),
+ stats,
+ };
+ jobs.set_done(&job_id, done).await;
+ jobs.send_callback(&job_id).await;
+ }
+ }
+ }
+ Ok(Err(e)) => {
+ eprintln!("[{job_id}] plan failed: {}", e.message);
+ jobs.set_error(&job_id, "TESSELLATION_FAILED", e.message)
+ .await;
+ }
+ Err(e) => {
+ let msg = format!("plan panicked: {e}");
+ eprintln!("[{job_id}] {msg}");
+ jobs.set_error(&job_id, "TESSELLATION_FAILED", msg).await;
+ }
+ }
+ });
+}
+
+type Opts = (
+ f64,
+ f64,
+ f64,
+ usize,
+ Option<Vec<PlanUnit>>,
+ Option<Vec<Vec<String>>>,
+ Option<f64>,
+);
+
+fn parse_options(options: &Value) -> Opts {
+ let lin = options["linearDeflection"].as_f64().unwrap_or(0.1);
+ let ang = options["angularDeflection"].as_f64().unwrap_or(0.5);
+ let clearance = options["clearance"].as_f64().unwrap_or(0.5);
+ let path_samples = options["pathSamples"].as_u64().unwrap_or(60) as usize;
+ let tolerance = options["tolerance"].as_f64();
+
+ let units = options["units"].as_array().map(|arr| {
+ arr.iter()
+ .map(|u| PlanUnit {
+ id: u["id"].as_str().unwrap_or("").to_string(),
+ name: u["name"].as_str().map(|s| s.to_string()),
+ node_ids: u["nodeIds"]
+ .as_array()
+ .map(|a| {
+ a.iter()
+ .filter_map(|v| v.as_str().map(|s| s.to_string()))
+ .collect()
+ })
+ .unwrap_or_default(),
+ })
+ .collect()
+ });
+ let sequence = options["sequence"].as_array().map(|arr| {
+ arr.iter()
+ .map(|g| {
+ g.as_array()
+ .map(|a| {
+ a.iter()
+ .filter_map(|v| v.as_str().map(|s| s.to_string()))
+ .collect()
+ })
+ .unwrap_or_default()
+ })
+ .collect()
+ });
+ (
+ lin,
+ ang,
+ clearance,
+ path_samples,
+ units,
+ sequence,
+ tolerance,
+ )
+}
diff --git a/apps/assembler/src/cache.rs b/apps/assembler/src/cache.rs
index 34e4ee9a38..97f8824540 100644
--- a/apps/assembler/src/cache.rs
+++ b/apps/assembler/src/cache.rs
@@ -13,7 +13,7 @@ use std::sync::{Arc, Mutex};
/// LRU (below) AND the Redis job/result-pointer store (`store.rs`). Bump on ANY
/// converter OR planner behavior change so every stale entry, in every cache,
/// auto-misses. This is the "content-hash key + CODE_VERSION" auto-invalidation.
-pub const CODE_VERSION: u32 = 1;
+pub const CODE_VERSION: u32 = 2;
pub struct CachedConvert {
pub glb: Bytes,
diff --git a/apps/assembler/src/config.rs b/apps/assembler/src/config.rs
index 5654a7dc64..9d42a3e792 100644
--- a/apps/assembler/src/config.rs
+++ b/apps/assembler/src/config.rs
@@ -2,41 +2,62 @@
use crate::error::ApiError;
-fn int_env(name: &str, default: usize) -> usize {
- std::env::var(name)
- .ok()
- .and_then(|s| s.parse().ok())
- .unwrap_or(default)
-}
+// Fixed, sane defaults — deliberately NOT env-tunable. Every knob here had a
+// plausible-sounding env var and no deployment that ever needed a different
+// value; unused knobs are just misconfiguration surface. Revisit a constant
+// when a real deployment proves it wrong, not before.
+/// Max source-download size: unlimited. The download streams to a temp file and
+/// the storage bucket already bounds upload size — no in-service cap.
pub fn max_source_bytes() -> usize {
- int_env("ASSEMBLER_MAX_SOURCE_MB", 250) * 1024 * 1024
+ 0
}
+/// Assembly part-instance ceiling (guards the planner's O(parts²) sweeps).
pub fn max_parts() -> usize {
- int_env("ASSEMBLER_MAX_PARTS", 5000)
+ 5000
}
-/// How long shutdown waits for running plan tasks after the HTTP listener
-/// drains. Match the orchestrator's termination grace period.
+/// How long shutdown waits for running tasks after the HTTP listener drains.
+/// Matches the orchestrator's termination grace period.
pub fn shutdown_grace() -> std::time::Duration {
- std::time::Duration::from_secs(int_env("ASSEMBLER_SHUTDOWN_GRACE_S", 600) as u64)
+ std::time::Duration::from_secs(600)
}
-/// Result-cache budget (bytes). 0 disables the cache.
+/// Result-cache budget.
pub fn cache_bytes() -> usize {
- int_env("ASSEMBLER_CACHE_MB", 512) * 1024 * 1024
+ 512 * 1024 * 1024
}
+/// Concurrent heavy jobs per instance — one per core, derived. Each job is
+/// CPU-bound (rayon sweeps saturate cores), so more slots than cores just
+/// thrashes; the semaphore also backs the 429-busy response and shutdown drain.
+/// Lambda runs one job per worker invocation regardless.
pub fn max_concurrency() -> usize {
- int_env("ASSEMBLER_MAX_CONCURRENCY", 2).max(1)
-}
-
-/// Redis URL for the shared job/result store. Unset => in-process backend (the
-/// single-process default). A set-but-unreachable URL falls back to memory at
-/// boot rather than refusing to start (mirrors @carbon/kv's soft-fail).
+ std::thread::available_parallelism()
+ .map(|n| n.get())
+ .unwrap_or(2)
+}
+
+/// Wall-clock budget (seconds) for the optimize simplify ladder. When active, a
+/// job running past it jumps straight to the coarsest rung instead of grinding
+/// every middle pass. Auto-derived: 720s on Lambda (lands under the 900s hard
+/// timeout), unbounded elsewhere (the standing service has no cap). Per-request
+/// `quality.time_budget_secs` overrides.
+pub fn optimize_budget_secs() -> Option<u64> {
+ std::env::var("AWS_LAMBDA_FUNCTION_NAME")
+ .is_ok()
+ .then_some(720)
+}
+
+/// Redis URL for the shared job/result store. REQUIRED — the store refuses to
+/// boot without it (see `JobStore::from_env`); job state must be shared so any
+/// replica / Lambda invocation can answer a poll. One `REDIS_URL` for the
+/// (prod, where the assembler's Redis must be reachable from Lambda and may
+/// differ from the app's), falling back to the stack-wide `REDIS_URL` so local
+/// dev reuses the crbn stack's Redis with zero extra config.
pub fn redis_url() -> Option<String> {
- std::env::var("ASSEMBLER_REDIS_URL")
+ std::env::var("REDIS_URL")
.ok()
.map(|s| s.trim().to_string())
.filter(|s| !s.is_empty())
@@ -45,25 +66,25 @@ pub fn redis_url() -> Option<String> {
/// TTL (seconds) for a Redis job-status entry — long enough to outlive any poll
/// window, short enough that abandoned jobs self-evict. Default 24h.
pub fn job_ttl_secs() -> u64 {
- int_env("ASSEMBLER_JOB_TTL_SECS", 86400) as u64
+ 86400
}
/// TTL (seconds) for a Redis content-hash result-pointer entry. Default 24h.
pub fn result_ttl_secs() -> u64 {
- int_env("ASSEMBLER_RESULT_TTL_SECS", 86400) as u64
+ 86400
}
/// TTL (seconds) for a computed-but-unuploaded plan held in Redis for hand-off
/// (compute -> the poll that uploads it). Short: a plan not drained within this
/// window is abandoned and the job re-plans. Default 5 min.
pub fn pending_ttl_secs() -> u64 {
- int_env("ASSEMBLER_PENDING_TTL_SECS", 300) as u64
+ 300
}
/// Server-side cap on the `?wait=` long-poll hold (seconds). Kept under typical
/// proxy/LB idle timeouts so a held request never trips them.
pub fn max_long_poll_secs() -> u64 {
- int_env("ASSEMBLER_MAX_LONG_POLL_S", 25) as u64
+ 25
}
/// Cap on tokio's blocking pool — the implicit convert queue. OCCT scales to
@@ -73,16 +94,7 @@ pub fn max_long_poll_secs() -> u64 {
/// tokio::fs ops from starving behind long converts.
pub fn blocking_threads() -> usize {
let cores = std::thread::available_parallelism().map_or(8, |n| n.get());
- int_env("ASSEMBLER_BLOCKING_THREADS", cores + 2).max(2)
-}
-
-pub fn allowed_url_hosts() -> Vec<String> {
- std::env::var("ASSEMBLER_ALLOWED_URL_HOSTS")
- .unwrap_or_default()
- .split(',')
- .map(|s| s.trim().to_lowercase())
- .filter(|s| !s.is_empty())
- .collect()
+ (cores + 2).max(2)
}
pub fn require_https() -> bool {
@@ -104,18 +116,11 @@ pub fn validate_url(url: &str) -> Result<(), ApiError> {
"unsupported URL scheme: {scheme}"
)));
}
- let allowed = allowed_url_hosts();
- if !allowed.is_empty() {
- let host = parsed.host_str().unwrap_or("").to_lowercase();
- if !allowed.contains(&host) {
- return Err(ApiError::invalid("URL host is not allowed"));
- }
- } else if require_https() {
- // No explicit allowlist, and not dev mode: default-deny SSRF against
- // internal targets by rejecting private/loopback/link-local IP literals.
- // (Dev fetches source URLs from local storage over portless, so this
- // only applies when ASSEMBLER_DEV_MODE != "true".) Set
- // ASSEMBLER_ALLOWED_URL_HOSTS in production for a positive allowlist.
+ if require_https() {
+ // Not dev mode: default-deny SSRF against internal targets by rejecting
+ // private/loopback/link-local IP literals. Sufficient because every URL
+ // reaching here was minted by our own bearer-authenticated jobs layer —
+ // a positive hostname allowlist added config surface, not security.
if let Some(host) = parsed.host_str() {
let literal = host.trim_start_matches('[').trim_end_matches(']');
if let Ok(ip) = literal.parse::<std::net::IpAddr>() {
diff --git a/apps/assembler/src/dispatch.rs b/apps/assembler/src/dispatch.rs
new file mode 100644
index 0000000000..0e188c837d
--- /dev/null
+++ b/apps/assembler/src/dispatch.rs
@@ -0,0 +1,178 @@
+//! Where the compute for a created job runs.
+//!
+//! `Local` (default): `tokio::spawn` in this process — correct for the ECS
+//! service, local dev, and the CLI, where the process outlives the request.
+//!
+//! `Lambda` (auto-detected via `AWS_LAMBDA_FUNCTION_NAME`): an instance FREEZES after the
+//! HTTP response, so an in-process spawn would never finish. Instead the create
+//! handler fires the job as a separate **Event-type self-invocation** of this
+//! same function (own 900s window). The Lambda Web Adapter delivers that
+//! non-HTTP event to `POST /events` (`AWS_LWA_PASS_THROUGH_PATH`), where the
+//! worker runs the exact `spawn` + `run_to_completion` path the CLI uses, and
+//! job state flows through the shared Redis `JobStore` so any instance's poll
+//! can answer. Requires `lambda:InvokeFunction` on itself (exec role) and
+//! `REDIS_URL` (a Memory store is invisible across instances).
+//!
+//! The Invoke call is SigV4-signed by hand: it is a single fixed-shape POST,
+//! the aws-sdk dependency tree needs a newer rustc than this workspace pins,
+//! and inside Lambda the credentials are simply env vars — no chain needed.
+
+use hmac::{Hmac, Mac};
+use serde_json::Value;
+use sha2::{Digest, Sha256};
+
+#[derive(Clone, Copy, PartialEq)]
+pub enum Dispatch {
+ Local,
+ Lambda,
+}
+
+/// Auto-detected: the Lambda runtime always sets `AWS_LAMBDA_FUNCTION_NAME`,
+/// and there is no legitimate cross-configuration (local dispatch inside Lambda
+/// dies at the post-response freeze; lambda dispatch outside has no invoke
+/// permission). Deriving it removes the knob AND its failure mode.
+pub fn from_env() -> Dispatch {
+ if std::env::var("AWS_LAMBDA_FUNCTION_NAME").is_ok() {
+ Dispatch::Lambda
+ } else {
+ Dispatch::Local
+ }
+}
+
+/// Fire-and-forget the job spec at this same function (`X-Amz-Invocation-Type:
+/// Event` → 202 + async retry semantics). Errors bubble to the create handler,
+/// which fails the job loudly — a spec that was never dispatched must not sit
+/// "pending" forever.
+pub async fn self_invoke(spec: &Value) -> Result<(), String> {
+ let env = |k: &str| std::env::var(k).map_err(|_| format!("{k} is not set"));
+ let fn_name = env("AWS_LAMBDA_FUNCTION_NAME")?;
+ let region = env("AWS_REGION").or_else(|_| env("AWS_DEFAULT_REGION"))?;
+ let access_key = env("AWS_ACCESS_KEY_ID")?;
+ let secret_key = env("AWS_SECRET_ACCESS_KEY")?;
+ let session_token = std::env::var("AWS_SESSION_TOKEN").ok();
+
+ let host = format!("lambda.{region}.amazonaws.com");
+ let path = format!("/2015-03-31/functions/{fn_name}/invocations");
+ let body = spec.to_string();
+ let (amz_date, date) = amz_timestamp();
+ let payload_hash = hex::encode(Sha256::digest(body.as_bytes()));
+
+ // Canonical request: sorted lowercase headers; no query string.
+ let mut headers: Vec<(String, String)> = vec![
+ ("content-type".into(), "application/json".into()),
+ ("host".into(), host.clone()),
+ ("x-amz-date".into(), amz_date.clone()),
+ ("x-amz-invocation-type".into(), "Event".into()),
+ ];
+ if let Some(t) = &session_token {
+ headers.push(("x-amz-security-token".into(), t.clone()));
+ }
+ headers.sort();
+ let canonical_headers: String = headers
+ .iter()
+ .map(|(k, v)| format!("{k}:{}\n", v.trim()))
+ .collect();
+ let signed_headers = headers
+ .iter()
+ .map(|(k, _)| k.as_str())
+ .collect::<Vec<_>>()
+ .join(";");
+ let canonical_request =
+ format!("POST\n{path}\n\n{canonical_headers}\n{signed_headers}\n{payload_hash}");
+
+ let scope = format!("{date}/{region}/lambda/aws4_request");
+ let string_to_sign = format!(
+ "AWS4-HMAC-SHA256\n{amz_date}\n{scope}\n{}",
+ hex::encode(Sha256::digest(canonical_request.as_bytes()))
+ );
+ let k_date = hmac_sha256(format!("AWS4{secret_key}").as_bytes(), date.as_bytes());
+ let k_region = hmac_sha256(&k_date, region.as_bytes());
+ let k_service = hmac_sha256(&k_region, b"lambda");
+ let k_signing = hmac_sha256(&k_service, b"aws4_request");
+ let signature = hex::encode(hmac_sha256(&k_signing, string_to_sign.as_bytes()));
+ let authorization = format!(
+ "AWS4-HMAC-SHA256 Credential={access_key}/{scope}, SignedHeaders={signed_headers}, Signature={signature}"
+ );
+
+ let client = reqwest::Client::new();
+ let mut req = client
+ .post(format!("https://{host}{path}"))
+ .header("content-type", "application/json")
+ .header("x-amz-date", &amz_date)
+ .header("x-amz-invocation-type", "Event")
+ .header("authorization", authorization)
+ .body(body);
+ if let Some(t) = &session_token {
+ req = req.header("x-amz-security-token", t);
+ }
+ let resp = req
+ .send()
+ .await
+ .map_err(|e| format!("lambda invoke request failed: {e}"))?;
+ let status = resp.status();
+ if !status.is_success() {
+ let text = resp.text().await.unwrap_or_default();
+ return Err(format!("lambda invoke returned {status}: {text}"));
+ }
+ Ok(())
+}
+
+fn hmac_sha256(key: &[u8], data: &[u8]) -> Vec<u8> {
+ let mut mac = Hmac::<Sha256>::new_from_slice(key).expect("hmac accepts any key length");
+ mac.update(data);
+ mac.finalize().into_bytes().to_vec()
+}
+
+/// Current UTC time as SigV4's (`YYYYMMDD'T'HHMMSS'Z'`, `YYYYMMDD`). Civil-date
+/// math (Hinnant's algorithm) instead of a chrono/time dependency.
+fn amz_timestamp() -> (String, String) {
+ let secs = std::time::SystemTime::now()
+ .duration_since(std::time::UNIX_EPOCH)
+ .expect("clock before epoch")
+ .as_secs() as i64;
+ let days = secs.div_euclid(86400);
+ let sod = secs.rem_euclid(86400);
+ let (h, mi, s) = (sod / 3600, (sod % 3600) / 60, sod % 60);
+
+ let z = days + 719_468;
+ let era = z.div_euclid(146_097);
+ let doe = z.rem_euclid(146_097);
+ let yoe = (doe - doe / 1460 + doe / 36524 - doe / 146_096) / 365;
+ let y = yoe + era * 400;
+ let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
+ let mp = (5 * doy + 2) / 153;
+ let d = doy - (153 * mp + 2) / 5 + 1;
+ let m = if mp < 10 { mp + 3 } else { mp - 9 };
+ let y = if m <= 2 { y + 1 } else { y };
+
+ let date = format!("{y:04}{m:02}{d:02}");
+ (format!("{date}T{h:02}{mi:02}{s:02}Z"), date)
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ // Signing-key derivation checked against the worked example in AWS's SigV4
+ // documentation (the canonical "AWS4-HMAC-SHA256" example secret + scope).
+ #[test]
+ fn sigv4_signing_key_matches_aws_example() {
+ let secret = "wJalrXUtnFEMI/K7MDENG+bPxRfiCYEXAMPLEKEY";
+ let k_date = hmac_sha256(format!("AWS4{secret}").as_bytes(), b"20150830");
+ let k_region = hmac_sha256(&k_date, b"us-east-1");
+ let k_service = hmac_sha256(&k_region, b"iam");
+ let k_signing = hmac_sha256(&k_service, b"aws4_request");
+ assert_eq!(
+ hex::encode(k_signing),
+ "c4afb1cc5771d871763a393e44b703571b55cc28424d1a5e86da6ed3c154a4b9"
+ );
+ }
+
+ #[test]
+ fn timestamp_shape() {
+ let (ts, d) = amz_timestamp();
+ assert_eq!(ts.len(), 16);
+ assert!(ts.ends_with('Z') && ts.as_bytes()[8] == b'T');
+ assert_eq!(&ts[..8], d.as_str());
+ }
+}
diff --git a/apps/assembler/src/error.rs b/apps/assembler/src/error.rs
index a5ccc831c1..fd2e096524 100644
--- a/apps/assembler/src/error.rs
+++ b/apps/assembler/src/error.rs
@@ -1,5 +1,5 @@
-//! Error contract — `{ok:false, error, code}` with the status codes from
-//! `app/errors.py` / `app/main.py`.
+//! Error contract — uniform `{ ok:false, error: { code, message } }` envelope
+//! with the status codes from `app/errors.py` / `app/main.py`.
use axum::{http::StatusCode, response::IntoResponse, Json};
use serde_json::json;
@@ -19,10 +19,10 @@ impl ApiError {
}
}
pub fn invalid(message: impl Into<String>) -> Self {
- ApiError::new(400, "INVALID_INPUT", message)
+ ApiError::new(400, "invalid_input", message)
}
pub fn unauthorized(message: impl Into<String>) -> Self {
- ApiError::new(401, "UNAUTHORIZED", message)
+ ApiError::new(401, "unauthorized", message)
}
}
@@ -46,7 +46,7 @@ impl IntoResponse for ApiError {
let status = StatusCode::from_u16(self.status).unwrap_or(StatusCode::INTERNAL_SERVER_ERROR);
let mut resp = (
status,
- Json(json!({"ok": false, "error": self.message, "code": self.code})),
+ Json(json!({"ok": false, "error": {"code": self.code, "message": self.message}})),
)
.into_response();
// 429s tell callers when to come back so their retries don't hammer
diff --git a/apps/assembler/src/formats.rs b/apps/assembler/src/formats.rs
new file mode 100644
index 0000000000..f0458e5f6b
--- /dev/null
+++ b/apps/assembler/src/formats.rs
@@ -0,0 +1,353 @@
+//! Explicit input-format registry + content auto-detection.
+//!
+//! One source of truth for what the assembler ingests. Surfaced via `GET /v1`
+//! discovery so the client never hand-maintains a format list. Detection is
+//! content-first (magic bytes / structural signatures + the binary-STL size
+//! formula), then the `file-format` crate as a broad net, then the filename
+//! extension as a last-resort hint. Genuinely unknown input fails loud
+//! (`ambiguous_format` / `unsupported_format`) — never a wrong guess into OCCT.
+
+#[derive(Clone, Copy, PartialEq, Eq, Debug)]
+pub enum Format {
+ Step,
+ Iges,
+ Brep,
+ /// OCCT BinXCAF document (`.xbf`) — the compacted lossless retained-raw form
+ /// of a STEP (B-rep + assembly tree + names + colors, already mm).
+ Xbf,
+ Glb,
+ Gltf,
+ Stl,
+ Obj,
+ Ply,
+ Off,
+ /// dotbim (`.bim`) — JSON meshes + instanced elements.
+ Bim,
+ /// 3MF (zip container, `3D/3dmodel.model` XML).
+ ThreeMf,
+ /// AMF (XML, optionally zip-wrapped).
+ Amf,
+}
+
+/// How the source is turned into a mesh: OCCT tessellation (exact B-rep) or a
+/// direct mesh parse.
+#[derive(Clone, Copy, PartialEq, Eq, Debug)]
+pub enum Loader {
+ Occt,
+ Mesh,
+}
+
+/// Every supported input token (canonical names + aliases), for the
+/// `unsupported_format` error payload.
+pub const SUPPORTED: &[&str] = &[
+ "step", "stp", "iges", "igs", "brep", "xbf", "glb", "gltf", "stl", "obj", "ply", "off", "bim", "3mf", "amf",
+];
+
+/// Canonical formats, in registry order — the `GET /v1` discovery listing.
+pub const ALL: &[Format] = &[
+ Format::Step,
+ Format::Iges,
+ Format::Brep,
+ Format::Xbf,
+ Format::Glb,
+ Format::Gltf,
+ Format::Stl,
+ Format::Obj,
+ Format::Ply,
+ Format::Off,
+ Format::Bim,
+ Format::ThreeMf,
+ Format::Amf,
+];
+
+impl Format {
+ pub fn name(self) -> &'static str {
+ match self {
+ Format::Step => "step",
+ Format::Iges => "iges",
+ Format::Brep => "brep",
+ Format::Xbf => "xbf",
+ Format::Glb => "glb",
+ Format::Gltf => "gltf",
+ Format::Stl => "stl",
+ Format::Obj => "obj",
+ Format::Ply => "ply",
+ Format::Off => "off",
+ Format::Bim => "bim",
+ Format::ThreeMf => "3mf",
+ Format::Amf => "amf",
+ }
+ }
+
+ pub fn loader(self) -> Loader {
+ match self {
+ Format::Step | Format::Iges | Format::Brep | Format::Xbf => Loader::Occt,
+ _ => Loader::Mesh,
+ }
+ }
+
+ pub fn loader_name(self) -> &'static str {
+ match self.loader() {
+ Loader::Occt => "occt",
+ Loader::Mesh => "mesh",
+ }
+ }
+
+ /// Exact B-rep source (precision preserved until tessellation).
+ pub fn exact(self) -> bool {
+ matches!(self.loader(), Loader::Occt)
+ }
+
+ /// Carries assembly structure (node hierarchy / groups) usable by `convert`.
+ pub fn structured(self) -> bool {
+ matches!(
+ self,
+ Format::Step
+ | Format::Iges
+ | Format::Brep
+ | Format::Xbf
+ | Format::Glb
+ | Format::Gltf
+ | Format::Obj
+ )
+ }
+
+ pub fn from_name(s: &str) -> Option<Format> {
+ match s.trim().to_ascii_lowercase().as_str() {
+ "step" | "stp" => Some(Format::Step),
+ "iges" | "igs" => Some(Format::Iges),
+ "brep" => Some(Format::Brep),
+ "xbf" => Some(Format::Xbf),
+ "glb" => Some(Format::Glb),
+ "gltf" => Some(Format::Gltf),
+ "stl" => Some(Format::Stl),
+ "obj" => Some(Format::Obj),
+ "ply" => Some(Format::Ply),
+ "off" => Some(Format::Off),
+ "bim" => Some(Format::Bim),
+ "3mf" => Some(Format::ThreeMf),
+ "amf" => Some(Format::Amf),
+ _ => None,
+ }
+ }
+}
+
+/// A typed detection failure. `code` is the snake_case API error code.
+#[derive(Debug)]
+pub struct FormatError {
+ pub code: &'static str,
+ pub message: String,
+}
+
+/// Resolve the effective format from the caller's `declared` value + content.
+/// `"auto"` (or empty) sniffs; an explicit format is trusted (content is only a
+/// cross-check). Returns `(format, detected_via)`.
+pub fn resolve(
+ declared: &str,
+ head: &[u8],
+ size: u64,
+ ext: Option<&str>,
+) -> Result<(Format, &'static str), FormatError> {
+ let declared = declared.trim().to_ascii_lowercase();
+ if declared.is_empty() || declared == "auto" {
+ return match sniff(head, size, ext) {
+ Some(f) => Ok((f, "content")),
+ None => Err(FormatError {
+ code: "ambiguous_format",
+ message: "could not determine format from content or extension".into(),
+ }),
+ };
+ }
+ match Format::from_name(&declared) {
+ Some(f) => Ok((f, "declared")),
+ None => Err(FormatError {
+ code: "unsupported_format",
+ message: format!(
+ "format '{declared}' not supported (supported: {})",
+ SUPPORTED.join(", ")
+ ),
+ }),
+ }
+}
+
+/// Content sniff. `head` = leading bytes, `size` = full byte length (for the
+/// binary-STL formula), `ext` = filename extension hint (last resort).
+pub fn sniff(head: &[u8], size: u64, ext: Option<&str>) -> Option<Format> {
+ // 1. Unambiguous binary/structural signatures.
+ if head.len() >= 4 && &head[0..4] == b"glTF" {
+ return Some(Format::Glb);
+ }
+ // OCCT BinXCAF documents start with the ASCII `BINFILE` magic.
+ if head.len() >= 7 && &head[0..7] == b"BINFILE" {
+ return Some(Format::Xbf);
+ }
+ let text = leading_text(head);
+ let trimmed = text.trim_start();
+ if trimmed.starts_with("ISO-10303-21") {
+ return Some(Format::Step);
+ }
+ if head.starts_with(b"ply") {
+ return Some(Format::Ply);
+ }
+ if trimmed.starts_with("OFF") || trimmed.starts_with("COFF") || trimmed.starts_with("NOFF") {
+ return Some(Format::Off);
+ }
+ if trimmed.starts_with("DBRep_") || text.contains("CASCADE Topology") {
+ return Some(Format::Brep);
+ }
+ if is_gltf_json(trimmed) {
+ return Some(Format::Gltf);
+ }
+ // dotbim: JSON with a schema_version + meshes (glTF JSON is caught above by
+ // its "asset" key, so no collision).
+ // AMF: XML root element (the zip-wrapped variant falls back to the ext hint,
+ // like 3MF — a bare PK header is indistinguishable from any other zip).
+ if trimmed.starts_with("<?xml") && text.contains("<amf") {
+ return Some(Format::Amf);
+ }
+ if trimmed.starts_with('{')
+ && trimmed.contains("\"schema_version\"")
+ && trimmed.contains("\"meshes\"")
+ {
+ return Some(Format::Bim);
+ }
+
+ // 2. Binary STL: the size formula BEFORE the ASCII "solid" prefix — a binary
+ // header can itself begin with "solid".
+ if head.len() >= 84 {
+ let count = u32::from_le_bytes([head[80], head[81], head[82], head[83]]) as u64;
+ if size == 84 + count * 50 {
+ return Some(Format::Stl);
+ }
+ }
+ if trimmed.starts_with("solid") && text.contains("facet") {
+ return Some(Format::Stl);
+ }
+
+ // 3. Text heuristics.
+ if looks_like_obj(&text) {
+ return Some(Format::Obj);
+ }
+ if is_iges(&text) {
+ return Some(Format::Iges);
+ }
+
+ // 4. Broad net, then the extension hint.
+ if let Some(f) = via_file_format(head) {
+ return Some(f);
+ }
+ ext.and_then(Format::from_name)
+}
+
+fn leading_text(head: &[u8]) -> String {
+ let n = head.len().min(4096);
+ String::from_utf8_lossy(&head[..n]).into_owned()
+}
+
+fn is_gltf_json(trimmed: &str) -> bool {
+ trimmed.starts_with('{') && trimmed.contains("\"asset\"")
+}
+
+fn looks_like_obj(text: &str) -> bool {
+ let mut has_vertex = false;
+ let mut has_face = false;
+ for line in text.lines() {
+ if line.starts_with("v ") {
+ has_vertex = true;
+ } else if line.starts_with("f ") {
+ has_face = true;
+ }
+ if has_vertex && has_face {
+ return true;
+ }
+ }
+ false
+}
+
+fn is_iges(text: &str) -> bool {
+ // IGES records are 80 columns; column 73 of the first record is the section
+ // letter ('S' for the start section).
+ text.lines()
+ .next()
+ .and_then(|l| l.as_bytes().get(72).copied())
+ == Some(b'S')
+}
+
+fn via_file_format(head: &[u8]) -> Option<Format> {
+ let ff = file_format::FileFormat::from_bytes(head);
+ Format::from_name(ff.extension())
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn sniff_bytes(b: &[u8]) -> Option<Format> {
+ sniff(b, b.len() as u64, None)
+ }
+
+ #[test]
+ fn detects_by_magic() {
+ assert_eq!(sniff_bytes(b"glTF\x02\0\0\0"), Some(Format::Glb));
+ assert_eq!(sniff_bytes(b"BINFILE\x01\x02\x03\x04"), Some(Format::Xbf));
+ assert_eq!(sniff_bytes(b"ISO-10303-21;\nHEADER;"), Some(Format::Step));
+ assert_eq!(sniff_bytes(b"ply\nformat ascii 1.0\n"), Some(Format::Ply));
+ assert_eq!(sniff_bytes(b"OFF\n8 6 0\n"), Some(Format::Off));
+ assert_eq!(
+ sniff_bytes(b"{\n \"asset\": { \"version\": \"2.0\" }\n}"),
+ Some(Format::Gltf)
+ );
+ }
+
+ #[test]
+ fn detects_binary_stl_by_size_formula() {
+ // 80-byte header (starting with "solid" to prove the formula wins over the
+ // ASCII prefix) + u32 count(1) + 50 bytes.
+ let mut b = vec![0u8; 80];
+ b[0..5].copy_from_slice(b"solid");
+ b.extend_from_slice(&1u32.to_le_bytes());
+ b.extend_from_slice(&[0u8; 50]);
+ assert_eq!(sniff(&b, b.len() as u64, None), Some(Format::Stl));
+ }
+
+ #[test]
+ fn detects_ascii_stl_and_obj() {
+ assert_eq!(
+ sniff_bytes(b"solid part\nfacet normal 0 0 1\nvertex 0 0 0\n"),
+ Some(Format::Stl)
+ );
+ assert_eq!(
+ sniff_bytes(b"# comment\nv 0 0 0\nv 1 0 0\nf 1 2 3\n"),
+ Some(Format::Obj)
+ );
+ }
+
+ #[test]
+ fn resolve_auto_vs_declared_vs_unsupported() {
+ let glb = b"glTF\x02\0\0\0";
+ assert_eq!(
+ resolve("auto", glb, glb.len() as u64, None).unwrap(),
+ (Format::Glb, "content")
+ );
+ // Declared is trusted (content advisory).
+ assert_eq!(
+ resolve("stl", b"", 0, None).unwrap(),
+ (Format::Stl, "declared")
+ );
+ assert_eq!(
+ resolve("fbx", glb, glb.len() as u64, None)
+ .unwrap_err()
+ .code,
+ "unsupported_format"
+ );
+ assert_eq!(
+ resolve("auto", b"random bytes", 12, None).unwrap_err().code,
+ "ambiguous_format"
+ );
+ // Extension fallback when content is inconclusive.
+ assert_eq!(
+ resolve("auto", b"random", 6, Some("stl")).unwrap(),
+ (Format::Stl, "content")
+ );
+ }
+}
diff --git a/apps/assembler/src/http.rs b/apps/assembler/src/http.rs
index 9fb9f4d830..b6445809cd 100644
--- a/apps/assembler/src/http.rs
+++ b/apps/assembler/src/http.rs
@@ -36,13 +36,20 @@ fn client() -> &'static reqwest::Client {
/// Stream the source to disk, hashing as it flows — one pass, no full-body RAM
/// buffer, and the content hash comes out free for the result-cache key.
/// `progress` (when given) is ticked with bytes done/total for live status.
+///
+/// Transparent zstd: a source whose first bytes are the zstd magic
+/// (`28 B5 2F FD`) is streamed through a decoder, so a stored `.zst` (e.g. the
+/// compacted `raw.xbf.zst`) lands on disk as the real STEP/XBF/mesh and every
+/// action consumes it unchanged. The hash + size guard are over the
+/// DECOMPRESSED bytes, so the result-cache key tracks geometry, not container.
pub async fn download_hashed(
url: &str,
dest: &std::path::Path,
progress: Option<&crate::progress::JobProgress>,
) -> Result<u128, ApiError> {
+ use async_compression::tokio::bufread::ZstdDecoder;
use futures_util::StreamExt;
- use tokio::io::AsyncWriteExt;
+ use tokio::io::{AsyncBufReadExt, AsyncReadExt, AsyncWriteExt};
let limit = config::max_source_bytes();
let resp = client().get(url).send().await.map_err(|e| {
@@ -59,19 +66,51 @@ pub async fn download_hashed(
format!("could not download source: {}", resp.status()),
));
}
- if let Some(len) = resp.content_length() {
- if len as usize > limit {
- return Err(ApiError::new(
- 413,
- "LIMIT_EXCEEDED",
- "source file exceeds the size limit",
- ));
- }
- if let Some(p) = progress {
+ // content-length is the on-the-wire (possibly compressed) size — advisory for
+ // progress only; the real cap is the decompressed `written` counter below.
+ if let Some(p) = progress {
+ if let Some(len) = resp.content_length() {
p.total.store(len, std::sync::atomic::Ordering::Relaxed);
}
}
+ let read_err = |e: std::io::Error, dest: &std::path::Path| {
+ let dest = dest.to_path_buf();
+ async move {
+ let _ = tokio::fs::remove_file(&dest).await;
+ ApiError::new(
+ 422,
+ "READ_FAILED",
+ format!("could not download source: {e}"),
+ )
+ }
+ };
+
+ // reqwest byte stream → AsyncBufRead, so the 4-byte magic can be peeked
+ // without consuming and the whole thing optionally piped through zstd.
+ let byte_stream = resp
+ .bytes_stream()
+ .map(|r| r.map_err(|e| std::io::Error::new(std::io::ErrorKind::Other, e)));
+ let mut buf_reader = tokio::io::BufReader::new(tokio_util::io::StreamReader::new(byte_stream));
+ let is_zstd = {
+ let head = buf_reader.fill_buf().await.map_err(|e| {
+ ApiError::new(
+ 422,
+ "READ_FAILED",
+ format!("could not download source: {e}"),
+ )
+ })?;
+ head.len() >= 4 && head[0..4] == [0x28, 0xB5, 0x2F, 0xFD]
+ };
+ // multiple_members: tolerate a source written as concatenated zstd frames.
+ let mut input: std::pin::Pin<Box<dyn tokio::io::AsyncRead + Send>> = if is_zstd {
+ let mut dec = ZstdDecoder::new(buf_reader);
+ dec.multiple_members(true);
+ Box::pin(dec)
+ } else {
+ Box::pin(buf_reader)
+ };
+
let mut file = tokio::fs::File::create(dest).await.map_err(|e| {
ApiError::new(
500,
@@ -81,23 +120,17 @@ pub async fn download_hashed(
})?;
let mut hasher = xxhash_rust::xxh3::Xxh3::new();
let mut written = 0usize;
- let mut stream = resp.bytes_stream();
- while let Some(chunk) = stream.next().await {
- // Any mid-stream failure must remove the partial temp file — leaving it
- // leaks disk (callers don't clean up on error).
- let chunk = match chunk {
- Ok(c) => c,
- Err(e) => {
- let _ = tokio::fs::remove_file(dest).await;
- return Err(ApiError::new(
- 422,
- "READ_FAILED",
- format!("could not download source: {e}"),
- ));
- }
+ let mut buf = vec![0u8; 256 * 1024];
+ loop {
+ // A decode error (corrupt/truncated zstd) surfaces here as an io::Error —
+ // fail loud rather than store a partial file.
+ let n = match input.read(&mut buf).await {
+ Ok(0) => break,
+ Ok(n) => n,
+ Err(e) => return Err(read_err(e, dest).await),
};
- written += chunk.len();
- if written > limit {
+ written += n;
+ if limit > 0 && written > limit {
let _ = tokio::fs::remove_file(dest).await;
return Err(ApiError::new(
413,
@@ -109,8 +142,8 @@ pub async fn download_hashed(
p.done
.store(written as u64, std::sync::atomic::Ordering::Relaxed);
}
- hasher.update(&chunk);
- if let Err(e) = file.write_all(&chunk).await {
+ hasher.update(&buf[..n]);
+ if let Err(e) = file.write_all(&buf[..n]).await {
let _ = tokio::fs::remove_file(dest).await;
return Err(ApiError::new(
500,
@@ -154,3 +187,24 @@ pub async fn upload(
}
Ok(())
}
+
+/// POST a JSON body (the completion-callback delivery). Short timeout; the
+/// caller owns retries.
+pub async fn post_json(url: &str, body: &serde_json::Value) -> Result<(), ApiError> {
+ let resp = client()
+ .post(url)
+ .header("Content-Type", "application/json")
+ .body(body.to_string())
+ .timeout(std::time::Duration::from_secs(10))
+ .send()
+ .await
+ .map_err(|e| ApiError::new(502, "CALLBACK_FAILED", format!("callback POST failed: {e}")))?;
+ if !resp.status().is_success() {
+ return Err(ApiError::new(
+ 502,
+ "CALLBACK_FAILED",
+ format!("callback POST returned {}", resp.status()),
+ ));
+ }
+ Ok(())
+}
diff --git a/apps/assembler/src/jobs.rs b/apps/assembler/src/jobs.rs
new file mode 100644
index 0000000000..eac301507b
--- /dev/null
+++ b/apps/assembler/src/jobs.rs
@@ -0,0 +1,615 @@
+//! Async job store shared by every heavy action (convert / optimize / plan).
+//! One lifecycle for all actions: create -> compute -> finalize (submit-time
+//! URLs) -> completion callback; GET /v1/jobs/{id}?wait= serves status and the
+//! late-mint fallback.
+//!
+//! Redis-backed, and Redis is REQUIRED (`REDIS_URL`): status +
+//! pointers (never artifact bytes) live in Redis, so a restart, a sibling
+//! replica, or a different Lambda invocation can still answer the poll — the
+//! service is stateless. Boot fails loudly when Redis is missing/unreachable;
+//! a silent in-memory fallback would strand cross-instance polls (Lambda
+//! dispatch depends on shared state) and hide the misconfiguration.
+//!
+//! Artifacts are PUT to caller-signed URLs; only a `{result, stats}` POINTER is
+//! stored — artifact bytes never enter Redis beyond the pending hand-off.
+
+use crate::{cache::CODE_VERSION, config, http};
+use dashmap::DashMap;
+use redis::AsyncCommands;
+use serde::{Deserialize, Serialize};
+use serde_json::{json, Value};
+use std::collections::HashMap;
+use std::sync::Arc;
+use std::time::{Duration, Instant};
+use tokio::sync::Notify;
+
+/// One job's persisted state, stored in Redis as a JSON blob. `result`/`stats`
+/// hold the completion POINTER (paths + counts) — never the artifact bytes.
+#[derive(Clone, Serialize, Deserialize)]
+struct JobRecord {
+ action: String, // convert | optimize | plan
+ status: String, // pending | running | uploading | done | error | canceled
+ #[serde(skip_serializing_if = "Option::is_none")]
+ result: Option<Value>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ stats: Option<Value>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ error: Option<Value>, // { code, message }
+ #[serde(skip_serializing_if = "Option::is_none")]
+ meta: Option<Value>,
+ /// Signed PUT URLs handed over AT SUBMIT (name → URL). Lets the job finalize
+ /// the moment compute ends — no poll needed to deliver upload URLs. Fresh
+ /// per-poll URLs remain the retry path if these expired. Never rendered.
+ #[serde(skip_serializing_if = "Option::is_none", default)]
+ upload_urls: Option<HashMap<String, String>>,
+ /// Completion webhook minted by the caller at submit: the terminal job
+ /// envelope is POSTed here (fire-with-retries) so the caller's workflow
+ /// wakes on an event instead of polling. Never rendered.
+ #[serde(skip_serializing_if = "Option::is_none", default)]
+ callback_url: Option<String>,
+}
+
+/// One artifact awaiting a late-minted upload URL (name → bytes + content type).
+#[derive(Clone)]
+pub struct Output {
+ pub name: String,
+ pub content_type: String,
+ pub bytes: Vec<u8>,
+}
+
+/// The terminal pointer to publish once every output is uploaded.
+#[derive(Clone)]
+pub struct Done {
+ pub result: Value,
+ pub stats: Value,
+}
+
+/// Shared job + content-hash result store. Cloned into every handler via
+/// `AppState`; inner state is `Arc`/manager-cloned so clones share one store.
+/// Computed-but-unuploaded artifacts (the late-mint hand-off) live in Redis
+/// under a short TTL so ANY replica's/invocation's poll can drain them.
+#[derive(Clone)]
+pub struct JobStore {
+ conn: redis::aio::ConnectionManager,
+ /// Per-job in-process wakeups so a same-replica long-poll returns the instant
+ /// the worker finishes (cross-replica completion caught by the Redis re-check).
+ notifiers: Arc<DashMap<String, Arc<Notify>>>,
+}
+
+/// Outcome of a finalize attempt during a long-poll.
+pub enum Finalize {
+ /// Uploaded — the job is now `done`.
+ Uploaded,
+ /// Nothing to upload here (already finalized, missing a URL, or on another
+ /// replica) — keep waiting.
+ NotPending,
+ /// Upload failed transiently; artifacts kept for the next poll to retry.
+ Retry,
+}
+
+impl JobStore {
+ /// Build from env. Redis is REQUIRED — a missing or unreachable
+ /// `REDIS_URL` refuses to boot (fail loud; a memory fallback would
+ /// strand cross-instance polls and hide the misconfiguration).
+ pub async fn from_env() -> Self {
+ let Some(url) = config::redis_url() else {
+ eprintln!(
+ "assembler: Redis is required (set REDIS_URL); refusing to start"
+ );
+ std::process::exit(1);
+ };
+ match connect(&url).await {
+ Ok(conn) => {
+ eprintln!("assembler: redis job store connected");
+ JobStore {
+ conn,
+ notifiers: Arc::new(DashMap::new()),
+ }
+ }
+ Err(e) => {
+ eprintln!("assembler: REDIS_URL unreachable ({e}); refusing to start");
+ std::process::exit(1);
+ }
+ }
+ }
+
+ // --- job status (pointer, not artifact bytes) --------------------------
+
+ async fn read(&self, id: &str) -> Option<JobRecord> {
+ let mut c = self.conn.clone();
+ match c.get::<_, Option<String>>(job_key(id)).await {
+ Ok(Some(s)) => serde_json::from_str(&s).ok(),
+ Ok(None) => None,
+ Err(e) => {
+ eprintln!("assembler: redis job read failed: {e}");
+ None
+ }
+ }
+ }
+
+ async fn write(&self, id: &str, rec: &JobRecord) {
+ let Ok(payload) = serde_json::to_string(rec) else {
+ return;
+ };
+ let mut c = self.conn.clone();
+ if let Err(e) = c
+ .set_ex::<_, _, ()>(job_key(id), payload, config::job_ttl_secs())
+ .await
+ {
+ eprintln!("assembler: redis job write failed: {e}");
+ }
+ }
+
+ /// The internal status of an active job (pending/running/uploading), for the
+ /// create handler's idempotency attach. None if unknown or terminal.
+ pub async fn existing_active(&self, id: &str) -> Option<String> {
+ self.read(id)
+ .await
+ .filter(|j| matches!(j.status.as_str(), "pending" | "running" | "uploading"))
+ .map(|j| external_status(&j.status).to_string())
+ }
+
+ pub async fn set_pending(
+ &self,
+ id: &str,
+ action: &str,
+ meta: Option<Value>,
+ upload_urls: HashMap<String, String>,
+ callback_url: Option<String>,
+ ) {
+ self.write(
+ id,
+ &JobRecord {
+ action: action.to_string(),
+ status: "pending".into(),
+ result: None,
+ stats: None,
+ error: None,
+ meta,
+ upload_urls: (!upload_urls.is_empty()).then_some(upload_urls),
+ callback_url,
+ },
+ )
+ .await;
+ }
+
+ pub async fn set_status(&self, id: &str, status: &str) {
+ if let Some(mut rec) = self.read(id).await {
+ // Canceled is terminal: a compute task that raced past its
+ // is_canceled check must not resurrect the job.
+ if rec.status == "canceled" {
+ return;
+ }
+ rec.status = status.to_string();
+ self.write(id, &rec).await;
+ }
+ }
+
+ /// Publish a terminal `done` pointer. Deliberately does NOT deliver the
+ /// completion callback: this runs on the poll path too (a late-mint
+ /// `try_finalize` inside GET /v1/jobs), where awaiting callback retries
+ /// would blow the poll's own timeout — and the poller already receives the
+ /// result synchronously. Owners that need the notification send it
+ /// explicitly: `finish()` on the direct-upload path, the plan action's
+ /// inline/cache-hit publishes, and the worker/CLI after run_to_completion.
+ pub async fn set_done(&self, id: &str, done: Done) {
+ if let Some(mut rec) = self.read(id).await {
+ if rec.status == "canceled" {
+ return;
+ }
+ rec.status = "done".into();
+ rec.result = Some(done.result);
+ rec.stats = Some(done.stats);
+ rec.error = None;
+ self.write(id, &rec).await;
+ }
+ self.wake(id);
+ }
+
+ pub async fn set_error(&self, id: &str, code: &str, message: String) {
+ if let Some(mut rec) = self.read(id).await {
+ if rec.status == "canceled" {
+ return;
+ }
+ rec.status = "error".into();
+ rec.error = Some(json!({ "code": code, "message": message }));
+ self.write(id, &rec).await;
+ }
+ self.send_callback(id).await;
+ self.wake(id);
+ }
+
+ /// Best-effort cancel: mark canceled only if still active. The running task
+ /// isn't forcibly killed — it drops its result when it finds the job canceled.
+ pub async fn cancel(&self, id: &str) -> Option<Value> {
+ let mut rec = self.read(id).await?;
+ if matches!(rec.status.as_str(), "pending" | "running" | "uploading") {
+ rec.status = "canceled".into();
+ self.write(id, &rec).await;
+ self.pending_remove(id).await;
+ // Wake the event-driven waiter immediately (terminal state).
+ self.send_callback(id).await;
+ self.wake(id);
+ }
+ Some(Self::render(id, &rec))
+ }
+
+ /// True once the job left the active set (terminal or canceled) — the compute
+ /// task polls this to abandon a canceled run.
+ pub async fn is_canceled(&self, id: &str) -> bool {
+ self.read(id)
+ .await
+ .map(|r| r.status == "canceled")
+ .unwrap_or(true)
+ }
+
+ /// The uniform poll envelope: `{ ok, job: { id, action, status, result?,
+ /// stats?, error? } }` with the internal status mapped to the public enum.
+ fn render(id: &str, rec: &JobRecord) -> Value {
+ let mut job = json!({
+ "id": id,
+ "action": rec.action,
+ "status": external_status(&rec.status),
+ });
+ if let Some(r) = &rec.result {
+ job["result"] = r.clone();
+ }
+ if let Some(s) = &rec.stats {
+ job["stats"] = s.clone();
+ }
+ if let Some(e) = &rec.error {
+ job["error"] = e.clone();
+ }
+ if let Some(m) = &rec.meta {
+ job["meta"] = m.clone();
+ }
+ json!({ "ok": true, "job": job })
+ }
+
+ /// Long-poll a job to a terminal state. `upload_urls` (name→signed PUT URL,
+ /// minted fresh by the caller each poll) drain a computed-but-unuploaded job
+ /// the instant it's ready. With `max`, holds until terminal or the deadline;
+ /// without, a single shot. `None` only if the job is unknown.
+ pub async fn poll(
+ &self,
+ id: &str,
+ upload_urls: &HashMap<String, String>,
+ max: Option<Duration>,
+ ) -> Option<Value> {
+ let deadline = max.map(|m| Instant::now() + m);
+ loop {
+ let rec = self.read(id).await?;
+ match rec.status.as_str() {
+ "done" | "error" | "canceled" => return Some(Self::render(id, &rec)),
+ "uploading" if !upload_urls.is_empty() => {
+ if let Finalize::Uploaded = self.try_finalize(id, upload_urls).await {
+ // re-read → the now-`done` record renders on the next loop
+ continue;
+ }
+ }
+ _ => {}
+ }
+ let Some(dl) = deadline else {
+ return Some(Self::render(id, &rec)); // single shot
+ };
+ let now = Instant::now();
+ if now >= dl {
+ return Some(Self::render(id, &rec));
+ }
+ let notify = self.notifier(id);
+ let tick = (dl - now).min(Duration::from_millis(500));
+ tokio::select! {
+ _ = notify.notified() => {}
+ _ = tokio::time::sleep(tick) => {}
+ }
+ }
+ }
+
+ fn notifier(&self, id: &str) -> Arc<Notify> {
+ self.notifiers
+ .entry(id.to_string())
+ .or_insert_with(|| Arc::new(Notify::new()))
+ .clone()
+ }
+
+ pub fn wake(&self, id: &str) {
+ if let Some(n) = self.notifiers.get(id) {
+ n.notify_waiters();
+ }
+ }
+
+ // --- late-mint hand-off -------------------------------------------------
+
+ /// Hold computed-but-unuploaded artifacts for hand-off, stored in Redis
+ /// (bytes + pointer) under a short TTL so ANY replica's poll can drain them.
+ pub async fn pending_put(
+ &self,
+ id: &str,
+ outputs: Vec<Output>,
+ done: Done,
+ cache: Option<(String, u128, u64)>,
+ ) {
+ let manifest: Vec<Value> = outputs
+ .iter()
+ .map(|o| json!({ "name": o.name, "contentType": o.content_type }))
+ .collect();
+ let done_json = json!({ "result": done.result, "stats": done.stats }).to_string();
+ let mut c = self.conn.clone();
+ let mut pipe = redis::pipe();
+ pipe.hset(
+ pending_key(id),
+ "manifest",
+ Value::from(manifest).to_string(),
+ )
+ .ignore()
+ .hset(pending_key(id), "done", done_json)
+ .ignore();
+ for o in &outputs {
+ pipe.hset(pending_key(id), format!("b:{}", o.name), o.bytes.clone())
+ .ignore();
+ }
+ if let Some((m, ch, op)) = &cache {
+ pipe.hset(pending_key(id), "cache", format!("{m}|{ch:032x}|{op}"))
+ .ignore();
+ }
+ pipe.expire(pending_key(id), config::pending_ttl_secs() as i64)
+ .ignore();
+ if let Err(e) = pipe.query_async::<()>(&mut c).await {
+ eprintln!("assembler: redis pending_put failed: {e}");
+ }
+ }
+
+ /// Complete a computed job: hold the artifacts for upload, and — when the
+ /// submit handed over upload URLs — finalize immediately (upload + publish
+ /// the terminal pointer + fire the completion callback), so no poll is ever
+ /// needed on the happy path. Without submit-time URLs the job parks in
+ /// `uploading` and a late-mint poll drains it (the legacy/retry path).
+ /// Replaces the pending_put + set_status("uploading") + wake trio in actions.
+ pub async fn finish(
+ &self,
+ id: &str,
+ outputs: Vec<Output>,
+ done: Done,
+ cache: Option<(String, u128, u64)>,
+ ) {
+ // A cancel that landed mid-compute wins: drop the result, upload nothing.
+ if self.is_canceled(id).await {
+ eprintln!("[{id}] finished after cancel; result dropped");
+ return;
+ }
+ self.pending_put(id, outputs, done, cache).await;
+ self.set_status(id, "uploading").await;
+ let urls = self.read(id).await.and_then(|r| r.upload_urls);
+ if let Some(urls) = urls {
+ if let Finalize::Uploaded = self.try_finalize(id, &urls).await {
+ // Terminal — deliver the callback from the action task, which
+ // owns the process lifetime on the server path (the Lambda
+ // worker re-sends after run_to_completion regardless).
+ // Retry/NotPending: submit-time URLs failed; a late-mint poll
+ // retries with fresh ones.
+ self.send_callback(id).await;
+ }
+ }
+ self.wake(id);
+ }
+
+ /// POST the terminal job envelope to the submit-time callback URL, if any.
+ /// Bounded retries; failure is logged only — the caller's waitForEvent
+ /// timeout + fallback poll covers a lost callback.
+ pub async fn send_callback(&self, id: &str) {
+ let Some(rec) = self.read(id).await else {
+ return;
+ };
+ let Some(url) = rec.callback_url.clone() else {
+ return;
+ };
+ if !matches!(rec.status.as_str(), "done" | "error" | "canceled") {
+ return;
+ }
+ let body = Self::render(id, &rec);
+ for attempt in 1..=3u32 {
+ match http::post_json(&url, &body).await {
+ Ok(()) => {
+ eprintln!("[{id}] completion callback delivered");
+ return;
+ }
+ Err(e) => {
+ eprintln!(
+ "[{id}] completion callback attempt {attempt} failed: {}",
+ e.message
+ );
+ tokio::time::sleep(Duration::from_secs(attempt as u64)).await;
+ }
+ }
+ }
+ eprintln!("[{id}] completion callback undelivered; caller falls back to poll");
+ }
+
+ async fn pending_take(
+ &self,
+ id: &str,
+ ) -> Option<(Vec<Output>, Done, Option<(String, u128, u64)>)> {
+ let mut c = self.conn.clone();
+ let res: redis::RedisResult<(Option<String>, Option<String>, Option<String>)> =
+ redis::pipe()
+ .hget(pending_key(id), "manifest")
+ .hget(pending_key(id), "done")
+ .hget(pending_key(id), "cache")
+ .query_async(&mut c)
+ .await;
+ let (manifest_s, done_s, cache_s) = match res {
+ Ok(t) => t,
+ Err(e) => {
+ eprintln!("assembler: redis pending_take failed: {e}");
+ return None;
+ }
+ };
+ let manifest: Vec<Value> = serde_json::from_str(&manifest_s?).ok()?;
+ let mut outputs = Vec::with_capacity(manifest.len());
+ for m in &manifest {
+ let name = m["name"].as_str()?.to_string();
+ let content_type = m["contentType"]
+ .as_str()
+ .unwrap_or("application/octet-stream")
+ .to_string();
+ let bytes: Option<Vec<u8>> =
+ c.hget(pending_key(id), format!("b:{name}")).await.ok()?;
+ outputs.push(Output {
+ name,
+ content_type,
+ bytes: bytes?,
+ });
+ }
+ let done_v: Value = serde_json::from_str(&done_s?).ok()?;
+ let done = Done {
+ result: done_v["result"].clone(),
+ stats: done_v["stats"].clone(),
+ };
+ Some((outputs, done, cache_s.and_then(parse_cache)))
+ }
+
+ async fn pending_remove(&self, id: &str) {
+ let mut c = self.conn.clone();
+ if let Err(e) = c.del::<_, ()>(pending_key(id)).await {
+ eprintln!("assembler: redis pending_remove failed: {e}");
+ }
+ }
+
+ /// Drain computed-but-unuploaded artifacts to their fresh signed URLs (from a
+ /// long-poll). Every output must have a matching URL; on success publishes the
+ /// terminal pointer, else keeps the artifacts for the next poll to retry.
+ pub async fn try_finalize(&self, id: &str, urls: &HashMap<String, String>) -> Finalize {
+ let Some((outputs, done, cache)) = self.pending_take(id).await else {
+ return Finalize::NotPending;
+ };
+ // Need a URL for every output before we can finalize.
+ if outputs.iter().any(|o| !urls.contains_key(&o.name)) {
+ return Finalize::NotPending;
+ }
+ for o in &outputs {
+ let url = &urls[&o.name];
+ if let Err(e) = http::upload(url, o.bytes.clone(), &o.content_type).await {
+ eprintln!(
+ "[{id}] output '{}' upload failed (retry next poll): {}",
+ o.name, e.message
+ );
+ return Finalize::Retry;
+ }
+ }
+ self.pending_remove(id).await;
+ if let Some((model, content, opts)) = cache {
+ let pointer = json!({ "result": done.result, "stats": done.stats });
+ self.result_put(&model, content, opts, pointer).await;
+ }
+ self.set_done(id, done).await;
+ Finalize::Uploaded
+ }
+
+ // --- content-hash result-pointer cache (CODE_VERSION-stamped) ----------
+
+ pub async fn result_get(&self, model: &str, content: u128, opts: u64) -> Option<Done> {
+ let key = result_key(model, content, opts);
+ let mut c = self.conn.clone();
+ let raw: Option<Value> = match c.get::<_, Option<String>>(&key).await {
+ Ok(Some(s)) => serde_json::from_str(&s).ok(),
+ Ok(None) => None,
+ Err(e) => {
+ eprintln!("assembler: redis result read failed: {e}");
+ None
+ }
+ };
+ raw.map(|v| Done {
+ result: v["result"].clone(),
+ stats: v["stats"].clone(),
+ })
+ }
+
+ async fn result_put(&self, model: &str, content: u128, opts: u64, pointer: Value) {
+ let key = result_key(model, content, opts);
+ let Ok(payload) = serde_json::to_string(&pointer) else {
+ return;
+ };
+ let mut c = self.conn.clone();
+ if let Err(e) = c
+ .set_ex::<_, _, ()>(&key, payload, config::result_ttl_secs())
+ .await
+ {
+ eprintln!("assembler: redis result write failed: {e}");
+ }
+ }
+
+ /// Central explicit invalidation: drop every cached result pointer for a
+ /// model so the next job re-derives. Returns how many entries were cleared.
+ pub async fn invalidate_model(&self, model: &str) -> usize {
+ let prefix = format!("asm:result:{model}:");
+ let pattern = format!("{prefix}*");
+ let mut scan = self.conn.clone();
+ let mut keys: Vec<String> = Vec::new();
+ match scan.scan_match::<_, String>(&pattern).await {
+ Ok(mut iter) => {
+ while let Some(k) = iter.next_item().await {
+ keys.push(k);
+ }
+ }
+ Err(e) => {
+ eprintln!("assembler: redis invalidate scan failed: {e}");
+ return 0;
+ }
+ }
+ if keys.is_empty() {
+ return 0;
+ }
+ let mut c = self.conn.clone();
+ if let Err(e) = c.del::<_, ()>(&keys).await {
+ eprintln!("assembler: redis invalidate del failed: {e}");
+ return 0;
+ }
+ keys.len()
+ }
+}
+
+async fn connect(url: &str) -> redis::RedisResult<redis::aio::ConnectionManager> {
+ let client = redis::Client::open(url)?;
+ let mut conn = client.get_connection_manager().await?;
+ redis::cmd("PING").query_async::<()>(&mut conn).await?;
+ Ok(conn)
+}
+
+/// Map an internal status to the public job-status enum.
+fn external_status(internal: &str) -> &'static str {
+ match internal {
+ "pending" => "queued",
+ "running" | "uploading" => "running",
+ "done" => "succeeded",
+ "error" => "failed",
+ "canceled" => "canceled",
+ _ => "running",
+ }
+}
+
+fn job_key(id: &str) -> String {
+ format!("asm:job:{id}")
+}
+
+fn result_key(model: &str, content: u128, opts: u64) -> String {
+ format!("asm:result:{model}:{content:032x}:{opts:016x}:v{CODE_VERSION}")
+}
+
+fn pending_key(id: &str) -> String {
+ format!("asm:pending:{id}")
+}
+
+/// Parse a `"model|contentHex|opts"` cache tuple stored alongside a pending job.
+fn parse_cache(s: String) -> Option<(String, u128, u64)> {
+ let mut it = s.splitn(3, '|');
+ let model = it.next()?.to_string();
+ let content = u128::from_str_radix(it.next()?, 16).ok()?;
+ let opts = it.next()?.parse().ok()?;
+ Some((model, content, opts))
+}
+
+/// Stable hash of an options object. `serde_json` serializes object keys sorted,
+/// so the string is deterministic.
+pub fn opts_hash(options: &Value) -> u64 {
+ xxhash_rust::xxh3::xxh3_64(options.to_string().as_bytes())
+}
diff --git a/apps/assembler/src/main.rs b/apps/assembler/src/main.rs
index af4d51026d..07b2b92369 100644
--- a/apps/assembler/src/main.rs
+++ b/apps/assembler/src/main.rs
@@ -1,27 +1,50 @@
-//! Carbon assembler service (Rust) — axum HTTP server: GET /health,
-//! POST /convert (STEP -> GLB + assembly graph), POST /plan (202 async,
-//! collision-free disassembly motion planning) + GET /plan/{jobId}. Wires the
-//! `converter` and `planner` crates.
-
+//! Carbon assembler service (Rust) — the CAD heavy-lifting hub. Action-based RPC
+//! over HTTP/JSON, versioned under `/v1`, with one shared async job model:
+//!
+//! POST /v1/convert | /v1/optimize | /v1/plan | /v1/compact
+//! → 202 { ok, job } (create, async)
+//! ...?sync → 200 { ok, job } (run inline; Lambda)
+//! GET /v1/jobs/{id}?wait=N → 200 { ok, job } (poll)
+//! POST /v1/jobs/{id}/cancel → 200 { ok, job }
+//! POST /v1/cache/invalidate → 200 { ok, cleared }
+//! GET /v1 → discovery
+//! GET /health → liveness (unauth)
+//!
+//! Every heavy action creates a job (holding a concurrency slot). Artifacts
+//! upload via submit-time signed URLs and completion POSTs to a submit-time
+//! callback URL; the poll endpoint remains for status + as the late-mint
+//! fallback. Wires the `converter` and `planner` crates via `actions::*`.
+
+mod actions;
mod cache;
mod config;
+mod dispatch;
mod error;
+mod formats;
mod http;
-mod plan_jobs;
+mod jobs;
mod progress;
+mod run;
use axum::{
extract::{Path, Query, State},
- http::HeaderMap,
+ http::{header, HeaderMap, StatusCode},
routing::{get, post},
Json, Router,
};
use error::ApiError;
use serde_json::{json, Value};
+use std::collections::HashMap;
+use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::Arc;
use tokio::sync::Semaphore;
+use tower_http::compression::{predicate::SizeAbove, CompressionLayer};
const VERSION: &str = "0.1.0";
+/// Default optimise output ceiling (encoded bytes) — the served-bucket safety net.
+const DEFAULT_MAX_OUTPUT_BYTES: u64 = 52_428_800; // 50 MiB
+/// Default decoded (render-weight) ceiling — guards viewer hangs on huge meshes.
+const DEFAULT_MAX_RENDER_WEIGHT_BYTES: u64 = 419_430_400; // 400 MiB
// jemalloc on the Linux deploy target: the planner's blocking tasks allocate
// heavily from many threads (rayon sweeps + tokio workers); glibc malloc is the
@@ -31,46 +54,64 @@ const VERSION: &str = "0.1.0";
static GLOBAL: tikv_jemallocator::Jemalloc = tikv_jemallocator::Jemalloc;
#[derive(Clone)]
-struct AppState {
- slots: Arc<Semaphore>,
- jobs: plan_jobs::JobStore,
- cache: Arc<cache::ResultCache>,
- progress: progress::ProgressStore,
+pub struct AppState {
+ pub slots: Arc<Semaphore>,
+ pub jobs: jobs::JobStore,
+ pub cache: Arc<cache::ResultCache>,
+ pub progress: progress::ProgressStore,
}
fn main() {
- // Manual runtime: cap the blocking pool at ~cores so converts queue inside
- // tokio instead of oversubscribing OCCT threads (async workers stay default
- // = cores, they only do I/O).
- tokio::runtime::Builder::new_multi_thread()
+ let rt = tokio::runtime::Builder::new_multi_thread()
.enable_all()
.max_blocking_threads(config::blocking_threads())
.build()
- .expect("tokio runtime")
- .block_on(serve());
+ .expect("tokio runtime");
+ // `assembler run-job <spec.json>` — one-shot job runner (no HTTP server), the
+ // ECS Fargate overflow / any-invoke path. Exits the process. Otherwise serve.
+ if std::env::args().nth(1).as_deref() == Some("run-job") {
+ rt.block_on(run::run_job_cli());
+ } else {
+ rt.block_on(serve());
+ }
}
-async fn serve() {
- // Throughput vs latency is picked by env, not code:
- // ASSEMBLER_MESH_PARALLEL=0 + ASSEMBLER_SEQUENTIAL=1 + max_concurrency=cores
- // runs each request single-threaded on its own worker (N concurrent requests
- // = N cores, no oversubscription). The defaults keep each request all-core
- // for lowest single-request latency (CLI / low-concurrency use).
- let max = config::max_concurrency();
- let state = AppState {
- slots: Arc::new(Semaphore::new(max)),
- jobs: plan_jobs::JobStore::from_env().await,
+/// Build the shared service state. Used by the HTTP server (`serve`) and the
+/// one-shot `run-job` CLI so both share one JobStore + cache + concurrency.
+pub async fn build_state() -> AppState {
+ AppState {
+ slots: Arc::new(Semaphore::new(config::max_concurrency())),
+ jobs: jobs::JobStore::from_env().await,
cache: Arc::new(cache::ResultCache::new(config::cache_bytes())),
progress: progress::ProgressStore::default(),
- };
+ }
+}
+
+async fn serve() {
+ let max = config::max_concurrency();
+ let state = build_state().await;
let slots = Arc::clone(&state.slots);
let app = Router::new()
.route("/health", get(health))
- .route("/convert", post(convert))
- .route("/convert/status/:job_id", get(convert_status))
- .route("/plan", post(plan))
- .route("/plan/:job_id", get(plan_status))
- .route("/cache/invalidate", post(cache_invalidate))
+ .route("/v1", get(discovery))
+ .route("/v1/convert", post(create_convert))
+ .route("/v1/optimize", post(create_optimize))
+ .route("/v1/plan", post(create_plan))
+ .route("/v1/compact", post(create_compact))
+ .route("/v1/jobs/:job_id", get(get_job))
+ .route("/v1/jobs/:job_id/cancel", post(cancel_job))
+ .route("/v1/cache/invalidate", post(cache_invalidate))
+ // Lambda self-invoke worker inlet: the Web Adapter delivers non-HTTP
+ // (Event) payloads here (AWS_LWA_PASS_THROUGH_PATH). Not part of the
+ // public API — the API Gateway routes only /health and /v1/*, and the
+ // spec's embedded token is verified in-handler.
+ .route("/events", post(worker_events))
+ // Negotiated response compression (zstd, gzip fallback). Content-encoding
+ // is chosen from the request's `Accept-Encoding`, so the server never
+ // sends an encoding the client didn't advertise — a caller bypasses it
+ // entirely with `Accept-Encoding: identity`. Skip bodies under 1KB
+ // (pointer-sized job envelopes) where a frame would cost more than it saves.
+ .layer(CompressionLayer::new().compress_when(SizeAbove::new(1024)))
.with_state(state);
eprintln!(
@@ -83,7 +124,9 @@ async fn serve() {
config::result_ttl_secs(),
);
- let addr = std::env::var("ASSEMBLER_BIND").unwrap_or_else(|_| "0.0.0.0:8000".into());
+ // Standard PORT convention — the Lambda Web Adapter reads the same variable.
+ let port = std::env::var("PORT").unwrap_or_else(|_| "8000".into());
+ let addr = format!("0.0.0.0:{port}");
let listener = tokio::net::TcpListener::bind(&addr).await.unwrap();
eprintln!("assembler (rust) listening on {addr}");
@@ -92,21 +135,14 @@ async fn serve() {
.await
.unwrap();
- // The listener has stopped and in-flight HTTP requests have drained (convert
- // is request-bound). Plan jobs run detached (POST /plan returns 202) and
- // each holds a slot, so wait for every slot to free — no permits held means
- // no plan is still running — before exiting, so a deploy/scale-down doesn't
- // kill a plan mid-flight. The grace deadline armed in shutdown_signal
- // force-exits if a wedged job overruns, so shutdown can't hang forever.
- eprintln!("assembler draining in-flight plan jobs");
+ // Jobs run detached (create returns 202) and each holds a slot; wait for
+ // every slot to free before exiting so a deploy/scale-down doesn't kill an
+ // in-flight job. The grace deadline in shutdown_signal force-exits a wedged one.
+ eprintln!("assembler draining in-flight jobs");
let _ = slots.acquire_many(max as u32).await;
eprintln!("assembler drained cleanly; exiting");
}
-/// Resolves on SIGTERM (container stop) or SIGINT (Ctrl-C), then arms a hard
-/// deadline: if the graceful drain isn't done within ASSEMBLER_SHUTDOWN_GRACE_S,
-/// the process force-exits — we stop on our own terms rather than waiting for
-/// the orchestrator's SIGKILL.
async fn shutdown_signal() {
let ctrl_c = async {
tokio::signal::ctrl_c().await.ok();
@@ -136,7 +172,35 @@ async fn shutdown_signal() {
}
async fn health() -> Json<Value> {
- Json(json!({"ok": true, "version": VERSION}))
+ Json(json!({ "ok": true, "version": VERSION }))
+}
+
+async fn discovery(headers: HeaderMap) -> Result<Json<Value>, ApiError> {
+ require_auth(&headers)?;
+ let input_formats: Vec<Value> = formats::ALL
+ .iter()
+ .map(|f| {
+ json!({
+ "format": f.name(),
+ "loader": f.loader_name(),
+ "exact": f.exact(),
+ "structured": f.structured(),
+ })
+ })
+ .collect();
+ Ok(Json(json!({
+ "version": VERSION,
+ "actions": ["convert", "optimize", "plan", "compact"],
+ "input_formats": input_formats,
+ "codecs": ["meshopt", "draco", "none"],
+ "limits": {
+ "max_parts": config::max_parts(),
+ "max_source_bytes": config::max_source_bytes(),
+ "max_output_bytes": DEFAULT_MAX_OUTPUT_BYTES,
+ "max_render_weight_bytes": DEFAULT_MAX_RENDER_WEIGHT_BYTES,
+ "max_long_poll_secs": config::max_long_poll_secs(),
+ },
+ })))
}
fn require_auth(headers: &HeaderMap) -> Result<(), ApiError> {
@@ -168,19 +232,6 @@ fn require_auth(headers: &HeaderMap) -> Result<(), ApiError> {
}
}
-/// Read at most `cap` bytes from the head of a file, lossy-decoded.
-fn read_head_lossy(path: &str, cap: usize) -> Result<String, converter::convert::ConvertError> {
- use std::io::Read;
- let file = std::fs::File::open(path).map_err(|e| {
- converter::convert::ConvertError::new("READ_FAILED", format!("read temp: {e}"))
- })?;
- let mut buf = Vec::new();
- file.take(cap as u64).read_to_end(&mut buf).map_err(|e| {
- converter::convert::ConvertError::new("READ_FAILED", format!("read temp: {e}"))
- })?;
- Ok(String::from_utf8_lossy(&buf).into_owned())
-}
-
fn constant_eq(a: &str, b: &str) -> bool {
let (a, b) = (a.as_bytes(), b.as_bytes());
if a.len() != b.len() {
@@ -193,240 +244,466 @@ fn constant_eq(a: &str, b: &str) -> bool {
diff == 0
}
-async fn convert(
+/// Resolve the job id: the caller's `Idempotency-Key` (so a re-POST attaches to
+/// the running job), else a generated id.
+fn resolve_job_id(headers: &HeaderMap) -> String {
+ headers
+ .get("idempotency-key")
+ .and_then(|v| v.to_str().ok())
+ .map(str::trim)
+ .filter(|s| !s.is_empty() && s.len() <= 128)
+ .map(str::to_string)
+ .unwrap_or_else(gen_id)
+}
+
+fn gen_id() -> String {
+ static COUNTER: AtomicU64 = AtomicU64::new(0);
+ let n = COUNTER.fetch_add(1, Ordering::Relaxed);
+ let nanos = std::time::SystemTime::now()
+ .duration_since(std::time::UNIX_EPOCH)
+ .map(|d| d.as_nanos())
+ .unwrap_or(0);
+ format!("job_{}_{nanos}_{n}", std::process::id())
+}
+
+
+/// Submit-time completion plumbing: the caller's `callback_url` (body) and
+/// upload URLs (X-Carbon-Upload-Urls header) are stored ON the job so it can
+/// finalize + notify the moment compute ends — no poll on the happy path.
+/// Both are caller-supplied URLs -> SSRF-validated like every other URL.
+fn submit_plumbing(
+ headers: &HeaderMap,
+ req: &Value,
+) -> Result<(HashMap<String, String>, Option<String>), ApiError> {
+ let urls = parse_upload_urls(headers)?;
+ let callback = match req["callback_url"].as_str().filter(|s| !s.is_empty()) {
+ Some(u) => {
+ config::validate_url(u)?;
+ Some(u.to_string())
+ }
+ None => None,
+ };
+ Ok((urls, callback))
+}
+
+/// The uniform 202 create response: `{ ok, job }` + a `Location` to poll.
+fn created(job_id: &str, action: &str, status: &str) -> (StatusCode, HeaderMap, Json<Value>) {
+ let mut hm = HeaderMap::new();
+ if let Ok(loc) = format!("/v1/jobs/{job_id}").parse() {
+ hm.insert(header::LOCATION, loc);
+ }
+ (
+ StatusCode::ACCEPTED,
+ hm,
+ Json(json!({ "ok": true, "job": { "id": job_id, "action": action, "status": status } })),
+ )
+}
+
+fn parse_body(
+ body: Result<Json<Value>, axum::extract::rejection::JsonRejection>,
+) -> Result<Value, ApiError> {
+ body.map(|Json(v)| v)
+ .map_err(|_| ApiError::invalid("invalid JSON body"))
+}
+
+#[derive(serde::Deserialize)]
+struct CreateQuery {
+ /// `?sync` (bare / `=true` / `=1`) runs the job **inline** and returns the
+ /// terminal `{ok, job}` in one response — the Lambda path (Lambda freezes
+ /// after the response, so a detached job would never finish). Absent => the
+ /// default async 202 + poll (what the standing ECS service uses).
+ sync: Option<String>,
+}
+
+fn sync_flag(q: &CreateQuery) -> bool {
+ matches!(q.sync.as_deref(), Some("" | "true" | "1" | "yes"))
+}
+
+/// Finalize a create request. Sync mode drives the just-spawned (or already
+/// running) job to terminal inline, uploading its outputs to the caller's
+/// per-request signed URLs via the same finalize path the async poll uses, and
+/// returns the terminal `{ok, job}` (200, same envelope as `GET /v1/jobs/{id}`).
+/// Async mode returns the uniform 202 + `Location`.
+async fn respond(
+ state: &AppState,
+ headers: &HeaderMap,
+ job_id: &str,
+ action: &str,
+ sync: bool,
+) -> Result<(StatusCode, HeaderMap, Json<Value>), ApiError> {
+ if !sync {
+ return Ok(created(job_id, action, "queued"));
+ }
+ let urls = parse_upload_urls(headers)?;
+ let result = run::run_to_completion(state, job_id, &urls).await;
+ Ok((StatusCode::OK, HeaderMap::new(), Json(result)))
+}
+
+/// Lambda-mode create path: instead of spawning in-process (this instance
+/// freezes after the response), fire the job as an Event-type self-invocation
+/// carrying a run-job spec — the request body plus `action`/`job_id`, the
+/// submit-time signed upload URLs, and the bearer for the worker inlet. A failed
+/// dispatch fails the job loudly (never a forever-"pending" record).
+async fn lambda_dispatch(
+ state: &AppState,
+ headers: &HeaderMap,
+ job_id: &str,
+ action: &str,
+ req: &Value,
+) -> Result<(), ApiError> {
+ let urls = parse_upload_urls(headers)?;
+ let mut spec = req.clone();
+ spec["action"] = action.into();
+ spec["job_id"] = job_id.into();
+ if !urls.is_empty() {
+ spec["upload_urls"] = json!(urls);
+ }
+ if let Ok(k) = std::env::var("ASSEMBLER_SERVICE_API_KEY") {
+ if !k.is_empty() {
+ spec["token"] = k.into();
+ }
+ }
+ if let Err(m) = dispatch::self_invoke(&spec).await {
+ state
+ .jobs
+ .set_error(job_id, "dispatch_failed", m.clone())
+ .await;
+ return Err(ApiError::new(503, "dispatch_failed", m));
+ }
+ eprintln!("[{job_id}] {action} dispatched to worker invocation");
+ Ok(())
+}
+
+/// Worker inlet for the Lambda self-invoke (LWA pass-through). Runs the spec's
+/// action to completion in THIS invocation — its own 900s window — uploading via
+/// the submit-time URLs; state lives in the shared (Redis) JobStore so any
+/// instance's poll can answer. Async-retry deliveries are deduped by job status:
+/// pending → run; uploading → finalize only; running/terminal → no-op.
+async fn worker_events(
State(state): State<AppState>,
- headers: HeaderMap,
body: Result<Json<Value>, axum::extract::rejection::JsonRejection>,
) -> Result<Json<Value>, ApiError> {
+ let spec = parse_body(body)?;
+ if let Ok(key) = std::env::var("ASSEMBLER_SERVICE_API_KEY") {
+ if !key.is_empty() && !constant_eq(spec["token"].as_str().unwrap_or(""), &key) {
+ return Err(ApiError::unauthorized("invalid worker token"));
+ }
+ }
+ let action = spec["action"].as_str().unwrap_or_default().to_string();
+ let job_id = spec["job_id"].as_str().unwrap_or_default().to_string();
+ if job_id.is_empty() {
+ return Err(ApiError::invalid("missing job_id"));
+ }
+ let urls = run::upload_urls(&spec);
+
+ match state.jobs.existing_active(&job_id).await.as_deref() {
+ Some("pending") => {
+ if let Err(m) = run::spawn_from_spec(&state, &job_id, &action, &spec) {
+ state.jobs.set_error(&job_id, "invalid_input", m.clone()).await;
+ return Err(ApiError::invalid(m));
+ }
+ eprintln!("[{job_id}] worker running {action}");
+ }
+ Some("uploading") => {
+ eprintln!("[{job_id}] worker resuming finalize");
+ }
+ other => {
+ // running (another live worker owns it) or terminal/unknown: no-op.
+ eprintln!("[{job_id}] worker no-op (status {other:?})");
+ return Ok(Json(json!({ "ok": true, "noop": true })));
+ }
+ }
+
+ let result = run::run_to_completion(&state, &job_id, &urls).await;
+ // The worker invocation owns the Lambda lifetime: the action task's inline
+ // callback send may be killed by the post-response freeze, so (re)send here
+ // before returning. Duplicate deliveries are harmless — the receiver's
+ // waitForEvent consumes the first matching event.
+ state.jobs.send_callback(&job_id).await;
+ eprintln!(
+ "[{job_id}] worker finished: {}",
+ result["job"]["status"].as_str().unwrap_or("?")
+ );
+ Ok(Json(result))
+}
+
+async fn create_convert(
+ State(state): State<AppState>,
+ headers: HeaderMap,
+ Query(q): Query<CreateQuery>,
+ body: Result<Json<Value>, axum::extract::rejection::JsonRejection>,
+) -> Result<(StatusCode, HeaderMap, Json<Value>), ApiError> {
require_auth(&headers)?;
- let Json(req) = body.map_err(|_| ApiError::invalid("invalid JSON body"))?;
+ let req = parse_body(body)?;
let source_url = req["source"]["url"]
.as_str()
.ok_or_else(|| ApiError::invalid("missing source.url"))?;
- let glb_url = req["outputs"]["glb"]["url"]
- .as_str()
- .ok_or_else(|| ApiError::invalid("missing outputs.glb.url"))?;
- let graph_url = req["outputs"]["graph"]["url"]
- .as_str()
- .ok_or_else(|| ApiError::invalid("missing outputs.graph.url"))?;
- for url in [source_url, glb_url, graph_url] {
- config::validate_url(url)?;
- }
- let job_id = req["jobId"]
- .as_str()
- .filter(|s| !s.is_empty())
- .ok_or_else(|| ApiError::invalid("missing jobId"))?
- .to_string();
- let lin = req["options"]["linearDeflection"].as_f64().unwrap_or(0.1);
- let ang = req["options"]["angularDeflection"].as_f64().unwrap_or(0.5);
-
- // No slot gate: OCCT reads scale across threads (thread_local allocator
- // patch) and the bounded blocking pool is the queue — overload waits, never
- // 429s. spawn_blocking, not inline: the sync OCCT call would pin an async
- // worker for its full duration (measured at c=64: /health p99 7ms -> 296ms
- // inline, and real files convert in 30-60s). One blocking hop does file
- // read + cache lookup + convert; DashMap ops are sync, never held across
- // an await.
- let started = std::time::Instant::now();
- // Live phase tracking for GET /convert/status/{jobId}; the guard removes
- // the entry when this request ends either way.
- let tracker = state.progress.start(&job_id);
-
- // Caller-declared content identity (storage etag): a hit here skips the
- // source download entirely.
- let declared = req["source"]["contentHash"]
- .as_str()
- .map(str::trim)
- .filter(|s| !s.is_empty() && s.len() <= 128)
- .map(str::to_string);
- if let Some(h) = &declared {
- let key = cache::ResultCache::key_declared(h, lin, ang);
- if let Some(entry) = state.cache.get(&key) {
- tracker.progress.set_phase(progress::PHASE_UPLOAD);
- return respond_convert(&job_id, entry, true, glb_url, graph_url, started).await;
- }
- }
-
- let tmp = http::temp_path("step");
- // Hash rides the download stream; a cache hit never touches the blocking
- // pool — it goes straight to the uploads.
- let content_hash =
- http::download_hashed(source_url, &tmp, Some(&tracker.progress)).await?;
- tracker.progress.set_phase(progress::PHASE_CONVERT);
- // Declared key when given (so the next declared lookup hits pre-download);
- // computed byte-hash key otherwise.
- let key = match &declared {
- Some(h) => cache::ResultCache::key_declared(h, lin, ang),
- None => cache::ResultCache::key(content_hash, lin, ang),
- };
- let hit = state.cache.get(&key);
- let was_hit = hit.is_some();
- let entry = match hit {
- Some(entry) => {
- let _ = tokio::fs::remove_file(&tmp).await;
- entry
+ config::validate_url(source_url)?;
+ let job_id = resolve_job_id(&headers);
+ let sync = sync_flag(&q);
+ let (submit_urls, callback_url) = submit_plumbing(&headers, &req)?;
+
+ match state.jobs.existing_active(&job_id).await {
+ Some(status) if !sync => return Ok(created(&job_id, "convert", &status)),
+ Some(_) => {} // sync: attach to the running job, don't re-spawn
+ None if dispatch::from_env() == dispatch::Dispatch::Lambda => {
+ state
+ .jobs
+ .set_pending(&job_id, "convert", optional_meta(&req), submit_urls.clone(), callback_url.clone())
+ .await;
+ lambda_dispatch(&state, &headers, &job_id, "convert", &req).await?;
}
None => {
- let tmp_str = tmp.to_string_lossy().to_string();
- let cache = Arc::clone(&state.cache);
- tokio::task::spawn_blocking(move || {
- // Unit detection scans at most the first 32MB (its own cap) —
- // never load the full source into RAM.
- let text = read_head_lossy(&tmp_str, 32 * 1024 * 1024)?;
- let out =
- converter::convert::convert_step(&tmp_str, &text, lin, ang).map(|conv| {
- let entry = Arc::new(cache::CachedConvert {
- glb: conv.glb.into(),
- graph_bytes: serde_json::to_vec(&conv.graph).unwrap().into(),
- component_count: conv.component_count,
- triangles: conv.triangles,
- unit: conv.graph["unit"].clone(),
- });
- cache.insert(key, Arc::clone(&entry));
- entry
- });
- let _ = std::fs::remove_file(&tmp_str);
- out
- })
- .await
- .map_err(|e| {
- ApiError::new(500, "TESSELLATION_FAILED", format!("convert panicked: {e}"))
- })?
- .map_err(ApiError::from)?
+ let declared_hash = req["source"]["contentHash"]
+ .as_str()
+ .map(str::trim)
+ .filter(|s| !s.is_empty() && s.len() <= 128)
+ .map(str::to_string);
+ let meta = optional_meta(&req);
+ state.jobs.set_pending(&job_id, "convert", meta, submit_urls.clone(), callback_url.clone()).await;
+ eprintln!("[{job_id}] convert queued");
+ actions::convert::spawn(
+ &state,
+ &job_id,
+ actions::convert::ConvertReq {
+ source_url: source_url.to_string(),
+ declared_hash,
+ glb_path: req["outputs"]["glb"]["path"].as_str().map(str::to_string),
+ graph_path: req["outputs"]["graph"]["path"].as_str().map(str::to_string),
+ lin: req["options"]["linearDeflection"].as_f64().unwrap_or(0.1),
+ ang: req["options"]["angularDeflection"].as_f64().unwrap_or(0.5),
+ optimize: req["options"]["optimize"].as_bool().unwrap_or(true),
+ },
+ );
}
- };
-
- tracker.progress.set_phase(progress::PHASE_UPLOAD);
- respond_convert(&job_id, entry, was_hit, glb_url, graph_url, started).await
+ }
+ respond(&state, &headers, &job_id, "convert", sync).await
}
-async fn convert_status(
+async fn create_optimize(
State(state): State<AppState>,
headers: HeaderMap,
- Path(job_id): Path<String>,
-) -> Result<Json<Value>, ApiError> {
+ Query(q): Query<CreateQuery>,
+ body: Result<Json<Value>, axum::extract::rejection::JsonRejection>,
+) -> Result<(StatusCode, HeaderMap, Json<Value>), ApiError> {
require_auth(&headers)?;
- match state.progress.get(&job_id) {
- Some(p) => {
- let (phase, done, total) = p.snapshot();
- Ok(Json(
- json!({"ok": true, "jobId": job_id, "phase": phase, "done": done, "total": total}),
- ))
+ let req = parse_body(body)?;
+
+ let source_url = req["source"]["url"]
+ .as_str()
+ .ok_or_else(|| ApiError::invalid("missing source.url"))?;
+ config::validate_url(source_url)?;
+ let job_id = resolve_job_id(&headers);
+ let sync = sync_flag(&q);
+ let (submit_urls, callback_url) = submit_plumbing(&headers, &req)?;
+
+ match state.jobs.existing_active(&job_id).await {
+ Some(status) if !sync => return Ok(created(&job_id, "optimize", &status)),
+ Some(_) => {} // sync: attach to the running job, don't re-spawn
+ None if dispatch::from_env() == dispatch::Dispatch::Lambda => {
+ state
+ .jobs
+ .set_pending(&job_id, "optimize", optional_meta(&req), submit_urls.clone(), callback_url.clone())
+ .await;
+ lambda_dispatch(&state, &headers, &job_id, "optimize", &req).await?;
+ }
+ None => {
+ let opts = optimize_opts(&req["output"], &req["quality"]);
+ // `auto` (the default) content-detects the format in the action.
+ let format = req["source"]["format"]
+ .as_str()
+ .unwrap_or("auto")
+ .to_string();
+ let meta = optional_meta(&req);
+ state.jobs.set_pending(&job_id, "optimize", meta, submit_urls.clone(), callback_url.clone()).await;
+ eprintln!("[{job_id}] optimize queued (format={format})");
+ actions::optimize::spawn(
+ &state,
+ &job_id,
+ actions::optimize::OptimizeReq {
+ source_url: source_url.to_string(),
+ format,
+ glb_path: req["output"]["path"].as_str().map(str::to_string),
+ opts,
+ },
+ );
}
- None => Err(ApiError::new(
- 404,
- "NOT_FOUND",
- format!("no in-flight convert {job_id}"),
- )),
}
+ respond(&state, &headers, &job_id, "optimize", sync).await
}
-/// Limit check + concurrent artifact PUTs + response — shared by the
-/// pre-download declared-hash hit and the normal path.
-async fn respond_convert(
- job_id: &str,
- entry: Arc<cache::CachedConvert>,
- was_hit: bool,
- glb_url: &str,
- graph_url: &str,
- started: std::time::Instant,
-) -> Result<Json<Value>, ApiError> {
- let mp = config::max_parts();
- if entry.component_count > mp as i64 {
- return Err(ApiError::new(
- 413,
- "LIMIT_EXCEEDED",
- format!(
- "assembly has {} part instances; the limit is {mp}",
- entry.component_count
- ),
- ));
+/// The simplify ladder: `quality.ladder` (array of number|null) if present, else
+/// a single rung from `quality.simplify`, else an aggressive default ladder
+/// (performance-first: walk down until the output fits the size/render gates).
+/// Build the optimise `Opts` from the request/spec JSON (`output` + `quality`
+/// objects, snake_case). Shared by the HTTP handler and the `run-job` CLI.
+pub fn optimize_opts(out: &Value, q: &Value) -> actions::optimize::Opts {
+ actions::optimize::Opts {
+ codec: out["codec"]
+ .as_str()
+ .and_then(optimize::Codec::from_str_opt)
+ .unwrap_or_default(),
+ ladder: parse_ladder(q),
+ simplify_aggressive: q["simplify_aggressive"].as_bool().unwrap_or(false),
+ weld: q["weld"].as_bool().unwrap_or(true),
+ reorder: q["reorder"].as_bool().unwrap_or(true),
+ // The quality/perf knob: max simplify deviation in mm. Absent = ratio-only.
+ tolerance: q["tolerance_mm"].as_f64().map(|f| f as f32),
+ // Auto mode by default (scale-invariant, per-mesh adaptive); `auto_error: 0`
+ // disables it for a lossless optimise (weld/reorder/encode only).
+ auto_error: Some(
+ q["auto_error"]
+ .as_f64()
+ .unwrap_or(optimize::DEFAULT_AUTO_ERROR as f64) as f32,
+ )
+ .filter(|&e| e > 0.0),
+ draco_bits: (
+ q["draco_position_bits"].as_i64().unwrap_or(14) as i32,
+ q["draco_normal_bits"].as_i64().unwrap_or(10) as i32,
+ q["draco_texcoord_bits"].as_i64().unwrap_or(12) as i32,
+ ),
+ quantize_normals: q["quantize_normals"].as_bool().unwrap_or(true),
+ merge_primitives: q["merge_primitives"].as_bool().unwrap_or(true),
+ max_packed: out["max_render_weight_bytes"]
+ .as_u64()
+ .unwrap_or(DEFAULT_MAX_RENDER_WEIGHT_BYTES) as usize,
+ max_output: out["max_bytes"]
+ .as_u64()
+ .unwrap_or(DEFAULT_MAX_OUTPUT_BYTES) as usize,
+ lin: q["linear_deflection"].as_f64().unwrap_or(0.1),
+ ang: q["angular_deflection"].as_f64().unwrap_or(0.5),
+ // Per-request budget wins; else the env default (set on the Lambda path).
+ budget: q["time_budget_secs"]
+ .as_u64()
+ .filter(|&s| s > 0)
+ .or_else(config::optimize_budget_secs)
+ .map(std::time::Duration::from_secs),
+ // Turned into an absolute deadline in `optimize::spawn` (charges the
+ // download + tessellation already spent).
+ deadline: None,
}
+}
- // Independent PUTs — run them concurrently.
- let (glb_res, graph_res) = tokio::join!(
- http::upload(glb_url, entry.glb.clone(), "model/gltf-binary"),
- http::upload(graph_url, entry.graph_bytes.clone(), "application/json"),
- );
- glb_res?;
- graph_res?;
-
- let convert_ms = started.elapsed().as_millis() as i64;
- eprintln!(
- "[{job_id}] convert done: {} parts, {} triangles, {convert_ms}ms{}",
- entry.component_count,
- entry.triangles,
- if was_hit { " (cache hit)" } else { "" }
- );
- Ok(Json(json!({
- "ok": true,
- "componentCount": entry.component_count,
- "unit": entry.unit,
- "stats": {"convertMs": convert_ms, "meshTriangles": entry.triangles, "warnings": []},
- })))
+fn parse_ladder(quality: &Value) -> Vec<Option<f32>> {
+ if let Some(arr) = quality["ladder"].as_array() {
+ return arr.iter().map(|v| v.as_f64().map(|f| f as f32)).collect();
+ }
+ match quality["simplify"].as_f64() {
+ Some(f) => vec![Some(f as f32)],
+ None => vec![None, Some(0.5), Some(0.25), Some(0.1)],
+ }
}
-async fn plan(
+async fn create_plan(
State(state): State<AppState>,
headers: HeaderMap,
+ Query(q): Query<CreateQuery>,
body: Result<Json<Value>, axum::extract::rejection::JsonRejection>,
-) -> Result<(axum::http::StatusCode, Json<Value>), ApiError> {
+) -> Result<(StatusCode, HeaderMap, Json<Value>), ApiError> {
require_auth(&headers)?;
- let Json(req) = body.map_err(|_| ApiError::invalid("invalid JSON body"))?;
+ let req = parse_body(body)?;
+
let source_url = req["source"]["url"]
.as_str()
.ok_or_else(|| ApiError::invalid("missing source.url"))?;
config::validate_url(source_url)?;
- let job_id = req["jobId"]
+ let job_id = resolve_job_id(&headers);
+ let sync = sync_flag(&q);
+ let (submit_urls, callback_url) = submit_plumbing(&headers, &req)?;
+
+ match state.jobs.existing_active(&job_id).await {
+ Some(status) if !sync => return Ok(created(&job_id, "plan", &status)),
+ Some(_) => {} // sync: attach to the running job, don't re-spawn
+ None if dispatch::from_env() == dispatch::Dispatch::Lambda => {
+ state
+ .jobs
+ .set_pending(&job_id, "plan", optional_meta(&req), submit_urls.clone(), callback_url.clone())
+ .await;
+ lambda_dispatch(&state, &headers, &job_id, "plan", &req).await?;
+ }
+ None => {
+ let meta = optional_meta(&req);
+ let plan_path = meta
+ .as_ref()
+ .and_then(|m| m["planPath"].as_str())
+ .map(str::to_string);
+ let model_upload_id = meta
+ .as_ref()
+ .and_then(|m| m["modelUploadId"].as_str())
+ .map(str::to_string);
+ state.jobs.set_pending(&job_id, "plan", meta, submit_urls.clone(), callback_url.clone()).await;
+ eprintln!(
+ "[{job_id}] plan queued (model={})",
+ model_upload_id.as_deref().unwrap_or("?")
+ );
+ actions::plan::spawn(
+ &state,
+ &job_id,
+ actions::plan::PlanReq {
+ source_url: source_url.to_string(),
+ plan_path,
+ model_upload_id,
+ options: req["options"].clone(),
+ },
+ );
+ }
+ }
+ respond(&state, &headers, &job_id, "plan", sync).await
+}
+
+async fn create_compact(
+ State(state): State<AppState>,
+ headers: HeaderMap,
+ Query(q): Query<CreateQuery>,
+ body: Result<Json<Value>, axum::extract::rejection::JsonRejection>,
+) -> Result<(StatusCode, HeaderMap, Json<Value>), ApiError> {
+ require_auth(&headers)?;
+ let req = parse_body(body)?;
+
+ let source_url = req["source"]["url"]
.as_str()
- .filter(|s| !s.is_empty())
- .ok_or_else(|| ApiError::invalid("missing jobId"))?
- .to_string();
+ .ok_or_else(|| ApiError::invalid("missing source.url"))?;
+ config::validate_url(source_url)?;
+ let mode = actions::compact::Mode::from_str(req["mode"].as_str().unwrap_or("xbf"))
+ .ok_or_else(|| ApiError::invalid("mode must be 'xbf' or 'zstd'"))?;
+ let job_id = resolve_job_id(&headers);
+ let sync = sync_flag(&q);
+ let (submit_urls, callback_url) = submit_plumbing(&headers, &req)?;
+
+ match state.jobs.existing_active(&job_id).await {
+ Some(status) if !sync => return Ok(created(&job_id, "compact", &status)),
+ Some(_) => {} // sync: attach to the running job, don't re-spawn
+ None if dispatch::from_env() == dispatch::Dispatch::Lambda => {
+ state
+ .jobs
+ .set_pending(&job_id, "compact", optional_meta(&req), submit_urls.clone(), callback_url.clone())
+ .await;
+ lambda_dispatch(&state, &headers, &job_id, "compact", &req).await?;
+ }
+ None => {
+ let meta = optional_meta(&req);
+ state.jobs.set_pending(&job_id, "compact", meta, submit_urls.clone(), callback_url.clone()).await;
+ eprintln!("[{job_id}] compact queued");
+ actions::compact::spawn(
+ &state,
+ &job_id,
+ actions::compact::CompactReq {
+ source_url: source_url.to_string(),
+ mode,
+ raw_path: req["output"]["path"].as_str().map(str::to_string),
+ },
+ );
+ }
+ }
+ respond(&state, &headers, &job_id, "compact", sync).await
+}
- // Opaque caller context echoed back in status responses; the storage path +
- // model id inside it also drive the completion pointer and the content-hash
- // result cache.
- let meta = match &req["meta"] {
+fn optional_meta(req: &Value) -> Option<Value> {
+ match &req["meta"] {
Value::Null => None,
m => Some(m.clone()),
- };
- let plan_path = meta
- .as_ref()
- .and_then(|m| m["planPath"].as_str())
- .map(str::to_string);
- let model_upload_id = meta
- .as_ref()
- .and_then(|m| m["modelUploadId"].as_str())
- .map(str::to_string);
-
- // Idempotent: attach to an in-flight run rather than starting a second.
- if let Some(status) = state.jobs.existing_active(&job_id).await {
- return Ok((
- axum::http::StatusCode::ACCEPTED,
- Json(json!({"ok": true, "jobId": job_id, "status": status})),
- ));
}
- eprintln!(
- "[{job_id}] plan queued (model={})",
- model_upload_id.as_deref().unwrap_or("?")
- );
- state.jobs.set_pending(&job_id, meta.clone()).await;
- state.jobs.spawn(
- &state,
- &job_id,
- plan_jobs::PlanReq {
- source_url: source_url.to_string(),
- plan_path,
- model_upload_id,
- options: req["options"].clone(),
- },
- );
-
- Ok((
- axum::http::StatusCode::ACCEPTED,
- Json(json!({"ok": true, "jobId": job_id, "status": "pending"})),
- ))
}
#[derive(serde::Deserialize)]
@@ -435,53 +712,96 @@ struct WaitQuery {
wait: Option<u64>,
}
-async fn plan_status(
+async fn get_job(
State(state): State<AppState>,
headers: HeaderMap,
Path(job_id): Path<String>,
Query(q): Query<WaitQuery>,
) -> Result<Json<Value>, ApiError> {
require_auth(&headers)?;
- // Late-mint offload: the app hands a FRESH signed upload URL on each poll, so
- // the service PUTs the finished plan.json the instant it's ready with a token
- // minted seconds ago (no long-lived URL). Absent for non-offload callers.
- let upload_url = headers
- .get("x-plan-upload-url")
- .and_then(|v| v.to_str().ok())
- .filter(|s| !s.is_empty())
- .map(str::to_string);
- if let Some(u) = &upload_url {
- config::validate_url(u)?;
- }
+ // Late-mint offload: the caller hands FRESH signed upload URLs on each poll
+ // (one per pending output, keyed by output name), so the service PUTs the
+ // finished artifacts with tokens minted seconds ago. Absent for callers that
+ // don't offload.
+ let upload_urls = parse_upload_urls(&headers)?;
let max = match q.wait {
Some(secs) if secs > 0 => Some(std::time::Duration::from_secs(
secs.min(config::max_long_poll_secs()),
)),
_ => None,
};
+ let mut v = state
+ .jobs
+ .poll(&job_id, &upload_urls, max)
+ .await
+ .ok_or_else(|| ApiError::new(404, "not_found", format!("no job {job_id}")))?;
+ // Best-effort live progress (same replica only): merge the convert phase
+ // checklist while the job is running.
+ if v["job"]["status"] == "running" {
+ if let Some(p) = state.progress.get(&job_id) {
+ let (phase, done, total) = p.snapshot();
+ v["job"]["progress"] = json!({ "phase": phase, "done": done, "total": total });
+ }
+ }
+ Ok(Json(v))
+}
+
+/// Parse fresh per-poll signed upload URLs. Preferred: the
+/// `X-Carbon-Upload-Urls` JSON header `{"glb":"…","graph":"…"}`. Also accepts the
+/// single-output legacy `X-Plan-Upload-Url` (→ `{"plan": …}`).
+fn parse_upload_urls(headers: &HeaderMap) -> Result<HashMap<String, String>, ApiError> {
+ let mut out = HashMap::new();
+ if let Some(raw) = headers
+ .get("x-carbon-upload-urls")
+ .and_then(|v| v.to_str().ok())
+ .filter(|s| !s.is_empty())
+ {
+ let map: HashMap<String, String> = serde_json::from_str(raw)
+ .map_err(|_| ApiError::invalid("invalid X-Carbon-Upload-Urls header"))?;
+ for (name, url) in map {
+ config::validate_url(&url)?;
+ out.insert(name, url);
+ }
+ }
+ if let Some(url) = headers
+ .get("x-plan-upload-url")
+ .and_then(|v| v.to_str().ok())
+ .filter(|s| !s.is_empty())
+ {
+ config::validate_url(url)?;
+ out.insert("plan".into(), url.to_string());
+ }
+ Ok(out)
+}
+
+async fn cancel_job(
+ State(state): State<AppState>,
+ headers: HeaderMap,
+ Path(job_id): Path<String>,
+) -> Result<Json<Value>, ApiError> {
+ require_auth(&headers)?;
state
.jobs
- .poll(&job_id, upload_url.as_deref(), max)
+ .cancel(&job_id)
.await
- .ok_or_else(|| ApiError::new(404, "NOT_FOUND", format!("no plan job {job_id}")))
.map(Json)
+ .ok_or_else(|| ApiError::new(404, "not_found", format!("no job {job_id}")))
}
/// Central explicit cache invalidation: drop every content-hash result pointer
-/// for a model so the next plan re-derives. Best-effort from the app's
-/// invalidateAssemblyPlanCache / invalidateAssemblyModelCache.
+/// for a model so the next job re-derives.
async fn cache_invalidate(
State(state): State<AppState>,
headers: HeaderMap,
body: Result<Json<Value>, axum::extract::rejection::JsonRejection>,
) -> Result<Json<Value>, ApiError> {
require_auth(&headers)?;
- let Json(req) = body.map_err(|_| ApiError::invalid("invalid JSON body"))?;
+ let req = parse_body(body)?;
let model = req["modelUploadId"]
.as_str()
.filter(|s| !s.is_empty())
.ok_or_else(|| ApiError::invalid("missing modelUploadId"))?;
let cleared = state.jobs.invalidate_model(model).await;
eprintln!("cache invalidate: model={model} cleared={cleared}");
- Ok(Json(json!({"ok": true, "cleared": cleared})))
+ Ok(Json(json!({ "ok": true, "cleared": cleared })))
}
diff --git a/apps/assembler/src/plan_jobs.rs b/apps/assembler/src/plan_jobs.rs
deleted file mode 100644
index 21df98e84a..0000000000
--- a/apps/assembler/src/plan_jobs.rs
+++ /dev/null
@@ -1,707 +0,0 @@
-//! Async plan jobs + shared job/result store. A job runs in a Tokio task
-//! (holding a concurrency slot); callers long-poll GET /plan/{jobId}?wait=.
-//!
-//! The store is backend-selectable at boot (`ASSEMBLER_REDIS_URL`):
-//! - `Memory` (default): process-local DashMaps — single-process behavior.
-//! - `Redis`: status + pointers (never plan/glb bytes) live in Redis, so a
-//! restart or a sibling replica can still answer the poll. This is what
-//! makes the service stateless. A set-but-unreachable URL falls back to
-//! memory at boot rather than refusing to start.
-//!
-//! On completion the plan artifact is PUT to the caller-signed `outputs.plan.url`
-//! (offload) and only the `{planPath, stats, …}` POINTER is stored — the plan
-//! JSON never enters Redis or lingers in memory.
-
-use crate::{cache::CODE_VERSION, config, http, AppState};
-use dashmap::DashMap;
-use planner::steps::PlanUnit;
-use redis::AsyncCommands;
-use serde::{Deserialize, Serialize};
-use serde_json::{json, Value};
-use std::sync::Arc;
-use std::time::{Duration, Instant};
-use tokio::sync::Notify;
-
-/// One job's persisted state. Serializable so the Redis backend stores it as a
-/// JSON blob and the memory backend keeps the same shape. `done` holds the
-/// completion POINTER (planPath/stats/counts) — not the plan itself.
-#[derive(Clone, Serialize, Deserialize)]
-struct JobRecord {
- status: String, // pending | running | done | error
- #[serde(skip_serializing_if = "Option::is_none")]
- done: Option<Value>,
- #[serde(skip_serializing_if = "Option::is_none")]
- error: Option<String>,
- #[serde(skip_serializing_if = "Option::is_none")]
- meta: Option<Value>,
-}
-
-#[derive(Clone)]
-enum Backend {
- Memory {
- jobs: Arc<DashMap<String, JobRecord>>,
- results: Arc<DashMap<String, Value>>,
- },
- Redis {
- conn: redis::aio::ConnectionManager,
- },
-}
-
-/// A finished plan held in memory until a long-poll hands the service a fresh
-/// signed upload URL to PUT it to (late-mint offload). Never touches Redis (it's
-/// bytes, not a pointer); lives only on the replica that computed the plan.
-struct Pending {
- plan: Vec<u8>,
- /// The completion pointer to publish once the upload succeeds.
- done: Value,
- /// Content-hash cache key `(model, contentHash, optsHash)` — the pointer is
- /// only cached once the artifact is durably uploaded (never a dangling path).
- cache: Option<(String, u128, u64)>,
-}
-
-/// Shared job + content-hash result store. Cloned into every handler via
-/// `AppState`; all inner state is `Arc`/manager-cloned so clones share one store.
-#[derive(Clone)]
-pub struct JobStore {
- backend: Backend,
- /// Per-job in-process wakeups so a same-replica long-poll returns the instant
- /// the worker finishes (cross-replica completion is caught by the Redis
- /// re-check inside `wait_status`).
- notifiers: Arc<DashMap<String, Arc<Notify>>>,
- /// Computed-but-not-yet-uploaded plans, keyed by job id. A long-poll that
- /// carries an upload URL drains this via `try_finalize`.
- pending: Arc<DashMap<String, Pending>>,
-}
-
-/// Outcome of a finalize attempt during a long-poll.
-pub enum Finalize {
- /// Uploaded — the returned value is the terminal `done` status.
- Uploaded(Value),
- /// Nothing to upload here (already finalized, or the artifact lives on
- /// another replica) — keep waiting.
- NotPending,
- /// Upload failed transiently; the artifact is kept for the next poll to retry.
- Retry,
-}
-
-/// Everything a plan task needs from the request.
-pub struct PlanReq {
- pub source_url: String,
- /// Storage path recorded in the completion pointer (what the app persists).
- /// The plan.json is PUT here later via a per-poll signed URL (late-mint).
- pub plan_path: Option<String>,
- /// Scopes the content-hash result cache; None disables caching for this job.
- pub model_upload_id: Option<String>,
- pub options: Value,
-}
-
-impl JobStore {
- /// Build from env: Redis when `ASSEMBLER_REDIS_URL` is set and reachable,
- /// else in-memory. Never refuses to boot.
- pub async fn from_env() -> Self {
- let notifiers = Arc::new(DashMap::new());
- if let Some(url) = config::redis_url() {
- match connect(&url).await {
- Ok(conn) => {
- eprintln!("assembler: redis job store enabled");
- return JobStore {
- backend: Backend::Redis { conn },
- notifiers,
- pending: Arc::new(DashMap::new()),
- };
- }
- Err(e) => {
- eprintln!(
- "assembler: ASSEMBLER_REDIS_URL unreachable ({e}); falling back to in-memory store"
- );
- }
- }
- } else {
- eprintln!("assembler: in-memory job store (ASSEMBLER_REDIS_URL unset)");
- }
- JobStore {
- backend: Backend::Memory {
- jobs: Arc::new(DashMap::new()),
- results: Arc::new(DashMap::new()),
- },
- notifiers,
- pending: Arc::new(DashMap::new()),
- }
- }
-
- // --- job status (pointer, not content) ---------------------------------
-
- async fn read(&self, id: &str) -> Option<JobRecord> {
- match &self.backend {
- Backend::Memory { jobs, .. } => jobs.get(id).map(|j| j.clone()),
- Backend::Redis { conn } => {
- let mut c = conn.clone();
- match c.get::<_, Option<String>>(job_key(id)).await {
- Ok(Some(s)) => serde_json::from_str(&s).ok(),
- Ok(None) => None,
- Err(e) => {
- eprintln!("assembler: redis job read failed: {e}");
- None
- }
- }
- }
- }
- }
-
- async fn write(&self, id: &str, rec: &JobRecord) {
- match &self.backend {
- Backend::Memory { jobs, .. } => {
- jobs.insert(id.to_string(), rec.clone());
- }
- Backend::Redis { conn } => {
- let Ok(payload) = serde_json::to_string(rec) else {
- return;
- };
- let mut c = conn.clone();
- if let Err(e) = c
- .set_ex::<_, _, ()>(job_key(id), payload, config::job_ttl_secs())
- .await
- {
- eprintln!("assembler: redis job write failed: {e}");
- }
- }
- }
- }
-
- pub async fn existing_active(&self, id: &str) -> Option<String> {
- self.read(id)
- .await
- .filter(|j| j.status == "pending" || j.status == "running")
- .map(|j| j.status)
- }
-
- pub async fn set_pending(&self, id: &str, meta: Option<Value>) {
- self.write(
- id,
- &JobRecord {
- status: "pending".into(),
- done: None,
- error: None,
- meta,
- },
- )
- .await;
- }
-
- async fn set_status(&self, id: &str, status: &str) {
- if let Some(mut rec) = self.read(id).await {
- rec.status = status.to_string();
- self.write(id, &rec).await;
- }
- }
-
- async fn set_done(&self, id: &str, done: Value) {
- let meta = self.read(id).await.and_then(|r| r.meta);
- self.write(
- id,
- &JobRecord {
- status: "done".into(),
- done: Some(done),
- error: None,
- meta,
- },
- )
- .await;
- self.wake(id);
- }
-
- async fn set_error(&self, id: &str, error: String) {
- let meta = self.read(id).await.and_then(|r| r.meta);
- self.write(
- id,
- &JobRecord {
- status: "error".into(),
- done: None,
- error: Some(error),
- meta,
- },
- )
- .await;
- self.wake(id);
- }
-
- fn render(rec: &JobRecord) -> Value {
- let mut out = match rec.status.as_str() {
- "done" => rec
- .done
- .clone()
- .unwrap_or_else(|| json!({"ok": true, "status": "done"})),
- "error" => json!({"ok": true, "status": "error", "error": rec.error}),
- s => json!({"ok": true, "status": s}),
- };
- if let Some(meta) = &rec.meta {
- out["meta"] = meta.clone();
- }
- out
- }
-
- pub async fn status(&self, id: &str) -> Option<Value> {
- self.read(id).await.map(|r| Self::render(&r))
- }
-
- /// Long-poll a job to a terminal state. `upload_url` (when the request
- /// carried one) is used to drain a computed-but-unuploaded plan the instant
- /// it's ready (late-mint offload). With `max`, holds until terminal or the
- /// deadline (same-replica wake via `Notify`, cross-replica via the ~500ms
- /// re-read); without `max`, a single shot. `None` only if the job is unknown.
- pub async fn poll(
- &self,
- id: &str,
- upload_url: Option<&str>,
- max: Option<Duration>,
- ) -> Option<Value> {
- let deadline = max.map(|m| Instant::now() + m);
- loop {
- let cur = self.status(id).await;
- if let Some(v) = &cur {
- match v["status"].as_str().unwrap_or("") {
- "done" | "error" => return cur,
- "uploading" => {
- if let Some(u) = upload_url {
- if let Finalize::Uploaded(done) = self.try_finalize(id, u).await {
- return Some(done);
- }
- }
- }
- _ => {}
- }
- }
- let Some(dl) = deadline else {
- return cur; // single shot: current status (or None if unknown)
- };
- let now = Instant::now();
- if now >= dl {
- return cur;
- }
- let notify = self.notifier(id);
- let tick = (dl - now).min(Duration::from_millis(500));
- tokio::select! {
- _ = notify.notified() => {}
- _ = tokio::time::sleep(tick) => {}
- }
- }
- }
-
- fn notifier(&self, id: &str) -> Arc<Notify> {
- self.notifiers
- .entry(id.to_string())
- .or_insert_with(|| Arc::new(Notify::new()))
- .clone()
- }
-
- fn wake(&self, id: &str) {
- if let Some(n) = self.notifiers.get(id) {
- n.notify_waiters();
- }
- }
-
- /// Hold a computed-but-unuploaded plan for hand-off. Memory backend keeps it
- /// in-process; Redis backend stores it (bytes + pointer) under a short TTL so
- /// ANY replica's poll can drain it — removing the single-process constraint.
- async fn pending_put(
- &self,
- id: &str,
- plan: Vec<u8>,
- done: Value,
- cache: Option<(String, u128, u64)>,
- ) {
- match &self.backend {
- Backend::Memory { .. } => {
- self.pending
- .insert(id.to_string(), Pending { plan, done, cache });
- }
- Backend::Redis { conn } => {
- let cache_s = cache.map(|(m, c, o)| format!("{m}|{c:032x}|{o}"));
- let mut c = conn.clone();
- let mut pipe = redis::pipe();
- pipe.hset(pending_key(id), "plan", plan)
- .ignore()
- .hset(pending_key(id), "done", done.to_string())
- .ignore();
- if let Some(cs) = cache_s {
- pipe.hset(pending_key(id), "cache", cs).ignore();
- }
- pipe.expire(pending_key(id), config::pending_ttl_secs() as i64)
- .ignore();
- if let Err(e) = pipe.query_async::<()>(&mut c).await {
- eprintln!("assembler: redis pending_put failed: {e}");
- }
- }
- }
- }
-
- async fn pending_take(&self, id: &str) -> Option<(Vec<u8>, Value, Option<(String, u128, u64)>)> {
- match &self.backend {
- Backend::Memory { .. } => self
- .pending
- .get(id)
- .map(|p| (p.plan.clone(), p.done.clone(), p.cache.clone())),
- Backend::Redis { conn } => {
- let mut c = conn.clone();
- let res: redis::RedisResult<(Option<Vec<u8>>, Option<String>, Option<String>)> =
- redis::pipe()
- .hget(pending_key(id), "plan")
- .hget(pending_key(id), "done")
- .hget(pending_key(id), "cache")
- .query_async(&mut c)
- .await;
- let (plan, done_s, cache_s) = match res {
- Ok(t) => t,
- Err(e) => {
- eprintln!("assembler: redis pending_take failed: {e}");
- return None;
- }
- };
- let done: Value = serde_json::from_str(&done_s?).ok()?;
- Some((plan?, done, cache_s.and_then(parse_cache)))
- }
- }
- }
-
- async fn pending_remove(&self, id: &str) {
- match &self.backend {
- Backend::Memory { .. } => {
- self.pending.remove(id);
- }
- Backend::Redis { conn } => {
- let mut c = conn.clone();
- if let Err(e) = c.del::<_, ()>(pending_key(id)).await {
- eprintln!("assembler: redis pending_remove failed: {e}");
- }
- }
- }
- }
-
- /// Drain a computed-but-unuploaded plan to `upload_url` (called from a
- /// long-poll that carried a fresh signed URL). On success publishes the
- /// terminal `done` pointer; on transient failure keeps the artifact so the
- /// next poll can retry with a fresher URL.
- pub async fn try_finalize(&self, id: &str, upload_url: &str) -> Finalize {
- let Some((plan, done, cache)) = self.pending_take(id).await else {
- return Finalize::NotPending;
- };
- match http::upload(upload_url, plan, "application/json").await {
- Ok(()) => {
- self.pending_remove(id).await;
- if let Some((model, content, opts)) = cache {
- self.result_put(&model, content, opts, done.clone()).await;
- }
- self.set_done(id, done.clone()).await;
- Finalize::Uploaded(done)
- }
- Err(e) => {
- eprintln!("[{id}] plan upload failed (will retry next poll): {}", e.message);
- Finalize::Retry
- }
- }
- }
-
- // --- content-hash result-pointer cache (CODE_VERSION-stamped) ----------
-
- async fn result_get(&self, model: &str, content: u128, opts: u64) -> Option<Value> {
- let key = result_key(model, content, opts);
- match &self.backend {
- Backend::Memory { results, .. } => results.get(&key).map(|v| v.clone()),
- Backend::Redis { conn } => {
- let mut c = conn.clone();
- match c.get::<_, Option<String>>(&key).await {
- Ok(Some(s)) => serde_json::from_str(&s).ok(),
- Ok(None) => None,
- Err(e) => {
- eprintln!("assembler: redis result read failed: {e}");
- None
- }
- }
- }
- }
- }
-
- async fn result_put(&self, model: &str, content: u128, opts: u64, pointer: Value) {
- let key = result_key(model, content, opts);
- match &self.backend {
- Backend::Memory { results, .. } => {
- results.insert(key, pointer);
- }
- Backend::Redis { conn } => {
- let Ok(payload) = serde_json::to_string(&pointer) else {
- return;
- };
- let mut c = conn.clone();
- if let Err(e) = c
- .set_ex::<_, _, ()>(&key, payload, config::result_ttl_secs())
- .await
- {
- eprintln!("assembler: redis result write failed: {e}");
- }
- }
- }
- }
-
- /// Central explicit invalidation: drop every cached result pointer for a
- /// model so the next plan re-derives. Returns how many entries were cleared.
- pub async fn invalidate_model(&self, model: &str) -> usize {
- let prefix = format!("asm:result:{model}:");
- match &self.backend {
- Backend::Memory { results, .. } => {
- let keys: Vec<String> = results
- .iter()
- .filter(|e| e.key().starts_with(&prefix))
- .map(|e| e.key().clone())
- .collect();
- for k in &keys {
- results.remove(k);
- }
- keys.len()
- }
- Backend::Redis { conn } => {
- let pattern = format!("{prefix}*");
- let mut scan = conn.clone();
- let mut keys: Vec<String> = Vec::new();
- match scan.scan_match::<_, String>(&pattern).await {
- Ok(mut iter) => {
- while let Some(k) = iter.next_item().await {
- keys.push(k);
- }
- }
- Err(e) => {
- eprintln!("assembler: redis invalidate scan failed: {e}");
- return 0;
- }
- }
- if keys.is_empty() {
- return 0;
- }
- let mut c = conn.clone();
- if let Err(e) = c.del::<_, ()>(&keys).await {
- eprintln!("assembler: redis invalidate del failed: {e}");
- return 0;
- }
- keys.len()
- }
- }
- }
-
- // --- the plan task ------------------------------------------------------
-
- pub fn spawn(&self, state: &AppState, job_id: &str, req: PlanReq) {
- let jobs = self.clone();
- let slots = Arc::clone(&state.slots);
- let job_id = job_id.to_string();
- tokio::spawn(async move {
- let _permit = slots.acquire().await;
- jobs.set_status(&job_id, "running").await;
- eprintln!("[{job_id}] plan running");
- let started = Instant::now();
-
- let tmp = http::temp_path("step");
- let content_hash = match http::download_hashed(&req.source_url, &tmp, None).await {
- Ok(h) => h,
- Err(e) => {
- let msg = e.message;
- eprintln!("[{job_id}] plan failed: source download: {msg}");
- let _ = tokio::fs::remove_file(&tmp).await;
- jobs.set_error(&job_id, msg).await;
- return;
- }
- };
- let opts_hash = opts_hash(&req.options);
-
- // Content-hash result cache: same model + same bytes + same options +
- // same CODE_VERSION => reuse the prior plan's storage pointer, skip
- // the FCL compute. Same-model scoped so a reused pointer shares the
- // model's invalidation (never a cross-model dangling path).
- if let Some(model) = &req.model_upload_id {
- if let Some(ptr) = jobs.result_get(model, content_hash, opts_hash).await {
- let _ = tokio::fs::remove_file(&tmp).await;
- eprintln!("[{job_id}] plan cache hit ({} parts)", ptr["componentCount"]);
- jobs.set_done(&job_id, ptr).await;
- return;
- }
- }
-
- let tmp_str = tmp.to_string_lossy().to_string();
- let (lin, ang, clearance, path_samples, units, sequence, tolerance) =
- parse_options(&req.options);
- let mp = config::max_parts();
-
- let res = tokio::task::spawn_blocking(move || {
- planner::steps::plan_step(
- &tmp_str,
- lin,
- ang,
- clearance,
- path_samples,
- Some(mp),
- units,
- sequence,
- tolerance,
- )
- })
- .await;
- let _ = tokio::fs::remove_file(&tmp).await;
-
- match res {
- Ok(Ok(r)) => {
- let plan_ms = started.elapsed().as_millis() as i64;
- let stats = json!({
- "planMs": plan_ms,
- "tiers": r.tiers,
- "warnings": r.warnings,
- "verifiedCount": r.verified_count,
- "componentCount": r.component_count,
- "plannedCount": r.planned_count,
- });
- let pointer = json!({
- "ok": true,
- "status": "done",
- "planPath": req.plan_path,
- "componentCount": r.component_count,
- "plannedCount": r.planned_count,
- "stats": stats,
- });
- eprintln!(
- "[{job_id}] plan computed: {} parts, {} planned, {plan_ms}ms",
- r.component_count, r.planned_count
- );
-
- match &req.plan_path {
- // Late-mint offload: hold the plan in memory and mark the
- // job "uploading"; a long-poll carrying a fresh signed URL
- // drains it (try_finalize) and publishes the pointer.
- Some(_) => match serde_json::to_vec(&r.plan) {
- Ok(bytes) => {
- let cache = req
- .model_upload_id
- .as_ref()
- .map(|m| (m.clone(), content_hash, opts_hash));
- jobs.pending_put(&job_id, bytes, pointer, cache).await;
- jobs.set_status(&job_id, "uploading").await;
- jobs.wake(&job_id);
- }
- Err(e) => {
- jobs.set_error(&job_id, format!("serialize plan: {e}")).await
- }
- },
- // No storage path (None meta): return the plan inline in
- // the status body for the app to persist itself.
- None => {
- let mut done = pointer;
- done["plan"] = r.plan;
- jobs.set_done(&job_id, done).await;
- }
- }
- }
- Ok(Err(e)) => {
- eprintln!("[{job_id}] plan failed: {}", e.message);
- jobs.set_error(&job_id, e.message).await;
- }
- Err(e) => {
- let msg = format!("plan panicked: {e}");
- eprintln!("[{job_id}] {msg}");
- jobs.set_error(&job_id, msg).await;
- }
- }
- });
- }
-}
-
-async fn connect(url: &str) -> redis::RedisResult<redis::aio::ConnectionManager> {
- let client = redis::Client::open(url)?;
- let mut conn = client.get_connection_manager().await?;
- // Validate the URL at boot so a bad one falls back to memory now, not on the
- // first job.
- redis::cmd("PING").query_async::<()>(&mut conn).await?;
- Ok(conn)
-}
-
-fn job_key(id: &str) -> String {
- format!("asm:job:{id}")
-}
-
-fn result_key(model: &str, content: u128, opts: u64) -> String {
- format!("asm:result:{model}:{content:032x}:{opts:016x}:v{CODE_VERSION}")
-}
-
-fn pending_key(id: &str) -> String {
- format!("asm:pending:{id}")
-}
-
-/// Parse a `"model|contentHex|opts"` cache tuple stored alongside a pending plan.
-fn parse_cache(s: String) -> Option<(String, u128, u64)> {
- let mut it = s.splitn(3, '|');
- let model = it.next()?.to_string();
- let content = u128::from_str_radix(it.next()?, 16).ok()?;
- let opts = it.next()?.parse().ok()?;
- Some((model, content, opts))
-}
-
-/// Stable hash of the plan options. serde_json serializes object keys sorted
-/// (BTreeMap), so the string is deterministic; it includes units/sequence, so
-/// dropping auto-swarm units on a fresh regenerate changes the key and misses.
-fn opts_hash(options: &Value) -> u64 {
- xxhash_rust::xxh3::xxh3_64(options.to_string().as_bytes())
-}
-
-type Opts = (
- f64,
- f64,
- f64,
- usize,
- Option<Vec<PlanUnit>>,
- Option<Vec<Vec<String>>>,
- Option<f64>,
-);
-
-fn parse_options(options: &Value) -> Opts {
- let lin = options["linearDeflection"].as_f64().unwrap_or(0.1);
- let ang = options["angularDeflection"].as_f64().unwrap_or(0.5);
- let clearance = options["clearance"].as_f64().unwrap_or(0.5);
- let path_samples = options["pathSamples"].as_u64().unwrap_or(60) as usize;
- // Optional explicit penetration tolerance (mm); absent => inferred from
- // linearDeflection inside plan_step.
- let tolerance = options["tolerance"].as_f64();
-
- let units = options["units"].as_array().map(|arr| {
- arr.iter()
- .map(|u| PlanUnit {
- id: u["id"].as_str().unwrap_or("").to_string(),
- name: u["name"].as_str().map(|s| s.to_string()),
- node_ids: u["nodeIds"]
- .as_array()
- .map(|a| {
- a.iter()
- .filter_map(|v| v.as_str().map(|s| s.to_string()))
- .collect()
- })
- .unwrap_or_default(),
- })
- .collect()
- });
- let sequence = options["sequence"].as_array().map(|arr| {
- arr.iter()
- .map(|g| {
- g.as_array()
- .map(|a| {
- a.iter()
- .filter_map(|v| v.as_str().map(|s| s.to_string()))
- .collect()
- })
- .unwrap_or_default()
- })
- .collect()
- });
- (
- lin,
- ang,
- clearance,
- path_samples,
- units,
- sequence,
- tolerance,
- )
-}
diff --git a/apps/assembler/src/run.rs b/apps/assembler/src/run.rs
new file mode 100644
index 0000000000..34e487073c
--- /dev/null
+++ b/apps/assembler/src/run.rs
@@ -0,0 +1,201 @@
+//! One-shot `run-job` CLI: run ONE action to completion and exit — no HTTP
+//! server. The ECS Fargate overflow entrypoint (and any non-HTTP invoke) for
+//! jobs past Lambda's 15-min cap. It reuses the *exact* compute + finalize path
+//! as the async HTTP mode (spawn the action, then drain it to terminal with the
+//! caller's signed upload URLs), so there is no second code path to keep in sync.
+//! The Lambda default still runs the HTTP server via the Lambda Web Adapter.
+//!
+//! Spec (JSON, from `argv[2]` or `$ASSEMBLER_JOB_SPEC`) — the same shape as the
+//! HTTP body plus an `action` and an `upload_urls` map:
+//! ```json
+//! { "action": "optimize"|"convert"|"plan",
+//! "job_id": "…", // optional
+//! "source": { "url": "<signed GET>", "format": "auto" },
+//! "output" | "outputs" | "options" | "quality": { … }, // per action, as HTTP
+//! "upload_urls": { "glb": "<signed PUT>", "graph": "…" } }
+//! ```
+
+use serde_json::{json, Value};
+use std::collections::HashMap;
+use std::time::{Duration, Instant};
+
+use crate::{actions, build_state, config, optimize_opts, AppState};
+
+/// Overall wall-clock ceiling for a one-shot job. Generous: ECS has no 15-min
+/// cap (that's exactly why the overflow path exists); Lambda's own timeout bounds
+/// the sync-HTTP variant separately.
+const RUN_JOB_MAX_SECS: u64 = 60 * 60;
+
+pub async fn run_job_cli() -> ! {
+ let spec = match load_spec() {
+ Ok(s) => s,
+ Err(m) => fail(&m),
+ };
+ let action = spec["action"].as_str().unwrap_or_default().to_string();
+ let source_url = spec["source"]["url"]
+ .as_str()
+ .unwrap_or_default()
+ .to_string();
+ if source_url.is_empty() {
+ fail("missing source.url");
+ }
+ if let Err(e) = config::validate_url(&source_url) {
+ fail(&format!("invalid source.url: {}", e.message));
+ }
+ let job_id = spec["job_id"]
+ .as_str()
+ .map(str::to_string)
+ .unwrap_or_else(|| format!("run-job-{action}"));
+ let urls = upload_urls(&spec);
+
+ let state = build_state().await;
+ let callback = spec["callback_url"].as_str().map(str::to_string);
+ state
+ .jobs
+ .set_pending(&job_id, &action, None, urls.clone(), callback)
+ .await;
+
+ if let Err(m) = spawn_from_spec(&state, &job_id, &action, &spec) {
+ fail(&m);
+ }
+
+ let result = run_to_completion(&state, &job_id, &urls).await;
+ // The CLI owns the process lifetime — (re)deliver the completion callback
+ // before exiting (no-op if none / already delivered semantics are idempotent
+ // for the receiver).
+ state.jobs.send_callback(&job_id).await;
+ println!("{result}");
+ let ok = matches!(result["job"]["status"].as_str(), Some("succeeded"));
+ std::process::exit(if ok { 0 } else { 1 });
+}
+
+/// Start the action described by a run-job spec (same field shapes as the HTTP
+/// create bodies, plus `action`/`job_id` at the top level). Shared by the CLI
+/// and the Lambda self-invoke worker (`POST /events`). The job must already be
+/// `set_pending`; the caller decides how to drain it (CLI/worker:
+/// `run_to_completion`; a poll from any replica also works via Redis).
+pub fn spawn_from_spec(
+ state: &AppState,
+ job_id: &str,
+ action: &str,
+ spec: &Value,
+) -> Result<(), String> {
+ let source_url = spec["source"]["url"]
+ .as_str()
+ .unwrap_or_default()
+ .to_string();
+ match action {
+ "optimize" => actions::optimize::spawn(
+ state,
+ job_id,
+ actions::optimize::OptimizeReq {
+ source_url,
+ format: spec["source"]["format"]
+ .as_str()
+ .unwrap_or("auto")
+ .to_string(),
+ glb_path: spec["output"]["path"].as_str().map(str::to_string),
+ opts: optimize_opts(&spec["output"], &spec["quality"]),
+ },
+ ),
+ "convert" => actions::convert::spawn(
+ state,
+ job_id,
+ actions::convert::ConvertReq {
+ source_url,
+ declared_hash: spec["source"]["contentHash"].as_str().map(str::to_string),
+ glb_path: spec["outputs"]["glb"]["path"].as_str().map(str::to_string),
+ graph_path: spec["outputs"]["graph"]["path"].as_str().map(str::to_string),
+ lin: spec["options"]["linearDeflection"].as_f64().unwrap_or(0.1),
+ ang: spec["options"]["angularDeflection"].as_f64().unwrap_or(0.5),
+ optimize: spec["options"]["optimize"].as_bool().unwrap_or(true),
+ },
+ ),
+ "plan" => actions::plan::spawn(
+ state,
+ job_id,
+ actions::plan::PlanReq {
+ source_url,
+ plan_path: spec["output"]["path"]
+ .as_str()
+ .or_else(|| spec["meta"]["planPath"].as_str())
+ .map(str::to_string),
+ model_upload_id: spec["model_upload_id"]
+ .as_str()
+ .or_else(|| spec["meta"]["modelUploadId"].as_str())
+ .map(str::to_string),
+ options: spec["options"].clone(),
+ },
+ ),
+ "compact" => {
+ let mode = actions::compact::Mode::from_str(spec["mode"].as_str().unwrap_or("xbf"))
+ .ok_or("mode must be 'xbf' or 'zstd'")?;
+ actions::compact::spawn(
+ state,
+ job_id,
+ actions::compact::CompactReq {
+ source_url,
+ mode,
+ raw_path: spec["output"]["path"].as_str().map(str::to_string),
+ },
+ )
+ }
+ other => return Err(format!("unsupported action: {other}")),
+ }
+ Ok(())
+}
+
+/// Drive a spawned job to a terminal state, uploading its outputs to the given
+/// signed URLs via the same finalize path the HTTP poll uses. Shared by the CLI
+/// here and the sync-HTTP path (`?sync`, the Lambda handler in `main::respond`).
+pub async fn run_to_completion(
+ state: &AppState,
+ job_id: &str,
+ urls: &HashMap<String, String>,
+) -> Value {
+ let deadline = Instant::now() + Duration::from_secs(RUN_JOB_MAX_SECS);
+ let step = Duration::from_secs(30);
+ loop {
+ match state.jobs.poll(job_id, urls, Some(step)).await {
+ None => {
+ return json!({ "ok": false,
+ "error": { "code": "not_found", "message": "job vanished" } })
+ }
+ Some(v) => match v["job"]["status"].as_str() {
+ Some("succeeded") | Some("failed") | Some("canceled") => return v,
+ // still running / uploading — keep waiting until the ceiling
+ _ if Instant::now() >= deadline => return v,
+ _ => continue,
+ },
+ }
+ }
+}
+
+pub fn upload_urls(spec: &Value) -> HashMap<String, String> {
+ let mut out = HashMap::new();
+ if let Some(map) = spec["upload_urls"].as_object() {
+ for (name, url) in map {
+ if let Some(u) = url.as_str() {
+ out.insert(name.clone(), u.to_string());
+ }
+ }
+ }
+ out
+}
+
+fn load_spec() -> Result<Value, String> {
+ let raw = std::env::args()
+ .nth(2)
+ .or_else(|| std::env::var("ASSEMBLER_JOB_SPEC").ok())
+ .ok_or("run-job: missing spec (argv[2] or $ASSEMBLER_JOB_SPEC)")?;
+ serde_json::from_str(&raw).map_err(|e| format!("run-job: invalid spec JSON: {e}"))
+}
+
+fn fail(msg: &str) -> ! {
+ eprintln!("run-job error: {msg}");
+ println!(
+ "{}",
+ json!({ "ok": false, "error": { "code": "invalid_input", "message": msg } })
+ );
+ std::process::exit(1);
+}
diff --git a/apps/assembler/sst-env.d.ts b/apps/assembler/sst-env.d.ts
new file mode 100644
index 0000000000..c1b62bdd43
--- /dev/null
+++ b/apps/assembler/sst-env.d.ts
@@ -0,0 +1,13 @@
+/* This file is auto-generated by SST. Do not edit. */
+/* tslint:disable */
+/* eslint-disable */
+/* deno-fmt-ignore-file */
+
+declare module "sst" {
+ export interface Resource {
+ }
+}
+/// <reference path="sst-env.d.ts" />
+
+import "sst"
+export {}
\ No newline at end of file
diff --git a/apps/assembler/sst.config.ts b/apps/assembler/sst.config.ts
new file mode 100644
index 0000000000..5df35ad594
--- /dev/null
+++ b/apps/assembler/sst.config.ts
@@ -0,0 +1,256 @@
+/// <reference path="./.sst/platform/config.d.ts" />
+
+// Assembler service infrastructure (SST v4 Ion / Pulumi-based). ONE shared deployment per
+// environment (commercial + GovCloud/ITAR), NOT per-workspace — point the env at
+// the target account/region and deploy on its own cadence.
+//
+// Two runtimes, ONE image (`carbon/assembler:${IMAGE_TAG}`, same default HTTP
+// entrypoint):
+// A. Lambda (default, $0 idle) — the app runs via the Lambda Web Adapter baked
+// into the Dockerfile (PORT=8000). Create self-invokes an Event-type worker
+// invocation; the auto time-budget gate keeps jobs under the 900s hard cap.
+// B. ECS Fargate Spot service (overflow, DEFAULT-OFF) — the same image as a warm
+// HTTP backend behind an ALB; async submit->poll, no 15-min cap. Enabled only
+// when ASSEMBLER_ECS_ENABLED=true ("don't scale until someone complains").
+//
+// Spec: .ai/specs/2026-07-15-assembler-deployment.md
+//
+// The Lambda + APIGW half is deploy-validated on staging. The ECS half is
+// typechecked against the generated platform types but has never been
+// deployed (gated off by default); fill the `DECISION:` markers and validate
+// on a throwaway stage before first enabling it.
+
+export default $config({
+ app(input) {
+ return {
+ name: "carbon-assembler",
+ home: "aws",
+ // DECISION: commercial vs GovCloud account/region come from the deploy env.
+ region: process.env.AWS_REGION,
+ removal: input?.stage === "prod" ? "retain" : "remove",
+ };
+ },
+ async run() {
+ const account = process.env.AWS_ACCOUNT_ID;
+ const region = process.env.AWS_REGION;
+ const imageTag = process.env.IMAGE_TAG ?? "latest";
+ // Same image for both runtimes (built once by .github/workflows/assembler.yml).
+ const image = `${account}.dkr.ecr.${region}.amazonaws.com/carbon/assembler:${imageTag}`;
+
+ // Shared runtime env (same knobs on Lambda and the ECS service).
+ const environment: Record<string, string | undefined> = {
+ // Bearer key checked in-app on every non-/health route.
+ ASSEMBLER_SERVICE_API_KEY: process.env.ASSEMBLER_SERVICE_API_KEY,
+ // Job/result store — REQUIRED; the assembler refuses to boot without it.
+ REDIS_URL: process.env.REDIS_URL,
+ // Optimize time budget + dispatch mode are AUTO-DETECTED in-service from
+ // AWS_LAMBDA_FUNCTION_NAME (720s ladder budget on Lambda; self-invoke
+ // dispatch) — no env needed here.
+ };
+
+ // ---------------------------------------------------------------------------
+ // Runtime A — Lambda (default, $0 idle)
+ // ---------------------------------------------------------------------------
+ // SST's `sst.aws.Function` has no prebuilt-container-image support, so use the
+ // raw provider (SST v4 Ion is Pulumi-based; raw `aws.*` composes fine).
+ const lambdaRole = new aws.iam.Role("AssemblerLambdaRole", {
+ assumeRolePolicy: JSON.stringify({
+ Version: "2012-10-17",
+ Statement: [
+ {
+ Effect: "Allow",
+ Principal: { Service: "lambda.amazonaws.com" },
+ Action: "sts:AssumeRole",
+ },
+ ],
+ }),
+ });
+ new aws.iam.RolePolicyAttachment("AssemblerLambdaLogs", {
+ role: lambdaRole.name,
+ // CloudWatch logs only — image pull is handled by the Lambda service + the
+ // ECR repo policy; the function makes no other AWS calls (storage I/O is via
+ // caller-provided signed URLs).
+ policyArn:
+ "arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole",
+ });
+
+ const fn = new aws.lambda.Function("Assembler", {
+ packageType: "Image",
+ imageUri: image,
+ role: lambdaRole.arn,
+ // Async job model on Lambda: create returns 202 and fires the compute as
+ // an Event-type SELF-invocation (its own 900s window); polls read the
+ // shared Redis job store. Requires REDIS_URL.
+ // Default 3008 MB: the cap on accounts without a Service Quotas increase,
+ // so a fresh deploy works out of the box. Lambda's platform max is 10240 —
+ // raise via ASSEMBLER_LAMBDA_MEMORY_MB once the quota bump lands (CPU
+ // scales with memory, so bigger = faster on heavy meshes).
+ memorySize: Number(process.env.ASSEMBLER_LAMBDA_MEMORY_MB ?? "3008"),
+ timeout: 900, // 900s hard cap (not raisable) — the time-budget gate keeps jobs under it
+ // /tmp for the source download + temp GLBs — 10 GB is GA on all accounts
+ // (no quota), so keep the max regardless of the memory tier.
+ ephemeralStorage: {
+ size: Number(process.env.ASSEMBLER_LAMBDA_TMP_MB ?? "10240"),
+ },
+ // MUST match the built image's platform. arm64 (Graviton) is cheaper + builds
+ // natively on Apple-Silicon dev machines; x86_64 matches the amd64 CI build.
+ architectures: [process.env.ASSEMBLER_LAMBDA_ARCH ?? "x86_64"],
+ environment: { variables: environment as Record<string, string> },
+ });
+
+ // The create handler invokes this same function (Event type) to run the job.
+ new aws.iam.RolePolicy("AssemblerSelfInvoke", {
+ role: lambdaRole.id,
+ policy: fn.arn.apply((arn) =>
+ JSON.stringify({
+ Version: "2012-10-17",
+ Statement: [
+ { Effect: "Allow", Action: "lambda:InvokeFunction", Resource: arn },
+ ],
+ }),
+ ),
+ });
+
+ // Public front door: API Gateway HTTP API (not a Function URL — those can't
+ // carry a custom domain and this org's guardrail denies their anonymous
+ // invoke; APIGW's service-principal invoke is allowed, TLS is built in, and
+ // a custom domain attaches later via aws.apigatewayv2.DomainName + ACM).
+ // Every request is short (create -> 202, poll ?wait<=25s) so the 30s
+ // integration cap never binds; the compute runs in the self-invoked worker.
+ // Only /health and /v1/* are routed — the /events worker inlet is
+ // unreachable from outside. In-app bearer stays the real auth gate.
+ const api = new aws.apigatewayv2.Api("AssemblerApi", {
+ protocolType: "HTTP",
+ });
+ const integration = new aws.apigatewayv2.Integration(
+ "AssemblerIntegration",
+ {
+ apiId: api.id,
+ integrationType: "AWS_PROXY",
+ integrationUri: fn.invokeArn,
+ payloadFormatVersion: "2.0",
+ },
+ );
+ for (const [name, routeKey] of [
+ ["AssemblerRouteHealth", "GET /health"],
+ ["AssemblerRouteV1", "ANY /v1/{proxy+}"],
+ ] as const) {
+ new aws.apigatewayv2.Route(name, {
+ apiId: api.id,
+ routeKey,
+ target: integration.id.apply((id) => `integrations/${id}`),
+ });
+ }
+ new aws.apigatewayv2.Stage("AssemblerStage", {
+ apiId: api.id,
+ name: "$default",
+ autoDeploy: true,
+ });
+ new aws.lambda.Permission("AssemblerApiInvoke", {
+ function: fn.name,
+ action: "lambda:InvokeFunction",
+ principal: "apigateway.amazonaws.com",
+ sourceArn: api.executionArn.apply((arn) => `${arn}/*/*`),
+ });
+
+ // Custom domain — repo convention: the ACM cert (REGIONAL, same region as
+ // the API) and the DNS record (Cloudflare, proxy OFF) are managed
+ // out-of-band; point a CNAME at the `apiDomainTarget` output. Gated on the
+ // cert: no ASSEMBLER_CERT_ARN => skipped (staging keeps the execute-api URL).
+ const domainName = process.env.ASSEMBLER_DOMAIN ?? "assembler.carbon.ms";
+ const certArn = process.env.ASSEMBLER_CERT_ARN;
+ let apiDomainTarget: $util.Output<string> | undefined;
+ if (certArn) {
+ const domain = new aws.apigatewayv2.DomainName("AssemblerDomain", {
+ domainName,
+ domainNameConfiguration: {
+ certificateArn: certArn,
+ endpointType: "REGIONAL",
+ securityPolicy: "TLS_1_2",
+ },
+ });
+ new aws.apigatewayv2.ApiMapping("AssemblerDomainMapping", {
+ apiId: api.id,
+ domainName: domain.id,
+ stage: "$default",
+ });
+ apiDomainTarget = domain.domainNameConfiguration.targetDomainName;
+ }
+
+ // ---------------------------------------------------------------------------
+ // Runtime B — ECS Fargate Spot service (overflow, DEFAULT-OFF)
+ // ---------------------------------------------------------------------------
+ // Only stood up when ASSEMBLER_ECS_ENABLED=true. Off => $0 standing; overflow
+ // jobs degrade (the app router falls back to poster tier). On => >=1 warm Spot
+ // task; Spot interruptions self-heal via the service scheduler.
+ const ecsEnabled = process.env.ASSEMBLER_ECS_ENABLED === "true";
+ let serviceUrl: string | undefined;
+ if (ecsEnabled) {
+ // Public-subnet VPC, NO NAT — the service only needs egress to storage over
+ // the public internet (signed URLs), which a public subnet + IGW gives for
+ // free. DECISION: reuse the ERP/MES VPC instead if same-account/same-region.
+ // No `nat` arg => no NAT gateway (verified against the platform types);
+ // tasks get public IPs + IGW egress for the signed-URL storage I/O.
+ const vpc = new sst.aws.Vpc("AssemblerVpc");
+ const cluster = new sst.aws.Cluster("AssemblerCluster", { vpc });
+
+ // cluster.addService is deprecated — Service takes the cluster directly.
+ const service = new sst.aws.Service("AssemblerService", {
+ cluster,
+ // Must match the image platform, same as the Lambda architectures arg.
+ architecture:
+ process.env.ASSEMBLER_LAMBDA_ARCH === "arm64" ? "arm64" : "x86_64",
+ cpu: "4 vCPU",
+ memory: "16 GB", // DECISION: the big-job tier; size to the largest expected model
+ image,
+ // Fargate Spot: 50-70% off; interruptions self-heal via the scheduler.
+ capacity: "spot",
+ scaling: {
+ // Default-off is expressed by not deploying the service at all (the
+ // `ecsEnabled` gate); when deployed, hold >=1 warm task.
+ min: Number(process.env.ASSEMBLER_ECS_MIN ?? "1"),
+ max: Number(process.env.ASSEMBLER_ECS_MAX ?? "4"),
+ cpuUtilization: 70,
+ memoryUtilization: 80,
+ },
+ loadBalancer: {
+ domain: {
+ // DECISION: hostname + ACM cert (e.g. assembler-svc.carbon.ms). Internal
+ // vs public+bearer is a decision; public+bearer here to match the Lambda.
+ name:
+ process.env.ASSEMBLER_SERVICE_HOSTNAME ??
+ "assembler-svc.carbon.ms",
+ dns: false,
+ cert: process.env.ASSEMBLER_SERVICE_CERT_ARN,
+ },
+ health: { "8000/http": { path: "/health" } },
+ ports: [
+ { listen: "80/http", forward: "8000/http" },
+ { listen: "443/https", forward: "8000/http" },
+ ],
+ },
+ environment: environment as Record<string, string>,
+ transform: {
+ loadBalancer: { idleTimeout: 600 },
+ target: (args: { healthCheck?: unknown }) => {
+ args.healthCheck = {
+ enabled: true,
+ path: "/health",
+ protocol: "HTTP",
+ };
+ },
+ },
+ });
+ serviceUrl = service.url as unknown as string;
+ }
+
+ // Outputs — wire these into the consumers' env at the human deploy step:
+ // ASSEMBLER_SERVICE_URL <- https://<ASSEMBLER_DOMAIN> when set, else apiUrl
+ // apiDomainTarget <- CNAME target for the out-of-band DNS record
+ return {
+ apiUrl: api.apiEndpoint,
+ apiDomainTarget,
+ serviceUrl,
+ };
+ },
+});
diff --git a/apps/erp/app/components/CadModel.tsx b/apps/erp/app/components/CadModel.tsx
index 704ba81ea6..338cb4184c 100644
--- a/apps/erp/app/components/CadModel.tsx
+++ b/apps/erp/app/components/CadModel.tsx
@@ -12,7 +12,6 @@ import {
ModalHeader,
ModalOverlay,
ModalTitle,
- ModelViewer,
Spinner,
toast,
useDisclosure,
@@ -23,16 +22,131 @@ import {
getFileSizeLimit,
supportedModelTypes
} from "@carbon/utils";
+import { ModelPreview } from "@carbon/viewer/model-preview";
import { nanoid } from "nanoid";
-import { useState } from "react";
+import { useEffect, useId, useRef, useState } from "react";
import { useDropzone } from "react-dropzone";
-import { LuCloudUpload } from "react-icons/lu";
+import { LuCloudUpload, LuZap } from "react-icons/lu";
import { useFetcher, useRevalidator } from "react-router";
-import { useUser } from "~/hooks";
-import { getPrivateUrl, path } from "~/utils/path";
+import { useModelUpload, useUser } from "~/hooks";
+import { getPrivateUrl, getRawModelUrl, path } from "~/utils/path";
+import { ModelUploadProgress } from "./ModelUploadProgress";
const SIZE_LIMIT = getFileSizeLimit("CAD_MODEL_UPLOAD");
+type ModelArtifacts = {
+ optimizedModelPath: string | null;
+ lodPath: string | null;
+ glbPath: string | null;
+ thumbnailPath: string | null;
+ /** Raw upload (non-`.zst`) for the viewer's WASM fallback tier, with its
+ * resolved bucket (temp-staging for current uploads, private for old rows). */
+ rawPath: string | null;
+ rawBucket: string;
+ optimizeStatus:
+ | "Idle"
+ | "Queued"
+ | "Processing"
+ | "Success"
+ | "Failed"
+ | null;
+ /** As-uploaded raw bytes (originalSize; older rows fall back to the stored
+ * size) — the loader resolves this so the reduction badge never compares
+ * against the compacted `.zst`. */
+ size: number | null;
+ /** Optimized GLB bytes — surfaced next to `size` to show the reduction. */
+ optimizedSize: number | null;
+};
+
+/**
+ * modelUpload.id is the model's filename (`${company}/models/${id}.ext`), so the
+ * id — and thus its artifact paths — is recoverable from `modelPath` alone.
+ */
+function modelIdFromPath(modelPath: string | null): string | null {
+ if (!modelPath) return null;
+ let base = modelPath.split("/").pop() ?? "";
+ // Retained raws are compacted in place (`${id}.step` → `${id}.step.zst`); peel
+ // the `.zst` wrapper before the source extension so the id resolves either way.
+ if (base.toLowerCase().endsWith(".zst")) base = base.slice(0, -4);
+ return base.replace(/\.[^.]+$/, "") || null;
+}
+
+/**
+ * Resolves a model's assembler artifact paths (optimised / LOD / assembly GLB /
+ * thumbnail) via the `model.artifacts` API loader — keyed by the id derived from
+ * `modelPath`, so no summary loader has to carry these columns. While optimise is
+ * in flight it polls so the compact GLB swaps into the viewer without a reload;
+ * it stops once an interactive artifact lands, optimise fails, or after a bounded
+ * window (non-mesh uploads stay `Idle` and are only briefly checked).
+ */
+function useModelArtifacts(modelPath: string | null): {
+ artifacts: ModelArtifacts | undefined;
+ /** True while a server GLB might still arrive (fetch unresolved / optimise in
+ * flight). */
+ pending: boolean;
+ /** Restart polling (after a re-optimise is fired) even if it had settled. */
+ retry: () => void;
+} {
+ const uid = useId();
+ const modelUploadId = modelIdFromPath(modelPath);
+ // Scope the fetcher per model id: a delete or swap gives a DIFFERENT fetcher
+ // whose `data` is undefined until its own load resolves — so a previous
+ // model's artifacts can never leak into the new one's viewer (the old model
+ // flashing before the spinner). The `none:<uid>` key keeps model-less
+ // instances from colliding on a shared fetcher.
+ const fetcher = useFetcher<ModelArtifacts>({
+ key: `model-artifacts:${modelUploadId ?? `none:${uid}`}`
+ });
+ const load = fetcher.load;
+ const dataRef = useRef<ModelArtifacts | undefined>(undefined);
+ dataRef.current = fetcher.data;
+ const [pending, setPending] = useState(true);
+ const [reloadKey, setReloadKey] = useState(0);
+
+ // biome-ignore lint/correctness/useExhaustiveDependencies: reloadKey re-runs the effect on retry without being read inside it
+ useEffect(() => {
+ if (!modelUploadId) {
+ setPending(false);
+ return;
+ }
+ setPending(true);
+ const url = path.to.api.modelArtifacts(modelUploadId);
+ load(url);
+
+ let attempts = 0;
+ const timer = setInterval(() => {
+ const data = dataRef.current;
+ const hasInteractive = Boolean(data?.optimizedModelPath || data?.glbPath);
+ if (hasInteractive || data?.optimizeStatus === "Failed") {
+ clearInterval(timer);
+ setPending(false);
+ return;
+ }
+ const inFlight =
+ data?.optimizeStatus === "Queued" ||
+ data?.optimizeStatus === "Processing";
+ // `Idle`/undefined is the brief window before the job starts (or a non-mesh
+ // upload that never optimises) — poll it only for a short grace period.
+ const cap = inFlight ? 60 : 8; // ~3min in flight vs ~24s settling
+ attempts += 1;
+ if (attempts > cap) {
+ clearInterval(timer);
+ setPending(false);
+ return;
+ }
+ load(url);
+ }, 3000);
+
+ return () => clearInterval(timer);
+ }, [modelUploadId, load, reloadKey]);
+
+ return {
+ artifacts: fetcher.data,
+ pending,
+ retry: () => setReloadKey((k) => k + 1)
+ };
+}
+
type CadModelProps = {
modelPath: string | null;
metadata?: {
@@ -63,12 +177,21 @@ const CadModel = ({
const mode = useMode();
const { carbon } = useCarbon();
const revalidator = useRevalidator();
+ const { upload, runUpload } = useModelUpload();
const fetcher = useFetcher<{}>();
const [file, setFile] = useState<File | null>(null);
const [isDeleting, setIsDeleting] = useState(false);
const deleteModal = useDisclosure();
+ const { artifacts, pending, retry } = useModelArtifacts(modelPath);
+ const reoptimizeFetcher = useFetcher<{ success: boolean }>();
+ // A server GLB may still be on its way while a fresh file uploads or the
+ // optimise job runs. There is no in-browser tessellation fallback — the viewer
+ // shows a spinner until the GLB lands, then "preview unavailable" if it never
+ // does (optimise failed / non-mesh).
+ const awaitingModel = pending || Boolean(file);
+
const onDelete = async () => {
if (!carbon) {
toast.error("Failed to initialize carbon client");
@@ -128,6 +251,18 @@ const CadModel = ({
metadata?.jobId
);
+ // Re-fire the optimise for an existing model (raw still in temp-staging) and
+ // restart artifact polling so the GLB swaps in without a reload.
+ const onRetry = () => {
+ const modelUploadId = modelIdFromPath(modelPath);
+ if (isReadOnly || !modelUploadId) return;
+ reoptimizeFetcher.submit(
+ { modelUploadId },
+ { method: "post", action: path.to.api.modelReoptimize }
+ );
+ retry();
+ };
+
const onFileChange = async (file: File | null) => {
const modelId = nanoid();
@@ -137,26 +272,31 @@ const CadModel = ({
if (!carbon) {
toast.error("Failed to initialize carbon client");
return;
- } else {
- toast.info(`Uploading ${file.name}`);
}
const fileExtension = file.name.split(".").pop();
const fileName = `${companyId}/models/${modelId}.${fileExtension}`;
- const modelUpload = await carbon.storage
- .from("private")
- .upload(fileName, file, {
- upsert: true
- });
-
- if (modelUpload.error) {
- toast.error("Failed to upload file to storage");
+ // Raw CAD lands in `temp-staging` (2.5 GB cap) via a resumable (TUS) upload
+ // — a standard buffered upload times out on multi-GB files. The
+ // optimise/assembly jobs read it from there and write the gated artifacts
+ // (<=50 MB) to `private`.
+ const toastId = toast.loading(`Uploading ${file.name}…`);
+ const { error: uploadError } = await runUpload({
+ bucket: "temp-staging",
+ path: fileName,
+ file
+ });
+ if (uploadError) {
+ toast.error("Failed to upload file to storage", { id: toastId });
+ setFile(null);
+ return;
}
+ toast.success(`Uploaded ${file.name}`, { id: toastId });
const formData = new FormData();
formData.append("name", file.name);
formData.append("modelId", modelId);
- formData.append("modelPath", modelUpload.data!.path);
+ formData.append("modelPath", fileName);
formData.append("size", file.size.toString());
if (metadata) {
if (metadata.itemId) {
@@ -194,14 +334,63 @@ const CadModel = ({
{() => {
return file || modelPath ? (
<>
- <ModelViewer
- key={modelPath}
- file={file}
- url={modelPath ? getPrivateUrl(modelPath) : null}
- mode={mode}
- className={viewerClassName}
- onDelete={canDelete ? deleteModal.onOpen : undefined}
- />
+ <div className="relative h-full w-full">
+ <ModelPreview
+ key={modelPath}
+ awaitingModel={awaitingModel}
+ optimizedUrl={
+ artifacts?.optimizedModelPath
+ ? getPrivateUrl(artifacts.optimizedModelPath)
+ : null
+ }
+ glbUrl={
+ artifacts?.glbPath ? getPrivateUrl(artifacts.glbPath) : null
+ }
+ lodUrl={
+ artifacts?.lodPath ? getPrivateUrl(artifacts.lodPath) : null
+ }
+ rawUrl={
+ artifacts?.rawPath
+ ? getRawModelUrl(artifacts.rawBucket, artifacts.rawPath)
+ : null
+ }
+ rawFile={file}
+ thumbnailUrl={
+ artifacts?.thumbnailPath
+ ? getPrivateUrl(artifacts.thumbnailPath)
+ : null
+ }
+ mode={mode}
+ className={viewerClassName}
+ onRetry={!isReadOnly && modelPath ? onRetry : undefined}
+ onDelete={canDelete ? deleteModal.onOpen : undefined}
+ />
+ {upload !== null && (
+ <div className="absolute inset-0 z-30 flex items-center justify-center rounded-lg bg-background/95 p-6">
+ <ModelUploadProgress
+ percent={upload.percent}
+ uploaded={upload.uploaded}
+ total={upload.total}
+ className="max-w-sm"
+ />
+ </div>
+ )}
+ {artifacts?.size && artifacts?.optimizedSize ? (
+ <div className="pointer-events-none absolute bottom-2 left-2 z-10 flex items-center gap-1.5 rounded-md border border-border bg-popover px-2 py-1 text-xs text-muted-foreground shadow-sm">
+ <LuZap className="size-3 shrink-0 text-emerald-500" />
+ <span>Optimized GLB</span>
+ <span className="font-mono tabular-nums">
+ {convertKbToString(Math.round(artifacts.size / 1024))}
+ {" → "}
+ <span className="text-emerald-500">
+ {convertKbToString(
+ Math.round(artifacts.optimizedSize / 1024)
+ )}
+ </span>
+ </span>
+ </div>
+ ) : null}
+ </div>
{deleteModal.isOpen && (
<Modal
open
@@ -317,7 +506,7 @@ const CadModelUpload = ({
<div
{...getRootProps()}
className={cn(
- "group flex flex-col flex-grow rounded-lg border border-border bg-gradient-to-bl from-card from-50% via-card to-background dark:border-none dark:shadow-[inset_0_0.5px_0_rgb(255_255_255_/_0.08),_inset_0_0_1px_rgb(255_255_255_/_0.24),_0_0_0_0.5px_rgb(0,0,0,1),0px_0px_4px_rgba(0,_0,_0,_0.08)] text-card-foreground shadow-sm w-full min-h-[400px] ",
+ "group flex h-full flex-col flex-grow rounded-lg border border-border bg-gradient-to-bl from-card from-50% via-card to-background dark:border-none dark:shadow-[inset_0_0.5px_0_rgb(255_255_255_/_0.08),_inset_0_0_1px_rgb(255_255_255_/_0.24),_0_0_0_0.5px_rgb(0,0,0,1),0px_0px_4px_rgba(0,_0,_0,_0.08)] text-card-foreground shadow-sm w-full min-h-[400px] ",
!hasFile &&
"cursor-pointer hover:border-primary/30 hover:border-dashed hover:to-primary/10 hover:via-card border-2 border-dashed",
className
diff --git a/apps/erp/app/components/Documents.tsx b/apps/erp/app/components/Documents.tsx
index 4d36943be3..cd24951e4d 100644
--- a/apps/erp/app/components/Documents.tsx
+++ b/apps/erp/app/components/Documents.tsx
@@ -21,7 +21,7 @@ import {
Tr,
toast
} from "@carbon/react";
-import { convertKbToString } from "@carbon/utils";
+import { convertKbToString, MODEL_RAW_KEEP_MAX_BYTES } from "@carbon/utils";
import { Trans, useLingui } from "@lingui/react/macro";
import type { ChangeEvent } from "react";
import { useCallback } from "react";
@@ -124,7 +124,7 @@ const Documents = ({
return;
}
- const url = path.to.file.previewFile(`private/${model.modelPath}`);
+ const url = path.to.file.previewFile(`temp-staging/${model.modelPath}`);
try {
const response = await fetch(url);
const blob = await response.blob();
@@ -291,71 +291,72 @@ const Documents = ({
</Tr>
</Thead>
<Tbody>
- {modelUpload?.modelName && (
- <Tr>
- <Td>
- <HStack>
- <LuAxis3D className="text-emerald-500 w-6 h-6" />
- <Hyperlink
- target="_blank"
- to={
- modelUpload.modelId
- ? path.to.file.cadModel(modelUpload.modelId)
- : ""
- }
- >
- {modelUpload.modelName}
- </Hyperlink>
- </HStack>
- </Td>
- <Td className="text-xs font-mono">
- {modelUpload.modelSize
- ? convertKbToString(
- Math.floor((modelUpload.modelSize ?? 0) / 1024)
- )
- : "--"}
- </Td>
- <Td className="text-xs font-mono">--</Td>
- <Td>
- <div className="flex justify-end w-full">
- <DropdownMenu>
- <DropdownMenuTrigger asChild>
- <IconButton
- aria-label={t`More`}
- icon={<LuEllipsisVertical />}
- variant="secondary"
- />
- </DropdownMenuTrigger>
- <DropdownMenuContent>
- <DropdownMenuItem
- onClick={() => downloadModel(modelUpload)}
- >
- <Trans>Download</Trans>
- </DropdownMenuItem>
- <DropdownMenuItem asChild>
- <Link
- to={
- modelUpload.modelId
- ? path.to.file.cadModel(modelUpload.modelId)
- : ""
- }
+ {modelUpload?.modelName &&
+ (modelUpload.modelSize ?? 0) <= MODEL_RAW_KEEP_MAX_BYTES && (
+ <Tr>
+ <Td>
+ <HStack>
+ <LuAxis3D className="text-emerald-500 w-6 h-6" />
+ <Hyperlink
+ target="_blank"
+ to={
+ modelUpload.modelId
+ ? path.to.file.cadModel(modelUpload.modelId)
+ : ""
+ }
+ >
+ {modelUpload.modelName}
+ </Hyperlink>
+ </HStack>
+ </Td>
+ <Td className="text-xs font-mono">
+ {modelUpload.modelSize
+ ? convertKbToString(
+ Math.floor((modelUpload.modelSize ?? 0) / 1024)
+ )
+ : "--"}
+ </Td>
+ <Td className="text-xs font-mono">--</Td>
+ <Td>
+ <div className="flex justify-end w-full">
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <IconButton
+ aria-label={t`More`}
+ icon={<LuEllipsisVertical />}
+ variant="secondary"
+ />
+ </DropdownMenuTrigger>
+ <DropdownMenuContent>
+ <DropdownMenuItem
+ onClick={() => downloadModel(modelUpload)}
>
- <Trans>View</Trans>
- </Link>
- </DropdownMenuItem>
- <DropdownMenuItem
- disabled={!canDelete}
- destructive
- onClick={() => deleteModel()}
- >
- <Trans>Delete</Trans>
- </DropdownMenuItem>
- </DropdownMenuContent>
- </DropdownMenu>
- </div>
- </Td>
- </Tr>
- )}
+ <Trans>Download</Trans>
+ </DropdownMenuItem>
+ <DropdownMenuItem asChild>
+ <Link
+ to={
+ modelUpload.modelId
+ ? path.to.file.cadModel(modelUpload.modelId)
+ : ""
+ }
+ >
+ <Trans>View</Trans>
+ </Link>
+ </DropdownMenuItem>
+ <DropdownMenuItem
+ disabled={!canDelete}
+ destructive
+ onClick={() => deleteModel()}
+ >
+ <Trans>Delete</Trans>
+ </DropdownMenuItem>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ </div>
+ </Td>
+ </Tr>
+ )}
{allFiles.map((file) => {
const type = getDocumentType(file.name);
const isPreviewable = ["PDF", "Image"].includes(type);
diff --git a/apps/erp/app/components/ModelUploadProgress.tsx b/apps/erp/app/components/ModelUploadProgress.tsx
new file mode 100644
index 0000000000..7cb04b8692
--- /dev/null
+++ b/apps/erp/app/components/ModelUploadProgress.tsx
@@ -0,0 +1,50 @@
+import { BarProgress, cn } from "@carbon/react";
+import { LuLoaderCircle } from "react-icons/lu";
+
+function formatBytes(n: number): string {
+ if (n >= 1024 ** 3) return `${(n / 1024 ** 3).toFixed(2)} GB`;
+ if (n >= 1024 ** 2) return `${(n / 1024 ** 2).toFixed(1)} MB`;
+ if (n >= 1024) return `${Math.round(n / 1024)} KB`;
+ return `${n} B`;
+}
+
+export type ModelUploadProgressProps = {
+ percent: number;
+ uploaded: number;
+ total: number;
+ className?: string;
+};
+
+/**
+ * Progress readout for a resumable model upload — the `BarProgress` visual
+ * language shared with assembly-convert / backups. Chrome-less on purpose (no
+ * card border/background) so it drops straight into whatever container is
+ * uploading — the dashed dropzone, or an overlay on the 3D viewer.
+ */
+export function ModelUploadProgress({
+ percent,
+ uploaded,
+ total,
+ className
+}: ModelUploadProgressProps) {
+ return (
+ <div className={cn("flex w-full flex-col gap-2.5", className)}>
+ <BarProgress
+ progress={percent}
+ max={100}
+ label="Uploading model"
+ value={`${Math.round(percent)}%`}
+ activeClassName="bg-primary"
+ />
+ <div className="flex items-center gap-2 text-xs text-muted-foreground">
+ <LuLoaderCircle className="h-3.5 w-3.5 shrink-0 animate-spin text-primary motion-reduce:animate-none" />
+ <span>
+ Uploading the CAD file ·{" "}
+ <span className="tabular-nums">
+ {formatBytes(uploaded)} / {formatBytes(total)}
+ </span>
+ </span>
+ </div>
+ </div>
+ );
+}
diff --git a/apps/erp/app/hooks/index.ts b/apps/erp/app/hooks/index.ts
index e3ea15a404..0c37d70c34 100644
--- a/apps/erp/app/hooks/index.ts
+++ b/apps/erp/app/hooks/index.ts
@@ -11,6 +11,7 @@ import { useDateFormatter } from "./useDateFormatter";
import { useFlags } from "./useFlags";
import { useGooglePlaces } from "./useGooglePlaces";
import { useHighlightFlash } from "./useHighlightFlash";
+import { useModelUpload } from "./useModelUpload";
import { useAllModules, useModules, useSettingsModule } from "./useModules";
import { useMovingCellRef } from "./useMovingCellRef";
import { useNextItemId } from "./useNextItemId";
@@ -37,6 +38,7 @@ export {
useAllModules,
useModules,
useSettingsModule,
+ useModelUpload,
useMovingCellRef,
useNanoStore,
useNextItemId,
diff --git a/apps/erp/app/hooks/useModelUpload.ts b/apps/erp/app/hooks/useModelUpload.ts
new file mode 100644
index 0000000000..31b4c913c5
--- /dev/null
+++ b/apps/erp/app/hooks/useModelUpload.ts
@@ -0,0 +1,52 @@
+import { useCarbon } from "@carbon/auth";
+import { useCallback, useState } from "react";
+import { uploadModelResumable } from "~/utils/resumable-upload";
+
+export type ModelUploadProgress = {
+ percent: number;
+ uploaded: number;
+ total: number;
+};
+
+/**
+ * Shared resumable (TUS) model-upload logic — the single source of truth for
+ * every CAD upload surface (CadModel, PartForm, ToolForm). Owns the progress
+ * state (render it with `<ModelUploadProgress {...upload} />`) and swallows the
+ * upload into a `{ error }` result so callers keep their existing flow.
+ */
+export function useModelUpload() {
+ const { accessToken } = useCarbon();
+ const [upload, setUpload] = useState<ModelUploadProgress | null>(null);
+
+ const runUpload = useCallback(
+ async ({
+ bucket,
+ path,
+ file
+ }: {
+ bucket: string;
+ path: string;
+ file: File;
+ }): Promise<{ error: unknown }> => {
+ setUpload({ percent: 0, uploaded: 0, total: file.size });
+ try {
+ await uploadModelResumable({
+ accessToken,
+ bucket,
+ path,
+ file,
+ onProgress: (percent, uploaded, total) =>
+ setUpload({ percent, uploaded, total })
+ });
+ return { error: null };
+ } catch (error) {
+ return { error };
+ } finally {
+ setUpload(null);
+ }
+ },
+ [accessToken]
+ );
+
+ return { upload, runUpload };
+}
diff --git a/apps/erp/app/modules/items/ui/Item/ItemDocuments.tsx b/apps/erp/app/modules/items/ui/Item/ItemDocuments.tsx
index 0ae125b7af..8017138675 100644
--- a/apps/erp/app/modules/items/ui/Item/ItemDocuments.tsx
+++ b/apps/erp/app/modules/items/ui/Item/ItemDocuments.tsx
@@ -21,7 +21,7 @@ import {
Tr,
toast
} from "@carbon/react";
-import { convertKbToString } from "@carbon/utils";
+import { convertKbToString, MODEL_RAW_KEEP_MAX_BYTES } from "@carbon/utils";
import { Trans, useLingui } from "@lingui/react/macro";
import type { FileObject } from "@supabase/storage-js";
import type { ChangeEvent } from "react";
@@ -128,58 +128,59 @@ const ItemDocuments = ({
</Tr>
</Thead>
<Tbody>
- {modelUpload?.modelId && (
- <Tr>
- <Td>
- <HStack>
- <LuAxis3D className="text-emerald-500 w-6 h-6" />
- <Hyperlink target="_blank" to={getModelPath(modelUpload)}>
- {modelUpload.modelName}
- </Hyperlink>
- </HStack>
- </Td>
- <Td className="text-xs font-mono">
- {modelUpload.modelSize
- ? convertKbToString(
- Math.floor((modelUpload.modelSize ?? 0) / 1024)
- )
- : "--"}
- </Td>
- <Td className="text-xs font-mono">--</Td>
- <Td>
- <div className="flex justify-end w-full">
- <DropdownMenu>
- <DropdownMenuTrigger asChild>
- <IconButton
- aria-label={t`More`}
- icon={<LuEllipsisVertical />}
- variant="secondary"
- />
- </DropdownMenuTrigger>
- <DropdownMenuContent>
- <DropdownMenuItem asChild>
- <Link to={getModelPath(modelUpload)}>
- <Trans>View</Trans>
- </Link>
- </DropdownMenuItem>
- <DropdownMenuItem
- onClick={() => downloadModel(modelUpload)}
- >
- Download
- </DropdownMenuItem>
- <DropdownMenuItem
- destructive
- disabled={isReadOnly || !canDelete}
- onClick={() => deleteModel()}
- >
- Delete
- </DropdownMenuItem>
- </DropdownMenuContent>
- </DropdownMenu>
- </div>
- </Td>
- </Tr>
- )}
+ {modelUpload?.modelId &&
+ (modelUpload.modelSize ?? 0) <= MODEL_RAW_KEEP_MAX_BYTES && (
+ <Tr>
+ <Td>
+ <HStack>
+ <LuAxis3D className="text-emerald-500 w-6 h-6" />
+ <Hyperlink target="_blank" to={getModelPath(modelUpload)}>
+ {modelUpload.modelName}
+ </Hyperlink>
+ </HStack>
+ </Td>
+ <Td className="text-xs font-mono">
+ {modelUpload.modelSize
+ ? convertKbToString(
+ Math.floor((modelUpload.modelSize ?? 0) / 1024)
+ )
+ : "--"}
+ </Td>
+ <Td className="text-xs font-mono">--</Td>
+ <Td>
+ <div className="flex justify-end w-full">
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <IconButton
+ aria-label={t`More`}
+ icon={<LuEllipsisVertical />}
+ variant="secondary"
+ />
+ </DropdownMenuTrigger>
+ <DropdownMenuContent>
+ <DropdownMenuItem asChild>
+ <Link to={getModelPath(modelUpload)}>
+ <Trans>View</Trans>
+ </Link>
+ </DropdownMenuItem>
+ <DropdownMenuItem
+ onClick={() => downloadModel(modelUpload)}
+ >
+ Download
+ </DropdownMenuItem>
+ <DropdownMenuItem
+ destructive
+ disabled={isReadOnly || !canDelete}
+ onClick={() => deleteModel()}
+ >
+ Delete
+ </DropdownMenuItem>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ </div>
+ </Td>
+ </Tr>
+ )}
{allFiles.map((file) => {
const type = getDocumentType(file.name);
return (
@@ -367,7 +368,7 @@ export const useItemDocuments = ({ itemId, type }: Props) => {
return;
}
- const url = path.to.file.previewFile(`private/${model.modelPath}`);
+ const url = path.to.file.previewFile(`temp-staging/${model.modelPath}`);
try {
const response = await fetch(url);
const blob = await response.blob();
diff --git a/apps/erp/app/modules/items/ui/Parts/PartForm.tsx b/apps/erp/app/modules/items/ui/Parts/PartForm.tsx
index d51cffd83c..d3934abc15 100644
--- a/apps/erp/app/modules/items/ui/Parts/PartForm.tsx
+++ b/apps/erp/app/modules/items/ui/Parts/PartForm.tsx
@@ -44,7 +44,13 @@ import {
UnitOfMeasure
} from "~/components/Form";
import { ReplenishmentSystemIcon } from "~/components/Icons";
-import { useNextItemId, usePermissions, useUser } from "~/hooks";
+import { ModelUploadProgress } from "~/components/ModelUploadProgress";
+import {
+ useModelUpload,
+ useNextItemId,
+ usePermissions,
+ useUser
+} from "~/hooks";
import { path } from "~/utils/path";
import {
itemReplenishmentSystems,
@@ -76,6 +82,7 @@ const PartForm = ({ initialValues, type = "card", onClose }: PartFormProps) => {
const [modelIsUploading, setModelIsUploading] = useState(false);
const [modelFile, setModelFile] = useState<File | null>(null);
const { carbon } = useCarbon();
+ const { upload, runUpload } = useModelUpload();
const {
company: { id: companyId }
} = useUser();
@@ -90,8 +97,10 @@ const PartForm = ({ initialValues, type = "card", onClose }: PartFormProps) => {
const fileExtension = file.name.split(".").pop();
const fileName = `${companyId}/models/${modelId}.${fileExtension}`;
- const [fileUpload, recordInsert] = await Promise.all([
- carbon.storage.from("private").upload(fileName, file),
+ // Resumable (TUS) upload — a standard buffered upload times out on multi-GB
+ // CAD files. Runs in parallel with the record insert.
+ const [{ error: uploadError }, recordInsert] = await Promise.all([
+ runUpload({ bucket: "temp-staging", path: fileName, file }),
carbon.from("modelUpload").insert({
id: modelId,
modelPath: fileName,
@@ -102,7 +111,7 @@ const PartForm = ({ initialValues, type = "card", onClose }: PartFormProps) => {
})
]);
- if (fileUpload.error || recordInsert.error) {
+ if (uploadError || recordInsert.error) {
toast.error(t`Failed to upload model`);
} else {
setModelUploadId(modelId);
@@ -368,7 +377,13 @@ const PartForm = ({ initialValues, type = "card", onClose }: PartFormProps) => {
}`}
>
<input id="model-upload" {...getInputProps()} />
- {modelFile ? (
+ {upload !== null ? (
+ <ModelUploadProgress
+ percent={upload.percent}
+ uploaded={upload.uploaded}
+ total={upload.total}
+ />
+ ) : modelFile ? (
<>
<p className="text-sm font-semibold text-card-foreground">
{modelFile.name}
diff --git a/apps/erp/app/modules/items/ui/Tools/ToolForm.tsx b/apps/erp/app/modules/items/ui/Tools/ToolForm.tsx
index 7fe4fda5be..ba09d47c8e 100644
--- a/apps/erp/app/modules/items/ui/Tools/ToolForm.tsx
+++ b/apps/erp/app/modules/items/ui/Tools/ToolForm.tsx
@@ -43,7 +43,13 @@ import {
UnitOfMeasure
} from "~/components/Form";
import { ReplenishmentSystemIcon, TrackingTypeIcon } from "~/components/Icons";
-import { useNextItemId, usePermissions, useUser } from "~/hooks";
+import { ModelUploadProgress } from "~/components/ModelUploadProgress";
+import {
+ useModelUpload,
+ useNextItemId,
+ usePermissions,
+ useUser
+} from "~/hooks";
import { path } from "~/utils/path";
import {
itemReplenishmentSystems,
@@ -75,6 +81,7 @@ const ToolForm = ({ initialValues, type = "card", onClose }: ToolFormProps) => {
const [modelIsUploading, setModelIsUploading] = useState(false);
const [modelFile, setModelFile] = useState<File | null>(null);
const { carbon } = useCarbon();
+ const { upload, runUpload } = useModelUpload();
const {
company: { id: companyId }
} = useUser();
@@ -89,8 +96,10 @@ const ToolForm = ({ initialValues, type = "card", onClose }: ToolFormProps) => {
const fileExtension = file.name.split(".").pop();
const fileName = `${companyId}/models/${modelId}.${fileExtension}`;
- const [fileUpload, recordInsert] = await Promise.all([
- carbon.storage.from("private").upload(fileName, file),
+ // Resumable (TUS) upload — a standard buffered upload times out on multi-GB
+ // CAD files. Runs in parallel with the record insert.
+ const [{ error: uploadError }, recordInsert] = await Promise.all([
+ runUpload({ bucket: "temp-staging", path: fileName, file }),
carbon.from("modelUpload").insert({
id: modelId,
modelPath: fileName,
@@ -101,7 +110,7 @@ const ToolForm = ({ initialValues, type = "card", onClose }: ToolFormProps) => {
})
]);
- if (fileUpload.error || recordInsert.error) {
+ if (uploadError || recordInsert.error) {
toast.error(t`Failed to upload model`);
} else {
setModelUploadId(modelId);
@@ -353,7 +362,13 @@ const ToolForm = ({ initialValues, type = "card", onClose }: ToolFormProps) => {
}`}
>
<input id="model-upload" {...getInputProps()} />
- {modelFile ? (
+ {upload !== null ? (
+ <ModelUploadProgress
+ percent={upload.percent}
+ uploaded={upload.uploaded}
+ total={upload.total}
+ />
+ ) : modelFile ? (
<>
<p className="text-sm font-semibold text-card-foreground">
{modelFile.name}
diff --git a/apps/erp/app/modules/production/production.models.ts b/apps/erp/app/modules/production/production.models.ts
index dfb362af2a..a7f2c96f61 100644
--- a/apps/erp/app/modules/production/production.models.ts
+++ b/apps/erp/app/modules/production/production.models.ts
@@ -1183,9 +1183,12 @@ export function getAssemblyModelState(
) {
return "converted";
}
- const isStep = [".step", ".stp"].some((ext) =>
- (model.modelPath ?? "").toLowerCase().endsWith(ext)
- );
+ // The retained raw is zstd-compacted in place after a successful optimise
+ // (`x.step` -> `x.step.zst`), so peel the `.zst` wrapper before the extension
+ // check — the compacted file is still a valid STEP the converter reads
+ // transparently.
+ const base = (model.modelPath ?? "").toLowerCase().replace(/\.zst$/, "");
+ const isStep = [".step", ".stp"].some((ext) => base.endsWith(ext));
if (!isStep) return "none";
if (
model.processingStatus === "Queued" ||
diff --git a/apps/erp/app/modules/production/production.server.ts b/apps/erp/app/modules/production/production.server.ts
index 2bf99c6642..195e9595fe 100644
--- a/apps/erp/app/modules/production/production.server.ts
+++ b/apps/erp/app/modules/production/production.server.ts
@@ -6,10 +6,17 @@ import { path } from "~/utils/path";
// The geometry (assembler) service backs model conversion and motion planning.
// When it's unreachable those actions can't run, so loaders probe its health and
-// the UI soft-gates the assembler-dependent controls. Result cached briefly so a
+// the UI soft-gates the assembler-dependent controls. Result cached so a
// navigation burst doesn't fan out one probe per route.
-const ASSEMBLER_HEALTH_TTL_MS = 15_000;
-const ASSEMBLER_HEALTH_TIMEOUT_MS = 2_000;
+//
+// The default deployment is a scale-to-zero Lambda: a cold /health takes ~2-5s
+// to init, so the probe timeout must outlast a cold start (the old 2s abort
+// read every cold service as down). Healthy sticks longer than unhealthy —
+// a failed probe usually WARMED the service (the request went through; we just
+// stopped waiting), so re-probe quickly instead of pinning "down" for 15s.
+const ASSEMBLER_HEALTHY_TTL_MS = 60_000;
+const ASSEMBLER_UNHEALTHY_TTL_MS = 5_000;
+const ASSEMBLER_HEALTH_TIMEOUT_MS = 10_000;
let assemblerHealthCache: { healthy: boolean; expires: number } | null = null;
export async function isAssemblerServiceHealthy(): Promise<boolean> {
@@ -40,7 +47,8 @@ export async function isAssemblerServiceHealthy(): Promise<boolean> {
assemblerHealthCache = {
healthy,
- expires: now + ASSEMBLER_HEALTH_TTL_MS
+ expires:
+ now + (healthy ? ASSEMBLER_HEALTHY_TTL_MS : ASSEMBLER_UNHEALTHY_TTL_MS)
};
return healthy;
}
diff --git a/apps/erp/app/modules/production/production.service.ts b/apps/erp/app/modules/production/production.service.ts
index 3ebdb27c70..c76008a4a0 100644
--- a/apps/erp/app/modules/production/production.service.ts
+++ b/apps/erp/app/modules/production/production.service.ts
@@ -4022,7 +4022,7 @@ export async function deleteAssemblyInstruction(
async function notifyAssemblerInvalidate(modelUploadId: string) {
if (!ASSEMBLER_SERVICE_URL) return;
try {
- await fetch(`${ASSEMBLER_SERVICE_URL}/cache/invalidate`, {
+ await fetch(`${ASSEMBLER_SERVICE_URL}/v1/cache/invalidate`, {
method: "POST",
headers: {
"Content-Type": "application/json",
diff --git a/apps/erp/app/modules/production/ui/Jobs/JobDocuments.tsx b/apps/erp/app/modules/production/ui/Jobs/JobDocuments.tsx
index 1956d3cc76..2b438d9c55 100644
--- a/apps/erp/app/modules/production/ui/Jobs/JobDocuments.tsx
+++ b/apps/erp/app/modules/production/ui/Jobs/JobDocuments.tsx
@@ -27,7 +27,7 @@ import {
toast,
VStack
} from "@carbon/react";
-import { convertKbToString } from "@carbon/utils";
+import { convertKbToString, MODEL_RAW_KEEP_MAX_BYTES } from "@carbon/utils";
import { Trans, useLingui } from "@lingui/react/macro";
import type { FileObject } from "@supabase/storage-js";
import type { ChangeEvent } from "react";
@@ -115,7 +115,7 @@ const useJobDocuments = ({
return;
}
- const url = path.to.file.previewFile(`private/${model.modelPath}`);
+ const url = path.to.file.previewFile(`temp-staging/${model.modelPath}`);
try {
const response = await fetch(url);
const blob = await response.blob();
@@ -406,66 +406,67 @@ const JobDocuments = ({
</Tr>
</Thead>
<Tbody>
- {modelUpload?.modelName && (
- <Tr>
- <Td>
- <HStack>
- <DocumentIcon type="Model" />
- <VStack>
- <Hyperlink
- target="_blank"
- to={getModelPath(modelUpload)}
- >
- {modelUpload.modelName}
- </Hyperlink>
- </VStack>
- </HStack>
- </Td>
- <Td>
- {modelUpload.modelSize
- ? convertKbToString(
- Math.floor((modelUpload.modelSize ?? 0) / 1024)
- )
- : "--"}
- </Td>
- <Td>
- <Enumerable value="Job" />
- </Td>
- <Td className="text-xs font-mono">--</Td>
- <Td>
- <div className="flex justify-end w-full">
- <DropdownMenu>
- <DropdownMenuTrigger asChild>
- <IconButton
- aria-label={t`More`}
- icon={<LuEllipsisVertical />}
- variant="secondary"
- />
- </DropdownMenuTrigger>
- <DropdownMenuContent>
- <DropdownMenuItem asChild>
- <Link to={getModelPath(modelUpload)}>
- <Trans>View</Trans>
- </Link>
- </DropdownMenuItem>
- <DropdownMenuItem
- onClick={() => downloadModel(modelUpload)}
- >
- Download
- </DropdownMenuItem>
- <DropdownMenuItem
- destructive
- disabled={!canDelete || isReadOnly}
- onClick={() => deleteModel()}
+ {modelUpload?.modelName &&
+ (modelUpload.modelSize ?? 0) <= MODEL_RAW_KEEP_MAX_BYTES && (
+ <Tr>
+ <Td>
+ <HStack>
+ <DocumentIcon type="Model" />
+ <VStack>
+ <Hyperlink
+ target="_blank"
+ to={getModelPath(modelUpload)}
>
- Delete
- </DropdownMenuItem>
- </DropdownMenuContent>
- </DropdownMenu>
- </div>
- </Td>
- </Tr>
- )}
+ {modelUpload.modelName}
+ </Hyperlink>
+ </VStack>
+ </HStack>
+ </Td>
+ <Td>
+ {modelUpload.modelSize
+ ? convertKbToString(
+ Math.floor((modelUpload.modelSize ?? 0) / 1024)
+ )
+ : "--"}
+ </Td>
+ <Td>
+ <Enumerable value="Job" />
+ </Td>
+ <Td className="text-xs font-mono">--</Td>
+ <Td>
+ <div className="flex justify-end w-full">
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <IconButton
+ aria-label={t`More`}
+ icon={<LuEllipsisVertical />}
+ variant="secondary"
+ />
+ </DropdownMenuTrigger>
+ <DropdownMenuContent>
+ <DropdownMenuItem asChild>
+ <Link to={getModelPath(modelUpload)}>
+ <Trans>View</Trans>
+ </Link>
+ </DropdownMenuItem>
+ <DropdownMenuItem
+ onClick={() => downloadModel(modelUpload)}
+ >
+ Download
+ </DropdownMenuItem>
+ <DropdownMenuItem
+ destructive
+ disabled={!canDelete || isReadOnly}
+ onClick={() => deleteModel()}
+ >
+ Delete
+ </DropdownMenuItem>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ </div>
+ </Td>
+ </Tr>
+ )}
{allFiles.map((file) => {
const type = getDocumentType(file.name);
return (
diff --git a/apps/erp/app/modules/sales/ui/Opportunity/OpportunityLineDocuments.tsx b/apps/erp/app/modules/sales/ui/Opportunity/OpportunityLineDocuments.tsx
index fb5a71c018..462bf17959 100644
--- a/apps/erp/app/modules/sales/ui/Opportunity/OpportunityLineDocuments.tsx
+++ b/apps/erp/app/modules/sales/ui/Opportunity/OpportunityLineDocuments.tsx
@@ -27,7 +27,7 @@ import {
toast,
VStack
} from "@carbon/react";
-import { convertKbToString } from "@carbon/utils";
+import { convertKbToString, MODEL_RAW_KEEP_MAX_BYTES } from "@carbon/utils";
import { Trans, useLingui } from "@lingui/react/macro";
import type { FileObject } from "@supabase/storage-js";
import type { ChangeEvent } from "react";
@@ -163,7 +163,7 @@ const useOpportunityLineDocuments = ({
return;
}
- const url = path.to.file.previewFile(`private/${model.modelPath}`);
+ const url = path.to.file.previewFile(`temp-staging/${model.modelPath}`);
try {
const response = await fetch(url);
const blob = await response.blob();
@@ -476,66 +476,67 @@ const OpportunityLineDocuments = ({
</Tr>
</Thead>
<Tbody>
- {modelUpload?.modelName && (
- <Tr>
- <Td>
- <HStack>
- <DocumentIcon type="Model" />
- <VStack>
- <Hyperlink
- target="_blank"
- to={getModelPath(modelUpload)}
- >
- {modelUpload.modelName}
- </Hyperlink>
- </VStack>
- </HStack>
- </Td>
- <Td>
- {modelUpload.modelSize
- ? convertKbToString(
- Math.floor((modelUpload.modelSize ?? 0) / 1024)
- )
- : "--"}
- </Td>
- <Td>
- <Enumerable value="Model" />
- </Td>
- <Td className="text-xs font-mono">--</Td>
- <Td>
- <div className="flex justify-end w-full">
- <DropdownMenu>
- <DropdownMenuTrigger asChild>
- <IconButton
- aria-label="More"
- icon={<LuEllipsisVertical />}
- variant="secondary"
- />
- </DropdownMenuTrigger>
- <DropdownMenuContent>
- <DropdownMenuItem asChild>
- <Link to={getModelPath(modelUpload)}>
- <Trans>View</Trans>
- </Link>
- </DropdownMenuItem>
- <DropdownMenuItem
- onClick={() => downloadModel(modelUpload)}
- >
- <Trans>Download</Trans>
- </DropdownMenuItem>
- <DropdownMenuItem
- destructive
- disabled={!canDelete}
- onClick={() => deleteModel(lineId)}
+ {modelUpload?.modelName &&
+ (modelUpload.modelSize ?? 0) <= MODEL_RAW_KEEP_MAX_BYTES && (
+ <Tr>
+ <Td>
+ <HStack>
+ <DocumentIcon type="Model" />
+ <VStack>
+ <Hyperlink
+ target="_blank"
+ to={getModelPath(modelUpload)}
>
- <Trans>Delete</Trans>
- </DropdownMenuItem>
- </DropdownMenuContent>
- </DropdownMenu>
- </div>
- </Td>
- </Tr>
- )}
+ {modelUpload.modelName}
+ </Hyperlink>
+ </VStack>
+ </HStack>
+ </Td>
+ <Td>
+ {modelUpload.modelSize
+ ? convertKbToString(
+ Math.floor((modelUpload.modelSize ?? 0) / 1024)
+ )
+ : "--"}
+ </Td>
+ <Td>
+ <Enumerable value="Model" />
+ </Td>
+ <Td className="text-xs font-mono">--</Td>
+ <Td>
+ <div className="flex justify-end w-full">
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <IconButton
+ aria-label="More"
+ icon={<LuEllipsisVertical />}
+ variant="secondary"
+ />
+ </DropdownMenuTrigger>
+ <DropdownMenuContent>
+ <DropdownMenuItem asChild>
+ <Link to={getModelPath(modelUpload)}>
+ <Trans>View</Trans>
+ </Link>
+ </DropdownMenuItem>
+ <DropdownMenuItem
+ onClick={() => downloadModel(modelUpload)}
+ >
+ <Trans>Download</Trans>
+ </DropdownMenuItem>
+ <DropdownMenuItem
+ destructive
+ disabled={!canDelete}
+ onClick={() => deleteModel(lineId)}
+ >
+ <Trans>Delete</Trans>
+ </DropdownMenuItem>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ </div>
+ </Td>
+ </Tr>
+ )}
{allFiles.map((file) => {
const type = getDocumentType(file.name);
return (
diff --git a/apps/erp/app/routes/api+/assembler.callback.ts b/apps/erp/app/routes/api+/assembler.callback.ts
new file mode 100644
index 0000000000..77ebaf9e27
--- /dev/null
+++ b/apps/erp/app/routes/api+/assembler.callback.ts
@@ -0,0 +1,52 @@
+import { createHmac, timingSafeEqual } from "node:crypto";
+import { SESSION_SECRET } from "@carbon/env";
+import { inngest } from "@carbon/lib/inngest";
+import type { ActionFunctionArgs } from "react-router";
+
+// Completion webhook for the assembler: the terminal job envelope lands here
+// and wakes the waiting run via `carbon/assembler-job-done`. Auth is the
+// per-job HMAC token (the caller is the assembler, not a user); duplicate
+// deliveries are inert (waitForEvent consumes the first match).
+
+export function assemblerCallbackToken(jobId: string): string {
+ return createHmac("sha256", SESSION_SECRET ?? "")
+ .update(`assembler-callback:${jobId}`)
+ .digest("hex");
+}
+
+export async function action({ request }: ActionFunctionArgs) {
+ const body = (await request.json().catch(() => null)) as {
+ job?: {
+ id?: string;
+ status?: string;
+ result?: unknown;
+ stats?: unknown;
+ error?: { code?: string; message?: string };
+ };
+ } | null;
+ const job = body?.job;
+ if (!job?.id || !job.status) {
+ throw new Response("Bad request", { status: 400 });
+ }
+
+ const token = new URL(request.url).searchParams.get("token") ?? "";
+ const expected = assemblerCallbackToken(job.id);
+ const a = Buffer.from(token);
+ const b = Buffer.from(expected);
+ if (a.length !== b.length || !timingSafeEqual(a, b)) {
+ throw new Response("Unauthorized", { status: 401 });
+ }
+
+ await inngest.send({
+ name: "carbon/assembler-job-done",
+ data: {
+ jobId: job.id,
+ status: job.status,
+ result: job.result ?? null,
+ stats: job.stats ?? null,
+ error: job.error ?? null
+ }
+ });
+
+ return { ok: true };
+}
diff --git a/apps/erp/app/routes/api+/mcp+/lib/tool-metadata.json b/apps/erp/app/routes/api+/mcp+/lib/tool-metadata.json
index faf5f386af..2f927b3acc 100644
--- a/apps/erp/app/routes/api+/mcp+/lib/tool-metadata.json
+++ b/apps/erp/app/routes/api+/mcp+/lib/tool-metadata.json
@@ -1,5 +1,5 @@
{
- "generated": "2026-07-20T03:25:50.771Z",
+ "generated": "2026-07-20T14:05:37.459Z",
"totalTools": 1374,
"modules": 15,
"tools": [
diff --git a/apps/erp/app/routes/api+/model.artifacts.$modelUploadId.ts b/apps/erp/app/routes/api+/model.artifacts.$modelUploadId.ts
new file mode 100644
index 0000000000..3232466eb8
--- /dev/null
+++ b/apps/erp/app/routes/api+/model.artifacts.$modelUploadId.ts
@@ -0,0 +1,60 @@
+import { requirePermissions } from "@carbon/auth/auth.server";
+import { getCarbonServiceRole } from "@carbon/auth/client.server";
+import type { LoaderFunctionArgs } from "react-router";
+
+// Resolves a model's optimised / preview artifact storage paths for the
+// progressive ModelPreview. CadModel fetches this by modelUploadId (derived from
+// modelPath — modelUpload.id is the model filename), so the tiers don't have to
+// be threaded through every item/line summary loader. Returns only paths (the
+// bytes are still served through the auth-checked /file/preview proxy), scoped to
+// the company. Any employee who can reach the page can resolve them.
+export async function loader({ request, params }: LoaderFunctionArgs) {
+ const { client, companyId } = await requirePermissions(request, {
+ role: "employee"
+ });
+ const { modelUploadId } = params;
+ if (!modelUploadId) throw new Response("Not found", { status: 404 });
+
+ const model = await client
+ .from("modelUpload")
+ .select(
+ "size, originalSize, optimizedSize, optimizedModelPath, glbPath, thumbnailPath, optimizeStatus, modelPath"
+ )
+ .eq("id", modelUploadId)
+ .eq("companyId", companyId)
+ .maybeSingle();
+
+ // Raw-source pointer for the viewer's WASM fallback tier (renders the original
+ // upload when no artifact exists). `.zst`-compacted raws are skipped — they
+ // only exist after a successful optimise, which means an artifact exists too.
+ // Bucket split: current uploads land in `temp-staging`; pre-assembler rows
+ // lived in `private` — probe temp-staging and fall back.
+ let rawPath: string | null = null;
+ let rawBucket = "temp-staging";
+ const modelPath = model.data?.modelPath ?? null;
+ if (modelPath && !modelPath.toLowerCase().endsWith(".zst")) {
+ rawPath = modelPath;
+ const staged = await getCarbonServiceRole()
+ .storage.from("temp-staging")
+ .info(modelPath)
+ .catch(() => ({ data: null, error: true as const }));
+ if (staged.error || !staged.data) rawBucket = "private";
+ }
+
+ return {
+ optimizedModelPath: model.data?.optimizedModelPath ?? null,
+ // lodPath tier is pending (assembler single-draw LOD) — added in a later migration.
+ lodPath: null as string | null,
+ glbPath: model.data?.glbPath ?? null,
+ thumbnailPath: model.data?.thumbnailPath ?? null,
+ rawPath,
+ rawBucket,
+ // Lets the client stop polling once optimisation lands (or fails).
+ optimizeStatus: model.data?.optimizeStatus ?? null,
+ // The reduction badge compares as-uploaded vs optimised bytes. `size` is
+ // the STORED raw (rewritten to the .zst size after compaction), so prefer
+ // the frozen originalSize; older rows fall back to size.
+ size: model.data?.originalSize ?? model.data?.size ?? null,
+ optimizedSize: model.data?.optimizedSize ?? null
+ };
+}
diff --git a/apps/erp/app/routes/api+/model.convert-status.$modelUploadId.ts b/apps/erp/app/routes/api+/model.convert-status.$modelUploadId.ts
index 42404021d8..55a93db310 100644
--- a/apps/erp/app/routes/api+/model.convert-status.$modelUploadId.ts
+++ b/apps/erp/app/routes/api+/model.convert-status.$modelUploadId.ts
@@ -18,22 +18,30 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
const { modelUploadId } = params;
if (!modelUploadId) throw new Response("Not found", { status: 404 });
- const job = await client
- .from("assemblyPlanJob")
- .select("id")
- .eq("modelUploadId", modelUploadId)
- .eq("companyId", companyId)
- .eq("kind", "convert")
- .eq("status", "Processing")
- .order("createdAt", { ascending: false })
- .limit(1)
- .maybeSingle();
+ // A status poll must degrade, never 500: during a convert the assembly page's
+ // realtime revalidation storm can briefly saturate the (shared, in dev)
+ // PostgREST pool, making the query below THROW at the connection level rather
+ // than return `{ error }`. Swallow anything transient → NO_SIGNAL; the next
+ // poll recovers, and the client falls back to its coarse processingStatus.
+ try {
+ const job = await client
+ .from("assemblyPlanJob")
+ .select("id")
+ .eq("modelUploadId", modelUploadId)
+ .eq("companyId", companyId)
+ .eq("kind", "convert")
+ .eq("status", "Processing")
+ .order("createdAt", { ascending: false })
+ .limit(1)
+ .maybeSingle();
- if (!job.data || !ASSEMBLER_SERVICE_URL) return NO_SIGNAL;
+ if (!job.data || !ASSEMBLER_SERVICE_URL) return NO_SIGNAL;
- try {
+ // Live phase comes from the assembler's uniform job endpoint (the assembler
+ // is keyed by the assemblyPlanJob id — see assembly-convert's `jobId`). The
+ // legacy `/convert/status/{id}` path is gone; progress rides on the job.
const response = await fetch(
- `${ASSEMBLER_SERVICE_URL}/convert/status/${job.data.id}`,
+ `${ASSEMBLER_SERVICE_URL}/v1/jobs/${job.data.id}`,
{
headers: ASSEMBLER_SERVICE_API_KEY
? { Authorization: `Bearer ${ASSEMBLER_SERVICE_API_KEY}` }
@@ -43,14 +51,13 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
);
if (!response.ok) return NO_SIGNAL;
const body = (await response.json()) as {
- phase?: string;
- done?: number;
- total?: number;
+ job?: { progress?: { phase?: string; done?: number; total?: number } };
};
+ const progress = body.job?.progress;
return {
- phase: body.phase ?? null,
- done: body.done ?? 0,
- total: body.total ?? 0
+ phase: progress?.phase ?? null,
+ done: progress?.done ?? 0,
+ total: progress?.total ?? 0
};
} catch {
return NO_SIGNAL;
diff --git a/apps/erp/app/routes/api+/model.reoptimize.ts b/apps/erp/app/routes/api+/model.reoptimize.ts
new file mode 100644
index 0000000000..63f2b2ecbb
--- /dev/null
+++ b/apps/erp/app/routes/api+/model.reoptimize.ts
@@ -0,0 +1,33 @@
+import { requirePermissions } from "@carbon/auth/auth.server";
+import { trigger } from "@carbon/jobs";
+import type { ActionFunctionArgs } from "react-router";
+import { data } from "react-router";
+
+// Re-fires the eager optimise for an already-uploaded model — the raw still lives
+// in `temp-staging`, so no re-upload is needed. Backs the viewer's "Retry" action
+// when a model settled with no GLB (optimise failed / was skipped).
+export async function action({ request }: ActionFunctionArgs) {
+ const { client, companyId, userId } = await requirePermissions(request, {
+ update: "parts"
+ });
+
+ const formData = await request.formData();
+ const modelUploadId = formData.get("modelUploadId") as string | null;
+ if (!modelUploadId) {
+ return data({ success: false }, { status: 400 });
+ }
+
+ // Confirm the model belongs to this tenant (RLS-scoped read) before re-firing.
+ const model = await client
+ .from("modelUpload")
+ .select("id")
+ .eq("id", modelUploadId)
+ .eq("companyId", companyId)
+ .maybeSingle();
+ if (model.error || !model.data) {
+ return data({ success: false }, { status: 404 });
+ }
+
+ await trigger("model-optimize", { modelUploadId, companyId, userId });
+ return { success: true };
+}
diff --git a/apps/erp/app/routes/api+/model.upload.ts b/apps/erp/app/routes/api+/model.upload.ts
index ffced0bd1d..6cbbac4bfb 100644
--- a/apps/erp/app/routes/api+/model.upload.ts
+++ b/apps/erp/app/routes/api+/model.upload.ts
@@ -40,6 +40,9 @@ export async function action({ request }: ActionFunctionArgs) {
modelPath,
name,
size,
+ // Frozen as-uploaded bytes: `size` is later overwritten with the compacted
+ // (.zst) stored size, but the viewer's reduction badge compares the original.
+ originalSize: size,
companyId,
createdBy: userId
});
@@ -81,9 +84,16 @@ export async function action({ request }: ActionFunctionArgs) {
modelId
});
- // Conversion to assembly-instruction artifacts (GLB + graph) is lazy:
- // triggered when an assembly instruction is created for this model, not
- // on upload — most uploaded models never become assemblies.
+ // Eager optimisation: the assembler's /v1/optimize turns a mesh model into a
+ // compact optimised GLB. The job derives the format from the stored file and
+ // skips non-mesh inputs, so trigger unconditionally. Independent of the lazy
+ // assembly-convert path — most uploads never become assemblies but should
+ // still be optimised.
+ await trigger("model-optimize", {
+ modelUploadId: modelId,
+ companyId,
+ userId
+ });
return {
success: true
diff --git a/apps/erp/app/routes/file+/model+/$id.tsx b/apps/erp/app/routes/file+/model+/$id.tsx
index bdb454fbbe..4afca24b77 100644
--- a/apps/erp/app/routes/file+/model+/$id.tsx
+++ b/apps/erp/app/routes/file+/model+/$id.tsx
@@ -1,11 +1,11 @@
import { notFound } from "@carbon/auth";
import { getCarbonServiceRole } from "@carbon/auth/client.server";
-import { ModelViewer } from "@carbon/react";
+import { ModelCanvas } from "@carbon/viewer/canvas";
import type { LoaderFunctionArgs } from "react-router";
import { useLoaderData } from "react-router";
import { getPublicModelUrl } from "~/utils/path";
-export async function loader({ request, params }: LoaderFunctionArgs) {
+export async function loader({ params }: LoaderFunctionArgs) {
const client = getCarbonServiceRole();
const { id } = params;
if (!id) throw notFound("id not found");
@@ -22,16 +22,25 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
export default function ModelRoute() {
const { model } = useLoaderData<typeof loader>();
+ // Prefer the compact optimised GLB, fall back to the lossless assembly GLB.
+ // No raw-STEP tessellation path — the assembler produces the GLB.
+ const glbPath = model.optimizedModelPath ?? model.glbPath;
return (
- <div className="w-screen h-screen bg-white p-0 m-0">
- <ModelViewer
- mode="light"
- key={model.modelPath}
- file={null}
- url={getPublicModelUrl(model.modelPath)}
- withProperties={false}
- />
+ <div className="h-screen w-screen bg-white">
+ {glbPath ? (
+ <ModelCanvas
+ key={glbPath}
+ glbUrl={getPublicModelUrl(glbPath)}
+ mode="light"
+ />
+ ) : (
+ <div className="flex h-full w-full items-center justify-center">
+ <p className="text-sm text-muted-foreground">
+ 3D preview unavailable
+ </p>
+ </div>
+ )}
</div>
);
}
diff --git a/apps/erp/app/routes/file+/model+/public.$.tsx b/apps/erp/app/routes/file+/model+/public.$.tsx
index 07bb4fdf61..55989b8adc 100644
--- a/apps/erp/app/routes/file+/model+/public.$.tsx
+++ b/apps/erp/app/routes/file+/model+/public.$.tsx
@@ -7,6 +7,7 @@ import type { LoaderFunctionArgs } from "react-router";
const logger = getLogger("erp", "public");
const supportedFileTypes: Record<string, string> = {
+ glb: "model/gltf-binary",
pdf: "application/pdf",
jpg: "image/jpeg",
jpeg: "image/jpeg",
diff --git a/apps/erp/app/routes/file+/preview+/$bucket.$.tsx b/apps/erp/app/routes/file+/preview+/$bucket.$.tsx
index 38e854d9e8..9d00acfe86 100644
--- a/apps/erp/app/routes/file+/preview+/$bucket.$.tsx
+++ b/apps/erp/app/routes/file+/preview+/$bucket.$.tsx
@@ -51,7 +51,17 @@ export let loader = async ({ request, params }: LoaderFunctionArgs) => {
if (!fileType) {
return new Response(null, { status: 400 });
}
- const contentType = supportedFileTypes[fileType];
+ // Retained CAD raws are stored zstd-compressed (`raw.step.zst`, …) to keep
+ // them from lingering as the fat upload. Decompress on the way out so a
+ // download yields the original, openable file. The content-type + extension
+ // come from the underlying format, not the `.zst` wrapper.
+ const isZst = fileType === "zst";
+ const effectiveType = isZst
+ ? path.slice(0, -4).split(".").pop()?.toLowerCase()
+ : fileType;
+ const contentType = effectiveType
+ ? supportedFileTypes[effectiveType]
+ : undefined;
// Authorize against the companyId as a full path segment (prefix or
// slash-bounded), not a loose substring — `.includes(companyId)` lets
@@ -95,5 +105,21 @@ export let loader = async ({ request, params }: LoaderFunctionArgs) => {
headers.set("Content-Type", contentType);
}
+ if (isZst) {
+ // Stream the storage object through a zstd decompress transform (Node
+ // >=22.15/24) rather than buffering the whole file — the decompressed source
+ // can be large, and this keeps memory flat.
+ const { createZstdDecompress } = await import("node:zlib");
+ const { Readable } = await import("node:stream");
+ const source = Readable.fromWeb(
+ fileData.stream() as import("node:stream/web").ReadableStream
+ );
+ const decompressed = source.pipe(createZstdDecompress());
+ return new Response(
+ Readable.toWeb(decompressed) as unknown as ReadableStream,
+ { status: 200, headers }
+ );
+ }
+
return new Response(fileData, { status: 200, headers });
};
diff --git a/apps/erp/app/routes/x+/assembly+/$id.jobs.cancel.tsx b/apps/erp/app/routes/x+/assembly+/$id.jobs.cancel.tsx
index ca7ff1571d..4c0f1211f4 100644
--- a/apps/erp/app/routes/x+/assembly+/$id.jobs.cancel.tsx
+++ b/apps/erp/app/routes/x+/assembly+/$id.jobs.cancel.tsx
@@ -1,15 +1,17 @@
import { assertIsPost, error, success } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import { flash } from "@carbon/auth/session.server";
+import { ASSEMBLER_SERVICE_API_KEY, ASSEMBLER_SERVICE_URL } from "@carbon/env";
import type { ActionFunctionArgs } from "react-router";
import { data } from "react-router";
/**
- * Cancels a stuck convert or plan job for the instruction's model by failing
- * its Processing rows, so the retry/generate buttons re-enable. This releases
- * the UI state only — an Inngest run that is genuinely still working isn't
- * killed, but a later completion just overwrites the failed marker, which is
- * harmless. The common case is a job orphaned by a geometry-service outage.
+ * Cancels a running/stuck convert or plan job: fails its Processing rows (the
+ * retry/generate buttons re-enable) AND cancels the job on the assembler —
+ * which marks it terminal (the compute result is dropped, never uploaded) and
+ * fires the completion callback, so the waiting Inngest run wakes and fails
+ * fast with a non-retriable "canceled" instead of retrying or later
+ * overwriting these rows with a success.
*/
export async function action({ request, params }: ActionFunctionArgs) {
assertIsPost(request);
@@ -67,6 +69,23 @@ export async function action({ request, params }: ActionFunctionArgs) {
);
}
+ // Best-effort: tell the assembler. Without this the job keeps computing and
+ // its success callback would resurrect the run; with it the store marks the
+ // job canceled (terminal), drops the result, and notifies the waiter.
+ if (ASSEMBLER_SERVICE_URL && cancelled.data.length > 0) {
+ await Promise.allSettled(
+ cancelled.data.map((job) =>
+ fetch(`${ASSEMBLER_SERVICE_URL}/v1/jobs/${job.id}/cancel`, {
+ method: "POST",
+ headers: ASSEMBLER_SERVICE_API_KEY
+ ? { Authorization: `Bearer ${ASSEMBLER_SERVICE_API_KEY}` }
+ : {},
+ signal: AbortSignal.timeout(5000)
+ })
+ )
+ );
+ }
+
if (kind === "convert") {
await client
.from("modelUpload")
diff --git a/apps/erp/app/routes/x+/part+/new.tsx b/apps/erp/app/routes/x+/part+/new.tsx
index a891c68c4c..56f897a37e 100644
--- a/apps/erp/app/routes/x+/part+/new.tsx
+++ b/apps/erp/app/routes/x+/part+/new.tsx
@@ -56,6 +56,11 @@ export async function action({ request }: ActionFunctionArgs) {
companyId,
modelId: validation.data.modelUploadId
});
+ await trigger("model-optimize", {
+ modelUploadId: validation.data.modelUploadId,
+ companyId,
+ userId
+ });
}
const itemId = createPart.data?.id;
diff --git a/apps/erp/app/routes/x+/quote+/$quoteId.drag.tsx b/apps/erp/app/routes/x+/quote+/$quoteId.drag.tsx
index 01d032f715..9d18d82c90 100644
--- a/apps/erp/app/routes/x+/quote+/$quoteId.drag.tsx
+++ b/apps/erp/app/routes/x+/quote+/$quoteId.drag.tsx
@@ -263,22 +263,36 @@ export async function action({ request, params }: ActionFunctionArgs) {
});
}
- // Move the file to the new path
- const move = await client.storage
- .from("private")
- .move(documentPath, newPath);
-
- if (move.error) {
+ // Relocate the raw across buckets: attachments live in `private`, but raw
+ // models must land in `temp-staging` (2.5 GB) for the optimise/assembly jobs
+ // to read (Supabase has no cross-bucket move).
+ const raw = await client.storage.from("private").download(documentPath);
+ if (raw.error) {
throw redirect(
path.to.quote(quoteId),
- await flash(request, error(move.error, "Failed to move file"))
+ await flash(request, error(raw.error, "Failed to read model file"))
);
}
+ const staged = await client.storage
+ .from("temp-staging")
+ .upload(newPath, raw.data, { upsert: true });
+ if (staged.error) {
+ throw redirect(
+ path.to.quote(quoteId),
+ await flash(request, error(staged.error, "Failed to stage model file"))
+ );
+ }
+ await client.storage.from("private").remove([documentPath]);
await trigger("model-thumbnail", {
companyId,
modelId
});
+ await trigger("model-optimize", {
+ modelUploadId: modelId,
+ companyId,
+ userId
+ });
} else {
newPath = `${companyId}/opportunity-line/${targetLineId}/${fileName}`;
// Move the file to the new path
diff --git a/apps/erp/app/routes/x+/sales-rfq+/$rfqId.drag.tsx b/apps/erp/app/routes/x+/sales-rfq+/$rfqId.drag.tsx
index a159c66e31..8ab58e51fb 100644
--- a/apps/erp/app/routes/x+/sales-rfq+/$rfqId.drag.tsx
+++ b/apps/erp/app/routes/x+/sales-rfq+/$rfqId.drag.tsx
@@ -118,22 +118,36 @@ export async function action({ request, params }: ActionFunctionArgs) {
);
}
- // Move the file to the new path
- const move = await client.storage
- .from("private")
- .move(documentPath, newPath);
-
- if (move.error) {
+ // Relocate the raw across buckets: attachments live in `private`, but raw
+ // models must land in `temp-staging` (2.5 GB) for the optimise/assembly jobs
+ // to read (Supabase has no cross-bucket move).
+ const raw = await client.storage.from("private").download(documentPath);
+ if (raw.error) {
throw redirect(
path.to.salesRfqDetails(rfqId),
- await flash(request, error(move.error, "Failed to move file"))
+ await flash(request, error(raw.error, "Failed to read model file"))
);
}
+ const staged = await client.storage
+ .from("temp-staging")
+ .upload(newPath, raw.data, { upsert: true });
+ if (staged.error) {
+ throw redirect(
+ path.to.salesRfqDetails(rfqId),
+ await flash(request, error(staged.error, "Failed to stage model file"))
+ );
+ }
+ await client.storage.from("private").remove([documentPath]);
await trigger("model-thumbnail", {
companyId,
modelId
});
+ await trigger("model-optimize", {
+ modelUploadId: modelId,
+ companyId,
+ userId
+ });
} else {
newPath = `${companyId}/opportunity-line/${targetLineId}/${fileName}`;
// Move the file to the new path
diff --git a/apps/erp/app/utils/path.ts b/apps/erp/app/utils/path.ts
index 7415e4c006..b8285d353a 100644
--- a/apps/erp/app/utils/path.ts
+++ b/apps/erp/app/utils/path.ts
@@ -141,8 +141,11 @@ export const path = {
materialTypes: (substanceId: string, formId: string) =>
generatePath(`${api}/items/types/${substanceId}/${formId}`),
messagingNotify: `${api}/messaging/notify`,
+ modelArtifacts: (modelUploadId: string) =>
+ generatePath(`${api}/model/artifacts/${modelUploadId}`),
modelConvertStatus: (modelUploadId: string) =>
generatePath(`${api}/model/convert-status/${modelUploadId}`),
+ modelReoptimize: `${api}/model/reoptimize`,
modelUpload: `${api}/model/upload`,
mrp: (locationId?: string) =>
generatePath(
@@ -2119,6 +2122,13 @@ export const getPrivateUrl = (path: string) => {
return `/file/preview/private/${path}`;
};
+/** Raw model source for the viewer's WASM fallback tier — bucket varies by era
+ * (current uploads: temp-staging; pre-assembler rows: private), resolved by the
+ * model.artifacts loader. */
+export const getRawModelUrl = (bucket: string, path: string) => {
+ return `/file/preview/${bucket}/${path}`;
+};
+
export const getPublicModelUrl = (path: string) => {
return `/file/model/public/${path}`;
};
diff --git a/apps/erp/app/utils/resumable-upload.ts b/apps/erp/app/utils/resumable-upload.ts
new file mode 100644
index 0000000000..0ce79659e0
--- /dev/null
+++ b/apps/erp/app/utils/resumable-upload.ts
@@ -0,0 +1,121 @@
+import { SUPABASE_ANON_KEY, SUPABASE_URL } from "@carbon/auth";
+import * as tus from "tus-js-client";
+
+// Supabase resumable (TUS) uploads. A standard `.upload()` buffers the whole
+// file into ONE multipart request; a multi-GB CAD model then times out at the
+// dev `.dev` proxy (it waits for storage to respond, but storage only responds
+// once the entire body has arrived). TUS streams the file in fixed chunks, so
+// the gateways never see a multi-GB body and the upload is resumable on failure.
+//
+// Supabase requires the chunk size to be EXACTLY 6 MB (except the final chunk).
+const CHUNK_SIZE = 6 * 1024 * 1024;
+
+// The TUS create (POST) returns a `Location` for subsequent PATCH/HEAD requests.
+// Behind the dev proxy chain (portless → kong → storage), kong overwrites
+// `X-Forwarded-Host` with its own internal address, so storage builds that
+// Location against `http://127.0.0.1:8000` (unreachable from the browser) and
+// drops the `/storage/v1` route prefix. Rewrite any non-public-origin request URL
+// back onto the public Supabase origin so the chunks route correctly.
+const PUBLIC_ORIGIN = (() => {
+ try {
+ return new URL(SUPABASE_URL ?? "").origin;
+ } catch {
+ return "";
+ }
+})();
+
+function rewriteToPublicOrigin(url: string): string {
+ if (!PUBLIC_ORIGIN) return url;
+ try {
+ const parsed = new URL(url, PUBLIC_ORIGIN);
+ if (parsed.origin === PUBLIC_ORIGIN) return url;
+ const pathname = parsed.pathname.startsWith("/storage/v1")
+ ? parsed.pathname
+ : `/storage/v1${parsed.pathname}`;
+ return `${PUBLIC_ORIGIN}${pathname}${parsed.search}`;
+ } catch {
+ return url;
+ }
+}
+
+/**
+ * Wraps tus-js-client's default HTTP stack, rewriting every request URL through
+ * `rewriteToPublicOrigin` before the request is built — so a `Location` the
+ * proxy mangled to an internal host is corrected on the PATCH/HEAD.
+ */
+class PublicOriginHttpStack implements tus.HttpStack {
+ constructor(private readonly inner: tus.HttpStack) {}
+
+ createRequest(method: string, url: string): tus.HttpRequest {
+ return this.inner.createRequest(method, rewriteToPublicOrigin(url));
+ }
+
+ getName(): string {
+ return "PublicOriginHttpStack";
+ }
+}
+
+export type ResumableUploadOptions = {
+ /** The signed-in user's Supabase access token (from `useCarbon()`). */
+ accessToken: string;
+ bucket: string;
+ /** Object key within the bucket, e.g. `${companyId}/models/${id}.step`. */
+ path: string;
+ file: File;
+ /** Overwrite an existing object at `path` (default true). */
+ upsert?: boolean;
+ onProgress?: (
+ percent: number,
+ bytesUploaded: number,
+ bytesTotal: number
+ ) => void;
+};
+
+/** Upload a file to Supabase Storage via the resumable (TUS) protocol. */
+export function uploadModelResumable({
+ accessToken,
+ bucket,
+ path,
+ file,
+ upsert = true,
+ onProgress
+}: ResumableUploadOptions): Promise<void> {
+ return new Promise((resolve, reject) => {
+ const upload = new tus.Upload(file, {
+ endpoint: `${SUPABASE_URL}/storage/v1/upload/resumable`,
+ httpStack: new PublicOriginHttpStack(new tus.DefaultHttpStack({})),
+ retryDelays: [0, 3000, 5000, 10000, 20000],
+ headers: {
+ authorization: `Bearer ${accessToken}`,
+ apikey: SUPABASE_ANON_KEY ?? "",
+ "x-upsert": upsert ? "true" : "false"
+ },
+ uploadDataDuringCreation: true,
+ removeFingerprintOnSuccess: true,
+ chunkSize: CHUNK_SIZE,
+ metadata: {
+ bucketName: bucket,
+ objectName: path,
+ contentType: file.type || "application/octet-stream",
+ cacheControl: "3600"
+ },
+ onError: reject,
+ onProgress: (bytesUploaded, bytesTotal) => {
+ onProgress?.(
+ bytesTotal ? (bytesUploaded / bytesTotal) * 100 : 0,
+ bytesUploaded,
+ bytesTotal
+ );
+ },
+ onSuccess: () => resolve()
+ });
+
+ // Resume a previously-interrupted upload of the same file if one is pending.
+ upload.findPreviousUploads().then((previous) => {
+ if (previous.length > 0) {
+ upload.resumeFromPreviousUpload(previous[0]);
+ }
+ upload.start();
+ });
+ });
+}
diff --git a/apps/erp/package.json b/apps/erp/package.json
index 1d0d6df767..94b5f8d5d9 100644
--- a/apps/erp/package.json
+++ b/apps/erp/package.json
@@ -129,6 +129,7 @@
"tar-stream": "^3.2.0",
"tiny-invariant": "1.3.3",
"tsup": "catalog:",
+ "tus-js-client": "4.3.1",
"unified": "11.0.5",
"unist-util-visit": "5.1.0",
"use-stick-to-bottom": "1.1.3",
diff --git a/apps/mes/app/components/JobOperation/JobOperation.tsx b/apps/mes/app/components/JobOperation/JobOperation.tsx
index c14351dd44..ff04abd148 100644
--- a/apps/mes/app/components/JobOperation/JobOperation.tsx
+++ b/apps/mes/app/components/JobOperation/JobOperation.tsx
@@ -25,7 +25,6 @@ import {
Heading,
HStack,
IconButton,
- ModelViewer,
ScrollArea,
Separator,
SidebarTrigger,
@@ -56,6 +55,7 @@ import {
formatDurationMilliseconds,
getItemReadableId
} from "@carbon/utils";
+import { ModelCanvas } from "@carbon/viewer/canvas";
import { Trans, useLingui } from "@lingui/react/macro";
import type { PostgrestSingleResponse } from "@supabase/supabase-js";
import { Suspense, useEffect, useMemo, useState } from "react";
@@ -143,6 +143,21 @@ import { useOperation } from "./hooks/useOperation";
const log = getLogger("mes", "job-operation");
+// The new pipeline serves an optimised GLB per model (no client-side
+// tessellation). Derive its private preview URL from the raw modelPath
+// `${co}/models/${id}.ext[.zst]` → `${co}/models/${id}/optimized.glb`.
+function optimizedModelPreviewUrl(rawModelPath: string | null): string | null {
+ if (!rawModelPath) return null;
+ const slash = rawModelPath.lastIndexOf("/");
+ if (slash < 0) return null;
+ const dir = rawModelPath.slice(0, slash);
+ let base = rawModelPath.slice(slash + 1);
+ if (base.toLowerCase().endsWith(".zst")) base = base.slice(0, -4);
+ const id = base.replace(/\.[^.]+$/, "");
+ if (!id) return null;
+ return `/file/preview/private/${dir}/${id}/optimized.glb`;
+}
+
type JobOperationProps = {
events: ProductionEvent[];
expiredEntityPolicy?: "Warn" | "Block" | "BlockWithOverride";
@@ -1749,15 +1764,25 @@ export const JobOperation = ({
</TabsContent>
<TabsContent value="model">
<div className="w-full h-[calc(100dvh-var(--header-height)*2)] p-0">
- <ModelViewer
- file={null}
- key={`model-${operation.itemModelPath ?? job.modelPath}`}
- url={`/file/preview/private/${
+ {(() => {
+ const glbUrl = optimizedModelPreviewUrl(
operation.itemModelPath ?? job.modelPath
- }`}
- mode={mode}
- className="rounded-none"
- />
+ );
+ return glbUrl ? (
+ <ModelCanvas
+ key={glbUrl}
+ glbUrl={glbUrl}
+ mode={mode}
+ className="rounded-none"
+ />
+ ) : (
+ <div className="flex h-full w-full items-center justify-center">
+ <p className="text-sm text-muted-foreground">
+ 3D preview unavailable
+ </p>
+ </div>
+ );
+ })()}
</div>
</TabsContent>
<TabsContent value="procedure" className="flex flex-grow">
diff --git a/crates/converter/examples/conc_convert.rs b/crates/converter/examples/conc_convert.rs
index c716798606..35a968b1d5 100644
--- a/crates/converter/examples/conc_convert.rs
+++ b/crates/converter/examples/conc_convert.rs
@@ -20,7 +20,12 @@ fn hash_output(step_path: &str, text: &str) -> String {
format!("{:x}", h.finalize())
}
-fn run(path: &Arc<String>, text: &Arc<String>, threads: usize, iters: usize) -> (f64, HashSet<String>) {
+fn run(
+ path: &Arc<String>,
+ text: &Arc<String>,
+ threads: usize,
+ iters: usize,
+) -> (f64, HashSet<String>) {
let hashes = Arc::new(Mutex::new(HashSet::new()));
let start = Instant::now();
let mut handles = Vec::new();
@@ -44,10 +49,16 @@ fn run(path: &Arc<String>, text: &Arc<String>, threads: usize, iters: usize) ->
fn main() {
let args: Vec<String> = std::env::args().collect();
- let path = Arc::new(args.get(1).cloned().expect("usage: conc_convert <file.step> [iters]"));
+ let path = Arc::new(
+ args.get(1)
+ .cloned()
+ .expect("usage: conc_convert <file.step> [iters]"),
+ );
let iters: usize = args.get(2).and_then(|s| s.parse().ok()).unwrap_or(20);
let text = Arc::new(std::fs::read_to_string(path.as_str()).expect("read step"));
- let cores = std::thread::available_parallelism().map(|n| n.get()).unwrap_or(8);
+ let cores = std::thread::available_parallelism()
+ .map(|n| n.get())
+ .unwrap_or(8);
// Establish the golden hash single-threaded.
let golden = hash_output(path.as_str(), text.as_str());
diff --git a/crates/converter/src/convert.rs b/crates/converter/src/convert.rs
index 490f12d81d..33c120b1ee 100644
--- a/crates/converter/src/convert.rs
+++ b/crates/converter/src/convert.rs
@@ -79,14 +79,39 @@ fn to_node(tree: &occt_bridge::Tree, index: u64) -> AssemblyNode {
}
}
-/// Read a STEP file into the assembly tree with nodeIds + world bboxes assigned,
-/// without emitting graph.json or GLB. Shared by `convert_step` and the planner.
+/// OCCT BinXCAF (`.xbf`) files start with the ASCII `BINFILE` magic. Content
+/// sniff (not extension): transparent zstd means a `.step`-named temp can hold
+/// xbf bytes, so the loader must be chosen by what's actually on disk.
+fn is_xbf(path: &str) -> bool {
+ use std::io::Read;
+ let mut head = [0u8; 7];
+ std::fs::File::open(path)
+ .and_then(|mut f| f.read_exact(&mut head))
+ .map(|_| &head == b"BINFILE")
+ .unwrap_or(false)
+}
+
+/// Read a CAD file (STEP or BinXCAF `.xbf`, auto-detected) into the assembly tree
+/// with nodeIds + world bboxes assigned, without emitting graph.json or GLB.
+/// Shared by `convert_step` / `convert_xbf` and the planner. Both loaders share
+/// the same OCCT tessellation walk, so a STEP and the `.xbf` derived from it
+/// yield identical nodeIds + geometry.
pub fn build_tree(
- step_path: &str,
+ path: &str,
linear_deflection: f64,
angular_deflection: f64,
) -> Result<AssemblyNode, ConvertError> {
- let tree = occt_bridge::read_step(step_path, linear_deflection, angular_deflection);
+ let tree = if is_xbf(path) {
+ occt_bridge::read_xbf(path, linear_deflection, angular_deflection)
+ } else {
+ occt_bridge::read_step(path, linear_deflection, angular_deflection)
+ };
+ tree_to_root(tree)
+}
+
+/// Shared post-processing for every OCCT reader: raw `Tree` → node tree with
+/// nodeIds + world bboxes. Keeps STEP/XBF/IGES/BREP byte-identical downstream.
+fn tree_to_root(tree: occt_bridge::Tree) -> Result<AssemblyNode, ConvertError> {
if !tree.ok {
return Err(ConvertError::new("READ_FAILED", tree.error.clone()));
}
@@ -96,6 +121,84 @@ pub fn build_tree(
Ok(root)
}
+/// Write a STEP file as a compact lossless BinXCAF (`.xbf`) document — the
+/// retained-raw form that replaces fat ASCII STEP in storage.
+pub fn step_to_xbf(step_path: &str, xbf_path: &str) -> Result<(), ConvertError> {
+ if !occt_bridge::step_to_xbf(step_path, xbf_path) {
+ return Err(ConvertError::new(
+ "READ_FAILED",
+ "could not write XBF from STEP",
+ ));
+ }
+ Ok(())
+}
+
+/// Convert an IGES file to graph.json + GLB. OCCT's XDE reader normalizes to mm
+/// (same `xstep.cascade.unit` static as STEP), so `sourceUnit` is `mm`.
+pub fn convert_iges(
+ iges_path: &str,
+ linear_deflection: f64,
+ angular_deflection: f64,
+) -> Result<Conversion, ConvertError> {
+ let root = tree_to_root(occt_bridge::read_iges(
+ iges_path,
+ linear_deflection,
+ angular_deflection,
+ ))?;
+ finish_conversion(root, "mm")
+}
+
+/// Convert a bare `.brep` shape file to graph.json + GLB. BREP carries no units
+/// (values are model-space, conventionally mm) and no structure/names/colors.
+pub fn convert_brep(
+ brep_path: &str,
+ linear_deflection: f64,
+ angular_deflection: f64,
+) -> Result<Conversion, ConvertError> {
+ let root = tree_to_root(occt_bridge::read_brep(
+ brep_path,
+ linear_deflection,
+ angular_deflection,
+ ))?;
+ finish_conversion(root, "mm")
+}
+
+fn finish_conversion(root: AssemblyNode, source_unit: &str) -> Result<Conversion, ConvertError> {
+ let component_count = count_leaves(&root);
+ let triangles = count_triangles(&root);
+ let graph = build_graph(&root, source_unit);
+ let glb = crate::glb::write_glb(&root);
+ Ok(Conversion {
+ graph,
+ glb,
+ root,
+ component_count,
+ triangles,
+ })
+}
+
+/// Convert a BinXCAF (`.xbf`) document to graph.json + GLB. Geometry is already
+/// mm (OCCT normalized units when the STEP was read into the xbf), so `sourceUnit`
+/// is reported as `mm` — there is no STEP header to re-detect from.
+pub fn convert_xbf(
+ xbf_path: &str,
+ linear_deflection: f64,
+ angular_deflection: f64,
+) -> Result<Conversion, ConvertError> {
+ let root = build_tree(xbf_path, linear_deflection, angular_deflection)?;
+ let component_count = count_leaves(&root);
+ let triangles = count_triangles(&root);
+ let graph = build_graph(&root, "mm");
+ let glb = crate::glb::write_glb(&root);
+ Ok(Conversion {
+ graph,
+ glb,
+ root,
+ component_count,
+ triangles,
+ })
+}
+
pub fn convert_step(
step_path: &str,
step_text: &str,
diff --git a/crates/converter/src/glb.rs b/crates/converter/src/glb.rs
index a36b34d77d..d651e68d5b 100644
--- a/crates/converter/src/glb.rs
+++ b/crates/converter/src/glb.rs
@@ -60,7 +60,9 @@ impl Builder {
}
fn material(&mut self, color: Option<[f64; 4]>) -> usize {
- let rgba = color.map_or(DEFAULT_COLOR, |c| [c[0] as f32, c[1] as f32, c[2] as f32, c[3] as f32]);
+ let rgba = color.map_or(DEFAULT_COLOR, |c| {
+ [c[0] as f32, c[1] as f32, c[2] as f32, c[3] as f32]
+ });
let key = format!("{:?}", rgba);
if let Some(&i) = self.material_by_color.get(&key) {
return i;
@@ -119,7 +121,8 @@ impl Builder {
let pos_view = self.append_buffer_view(&pos_bytes, json::buffer::Target::ArrayBuffer);
let nrm_view = self.append_buffer_view(&nrm_bytes, json::buffer::Target::ArrayBuffer);
- let idx_view = self.append_buffer_view(&idx_bytes, json::buffer::Target::ElementArrayBuffer);
+ let idx_view =
+ self.append_buffer_view(&idx_bytes, json::buffer::Target::ElementArrayBuffer);
self.accessors.push(json::Accessor {
buffer_view: Some(json::Index::new(pos_view as u32)),
@@ -213,14 +216,16 @@ impl Builder {
} else {
None
};
- let mesh = node.mesh.as_ref().filter(|m| !m.positions.is_empty()).map(|m| {
- let i = self.mesh(m, node.color, &node.product_name);
- json::Index::new(i as u32)
- });
- let extras = serde_json::value::to_raw_value(
- &serde_json::json!({ "nodeId": node.node_id }),
- )
- .ok();
+ let mesh = node
+ .mesh
+ .as_ref()
+ .filter(|m| !m.positions.is_empty())
+ .map(|m| {
+ let i = self.mesh(m, node.color, &node.product_name);
+ json::Index::new(i as u32)
+ });
+ let extras =
+ serde_json::value::to_raw_value(&serde_json::json!({ "nodeId": node.node_id })).ok();
self.nodes.push(json::Node {
name: Some(node.name.clone()),
diff --git a/crates/converter/tests/multibody_split.rs b/crates/converter/tests/multibody_split.rs
index 5f9323b2be..e287b9f292 100644
--- a/crates/converter/tests/multibody_split.rs
+++ b/crates/converter/tests/multibody_split.rs
@@ -40,7 +40,10 @@ fn splits_a_flat_two_solid_product_into_two_components() {
assert_eq!(parts.len(), 2);
// Distinct identity per solid
- let ids: Vec<&str> = parts.iter().map(|p| p["nodeId"].as_str().unwrap()).collect();
+ let ids: Vec<&str> = parts
+ .iter()
+ .map(|p| p["nodeId"].as_str().unwrap())
+ .collect();
assert_ne!(ids[0], ids[1], "solids must get distinct nodeIds");
let hashes: Vec<&str> = parts
.iter()
diff --git a/crates/converter/tests/xbf_parity.rs b/crates/converter/tests/xbf_parity.rs
new file mode 100644
index 0000000000..a971bf6662
--- /dev/null
+++ b/crates/converter/tests/xbf_parity.rs
@@ -0,0 +1,73 @@
+//! STEP → BinXCAF (`.xbf`) → build_tree must yield the SAME assembly tree as
+//! STEP → build_tree: identical nodeIds, geometry hashes, volumes, and
+//! component count. The xbf is the compacted retained-raw form; if it drifted
+//! from the STEP, lazy planning off the xbf would produce different components
+//! than the original. Hermetic: fixtures generated by the occt bridge.
+
+use converter::convert::{build_tree, convert_xbf, step_to_xbf};
+use converter::graph::AssemblyNode;
+use serde_json::Value;
+
+fn fixture_paths(boxes: u32) -> (String, String) {
+ let dir = std::env::temp_dir().join(format!("carbon-xbf-parity-{boxes}"));
+ std::fs::create_dir_all(&dir).unwrap();
+ let step = dir.join("fixture.step");
+ let xbf = dir.join("fixture.xbf");
+ let step_str = step.to_str().unwrap().to_string();
+ assert!(
+ occt_bridge::write_test_step(&step_str, boxes),
+ "failed to write test STEP"
+ );
+ assert!(
+ step_to_xbf(&step_str, xbf.to_str().unwrap()).is_ok(),
+ "step_to_xbf"
+ );
+ (step_str, xbf.to_str().unwrap().to_string())
+}
+
+fn flatten<'a>(node: &'a AssemblyNode, out: &mut Vec<&'a AssemblyNode>) {
+ out.push(node);
+ for c in &node.children {
+ flatten(c, out);
+ }
+}
+
+#[test]
+fn xbf_tree_matches_step_tree() {
+ let (step, xbf) = fixture_paths(3);
+
+ let from_step = build_tree(&step, 0.1, 0.5).expect("build_tree step");
+ let from_xbf = build_tree(&xbf, 0.1, 0.5).expect("build_tree xbf");
+
+ let (mut a, mut b) = (Vec::new(), Vec::new());
+ flatten(&from_step, &mut a);
+ flatten(&from_xbf, &mut b);
+
+ assert_eq!(a.len(), b.len(), "node count must match");
+ for (x, y) in a.iter().zip(b.iter()) {
+ assert_eq!(x.node_id, y.node_id, "nodeId parity");
+ assert_eq!(x.is_assembly, y.is_assembly, "assembly flag parity");
+ assert_eq!(
+ x.mesh.as_ref().map(|m| m.geometry_hash.as_str()),
+ y.mesh.as_ref().map(|m| m.geometry_hash.as_str()),
+ "geometryHash parity"
+ );
+ assert_eq!(x.volume, y.volume, "volume parity");
+ }
+}
+
+#[test]
+fn convert_xbf_reports_mm_and_same_component_count() {
+ let (step, xbf) = fixture_paths(2);
+ let step_graph = {
+ let text = std::fs::read_to_string(&step).unwrap();
+ converter::convert::convert_step(&step, &text, 0.1, 0.5)
+ .unwrap()
+ .graph
+ };
+ let conv = convert_xbf(&xbf, 0.1, 0.5).expect("convert_xbf");
+ assert_eq!(conv.component_count, 2);
+ assert_eq!(conv.graph["componentCount"], step_graph["componentCount"]);
+ // Geometry is OCCT-normalized to mm inside the xbf; no STEP header to detect.
+ assert_eq!(conv.graph["sourceUnit"], Value::String("mm".into()));
+}
diff --git a/crates/draco-bridge/Cargo.toml b/crates/draco-bridge/Cargo.toml
new file mode 100644
index 0000000000..c9db40c6f5
--- /dev/null
+++ b/crates/draco-bridge/Cargo.toml
@@ -0,0 +1,15 @@
+[package]
+name = "draco-bridge"
+version.workspace = true
+edition.workspace = true
+license.workspace = true
+
+# Rust bridge over C++ Google Draco (KHR_draco_mesh_compression encoding).
+# build.rs resolves draco via `DRACO_PREFIX` env or the Homebrew/distro layout;
+# links the static libdraco.a when present (self-contained binary), else dynamic.
+
+[dependencies]
+cxx = "1"
+
+[build-dependencies]
+cxx-build = "1"
diff --git a/crates/draco-bridge/build.rs b/crates/draco-bridge/build.rs
new file mode 100644
index 0000000000..450659bbc2
--- /dev/null
+++ b/crates/draco-bridge/build.rs
@@ -0,0 +1,44 @@
+/// Resolve the draco install prefix: `DRACO_PREFIX` env when set, else the
+/// per-target default (Homebrew `opt` on macOS, distro `/usr` on Linux). The
+/// Dockerfile builds static draco and sets `DRACO_PREFIX` explicitly.
+fn prefix() -> String {
+ if let Ok(p) = std::env::var("DRACO_PREFIX") {
+ if !p.is_empty() {
+ return p;
+ }
+ }
+ let os = std::env::var("CARGO_CFG_TARGET_OS").unwrap_or_default();
+ let arch = std::env::var("CARGO_CFG_TARGET_ARCH").unwrap_or_default();
+ match os.as_str() {
+ "macos" if arch == "aarch64" => "/opt/homebrew/opt/draco".to_string(),
+ "macos" => "/usr/local/opt/draco".to_string(),
+ _ => "/usr".to_string(),
+ }
+}
+
+fn main() {
+ let draco = prefix();
+
+ let mut build = cxx_build::bridge("src/lib.rs");
+ build
+ .file("src/shim.cc")
+ .std("c++17")
+ .include(format!("{draco}/include"))
+ .warnings(false);
+ build.compile("carbon_draco_shim");
+
+ println!("cargo:rustc-link-search=native={draco}/lib");
+ println!("cargo:rustc-link-search=native={draco}/lib/x86_64-linux-gnu");
+ // Static libdraco.a when the prefix ships one (deployment build → a
+ // self-contained binary with no draco runtime .so); else dynamic (brew dev).
+ let static_archive = ["lib", "lib/x86_64-linux-gnu"]
+ .iter()
+ .any(|sub| std::path::Path::new(&format!("{draco}/{sub}/libdraco.a")).exists());
+ let kind = if static_archive { "static" } else { "dylib" };
+ println!("cargo:rustc-link-lib={kind}=draco");
+
+ println!("cargo:rerun-if-changed=src/lib.rs");
+ println!("cargo:rerun-if-changed=src/shim.cc");
+ println!("cargo:rerun-if-changed=src/shim.h");
+ println!("cargo:rerun-if-env-changed=DRACO_PREFIX");
+}
diff --git a/crates/draco-bridge/src/lib.rs b/crates/draco-bridge/src/lib.rs
new file mode 100644
index 0000000000..5e625461cb
--- /dev/null
+++ b/crates/draco-bridge/src/lib.rs
@@ -0,0 +1,78 @@
+//! cxx bridge over C++ Google Draco: encode one triangle mesh (positions +
+//! optional normals/UVs + indices) into a `KHR_draco_mesh_compression` blob.
+//! The caller (`crates/optimize`) assembles the glTF extension records from the
+//! returned draco attribute ids.
+
+#[cxx::bridge(namespace = "carbon_draco")]
+pub mod ffi {
+ /// One encoded primitive: the draco byte stream plus the draco attribute
+ /// `unique_id` assigned to each glTF semantic (`-1` when the attribute was
+ /// absent). These ids are what `primitive.extensions.KHR_draco_mesh_
+ /// compression.attributes` maps each semantic to.
+ #[derive(Debug, Clone)]
+ pub struct DracoEncoded {
+ pub data: Vec<u8>,
+ pub ok: bool,
+ pub pos_id: i32,
+ pub norm_id: i32,
+ pub uv_id: i32,
+ }
+
+ unsafe extern "C++" {
+ include!("draco-bridge/src/shim.h");
+
+ /// Encode an indexed triangle mesh. `positions` is `n*3` f32, `normals`
+ /// `n*3` (or empty), `uvs` `n*2` (or empty), `indices` `m*3` u32. The
+ /// `*_bits` are draco quantization bit counts (0 = leave that attribute
+ /// unquantized). Returns `ok=false` with empty data on any draco error.
+ fn encode_mesh(
+ positions: &[f32],
+ normals: &[f32],
+ uvs: &[f32],
+ indices: &[u32],
+ pos_bits: i32,
+ norm_bits: i32,
+ uv_bits: i32,
+ ) -> DracoEncoded;
+ }
+}
+
+pub use ffi::{encode_mesh, DracoEncoded};
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn encodes_quad_to_draco() {
+ // Unit quad, two triangles.
+ let positions: Vec<f32> = vec![
+ 0.0, 0.0, 0.0, //
+ 1.0, 0.0, 0.0, //
+ 0.0, 1.0, 0.0, //
+ 1.0, 1.0, 0.0,
+ ];
+ let indices: Vec<u32> = vec![0, 1, 2, 2, 1, 3];
+ let enc = encode_mesh(&positions, &[], &[], &indices, 14, 10, 12);
+ assert!(enc.ok, "draco encode failed");
+ assert!(!enc.data.is_empty());
+ // Every draco stream starts with the "DRACO" magic.
+ assert_eq!(&enc.data[0..5], b"DRACO");
+ assert_eq!(enc.pos_id, 0);
+ assert_eq!(enc.norm_id, -1);
+ assert_eq!(enc.uv_id, -1);
+ }
+
+ #[test]
+ fn encodes_with_normals_and_uvs() {
+ let positions: Vec<f32> = vec![0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 1.0, 1.0, 0.0];
+ let normals: Vec<f32> = vec![0.0, 0.0, 1.0, 0.0, 0.0, 1.0, 0.0, 0.0, 1.0, 0.0, 0.0, 1.0];
+ let uvs: Vec<f32> = vec![0.0, 0.0, 1.0, 0.0, 0.0, 1.0, 1.0, 1.0];
+ let indices: Vec<u32> = vec![0, 1, 2, 2, 1, 3];
+ let enc = encode_mesh(&positions, &normals, &uvs, &indices, 14, 10, 12);
+ assert!(enc.ok);
+ assert_eq!(enc.pos_id, 0);
+ assert_eq!(enc.norm_id, 1);
+ assert_eq!(enc.uv_id, 2);
+ }
+}
diff --git a/crates/draco-bridge/src/shim.cc b/crates/draco-bridge/src/shim.cc
new file mode 100644
index 0000000000..4017aff480
--- /dev/null
+++ b/crates/draco-bridge/src/shim.cc
@@ -0,0 +1,96 @@
+#include "draco-bridge/src/shim.h"
+
+#include "draco-bridge/src/lib.rs.h"
+
+#include "draco/attributes/geometry_attribute.h"
+#include "draco/compression/encode.h"
+#include "draco/core/encoder_buffer.h"
+#include "draco/mesh/mesh.h"
+
+namespace carbon_draco {
+
+// Add one float attribute (identity-mapped: point i -> attribute value i) and
+// stamp its unique_id (what the KHR_draco extension references). Returns the id.
+static int32_t add_attribute(draco::Mesh &mesh, draco::GeometryAttribute::Type type,
+ int8_t components, const float *values, size_t num_points,
+ uint32_t unique_id) {
+ draco::GeometryAttribute ga;
+ ga.Init(type, nullptr, components, draco::DT_FLOAT32, /*normalized=*/false,
+ /*byte_stride=*/sizeof(float) * components, /*byte_offset=*/0);
+ const int att_id = mesh.AddAttribute(ga, /*identity_mapping=*/true, num_points);
+ draco::PointAttribute *att = mesh.attribute(att_id);
+ att->set_unique_id(unique_id);
+ for (size_t i = 0; i < num_points; i++) {
+ att->SetAttributeValue(draco::AttributeValueIndex(static_cast<uint32_t>(i)),
+ &values[i * components]);
+ }
+ return static_cast<int32_t>(unique_id);
+}
+
+DracoEncoded encode_mesh(rust::Slice<const float> positions, rust::Slice<const float> normals,
+ rust::Slice<const float> uvs, rust::Slice<const uint32_t> indices,
+ int32_t pos_bits, int32_t norm_bits, int32_t uv_bits) {
+ DracoEncoded out;
+ out.ok = false;
+ out.pos_id = -1;
+ out.norm_id = -1;
+ out.uv_id = -1;
+
+ const size_t nv = positions.size() / 3;
+ const size_t nf = indices.size() / 3;
+ if (nv == 0 || nf == 0) {
+ return out;
+ }
+
+ draco::Mesh mesh;
+ mesh.set_num_points(static_cast<uint32_t>(nv));
+ mesh.SetNumFaces(nf);
+ for (size_t f = 0; f < nf; f++) {
+ draco::Mesh::Face face;
+ face[0] = draco::PointIndex(indices[f * 3 + 0]);
+ face[1] = draco::PointIndex(indices[f * 3 + 1]);
+ face[2] = draco::PointIndex(indices[f * 3 + 2]);
+ mesh.SetFace(draco::FaceIndex(static_cast<uint32_t>(f)), face);
+ }
+
+ uint32_t uid = 0;
+ out.pos_id =
+ add_attribute(mesh, draco::GeometryAttribute::POSITION, 3, positions.data(), nv, uid++);
+ const bool has_normals = normals.size() == nv * 3;
+ const bool has_uvs = uvs.size() == nv * 2;
+ if (has_normals) {
+ out.norm_id =
+ add_attribute(mesh, draco::GeometryAttribute::NORMAL, 3, normals.data(), nv, uid++);
+ }
+ if (has_uvs) {
+ out.uv_id =
+ add_attribute(mesh, draco::GeometryAttribute::TEX_COORD, 2, uvs.data(), nv, uid++);
+ }
+
+ draco::Encoder encoder;
+ if (pos_bits > 0) {
+ encoder.SetAttributeQuantization(draco::GeometryAttribute::POSITION, pos_bits);
+ }
+ if (has_normals && norm_bits > 0) {
+ encoder.SetAttributeQuantization(draco::GeometryAttribute::NORMAL, norm_bits);
+ }
+ if (has_uvs && uv_bits > 0) {
+ encoder.SetAttributeQuantization(draco::GeometryAttribute::TEX_COORD, uv_bits);
+ }
+
+ draco::EncoderBuffer buffer;
+ const draco::Status status = encoder.EncodeMeshToBuffer(mesh, &buffer);
+ if (!status.ok()) {
+ return out;
+ }
+
+ const uint8_t *bytes = reinterpret_cast<const uint8_t *>(buffer.data());
+ out.data.reserve(buffer.size());
+ for (size_t i = 0; i < buffer.size(); i++) {
+ out.data.push_back(bytes[i]);
+ }
+ out.ok = true;
+ return out;
+}
+
+} // namespace carbon_draco
diff --git a/crates/draco-bridge/src/shim.h b/crates/draco-bridge/src/shim.h
new file mode 100644
index 0000000000..8264a5748c
--- /dev/null
+++ b/crates/draco-bridge/src/shim.h
@@ -0,0 +1,13 @@
+#pragma once
+#include "rust/cxx.h"
+#include <cstdint>
+
+namespace carbon_draco {
+struct DracoEncoded; // generated by cxx from the shared struct
+
+DracoEncoded encode_mesh(rust::Slice<const float> positions,
+ rust::Slice<const float> normals,
+ rust::Slice<const float> uvs,
+ rust::Slice<const uint32_t> indices, int32_t pos_bits,
+ int32_t norm_bits, int32_t uv_bits);
+} // namespace carbon_draco
diff --git a/crates/occt-bridge/examples/conc_read.rs b/crates/occt-bridge/examples/conc_read.rs
index 3343f15ed0..f64512c785 100644
--- a/crates/occt-bridge/examples/conc_read.rs
+++ b/crates/occt-bridge/examples/conc_read.rs
@@ -35,9 +35,15 @@ fn run(path: &Arc<String>, threads: usize, iters: usize) -> (f64, u64) {
fn main() {
let args: Vec<String> = std::env::args().collect();
- let path = Arc::new(args.get(1).cloned().expect("usage: conc_read <file.step> [iters]"));
+ let path = Arc::new(
+ args.get(1)
+ .cloned()
+ .expect("usage: conc_read <file.step> [iters]"),
+ );
let iters: usize = args.get(2).and_then(|s| s.parse().ok()).unwrap_or(100);
- let cores = std::thread::available_parallelism().map(|n| n.get()).unwrap_or(8);
+ let cores = std::thread::available_parallelism()
+ .map(|n| n.get())
+ .unwrap_or(8);
// Warm globals single-threaded (mirrors the call_once init path).
let _ = occt_bridge::read_step(path.as_str(), 0.1, 0.5);
diff --git a/crates/occt-bridge/src/lib.rs b/crates/occt-bridge/src/lib.rs
index ef14dd964b..6c339ee0b8 100644
--- a/crates/occt-bridge/src/lib.rs
+++ b/crates/occt-bridge/src/lib.rs
@@ -41,6 +41,24 @@ pub mod ffi {
/// (unreadable STEP, transfer failure, no shapes).
fn read_step(path: &str, linear_deflection: f64, angular_deflection: f64) -> Tree;
+ /// Read + tessellate an IGES file — the XDE twin of `read_step` (same
+ /// XCAF transfer, same walk → same `Tree` shape).
+ fn read_iges(path: &str, linear_deflection: f64, angular_deflection: f64) -> Tree;
+
+ /// Read + tessellate a bare `.brep` shape file, wrapped in a fresh XCAF
+ /// doc so the identical walk applies (no names/colors/structure in BREP).
+ fn read_brep(path: &str, linear_deflection: f64, angular_deflection: f64) -> Tree;
+
+ /// Read a STEP file, transfer to XCAF, and store it as a BinXCAF (`.xbf`)
+ /// document: lossless B-rep + assembly tree + names + colors, far smaller
+ /// and faster to parse than ASCII STEP. Returns false on any failure.
+ fn step_to_xbf(step_path: &str, xbf_path: &str) -> bool;
+
+ /// Read a BinXCAF (`.xbf`) document and tessellate exactly like
+ /// `read_step` (same walk → identical `Tree`). `ok=false` with `error`
+ /// on failure.
+ fn read_xbf(path: &str, linear_deflection: f64, angular_deflection: f64) -> Tree;
+
/// Test fixture generator: write `boxes` disjoint solids as ONE
/// product (flat multi-body, no assembly tree) to a STEP file.
/// Hermetic tests use this instead of committed fixture files.
@@ -48,4 +66,4 @@ pub mod ffi {
}
}
-pub use ffi::{read_step, write_test_step, RawNode, Tree};
+pub use ffi::{read_brep, read_iges, read_step, read_xbf, step_to_xbf, write_test_step, RawNode, Tree};
diff --git a/crates/occt-bridge/src/occt.cc b/crates/occt-bridge/src/occt.cc
index b27aa1c594..0db7c9e3d8 100644
--- a/crates/occt-bridge/src/occt.cc
+++ b/crates/occt-bridge/src/occt.cc
@@ -10,6 +10,7 @@
#include <mutex>
#include <cstdio>
#include <cstdlib>
+#include <BinXCAFDrivers.hxx>
#include <BRepMesh_IncrementalMesh.hxx>
#include <BRepPrimAPI_MakeBox.hxx>
#include <BRep_Builder.hxx>
@@ -18,9 +19,14 @@
#include <GProp_GProps.hxx>
#include <IFSelect_ReturnStatus.hxx>
#include <Interface_Static.hxx>
+#include <PCDM_ReaderStatus.hxx>
+#include <PCDM_StoreStatus.hxx>
#include <Poly_Triangle.hxx>
#include <Poly_Triangulation.hxx>
#include <Quantity_ColorRGBA.hxx>
+#include <BRepTools.hxx>
+#include <BRep_Builder.hxx>
+#include <IGESCAFControl_Reader.hxx>
#include <STEPCAFControl_Reader.hxx>
#include <STEPControl_Controller.hxx>
#include <STEPControl_Writer.hxx>
@@ -31,6 +37,7 @@
#include <TDF_LabelSequence.hxx>
#include <TDF_Tool.hxx>
#include <TDataStd_Name.hxx>
+#include <TDocStd_Application.hxx>
#include <TDocStd_Document.hxx>
#include <TopAbs_Orientation.hxx>
#include <TopAbs_ShapeEnum.hxx>
@@ -380,6 +387,98 @@ class Builder {
}
};
+// OCCT STEP reading is thread-safe under a strict contract: one reader per
+// thread AND no per-request mutation of the process-wide Interface_Static /
+// no concurrent STEPControl_Controller::Init(). So warm both ONCE here,
+// single-threaded; concurrent reads then only touch their own local reader
+// instance and read (never write) the shared config.
+static void ensure_step_init() {
+ static std::once_flag occt_init;
+ std::call_once(occt_init, [] {
+ STEPControl_Controller::Init();
+ Interface_Static::SetCVal("xstep.cascade.unit", "MM");
+ });
+}
+
+// One process-wide XCAF application with the BinXCAF (`.xbf`) storage/retrieval
+// drivers registered — required to SaveAs/Open XCAF documents. TDocStd_Application
+// is internally guarded, so a single shared instance is fine across threads.
+static const Handle(TDocStd_Application) & xcaf_app() {
+ static Handle(TDocStd_Application) app = [] {
+ Handle(TDocStd_Application) a = new TDocStd_Application();
+ BinXCAFDrivers::DefineFormat(a);
+ return a;
+ }();
+ return app;
+}
+
+// Read + transfer a STEP file into a fresh XCAF document. Returns null and sets
+// `error` on failure (unreadable STEP, transfer failure).
+static Handle(TDocStd_Document) read_step_to_doc(const std::string &p,
+ std::string &error) {
+ ensure_step_init();
+ STEPCAFControl_Reader reader;
+ reader.SetColorMode(true);
+ reader.SetNameMode(true);
+ reader.SetLayerMode(false);
+ reader.SetMatMode(false);
+ if (reader.ReadFile(p.c_str()) != IFSelect_RetDone) {
+ error = "could not read STEP file";
+ return nullptr;
+ }
+ Handle(TDocStd_Document) doc = new TDocStd_Document(TCollection_ExtendedString("BinXCAF"));
+ if (!reader.Transfer(doc)) {
+ error = "STEP transfer to XCAF failed";
+ return nullptr;
+ }
+ return doc;
+}
+
+// Walk an XCAF document's free shapes into the flat node `Tree` — the single
+// tessellation path shared by STEP and XBF loaders, so both yield identical
+// nodeIds + geometry.
+static Tree doc_to_tree(const Handle(TDocStd_Document) &doc, double lin, double ang) {
+ Tree t;
+ t.ok = false;
+ t.root_index = 0;
+ Handle(XCAFDoc_ShapeTool) shapeTool = XCAFDoc_DocumentTool::ShapeTool(doc->Main());
+ TDF_LabelSequence freeShapes;
+ shapeTool->GetFreeShapes(freeShapes);
+ if (freeShapes.Length() == 0) {
+ t.error = "document contains no shapes";
+ return t;
+ }
+
+ Builder b(lin, ang, shapeTool);
+ std::vector<uint64_t> roots;
+ for (int i = 1; i <= freeShapes.Length(); ++i) {
+ roots.push_back(b.build(freeShapes.Value(i), TDF_Label(), false, TopLoc_Location(), false));
+ }
+ uint64_t root_index;
+ if (roots.size() == 1) {
+ root_index = roots[0];
+ } else {
+ RawNode r;
+ r.name = "ROOT";
+ r.product_name = "ROOT";
+ for (double x : IDENTITY_4X4) r.transform.push_back(x);
+ r.is_assembly = true;
+ r.has_mesh = false;
+ r.is_proxy = false;
+ r.has_color = false;
+ r.has_volume = false;
+ r.volume = 0.0;
+ for (auto c : roots) r.children.push_back(c);
+ b.nodes.push_back(r);
+ root_index = b.nodes.size() - 1;
+ }
+
+ for (auto &n : b.nodes) t.nodes.push_back(n);
+ t.root_index = root_index;
+ t.ok = true;
+ return t;
+}
+
Tree read_step(rust::Str path, double linear_deflection, double angular_deflection) {
Tree t;
t.ok = false;
@@ -391,73 +490,132 @@ Tree read_step(rust::Str path, double linear_deflection, double angular_deflecti
};
try {
auto t0 = now();
- // OCCT STEP reading is thread-safe under a strict contract: one reader per
- // thread AND no per-request mutation of the process-wide Interface_Static /
- // no concurrent STEPControl_Controller::Init(). So warm both ONCE here,
- // single-threaded; concurrent read_step calls then only touch their own
- // local reader instance and read (never write) the shared config.
- static std::once_flag occt_init;
- std::call_once(occt_init, [] {
- STEPControl_Controller::Init();
- Interface_Static::SetCVal("xstep.cascade.unit", "MM");
- });
- STEPCAFControl_Reader reader;
- reader.SetColorMode(true);
- reader.SetNameMode(true);
- reader.SetLayerMode(false);
- reader.SetMatMode(false);
std::string p(path);
- if (reader.ReadFile(p.c_str()) != IFSelect_RetDone) {
- t.error = "could not read STEP file";
- return t;
- }
- auto t1 = now();
- Handle(TDocStd_Document) doc = new TDocStd_Document(TCollection_ExtendedString("BinXCAF"));
- if (!reader.Transfer(doc)) {
- t.error = "STEP transfer to XCAF failed";
+ std::string err;
+ Handle(TDocStd_Document) doc = read_step_to_doc(p, err);
+ if (doc.IsNull()) {
+ t.error = err;
return t;
}
auto t2 = now();
- Handle(XCAFDoc_ShapeTool) shapeTool = XCAFDoc_DocumentTool::ShapeTool(doc->Main());
- TDF_LabelSequence freeShapes;
- shapeTool->GetFreeShapes(freeShapes);
- if (freeShapes.Length() == 0) {
- t.error = "STEP file contains no shapes";
- return t;
+ t = doc_to_tree(doc, linear_deflection, angular_deflection);
+ if (prof) {
+ auto t3 = now();
+ fprintf(stderr, "OCCT read+transfer=%lldms walk+mesh=%lldms\n",
+ (long long)ms(t0, t2), (long long)ms(t2, t3));
}
+ } catch (Standard_Failure &e) {
+ t.error = std::string("OCCT error: ") + e.GetMessageString();
+ } catch (...) {
+ t.error = "unknown OCCT error";
+ }
+ return t;
+}
+
+// IGES → XCAF doc, mirroring read_step_to_doc (IGESCAFControl_Reader is the
+// XDE twin of the STEP one; same statics, same transfer target).
+static Handle(TDocStd_Document) read_iges_to_doc(const std::string &p,
+ std::string &error) {
+ ensure_step_init();
+ IGESCAFControl_Reader reader;
+ reader.SetColorMode(true);
+ reader.SetNameMode(true);
+ reader.SetLayerMode(false);
+ if (reader.ReadFile(p.c_str()) != IFSelect_RetDone) {
+ error = "could not read IGES file";
+ return nullptr;
+ }
+ Handle(TDocStd_Document) doc = new TDocStd_Document(TCollection_ExtendedString("BinXCAF"));
+ if (!reader.Transfer(doc)) {
+ error = "IGES transfer to XCAF failed";
+ return nullptr;
+ }
+ return doc;
+}
- Builder b(linear_deflection, angular_deflection, shapeTool);
- std::vector<uint64_t> roots;
- for (int i = 1; i <= freeShapes.Length(); ++i) {
- roots.push_back(b.build(freeShapes.Value(i), TDF_Label(), false, TopLoc_Location(), false));
+Tree read_iges(rust::Str path, double linear_deflection, double angular_deflection) {
+ Tree t;
+ t.ok = false;
+ t.root_index = 0;
+ try {
+ std::string p(path);
+ std::string err;
+ Handle(TDocStd_Document) doc = read_iges_to_doc(p, err);
+ if (doc.IsNull()) {
+ t.error = err;
+ return t;
}
- if (prof) {
- auto t3 = now();
- fprintf(stderr, "OCCT read=%lldms transfer=%lldms walk+mesh=%lldms\n",
- (long long)ms(t0, t1), (long long)ms(t1, t2), (long long)ms(t2, t3));
+ t = doc_to_tree(doc, linear_deflection, angular_deflection);
+ } catch (Standard_Failure &e) {
+ t.error = std::string("OCCT error: ") + e.GetMessageString();
+ } catch (...) {
+ t.error = "unknown OCCT error";
+ }
+ return t;
+}
+
+Tree read_brep(rust::Str path, double linear_deflection, double angular_deflection) {
+ // A .brep file is a bare shape (no product structure, names, or colors).
+ // Wrap it in a fresh XCAF doc so the exact same doc_to_tree walk applies —
+ // one tessellation path for every OCCT-loaded format.
+ Tree t;
+ t.ok = false;
+ t.root_index = 0;
+ try {
+ std::string p(path);
+ TopoDS_Shape shape;
+ BRep_Builder builder;
+ if (!BRepTools::Read(shape, p.c_str(), builder)) {
+ t.error = "could not read BREP file";
+ return t;
}
- uint64_t root_index;
- if (roots.size() == 1) {
- root_index = roots[0];
- } else {
- RawNode r;
- r.name = "ROOT";
- r.product_name = "ROOT";
- for (double x : IDENTITY_4X4) r.transform.push_back(x);
- r.is_assembly = true;
- r.has_mesh = false;
- r.is_proxy = false;
- r.has_color = false;
- r.has_volume = false;
- r.volume = 0.0;
- for (auto c : roots) r.children.push_back(c);
- b.nodes.push_back(r);
- root_index = b.nodes.size() - 1;
+ Handle(TDocStd_Document) doc =
+ new TDocStd_Document(TCollection_ExtendedString("BinXCAF"));
+ Handle(XCAFDoc_ShapeTool) shapeTool = XCAFDoc_DocumentTool::ShapeTool(doc->Main());
+ shapeTool->AddShape(shape);
+ t = doc_to_tree(doc, linear_deflection, angular_deflection);
+ } catch (Standard_Failure &e) {
+ t.error = std::string("OCCT error: ") + e.GetMessageString();
+ } catch (...) {
+ t.error = "unknown OCCT error";
+ }
+ return t;
+}
+
+bool step_to_xbf(rust::Str step_path, rust::Str xbf_path) {
+ try {
+ std::string sp(step_path);
+ std::string error;
+ Handle(TDocStd_Document) doc = read_step_to_doc(sp, error);
+ if (doc.IsNull()) {
+ fprintf(stderr, "step_to_xbf: %s\n", error.c_str());
+ return false;
}
+ std::string xp(xbf_path);
+ PCDM_StoreStatus st = xcaf_app()->SaveAs(doc, TCollection_ExtendedString(xp.c_str()));
+ return st == PCDM_SS_OK;
+ } catch (Standard_Failure &e) {
+ fprintf(stderr, "step_to_xbf: OCCT error: %s\n", e.GetMessageString());
+ return false;
+ } catch (...) {
+ fprintf(stderr, "step_to_xbf: unknown OCCT error\n");
+ return false;
+ }
+}
- for (auto &n : b.nodes) t.nodes.push_back(n);
- t.root_index = root_index;
- t.ok = true;
+Tree read_xbf(rust::Str path, double linear_deflection, double angular_deflection) {
+ Tree t;
+ t.ok = false;
+ t.root_index = 0;
+ try {
+ std::string p(path);
+ Handle(TDocStd_Document) doc;
+ PCDM_ReaderStatus rs = xcaf_app()->Open(TCollection_ExtendedString(p.c_str()), doc);
+ if (rs != PCDM_RS_OK || doc.IsNull()) {
+ t.error = "could not open XBF document";
+ return t;
+ }
+ t = doc_to_tree(doc, linear_deflection, angular_deflection);
} catch (Standard_Failure &e) {
t.error = std::string("OCCT error: ") + e.GetMessageString();
} catch (...) {
@@ -472,11 +630,7 @@ Tree read_step(rust::Str path, double linear_deflection, double angular_deflecti
// instead of committing fixture files.
bool write_test_step(rust::Str path, uint32_t boxes) {
try {
- static std::once_flag occt_init;
- std::call_once(occt_init, [] {
- STEPControl_Controller::Init();
- Interface_Static::SetCVal("xstep.cascade.unit", "MM");
- });
+ ensure_step_init();
TopoDS_Shape shape;
if (boxes <= 1) {
shape = BRepPrimAPI_MakeBox(10.0, 10.0, 10.0).Shape();
diff --git a/crates/occt-bridge/src/occt.h b/crates/occt-bridge/src/occt.h
index 985be13958..654d765756 100644
--- a/crates/occt-bridge/src/occt.h
+++ b/crates/occt-bridge/src/occt.h
@@ -7,5 +7,13 @@ struct Tree; // generated by cxx from the shared struct
Tree read_step(rust::Str path, double linear_deflection, double angular_deflection);
+Tree read_iges(rust::Str path, double linear_deflection, double angular_deflection);
+
+Tree read_brep(rust::Str path, double linear_deflection, double angular_deflection);
+
+bool step_to_xbf(rust::Str step_path, rust::Str xbf_path);
+
+Tree read_xbf(rust::Str path, double linear_deflection, double angular_deflection);
+
bool write_test_step(rust::Str path, uint32_t boxes);
} // namespace carbon_occt
diff --git a/crates/optimize/AGENTS.md b/crates/optimize/AGENTS.md
new file mode 100644
index 0000000000..0f5e743c02
--- /dev/null
+++ b/crates/optimize/AGENTS.md
@@ -0,0 +1,74 @@
+# optimize (crate)
+
+Mesh optimiser for the assembler: parse a glTF/GLB, run meshopt per mesh (weld →
+reorder → optional simplify ladder), optionally merge same-material primitives
+and quantize normals, then re-encode as plain glTF, `EXT_meshopt_compression`, or
+`KHR_draco_mesh_compression`. Codec-agnostic core behind one entry point. Consumed
+by `apps/assembler`'s `/v1/optimize` action; the output GLB is rendered by
+`@carbon/viewer` (`useAssembly` → three.js `GLTFLoader` + `MeshoptDecoder`).
+
+Geometry-only focus: mesh `POSITION` / `NORMAL` / `TEXCOORD_0` + indices. Non-mesh
+bufferViews (images, etc.) are copied through untouched.
+
+## Public API (`src/lib.rs`)
+
+- `optimize_glb(glb_bytes, &Options) -> Result<Optimized, OptimizeError>` — GLB in,
+ optimised GLB out. Binary-GLB entry point.
+- `gltf_to_glb(gltf, &mut impl Write) -> Result<(), OptimizeError>` — repack a text
+ `.gltf` whose single buffer is an embedded base64 `data:` URI (the Onshape export
+ shape) into a binary `.glb`, **streaming** the base64 decode (`struson`
+ `next_string_reader` + `base64::read::DecoderReader`) so a multi-GB buffer never
+ materialises. Callers mmap the `.glb` and use `optimize_glb`. (Replaced
+ `optimize_gltf`, whose serde parse held the base64 string + decoded bytes at once
+ ≈ 3× the file.) External `.bin` and multi-buffer glTF are rejected.
+- `optimize_root(root, bin, input_bytes, &Options) -> …` — lowest level; the two
+ above wrap it. Use when you already hold a parsed `json::Root` + BIN slice
+ (lets the caller mmap/stream the source — see `examples/optimize_file.rs`).
+- `Optimized { glb: Vec<u8>, stats: Stats }`; `Stats` carries in/out vertex &
+ triangle counts, byte sizes, `decoded_bytes` (meshopt fallback footprint), and
+ `warnings` (e.g. dropped degenerate primitives).
+- `OptimizeError { message }`.
+- `Codec` (from `src/codec.rs`): `None` | `Meshopt` | `Draco`; `Codec::from_str_opt`.
+
+### `Options`
+
+`codec`, `simplify: Option<f32>` (explicit target ratio), `tolerance: Option<f32>`
+(absolute mm, via `simplify_scale`), `auto_error: Option<f32>` (normalized budget,
+`DEFAULT_AUTO_ERROR = 0.005`), `simplify_aggressive`, `draco_bits: (pos, norm, uv)`,
+`quantize_normals`, `merge_primitives`, `weld`, `reorder`. `Options::default()` =
+meshopt off/lossless-ish defaults; the assembler action sets its own.
+
+## Invariants — do not break
+
+- **meshopt vertex stride must be a multiple of 4.** i16 VEC3 normals are 6 bytes,
+ which the spec JS `MeshoptDecoder` rejects (`Malformed buffer data: -2`) even
+ though the Rust decoder round-trips them. `ViewData::Attr3i16` therefore stores
+ `[i16; 4]` (stride 8, 4th lane `0`); the accessor stays VEC3. Any new quantized
+ attribute must keep its stride `% 4 == 0`. Guarded by
+ `quantized_normals_keep_meshopt_stride_multiple_of_four`.
+- **Drop degenerate primitives, don't feed them to meshopt.** `is_encodable`
+ requires non-empty verts, `indices.len() >= 3 && % 3 == 0`, and every index in
+ range; skipping this segfaults `meshopt::encode_*` on real models. Dropped
+ primitives are counted in `Stats::warnings`.
+- **Set extension records on the typed `json` structs** (the gltf `extensions`
+ feature: `bufferView.extensions.others`) — never round-trip the whole document
+ through `serde_json::Value` (that path cost ~1.65 GB on a 27 M-tri model).
+
+## Validation
+
+```bash
+cargo test -p optimize # unit + codec + stride regression
+cargo run --release --example optimize_file -- <path.glb|.gltf> [none|meshopt|draco]
+```
+
+The example mmaps the source, streams the base64 decode, and writes
+`/tmp/optimized-<codec>.glb` — use it to check real files, then verify the output
+loads in a spec JS decoder (three.js `GLTFLoader.setMeshoptDecoder`), not just
+that it reparses in Rust.
+
+## Cross-references
+
+- `apps/assembler` — the `/v1/optimize` action + service contract (`AGENTS.md`).
+- `crates/draco-bridge` — cxx bridge to static Google Draco (the `Draco` codec).
+- `packages/viewer` — `useAssembly` loads these GLBs with `MeshoptDecoder`.
+- `.ai/lessons.md` — the meshopt-stride pitfall in full.
diff --git a/crates/optimize/Cargo.toml b/crates/optimize/Cargo.toml
new file mode 100644
index 0000000000..4b4c6b642e
--- /dev/null
+++ b/crates/optimize/Cargo.toml
@@ -0,0 +1,24 @@
+[package]
+name = "optimize"
+version.workspace = true
+edition.workspace = true
+license.workspace = true
+
+# Mesh optimisation: parse a GLB, run meshopt per-mesh (weld, vertex-cache /
+# overdraw / fetch reorder, optional simplify ladder), and re-encode
+# (plain, or EXT_meshopt_compression). Codec-agnostic core so Draco slots in
+# behind the same `optimize_glb` entry point.
+
+[dependencies]
+gltf.workspace = true
+meshopt.workspace = true
+bytemuck.workspace = true
+serde_json.workspace = true
+base64 = "0.22"
+struson = "0.6"
+draco-bridge = { path = "../draco-bridge" }
+zip = { version = "8.6.0", default-features = false, features = ["deflate"] }
+quick-xml = "0.41.0"
+
+[dev-dependencies]
+memmap2 = "0.9"
diff --git a/crates/optimize/examples/optimize_file.rs b/crates/optimize/examples/optimize_file.rs
new file mode 100644
index 0000000000..93a653acc9
--- /dev/null
+++ b/crates/optimize/examples/optimize_file.rs
@@ -0,0 +1,147 @@
+//! Ad-hoc harness: optimise a real .glb or .gltf (embedded-base64 buffer) and
+//! print before/after stats. Not part of the service — a verification tool.
+//!
+//! cargo run --release --example optimize_file -- "<path>" [none|meshopt|draco]
+
+use gltf::json;
+use std::io::BufReader;
+use std::time::Instant;
+
+fn mb(bytes: usize) -> String {
+ format!("{:.1} MB", bytes as f64 / 1_048_576.0)
+}
+
+/// Holds the binary buffer either memory-mapped (OS-paged, off the RSS) — with
+/// the BIN sub-range within the map — or owned.
+enum Bin {
+ Mapped(memmap2::Mmap, usize, usize),
+ Owned(Vec<u8>),
+}
+impl Bin {
+ fn as_slice(&self) -> &[u8] {
+ match self {
+ Bin::Mapped(m, off, len) => &m[*off..*off + *len],
+ Bin::Owned(v) => v,
+ }
+ }
+}
+
+fn le_u32(b: &[u8], off: usize) -> usize {
+ u32::from_le_bytes([b[off], b[off + 1], b[off + 2], b[off + 3]]) as usize
+}
+
+fn main() {
+ let args: Vec<String> = std::env::args().collect();
+ let path = args.get(1).expect("usage: optimize_file <path> [codec]");
+ let codec_name = args.get(2).map(String::as_str).unwrap_or("meshopt");
+ let codec = optimize::Codec::from_str_opt(codec_name).expect("bad codec");
+
+ let input_bytes = std::fs::metadata(path)
+ .map(|m| m.len() as usize)
+ .unwrap_or(0);
+ eprintln!("loading {path} ({}) …", mb(input_bytes));
+
+ let t = Instant::now();
+ let (root, bin) = load(path);
+ eprintln!(
+ "loaded: {} meshes, bin {} in {} ms",
+ root.meshes.len(),
+ mb(bin.as_slice().len()),
+ t.elapsed().as_millis()
+ );
+
+ let opts = optimize::Options {
+ codec,
+ quantize_normals: true,
+ merge_primitives: true,
+ ..Default::default()
+ };
+ eprintln!("optimising (codec={codec_name}) …");
+ let t = Instant::now();
+ let res = match optimize::optimize_root(root, bin.as_slice(), input_bytes, &opts) {
+ Ok(r) => r,
+ Err(e) => {
+ eprintln!("ERROR: {}", e.message);
+ std::process::exit(1);
+ }
+ };
+ let ms = t.elapsed().as_millis();
+
+ println!("--- {codec_name} ---");
+ println!(
+ "tris {:>10} -> {:>10} ({:.1}%)",
+ res.stats.input_triangles,
+ res.stats.output_triangles,
+ pct(res.stats.output_triangles, res.stats.input_triangles)
+ );
+ println!(
+ "verts {:>10} -> {:>10}",
+ res.stats.input_vertices, res.stats.output_vertices
+ );
+ println!(
+ "bytes {:>10} -> {:>10} (decoded {}) ({:.1}%)",
+ mb(res.stats.input_bytes),
+ mb(res.glb.len()),
+ mb(res.stats.decoded_bytes),
+ pct(res.glb.len(), res.stats.input_bytes)
+ );
+ println!("time {ms} ms");
+ if !res.stats.warnings.is_empty() {
+ println!("warnings: {:?}", res.stats.warnings);
+ }
+
+ let out = format!("/tmp/optimized-{codec_name}.glb");
+ std::fs::write(&out, &res.glb).expect("write output");
+ println!("wrote {out} ({})", mb(res.glb.len()));
+}
+
+fn pct(a: usize, b: usize) -> f64 {
+ if b == 0 {
+ 0.0
+ } else {
+ 100.0 * a as f64 / b as f64
+ }
+}
+
+fn load(path: &str) -> (json::Root, Bin) {
+ if path.to_lowercase().ends_with(".glb") {
+ // mmap the whole file; the BIN chunk becomes an OS-paged sub-slice, off
+ // the RSS. Parse the GLB chunk layout by hand to avoid a Cow borrow of
+ // the map: [magic,ver,len] then chunks [len,type,data]; chunk0=JSON (its
+ // length is 4-aligned), chunk1=BIN.
+ let file = std::fs::File::open(path).expect("open glb");
+ let map = unsafe { memmap2::Mmap::map(&file) }.expect("mmap glb");
+ let json_len = le_u32(&map, 12);
+ let root: json::Root = serde_json::from_slice(&map[20..20 + json_len]).expect("parse json");
+ let bin_hdr = 20 + json_len;
+ let bin_len = le_u32(&map, bin_hdr);
+ let bin_off = bin_hdr + 8;
+ (root, Bin::Mapped(map, bin_off, bin_len))
+ } else {
+ // .gltf — parse the JSON, then STREAM-decode buffer[0]'s base64 data URI
+ // straight to a temp file and mmap it, so the ~900 MB buffer is never a
+ // resident Vec. The 1.3 GB base64 string is dropped right after.
+ let file = std::fs::File::open(path).expect("open gltf");
+ let mut root: json::Root =
+ serde_json::from_reader(BufReader::new(file)).expect("parse gltf json");
+ let uri = std::mem::take(&mut root.buffers[0].uri).expect("buffer has no uri");
+ let comma = uri.find(',').expect("not a data URI") + 1;
+
+ let tmp = std::env::temp_dir().join(format!("optimize-bin-{}.bin", std::process::id()));
+ {
+ let mut out = std::fs::File::create(&tmp).expect("create temp");
+ let mut dec = base64::read::DecoderReader::new(
+ std::io::Cursor::new(&uri.as_bytes()[comma..]),
+ &base64::engine::general_purpose::STANDARD,
+ );
+ std::io::copy(&mut dec, &mut out).expect("stream-decode base64");
+ }
+ drop(uri); // free the ~1.3 GB base64 string
+ root.buffers.clear();
+ let map = unsafe { memmap2::Mmap::map(&std::fs::File::open(&tmp).expect("open temp")) }
+ .expect("mmap temp");
+ let len = map.len();
+ let _ = std::fs::remove_file(&tmp); // unlinked; the mmap keeps it alive
+ (root, Bin::Mapped(map, 0, len))
+ }
+}
diff --git a/crates/optimize/src/codec.rs b/crates/optimize/src/codec.rs
new file mode 100644
index 0000000000..661dfe4957
--- /dev/null
+++ b/crates/optimize/src/codec.rs
@@ -0,0 +1,28 @@
+//! Output buffer codec for the optimised GLB. Geometry optimisation (weld,
+//! reorder, simplify) is codec-independent; this only selects how the resulting
+//! vertex/index buffers are encoded in the container.
+
+/// Transmission codec for the optimised GLB buffers.
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
+pub enum Codec {
+ /// Plain little-endian buffers, no compression extension.
+ None,
+ /// `EXT_meshopt_compression` (native meshopt encode). Decoded by the viewer's
+ /// MeshoptDecoder. (Phase 1b.)
+ #[default]
+ Meshopt,
+ /// `KHR_draco_mesh_compression` (via crates/draco-bridge → C++ Google Draco).
+ /// Per-primitive; quantizes attributes (the decoder dequantizes).
+ Draco,
+}
+
+impl Codec {
+ pub fn from_str_opt(s: &str) -> Option<Codec> {
+ match s {
+ "none" => Some(Codec::None),
+ "meshopt" => Some(Codec::Meshopt),
+ "draco" => Some(Codec::Draco),
+ _ => None,
+ }
+ }
+}
diff --git a/crates/optimize/src/ingest.rs b/crates/optimize/src/ingest.rs
new file mode 100644
index 0000000000..46fd1a3990
--- /dev/null
+++ b/crates/optimize/src/ingest.rs
@@ -0,0 +1,948 @@
+//! Mesh-format ingest: OBJ / PLY / OFF / dotbim → uncompressed, weldable GLB.
+//!
+//! Mirrors `stl_to_glb`'s strategy: every format is expanded to a flat triangle
+//! soup (positions + per-face or carried normals) and built into a single-mesh
+//! GLB via `build_triangle_glb`. Sharing/topology is deliberately NOT preserved
+//! here — the optimiser's weld pass reconstructs it (that is its job), then
+//! simplifies and encodes like any other input. Fail loud on malformed input;
+//! never emit an empty mesh.
+
+use crate::{build_triangle_glb, OptimizeError};
+
+/// Wavefront OBJ. Geometry only: `v` + `f` (polygons fan-triangulated, negative
+/// and 1-based indices per spec). Materials/uv/vn are ignored — per-face normals
+/// are recomputed, matching the STL path.
+pub fn obj_to_glb(bytes: &[u8]) -> Result<Vec<u8>, OptimizeError> {
+ let text =
+ std::str::from_utf8(bytes).map_err(|_| OptimizeError::new("OBJ is not valid UTF-8"))?;
+ let mut vertices: Vec<[f32; 3]> = Vec::new();
+ let mut triangles: Vec<[usize; 3]> = Vec::new();
+
+ for line in text.lines() {
+ let line = line.trim();
+ if let Some(rest) = line.strip_prefix("v ") {
+ let mut it = rest.split_whitespace().filter_map(|t| t.parse::<f32>().ok());
+ match (it.next(), it.next(), it.next()) {
+ (Some(x), Some(y), Some(z)) => vertices.push([x, y, z]),
+ _ => return Err(OptimizeError::new("OBJ vertex with fewer than 3 coords")),
+ }
+ } else if let Some(rest) = line.strip_prefix("f ") {
+ // Each face token is `v`, `v/vt`, `v//vn`, or `v/vt/vn`; only the
+ // vertex index matters here. Negative = relative to current count.
+ let mut face: Vec<usize> = Vec::new();
+ for token in rest.split_whitespace() {
+ let first = token.split('/').next().unwrap_or("");
+ let idx: i64 = first
+ .parse()
+ .map_err(|_| OptimizeError::new("OBJ face has a non-numeric index"))?;
+ let resolved = if idx < 0 {
+ vertices.len() as i64 + idx
+ } else {
+ idx - 1
+ };
+ if resolved < 0 || resolved as usize >= vertices.len() {
+ return Err(OptimizeError::new("OBJ face index out of range"));
+ }
+ face.push(resolved as usize);
+ }
+ fan_triangulate(&face, &mut triangles);
+ }
+ }
+ soup_to_glb(&vertices, &triangles, "OBJ")
+}
+
+/// OFF (Object File Format): counts line, vertices, polygon faces.
+pub fn off_to_glb(bytes: &[u8]) -> Result<Vec<u8>, OptimizeError> {
+ let text =
+ std::str::from_utf8(bytes).map_err(|_| OptimizeError::new("OFF is not valid UTF-8"))?;
+ let mut tokens = text
+ .lines()
+ .map(|l| l.split('#').next().unwrap_or("").trim())
+ .filter(|l| !l.is_empty())
+ .flat_map(|l| l.split_whitespace())
+ .peekable();
+
+ if tokens.peek() == Some(&"OFF") {
+ tokens.next();
+ }
+ let mut next_usize = |what: &str| -> Result<usize, OptimizeError> {
+ tokens
+ .next()
+ .and_then(|t| t.parse::<usize>().ok())
+ .ok_or_else(|| OptimizeError::new(format!("OFF: missing/invalid {what}")))
+ };
+ let n_vertices = next_usize("vertex count")?;
+ let n_faces = next_usize("face count")?;
+ let _n_edges = tokens.next(); // unused
+
+ let mut vertices: Vec<[f32; 3]> = Vec::with_capacity(n_vertices);
+ for _ in 0..n_vertices {
+ let mut coord = [0.0f32; 3];
+ for c in &mut coord {
+ *c = tokens
+ .next()
+ .and_then(|t| t.parse().ok())
+ .ok_or_else(|| OptimizeError::new("OFF: truncated vertex"))?;
+ }
+ vertices.push(coord);
+ }
+ let mut triangles: Vec<[usize; 3]> = Vec::new();
+ for _ in 0..n_faces {
+ let count = tokens
+ .next()
+ .and_then(|t| t.parse::<usize>().ok())
+ .ok_or_else(|| OptimizeError::new("OFF: truncated face"))?;
+ let mut face = Vec::with_capacity(count);
+ for _ in 0..count {
+ let idx = tokens
+ .next()
+ .and_then(|t| t.parse::<usize>().ok())
+ .ok_or_else(|| OptimizeError::new("OFF: truncated face index"))?;
+ if idx >= vertices.len() {
+ return Err(OptimizeError::new("OFF face index out of range"));
+ }
+ face.push(idx);
+ }
+ fan_triangulate(&face, &mut triangles);
+ }
+ soup_to_glb(&vertices, &triangles, "OFF")
+}
+
+/// dotbim (`.bim`): plain JSON — shared meshes instanced by elements carrying a
+/// translation + quaternion. Transforms are baked into the soup; colors are not
+/// carried (the optimise pipeline is geometry-only).
+pub fn bim_to_glb(bytes: &[u8]) -> Result<Vec<u8>, OptimizeError> {
+ let parsed: serde_json::Value = serde_json::from_slice(bytes)
+ .map_err(|_| OptimizeError::new("dotbim is not valid JSON"))?;
+ let meshes = parsed["meshes"]
+ .as_array()
+ .ok_or_else(|| OptimizeError::new("dotbim has no meshes array"))?;
+
+ // mesh_id -> (vertices, triangles)
+ let mut library: std::collections::HashMap<i64, (Vec<[f32; 3]>, Vec<[usize; 3]>)> =
+ std::collections::HashMap::new();
+ for mesh in meshes {
+ let id = mesh["mesh_id"]
+ .as_i64()
+ .ok_or_else(|| OptimizeError::new("dotbim mesh without mesh_id"))?;
+ let coords: Vec<f32> = mesh["coordinates"]
+ .as_array()
+ .ok_or_else(|| OptimizeError::new("dotbim mesh without coordinates"))?
+ .iter()
+ .filter_map(|v| v.as_f64().map(|f| f as f32))
+ .collect();
+ let indices: Vec<usize> = mesh["indices"]
+ .as_array()
+ .ok_or_else(|| OptimizeError::new("dotbim mesh without indices"))?
+ .iter()
+ .filter_map(|v| v.as_u64().map(|u| u as usize))
+ .collect();
+ if coords.len() % 3 != 0 || indices.len() % 3 != 0 {
+ return Err(OptimizeError::new("dotbim mesh arrays not multiples of 3"));
+ }
+ let vertices: Vec<[f32; 3]> = coords.chunks_exact(3).map(|c| [c[0], c[1], c[2]]).collect();
+ for &i in &indices {
+ if i >= vertices.len() {
+ return Err(OptimizeError::new("dotbim index out of range"));
+ }
+ }
+ let triangles = indices.chunks_exact(3).map(|t| [t[0], t[1], t[2]]).collect();
+ library.insert(id, (vertices, triangles));
+ }
+
+ // Elements instance the meshes; absent/empty elements = render meshes once.
+ let default_elements: Vec<serde_json::Value>;
+ let elements = match parsed["elements"].as_array() {
+ Some(arr) if !arr.is_empty() => arr,
+ _ => {
+ default_elements = library
+ .keys()
+ .map(|id| serde_json::json!({ "mesh_id": id }))
+ .collect();
+ &default_elements
+ }
+ };
+
+ let mut positions: Vec<[f32; 3]> = Vec::new();
+ let mut normals: Vec<[f32; 3]> = Vec::new();
+ for el in elements {
+ let Some((vertices, triangles)) = el["mesh_id"].as_i64().and_then(|id| library.get(&id))
+ else {
+ continue;
+ };
+ let q = &el["rotation"];
+ let quat = [
+ q["qx"].as_f64().unwrap_or(0.0) as f32,
+ q["qy"].as_f64().unwrap_or(0.0) as f32,
+ q["qz"].as_f64().unwrap_or(0.0) as f32,
+ q["qw"].as_f64().unwrap_or(1.0) as f32,
+ ];
+ let v = &el["vector"];
+ let translate = [
+ v["x"].as_f64().unwrap_or(0.0) as f32,
+ v["y"].as_f64().unwrap_or(0.0) as f32,
+ v["z"].as_f64().unwrap_or(0.0) as f32,
+ ];
+ for tri in triangles {
+ let p: Vec<[f32; 3]> = tri
+ .iter()
+ .map(|&i| {
+ let r = rotate(quat, vertices[i]);
+ [
+ r[0] + translate[0],
+ r[1] + translate[1],
+ r[2] + translate[2],
+ ]
+ })
+ .collect();
+ let n = face_normal(p[0], p[1], p[2]);
+ positions.extend_from_slice(&p);
+ normals.extend_from_slice(&[n, n, n]);
+ }
+ }
+ if positions.is_empty() {
+ return Err(OptimizeError::new("dotbim contains no renderable geometry"));
+ }
+ build_triangle_glb(&positions, &normals)
+}
+
+/// PLY: ascii and binary_little_endian, the two formats seen in the wild for
+/// exports. Vertex x/y/z are read; other vertex properties are skipped by size;
+/// faces are `property list` polygons, fan-triangulated.
+pub fn ply_to_glb(bytes: &[u8]) -> Result<Vec<u8>, OptimizeError> {
+ let header_end = find_subslice(bytes, b"end_header\n")
+ .ok_or_else(|| OptimizeError::new("PLY has no end_header"))?
+ + b"end_header\n".len();
+ let header = std::str::from_utf8(&bytes[..header_end])
+ .map_err(|_| OptimizeError::new("PLY header is not UTF-8"))?;
+
+ #[derive(Clone, Copy, PartialEq)]
+ enum Fmt {
+ Ascii,
+ BinaryLe,
+ }
+ let mut fmt = None;
+ // (element name, count, per-element property sizes/kinds)
+ struct Elem {
+ name: String,
+ count: usize,
+ // scalar property byte sizes in order; x/y/z positions tracked by index
+ props: Vec<(String, usize)>,
+ list: Option<(usize, usize)>, // (count-type size, item-type size) for face lists
+ }
+ let mut elems: Vec<Elem> = Vec::new();
+
+ for line in header.lines() {
+ let mut it = line.split_whitespace();
+ match it.next() {
+ Some("format") => {
+ fmt = match it.next() {
+ Some("ascii") => Some(Fmt::Ascii),
+ Some("binary_little_endian") => Some(Fmt::BinaryLe),
+ other => {
+ return Err(OptimizeError::new(format!(
+ "unsupported PLY format: {}",
+ other.unwrap_or("?")
+ )))
+ }
+ };
+ }
+ Some("element") => {
+ let name = it.next().unwrap_or("").to_string();
+ let count = it
+ .next()
+ .and_then(|t| t.parse().ok())
+ .ok_or_else(|| OptimizeError::new("PLY element without count"))?;
+ elems.push(Elem {
+ name,
+ count,
+ props: Vec::new(),
+ list: None,
+ });
+ }
+ Some("property") => {
+ let Some(elem) = elems.last_mut() else { continue };
+ let kind = it.next().unwrap_or("");
+ if kind == "list" {
+ let count_size = ply_type_size(it.next().unwrap_or(""))?;
+ let item_size = ply_type_size(it.next().unwrap_or(""))?;
+ elem.list = Some((count_size, item_size));
+ } else {
+ let size = ply_type_size(kind)?;
+ let name = it.next().unwrap_or("").to_string();
+ elem.props.push((name, size));
+ }
+ }
+ _ => {}
+ }
+ }
+ let fmt = fmt.ok_or_else(|| OptimizeError::new("PLY has no format line"))?;
+
+ let mut vertices: Vec<[f32; 3]> = Vec::new();
+ let mut triangles: Vec<[usize; 3]> = Vec::new();
+
+ match fmt {
+ Fmt::Ascii => {
+ let body = std::str::from_utf8(&bytes[header_end..])
+ .map_err(|_| OptimizeError::new("ASCII PLY body is not UTF-8"))?;
+ let mut lines = body.lines().filter(|l| !l.trim().is_empty());
+ for elem in &elems {
+ for _ in 0..elem.count {
+ let line = lines
+ .next()
+ .ok_or_else(|| OptimizeError::new("PLY body truncated"))?;
+ let tokens: Vec<&str> = line.split_whitespace().collect();
+ if elem.name == "vertex" {
+ vertices.push(read_ply_vertex_ascii(&tokens, &elem.props)?);
+ } else if elem.list.is_some() {
+ let count: usize = tokens
+ .first()
+ .and_then(|t| t.parse().ok())
+ .ok_or_else(|| OptimizeError::new("PLY face without count"))?;
+ let face: Vec<usize> = tokens
+ .iter()
+ .skip(1)
+ .take(count)
+ .filter_map(|t| t.parse().ok())
+ .collect();
+ if face.len() != count {
+ return Err(OptimizeError::new("PLY face truncated"));
+ }
+ push_face(&face, vertices.len(), &mut triangles)?;
+ }
+ }
+ }
+ }
+ Fmt::BinaryLe => {
+ let mut off = header_end;
+ let read_f32 = |bytes: &[u8], off: usize| -> Result<f32, OptimizeError> {
+ bytes
+ .get(off..off + 4)
+ .map(|b| f32::from_le_bytes([b[0], b[1], b[2], b[3]]))
+ .ok_or_else(|| OptimizeError::new("PLY body truncated"))
+ };
+ for elem in &elems {
+ for _ in 0..elem.count {
+ if elem.name == "vertex" {
+ let mut coord = [0.0f32; 3];
+ let mut cursor = off;
+ for (name, size) in &elem.props {
+ match name.as_str() {
+ "x" => coord[0] = read_f32(bytes, cursor)?,
+ "y" => coord[1] = read_f32(bytes, cursor)?,
+ "z" => coord[2] = read_f32(bytes, cursor)?,
+ _ => {}
+ }
+ cursor += size;
+ }
+ vertices.push(coord);
+ off = cursor;
+ } else if let Some((count_size, item_size)) = elem.list {
+ let count = read_uint_le(bytes, off, count_size)? as usize;
+ off += count_size;
+ let mut face = Vec::with_capacity(count);
+ for _ in 0..count {
+ face.push(read_uint_le(bytes, off, item_size)? as usize);
+ off += item_size;
+ }
+ push_face(&face, vertices.len(), &mut triangles)?;
+ } else {
+ // Unknown fixed-size element: skip its bytes.
+ off += elem.props.iter().map(|(_, s)| s).sum::<usize>();
+ }
+ }
+ }
+ }
+ }
+ soup_to_glb(&vertices, &triangles, "PLY")
+}
+
+/// 3MF: a zip whose `3D/3dmodel.model` entry is the model XML — objects hold
+/// meshes (and/or components referencing other objects with a 4x3 transform);
+/// `<build>` items place objects. Transforms are baked in; units scaled to mm.
+pub fn threemf_to_glb(bytes: &[u8]) -> Result<Vec<u8>, OptimizeError> {
+ let mut archive = zip::ZipArchive::new(std::io::Cursor::new(bytes))
+ .map_err(|_| OptimizeError::new("3MF is not a valid zip archive"))?;
+ let model_name = (0..archive.len())
+ .filter_map(|i| archive.by_index(i).ok().map(|f| f.name().to_string()))
+ .find(|n| n == "3D/3dmodel.model" || n.ends_with(".model"))
+ .ok_or_else(|| OptimizeError::new("3MF has no 3dmodel.model entry"))?;
+ let mut xml = Vec::new();
+ {
+ use std::io::Read;
+ let mut entry = archive
+ .by_name(&model_name)
+ .map_err(|_| OptimizeError::new("3MF model entry unreadable"))?;
+ entry
+ .read_to_end(&mut xml)
+ .map_err(|_| OptimizeError::new("3MF model entry unreadable"))?;
+ }
+ parse_3mf_model(&xml)
+}
+
+fn parse_3mf_model(xml: &[u8]) -> Result<Vec<u8>, OptimizeError> {
+ use quick_xml::events::Event;
+
+ struct ObjectData {
+ vertices: Vec<[f32; 3]>,
+ triangles: Vec<[usize; 3]>,
+ components: Vec<(String, [f32; 12])>,
+ }
+ let mut objects: std::collections::HashMap<String, ObjectData> =
+ std::collections::HashMap::new();
+ let mut build: Vec<(String, [f32; 12])> = Vec::new();
+ let mut unit_scale = 1.0f32; // millimeter default
+
+ let mut reader = quick_xml::Reader::from_reader(xml);
+ reader.config_mut().trim_text(true);
+ let mut current: Option<String> = None;
+ let mut buf = Vec::new();
+ loop {
+ let event = reader
+ .read_event_into(&mut buf)
+ .map_err(|e| OptimizeError::new(format!("3MF XML error: {e}")))?;
+ match &event {
+ Event::Start(e) | Event::Empty(e) => {
+ let attr = |name: &str| -> Option<String> {
+ e.attributes().flatten().find_map(|a| {
+ (a.key.as_ref() == name.as_bytes())
+ .then(|| String::from_utf8_lossy(&a.value).into_owned())
+ })
+ };
+ match e.local_name().as_ref() {
+ b"model" => {
+ unit_scale = unit_to_mm(attr("unit").as_deref().unwrap_or("millimeter"))?;
+ }
+ b"object" => {
+ if let Some(id) = attr("id") {
+ objects.insert(
+ id.clone(),
+ ObjectData {
+ vertices: Vec::new(),
+ triangles: Vec::new(),
+ components: Vec::new(),
+ },
+ );
+ current = Some(id);
+ }
+ }
+ b"vertex" => {
+ let Some(obj) = current.as_ref().and_then(|id| objects.get_mut(id)) else {
+ continue;
+ };
+ let coord = |n: &str| -> f32 {
+ attr(n).and_then(|v| v.parse().ok()).unwrap_or(0.0)
+ };
+ obj.vertices.push([coord("x"), coord("y"), coord("z")]);
+ }
+ b"triangle" => {
+ let Some(obj) = current.as_ref().and_then(|id| objects.get_mut(id)) else {
+ continue;
+ };
+ let idx = |n: &str| -> Option<usize> { attr(n)?.parse().ok() };
+ if let (Some(v1), Some(v2), Some(v3)) = (idx("v1"), idx("v2"), idx("v3")) {
+ if v1 >= obj.vertices.len()
+ || v2 >= obj.vertices.len()
+ || v3 >= obj.vertices.len()
+ {
+ return Err(OptimizeError::new("3MF triangle index out of range"));
+ }
+ obj.triangles.push([v1, v2, v3]);
+ }
+ }
+ b"component" => {
+ let Some(obj) = current.as_ref().and_then(|id| objects.get_mut(id)) else {
+ continue;
+ };
+ if let Some(refid) = attr("objectid") {
+ obj.components
+ .push((refid, parse_3mf_transform(attr("transform").as_deref())));
+ }
+ }
+ b"item" => {
+ if let Some(id) = attr("objectid") {
+ build.push((id, parse_3mf_transform(attr("transform").as_deref())));
+ }
+ }
+ _ => {}
+ }
+ }
+ Event::End(e) => {
+ if e.local_name().as_ref() == b"object" {
+ current = None;
+ }
+ }
+ Event::Eof => break,
+ _ => {}
+ }
+ buf.clear();
+ }
+
+ // No <build> section: render every object once.
+ if build.is_empty() {
+ build = objects.keys().map(|id| (id.clone(), IDENTITY_4X3)).collect();
+ }
+
+ let mut positions: Vec<[f32; 3]> = Vec::new();
+ let mut normals: Vec<[f32; 3]> = Vec::new();
+ // Recursively emit an object (mesh + components) under an accumulated transform.
+ fn emit(
+ id: &str,
+ transform: [f32; 12],
+ objects: &std::collections::HashMap<
+ String,
+ (Vec<[f32; 3]>, Vec<[usize; 3]>, Vec<(String, [f32; 12])>),
+ >,
+ depth: usize,
+ positions: &mut Vec<[f32; 3]>,
+ normals: &mut Vec<[f32; 3]>,
+ ) {
+ if depth > 16 {
+ return; // cycle guard
+ }
+ let Some((vertices, triangles, components)) = objects.get(id) else {
+ return;
+ };
+ for tri in triangles {
+ let p: Vec<[f32; 3]> = tri
+ .iter()
+ .map(|&i| apply_4x3(transform, vertices[i]))
+ .collect();
+ let n = face_normal(p[0], p[1], p[2]);
+ positions.extend_from_slice(&p);
+ normals.extend_from_slice(&[n, n, n]);
+ }
+ for (refid, child) in components {
+ emit(
+ refid,
+ compose_4x3(transform, *child),
+ objects,
+ depth + 1,
+ positions,
+ normals,
+ );
+ }
+ }
+ let plain: std::collections::HashMap<_, _> = objects
+ .into_iter()
+ .map(|(id, o)| (id, (o.vertices, o.triangles, o.components)))
+ .collect();
+ for (id, transform) in &build {
+ emit(id, *transform, &plain, 0, &mut positions, &mut normals);
+ }
+ if positions.is_empty() {
+ return Err(OptimizeError::new("3MF contains no renderable geometry"));
+ }
+ for p in &mut positions {
+ for c in p.iter_mut() {
+ *c *= unit_scale;
+ }
+ }
+ build_triangle_glb(&positions, &normals)
+}
+
+/// AMF: XML (optionally zip-wrapped, same-name entry). Objects hold vertex
+/// coordinates + volume triangles. Constellations (instance placements) are not
+/// applied — objects render once, which matches how slicers treat plain parts.
+pub fn amf_to_glb(bytes: &[u8]) -> Result<Vec<u8>, OptimizeError> {
+ let xml: Vec<u8> = if bytes.starts_with(b"PK\x03\x04") {
+ use std::io::Read;
+ let mut archive = zip::ZipArchive::new(std::io::Cursor::new(bytes))
+ .map_err(|_| OptimizeError::new("AMF zip is invalid"))?;
+ let name = (0..archive.len())
+ .filter_map(|i| archive.by_index(i).ok().map(|f| f.name().to_string()))
+ .find(|n| n.to_lowercase().ends_with(".amf"))
+ .ok_or_else(|| OptimizeError::new("AMF zip has no .amf entry"))?;
+ let mut out = Vec::new();
+ archive
+ .by_name(&name)
+ .map_err(|_| OptimizeError::new("AMF entry unreadable"))?
+ .read_to_end(&mut out)
+ .map_err(|_| OptimizeError::new("AMF entry unreadable"))?;
+ out
+ } else {
+ bytes.to_vec()
+ };
+
+ use quick_xml::events::Event;
+ let mut reader = quick_xml::Reader::from_reader(xml.as_slice());
+ reader.config_mut().trim_text(true);
+
+ let mut unit_scale = 1.0f32;
+ let mut vertices: Vec<[f32; 3]> = Vec::new();
+ let mut triangles: Vec<[usize; 3]> = Vec::new();
+ // Per-object vertex offset: AMF triangle indices are object-local.
+ let mut object_base = 0usize;
+ let mut coord = [0.0f32; 3];
+ let mut tri = [0usize; 3];
+ let mut text_target: Option<usize> = None; // 0-2 into coord, 3-5 into tri
+ let mut buf = Vec::new();
+ loop {
+ let event = reader
+ .read_event_into(&mut buf)
+ .map_err(|e| OptimizeError::new(format!("AMF XML error: {e}")))?;
+ match &event {
+ Event::Start(e) | Event::Empty(e) => match e.local_name().as_ref() {
+ b"amf" => {
+ let unit = e.attributes().flatten().find_map(|a| {
+ (a.key.as_ref() == b"unit")
+ .then(|| String::from_utf8_lossy(&a.value).into_owned())
+ });
+ unit_scale = unit_to_mm(unit.as_deref().unwrap_or("millimeter"))?;
+ }
+ b"object" => object_base = vertices.len(),
+ b"x" => text_target = Some(0),
+ b"y" => text_target = Some(1),
+ b"z" => text_target = Some(2),
+ b"v1" => text_target = Some(3),
+ b"v2" => text_target = Some(4),
+ b"v3" => text_target = Some(5),
+ _ => {}
+ },
+ Event::Text(t) => {
+ if let Some(slot) = text_target {
+ let text = t.decode().unwrap_or_default();
+ let text = text.trim();
+ if slot < 3 {
+ coord[slot] = text.parse().unwrap_or(0.0);
+ } else {
+ tri[slot - 3] = text.parse().unwrap_or(0);
+ }
+ }
+ }
+ Event::End(e) => {
+ text_target = None;
+ match e.local_name().as_ref() {
+ b"coordinates" => {
+ vertices.push([
+ coord[0] * unit_scale,
+ coord[1] * unit_scale,
+ coord[2] * unit_scale,
+ ]);
+ coord = [0.0; 3];
+ }
+ b"triangle" => {
+ let t = [
+ object_base + tri[0],
+ object_base + tri[1],
+ object_base + tri[2],
+ ];
+ if t.iter().any(|&i| i >= vertices.len()) {
+ return Err(OptimizeError::new("AMF triangle index out of range"));
+ }
+ triangles.push(t);
+ tri = [0; 3];
+ }
+ _ => {}
+ }
+ }
+ Event::Eof => break,
+ _ => {}
+ }
+ buf.clear();
+ }
+ soup_to_glb(&vertices, &triangles, "AMF")
+}
+
+// ---- shared helpers ----------------------------------------------------------
+
+/// 3MF/AMF unit attribute → mm scale factor.
+fn unit_to_mm(unit: &str) -> Result<f32, OptimizeError> {
+ match unit {
+ "micron" => Ok(0.001),
+ "millimeter" => Ok(1.0),
+ "centimeter" => Ok(10.0),
+ "inch" => Ok(25.4),
+ "foot" => Ok(304.8),
+ "meter" => Ok(1000.0),
+ other => Err(OptimizeError::new(format!("unknown unit: {other}"))),
+ }
+}
+
+/// Row-major 4x3 affine (the 3MF `transform` attribute: 9 rotation/scale values
+/// then the translation row), identity when absent/malformed.
+const IDENTITY_4X3: [f32; 12] = [1., 0., 0., 0., 1., 0., 0., 0., 1., 0., 0., 0.];
+
+fn parse_3mf_transform(attr: Option<&str>) -> [f32; 12] {
+ let Some(attr) = attr else {
+ return IDENTITY_4X3;
+ };
+ let values: Vec<f32> = attr
+ .split_whitespace()
+ .filter_map(|t| t.parse().ok())
+ .collect();
+ match <[f32; 12]>::try_from(values) {
+ Ok(m) => m,
+ Err(_) => IDENTITY_4X3,
+ }
+}
+
+/// 3MF row-vector convention: p' = p·M + t.
+fn apply_4x3(m: [f32; 12], p: [f32; 3]) -> [f32; 3] {
+ [
+ p[0] * m[0] + p[1] * m[3] + p[2] * m[6] + m[9],
+ p[0] * m[1] + p[1] * m[4] + p[2] * m[7] + m[10],
+ p[0] * m[2] + p[1] * m[5] + p[2] * m[8] + m[11],
+ ]
+}
+
+/// Compose parent ∘ child for the row-vector convention (apply child first).
+fn compose_4x3(parent: [f32; 12], child: [f32; 12]) -> [f32; 12] {
+ let mut out = [0.0f32; 12];
+ for row in 0..3 {
+ for col in 0..3 {
+ out[row * 3 + col] = child[row * 3] * parent[col]
+ + child[row * 3 + 1] * parent[3 + col]
+ + child[row * 3 + 2] * parent[6 + col];
+ }
+ }
+ let t = apply_4x3(parent, [child[9], child[10], child[11]]);
+ out[9] = t[0];
+ out[10] = t[1];
+ out[11] = t[2];
+ out
+}
+
+fn fan_triangulate(face: &[usize], out: &mut Vec<[usize; 3]>) {
+ for t in 1..face.len().saturating_sub(1) {
+ out.push([face[0], face[t], face[t + 1]]);
+ }
+}
+
+fn push_face(
+ face: &[usize],
+ vertex_count: usize,
+ out: &mut Vec<[usize; 3]>,
+) -> Result<(), OptimizeError> {
+ if face.iter().any(|&i| i >= vertex_count) {
+ return Err(OptimizeError::new("PLY face index out of range"));
+ }
+ fan_triangulate(face, out);
+ Ok(())
+}
+
+/// Expand an indexed polygon soup to flat triangles with per-face normals and
+/// build the GLB (the optimiser welds it back).
+fn soup_to_glb(
+ vertices: &[[f32; 3]],
+ triangles: &[[usize; 3]],
+ what: &str,
+) -> Result<Vec<u8>, OptimizeError> {
+ if triangles.is_empty() {
+ return Err(OptimizeError::new(format!("{what} has no triangles")));
+ }
+ let mut positions = Vec::with_capacity(triangles.len() * 3);
+ let mut normals = Vec::with_capacity(triangles.len() * 3);
+ for tri in triangles {
+ let [a, b, c] = [vertices[tri[0]], vertices[tri[1]], vertices[tri[2]]];
+ let n = face_normal(a, b, c);
+ positions.extend_from_slice(&[a, b, c]);
+ normals.extend_from_slice(&[n, n, n]);
+ }
+ build_triangle_glb(&positions, &normals)
+}
+
+fn face_normal(a: [f32; 3], b: [f32; 3], c: [f32; 3]) -> [f32; 3] {
+ let u = [b[0] - a[0], b[1] - a[1], b[2] - a[2]];
+ let v = [c[0] - a[0], c[1] - a[1], c[2] - a[2]];
+ let n = [
+ u[1] * v[2] - u[2] * v[1],
+ u[2] * v[0] - u[0] * v[2],
+ u[0] * v[1] - u[1] * v[0],
+ ];
+ let len = (n[0] * n[0] + n[1] * n[1] + n[2] * n[2]).sqrt();
+ if len > 0.0 {
+ [n[0] / len, n[1] / len, n[2] / len]
+ } else {
+ [0.0, 0.0, 1.0]
+ }
+}
+
+/// Rotate a point by a quaternion (x, y, z, w).
+fn rotate(q: [f32; 4], p: [f32; 3]) -> [f32; 3] {
+ let [qx, qy, qz, qw] = q;
+ // v' = v + 2q × (q × v + w v)
+ let cx = qy * p[2] - qz * p[1] + qw * p[0];
+ let cy = qz * p[0] - qx * p[2] + qw * p[1];
+ let cz = qx * p[1] - qy * p[0] + qw * p[2];
+ [
+ p[0] + 2.0 * (qy * cz - qz * cy),
+ p[1] + 2.0 * (qz * cx - qx * cz),
+ p[2] + 2.0 * (qx * cy - qy * cx),
+ ]
+}
+
+fn ply_type_size(t: &str) -> Result<usize, OptimizeError> {
+ match t {
+ "char" | "uchar" | "int8" | "uint8" => Ok(1),
+ "short" | "ushort" | "int16" | "uint16" => Ok(2),
+ "int" | "uint" | "int32" | "uint32" | "float" | "float32" => Ok(4),
+ "double" | "float64" => Ok(8),
+ other => Err(OptimizeError::new(format!("unknown PLY type: {other}"))),
+ }
+}
+
+fn read_uint_le(bytes: &[u8], off: usize, size: usize) -> Result<u64, OptimizeError> {
+ let slice = bytes
+ .get(off..off + size)
+ .ok_or_else(|| OptimizeError::new("PLY body truncated"))?;
+ let mut value = 0u64;
+ for (i, b) in slice.iter().enumerate() {
+ value |= (*b as u64) << (8 * i);
+ }
+ Ok(value)
+}
+
+fn read_ply_vertex_ascii(
+ tokens: &[&str],
+ props: &[(String, usize)],
+) -> Result<[f32; 3], OptimizeError> {
+ let mut coord = [0.0f32; 3];
+ for (i, (name, _)) in props.iter().enumerate() {
+ let slot = match name.as_str() {
+ "x" => 0,
+ "y" => 1,
+ "z" => 2,
+ _ => continue,
+ };
+ coord[slot] = tokens
+ .get(i)
+ .and_then(|t| t.parse().ok())
+ .ok_or_else(|| OptimizeError::new("PLY vertex missing coordinate"))?;
+ }
+ Ok(coord)
+}
+
+fn find_subslice(haystack: &[u8], needle: &[u8]) -> Option<usize> {
+ haystack
+ .windows(needle.len())
+ .position(|window| window == needle)
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn tri_count(glb: &[u8]) -> usize {
+ let stats = crate::optimize_glb(glb, &crate::Options::default())
+ .expect("optimize parses ingested glb")
+ .stats;
+ stats.input_triangles
+ }
+
+ #[test]
+ fn obj_quad_fan_triangulates() {
+ let obj = b"v 0 0 0\nv 1 0 0\nv 1 1 0\nv 0 1 0\nf 1 2 3 4\n";
+ let glb = obj_to_glb(obj).unwrap();
+ assert_eq!(tri_count(&glb), 2);
+ }
+
+ #[test]
+ fn obj_negative_and_slashed_indices() {
+ let obj = b"v 0 0 0\nv 1 0 0\nv 0 1 0\nf -3/1/1 -2/2/2 -1/3/3\n";
+ let glb = obj_to_glb(obj).unwrap();
+ assert_eq!(tri_count(&glb), 1);
+ }
+
+ #[test]
+ fn off_polygon_faces() {
+ let off = b"OFF\n4 1 0\n0 0 0\n1 0 0\n1 1 0\n0 1 0\n4 0 1 2 3\n";
+ let glb = off_to_glb(off).unwrap();
+ assert_eq!(tri_count(&glb), 2);
+ }
+
+ #[test]
+ fn ply_ascii_roundtrip() {
+ let ply = b"ply\nformat ascii 1.0\nelement vertex 3\nproperty float x\nproperty float y\nproperty float z\nelement face 1\nproperty list uchar int vertex_indices\nend_header\n0 0 0\n1 0 0\n0 1 0\n3 0 1 2\n";
+ let glb = ply_to_glb(ply).unwrap();
+ assert_eq!(tri_count(&glb), 1);
+ }
+
+ #[test]
+ fn ply_binary_le_roundtrip() {
+ let mut ply: Vec<u8> = b"ply\nformat binary_little_endian 1.0\nelement vertex 3\nproperty float x\nproperty float y\nproperty float z\nelement face 1\nproperty list uchar uint vertex_indices\nend_header\n".to_vec();
+ for v in [[0f32, 0., 0.], [1., 0., 0.], [0., 1., 0.]] {
+ for c in v {
+ ply.extend_from_slice(&c.to_le_bytes());
+ }
+ }
+ ply.push(3);
+ for i in [0u32, 1, 2] {
+ ply.extend_from_slice(&i.to_le_bytes());
+ }
+ let glb = ply_to_glb(&ply).unwrap();
+ assert_eq!(tri_count(&glb), 1);
+ }
+
+ #[test]
+ fn bim_instanced_elements() {
+ let bim = serde_json::json!({
+ "schema_version": "1.1.0",
+ "meshes": [{ "mesh_id": 0,
+ "coordinates": [0,0,0, 1,0,0, 0,1,0],
+ "indices": [0,1,2] }],
+ "elements": [
+ { "mesh_id": 0, "vector": {"x":0,"y":0,"z":0},
+ "rotation": {"qx":0,"qy":0,"qz":0,"qw":1} },
+ { "mesh_id": 0, "vector": {"x":5,"y":0,"z":0},
+ "rotation": {"qx":0,"qy":0,"qz":0,"qw":1} }
+ ]
+ });
+ let glb = bim_to_glb(bim.to_string().as_bytes()).unwrap();
+ assert_eq!(tri_count(&glb), 2);
+ }
+
+ #[test]
+ fn threemf_build_item_and_component() {
+ // One triangle object; a second object referencing it as a component with
+ // a translation; the build places the second → still 1 emitted instance
+ // chain = 1 triangle from the component path.
+ let model = r#"<?xml version="1.0"?>
+<model unit="millimeter" xmlns="http://schemas.microsoft.com/3dmanufacturing/core/2015/02">
+ <resources>
+ <object id="1" type="model"><mesh>
+ <vertices><vertex x="0" y="0" z="0"/><vertex x="1" y="0" z="0"/><vertex x="0" y="1" z="0"/></vertices>
+ <triangles><triangle v1="0" v2="1" v3="2"/></triangles>
+ </mesh></object>
+ <object id="2" type="model"><components>
+ <component objectid="1" transform="1 0 0 0 1 0 0 0 1 5 0 0"/>
+ </components></object>
+ </resources>
+ <build><item objectid="2"/></build>
+</model>"#;
+ let mut zip_bytes = Vec::new();
+ {
+ let mut writer = zip::ZipWriter::new(std::io::Cursor::new(&mut zip_bytes));
+ writer
+ .start_file::<_, ()>("3D/3dmodel.model", zip::write::FileOptions::default())
+ .unwrap();
+ std::io::Write::write_all(&mut writer, model.as_bytes()).unwrap();
+ writer.finish().unwrap();
+ }
+ let glb = threemf_to_glb(&zip_bytes).unwrap();
+ assert_eq!(tri_count(&glb), 1);
+ }
+
+ #[test]
+ fn amf_plain_xml() {
+ let amf = r#"<?xml version="1.0"?>
+<amf unit="millimeter"><object id="0"><mesh>
+ <vertices>
+ <vertex><coordinates><x>0</x><y>0</y><z>0</z></coordinates></vertex>
+ <vertex><coordinates><x>1</x><y>0</y><z>0</z></coordinates></vertex>
+ <vertex><coordinates><x>0</x><y>1</y><z>0</z></coordinates></vertex>
+ </vertices>
+ <volume><triangle><v1>0</v1><v2>1</v2><v3>2</v3></triangle></volume>
+</mesh></object></amf>"#;
+ let glb = amf_to_glb(amf.as_bytes()).unwrap();
+ assert_eq!(tri_count(&glb), 1);
+ }
+
+ #[test]
+ fn rejects_empty_or_garbage() {
+ assert!(obj_to_glb(b"v 0 0 0\n").is_err());
+ assert!(off_to_glb(b"OFF\n0 0 0\n").is_err());
+ assert!(bim_to_glb(b"{}").is_err());
+ assert!(ply_to_glb(b"not a ply").is_err());
+ }
+}
diff --git a/crates/optimize/src/lib.rs b/crates/optimize/src/lib.rs
new file mode 100644
index 0000000000..71284ce706
--- /dev/null
+++ b/crates/optimize/src/lib.rs
@@ -0,0 +1,2164 @@
+//! Mesh optimisation for GLB assets. Parses a binary glTF, runs meshopt on every
+//! mesh primitive (weld/remap → vertex-cache → overdraw → vertex-fetch, plus an
+//! optional simplify ladder), and re-encodes the GLB. The node tree, materials,
+//! and `extras` (e.g. `nodeId`) are preserved verbatim — only the geometry
+//! buffers are rebuilt.
+//!
+//! Phase 1 targets geometry-only GLBs (mesh POSITION/NORMAL/TEXCOORD_0 +
+//! indices) — the converter's output and the assembly pipeline. Embedded image
+//! bufferViews are rejected with a clear error rather than silently corrupted;
+//! texture support is a later extension.
+
+use gltf::json;
+use json::validation::Checked::Valid;
+use json::validation::USize64;
+use std::borrow::Cow;
+use std::mem::size_of;
+
+mod codec;
+mod ingest;
+pub use ingest::{amf_to_glb, bim_to_glb, obj_to_glb, off_to_glb, ply_to_glb, threemf_to_glb};
+pub use codec::Codec;
+
+#[derive(Debug, Clone)]
+pub struct Options {
+ /// Transmission codec for the output buffers.
+ pub codec: Codec,
+ /// Simplify target as a fraction of the input triangle count (`None` = no
+ /// ratio target; simplification then runs only if `tolerance` is set, taking
+ /// it as far as the tolerance allows). The ladder that walks several fractions
+ /// lives in the caller; this runs a single ratio.
+ pub simplify: Option<f32>,
+ /// **The quality/perf knob.** Max simplify error in source units (mm): the
+ /// simplified surface never deviates more than this from the original.
+ /// Converted per-mesh from meshopt's normalized error via `simplify_scale`.
+ /// Larger = coarser/smaller/faster, smaller = higher precision. `None` =
+ /// ratio-only (hit the simplify target regardless of error).
+ pub tolerance: Option<f32>,
+ /// **Auto mode** — a scale-invariant normalized error budget (fraction of each
+ /// mesh's extent, e.g. `0.005` = 0.5%) used only when neither `simplify` nor
+ /// `tolerance` is given. meshopt then reduces every mesh maximally within this
+ /// bound: adaptive per-mesh (a cube stays a cube, a dense surface decimates),
+ /// scale-invariant across models. `None` = no auto simplification (lossless —
+ /// convert uses this so geometry is only welded/reordered/encoded).
+ pub auto_error: Option<f32>,
+ /// Use `simplify_sloppy` (topology-breaking, faster/smaller) instead of the
+ /// error-bounded `simplify`.
+ pub simplify_aggressive: bool,
+ /// Draco quantization bits (position, normal, texcoord) — the Draco quality/
+ /// perf knob. Fewer bits = smaller + coarser. `Codec::Draco` only.
+ pub draco_bits: (i32, i32, i32),
+ /// Quantize normals to `i16` (SHORT, normalized) — core glTF, no node
+ /// transform, halves normal bytes, visually lossless. `none`/`meshopt` codecs
+ /// (Draco quantizes via `draco_bits`). Off by default so convert stays exact.
+ pub quantize_normals: bool,
+ /// Merge a mesh's primitives that share a material (and attribute set) into
+ /// one — fewer draw calls, fewer accessors/JSON, smaller. Within a mesh only,
+ /// so node/part identity (and assembly animation) is untouched.
+ pub merge_primitives: bool,
+ pub weld: bool,
+ pub reorder: bool,
+}
+
+impl Default for Options {
+ fn default() -> Self {
+ Options {
+ codec: Codec::Meshopt,
+ simplify: None,
+ tolerance: None,
+ auto_error: None,
+ simplify_aggressive: false,
+ draco_bits: (DRACO_POS_BITS, DRACO_NORM_BITS, DRACO_UV_BITS),
+ quantize_normals: false,
+ merge_primitives: false,
+ weld: true,
+ reorder: true,
+ }
+ }
+}
+
+/// Default auto-mode error budget: 0.5% of each mesh's extent — a balanced
+/// perf/quality mix. Tunable per request; `crates/optimize` never simplifies
+/// unless the caller opts in (explicit ratio/tolerance or a non-None auto_error).
+pub const DEFAULT_AUTO_ERROR: f32 = 0.005;
+
+/// Below this triangle count auto mode skips simplification — trivial meshes
+/// aren't worth reducing and low-poly geometry risks visible artifacts.
+const AUTO_TRI_FLOOR: usize = 256;
+
+#[derive(Debug, Default, Clone)]
+pub struct Stats {
+ pub input_vertices: usize,
+ pub output_vertices: usize,
+ pub input_triangles: usize,
+ pub output_triangles: usize,
+ pub input_bytes: usize,
+ pub output_bytes: usize,
+ /// Uncompressed vertex+index size the decoder must materialise (the
+ /// "render weight"). The ladder gate bounds this — a codec shrinks download,
+ /// not what the GPU decodes back to. See PR #1092's packed-size gate.
+ pub decoded_bytes: usize,
+ pub warnings: Vec<String>,
+}
+
+#[derive(Debug)]
+pub struct Optimized {
+ pub glb: Vec<u8>,
+ pub stats: Stats,
+}
+
+#[derive(Debug)]
+pub struct OptimizeError {
+ pub message: String,
+}
+
+impl OptimizeError {
+ pub(crate) fn new(m: impl Into<String>) -> Self {
+ OptimizeError { message: m.into() }
+ }
+}
+
+impl std::fmt::Display for OptimizeError {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ write!(f, "{}", self.message)
+ }
+}
+impl std::error::Error for OptimizeError {}
+
+/// Interleaved vertex used for meshopt (pos always present; normal/uv zero-filled
+/// when the source primitive lacks them — the emitted accessors follow what was
+/// actually present, tracked per primitive).
+#[repr(C)]
+#[derive(Clone, Copy, Default, PartialEq, bytemuck::Pod, bytemuck::Zeroable)]
+struct Vertex {
+ pos: [f32; 3],
+ nrm: [f32; 3],
+ uv: [f32; 2],
+}
+
+const VSTRIDE: usize = size_of::<Vertex>(); // 32
+
+/// Optimise every mesh primitive in a GLB and re-encode. `Options::codec`
+/// chooses the output buffer encoding.
+pub fn optimize_glb(glb_bytes: &[u8], options: &Options) -> Result<Optimized, OptimizeError> {
+ let glb = gltf::binary::Glb::from_slice(glb_bytes)
+ .map_err(|e| OptimizeError::new(format!("parse GLB: {e}")))?;
+ let bin = glb
+ .bin
+ .as_deref()
+ .ok_or_else(|| OptimizeError::new("GLB has no binary chunk"))?;
+ let root: json::Root = serde_json::from_slice(&glb.json)
+ .map_err(|e| OptimizeError::new(format!("parse glTF json: {e}")))?;
+ optimize_root(root, bin, glb_bytes.len(), options)
+}
+
+/// Repack a text `.gltf` whose single buffer is an embedded base64 data URI (the
+/// Onshape export shape) into a binary `.glb`, streaming the base64 decode so a
+/// multi-GB buffer never materialises in memory. The caller then mmaps the `.glb`
+/// and runs the (bounded) [`optimize_glb`] path — a serde parse of a multi-GB
+/// glTF holds the ~1.3× base64 string plus the decoded bytes at once (~3× the
+/// file). External `.bin` references and multi-buffer glTF are not supported.
+///
+/// Two passes over the source slice (mmap-backed; the second is page-cache-warm):
+/// pass 1 copies the small structural JSON verbatim (dropping the buffer's `uri`,
+/// since a GLB embeds its buffer) and captures `byteLength`; pass 2 streams the
+/// base64 value straight into the GLB BIN chunk via a [`base64::read::DecoderReader`].
+pub fn gltf_to_glb(gltf: &[u8], out: &mut impl std::io::Write) -> Result<(), OptimizeError> {
+ gltf_to_glb_inner(gltf, out).map_err(|e| OptimizeError::new(format!("repack glTF to GLB: {e}")))
+}
+
+fn gltf_to_glb_inner(
+ gltf: &[u8],
+ out: &mut impl std::io::Write,
+) -> Result<(), Box<dyn std::error::Error>> {
+ use std::io::Cursor;
+ use struson::reader::{JsonReader, JsonStreamReader};
+ use struson::writer::{JsonStreamWriter, JsonWriter};
+
+ // Pass 1: copy the structural JSON minus the buffer's data URI, capturing the
+ // (single) buffer's declared byteLength for the BIN chunk.
+ let mut json_buf: Vec<u8> = Vec::new();
+ let byte_length: u64;
+ {
+ let mut r = JsonStreamReader::new(Cursor::new(gltf));
+ let mut w = JsonStreamWriter::new(&mut json_buf);
+ let mut found_len: Option<u64> = None;
+ r.begin_object()?;
+ w.begin_object()?;
+ while r.has_next()? {
+ let name = r.next_name_owned()?;
+ if name == "buffers" {
+ w.name("buffers")?;
+ found_len = Some(rewrite_buffers(&mut r, &mut w)?);
+ } else {
+ w.name(&name)?;
+ r.transfer_to(&mut w)?;
+ }
+ }
+ r.end_object()?;
+ w.end_object()?;
+ w.finish_document()?;
+ byte_length = found_len.ok_or("glTF has no buffers")?;
+ }
+
+ // GLB layout: 12B header + [len|"JSON"|json+space-pad] + [len|"BIN\0"|bin+zero-pad].
+ // A chunk's length field includes its 4-byte-alignment padding.
+ let json_pad = (4 - json_buf.len() % 4) % 4;
+ let json_chunk_len = json_buf.len() + json_pad;
+ let bin_len = byte_length as usize;
+ let bin_pad = (4 - bin_len % 4) % 4;
+ let bin_chunk_len = bin_len + bin_pad;
+ let total = 12 + 8 + json_chunk_len + 8 + bin_chunk_len;
+
+ out.write_all(b"glTF")?;
+ out.write_all(&2u32.to_le_bytes())?;
+ out.write_all(&u32::try_from(total)?.to_le_bytes())?;
+ out.write_all(&u32::try_from(json_chunk_len)?.to_le_bytes())?;
+ out.write_all(b"JSON")?;
+ out.write_all(&json_buf)?;
+ out.write_all(&vec![0x20u8; json_pad])?;
+ out.write_all(&u32::try_from(bin_chunk_len)?.to_le_bytes())?;
+ out.write_all(&[0x42, 0x49, 0x4E, 0x00])?; // "BIN\0"
+
+ // Pass 2: stream the base64 buffer value straight into the BIN chunk.
+ {
+ let mut r = JsonStreamReader::new(Cursor::new(gltf));
+ navigate_to_buffer0_uri(&mut r)?;
+ let mut sr = r.next_string_reader()?;
+ skip_data_uri_prefix(&mut sr)?;
+ let mut dec =
+ base64::read::DecoderReader::new(&mut sr, &base64::engine::general_purpose::STANDARD);
+ let n = std::io::copy(&mut dec, out)?;
+ drop(dec);
+ // Drain any trailing bytes so the string value is fully consumed.
+ std::io::copy(&mut sr, &mut std::io::sink())?;
+ if n != bin_len as u64 {
+ return Err(
+ format!("decoded buffer is {n}B but byteLength declares {bin_len}B").into(),
+ );
+ }
+ }
+ out.write_all(&vec![0x00u8; bin_pad])?;
+ Ok(())
+}
+
+/// Copy a glTF `buffers` array, dropping each buffer's `uri` (a GLB embeds its
+/// buffer). Rejects external `.bin` (validated in pass 2 when the URI is read) and
+/// multi-buffer glTF. Returns buffer 0's `byteLength`.
+fn rewrite_buffers(
+ r: &mut struson::reader::JsonStreamReader<std::io::Cursor<&[u8]>>,
+ w: &mut struson::writer::JsonStreamWriter<&mut Vec<u8>>,
+) -> Result<u64, Box<dyn std::error::Error>> {
+ use struson::reader::JsonReader;
+ use struson::writer::JsonWriter;
+
+ r.begin_array()?;
+ w.begin_array()?;
+ let mut count = 0u32;
+ let mut byte_length = 0u64;
+ let mut saw_uri = false;
+ while r.has_next()? {
+ count += 1;
+ if count > 1 {
+ return Err("multi-buffer glTF is not supported (single embedded buffer only)".into());
+ }
+ r.begin_object()?;
+ w.begin_object()?;
+ while r.has_next()? {
+ let key = r.next_name_owned()?;
+ match key.as_str() {
+ "uri" => {
+ // Dropped from the GLB (embedded); the bytes are streamed in pass 2.
+ r.skip_value()?;
+ saw_uri = true;
+ }
+ "byteLength" => {
+ let s = r.next_number_as_string()?;
+ byte_length = s.parse::<u64>()?;
+ w.name("byteLength")?;
+ w.number_value_from_string(&s)?;
+ }
+ other => {
+ w.name(other)?;
+ r.transfer_to(w)?;
+ }
+ }
+ }
+ r.end_object()?;
+ w.end_object()?;
+ }
+ r.end_array()?;
+ w.end_array()?;
+ if count == 0 {
+ return Err("glTF has no buffers".into());
+ }
+ if !saw_uri {
+ return Err("glTF buffer has no embedded data URI (external .bin unsupported)".into());
+ }
+ Ok(byte_length)
+}
+
+/// Walk the root object to buffer 0's `uri`, leaving the reader positioned at the
+/// (string) value ready for `next_string_reader`.
+fn navigate_to_buffer0_uri(
+ r: &mut struson::reader::JsonStreamReader<std::io::Cursor<&[u8]>>,
+) -> Result<(), Box<dyn std::error::Error>> {
+ use struson::reader::JsonReader;
+ r.begin_object()?;
+ loop {
+ if !r.has_next()? {
+ return Err("glTF buffer uri not found".into());
+ }
+ if r.next_name_owned()? == "buffers" {
+ r.begin_array()?;
+ if !r.has_next()? {
+ return Err("glTF has no buffers".into());
+ }
+ r.begin_object()?;
+ loop {
+ if !r.has_next()? {
+ return Err("glTF buffer 0 has no uri".into());
+ }
+ if r.next_name_owned()? == "uri" {
+ return Ok(());
+ }
+ r.skip_value()?;
+ }
+ }
+ r.skip_value()?;
+ }
+}
+
+/// Consume the `data:<media>;base64,` prefix of a data-URI string reader, up to and
+/// including the first `,`. Errors if it isn't a base64 data URI (e.g. external `.bin`).
+fn skip_data_uri_prefix(r: &mut impl std::io::Read) -> Result<(), Box<dyn std::error::Error>> {
+ let mut prefix = Vec::new();
+ let mut byte = [0u8; 1];
+ loop {
+ if r.read(&mut byte)? == 0 {
+ return Err("glTF buffer uri is not a base64 data URI".into());
+ }
+ if byte[0] == b',' {
+ break;
+ }
+ prefix.push(byte[0]);
+ if prefix.len() > 256 {
+ return Err("glTF buffer uri prefix is implausibly long".into());
+ }
+ }
+ let p = String::from_utf8_lossy(&prefix);
+ if !p.starts_with("data:") || !p.contains("base64") {
+ return Err(format!("glTF buffer uri is not a base64 data URI: {p:?}").into());
+ }
+ Ok(())
+}
+
+/// Optimise an already-parsed glTF (`root` + its single binary buffer). Used by
+/// `optimize_glb` after unwrapping the GLB container, and by callers that load a
+/// `.gltf` (external / embedded buffer) themselves. `input_bytes` is reported in
+/// stats as the source size.
+pub fn optimize_root(
+ mut root: json::Root,
+ bin: &[u8],
+ input_bytes: usize,
+ options: &Options,
+) -> Result<Optimized, OptimizeError> {
+ let mut stats = Stats {
+ input_bytes,
+ ..Default::default()
+ };
+
+ // Which bufferViews are referenced by mesh geometry — everything else (image
+ // data, etc.) is unsupported in Phase 1.
+ let geometry_views = geometry_buffer_views(&root);
+ for (i, _) in root.buffer_views.iter().enumerate() {
+ if !geometry_views.contains(&i) {
+ return Err(OptimizeError::new(
+ "optimize: GLB has non-geometry bufferViews (embedded images/other) — not supported yet",
+ ));
+ }
+ }
+
+ // Extract + optimise each primitive, then hand it to the codec's builder:
+ // the view builder (plain / EXT_meshopt) or the per-primitive Draco builder.
+ let draco = options.codec == Codec::Draco;
+ let mut vb = Builder {
+ quantize_normals: options.quantize_normals,
+ ..Default::default()
+ };
+ let mut db = DracoBuilder::default();
+ let mut dropped = 0usize;
+ let meshes = std::mem::take(&mut root.meshes);
+ let mut new_meshes = Vec::with_capacity(meshes.len());
+ for mut mesh in meshes {
+ let prims = std::mem::take(&mut mesh.primitives);
+ // Collect each primitive's geometry, tagged by material. With
+ // merge_primitives, same-(material, attribute-set) primitives accumulate
+ // into one group; otherwise each is its own group.
+ let mut groups: Vec<(Option<u32>, Primitive)> = Vec::with_capacity(prims.len());
+ let mut group_idx: std::collections::HashMap<(Option<u32>, bool, bool), usize> =
+ std::collections::HashMap::new();
+ for prim in &prims {
+ let ex = extract_primitive(&root, bin, prim)?;
+ stats.input_vertices += ex.count;
+ stats.input_triangles += ex.indices.len() / 3;
+ // Drop degenerate primitives before they reach the C encoders.
+ if !is_encodable(&ex) {
+ dropped += 1;
+ continue;
+ }
+ let material = prim.material.map(|m| m.value() as u32);
+ if options.merge_primitives {
+ let key = (material, ex.has_normals, ex.has_uv);
+ if let Some(&gi) = group_idx.get(&key) {
+ let g = &mut groups[gi].1;
+ let base = g.vertices.len() as u32;
+ g.vertices.extend(ex.vertices);
+ g.indices.extend(ex.indices.iter().map(|i| i + base));
+ continue;
+ }
+ group_idx.insert(key, groups.len());
+ }
+ groups.push((material, ex));
+ }
+
+ let mut kept: Vec<json::mesh::Primitive> = Vec::with_capacity(groups.len());
+ for (material, ex) in groups {
+ let opt = optimize_primitive(ex, options);
+ if opt.vertices.is_empty() || opt.indices.len() < 3 {
+ continue;
+ }
+ stats.output_vertices += opt.vertices.len();
+ stats.output_triangles += opt.indices.len() / 3;
+ // Uncompressed vertex+index footprint (the decoder's render weight).
+ stats.decoded_bytes += decoded_len(&opt);
+ let mut prim = new_primitive(material.map(json::Index::new));
+ if draco {
+ db.write_primitive(&mut prim, &opt, options.draco_bits)?;
+ } else {
+ vb.write_primitive(&mut prim, &opt);
+ }
+ kept.push(prim);
+ }
+ mesh.primitives = kept;
+ new_meshes.push(mesh);
+ }
+ root.meshes = new_meshes;
+ if dropped > 0 {
+ stats
+ .warnings
+ .push(format!("dropped {dropped} degenerate primitives"));
+ }
+
+ let out = if draco {
+ assemble_draco(root, db)?
+ } else {
+ root.accessors = vb.accessors;
+ assemble(root, vb.views, options.codec)?
+ };
+ stats.output_bytes = out.len();
+ Ok(Optimized { glb: out, stats })
+}
+
+fn decoded_len(opt: &OptimizedPrimitive) -> usize {
+ let n = opt.vertices.len();
+ let mut b = n * 12; // positions
+ if opt.has_normals {
+ b += n * 12;
+ }
+ if opt.has_uv {
+ b += n * 8;
+ }
+ b + opt.indices.len() * 4
+}
+
+// ---- extraction --------------------------------------------------------------
+
+struct Primitive {
+ vertices: Vec<Vertex>,
+ indices: Vec<u32>,
+ count: usize,
+ has_normals: bool,
+ has_uv: bool,
+}
+
+fn geometry_buffer_views(root: &json::Root) -> std::collections::HashSet<usize> {
+ let mut set = std::collections::HashSet::new();
+ let mut add = |acc_idx: usize| {
+ if let Some(a) = root.accessors.get(acc_idx) {
+ if let Some(v) = a.buffer_view {
+ set.insert(v.value());
+ }
+ }
+ };
+ for mesh in &root.meshes {
+ for p in &mesh.primitives {
+ if let Some(i) = p.indices {
+ add(i.value());
+ }
+ for (_, acc) in p.attributes.iter() {
+ add(acc.value());
+ }
+ }
+ }
+ set
+}
+
+fn extract_primitive(
+ root: &json::Root,
+ bin: &[u8],
+ prim: &json::mesh::Primitive,
+) -> Result<Primitive, OptimizeError> {
+ let pos_acc = prim
+ .attributes
+ .iter()
+ .find(|(sem, _)| matches!(sem, Valid(json::mesh::Semantic::Positions)))
+ .map(|(_, a)| a.value())
+ .ok_or_else(|| OptimizeError::new("primitive has no POSITION"))?;
+ let positions = read_vec3(root, bin, pos_acc)?;
+ let count = positions.len();
+
+ let nrm_acc = prim
+ .attributes
+ .iter()
+ .find(|(sem, _)| matches!(sem, Valid(json::mesh::Semantic::Normals)))
+ .map(|(_, a)| a.value());
+ let normals = match nrm_acc {
+ Some(a) => Some(read_vec3(root, bin, a)?),
+ None => None,
+ };
+ let uv_acc = prim
+ .attributes
+ .iter()
+ .find(|(sem, _)| matches!(sem, Valid(json::mesh::Semantic::TexCoords(0))))
+ .map(|(_, a)| a.value());
+ let uvs = match uv_acc {
+ Some(a) => Some(read_vec2(root, bin, a)?),
+ None => None,
+ };
+
+ let indices = match prim.indices {
+ Some(a) => read_indices(root, bin, a.value())?,
+ None => (0..count as u32).collect(),
+ };
+
+ let mut vertices = Vec::with_capacity(count);
+ for i in 0..count {
+ vertices.push(Vertex {
+ pos: positions[i],
+ nrm: normals.as_ref().map(|n| n[i]).unwrap_or([0.0; 3]),
+ uv: uvs.as_ref().map(|u| u[i]).unwrap_or([0.0; 2]),
+ });
+ }
+
+ Ok(Primitive {
+ vertices,
+ indices,
+ count,
+ has_normals: normals.is_some(),
+ has_uv: uvs.is_some(),
+ })
+}
+
+fn accessor_view<'a>(
+ root: &json::Root,
+ bin: &'a [u8],
+ acc_idx: usize,
+) -> Result<
+ (
+ &'a [u8],
+ usize,
+ usize,
+ json::accessor::ComponentType,
+ json::accessor::Type,
+ ),
+ OptimizeError,
+> {
+ let acc = root
+ .accessors
+ .get(acc_idx)
+ .ok_or_else(|| OptimizeError::new("accessor out of range"))?;
+ let view_idx = acc
+ .buffer_view
+ .ok_or_else(|| OptimizeError::new("accessor has no bufferView"))?
+ .value();
+ let view = root
+ .buffer_views
+ .get(view_idx)
+ .ok_or_else(|| OptimizeError::new("bufferView out of range"))?;
+ let comp = match acc.component_type {
+ Valid(c) => c.0,
+ _ => return Err(OptimizeError::new("invalid component type")),
+ };
+ let ty = match acc.type_ {
+ Valid(t) => t,
+ _ => return Err(OptimizeError::new("invalid accessor type")),
+ };
+ let view_off = view.byte_offset.map(|o| o.0 as usize).unwrap_or(0);
+ let acc_off = acc.byte_offset.map(|o| o.0 as usize).unwrap_or(0);
+ let start = view_off + acc_off;
+ let stride = view
+ .byte_stride
+ .map(|s| s.0)
+ .unwrap_or_else(|| component_size(comp) * type_components(ty));
+ Ok((bin, start, stride, comp, ty))
+}
+
+fn read_vec3(
+ root: &json::Root,
+ bin: &[u8],
+ acc_idx: usize,
+) -> Result<Vec<[f32; 3]>, OptimizeError> {
+ let (data, start, stride, comp, _) = accessor_view(root, bin, acc_idx)?;
+ if !matches!(comp, json::accessor::ComponentType::F32) {
+ return Err(OptimizeError::new("expected f32 VEC3"));
+ }
+ let count = root.accessors[acc_idx].count.0 as usize;
+ let mut out = Vec::with_capacity(count);
+ for i in 0..count {
+ let o = start + i * stride;
+ out.push([
+ read_f32(data, o)?,
+ read_f32(data, o + 4)?,
+ read_f32(data, o + 8)?,
+ ]);
+ }
+ Ok(out)
+}
+
+fn read_vec2(
+ root: &json::Root,
+ bin: &[u8],
+ acc_idx: usize,
+) -> Result<Vec<[f32; 2]>, OptimizeError> {
+ let (data, start, stride, comp, _) = accessor_view(root, bin, acc_idx)?;
+ if !matches!(comp, json::accessor::ComponentType::F32) {
+ return Err(OptimizeError::new("expected f32 VEC2"));
+ }
+ let count = root.accessors[acc_idx].count.0 as usize;
+ let mut out = Vec::with_capacity(count);
+ for i in 0..count {
+ let o = start + i * stride;
+ out.push([read_f32(data, o)?, read_f32(data, o + 4)?]);
+ }
+ Ok(out)
+}
+
+fn read_indices(root: &json::Root, bin: &[u8], acc_idx: usize) -> Result<Vec<u32>, OptimizeError> {
+ let (data, start, stride, comp, _) = accessor_view(root, bin, acc_idx)?;
+ let count = root.accessors[acc_idx].count.0 as usize;
+ let mut out = Vec::with_capacity(count);
+ for i in 0..count {
+ let o = start + i * stride;
+ use json::accessor::ComponentType;
+ let v = match comp {
+ ComponentType::U8 => {
+ *data.get(o).ok_or_else(|| OptimizeError::new("index oob"))? as u32
+ }
+ ComponentType::U16 => read_u16(data, o)? as u32,
+ ComponentType::U32 => read_u32(data, o)?,
+ _ => return Err(OptimizeError::new("unsupported index component type")),
+ };
+ out.push(v);
+ }
+ Ok(out)
+}
+
+fn read_f32(d: &[u8], o: usize) -> Result<f32, OptimizeError> {
+ let b = d
+ .get(o..o + 4)
+ .ok_or_else(|| OptimizeError::new("f32 oob"))?;
+ Ok(f32::from_le_bytes([b[0], b[1], b[2], b[3]]))
+}
+fn read_u16(d: &[u8], o: usize) -> Result<u16, OptimizeError> {
+ let b = d
+ .get(o..o + 2)
+ .ok_or_else(|| OptimizeError::new("u16 oob"))?;
+ Ok(u16::from_le_bytes([b[0], b[1]]))
+}
+fn read_u32(d: &[u8], o: usize) -> Result<u32, OptimizeError> {
+ let b = d
+ .get(o..o + 4)
+ .ok_or_else(|| OptimizeError::new("u32 oob"))?;
+ Ok(u32::from_le_bytes([b[0], b[1], b[2], b[3]]))
+}
+
+fn component_size(comp: json::accessor::ComponentType) -> usize {
+ use json::accessor::ComponentType::*;
+ match comp {
+ I8 | U8 => 1,
+ I16 | U16 => 2,
+ U32 | F32 => 4,
+ }
+}
+fn type_components(ty: json::accessor::Type) -> usize {
+ use json::accessor::Type::*;
+ match ty {
+ Scalar => 1,
+ Vec2 => 2,
+ Vec3 => 3,
+ Vec4 | Mat2 => 4,
+ Mat3 => 9,
+ Mat4 => 16,
+ }
+}
+
+// ---- optimisation ------------------------------------------------------------
+
+struct OptimizedPrimitive {
+ vertices: Vec<Vertex>,
+ indices: Vec<u32>,
+ has_normals: bool,
+ has_uv: bool,
+}
+
+/// True when a primitive has usable triangle geometry meshopt/draco can encode.
+/// A degenerate one (empty, non-triangle-count, or an index past the vertex
+/// range) would out-of-bounds-read in the C encoders → segfault; the caller
+/// drops those. Real exports (fragmented Onshape gltf) contain them.
+fn is_encodable(p: &Primitive) -> bool {
+ !p.vertices.is_empty()
+ && p.indices.len() >= 3
+ && p.indices.len() % 3 == 0
+ && p.indices
+ .iter()
+ .copied()
+ .max()
+ .is_some_and(|m| (m as usize) < p.vertices.len())
+}
+
+fn optimize_primitive(p: Primitive, opts: &Options) -> OptimizedPrimitive {
+ let mut vertices = p.vertices;
+ let mut indices = p.indices;
+
+ if opts.weld {
+ let (vcount, remap) = meshopt::generate_vertex_remap(&vertices, Some(&indices));
+ indices = meshopt::remap_index_buffer(Some(&indices), indices.len(), &remap);
+ vertices = meshopt::remap_vertex_buffer(&vertices, vcount, &remap);
+ }
+
+ // Simplify precedence:
+ // explicit `simplify` (ratio) and/or `tolerance` (absolute mm) — size- or
+ // precision-driven, honoured on any mesh (>= 1 triangle);
+ // else `auto_error` (normalized budget) — quality-driven, per-mesh adaptive,
+ // skipped below AUTO_TRI_FLOOR;
+ // else off (lossless: only weld/reorder run).
+ let explicit = opts.simplify.is_some() || opts.tolerance.is_some();
+ let run = if explicit {
+ indices.len() >= 3
+ } else if opts.auto_error.is_some() {
+ indices.len() / 3 >= AUTO_TRI_FLOOR
+ } else {
+ false
+ };
+ if run {
+ let bytes: &[u8] = bytemuck::cast_slice(&vertices);
+ if let Ok(adapter) = meshopt::VertexDataAdapter::new(bytes, VSTRIDE, 0) {
+ // Ratio sets the triangle target; 0 = "reduce as far as the error
+ // bound allows" (tolerance/auto modes).
+ let target = match opts.simplify {
+ Some(r) if r > 0.0 && r < 1.0 => {
+ (((indices.len() as f32) * r) as usize / 3).max(1) * 3
+ }
+ _ => 0,
+ };
+ // Error ceiling (meshopt's normalized units): an explicit absolute
+ // `tolerance` (mm → normalized via simplify_scale) wins; else the
+ // normalized `auto_error` when no ratio was given; else unbounded
+ // (a pure ratio hits its target regardless of error).
+ let rel_err = if let Some(mm) = opts.tolerance.filter(|&m| m > 0.0) {
+ let scale = meshopt::simplify_scale(&adapter);
+ if scale > 0.0 {
+ (mm / scale).min(1.0)
+ } else {
+ 1.0
+ }
+ } else if opts.simplify.is_none() {
+ opts.auto_error.unwrap_or(1.0)
+ } else {
+ 1.0
+ };
+ indices = if opts.simplify_aggressive {
+ meshopt::simplify_sloppy(&indices, &adapter, target, rel_err, None)
+ } else {
+ meshopt::simplify(
+ &indices,
+ &adapter,
+ target,
+ rel_err,
+ meshopt::SimplifyOptions::None,
+ None,
+ )
+ };
+ }
+ }
+
+ if opts.reorder && !indices.is_empty() {
+ meshopt::optimize_vertex_cache_in_place(&mut indices, vertices.len());
+ let bytes: &[u8] = bytemuck::cast_slice(&vertices);
+ if let Ok(adapter) = meshopt::VertexDataAdapter::new(bytes, VSTRIDE, 0) {
+ meshopt::optimize_overdraw_in_place(&mut indices, &adapter, 1.05);
+ }
+ vertices = meshopt::optimize_vertex_fetch(&mut indices, &vertices);
+ }
+
+ OptimizedPrimitive {
+ vertices,
+ indices,
+ has_normals: p.has_normals,
+ has_uv: p.has_uv,
+ }
+}
+
+// ---- STL ingest --------------------------------------------------------------
+
+/// Parse a binary or ASCII STL triangle soup into an uncompressed, weldable GLB
+/// (POSITION + per-face NORMAL + sequential indices). STL has no shared vertices
+/// or structure, so the result is a single flat mesh — the optimiser then welds,
+/// reorders, simplifies, and encodes it like any other input.
+pub fn stl_to_glb(bytes: &[u8]) -> Result<Vec<u8>, OptimizeError> {
+ let (positions, normals) = parse_stl(bytes)?;
+ if positions.is_empty() {
+ return Err(OptimizeError::new("STL has no triangles"));
+ }
+ build_triangle_glb(&positions, &normals)
+}
+
+fn parse_stl(bytes: &[u8]) -> Result<(Vec<[f32; 3]>, Vec<[f32; 3]>), OptimizeError> {
+ // Binary STL: 80-byte header, u32 triangle count, then 50 bytes/triangle. The
+ // size formula is the reliable discriminator — a binary header can itself
+ // start with "solid", so never trust that prefix over the byte math.
+ if bytes.len() >= 84 {
+ let count = u32::from_le_bytes([bytes[80], bytes[81], bytes[82], bytes[83]]) as usize;
+ if bytes.len() == 84 + count * 50 {
+ return Ok(parse_binary_stl(bytes, count));
+ }
+ }
+ parse_ascii_stl(bytes)
+}
+
+fn parse_binary_stl(bytes: &[u8], count: usize) -> (Vec<[f32; 3]>, Vec<[f32; 3]>) {
+ let f = |o: usize| f32::from_le_bytes([bytes[o], bytes[o + 1], bytes[o + 2], bytes[o + 3]]);
+ let mut positions = Vec::with_capacity(count * 3);
+ let mut normals = Vec::with_capacity(count * 3);
+ for i in 0..count {
+ let base = 84 + i * 50;
+ let normal = [f(base), f(base + 4), f(base + 8)];
+ for v in 0..3 {
+ let p = base + 12 + v * 12;
+ positions.push([f(p), f(p + 4), f(p + 8)]);
+ normals.push(normal);
+ }
+ }
+ (positions, normals)
+}
+
+fn parse_ascii_stl(bytes: &[u8]) -> Result<(Vec<[f32; 3]>, Vec<[f32; 3]>), OptimizeError> {
+ let text = std::str::from_utf8(bytes)
+ .map_err(|_| OptimizeError::new("STL is neither valid binary nor UTF-8 ASCII"))?;
+ let mut positions = Vec::new();
+ let mut normals = Vec::new();
+ let mut normal = [0.0f32; 3];
+ for line in text.lines() {
+ let line = line.trim();
+ if let Some(rest) = line.strip_prefix("facet normal ") {
+ let n: Vec<f32> = rest
+ .split_whitespace()
+ .filter_map(|t| t.parse().ok())
+ .collect();
+ normal = [
+ *n.first().unwrap_or(&0.0),
+ *n.get(1).unwrap_or(&0.0),
+ *n.get(2).unwrap_or(&0.0),
+ ];
+ } else if let Some(rest) = line.strip_prefix("vertex ") {
+ let v: Vec<f32> = rest
+ .split_whitespace()
+ .filter_map(|t| t.parse().ok())
+ .collect();
+ if v.len() >= 3 {
+ positions.push([v[0], v[1], v[2]]);
+ normals.push(normal);
+ }
+ }
+ }
+ if positions.len() % 3 != 0 {
+ return Err(OptimizeError::new("ASCII STL has an incomplete triangle"));
+ }
+ Ok((positions, normals))
+}
+
+/// Build an uncompressed GLB from a flat triangle list (3N vertices, sequential
+/// indices). `positions.len()` must equal `normals.len()` and be a multiple of 3.
+pub(crate) fn build_triangle_glb(
+ positions: &[[f32; 3]],
+ normals: &[[f32; 3]],
+) -> Result<Vec<u8>, OptimizeError> {
+ use json::accessor::{ComponentType, Type};
+
+ let count = positions.len();
+ let mut min = [f32::INFINITY; 3];
+ let mut max = [f32::NEG_INFINITY; 3];
+ for p in positions {
+ for k in 0..3 {
+ min[k] = min[k].min(p[k]);
+ max[k] = max[k].max(p[k]);
+ }
+ }
+
+ let mut blob = Vec::with_capacity(count * (12 + 12) + count * 4);
+ for p in positions {
+ for c in p {
+ blob.extend_from_slice(&c.to_le_bytes());
+ }
+ }
+ let nrm_off = blob.len();
+ for n in normals {
+ for c in n {
+ blob.extend_from_slice(&c.to_le_bytes());
+ }
+ }
+ let idx_off = blob.len();
+ for i in 0..count as u32 {
+ blob.extend_from_slice(&i.to_le_bytes());
+ }
+
+ let mut root = json::Root {
+ buffer_views: vec![
+ make_view(0, 0, nrm_off, None, json::buffer::Target::ArrayBuffer),
+ make_view(
+ 0,
+ nrm_off,
+ idx_off - nrm_off,
+ None,
+ json::buffer::Target::ArrayBuffer,
+ ),
+ make_view(
+ 0,
+ idx_off,
+ blob.len() - idx_off,
+ None,
+ json::buffer::Target::ElementArrayBuffer,
+ ),
+ ],
+ buffers: vec![make_buffer(blob.len())],
+ ..Default::default()
+ };
+
+ let pos_acc = json::Accessor {
+ buffer_view: Some(json::Index::new(0)),
+ byte_offset: Some(USize64(0)),
+ count: USize64::from(count),
+ component_type: Valid(json::accessor::GenericComponentType(ComponentType::F32)),
+ type_: Valid(Type::Vec3),
+ min: Some(serde_json::json!(min.to_vec())),
+ max: Some(serde_json::json!(max.to_vec())),
+ name: None,
+ normalized: false,
+ sparse: None,
+ extensions: Default::default(),
+ extras: Default::default(),
+ };
+ let nrm_acc = json::Accessor {
+ buffer_view: Some(json::Index::new(1)),
+ type_: Valid(Type::Vec3),
+ ..pos_acc.clone()
+ };
+ let idx_acc = json::Accessor {
+ buffer_view: Some(json::Index::new(2)),
+ byte_offset: Some(USize64(0)),
+ count: USize64::from(count),
+ component_type: Valid(json::accessor::GenericComponentType(ComponentType::U32)),
+ type_: Valid(Type::Scalar),
+ min: None,
+ max: None,
+ name: None,
+ normalized: false,
+ sparse: None,
+ extensions: Default::default(),
+ extras: Default::default(),
+ };
+ root.accessors = vec![pos_acc, nrm_acc, idx_acc];
+
+ let mut attributes = std::collections::BTreeMap::new();
+ attributes.insert(Valid(json::mesh::Semantic::Positions), json::Index::new(0));
+ attributes.insert(Valid(json::mesh::Semantic::Normals), json::Index::new(1));
+ let mut prim = new_primitive(None);
+ prim.attributes = attributes;
+ prim.indices = Some(json::Index::new(2));
+ root.meshes = vec![json::Mesh {
+ primitives: vec![prim],
+ weights: None,
+ name: None,
+ extensions: Default::default(),
+ extras: Default::default(),
+ }];
+ root.nodes = vec![json::Node {
+ mesh: Some(json::Index::new(0)),
+ ..Default::default()
+ }];
+ root.scene = Some(json::Index::new(0));
+ root.scenes = vec![json::Scene {
+ nodes: vec![json::Index::new(0)],
+ name: None,
+ extensions: Default::default(),
+ extras: Default::default(),
+ }];
+
+ let json_bytes = json::serialize::to_vec(&root)
+ .map_err(|e| OptimizeError::new(format!("serialize STL glTF: {e}")))?;
+ build_glb(json_bytes, blob)
+}
+
+// ---- rebuild -----------------------------------------------------------------
+
+/// One output bufferView's typed data, kept until assembly so the meshopt codec
+/// can encode from the correct element type.
+enum ViewData {
+ Attr3(Vec<[f32; 3]>),
+ /// Normalized `i16` VEC3 normals padded to a 4th `0` component. The accessor
+ /// stays VEC3 (reads x,y,z; the padding lane is skipped by the 8-byte
+ /// stride), but the stored element is 8 bytes — meshopt's vertex codec
+ /// requires the stride be a multiple of 4, so a bare `[i16; 3]` (6 bytes)
+ /// encodes to data the spec decoder rejects ("malformed buffer"). Still
+ /// smaller than f32 VEC3 (12 bytes) and the padding lane compresses to ~zero.
+ Attr3i16(Vec<[i16; 4]>),
+ Attr2(Vec<[f32; 2]>),
+ Idx {
+ indices: Vec<u32>,
+ vertex_count: usize,
+ },
+}
+
+impl ViewData {
+ fn raw_bytes(&self) -> Vec<u8> {
+ match self {
+ ViewData::Attr3(v) => {
+ let mut b = Vec::with_capacity(v.len() * 12);
+ for e in v {
+ for c in e {
+ b.extend_from_slice(&c.to_le_bytes());
+ }
+ }
+ b
+ }
+ ViewData::Attr3i16(v) => {
+ let mut b = Vec::with_capacity(v.len() * 8);
+ for e in v {
+ for c in e {
+ b.extend_from_slice(&c.to_le_bytes());
+ }
+ }
+ b
+ }
+ ViewData::Attr2(v) => {
+ let mut b = Vec::with_capacity(v.len() * 8);
+ for e in v {
+ for c in e {
+ b.extend_from_slice(&c.to_le_bytes());
+ }
+ }
+ b
+ }
+ ViewData::Idx { indices, .. } => {
+ let mut b = Vec::with_capacity(indices.len() * 4);
+ for &i in indices {
+ b.extend_from_slice(&i.to_le_bytes());
+ }
+ b
+ }
+ }
+ }
+ fn stride(&self) -> usize {
+ match self {
+ ViewData::Attr3(_) => 12,
+ ViewData::Attr3i16(_) => 8,
+ ViewData::Attr2(_) => 8,
+ ViewData::Idx { .. } => 4,
+ }
+ }
+ fn count(&self) -> usize {
+ match self {
+ ViewData::Attr3(v) => v.len(),
+ ViewData::Attr3i16(v) => v.len(),
+ ViewData::Attr2(v) => v.len(),
+ ViewData::Idx { indices, .. } => indices.len(),
+ }
+ }
+ fn is_index(&self) -> bool {
+ matches!(self, ViewData::Idx { .. })
+ }
+ /// EXT_meshopt_compression buffer mode.
+ fn mode(&self) -> &'static str {
+ if self.is_index() {
+ "TRIANGLES"
+ } else {
+ "ATTRIBUTES"
+ }
+ }
+ fn target(&self) -> json::buffer::Target {
+ if self.is_index() {
+ json::buffer::Target::ElementArrayBuffer
+ } else {
+ json::buffer::Target::ArrayBuffer
+ }
+ }
+ fn encode_meshopt(&self) -> Vec<u8> {
+ match self {
+ ViewData::Attr3(v) => meshopt::encode_vertex_buffer(v).unwrap_or_default(),
+ ViewData::Attr3i16(v) => meshopt::encode_vertex_buffer(v).unwrap_or_default(),
+ ViewData::Attr2(v) => meshopt::encode_vertex_buffer(v).unwrap_or_default(),
+ ViewData::Idx {
+ indices,
+ vertex_count,
+ } => meshopt::encode_index_buffer(indices, *vertex_count).unwrap_or_default(),
+ }
+ }
+}
+
+#[derive(Default)]
+struct Builder {
+ views: Vec<ViewData>,
+ accessors: Vec<json::Accessor>,
+ /// Quantize normals to `i16` (SHORT normalized) instead of f32.
+ quantize_normals: bool,
+}
+
+impl Builder {
+ fn add_view(&mut self, v: ViewData) -> usize {
+ self.views.push(v);
+ self.views.len() - 1
+ }
+
+ fn write_primitive(&mut self, prim: &mut json::mesh::Primitive, opt: &OptimizedPrimitive) {
+ use json::accessor::{ComponentType, Type};
+ let positions: Vec<[f32; 3]> = opt.vertices.iter().map(|v| v.pos).collect();
+ let mut min = [f32::INFINITY; 3];
+ let mut max = [f32::NEG_INFINITY; 3];
+ for p in &positions {
+ for k in 0..3 {
+ min[k] = min[k].min(p[k]);
+ max[k] = max[k].max(p[k]);
+ }
+ }
+ let pos_view = self.add_view(ViewData::Attr3(positions));
+ let pos_acc = self.push_accessor(
+ pos_view,
+ opt.vertices.len(),
+ ComponentType::F32,
+ Type::Vec3,
+ false,
+ Some((min, max)),
+ );
+
+ let mut attributes = std::collections::BTreeMap::new();
+ attributes.insert(
+ Valid(json::mesh::Semantic::Positions),
+ json::Index::new(pos_acc as u32),
+ );
+
+ if opt.has_normals {
+ let n = opt.vertices.len();
+ let na = if self.quantize_normals {
+ // f32 unit normal → i16 snorm (normalized), padded to a 4th `0`
+ // lane so the meshopt vertex stride is 8 (a multiple of 4, which
+ // the codec requires). Accessor is still VEC3 — it reads x,y,z and
+ // the 8-byte stride skips the padding. Core glTF, no node
+ // transform, smaller than f32, visually lossless.
+ let normals: Vec<[i16; 4]> = opt
+ .vertices
+ .iter()
+ .map(|v| {
+ [
+ meshopt::quantize_snorm(v.nrm[0], 16) as i16,
+ meshopt::quantize_snorm(v.nrm[1], 16) as i16,
+ meshopt::quantize_snorm(v.nrm[2], 16) as i16,
+ 0,
+ ]
+ })
+ .collect();
+ let nv = self.add_view(ViewData::Attr3i16(normals));
+ self.push_accessor(nv, n, ComponentType::I16, Type::Vec3, true, None)
+ } else {
+ let normals: Vec<[f32; 3]> = opt.vertices.iter().map(|v| v.nrm).collect();
+ let nv = self.add_view(ViewData::Attr3(normals));
+ self.push_accessor(nv, n, ComponentType::F32, Type::Vec3, false, None)
+ };
+ attributes.insert(
+ Valid(json::mesh::Semantic::Normals),
+ json::Index::new(na as u32),
+ );
+ }
+ if opt.has_uv {
+ let uvs: Vec<[f32; 2]> = opt.vertices.iter().map(|v| v.uv).collect();
+ let uvv = self.add_view(ViewData::Attr2(uvs));
+ let uva = self.push_accessor(
+ uvv,
+ opt.vertices.len(),
+ ComponentType::F32,
+ Type::Vec2,
+ false,
+ None,
+ );
+ attributes.insert(
+ Valid(json::mesh::Semantic::TexCoords(0)),
+ json::Index::new(uva as u32),
+ );
+ }
+
+ let iv = self.add_view(ViewData::Idx {
+ indices: opt.indices.clone(),
+ vertex_count: opt.vertices.len(),
+ });
+ let ia = self.push_accessor(
+ iv,
+ opt.indices.len(),
+ ComponentType::U32,
+ Type::Scalar,
+ false,
+ None,
+ );
+
+ prim.attributes = attributes;
+ prim.indices = Some(json::Index::new(ia as u32));
+ }
+
+ fn push_accessor(
+ &mut self,
+ view: usize,
+ count: usize,
+ comp: json::accessor::ComponentType,
+ ty: json::accessor::Type,
+ normalized: bool,
+ minmax: Option<([f32; 3], [f32; 3])>,
+ ) -> usize {
+ let (min, max) = match minmax {
+ Some((mn, mx)) => (
+ Some(serde_json::json!(mn.to_vec())),
+ Some(serde_json::json!(mx.to_vec())),
+ ),
+ None => (None, None),
+ };
+ self.accessors.push(json::Accessor {
+ buffer_view: Some(json::Index::new(view as u32)),
+ byte_offset: Some(USize64(0)),
+ count: USize64::from(count),
+ component_type: Valid(json::accessor::GenericComponentType(comp)),
+ type_: Valid(ty),
+ min,
+ max,
+ name: None,
+ normalized,
+ sparse: None,
+ extensions: Default::default(),
+ extras: Default::default(),
+ });
+ self.accessors.len() - 1
+ }
+}
+
+fn make_view(
+ buffer: u32,
+ offset: usize,
+ len: usize,
+ byte_stride: Option<usize>,
+ target: json::buffer::Target,
+) -> json::buffer::View {
+ json::buffer::View {
+ buffer: json::Index::new(buffer),
+ byte_length: USize64::from(len),
+ byte_offset: Some(USize64::from(offset)),
+ byte_stride: byte_stride.map(json::buffer::Stride),
+ target: Some(Valid(target)),
+ name: None,
+ extensions: Default::default(),
+ extras: Default::default(),
+ }
+}
+
+fn make_buffer(len: usize) -> json::Buffer {
+ json::Buffer {
+ byte_length: USize64::from(len),
+ name: None,
+ uri: None,
+ extensions: Default::default(),
+ extras: Default::default(),
+ }
+}
+
+/// A fresh triangle-list primitive with the given material; attributes/indices
+/// are filled by the codec builder.
+fn new_primitive(material: Option<json::Index<json::Material>>) -> json::mesh::Primitive {
+ json::mesh::Primitive {
+ attributes: Default::default(),
+ indices: None,
+ material,
+ mode: Valid(json::mesh::Mode::Triangles),
+ targets: None,
+ extensions: Default::default(),
+ extras: Default::default(),
+ }
+}
+
+fn build_glb(json_bytes: Vec<u8>, bin: Vec<u8>) -> Result<Vec<u8>, OptimizeError> {
+ gltf::binary::Glb {
+ header: gltf::binary::Header {
+ magic: *b"glTF",
+ version: 2,
+ length: 0,
+ },
+ json: Cow::Owned(json_bytes),
+ bin: if bin.is_empty() {
+ None
+ } else {
+ Some(Cow::Owned(bin))
+ },
+ }
+ .to_vec()
+ .map_err(|e| OptimizeError::new(format!("assemble GLB: {e}")))
+}
+
+/// Serialize `root` + geometry `views` into a GLB using the chosen codec.
+fn assemble(
+ mut root: json::Root,
+ views: Vec<ViewData>,
+ codec: Codec,
+) -> Result<Vec<u8>, OptimizeError> {
+ match codec {
+ // Draco falls back to plain in Phase 1 (crates/draco-bridge is Phase 2).
+ Codec::None | Codec::Draco => {
+ let mut blob = Vec::new();
+ let mut bvs = Vec::with_capacity(views.len());
+ for v in &views {
+ while blob.len() % 4 != 0 {
+ blob.push(0);
+ }
+ let off = blob.len();
+ let bytes = v.raw_bytes();
+ blob.extend_from_slice(&bytes);
+ bvs.push(make_view(0, off, bytes.len(), None, v.target()));
+ }
+ root.buffer_views = bvs;
+ root.buffers = if blob.is_empty() {
+ Vec::new()
+ } else {
+ vec![make_buffer(blob.len())]
+ };
+ let json_bytes = json::serialize::to_vec(&root)
+ .map_err(|e| OptimizeError::new(format!("serialize glTF json: {e}")))?;
+ build_glb(json_bytes, blob)
+ }
+ // EXT_meshopt_compression: buffer 0 is the GLB BIN holding the meshopt-
+ // encoded data; buffer 1 is a memory-only fallback the decoder writes the
+ // decompressed data into. Each geometry bufferView points at the fallback
+ // (top-level) and at the compressed data (extension). See the EXT spec.
+ Codec::Meshopt => {
+ let mut bin = Vec::new(); // buffer 0: compressed (the GLB BIN)
+ let mut fallback_len = 0usize; // buffer 1: fallback (no bytes emitted)
+ let mut bvs = Vec::with_capacity(views.len());
+ for v in &views {
+ let raw_len = v.count() * v.stride(); // decompressed footprint (no alloc)
+ while fallback_len % 4 != 0 {
+ fallback_len += 1;
+ }
+ let f_off = fallback_len;
+ fallback_len += raw_len;
+
+ let comp = v.encode_meshopt();
+ if comp.is_empty() {
+ return Err(OptimizeError::new("meshopt encode produced empty buffer"));
+ }
+ while bin.len() % 4 != 0 {
+ bin.push(0);
+ }
+ let c_off = bin.len();
+ let c_len = comp.len();
+ bin.extend_from_slice(&comp);
+
+ let byte_stride = if v.is_index() { None } else { Some(v.stride()) };
+ let mut view = make_view(1, f_off, raw_len, byte_stride, v.target());
+ // Set the EXT_meshopt_compression record directly on the typed
+ // bufferView (gltf "extensions" feature) — no whole-document Value
+ // round-trip, so memory stays flat.
+ let mut m = serde_json::Map::new();
+ m.insert(
+ "EXT_meshopt_compression".into(),
+ serde_json::json!({
+ "buffer": 0, "byteOffset": c_off, "byteLength": c_len,
+ "byteStride": v.stride(), "count": v.count(), "mode": v.mode(),
+ }),
+ );
+ view.extensions = Some(json::extensions::buffer::View { others: m });
+ bvs.push(view);
+ }
+ root.buffer_views = bvs;
+ let mut fallback = make_buffer(fallback_len);
+ let mut fm = serde_json::Map::new();
+ fm.insert(
+ "EXT_meshopt_compression".into(),
+ serde_json::json!({ "fallback": true }),
+ );
+ fallback.extensions = Some(json::extensions::buffer::Buffer { others: fm });
+ root.buffers = vec![make_buffer(bin.len()), fallback];
+ add_ext(&mut root.extensions_used, "EXT_meshopt_compression");
+ add_ext(&mut root.extensions_required, "EXT_meshopt_compression");
+
+ let json_bytes = json::serialize::to_vec(&root)
+ .map_err(|e| OptimizeError::new(format!("serialize glTF json: {e}")))?;
+ build_glb(json_bytes, bin)
+ }
+ }
+}
+
+fn add_ext(list: &mut Vec<String>, name: &str) {
+ if !list.iter().any(|e| e == name) {
+ list.push(name.to_string());
+ }
+}
+
+// ---- Draco (KHR_draco_mesh_compression) --------------------------------------
+
+// Quantization bits (gltf-transform defaults). Draco compresses by quantizing
+// attributes; the KHR_draco decoder dequantizes back to float.
+const DRACO_POS_BITS: i32 = 14;
+const DRACO_NORM_BITS: i32 = 10;
+const DRACO_UV_BITS: i32 = 12;
+
+/// Draco is per-primitive: each primitive is encoded into one draco blob, and
+/// its accessors carry type/count/min-max but no bufferView (the decoder
+/// supplies the data).
+#[derive(Default)]
+struct DracoBuilder {
+ bin: Vec<u8>,
+ buffer_views: Vec<json::buffer::View>,
+ accessors: Vec<json::Accessor>,
+}
+
+impl DracoBuilder {
+ fn write_primitive(
+ &mut self,
+ prim: &mut json::mesh::Primitive,
+ opt: &OptimizedPrimitive,
+ bits: (i32, i32, i32),
+ ) -> Result<(), OptimizeError> {
+ let n = opt.vertices.len();
+ let positions: Vec<f32> = opt.vertices.iter().flat_map(|v| v.pos).collect();
+ let mut min = [f32::INFINITY; 3];
+ let mut max = [f32::NEG_INFINITY; 3];
+ for v in &opt.vertices {
+ for k in 0..3 {
+ min[k] = min[k].min(v.pos[k]);
+ max[k] = max[k].max(v.pos[k]);
+ }
+ }
+ let normals: Vec<f32> = if opt.has_normals {
+ opt.vertices.iter().flat_map(|v| v.nrm).collect()
+ } else {
+ Vec::new()
+ };
+ let uvs: Vec<f32> = if opt.has_uv {
+ opt.vertices.iter().flat_map(|v| v.uv).collect()
+ } else {
+ Vec::new()
+ };
+
+ let enc = draco_bridge::encode_mesh(
+ &positions,
+ &normals,
+ &uvs,
+ &opt.indices,
+ bits.0,
+ bits.1,
+ bits.2,
+ );
+ if !enc.ok || enc.data.is_empty() {
+ return Err(OptimizeError::new("draco encode failed"));
+ }
+
+ while self.bin.len() % 4 != 0 {
+ self.bin.push(0);
+ }
+ let off = self.bin.len();
+ self.bin.extend_from_slice(&enc.data);
+ self.buffer_views.push(json::buffer::View {
+ buffer: json::Index::new(0),
+ byte_length: USize64::from(enc.data.len()),
+ byte_offset: Some(USize64::from(off)),
+ byte_stride: None,
+ target: None,
+ name: None,
+ extensions: Default::default(),
+ extras: Default::default(),
+ });
+ let bv = self.buffer_views.len() - 1;
+
+ let mut attributes = std::collections::BTreeMap::new();
+ let pos_acc = self.accessor_noview(
+ n,
+ json::accessor::ComponentType::F32,
+ json::accessor::Type::Vec3,
+ Some((min, max)),
+ );
+ attributes.insert(
+ Valid(json::mesh::Semantic::Positions),
+ json::Index::new(pos_acc as u32),
+ );
+ if opt.has_normals {
+ let a = self.accessor_noview(
+ n,
+ json::accessor::ComponentType::F32,
+ json::accessor::Type::Vec3,
+ None,
+ );
+ attributes.insert(
+ Valid(json::mesh::Semantic::Normals),
+ json::Index::new(a as u32),
+ );
+ }
+ if opt.has_uv {
+ let a = self.accessor_noview(
+ n,
+ json::accessor::ComponentType::F32,
+ json::accessor::Type::Vec2,
+ None,
+ );
+ attributes.insert(
+ Valid(json::mesh::Semantic::TexCoords(0)),
+ json::Index::new(a as u32),
+ );
+ }
+ let idx_acc = self.accessor_noview(
+ opt.indices.len(),
+ json::accessor::ComponentType::U32,
+ json::accessor::Type::Scalar,
+ None,
+ );
+ prim.attributes = attributes;
+ prim.indices = Some(json::Index::new(idx_acc as u32));
+
+ // Set the KHR_draco_mesh_compression record directly on the typed
+ // primitive (no whole-document Value round-trip).
+ let mut attrs = serde_json::Map::new();
+ attrs.insert("POSITION".into(), serde_json::json!(enc.pos_id));
+ if enc.norm_id >= 0 {
+ attrs.insert("NORMAL".into(), serde_json::json!(enc.norm_id));
+ }
+ if enc.uv_id >= 0 {
+ attrs.insert("TEXCOORD_0".into(), serde_json::json!(enc.uv_id));
+ }
+ let mut m = serde_json::Map::new();
+ m.insert(
+ "KHR_draco_mesh_compression".into(),
+ serde_json::json!({ "bufferView": bv, "attributes": serde_json::Value::Object(attrs) }),
+ );
+ prim.extensions = Some(json::extensions::mesh::Primitive {
+ others: m,
+ ..Default::default()
+ });
+ Ok(())
+ }
+
+ fn accessor_noview(
+ &mut self,
+ count: usize,
+ comp: json::accessor::ComponentType,
+ ty: json::accessor::Type,
+ minmax: Option<([f32; 3], [f32; 3])>,
+ ) -> usize {
+ let (min, max) = match minmax {
+ Some((mn, mx)) => (
+ Some(serde_json::json!(mn.to_vec())),
+ Some(serde_json::json!(mx.to_vec())),
+ ),
+ None => (None, None),
+ };
+ self.accessors.push(json::Accessor {
+ buffer_view: None,
+ byte_offset: None,
+ count: USize64::from(count),
+ component_type: Valid(json::accessor::GenericComponentType(comp)),
+ type_: Valid(ty),
+ min,
+ max,
+ name: None,
+ normalized: false,
+ sparse: None,
+ extensions: Default::default(),
+ extras: Default::default(),
+ });
+ self.accessors.len() - 1
+ }
+}
+
+fn assemble_draco(mut root: json::Root, db: DracoBuilder) -> Result<Vec<u8>, OptimizeError> {
+ root.accessors = db.accessors;
+ root.buffer_views = db.buffer_views;
+ root.buffers = if db.bin.is_empty() {
+ Vec::new()
+ } else {
+ vec![make_buffer(db.bin.len())]
+ };
+ add_ext(&mut root.extensions_used, "KHR_draco_mesh_compression");
+ add_ext(&mut root.extensions_required, "KHR_draco_mesh_compression");
+
+ let json_bytes = json::serialize::to_vec(&root)
+ .map_err(|e| OptimizeError::new(format!("serialize glTF json: {e}")))?;
+ build_glb(json_bytes, db.bin)
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ /// A quad as two triangles with the shared edge duplicated: 6 unindexed
+ /// vertices, 4 of them unique. Weld must collapse to 4.
+ fn quad_glb() -> Vec<u8> {
+ // A(0,0,0) B(1,0,0) C(0,1,0) D(1,1,0); tri1 A,B,C tri2 C,B,D
+ let verts: [[f32; 3]; 6] = [
+ [0.0, 0.0, 0.0],
+ [1.0, 0.0, 0.0],
+ [0.0, 1.0, 0.0],
+ [0.0, 1.0, 0.0],
+ [1.0, 0.0, 0.0],
+ [1.0, 1.0, 0.0],
+ ];
+ let indices: [u32; 6] = [0, 1, 2, 3, 4, 5];
+
+ let mut blob = Vec::new();
+ for v in &verts {
+ for c in v {
+ blob.extend_from_slice(&c.to_le_bytes());
+ }
+ }
+ let idx_off = blob.len();
+ for i in &indices {
+ blob.extend_from_slice(&i.to_le_bytes());
+ }
+
+ let pos_view = json::buffer::View {
+ buffer: json::Index::new(0),
+ byte_length: USize64::from(idx_off),
+ byte_offset: Some(USize64(0)),
+ byte_stride: None,
+ target: Some(Valid(json::buffer::Target::ArrayBuffer)),
+ name: None,
+ extensions: Default::default(),
+ extras: Default::default(),
+ };
+ let idx_view = json::buffer::View {
+ buffer: json::Index::new(0),
+ byte_length: USize64::from(blob.len() - idx_off),
+ byte_offset: Some(USize64::from(idx_off)),
+ byte_stride: None,
+ target: Some(Valid(json::buffer::Target::ElementArrayBuffer)),
+ name: None,
+ extensions: Default::default(),
+ extras: Default::default(),
+ };
+ let pos_acc = json::Accessor {
+ buffer_view: Some(json::Index::new(0)),
+ byte_offset: Some(USize64(0)),
+ count: USize64::from(6usize),
+ component_type: Valid(json::accessor::GenericComponentType(
+ json::accessor::ComponentType::F32,
+ )),
+ type_: Valid(json::accessor::Type::Vec3),
+ min: Some(serde_json::json!([0.0, 0.0, 0.0])),
+ max: Some(serde_json::json!([1.0, 1.0, 0.0])),
+ name: None,
+ normalized: false,
+ sparse: None,
+ extensions: Default::default(),
+ extras: Default::default(),
+ };
+ let idx_acc = json::Accessor {
+ buffer_view: Some(json::Index::new(1)),
+ byte_offset: Some(USize64(0)),
+ count: USize64::from(6usize),
+ component_type: Valid(json::accessor::GenericComponentType(
+ json::accessor::ComponentType::U32,
+ )),
+ type_: Valid(json::accessor::Type::Scalar),
+ min: None,
+ max: None,
+ name: None,
+ normalized: false,
+ sparse: None,
+ extensions: Default::default(),
+ extras: Default::default(),
+ };
+ let mut attributes = std::collections::BTreeMap::new();
+ attributes.insert(Valid(json::mesh::Semantic::Positions), json::Index::new(0));
+ let prim = json::mesh::Primitive {
+ attributes,
+ indices: Some(json::Index::new(1)),
+ material: None,
+ mode: Valid(json::mesh::Mode::Triangles),
+ targets: None,
+ extensions: Default::default(),
+ extras: Default::default(),
+ };
+ let root = json::Root {
+ accessors: vec![pos_acc, idx_acc],
+ buffer_views: vec![pos_view, idx_view],
+ buffers: vec![json::Buffer {
+ byte_length: USize64::from(blob.len()),
+ name: None,
+ uri: None,
+ extensions: Default::default(),
+ extras: Default::default(),
+ }],
+ meshes: vec![json::Mesh {
+ primitives: vec![prim],
+ weights: None,
+ name: None,
+ extensions: Default::default(),
+ extras: Default::default(),
+ }],
+ nodes: vec![json::Node {
+ mesh: Some(json::Index::new(0)),
+ ..Default::default()
+ }],
+ scene: Some(json::Index::new(0)),
+ scenes: vec![json::Scene {
+ nodes: vec![json::Index::new(0)],
+ name: None,
+ extensions: Default::default(),
+ extras: Default::default(),
+ }],
+ ..Default::default()
+ };
+
+ let json_bytes = json::serialize::to_vec(&root).unwrap();
+ gltf::binary::Glb {
+ header: gltf::binary::Header {
+ magic: *b"glTF",
+ version: 2,
+ length: 0,
+ },
+ json: Cow::Owned(json_bytes),
+ bin: Some(Cow::Owned(blob)),
+ }
+ .to_vec()
+ .unwrap()
+ }
+
+ /// Same quad but with a NORMAL attribute, so `quantize_normals` produces an
+ /// i16 normal view — the case that regressed the meshopt vertex stride.
+ fn quad_glb_with_normals() -> Vec<u8> {
+ let verts: [[f32; 3]; 6] = [
+ [0.0, 0.0, 0.0],
+ [1.0, 0.0, 0.0],
+ [0.0, 1.0, 0.0],
+ [0.0, 1.0, 0.0],
+ [1.0, 0.0, 0.0],
+ [1.0, 1.0, 0.0],
+ ];
+ let normals: [[f32; 3]; 6] = [[0.0, 0.0, 1.0]; 6];
+ let indices: [u32; 6] = [0, 1, 2, 3, 4, 5];
+
+ let mut blob = Vec::new();
+ for v in &verts {
+ for c in v {
+ blob.extend_from_slice(&c.to_le_bytes());
+ }
+ }
+ let nrm_off = blob.len();
+ for n in &normals {
+ for c in n {
+ blob.extend_from_slice(&c.to_le_bytes());
+ }
+ }
+ let idx_off = blob.len();
+ for i in &indices {
+ blob.extend_from_slice(&i.to_le_bytes());
+ }
+
+ let vec3 = |off: usize, len: usize| json::buffer::View {
+ buffer: json::Index::new(0),
+ byte_length: USize64::from(len),
+ byte_offset: Some(USize64::from(off)),
+ byte_stride: None,
+ target: Some(Valid(json::buffer::Target::ArrayBuffer)),
+ name: None,
+ extensions: Default::default(),
+ extras: Default::default(),
+ };
+ let pos_view = vec3(0, nrm_off);
+ let nrm_view = vec3(nrm_off, idx_off - nrm_off);
+ let idx_view = json::buffer::View {
+ buffer: json::Index::new(0),
+ byte_length: USize64::from(blob.len() - idx_off),
+ byte_offset: Some(USize64::from(idx_off)),
+ byte_stride: None,
+ target: Some(Valid(json::buffer::Target::ElementArrayBuffer)),
+ name: None,
+ extensions: Default::default(),
+ extras: Default::default(),
+ };
+ let vec3_acc = |view: u32| json::Accessor {
+ buffer_view: Some(json::Index::new(view)),
+ byte_offset: Some(USize64(0)),
+ count: USize64::from(6usize),
+ component_type: Valid(json::accessor::GenericComponentType(
+ json::accessor::ComponentType::F32,
+ )),
+ type_: Valid(json::accessor::Type::Vec3),
+ min: None,
+ max: None,
+ name: None,
+ normalized: false,
+ sparse: None,
+ extensions: Default::default(),
+ extras: Default::default(),
+ };
+ let idx_acc = json::Accessor {
+ buffer_view: Some(json::Index::new(2)),
+ byte_offset: Some(USize64(0)),
+ count: USize64::from(6usize),
+ component_type: Valid(json::accessor::GenericComponentType(
+ json::accessor::ComponentType::U32,
+ )),
+ type_: Valid(json::accessor::Type::Scalar),
+ min: None,
+ max: None,
+ name: None,
+ normalized: false,
+ sparse: None,
+ extensions: Default::default(),
+ extras: Default::default(),
+ };
+ let mut attributes = std::collections::BTreeMap::new();
+ attributes.insert(Valid(json::mesh::Semantic::Positions), json::Index::new(0));
+ attributes.insert(Valid(json::mesh::Semantic::Normals), json::Index::new(1));
+ let prim = json::mesh::Primitive {
+ attributes,
+ indices: Some(json::Index::new(2)),
+ material: None,
+ mode: Valid(json::mesh::Mode::Triangles),
+ targets: None,
+ extensions: Default::default(),
+ extras: Default::default(),
+ };
+ let root = json::Root {
+ accessors: vec![vec3_acc(0), vec3_acc(1), idx_acc],
+ buffer_views: vec![pos_view, nrm_view, idx_view],
+ buffers: vec![json::Buffer {
+ byte_length: USize64::from(blob.len()),
+ name: None,
+ uri: None,
+ extensions: Default::default(),
+ extras: Default::default(),
+ }],
+ meshes: vec![json::Mesh {
+ primitives: vec![prim],
+ weights: None,
+ name: None,
+ extensions: Default::default(),
+ extras: Default::default(),
+ }],
+ nodes: vec![json::Node {
+ mesh: Some(json::Index::new(0)),
+ ..Default::default()
+ }],
+ scene: Some(json::Index::new(0)),
+ scenes: vec![json::Scene {
+ nodes: vec![json::Index::new(0)],
+ name: None,
+ extensions: Default::default(),
+ extras: Default::default(),
+ }],
+ ..Default::default()
+ };
+ let json_bytes = json::serialize::to_vec(&root).unwrap();
+ gltf::binary::Glb {
+ header: gltf::binary::Header {
+ magic: *b"glTF",
+ version: 2,
+ length: 0,
+ },
+ json: Cow::Owned(json_bytes),
+ bin: Some(Cow::Owned(blob)),
+ }
+ .to_vec()
+ .unwrap()
+ }
+
+ #[test]
+ fn welds_duplicate_vertices_and_reparses() {
+ let glb = quad_glb();
+ let opt = optimize_glb(
+ &glb,
+ &Options {
+ codec: Codec::None,
+ ..Default::default()
+ },
+ )
+ .expect("optimize");
+ assert_eq!(opt.stats.input_vertices, 6);
+ assert_eq!(opt.stats.input_triangles, 2);
+ // Weld collapses the two duplicated corners.
+ assert_eq!(opt.stats.output_vertices, 4);
+ assert_eq!(opt.stats.output_triangles, 2);
+ // Output must be a valid GLB that round-trips through the parser.
+ let reparsed = gltf::binary::Glb::from_slice(&opt.glb).expect("reparse");
+ let root: json::Root = serde_json::from_slice(reparsed.json.as_ref()).expect("json");
+ assert_eq!(root.meshes.len(), 1);
+ assert_eq!(root.nodes.len(), 1);
+ }
+
+ #[test]
+ fn gltf_to_glb_repacks_embedded_base64() {
+ use base64::Engine as _;
+ // A known GLB → a text glTF with its buffer as a base64 data URI → repack
+ // back to GLB, streaming the base64 decode.
+ let glb = quad_glb();
+ let parsed = gltf::binary::Glb::from_slice(&glb).expect("parse glb");
+ let bin = parsed.bin.as_deref().expect("bin").to_vec();
+ let mut root: json::Root = serde_json::from_slice(parsed.json.as_ref()).expect("json");
+ let b64 = base64::engine::general_purpose::STANDARD.encode(&bin);
+ root.buffers[0].uri = Some(format!("data:application/octet-stream;base64,{b64}"));
+ let gltf_text = serde_json::to_vec(&root).expect("serialize gltf");
+
+ let mut out = Vec::new();
+ gltf_to_glb(&gltf_text, &mut out).expect("repack");
+ assert_eq!(&out[0..4], b"glTF");
+
+ // The repacked BIN chunk is byte-identical to the source buffer.
+ let re = gltf::binary::Glb::from_slice(&out).expect("parse repacked");
+ assert_eq!(&re.bin.as_deref().expect("bin")[..bin.len()], &bin[..]);
+
+ // And it optimises identically to the original GLB (weld → 4 verts).
+ let opt = optimize_glb(
+ &out,
+ &Options {
+ codec: Codec::None,
+ ..Default::default()
+ },
+ )
+ .expect("optimize repacked");
+ assert_eq!(opt.stats.input_vertices, 6);
+ assert_eq!(opt.stats.output_vertices, 4);
+ }
+
+ #[test]
+ fn gltf_to_glb_rejects_external_bin() {
+ let glb = quad_glb();
+ let parsed = gltf::binary::Glb::from_slice(&glb).unwrap();
+ let mut root: json::Root = serde_json::from_slice(parsed.json.as_ref()).unwrap();
+ root.buffers[0].uri = Some("buffer.bin".to_string()); // external, not a data URI
+ let gltf_text = serde_json::to_vec(&root).unwrap();
+
+ let mut out = Vec::new();
+ let err = gltf_to_glb(&gltf_text, &mut out).unwrap_err();
+ assert!(
+ err.message.contains("data URI"),
+ "unexpected error: {}",
+ err.message
+ );
+ }
+
+ #[test]
+ fn meshopt_codec_emits_ext_and_reparses() {
+ let glb = quad_glb();
+ let opt = optimize_glb(
+ &glb,
+ &Options {
+ codec: Codec::Meshopt,
+ ..Default::default()
+ },
+ )
+ .expect("optimize");
+ let reparsed = gltf::binary::Glb::from_slice(&opt.glb).expect("reparse");
+ let root: serde_json::Value = serde_json::from_slice(reparsed.json.as_ref()).expect("json");
+ // Extension declared + required.
+ let used = root["extensionsUsed"].as_array().expect("extensionsUsed");
+ assert!(used.iter().any(|e| e == "EXT_meshopt_compression"));
+ // Two buffers: compressed BIN + memory-only fallback.
+ let buffers = root["buffers"].as_array().expect("buffers");
+ assert_eq!(buffers.len(), 2);
+ assert_eq!(
+ buffers[1]["extensions"]["EXT_meshopt_compression"]["fallback"],
+ true
+ );
+ // Every bufferView carries a compression record pointing at buffer 0.
+ for bv in root["bufferViews"].as_array().expect("bufferViews") {
+ let ext = &bv["extensions"]["EXT_meshopt_compression"];
+ assert_eq!(ext["buffer"], 0);
+ assert!(ext["byteLength"].as_u64().unwrap() > 0);
+ assert!(ext["mode"].is_string());
+ }
+ }
+
+ #[test]
+ fn quantized_normals_keep_meshopt_stride_multiple_of_four() {
+ // Regression: i16 VEC3 normals are 6 bytes, but the meshopt vertex codec
+ // requires the stride be a multiple of 4 — a bare [i16; 3] view encodes to
+ // data the spec decoder rejects ("malformed buffer data: -2"). Every
+ // meshopt bufferView stride must be padded (normals → 8 bytes).
+ let glb = quad_glb_with_normals();
+ let opt = optimize_glb(
+ &glb,
+ &Options {
+ codec: Codec::Meshopt,
+ quantize_normals: true,
+ ..Default::default()
+ },
+ )
+ .expect("optimize");
+ let reparsed = gltf::binary::Glb::from_slice(&opt.glb).expect("reparse");
+ let root: serde_json::Value = serde_json::from_slice(reparsed.json.as_ref()).expect("json");
+ let mut saw_normal_stride_8 = false;
+ for bv in root["bufferViews"].as_array().expect("bufferViews") {
+ let ext = &bv["extensions"]["EXT_meshopt_compression"];
+ // Index views ("TRIANGLES") legitimately use a 2/4-byte element; the
+ // %4 rule is on ATTRIBUTES vertex streams.
+ if ext["mode"] == "ATTRIBUTES" {
+ let stride = ext["byteStride"].as_u64().expect("byteStride");
+ assert_eq!(stride % 4, 0, "meshopt vertex stride {stride} not %4");
+ if stride == 8 {
+ saw_normal_stride_8 = true;
+ }
+ }
+ }
+ assert!(
+ saw_normal_stride_8,
+ "expected the quantized normal view at stride 8"
+ );
+ }
+
+ #[test]
+ fn stl_binary_ingests_and_optimizes() {
+ // 1-triangle binary STL: 80-byte header, u32 count, then normal + 3 verts.
+ let mut stl = vec![0u8; 80];
+ stl.extend_from_slice(&1u32.to_le_bytes());
+ let tri: [[f32; 3]; 4] = [
+ [0.0, 0.0, 1.0], // normal
+ [0.0, 0.0, 0.0],
+ [1.0, 0.0, 0.0],
+ [0.0, 1.0, 0.0],
+ ];
+ for v in &tri {
+ for c in v {
+ stl.extend_from_slice(&c.to_le_bytes());
+ }
+ }
+ stl.extend_from_slice(&0u16.to_le_bytes()); // attribute byte count
+ assert_eq!(stl.len(), 84 + 50);
+
+ let glb = stl_to_glb(&stl).expect("stl_to_glb");
+ assert_eq!(&glb[0..4], b"glTF");
+ // Round-trips through the optimiser like any other GLB.
+ let opt = optimize_glb(
+ &glb,
+ &Options {
+ codec: Codec::Meshopt,
+ ..Default::default()
+ },
+ )
+ .expect("optimize");
+ let reparsed = gltf::binary::Glb::from_slice(&opt.glb).expect("reparse");
+ let root: serde_json::Value = serde_json::from_slice(reparsed.json.as_ref()).expect("json");
+ assert_eq!(root["meshes"].as_array().expect("meshes").len(), 1);
+ }
+
+ #[test]
+ fn stl_ascii_ingests() {
+ let ascii = "solid t\nfacet normal 0 0 1\nouter loop\nvertex 0 0 0\nvertex 1 0 0\nvertex 0 1 0\nendloop\nendfacet\nendsolid t\n";
+ let glb = stl_to_glb(ascii.as_bytes()).expect("ascii stl");
+ assert_eq!(&glb[0..4], b"glTF");
+ }
+
+ #[test]
+ fn draco_codec_emits_khr_ext_and_reparses() {
+ let glb = quad_glb();
+ let opt = optimize_glb(
+ &glb,
+ &Options {
+ codec: Codec::Draco,
+ ..Default::default()
+ },
+ )
+ .expect("optimize");
+ let reparsed = gltf::binary::Glb::from_slice(&opt.glb).expect("reparse");
+ let root: serde_json::Value = serde_json::from_slice(reparsed.json.as_ref()).expect("json");
+
+ for key in ["extensionsUsed", "extensionsRequired"] {
+ assert!(
+ root[key]
+ .as_array()
+ .expect(key)
+ .iter()
+ .any(|e| e == "KHR_draco_mesh_compression"),
+ "{key} missing KHR_draco_mesh_compression"
+ );
+ }
+ // Primitive carries the draco extension.
+ let ext = &root["meshes"][0]["primitives"][0]["extensions"]["KHR_draco_mesh_compression"];
+ assert_eq!(ext["bufferView"], 0);
+ assert_eq!(ext["attributes"]["POSITION"], 0);
+ // Draco accessors have no bufferView (decoder provides the data).
+ for acc in root["accessors"].as_array().expect("accessors") {
+ assert!(acc.get("bufferView").is_none() || acc["bufferView"].is_null());
+ }
+ // The draco blob is present as the single buffer.
+ assert_eq!(root["buffers"].as_array().expect("buffers").len(), 1);
+ }
+
+ #[test]
+ fn meshopt_roundtrip_decodes_positions() {
+ let glb = quad_glb();
+ let opt = optimize_glb(
+ &glb,
+ &Options {
+ codec: Codec::Meshopt,
+ weld: true,
+ reorder: false, // keep it simple; still exercises encode/offsets
+ ..Default::default()
+ },
+ )
+ .expect("optimize");
+ let reparsed = gltf::binary::Glb::from_slice(&opt.glb).expect("reparse");
+ let root: serde_json::Value = serde_json::from_slice(reparsed.json.as_ref()).expect("json");
+ let bin = reparsed.bin.as_deref().expect("bin");
+
+ // bufferView 0 is POSITION (first view written per primitive).
+ let ext = &root["bufferViews"][0]["extensions"]["EXT_meshopt_compression"];
+ let off = ext["byteOffset"].as_u64().unwrap() as usize;
+ let len = ext["byteLength"].as_u64().unwrap() as usize;
+ let count = ext["count"].as_u64().unwrap() as usize;
+ let decoded: Vec<[f32; 3]> =
+ meshopt::decode_vertex_buffer(&bin[off..off + len], count).expect("decode");
+ assert_eq!(decoded.len(), 4); // welded quad corners
+ // The four unit-quad corners must all be present.
+ for corner in [
+ [0.0, 0.0, 0.0],
+ [1.0, 0.0, 0.0],
+ [0.0, 1.0, 0.0],
+ [1.0, 1.0, 0.0],
+ ] {
+ assert!(
+ decoded.iter().any(|p| *p == corner),
+ "missing corner {corner:?} in {decoded:?}"
+ );
+ }
+ }
+
+ #[test]
+ fn simplify_reduces_triangles() {
+ let glb = quad_glb();
+ let opt = optimize_glb(
+ &glb,
+ &Options {
+ codec: Codec::None,
+ simplify: Some(0.5),
+ ..Default::default()
+ },
+ )
+ .expect("optimize");
+ // A 2-triangle quad can't meaningfully simplify, but it must stay valid
+ // and not grow.
+ assert!(opt.stats.output_triangles <= 2);
+ gltf::binary::Glb::from_slice(&opt.glb).expect("reparse");
+ }
+}
diff --git a/packages/auth/src/lib/supabase/client.ts b/packages/auth/src/lib/supabase/client.ts
index 92ffb3ba7a..0a687b8afd 100644
--- a/packages/auth/src/lib/supabase/client.ts
+++ b/packages/auth/src/lib/supabase/client.ts
@@ -13,7 +13,22 @@ const RETRYABLE_STATUS = new Set([500, 502, 503, 504, 512, 408, 524]);
const sleep = (ms: number) =>
new Promise<void>((resolve) => setTimeout(resolve, ms));
+// Storage object writes (uploads) must NOT go through the retry/timeout wrapper:
+// re-sending a multi-GB PUT on a 5xx is wasteful, and the 25s per-attempt timeout
+// would abort any legitimately long upload. Fail fast — pass straight through and
+// honor only the caller's own signal.
+const isStorageUpload = (input: RequestInfo | URL, init?: RequestInit) => {
+ const method = (
+ init?.method ?? (input instanceof Request ? input.method : "GET")
+ ).toUpperCase();
+ if (method !== "POST" && method !== "PUT") return false;
+ const url = input instanceof Request ? input.url : String(input);
+ return url.includes("/storage/v1/object/");
+};
+
const fetchWithRetry: typeof fetch = async (input, init) => {
+ if (isStorageUpload(input, init)) return fetch(input, init);
+
let lastError: unknown;
for (let attempt = 0; attempt <= MAX_RETRIES; attempt++) {
const timeoutSignal = AbortSignal.timeout(PER_ATTEMPT_TIMEOUT_MS);
diff --git a/packages/database/src/types.ts b/packages/database/src/types.ts
index 8a406bcbf3..d4c7513394 100644
--- a/packages/database/src/types.ts
+++ b/packages/database/src/types.ts
@@ -27526,6 +27526,12 @@ export type Database = {
id: string
modelPath: string
name: string | null
+ optimizedAt: string | null
+ optimizedModelPath: string | null
+ optimizedSize: number | null
+ optimizeError: string | null
+ optimizeStatus: Database["public"]["Enums"]["modelProcessingStatus"]
+ originalSize: number | null
processedAt: string | null
processingError: string | null
processingStatus: Database["public"]["Enums"]["modelProcessingStatus"]
@@ -27545,6 +27551,12 @@ export type Database = {
id?: string
modelPath: string
name?: string | null
+ optimizedAt?: string | null
+ optimizedModelPath?: string | null
+ optimizedSize?: number | null
+ optimizeError?: string | null
+ optimizeStatus?: Database["public"]["Enums"]["modelProcessingStatus"]
+ originalSize?: number | null
processedAt?: string | null
processingError?: string | null
processingStatus?: Database["public"]["Enums"]["modelProcessingStatus"]
@@ -27564,6 +27576,12 @@ export type Database = {
id?: string
modelPath?: string
name?: string | null
+ optimizedAt?: string | null
+ optimizedModelPath?: string | null
+ optimizedSize?: number | null
+ optimizeError?: string | null
+ optimizeStatus?: Database["public"]["Enums"]["modelProcessingStatus"]
+ originalSize?: number | null
processedAt?: string | null
processingError?: string | null
processingStatus?: Database["public"]["Enums"]["modelProcessingStatus"]
@@ -67660,21 +67678,21 @@ export type Database = {
Relationships: [
{
foreignKeyName: "address_countryCode_fkey"
- columns: ["customerCountryCode"]
+ columns: ["shipmentCountryCode"]
isOneToOne: false
referencedRelation: "country"
referencedColumns: ["alpha2"]
},
{
foreignKeyName: "address_countryCode_fkey"
- columns: ["shipmentCountryCode"]
+ columns: ["invoiceCountryCode"]
isOneToOne: false
referencedRelation: "country"
referencedColumns: ["alpha2"]
},
{
foreignKeyName: "address_countryCode_fkey"
- columns: ["invoiceCountryCode"]
+ columns: ["customerCountryCode"]
isOneToOne: false
referencedRelation: "country"
referencedColumns: ["alpha2"]
diff --git a/packages/database/supabase/config.toml b/packages/database/supabase/config.toml
index fdb8b2f0cf..ac420efc7a 100644
--- a/packages/database/supabase/config.toml
+++ b/packages/database/supabase/config.toml
@@ -68,7 +68,10 @@ port = 54324
[storage]
enabled = true
# The maximum file size allowed (e.g. "5MB", "500KB").
-file_size_limit = "50MiB"
+# Must be >= the largest app-level limit (CAD_MODEL_UPLOAD = 512MB in
+# packages/utils FILE_SIZE_LIMIT_MB); otherwise Storage 413s CAD uploads the UI
+# accepts. Per-type limits are enforced client-side and per-bucket.
+file_size_limit = "2500MB"
[auth]
enabled = true
diff --git a/packages/database/supabase/functions/lib/types.ts b/packages/database/supabase/functions/lib/types.ts
index 8a406bcbf3..d4c7513394 100644
--- a/packages/database/supabase/functions/lib/types.ts
+++ b/packages/database/supabase/functions/lib/types.ts
@@ -27526,6 +27526,12 @@ export type Database = {
id: string
modelPath: string
name: string | null
+ optimizedAt: string | null
+ optimizedModelPath: string | null
+ optimizedSize: number | null
+ optimizeError: string | null
+ optimizeStatus: Database["public"]["Enums"]["modelProcessingStatus"]
+ originalSize: number | null
processedAt: string | null
processingError: string | null
processingStatus: Database["public"]["Enums"]["modelProcessingStatus"]
@@ -27545,6 +27551,12 @@ export type Database = {
id?: string
modelPath: string
name?: string | null
+ optimizedAt?: string | null
+ optimizedModelPath?: string | null
+ optimizedSize?: number | null
+ optimizeError?: string | null
+ optimizeStatus?: Database["public"]["Enums"]["modelProcessingStatus"]
+ originalSize?: number | null
processedAt?: string | null
processingError?: string | null
processingStatus?: Database["public"]["Enums"]["modelProcessingStatus"]
@@ -27564,6 +27576,12 @@ export type Database = {
id?: string
modelPath?: string
name?: string | null
+ optimizedAt?: string | null
+ optimizedModelPath?: string | null
+ optimizedSize?: number | null
+ optimizeError?: string | null
+ optimizeStatus?: Database["public"]["Enums"]["modelProcessingStatus"]
+ originalSize?: number | null
processedAt?: string | null
processingError?: string | null
processingStatus?: Database["public"]["Enums"]["modelProcessingStatus"]
@@ -67660,21 +67678,21 @@ export type Database = {
Relationships: [
{
foreignKeyName: "address_countryCode_fkey"
- columns: ["customerCountryCode"]
+ columns: ["shipmentCountryCode"]
isOneToOne: false
referencedRelation: "country"
referencedColumns: ["alpha2"]
},
{
foreignKeyName: "address_countryCode_fkey"
- columns: ["shipmentCountryCode"]
+ columns: ["invoiceCountryCode"]
isOneToOne: false
referencedRelation: "country"
referencedColumns: ["alpha2"]
},
{
foreignKeyName: "address_countryCode_fkey"
- columns: ["invoiceCountryCode"]
+ columns: ["customerCountryCode"]
isOneToOne: false
referencedRelation: "country"
referencedColumns: ["alpha2"]
diff --git a/packages/database/supabase/migrations/20260714120000_model-optimize-artifact.sql b/packages/database/supabase/migrations/20260714120000_model-optimize-artifact.sql
new file mode 100644
index 0000000000..96db9d9204
--- /dev/null
+++ b/packages/database/supabase/migrations/20260714120000_model-optimize-artifact.sql
@@ -0,0 +1,11 @@
+-- Optimised model artifact. On upload, mesh models (STEP / glTF / GLB) are
+-- eagerly run through the assembler's /v1/optimize (merge + simplify + meshopt/
+-- Draco encode) into a compact GLB. This is separate from the assembly-convert
+-- artifact ("glbPath"): that one is lossless and feeds the animated assembly
+-- viewer; this one is the aggressively-optimised version for storage/preview.
+-- Reuses the existing "modelProcessingStatus" enum and modelUpload's RLS.
+
+ALTER TABLE "modelUpload" ADD COLUMN "optimizedModelPath" TEXT;
+ALTER TABLE "modelUpload" ADD COLUMN "optimizeStatus" "modelProcessingStatus" NOT NULL DEFAULT 'Idle';
+ALTER TABLE "modelUpload" ADD COLUMN "optimizeError" TEXT;
+ALTER TABLE "modelUpload" ADD COLUMN "optimizedAt" TIMESTAMP WITH TIME ZONE;
diff --git a/packages/database/supabase/migrations/20260714224233_model-optimized-size.sql b/packages/database/supabase/migrations/20260714224233_model-optimized-size.sql
new file mode 100644
index 0000000000..21bb0966fd
--- /dev/null
+++ b/packages/database/supabase/migrations/20260714224233_model-optimized-size.sql
@@ -0,0 +1,4 @@
+-- Persist the optimised GLB's byte size so the viewer can show the reduction
+-- (raw STEP/glTF is kept as source of truth; its "size" never shrinks). Written
+-- by the model-optimize job on success. BIGINT to match modelUpload."size".
+ALTER TABLE "modelUpload" ADD COLUMN "optimizedSize" BIGINT;
diff --git a/packages/database/supabase/migrations/20260715150742_temp-staging-bucket.sql b/packages/database/supabase/migrations/20260715150742_temp-staging-bucket.sql
new file mode 100644
index 0000000000..f30b621cc1
--- /dev/null
+++ b/packages/database/supabase/migrations/20260715150742_temp-staging-bucket.sql
@@ -0,0 +1,67 @@
+-- temp-staging bucket — raw CAD uploads that may exceed the served-bucket size
+-- cap land here first (high size limit). The optimizer reads the raw via a signed
+-- URL, writes the gated (<=50 MB) optimised GLB to `private`, then the staged raw
+-- is dropped (keep-raw-if-<=50MB happens in `private`; only genuinely-too-big raws
+-- are stage-and-dropped). Browser uploads use the normal resumable storage path —
+-- nothing streams through the assembler.
+--
+-- Design: .ai/specs/2026-07-15-assembler-model-pipeline.md (slice 2).
+-- TTL/cleanup: a scheduled job prunes staged objects older than the retention
+-- window as an orphan backstop (a failed drop-after-optimise never leaks storage);
+-- wired separately, not in this migration.
+--
+-- Limits (Supabase enforces effective = min(global FILE_SIZE_LIMIT, per-bucket);
+-- the global ceiling is set to 2.5 GB so these per-bucket caps take effect):
+-- * temp-staging = 2.5 GB — raw CAD staging
+-- * private = 50 MB — served artifacts only
+--
+-- Raw CAD uploads route to `temp-staging` (slice 2 flow-wiring, done): uploads,
+-- the optimise/assembly jobs, and the document download links all read the raw
+-- from this bucket, so a >50 MB raw no longer hits the `private` 50 MB cap.
+--
+-- CAVEAT (still pending): the lossless assembly-convert GLB (glbPath) is written
+-- to `private`, so an assembly whose GLB exceeds 50 MB will 413 until the
+-- structure-preserving assembly tier (slice 3) gates it.
+
+-- 2.5 GB per-bucket cap for raw staged CAD. Private, company-scoped by the object
+-- key's first path segment.
+INSERT INTO storage.buckets (id, name, public, file_size_limit)
+VALUES ('temp-staging', 'temp-staging', false, 2500000000);
+
+-- Served bucket holds only gated artifacts → cap at 50 MB per-bucket.
+UPDATE storage.buckets SET file_size_limit = 52428800 WHERE id = 'private';
+
+-- RLS mirrors the `private` model policies but with the current helpers
+-- (`get_companies_with_employee_role` / `_permission`, per the RLS refactor —
+-- the old `has_role`/`has_company_permission` pattern is deprecated). Scoped to
+-- the temp-staging bucket + the `${companyId}/models/...` key layout, so the same
+-- authenticated client that uploads a model can stage its raw. SELECT gates on
+-- employee role; writes gate on the parts_* permission (which already implies
+-- employee membership of that company).
+CREATE POLICY "Employees can view staged models" ON storage.objects
+FOR SELECT USING (
+ bucket_id = 'temp-staging'
+ AND (storage.foldername(name))[1] = ANY ((SELECT get_companies_with_employee_role())::text[])
+ AND (storage.foldername(name))[2] = 'models'
+);
+
+CREATE POLICY "Employees with parts_create can stage models" ON storage.objects
+FOR INSERT WITH CHECK (
+ bucket_id = 'temp-staging'
+ AND (storage.foldername(name))[1] = ANY ((SELECT get_companies_with_employee_permission('parts_create'))::text[])
+ AND (storage.foldername(name))[2] = 'models'
+);
+
+CREATE POLICY "Employees with parts_update can update staged models" ON storage.objects
+FOR UPDATE USING (
+ bucket_id = 'temp-staging'
+ AND (storage.foldername(name))[1] = ANY ((SELECT get_companies_with_employee_permission('parts_update'))::text[])
+ AND (storage.foldername(name))[2] = 'models'
+);
+
+CREATE POLICY "Employees with parts_delete can delete staged models" ON storage.objects
+FOR DELETE USING (
+ bucket_id = 'temp-staging'
+ AND (storage.foldername(name))[1] = ANY ((SELECT get_companies_with_employee_permission('parts_delete'))::text[])
+ AND (storage.foldername(name))[2] = 'models'
+);
diff --git a/packages/database/supabase/migrations/20260720094011_model-original-size.sql b/packages/database/supabase/migrations/20260720094011_model-original-size.sql
new file mode 100644
index 0000000000..a91fcd0838
--- /dev/null
+++ b/packages/database/supabase/migrations/20260720094011_model-original-size.sql
@@ -0,0 +1,7 @@
+-- Bytes of the file AS UPLOADED, frozen at upload time. "size" cannot carry
+-- this: raw compaction (model-optimize) overwrites it with the stored .zst
+-- size so file lists reflect disk usage — which silently changed the viewer's
+-- "original -> optimized" reduction badge to compare the compacted raw instead
+-- of the true original. Nullable; rows from before this column fall back to
+-- "size" in the UI.
+ALTER TABLE "modelUpload" ADD COLUMN "originalSize" BIGINT;
diff --git a/packages/dev/AGENTS.md b/packages/dev/AGENTS.md
index ebf8fda4be..af16e1ab1e 100644
--- a/packages/dev/AGENTS.md
+++ b/packages/dev/AGENTS.md
@@ -30,7 +30,7 @@ pnpm --filter @carbon/dev typecheck # tsgo --noEmit
## Key Patterns
-- **Commands**: `up`, `down` (`--purge` releases the slot), `new`, `init`, `remove`, `list`, `status`, `reset`, `migrate`, `copy` (env sync)
+- **Commands**: `up`, `down` (`--purge` releases the slot), `new`, `init`, `remove`, `list`, `status`, `reset`, `migrate`, `copy` (env sync), `reload` (`crbn reload <service...>` → `docker compose up -d --force-recreate` a subset, applying compose/`.env.local` edits without restarting the app dev servers)
- **Stack boot** (`commands/up.ts`): Docker Compose → wait Postgres → migrations → regen types → spawn apps → portless aliases
- **Provision** (`commands/init.ts`): `crbn init` provisions an already-created worktree (canonical slug + env sync + skills) to match a `crbn checkout`; shared by `new`, the bash `checkout` post-create hook, and Conductor's `setup` (`.conductor/settings.toml`). It does NOT boot the stack — `crbn up` still mints ports/`.env.local`.
- **Worktree** (`worktree.ts`): `resolveSlug()`, `canonicalSlug()` (branch-derived `<repoBase>-<branch>`), `getWorktreeRoot()`, `projectName()`, `ensureSlugAvailable()`
diff --git a/packages/dev/bin/crbn b/packages/dev/bin/crbn
index a45bcc672b..3111bc06e8 100755
--- a/packages/dev/bin/crbn
+++ b/packages/dev/bin/crbn
@@ -450,6 +450,7 @@ crbn — Carbon dev CLI
crbn reset Wipe volumes + redis, then up.
crbn status Port assignment + container health.
crbn migrate Apply DB migrations (loads .env.local).
+ crbn reload <service...> Recreate compose services (apply compose/env edits, apps untouched).
Files:
crbn copy <file...> Copy file(s) from main checkout.
@@ -480,7 +481,7 @@ case "$cmd" in
checkout)
cmd_checkout "$@"
;;
- copy|env|up|down|reset|status|migrate|new|init|list|remove|complete)
+ copy|env|up|down|reset|status|migrate|new|init|list|remove|reload|complete)
delegate_ts "$cmd" "$@"
;;
*)
diff --git a/packages/dev/docker/docker-compose.dev.yml b/packages/dev/docker/docker-compose.dev.yml
index 1162f5b26e..6cd05a5653 100644
--- a/packages/dev/docker/docker-compose.dev.yml
+++ b/packages/dev/docker/docker-compose.dev.yml
@@ -184,8 +184,14 @@ services:
deploy:
resources:
limits:
- memory: ${MEM_STORAGE:-192m}
- cpus: ${CPU_STORAGE:-0.25}
+ # GB-scale CAD: temp-staging allows 2.5 GB objects. Serving a 1.85 GB
+ # object, storage-api is CPU-bound (reads/hashes the whole file before
+ # streaming) — at the old 0.25-core limit it never produced a byte
+ # before the client timed out. Give it real cores + headroom RAM. Limits
+ # are ceilings (idle ~160 MB / ~0%), only used when serving a big file.
+ # Paired with kong `proxy_buffering off` so the response streams.
+ memory: ${MEM_STORAGE:-2g}
+ cpus: ${CPU_STORAGE:-2}
depends_on:
postgres:
condition: service_healthy
@@ -195,7 +201,11 @@ services:
POSTGREST_URL: http://postgrest:3000
PGRST_JWT_SECRET: ${SUPABASE_JWT_SECRET}
DATABASE_URL: postgres://supabase_storage_admin:postgres@postgres:5432/postgres
- FILE_SIZE_LIMIT: 52428800
+ # 2.5 GB global storage ceiling (must be >= the largest per-bucket limit;
+ # effective per-bucket = min(this, bucket limit)). Per-bucket limits then
+ # differentiate: `private` = 50 MB (served artifacts), `temp-staging` =
+ # 2.5 GB (raw CAD). Keep in sync with config.toml [storage].
+ FILE_SIZE_LIMIT: 2500000000
STORAGE_BACKEND: file
FILE_STORAGE_BACKEND_PATH: /var/lib/storage
TENANT_ID: stub
@@ -327,6 +337,11 @@ services:
KONG_DNS_ORDER: LAST,A,CNAME
KONG_PLUGINS: request-transformer,cors,key-auth,acl,basic-auth
KONG_NGINX_WORKER_PROCESSES: ${KONG_WORKERS:-1}
+ # Stream proxied responses instead of buffering them. Default nginx
+ # `proxy_buffering on` buffers the whole upstream response (to RAM then a
+ # temp file capped at 1 GB) before sending — so a >1 GB storage download
+ # (2.5 GB temp-staging cap) stalls/aborts. `off` streams upstream→client.
+ KONG_NGINX_PROXY_PROXY_BUFFERING: "off"
volumes:
- ./packages/dev/docker/kong.yml:/home/kong/kong.yml:ro
diff --git a/packages/dev/src/commands/reload.ts b/packages/dev/src/commands/reload.ts
new file mode 100644
index 0000000000..986ad752a3
--- /dev/null
+++ b/packages/dev/src/commands/reload.ts
@@ -0,0 +1,41 @@
+import { intro, log, outro, spinner } from "@clack/prompts";
+import pc from "picocolors";
+import { recreateServices } from "../services/compose.js";
+import { getWorktreeRoot, projectName, resolveSlug } from "../worktree.js";
+
+// `crbn reload <service...>` — recreate specific compose services so an edit to
+// docker-compose.dev.yml / .env.local (memory limit, env var, image, port) takes
+// effect, WITHOUT `crbn up` restarting the app dev servers. Wraps
+// `docker compose up -d --force-recreate <services>`.
+export async function reload(services: string[]) {
+ intro("Carbon · dev reload");
+
+ const names = services.filter((s) => s && !s.startsWith("-"));
+ if (names.length === 0) {
+ log.error(
+ "Usage: crbn reload <service...> (e.g. crbn reload storage kong)"
+ );
+ outro("");
+ process.exitCode = 1;
+ return;
+ }
+
+ const root = await getWorktreeRoot();
+ const slug = resolveSlug(root);
+ log.info(
+ `worktree: ${pc.cyan(slug)} project: ${pc.cyan(projectName(slug))}`
+ );
+
+ const s = spinner();
+ s.start(`Recreating ${names.map((n) => pc.cyan(n)).join(", ")}`);
+ try {
+ await recreateServices(root, slug, names);
+ s.stop(`Recreated ${names.map((n) => pc.cyan(n)).join(", ")}`);
+ outro(pc.green("Done"));
+ } catch (err) {
+ s.stop("Reload failed");
+ log.error(err instanceof Error ? err.message : String(err));
+ outro("");
+ process.exitCode = 1;
+ }
+}
diff --git a/packages/dev/src/commands/up.ts b/packages/dev/src/commands/up.ts
index ed92f59368..5f289e722f 100644
--- a/packages/dev/src/commands/up.ts
+++ b/packages/dev/src/commands/up.ts
@@ -8,6 +8,7 @@ import { currentBranch } from "../git.js";
import { onShutdown } from "../helpers.js";
import { pickApps, pickBorrowSlug } from "../prompts.js";
import {
+ assemblerDepsBuilt,
assertAssemblerDepsBuilt,
installDeps,
installSkills,
@@ -157,9 +158,19 @@ export async function up(opts: UpOpts = {}) {
const allApps = opts.all === true;
const selectedApps = appsRequested
? allApps
- ? // --all excludes the assembler: it needs a one-time native OCCT build,
- // so it stays opt-in (CARBON_DEV_APPS or an explicit pick).
- APP_CHOICES.map((c) => c.value).filter((v) => v !== "assembler")
+ ? // --all includes the assembler, but only when its one-time native OCCT
+ // build exists — otherwise skip it (with a note) rather than hard-failing
+ // the whole --all on a machine that hasn't built it. An explicit pick of
+ // the assembler still fails fast below.
+ APP_CHOICES.map((c) => c.value).filter((v) => {
+ if (v !== "assembler") return true;
+ if (assemblerDepsBuilt()) return true;
+ log.warn(
+ "assembler skipped from --all: its OCCT build isn't present " +
+ "(apps/assembler/scripts/build-occt.sh)"
+ );
+ return false;
+ })
: await pickApps()
: [];
// Fail before booting anything heavy (docker, migrations) if the assembler is
diff --git a/packages/dev/src/env.test.ts b/packages/dev/src/env.test.ts
index 373dec766c..56705296e3 100644
--- a/packages/dev/src/env.test.ts
+++ b/packages/dev/src/env.test.ts
@@ -1,5 +1,5 @@
import { describe, expect, it } from "vitest";
-import { renderEnv } from "./env.js";
+import { forcedKeys, omitForcedKeys, renderEnv } from "./env.js";
import type { JwtCreds, PortMap } from "./worktree.js";
const ports: PortMap = {
@@ -161,3 +161,35 @@ describe("renderEnv (portless enabled)", () => {
expect(out.endsWith("\n")).toBe(true);
});
});
+
+describe("#force escape hatch", () => {
+ it("collects keys marked with a trailing #force comment", () => {
+ const dotEnv = [
+ "OPENAI_API_KEY=sk-123",
+ "ASSEMBLER_SERVICE_URL=https://xxx.execute-api.us-east-1.amazonaws.com #force",
+ "ASSEMBLER_SERVICE_API_KEY=abc # FORCE",
+ "# a comment mentioning force",
+ "NOT_FORCED=1 # forceful suffix means nothing"
+ ].join("\n");
+ expect(forcedKeys(dotEnv)).toEqual(
+ new Set(["ASSEMBLER_SERVICE_URL", "ASSEMBLER_SERVICE_API_KEY"])
+ );
+ });
+
+ it("omits forced keys from the generated .env.local content", () => {
+ const dotEnv = "ASSEMBLER_SERVICE_URL=https://remote #force\n";
+ const content = [
+ "ASSEMBLER_SERVICE_URL=https://assembler.s.dev",
+ "ASSEMBLER_SERVICE_API_KEY=dev-local-key"
+ ].join("\n");
+ const out = omitForcedKeys(content, dotEnv);
+ expect(out).not.toContain("ASSEMBLER_SERVICE_URL=");
+ expect(out).toContain("ASSEMBLER_SERVICE_API_KEY=dev-local-key");
+ expect(out).toContain("omitted");
+ });
+
+ it("no markers -> content untouched", () => {
+ const content = "A=1\nB=2";
+ expect(omitForcedKeys(content, "A=1\nB=2")).toBe(content);
+ });
+});
diff --git a/packages/dev/src/env.ts b/packages/dev/src/env.ts
index 329e6ec836..a9ccad902c 100644
--- a/packages/dev/src/env.ts
+++ b/packages/dev/src/env.ts
@@ -1,4 +1,4 @@
-import { existsSync, unlinkSync, writeFileSync } from "node:fs";
+import { existsSync, readFileSync, unlinkSync, writeFileSync } from "node:fs";
import { join } from "pathe";
import { APP_CHOICES } from "./constants.js";
import { type JwtCreds, type PortMap, SHARED_REDIS_PORT } from "./worktree.js";
@@ -108,8 +108,48 @@ export function renderEnv(opts: {
return lines.join("\n");
}
+/**
+ * The `#force` escape hatch: a line in the user-owned `.env` ending with a
+ * `#force` comment pins that key — the generated `.env.local` omits it, so the
+ * `.env` value wins even though `.env.local` normally overrides `.env` (Vite
+ * load order). Survives regeneration by construction: the marker lives in
+ * `.env`, which crbn never writes. e.g. point the local stack at a remote
+ * assembler: `ASSEMBLER_SERVICE_URL=https://xxx.execute-api.… #force`
+ */
+const FORCE_MARKER = /#\s*force\s*$/i;
+const ENV_KEY = /^\s*(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*=/;
+
+export function forcedKeys(dotEnvText: string): Set<string> {
+ const keys = new Set<string>();
+ for (const line of dotEnvText.split("\n")) {
+ if (!FORCE_MARKER.test(line)) continue;
+ const key = line.match(ENV_KEY)?.[1];
+ if (key) keys.add(key);
+ }
+ return keys;
+}
+
+export function omitForcedKeys(content: string, dotEnvText: string): string {
+ const forced = forcedKeys(dotEnvText);
+ if (forced.size === 0) return content;
+ return content
+ .split("\n")
+ .map((line) => {
+ const key = line.match(ENV_KEY)?.[1];
+ return key && forced.has(key)
+ ? `# ${key} omitted — #force'd in .env`
+ : line;
+ })
+ .join("\n");
+}
+
export function writeEnv(worktreeRoot: string, content: string) {
- writeFileSync(join(worktreeRoot, ".env.local"), content);
+ const dotEnvPath = join(worktreeRoot, ".env");
+ const dotEnv = existsSync(dotEnvPath) ? readFileSync(dotEnvPath, "utf8") : "";
+ writeFileSync(
+ join(worktreeRoot, ".env.local"),
+ omitForcedKeys(content, dotEnv)
+ );
}
export function syncAppPortlessConfigs(worktreeRoot: string) {
diff --git a/packages/dev/src/main.ts b/packages/dev/src/main.ts
index 42eb6e8ced..55e382285d 100644
--- a/packages/dev/src/main.ts
+++ b/packages/dev/src/main.ts
@@ -5,6 +5,7 @@ import { initWorktree } from "./commands/init.js";
import { listWorktrees } from "./commands/list.js";
import { migrate } from "./commands/migrate.js";
import { newWorktree } from "./commands/new.js";
+import { reload } from "./commands/reload.js";
import { removeWorktreeCmd } from "./commands/remove.js";
import { reset } from "./commands/reset.js";
import { status } from "./commands/status.js";
@@ -118,6 +119,21 @@ const main = defineCommand({
meta: { description: "Show port assignment + container health" },
run: () => status()
}),
+ reload: defineCommand({
+ meta: {
+ description:
+ "Recreate specific compose services to apply docker-compose/.env.local edits (memory, env, image, ports) WITHOUT restarting the app dev servers — `crbn reload <service...>` (e.g. storage kong)"
+ },
+ args: {
+ service: {
+ type: "positional",
+ required: true,
+ description: "Service name(s) to recreate, e.g. storage kong"
+ }
+ },
+ run: ({ rawArgs }) =>
+ reload(rawArgs.filter((a) => a && !a.startsWith("-")))
+ }),
migrate: defineCommand({
meta: {
description:
diff --git a/packages/dev/src/services/apps.ts b/packages/dev/src/services/apps.ts
index 36ac838889..04271c9261 100644
--- a/packages/dev/src/services/apps.ts
+++ b/packages/dev/src/services/apps.ts
@@ -238,11 +238,19 @@ const ASSEMBLER_PREFIX = pc.yellow(pc.bold("asm | "));
* what a plain `crbn up` should do. We never auto-build it: the user runs the
* OCCT script once, then the assembler is available.
*/
-export function assertAssemblerDepsBuilt(): void {
+/** Non-throwing check: is the assembler's one-time native OCCT build present? */
+export function assemblerDepsBuilt(): boolean {
const prefix =
process.env.OCCT_PREFIX ||
join(homedir(), ".cache", "carbon-occt", "8.0.0-p1");
- if (!existsSync(prefix)) {
+ return existsSync(prefix);
+}
+
+export function assertAssemblerDepsBuilt(): void {
+ if (!assemblerDepsBuilt()) {
+ const prefix =
+ process.env.OCCT_PREFIX ||
+ join(homedir(), ".cache", "carbon-occt", "8.0.0-p1");
throw new Error(
`Assembler selected, but its OCCT dependency isn't built.\n` +
` expected: ${prefix}\n` +
@@ -272,13 +280,13 @@ export function spawnAssembler(opts: {
const appEnv = spawnAppEnv(root, "assembler");
// ASSEMBLER_DEV_MODE=true also disables TLS verification in the service, so
// portless's self-signed CA needs no extra trust wiring. Passing
- // ASSEMBLER_REDIS_URL flips the service to the stateless Redis-backed job +
+ // REDIS_URL points the service at the stateless Redis-backed job +
// result store; unset (no worktree REDIS_URL) => in-memory, single-process.
const extraEnv: NodeJS.ProcessEnv = {
- ASSEMBLER_BIND: `127.0.0.1:${port}`,
+ PORT: String(port),
ASSEMBLER_SERVICE_API_KEY: "dev-local-key",
ASSEMBLER_DEV_MODE: "true",
- ...(appEnv.REDIS_URL ? { ASSEMBLER_REDIS_URL: appEnv.REDIS_URL } : {})
+ ...(appEnv.REDIS_URL ? { REDIS_URL: appEnv.REDIS_URL } : {})
};
process.stderr.write(
`${prefix}${pc.dim(
diff --git a/packages/dev/src/services/compose.ts b/packages/dev/src/services/compose.ts
index e12eff9427..3503b241a7 100644
--- a/packages/dev/src/services/compose.ts
+++ b/packages/dev/src/services/compose.ts
@@ -83,6 +83,32 @@ export async function restartServices(
});
}
+// `docker compose up -d --force-recreate` a subset of services — reapplies
+// compose/.env.local changes (image, env, memory, ports) to just those
+// containers, leaving the rest of the stack (and the app dev servers) running.
+// Unlike `restart`, this picks up edits to the compose file.
+export async function recreateServices(
+ root: string,
+ slug: string,
+ services: string[]
+) {
+ if (services.length === 0) return;
+ await execStrict(
+ "docker",
+ devArgs(
+ root,
+ slug,
+ "--env-file",
+ ".env.local",
+ "up",
+ "-d",
+ "--force-recreate",
+ ...services
+ ),
+ root
+ );
+}
+
// Pull all images before `up -d` so `bootStack` doesn't block silently behind
// a multi-GB download. `--progress=plain` emits parseable per-line status to
// stderr (`<service> Pulling`, `<service> Pulled`); we stream the latest line
diff --git a/packages/dev/src/services/migrations.ts b/packages/dev/src/services/migrations.ts
index 09fd7c8836..d7b814b8c0 100644
--- a/packages/dev/src/services/migrations.ts
+++ b/packages/dev/src/services/migrations.ts
@@ -166,8 +166,7 @@ export async function applyMigrations(
preferLocal: true
});
if (retry.exitCode === 0) {
- const applied = /Applying migration/i.test(retry.stdout ?? "");
- return { applied };
+ return { applied: didApplyMigrations(retry) };
}
process.stderr.write(retry.stderr?.toString() ?? "");
process.stdout.write(retry.stdout?.toString() ?? "");
@@ -180,10 +179,14 @@ export async function applyMigrations(
process.stdout.write(r.stdout?.toString() ?? "");
throw new Error(`supabase ${args.join(" ")} failed (exit ${r.exitCode})`);
}
- // supabase prints "Applying migration <ts>_<name>.sql..." per applied
- // migration; absent that, the schema was already current.
- const applied = /Applying migration/i.test(r.stdout ?? "");
- return { applied };
+ return { applied: didApplyMigrations(r) };
+}
+
+// supabase prints "Applying migration <ts>_<name>.sql..." per applied
+// migration — on STDERR (stdout says "Local database is up to date." even
+// while applying), so both streams must be checked.
+function didApplyMigrations(r: { stdout?: string; stderr?: string }): boolean {
+ return /Applying migration/i.test(`${r.stderr ?? ""}\n${r.stdout ?? ""}`);
}
// Find migration versions in DB that have no corresponding local file and
diff --git a/packages/env/src/index.ts b/packages/env/src/index.ts
index 7af0581f79..70f4a5e346 100644
--- a/packages/env/src/index.ts
+++ b/packages/env/src/index.ts
@@ -198,10 +198,23 @@ export const MES_URL =
export const ASSEMBLER_SERVICE_URL = getEnv("ASSEMBLER_SERVICE_URL", {
isRequired: false
});
+// Dev-only (crbn-written): local kong port for the storage-URL rewrite in
+// internalizeStorageUrl. Unset in prod.
+export const PORT_API = getEnv("PORT_API", {
+ isRequired: false,
+ isSecret: false
+});
export const ASSEMBLER_SERVICE_API_KEY = getEnv("ASSEMBLER_SERVICE_API_KEY", {
isRequired: false,
isSecret: true
});
+// Dev-only: public tunnel origin substituted into assembler-bound storage URLs
+// when the assembler is remote (local `.dev` hosts resolve only on this
+// machine). Unset in prod/preview.
+export const ASSEMBLER_STORAGE_PUBLIC_URL = getEnv(
+ "ASSEMBLER_STORAGE_PUBLIC_URL",
+ { isRequired: false, isSecret: false }
+);
export const GOOGLE_PLACES_API_KEY = getEnv("GOOGLE_PLACES_API_KEY", {
isRequired: false
diff --git a/packages/jobs/src/inngest/functions/scheduled/cleanup.ts b/packages/jobs/src/inngest/functions/scheduled/cleanup.ts
index 7d0e23f1c5..1564f2f365 100644
--- a/packages/jobs/src/inngest/functions/scheduled/cleanup.ts
+++ b/packages/jobs/src/inngest/functions/scheduled/cleanup.ts
@@ -1,7 +1,13 @@
import { getCarbonServiceRole } from "@carbon/auth/client.server";
import { NotificationEvent } from "@carbon/notifications";
+import { MODEL_RAW_KEEP_MAX_BYTES } from "@carbon/utils";
import { inngest } from "../../client";
+// Raw CAD in `temp-staging` is transient — the optimise/assembly jobs read it,
+// then only the gated GLB is kept in `private`. Prune raws over the served cap
+// older than this so huge sources never linger; small raws stay (downloadable).
+const STAGED_RAW_TTL_DAYS = 7;
+
type NotifyEvent = {
name: "carbon/notify";
data: {
@@ -310,5 +316,54 @@ export const cleanupFunction = inngest.createFunction(
logger.info(`Cleanup tasks completed: ${new Date().toISOString()}`);
});
+
+ await step.run("prune-staged-raw-models", async () => {
+ logger.info("Pruning stale large staged raw models...");
+ const cutoff = new Date(
+ Date.now() - STAGED_RAW_TTL_DAYS * 24 * 60 * 60 * 1000
+ ).toISOString();
+
+ const stale = await serviceRole
+ .schema("storage")
+ .from("objects")
+ .select("name, metadata")
+ .eq("bucket_id", "temp-staging")
+ .lt("created_at", cutoff)
+ .limit(1000);
+
+ if (stale.error) {
+ logger.error("Error listing stale staged raws", { error: stale.error });
+ return;
+ }
+
+ // Prune only UNCOMPACTED fat raws — a successful optimise replaces its raw
+ // with a compacted `raw.<ext>.zst` (the permanent lazy-plan source, never
+ // pruned even when its compressed size still exceeds the cap). A leftover
+ // non-`.zst` raw over the cap means optimise never completed, so it's dead
+ // weight past the TTL.
+ const big = (stale.data ?? [])
+ .filter(
+ (o) =>
+ !o.name?.toLowerCase().endsWith(".zst") &&
+ Number((o.metadata as { size?: number } | null)?.size ?? 0) >
+ MODEL_RAW_KEEP_MAX_BYTES
+ )
+ .map((o) => o.name)
+ .filter((n): n is string => Boolean(n));
+
+ if (big.length === 0) {
+ logger.info("No large staged raws to prune");
+ return;
+ }
+
+ const removed = await serviceRole.storage
+ .from("temp-staging")
+ .remove(big);
+ if (removed.error) {
+ logger.error("Error pruning staged raws", { error: removed.error });
+ } else {
+ logger.info("Pruned large staged raw models", { count: big.length });
+ }
+ });
}
);
diff --git a/packages/jobs/src/inngest/functions/tasks/assembler-client.ts b/packages/jobs/src/inngest/functions/tasks/assembler-client.ts
new file mode 100644
index 0000000000..a574a012bf
--- /dev/null
+++ b/packages/jobs/src/inngest/functions/tasks/assembler-client.ts
@@ -0,0 +1,401 @@
+import { createHmac } from "node:crypto";
+import type { Json } from "@carbon/database";
+import {
+ ASSEMBLER_SERVICE_API_KEY,
+ ASSEMBLER_SERVICE_URL,
+ ASSEMBLER_STORAGE_PUBLIC_URL,
+ ERP_URL,
+ PORT_API,
+ SESSION_SECRET,
+ SUPABASE_URL
+} from "@carbon/env";
+import { NonRetriableError } from "inngest";
+
+// Shared client for the assembler service's `/v1` action-RPC API. Submit
+// creates a job (202) with upload URLs + a completion-callback URL in the
+// request; the run then waits on the callback's event, with a single late-mint
+// poll as the timeout fallback. See .ai/specs/2026-07-15-assembler-deployment.md.
+
+// Submits are short; a tight per-request timeout catches an unreachable service.
+const REQUEST_TIMEOUT_MS = 60 * 1000;
+// Bounded backoff when the service 429s (all slots busy), honoring Retry-After.
+const BUSY_RETRIES = 4;
+// GET /v1/jobs/{id}?wait=N holds the request open until the job finishes (or N
+// elapses), so completion is near-immediate and a whole job costs a handful of
+// checkpointed steps, not hundreds of short polls. Client timeout must exceed it.
+export const LONG_POLL_WAIT_S = 25;
+const LONG_POLL_TIMEOUT_MS = (LONG_POLL_WAIT_S + 10) * 1000;
+// Floor between polls — negligible when the service holds ~25s, but stops a loop
+// from hammering Inngest when a poll returns immediately (404, blip, no ?wait).
+export const POLL_GAP = "3s";
+
+export const assemblerAuthHeaders: Record<string, string> =
+ ASSEMBLER_SERVICE_API_KEY
+ ? { Authorization: `Bearer ${ASSEMBLER_SERVICE_API_KEY}` }
+ : {};
+
+/**
+ * The assembler feature flag IS the config: unset `ASSEMBLER_SERVICE_URL` means
+ * the whole pipeline is off. Gate the Inngest functions on this so triggered
+ * events skip cleanly (rows stay untouched, the viewer falls back to the raw
+ * model tier) instead of failing runs and stamping rows `Failed`.
+ */
+export function assemblerEnabled(): boolean {
+ return Boolean(ASSEMBLER_SERVICE_URL);
+}
+
+export function assemblerBaseUrl(): string {
+ if (!ASSEMBLER_SERVICE_URL) {
+ throw new Error("ASSEMBLER_SERVICE_URL is not configured");
+ }
+ return ASSEMBLER_SERVICE_URL;
+}
+
+/**
+ * Dev-only URL surgery on assembler-bound signed storage URLs. The portless
+ * `.dev` proxy exists only on this machine (/etc/hosts + local CA), so: a LOCAL
+ * assembler gets a direct `localhost:<kong>` rewrite (the proxy also times out
+ * on multi-GB transfers), and a REMOTE assembler (staging Lambda) gets the
+ * public tunnel origin when one is configured. No-op in prod/preview.
+ */
+export function internalizeStorageUrl(url: string): string {
+ if (!SUPABASE_URL) return url;
+ let publicHost: string;
+ try {
+ publicHost = new URL(SUPABASE_URL).host;
+ } catch {
+ return url;
+ }
+
+ // Which host the assembler runs on decides the rewrite. Derived from
+ // ASSEMBLER_SERVICE_URL rather than hand-editing the crbn-owned PORT_API out
+ // of .env.local (which crbn up regenerates anyway).
+ let assemblerIsLocal = true;
+ try {
+ const h = new URL(assemblerBaseUrl()).hostname;
+ assemblerIsLocal = h === "localhost" || h === "127.0.0.1";
+ } catch {
+ return url; // no/invalid assembler URL -> nothing consumes the rewrite
+ }
+
+ if (!assemblerIsLocal) {
+ if (!ASSEMBLER_STORAGE_PUBLIC_URL) return url;
+ try {
+ const parsed = new URL(url);
+ if (parsed.host !== publicHost) return url;
+ const pub = new URL(ASSEMBLER_STORAGE_PUBLIC_URL);
+ parsed.protocol = pub.protocol;
+ parsed.host = pub.host;
+ return parsed.toString();
+ } catch {
+ return url;
+ }
+ }
+
+ if (!PORT_API) return url;
+ if (!/\.dev(?::\d+)?$/.test(publicHost)) return url;
+ try {
+ const parsed = new URL(url);
+ if (parsed.host !== publicHost) return url;
+ parsed.protocol = "http:";
+ parsed.host = `localhost:${PORT_API}`;
+ return parsed.toString();
+ } catch {
+ return url;
+ }
+}
+
+type ErrorBody = { message?: string } | string | null | undefined;
+
+function errorMessage(error: ErrorBody, fallback: string): string {
+ if (typeof error === "string") return error;
+ return error?.message ?? fallback;
+}
+
+/**
+ * POST /v1/{action} to create a job, idempotent on `jobId` (sent as
+ * Idempotency-Key so a re-POST attaches to the running job). Bounded 429 backoff
+ * honoring Retry-After; a genuine outage / permanent rejection fails fast.
+ */
+export async function submitAssemblerJob(opts: {
+ action: "convert" | "optimize" | "plan" | "compact";
+ jobId: string;
+ body: unknown;
+ logger: { warn: (msg: string, meta?: unknown) => void };
+ /** Override the target base (e.g. the ECS overflow service). Default: `ASSEMBLER_SERVICE_URL`. */
+ baseUrl?: string;
+ /** Signed upload URLs handed over AT SUBMIT, so the job can finalize the
+ * moment compute ends — the Lambda worker has no instance left to poll. */
+ uploadUrls?: Record<string, string>;
+}): Promise<void> {
+ const { action, jobId, body, logger } = opts;
+ const base = opts.baseUrl ?? assemblerBaseUrl();
+ const payload = JSON.stringify(body);
+
+ for (let attempt = 0; ; attempt++) {
+ let response: Response;
+ try {
+ response = await fetch(`${base}/v1/${action}`, {
+ method: "POST",
+ headers: {
+ "Content-Type": "application/json",
+ "Idempotency-Key": jobId,
+ ...assemblerAuthHeaders,
+ ...(opts.uploadUrls && Object.keys(opts.uploadUrls).length > 0
+ ? { "X-Carbon-Upload-Urls": JSON.stringify(opts.uploadUrls) }
+ : {})
+ },
+ body: payload,
+ signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS)
+ });
+ } catch (e) {
+ const err = e as Error;
+ // A timeout may be transient (briefly saturated) — let Inngest retry.
+ // Genuine unreachability (down, DNS, TLS) is permanent — fail fast.
+ if (err.name === "TimeoutError" || err.name === "AbortError") {
+ throw new Error(
+ `Assembler service timed out after ${REQUEST_TIMEOUT_MS}ms`
+ );
+ }
+ throw new NonRetriableError(
+ `Assembler service unreachable: ${err.message}`
+ );
+ }
+
+ if (response.status === 429 && attempt < BUSY_RETRIES) {
+ const retryAfter = Number(response.headers.get("retry-after")) || 15;
+ const waitMs = Math.min(retryAfter * 1000 * (attempt + 1), 120_000);
+ logger.warn(`assembler /v1/${action} busy (429); backing off`, {
+ jobId,
+ attempt,
+ waitMs
+ });
+ await new Promise((resolve) => setTimeout(resolve, waitMs));
+ continue;
+ }
+
+ const result = (await response.json().catch(() => null)) as {
+ ok?: boolean;
+ error?: ErrorBody;
+ } | null;
+ if (!response.ok || !result?.ok) {
+ // Non-429 errors are an outage (5xx) or permanent rejection (4xx):
+ // retrying holds the job for nothing — fail fast.
+ throw new NonRetriableError(
+ errorMessage(
+ result?.error,
+ `Assembler service returned ${response.status}`
+ )
+ );
+ }
+ return;
+ }
+}
+
+export type JobResult = { result: Json; stats: Json };
+
+/**
+ * One GET /v1/jobs/{id}?wait=N poll. Mints fresh signed upload URLs (late-mint)
+ * for this poll via `mintUploadUrls` and sends them in X-Carbon-Upload-Urls, so
+ * the service PUTs finished artifacts with seconds-old tokens. Transient
+ * failures (dropped hold, 404 on a Redis-backed store, blip) read as "pending"
+ * so the caller long-polls again rather than failing the run.
+ */
+export async function pollAssemblerJobOnce(opts: {
+ jobId: string;
+ mintUploadUrls: () => Promise<Record<string, string>>;
+ /** Override the target base (e.g. the ECS overflow service). Default: `ASSEMBLER_SERVICE_URL`. */
+ baseUrl?: string;
+}): Promise<
+ | { status: "pending" }
+ | { status: "done"; result: Json; stats: Json }
+ | { status: "error"; error: string }
+> {
+ const { jobId, mintUploadUrls } = opts;
+ const base = opts.baseUrl ?? assemblerBaseUrl();
+ const uploadUrls = await mintUploadUrls();
+ const headers: Record<string, string> = {
+ ...assemblerAuthHeaders,
+ ...(Object.keys(uploadUrls).length > 0
+ ? { "X-Carbon-Upload-Urls": JSON.stringify(uploadUrls) }
+ : {})
+ };
+
+ let response: Response;
+ try {
+ response = await fetch(
+ `${base}/v1/jobs/${jobId}?wait=${LONG_POLL_WAIT_S}`,
+ {
+ headers,
+ signal: AbortSignal.timeout(LONG_POLL_TIMEOUT_MS)
+ }
+ );
+ } catch {
+ return { status: "pending" };
+ }
+ if (response.status === 404) return { status: "pending" };
+
+ const body = (await response.json().catch(() => null)) as {
+ ok?: boolean;
+ job?: {
+ status?: string;
+ result?: Json;
+ stats?: Json;
+ error?: { message?: string };
+ };
+ } | null;
+ if (!response.ok || !body?.job) {
+ throw new Error(`GET /v1/jobs returned ${response.status}`);
+ }
+ const job = body.job;
+ if (job.status === "succeeded") {
+ return {
+ status: "done",
+ result: job.result ?? null,
+ stats: job.stats ?? null
+ };
+ }
+ if (job.status === "failed") {
+ return { status: "error", error: job.error?.message ?? "Job failed" };
+ }
+ if (job.status === "canceled") {
+ return { status: "error", error: "Job canceled" };
+ }
+ return { status: "pending" };
+}
+
+// The minimal Inngest step surface the router needs; keeps this module free of a
+// version-pinned Inngest type import while staying structurally compatible with
+// the real `step` tools. `run` returns `any` because Inngest wraps the result in
+// `Jsonify<T>` (not a bare `T`) — call sites annotate the awaited value.
+type StepTools = {
+ run: (id: string, fn: () => unknown) => Promise<any>;
+ sleep: (id: string, duration: string | number) => Promise<unknown>;
+ waitForEvent: (
+ id: string,
+ opts: { event: string; timeout: string | number; if?: string }
+ ) => Promise<any | null>;
+};
+
+type PollOutcome = Awaited<ReturnType<typeof pollAssemblerJobOnce>>;
+
+type AssemblerLogger = {
+ warn: (msg: string, meta?: unknown) => void;
+ info: (msg: string, meta?: unknown) => void;
+};
+
+type AssemblerJobSpec = {
+ /** Namespaces this job's Inngest step ids (a caller may run several). */
+ idPrefix: string;
+ action: "convert" | "optimize" | "plan" | "compact";
+ jobId: string;
+ /** Build the request body (signs a fresh source URL) — run inside a step. */
+ buildBody: () => Promise<unknown>;
+ /** Mint fresh signed upload URLs for the completion artifacts (late-mint). */
+ mintUploadUrls: () => Promise<Record<string, string>>;
+ maxWaitMs: number;
+ logger: AssemblerLogger;
+};
+
+/** Mirrors `assemblerCallbackToken` in the ERP callback route — both sides
+ * derive the per-job token from SESSION_SECRET so no state is stored. */
+function callbackToken(jobId: string): string {
+ return createHmac("sha256", SESSION_SECRET ?? "")
+ .update(`assembler-callback:${jobId}`)
+ .digest("hex");
+}
+
+/** The completion-webhook URL minted into the job spec at submit. */
+function callbackUrl(jobId: string): string {
+ return `${ERP_URL}/api/assembler/callback?token=${callbackToken(jobId)}`;
+}
+
+/**
+ * Run an assembler action to completion — event-driven: submit (with upload
+ * URLs + a minted callback URL) -> waitForEvent on the callback's event ->
+ * on timeout, ONE late-mint poll (covers a lost callback and drains any
+ * still-pending upload with fresh URLs). Returns terminal `{ result, stats }`;
+ * throws on job error / timeout.
+ */
+export async function runAssemblerJob(
+ step: StepTools,
+ spec: AssemblerJobSpec,
+ baseUrl?: string
+): Promise<{ result: Json; stats: Json }> {
+ const {
+ idPrefix,
+ action,
+ jobId,
+ buildBody,
+ mintUploadUrls,
+ maxWaitMs,
+ logger
+ } = spec;
+
+ await step.run(`${idPrefix}-submit`, async () => {
+ const [body, uploadUrls] = await Promise.all([
+ buildBody(),
+ mintUploadUrls()
+ ]);
+ await submitAssemblerJob({
+ action,
+ jobId,
+ body: {
+ ...(body as Record<string, unknown>),
+ callback_url: callbackUrl(jobId)
+ },
+ logger,
+ baseUrl,
+ uploadUrls
+ });
+ });
+
+ const done = await step.waitForEvent(`${idPrefix}-wait`, {
+ event: "carbon/assembler-job-done",
+ timeout: maxWaitMs,
+ if: `async.data.jobId == "${jobId}"`
+ });
+
+ if (done) {
+ const data = (
+ done as {
+ data?: {
+ status?: string;
+ result?: Json;
+ stats?: Json;
+ error?: { message?: string } | null;
+ };
+ }
+ ).data;
+ if (data?.status === "succeeded") {
+ return { result: data.result ?? null, stats: data.stats ?? null };
+ }
+ // A user cancel is intentional — retrying would resurrect the canceled job.
+ if (data?.status === "canceled") {
+ throw new NonRetriableError(`assembler ${action} canceled`);
+ }
+ throw new Error(
+ data?.error?.message ?? `assembler ${action} ${data?.status ?? "failed"}`
+ );
+ }
+
+ // Timeout: the callback was lost (worker couldn't reach the app, or the job
+ // is genuinely still running/stuck). One late-mint poll resolves from the
+ // store — and finalizes any parked upload with fresh URLs.
+ logger.warn(`assembler ${action} completion event timed out; polling once`, {
+ jobId
+ });
+ const poll: PollOutcome = await step.run(`${idPrefix}-fallback-poll`, () =>
+ pollAssemblerJobOnce({ jobId, mintUploadUrls, baseUrl })
+ );
+ if (poll.status === "done") {
+ return { result: poll.result, stats: poll.stats };
+ }
+ if (poll.status === "error") {
+ if (poll.error === "Job canceled") {
+ throw new NonRetriableError(`assembler ${action} canceled`);
+ }
+ throw new Error(poll.error);
+ }
+ throw new Error(`assembler ${action} did not finish within ${maxWaitMs}ms`);
+}
diff --git a/packages/jobs/src/inngest/functions/tasks/assembly-convert.ts b/packages/jobs/src/inngest/functions/tasks/assembly-convert.ts
index 0d0ff53bfc..e7654c9791 100644
--- a/packages/jobs/src/inngest/functions/tasks/assembly-convert.ts
+++ b/packages/jobs/src/inngest/functions/tasks/assembly-convert.ts
@@ -1,28 +1,31 @@
import { getCarbonServiceRole } from "@carbon/auth/client.server";
import type { Json } from "@carbon/database";
-import { ASSEMBLER_SERVICE_API_KEY, ASSEMBLER_SERVICE_URL } from "@carbon/env";
-import { NonRetriableError } from "inngest";
import { inngest } from "../../client";
-
-const SIGNED_URL_EXPIRY = 60 * 60; // seconds
-// Conversion is synchronous on the service — the request stays open for the
-// whole run. A generous cap turns a wedged convert into a fast Inngest retry
-// instead of a hung step.
-const CONVERT_TIMEOUT_MS = 5 * 60 * 1000;
-// Bounded backoff when the service 429s (all slots busy), honoring Retry-After.
-const BUSY_RETRIES = 4;
+import {
+ assemblerEnabled,
+ internalizeStorageUrl,
+ runAssemblerJob
+} from "./assembler-client";
+
+const SIGNED_URL_EXPIRY = 60 * 60; // seconds — the source (read) URL only.
+// Total wall-clock budget before giving up, bounded by time (not a poll count)
+// so it holds whether the service long-polls or returns immediately. Convert is
+// far faster than plan, but the job model long-polls the same way.
+const MAX_CONVERT_WAIT_MS = 10 * 60 * 1000;
/**
- * Converts an uploaded CAD model (STEP) into web artifacts via the geometry
- * service: a meshopt-compressed GLB and an assembly graph JSON. See
- * docs/specs/animated-work-instructions-contracts.md for the API contract.
+ * Converts an uploaded CAD model (STEP) into web artifacts via the assembler
+ * service: a meshopt-optimised GLB and an assembly graph JSON. Async job model:
+ * create → long-poll GET /v1/jobs/{id} → the service late-mint uploads both
+ * artifacts to signed URLs handed over on each poll. See
+ * .ai/specs/2026-07-04-animated-work-instructions-contracts.md.
*/
export const assemblyConvertFunction = inngest.createFunction(
{
id: "assembly-convert",
retries: 2,
- // The geometry service is CPU-bound and rejects work beyond its slot
- // count with 429s; keep per-company fan-out from starving other tenants.
+ // This function holds its run for the whole convert (it long-polls to
+ // completion); keep per-company fan-out from starving other tenants.
concurrency: [{ limit: 4 }, { key: "event.data.companyId", limit: 2 }],
onFailure: async ({ event }) => {
const { modelUploadId } = event.data.event.data;
@@ -52,6 +55,16 @@ export const assemblyConvertFunction = inngest.createFunction(
async ({ event, step, logger }) => {
const { modelUploadId, companyId, userId } = event.data;
+ // Feature-gated: no assembler configured -> skip before creating the plan
+ // job row or flipping processingStatus, so the UI never shows a stuck
+ // "Processing" and the viewer serves the unconverted model.
+ if (!assemblerEnabled()) {
+ logger.info("assembly convert skipped — assembler is not configured", {
+ modelUploadId
+ });
+ return;
+ }
+
const job = await step.run("queue", async () => {
const client = getCarbonServiceRole();
@@ -94,125 +107,88 @@ export const assemblyConvertFunction = inngest.createFunction(
return { id: planJob.data.id, modelPath: modelUpload.data.modelPath };
});
- await step.run("convert", async () => {
- const client = getCarbonServiceRole();
-
- if (!ASSEMBLER_SERVICE_URL) {
- throw new Error("ASSEMBLER_SERVICE_URL is not configured");
- }
-
- const glbPath = `${companyId}/models/${modelUploadId}/${job.id}/model.glb`;
- const graphPath = `${companyId}/models/${modelUploadId}/${job.id}/graph.json`;
-
- const source = await client.storage
- .from("private")
- .createSignedUrl(job.modelPath, SIGNED_URL_EXPIRY);
- if (source.error) {
- throw new Error(`Failed to sign source URL: ${source.error.message}`);
- }
-
- // Content identity for the geometry service's result cache: with a
- // contentHash a repeat convert of unchanged bytes is served without
- // re-downloading the source. etag is content-derived; size disambiguates
- // multipart etags. Best-effort — omitted on any failure.
- let contentHash: string | undefined;
- try {
- const info = await client.storage.from("private").info(job.modelPath);
- const etag = info.data?.etag?.replaceAll('"', "");
- if (!info.error && etag) {
- contentHash = `${etag}-${info.data?.size ?? 0}`;
+ // Job-scoped artifact paths. The service late-mint uploads to these via
+ // signed URLs minted fresh on each poll (below); we record the paths.
+ const glbPath = `${companyId}/models/${modelUploadId}/${job.id}/model.glb`;
+ const graphPath = `${companyId}/models/${modelUploadId}/${job.id}/graph.json`;
+
+ // Router: sync inline on Lambda (default when enabled) or async submit->poll
+ // on the standing service / dev container. Sync off => today's async path.
+ // Each attempt mints a fresh signed source URL (retries never reuse an
+ // expired one) and fresh signed upload URLs for both artifacts (late-mint).
+ const convert = await runAssemblerJob(step, {
+ idPrefix: "convert",
+ action: "convert",
+ jobId: job.id,
+ maxWaitMs: MAX_CONVERT_WAIT_MS,
+ logger,
+ buildBody: async () => {
+ const client = getCarbonServiceRole();
+ // Raw source lives in `temp-staging` (2.5 GB cap); assembly artifacts
+ // (glb/graph) are written to `private`.
+ const source = await client.storage
+ .from("temp-staging")
+ .createSignedUrl(job.modelPath, SIGNED_URL_EXPIRY);
+ if (source.error) {
+ throw new Error(`Failed to sign source URL: ${source.error.message}`);
}
- } catch {
- // optimization only
- }
- // upsert: Inngest retries re-upload to the same paths; without it the
- // storage API rejects the second attempt with "resource already exists"
- const [glbUpload, graphUpload] = await Promise.all([
- client.storage
- .from("private")
- .createSignedUploadUrl(glbPath, { upsert: true }),
- client.storage
- .from("private")
- .createSignedUploadUrl(graphPath, { upsert: true })
- ]);
- if (glbUpload.error || graphUpload.error) {
- throw new Error("Failed to sign artifact upload URLs");
- }
-
- const requestBody = JSON.stringify({
- jobId: job.id,
- source: {
- url: source.data.signedUrl,
- format: "step",
- ...(contentHash ? { contentHash } : {})
- },
- outputs: {
- glb: { url: glbUpload.data.signedUrl },
- graph: { url: graphUpload.data.signedUrl }
- }
- });
-
- let response: Response;
- // Bounded 429 backoff honoring Retry-After — the service sheds load with
- // BUSY when its conversion slots are full.
- for (let attempt = 0; ; attempt++) {
+ // Content identity for the service's result cache: with a contentHash a
+ // repeat convert of unchanged bytes is served without re-downloading the
+ // source. etag is content-derived; size disambiguates multipart etags.
+ // Best-effort — omitted on any failure.
+ let contentHash: string | undefined;
try {
- response = await fetch(`${ASSEMBLER_SERVICE_URL}/convert`, {
- method: "POST",
- headers: {
- "Content-Type": "application/json",
- ...(ASSEMBLER_SERVICE_API_KEY
- ? { Authorization: `Bearer ${ASSEMBLER_SERVICE_API_KEY}` }
- : {})
- },
- body: requestBody,
- signal: AbortSignal.timeout(CONVERT_TIMEOUT_MS)
- });
- } catch (e) {
- const err = e as Error;
- // A timeout may be transient (the service was briefly saturated) — let
- // Inngest retry it. Genuine unreachability (down, DNS, TLS) is
- // permanent, so fail fast → onFailure releases the model + job rows now
- // instead of after the retry backoff.
- if (err.name === "TimeoutError" || err.name === "AbortError") {
- throw new Error(
- `Geometry service timed out after ${CONVERT_TIMEOUT_MS}ms`
- );
+ const info = await client.storage
+ .from("temp-staging")
+ .info(job.modelPath);
+ const etag = info.data?.etag?.replaceAll('"', "");
+ if (!info.error && etag) {
+ contentHash = `${etag}-${info.data?.size ?? 0}`;
}
- throw new NonRetriableError(
- `Geometry service unreachable: ${err.message}`
- );
- }
- if (response.status === 429 && attempt < BUSY_RETRIES) {
- const retryAfter = Number(response.headers.get("retry-after")) || 15;
- const waitMs = Math.min(retryAfter * 1000 * (attempt + 1), 120_000);
- logger.warn("geometry /convert busy (429); backing off", {
- modelUploadId,
- attempt,
- waitMs
- });
- await new Promise((resolve) => setTimeout(resolve, waitMs));
- continue;
+ } catch {
+ // optimization only
}
- break;
- }
- const result = (await response.json().catch(() => null)) as {
- ok: boolean;
- componentCount?: number;
- stats?: Record<string, unknown>;
- error?: string;
- } | null;
-
- if (!response.ok || !result?.ok) {
- // Non-429 errors are an outage (5xx) or a permanent rejection (4xx):
- // retrying holds the job in Processing for nothing — fail fast.
- throw new NonRetriableError(
- result?.error ?? `Geometry service returned ${response.status}`
- );
+ return {
+ source: {
+ url: internalizeStorageUrl(source.data.signedUrl),
+ format: "step",
+ ...(contentHash ? { contentHash } : {})
+ },
+ // Storage paths (not URLs) — recorded in the completion pointer; the
+ // signed PUT URLs are late-minted, keyed glb/graph.
+ outputs: {
+ glb: { path: glbPath },
+ graph: { path: graphPath }
+ }
+ };
+ },
+ mintUploadUrls: async () => {
+ const client = getCarbonServiceRole();
+ const [glbUpload, graphUpload] = await Promise.all([
+ client.storage
+ .from("private")
+ .createSignedUploadUrl(glbPath, { upsert: true }),
+ client.storage
+ .from("private")
+ .createSignedUploadUrl(graphPath, { upsert: true })
+ ]);
+ const urls: Record<string, string> = {};
+ if (glbUpload.data)
+ urls.glb = internalizeStorageUrl(glbUpload.data.signedUrl);
+ if (graphUpload.data)
+ urls.graph = internalizeStorageUrl(graphUpload.data.signedUrl);
+ return urls;
}
+ });
+ const componentCount =
+ ((convert.result ?? {}) as { componentCount?: number }).componentCount ??
+ null;
+ const stats: Json = convert.stats;
+ await step.run("persist", async () => {
+ const client = getCarbonServiceRole();
await client
.from("modelUpload")
.update({
@@ -220,7 +196,7 @@ export const assemblyConvertFunction = inngest.createFunction(
processingError: null,
glbPath,
graphPath,
- componentCount: result.componentCount ?? null,
+ componentCount,
processedAt: new Date().toISOString()
})
.eq("id", modelUploadId);
@@ -229,14 +205,14 @@ export const assemblyConvertFunction = inngest.createFunction(
.from("assemblyPlanJob")
.update({
status: "Success",
- stats: (result.stats ?? null) as Json,
+ stats,
updatedAt: new Date().toISOString()
})
.eq("id", job.id);
});
// Planning is NOT chained here — it's expensive (minutes) and the user may
- // author steps manually. It runs lazily on the first "Generate Steps"
- // click (or an explicit re-plan), which then auto-creates the steps.
+ // author steps manually. It runs lazily on the first "Generate Steps" click
+ // (or an explicit re-plan), which then auto-creates the steps.
}
);
diff --git a/packages/jobs/src/inngest/functions/tasks/assembly-plan.ts b/packages/jobs/src/inngest/functions/tasks/assembly-plan.ts
index 9aa51da4af..ba934648a0 100644
--- a/packages/jobs/src/inngest/functions/tasks/assembly-plan.ts
+++ b/packages/jobs/src/inngest/functions/tasks/assembly-plan.ts
@@ -1,56 +1,40 @@
import { getCarbonServiceRole } from "@carbon/auth/client.server";
import type { Json } from "@carbon/database";
-import { ASSEMBLER_SERVICE_API_KEY, ASSEMBLER_SERVICE_URL } from "@carbon/env";
import type { AssemblyPlan } from "@carbon/viewer/steps";
-import { NonRetriableError } from "inngest";
import { inngest } from "../../client";
+import {
+ assemblerEnabled,
+ internalizeStorageUrl,
+ POLL_GAP,
+ pollAssemblerJobOnce,
+ submitAssemblerJob
+} from "./assembler-client";
import { loadPlanUnits } from "./plan-units";
import { updateAssemblyStepMotionsFromPlan } from "./update-step-motions";
const SIGNED_URL_EXPIRY = 60 * 60; // seconds — the source (read) URL only.
-// Every geometry HTTP call is short (a submit), so a tight per-request timeout
-// is safe and catches a genuinely unreachable service.
-const REQUEST_TIMEOUT_MS = 60 * 1000;
-// Bounded backoff when the service 429s a submit (all slots busy) — honors
-// Retry-After so Inngest's own retries don't hammer the semaphore.
-const BUSY_RETRIES = 4;
// This function holds its run for the whole plan (it long-polls to completion),
// so the global concurrency limit caps concurrent long-running plans
// cluster-wide. Keep it aligned with the service's ASSEMBLER_MAX_CONCURRENCY
// (default 2) so Inngest queues surplus plans instead of 429-storming.
const PLAN_CONCURRENCY = 2;
-// Long-poll: GET /plan/{id}?wait=N holds the request open until the plan
-// finishes (or N elapses), so completion is near-immediate and a whole plan
-// costs a handful of checkpointed steps, not ~180 short polls. The client
-// timeout must exceed the server hold.
-const LONG_POLL_WAIT_S = 25;
-const LONG_POLL_TIMEOUT_MS = (LONG_POLL_WAIT_S + 10) * 1000;
-// Floor between polls. When the service actually holds the request for ~25s this
-// is negligible; when a poll returns immediately (a service without ?wait
-// support, a 404, or a network blip) this is what stops the loop from hammering
-// Inngest with back-to-back re-invocations.
-const POLL_GAP = "3s";
// Total wall-clock budget before giving up, bounded by time (not a fixed poll
// count) so it holds whether the service long-polls or returns immediately.
const MAX_PLAN_WAIT_MS = 40 * 60 * 1000;
-const authHeaders: Record<string, string> = ASSEMBLER_SERVICE_API_KEY
- ? { Authorization: `Bearer ${ASSEMBLER_SERVICE_API_KEY}` }
- : {};
-
/**
- * Runs the geometry service motion planner over a converted model: computes a
+ * Runs the assembler service motion planner over a converted model: computes a
* collision-free insertion motion per part plus an assembly sequence, stored as
* plan.json next to the model artifacts. See
- * .ai/specs/2026-07-04-animated-work-instructions-contracts.md (POST /plan, GET /plan).
+ * .ai/specs/2026-07-04-animated-work-instructions-contracts.md (POST /v1/plan,
+ * GET /v1/jobs/{id}).
*
- * One durable function owns the whole lifecycle: submit → long-poll GET /plan
- * until the service finishes → flip the job row. Each poll carries a freshly
- * minted signed upload URL (X-Plan-Upload-Url); the service PUTs plan.json to it
- * (late-mint offload) and stores only a {status, planPath, stats} pointer in its
- * Redis-backed store, so a restart still answers the poll (no 404-on-restart
- * loss). Long-poll (rather than short-poll or a pushed completion event) keeps
- * the whole flow inside this run with no dependency on service→Inngest events.
+ * One durable function owns the whole lifecycle: create job → long-poll
+ * GET /v1/jobs/{id} until the service finishes → flip the job row. Each poll
+ * carries a freshly minted signed upload URL (X-Carbon-Upload-Urls {plan}); the
+ * service PUTs plan.json to it (late-mint offload) and stores only a
+ * {result, stats} pointer in its Redis-backed store, so a restart still answers
+ * the poll (no 404-on-restart loss).
*/
export const assemblyPlanFunction = inngest.createFunction(
{
@@ -89,6 +73,29 @@ export const assemblyPlanFunction = inngest.createFunction(
reDetectUnits
} = event.data;
+ // Feature-gated. Plan is an explicit user action ("Generate Steps"), so a
+ // pre-created Queued row is failed with a clear reason instead of hanging.
+ if (!assemblerEnabled()) {
+ if (planJobId) {
+ await step.run("mark-unconfigured", async () => {
+ const client = getCarbonServiceRole();
+ await client
+ .from("assemblyPlanJob")
+ .update({
+ status: "Failed",
+ error: "Assembler service is not configured",
+ updatedAt: new Date().toISOString()
+ })
+ .eq("id", planJobId)
+ .eq("companyId", companyId);
+ });
+ }
+ logger.info("assembly plan skipped — assembler is not configured", {
+ modelUploadId
+ });
+ return { jobId: planJobId ?? null, status: "Skipped" as const };
+ }
+
const job = await step.run("queue", async () => {
const client = getCarbonServiceRole();
@@ -151,11 +158,6 @@ export const assemblyPlanFunction = inngest.createFunction(
};
});
- if (!ASSEMBLER_SERVICE_URL) {
- throw new Error("ASSEMBLER_SERVICE_URL is not configured");
- }
- const geometryUrl = ASSEMBLER_SERVICE_URL;
-
// Where plan.json lands. The service PUTs it here itself (offload) via a
// signed upload URL minted fresh on each poll (below); this run just records
// the pointer the service reports back.
@@ -210,175 +212,89 @@ export const assemblyPlanFunction = inngest.createFunction(
})
);
- // Kick off the planner. The service starts it in the background and returns
- // 202 immediately; we then poll GET /plan below. A fresh signed source URL
- // is minted per submit so retries don't reuse an expired one.
- const submitPlan = async () => {
+ // Create the plan job. The service starts it in the background and returns
+ // 202; we then long-poll GET /v1/jobs/{id}. A fresh signed source URL is
+ // minted here so retries don't reuse an expired one. Idempotent on job.id.
+ await step.run("submit", async () => {
const client = getCarbonServiceRole();
+ // Raw source lives in `temp-staging` (2.5 GB cap).
const source = await client.storage
- .from("private")
+ .from("temp-staging")
.createSignedUrl(job.modelPath, SIGNED_URL_EXPIRY);
if (source.error) {
throw new Error(`Failed to sign source URL: ${source.error.message}`);
}
- const body = JSON.stringify({
+ await submitAssemblerJob({
+ action: "plan",
jobId: job.id,
- source: { url: source.data.signedUrl, format: "step" },
- // No upload URL here — it's minted fresh on each poll (late-mint) so the
- // token is only seconds old when the service PUTs plan.json. The service
- // reads planPath (for the completion pointer) and modelUploadId (to scope
- // its content-hash result cache) out of meta.
- meta: {
- companyId,
- userId,
- modelUploadId,
- reMotionFor: reMotionFor ?? null,
- graphPath: job.graphPath ?? null,
- planPath
- },
- ...(sequence != null
- ? { options: { sequence } }
- : units.length > 0
- ? { options: { units } }
- : {})
- });
-
- // Bounded 429 backoff honoring Retry-After: the service sheds load with
- // BUSY when its slots are full; hammering it via instant retries only
- // extends the outage.
- for (let attempt = 0; ; attempt++) {
- let response: Response;
- try {
- response = await fetch(`${geometryUrl}/plan`, {
- method: "POST",
- headers: { "Content-Type": "application/json", ...authHeaders },
- body,
- signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS)
- });
- } catch (e) {
- const err = e as Error;
- // A timeout may be transient (the service was briefly saturated) — let
- // Inngest retry it. Genuine unreachability (down, DNS, TLS) is
- // permanent, so fail fast → onFailure releases the job row now instead
- // of after the retry backoff.
- if (err.name === "TimeoutError" || err.name === "AbortError") {
- throw new Error(
- `Geometry service timed out after ${REQUEST_TIMEOUT_MS}ms`
- );
- }
- throw new NonRetriableError(
- `Geometry service unreachable: ${err.message}`
- );
- }
-
- if (response.status === 429 && attempt < BUSY_RETRIES) {
- const retryAfter = Number(response.headers.get("retry-after")) || 15;
- const waitMs = Math.min(retryAfter * 1000 * (attempt + 1), 120_000);
- logger.warn("geometry /plan busy (429); backing off", {
- jobId: job.id,
- attempt,
- waitMs
- });
- await new Promise((resolve) => setTimeout(resolve, waitMs));
- continue;
- }
-
- const result = (await response.json().catch(() => null)) as {
- ok?: boolean;
- error?: string;
- } | null;
- if (!response.ok || !result?.ok) {
- // Non-429 errors are an outage (5xx) or a permanent rejection (4xx):
- // retrying holds the job in Processing for nothing — fail fast.
- throw new NonRetriableError(
- result?.error ?? `Geometry service returned ${response.status}`
- );
+ logger,
+ body: {
+ source: {
+ url: internalizeStorageUrl(source.data.signedUrl),
+ format: "step"
+ },
+ // No upload URL here — it's minted fresh on each poll (late-mint) so
+ // the token is only seconds old when the service PUTs plan.json. The
+ // service reads planPath (completion pointer) and modelUploadId (to
+ // scope its content-hash result cache) out of meta.
+ meta: {
+ companyId,
+ userId,
+ modelUploadId,
+ reMotionFor: reMotionFor ?? null,
+ graphPath: job.graphPath ?? null,
+ planPath
+ },
+ ...(sequence != null
+ ? { options: { sequence } }
+ : units.length > 0
+ ? { options: { units } }
+ : {})
}
- logger.info("plan submitted to geometry service", { jobId: job.id });
- return { ok: true };
- }
- };
-
- await step.run("submit", submitPlan);
+ });
+ logger.info("plan submitted to assembler service", { jobId: job.id });
+ });
- // Long-poll GET /plan?wait until the service finishes. Each request holds
- // open server-side until the plan lands (or ~25s elapses), so completion is
- // near-immediate and each is a checkpointed step (a worker restart resumes
- // the loop). The service offloaded plan.json to storage, so "done" carries
- // only a { planPath, stats } pointer — not the plan body. A legacy service
- // that ignored outputs.plan.url still returns the plan inline; handle both.
+ // Long-poll GET /v1/jobs/{id}?wait until the service finishes. Each request
+ // holds open server-side until the plan lands (or ~25s elapses), so
+ // completion is near-immediate and each is a checkpointed step (a worker
+ // restart resumes the loop). The service offloaded plan.json to storage, so
+ // the result carries only a { planPath } pointer — not the plan body.
let resolvedPlanPath: string | null = null;
let inlinePlan: AssemblyPlan | null = null;
let stats: Json = null;
let finished = false;
- // Bound by elapsed time, not a fixed poll count: the loop must behave whether
- // the service long-polls (few iterations) or returns immediately (many).
const planStartedAt = await step.run("plan-poll-start", () => Date.now());
let i = 0;
while (Date.now() - planStartedAt < MAX_PLAN_WAIT_MS) {
- const poll = await step.run(`poll-${i}`, async () => {
- // Mint a fresh upload URL for THIS poll (late-mint). The service holds
- // the finished plan until a poll carries a URL, then PUTs plan.json with
- // this seconds-old token. Best-effort: a poll without it just keeps the
- // service waiting for the next one.
- const client = getCarbonServiceRole();
- const upload = await client.storage
- .from("private")
- .createSignedUploadUrl(planPath, { upsert: true });
- const headers: Record<string, string> = {
- ...authHeaders,
- ...(upload.data ? { "X-Plan-Upload-Url": upload.data.signedUrl } : {})
- };
- let response: Response;
- try {
- response = await fetch(
- `${geometryUrl}/plan/${job.id}?wait=${LONG_POLL_WAIT_S}`,
- {
- headers,
- signal: AbortSignal.timeout(LONG_POLL_TIMEOUT_MS)
- }
- );
- } catch {
- // A dropped/timed-out hold (service restart mid-hold, brief network
- // blip) is transient with the Redis-backed store — treat as "still
- // waiting" and long-poll again rather than failing the run.
- return { status: "pending" as const };
- }
- // 404 with the Redis store is rare (only a genuinely unknown/expired
- // job); treat as transient within the wall-clock window.
- if (response.status === 404) return { status: "pending" as const };
- const bodyJson = (await response.json().catch(() => null)) as {
- status?: string;
- planPath?: string;
- plan?: AssemblyPlan;
- stats?: Json;
- error?: string;
- } | null;
- if (!response.ok || !bodyJson) {
- throw new Error(`GET /plan returned ${response.status}`);
- }
- if (bodyJson.status === "done") {
- return {
- status: "done" as const,
- planPath: bodyJson.planPath ?? null,
- plan: bodyJson.plan ?? null,
- stats: bodyJson.stats ?? null
- };
- }
- if (bodyJson.status === "error") {
- return {
- status: "error" as const,
- error: bodyJson.error ?? "Motion planning failed"
- };
- }
- return { status: "pending" as const };
- });
+ const poll = await step.run(`poll-${i}`, () =>
+ pollAssemblerJobOnce({
+ jobId: job.id,
+ // Mint a fresh upload URL for THIS poll (late-mint). The service holds
+ // the finished plan until a poll carries a URL, then PUTs plan.json
+ // with this seconds-old token.
+ mintUploadUrls: async () => {
+ const client = getCarbonServiceRole();
+ const upload = await client.storage
+ .from("private")
+ .createSignedUploadUrl(planPath, { upsert: true });
+ const urls: Record<string, string> = {};
+ if (upload.data)
+ urls.plan = internalizeStorageUrl(upload.data.signedUrl);
+ return urls;
+ }
+ })
+ );
if (poll.status === "done") {
- resolvedPlanPath = poll.planPath ?? planPath;
- inlinePlan = poll.plan;
+ const result = (poll.result ?? {}) as {
+ planPath?: string;
+ plan?: AssemblyPlan | null;
+ };
+ resolvedPlanPath = result.planPath ?? planPath;
+ inlinePlan = result.plan ?? null;
stats = poll.stats;
finished = true;
break;
@@ -399,7 +315,7 @@ export const assemblyPlanFunction = inngest.createFunction(
const donePlanPath = resolvedPlanPath ?? planPath;
// Persist: flip the row to the pointer the service reported. A legacy
- // service returned the plan inline instead of offloading — upload it here in
+ // response returned the plan inline instead of offloading — upload it here in
// that case. Guarded by status=Processing so a cancel/racing-retry no-ops.
await step.run("persist-plan", async () => {
const client = getCarbonServiceRole();
diff --git a/packages/jobs/src/inngest/functions/tasks/company-backup.closure.test.ts b/packages/jobs/src/inngest/functions/tasks/company-backup.closure.test.ts
index e4c84a6b9b..2bd59fa1c4 100644
--- a/packages/jobs/src/inngest/functions/tasks/company-backup.closure.test.ts
+++ b/packages/jobs/src/inngest/functions/tasks/company-backup.closure.test.ts
@@ -424,17 +424,21 @@ describe("buildRowTransforms", () => {
});
it("rewrites a storage path to the shared template prefix when templateIndustryId is set", () => {
- const t = table("item", [
+ const t = table("modelUpload", [
col("id"),
col("companyId"),
- col("modelPath", { nullable: true })
+ col("thumbnailPath", { nullable: true })
]);
const out = apply(
t,
- { id: "i1", companyId: "src-co", modelPath: "src-co/models/x.stl" },
+ {
+ id: "i1",
+ companyId: "src-co",
+ thumbnailPath: "src-co/thumbnails/x.png"
+ },
ctx({ templateIndustryId: "metal" })
);
- expect(out.modelPath).toBe("_templates/metal/models/x.stl");
+ expect(out.thumbnailPath).toBe("_templates/metal/thumbnails/x.png");
});
it("nulls a nullable FK into a skipped (not-imported) table", () => {
diff --git a/packages/jobs/src/inngest/functions/tasks/company-backup.ts b/packages/jobs/src/inngest/functions/tasks/company-backup.ts
index 65beb52c4e..0b9ae76757 100644
--- a/packages/jobs/src/inngest/functions/tasks/company-backup.ts
+++ b/packages/jobs/src/inngest/functions/tasks/company-backup.ts
@@ -45,11 +45,17 @@ export const TEMPLATE_BUCKET = "company-templates";
export const STORAGE_BUCKET = "private";
/**
- * TEXT columns that hold a storage path (`{companyId}/…/{id}.ext`). On reseed
- * the companyId and the embedded ids both change, so these must be rewritten in
- * lock-step with the files they point at (see `rewriteStoragePath`).
+ * TEXT columns that hold a storage path (`{companyId}/…/{id}.ext`) in the
+ * `private` backup bucket. On reseed the companyId and the embedded ids both
+ * change, so these must be rewritten in lock-step with the files they point at
+ * (see `rewriteStoragePath`).
+ *
+ * `modelPath` (the raw CAD source) is intentionally excluded — raw models live in
+ * the `temp-staging` bucket (2.5 GB, transient), not `private`, so they are not
+ * carried by a backup. A restored model keeps its thumbnail; its 3D artifacts are
+ * regenerated by re-optimising if the raw is re-uploaded.
*/
-export const STORAGE_PATH_COLUMNS = new Set(["modelPath", "thumbnailPath"]);
+export const STORAGE_PATH_COLUMNS = new Set(["thumbnailPath"]);
/**
* Prefix in the `private` bucket where onboarding demo-template assets live ONCE
diff --git a/packages/jobs/src/inngest/functions/tasks/index.ts b/packages/jobs/src/inngest/functions/tasks/index.ts
index d9b4512474..f5387204c2 100644
--- a/packages/jobs/src/inngest/functions/tasks/index.ts
+++ b/packages/jobs/src/inngest/functions/tasks/index.ts
@@ -7,6 +7,7 @@ export {
companyRestoreFunction,
companyRestoreRevertFunction
} from "./company-restore";
+export { modelOptimizeFunction } from "./model-optimize";
export { modelThumbnailFunction } from "./model-thumbnail";
export { onboardFunction } from "./onboard";
export { postTransactionFunction } from "./post-transaction";
diff --git a/packages/jobs/src/inngest/functions/tasks/model-optimize.ts b/packages/jobs/src/inngest/functions/tasks/model-optimize.ts
new file mode 100644
index 0000000000..e665d33f8c
--- /dev/null
+++ b/packages/jobs/src/inngest/functions/tasks/model-optimize.ts
@@ -0,0 +1,246 @@
+import { getCarbonServiceRole } from "@carbon/auth/client.server";
+import type { Json } from "@carbon/database";
+import { modelPathOptimizeFormat } from "@carbon/utils";
+import { inngest } from "../../client";
+import {
+ assemblerEnabled,
+ internalizeStorageUrl,
+ runAssemblerJob
+} from "./assembler-client";
+
+const SIGNED_URL_EXPIRY = 60 * 60; // seconds — the source (read) URL only.
+const MAX_OPTIMIZE_WAIT_MS = 15 * 60 * 1000;
+
+/**
+ * Eager model optimisation on upload. Runs a mesh model (STEP / glTF / GLB)
+ * through the assembler's POST /v1/optimize (merge same-material primitives,
+ * simplify within the auto tolerance, meshopt-encode, gate on size) into a
+ * compact optimised GLB stored at optimizedModelPath. Separate from
+ * assembly-convert: that produces the lossless GLB the animated viewer needs;
+ * this is the aggressively-optimised version for storage/preview.
+ */
+export const modelOptimizeFunction = inngest.createFunction(
+ {
+ id: "model-optimize",
+ retries: 2,
+ // The assembler is CPU-bound; keep per-company fan-out from starving tenants.
+ concurrency: [{ limit: 4 }, { key: "event.data.companyId", limit: 2 }],
+ onFailure: async ({ event }) => {
+ const { modelUploadId } = event.data.event.data;
+ const client = getCarbonServiceRole();
+ await client
+ .from("modelUpload")
+ .update({
+ optimizeStatus: "Failed",
+ optimizeError: event.data.error.message
+ })
+ .eq("id", modelUploadId);
+ }
+ },
+ { event: "carbon/model-optimize" },
+ async ({ event, step, logger }) => {
+ const { modelUploadId, companyId } = event.data;
+
+ // Feature-gated: no assembler configured -> skip before touching the row,
+ // so the viewer just serves the raw model tier (optimizeStatus stays null).
+ if (!assemblerEnabled()) {
+ logger.info("model optimise skipped — assembler is not configured", {
+ modelUploadId
+ });
+ return { modelUploadId, status: "Skipped" as const };
+ }
+
+ const model = await step.run("queue", async () => {
+ const client = getCarbonServiceRole();
+ const upload = await client
+ .from("modelUpload")
+ .select("id, modelPath")
+ .eq("id", modelUploadId)
+ .eq("companyId", companyId)
+ .single();
+ if (upload.error || !upload.data?.modelPath) {
+ throw new Error(
+ `Model upload ${modelUploadId} not found or has no file`
+ );
+ }
+ // Derive the source format from the stored file, not the caller — every
+ // attach point (part/quote/rfq create, generic upload) then triggers with
+ // just the id, and non-mesh inputs (stl/obj/iges/…) skip cleanly. Strips a
+ // `.zst` compaction suffix so reoptimise of a compacted raw resolves too.
+ const format = modelPathOptimizeFormat(upload.data.modelPath);
+ if (format) {
+ await client
+ .from("modelUpload")
+ .update({ optimizeStatus: "Processing", optimizeError: null })
+ .eq("id", modelUploadId);
+ }
+ return { modelPath: upload.data.modelPath, format };
+ });
+
+ if (!model.format) {
+ logger.info("model optimise skipped — not an optimisable mesh format", {
+ modelUploadId,
+ modelPath: model.modelPath
+ });
+ return { modelUploadId, status: "Skipped" as const };
+ }
+ const format = model.format;
+
+ // Where the optimised GLB lands. The service late-mint uploads to this via a
+ // signed URL minted fresh on each poll (below).
+ const optimizedPath = `${companyId}/models/${modelUploadId}/optimized.glb`;
+ // Idempotent per model — a re-run attaches to the in-flight optimise.
+ const jobId = `optimize-${modelUploadId}`;
+
+ // Router: sync inline on Lambda (default when enabled) or async submit->poll
+ // on the standing service / dev container. Sync off => today's async path.
+ const optimize = await runAssemblerJob(step, {
+ idPrefix: "optimize",
+ action: "optimize",
+ jobId,
+ maxWaitMs: MAX_OPTIMIZE_WAIT_MS,
+ logger,
+ buildBody: async () => {
+ const client = getCarbonServiceRole();
+ // Raw source lands in `temp-staging` (2.5 GB cap); optimised artifacts are
+ // written to `private` (50 MB served cap) below.
+ const source = await client.storage
+ .from("temp-staging")
+ .createSignedUrl(model.modelPath, SIGNED_URL_EXPIRY);
+ if (source.error) {
+ throw new Error(`Failed to sign source URL: ${source.error.message}`);
+ }
+ return {
+ source: { url: internalizeStorageUrl(source.data.signedUrl), format },
+ output: { path: optimizedPath }
+ // quality omitted → the service defaults apply (codec meshopt, merge on,
+ // normal quant on, auto simplify tolerance, aggressive ladder to fit the
+ // size + render-weight gates).
+ };
+ },
+ mintUploadUrls: async () => {
+ const client = getCarbonServiceRole();
+ const upload = await client.storage
+ .from("private")
+ .createSignedUploadUrl(optimizedPath, { upsert: true });
+ const urls: Record<string, string> = {};
+ if (upload.data)
+ urls.glb = internalizeStorageUrl(upload.data.signedUrl);
+ return urls;
+ }
+ });
+ const stats: Json = optimize.stats;
+
+ await step.run("persist", async () => {
+ const client = getCarbonServiceRole();
+ // Read the optimised object's byte size from storage (the service uploads
+ // it via the late-mint URL, so the job never holds the bytes) to surface
+ // the reduction against the untouched source `size`.
+ const dir = `${companyId}/models/${modelUploadId}`;
+ const listed = await client.storage
+ .from("private")
+ .list(dir, { search: "optimized.glb" });
+ const optimizedSize =
+ listed.data?.find((o) => o.name === "optimized.glb")?.metadata?.size ??
+ null;
+
+ await client
+ .from("modelUpload")
+ .update({
+ optimizeStatus: "Success",
+ optimizeError: null,
+ optimizedModelPath: optimizedPath,
+ optimizedSize,
+ optimizedAt: new Date().toISOString()
+ })
+ .eq("id", modelUploadId);
+ });
+
+ // Compact the retained raw so it never lingers as the fat upload. Every
+ // optimisable source (any size) is zstd-compressed IN ITS ORIGINAL FORMAT —
+ // `raw.<ext>.zst` stays a valid STEP/glTF/… that the download route
+ // decompresses back to the source file, and the assembler reads it back
+ // transparently (zstd-decoded on fetch), so plan/convert/reoptimise need no
+ // change. Already-compacted (`.zst`) raws are skipped. Best-effort: a
+ // compaction failure must not fail the already-succeeded optimise (the
+ // scheduled big-raw TTL prune is the safety net).
+ const alreadyCompacted = model.modelPath.toLowerCase().endsWith(".zst");
+ if (!alreadyCompacted) {
+ // Flat, mirroring the original raw (`${id}.step` → `${id}.step.zst`), so the
+ // model id stays recoverable from the path (CadModel's `modelIdFromPath`)
+ // and the download route resolves the underlying format from the extension.
+ const compactPath = `${companyId}/models/${modelUploadId}.${format}.zst`;
+ const compactJobId = `compact-${modelUploadId}`;
+ try {
+ const compact = await runAssemblerJob(step, {
+ idPrefix: "compact",
+ action: "compact",
+ jobId: compactJobId,
+ maxWaitMs: MAX_OPTIMIZE_WAIT_MS,
+ logger,
+ buildBody: async () => {
+ const client = getCarbonServiceRole();
+ const source = await client.storage
+ .from("temp-staging")
+ .createSignedUrl(model.modelPath, SIGNED_URL_EXPIRY);
+ if (source.error) {
+ throw new Error(`sign source: ${source.error.message}`);
+ }
+ return {
+ source: { url: internalizeStorageUrl(source.data.signedUrl) },
+ mode: "zstd",
+ output: { path: compactPath }
+ };
+ },
+ mintUploadUrls: async () => {
+ const client = getCarbonServiceRole();
+ const upload = await client.storage
+ .from("temp-staging")
+ .createSignedUploadUrl(compactPath, { upsert: true });
+ const urls: Record<string, string> = {};
+ if (upload.data)
+ urls.raw = internalizeStorageUrl(upload.data.signedUrl);
+ return urls;
+ }
+ });
+ const compactedSize =
+ (compact.stats as { outputBytes?: number } | null)?.outputBytes ??
+ null;
+
+ await step.run("compact-persist", async () => {
+ const client = getCarbonServiceRole();
+ // Repoint modelPath at the compacted raw and record its (compressed)
+ // stored size so the files list reflects what's actually on disk, then
+ // drop the fat original. Freeze the as-uploaded bytes into
+ // originalSize first (rows from before the column exist with null) —
+ // the viewer's reduction badge compares the ORIGINAL, not the .zst.
+ const existing = await client
+ .from("modelUpload")
+ .select("size, originalSize")
+ .eq("id", modelUploadId)
+ .maybeSingle();
+ await client
+ .from("modelUpload")
+ .update({
+ modelPath: compactPath,
+ ...(existing.data && existing.data.originalSize == null
+ ? { originalSize: existing.data.size }
+ : {}),
+ ...(compactedSize != null ? { size: compactedSize } : {})
+ })
+ .eq("id", modelUploadId);
+ await client.storage.from("temp-staging").remove([model.modelPath]);
+ });
+ logger.info("raw compacted", { modelUploadId, compactPath });
+ } catch (err) {
+ logger.warn("raw compaction skipped", {
+ modelUploadId,
+ error: (err as Error).message
+ });
+ }
+ }
+
+ logger.info("model optimise finalized", { modelUploadId, stats });
+ return { modelUploadId, status: "Success" as const };
+ }
+);
diff --git a/packages/jobs/src/inngest/functions/tasks/model-thumbnail.ts b/packages/jobs/src/inngest/functions/tasks/model-thumbnail.ts
index 84dec96dcd..3abb0e88ac 100644
--- a/packages/jobs/src/inngest/functions/tasks/model-thumbnail.ts
+++ b/packages/jobs/src/inngest/functions/tasks/model-thumbnail.ts
@@ -1,5 +1,10 @@
import { getCarbonServiceRole } from "@carbon/auth/client.server";
-import { SUPABASE_ANON_KEY, SUPABASE_URL, VERCEL_URL } from "@carbon/env";
+import {
+ NODE_ENV,
+ SUPABASE_ANON_KEY,
+ SUPABASE_URL,
+ VERCEL_URL
+} from "@carbon/env";
import { inngest } from "../../client";
export const modelThumbnailFunction = inngest.createFunction(
@@ -8,8 +13,7 @@ export const modelThumbnailFunction = inngest.createFunction(
async ({ event, step, logger }) => {
const { modelId, companyId } = event.data;
- const isLocal =
- VERCEL_URL === undefined || VERCEL_URL.includes("localhost");
+ const isLocal = NODE_ENV !== "production";
const getModelUrl = (id: string) => {
if (isLocal) return `http://localhost:3000/file/model/${id}`;
diff --git a/packages/jobs/src/inngest/index.ts b/packages/jobs/src/inngest/index.ts
index 985ab5ac87..7cd8410e83 100644
--- a/packages/jobs/src/inngest/index.ts
+++ b/packages/jobs/src/inngest/index.ts
@@ -47,6 +47,7 @@ import {
companyRestoreFinalizeFunction,
companyRestoreFunction,
companyRestoreRevertFunction,
+ modelOptimizeFunction,
modelThumbnailFunction,
onboardFunction,
postTransactionFunction,
@@ -80,6 +81,7 @@ export const functions = [
companyRestoreFunction,
companyRestoreFinalizeFunction,
companyRestoreRevertFunction,
+ modelOptimizeFunction,
modelThumbnailFunction,
updatePermissionsFunction,
recalculateFunction,
diff --git a/packages/lib/src/events.ts b/packages/lib/src/events.ts
index 0e8092cd25..635c3a7893 100644
--- a/packages/lib/src/events.ts
+++ b/packages/lib/src/events.ts
@@ -112,6 +112,27 @@ export type Events = {
};
};
+ // Eager model optimisation on upload (mesh inputs → compact optimised GLB)
+ "carbon/assembler-job-done": {
+ data: {
+ /** The assembler job id the waiting run matches on. */
+ jobId: string;
+ /** Terminal public status: succeeded | failed | canceled. */
+ status: string;
+ result: unknown;
+ stats: unknown;
+ error: { code?: string; message?: string } | null;
+ };
+ };
+ "carbon/model-optimize": {
+ data: {
+ modelUploadId: string;
+ companyId: string;
+ userId: string;
+ // format is derived from the stored file inside the job, not passed here.
+ };
+ };
+
// Company backup export — snapshot all company-scoped rows (and
// optionally storage files) into a gzipped backup in the company bucket
"carbon/company-export": {
diff --git a/packages/lib/src/trigger.ts b/packages/lib/src/trigger.ts
index d1d52cf4b9..feaecf4507 100644
--- a/packages/lib/src/trigger.ts
+++ b/packages/lib/src/trigger.ts
@@ -16,6 +16,7 @@ const taskToEvent = {
"company-restore-finalize": "carbon/company-restore-finalize",
"company-restore-revert": "carbon/company-restore-revert",
"model-thumbnail": "carbon/model-thumbnail",
+ "model-optimize": "carbon/model-optimize",
notify: "carbon/notify",
onboard: "carbon/onboard",
"paperless-parts": "carbon/paperless-parts",
diff --git a/packages/react/package.json b/packages/react/package.json
index 89c256a405..4b383a82ac 100644
--- a/packages/react/package.json
+++ b/packages/react/package.json
@@ -78,7 +78,6 @@
"nanoid": "catalog:",
"nanostores": "catalog:",
"nprogress": "0.2.0",
- "online-3d-viewer": "0.15.0",
"react-aria-components": "1.0.1",
"react-colorful": "5.6.1",
"react-hotkeys-hook": "catalog:",
@@ -88,7 +87,6 @@
"sonner": "2.0.7",
"tailwind-merge": "catalog:",
"tailwindcss-animate": "catalog:",
- "three": "0.163.0",
"zustand": "catalog:"
},
"devDependencies": {
diff --git a/packages/react/src/ModelViewer.tsx b/packages/react/src/ModelViewer.tsx
deleted file mode 100644
index dc8c217c64..0000000000
--- a/packages/react/src/ModelViewer.tsx
+++ /dev/null
@@ -1,496 +0,0 @@
-import * as OV from "online-3d-viewer";
-import { useEffect, useMemo, useRef, useState } from "react";
-import { useLocale } from "react-aria-components";
-import { LuTrash2 } from "react-icons/lu";
-// @ts-ignore -- three has no declaration file in this context
-import * as THREE from "three";
-import { IconButton } from "./IconButton";
-import { Spinner } from "./Spinner";
-import { Tabs, TabsContent, TabsList, TabsTrigger } from "./Tabs";
-import { cn } from "./utils/cn";
-
-type UnitSystem = "metric" | "imperial";
-
-export function ModelViewer({
- file,
- url,
- mode = "dark",
- className,
- withProperties = true,
- onDataUrl,
- onDelete,
- resetZoomButton = true
-}: {
- file: File | null;
- url: string | null;
- mode?: "dark" | "light";
- withProperties?: boolean;
- onDataUrl?: (dataUrl: string) => void;
- onDelete?: () => void;
- resetZoomButton?: boolean;
- className?: string;
-}) {
- const parentDiv = useRef<HTMLDivElement>(null);
- const viewerRef = useRef<OV.EmbeddedViewer | null>(null);
- // Lights added to the scene, tracked so teardown can remove them
- // (Viewer.Clear() only disposes model objects, not scene-level lights).
- const addedLightsRef = useRef<any[]>([]);
- const [isLoading, setIsLoading] = useState(true);
- const [isActive, setIsActive] = useState(false);
- const [unitSystem, setUnitSystem] = useState<UnitSystem>("metric");
- const [modelInfo, setModelInfo] = useState<{
- surfaceArea: number;
- volume: number;
- dimensions: { x: number; y: number; z: number };
- } | null>(null);
-
- // Mount/unmount the viewer. Must be useEffect (not useMount) so the returned
- // teardown is actually registered as the cleanup — useMount discards it.
- // biome-ignore lint/correctness/useExhaustiveDependencies: mount-once lifecycle
- useEffect(() => {
- if (file || url) {
- setIsLoading(true);
-
- if (viewerRef.current === null) {
- let viewer = new OV.EmbeddedViewer(parentDiv.current!, {
- camera: new OV.Camera(
- new OV.Coord3D(100, 100, 100),
- new OV.Coord3D(0, 0, 0),
- new OV.Coord3D(0, 1, 0),
- 45.0
- ),
- backgroundColor: isDarkMode
- ? new OV.RGBAColor(20, 22, 25, 0)
- : new OV.RGBAColor(255, 255, 255, 0),
- defaultColor: new OV.RGBColor(0, 125, 125),
- onModelLoaded: () => {
- if (viewerRef.current) {
- const viewer3D = viewerRef.current.GetViewer();
-
- viewer3D.Resize(
- parentDiv.current?.clientWidth,
- parentDiv.current?.clientHeight
- );
-
- const boundingSphere = viewer3D.GetBoundingSphere(() => true);
- if (boundingSphere) {
- const scene = viewer3D.scene;
- const center = boundingSphere.center;
- const radius = boundingSphere.radius;
- const camera = viewer3D.GetCamera();
- const direction = new OV.Coord3D(1, 1, 1);
- const eye = new OV.Coord3D(
- center.x + direction.x * radius * 1.5,
- center.y + direction.y * radius * 1.5,
- center.z + direction.z * radius * 1.5
- );
- camera.center = center;
- camera.eye = eye;
- camera.up = new OV.Coord3D(0, 1, 0);
- viewer3D.SetCamera(camera);
-
- // onModelLoaded fires on every (re)load; guard so lights are
- // added once per viewer instead of stacking on each reload.
- if (addedLightsRef.current.length === 0) {
- const ambientLight = new THREE.AmbientLight(0xffffff, 0.5);
-
- const dirLight1 = new THREE.DirectionalLight(0xffffff, 0.8);
- dirLight1.position.set(1, 1, 1);
-
- const dirLight2 = new THREE.DirectionalLight(0xffffff, 0.4);
- dirLight2.position.set(-1, 0.5, -1);
-
- const pointLight = new THREE.PointLight(0xffffff, 0.3);
- pointLight.position.set(0, radius * 2, 0);
-
- addedLightsRef.current = [
- ambientLight,
- dirLight1,
- dirLight2,
- pointLight
- ];
- addedLightsRef.current.forEach((light) => scene.add(light));
- }
-
- viewer3D.Render();
- }
-
- let model;
- if (withProperties) {
- model = viewer.GetModel();
- }
-
- if (model) {
- // Calculate model dimensions and properties
- const boundingBox = OV.GetBoundingBox(model);
- const surfaceArea = OV.CalculateSurfaceArea(model);
- const volume = OV.CalculateVolume(model);
- const dimensions = {
- x: boundingBox.max.x - boundingBox.min.x,
- y: boundingBox.max.y - boundingBox.min.y,
- z: boundingBox.max.z - boundingBox.min.z
- };
-
- setModelInfo({
- surfaceArea,
- volume,
- dimensions
- });
- }
- }
-
- setIsLoading(false);
- }
- });
-
- viewerRef.current = viewer;
-
- if (file) {
- loadFile(file);
- }
- if (url) {
- loadUrl(url);
- }
- }
- }
-
- // Teardown must be self-contained: by the time this passive cleanup runs,
- // React has already nulled `parentDiv.current`, so derive everything from
- // the viewer ref instead.
- return () => {
- const embeddedViewer = viewerRef.current;
- if (embeddedViewer === null) return;
- const viewer3D = (embeddedViewer as any).viewer;
-
- // Clear() disposes model objects but not these scene lights.
- addedLightsRef.current.forEach((light) => {
- viewer3D?.scene?.remove(light);
- light.dispose?.();
- });
- addedLightsRef.current = [];
-
- (embeddedViewer as any).model = undefined;
- viewer3D?.renderer?.resetState();
- viewer3D?.Clear();
- viewer3D?.renderer?.dispose();
-
- // online-3d-viewer leaks two listeners it never removes, and each pins
- // the whole model graph (scene, geometry, renderer, WebGL context) so GC
- // never reclaims it. The library exposes no teardown and the bound
- // listener refs aren't accessible, so we break the retention by nulling
- // every heavy field the leaked closures reach.
-
- // 1) Navigation attaches mousemove/mouseup/mouseleave on `document`; its
- // `callbacks.onUpdate` closure references the Viewer.
- const navigation = viewer3D?.navigation;
- if (navigation) {
- navigation.camera = null;
- navigation.canvas = null;
- navigation.callbacks = null;
- navigation.mouse = null;
- navigation.touch = null;
- navigation.clickDetector = null;
- }
-
- // 2) EmbeddedViewer attaches a `resize` listener on `window` whose closure
- // captures the EmbeddedViewer itself. Neutralize the handler so it
- // can't fire after teardown, then null its references.
- const canvas = embeddedViewer.canvas;
- (embeddedViewer as any).Resize = () => {};
- (embeddedViewer as any).viewer = undefined;
- (embeddedViewer as any).modelLoader = undefined;
- (embeddedViewer as any).parameters = undefined;
- (embeddedViewer as any).parentElement = null;
-
- canvas
- ?.getContext("webgl2")
- ?.getExtension("WEBGL_lose_context")
- ?.loseContext();
- canvas?.parentNode?.removeChild(canvas);
- (embeddedViewer as any).canvas = null;
- viewerRef.current = null;
- };
- }, []);
-
- function resetZoom() {
- if (!viewerRef.current) return;
-
- const viewer3D = viewerRef.current.GetViewer();
- viewer3D.Resize(
- parentDiv.current?.clientWidth,
- parentDiv.current?.clientHeight
- );
-
- const boundingSphere = viewer3D.GetBoundingSphere(
- (_meshUserData: any) => true
- );
- if (boundingSphere) {
- const center = boundingSphere.center;
- const radius = boundingSphere.radius;
- const camera = viewer3D.GetCamera();
- const direction = new OV.Coord3D(1, 1, 1);
- const eye = new OV.Coord3D(
- center.x + direction.x * radius * 1.5,
- center.y + direction.y * radius * 1.5,
- center.z + direction.z * radius * 1.5
- );
- camera.center = center;
- camera.eye = eye;
- camera.up = new OV.Coord3D(0, 1, 0);
- viewer3D.SetCamera(camera);
- }
- }
-
- function loadFile(file: File) {
- if (!file) return;
- if (!viewerRef.current) return;
- const viewer = viewerRef.current;
- if (!viewer) return;
-
- viewer.LoadModelFromFileList([file]);
- }
-
- function loadUrl(url: string) {
- if (!url) return;
- if (!viewerRef.current) return;
- const viewer = viewerRef.current;
- if (!viewer) return;
- viewer.LoadModelFromUrlList([url]);
- }
-
- // biome-ignore lint/correctness/useExhaustiveDependencies: suppressed due to migration
- useEffect(() => {
- if (!file || !viewerRef.current) return;
- setIsLoading(true);
- loadFile(file);
- }, [file]);
-
- // biome-ignore lint/correctness/useExhaustiveDependencies: suppressed due to migration
- useEffect(() => {
- if (!url || file || !viewerRef.current) return;
- setIsLoading(true);
- loadUrl(url);
- }, [url, file]);
-
- const isDarkMode = mode === "dark";
- // biome-ignore lint/correctness/useExhaustiveDependencies: suppressed due to migration
- useEffect(() => {
- if (viewerRef.current) {
- const viewer3D = viewerRef.current.GetViewer();
- viewer3D.SetBackgroundColor(
- isDarkMode
- ? new OV.RGBAColor(21, 22, 25, 255)
- : new OV.RGBAColor(255, 255, 255, 255)
- );
- }
- }, [isDarkMode]);
-
- const { locale } = useLocale();
-
- // Conversion functions
- const mmToInches = (mm: number) => mm / 25.4;
- const mm2ToInches2 = (mm2: number) => mm2 / (25.4 * 25.4);
- const mm3ToInches3 = (mm3: number) => mm3 / (25.4 * 25.4 * 25.4);
-
- const formatter = useMemo(() => {
- const decimals = unitSystem === "imperial" ? 6 : 2;
- return new Intl.NumberFormat(locale, {
- style: "decimal",
- minimumFractionDigits: 0,
- maximumFractionDigits: decimals
- });
- }, [locale, unitSystem]);
-
- // Helper functions to get converted values
- const getDisplayValue = (
- value: number,
- type: "linear" | "area" | "volume"
- ) => {
- if (unitSystem === "imperial") {
- switch (type) {
- case "linear":
- return mmToInches(value);
- case "area":
- return mm2ToInches2(value);
- case "volume":
- return mm3ToInches3(value);
- }
- }
- return value;
- };
-
- const getUnit = (type: "linear" | "area" | "volume") => {
- if (unitSystem === "imperial") {
- switch (type) {
- case "linear":
- return "in";
- case "area":
- return "in²";
- case "volume":
- return "in³";
- }
- }
- switch (type) {
- case "linear":
- return "mm";
- case "area":
- return "mm²";
- case "volume":
- return "mm³";
- }
- };
-
- return (
- <>
- <div
- ref={parentDiv}
- role={"img"}
- aria-label="Canvas showing the model in the 3D Viewer"
- onMouseLeave={() => setIsActive(false)}
- className={cn(
- "h-full w-full items-center justify-center rounded-lg border border-border bg-gradient-to-bl from-card from-50% via-card to-background min-h-[400px] shadow-md dark:border-none dark:shadow-[inset_0_0.5px_0_rgb(255_255_255_/_0.08),_inset_0_0_1px_rgb(255_255_255_/_0.24),_0_0_0_0.5px_rgb(0,0,0,1),0px_0px_4px_rgba(0,_0,_0,_0.08)] relative",
-
- className
- )}
- >
- {isLoading ? (
- <div className="absolute inset-0 bg-card h-full w-full flex items-center justify-center">
- <Spinner className="w-10 h-10" />
- </div>
- ) : (
- <>
- {!isActive && (
- <button
- type="button"
- onClick={() => setIsActive(true)}
- aria-label="Click to interact with 3D model"
- className="absolute inset-0 flex items-end justify-center pb-4 cursor-pointer focus:outline-none group"
- >
- <span className="text-xs text-muted-foreground bg-background/80 backdrop-blur-sm px-3 py-1 rounded-full border border-border shadow-sm transition-opacity opacity-70 group-hover:opacity-100">
- Click to interact
- </span>
- </button>
- )}
- <pre id="model-viewer-canvas" aria-hidden className="sr-only" />
- {onDelete && (
- <IconButton
- aria-label="Delete model"
- className="absolute bottom-2 right-2 z-10 text-muted-foreground hover:text-destructive-foreground hover:bg-destructive"
- icon={<LuTrash2 />}
- variant="ghost"
- onClick={onDelete}
- />
- )}
- {resetZoomButton && (
- <IconButton
- aria-label="Reset zoom"
- className="absolute top-2 right-2"
- icon={
- <svg
- xmlns="http://www.w3.org/2000/svg"
- width="24"
- height="24"
- viewBox="0 0 24 24"
- fill="none"
- stroke="currentColor"
- strokeWidth="2"
- strokeLinecap="round"
- strokeLinejoin="round"
- >
- <path d="M3 7V5a2 2 0 0 1 2-2h2" />
- <path d="M17 3h2a2 2 0 0 1 2 2v2" />
- <path d="M21 17v2a2 2 0 0 1-2 2h-2" />
- <path d="M7 21H5a2 2 0 0 1-2-2v-2" />
- <rect width="10" height="8" x="7" y="8" rx="1" />
- </svg>
- }
- variant="ghost"
- onClick={resetZoom}
- />
- )}
- {modelInfo && withProperties && (
- <>
- <div className="absolute top-2 left-2 text-xs z-10 text-foreground">
- <Tabs defaultValue="dimensions" className="w-full gap-0">
- <TabsList className="grid w-full grid-cols-2 mb-1">
- <TabsTrigger className="text-xs" value="dimensions">
- Dimensions
- </TabsTrigger>
- <TabsTrigger className="text-xs" value="properties">
- Properties
- </TabsTrigger>
- </TabsList>
- <TabsContent value="properties">
- <div className="flex flex-col gap-1 pt-1 p-2 items-start justify-start font-mono">
- <div>
- Surface Area:{" "}
- {formatter.format(
- getDisplayValue(modelInfo.surfaceArea, "area")
- )}{" "}
- {getUnit("area")}
- </div>
- <div>
- Volume:{" "}
- {formatter.format(
- getDisplayValue(modelInfo.volume, "volume")
- )}{" "}
- {getUnit("volume")}
- </div>
- </div>
- </TabsContent>
- <TabsContent value="dimensions">
- <div className="flex flex-col gap-1 pt-1 p-2 items-start justify-start font-mono">
- <div className="flex items-center gap-1.5">
- <div className="size-2 bg-green-500 rounded-full" />
- W:{" "}
- {formatter.format(
- getDisplayValue(modelInfo.dimensions.x, "linear")
- )}{" "}
- {getUnit("linear")}
- </div>
- <div className="flex items-center gap-1.5">
- <div className="size-2 bg-blue-500 rounded-full" />
- H:{" "}
- {formatter.format(
- getDisplayValue(modelInfo.dimensions.y, "linear")
- )}{" "}
- {getUnit("linear")}
- </div>
- <div className="flex items-center gap-1.5">
- <div className="size-2 bg-red-500 rounded-full" />
- L:{" "}
- {formatter.format(
- getDisplayValue(modelInfo.dimensions.z, "linear")
- )}{" "}
- {getUnit("linear")}
- </div>
- </div>
- </TabsContent>
- </Tabs>
- </div>
- <div className="absolute top-2 right-2 text-xs z-10 text-foreground">
- <Tabs
- value={unitSystem}
- onValueChange={(value) =>
- setUnitSystem(value as UnitSystem)
- }
- className="w-full gap-0"
- >
- <TabsList className="grid w-full grid-cols-2 mb-1">
- <TabsTrigger className="text-xs" value="metric">
- mm
- </TabsTrigger>
- <TabsTrigger className="text-xs" value="imperial">
- in
- </TabsTrigger>
- </TabsList>
- </Tabs>
- </div>
- </>
- )}
- </>
- )}
- </div>
- </>
- );
-}
diff --git a/packages/react/src/index.tsx b/packages/react/src/index.tsx
index 3d8798bd47..91dce75a2d 100644
--- a/packages/react/src/index.tsx
+++ b/packages/react/src/index.tsx
@@ -230,7 +230,6 @@ import {
ModalDrawerTypeProvider,
useModalDrawerType
} from "./ModalDrawer";
-import { ModelViewer } from "./ModelViewer";
import type { MultiSelectProps } from "./MultiSelect";
import { MultiSelect } from "./MultiSelect";
import type { NumberFieldProps } from "./Number";
@@ -525,7 +524,6 @@ export {
ModalPortal,
ModalTitle,
ModalTrigger,
- ModelViewer,
MultiSelect,
NumberDecrementStepper,
NumberField,
diff --git a/packages/utils/src/const.ts b/packages/utils/src/const.ts
index 984d480859..ee07c6cd11 100644
--- a/packages/utils/src/const.ts
+++ b/packages/utils/src/const.ts
@@ -12,10 +12,15 @@ export function isInternalEmail(email: string | null | undefined): boolean {
}
export const FILE_SIZE_LIMIT_MB = {
- CAD_MODEL_UPLOAD: 120,
+ CAD_MODEL_UPLOAD: 2560, // 2.5 GB — matches temp-staging bucket cap
DOCUMENT_UPLOAD: 50
} as const;
+// Raw CAD source is kept in `temp-staging` and shown as a downloadable file in the
+// documents list only when <= this (the served-bucket cap). Larger raws are hidden
+// from the files list and TTL-pruned from staging — only the optimised GLB is kept.
+export const MODEL_RAW_KEEP_MAX_BYTES = 50 * 1024 * 1024;
+
export const PO_EMAIL_ATTACHMENT_LIMIT_MB = 25;
export const PO_EMAIL_ATTACHMENT_WARN_MB = 20;
diff --git a/packages/utils/src/file.ts b/packages/utils/src/file.ts
index 4e5952ee84..fdac33a0f2 100644
--- a/packages/utils/src/file.ts
+++ b/packages/utils/src/file.ts
@@ -10,6 +10,80 @@ export const convertKbToString = (kb: number) => {
return `${gb.toFixed(2)} GB`;
};
+// Formats the assembler's /v1/optimize can ingest: exact B-rep sources OCCT
+// tessellates (step/iges/brep + the compacted BinXCAF `xbf` retained-raw form)
+// and mesh sources it parses directly (glb/gltf/stl/obj/ply/off/bim/3mf/amf).
+// Widen this in lockstep with the assembler's format registry — each addition
+// makes that format optimise on upload (GLB-always doctrine); the remaining mesh
+// formats (fbx/dae/3ds/3dm) render via the viewer's WASM raw tier only. Returns
+// the service `format` string, or null if not optimisable.
+export function optimizableModelFormat(
+ ext: string
+):
+ | "step"
+ | "iges"
+ | "brep"
+ | "xbf"
+ | "gltf"
+ | "glb"
+ | "stl"
+ | "obj"
+ | "ply"
+ | "off"
+ | "bim"
+ | "3mf"
+ | "amf"
+ | null {
+ switch (ext.toLowerCase()) {
+ case "step":
+ case "stp":
+ return "step";
+ case "iges":
+ case "igs":
+ return "iges";
+ case "brep":
+ case "brp":
+ return "brep";
+ case "xbf":
+ return "xbf";
+ case "gltf":
+ return "gltf";
+ case "glb":
+ return "glb";
+ case "stl":
+ return "stl";
+ case "obj":
+ return "obj";
+ case "ply":
+ return "ply";
+ case "off":
+ return "off";
+ case "bim":
+ return "bim";
+ case "3mf":
+ return "3mf";
+ case "amf":
+ return "amf";
+ default:
+ return null;
+ }
+}
+
+// Resolve the assembler source format from a stored modelPath, transparently
+// stripping a `.zst` compaction suffix — the retained raw may have been compacted
+// to `raw.xbf.zst` / `raw.gltf.zst`, which the assembler decompresses on read.
+export function modelPathOptimizeFormat(modelPath: string) {
+ const lower = modelPath.toLowerCase();
+ const base = lower.endsWith(".zst") ? lower.slice(0, -4) : lower;
+ const ext = base.split(".").pop() ?? "";
+ return optimizableModelFormat(ext);
+}
+
+// Every format here is renderable in the browser (viewer raw tier: three-stdlib
+// loaders + occt/rhino3dm WASM). ifc and fcstd were dropped 2026-07-18: nothing
+// in the stack can preview them (each needs its own heavy WASM dep) and both
+// export STEP natively — accepting them just produced a dead upload. glb added
+// (was oddly absent while gltf/stl were accepted and the optimiser supports it).
export const supportedModelTypes = [
"3dm",
"3ds",
@@ -19,9 +93,8 @@ export const supportedModelTypes = [
"brep",
"dae",
"fbx",
- "fcstd",
+ "glb",
"gltf",
- "ifc",
"iges",
"obj",
"off",
diff --git a/packages/viewer/package.json b/packages/viewer/package.json
index 4a7cd505db..79b3f63979 100644
--- a/packages/viewer/package.json
+++ b/packages/viewer/package.json
@@ -1,8 +1,12 @@
{
"name": "@carbon/viewer",
"dependencies": {
+ "@carbon/react": "workspace:*",
"@react-three/drei": "9.122.0",
"@react-three/fiber": "8.18.0",
+ "occt-import-js": "0.0.23",
+ "rhino3dm": "8.17.0",
+ "react-icons": "catalog:",
"three": "0.163.0",
"three-mesh-bvh": "0.7.8",
"three-stdlib": "2.36.1"
@@ -19,7 +23,9 @@
},
"exports": {
".": "./src/index.ts",
- "./steps": "./src/steps.ts"
+ "./steps": "./src/steps.ts",
+ "./canvas": "./src/ModelCanvas.tsx",
+ "./model-preview": "./src/ModelPreview.tsx"
},
"peerDependencies": {
"react": "catalog:",
diff --git a/packages/viewer/src/AssemblyViewer.tsx b/packages/viewer/src/AssemblyViewer.tsx
index 3eedfb072d..1e66e83eae 100644
--- a/packages/viewer/src/AssemblyViewer.tsx
+++ b/packages/viewer/src/AssemblyViewer.tsx
@@ -1,6 +1,8 @@
import { GizmoHelper, GizmoViewcube, OrbitControls } from "@react-three/drei";
-import { Canvas } from "@react-three/fiber";
-import type { ReactNode } from "react";
+import { Canvas, useFrame, useThree } from "@react-three/fiber";
+import { type ReactNode, useEffect, useRef } from "react";
+import { Vector3 } from "three";
+import type { OrbitControls as OrbitControlsImpl } from "three-stdlib";
import { cn } from "./utils";
export type AssemblyViewerProps = {
@@ -8,6 +10,8 @@ export type AssemblyViewerProps = {
mode?: "dark" | "light";
/** Orientation cube in the top-right with click-to-snap views */
viewCube?: boolean;
+ /** When false, orbit/zoom/pan are disabled so page scroll passes through. */
+ interactive?: boolean;
className?: string;
};
@@ -20,6 +24,7 @@ export function AssemblyViewer({
children,
mode = "dark",
viewCube = true,
+ interactive = true,
className
}: AssemblyViewerProps) {
const isDarkMode = mode === "dark";
@@ -33,7 +38,10 @@ export function AssemblyViewer({
)}
>
<Canvas
- gl={{ antialias: true, alpha: true }}
+ // Logarithmic depth buffer: distributes depth precision across a huge
+ // CAD scale range (metre-scale body, mm-scale parts) so coplanar faces
+ // don't z-fight into shimmering seams.
+ gl={{ antialias: true, alpha: true, logarithmicDepthBuffer: true }}
// Cap the render resolution: a 3x-retina panel otherwise renders ~9x the
// pixels, which is the main fill-rate cost when orbiting a dense model.
// 2x keeps edges crisp without paying for the top DPR tier.
@@ -59,7 +67,16 @@ export function AssemblyViewer({
/>
<directionalLight position={[1, 1, 1]} intensity={1.6} />
<directionalLight position={[-1, 0.5, -1]} intensity={0.8} />
- <OrbitControls makeDefault enableDamping dampingFactor={0.1} />
+ <OrbitControls
+ makeDefault
+ enabled={interactive}
+ enableDamping
+ dampingFactor={0.1}
+ // OrbitControls' own dolly snaps (it resets `scale` every frame), so we
+ // drive the zoom ourselves for glide — see ZoomInertia below.
+ enableZoom={false}
+ />
+ <ZoomInertia enabled={interactive} />
{viewCube && (
// GizmoHelper animates the default OrbitControls on face clicks
<GizmoHelper alignment="top-right" margin={[56, 56]}>
@@ -81,3 +98,66 @@ export function AssemblyViewer({
</div>
);
}
+
+// Wheel → zoom impulse (accumulated into velocity). Larger = zoom reaches further
+// per notch.
+const ZOOM_SENSITIVITY = 0.00016;
+// Per-frame velocity decay. Higher = longer glide / more inertia (0.9 ≈ ~0.4s,
+// 0.92 ≈ ~0.6s of coast).
+const ZOOM_FRICTION = 0.92;
+const ZOOM_EPSILON = 1e-4;
+
+/**
+ * Inertial dolly. `OrbitControls` applies its wheel zoom instantly (it zeroes the
+ * dolly `scale` every `update()`), so with its own zoom disabled we accumulate a
+ * velocity from the wheel and ease the camera in/out over subsequent frames — the
+ * zoom coasts to a stop instead of stepping. Zooms toward the orbit target,
+ * clamped to the controls' min/max distance.
+ */
+function ZoomInertia({ enabled }: { enabled: boolean }) {
+ const camera = useThree((state) => state.camera);
+ const controls = useThree(
+ (state) => state.controls
+ ) as unknown as OrbitControlsImpl | null;
+ const gl = useThree((state) => state.gl);
+ const velocity = useRef(0);
+
+ useEffect(() => {
+ if (!enabled) {
+ velocity.current = 0;
+ return;
+ }
+ const el = gl.domElement;
+ const onWheel = (event: WheelEvent) => {
+ event.preventDefault();
+ velocity.current += event.deltaY * ZOOM_SENSITIVITY;
+ };
+ el.addEventListener("wheel", onWheel, { passive: false });
+ return () => el.removeEventListener("wheel", onWheel);
+ }, [enabled, gl]);
+
+ const offset = useRef(new Vector3());
+ useFrame(() => {
+ if (!controls || Math.abs(velocity.current) < ZOOM_EPSILON) return;
+ const dist = offset.current
+ .subVectors(camera.position, controls.target)
+ .length();
+ if (dist === 0) {
+ velocity.current = 0;
+ return;
+ }
+ const min = controls.minDistance || 0.001;
+ const max = controls.maxDistance || Number.POSITIVE_INFINITY;
+ const next = Math.min(
+ Math.max(dist * Math.exp(velocity.current), min),
+ max
+ );
+ camera.position
+ .copy(controls.target)
+ .addScaledVector(offset.current.divideScalar(dist), next);
+ controls.update();
+ velocity.current *= ZOOM_FRICTION;
+ });
+
+ return null;
+}
diff --git a/packages/viewer/src/ModelCanvas.tsx b/packages/viewer/src/ModelCanvas.tsx
new file mode 100644
index 0000000000..4fab07e66f
--- /dev/null
+++ b/packages/viewer/src/ModelCanvas.tsx
@@ -0,0 +1,324 @@
+import { useThree } from "@react-three/fiber";
+import { useCallback, useEffect, useRef, useState } from "react";
+import { LuRotateCw } from "react-icons/lu";
+import {
+ Box3,
+ type Mesh,
+ type Object3D,
+ PerspectiveCamera,
+ Vector3
+} from "three";
+import type { OrbitControls as OrbitControlsImpl } from "three-stdlib";
+import { AssemblyViewer } from "./AssemblyViewer";
+import { useAssembly } from "./useAssembly";
+import { cn } from "./utils";
+
+/** Model measurements in model-space units (CAD tessellations are mm). */
+export type ModelMetrics = {
+ dimensions: { x: number; y: number; z: number };
+ /** Surface area (mm²), or null when skipped on a very large mesh. */
+ surfaceArea: number | null;
+ /** Enclosed volume (mm³), or null when skipped / mesh isn't closed. */
+ volume: number | null;
+};
+
+export type ModelCanvasProps = {
+ /** URL of a meshopt-compressed GLB (the assembler's optimised / LOD artifact). */
+ glbUrl: string | null;
+ /** Alternative source: an async factory producing a ready Object3D (the raw
+ * WASM fallback tier). Used when `glbUrl` is null; the factory lives in the
+ * caller's lazy chunk so this component stays lean. Re-created factory =
+ * reload (memoize it). */
+ loadObject?: (() => Promise<Object3D>) | null;
+ mode?: "dark" | "light";
+ /** Orientation cube in the top-right (default true). */
+ viewCube?: boolean;
+ /** Fit the camera to the model's bounds once it loads (default true). */
+ autoFrame?: boolean;
+ /** Gate orbit/zoom/pan — false shows the model but passes scroll through. */
+ interactive?: boolean;
+ /** Bump this to re-frame the camera (the "reset view" action). */
+ resetSignal?: number;
+ /** Fired once the GLB has loaded and framed — the cross-fade trigger. */
+ onLoaded?: () => void;
+ /** Fired once with the loaded model's measurements (bbox always; area/volume
+ * when the mesh is small enough to measure client-side). */
+ onMetrics?: (metrics: ModelMetrics) => void;
+ className?: string;
+};
+
+// Above this triangle count, skip the O(n) area/volume sweep — it would jank the
+// main thread. Dimensions (bbox) are always cheap. Exact mass properties should
+// come from the assembler (OCCT) for big models.
+const MAX_MEASURE_TRIS = 1_500_000;
+
+/**
+ * Standalone static GLB viewer — the reusable core behind the assembly player.
+ * Loads a meshopt GLB (via `useAssembly`), frames it, applies the CAD depth
+ * fixes (near/far range + per-material polygon offset), and reports the model's
+ * measurements. No steps, motion, or picking — just orbit + view. The
+ * interactive tier of the progressive `ModelPreview`; also usable anywhere a
+ * single optimised model needs showing.
+ */
+export function ModelCanvas({
+ glbUrl,
+ loadObject = null,
+ mode = "dark",
+ viewCube = true,
+ autoFrame = true,
+ interactive = true,
+ resetSignal = 0,
+ onLoaded,
+ onMetrics,
+ className
+}: ModelCanvasProps) {
+ const [reloadKey, setReloadKey] = useState(0);
+ const assembly = useAssembly(glbUrl, null, reloadKey);
+ const raw = useLoadedObject(glbUrl ? null : loadObject, reloadKey);
+ const { scene, isLoading, error } = glbUrl ? assembly : raw;
+
+ const onLoadedRef = useRef(onLoaded);
+ onLoadedRef.current = onLoaded;
+ const onMetricsRef = useRef(onMetrics);
+ onMetricsRef.current = onMetrics;
+
+ useEffect(() => {
+ if (!scene) return;
+ onLoadedRef.current?.();
+ onMetricsRef.current?.(measureModel(scene));
+ }, [scene]);
+
+ return (
+ <div className={cn("relative h-full w-full", className)}>
+ <AssemblyViewer
+ mode={mode}
+ viewCube={viewCube}
+ interactive={interactive}
+ className="absolute inset-0"
+ >
+ {scene && (
+ <ModelScene
+ scene={scene}
+ autoFrame={autoFrame}
+ resetSignal={resetSignal}
+ />
+ )}
+ </AssemblyViewer>
+ {isLoading && (
+ <div className="pointer-events-none absolute inset-0 flex items-center justify-center">
+ <svg
+ className="h-6 w-6 animate-spin text-muted-foreground"
+ viewBox="0 0 24 24"
+ fill="none"
+ aria-label="Loading model"
+ >
+ <circle
+ className="opacity-25"
+ cx="12"
+ cy="12"
+ r="10"
+ stroke="currentColor"
+ strokeWidth="4"
+ />
+ <path
+ className="opacity-75"
+ fill="currentColor"
+ d="M4 12a8 8 0 018-8v4a4 4 0 00-4 4H4z"
+ />
+ </svg>
+ </div>
+ )}
+ {error && (
+ <div className="absolute inset-0 flex flex-col items-center justify-center gap-3 p-4 text-center">
+ <p className="max-w-xs text-sm text-muted-foreground">
+ Couldn't load the 3D model.
+ </p>
+ <button
+ type="button"
+ onClick={() => setReloadKey((n) => n + 1)}
+ className="flex items-center gap-1.5 rounded-md border border-border bg-popover px-3 py-1.5 text-xs font-medium text-foreground shadow-sm transition-transform hover:bg-accent active:scale-[0.96]"
+ >
+ <LuRotateCw className="size-3.5" />
+ Retry
+ </button>
+ </div>
+ )}
+ </div>
+ );
+}
+
+/** Drive an async Object3D factory with the same {scene,isLoading,error} shape
+ * `useAssembly` returns, so either source plugs into the same render path. */
+function useLoadedObject(
+ loadObject: (() => Promise<Object3D>) | null,
+ reloadKey: number
+): { scene: Object3D | null; isLoading: boolean; error: string | null } {
+ const [state, setState] = useState<{
+ scene: Object3D | null;
+ isLoading: boolean;
+ error: string | null;
+ }>({ scene: null, isLoading: Boolean(loadObject), error: null });
+
+ // biome-ignore lint/correctness/useExhaustiveDependencies: reloadKey re-runs the load on retry without being read inside
+ useEffect(() => {
+ if (!loadObject) {
+ setState({ scene: null, isLoading: false, error: null });
+ return;
+ }
+ let cancelled = false;
+ setState({ scene: null, isLoading: true, error: null });
+ loadObject().then(
+ (scene) => {
+ if (!cancelled) setState({ scene, isLoading: false, error: null });
+ },
+ (e: unknown) => {
+ if (!cancelled) {
+ setState({
+ scene: null,
+ isLoading: false,
+ error: e instanceof Error ? e.message : String(e)
+ });
+ }
+ }
+ );
+ return () => {
+ cancelled = true;
+ };
+ }, [loadObject, reloadKey]);
+
+ return state;
+}
+
+function ModelScene({
+ scene,
+ autoFrame,
+ resetSignal
+}: {
+ scene: Object3D;
+ autoFrame: boolean;
+ resetSignal: number;
+}) {
+ const camera = useThree((state) => state.camera);
+ const controls = useThree(
+ (state) => state.controls
+ ) as unknown as OrbitControlsImpl | null;
+
+ // Fit the perspective near/far planes to the model. A static 0.1 → 100000
+ // range spends nearly all depth precision right in front of `near`, so
+ // coplanar CAD faces z-fight into a moiré at model distance. Sizing the range
+ // to the model diagonal keeps them stable.
+ useEffect(() => {
+ if (!(camera instanceof PerspectiveCamera)) return;
+ const box = new Box3().setFromObject(scene);
+ if (box.isEmpty()) return;
+ const diag = box.getSize(new Vector3()).length();
+ if (!(diag > 0)) return;
+ camera.near = Math.max(diag / 500, 0.01);
+ camera.far = diag * 20;
+ camera.updateProjectionMatrix();
+ }, [camera, scene]);
+
+ // Coincident-face z-fighting across the model's scale range is handled by the
+ // renderer's logarithmic depth buffer (`logarithmicDepthBuffer` on the Canvas)
+ // plus the near/far fit above.
+
+ const frameBox = useCallback(
+ (box: Box3) => {
+ if (box.isEmpty() || !controls) return;
+ const center = box.getCenter(new Vector3());
+ const radius = box.getSize(new Vector3()).length() / 2;
+ const fov = camera instanceof PerspectiveCamera ? camera.fov : 45;
+ // Fit the bounding sphere with a small margin. Lower factors zoom in more —
+ // the sphere circumscribes the model, so a tight fit still leaves headroom.
+ const distance = Math.max(
+ (radius / Math.tan(((fov / 2) * Math.PI) / 180)) * 1.1,
+ radius * 1.5
+ );
+ const direction = camera.position
+ .clone()
+ .sub(controls.target)
+ .normalize();
+ // Front-top-right isometric (models are Z-up, -Y front).
+ if (direction.lengthSq() === 0) direction.set(1, -1, 1).normalize();
+ camera.position.copy(center).addScaledVector(direction, distance);
+ controls.target.copy(center);
+ controls.update();
+ },
+ [camera, controls]
+ );
+
+ // Frame once per loaded scene.
+ const framedRef = useRef<Object3D | null>(null);
+ useEffect(() => {
+ if (!autoFrame || !controls || framedRef.current === scene) return;
+ framedRef.current = scene;
+ frameBox(new Box3().setFromObject(scene));
+ }, [scene, controls, autoFrame, frameBox]);
+
+ // Re-frame on demand (the reset-view action). Skip the initial value so it
+ // doesn't double-frame on mount.
+ const resetSeenRef = useRef(resetSignal);
+ useEffect(() => {
+ if (resetSignal === resetSeenRef.current) return;
+ resetSeenRef.current = resetSignal;
+ frameBox(new Box3().setFromObject(scene));
+ }, [resetSignal, scene, frameBox]);
+
+ return <primitive object={scene} />;
+}
+
+/** Bounding-box dimensions (always) + surface area / volume (small meshes). */
+function measureModel(scene: Object3D): ModelMetrics {
+ scene.updateMatrixWorld(true);
+ const box = new Box3().setFromObject(scene);
+ const size = box.getSize(new Vector3());
+ const dimensions = { x: size.x, y: size.y, z: size.z };
+
+ let triangles = 0;
+ scene.traverse((object) => {
+ const mesh = object as Mesh;
+ if (!mesh.isMesh || !mesh.geometry) return;
+ const geom = mesh.geometry;
+ triangles += geom.index
+ ? geom.index.count / 3
+ : (geom.attributes.position?.count ?? 0) / 3;
+ });
+ if (triangles === 0 || triangles > MAX_MEASURE_TRIS) {
+ return { dimensions, surfaceArea: null, volume: null };
+ }
+
+ let area = 0;
+ let volume = 0;
+ const a = new Vector3();
+ const b = new Vector3();
+ const c = new Vector3();
+ const ab = new Vector3();
+ const ac = new Vector3();
+ const cross = new Vector3();
+ scene.traverse((object) => {
+ const mesh = object as Mesh;
+ if (!mesh.isMesh || !mesh.geometry) return;
+ const pos = mesh.geometry.attributes.position;
+ if (!pos) return;
+ const idx = mesh.geometry.index;
+ const mw = mesh.matrixWorld;
+ const tri = (i0: number, i1: number, i2: number) => {
+ a.fromBufferAttribute(pos, i0).applyMatrix4(mw);
+ b.fromBufferAttribute(pos, i1).applyMatrix4(mw);
+ c.fromBufferAttribute(pos, i2).applyMatrix4(mw);
+ area += cross.subVectors(b, a).cross(ac.subVectors(c, a)).length() * 0.5;
+ // Signed volume of the tetrahedron (origin, a, b, c); sums to the enclosed
+ // volume for a closed mesh regardless of where the origin sits.
+ volume += a.dot(ab.copy(b).cross(c)) / 6;
+ };
+ if (idx) {
+ for (let i = 0; i < idx.count; i += 3) {
+ tri(idx.getX(i), idx.getX(i + 1), idx.getX(i + 2));
+ }
+ } else {
+ for (let i = 0; i < pos.count; i += 3) tri(i, i + 1, i + 2);
+ }
+ });
+
+ return { dimensions, surfaceArea: area, volume: Math.abs(volume) };
+}
diff --git a/packages/viewer/src/ModelPreview.tsx b/packages/viewer/src/ModelPreview.tsx
new file mode 100644
index 0000000000..30c8681abe
--- /dev/null
+++ b/packages/viewer/src/ModelPreview.tsx
@@ -0,0 +1,457 @@
+import { cn, IconButton } from "@carbon/react";
+import { lazy, Suspense, useEffect, useMemo, useRef, useState } from "react";
+import {
+ LuChevronDown,
+ LuDownload,
+ LuMaximize,
+ LuRotateCw,
+ LuTrash2
+} from "react-icons/lu";
+import type { ModelMetrics } from "./ModelCanvas";
+import { isRawRenderable } from "./raw/formats";
+
+// The three.js renderer is code-split: a page with a model ships only this tier
+// selector until the viewer scrolls into view, then loads three.js on demand.
+const ModelCanvas = lazy(() =>
+ import("./ModelCanvas").then((m) => ({ default: m.ModelCanvas }))
+);
+
+// Build-time switch for the in-browser raw-CAD (WASM) fallback tier: renders the
+// user's original upload (GLB/STL directly; STEP/IGES via occt-import-js) when
+// no assembler artifact exists. ON by default; a deployment that relies purely on
+// assembler artifacts opts out with VITE_CAD_VIEWER_USE_SERVER=true, and the
+// exact `import.meta.env.X` form is statically replaced by Vite so the whole
+// tier — occt WASM included — is then dead-code-eliminated from the build.
+const WASM_RAW_ENABLED = import.meta.env.VITE_CAD_VIEWER_USE_SERVER !== "true";
+const RawModelCanvas = WASM_RAW_ENABLED
+ ? lazy(() =>
+ import("./raw/RawModelCanvas").then((m) => ({
+ default: m.RawModelCanvas
+ }))
+ )
+ : null;
+
+export type ModelPreviewProps = {
+ /** True while a server GLB might still arrive (upload / optimise in flight).
+ * Distinguishes "preparing" (spinner) from "no preview available". */
+ awaitingModel?: boolean;
+ /** Instant single-draw LOD GLB (assembler), rendered immediately on visible. */
+ lodUrl?: string | null;
+ /** Full optimised GLB (assembler) — the interactive tier. */
+ optimizedUrl?: string | null;
+ /** Lossless assembly GLB — used as the interactive tier if no optimised one. */
+ glbUrl?: string | null;
+ /** Static poster image (thumbnail PNG) shown before any 3D loads. */
+ thumbnailUrl?: string | null;
+ /** The raw uploaded file's auth-proxied URL — the WASM fallback tier renders
+ * it in-browser when no assembler artifact exists (build-flag gated). */
+ rawUrl?: string | null;
+ /** A just-dropped local File for the same tier — instant preview while the
+ * upload / optimise is still in flight. */
+ rawFile?: File | null;
+ /** Filename for the download-GLB action (defaults to the URL basename). */
+ downloadName?: string;
+ /** Re-run optimise when the model settled with no GLB (shows a Retry button). */
+ onRetry?: () => void;
+ mode?: "dark" | "light";
+ onDelete?: () => void;
+ className?: string;
+};
+
+/**
+ * Progressive model preview. Renders the assembler's artifacts with three.js
+ * (`ModelCanvas`): the single-draw LOD paints instantly, the full optimised GLB
+ * cross-fades in on top. When there is no server GLB it shows a spinner (while
+ * one may still arrive) or a "preview unavailable" notice — there is no
+ * in-browser tessellation fallback. The renderer is lazy-imported and only
+ * mounts once the viewer scrolls into view. Chrome: dimensions/properties, unit
+ * toggle, download, reset view, click-to-interact.
+ */
+export function ModelPreview({
+ awaitingModel = false,
+ lodUrl = null,
+ optimizedUrl = null,
+ glbUrl = null,
+ thumbnailUrl = null,
+ rawUrl = null,
+ rawFile = null,
+ downloadName,
+ onRetry,
+ mode = "dark",
+ onDelete,
+ className
+}: ModelPreviewProps) {
+ const containerRef = useRef<HTMLDivElement>(null);
+ const inView = useInView(containerRef);
+ const [fullLoaded, setFullLoaded] = useState(false);
+ const [metrics, setMetrics] = useState<ModelMetrics | null>(null);
+ const [resetSignal, setResetSignal] = useState(0);
+ // Gate orbit until the user opts in, so scrolling the page over the viewer
+ // doesn't hijack the wheel (matches the WASM viewer's "click to interact").
+ const [interactive, setInteractive] = useState(false);
+
+ const interactiveUrl = optimizedUrl ?? glbUrl;
+ // The instant 3D layer: the LOD if it's distinct from the interactive model
+ // (else the interactive model is the only 3D layer).
+ const showLodLayer = Boolean(lodUrl && interactiveUrl && !fullLoaded);
+ const mainUrl = interactiveUrl ?? lodUrl;
+ const hasServerModel = Boolean(mainUrl);
+ // Raw (WASM) fallback tier — only when compiled in, no artifact exists, and
+ // the raw source's format is one the in-browser loaders speak.
+ const rawFilename = rawFile?.name ?? rawUrl?.split("?")[0] ?? "";
+ const useRawTier = Boolean(
+ !hasServerModel &&
+ RawModelCanvas &&
+ (rawFile || rawUrl) &&
+ isRawRenderable(rawFilename)
+ );
+
+ return (
+ <div
+ ref={containerRef}
+ role="img"
+ aria-label="3D model preview"
+ className={cn(
+ "relative h-full min-h-[400px] w-full overflow-hidden rounded-lg border border-border bg-gradient-to-bl from-card from-50% via-card to-background shadow-md dark:border-none",
+ className
+ )}
+ >
+ {hasServerModel || useRawTier ? (
+ <>
+ {/* Tier 0: instant poster — thumbnail image while the 3D boots. */}
+ {thumbnailUrl && !fullLoaded && (
+ <img
+ src={thumbnailUrl}
+ alt=""
+ aria-hidden
+ className="absolute inset-0 h-full w-full object-contain"
+ />
+ )}
+ {inView && (
+ <Suspense fallback={null}>
+ {/* Tier 0 (3D): single-draw LOD — one draw call, near-instant. */}
+ {showLodLayer && lodUrl && (
+ <div className="absolute inset-0">
+ <ModelCanvas
+ glbUrl={lodUrl}
+ mode={mode}
+ viewCube={false}
+ interactive={false}
+ />
+ </div>
+ )}
+ {/* Tier 1: the full model, cross-faded in once loaded. The raw
+ (WASM) tier plugs in here through the same canvas + chrome. */}
+ <div
+ className="absolute inset-0 transition-opacity duration-300"
+ style={{ opacity: fullLoaded || !showLodLayer ? 1 : 0 }}
+ >
+ {useRawTier && RawModelCanvas ? (
+ <RawModelCanvas
+ url={rawUrl}
+ file={rawFile}
+ filename={rawFilename}
+ mode={mode}
+ interactive={interactive}
+ resetSignal={resetSignal}
+ onLoaded={() => setFullLoaded(true)}
+ onMetrics={setMetrics}
+ />
+ ) : (
+ <ModelCanvas
+ glbUrl={mainUrl}
+ mode={mode}
+ interactive={interactive}
+ resetSignal={resetSignal}
+ onLoaded={() => setFullLoaded(true)}
+ onMetrics={setMetrics}
+ />
+ )}
+ </div>
+ </Suspense>
+ )}
+
+ {/* Measurements + unit toggle (top-left), like the WASM viewer. */}
+ {metrics && fullLoaded && <ModelMetricsPanel metrics={metrics} />}
+
+ {/* Click-to-interact gate. */}
+ {fullLoaded && !interactive && (
+ <button
+ type="button"
+ onClick={() => setInteractive(true)}
+ aria-label="Click to interact with 3D model"
+ className="group absolute inset-0 z-10 flex items-end justify-center pb-4 focus:outline-none"
+ >
+ <span className="rounded-full border border-border bg-background/80 px-3 py-1 text-xs text-muted-foreground opacity-70 shadow-sm backdrop-blur-sm transition-opacity group-hover:opacity-100">
+ Click to interact
+ </span>
+ </button>
+ )}
+
+ {/* Toolbar: download + reset view + delete. */}
+ <div className="absolute bottom-2 right-2 z-20 flex items-center gap-1">
+ {mainUrl && (
+ <IconButton
+ aria-label="Download optimised GLB"
+ className="text-muted-foreground"
+ icon={<LuDownload />}
+ variant="ghost"
+ onClick={() => downloadFile(mainUrl, downloadName)}
+ />
+ )}
+ {fullLoaded && (
+ <IconButton
+ aria-label="Reset view"
+ className="text-muted-foreground"
+ icon={<LuMaximize />}
+ variant="ghost"
+ onClick={() => setResetSignal((n) => n + 1)}
+ />
+ )}
+ {onDelete && (
+ <IconButton
+ aria-label="Delete model"
+ className="text-muted-foreground hover:bg-destructive hover:text-destructive-foreground"
+ icon={<LuTrash2 />}
+ variant="ghost"
+ onClick={onDelete}
+ />
+ )}
+ </div>
+ </>
+ ) : inView && awaitingModel ? (
+ // Server GLB still being prepared (upload / optimise in flight) — spinner.
+ <div className="absolute inset-0 flex items-center justify-center">
+ <svg
+ className="h-6 w-6 animate-spin text-muted-foreground"
+ viewBox="0 0 24 24"
+ fill="none"
+ aria-label="Preparing model"
+ >
+ <circle
+ className="opacity-25"
+ cx="12"
+ cy="12"
+ r="10"
+ stroke="currentColor"
+ strokeWidth="4"
+ />
+ <path
+ className="opacity-75"
+ fill="currentColor"
+ d="M4 12a8 8 0 018-8v4a4 4 0 00-4 4H4z"
+ />
+ </svg>
+ </div>
+ ) : inView ? (
+ // Settled with no server GLB (optimise failed / non-mesh). No in-browser
+ // tessellation fallback — surface the state instead of a dead spinner.
+ <div className="absolute inset-0 flex flex-col items-center justify-center gap-3 p-4 text-center">
+ <p className="text-sm text-muted-foreground">
+ 3D preview unavailable
+ </p>
+ <div className="flex items-center gap-2">
+ {onRetry && (
+ <button
+ type="button"
+ onClick={onRetry}
+ className="flex items-center gap-1.5 rounded-md border border-border bg-popover px-3 py-1.5 text-xs font-medium text-foreground shadow-sm transition-transform hover:bg-accent active:scale-[0.96]"
+ >
+ <LuRotateCw className="size-3.5" />
+ Retry
+ </button>
+ )}
+ {onDelete && (
+ <IconButton
+ aria-label="Delete model"
+ className="text-muted-foreground hover:bg-destructive hover:text-destructive-foreground"
+ icon={<LuTrash2 />}
+ variant="ghost"
+ onClick={onDelete}
+ />
+ )}
+ </div>
+ </div>
+ ) : null}
+ </div>
+ );
+}
+
+type UnitSystem = "metric" | "imperial";
+
+const MM_PER_IN = 25.4;
+
+/** Dimensions + surface area / volume, with an mm/in toggle. Model space is mm. */
+function ModelMetricsPanel({ metrics }: { metrics: ModelMetrics }) {
+ const [unit, setUnit] = useState<UnitSystem>("imperial");
+ const [open, setOpen] = useState(false);
+ const imperial = unit === "imperial";
+
+ const fmt = useMemo(
+ () =>
+ new Intl.NumberFormat(undefined, {
+ maximumFractionDigits: imperial ? 3 : 1,
+ minimumFractionDigits: 0
+ }),
+ [imperial]
+ );
+
+ const linear = (mm: number) => fmt.format(imperial ? mm / MM_PER_IN : mm);
+ const areaVal = (mm2: number) =>
+ fmt.format(imperial ? mm2 / MM_PER_IN ** 2 : mm2);
+ const volVal = (mm3: number) =>
+ fmt.format(imperial ? mm3 / MM_PER_IN ** 3 : mm3);
+ const u = imperial ? "in" : "mm";
+ const hasProps = metrics.surfaceArea !== null || metrics.volume !== null;
+
+ return (
+ <div
+ className={cn(
+ "absolute left-2 top-2 z-20 rounded-lg border border-border bg-popover p-2.5 text-xs text-popover-foreground shadow-md",
+ open ? "w-56" : "w-auto"
+ )}
+ >
+ <div className="flex items-center justify-between gap-2">
+ <button
+ type="button"
+ onClick={() => setOpen((o) => !o)}
+ aria-expanded={open}
+ className="flex items-center gap-1 text-[10px] font-medium uppercase tracking-wide text-muted-foreground transition-colors hover:text-foreground"
+ >
+ <LuChevronDown
+ className={cn("size-3 transition-transform", !open && "-rotate-90")}
+ />
+ Measurements
+ </button>
+ {open && <UnitToggle unit={unit} onChange={setUnit} />}
+ </div>
+
+ {open && (
+ <>
+ <div className="mt-2 flex flex-col gap-1 font-mono tabular-nums">
+ <Row
+ dot="bg-green-500"
+ label="W"
+ value={`${linear(metrics.dimensions.x)} ${u}`}
+ />
+ <Row
+ dot="bg-blue-500"
+ label="H"
+ value={`${linear(metrics.dimensions.y)} ${u}`}
+ />
+ <Row
+ dot="bg-red-500"
+ label="L"
+ value={`${linear(metrics.dimensions.z)} ${u}`}
+ />
+ </div>
+
+ {hasProps && (
+ <div className="mt-2 flex flex-col gap-1 border-t border-border/50 pt-2 font-mono tabular-nums text-muted-foreground">
+ <Row
+ label="Area"
+ value={
+ metrics.surfaceArea === null
+ ? "—"
+ : `${areaVal(metrics.surfaceArea)} ${u}²`
+ }
+ />
+ <Row
+ label="Volume"
+ value={
+ metrics.volume === null
+ ? "—"
+ : `${volVal(metrics.volume)} ${u}³`
+ }
+ />
+ </div>
+ )}
+ </>
+ )}
+ </div>
+ );
+}
+
+/** iOS-style segmented mm/in toggle — lighter than the tab pills. */
+function UnitToggle({
+ unit,
+ onChange
+}: {
+ unit: UnitSystem;
+ onChange: (u: UnitSystem) => void;
+}) {
+ return (
+ <div className="flex rounded-md bg-muted/60 p-0.5">
+ {(["metric", "imperial"] as const).map((value) => (
+ <button
+ key={value}
+ type="button"
+ onClick={() => onChange(value)}
+ className={cn(
+ "min-w-[30px] rounded px-2 py-1 text-center text-[11px] font-medium leading-none transition-colors",
+ unit === value
+ ? "bg-background text-foreground shadow-sm"
+ : "text-muted-foreground hover:text-foreground"
+ )}
+ >
+ {value === "metric" ? "mm" : "in"}
+ </button>
+ ))}
+ </div>
+ );
+}
+
+function Row({
+ dot,
+ label,
+ value
+}: {
+ dot?: string;
+ label: string;
+ value: string;
+}) {
+ return (
+ <div className="flex items-center justify-between gap-2">
+ <span className="flex items-center gap-1.5">
+ {dot && <span className={cn("size-2 rounded-full", dot)} />}
+ {label}
+ </span>
+ <span>{value}</span>
+ </div>
+ );
+}
+
+/** Trigger a browser download of a same-origin URL (the served GLB proxy). */
+function downloadFile(url: string, name?: string) {
+ const anchor = document.createElement("a");
+ anchor.href = url;
+ anchor.download = name ?? url.split("/").pop()?.split("?")[0] ?? "model.glb";
+ document.body.appendChild(anchor);
+ anchor.click();
+ anchor.remove();
+}
+
+/**
+ * True once the element has scrolled within `rootMargin` of the viewport — then
+ * it stays true (we only need to trigger the one-time lazy load). Native
+ * IntersectionObserver; no dependency.
+ */
+function useInView(ref: React.RefObject<Element | null>) {
+ const [inView, setInView] = useState(false);
+ useEffect(() => {
+ const el = ref.current;
+ if (!el || inView) return;
+ const observer = new IntersectionObserver(
+ (entries) => {
+ if (entries.some((entry) => entry.isIntersecting)) {
+ setInView(true);
+ observer.disconnect();
+ }
+ },
+ { rootMargin: "200px" }
+ );
+ observer.observe(el);
+ return () => observer.disconnect();
+ }, [ref, inView]);
+ return inView;
+}
diff --git a/packages/viewer/src/index.ts b/packages/viewer/src/index.ts
index 8b8caadbe2..dff954954f 100644
--- a/packages/viewer/src/index.ts
+++ b/packages/viewer/src/index.ts
@@ -14,6 +14,11 @@ export {
groupComponentNodeIds,
indexAssemblyGraph
} from "./graph";
+export {
+ ModelCanvas,
+ type ModelCanvasProps,
+ type ModelMetrics
+} from "./ModelCanvas";
export {
buildStepClip,
displayMotionForStep,
diff --git a/packages/viewer/src/raw/RawModelCanvas.tsx b/packages/viewer/src/raw/RawModelCanvas.tsx
new file mode 100644
index 0000000000..d95e0d421b
--- /dev/null
+++ b/packages/viewer/src/raw/RawModelCanvas.tsx
@@ -0,0 +1,31 @@
+// The raw (WASM) fallback tier: renders the user's original upload through the
+// SAME ModelCanvas as the artifact tiers — one renderer, one set of chrome.
+// Lazy chunk: ships only when the tier is compiled in (VITE_CAD_VIEWER_USE_SERVER
+// unset) and mounts, occt-import-js WASM included.
+
+import { useMemo } from "react";
+import { ModelCanvas, type ModelCanvasProps } from "../ModelCanvas";
+import { loadRawModel } from "./loadRawModel";
+
+export type RawModelCanvasProps = Omit<
+ ModelCanvasProps,
+ "glbUrl" | "loadObject"
+> & {
+ url?: string | null;
+ file?: File | null;
+ /** Format is detected from this (file name or storage path). */
+ filename: string;
+};
+
+export function RawModelCanvas({
+ url = null,
+ file = null,
+ filename,
+ ...canvasProps
+}: RawModelCanvasProps) {
+ const loadObject = useMemo(
+ () => () => loadRawModel({ url, file, filename }),
+ [url, file, filename]
+ );
+ return <ModelCanvas glbUrl={null} loadObject={loadObject} {...canvasProps} />;
+}
diff --git a/packages/viewer/src/raw/formats.ts b/packages/viewer/src/raw/formats.ts
new file mode 100644
index 0000000000..c7f6ab1ab8
--- /dev/null
+++ b/packages/viewer/src/raw/formats.ts
@@ -0,0 +1,33 @@
+// Raw-tier format detection. Deliberately dependency-free: ModelPreview imports
+// this eagerly to decide whether the (lazy) WASM tier is worth mounting, without
+// pulling three/occt into the eager bundle.
+
+export const OCCT_EXTS = ["step", "stp", "iges", "igs", "brep", "brp"];
+/** Mesh formats three-stdlib loads directly (no WASM). */
+export const MESH_EXTS = [
+ "glb",
+ "gltf",
+ "stl",
+ "obj",
+ "ply",
+ "dae",
+ "fbx",
+ "3ds",
+ "3mf",
+ "amf",
+ "off",
+ // dotbim: plain JSON meshes, hand-parsed.
+ "bim"
+];
+/** Rhino .3dm via the official rhino3dm WASM (lazy, ~4MB, only for .3dm). */
+export const RHINO_EXTS = ["3dm"];
+export const RAW_RENDERABLE_EXTS = [...MESH_EXTS, ...RHINO_EXTS, ...OCCT_EXTS];
+
+export function rawExtension(filename: string): string {
+ const base = filename.split("?")[0] ?? "";
+ return base.split(".").pop()?.toLowerCase() ?? "";
+}
+
+export function isRawRenderable(filename: string): boolean {
+ return RAW_RENDERABLE_EXTS.includes(rawExtension(filename));
+}
diff --git a/packages/viewer/src/raw/loadRawModel.ts b/packages/viewer/src/raw/loadRawModel.ts
new file mode 100644
index 0000000000..37d48a8913
--- /dev/null
+++ b/packages/viewer/src/raw/loadRawModel.ts
@@ -0,0 +1,371 @@
+// In-browser raw-model loading for the WASM fallback tier: turns the user's
+// original upload (GLB/glTF/STL directly; STEP/IGES/BREP via the occt-import-js
+// WASM tessellator) into a THREE Object3D for the existing ModelCanvas. Lives in
+// its own lazily-imported chunk — nothing here loads unless the tier renders.
+
+// occt-import-js ships no types; the reference makes our declaration travel with
+// this file into every consuming app's program (erp compiles package source).
+/// <reference path="./occt-import-js.d.ts" />
+
+import {
+ BufferAttribute,
+ BufferGeometry,
+ Color,
+ DoubleSide,
+ Group,
+ Mesh,
+ MeshStandardMaterial,
+ type Object3D
+} from "three";
+
+export type RawSource = {
+ /** Same-origin URL of the raw file (the auth-proxied /file/preview route). */
+ url?: string | null;
+ /** A just-dropped local File — renders before the upload even finishes. */
+ file?: File | null;
+ /** Name the format is detected from (file name or storage path). */
+ filename: string;
+};
+
+import { RAW_RENDERABLE_EXTS, rawExtension } from "./formats";
+
+export async function loadRawModel(source: RawSource): Promise<Object3D> {
+ const ext = rawExtension(source.filename);
+ if (!RAW_RENDERABLE_EXTS.includes(ext)) {
+ throw new Error(`unsupported raw model format: ${ext || "unknown"}`);
+ }
+ if (ext === "glb" || ext === "gltf") return loadGltf(source);
+ const bytes = await readBytes(source);
+ switch (ext) {
+ case "stl":
+ return loadStl(bytes);
+ case "obj":
+ case "ply":
+ case "dae":
+ case "fbx":
+ case "3ds":
+ case "3mf":
+ case "amf":
+ return loadMesh(bytes, ext);
+ case "off":
+ return loadOff(bytes);
+ case "bim":
+ return loadDotbim(bytes);
+ case "3dm":
+ return loadRhino(bytes);
+ default:
+ return loadOcct(bytes, ext);
+ }
+}
+
+async function readBytes(source: RawSource): Promise<ArrayBuffer> {
+ if (source.file) return source.file.arrayBuffer();
+ if (!source.url) throw new Error("raw model source has no url or file");
+ // Same-origin route; cookies ride along for the auth check.
+ const res = await fetch(source.url);
+ if (!res.ok) throw new Error(`raw model fetch failed: ${res.status}`);
+ return res.arrayBuffer();
+}
+
+async function loadGltf(source: RawSource): Promise<Object3D> {
+ const { GLTFLoader } = await import("three-stdlib");
+ const loader = new GLTFLoader();
+ if (source.file) {
+ const buffer = await source.file.arrayBuffer();
+ const gltf = await loader.parseAsync(buffer, "");
+ return gltf.scene;
+ }
+ const gltf = await loader.loadAsync(source.url!);
+ return gltf.scene;
+}
+
+async function loadStl(bytes: ArrayBuffer): Promise<Object3D> {
+ const { STLLoader } = await import("three-stdlib");
+ const geometry = new STLLoader().parse(bytes);
+ if (!geometry.attributes.normal) geometry.computeVertexNormals();
+ return new Mesh(geometry, defaultMaterial());
+}
+
+/** The three-stdlib mesh loaders (no WASM): obj/ply/dae/fbx/3ds/3mf/amf. Their
+ * own materials are kept when the format carries them; bare geometry gets the
+ * default part material and computed normals. */
+async function loadMesh(bytes: ArrayBuffer, ext: string): Promise<Object3D> {
+ const stdlib = await import("three-stdlib");
+ const text = () => new TextDecoder().decode(bytes);
+ let object: Object3D;
+ switch (ext) {
+ case "obj":
+ object = new stdlib.OBJLoader().parse(text());
+ break;
+ case "ply": {
+ const geometry = new stdlib.PLYLoader().parse(bytes);
+ if (!geometry.attributes.normal) geometry.computeVertexNormals();
+ const material = defaultMaterial();
+ if (geometry.attributes.color) material.vertexColors = true;
+ return new Mesh(geometry, material);
+ }
+ case "dae":
+ object = new stdlib.ColladaLoader().parse(text(), "").scene;
+ break;
+ case "fbx":
+ object = new stdlib.FBXLoader().parse(bytes, "");
+ break;
+ case "3ds":
+ object = new stdlib.TDSLoader().parse(bytes, "");
+ break;
+ case "3mf":
+ object = new stdlib.ThreeMFLoader().parse(bytes);
+ break;
+ case "amf":
+ object = new stdlib.AMFLoader().parse(bytes);
+ break;
+ default:
+ throw new Error(`unsupported mesh format: ${ext}`);
+ }
+ object.traverse((child) => {
+ const mesh = child as Mesh;
+ if (!mesh.isMesh || !mesh.geometry) return;
+ if (!mesh.geometry.attributes.normal) mesh.geometry.computeVertexNormals();
+ if (!mesh.material) mesh.material = defaultMaterial();
+ });
+ return object;
+}
+
+/** OFF (Object File Format): tiny text format, hand-parsed — no loader ships in
+ * three-stdlib. Polygon faces are fan-triangulated. */
+async function loadOff(bytes: ArrayBuffer): Promise<Object3D> {
+ const tokens = new TextDecoder()
+ .decode(bytes)
+ .split("\n")
+ .map((line) => line.replace(/#.*$/, "").trim())
+ .filter(Boolean)
+ .join(" ")
+ .split(/\s+/);
+ let i = 0;
+ if (tokens[i] === "OFF") i++;
+ const nVerts = Number(tokens[i++]);
+ const nFaces = Number(tokens[i++]);
+ i++; // edge count, unused
+ if (!Number.isFinite(nVerts) || !Number.isFinite(nFaces)) {
+ throw new Error("invalid OFF file");
+ }
+ const positions = new Float32Array(nVerts * 3);
+ for (let v = 0; v < nVerts * 3; v++) positions[v] = Number(tokens[i++]);
+ const indices: number[] = [];
+ for (let f = 0; f < nFaces; f++) {
+ const count = Number(tokens[i++]);
+ const face: number[] = [];
+ for (let c = 0; c < count; c++) face.push(Number(tokens[i++]));
+ for (let t = 1; t + 1 < face.length; t++) {
+ const [a, b, c] = [face[0], face[t], face[t + 1]];
+ if (a === undefined || b === undefined || c === undefined) continue;
+ indices.push(a, b, c);
+ }
+ }
+ const geometry = new BufferGeometry();
+ geometry.setAttribute("position", new BufferAttribute(positions, 3));
+ geometry.setIndex(indices);
+ geometry.computeVertexNormals();
+ return new Mesh(geometry, defaultMaterial());
+}
+
+/** STEP/IGES/BREP → meshes via the occt-import-js WASM build (OCCT compiled to
+ * WebAssembly — the same kernel the assembler uses server-side). */
+async function loadOcct(bytes: ArrayBuffer, ext: string): Promise<Object3D> {
+ const [{ default: occtimportjs }, { default: wasmUrl }] = await Promise.all([
+ import("occt-import-js"),
+ import("occt-import-js/dist/occt-import-js.wasm?url")
+ ]);
+ const occt = await occtimportjs({
+ locateFile: () => wasmUrl
+ });
+
+ const content = new Uint8Array(bytes);
+ const result =
+ ext === "brep" || ext === "brp"
+ ? occt.ReadBrepFile(content, null)
+ : ext === "iges" || ext === "igs"
+ ? occt.ReadIgesFile(content, null)
+ : occt.ReadStepFile(content, null);
+ if (!result?.success || !result.meshes?.length) {
+ throw new Error(`could not tessellate ${ext} file in the browser`);
+ }
+
+ const group = new Group();
+ for (const meshData of result.meshes) {
+ const geometry = new BufferGeometry();
+ geometry.setAttribute(
+ "position",
+ new BufferAttribute(
+ new Float32Array(meshData.attributes.position.array),
+ 3
+ )
+ );
+ if (meshData.attributes.normal) {
+ geometry.setAttribute(
+ "normal",
+ new BufferAttribute(
+ new Float32Array(meshData.attributes.normal.array),
+ 3
+ )
+ );
+ } else {
+ geometry.computeVertexNormals();
+ }
+ geometry.setIndex(
+ new BufferAttribute(new Uint32Array(meshData.index.array), 1)
+ );
+ const material = defaultMaterial();
+ if (meshData.color) {
+ material.color = new Color(
+ meshData.color[0],
+ meshData.color[1],
+ meshData.color[2]
+ );
+ }
+ group.add(new Mesh(geometry, material));
+ }
+ return group;
+}
+
+/** dotbim (.bim): plain JSON — shared meshes instanced by elements carrying a
+ * translation + quaternion + color. Hand-parsed; no dependency. */
+async function loadDotbim(bytes: ArrayBuffer): Promise<Object3D> {
+ type DotbimElement = {
+ mesh_id: number;
+ vector?: { x: number; y: number; z: number };
+ rotation?: { qx: number; qy: number; qz: number; qw: number };
+ color?: { r: number; g: number; b: number; a: number };
+ };
+ type DotbimFile = {
+ meshes?: { mesh_id: number; coordinates: number[]; indices: number[] }[];
+ elements?: DotbimElement[];
+ };
+ const parsed = JSON.parse(new TextDecoder().decode(bytes)) as DotbimFile;
+ if (!parsed.meshes?.length) throw new Error("invalid dotbim file");
+
+ const geometries = new Map<number, BufferGeometry>();
+ for (const m of parsed.meshes) {
+ const geometry = new BufferGeometry();
+ geometry.setAttribute(
+ "position",
+ new BufferAttribute(new Float32Array(m.coordinates), 3)
+ );
+ geometry.setIndex(new BufferAttribute(new Uint32Array(m.indices), 1));
+ geometry.computeVertexNormals();
+ geometries.set(m.mesh_id, geometry);
+ }
+
+ const group = new Group();
+ const elements: DotbimElement[] = parsed.elements?.length
+ ? parsed.elements
+ : [...geometries.keys()].map((mesh_id) => ({ mesh_id }));
+ for (const el of elements) {
+ const geometry = geometries.get(el.mesh_id);
+ if (!geometry) continue;
+ const material = defaultMaterial();
+ if (el.color) {
+ material.color = new Color(
+ el.color.r / 255,
+ el.color.g / 255,
+ el.color.b / 255
+ );
+ if (el.color.a < 255) {
+ material.transparent = true;
+ material.opacity = el.color.a / 255;
+ }
+ }
+ const mesh = new Mesh(geometry, material);
+ if (el.rotation) {
+ mesh.quaternion.set(
+ el.rotation.qx,
+ el.rotation.qy,
+ el.rotation.qz,
+ el.rotation.qw
+ );
+ }
+ if (el.vector) mesh.position.set(el.vector.x, el.vector.y, el.vector.z);
+ group.add(mesh);
+ }
+ return group;
+}
+
+/** Rhino .3dm via the official rhino3dm WASM. Direct module use (no worker /
+ * library-path dance): meshes are taken as-is; Breps and Extrusions contribute
+ * their embedded render meshes. Curves/points/annotations are skipped. */
+async function loadRhino(bytes: ArrayBuffer): Promise<Object3D> {
+ const [{ default: rhino3dm }, { default: wasmUrl }] = await Promise.all([
+ import("rhino3dm"),
+ import("rhino3dm/rhino3dm.wasm?url")
+ ]);
+ // The shipped .d.ts types the factory as zero-arg, but it's an emscripten
+ // module factory — it accepts the standard init object; locateFile points the
+ // loader at Vite's hashed .wasm asset URL.
+ const factory = rhino3dm as unknown as (opts: {
+ locateFile: (path: string) => string;
+ }) => ReturnType<typeof rhino3dm>;
+ const rhino = await factory({ locateFile: () => wasmUrl });
+ const doc = rhino.File3dm.fromByteArray(new Uint8Array(bytes));
+ if (!doc) throw new Error("could not read 3dm file");
+
+ const { BufferGeometryLoader } = await import("three");
+ const geometryLoader = new BufferGeometryLoader();
+ const group = new Group();
+ const addRhinoMesh = (rhinoMesh: { toThreejsJSON: () => object }) => {
+ const geometry = geometryLoader.parse(rhinoMesh.toThreejsJSON());
+ if (!geometry.attributes.normal) geometry.computeVertexNormals();
+ group.add(new Mesh(geometry, defaultMaterial()));
+ };
+
+ const objects = doc.objects();
+ for (let i = 0; i < objects.count; i++) {
+ const geometry = objects.get(i)?.geometry();
+ if (!geometry) continue;
+ switch (geometry.objectType) {
+ case rhino.ObjectType.Mesh:
+ addRhinoMesh(geometry as unknown as { toThreejsJSON: () => object });
+ break;
+ case rhino.ObjectType.Brep: {
+ const brep = geometry as unknown as {
+ faces: () => {
+ count: number;
+ get: (i: number) => {
+ getMesh: (t: unknown) => { toThreejsJSON: () => object } | null;
+ };
+ };
+ };
+ const faces = brep.faces();
+ for (let f = 0; f < faces.count; f++) {
+ const mesh = faces.get(f).getMesh(rhino.MeshType.Any);
+ if (mesh) addRhinoMesh(mesh);
+ }
+ break;
+ }
+ case rhino.ObjectType.Extrusion: {
+ const mesh = (
+ geometry as unknown as {
+ getMesh: (t: unknown) => { toThreejsJSON: () => object } | null;
+ }
+ ).getMesh(rhino.MeshType.Any);
+ if (mesh) addRhinoMesh(mesh);
+ break;
+ }
+ default:
+ break;
+ }
+ }
+ if (group.children.length === 0) {
+ throw new Error("3dm file contains no renderable meshes");
+ }
+ return group;
+}
+
+function defaultMaterial(): MeshStandardMaterial {
+ // Matches the old WASM viewer's default part color (teal) for continuity.
+ return new MeshStandardMaterial({
+ color: new Color(0 / 255, 125 / 255, 125 / 255),
+ metalness: 0.1,
+ roughness: 0.6,
+ side: DoubleSide
+ });
+}
diff --git a/packages/viewer/src/raw/occt-import-js.d.ts b/packages/viewer/src/raw/occt-import-js.d.ts
new file mode 100644
index 0000000000..0e601049cb
--- /dev/null
+++ b/packages/viewer/src/raw/occt-import-js.d.ts
@@ -0,0 +1,25 @@
+declare module "occt-import-js" {
+ type OcctMesh = {
+ name?: string;
+ color?: [number, number, number];
+ attributes: {
+ position: { array: number[] };
+ normal?: { array: number[] };
+ };
+ index: { array: number[] };
+ };
+ type OcctResult = {
+ success: boolean;
+ root?: unknown;
+ meshes: OcctMesh[];
+ };
+ type OcctModule = {
+ ReadStepFile: (content: Uint8Array, params: unknown) => OcctResult;
+ ReadIgesFile: (content: Uint8Array, params: unknown) => OcctResult;
+ ReadBrepFile: (content: Uint8Array, params: unknown) => OcctResult;
+ };
+ const factory: (options?: {
+ locateFile?: (path: string) => string;
+ }) => Promise<OcctModule>;
+ export default factory;
+}
diff --git a/packages/viewer/src/useAssembly.ts b/packages/viewer/src/useAssembly.ts
index d20dbff01f..8bada6b66d 100644
--- a/packages/viewer/src/useAssembly.ts
+++ b/packages/viewer/src/useAssembly.ts
@@ -24,7 +24,9 @@ export type UseAssemblyResult = {
*/
export function useAssembly(
glbUrl: string | null,
- graphUrl: string | null
+ graphUrl: string | null,
+ /** Bump to force a re-fetch of the same URL (the "retry" action). */
+ reloadKey: number = 0
): UseAssemblyResult {
const [scene, setScene] = useState<Group | null>(null);
const [graph, setGraph] = useState<AssemblyGraph | null>(null);
@@ -77,7 +79,7 @@ export function useAssembly(
cancelled = true;
if (loadedScene) disposeObject(loadedScene);
};
- }, [glbUrl]);
+ }, [glbUrl, reloadKey]);
useEffect(() => {
if (!graphUrl) {
diff --git a/packages/viewer/src/vite-env.d.ts b/packages/viewer/src/vite-env.d.ts
new file mode 100644
index 0000000000..35206f9a33
--- /dev/null
+++ b/packages/viewer/src/vite-env.d.ts
@@ -0,0 +1,18 @@
+// This package ships raw source compiled by the consuming app's Vite build.
+// Type the Vite-injected globals the source references without depending on
+// vite (typecheck runs standalone via tsgo).
+interface ImportMetaEnv {
+ /** Build-time flag: "true" = server-artifacts-only viewer (the in-browser
+ * raw-CAD WASM tier and its occt-import-js chunk are dead-code-dropped).
+ * Unset/false (the default) = the WASM fallback tier is compiled in. */
+ readonly VITE_CAD_VIEWER_USE_SERVER?: string;
+}
+
+interface ImportMeta {
+ readonly env: ImportMetaEnv;
+}
+
+declare module "*.wasm?url" {
+ const url: string;
+ export default url;
+}
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 2beace32e1..d2307a8d93 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -546,6 +546,12 @@ importers:
specifier: 'catalog:'
version: 7.2.0
+ apps/assembler:
+ devDependencies:
+ sst:
+ specifier: 4.6.9
+ version: 4.6.9
+
apps/erp:
dependencies:
'@ai-sdk-tools/agents':
@@ -688,7 +694,7 @@ importers:
'@react-router/remix-routes-option-adapter':
specifier: 'catalog:'
'@react-router/serve':
specifier: 'catalog:'
@@ -733,7 +739,7 @@ importers:
'@vercel/react-router':
specifier: 'catalog:'
'@visx/responsive':
specifier: 2.17.0
version: 2.17.0([email protected])
@@ -778,7 +784,7 @@ importers:
inngest:
specifier: ^3.52.7
intl-parse-accept-language:
specifier: 'catalog:'
version: 1.0.0
@@ -929,6 +935,9 @@ importers:
tsup:
specifier: 'catalog:'
+ tus-js-client:
+ specifier: 4.3.1
+ version: 4.3.1
unified:
specifier: 11.0.5
version: 11.0.5
@@ -965,16 +974,16 @@ importers:
'@lingui/vite-plugin':
specifier: 'catalog:'
'@react-router/dev':
specifier: 'catalog:'
'@tailwindcss/typography':
specifier: 'catalog:'
version: 0.5.19([email protected])
'@tailwindcss/vite':
specifier: 'catalog:'
'@types/d3':
specifier: 7.4.3
version: 7.4.3
@@ -1034,13 +1043,13 @@ importers:
version: 5.8.3
vite:
specifier: 'catalog:'
vite-plugin-babel-macros:
specifier: 'catalog:'
vitest:
specifier: 'catalog:'
apps/mes:
dependencies:
@@ -1124,7 +1133,7 @@ importers:
'@lingui/vite-plugin':
specifier: 'catalog:'
'@nanostores/react':
specifier: 'catalog:'
@@ -1136,10 +1145,10 @@ importers:
'@react-router/dev':
specifier: 'catalog:'
'@react-router/remix-routes-option-adapter':
specifier: 'catalog:'
'@react-router/serve':
specifier: 'catalog:'
@@ -1160,7 +1169,7 @@ importers:
version: 0.5.19([email protected])
'@tailwindcss/vite':
specifier: 'catalog:'
'@tiptap/core':
specifier: 'catalog:'
version: 2.27.2(@tiptap/[email protected])
@@ -1202,7 +1211,7 @@ importers:
'@vercel/react-router':
specifier: 'catalog:'
'@xyflow/react':
specifier: 12.10.2
@@ -1320,13 +1329,13 @@ importers:
version: 5.8.3
vite:
specifier: 'catalog:'
vite-plugin-babel-macros:
specifier: 'catalog:'
vitest:
specifier: 'catalog:'
wait-on:
specifier: 'catalog:'
version: 7.2.0
@@ -3097,9 +3106,6 @@ importers:
nprogress:
specifier: 0.2.0
version: 0.2.0
- online-3d-viewer:
- specifier: 0.15.0
- version: 0.15.0
react-aria-components:
specifier: 1.0.1
@@ -3136,9 +3142,6 @@ importers:
tailwindcss-animate:
specifier: 'catalog:'
version: 1.0.7([email protected])
- three:
- specifier: 0.163.0
- version: 0.163.0
zustand:
specifier: 'catalog:'
@@ -3464,12 +3467,24 @@ importers:
packages/viewer:
dependencies:
+ '@carbon/react':
+ specifier: workspace:*
+ version: link:../react
'@react-three/drei':
specifier: 9.122.0
'@react-three/fiber':
specifier: 8.18.0
+ occt-import-js:
+ specifier: 0.0.23
+ version: 0.0.23
+ react-icons:
+ specifier: 'catalog:'
+ version: 5.6.0([email protected])
+ rhino3dm:
+ specifier: 8.17.0
+ version: 8.17.0
three:
specifier: 0.163.0
version: 0.163.0
@@ -9002,9 +9017,6 @@ packages:
'@sideway/[email protected]':
resolution: {integrity: sha512-RNiOoTPkptFtSVzQevY/yWtZwf/RxyVnPy/OcA9HBM3MlGDnBEYL5B41H0MTn0Uec8Hi+2qUtTfG2WWZBmMejQ==}
- '@simonwep/[email protected]':
- resolution: {integrity: sha512-oEYvv15PyfZzjoAzvXYt3UyNGwzsrpFxLaZKzkOSd0WYBVwLd19iJerePDONxC1iF6+DpcswPdLIM2KzCJuYFg==}
-
'@simplewebauthn/[email protected]':
resolution: {integrity: sha512-BE/UWv6FOToAdVk0EokzkqQQDOWtNydYlY6+OrmiZ5SCNmb41VehttboTetUM3T/fr6EAFYVXjz4My2wg230rQ==}
@@ -11057,6 +11069,9 @@ packages:
resolution: {integrity: sha512-pFGrxThWcWQ2MsAz6RtgeWe4NK2kUE1WfsrvvlctdII745EW9I0yflqhe7++M5LEc7bV2c/9/5zc8sFcpL0Drw==}
engines: {node: '>=0.1.90'}
+ resolution: {integrity: sha512-C8ikRNRMygCwaTx+Ek3Yr+OuZzgZjduCOfSQBjbM8V3MfgcjSTeto/GXP6PAwKvJz/v15b7GHZvx5rOlczFw/Q==}
+
resolution: {integrity: sha512-FQN4MRfuJeHf7cBbBMJFXhKSDq+2kAArBlmRBvcvFE5BB1HZKXtSFASDhdlz9zOYwxh8lDdnvmMOe/+5cdoEdg==}
engines: {node: '>= 0.8'}
@@ -11161,9 +11176,6 @@ packages:
resolution: {integrity: sha512-ei8Aos7ja0weRpFzJnEA9UHJ/7XQmqglbRwnf2ATjcB9Wq874VKH9kfjjirM6UhU2/E5fFYadylyhFldcqSidQ==}
engines: {node: '>=18'}
- resolution: {integrity: sha512-pxXSw1mYZPDGvTQqEc5vgIb83jGQKFGYWY76z4a7weZXUolw3G+OvpZqSRcfYOoOVUQJYEPsWeQK8pKEnUtWxQ==}
-
resolution: {integrity: sha512-es1U2+YTtzpwkxVLwAFdSpaIMyQaq0PBgm3YD1W3Qpsn1NAmO3KSgZfu+oGSWVu6NvLHoHCV/aYcsE5wiB7ALg==}
@@ -11241,6 +11253,9 @@ packages:
resolution: {integrity: sha512-l3nz3euub2QMg5ouu5U09Ew9Wf6/wQ8I++ch1loQ0ljmzhmfZYrH9fflS22i/PQEvsPvxCwxgz5q7UB8K1JO4Q==}
+ resolution: {integrity: sha512-p6JFxJc3M4OTD2li2qaHkDCw9SfMw82Ldr6OC9Je1aXiGfhx2W8p3GaoeaGrPJTUN9NirTM/KTxHWMUdR1rsUg==}
+
resolution: {integrity: sha512-gUY/qeHq/yNqqoCKNq4vtpFLdoCdvyNpWoC/KNjhGbhDuQpAM9sIQQKkXSNpXa9h5KySs/gzm7R88WkUutgwWQ==}
engines: {node: '>=12'}
@@ -12905,6 +12920,9 @@ packages:
resolution: {integrity: sha512-34wB/Y7MW7bzjKRjUKTa46I2Z7eV62Rkhva+KkopW7Qvv/OSWBqvkSY7vusOPrNuZcUG3tApvdVgNB8POj3SPw==}
engines: {node: '>=10'}
+ resolution: {integrity: sha512-5xVjhUZlHHeuO2W7w2rDFj/Kl1xLX+HjZxdOQwCsUOifl6UaoH1o1wsbsTMz+r0aeC7gCijvru02j6TfKZWzKg==}
+
resolution: {integrity: sha512-9/KXeZUKKJwqCXUdBxFJ3vPh467OCckSBmYDwSK/EtV090K+iMJ7zx2S3HLVDIWFQdqMIsZWbnaGiba18aWhaA==}
engines: {node: '>=14'}
@@ -13151,9 +13169,27 @@ packages:
resolution: {integrity: sha512-14/H1aX7hzBBmmh7sGPd+AOMkkIrHM3Z1PAyGgZigA1H1p5O5ANnMyWzvpAETtG68/dC4pC0ncy3+PPGzXZHPg==}
+ resolution: {integrity: sha512-nqB9M+wITz0BX/Q2xg6fQ8mLkyfF7MU7eE+MNBNjTHFKeKaZAPEzEg+E8LWxKWf1DQVflNEn9N49yAuqKh2mWQ==}
+
+ resolution: {integrity: sha512-SwcRIbyxnN6CFEEK4K1y+zuApvWdpQdBHM/swxP962s8HIxPO3alBH5t3m/dl+f4CMUug6sJb7Pww8d13/9WSw==}
+
+ resolution: {integrity: sha512-Ja1YevpHZctlI5beLA7oc5KNDhGcPixFhcqSiORHNsp/1QTv7amAXzw+gu4YOvErqVlMVyIJGgtzeepCnnur0A==}
+
+ resolution: {integrity: sha512-GTkC6YMprrJZCYU3zcqZj+jkXkrXzq3IPBcF/fIPpNEAB4hZEtXU8zp/RwKOvZl43NUmwDbyRk3+ZTbeRdEBXA==}
+
resolution: {integrity: sha512-xYHt68QRoYGjeeM/XOE1uJtvXQAgvszfBhjV4yvsQH0u2i9I6cI6c6/eG4Hh3UAOVn0y/xAXwmTzEay49Q//HA==}
+ resolution: {integrity: sha512-O0pWuFSK6x4EXhM1dhZ8gchNtG7JMqBtrHdoUFUWXD7dJnNSUze1GuyQr5sOs0aCvgGeI3o/OJW8f4ca7FDxmQ==}
+
+ resolution: {integrity: sha512-SXL66C731p0xPDC5LZg4wI5H+dJo/EO4KTqOMwLYCH3+FmmfAKJEZCm6ohGpI+T1xwsDsJCfL4OnhorllvlTPQ==}
+
resolution: {integrity: sha512-TwuEnCnxbc3rAvhf/LbG7tJUDzhqXyFnv3dtzLOPgCG/hODL7WFnsbwktkD7yUV0RrreP/l1PALq/YSg6VvjlA==}
@@ -13198,6 +13234,12 @@ packages:
resolution: {integrity: sha512-stgLz+i3Aa9mZgnjr/O+v9ruKZsPsndy7qPZOchbqk2cnTU1ZaldKK+v7m54WoKIyxiuMZTKT2H81F8BeAc3ZQ==}
+ resolution: {integrity: sha512-wIkUCfVKpVsWo3JSZlc+8MB5it+2AN5W8J7YVMST30UrvcQNZ1Okbj+rbVniijTWE6FGYy4XJq/rHkas8qJMLQ==}
+
+ resolution: {integrity: sha512-IRt7cfTtHy6f1aRVA5n7kT8rgN3N1nH6MOWLcHfpWG2SH19E3JksLK38MktLxZDhlAjCP9jpIXkOnRXlu6oByQ==}
+
resolution: {integrity: sha512-mXxqd8Yx9BGPij3lZKFSdOsjOTbL4krbCCp9slEozaN4EMppA2dFmK/f8HeohodprY6W0vOdiQ5WFgPaTI75xQ==}
@@ -13721,9 +13763,6 @@ packages:
engines: {node: ^18 || >=20}
hasBin: true
- resolution: {integrity: sha512-fzN+T2K7/Ah25XU02MJkPZ5q4Tj5FpjmIYq4rvoHX4yb16HzFdCO6JxFFn5Y/oBhQ8no8fUZavnyIv9/+xkBBw==}
-
resolution: {integrity: sha512-Z+p+g8E7yzaWwOe5gEUB2Ox0rCEeXWYIZWmYvw/ajNYX8DlXdMvMDj8DWfM/subqPAcsf8l8Td4iAwO1DeIIRQ==}
engines: {node: ^16.0.0 || ^18.0.0 || >=20.0.0}
@@ -13992,6 +14031,9 @@ packages:
resolution: {integrity: sha512-uTqF9MuPraAQ+IsnPf366RG4cP9RtUi7MLO1N3KEc+wb0a6yKpeL0lmk2IB1jY5KHPAlTc6T/JRdC/YqxHNwkQ==}
+ resolution: {integrity: sha512-RFfYQXYFX5C1mB1Aywm0ShcUKzXOr/VzTnlzhBSDJOR6YCAPt1HYCzeXWg1vwwjn/cUxwqRNhhtf1dlewoZYCQ==}
+
resolution: {integrity: sha512-6gj2m8cJZ+iSW8bm0FXdGF0YhIQbKrfP4yWTNzxc31U6MOjfEmB1rHvlYvxI1B7t7BCi1F2vYTT6YhtQRG4hxw==}
engines: {node: ^10.13.0 || >=12.0.0}
@@ -14038,9 +14080,6 @@ packages:
resolution: {integrity: sha512-csuQ9x3Yr0cEIs/Zgx/OEt9iBw9vqIunAPQkx19R/fiMq2oGVTgcMqO/V3Ybqefr1TBvosI6jU539ksaBULJyA==}
- resolution: {integrity: sha512-Pp6SCn7Q+T4LlEPq/AHJW+Y4B9Yzc7L8XvVlIf/XFEUhmbPqYd7bOW+fKKXl4d/uosDvrsoHYdIlrPJTLrtGYQ==}
-
resolution: {integrity: sha512-T1h3B10BRPKfcObdBklX639tVz+xh34O7GjofqrqiAQdm7eHsQ00ih18x6wuJ/E6FxdtS2u3FmUGPDeEcMwzNA==}
@@ -14426,6 +14465,9 @@ packages:
resolution: {integrity: sha512-oj87CgZICdulUohogVAR7AjlC0327U4el4L6eAvOqCeudMDVU0NThNaV+b9Df4dXgSP1gXMTnPdhfe/2qDH5cg==}
+ resolution: {integrity: sha512-TjNPblN4BwAWMXU8s9AEz4JmQxnD1NNL7bNOY/AKUzyamc379FWASUhc/K1pL2noVb+XmZKLL68cjzLsiOAMaA==}
+
resolution: {integrity: sha512-TwEZ+X+yCJmYfL7TPUOcvBZ4QfoT5YenQiJuX//0th53DE6w0xxLEtfK3iyryQFddXuvkIk51EEgrJQ0WJkOmQ==}
@@ -14536,6 +14578,9 @@ packages:
resolution: {integrity: sha512-lT5yCqEBgfoMYpf3F2xQRK7zEr1rhIIZuceDK6+xRkJQ4NMbHTwXqk4NkwDwQMNqXgG9r9fyHnzwNVs6zV5KRw==}
+ resolution: {integrity: sha512-FIqgj2EUvTa7R50u0rGsyTftzjYmv/a3hO345bZNrqabNqjtgiDMgmo4mkUjd+nzU5oF3dClKqFIPUKybUyqoQ==}
+
resolution: {integrity: sha512-NuaNSa6flKT5JaSYQzJok04JzTL1CA6aGhv5rfLW3PgqA+M2ChpZQnAC8h8i4ZFkBS8X5RqkDBHA7r4hej3K9A==}
@@ -14964,6 +15009,9 @@ packages:
resolution: {integrity: sha512-QT7FVMXfWOYFbeRBF6nu+I6tr2Tf3u0q8RIEjNob/heKY/nh7drD/k7eeMFmSQgnTtCzLDcCu/XEnpW2wk4xCQ==}
engines: {node: '>=9.3.0 || >=8.10.0 <9.0.0'}
+ resolution: {integrity: sha512-KigOCHcocU3XODJxsu8i/j8T9tzT4adHiecwORRQ0ZZFcp7ahwXuRU1m+yuO90C5ZUyGeGfocHDI14M3L3yDAQ==}
+
resolution: {integrity: sha512-AgZ3UOZm3YndfrJ4OYjgrT7bmCm/1iqkjvEfH/oYjzh6PD2qw4QuT3jjnXIrpdt4MTpMXclMT3lXbmRY+XRakw==}
@@ -15002,6 +15050,10 @@ packages:
resolution: {integrity: sha512-gSfoiOEA0VPE6Tukkrr7I0RBdE0s7H1eFCDBk05l1KIQT1UIKNc5JZy6jdyW6eYH3aR3g5b3PuL77rq0hvwtAw==}
+ resolution: {integrity: sha512-9LkiTwjUh6rT555DtE9rTX+BKByPfrMzEAtnlEtdEwr3Nkffwiihqe2bWADg+OQRjt9gl6ICdmB/ZFDCGAtSow==}
+ engines: {node: '>= 4'}
+
resolution: {integrity: sha512-XQBQ3I8W1Cge0Seh+6gjj03LbmRFWuoszgK9ooCpwYIrhhoO80pfq4cUkU5DkknwfOfFteRwlZ56PYOGYyFWdg==}
engines: {node: '>= 4'}
@@ -15013,6 +15065,9 @@ packages:
resolution: {integrity: sha512-q1b3N5QkRUWUl7iyylaaj3kOpIT0N2i9MqIEQXP73GVsN9cw3fdx8X63cEmWhJGi2PPCF23Ijp7ktmd39rawIA==}
+ resolution: {integrity: sha512-6m3nE/DUwu8vgc4Y7ffmLvV+WvUgjGYAf68q5WAn/CJZvboAPRlU6wTM7PpPU+wxiKfyfkOKKEkXVyPGIQyGeg==}
+
resolution: {integrity: sha512-l0OE8wL34P4nJH/H2ffoaniAokM2qSmrtXHmlpvYr5AVVX8msAyW0l8NVJFDxlSK4u3Uh/f41cQheDVdnYijwQ==}
hasBin: true
@@ -15808,6 +15863,10 @@ packages:
resolution: {integrity: sha512-+v2QJey7ZUeUiuigkU+uFfklvNUyPI2VO2vBpMYJA+a1hKFLFiKtUYlRHdb3P9CrAvMzi0upbjI4WT+zKtqkBg==}
hasBin: true
+ resolution: {integrity: sha512-ZLeYmjrkaU1fUsKbIi8JML52uAocjEZtBx4DKjRrqzrZa0O4MYwT6db+oqePlspV+FxXJAyFBc/L5gwUi2OFsg==}
+ engines: {node: '>=18'}
+
resolution: {integrity: sha512-PZBtLYcCLtEcjL14Fzb1gSxPBeL7nWvGhO5ZFPGqziCcr8uvHp0NDmdjBchp6KHL+tExcg0m3NISmKxhU394dA==}
@@ -15928,6 +15987,9 @@ packages:
resolution: {integrity: sha512-7rKUyy33Q1yc98pQ1DAmLtwX109F7TIfWlW1Ydo8Wl1ii1SeHieeh0HHfPeL2fMXK6z0s8ecKs9frCuLJvndBg==}
+ resolution: {integrity: sha512-WypcfiRhfeUP9vvF0j6rw0J3hrWrw6iZv3+22h6iRMJ/8z1Tj6XfLP4DsUix5MhMPnXpiHDoKyoZ/bdCkwBCiQ==}
+
resolution: {integrity: sha512-jQL3lRnocaFtu3V00JToYz/4QkNWswxijDaCVNZRiRTO3HQDLsdu1ZtmIUvV4yPp+rvWm5j0y0TG/S61cuijTg==}
engines: {node: '>=10'}
@@ -22811,11 +22873,6 @@ snapshots:
'@sideway/[email protected]': {}
- '@simonwep/[email protected]':
- dependencies:
- core-js: 3.32.2
- nanopop: 2.3.0
-
'@simplewebauthn/[email protected]': {}
'@simplewebauthn/[email protected]':
@@ -25181,6 +25238,11 @@ snapshots:
+ dependencies:
+ custom-error-instance: 2.1.1
+ lodash.uniqby: 4.5.0
+
dependencies:
delayed-stream: 1.0.0
@@ -25263,8 +25325,6 @@ snapshots:
-
@@ -25352,6 +25412,8 @@ snapshots:
+
dependencies:
internmap: 2.0.3
@@ -26990,6 +27052,44 @@ snapshots:
+ dependencies:
+ '@bufbuild/protobuf': 2.11.0
+ '@inngest/ai': 0.1.7
+ '@jpwilliams/waitgroup': 2.1.1
+ '@opentelemetry/api': 1.9.0
+ '@opentelemetry/auto-instrumentations-node': 0.72.0(@opentelemetry/[email protected])(@opentelemetry/[email protected](@opentelemetry/[email protected]))
+ '@opentelemetry/context-async-hooks': 2.6.1(@opentelemetry/[email protected])
+ '@opentelemetry/exporter-trace-otlp-http': 0.214.0(@opentelemetry/[email protected])
+ '@opentelemetry/instrumentation': 0.214.0(@opentelemetry/[email protected])
+ '@opentelemetry/resources': 2.6.1(@opentelemetry/[email protected])
+ '@opentelemetry/sdk-trace-base': 2.6.1(@opentelemetry/[email protected])
+ '@standard-schema/spec': 1.1.0
+ '@traceloop/instrumentation-anthropic': 0.20.0
+ '@types/debug': 4.1.13
+ '@types/ms': 2.1.0
+ canonicalize: 1.0.8
+ chalk: 4.1.2
+ cross-fetch: 4.1.0([email protected])
+ debug: 4.4.3([email protected])
+ hash.js: 1.1.7
+ json-stringify-safe: 5.0.1
+ ms: 2.1.3
+ serialize-error-cjs: 0.1.4
+ strip-ansi: 5.2.0
+ temporal-polyfill: 0.2.5
+ ulid: 2.4.0
+ zod: 3.25.76
+ optionalDependencies:
+ express: 4.22.1
+ hono: 4.12.14
+ typescript: 5.8.3
+ transitivePeerDependencies:
+ - '@opentelemetry/core'
+ - encoding
+ - supports-color
+
dependencies:
'@bufbuild/protobuf': 2.11.0
@@ -27344,6 +27444,8 @@ snapshots:
+
dependencies:
config-chain: 1.1.13
@@ -27594,8 +27696,27 @@ snapshots:
dependencies:
lie: 3.1.1
+ dependencies:
+ lodash._stringtopath: 4.8.0
+
+
+ dependencies:
+ lodash._createset: 4.0.3
+ lodash._root: 3.0.1
+
+
+
+ dependencies:
+ lodash._basetostring: 4.12.0
+
@@ -27629,6 +27750,13 @@ snapshots:
dependencies:
lodash._reinterpolate: 3.0.0
+
+ dependencies:
+ lodash._baseiteratee: 4.7.0
+ lodash._baseuniq: 4.6.0
+
@@ -28332,8 +28460,6 @@ snapshots:
-
@@ -28530,6 +28656,8 @@ snapshots:
+
@@ -28574,12 +28702,6 @@ snapshots:
regex: 6.1.0
regex-recursion: 6.0.2
- dependencies:
- '@simonwep/pickr': 1.9.0
- fflate: 0.8.2
- three: 0.163.0
-
dependencies:
jose: 4.15.9
@@ -28968,6 +29090,12 @@ snapshots:
object-assign: 4.1.1
react-is: 16.13.1
+ dependencies:
+ graceful-fs: 4.2.11
+ retry: 0.12.0
+ signal-exit: 3.0.7
+
@@ -29123,6 +29251,8 @@ snapshots:
+
@@ -29764,6 +29894,8 @@ snapshots:
transitivePeerDependencies:
- supports-color
+
@@ -29802,12 +29934,16 @@ snapshots:
+
+
dependencies:
glob: 10.5.0
@@ -30902,6 +31038,16 @@ snapshots:
'@turbo/windows-64': 2.9.6
'@turbo/windows-arm64': 2.9.6
+ dependencies:
+ buffer-from: 1.1.2
+ combine-errors: 3.0.3
+ is-stream: 2.0.1
+ js-base64: 3.8.1
+ lodash.throttle: 4.1.1
+ proper-lockfile: 4.1.2
+ url-parse: 1.5.10
+
@@ -31046,6 +31192,11 @@ snapshots:
dependencies:
punycode: 2.3.1
+ dependencies:
+ querystringify: 2.2.0
+ requires-port: 1.0.0
+
dependencies:
react: 18.3.1