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.

Onshape models as STEP through the assembler; assembler hardening; RFQ emails carry models (#1956)

Sid3f46240d0d5d
diff --git a/.ai/plans/2026-10-18-onshape-assembler-fetch.md b/.ai/plans/2026-10-18-onshape-assembler-fetch.md
new file mode 100644
index 0000000000..aad9327b64
--- /dev/null
+++ b/.ai/plans/2026-10-18-onshape-assembler-fetch.md
@@ -0,0 +1,231 @@
+# Onshape STEP sync through the assembler + assembler cleanup
+
+## Context
+
+Onshape models now export as STEP (branch `feat/onshape-step-export`, uncommitted) so
+Onshape items get a downloadable STEP, the company-bucket original, and 3D assembly
+instructions. But the sync still moves every byte through the app's Inngest function
+on Vercel: Onshape → function /tmp → a second full read to hash → upload to staging →
+the assembler downloads it again. The whole sync is ONE `step.run` that also sleeps
+through Onshape's translation, so a large export hits the function's disk/time limits
+and any late failure re-runs the Onshape translation (API quota, 402 when spent).
+
+Goals: (1) the app function never touches model bytes — the assembler fetches from
+Onshape straight into staging; (2) the sync is split into resumable steps that hold no
+function while waiting; (3) no export when the model already exists; (4) drawings
+translate in parallel with the model; (5) the assembler never puts a model (or any
+large payload) in Redis, and the other resource/secret issues the audit finds are fixed.
+
+Out of scope: eager assembly conversion (stays lazy), merging fetch+optimize into one
+assembler pass (needs the model-row-triggered pipeline redesigned).
+
+## Part A — Assembler cleanup (all actions)
+
+Audited 2026-10-18 (read-only agent, every claim with file:line). Grouped by fix,
+ordered so the first one closes the most findings. Paths are `apps/assembler/src/`.
+
+A1. **Delete late-mint and parking — no model bytes ever go to Redis.** Every TS caller
+mints upload URLs at submit (`assembler-client.ts:576-591`), so parking only runs after a
+failed PUT. Today it stores every output's bytes in `asm:pending:{id}` on Lambda
+(`jobs.rs:502-515`, non-atomic with `EXPIRE` last ⇒ a cut-off write can leave a key with
+no TTL), `try_finalize` reloads the whole blob from Redis on every 500 ms poll tick
+(`jobs.rs:533-585`), the Lambda/CLI path re-PUTs the same URL every 500 ms until 3600 s,
+and an expired park leaves the job `uploading` until the caller's `maxWaitMs` ends it as
+non-retriable. Replace all of it with: retry each PUT 3× with backoff (1/2/4 s) inside
+`finish`, then `set_error("UPLOAD_FAILED")` (the TS resubmits that code,
+`assembler-client.ts:457-462`). Delete `park`/`parked`/`unpark`/`park_on_disk`/
+`parked_on_disk`/`sweep_dir`/`try_finalize`/`Finalize` (`jobs.rs:137-146,481-601,720-765`),
+the sweeper (`main.rs:111-119`), and URL handling on poll (`main.rs:873-877`). TS: throw on
+a partial mint (`assembly-convert.ts:165-168`, `model-optimize.ts` drop a URL silently)
+and stop minting on every poll (`assembler-client.ts:351`). Drop `outputs` before the
+callback runs (`jobs.rs:418-447`).
+
+A2. **One request parser per action, shared by both dispatch paths — fixes a nodeId
+bug.** `ang` defaults to 0.15 on the standing service (`main.rs:525`) and 0.5 on Lambda
+(`run.rs:125`); the TS sends no convert options and plan always tessellates at 0.5
+(`plan.rs:196`). nodeIds hash the tessellated positions (`crates/converter/src/nodeid.rs`),
+so on the standing service graph.json and plan.json disagree, and one model gets
+different ids per runtime. One `convert_req`/`plan_req`/`compact_req` used by `main.rs`
+and `run.rs::spawn_from_spec`, one tessellation-default constant (0.5, what plan uses and
+what Lambda already produces), bump `cache.rs` `CODE_VERSION`. Also aligns
+`declared_hash` trimming, plan `plan_path`/`model_upload_id`, URL validation.
+
+A3. **Secrets out of the Lambda payload, the job record and error text.**
+- Lambda spec (`main.rs:395-406`) carries the service API key, signed source/PUT URLs
+ and the callback HMAC. Send only `{ action, job_id, traceparent }`; the worker reads the
+ request body from `asm:req:{id}` (TTL 15 min, deleted when the worker takes it). Also
+ removes the Invoke payload-size failure for large plan options.
+- Clear `upload_urls` and `callback_url` from the job record on done/error/cancel
+ (`jobs.rs:54-60,265-266`; kept 24 h today).
+- `reqwest::Error::without_url()` at every `map_err` in `http.rs` (`:90,115,131,228,259`);
+ the callback failure log (`jobs.rs:470`) prints its `?token=`.
+- `/events` mounted only on Lambda, failing closed with no key, and `spawn_from_spec`
+ validates every URL (`main.rs:135,428-432`, `run.rs:93-96,192-202`).
+- Redirects: `Policy::none()` for storage URLs; `fetch` alone follows redirects with
+ `validate_url` on every hop.
+- `invalidate_model` SCAN pattern: escape glob characters (`jobs.rs:639-640`; a
+ `modelUploadId` of `*` clears every result pointer).
+
+A4. **Disk and deadlines.**
+- Acquire the admission grant BEFORE downloading (every action downloads first —
+ `convert.rs:56/81`, `plan.rs:37/69`, …), so queued jobs hold no disk.
+- Total deadlines on download/upload (size-scaled `tokio::time::timeout`) and a 10 s
+ timeout on `dispatch::self_invoke` (`dispatch.rs:101-115`, `set_error` on expiry).
+- Idempotent create via `SET NX` on a lock key (`main.rs:491/508`, worker `:440-444`) —
+ two concurrent POSTs with one key both spawn today.
+- `send_callback` in a spawned task (≤ 36 s inline today in `cancel` and dispatch failure,
+ past API Gateway's 30 s).
+- Drop the memory grant before any await after compute and use `std::fs` inside the
+ blocking closure (`convert.rs:81-131`; possible blocking-pool deadlock, unverified).
+- Temp files named `geometry-*` so startup cleanup catches them (`optimize.rs:686`).
+
+A5. **Fewer whole-model copies in memory.**
+- GLB built then copied by `to_vec()` (`crates/converter/src/glb.rs:331-347`): write into
+ one Vec sized up front.
+- Optimize keeps the full lossless result through every targeted pass
+ (`optimize.rs:508-582,627`): keep only the sizes.
+- Ingest's compressed raw stays in memory through optimize, thumbnail and upload
+ (`optimize.rs:63-119,326-331`): compress to a temp file after optimize, upload via mmap.
+- Mesh sources read whole with `std::fs::read` (`optimize.rs:663-664,706-707`): mmap, as
+ GLB/glTF already are.
+
+A6. **Dead code.** `X-Plan-Upload-Url` (`main.rs:917-924`), the inline plan result
+(`plan.rs:155-167`, TS `inlinePlan` `assembly-plan.ts:214`; 400 without `planPath`),
+`?sync` (`main.rs:349-380`), the `run-job` CLI (`run.rs:35-78,204-220`, `main.rs:85-89`;
+nothing deploys it), `meta` capped to known keys (`main.rs:853-858`), and the stale
+"late-mint"/"never bytes in Redis" comments (`convert.rs`, `compact.rs`, `thumbnail.rs`,
+`plan.rs`, `config.rs`, `jobs.rs` headers).
+
+Follow-ups (not in this plan): a stale-lease takeover for a Lambda worker that crashed
+mid-job (`main.rs:444-458`), compare-and-set status writes so `set_done` cannot overwrite
+a cancel (`jobs.rs:272-317`), cancellation inside an in-flight download/upload, DNS-level
+SSRF checks, a compute deadline on the standing service.
+
+## Part B — Assembler `fetch` action
+
+New action modelled on `src/actions/thumbnail.rs` (smallest template).
+
+- Request: `POST /v1/fetch` `{ source: { url, authorization? }, maxBytes? }`,
+ `X-Carbon-Upload-Urls: { raw }`, `Idempotency-Key: jobId`, `callback_url`.
+- Registration in every place actions are listed: route in `main.rs` (~120–135),
+ `actions/mod.rs`, `run.rs::spawn_from_spec` match, discovery list `main.rs:233`, the
+ TS `action` union in `assembler-client.ts:251`.
+- `http::download_hashed` gains an optional `authorization` header, set with
+ `HeaderValue::set_sensitive(true)`. reqwest's default redirect policy already strips
+ `Authorization` on a cross-host redirect (`remove_sensitive_headers`), so an Onshape
+ redirect to a presigned store is safe. The header is never copied into `meta`, the
+ Redis record, logs or spans.
+- Enforce `maxBytes` during download → 413 `LIMIT_EXCEEDED` (the existing check at
+ `http.rs:165` reads `config::max_source_bytes()`; make it per-request).
+- Upload the downloaded file unchanged via `http::map_file` (memory-mapped, no heap
+ copy) as the single `raw` output through `finish` (A1's retry, never parked).
+ zstd auto-decode cannot trigger: STEP starts `ISO-10303-21;`.
+- Follows redirects with `validate_url` on each hop (A3); everything else uses none.
+- No admission grant beyond the 64 MB minimum (no compute).
+- Result: `{ contentHash: <xxh3-128 hex>, bytes }`.
+- The Onshape token (≤ 1 h) lives only in the request: on Lambda in `asm:req:{id}`
+ until the worker takes it (A3), never in the Invoke payload, the job record or `meta`.
+
+## Part C — Onshape sync pipeline (jobs)
+
+Files: `packages/jobs/src/inngest/functions/integrations/onshape-sync-element.ts`,
+`onshape-attach.ts`, `onshape-panel-sync.ts`, `onshape-revision-sync.ts`,
+`onshape-backfill.ts`; `packages/ee/src/onshape/lib/client.ts`.
+
+C1. **Client:** add `OnshapeClient.externalDataDownload(documentId, foreignId)` →
+`{ url, authorization }` (the token and base URL are private today; base URL covers
+onshape-government tenants). Called inside the assembler submit step, so every
+(re)submit gets a fresh token from `getOnshapeClient` (refreshes within 120 s of expiry).
+
+C2. **`runOnshapeElementSync(step, carbon, input, prefix)`** replaces
+`syncOnshapeElementAssetsToItem` (which runs everything in one caller step):
+1. `${p}-existing` — for a part with a source id (computed BEFORE export now), look up
+ the `modelUpload`; if it exists, skip the model translation and fetch entirely.
+2. `${p}-translate` — start the model translation (unless reused) and every drawing
+ translation at once; return their ids.
+3. `${p}-poll-${n}` + `step.sleep(${p}-sleep-${n})` — poll all pending translations
+ together, same backoff as today (2 s × 1.5 → 15 s, 40 polls). Holds no function.
+4. `${p}-fetch` — `assemblerEnabled()` ? `runAssemblerJob({ action: "fetch" })` into
+ `temp-staging/${companyId}/models/onshape-fetch-${translationId}.step`
+ : one step that runs today's `downloadExternalDataToFile` + upload to the same key
+ (no assembler configured ⇒ unchanged behaviour). Both return
+ `{ stagedPath, size, contentHash }`, or `{ tooLarge: true }` — returned, not thrown,
+ because error classes don't survive Inngest step serialization.
+5. `${p}-drawings` — download the PDFs in parallel and upload them to their document
+ paths; return metadata only (step output size limit).
+6. `${p}-attach` — `attachOnshapeAssetsToItem` takes the staged model and pre-uploaded
+ documents. `ensureImmutableModel` MOVES the staged object to
+ `${companyId}/models/${id}.step` (`storage.move`, same bucket) instead of uploading;
+ `contentSourceId` hashes `["content-v2", companyId, itemId, fileName, contentHash]`
+ — no second pass over the file.
+7. `${p}-thumbnail` — unchanged.
+Each Onshape-calling step is wrapped in `withRateLimitRetry` (move it out of
+`onshape-backfill.ts` into a shared module).
+
+C3. **Callers:**
+- `onshape-panel-sync`: call the pipeline at top level; add `ASSEMBLER_CONCURRENCY`
+ as its second concurrency key.
+- `onshape-revision-sync`: split `runOnshapeRevisionSync` into a `resolve-revision`
+ step (revision lookup + item match), then the pipeline; `asset-too-large` from the
+ returned flag.
+- `onshape-backfill`: per item, `step.invoke` a new thin function
+ `onshape-element-sync` (event `carbon/onshape-element-sync`) that runs the pipeline —
+ keeps a long backfill under Inngest's per-run step limit. Same failure counting.
+
+C4. **Orphans:** confirm the temp-staging sweep (`scheduled/cleanup.ts`) removes an
+unreferenced `onshape-fetch-*` object left by a failed attach; extend it if not.
+
+## Order and deploy
+
+One branch, `feat/onshape-step-export` (already holds the uncommitted STEP switch, which
+becomes the first commit). Then commits in this order: A1 → A2 → A3 → A4 → A5 → A6 → B →
+C, each with its own tests; plan copy at `.ai/plans/2026-10-18-onshape-assembler-fetch.md`.
+The assembler (A + B) is deployed from this branch before the branch merges (C needs it). A1's TS half (no mint on poll, throw on a
+partial mint) ships with the assembler change, since the service stops reading poll URLs.
+A jobs deploy against an assembler without `fetch` fails the sync with a 404
+(non-retriable) — no silent data loss. A2 changes nodeIds on the standing service only
+(Lambda already uses 0.5); `CODE_VERSION` invalidates cached graphs/plans.
+
+## Docs and rules
+
+`.claude/rules/onshape-panel.md` (Background job section), `apps/assembler/AGENTS.md`
+(actions list, parking, fetch), `packages/jobs/AGENTS.md` (new function),
+`docs/content/docs/integrations/cad.mdx` only if behaviour visible to users changes.
+
+## Verification
+
+- `cargo test` in `apps/assembler`, with a small local axum listener as the HTTP
+ boundary (none exists today): fetch (bearer checked, hash + size, header dropped on a
+ cross-host redirect, 413 past `maxBytes`); A1 (a PUT that fails twice then succeeds
+ finishes `done`; three failures ⇒ `UPLOAD_FAILED`, nothing written under
+ `asm:pending:*`); A2 (both dispatch paths parse one body to the same request);
+ A3 (`without_url` error text has no query string; glob escaping). Redis-backed tests
+ run against the local Redis `crbn up` starts, skipped when absent.
+- Existing stored graph.json/plan.json are untouched by A2: only new conversions change,
+ and only on the standing service.
+- `pnpm --filter @carbon/jobs test` (Onshape + assembler-client) and scoped typechecks
+ (`@carbon/ee`, `@carbon/jobs`, `erp`, one at a time).
+- Live (local stack + local assembler): push a part and an assembly from the panel —
+ `modelUpload` is `.step`, optimize succeeds, Download returns STEP, a new assembly
+ instruction converts and plans; re-push the same release ⇒ no translate/fetch step in
+ the Inngest run; a part with a drawing shows model + drawing translated concurrently.
+
+## As built (2026-10-18)
+
+- A2 and A6 landed as one commit: removing the `run-job` CLI and `?sync` is what
+ let one `request::parse` serve both runtimes (`src/request.rs`).
+- A4's "admission before download" became a separate bound: `source.rs` source
+ slots (cores + 2), held from download until the `Source` drops (which deletes
+ the file). Taking a memory grant first would let `Grant::resize` release it
+ while waiting and admit new downloads anyway.
+- A3 kept `callback_url` on ended jobs (the Lambda worker re-sends the
+ callback); only upload URLs are cleared.
+- A5's GLB fix shifts the header and JSON into the binary buffer's allocation
+ (`layout_glb`), pinned byte-for-byte against `gltf`'s `Glb::to_vec`.
+- C3 changed after reading Inngest's concurrency guide: no Onshape function
+ carries `ASSEMBLER_CONCURRENCY` (every executing step counts against a
+ function's keys, so the polls took the five shared slots). The fetch is its
+ own function, `onshape-fetch`, `step.invoke`d by the pipeline.
+- Not done: the live verification (needs an Onshape document pushed through a
+ local stack with a local assembler), and Inngest checkpointing (a client-wide
+ change that needs the Vercel function's max duration for `maxRuntime`).
diff --git a/.claude/rules/onshape-panel.md b/.claude/rules/onshape-panel.md
index 62beef5e6e..d2e3824f22 100644
--- a/.claude/rules/onshape-panel.md
+++ b/.claude/rules/onshape-panel.md
@@ -111,7 +111,8 @@ One map per company: `metadata.propertyMap`, plus `metadata.descriptionModes` fo
- Model exports carry the revision's `partId` and configuration (`releaseExportSelection`). A Part Studio item with no single `partId` is skipped.
- A released drawing attaches to its model item as `<partNumber>-<revision>.pdf` (`releaseDrawingFileName`), its only record. The Releases tab reads it back by name, so a drawing-only release reads In Carbon once its PDFs land. A re-push re-exports onto the same path.
-- Every model export gets its own `modelUpload` row (`attachOnshapeAssetsToItem`, `packages/jobs/.../integrations/onshape-attach.ts`). A released part is named by its source (`sourceId`, `onshape-sync-element.ts`); an assembly, or a workspace part with no microversion, by its bytes (`contentSourceId`). Unchanged bytes reuse the row. Changed bytes get a new row and the item is repointed to it. Never refresh a row in place: the compacted raw, the preview and the assembly graph are keyed by the model id, and a durable copy is never overwritten, so an in-place refresh kept the old geometry. The prior model is kept as an item document unless it is an earlier Onshape sync: an `onshape-` id, or, for an export with no source id, the same file name (the old in-place rows had plain ids). The new row starts `model-optimize` (`queue_model_pipeline`); no Onshape job sends it.
+- Models export as STEP (`exportStepModel`, `onshape-sync-element.ts`), never a mesh: the row is what a manual STEP upload makes, so the optimizer builds the preview GLB, compaction keeps the original (`originalPath`, the Download) in the company bucket, and an assembly instruction can convert and plan it. A part's source id is tagged `selected-part-step-v1`; the GLTF generations hold `selected-part-v1`, and reusing that id fails the attach's identity check.
+- Every model export gets its own `modelUpload` row (`attachOnshapeAssetsToItem`, `packages/jobs/.../integrations/onshape-attach.ts`). A released part is named by its source (`sourceId`, `onshape-sync-element.ts`); an assembly, or a workspace part with no microversion, by its bytes (`contentSourceId`: a hash of the content hash whoever staged the export reported, so the file is never read again). Unchanged bytes reuse the row. Changed bytes get a new row and the item is repointed to it. Never refresh a row in place: the compacted raw, the preview and the assembly graph are keyed by the model id, and a durable copy is never overwritten, so an in-place refresh kept the old geometry. The prior model is kept as an item document unless it is an earlier Onshape sync: an `onshape-` id, or, for an export with no source id, the same file name (the old in-place rows had plain ids). The new row starts `model-optimize` (`queue_model_pipeline`); no Onshape job sends it.
## Batch every `.in()` sized by CAD data
@@ -128,7 +129,10 @@ The gateway rejects a request line over 4,096 bytes, and a PostgREST `.in()` lis
## Background job and dev workflow
-- `onshape-panel-sync` (Inngest) does the slow work: export, poll, download, thumbnail, and released drawings as PDF. `elementKind` is `partstudio`, `assembly` or `drawing`; retries 1; concurrency 1 per item. Applies queue it with event id `<planId>:<itemId>:<elementId>`, so a retried apply exports once. A queue failure is reported and the writes stay; a part push then deletes the new link so the next push retries.
+- An element's export is `runOnshapeElementSync` (`onshape-sync-element.ts`), resumable steps namespaced by a prefix: `existing` (a released part's model id is known before any export; when its row exists the export is skipped and the item linked to it), `translate` (the model and every drawing translation start at once), `poll-n` / `sleep-n` (all translations polled together, `step.sleep` between, so no function is held), `fetch` (a `step.invoke` of `onshape-fetch`, `onshape-fetch.ts`: the assembler's `fetch` action copies the STEP from Onshape into temp-staging at `{companyId}/models/onshape-fetch-{translationId}.step`, with a bearer from `OnshapeClient.externalDataDownload` minted inside the submit step; with no assembler configured, one `download` step stages it), `drawings`, `attach` (moves the staged object to `{companyId}/models/{id}.step`, inserts the row) and `thumbnail`. A retry resumes at the failed step, so a late failure never re-runs a translation. A fetch refused with `LIMIT_EXCEEDED` returns `tooLarge` (a permanent skip), never throws. Every Onshape-calling step is wrapped in `withRateLimitRetry` (`onshape-rate-limit.ts`). A staged object a failed attach leaves behind is an unreferenced temp-staging object, which the 7-day staged-raw sweep (`scheduled/cleanup.ts`) removes.
+- A released drawing alone (no model element) is `runOnshapeDrawingSync`, the same steps without the model: `translate`, `poll-n` / `sleep-n`, `attach` (downloads the PDF and attaches it; a PDF past the document limit returns `tooLarge`).
+- Callers: `onshape-panel-sync` and `onshape-revision-sync` (after its `resolve-revision` step, which returns either an element or a drawing to sync) run the pipeline in their own run; the backfill `step.invoke`s `onshape-element-sync` per model item and `onshape-drawing-sync` per released drawing, so a long backfill stays under the per-run step limit. None of them carries `ASSEMBLER_CONCURRENCY`: Inngest counts every executing step of a function against its keys, so the Onshape polls would take the five env-wide assembler slots from optimize, convert and plan. Only `onshape-fetch` carries it. The three run checkpointing (`ONSHAPE_CHECKPOINTING`, `maxRuntime: "60s"`): consecutive steps share one request. Keep `maxRuntime` far below Vercel's 300 s, since a step that starts late in the window gets only the rest of the request; checkpointing is not on client-wide because other functions have single steps that run for minutes.
+- `onshape-panel-sync` (Inngest) is the panel's job: the element pipeline above, or a released drawing as PDF. `elementKind` is `partstudio`, `assembly` or `drawing`; retries 1; concurrency 1 per item. Applies queue it with event id `<planId>:<itemId>:<elementId>`, so a retried apply exports once. A queue failure is reported and the writes stay; a part push then deletes the new link so the next push retries.
- `ONSHAPE_DEV_CACHE=1` serves repeated GETs from a 10-minute Redis cache, only for `DEV_CACHEABLE_PATHS` in `lib/client.ts`; the key is the path alone, so every company shares entries. Never add a polling endpoint. Live calls are counted in Redis `onshape:api-calls:<year>`.
## Panel UI
diff --git a/Cargo.lock b/Cargo.lock
index a97d416d4d..4f2483dcc1 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -2044,6 +2044,7 @@ dependencies = [
"rustls-pemfile",
"rustls-pki-types",
"ryu",
+ "sha1_smol",
"tokio",
"tokio-rustls",
"tokio-util",
@@ -2394,6 +2395,12 @@ dependencies = [
"digest",
]
+[[package]]
+name = "sha1_smol"
+version = "1.0.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "bbfa15b3dddfee50a0fff136974b3e1bde555604ba463834a7eb7deb6417705d"
+
[[package]]
name = "sha2"
version = "0.10.9"
diff --git a/apps/assembler/AGENTS.md b/apps/assembler/AGENTS.md
index 89071406e9..f91f78083f 100644
--- a/apps/assembler/AGENTS.md
+++ b/apps/assembler/AGENTS.md
@@ -118,9 +118,9 @@ One trace per job: the caller's `traceparent` → the request span
- **A job is spawned with `telemetry::spawn_job`, never bare `tokio::spawn`.**
The job outlives its request, so the span context has to travel with the task;
a bare spawn starts a job whose spans belong to no trace.
-- **Across the Lambda self-invoke the parent rides in the run-job spec**
+- **Across the Lambda self-invoke the parent rides in the worker spec**
(`traceparent`, written by `telemetry::inject` in `lambda_dispatch`, restored
- by `telemetry::attach` in `run::spawn_from_spec`). A spec built anywhere else
+ by `telemetry::attach` in `main::spawn_traced`). A spec built anywhere else
can carry the same key.
- **Outbound requests go through `http::{download_hashed, upload, post_json}`**,
which record the host only. The URLs are signed, and error text that quotes
@@ -166,21 +166,70 @@ retries a lost connection with delays that double from 1 s to 5 s, so the
service is healthy again within seconds of Redis returning. The crate's
defaults wait forever and back off to a minute or two.
-**Outputs go from memory to storage.** The service has no storage credentials.
-When the submit carried a URL for every output, `finish()` PUTs them straight
-from `Bytes` and stores nothing. Otherwise (no URLs at submit, or that upload
-failed) the outputs are **parked** and the job stays `uploading` until a poll
-brings fresh URLs (late-mint):
-
-- on a standing service, as files under `<tmp>/asm-pending/<hash of job id>/`,
- memory-mapped for the upload and swept after the pending TTL;
-- on Lambda, in Redis (`asm:pending:{jobId}`, same TTL), because the poll there
- is answered by a different invocation than the one that computed.
-
-A parked job not drained within the TTL is abandoned (the caller resubmits).
-Disk parking is per instance: with more than one standing replica a late-mint
-poll must reach the replica that computed, so pass the URLs at submit. (Legacy:
-a plan with no `planPath` returns the plan inline in the job record.)
+**Outputs go from memory to storage, never through Redis.** The service has no
+storage credentials: the caller signs one upload URL per output at submit
+(`X-Carbon-Upload-Urls`), and `finish()` PUTs each output straight from `Bytes`.
+A PUT that fails is retried after 1, 2 and 4 s; still failing (or a missing
+URL), the job fails with `UPLOAD_FAILED` and the caller resubmits with fresh
+URLs. Outputs are never parked for a later poll: a late-mint hand-off used to
+keep them on disk, or in Redis on Lambda, which put whole models in a shared
+Redis.
+
+**One parser per action** (`src/request.rs`). `POST /v1/{action}` and the
+Lambda worker both parse the body through `request::parse`, so a default
+cannot differ between runtimes. Convert and plan share one tessellation
+(`config::TESSELLATION_*`): nodeIds hash the tessellated positions, so a
+graph.json and a plan.json made at different deflections disagree. A plan
+needs `meta.planPath` (400 without); there is no inline plan result, no
+`?sync` mode and no `run-job` CLI.
+
+**Job state is a Redis hash, changed only while the job is active.** A
+record is `asm:job2:{id}` (fields `action`, `status`, `result`, `stats`,
+`error`, `upload_urls`, `callback_url`). Every status change goes through one
+Lua script (`TRANSITION`) that checks the job is still pending, starting,
+running or uploading before it writes, so a finish can never overwrite a cancel
+that landed meanwhile.
+
+**Leases: who is running a job.** A working job (not `pending`) holds
+`asm:lease:{id}` (30 s), renewed every 10 s by the process's `heartbeat` for
+every job `jobs::track` lists (`telemetry::spawn_job` tracks each job). A poll
+that finds a working job with no lease ends it `WORKER_LOST`, which the caller
+resubmits: the process running it died. On Lambda the lease is the worker's
+claim (`SET NX`): of two deliveries one runs, and a redelivery after a crashed
+or timed-out invocation takes the job over; the request body stays in
+`asm:req:{id}` until the job ends so it can.
+
+**Cancel stops transfers.** `track` gives each job a cancel token; `cancel`
+fires it at once on the replica running the job, and the heartbeat fires it on
+any other within 10 s. Downloads and uploads race it (`http::unless_canceled`)
+and fail `canceled`.
+
+**A compute has a deadline** (`compute.rs`, 60 min; Lambda's 900 s comes
+first there). OCCT and FCL cannot be interrupted and a blocking thread cannot
+be killed, so past the deadline, or on a cancel, the job ends at once
+(`COMPUTE_TIMEOUT` / `canceled`) and the thread finishes in the background
+still holding the job's memory grant: admission never hands out memory a
+stuck thread may still be using. A plan's grant lives inside its work (it is
+resized as parts are counted), so it is released the same way.
+
+**Secrets stay out of payloads, records and errors.**
+- The Lambda self-invoke spec is `{ action, job_id, traceparent }` and nothing
+ else. The request body waits in Redis (`asm:req:{id}`, 2 h) and the worker
+ reads it (`GET`); it is deleted when the job ends (`ended()`), so a
+ redelivery can take over a job whose worker died. No signed URL, caller
+ token or service key rides in the Invoke payload, which AWS keeps for its
+ async retries, but the stored body holds them, a `fetch`'s `authorization`
+ included, until the job ends.
+- `/events` is mounted only on Lambda, where only an IAM-signed Invoke reaches
+ it; a spec names a job, so a delivery can only start a pending job with the
+ body its create stored.
+- A job's upload URLs are cleared when it ends. Its `callback_url` stays (the
+ worker re-sends the callback; it only reports that one job).
+- Every reqwest error goes through `without_url()`: signed URLs keep their
+ token in the query string, and the message is logged, stored on the job and
+ returned to the caller.
+- The shared HTTP client follows no redirects: a redirect would reach a host
+ `validate_url` never checked.
**Content-hash result cache** (`asm:result:{model}:{contentHash}:{optsHash}:v{CODE_VERSION}`
→ pointer, 24 h): a repeat of the same model + bytes + options + code version
@@ -210,6 +259,17 @@ Built to sit as a small always-on pod beside other workloads.
above the whole budget takes all of it and runs alone. Nothing is rejected.
The reservation covers the compute only, not the download or the upload. CPU
is bounded separately by the blocking pool (cores + 2).
+- **Downloaded sources are bounded too** (`source.rs`). A job takes one of
+ `cores + 2` source slots before it downloads and holds it until its `Source`
+ drops, which deletes the file on every path (a panic included). A queue past
+ that waits with no file on disk; it used to hold every queued job's source
+ at once.
+- **Every transfer has a deadline**: a download 1 h end to end (the 60 s read
+ timeout only catches a stalled one), an upload 2 min plus 2 MB/s of body, the
+ Lambda self-invoke 10 s. A create claims `asm:create:{id}` (`SET NX`, 30 s,
+ released when done) so two POSTs with one key cannot both spawn; a Lambda
+ worker claims the job's lease (`claim_lease`, `SET NX`), so of two live
+ deliveries exactly one runs. Callbacks from `set_error`/`cancel` go out in their own task.
- **A waiting job is `pending` or `starting`, not `running`.** Each action sets
`running` only after `admission.acquire` returns. On Lambda the worker inlet
sets `starting` when it takes a `pending` job, before the download and the
@@ -244,8 +304,8 @@ Built to sit as a small always-on pod beside other workloads.
prints its settings at exit.
- **The convert result cache** is files under `<tmp>/asm-cache` (2 GiB LRU, off
on Lambda), memory-mapped when a hit is served and cleared at startup.
-- **`<tmp>` must be real disk** with room for the cache, parked outputs and
- downloaded sources. A memory-backed `emptyDir` would charge all of it to the
+- **`<tmp>` must be real disk** with room for the cache and downloaded
+ sources. A memory-backed `emptyDir` would charge all of it to the
pod's memory limit. The server clears downloaded sources (`geometry-*`) left
by an earlier process when it starts: a killed container skips its own
cleanup and the volume outlives the restart.
@@ -255,11 +315,38 @@ Built to sit as a small always-on pod beside other workloads.
- **CI + registry** — no workflow yet builds/publishes the `carbon-occt` base or
the `carbon-assembler` image, or deploys the container.
+## Fetch
+
+`POST /v1/fetch` `{ source: { url, authorization? }, maxBytes?, output: { path?,
+contentType? } }` copies the file at `source.url` into storage unchanged, as the
+`raw` output, and returns `{ contentHash, outputs: { raw: { path, bytes } } }`
+(`contentHash` = xxh3-128 hex). It exists so a caller never holds a large file:
+the Onshape sync has the assembler pull a STEP export straight from Onshape into
+staging instead of streaming it through the app's function.
+
+- `authorization` is sent as the `Authorization` header (marked sensitive) and
+ lives only in the request: never in the job record, a log or a span. On
+ Lambda the request is the stored body (`asm:req:{id}`), so the token sits in
+ Redis until the job ends, at most the request's 2 h.
+- `fetch` alone follows redirects, at most five and each to a URL that passes
+ `validate_url`; reqwest drops `Authorization` on a redirect to another host.
+- Outside dev mode `fetch` connects only to public addresses: its resolver
+ (`PublicOnly`) drops private, loopback, link-local, CGNAT and IPv6
+ unique-local results and refuses a host with none left. Its URL is the one a
+ third party decides (an Onshape Government tenant URL is the customer's to
+ set); every other action reaches our own signed storage URLs, which a
+ self-hosted install may serve from a private network. `validate_url` checks
+ IP literals by the same rule (`config::is_public_ip`).
+- `maxBytes` fails the job `LIMIT_EXCEEDED` (413), from `Content-Length` when
+ sent, else as the bytes cross it.
+- No zstd decoding: the stored bytes are exactly what the source served.
+- No memory grant (no compute); it takes a source slot like every download.
+
## Thumbnails
`POST /v1/thumbnail` `{ source: { url }, output: { path?, size?, direction? } }`
renders the GLB at `source.url` to a square PNG (300 px unless `size` says
-otherwise) and late-mint uploads it as the `thumbnail` output.
+otherwise) and uploads it as the `thumbnail` output.
The camera is the viewer's: a 45° perspective looking at the centre of the
bounding box, standing back far enough to fit the bounding sphere (`FOV_DEGREES`
diff --git a/apps/assembler/Cargo.toml b/apps/assembler/Cargo.toml
index cc4e3f5ba8..dd46b59b34 100644
--- a/apps/assembler/Cargo.toml
+++ b/apps/assembler/Cargo.toml
@@ -26,7 +26,7 @@ futures-util = "0.3"
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"] }
+redis = { version = "0.27", default-features = false, features = ["tokio-comp", "connection-manager", "tokio-rustls-comp", "script"] }
# 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
diff --git a/apps/assembler/src/actions/compact.rs b/apps/assembler/src/actions/compact.rs
index 1fc94d19c6..728e126eb0 100644
--- a/apps/assembler/src/actions/compact.rs
+++ b/apps/assembler/src/actions/compact.rs
@@ -12,13 +12,14 @@
//! - `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
+//! Async job; the single compressed `raw` output is uploaded to its
+//! submit-time URL. 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::{admission, http, telemetry, AppState};
+use crate::{admission, compute, http, telemetry, AppState};
use serde_json::json;
use std::time::Instant;
@@ -44,7 +45,7 @@ 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`.
+ /// repoints modelPath); the signed PUT URL comes with the submit, key `raw`.
pub raw_path: Option<String>,
}
@@ -55,6 +56,7 @@ pub(crate) const ZSTD_LEVEL: i32 = 12;
pub fn spawn(state: &AppState, job_id: &str, req: CompactReq) {
let jobs = state.jobs.clone();
let admission = state.admission.clone();
+ let sources = state.sources.clone();
let job_id = job_id.to_string();
telemetry::spawn_job(&job_id.clone(), "compact", async move {
if jobs.is_canceled(&job_id).await {
@@ -62,33 +64,33 @@ pub fn spawn(state: &AppState, job_id: &str, req: CompactReq) {
}
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 src = match sources.download(&req.source_url, "src", None).await {
+ Ok(src) => src,
+ Err(e) => {
+ eprintln!("[{job_id}] compact failed: source download: {}", e.message);
+ jobs.set_error(&job_id, &e.code, e.message).await;
+ return;
+ }
+ };
+ let src_str = src.path_string();
let mode = req.mode;
let level = ZSTD_LEVEL;
let res = {
- let _grant = admission
- .acquire(admission::estimate_mb(http::file_len(&src).await))
+ let grant = admission
+ .acquire(admission::estimate_mb(http::file_len(src.path()).await))
.await;
// The wait may have been long: a job cancelled meanwhile is dropped
// before it takes the memory it was granted.
if jobs.is_canceled(&job_id).await {
- let _ = tokio::fs::remove_file(&src).await;
return;
}
// Running from here on: the wait for memory is queue time, not work.
jobs.set_status(&job_id, "running").await;
eprintln!("[{job_id}] compact running");
- telemetry::in_span("compute", tokio::task::spawn_blocking(move || compress(&src_str, mode, level))).await
+ compute::run(Some(grant), move || compress(&src_str, mode, level)).await
};
- let _ = tokio::fs::remove_file(&src).await;
+ drop(src);
let out = match res {
Ok(Ok(o)) => o,
@@ -98,9 +100,9 @@ pub fn spawn(state: &AppState, job_id: &str, req: CompactReq) {
return;
}
Err(e) => {
- let msg = format!("compact panicked: {e}");
+ let msg = format!("compact {e}");
eprintln!("[{job_id}] {msg}");
- jobs.set_error(&job_id, "compact_failed", msg).await;
+ jobs.set_error(&job_id, e.code("compact_failed"), msg).await;
return;
}
};
@@ -127,7 +129,7 @@ pub fn spawn(state: &AppState, job_id: &str, req: CompactReq) {
let outputs = vec![Output {
name: "raw".into(),
content_type: "application/zstd".into(),
- bytes: out.bytes.into(),
+ bytes: out.bytes,
}];
jobs.finish(&job_id, outputs, done, None).await;
});
@@ -139,7 +141,7 @@ struct CompactErr {
}
struct Compacted {
- bytes: Vec<u8>,
+ bytes: bytes::Bytes,
input_bytes: u64,
kind: &'static str,
}
@@ -158,7 +160,7 @@ fn compress(src_path: &str, mode: Mode, level: i32) -> Result<Compacted, Compact
let _ = std::fs::remove_file(&xbf);
return Err(e);
}
- let bytes = zstd_file(&xbf_str, level).map_err(|e| CompactErr {
+ let bytes = zstd_file_mapped(&xbf_str, level).map_err(|e| CompactErr {
code: "compact_failed",
message: e,
});
@@ -170,7 +172,7 @@ fn compress(src_path: &str, mode: Mode, level: i32) -> Result<Compacted, Compact
})
}
Mode::Zstd => {
- let bytes = zstd_file(src_path, level).map_err(|e| CompactErr {
+ let bytes = zstd_file_mapped(src_path, level).map_err(|e| CompactErr {
code: "compact_failed",
message: e,
})?;
@@ -183,10 +185,20 @@ fn compress(src_path: &str, mode: Mode, level: i32) -> Result<Compacted, Compact
}
}
-/// Stream a file through zstd into an owned buffer (the compressed artifact is
-/// small — read is streaming, only the result is held).
-pub(crate) 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}"))
+/// zstd `path` into a temp file and hand it back memory-mapped: the page cache
+/// holds the compressed bytes, not the heap. The file is unlinked at once; the
+/// map keeps it readable until the bytes drop.
+pub(crate) fn zstd_file_mapped(path: &str, level: i32) -> Result<bytes::Bytes, String> {
+ let out = http::temp_path("zst");
+ let written = (|| {
+ let input = std::fs::File::open(path).map_err(|e| format!("open {path}: {e}"))?;
+ let output = std::fs::File::create(&out).map_err(|e| format!("create temp: {e}"))?;
+ let mut writer = std::io::BufWriter::new(output);
+ zstd::stream::copy_encode(std::io::BufReader::new(input), &mut writer, level)
+ .map_err(|e| format!("zstd encode: {e}"))?;
+ std::io::Write::flush(&mut writer).map_err(|e| format!("flush temp: {e}"))?;
+ http::map_file(&out).map_err(|e| format!("map temp: {e}"))
+ })();
+ let _ = std::fs::remove_file(&out);
+ written
}
diff --git a/apps/assembler/src/actions/convert.rs b/apps/assembler/src/actions/convert.rs
index ef22f8bd82..c6138d32df 100644
--- a/apps/assembler/src/actions/convert.rs
+++ b/apps/assembler/src/actions/convert.rs
@@ -2,14 +2,14 @@
// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,
// including ports, remain AGPLv3; serving them over a network requires releasing their source.
-//! `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
+//! `convert` action — STEP → GLB + graph.json. Async job: the caller hands the
+//! signed upload URLs (`glb`, `graph`) at submit and long-polls. 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::{admission, config, http, progress, telemetry, AppState};
+use crate::{admission, compute, config, http, progress, telemetry, AppState};
use serde_json::json;
use std::sync::Arc;
use std::time::Instant;
@@ -20,7 +20,7 @@ pub struct ConvertReq {
/// 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`.
+ /// the signed PUT URLs come with the submit, keyed `glb`/`graph`.
pub glb_path: Option<String>,
pub graph_path: Option<String>,
pub lin: f64,
@@ -34,6 +34,7 @@ pub fn spawn(state: &AppState, job_id: &str, req: ConvertReq) {
let cache = Arc::clone(&state.cache);
let progress_store = state.progress.clone();
let admission = state.admission.clone();
+ let sources = state.sources.clone();
let job_id = job_id.to_string();
telemetry::spawn_job(&job_id.clone(), "convert", async move {
if jobs.is_canceled(&job_id).await {
@@ -53,17 +54,18 @@ pub fn spawn(state: &AppState, job_id: &str, req: ConvertReq) {
}
}
- 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;
- }
- };
+ let src = match sources
+ .download(&req.source_url, "step", Some(&tracker.progress))
+ .await
+ {
+ Ok(src) => src,
+ Err(e) => {
+ eprintln!("[{job_id}] convert failed: source download: {}", e.message);
+ jobs.set_error(&job_id, &e.code, e.message).await;
+ return;
+ }
+ };
+ let content_hash = src.hash;
tracker.progress.set_phase(progress::PHASE_CONVERT);
let key = match &req.declared_hash {
@@ -72,27 +74,26 @@ pub fn spawn(state: &AppState, job_id: &str, req: ConvertReq) {
};
let entry = match cache.get(&key) {
Some(entry) => {
- let _ = tokio::fs::remove_file(&tmp).await;
+ drop(src);
entry
}
None => {
// Held for the tessellation only: the download before it streams
// to disk and the upload after it holds just the outputs.
- let _grant = admission
- .acquire(admission::estimate_mb(http::file_len(&tmp).await))
+ let grant = admission
+ .acquire(admission::estimate_mb(http::file_len(src.path()).await))
.await;
// The wait may have been long: a job cancelled meanwhile is
// dropped before it takes the memory it was granted.
if jobs.is_canceled(&job_id).await {
- let _ = tokio::fs::remove_file(&tmp).await;
return;
}
// Running from here on: the wait for memory is queue time, not work.
jobs.set_status(&job_id, "running").await;
- let tmp_str = tmp.to_string_lossy().to_string();
+ let tmp_str = src.path_string();
let cache_ins = Arc::clone(&cache);
let (lin, ang, optimize) = (req.lin, req.ang, req.optimize);
- let res = telemetry::in_span("compute", tokio::task::spawn_blocking(move || {
+ let res = compute::run(Some(grant), move || {
// Compacted retained raws are BinXCAF (`.xbf`) — binary, no
// STEP header to unit-detect (already mm); running the lossy
// text scan on them is wasted work at best.
@@ -126,9 +127,9 @@ pub fn spawn(state: &AppState, job_id: &str, req: ConvertReq) {
},
)
})
- }))
+ })
.await;
- let _ = tokio::fs::remove_file(&tmp).await;
+ drop(src);
match res {
Ok(Ok(entry)) => entry,
Ok(Err(e)) => {
@@ -138,9 +139,9 @@ pub fn spawn(state: &AppState, job_id: &str, req: ConvertReq) {
return;
}
Err(e) => {
- let msg = format!("convert panicked: {e}");
+ let msg = format!("convert {e}");
eprintln!("[{job_id}] {msg}");
- jobs.set_error(&job_id, "TESSELLATION_FAILED", msg).await;
+ jobs.set_error(&job_id, e.code("TESSELLATION_FAILED"), msg).await;
return;
}
}
@@ -152,7 +153,7 @@ pub fn spawn(state: &AppState, job_id: &str, req: ConvertReq) {
});
}
-/// Enforce the part-count limit, then hold the GLB + graph for late-mint upload.
+/// Enforce the part-count limit, then upload the GLB + graph.
async fn complete(
jobs: &crate::jobs::JobStore,
job_id: &str,
diff --git a/apps/assembler/src/actions/fetch.rs b/apps/assembler/src/actions/fetch.rs
new file mode 100644
index 0000000000..3581eda48b
--- /dev/null
+++ b/apps/assembler/src/actions/fetch.rs
@@ -0,0 +1,80 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,
+// including ports, remain AGPLv3; serving them over a network requires releasing their source.
+
+//! `fetch` action — copy a file from a URL the caller may not reach cheaply
+//! (a CAD system's export, behind its own `Authorization`) into storage,
+//! unchanged, and report its size and content hash. The bytes go source →
+//! this service's disk → the `raw` upload URL; the caller never holds them.
+//! No compute, so no memory grant: only a source slot.
+
+use crate::jobs::{Done, Output};
+use crate::{http, telemetry, AppState};
+use serde_json::json;
+use std::time::Instant;
+
+pub struct FetchReq {
+ pub source_url: String,
+ /// Sent as the `Authorization` header. Lives only in this request: never
+ /// in the job record, a log or a span.
+ pub authorization: Option<String>,
+ /// Refuse a file past this many bytes (413 `LIMIT_EXCEEDED`).
+ pub max_bytes: Option<u64>,
+ /// The upload's content type.
+ pub content_type: String,
+ /// Storage path recorded in the completion pointer; the signed PUT URL
+ /// comes with the submit, key `raw`.
+ pub path: Option<String>,
+}
+
+pub fn spawn(state: &AppState, job_id: &str, req: FetchReq) {
+ let jobs = state.jobs.clone();
+ let sources = state.sources.clone();
+ let job_id = job_id.to_string();
+ telemetry::spawn_job(&job_id.clone(), "fetch", async move {
+ if jobs.is_canceled(&job_id).await {
+ return;
+ }
+ let started = Instant::now();
+ jobs.set_status(&job_id, "running").await;
+ let opts = http::DownloadOpts {
+ authorization: req.authorization.as_deref(),
+ max_bytes: req.max_bytes,
+ passthrough: true,
+ };
+ let src = match sources.download_with(&req.source_url, "fetch", None, &opts).await {
+ Ok(src) => src,
+ Err(e) => {
+ eprintln!("[{job_id}] fetch failed: {}", e.message);
+ jobs.set_error(&job_id, &e.code, e.message).await;
+ return;
+ }
+ };
+ let bytes = match http::map_file(src.path()) {
+ Ok(bytes) => bytes,
+ Err(e) => {
+ jobs.set_error(&job_id, "READ_FAILED", format!("map fetched file: {e}"))
+ .await;
+ return;
+ }
+ };
+ let size = bytes.len();
+ let fetch_ms = started.elapsed().as_millis() as i64;
+ eprintln!("[{job_id}] fetch done: {size} bytes, {fetch_ms}ms");
+
+ let done = Done {
+ result: json!({
+ "contentHash": format!("{:032x}", src.hash),
+ "outputs": { "raw": { "path": req.path, "bytes": size } },
+ }),
+ stats: json!({ "outputBytes": size, "fetchMs": fetch_ms }),
+ };
+ let outputs = vec![Output {
+ name: "raw".into(),
+ content_type: req.content_type,
+ bytes,
+ }];
+ jobs.finish(&job_id, outputs, done, None).await;
+ drop(src);
+ });
+}
diff --git a/apps/assembler/src/actions/mod.rs b/apps/assembler/src/actions/mod.rs
index 3b475b1e5f..7d85070383 100644
--- a/apps/assembler/src/actions/mod.rs
+++ b/apps/assembler/src/actions/mod.rs
@@ -9,6 +9,7 @@
pub mod compact;
pub mod convert;
+pub mod fetch;
pub mod optimize;
pub mod plan;
pub mod thumbnail;
diff --git a/apps/assembler/src/actions/optimize.rs b/apps/assembler/src/actions/optimize.rs
index 73caa289c1..7579e2affd 100644
--- a/apps/assembler/src/actions/optimize.rs
+++ b/apps/assembler/src/actions/optimize.rs
@@ -8,13 +8,13 @@
//! 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
+//! uploads the single `glb` output to its submit-time URL. 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::{admission, http, telemetry, AppState};
+use crate::{admission, compute, http, telemetry, AppState};
use serde_json::json;
use std::time::{Duration, Instant};
@@ -22,7 +22,7 @@ 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).
+ /// Storage path recorded in the completion pointer (the `glb` upload).
pub glb_path: Option<String>,
pub opts: Opts,
/// Ingest: also write the retained raw's compact form (output `raw`), from
@@ -42,7 +42,7 @@ pub struct ThumbnailOut {
/// The retained raw's compact form.
struct Compacted {
- bytes: Vec<u8>,
+ bytes: bytes::Bytes,
/// `xbf` (a STEP as BinXCAF, then zstd) or `zstd` (the raw as it is).
kind: &'static str,
}
@@ -55,13 +55,14 @@ struct Ingest {
load_path: String,
declared: String,
source_format: &'static str,
- compacted: Option<Compacted>,
+ /// The file to compress for the retained raw, and what it is. Compressed
+ /// after the optimise, so its bytes are not held through it.
+ compact_from: Option<(String, &'static str)>,
xbf: Option<std::path::PathBuf>,
warnings: Vec<String>,
}
fn prepare_ingest(path: &str, declared: &str, ext: Option<&str>) -> Result<Ingest, ActionErr> {
- use crate::actions::compact::{zstd_file, ZSTD_LEVEL};
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, _) = formats::resolve(declared, &head, size, ext)
@@ -70,7 +71,7 @@ fn prepare_ingest(path: &str, declared: &str, ext: Option<&str>) -> Result<Inges
load_path: path.to_string(),
declared: declared.to_string(),
source_format: format.name(),
- compacted: None,
+ compact_from: None,
xbf: None,
warnings: Vec::new(),
};
@@ -82,10 +83,7 @@ fn prepare_ingest(path: &str, declared: &str, ext: Option<&str>) -> Result<Inges
let xbf_str = xbf.to_string_lossy().to_string();
match converter::convert::step_to_xbf(path, &xbf_str) {
Ok(()) => {
- match zstd_file(&xbf_str, ZSTD_LEVEL) {
- Ok(bytes) => ingest.compacted = Some(Compacted { bytes, kind: "xbf" }),
- Err(e) => ingest.warnings.push(format!("compact: {e}")),
- }
+ ingest.compact_from = Some((xbf_str.clone(), "xbf"));
ingest.load_path = xbf_str;
ingest.declared = "xbf".into();
ingest.xbf = Some(xbf);
@@ -97,10 +95,7 @@ fn prepare_ingest(path: &str, declared: &str, ext: Option<&str>) -> Result<Inges
}
}
}
- _ => match zstd_file(path, ZSTD_LEVEL) {
- Ok(bytes) => ingest.compacted = Some(Compacted { bytes, kind: "zstd" }),
- Err(e) => ingest.warnings.push(format!("compact: {e}")),
- },
+ _ => ingest.compact_from = Some((path.to_string(), "zstd")),
}
Ok(ingest)
}
@@ -122,16 +117,31 @@ fn run_ingest(
None => (path, declared),
};
let outcome = run_optimize(load_path, load_declared, ext, opts);
+ // Compress the retained raw only once the optimise has succeeded, and
+ // before the BinXCAF it may be made from is deleted.
+ let compacted = match (&outcome, ingest.as_ref().and_then(|i| i.compact_from.as_ref())) {
+ (Ok(_), Some((from, kind))) => Some(
+ crate::actions::compact::zstd_file_mapped(from, crate::actions::compact::ZSTD_LEVEL)
+ .map(|bytes| Compacted { bytes, kind }),
+ ),
+ _ => None,
+ };
if let Some(xbf) = ingest.as_ref().and_then(|i| i.xbf.as_ref()) {
let _ = std::fs::remove_file(xbf);
}
let mut outcome = outcome?;
- let mut compacted = None;
if let Some(i) = ingest {
outcome.detected_format = i.source_format;
outcome.warnings.extend(i.warnings);
- compacted = i.compacted;
}
+ let compacted = match compacted {
+ Some(Ok(c)) => Some(c),
+ Some(Err(e)) => {
+ outcome.warnings.push(format!("compact: {e}"));
+ None
+ }
+ None => None,
+ };
let png = thumbnail.map(|(size, direction)| {
thumbnail::render_png(&outcome.glb, size, direction).map_err(|e| e.0)
});
@@ -198,6 +208,7 @@ impl ActionErr {
pub fn spawn(state: &AppState, job_id: &str, req: OptimizeReq) {
let jobs = state.jobs.clone();
let admission = state.admission.clone();
+ let sources = state.sources.clone();
let job_id = job_id.to_string();
telemetry::spawn_job(&job_id.clone(), "optimize", async move {
if jobs.is_canceled(&job_id).await {
@@ -205,14 +216,15 @@ pub fn spawn(state: &AppState, job_id: &str, req: OptimizeReq) {
}
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 src = match sources.download(&req.source_url, "model", None).await {
+ Ok(src) => src,
+ Err(e) => {
+ eprintln!("[{job_id}] optimize failed: source download: {}", e.message);
+ jobs.set_error(&job_id, &e.code, e.message).await;
+ return;
+ }
+ };
+ let tmp_str = src.path_string();
let declared = req.format.clone();
let ext = url_ext(&req.source_url);
let mut opts = req.opts;
@@ -220,13 +232,12 @@ pub fn spawn(state: &AppState, job_id: &str, req: OptimizeReq) {
let thumbnail = req.thumbnail.as_ref().map(|t| (t.size, t.direction));
let res = {
- let _grant = admission
- .acquire(admission::estimate_mb(http::file_len(&tmp).await))
+ let grant = admission
+ .acquire(admission::estimate_mb(http::file_len(src.path()).await))
.await;
// The wait may have been long: a job cancelled meanwhile is dropped
// before it takes the memory it was granted.
if jobs.is_canceled(&job_id).await {
- let _ = tokio::fs::remove_file(&tmp).await;
return;
}
// Running from here on: the wait for memory is queue time, not
@@ -237,12 +248,12 @@ pub fn spawn(state: &AppState, job_id: &str, req: OptimizeReq) {
opts.codec
);
opts.deadline = opts.budget.map(|b| Instant::now() + b);
- telemetry::in_span("compute", tokio::task::spawn_blocking(move || {
+ compute::run(Some(grant), move || {
run_ingest(&tmp_str, &declared, ext.as_deref(), &opts, compact, thumbnail)
- }))
+ })
.await
};
- let _ = tokio::fs::remove_file(&tmp).await;
+ drop(src);
let (mut outcome, compacted, png) = match res {
Ok(Ok(o)) => o,
@@ -252,9 +263,9 @@ pub fn spawn(state: &AppState, job_id: &str, req: OptimizeReq) {
return;
}
Err(e) => {
- let msg = format!("optimize panicked: {e}");
+ let msg = format!("optimize {e}");
eprintln!("[{job_id}] {msg}");
- jobs.set_error(&job_id, "optimize_failed", msg).await;
+ jobs.set_error(&job_id, e.code("optimize_failed"), msg).await;
return;
}
};
@@ -327,7 +338,7 @@ pub fn spawn(state: &AppState, job_id: &str, req: OptimizeReq) {
outputs.push(Output {
name: "raw".into(),
content_type: "application/zstd".into(),
- bytes: c.bytes.into(),
+ bytes: c.bytes,
});
}
if let Some(png) = png {
@@ -541,6 +552,9 @@ fn run_optimize(
.unwrap_or(1.0);
let mut smallest = lossless.glb.len();
let mut prev_encoded = lossless.glb.len();
+ // Only its sizes are needed from here: free the full-fidelity model
+ // before the targeted passes build theirs.
+ drop(lossless);
let mut aggressive = false;
for _ in 0..AUTO_MAX_TARGETED_PASSES {
// Ratio targeting hits its triangle count whatever the error — the
@@ -598,7 +612,8 @@ fn run_optimize(
} else {
opts.ladder.clone()
};
- let mut best: Option<Outcome> = None;
+ // Only the last rung's size is reported; its model is not kept.
+ let mut last_len: Option<usize> = None;
let mut warnings: Vec<String> = Vec::new();
let mut i = 0;
while i < ladder.len() {
@@ -624,13 +639,13 @@ fn run_optimize(
return Ok(outcome);
}
warnings.push(over_msg(&format!("rung {rung:?}"), &outcome));
- best = Some(outcome);
+ last_len = Some(outcome.glb.len());
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);
+ let smallest = last_len.unwrap_or(0);
Err(ActionErr::new(
"cannot_fit_budget",
format!(
@@ -642,6 +657,17 @@ fn run_optimize(
))
}
+/// The downloaded source, memory-mapped: the page cache holds it, not the
+/// heap, while it is parsed.
+fn map_source(path: &str) -> Result<memmap2::Mmap, ActionErr> {
+ let file = std::fs::File::open(path)
+ .map_err(|e| ActionErr::new("invalid_input", format!("open source: {e}")))?;
+ // SAFETY: the source is this job's own temp file; nothing writes it while
+ // it is mapped.
+ unsafe { memmap2::Mmap::map(&file) }
+ .map_err(|e| ActionErr::new("invalid_input", format!("mmap source: {e}")))
+}
+
/// Load the resolved format into GLB bytes.
fn load_source(path: &str, format: Format, head: &[u8], opts: &Opts) -> Result<Src, ActionErr> {
match format {
@@ -660,30 +686,23 @@ fn load_source(path: &str, format: Format, head: &[u8], opts: &Opts) -> Result<S
Ok(Src::Owned(glb))
}
Format::Stl => {
- let bytes =
- std::fs::read(path).map_err(|e| ActionErr::new("invalid_input", e.to_string()))?;
+ let bytes = map_source(path)?;
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::Glb => Ok(Src::Mapped(map_source(path)?)),
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()
+ let gltf = map_source(path)?;
+ // `geometry-*`, so startup cleanup removes it after a kill.
+ let mut tmp = tempfile::Builder::new()
+ .prefix("geometry-")
+ .tempfile()
.map_err(|e| ActionErr::new("invalid_input", format!("temp glb: {e}")))?;
{
let mut bw = std::io::BufWriter::new(&mut tmp);
@@ -703,8 +722,7 @@ fn load_source(path: &str, format: Format, head: &[u8], opts: &Opts) -> Result<S
// 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 bytes = map_source(path)?;
let glb = match format {
Format::Obj => optimize::obj_to_glb(&bytes),
Format::Ply => optimize::ply_to_glb(&bytes),
@@ -764,7 +782,7 @@ mod tests {
use super::*;
fn default_opts() -> Opts {
- crate::optimize_opts(&serde_json::json!({}), &serde_json::json!({}))
+ crate::request::optimize_opts(&serde_json::json!({}), &serde_json::json!({}))
}
fn fixture_step(name: &str, boxes: u32) -> String {
@@ -800,7 +818,7 @@ mod tests {
);
let compacted = compacted.expect("compacted raw");
assert_eq!(compacted.kind, "xbf");
- let xbf = zstd::decode_all(compacted.bytes.as_slice()).unwrap();
+ let xbf = zstd::decode_all(compacted.bytes.as_ref()).unwrap();
assert!(xbf.starts_with(b"BINFILE"), "the compact form is BinXCAF");
let png = png.expect("thumbnail asked for").expect("thumbnail rendered");
assert!(png.starts_with(b"\x89PNG"));
@@ -824,7 +842,7 @@ mod tests {
let compacted = compacted.expect("compacted raw");
assert_eq!(compacted.kind, "zstd");
- assert_eq!(zstd::decode_all(compacted.bytes.as_slice()).unwrap(), glb);
+ assert_eq!(zstd::decode_all(compacted.bytes.as_ref()).unwrap(), glb);
assert!(png.is_none(), "no thumbnail asked for");
}
@@ -841,7 +859,7 @@ mod tests {
#[ignore = "scratch probe: needs real STEP files in .ai/scratch/"]
fn probe_real_model() {
let scratch = concat!(env!("CARGO_MANIFEST_DIR"), "/../../.ai/scratch");
- let opts = crate::optimize_opts(&serde_json::json!({}), &serde_json::json!({}));
+ let opts = crate::request::optimize_opts(&serde_json::json!({}), &serde_json::json!({}));
eprintln!(
"PROBE opts lin={} ang={} auto_scale={} max_packed={} max_output={}",
opts.lin, opts.ang, opts.auto_scale, opts.max_packed, opts.max_output
@@ -866,7 +884,7 @@ mod tests {
// Force the measured-overshoot predictor path.
("tight-gates", 8 * 1024 * 1024, 2 * 1024 * 1024),
] {
- let mut o = crate::optimize_opts(&serde_json::json!({}), &serde_json::json!({}));
+ let mut o = crate::request::optimize_opts(&serde_json::json!({}), &serde_json::json!({}));
o.max_packed = max_packed;
o.max_output = max_output;
let t0 = std::time::Instant::now();
diff --git a/apps/assembler/src/actions/plan.rs b/apps/assembler/src/actions/plan.rs
index 356dabe12d..8f992e8ee8 100644
--- a/apps/assembler/src/actions/plan.rs
+++ b/apps/assembler/src/actions/plan.rs
@@ -3,11 +3,11 @@
// including ports, remain AGPLv3; serving them over a network requires releasing their source.
//! `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.
+//! runs detached, the caller long-polls. On completion the plan.json is
+//! uploaded to its submit-time URL.
use crate::jobs::{opts_hash, Done, Output};
-use crate::{admission, config, http, telemetry, AppState};
+use crate::{admission, compute, config, http, telemetry, AppState};
use planner::steps::PlanUnit;
use serde_json::{json, Value};
use std::time::Instant;
@@ -16,8 +16,8 @@ use std::time::Instant;
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>,
+ /// The plan.json is PUT to the submit-time signed URL, key `plan`.
+ pub plan_path: String,
/// Scopes the content-hash result cache; None disables caching for this job.
pub model_upload_id: Option<String>,
pub options: Value,
@@ -26,6 +26,7 @@ pub struct PlanReq {
pub fn spawn(state: &AppState, job_id: &str, req: PlanReq) {
let jobs = state.jobs.clone();
let admission = state.admission.clone();
+ let sources = state.sources.clone();
let job_id = job_id.to_string();
telemetry::spawn_job(&job_id.clone(), "plan", async move {
if jobs.is_canceled(&job_id).await {
@@ -33,24 +34,23 @@ pub fn spawn(state: &AppState, job_id: &str, req: PlanReq) {
}
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,
+ let src = match sources.download(&req.source_url, "step", None).await {
+ Ok(src) => src,
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 content_hash = src.hash;
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;
+ drop(src);
eprintln!("[{job_id}] plan cache hit");
jobs.set_done(&job_id, done).await;
jobs.send_callback(&job_id).await;
@@ -58,29 +58,29 @@ pub fn spawn(state: &AppState, job_id: &str, req: PlanReq) {
}
}
- let tmp_str = tmp.to_string_lossy().to_string();
+ let tmp_str = src.path_string();
let (lin, ang, clearance, path_samples, units, sequence, tolerance) =
parse_options(&req.options);
let mp = config::max_parts();
// Sized by the source until the model is read, then by its part count:
// the sweeps, not the read, are where a plan's memory goes.
- let source_bytes = http::file_len(&tmp).await;
+ let source_bytes = http::file_len(src.path()).await;
let grant = admission
.acquire(admission::plan_estimate_mb(source_bytes, None))
.await;
// The wait may have been long: a job cancelled meanwhile is dropped
// before it takes the memory it was granted.
if jobs.is_canceled(&job_id).await {
- drop(grant);
- let _ = tokio::fs::remove_file(&tmp).await;
return;
}
// Running from here on: the wait for memory is queue time, not work.
jobs.set_status(&job_id, "running").await;
eprintln!("[{job_id}] plan running");
let runtime = tokio::runtime::Handle::current();
- let res = telemetry::in_span("compute", tokio::task::spawn_blocking(move || {
+ // The grant moves into the work (it is resized as parts are counted),
+ // so it is released when the thread really ends.
+ let res = compute::run(None, move || {
let grant = std::sync::Mutex::new(grant);
planner::steps::plan_step_observed(
&tmp_str,
@@ -98,9 +98,9 @@ pub fn spawn(state: &AppState, job_id: &str, req: PlanReq) {
runtime.block_on(grant.resize(estimate));
},
)
- }))
+ })
.await;
- let _ = tokio::fs::remove_file(&tmp).await;
+ drop(src);
match res {
Ok(Ok(r)) => {
@@ -122,50 +122,36 @@ pub fn spawn(state: &AppState, job_id: &str, req: PlanReq) {
.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: bytes.into(),
- }];
- jobs.finish(&job_id, outputs, done, cache).await;
+ let (component_count, planned_count) = (r.component_count, r.planned_count);
+ let bytes = serde_json::to_vec(&r.plan);
+ // The serialized copy is all that is uploaded; free the plan.
+ drop(r);
+ let bytes = match bytes {
+ Ok(b) => b,
+ Err(e) => {
+ jobs.set_error(
+ &job_id,
+ "TESSELLATION_FAILED",
+ format!("serialize plan: {e}"),
+ )
+ .await;
+ return;
}
- // 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;
- }
- }
+ };
+ let done = Done {
+ result: json!({
+ "planPath": req.plan_path,
+ "componentCount": component_count,
+ "plannedCount": planned_count,
+ }),
+ stats,
+ };
+ let outputs = vec![Output {
+ name: "plan".into(),
+ content_type: "application/json".into(),
+ bytes: bytes.into(),
+ }];
+ jobs.finish(&job_id, outputs, done, cache).await;
}
Ok(Err(e)) => {
eprintln!("[{job_id}] plan failed: {}", e.message);
@@ -173,9 +159,9 @@ pub fn spawn(state: &AppState, job_id: &str, req: PlanReq) {
.await;
}
Err(e) => {
- let msg = format!("plan panicked: {e}");
+ let msg = format!("plan {e}");
eprintln!("[{job_id}] {msg}");
- jobs.set_error(&job_id, "TESSELLATION_FAILED", msg).await;
+ jobs.set_error(&job_id, e.code("TESSELLATION_FAILED"), msg).await;
}
}
});
@@ -192,8 +178,12 @@ type Opts = (
);
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 lin = options["linearDeflection"]
+ .as_f64()
+ .unwrap_or(config::TESSELLATION_LINEAR);
+ let ang = options["angularDeflection"]
+ .as_f64()
+ .unwrap_or(config::TESSELLATION_ANGULAR);
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();
diff --git a/apps/assembler/src/actions/thumbnail.rs b/apps/assembler/src/actions/thumbnail.rs
index 2ef36b5686..b61f53e25f 100644
--- a/apps/assembler/src/actions/thumbnail.rs
+++ b/apps/assembler/src/actions/thumbnail.rs
@@ -5,11 +5,11 @@
//! `thumbnail` action — a model's GLB → a square PNG preview, rendered on the
//! CPU by `crates/thumbnail` (no GPU, no browser). The source is a GLB this
//! service wrote: the optimised one (`EXT_meshopt_compression`) or the lossless
-//! `convert` output. Async job; the single `thumbnail` output is late-mint
-//! uploaded.
+//! `convert` output. Async job; the single `thumbnail` output is uploaded to
+//! its submit-time URL.
use crate::jobs::{Done, Output};
-use crate::{admission, http, telemetry, AppState};
+use crate::{admission, compute, http, telemetry, AppState};
use serde_json::json;
use std::time::Instant;
@@ -20,14 +20,15 @@ pub struct ThumbnailReq {
/// Where the camera stands: model towards camera, Z up. The viewer's home
/// direction unless the caller captured another.
pub direction: [f32; 3],
- /// Storage path recorded in the completion pointer; the signed PUT URL is
- /// late-minted per poll, key `thumbnail`.
+ /// Storage path recorded in the completion pointer; the signed PUT URL
+ /// comes with the submit, key `thumbnail`.
pub path: Option<String>,
}
pub fn spawn(state: &AppState, job_id: &str, req: ThumbnailReq) {
let jobs = state.jobs.clone();
let admission = state.admission.clone();
+ let sources = state.sources.clone();
let job_id = job_id.to_string();
telemetry::spawn_job(&job_id.clone(), "thumbnail", async move {
if jobs.is_canceled(&job_id).await {
@@ -35,32 +36,32 @@ pub fn spawn(state: &AppState, job_id: &str, req: ThumbnailReq) {
}
let started = Instant::now();
- let src = http::temp_path("glb");
- if let Err(e) = http::download_hashed(&req.source_url, &src, None).await {
- let _ = tokio::fs::remove_file(&src).await;
- eprintln!("[{job_id}] thumbnail 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 src = match sources.download(&req.source_url, "glb", None).await {
+ Ok(src) => src,
+ Err(e) => {
+ eprintln!("[{job_id}] thumbnail failed: source download: {}", e.message);
+ jobs.set_error(&job_id, &e.code, e.message).await;
+ return;
+ }
+ };
+ let src_str = src.path_string();
let (size, direction) = (req.size, req.direction);
let res = {
- let _grant = admission
- .acquire(admission::estimate_mb(http::file_len(&src).await))
+ let grant = admission
+ .acquire(admission::estimate_mb(http::file_len(src.path()).await))
.await;
// The wait may have been long: a job cancelled meanwhile is dropped
// before it takes the memory it was granted.
if jobs.is_canceled(&job_id).await {
- let _ = tokio::fs::remove_file(&src).await;
return;
}
// Running from here on: the wait for memory is queue time, not work.
jobs.set_status(&job_id, "running").await;
eprintln!("[{job_id}] thumbnail running");
- telemetry::in_span("compute", tokio::task::spawn_blocking(move || render(&src_str, size, direction))).await
+ compute::run(Some(grant), move || render(&src_str, size, direction)).await
};
- let _ = tokio::fs::remove_file(&src).await;
+ drop(src);
let png = match res {
Ok(Ok(png)) => png,
@@ -70,9 +71,9 @@ pub fn spawn(state: &AppState, job_id: &str, req: ThumbnailReq) {
return;
}
Err(e) => {
- let msg = format!("thumbnail panicked: {e}");
+ let msg = format!("thumbnail {e}");
eprintln!("[{job_id}] {msg}");
- jobs.set_error(&job_id, "thumbnail_failed", msg).await;
+ jobs.set_error(&job_id, e.code("thumbnail_failed"), msg).await;
return;
}
};
diff --git a/apps/assembler/src/cache.rs b/apps/assembler/src/cache.rs
index 54230df431..c80a6f518b 100644
--- a/apps/assembler/src/cache.rs
+++ b/apps/assembler/src/cache.rs
@@ -24,7 +24,9 @@ use std::sync::{Arc, Mutex};
/// converter OR planner behavior change so every stale entry, in every cache,
/// auto-misses. This is the "content-hash key + CODE_VERSION" auto-invalidation.
// v3: geometry_hash recipe changed to position-only (nodeIds renamed globally).
-pub const CODE_VERSION: u32 = 3;
+// v4: convert's default angular deflection is 0.5 on every runtime (the standing
+// service used 0.15), matching plan.
+pub const CODE_VERSION: u32 = 4;
pub struct CachedConvert {
pub glb: Bytes,
diff --git a/apps/assembler/src/compute.rs b/apps/assembler/src/compute.rs
new file mode 100644
index 0000000000..52b49d8da3
--- /dev/null
+++ b/apps/assembler/src/compute.rs
@@ -0,0 +1,141 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,
+// including ports, remain AGPLv3; serving them over a network requires releasing their source.
+
+//! A job's blocking compute, bounded. OCCT and FCL calls cannot be interrupted
+//! and a blocking thread cannot be killed, so a compute that hangs (or is
+//! canceled) is not stopped: the job ends at once, and the thread finishes in
+//! the background still holding the job's memory grant, so admission never
+//! counts as free the memory that thread may still be using.
+
+use crate::{admission::Grant, jobs, telemetry};
+use std::time::Duration;
+
+/// The longest a compute may run before its job fails. Lambda's own 900 s
+/// timeout comes first there; this bounds the standing service, which has
+/// none. Generous: the largest plans take tens of minutes.
+pub const COMPUTE_DEADLINE: Duration = Duration::from_secs(60 * 60);
+
+pub enum ComputeFailure {
+ Panicked(String),
+ TimedOut,
+ Canceled,
+}
+
+impl ComputeFailure {
+ /// The job's error code: the action's own for a panic.
+ pub fn code(&self, panic_code: &'static str) -> &'static str {
+ match self {
+ ComputeFailure::Panicked(_) => panic_code,
+ ComputeFailure::TimedOut => "COMPUTE_TIMEOUT",
+ ComputeFailure::Canceled => "canceled",
+ }
+ }
+}
+
+impl std::fmt::Display for ComputeFailure {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ match self {
+ ComputeFailure::Panicked(e) => write!(f, "panicked: {e}"),
+ ComputeFailure::TimedOut => write!(
+ f,
+ "did not finish within {} minutes",
+ COMPUTE_DEADLINE.as_secs() / 60
+ ),
+ ComputeFailure::Canceled => write!(f, "was canceled"),
+ }
+ }
+}
+
+/// Run `work` on the blocking pool in a `compute` span, until it returns, the
+/// deadline passes, or the job is canceled. `grant` is held until the thread
+/// really finishes, whichever comes first.
+pub async fn run<T: Send + 'static>(
+ grant: Option<Grant>,
+ work: impl FnOnce() -> T + Send + 'static,
+) -> Result<T, ComputeFailure> {
+ bounded(grant, work, COMPUTE_DEADLINE).await
+}
+
+async fn bounded<T: Send + 'static>(
+ grant: Option<Grant>,
+ work: impl FnOnce() -> T + Send + 'static,
+ deadline: Duration,
+) -> Result<T, ComputeFailure> {
+ let mut handle = tokio::task::spawn_blocking(work);
+ let cancel = jobs::current_cancel();
+ let canceled = async {
+ match &cancel {
+ Some(token) => token.cancelled().await,
+ None => std::future::pending().await,
+ }
+ };
+ let finished = telemetry::in_span("compute", async {
+ tokio::select! {
+ joined = &mut handle => Some(joined),
+ _ = tokio::time::sleep(deadline) => None,
+ _ = canceled => None,
+ }
+ })
+ .await;
+ match finished {
+ Some(joined) => {
+ drop(grant);
+ joined.map_err(|e| ComputeFailure::Panicked(e.to_string()))
+ }
+ None => {
+ let timed_out = !cancel.as_ref().is_some_and(|t| t.is_cancelled());
+ // The thread runs on; its memory stays counted until it is done.
+ tokio::spawn(async move {
+ let _ = handle.await;
+ drop(grant);
+ });
+ Err(if timed_out {
+ ComputeFailure::TimedOut
+ } else {
+ ComputeFailure::Canceled
+ })
+ }
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::admission::Admission;
+
+ #[tokio::test]
+ async fn a_compute_past_its_deadline_fails_but_keeps_its_memory_until_done() {
+ let admission = Admission::with_budget_mb(100);
+ let grant = admission.acquire(100).await;
+ let (release, wait) = std::sync::mpsc::channel::<()>();
+ let failed = bounded(Some(grant), move || wait.recv().unwrap(), Duration::from_millis(50))
+ .await
+ .err()
+ .unwrap();
+ assert!(matches!(failed, ComputeFailure::TimedOut));
+
+ // The thread is still running: its 100 MB are still taken.
+ let next = tokio::time::timeout(Duration::from_millis(100), admission.acquire(100)).await;
+ assert!(next.is_err(), "memory was handed out while the thread still used it");
+
+ release.send(()).unwrap();
+ tokio::time::timeout(Duration::from_secs(1), admission.acquire(100))
+ .await
+ .expect("memory is free once the thread is done");
+ }
+
+ #[tokio::test]
+ async fn a_compute_that_finishes_returns_its_value() {
+ assert_eq!(bounded(None, || 7, Duration::from_secs(5)).await.ok(), Some(7));
+ }
+
+ #[tokio::test]
+ async fn a_canceled_job_stops_waiting_on_its_compute() {
+ let job = crate::jobs::track("cancel-compute", async {
+ crate::jobs::current_cancel().unwrap().cancel();
+ bounded(None, || std::thread::sleep(Duration::from_millis(200)), Duration::from_secs(5)).await
+ });
+ assert!(matches!(job.await.err().unwrap(), ComputeFailure::Canceled));
+ }
+}
diff --git a/apps/assembler/src/config.rs b/apps/assembler/src/config.rs
index bb77e87228..703dbee264 100644
--- a/apps/assembler/src/config.rs
+++ b/apps/assembler/src/config.rs
@@ -11,6 +11,12 @@ use crate::error::ApiError;
// value; unused knobs are just misconfiguration surface. Revisit a constant
// when a real deployment proves it wrong, not before.
+/// The tessellation every nodeId derives from. nodeIds hash the tessellated
+/// vertex positions, so convert's graph.json and plan's plan.json must use the
+/// same one or their nodeIds disagree. 0.5 rad is what every stored plan used.
+pub const TESSELLATION_LINEAR: f64 = 0.1;
+pub const TESSELLATION_ANGULAR: f64 = 0.5;
+
/// 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 {
@@ -78,18 +84,6 @@ pub fn result_ttl_secs() -> 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 {
- 300
-}
-
-/// Where outputs wait on disk for a late-minted upload URL (see `jobs.rs`).
-pub fn pending_dir() -> std::path::PathBuf {
- std::env::temp_dir().join("asm-pending")
-}
-
/// 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 {
@@ -107,6 +101,13 @@ pub fn blocking_threads() -> usize {
(cores + 2).max(2)
}
+/// How many downloaded sources may sit on disk at once (see `source.rs`): one
+/// per compute the blocking pool can run, so a queue past it waits without a
+/// file of its own.
+pub fn source_slots() -> usize {
+ blocking_threads()
+}
+
pub fn require_https() -> bool {
std::env::var("ASSEMBLER_DEV_MODE").as_deref() != Ok("true")
}
@@ -134,13 +135,7 @@ pub fn validate_url(url: &str) -> Result<(), ApiError> {
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>() {
- let blocked = match ip {
- std::net::IpAddr::V4(v4) => {
- v4.is_private() || v4.is_loopback() || v4.is_link_local()
- }
- std::net::IpAddr::V6(v6) => v6.is_loopback() || v6.is_unspecified(),
- };
- if blocked {
+ if !is_public_ip(ip) {
return Err(ApiError::invalid("URL host is not allowed"));
}
}
@@ -148,3 +143,50 @@ pub fn validate_url(url: &str) -> Result<(), ApiError> {
}
Ok(())
}
+
+/// Whether an address is on the public internet: not loopback, private,
+/// link-local, unspecified, broadcast, CGNAT (100.64/10) or IPv6 unique-local,
+/// and an IPv4-mapped IPv6 address is judged as the IPv4 it maps.
+pub fn is_public_ip(ip: std::net::IpAddr) -> bool {
+ match ip {
+ std::net::IpAddr::V4(v4) => {
+ let [a, b, ..] = v4.octets();
+ !(v4.is_private()
+ || v4.is_loopback()
+ || v4.is_link_local()
+ || v4.is_unspecified()
+ || v4.is_broadcast()
+ || a == 0
+ || (a == 100 && (64..128).contains(&b)))
+ }
+ std::net::IpAddr::V6(v6) => {
+ if let Some(v4) = v6.to_ipv4_mapped() {
+ return is_public_ip(std::net::IpAddr::V4(v4));
+ }
+ let first = v6.segments()[0];
+ !(v6.is_loopback()
+ || v6.is_unspecified()
+ || (first & 0xfe00) == 0xfc00 // unique local, fc00::/7
+ || (first & 0xffc0) == 0xfe80) // link local, fe80::/10
+ }
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::is_public_ip;
+
+ #[test]
+ fn only_public_addresses_pass() {
+ for blocked in [
+ "127.0.0.1", "10.1.2.3", "172.16.0.1", "192.168.1.1", "169.254.169.254",
+ "0.0.0.0", "100.64.0.1", "255.255.255.255", "::1", "::", "fd00::1",
+ "fe80::1", "::ffff:127.0.0.1", "::ffff:10.0.0.1",
+ ] {
+ assert!(!is_public_ip(blocked.parse().unwrap()), "{blocked}");
+ }
+ for public in ["8.8.8.8", "100.128.0.1", "2606:4700::1111", "::ffff:1.1.1.1"] {
+ assert!(is_public_ip(public.parse().unwrap()), "{public}");
+ }
+ }
+}
diff --git a/apps/assembler/src/dispatch.rs b/apps/assembler/src/dispatch.rs
index fa2d2865b1..725a4d45e8 100644
--- a/apps/assembler/src/dispatch.rs
+++ b/apps/assembler/src/dispatch.rs
@@ -98,7 +98,11 @@ pub async fn self_invoke(spec: &Value) -> Result<(), String> {
"AWS4-HMAC-SHA256 Credential={access_key}/{scope}, SignedHeaders={signed_headers}, Signature={signature}"
);
- let client = reqwest::Client::new();
+ // Bounded: the create handler waits on this inside API Gateway's 30 s.
+ let client = reqwest::Client::builder()
+ .timeout(std::time::Duration::from_secs(10))
+ .build()
+ .map_err(|e| format!("lambda invoke client: {e}"))?;
let mut req = client
.post(format!("https://{host}{path}"))
.header("content-type", "application/json")
diff --git a/apps/assembler/src/error.rs b/apps/assembler/src/error.rs
index 3c7fc34acf..2daf21eefe 100644
--- a/apps/assembler/src/error.rs
+++ b/apps/assembler/src/error.rs
@@ -8,6 +8,7 @@
use axum::{http::StatusCode, response::IntoResponse, Json};
use serde_json::json;
+#[derive(Debug)]
pub struct ApiError {
pub status: u16,
pub code: String,
diff --git a/apps/assembler/src/http.rs b/apps/assembler/src/http.rs
index 0a88c00048..46fc5f3172 100644
--- a/apps/assembler/src/http.rs
+++ b/apps/assembler/src/http.rs
@@ -40,12 +40,29 @@ fn clear_sources_in(dir: &std::path::Path) {
}
}
+/// The whole download, headers to last byte. The read timeout below catches a
+/// stalled connection; this catches one that trickles. Generous: a 2.5 GB
+/// source at 1 MB/s still lands.
+const DOWNLOAD_DEADLINE: std::time::Duration = std::time::Duration::from_secs(60 * 60);
+
+/// The whole upload: two minutes plus 2 MB/s of body.
+fn upload_deadline(bytes: Option<u64>) -> std::time::Duration {
+ std::time::Duration::from_secs(120 + bytes.unwrap_or(0) / (2 * 1024 * 1024))
+}
+
/// One shared client for the process: reuses connections (keep-alive/h2)
/// instead of paying a fresh pool + TLS handshake per download/upload.
+///
+/// Follows no redirects: every URL here is a signed storage URL or our own
+/// callback, checked by `config::validate_url`, and a redirect would take the
+/// request to a host that was never checked. Errors never carry the URL
+/// (`without_url`): signed URLs hold their token in the query string, and an
+/// error message is logged, stored on the job and returned to the caller.
fn client() -> &'static reqwest::Client {
static CLIENT: std::sync::OnceLock<reqwest::Client> = std::sync::OnceLock::new();
CLIENT.get_or_init(|| {
reqwest::Client::builder()
+ .redirect(reqwest::redirect::Policy::none())
.danger_accept_invalid_certs(!config::verify_tls())
.connect_timeout(std::time::Duration::from_secs(10))
// Idle-read timeout, not a total deadline: a large source can stream
@@ -57,6 +74,81 @@ fn client() -> &'static reqwest::Client {
})
}
+/// Resolves a host to its public addresses only, refusing one that has none.
+/// `validate_url` sees only the URL, so a hostname that resolves to a private
+/// address (a tenant URL pointed inside the network) passed it.
+struct PublicOnly;
+
+impl reqwest::dns::Resolve for PublicOnly {
+ fn resolve(&self, name: reqwest::dns::Name) -> reqwest::dns::Resolving {
+ let host = name.as_str().to_string();
+ Box::pin(async move {
+ let addrs = public_addrs(&host).await?;
+ Ok(Box::new(addrs.into_iter()) as reqwest::dns::Addrs)
+ })
+ }
+}
+
+async fn public_addrs(
+ host: &str,
+) -> Result<Vec<std::net::SocketAddr>, Box<dyn std::error::Error + Send + Sync>> {
+ let addrs: Vec<_> = tokio::net::lookup_host((host, 0))
+ .await?
+ .filter(|addr| config::is_public_ip(addr.ip()))
+ .collect();
+ if addrs.is_empty() {
+ return Err(format!("{host} resolves to no public address").into());
+ }
+ Ok(addrs)
+}
+
+/// The `fetch` action's client: it follows redirects (a CAD system may answer
+/// a download with one to its object store), but only to URLs that pass
+/// `config::validate_url`, and at most five. reqwest drops the Authorization
+/// header on a redirect to another host. Outside dev mode it connects only to
+/// public addresses (`PublicOnly`): `fetch` is the one action whose URL comes
+/// from a third party (a CAD system's tenant URL is the customer's to set),
+/// while every other URL is one of our own signed storage URLs.
+fn fetch_client() -> &'static reqwest::Client {
+ static CLIENT: std::sync::OnceLock<reqwest::Client> = std::sync::OnceLock::new();
+ CLIENT.get_or_init(|| {
+ let policy = reqwest::redirect::Policy::custom(|attempt| {
+ if attempt.previous().len() >= 5 {
+ attempt.error("too many redirects")
+ } else if config::validate_url(attempt.url().as_str()).is_err() {
+ attempt.error("redirect to a host that is not allowed")
+ } else {
+ attempt.follow()
+ }
+ });
+ let builder = reqwest::Client::builder();
+ let builder = if config::require_https() {
+ builder.dns_resolver(std::sync::Arc::new(PublicOnly))
+ } else {
+ builder
+ };
+ builder
+ .redirect(policy)
+ .danger_accept_invalid_certs(!config::verify_tls())
+ .connect_timeout(std::time::Duration::from_secs(10))
+ .read_timeout(std::time::Duration::from_secs(60))
+ .build()
+ .expect("reqwest client")
+ })
+}
+
+/// What a download may do beyond the default (the `fetch` action's).
+#[derive(Default)]
+pub struct DownloadOpts<'a> {
+ /// Sent as the `Authorization` header, marked sensitive.
+ pub authorization: Option<&'a str>,
+ /// Refuse a body past this many bytes (413 `LIMIT_EXCEEDED`).
+ pub max_bytes: Option<u64>,
+ /// Write the bytes exactly as served: no zstd decoding, and follow
+ /// validated redirects.
+ pub passthrough: bool,
+}
+
/// 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.
@@ -66,29 +158,66 @@ fn client() -> &'static reqwest::Client {
/// 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(
+pub async fn download_with(
url: &str,
dest: &std::path::Path,
progress: Option<&crate::progress::JobProgress>,
+ opts: &DownloadOpts<'_>,
) -> Result<u128, ApiError> {
- telemetry::outbound("download source", url, download(url, dest, progress)).await
+ let mut request = if opts.passthrough {
+ fetch_client().get(url)
+ } else {
+ client().get(url)
+ };
+ if let Some(auth) = opts.authorization {
+ let mut value = reqwest::header::HeaderValue::from_str(auth)
+ .map_err(|_| ApiError::invalid("invalid source.authorization"))?;
+ value.set_sensitive(true);
+ request = request.header(reqwest::header::AUTHORIZATION, value);
+ }
+ let limit = opts
+ .max_bytes
+ .map_or(config::max_source_bytes(), |b| b as usize);
+ let span = if opts.passthrough { "fetch source" } else { "download source" };
+ let download = download(request.timeout(DOWNLOAD_DEADLINE), dest, progress, limit, !opts.passthrough);
+ telemetry::outbound(span, url, unless_canceled(download)).await
+}
+
+/// Run a transfer for the current job, giving up the moment the job is
+/// canceled (`jobs::track`'s token): a canceled job stops moving bytes.
+async fn unless_canceled<T>(
+ transfer: impl std::future::Future<Output = Result<T, ApiError>>,
+) -> Result<T, ApiError> {
+ let Some(token) = crate::jobs::current_cancel() else {
+ return transfer.await;
+ };
+ tokio::select! {
+ result = transfer => result,
+ _ = token.cancelled() => Err(ApiError::new(409, "canceled", "the job was canceled")),
+ }
}
+/// `limit` 0 = unlimited.
async fn download(
- url: &str,
+ request: reqwest::RequestBuilder,
dest: &std::path::Path,
progress: Option<&crate::progress::JobProgress>,
+ limit: usize,
+ decode_zstd: bool,
) -> Result<u128, ApiError> {
use async_compression::tokio::bufread::ZstdDecoder;
use futures_util::StreamExt;
use tokio::io::{AsyncBufReadExt, AsyncReadExt, AsyncWriteExt};
- let limit = config::max_source_bytes();
- let resp = client().get(url).send().await.map_err(|e| {
+ let too_large = || ApiError::new(413, "LIMIT_EXCEEDED", "source file exceeds the size limit");
+ let resp = request
+ .send()
+ .await
+ .map_err(|e| {
ApiError::new(
422,
"READ_FAILED",
- format!("could not download source: {e}"),
+ format!("could not download source: {}", e.without_url()),
)
})?;
if !resp.status().is_success() {
@@ -98,6 +227,9 @@ async fn download(
format!("could not download source: {}", resp.status()),
));
}
+ if limit > 0 && resp.content_length().is_some_and(|len| len > limit as u64) {
+ return Err(too_large());
+ }
// 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 {
@@ -122,7 +254,7 @@ async fn download(
// 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)));
+ .map(|r| r.map_err(|e| std::io::Error::new(std::io::ErrorKind::Other, e.without_url())));
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| {
@@ -132,7 +264,7 @@ async fn download(
format!("could not download source: {e}"),
)
})?;
- head.len() >= 4 && head[0..4] == [0x28, 0xB5, 0x2F, 0xFD]
+ decode_zstd && 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 {
@@ -164,11 +296,7 @@ async fn download(
written += n;
if limit > 0 && written > limit {
let _ = tokio::fs::remove_file(dest).await;
- return Err(ApiError::new(
- 413,
- "LIMIT_EXCEEDED",
- "source file exceeds the size limit",
- ));
+ return Err(too_large());
}
if let Some(p) = progress {
p.done
@@ -194,7 +322,7 @@ pub async fn file_len(path: &std::path::Path) -> u64 {
}
/// A file's bytes, memory-mapped: the page cache backs them, so uploading a
-/// parked or cached artifact does not copy it onto the heap.
+/// cached artifact does not copy it onto the heap.
pub fn map_file(path: &std::path::Path) -> std::io::Result<bytes::Bytes> {
let file = std::fs::File::open(path)?;
if file.metadata()?.len() == 0 {
@@ -211,12 +339,15 @@ pub async fn upload(
body: impl Into<reqwest::Body>,
content_type: &str,
) -> Result<(), ApiError> {
- telemetry::outbound("upload artifact", url, put(url, body.into(), content_type)).await
+ let put = put(url, body.into(), content_type);
+ telemetry::outbound("upload artifact", url, unless_canceled(put)).await
}
async fn put(url: &str, body: reqwest::Body, content_type: &str) -> Result<(), ApiError> {
+ let deadline = upload_deadline(body.as_bytes().map(|b| b.len() as u64));
let resp = client()
.put(url)
+ .timeout(deadline)
.header("Content-Type", content_type)
.header("x-upsert", "true") // retried jobs re-upload to the same path
.body(body)
@@ -226,7 +357,7 @@ async fn put(url: &str, body: reqwest::Body, content_type: &str) -> Result<(), A
ApiError::new(
502,
"UPLOAD_FAILED",
- format!("could not upload artifact: {e}"),
+ format!("could not upload artifact: {}", e.without_url()),
)
})?;
if !resp.status().is_success() {
@@ -256,7 +387,13 @@ async fn post(url: &str, body: &serde_json::Value) -> Result<(), ApiError> {
.timeout(std::time::Duration::from_secs(10))
.send()
.await
- .map_err(|e| ApiError::new(502, "CALLBACK_FAILED", format!("callback POST failed: {e}")))?;
+ .map_err(|e| {
+ ApiError::new(
+ 502,
+ "CALLBACK_FAILED",
+ format!("callback POST failed: {}", e.without_url()),
+ )
+ })?;
if !resp.status().is_success() {
return Err(ApiError::new(
502,
@@ -271,6 +408,181 @@ async fn post(url: &str, body: &serde_json::Value) -> Result<(), ApiError> {
mod tests {
use super::*;
+ #[tokio::test]
+ async fn a_failed_request_never_echoes_its_signed_url() {
+ // Nothing listens on port 1: the connect fails, and reqwest's error
+ // would normally quote the whole URL, token included.
+ let url = "http://127.0.0.1:1/object/sign/m.step?token=secret-token";
+ let dest = temp_path("step");
+ let download = download_with(url, &dest, None, &DownloadOpts::default()).await.err().unwrap();
+ let upload = upload(url, bytes::Bytes::new(), "application/step").await.err().unwrap();
+ let callback = post_json(url, &serde_json::json!({})).await.err().unwrap();
+ for message in [download.message, upload.message, callback.message] {
+ assert!(!message.contains("secret-token"), "{message}");
+ assert!(!message.contains("/object/sign"), "{message}");
+ }
+ }
+
+ #[tokio::test]
+ async fn a_redirect_is_not_followed() {
+ let app = axum::Router::new()
+ .route(
+ "/object",
+ axum::routing::get(|| async {
+ (axum::http::StatusCode::FOUND, [("location", "/elsewhere")])
+ }),
+ )
+ .route("/elsewhere", axum::routing::get(|| async { "unchecked host" }));
+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
+ let addr = listener.local_addr().unwrap();
+ tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });
+
+ let dest = temp_path("step");
+ let err = download_with(&format!("http://{addr}/object"), &dest, None, &DownloadOpts::default())
+ .await
+ .err()
+ .unwrap();
+ assert!(err.message.contains("302"), "{}", err.message);
+ }
+
+ /// A CAD system's download stand-in: `/export` needs the bearer and
+ /// redirects to `/blob` on the SAME host; `/elsewhere` redirects to a
+ /// second listener, which records whether an Authorization header came.
+ async fn cad_system(body: &'static [u8]) -> (String, std::sync::Arc<std::sync::atomic::AtomicBool>) {
+ use axum::http::{HeaderMap, StatusCode};
+ use std::sync::atomic::{AtomicBool, Ordering};
+ let leaked = std::sync::Arc::new(AtomicBool::new(false));
+ let seen = leaked.clone();
+ let other = axum::Router::new().route(
+ "/blob",
+ axum::routing::get(move |headers: HeaderMap| {
+ let seen = seen.clone();
+ async move {
+ seen.store(headers.contains_key("authorization"), Ordering::SeqCst);
+ body
+ }
+ }),
+ );
+ let other_listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
+ let other_addr = other_listener.local_addr().unwrap();
+ tokio::spawn(async move { axum::serve(other_listener, other).await.unwrap() });
+
+ let app = axum::Router::new()
+ .route(
+ "/export",
+ axum::routing::get(|headers: HeaderMap| async move {
+ if headers.get("authorization").and_then(|v| v.to_str().ok())
+ == Some("Bearer onshape-token")
+ {
+ (StatusCode::FOUND, [("location", "/blob")]).into_response()
+ } else {
+ StatusCode::UNAUTHORIZED.into_response()
+ }
+ }),
+ )
+ .route("/blob", axum::routing::get(move || async move { body }))
+ .route(
+ "/elsewhere",
+ axum::routing::get(move || async move {
+ (StatusCode::FOUND, [("location", format!("http://{other_addr}/blob"))])
+ }),
+ );
+ use axum::response::IntoResponse;
+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
+ let addr = listener.local_addr().unwrap();
+ tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });
+ (format!("http://{addr}"), leaked)
+ }
+
+ #[tokio::test]
+ async fn a_host_resolving_only_to_private_addresses_is_refused() {
+ let err = public_addrs("localhost").await.err().unwrap();
+ assert!(err.to_string().contains("no public address"), "{err}");
+ }
+
+ #[tokio::test]
+ async fn a_canceled_job_stops_its_download_at_once() {
+ // A source that sends headers and then nothing: the download would sit
+ // in its 60 s read timeout.
+ let app = axum::Router::new().route(
+ "/slow",
+ axum::routing::get(|| async {
+ let stream = futures_util::stream::pending::<Result<bytes::Bytes, std::io::Error>>();
+ axum::body::Body::from_stream(stream)
+ }),
+ );
+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
+ let addr = listener.local_addr().unwrap();
+ tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });
+
+ let dest = temp_path("step");
+ let url = format!("http://{addr}/slow");
+ let job = crate::jobs::track("cancel-download", async move {
+ let token = crate::jobs::current_cancel().unwrap();
+ tokio::spawn(async move {
+ tokio::time::sleep(std::time::Duration::from_millis(100)).await;
+ token.cancel();
+ });
+ download_with(&url, &dest, None, &DownloadOpts::default()).await
+ });
+ let err = tokio::time::timeout(std::time::Duration::from_secs(5), job)
+ .await
+ .expect("the download stopped")
+ .err()
+ .unwrap();
+ assert_eq!(err.code, "canceled");
+ }
+
+ fn fetch_opts(auth: Option<&str>, max_bytes: Option<u64>) -> DownloadOpts<'_> {
+ // The stand-ins are plain http on 127.0.0.1, which `validate_url` (and
+ // so the redirect policy) allows only in dev mode, as in local dev.
+ std::env::set_var("ASSEMBLER_DEV_MODE", "true");
+ DownloadOpts { authorization: auth, max_bytes, passthrough: true }
+ }
+
+ #[tokio::test]
+ async fn a_fetch_sends_its_bearer_and_writes_the_bytes_unchanged() {
+ // zstd magic first: a passthrough must not decode it.
+ let body: &'static [u8] = &[0x28, 0xB5, 0x2F, 0xFD, 1, 2, 3];
+ let (base, _) = cad_system(body).await;
+ let dest = temp_path("fetch");
+ let hash = download_with(&format!("{base}/export"), &dest, None, &fetch_opts(Some("Bearer onshape-token"), None))
+ .await
+ .unwrap();
+ assert_eq!(std::fs::read(&dest).unwrap(), body);
+ assert_eq!(hash, xxhash_rust::xxh3::xxh3_128(body));
+ let _ = std::fs::remove_file(&dest);
+
+ let refused = download_with(&format!("{base}/export"), &dest, None, &fetch_opts(None, None))
+ .await
+ .err()
+ .unwrap();
+ assert!(refused.message.contains("401"), "{}", refused.message);
+ }
+
+ #[tokio::test]
+ async fn a_fetch_redirected_to_another_host_does_not_carry_the_bearer() {
+ let (base, leaked) = cad_system(b"ISO-10303-21;").await;
+ let dest = temp_path("fetch");
+ download_with(&format!("{base}/elsewhere"), &dest, None, &fetch_opts(Some("Bearer onshape-token"), None))
+ .await
+ .unwrap();
+ let _ = std::fs::remove_file(&dest);
+ assert!(!leaked.load(std::sync::atomic::Ordering::SeqCst));
+ }
+
+ #[tokio::test]
+ async fn a_fetch_past_its_cap_is_refused() {
+ let (base, _) = cad_system(b"ISO-10303-21; far too long").await;
+ let dest = temp_path("fetch");
+ let err = download_with(&format!("{base}/export"), &dest, None, &fetch_opts(Some("Bearer onshape-token"), Some(4)))
+ .await
+ .err()
+ .unwrap();
+ assert_eq!((err.status, err.code.as_str()), (413, "LIMIT_EXCEEDED"));
+ assert!(!dest.exists());
+ }
+
#[test]
fn stale_sources_are_cleared_and_nothing_else() {
let dir = tempfile::tempdir().unwrap();
diff --git a/apps/assembler/src/jobs.rs b/apps/assembler/src/jobs.rs
index 480354e6f1..31cf2f321b 100644
--- a/apps/assembler/src/jobs.rs
+++ b/apps/assembler/src/jobs.rs
@@ -2,64 +2,141 @@
// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,
// including ports, remain AGPLv3; serving them over a network requires releasing their source.
-//! Async job store shared by every action (convert / optimize / plan / compact / thumbnail).
-//! 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.
+//! Async job store shared by every action (`request::ACTIONS`).
+//! One lifecycle for all actions: create -> compute -> upload to the submit-time
+//! URLs -> completion callback; GET /v1/jobs/{id}?wait= serves status.
//!
//! 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.
+//! pointers 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 straight from memory when the submit
-//! carried the URLs; only a `{result, stats}` POINTER is stored. Outputs that
-//! could not be uploaded yet (no URL at submit, or the upload failed) are parked
-//! for a late-mint poll: as files under the temp dir on a standing service, so
-//! a large model never lands in a Redis the apps share, or in Redis on Lambda,
-//! where the poll is answered by a different invocation than the one that
-//! computed.
-
-use crate::{cache::CODE_VERSION, config, dispatch, http};
+//! Artifacts are PUT to the caller's signed URLs straight from memory; only a
+//! `{result, stats}` POINTER is stored. Artifact bytes never go to Redis: an
+//! upload that still fails after its retries fails the job with
+//! `UPLOAD_FAILED`, and the caller resubmits with fresh URLs.
+
+use crate::{cache::CODE_VERSION, config, http};
use bytes::Bytes;
use dashmap::DashMap;
use redis::AsyncCommands;
-use serde::{Deserialize, Serialize};
use serde_json::{json, Value};
use std::collections::HashMap;
-use std::path::PathBuf;
-use std::sync::Arc;
+use std::future::Future;
+use std::sync::{Arc, LazyLock};
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)]
+use tokio_util::sync::CancellationToken;
+
+/// Waits between upload attempts: four tries in all, about seven seconds.
+const UPLOAD_RETRY_DELAYS: [Duration; 3] = [
+ Duration::from_secs(1),
+ Duration::from_secs(2),
+ Duration::from_secs(4),
+];
+
+/// One job's state: a Redis HASH (one field each), so a status change can be
+/// made conditional on the current status in one script without decoding the
+/// rest. `result`/`stats` hold the completion POINTER (paths + counts) — never
+/// the artifact bytes.
+#[derive(Clone)]
struct JobRecord {
- action: String, // convert | optimize | plan | compact | thumbnail
- status: String, // pending | running | uploading | done | error | canceled
- #[serde(skip_serializing_if = "Option::is_none")]
+ action: String, // one of `request::ACTIONS`
+ status: String, // pending | starting | running | uploading | done | error | canceled
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)]
+ /// Signed PUT URLs handed over AT SUBMIT (name → URL), one per output.
+ /// Never rendered; cleared once the job ends (they are bearer tokens).
+ /// `callback_url` stays: the Lambda worker re-sends the callback after the
+ /// job ends, and it only lets its holder report this one job.
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>,
}
+impl JobRecord {
+ fn from_fields(mut fields: HashMap<String, String>) -> Option<Self> {
+ fn json<T: serde::de::DeserializeOwned>(v: Option<String>) -> Option<T> {
+ v.and_then(|s| serde_json::from_str(&s).ok())
+ }
+ Some(JobRecord {
+ action: fields.remove("action")?,
+ status: fields.remove("status")?,
+ result: json(fields.remove("result")),
+ stats: json(fields.remove("stats")),
+ error: json(fields.remove("error")),
+ upload_urls: json(fields.remove("upload_urls")),
+ callback_url: fields.remove("callback_url"),
+ })
+ }
+}
+
+/// Change a job only while it is still active (the one status check and the
+/// write are a single atomic script, so a finish can never overwrite a cancel
+/// that landed meanwhile). ARGV: ttl, n, then n field/value pairs to set, then
+/// fields to delete. Returns 1 when it changed the job.
+static TRANSITION: LazyLock<redis::Script> = LazyLock::new(|| {
+ redis::Script::new(
+ r"
+ local s = redis.call('HGET', KEYS[1], 'status')
+ if s ~= 'pending' and s ~= 'starting' and s ~= 'running' and s ~= 'uploading' then
+ return 0
+ end
+ local n = tonumber(ARGV[2])
+ for i = 0, n - 1 do
+ redis.call('HSET', KEYS[1], ARGV[3 + 2 * i], ARGV[4 + 2 * i])
+ end
+ for i = 3 + 2 * n, #ARGV do
+ redis.call('HDEL', KEYS[1], ARGV[i])
+ end
+ redis.call('EXPIRE', KEYS[1], ARGV[1])
+ return 1
+ ",
+ )
+});
+
+/// How long a running job's lease lives, and how often its worker renews it.
+/// A poll that finds an active job with no lease ends it as `WORKER_LOST`: the
+/// process running it died (a restart, an OOM kill, a Lambda timeout).
+const LEASE_TTL_SECS: u64 = 30;
+const LEASE_RENEW_EVERY: Duration = Duration::from_secs(10);
+
+/// The jobs this process is running, with each one's cancel token.
+static RUNNING: LazyLock<DashMap<String, CancellationToken>> = LazyLock::new(DashMap::new);
+
+tokio::task_local! {
+ /// The running job's cancel token, for the downloads and uploads it makes.
+ static JOB_CANCEL: CancellationToken;
+}
+
+/// Run `job` as job `id` of this process: listed for the lease heartbeat, and
+/// with a cancel token its transfers watch (`current_cancel`).
+pub fn track<F: Future>(id: &str, job: F) -> impl Future<Output = F::Output> {
+ struct Untrack(String);
+ impl Drop for Untrack {
+ fn drop(&mut self) {
+ RUNNING.remove(&self.0);
+ }
+ }
+ let token = CancellationToken::new();
+ RUNNING.insert(id.to_string(), token.clone());
+ let untrack = Untrack(id.to_string());
+ JOB_CANCEL.scope(token, async move {
+ let _untrack = untrack;
+ job.await
+ })
+}
+
+/// The cancel token of the job this task is running, if it is one.
+pub fn current_cancel() -> Option<CancellationToken> {
+ JOB_CANCEL.try_with(CancellationToken::clone).ok()
+}
+
/// One artifact to upload (name → bytes + content type). `Bytes`, so handing it
/// to an upload or a retry is a refcount, never a copy.
#[derive(Clone)]
@@ -76,17 +153,11 @@ pub struct Done {
pub stats: Value,
}
-/// A parked job: its outputs, terminal pointer, and result-cache key.
-type Parked = (Vec<Output>, Done, Option<(String, u128, u64)>);
-
/// Shared job + content-hash result store. Cloned into every handler via
/// `AppState`; inner state is `Arc`/manager-cloned so clones share one store.
#[derive(Clone)]
pub struct JobStore {
conn: redis::aio::ConnectionManager,
- /// Where outputs wait for a late-minted URL: this directory, or Redis when
- /// `None` (Lambda — see the module doc).
- park_dir: Option<PathBuf>,
/// 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: Notifiers,
@@ -134,17 +205,6 @@ impl Drop for Watch {
}
}
-/// 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
@@ -161,8 +221,6 @@ impl JobStore {
eprintln!("assembler: redis job store connected");
JobStore {
conn,
- park_dir: (dispatch::from_env() == dispatch::Dispatch::Local)
- .then(config::pending_dir),
notifiers: Notifiers::default(),
}
}
@@ -202,9 +260,9 @@ impl JobStore {
/// it does not have.
async fn try_read(&self, id: &str) -> Result<Option<JobRecord>, ()> {
let mut c = self.conn.clone();
- match c.get::<_, Option<String>>(job_key(id)).await {
- Ok(Some(s)) => Ok(serde_json::from_str(&s).ok()),
- Ok(None) => Ok(None),
+ match c.hgetall::<_, HashMap<String, String>>(job_key(id)).await {
+ Ok(fields) if fields.is_empty() => Ok(None),
+ Ok(fields) => Ok(JobRecord::from_fields(fields)),
Err(e) => {
eprintln!("assembler: redis job read failed: {e}");
Err(())
@@ -212,16 +270,24 @@ impl JobStore {
}
}
- async fn write(&self, id: &str, rec: &JobRecord) {
- let Ok(payload) = serde_json::to_string(rec) else {
- return;
- };
+ /// Apply `set` and `delete` to an active job; false when the job is gone
+ /// or already ended (canceled included), so nothing was changed.
+ async fn transition(&self, id: &str, set: &[(&str, String)], delete: &[&str]) -> bool {
+ let mut invocation = TRANSITION.key(job_key(id));
+ invocation.arg(config::job_ttl_secs()).arg(set.len());
+ for (field, value) in set {
+ invocation.arg(*field).arg(value);
+ }
+ for field in delete {
+ invocation.arg(*field);
+ }
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}");
+ match invocation.invoke_async::<i64>(&mut c).await {
+ Ok(changed) => changed == 1,
+ Err(e) => {
+ eprintln!("assembler: redis job transition failed: {e}");
+ false
+ }
}
}
@@ -234,10 +300,8 @@ impl JobStore {
}
/// The INTERNAL status of an active job (pending/starting/running/uploading).
- /// The worker inlet dedupes deliveries on these exact names — the external
- /// mapping folds pending/starting->queued and uploading->running, which
- /// would make the worker's pending/uploading branches unreachable (every
- /// Lambda job no-op'd forever).
+ /// The worker inlet decides on these exact names — the external mapping
+ /// folds pending/starting->queued and uploading->running.
pub async fn internal_active(&self, id: &str) -> Option<String> {
self.read(id)
.await
@@ -249,85 +313,235 @@ impl JobStore {
&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;
+ let mut fields = vec![
+ ("action", action.to_string()),
+ ("status", "pending".to_string()),
+ ];
+ if !upload_urls.is_empty() {
+ fields.push(("upload_urls", json!(upload_urls).to_string()));
+ }
+ if let Some(url) = callback_url {
+ fields.push(("callback_url", url));
+ }
+ let key = job_key(id);
+ let mut c = self.conn.clone();
+ let written = redis::pipe()
+ .atomic()
+ .del(&key)
+ .ignore()
+ .hset_multiple(&key, &fields)
+ .ignore()
+ .expire(&key, config::job_ttl_secs() as i64)
+ .ignore()
+ .query_async::<()>(&mut c)
+ .await;
+ if let Err(e) = written {
+ eprintln!("assembler: redis job write failed: {e}");
+ }
}
+ /// Move an active job to `status`. A job that is working (not `pending`)
+ /// holds a lease, renewed by `heartbeat` while this process runs it.
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;
+ // The lease first: a poll between the two writes would otherwise see a
+ // working status with no lease and end a live job `WORKER_LOST`. A
+ // lease left on a job that already ended expires on its own.
+ if status != "pending" {
+ self.renew_lease(id).await;
}
+ self.transition(id, &[("status", status.to_string())], &[]).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.
+ /// Publish a terminal `done` pointer. Does NOT deliver the completion
+ /// callback; its owner sends it: `finish()`, the plan action's cache-hit
+ /// publish, and the Lambda worker 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;
+ let set = [
+ ("status", "done".to_string()),
+ ("result", done.result.to_string()),
+ ("stats", done.stats.to_string()),
+ ];
+ if self.transition(id, &set, &["error", "upload_urls"]).await {
+ self.ended(id).await;
}
self.wake(id);
}
pub async fn set_error(&self, id: &str, code: &str, message: String) {
crate::telemetry::record_error(code, &message);
- 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;
+ let set = [
+ ("status", "error".to_string()),
+ ("error", json!({ "code": code, "message": message }).to_string()),
+ ];
+ if self.transition(id, &set, &["upload_urls"]).await {
+ self.ended(id).await;
}
- self.send_callback(id).await;
+ self.notify(id);
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.
+ /// A job ended: drop its lease and the request a Lambda worker read.
+ async fn ended(&self, id: &str) {
+ let mut c = self.conn.clone();
+ if let Err(e) = c.del::<_, ()>(&[lease_key(id), request_key(id)]).await {
+ eprintln!("assembler: redis job cleanup failed: {e}");
+ }
+ }
+
+ /// Deliver the callback in its own task: its retries can take ~36 s, and
+ /// `set_error`/`cancel` run inside requests that API Gateway cuts at 30 s.
+ fn notify(&self, id: &str) {
+ let store = self.clone();
+ let id = id.to_string();
+ tokio::spawn(async move { store.send_callback(&id).await });
+ }
+
+ // --- leases: who is running a job --------------------------------------
+
+ /// Take a job no live worker holds (a Lambda worker's claim: of two
+ /// deliveries one wins, and a redelivery after a crash takes over).
+ pub async fn claim_lease(&self, id: &str) -> bool {
+ let mut c = self.conn.clone();
+ let claimed: redis::RedisResult<Option<String>> = redis::cmd("SET")
+ .arg(lease_key(id))
+ .arg(1)
+ .arg("NX")
+ .arg("EX")
+ .arg(LEASE_TTL_SECS)
+ .query_async(&mut c)
+ .await;
+ claimed.map_or_else(
+ |e| {
+ eprintln!("assembler: redis lease claim failed: {e}");
+ false
+ },
+ |reply| reply.is_some(),
+ )
+ }
+
+ async fn renew_lease(&self, id: &str) {
+ let mut c = self.conn.clone();
+ if let Err(e) = c
+ .set_ex::<_, _, ()>(lease_key(id), 1, LEASE_TTL_SECS)
+ .await
+ {
+ eprintln!("assembler: redis lease renew failed: {e}");
+ }
+ }
+
+ /// Whether a live worker holds the job. A Redis that cannot be asked
+ /// answers yes: a job is never ended over one failed read.
+ async fn lease_alive(&self, id: &str) -> bool {
+ let mut c = self.conn.clone();
+ c.exists::<_, bool>(lease_key(id)).await.unwrap_or(true)
+ }
+
+ /// Every `LEASE_RENEW_EVERY`: renew the lease of each job this process
+ /// runs, and cancel the token of any that was canceled (from any replica).
+ /// Runs for the life of the process.
+ pub async fn heartbeat(&self) {
+ loop {
+ tokio::time::sleep(LEASE_RENEW_EVERY).await;
+ let running: Vec<(String, CancellationToken)> = RUNNING
+ .iter()
+ .map(|e| (e.key().clone(), e.value().clone()))
+ .collect();
+ if running.is_empty() {
+ continue;
+ }
+ let mut pipe = redis::pipe();
+ for (id, _) in &running {
+ pipe.set_ex(lease_key(id), 1, LEASE_TTL_SECS).ignore();
+ pipe.hget(job_key(id), "status");
+ }
+ let mut c = self.conn.clone();
+ match pipe.query_async::<Vec<Option<String>>>(&mut c).await {
+ Ok(statuses) => {
+ for ((_, token), status) in running.iter().zip(statuses) {
+ if status.as_deref() == Some("canceled") {
+ token.cancel();
+ }
+ }
+ }
+ Err(e) => eprintln!("assembler: redis heartbeat failed: {e}"),
+ }
+ }
+ }
+
+ // --- Lambda requests ----------------------------------------------------
+
+ /// Hold a Lambda job's request body for its worker. The worker spec carries
+ /// only ids, so signed URLs and caller tokens never ride in the Invoke
+ /// payload (which AWS keeps for its async retries). Kept until the job
+ /// ends, so a redelivery after a crashed worker can run it again.
+ pub async fn put_request(&self, id: &str, body: &Value) -> Result<(), String> {
+ let mut c = self.conn.clone();
+ c.set_ex::<_, _, ()>(request_key(id), body.to_string(), REQUEST_TTL_SECS)
+ .await
+ .map_err(|e| format!("could not store the request: {e}"))
+ }
+
+ /// A Lambda job's request body; `None` once the job ended or it expired.
+ pub async fn read_request(&self, id: &str) -> Option<Value> {
+ let mut c = self.conn.clone();
+ let raw: Option<String> = c
+ .get(request_key(id))
+ .await
+ .map_err(|e| eprintln!("assembler: redis request read failed: {e}"))
+ .ok()?;
+ serde_json::from_str(&raw?).ok()
+ }
+
+ /// Hold the create window for `id`, so two POSTs with one Idempotency-Key
+ /// cannot both spawn (the active check and the pending write are separate
+ /// round trips). False while another create holds it. A Redis that cannot
+ /// be asked does not block the create: its own writes fail just the same.
+ pub async fn claim_create(&self, id: &str) -> bool {
+ let mut c = self.conn.clone();
+ let claimed: redis::RedisResult<Option<String>> = redis::cmd("SET")
+ .arg(create_key(id))
+ .arg(1)
+ .arg("NX")
+ .arg("EX")
+ .arg(CREATE_CLAIM_TTL_SECS)
+ .query_async(&mut c)
+ .await;
+ match claimed {
+ Ok(reply) => reply.is_some(),
+ Err(e) => {
+ eprintln!("assembler: redis create claim failed: {e}");
+ true
+ }
+ }
+ }
+
+ pub async fn release_create(&self, id: &str) {
+ let mut c = self.conn.clone();
+ if let Err(e) = c.del::<_, ()>(create_key(id)).await {
+ eprintln!("assembler: redis create release failed: {e}");
+ }
+ }
+
+ /// Cancel an active job. Its downloads and uploads stop at once on this
+ /// replica, or within a heartbeat on another; a compute already running
+ /// finishes and its result is dropped.
pub async fn cancel(&self, id: &str) -> Option<Value> {
- let mut rec = self.read(id).await?;
- if is_active(&rec.status) {
- rec.status = "canceled".into();
- self.write(id, &rec).await;
- self.unpark(id).await;
+ if self
+ .transition(id, &[("status", "canceled".to_string())], &["upload_urls"])
+ .await
+ {
+ if let Some(token) = RUNNING.get(id) {
+ token.cancel();
+ }
+ self.ended(id).await;
// Wake the event-driven waiter immediately (terminal state).
- self.send_callback(id).await;
+ self.notify(id);
self.wake(id);
}
+ let rec = self.read(id).await?;
Some(Self::render(id, &rec))
}
@@ -360,35 +574,26 @@ impl JobStore {
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> {
+ /// Long-poll a job to a terminal state. 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, max: Option<Duration>) -> Option<Value> {
let deadline = max.map(|m| Instant::now() + m);
let mut watch = None;
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 mut rec = self.read(id).await?;
+ // Working, but no process holds its lease: whatever ran it died.
+ if matches!(rec.status.as_str(), "starting" | "running" | "uploading")
+ && !self.lease_alive(id).await
+ {
+ self.set_error(id, "WORKER_LOST", "the worker running this job stopped".into())
+ .await;
+ rec = self.read(id).await?;
+ }
+ if matches!(rec.status.as_str(), "done" | "error" | "canceled") {
+ return Some(Self::render(id, &rec));
}
let Some(dl) = deadline else {
return Some(Self::render(id, &rec)); // single shot
@@ -410,11 +615,10 @@ impl JobStore {
self.notifiers.wake(id);
}
- /// Complete a computed job. When the submit handed over an upload URL for
- /// every output, upload them straight from memory and publish the terminal
- /// pointer + completion callback — nothing is stored anywhere. Otherwise
- /// (no URLs at submit, or that upload failed) park the outputs and leave the
- /// job `uploading` for a late-mint poll to drain.
+ /// Complete a computed job: upload every output to its submit-time URL,
+ /// then publish the terminal pointer and deliver the callback. An upload
+ /// that fails after its retries fails the job with `UPLOAD_FAILED`; the
+ /// outputs are dropped, never kept for later.
pub async fn finish(
&self,
id: &str,
@@ -433,17 +637,21 @@ impl JobStore {
.await
.and_then(|r| r.upload_urls)
.unwrap_or_default();
- if has_every_url(&outputs, &urls) && upload_all(id, &outputs, &urls).await {
- self.publish(id, done, cache).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).
- self.send_callback(id).await;
- self.wake(id);
- return;
+ let uploaded = upload_all(id, &outputs, &urls, &UPLOAD_RETRY_DELAYS).await;
+ // Nothing reads the bytes past this point; don't hold them through
+ // the callback's retries.
+ drop(outputs);
+ match uploaded {
+ Ok(()) => {
+ self.publish(id, done, cache).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).
+ self.send_callback(id).await;
+ self.wake(id);
+ }
+ Err(message) => self.set_error(id, "UPLOAD_FAILED", message).await,
}
- self.park(id, &outputs, &done, &cache).await;
- self.wake(id);
}
/// POST the terminal job envelope to the submit-time callback URL, if any.
@@ -478,119 +686,6 @@ impl JobStore {
eprintln!("[{id}] completion callback undelivered; caller falls back to poll");
}
- // --- late-mint hand-off -------------------------------------------------
-
- /// Hold computed-but-unuploaded outputs until a poll brings URLs for them.
- /// A failure is logged only: the job then sits `uploading` with nothing to
- /// drain until the caller times out and resubmits, as with an expired TTL.
- async fn park(
- &self,
- id: &str,
- outputs: &[Output],
- done: &Done,
- cache: &Option<(String, u128, u64)>,
- ) {
- let manifest = json!({
- "outputs": outputs
- .iter()
- .map(|o| json!({ "name": o.name, "contentType": o.content_type }))
- .collect::<Vec<_>>(),
- "done": { "result": done.result, "stats": done.stats },
- "cache": cache.as_ref().map(|(m, ch, op)| format!("{m}|{ch:032x}|{op}")),
- })
- .to_string();
- let Some(dir) = self.park_path(id) else {
- let mut c = self.conn.clone();
- let mut pipe = redis::pipe();
- pipe.hset(pending_key(id), "manifest", manifest).ignore();
- for o in outputs {
- pipe.hset(pending_key(id), format!("b:{}", o.name), o.bytes.as_ref())
- .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 park failed: {e}");
- }
- return;
- };
- if let Err(e) = park_on_disk(&dir, &manifest, outputs).await {
- eprintln!("[{id}] could not park outputs in {}: {e}", dir.display());
- let _ = tokio::fs::remove_dir_all(&dir).await;
- }
- }
-
- /// The parked outputs of a job, if any are parked here.
- async fn parked(&self, id: &str) -> Option<Parked> {
- let Some(dir) = self.park_path(id) else {
- let mut c = self.conn.clone();
- let manifest: Option<String> = c
- .hget(pending_key(id), "manifest")
- .await
- .map_err(|e| eprintln!("assembler: redis parked read failed: {e}"))
- .ok()?;
- let manifest: Value = serde_json::from_str(&manifest?).ok()?;
- let mut outputs = Vec::new();
- for (name, content_type) in manifest_outputs(&manifest)? {
- let bytes: Option<Vec<u8>> =
- c.hget(pending_key(id), format!("b:{name}")).await.ok()?;
- outputs.push(Output {
- name,
- content_type,
- bytes: bytes?.into(),
- });
- }
- return Some((outputs, manifest_done(&manifest), manifest_cache(&manifest)));
- };
- parked_on_disk(&dir).await
- }
-
- async fn unpark(&self, id: &str) {
- let Some(dir) = self.park_path(id) else {
- let mut c = self.conn.clone();
- if let Err(e) = c.del::<_, ()>(pending_key(id)).await {
- eprintln!("assembler: redis unpark failed: {e}");
- }
- return;
- };
- let _ = tokio::fs::remove_dir_all(&dir).await;
- }
-
- /// The directory a job's outputs park in. Job ids are caller-chosen
- /// (`Idempotency-Key`), so the name is a hash of the id, never the id.
- fn park_path(&self, id: &str) -> Option<PathBuf> {
- let name = format!("{:032x}", xxhash_rust::xxh3::xxh3_128(id.as_bytes()));
- self.park_dir.as_ref().map(|dir| dir.join(name))
- }
-
- /// Delete parked outputs older than the pending TTL — the job they belong to
- /// was never drained and has been (or will be) resubmitted. Redis expires
- /// its own keys, so this is the disk half of that TTL.
- pub async fn sweep_parked(&self) {
- let Some(dir) = &self.park_dir else {
- return;
- };
- sweep_dir(dir, Duration::from_secs(config::pending_ttl_secs())).await;
- }
-
- /// Drain parked outputs to fresh signed URLs (from a long-poll). Every
- /// output must have a matching URL; on success publishes the terminal
- /// pointer, else keeps the outputs 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.parked(id).await else {
- return Finalize::NotPending;
- };
- if !has_every_url(&outputs, urls) {
- return Finalize::NotPending;
- }
- if !upload_all(id, &outputs, urls).await {
- return Finalize::Retry;
- }
- self.unpark(id).await;
- self.publish(id, done, cache).await;
- Finalize::Uploaded
- }
-
/// Every output is uploaded: record the result pointer and mark the job done.
async fn publish(&self, id: &str, done: Done, cache: Option<(String, u128, u64)>) {
if let Some((model, content, opts)) = cache {
@@ -636,8 +731,7 @@ impl JobStore {
/// 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 pattern = format!("asm:result:{}:*", escape_glob(model));
let mut scan = self.conn.clone();
let mut keys: Vec<String> = Vec::new();
match scan.scan_match::<_, String>(&pattern).await {
@@ -705,117 +799,80 @@ fn external_status(internal: &str) -> &'static str {
}
}
+/// `asm:job2`: the record became a hash (it was a JSON string under
+/// `asm:job`), and a new prefix keeps the two from meeting during a deploy.
fn job_key(id: &str) -> String {
- format!("asm:job:{id}")
+ format!("asm:job2:{id}")
}
-fn result_key(model: &str, content: u128, opts: u64) -> String {
- format!("asm:result:{model}:{content:032x}:{opts:016x}:v{CODE_VERSION}")
+fn lease_key(id: &str) -> String {
+ format!("asm:lease:{id}")
}
-fn pending_key(id: &str) -> String {
- format!("asm:pending:{id}")
-}
+/// How long a Lambda job's request is kept at most (it is deleted when the job
+/// ends): long enough for AWS's async retries to redeliver a crashed job.
+const REQUEST_TTL_SECS: u64 = 2 * 60 * 60;
-async fn park_on_disk(
- dir: &std::path::Path,
- manifest: &str,
- outputs: &[Output],
-) -> std::io::Result<()> {
- tokio::fs::create_dir_all(dir).await?;
- for (i, o) in outputs.iter().enumerate() {
- tokio::fs::write(dir.join(i.to_string()), &o.bytes).await?;
- }
- // The manifest is written last, under its final name by rename, so a reader
- // never sees a job whose output files are still being written.
- tokio::fs::write(dir.join("manifest.tmp"), manifest).await?;
- tokio::fs::rename(dir.join("manifest.tmp"), dir.join("manifest.json")).await
+/// How long a create may hold its window; released as soon as it is done.
+const CREATE_CLAIM_TTL_SECS: u64 = 30;
+
+fn create_key(id: &str) -> String {
+ format!("asm:create:{id}")
}
-async fn parked_on_disk(dir: &std::path::Path) -> Option<Parked> {
- let manifest = tokio::fs::read(dir.join("manifest.json")).await.ok()?;
- let manifest: Value = serde_json::from_slice(&manifest).ok()?;
- let mut outputs = Vec::new();
- for (i, (name, content_type)) in manifest_outputs(&manifest)?.into_iter().enumerate() {
- outputs.push(Output {
- name,
- content_type,
- bytes: http::map_file(&dir.join(i.to_string())).ok()?,
- });
- }
- Some((outputs, manifest_done(&manifest), manifest_cache(&manifest)))
+fn request_key(id: &str) -> String {
+ format!("asm:req:{id}")
}
-/// Remove every entry of `dir` last modified more than `ttl` ago.
-async fn sweep_dir(dir: &std::path::Path, ttl: Duration) {
- let Ok(mut entries) = tokio::fs::read_dir(dir).await else {
- return;
- };
- while let Ok(Some(entry)) = entries.next_entry().await {
- let age = entry
- .metadata()
- .await
- .and_then(|m| m.modified())
- .ok()
- .and_then(|modified| modified.elapsed().ok());
- if age.is_some_and(|age| age > ttl) {
- let _ = tokio::fs::remove_dir_all(entry.path()).await;
+/// Escape Redis glob metacharacters, so a caller's id matches only itself.
+fn escape_glob(s: &str) -> String {
+ let mut out = String::with_capacity(s.len());
+ for c in s.chars() {
+ if matches!(c, '*' | '?' | '[' | ']' | '\\') {
+ out.push('\\');
}
+ out.push(c);
}
+ out
}
-fn has_every_url(outputs: &[Output], urls: &HashMap<String, String>) -> bool {
- outputs.iter().all(|o| urls.contains_key(&o.name))
+fn result_key(model: &str, content: u128, opts: u64) -> String {
+ format!("asm:result:{model}:{content:032x}:{opts:016x}:v{CODE_VERSION}")
}
-/// PUT every output to its URL. False on the first failure (logged).
-async fn upload_all(id: &str, outputs: &[Output], urls: &HashMap<String, String>) -> bool {
+/// PUT every output to its URL, retrying each one after every wait in
+/// `delays`. An output with no URL, or one still failing after its retries,
+/// is the error (the message names the output).
+async fn upload_all(
+ id: &str,
+ outputs: &[Output],
+ urls: &HashMap<String, String>,
+ delays: &[Duration],
+) -> Result<(), String> {
for o in outputs {
- if let Err(e) = http::upload(&urls[&o.name], o.bytes.clone(), &o.content_type).await {
- eprintln!(
- "[{id}] output '{}' upload failed (a poll retries with fresh URLs): {}",
- o.name, e.message
- );
- return false;
+ let Some(url) = urls.get(&o.name) else {
+ return Err(format!("no upload URL for output '{}'", o.name));
+ };
+ let mut waits = delays.iter();
+ loop {
+ match http::upload(url, o.bytes.clone(), &o.content_type).await {
+ Ok(()) => break,
+ Err(e) => match waits.next() {
+ Some(wait) => {
+ eprintln!(
+ "[{id}] output '{}' upload failed, retrying in {wait:?}: {}",
+ o.name, e.message
+ );
+ tokio::time::sleep(*wait).await;
+ }
+ None => {
+ return Err(format!("output '{}' upload failed: {}", o.name, e.message))
+ }
+ },
+ }
}
}
- true
-}
-
-fn manifest_outputs(manifest: &Value) -> Option<Vec<(String, String)>> {
- manifest["outputs"]
- .as_array()?
- .iter()
- .map(|o| {
- Some((
- o["name"].as_str()?.to_string(),
- o["contentType"]
- .as_str()
- .unwrap_or("application/octet-stream")
- .to_string(),
- ))
- })
- .collect()
-}
-
-fn manifest_done(manifest: &Value) -> Done {
- Done {
- result: manifest["done"]["result"].clone(),
- stats: manifest["done"]["stats"].clone(),
- }
-}
-
-fn manifest_cache(manifest: &Value) -> Option<(String, u128, u64)> {
- manifest["cache"].as_str().map(str::to_string).and_then(parse_cache)
-}
-
-/// 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))
+ Ok(())
}
/// Stable hash of an options object. `serde_json` serializes object keys sorted,
@@ -827,14 +884,7 @@ pub fn opts_hash(options: &Value) -> u64 {
#[cfg(test)]
mod tests {
use super::*;
-
- fn output(name: &str, bytes: &'static [u8]) -> Output {
- Output {
- name: name.into(),
- content_type: "application/octet-stream".into(),
- bytes: Bytes::from_static(bytes),
- }
- }
+ use std::sync::atomic::{AtomicUsize, Ordering};
#[test]
fn a_wakeup_lives_only_while_a_poll_waits_on_it() {
@@ -849,35 +899,11 @@ mod tests {
assert!(notifiers.0.is_empty());
}
- #[tokio::test]
- async fn parked_outputs_come_back_from_disk_as_they_went_in() {
- let dir = tempfile::tempdir().unwrap();
- let job = dir.path().join("job");
- let manifest = json!({
- "outputs": [
- { "name": "glb", "contentType": "model/gltf-binary" },
- { "name": "graph", "contentType": "application/json" },
- { "name": "empty", "contentType": "text/plain" },
- ],
- "done": { "result": { "componentCount": 3 }, "stats": { "ms": 7 } },
- "cache": "model-1|000000000000000000000000000000ff|42",
- })
- .to_string();
- let outputs = [output("glb", b"glTF-bytes"), output("graph", b"{}"), output("empty", b"")];
-
- assert!(parked_on_disk(&job).await.is_none());
- park_on_disk(&job, &manifest, &outputs).await.unwrap();
-
- let (back, done, cache) = parked_on_disk(&job).await.unwrap();
- let names: Vec<_> = back.iter().map(|o| (o.name.as_str(), &o.bytes[..])).collect();
- assert_eq!(
- names,
- [("glb", &b"glTF-bytes"[..]), ("graph", &b"{}"[..]), ("empty", &b""[..])]
- );
- assert_eq!(back[0].content_type, "model/gltf-binary");
- assert_eq!(done.result["componentCount"], 3);
- assert_eq!(done.stats["ms"], 7);
- assert_eq!(cache, Some(("model-1".to_string(), 0xff, 42)));
+ #[test]
+ fn a_model_id_matches_only_itself_in_a_scan() {
+ assert_eq!(escape_glob("model-1"), "model-1");
+ assert_eq!(escape_glob("*"), "\\*");
+ assert_eq!(escape_glob("a?b[c]\\"), "a\\?b\\[c\\]\\\\");
}
#[test]
@@ -889,26 +915,183 @@ mod tests {
assert!(!is_active("canceled"));
}
+ /// A storage stand-in that answers 503 to the first `failures` PUTs and
+ /// 200 after, counting every attempt.
+ async fn flaky_storage(failures: usize) -> (String, Arc<AtomicUsize>) {
+ let attempts = Arc::new(AtomicUsize::new(0));
+ let seen = attempts.clone();
+ let app = axum::Router::new().route(
+ "/upload",
+ axum::routing::put(move || {
+ let seen = seen.clone();
+ async move {
+ if seen.fetch_add(1, Ordering::SeqCst) < failures {
+ axum::http::StatusCode::SERVICE_UNAVAILABLE
+ } else {
+ axum::http::StatusCode::OK
+ }
+ }
+ }),
+ );
+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
+ let addr = listener.local_addr().unwrap();
+ tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });
+ (format!("http://{addr}/upload"), attempts)
+ }
+
+ fn glb() -> Vec<Output> {
+ vec![Output {
+ name: "glb".into(),
+ content_type: "model/gltf-binary".into(),
+ bytes: Bytes::from_static(b"glTF"),
+ }]
+ }
+
+ const NO_WAIT: [Duration; 3] = [Duration::ZERO; 3];
+
+ /// A store on the Redis in `REDIS_URL` (the local stack's), or `None` to
+ /// skip: these pin behaviour that only Redis itself can show.
+ async fn redis_store() -> Option<JobStore> {
+ let url = std::env::var("REDIS_URL").ok().filter(|u| !u.is_empty())?;
+ let conn = connect(&url).await.ok()?;
+ Some(JobStore {
+ conn,
+ notifiers: Notifiers::default(),
+ })
+ }
+
+ fn unique(name: &str) -> String {
+ let nanos = std::time::SystemTime::now()
+ .duration_since(std::time::UNIX_EPOCH)
+ .unwrap()
+ .as_nanos();
+ format!("test-{name}-{nanos}")
+ }
+
+ #[tokio::test]
+ async fn one_create_window_per_job_id() {
+ let Some(store) = redis_store().await else { return };
+ let id = unique("claim");
+ assert!(store.claim_create(&id).await);
+ assert!(!store.claim_create(&id).await, "a second create waits it out");
+ store.release_create(&id).await;
+ assert!(store.claim_create(&id).await);
+ store.release_create(&id).await;
+ }
+
#[tokio::test]
- async fn a_job_without_its_manifest_is_not_parked() {
- // Output files land before the manifest; a reader in between sees nothing.
- let dir = tempfile::tempdir().unwrap();
- let job = dir.path().join("job");
- tokio::fs::create_dir_all(&job).await.unwrap();
- tokio::fs::write(job.join("0"), b"half-written").await.unwrap();
- assert!(parked_on_disk(&job).await.is_none());
+ async fn a_lambda_request_is_kept_until_its_job_ends() {
+ let Some(store) = redis_store().await else { return };
+ let id = unique("request");
+ let body = json!({ "source": { "url": "https://storage.test/m.step" } });
+ store.set_pending(&id, "thumbnail", HashMap::new(), None).await;
+ store.put_request(&id, &body).await.unwrap();
+ assert_eq!(store.read_request(&id).await, Some(body.clone()));
+ assert_eq!(store.read_request(&id).await, Some(body), "a redelivery reads it too");
+ store.set_error(&id, "thumbnail_failed", "x".into()).await;
+ assert_eq!(store.read_request(&id).await, None);
}
#[tokio::test]
- async fn the_sweep_removes_only_what_outlived_the_ttl() {
- let dir = tempfile::tempdir().unwrap();
- let manifest = json!({ "outputs": [], "done": {} }).to_string();
- park_on_disk(&dir.path().join("old"), &manifest, &[]).await.unwrap();
+ async fn one_worker_claims_a_job_and_a_crashed_one_releases_it() {
+ let Some(store) = redis_store().await else { return };
+ let id = unique("lease");
+ assert!(store.claim_lease(&id).await);
+ assert!(!store.claim_lease(&id).await, "a second delivery is a no-op");
+ let mut c = store.conn.clone();
+ let _: () = c.del(lease_key(&id)).await.unwrap(); // the lease ran out
+ assert!(store.claim_lease(&id).await, "a redelivery takes over");
+ }
- sweep_dir(dir.path(), Duration::from_secs(3600)).await;
- assert!(dir.path().join("old").exists());
+ #[tokio::test]
+ async fn a_job_whose_worker_died_ends_as_worker_lost() {
+ let Some(store) = redis_store().await else { return };
+ let id = unique("lost");
+ store.set_pending(&id, "thumbnail", HashMap::new(), None).await;
+ store.set_status(&id, "running").await;
+ let job = store.poll(&id, None).await.unwrap();
+ assert_eq!(job["job"]["status"], "running", "its lease is live");
+
+ let mut c = store.conn.clone();
+ let _: () = c.del(lease_key(&id)).await.unwrap(); // no renewal came
+ let job = store.poll(&id, None).await.unwrap();
+ assert_eq!(job["job"]["status"], "failed");
+ assert_eq!(job["job"]["error"]["code"], "WORKER_LOST");
+ }
- sweep_dir(dir.path(), Duration::ZERO).await;
- assert!(!dir.path().join("old").exists());
+ #[tokio::test]
+ async fn a_finish_never_overwrites_a_cancel() {
+ let Some(store) = redis_store().await else { return };
+ let id = unique("cancel");
+ store.set_pending(&id, "thumbnail", HashMap::new(), None).await;
+ store.set_status(&id, "running").await;
+ store.cancel(&id).await;
+ store.set_done(&id, Done { result: json!({}), stats: json!({}) }).await;
+ store.set_error(&id, "thumbnail_failed", "late".into()).await;
+ store.set_status(&id, "uploading").await;
+ let job = store.poll(&id, None).await.unwrap();
+ assert_eq!(job["job"]["status"], "canceled");
+ }
+
+ #[tokio::test]
+ async fn a_cancel_fires_the_running_jobs_token() {
+ let Some(store) = redis_store().await else { return };
+ let id = unique("token");
+ store.set_pending(&id, "thumbnail", HashMap::new(), None).await;
+ let (fired_tx, fired_rx) = tokio::sync::oneshot::channel();
+ let job = track(&id, async move {
+ current_cancel().unwrap().cancelled().await;
+ let _ = fired_tx.send(());
+ });
+ let running = tokio::spawn(job);
+ tokio::task::yield_now().await;
+ store.cancel(&id).await;
+ tokio::time::timeout(Duration::from_secs(1), fired_rx).await.unwrap().unwrap();
+ running.await.unwrap();
+ assert!(!RUNNING.contains_key(&id), "an ended job is untracked");
+ }
+
+ #[tokio::test]
+ async fn a_failed_upload_fails_the_job_and_parks_nothing() {
+ let Some(store) = redis_store().await else { return };
+ let (url, _) = flaky_storage(usize::MAX).await;
+ let id = unique("upload");
+ store
+ .set_pending(&id, "thumbnail", HashMap::from([("glb".to_string(), url)]), None)
+ .await;
+ let done = Done { result: json!({}), stats: json!({}) };
+ store.finish(&id, glb(), done, None).await;
+
+ let job = store.poll(&id, None).await.unwrap();
+ assert_eq!(job["job"]["status"], "failed");
+ assert_eq!(job["job"]["error"]["code"], "UPLOAD_FAILED");
+ let mut c = store.conn.clone();
+ let parked: Vec<String> = c.keys(format!("asm:pending:{id}*")).await.unwrap();
+ assert!(parked.is_empty());
+ let rec = store.read(&id).await.unwrap();
+ assert!(rec.upload_urls.is_none(), "an ended job keeps no signed URLs");
+ }
+
+ #[tokio::test]
+ async fn an_upload_that_fails_twice_then_lands_succeeds() {
+ let (url, attempts) = flaky_storage(2).await;
+ let urls = HashMap::from([("glb".to_string(), url)]);
+ assert_eq!(upload_all("job", &glb(), &urls, &NO_WAIT).await, Ok(()));
+ assert_eq!(attempts.load(Ordering::SeqCst), 3);
+ }
+
+ #[tokio::test]
+ async fn an_upload_still_failing_after_its_retries_is_an_error() {
+ let (url, attempts) = flaky_storage(usize::MAX).await;
+ let urls = HashMap::from([("glb".to_string(), url)]);
+ let err = upload_all("job", &glb(), &urls, &NO_WAIT).await.unwrap_err();
+ assert!(err.starts_with("output 'glb' upload failed"), "{err}");
+ assert_eq!(attempts.load(Ordering::SeqCst), 4, "one try plus three retries");
+ }
+
+ #[tokio::test]
+ async fn an_output_without_a_url_is_an_error_not_a_wait() {
+ let err = upload_all("job", &glb(), &HashMap::new(), &NO_WAIT).await.unwrap_err();
+ assert_eq!(err, "no upload URL for output 'glb'");
}
}
diff --git a/apps/assembler/src/main.rs b/apps/assembler/src/main.rs
index 74b77c8b4d..ded3719b71 100644
--- a/apps/assembler/src/main.rs
+++ b/apps/assembler/src/main.rs
@@ -7,7 +7,6 @@
//!
//! POST /v1/convert | /v1/optimize | /v1/plan | /v1/compact | /v1/thumbnail
//! → 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 }
@@ -16,12 +15,12 @@
//!
//! 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::*`.
+//! callback URL; the poll endpoint remains for status. Wires the `converter` and `planner` crates via `actions::*`.
mod actions;
mod admission;
mod cache;
+mod compute;
mod config;
mod dispatch;
mod error;
@@ -29,7 +28,8 @@ mod formats;
mod http;
mod jobs;
mod progress;
-mod run;
+mod request;
+mod source;
mod telemetry;
use axum::{
@@ -43,13 +43,12 @@ use serde_json::{json, Value};
use std::collections::HashMap;
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::Arc;
+use std::time::{Duration, Instant};
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
+/// How long the Lambda worker waits for its job: Lambda's own hard timeout.
+const WORKER_MAX_WAIT: Duration = Duration::from_secs(900);
// jemalloc on the Linux deploy target: the planner's blocking tasks allocate
// heavily from many threads (rayon sweeps + tokio workers); glibc malloc is the
@@ -72,6 +71,7 @@ pub struct AppState {
pub jobs: jobs::JobStore,
pub cache: Arc<cache::ResultCache>,
pub progress: progress::ProgressStore,
+ pub sources: source::Sources,
}
fn main() {
@@ -80,18 +80,11 @@ fn main() {
.max_blocking_threads(config::blocking_threads())
.build()
.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());
- }
+ rt.block_on(serve());
}
-/// 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 {
+/// Build the shared service state: one JobStore + cache + concurrency.
+async fn build_state() -> AppState {
AppState {
admission: admission::Admission::from_env(),
jobs: jobs::JobStore::from_env().await,
@@ -100,6 +93,7 @@ pub async fn build_state() -> AppState {
config::cache_bytes(),
)),
progress: progress::ProgressStore::default(),
+ sources: source::Sources::new(config::source_slots()),
}
}
@@ -108,31 +102,27 @@ async fn serve() {
http::clear_stale_sources();
let state = build_state().await;
let admission = state.admission.clone();
- // Parked outputs nobody drained (see `jobs.rs`): the disk half of the
- // pending TTL, including whatever a previous process left behind.
- let sweeper = state.jobs.clone();
- tokio::spawn(async move {
- loop {
- sweeper.sweep_parked().await;
- tokio::time::sleep(std::time::Duration::from_secs(60)).await;
- }
- });
+ // Renews the lease of every job this process runs, and relays cancels.
+ let heartbeat = state.jobs.clone();
+ tokio::spawn(async move { heartbeat.heartbeat().await });
let app = Router::new()
.route("/health", get(health))
.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/thumbnail", post(create_thumbnail))
+ .route("/v1/:action", post(create_job))
.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))
+ .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). Mounted only on
+ // Lambda, where it is reachable only by an IAM-signed Invoke — API Gateway
+ // routes /health and /v1/* alone. A spec names a job and nothing else, so
+ // a delivery can only start a pending job with the body its create stored.
+ let app = if dispatch::from_env() == dispatch::Dispatch::Lambda {
+ app.route("/events", post(worker_events))
+ } else {
+ app
+ };
+ let app = app
// 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
@@ -230,14 +220,14 @@ async fn discovery(headers: HeaderMap) -> Result<Json<Value>, ApiError> {
.collect();
Ok(Json(json!({
"version": VERSION,
- "actions": ["convert", "optimize", "plan", "compact", "thumbnail"],
+ "actions": request::ACTIONS,
"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_output_bytes": request::DEFAULT_MAX_OUTPUT_BYTES,
+ "max_render_weight_bytes": request::DEFAULT_MAX_RENDER_WEIGHT_BYTES,
"max_long_poll_secs": config::max_long_poll_secs(),
},
})))
@@ -346,65 +336,65 @@ fn parse_body(
.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,
+/// Create a job for any action (`POST /v1/{action}`). The body is parsed and
+/// validated before anything is recorded, so a bad request leaves no job.
+/// A re-POST with the same `Idempotency-Key` attaches to the active job.
+async fn create_job(
+ State(state): State<AppState>,
+ Path(action): Path<String>,
+ headers: HeaderMap,
+ body: Result<Json<Value>, axum::extract::rejection::JsonRejection>,
) -> Result<(StatusCode, HeaderMap, Json<Value>), ApiError> {
- if !sync {
- return Ok(created(job_id, action, "queued"));
+ require_auth(&headers)?;
+ let req = parse_body(body)?;
+ let parsed = request::parse(&action, &req)?;
+ let job_id = resolve_job_id(&headers);
+ let (upload_urls, callback_url) = submit_plumbing(&headers, &req)?;
+
+ // Another create with this key is in its window: it will start the job.
+ if !state.jobs.claim_create(&job_id).await {
+ 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)))
+ let started = async {
+ if let Some(status) = state.jobs.existing_active(&job_id).await {
+ return Ok(status);
+ }
+ state
+ .jobs
+ .set_pending(&job_id, &action, upload_urls, callback_url)
+ .await;
+ if dispatch::from_env() == dispatch::Dispatch::Lambda {
+ lambda_dispatch(&state, &job_id, &action, &req).await?;
+ } else {
+ eprintln!("[{job_id}] {action} queued");
+ request::spawn(&state, &job_id, parsed);
+ }
+ Ok::<_, ApiError>("queued".to_string())
+ }
+ .await;
+ state.jobs.release_create(&job_id).await;
+ Ok(created(&job_id, &action, &started?))
}
/// 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).
+/// freezes after the response), fire the job as an Event-type self-invocation.
+/// The request body waits in Redis for the worker; the spec carries only
+/// `action`, `job_id` and the trace, so no signed URL, caller token or service
+/// key rides in the Invoke payload. 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();
- }
- }
+ let mut spec = json!({ "action": action, "job_id": job_id });
telemetry::inject(&mut spec);
- if let Err(m) = dispatch::self_invoke(&spec).await {
+ let dispatched = match state.jobs.put_request(job_id, req).await {
+ Ok(()) => dispatch::self_invoke(&spec).await,
+ Err(m) => Err(m),
+ };
+ if let Err(m) = dispatched {
state
.jobs
.set_error(job_id, "dispatch_failed", m.clone())
@@ -418,47 +408,50 @@ async fn lambda_dispatch(
/// 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.
+/// instance's poll can answer. A delivery runs the job when it can claim the
+/// job's lease: a pending job, or one whose worker stopped renewing it (a
+/// crashed or timed-out invocation Lambda redelivers). Otherwise it is a no-op.
async fn worker_events(
State(state): State<AppState>,
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.internal_active(&job_id).await.as_deref() {
- Some("pending") => {
- // Take the job before the long download and admission wait, so a
- // second delivery in that window sees it as taken.
+ match state.jobs.internal_active(&job_id).await {
+ Some(status) => {
+ // The lease is the claim: of two deliveries one wins, and while a
+ // live worker renews it every other delivery is a no-op.
+ if !state.jobs.claim_lease(&job_id).await {
+ eprintln!("[{job_id}] worker no-op (another worker holds it)");
+ return Ok(Json(json!({ "ok": true, "noop": true })));
+ }
+ let Some(req) = state.jobs.read_request(&job_id).await else {
+ let message = "the request expired before a worker took it".to_string();
+ state.jobs.set_error(&job_id, "dispatch_failed", message.clone()).await;
+ return Err(ApiError::new(410, "dispatch_failed", message));
+ };
+ if status != "pending" {
+ eprintln!("[{job_id}] worker taking over a job left {status}");
+ }
+ // Mark it taken before the long download and admission wait.
state.jobs.set_status(&job_id, "starting").await;
- 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));
+ if let Err(e) = spawn_traced(&state, &job_id, &action, &spec, &req) {
+ state.jobs.set_error(&job_id, "invalid_input", e.message.clone()).await;
+ return Err(e);
}
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:?})");
+ None => {
+ eprintln!("[{job_id}] worker no-op (job ended or unknown)");
return Ok(Json(json!({ "ok": true, "noop": true })));
}
}
- let result = run::run_to_completion(&state, &job_id, &urls).await;
+ let result = run_to_completion(&state, &job_id).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
@@ -471,389 +464,35 @@ async fn worker_events(
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 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, "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 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),
- // Matches the optimize default: 0.15 rad ≈ 42 segments per
- // circle (0.25 gave 25, 0.5 a blocky 13). Angular deflection
- // is the ONLY scale-invariant constraint, so this is what a
- // small hole/groove's roundness actually comes from — sag
- // never binds on a small radius. Also part of the convert
- // result-cache key, so older coarse results aren't reused.
- ang: req["options"]["angularDeflection"].as_f64().unwrap_or(0.15),
- optimize: req["options"]["optimize"].as_bool().unwrap_or(true),
- },
- );
- }
- }
- respond(&state, &headers, &job_id, "convert", sync).await
-}
-
-async fn create_optimize(
- 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()
- .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})");
- let (compact, thumbnail) = optimize_ingest(&req);
- 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,
- compact,
- thumbnail,
- },
- );
- }
- }
- respond(&state, &headers, &job_id, "optimize", sync).await
-}
-
-/// 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),
- // Size-adaptive quality applies only when the caller pinned no explicit
- // quality knob (the eager-optimise job's case). Any explicit ladder /
- // simplify / tolerance / auto_error is a full override and disables it.
- auto_scale: q["ladder"].is_null()
- && q["simplify"].is_null()
- && q["tolerance_mm"].is_null()
- && q["auto_error"].is_null(),
- 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),
- // 0.15 rad → ≈ 42 segments per circle (0.25 gave 25, 0.5 a blocky 13).
- // Angular deflection is the only SCALE-INVARIANT constraint: a small
- // hole's sag budget is satisfied after a handful of chords, so segment
- // count on holes/grooves/fillets comes from this value alone. The bridge
- // also scales linear deflection to each shape, which covers the large
- // curved faces where sag does bind.
- ang: q["angular_deflection"].as_f64().unwrap_or(0.15),
- // 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,
- }
-}
-
-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 create_plan(
- 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()
- .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, "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()
- .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
-}
-
-async fn create_thumbnail(
- 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()
- .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, "thumbnail", &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, "thumbnail", optional_meta(&req), submit_urls.clone(), callback_url.clone())
- .await;
- lambda_dispatch(&state, &headers, &job_id, "thumbnail", &req).await?;
- }
- None => {
- let meta = optional_meta(&req);
- state.jobs.set_pending(&job_id, "thumbnail", meta, submit_urls.clone(), callback_url.clone()).await;
- eprintln!("[{job_id}] thumbnail queued");
- actions::thumbnail::spawn(&state, &job_id, thumbnail_req(source_url, &req["output"]));
- }
- }
- respond(&state, &headers, &job_id, "thumbnail", sync).await
-}
-
-/// The ingest outputs an optimize may also write: `compact: { path? }` (the
-/// retained raw's compact form, output `raw`) and `thumbnail: { path?, size?,
-/// direction? }` (output `thumbnail`). Shared by the HTTP body and the run-job
-/// spec.
-pub fn optimize_ingest(
+/// Parse and spawn the worker's job under the submitting request's trace, when
+/// the spec carries it. Sync: the trace guard cannot be held across an await.
+fn spawn_traced(
+ state: &AppState,
+ job_id: &str,
+ action: &str,
+ spec: &Value,
req: &Value,
-) -> (Option<Option<String>>, Option<actions::optimize::ThumbnailOut>) {
- let compact = req["compact"]
- .is_object()
- .then(|| req["compact"]["path"].as_str().map(str::to_string));
- let thumbnail = req["thumbnail"].is_object().then(|| {
- let t = thumbnail_req("", &req["thumbnail"]);
- actions::optimize::ThumbnailOut {
- path: t.path,
- size: t.size,
- direction: t.direction,
- }
- });
- (compact, thumbnail)
-}
-
-/// `output: { path?, size?, direction? }` — shared by the HTTP body and the
-/// run-job spec. `direction` is `[x, y, z]`, model towards camera.
-pub fn thumbnail_req(source_url: &str, output: &Value) -> actions::thumbnail::ThumbnailReq {
- actions::thumbnail::ThumbnailReq {
- source_url: source_url.to_string(),
- size: output["size"]
- .as_u64()
- .map_or(thumbnail::DEFAULT_SIZE, |s| s.min(u32::MAX as u64) as u32),
- path: output["path"].as_str().map(str::to_string),
- direction: view_direction(&output["direction"]),
- }
+) -> Result<(), ApiError> {
+ let _trace = telemetry::attach(spec);
+ request::spawn(state, job_id, request::parse(action, req)?);
+ Ok(())
}
-/// Three finite numbers that are not all zero, else the viewer's home direction.
-fn view_direction(value: &Value) -> [f32; 3] {
- let parsed: Option<Vec<f32>> = value
- .as_array()
- .filter(|a| a.len() == 3)
- .and_then(|a| a.iter().map(|n| n.as_f64().map(|n| n as f32)).collect());
- match parsed.as_deref() {
- Some(&[x, y, z]) if [x, y, z].iter().all(|c| c.is_finite()) && (x, y, z) != (0.0, 0.0, 0.0) => {
- [x, y, z]
+/// Wait for a spawned job to reach a terminal state, or the worker's ceiling.
+async fn run_to_completion(state: &AppState, job_id: &str) -> Value {
+ let deadline = Instant::now() + WORKER_MAX_WAIT;
+ loop {
+ match state.jobs.poll(job_id, Some(Duration::from_secs(30))).await {
+ None => {
+ return json!({ "ok": false,
+ "error": { "code": "not_found", "message": "job vanished" } })
+ }
+ Some(v) => match v["job"]["status"].as_str() {
+ Some("succeeded" | "failed" | "canceled") => return v,
+ _ if Instant::now() >= deadline => return v,
+ _ => continue,
+ },
}
- _ => thumbnail::DEFAULT_DIRECTION,
- }
-}
-
-fn optional_meta(req: &Value) -> Option<Value> {
- match &req["meta"] {
- Value::Null => None,
- m => Some(m.clone()),
}
}
@@ -870,20 +509,13 @@ async fn get_job(
Query(q): Query<WaitQuery>,
) -> Result<Json<Value>, ApiError> {
require_auth(&headers)?;
- // 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()),
- )),
+ Some(secs) if secs > 0 => Some(Duration::from_secs(secs.min(config::max_long_poll_secs()))),
_ => None,
};
let mut v = state
.jobs
- .poll(&job_id, &upload_urls, max)
+ .poll(&job_id, 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
@@ -897,9 +529,8 @@ async fn get_job(
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": …}`).
+/// Parse the submit-time signed upload URLs: the `X-Carbon-Upload-Urls` JSON
+/// header `{"glb":"…","graph":"…"}`.
fn parse_upload_urls(headers: &HeaderMap) -> Result<HashMap<String, String>, ApiError> {
let mut out = HashMap::new();
if let Some(raw) = headers
@@ -914,14 +545,6 @@ fn parse_upload_urls(headers: &HeaderMap) -> Result<HashMap<String, String>, Api
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)
}
diff --git a/apps/assembler/src/progress.rs b/apps/assembler/src/progress.rs
index 24307cfffc..23fd8d995a 100644
--- a/apps/assembler/src/progress.rs
+++ b/apps/assembler/src/progress.rs
@@ -2,10 +2,9 @@
// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,
// including ports, remain AGPLv3; serving them over a network requires releasing their source.
-//! Live per-job convert progress, served by `GET /convert/status/{jobId}` so
-//! the app can render a real phase checklist instead of a bare spinner.
-//! Entries exist only while a convert is in flight; unknown id => 404 and the
-//! caller falls back to its coarse DB status.
+//! Live per-job convert progress, merged into `GET /v1/jobs/{id}` while the job
+//! runs on the replica answering the poll. Entries exist only while a convert
+//! is in flight.
use dashmap::DashMap;
use std::sync::atomic::{AtomicU64, AtomicU8, Ordering};
diff --git a/apps/assembler/src/request.rs b/apps/assembler/src/request.rs
new file mode 100644
index 0000000000..1e82065165
--- /dev/null
+++ b/apps/assembler/src/request.rs
@@ -0,0 +1,289 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,
+// including ports, remain AGPLv3; serving them over a network requires releasing their source.
+
+//! Every action's request, parsed in ONE place. The create handler parses the
+//! HTTP body here and the Lambda worker parses the same body here again, so a
+//! default cannot differ between the standing service and Lambda. (They did:
+//! convert tessellated at 0.15 rad on one and 0.5 on the other, so the same
+//! model got different nodeIds depending on where it ran.)
+
+use crate::{actions, config, error::ApiError, AppState};
+use serde_json::Value;
+
+/// Default optimise output ceiling (encoded bytes) — the served-bucket safety net.
+pub const DEFAULT_MAX_OUTPUT_BYTES: u64 = 52_428_800; // 50 MiB
+/// Default decoded (render-weight) ceiling — guards viewer hangs on huge meshes.
+pub const DEFAULT_MAX_RENDER_WEIGHT_BYTES: u64 = 419_430_400; // 400 MiB
+
+/// The actions a job can run.
+pub const ACTIONS: [&str; 6] = ["convert", "optimize", "plan", "compact", "thumbnail", "fetch"];
+
+/// A parsed request, ready to spawn.
+pub enum ActionReq {
+ Convert(actions::convert::ConvertReq),
+ Optimize(actions::optimize::OptimizeReq),
+ Plan(actions::plan::PlanReq),
+ Compact(actions::compact::CompactReq),
+ Thumbnail(actions::thumbnail::ThumbnailReq),
+ Fetch(actions::fetch::FetchReq),
+}
+
+/// Parse and validate a create body for `action`. Errors are 400s (an
+/// unknown action is a 404), raised before any job is recorded.
+pub fn parse(action: &str, req: &Value) -> Result<ActionReq, ApiError> {
+ if !ACTIONS.contains(&action) {
+ return Err(ApiError::new(404, "not_found", format!("no action {action}")));
+ }
+ let source_url = req["source"]["url"]
+ .as_str()
+ .filter(|s| !s.is_empty())
+ .ok_or_else(|| ApiError::invalid("missing source.url"))?;
+ config::validate_url(source_url)?;
+ let source_url = source_url.to_string();
+ let path = |v: &Value| v.as_str().map(str::to_string);
+
+ Ok(match action {
+ "convert" => ActionReq::Convert(actions::convert::ConvertReq {
+ source_url,
+ declared_hash: req["source"]["contentHash"]
+ .as_str()
+ .map(str::trim)
+ .filter(|s| !s.is_empty() && s.len() <= 128)
+ .map(str::to_string),
+ glb_path: path(&req["outputs"]["glb"]["path"]),
+ graph_path: path(&req["outputs"]["graph"]["path"]),
+ lin: req["options"]["linearDeflection"]
+ .as_f64()
+ .unwrap_or(config::TESSELLATION_LINEAR),
+ ang: req["options"]["angularDeflection"]
+ .as_f64()
+ .unwrap_or(config::TESSELLATION_ANGULAR),
+ optimize: req["options"]["optimize"].as_bool().unwrap_or(true),
+ }),
+ "optimize" => {
+ let (compact, thumbnail) = optimize_ingest(req);
+ ActionReq::Optimize(actions::optimize::OptimizeReq {
+ source_url,
+ // `auto` content-detects the format in the action.
+ format: req["source"]["format"].as_str().unwrap_or("auto").to_string(),
+ glb_path: path(&req["output"]["path"]),
+ opts: optimize_opts(&req["output"], &req["quality"]),
+ compact,
+ thumbnail,
+ })
+ }
+ "plan" => ActionReq::Plan(actions::plan::PlanReq {
+ source_url,
+ plan_path: path(&req["meta"]["planPath"])
+ .filter(|p| !p.is_empty())
+ .ok_or_else(|| ApiError::invalid("missing meta.planPath"))?,
+ model_upload_id: path(&req["meta"]["modelUploadId"]),
+ options: req["options"].clone(),
+ }),
+ "compact" => ActionReq::Compact(actions::compact::CompactReq {
+ source_url,
+ mode: actions::compact::Mode::from_str(req["mode"].as_str().unwrap_or("xbf"))
+ .ok_or_else(|| ApiError::invalid("mode must be 'xbf' or 'zstd'"))?,
+ raw_path: path(&req["output"]["path"]),
+ }),
+ "fetch" => ActionReq::Fetch(actions::fetch::FetchReq {
+ source_url,
+ authorization: req["source"]["authorization"]
+ .as_str()
+ .filter(|s| !s.is_empty())
+ .map(str::to_string),
+ max_bytes: req["maxBytes"].as_u64().filter(|&b| b > 0),
+ content_type: req["output"]["contentType"]
+ .as_str()
+ .unwrap_or("application/octet-stream")
+ .to_string(),
+ path: path(&req["output"]["path"]),
+ }),
+ _ => ActionReq::Thumbnail(thumbnail_req(&source_url, &req["output"])),
+ })
+}
+
+/// Start a parsed request as job `job_id` (already `set_pending`).
+pub fn spawn(state: &AppState, job_id: &str, req: ActionReq) {
+ match req {
+ ActionReq::Convert(r) => actions::convert::spawn(state, job_id, r),
+ ActionReq::Optimize(r) => actions::optimize::spawn(state, job_id, r),
+ ActionReq::Plan(r) => actions::plan::spawn(state, job_id, r),
+ ActionReq::Compact(r) => actions::compact::spawn(state, job_id, r),
+ ActionReq::Thumbnail(r) => actions::thumbnail::spawn(state, job_id, r),
+ ActionReq::Fetch(r) => actions::fetch::spawn(state, job_id, r),
+ }
+}
+
+/// Build the optimise `Opts` from the request's `output` + `quality` objects
+/// (snake_case).
+pub(crate) 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),
+ // Size-adaptive quality applies only when the caller pinned no explicit
+ // quality knob (the eager-optimise job's case). Any explicit ladder /
+ // simplify / tolerance / auto_error is a full override and disables it.
+ auto_scale: q["ladder"].is_null()
+ && q["simplify"].is_null()
+ && q["tolerance_mm"].is_null()
+ && q["auto_error"].is_null(),
+ 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),
+ // The preview GLB only — no nodeId comes from it, so it is free to
+ // tessellate finer than `config::TESSELLATION_ANGULAR`. 0.15 rad ≈ 42
+ // segments per circle (0.25 gave 25, 0.5 a blocky 13). Angular
+ // deflection is the only SCALE-INVARIANT constraint: a small hole's sag
+ // budget is satisfied after a handful of chords, so segment count on
+ // holes/grooves/fillets comes from this value alone. The bridge also
+ // scales linear deflection to each shape, which covers the large curved
+ // faces where sag does bind.
+ ang: q["angular_deflection"].as_f64().unwrap_or(0.15),
+ // 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,
+ }
+}
+
+/// 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).
+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)],
+ }
+}
+
+/// The ingest outputs an optimize may also write: `compact: { path? }` (the
+/// retained raw's compact form, output `raw`) and `thumbnail: { path?, size?,
+/// direction? }` (output `thumbnail`).
+fn optimize_ingest(
+ req: &Value,
+) -> (Option<Option<String>>, Option<actions::optimize::ThumbnailOut>) {
+ let compact = req["compact"]
+ .is_object()
+ .then(|| req["compact"]["path"].as_str().map(str::to_string));
+ let thumbnail = req["thumbnail"].is_object().then(|| {
+ let t = thumbnail_req("", &req["thumbnail"]);
+ actions::optimize::ThumbnailOut {
+ path: t.path,
+ size: t.size,
+ direction: t.direction,
+ }
+ });
+ (compact, thumbnail)
+}
+
+/// `output: { path?, size?, direction? }`. `direction` is `[x, y, z]`, model
+/// towards camera.
+fn thumbnail_req(source_url: &str, output: &Value) -> actions::thumbnail::ThumbnailReq {
+ actions::thumbnail::ThumbnailReq {
+ source_url: source_url.to_string(),
+ size: output["size"]
+ .as_u64()
+ .map_or(thumbnail::DEFAULT_SIZE, |s| s.min(u32::MAX as u64) as u32),
+ path: output["path"].as_str().map(str::to_string),
+ direction: view_direction(&output["direction"]),
+ }
+}
+
+/// Three finite numbers that are not all zero, else the viewer's home direction.
+fn view_direction(value: &Value) -> [f32; 3] {
+ let parsed: Option<Vec<f32>> = value
+ .as_array()
+ .filter(|a| a.len() == 3)
+ .and_then(|a| a.iter().map(|n| n.as_f64().map(|n| n as f32)).collect());
+ match parsed.as_deref() {
+ Some(&[x, y, z])
+ if [x, y, z].iter().all(|c| c.is_finite()) && (x, y, z) != (0.0, 0.0, 0.0) =>
+ {
+ [x, y, z]
+ }
+ _ => thumbnail::DEFAULT_DIRECTION,
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use serde_json::json;
+
+ #[test]
+ fn convert_and_plan_tessellate_alike_by_default() {
+ let body = json!({ "source": { "url": "https://storage.test/model.step" } });
+ let ActionReq::Convert(convert) = parse("convert", &body).unwrap() else {
+ panic!("not a convert");
+ };
+ assert_eq!(convert.ang, config::TESSELLATION_ANGULAR);
+ assert_eq!(convert.lin, config::TESSELLATION_LINEAR);
+ }
+
+ #[test]
+ fn a_plan_without_a_plan_path_is_refused() {
+ let body = json!({ "source": { "url": "https://storage.test/model.step" } });
+ let err = parse("plan", &body).err().unwrap();
+ assert_eq!(err.message, "missing meta.planPath");
+ }
+
+ #[test]
+ fn a_bad_compact_mode_is_refused_before_a_job_exists() {
+ let body = json!({ "source": { "url": "https://storage.test/m.step" }, "mode": "gzip" });
+ assert!(parse("compact", &body).is_err());
+ }
+
+ #[test]
+ fn an_unknown_action_is_not_found() {
+ let body = json!({ "source": { "url": "https://storage.test/m.step" } });
+ assert_eq!(parse("render", &body).err().unwrap().status, 404);
+ }
+
+ #[test]
+ fn a_declared_hash_is_trimmed_and_bounded() {
+ let body = json!({
+ "source": { "url": "https://storage.test/m.step", "contentHash": " abc " }
+ });
+ let ActionReq::Convert(convert) = parse("convert", &body).unwrap() else {
+ panic!("not a convert");
+ };
+ assert_eq!(convert.declared_hash.as_deref(), Some("abc"));
+ }
+}
diff --git a/apps/assembler/src/run.rs b/apps/assembler/src/run.rs
deleted file mode 100644
index bc42968d78..0000000000
--- a/apps/assembler/src/run.rs
+++ /dev/null
@@ -1,220 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-only
-// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,
-// including ports, remain AGPLv3; serving them over a network requires releasing their source.
-
-//! 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"|"compact"|"thumbnail",
-//! "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_ingest, optimize_opts, telemetry, thumbnail_req, 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() -> ! {
- telemetry::init();
- 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}");
- telemetry::shutdown();
- 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> {
- // The submitting request's trace, when the spec carries it.
- let _trace = telemetry::attach(spec);
- let source_url = spec["source"]["url"]
- .as_str()
- .unwrap_or_default()
- .to_string();
- match action {
- "optimize" => {
- let (compact, thumbnail) = optimize_ingest(spec);
- 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"]),
- compact,
- thumbnail,
- },
- )
- }
- "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),
- },
- )
- }
- "thumbnail" => {
- actions::thumbnail::spawn(state, job_id, thumbnail_req(&source_url, &spec["output"]))
- }
- 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 } })
- );
- telemetry::shutdown();
- std::process::exit(1);
-}
diff --git a/apps/assembler/src/source.rs b/apps/assembler/src/source.rs
new file mode 100644
index 0000000000..10884e9364
--- /dev/null
+++ b/apps/assembler/src/source.rs
@@ -0,0 +1,123 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,
+// including ports, remain AGPLv3; serving them over a network requires releasing their source.
+
+//! Downloaded sources, bounded. Every job downloads its source before it waits
+//! for memory, so without a bound a queue of N jobs held N sources on disk at
+//! once. A job now takes a slot before it downloads and holds it until its
+//! `Source` drops, which also deletes the file — on every path, a panic
+//! included.
+
+use crate::{error::ApiError, http, progress::JobProgress};
+use std::path::{Path, PathBuf};
+use std::sync::Arc;
+use tokio::sync::{OwnedSemaphorePermit, Semaphore};
+
+/// The slots: how many downloaded sources may exist at once.
+#[derive(Clone)]
+pub struct Sources {
+ slots: Arc<Semaphore>,
+}
+
+/// One downloaded source on disk. Dropping it deletes the file and frees the
+/// slot.
+pub struct Source {
+ path: PathBuf,
+ /// xxh3-128 of the (decompressed) bytes.
+ pub hash: u128,
+ _slot: OwnedSemaphorePermit,
+}
+
+impl Sources {
+ pub fn new(slots: usize) -> Self {
+ Sources {
+ slots: Arc::new(Semaphore::new(slots.max(1))),
+ }
+ }
+
+ /// Wait for a slot, then download `url` to a temp file named `*.{ext}`.
+ pub async fn download(
+ &self,
+ url: &str,
+ ext: &str,
+ progress: Option<&JobProgress>,
+ ) -> Result<Source, ApiError> {
+ self.download_with(url, ext, progress, &http::DownloadOpts::default())
+ .await
+ }
+
+ pub async fn download_with(
+ &self,
+ url: &str,
+ ext: &str,
+ progress: Option<&JobProgress>,
+ opts: &http::DownloadOpts<'_>,
+ ) -> Result<Source, ApiError> {
+ let slot = Arc::clone(&self.slots)
+ .acquire_owned()
+ .await
+ .expect("source semaphore is never closed");
+ let path = http::temp_path(ext);
+ match http::download_with(url, &path, progress, opts).await {
+ Ok(hash) => Ok(Source {
+ path,
+ hash,
+ _slot: slot,
+ }),
+ Err(e) => {
+ let _ = std::fs::remove_file(&path);
+ Err(e)
+ }
+ }
+ }
+}
+
+impl Source {
+ pub fn path(&self) -> &Path {
+ &self.path
+ }
+
+ pub fn path_string(&self) -> String {
+ self.path.to_string_lossy().to_string()
+ }
+}
+
+impl Drop for Source {
+ fn drop(&mut self) {
+ let _ = std::fs::remove_file(&self.path);
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[tokio::test]
+ async fn a_source_is_deleted_and_its_slot_freed_when_it_drops() {
+ let sources = Sources::new(1);
+ let path = http::temp_path("step");
+ std::fs::write(&path, b"ISO-10303-21;").unwrap();
+ let slot = Arc::clone(&sources.slots).acquire_owned().await.unwrap();
+ let source = Source {
+ path: path.clone(),
+ hash: 0,
+ _slot: slot,
+ };
+ assert_eq!(sources.slots.available_permits(), 0);
+ drop(source);
+ assert!(!path.exists());
+ assert_eq!(sources.slots.available_permits(), 1);
+ }
+
+ #[tokio::test]
+ async fn a_failed_download_leaves_no_file_and_no_slot_held() {
+ let sources = Sources::new(1);
+ let err = sources
+ .download("http://127.0.0.1:1/missing.step", "step", None)
+ .await
+ .err()
+ .unwrap();
+ assert_eq!(err.code, "READ_FAILED");
+ assert_eq!(sources.slots.available_permits(), 1);
+ }
+}
diff --git a/apps/assembler/src/telemetry.rs b/apps/assembler/src/telemetry.rs
index db4787cf4a..8aca4f34b9 100644
--- a/apps/assembler/src/telemetry.rs
+++ b/apps/assembler/src/telemetry.rs
@@ -14,7 +14,7 @@
//! `job <action>` span → `download source` / `compute` / `upload artifact` /
//! `callback`. The job runs detached from the request (and, on Lambda, in
//! another invocation), so its parent travels explicitly: through the spawn
-//! (`spawn_job`) in-process, and through the run-job spec (`inject` / `attach`)
+//! (`spawn_job`) in-process, and through the worker spec (`inject` / `attach`)
//! across the self-invoke.
use std::collections::HashMap;
@@ -38,7 +38,7 @@ use crate::error::ApiError;
static PROVIDER: OnceLock<SdkTracerProvider> = OnceLock::new();
-/// The key the parent context travels under in a run-job spec.
+/// The key the parent context travels under in a worker spec.
const SPEC_KEY: &str = "traceparent";
fn tracer() -> BoxedTracer {
@@ -217,6 +217,7 @@ where
])
.start(&tracer);
let cx = Context::current_with_span(span);
+ let job = crate::jobs::track(job_id, job);
tokio::spawn(
async move {
job.await;
@@ -291,7 +292,7 @@ pub async fn outbound<T>(
out
}
-/// Write the current context into a run-job spec, so the worker invocation
+/// Write the current context into a worker spec, so the worker invocation
/// that runs it continues this trace.
pub fn inject(spec: &mut Value) {
let mut carrier = HashMap::new();
@@ -303,7 +304,7 @@ pub fn inject(spec: &mut Value) {
}
}
-/// Make the context a run-job spec carries current until the guard drops. The
+/// Make the context a worker spec carries current until the guard drops. The
/// guard is not `Send`: hold it across the spawn only, never across an await.
pub fn attach(spec: &Value) -> Option<ContextGuard> {
let traceparent = spec[SPEC_KEY].as_str()?;
diff --git a/apps/erp/app/modules/production/AGENTS.md b/apps/erp/app/modules/production/AGENTS.md
index 97f16d67ae..2c1117c5b9 100644
--- a/apps/erp/app/modules/production/AGENTS.md
+++ b/apps/erp/app/modules/production/AGENTS.md
@@ -13,6 +13,7 @@ Work orders (jobs), scheduling, routings (operations), bill of materials, proced
- **Operation Batch** (`jobOperationBatch`) — N job operations sharing one run on a **batchable process** (`process.batchable`: laser table, furnace, plating; `process.batchType` `Sequential`/`Simultaneous` = the s-batch/p-batch physics — serial queue vs parallel load — driving the batch's planned duration `setup(max) + Σ|max(run)` via `@carbon/utils` `batchDuration`). Jobs are never merged and the BOM is never modified; each member stays a first-class `jobOperation`. Time/cost split **proportional to `operationQuantity`**, materialized at completion as per-member `productionEvent` slices, so job costing/GL post per job with no special-casing. Status **`Planned → Active → Completing → Completed`** (no `Cancelled` — dissolve deletes a pre-start batch instead). `Planned` is the pre-floor state: composed in the builder from ANY live job's unstarted ops (the planner RPC no longer requires released jobs), fully editable (add/remove/work-center widened to Planned+Active pre-event), invisible to MES. **`Active` displays as "Released"** (exactly like job `Ready`); the `release` posting intent (`Planned → Active`, requires ≥1 member — NO work center: the scheduler pre-pass auto-selects earliest-finish among the process's work centers and persists it to batch + members) puts members on the floor, and releasing it RELEASES its Draft/Planned member jobs through the job page's own path — `releaseBatches` → `releaseBatchMemberJobs` → `releaseCheckedJobs` (`production.server.ts`: recalc, MRP, status Ready, outside-operation POs via `create` `purchaseOrderFromJob`, releasedDate) after `getJobReleaseReadiness` validates EVERY such job (assemblies without operations, manufacturing blocked, or an outside operation whose supplier can't be resolved — `resolveOperationSupplier`: its own supplier process, else the process's only supplier — refuse the whole batch untouched; there is no per-operation supplier picker on batch release); a supplier's first new PO is reused for the later jobs so a batch lands on one PO per supplier. The `BatchReleaseModal` (drawer, table row action, builder Create & Release) shows the checks and the per-supplier PO choice; bulk `batches/release` passes no choice, so a batch needing a fix or with Draft POs to choose from is skipped and named. Then it notifies the scheduler; `unrelease` (`Active → Planned`) is allowed only before the first production event. **Membership-handoff floor rule**: an op in a batch is floor-visible iff its BATCH is Released (`Active`/`Completing`) — even when its job is Draft/Planned; an op in no batch follows its JOB's release (the pre-batching rule — a released job's un-batched batchable op always remains runnable, never blocked; removing it from a batch is the escape hatch). Enforced in `get_active_job_operations_by_location`, MES `getOpenJobs`, AND server-side in the MES operation loader + start route (list visibility alone was the leak). **Scheduling**: a Released batch is ONE scheduling unit — the batch pre-pass (`packages/planning/src/scheduling/batch-scheduler.ts`, run by `runLocationSchedule` before the per-job passes) writes a single coalesced `capacityReservation` tagged `jobOperationBatchId` (NOT NULL `operationId`/`jobId` anchored on the min member op), members pin to the window in the selector (generalized pinned-OSP path, no per-member reservation), downstream ops chain after the batch end, and the anchor comes from persisted predecessor forecasts (overruns flag a conflict and converge next wave); a batch whose open members all carry zero time standards still surfaces — a flagged 1h placeholder (`workHours` 0, never blocks) with a conflict naming the data gap, instead of silently vanishing from the reservation-driven forecast; Planned batches still schedule per-op. Completion is **two-phase and resumable** — Phase 1 (one txn) slices events + records quantities + flips `Active → Completing`; Phase 2 (idempotent, posting-owned) issues each member's BOM, flips members `Done`, posts GL, then `Completing → Completed`. A Phase-2 failure leaves the batch `Completing` and re-invoking resumes (no double issue/GL). A retry MUST resubmit the quantities Phase 1 recorded — a changed quantity is rejected, not silently applied. Proportional split logic lives in `@carbon/utils` `batch-time-split`. Distinct from lot/batch tracking (`trackedEntity`/`batchNumber`). Outside Processing operations are never batchable — a batch is one run on one of our work centers, and joining one would stamp its work center onto subcontracted work: `get_batchable_operations` leaves them out of the candidates and `assertEligible` refuses them. Mutations go through the `batch-operations` posting (create/add/remove/update/dissolve/complete); payload record ids are re-read under `companyId` (`assertCompanyRecord` for location/work center) and the batch table's location/process/workCenter FKs are composite `(<col>, "companyId")` (`20260905132037_job-operation-batching.sql` (the consolidated branch migration)), so a cross-tenant id is refused by the fn AND rejected by the schema. Batch COMPOSITION happens ONLY in the batch builder (below) — the operations priority board's select-to-batch flow (checkboxes on cards, `BatchSelectionProvider`, the floating create bar, and the `BatchOpportunity` banner/column hints) was removed 2026-09-01 at Sid's direction, after the dedicated drag-and-drop batching board went the same way 2026-08-21. The board still SHOWS batches: each live batch collapses to one `BatchItemCard` in its work-center column (drag across columns reassigns the batch work center via `priorityBatchingUpdate`; Completing cards are read-only). The one composition surface — a guided **batch builder** — launches from the Batches list (`New Batch`) and an Active batch's drawer (`Add operations` → add-mode): a full-screen three-step drawer wizard (`ui/Batches/BatchBuilder.tsx`) that picks a location + batchable process (deep-linkable via `?location=&process=`; the last scope/view is remembered in localStorage), fetches candidates from `api/production/batchable-operations` (the revived `getBatchableOperations` RPC wrapper, enriched with each op's setup/labor/machine time, due date, and item thumbnail, plus per-work-center queue load and a hidden-ops count), and offers local search, a due-window quick filter (7/14/30d, due-date-sorted), a dynamic local-state "+ Filter" facet picker over the dimensions the candidates' BOMs actually contain (the material ITEM itself plus substance/grade/dimension/form/finish where populated — ANY BOM line matches ALL active facets; active facets render as removable/editable chips), two list views (polished table or group-by-material-signature sections with per-group select-all and setup-saving chips — a line's signature falls back to its BOM item's readable id when no normalized properties exist, so property-less BOMs still group by what they consume; an operation with NO op-linked BOM lines takes the JOB's unassigned (`jobOperationId IS NULL`) lines — BOMs are routinely authored without per-operation assignment, and without the fallback every such op read "No materials", emptied the facet picker, and degraded grouping to the produced item), a prominent scored suggestions banner at the top of the operations list — groups ranked by `rankSuggestions` (blended, normalised score: setup saved + due urgency + capacity fit + dimension specificity; each signature group is first split into due-date clusters no wider than `SUGGESTION_DUE_WINDOW_DAYS` = 7 via `splitByDueWindow`, so a suggestion never spans weeks — same material next month is next month's batch), each row a one-click apply with a reason chip (due now / fills a run); grouping uses `groupingKey` (material signature, falling back to the produced item for material-less assembly ops) while the mixed-materials warning uses the materials-only `materialSignature`, so the fallback never fakes a material clash. The pure logic (signatures, value sets, duration math, scoring) lives in `ui/Batches/batch-builder-logic.ts` — no JSX/lingui, unit-tested by `apps/erp/test/batch-suggestions.test.ts`, and a live preview (count · quantity · estimated run time, setup-saving + due-spread chips, plus a non-blocking "mixing materials" warning — material compatibility guides but never blocks, per the locked spec decision). Create-mode can attach a work center (picker shows each center's queue depth) and optional notes (additive `notes` field on the posting's create payload), and — instead of creating a duplicate — offers a searchable **"Add to batch"** footer popover (`AddToBatchButton`: a `Command` list over the compatible Active same-process batches from `deriveAddTargets`, each row `readableId · N ops`, on-select → the same `add` submit) rather than one button per batch, so it scales to hundreds of open batches. When the chosen work center has a `batchCapacity` set, a fill bar under the picker shows selected qty vs capacity ("fits in one run" / "over capacity — N loads") plus a `minimumBatchQuantity` met/short line — purely ADVISORY, Create never blocks (`resources.workCenter.batchCapacity`/`minimumBatchQuantity`). The scoped process's `batchRules` (`process.batchRules`, threaded through `getBatchableProcesses`) drives compatibility: the candidate signature/facets/mixed-material warning use every non-"ignore" dimension (default substance/grade/dimension, with the material item as a fallback for property-less BOMs), a "guide" mismatch versus the current selection shows a quiet amber tag on the row, and a "must" mismatch renders the row visible-but-LOCKED (grey lock tag, checkbox no-op, excluded from suggestions/select-all — clears when the selection empties). All resolution/enforcement is the shared `@carbon/utils` `batch-compatibility` module (`resolveBatchRules`/`mustViolations`); the client uses names and the posting uses ids through the same value-agnostic fold, so they always agree. The posting's `assertMaterialCompatible` re-checks the WHOLE membership (create: incoming set; add: existing members + incoming) after `assertEligible` and rejects a must-violating batch naming the dimension — the LOCK in the UI is advisory-fast; the posting is the real gate. It submits `create`/`add` to the same `batching.update` action + `batch-operations` posting — no new mutation path. Completion (MES modal → `complete`) can mark a member "not in this run" (`excluded`): it detaches back to the schedule un-run inside the Phase-1 txn instead of flipping Done; excluded members carry no quantities, all-excluded is rejected (dissolve instead), and a resume drops already-applied exclusions but rejects new ones. Batches LIST at `/x/production/batches` (nav: Production → Batches; `getJobOperationBatches` + `getJobOperationBatchMemberStats` + `getJobOperationBatchMembers`); rows are **expandable** (`renderExpandedRow`/`canExpandRow` on the shared `Table`, same mechanism as the ECO change-notices table) to reveal each member operation (job link, item thumbnail + readable id, completed/qty + scrap); clicking a batch opens a FULL-SIZE detail drawer (`ui/Batches/BatchDetailDrawer.tsx`): header meta (status/process/WC/location/created-by/notes), an enriched member table (thumbnails, completed/qty + scrap, status badges), and a Run card — per-type actual-vs-plan progress (per-type plan buckets = max member setup + Σ|max labor/machine by `process.batchType`; the "Planned time" total = shared setup + Σ|max of each member's run `max(labor, machine)`, matching the scheduler's reservation and MES batch mode via `@carbon/utils` `batchPlanBreakdown`) with a pulsing timer-running badge and the batch's production-event history (`getJobOperationBatchWithMembers` + `getJobOperationBatchEvents`; completed batches show the per-member slices, which keep the batch tag). The Batches list also bulk-RELEASES via selectable rows → a "Release N batches" bulk action posting the selected **Planned** ids to the `batches/release` route (one release per id, the same `releaseBatches` the single-batch `batching.update` release branch calls: `releaseBatchMemberJobs` → `releaseJobOperationBatch` → `notifyScheduleInputsChanged`, member reads in one query; per-batch posting refusals land in the toast summary's `failed` list, the rest still release; a non-Planned id from a stale selection is skipped). Deleting from ERP = the posting's `dissolve`: single via the `batches/delete/:batchId` ConfirmDelete route (destructive "Dissolve Batch" in the table's row context menu + a destructive Dissolve button on the detail drawer, Active only), and bulk via selectable rows → a "Dissolve N batches" bulk action posting the selected Active ids to the `batches/dissolve` route (one posting dissolve per id; the server's per-batch refusal for started batches lands in the toast summary's `failed` list, the rest still dissolve), and a printable **batch list** serves at `/file/batch/:id.pdf` (`BatchListPDF` in `@carbon/documents`; menu entries on the batch card and MES batch chip). **Materials and output lots (2026-09-16):** the MES batch-mode materials panel shows each item's summed BATCH requirement alongside the member's own (`getBatchMaterialTotals`), and ONE pick covers the whole batch — `issue` case `trackedEntitiesToBatch` splits the picked lot(s) **pro-rata by each member's REMAINING requirement** (`splitPickAcrossMembers` in `@carbon/utils` `batch-pick-split`, largest-remainder so shares sum exactly) and records each member's own consumption against its own WIP entity, so cost and lot genealogy stay per job while the operator acts once; the pick modal's default quantity is the batch remaining, NOT the member's share (defaulting to one member's share splits it again across all of them and satisfies none). Completion finalizes each member's produced lot via the lean `issue` case `jobOperationBatchOutput` (the `Produce` activity + entity flip EXTRACTED from `jobOperationBatchComplete`, WITHOUT that case's `productionQuantity` insert and backflush — Phase 1 and the Phase-2 issue step already did both), under lot numbers PLANNED AT CREATION — the builder's Output section (`ui/Batches/BatchOutputLots.tsx`) either sets each member's lot (written to its WIP `trackedEntity.readableId` by the `batch-operations` create) or, when every member makes the same batch-tracked item, "Combine output into one lot" (`jobOperationBatch.mergeOutput` + `outputLotNumber`, migration `20260918094217_batch-output-lot-at-creation.sql`); the operator never edits lots at completion. A merged batch's member lots are combined right after completion (and the batch drawer's "Merge output lots" covers a Completed batch kept separate) into ONE lot via `issue` `mergeTrackedEntities` — genealogy keeps every source job, so the merged lot is strictly more traceable than a single directly-produced one. Both entry points derive the parent ids SERVER-SIDE from the batch's membership and call the `issue` posting. Eligibility gained a `producedItem` dimension in `BATCH_RULE_DIMENSIONS` (default `ignore`) so a process can require members to make the same item. Serial-tracked members are unchanged — batch mode still disables tracked activity for them. Job surfaces show live-batch membership: a Batches column on the jobs table (loader-side lookup), a badge on the `JobBillOfProcess` operation row (`jobOperationBatch` embed), and a chip on the MES job DAG node.
- **Procedure** — versioned work instructions linked to operations via `processId`. Statuses: Draft/Active/Archived.
- **Assembly Instructions** — 3D animated work instructions, available to all users. (Previously gated to Carbon-internal emails via `requireAssembliesInternal` / `useFlags().isInternal`; that gate was removed to ship publicly.) **Versioned** (Draft/Published/Archived) as **row-per-version**, not an in-place counter: sibling versions are grouped by a self-referential `assemblyInstruction.rootInstructionId` (NULL = "I am the root"; group root = `rootInstructionId ?? id`, siblings = `id = root OR rootInstructionId = root`). `copyAssemblyInstructionAsVersion` spins a new editable **Draft** as a perfect copy (`version = max+1`, deep-copies steps with `parentStepId` remapped + each step's materials/slides/tools). `activateAssemblyInstructionVersion` makes a version active: publishes it, **archives the prior Published sibling**, and repoints `jobOperation.assemblyInstructionId` from other group versions to it — but only for active operations (status ≠ Done/Canceled) on active jobs (`!isJobLocked`). Only Draft is editable; the header exposes a "Versions" switcher + Make Active / New Version. `updateAssemblyInstructionStatus` no longer bumps `version`. The **list** (`getAssemblyInstructions`) reads the `assemblyInstructions` **view** (not the base table): it collapses each group to its latest version (`WHERE version = MAX(version)` per `rootInstructionId ?? id`) and rolls every sibling into a `versions` jsonb array, mirroring the `procedures` view — the table shows a `Version N` subtitle on the name plus a "Versions" hover card. Migration `20260730153412_assembly-instructions-view.sql`.
+- **Outdated model** — an instruction keeps the `modelUploadId` it was made from; when its part's `item.modelUploadId` is another model (a new upload, a re-push from Onshape), the page shows a notice over the viewer with a link to a new instruction for the part. Derived on read (`getAssemblyInstruction` embeds `item(modelUploadId)`), nothing stored. A new version is no answer: `copyAssemblyInstructionAsVersion` copies the old model and its steps, whose `componentNodeIds` name that model's nodes.
- **Sub-assemblies** — a header row (`assemblyInstructionStep.isSubAssembly`, no parts of its own) plus the steps whose `parentStepId` is that header, stored directly BEFORE it in `sortOrder` (play order); the header's `usedInStepId` is the later step that fits the finished unit (NULL = it joins the main build at the header). One level only. Every structural write (`makeAssemblySubAssembly`, `insertAssemblyInstructionStep`, `updateAssemblySubAssembly`, `ungroupAssemblySubAssembly`, `deleteAssemblySubAssembly`, `updateAssemblyInstructionStepOrder`) is a Kysely transaction that locks the instruction, applies the change in memory, checks `validateSubAssemblies` and writes the new order — never a partial update. Header rows are never copied into job steps. The step that uses a sub-assembly never re-lists its parts, so BOM materials are seeded once. Viewer side: `packages/viewer/src/subassembly.ts`.
- **Maintenance Dispatch** — reactive/scheduled repair for work centers with comments, events, items, and linked work centers.
- **Scheduling** — forecast-first finite scheduling run **IN-PROCESS in Node** via `runLocationSchedule` / `runExpediteWhatIf` from `@carbon/planning` (the ERP app and `@carbon/jobs` call it directly; the engine lives in `packages/planning/src/scheduling/`). It regenerates a **whole LOCATION** in one deterministic FORWARD-ASAP pass (no backward JIT pass in placement, no `initial`/`reschedule` modes). Machine availability comes from a per-work-center ladder: `workCenter.alwaysOn` = 24×7 lights-out → explicit `workCenterShift` rows → the location's `shift` rows → a stock Mon–Fri 8h week; open maintenance dispatches flagged `takesWorkCenterOffline` subtract downtime from those windows. Work centers are finite (capacity 1 — one op at a time) AND, for ability-gated processes, qualified PEOPLE are finite: work only accumulates while a qualified employee is on shift (`employeeShift` ⋈ `shift`; no shift assignment = the job location's calendar) and not reserved elsewhere. Started ops net **remaining work** only — labor+machine scaled by `(1 − quantityComplete/operationQuantity)`, setup done once any `productionEvent` exists. Placements persist as `capacityReservation` rows (a materialized output: delete-by-job + bulk insert per run, `scenarioId IS NULL`; `WorkCenter` + `Employee` kinds — `OperatorPool` is read-tolerated legacy, never written); the run also writes `job.projectedCompletionAt` (forecast finish) and clears the job's schedule-outdated stamps. **Dual dates** (`20260818031629_dual-dates.sql`, spec `.ai/specs/2026-08-15-dual-dates-due-vs-projected.md`): every regen writes each op's forward projection — `startDate` (projected start day) + `jobOperation.projectedCompletionAt` (projected finish instant) — and DIFF-writes `jobOperation.dueDate` from a backward demand-anchored need-by pass (`computeNeedByDates`, `packages/planning/src/scheduling/need-by-calculator.ts` — a pure pre-placement step: reverse-topo from `job.dueDate`, `operationLeadTime` + assembly lead times, day lengths from the work centers' real calendars). Targets NEVER floor placement; `manuallyScheduled` = a human owns the need-by (the pin is taken as-is, propagates upstream, and is never overwritten — pinned ops still place normally; the old frozen-window branch is gone). An op projected past its need-by gets an informational amber behind-target state (BOP rows, ops-board `ItemCard`, MES operation detail) — never per-op `hasConflict`; when the job is late, the cause sentence appends "First behind target: {op} (due X, projected Y)". `jobOperation.priority` = the per-work-center placement order (reservation start ascending) — one source of truth for dispatch order (there is no configurable dispatch-sequencing policy). **People assignments** (manning board, `peopleAssignment`) make a staffed station a TEAM: the station still runs ONE op at a time, but the whole team present is booked on that op together — labor is parallelized across the present people (two people halve the labor wall-clock; setup and machine time are never compressed). Gated ops team-book people∩qualified on their assigned dates, falling back to an any-qualified single-person relay — but the board is a COMMITMENT, not a soft preference: the fallback may only draw on true FLOATERS (people with NO board assignment anywhere in the horizon, via `assignmentsByEmployee.has(id)`). A person you have manned anywhere is spoken for and is never pulled to a station they weren't assigned to — so moving your only welder off a station makes that station's op an unschedulable placeholder (visible on the Forecast) rather than silently double-booking the welder or shoving the op onto an unmanned weekend. A blank board leaves every qualified person a floater ⇒ classic any-qualified fallback, unchanged. Ungated ops at a staffed station are manned the same way with machine-only fallback. **Require-staffing policy** (`location.requiresStaffing`, per-location, default off, edited on the Production settings page (Settings → Production → Scheduling)): when ON, the scheduler places work ONLY where an operator is manned — the gated floater fallback and the ungated machine-only fallback are both removed, EXCEPT lights-out (`workCenter.alwaysOn`) stations keep running unattended. An op with no manned coverage (and not lights-out) becomes an unschedulable placeholder, so work routes to the staffed work centers and unstaffed ones get nothing. Threaded through `provider.getLocationRequiresStaffing` + `getAlwaysOnWorkCenterIds` → `FiniteSchedulingContext.requiresStaffing` + `capacity.workCenter.alwaysOn`. `peopleAbsence` subtracts the person's availability for that date everywhere; `peopleAssignment.overtimeHours` lengthens the person's day (window extension) and `peopleAssignment.hours` splits deal the day out per station sequentially — all as pure window edits before allocation. A blank board changes nothing. To reschedule, call `notifyScheduleInputsChanged` (stamps jobs; the debounced wave regenerates the whole location) — never direct date writes. An expedite what-if (`expediteJobId`) re-runs the sim with one job first, simulate-only, and returns its projected completion.
diff --git a/apps/erp/app/modules/production/production.service.ts b/apps/erp/app/modules/production/production.service.ts
index 387d7331f8..c4702dfb85 100644
--- a/apps/erp/app/modules/production/production.service.ts
+++ b/apps/erp/app/modules/production/production.service.ts
@@ -7210,7 +7210,7 @@ export async function getAssemblyInstruction(
return client
.from("assemblyInstruction")
.select(
- "*, modelUpload(id, name, modelPath, glbPath, graphPath, componentCount, processingStatus, processingError)"
+ "*, modelUpload(id, name, modelPath, glbPath, graphPath, componentCount, processingStatus, processingError), item(modelUploadId)"
)
.eq("id", id)
.single();
diff --git a/apps/erp/app/modules/purchasing/AGENTS.md b/apps/erp/app/modules/purchasing/AGENTS.md
index 08131ebd78..d53b4f0f43 100644
--- a/apps/erp/app/modules/purchasing/AGENTS.md
+++ b/apps/erp/app/modules/purchasing/AGENTS.md
@@ -86,7 +86,7 @@ Each is a `defineServiceFn` const in `purchasing.server.ts`. The route calls it
- Purchase orders — `updatePurchaseOrder` (the details form: header columns only, never `status`, refused on a finalized order), `updatePurchaseOrders` (one field of the properties panel, refused on a released order except `deliveryDate`), `deletePurchaseOrders` (Draft / Planned, or Needs Approval by its requester — `purchaseOrderDeleteRefusal` in `purchasing.models.ts`; cancels the pending approvals in the delete's transaction), `finalizePurchaseOrderAndNotify` (party contact and supplier approval rules, the approval rule or the planning bypass, then prices, the PDF document and the email; an order that needs approval is never released: `submitPurchaseOrderForApproval` sets Needs Approval and opens the request in one transaction, and the approvers are notified after it commits), `decidePurchaseOrderApproval`, `reopenPurchaseOrder` (Draft / Planned, optionally as a revision; `delete` permission from a released status), `closePurchaseOrderAndApprovals`. The status route takes only Draft, Planned and Closed.
- Return orders — `updateReturnOrders`, `confirmReturnOrder` (stores the PDF; a failed PDF is a `warning`), `cancelReturnOrder`, `reopenReturnOrder`, `addReturnOrderLine` (Draft only), `updateReturnOrderLine` (post-confirm locks: `lockedReturnLineField`).
-- RFQs — `createPurchasingRfq`, `updatePurchasingRfqs`, `cancelPurchasingRfq` (cancels the linked supplier quotes), `finalizePurchasingRfqAndNotify` (`service.finalizePurchasingRfq`, ported from `finalize-purchasing-rfq`, then the emails).
+- RFQs — `createPurchasingRfq`, `updatePurchasingRfqs`, `cancelPurchasingRfq` (cancels the linked supplier quotes), `finalizePurchasingRfqAndNotify` (`service.finalizePurchasingRfq`, ported from `finalize-purchasing-rfq`, then the emails: the RFQ and line documents, and each line item's original CAD file from `getItemModelFiles` — attached in line order while the total stays under `PO_EMAIL_ATTACHMENT_LIMIT_MB` (`splitRfqModelAttachments`), the rest signed for 7 days and listed as links in the body; a model with no known size goes as a link, one whose attachment cannot be signed falls back to a link, and one with no link either is named in the body).
- Supplier quotes — `updateSupplierQuotes`, `finalizeSupplierQuoteWithLink`, `sendSupplierQuoteToSupplier`; `submitDigitalSupplierQuote` / `declineDigitalSupplierQuote` / `updateDigitalSupplierQuoteLineNotes` / `recordSupplierQuoteLinkVisit` (system only, not published: the supplier's share link runs them through `shareLinkContext`, `~/modules/service-context.server`; submit refuses a line that is not the quote's).
- Suppliers — `requestSupplierApproval`, `deactivateSupplier`, `decideSupplierApproval`.
- Planning — `orderPlannedPurchases` (suggestions to Planned POs, one per supplier per week), `updatePlanningPurchaseOrderLine`, `applyPlanningActions`, `dismissPurchasingPlanningActions`, `reopenPurchasingPlanningActions`, `assignPurchasingPlanningActions`. The route answers `{ success, message }`, the shape `usePlanningActions` (production module, shared with production planning) reads.
diff --git a/apps/erp/app/modules/purchasing/purchasing.models.test.ts b/apps/erp/app/modules/purchasing/purchasing.models.test.ts
index 353dfdde16..efb362e931 100644
--- a/apps/erp/app/modules/purchasing/purchasing.models.test.ts
+++ b/apps/erp/app/modules/purchasing/purchasing.models.test.ts
@@ -40,6 +40,7 @@ import {
purchaseOrderStatusType,
purchaseOrderValidator,
resolveLeaseDates,
+ splitRfqModelAttachments,
supplierQuoteValidator
} from "./purchasing.models";
@@ -629,3 +630,22 @@ describe("lockedReturnLineField", () => {
).toBeNull();
});
});
+
+describe("splitRfqModelAttachments", () => {
+ const model = (id: string, size: number) => ({ id, size });
+
+ it("attaches what fits in line order and links the rest", () => {
+ const { attach, link } = splitRfqModelAttachments(
+ [model("a", 10), model("big", 30), model("b", 5)],
+ 20
+ );
+ expect(attach.map((m) => m.id)).toEqual(["a", "b"]);
+ expect(link.map((m) => m.id)).toEqual(["big"]);
+ });
+
+ it("links every model when documents already use the budget", () => {
+ const { attach, link } = splitRfqModelAttachments([model("a", 1)], -5);
+ expect(attach).toEqual([]);
+ expect(link.map((m) => m.id)).toEqual(["a"]);
+ });
+});
diff --git a/apps/erp/app/modules/purchasing/purchasing.models.ts b/apps/erp/app/modules/purchasing/purchasing.models.ts
index ce56e36189..9e3d1e0512 100644
--- a/apps/erp/app/modules/purchasing/purchasing.models.ts
+++ b/apps/erp/app/modules/purchasing/purchasing.models.ts
@@ -1517,3 +1517,26 @@ export const leasePurchaseValidator = z.object({
name: z.string().trim().min(1, { message: "Asset name is required" }),
notes: zfd.text(z.string().optional())
});
+
+/**
+ * Which RFQ models go in the email and which go as download links: in line
+ * order, each model that still fits in `budgetBytes` is attached, the rest are
+ * linked, so one large model does not push out the small ones after it.
+ */
+export function splitRfqModelAttachments<T extends { size: number }>(
+ models: T[],
+ budgetBytes: number
+): { attach: T[]; link: T[] } {
+ const attach: T[] = [];
+ const link: T[] = [];
+ let left = budgetBytes;
+ for (const model of models) {
+ if (model.size <= left) {
+ attach.push(model);
+ left -= model.size;
+ } else {
+ link.push(model);
+ }
+ }
+ return { attach, link };
+}
diff --git a/apps/erp/app/modules/purchasing/purchasing.server.ts b/apps/erp/app/modules/purchasing/purchasing.server.ts
index c46381cdad..9950d9c169 100644
--- a/apps/erp/app/modules/purchasing/purchasing.server.ts
+++ b/apps/erp/app/modules/purchasing/purchasing.server.ts
@@ -33,8 +33,10 @@ import { NotificationEvent } from "@carbon/notifications";
import type { JSONContent } from "@carbon/react";
import {
applyRate,
+ async,
datetime,
deriveRate,
+ escapeHTMLChars,
PO_EMAIL_ATTACHMENT_LIMIT_MB,
SCALE,
taxableBase,
@@ -88,6 +90,7 @@ import {
purchasingRfqFinalizeValidator,
purchasingRfqValidator,
selectedLineSchema,
+ splitRfqModelAttachments,
supplierQuoteFinalizeValidator,
taxPairForQuantity
} from "./purchasing.models";
@@ -100,6 +103,9 @@ import * as service from "./purchasing.service";
const logger = getLogger("erp", "purchasing");
+/** How long a model link in an RFQ email works: a supplier may open it days later. */
+const RFQ_MODEL_LINK_SECONDS = 7 * 24 * 60 * 60;
+
/** Custom field values, as `setCustomFields` reads them from a form. */
const customFieldsInput = z.record(
z.string(),
@@ -118,6 +124,7 @@ const customFieldsInput = z.record(
*
* @mcp
*/
+
export const createPurchasingRfq = defineServiceFn({
input: purchasingRfqValidator
.omit({ id: true })
@@ -386,6 +393,79 @@ export const finalizePurchasingRfqAndNotify = defineServiceFn({
(lines.data ?? []).flatMap((line) => (line.id ? [line.id] : []))
))
];
+ // Each part's original CAD file: attached while the email stays under the
+ // limit, a download link past it.
+ const models = await service.getItemModelFiles(
+ client,
+ ctx.asSystem.pg,
+ companyId,
+ [
+ ...new Set(
+ (lines.data ?? []).flatMap((line) =>
+ line.itemId ? [line.itemId] : []
+ )
+ )
+ ]
+ );
+ const documentBytes = attachments.reduce(
+ (sum, file) => sum + (file.size ?? 0),
+ 0
+ );
+ const split = splitRfqModelAttachments(
+ models,
+ PO_EMAIL_ATTACHMENT_LIMIT_MB * 1024 * 1024 - documentBytes
+ );
+ // A model whose attachment link could not be signed goes as a link; one
+ // with no link either is named, so the supplier knows to ask for it.
+ const attachSigned = await async.map(split.attach, async (model) => ({
+ model,
+ url: await service.signOriginalModelFile(client, companyId, model, 3600)
+ }));
+ const modelAttachments = attachSigned.flatMap(({ model, url }) =>
+ url ? [{ filename: model.filename, path: url }] : []
+ );
+ const signedLinks = await async.map(
+ [
+ ...split.link,
+ ...attachSigned.flatMap(({ model, url }) => (url ? [] : [model]))
+ ],
+ async (model) => ({
+ model,
+ url: await service.signOriginalModelFile(
+ client,
+ companyId,
+ model,
+ RFQ_MODEL_LINK_SECONDS
+ )
+ })
+ );
+ const modelLinks = signedLinks.flatMap(({ model, url }) =>
+ url ? [{ filename: model.filename, url }] : []
+ );
+ const missingModels = signedLinks.flatMap(({ model, url }) =>
+ url ? [] : [model.filename]
+ );
+ const missingHtml = missingModels.length
+ ? `<br><br>These models could not be included; reply to ask for them: ${missingModels
+ .map(escapeHTMLChars)
+ .join(", ")}`
+ : "";
+ const missingText = missingModels.length
+ ? `\n\nThese models could not be included; reply to ask for them: ${missingModels.join(", ")}`
+ : "";
+ const modelLinksHtml = modelLinks.length
+ ? `<br><br>Models too large to attach (links valid for 7 days):<br>${modelLinks
+ .map(
+ (model) =>
+ `<a href="${escapeHTMLChars(model.url)}">${escapeHTMLChars(model.filename)}</a>`
+ )
+ .join("<br>")}${missingHtml}`
+ : missingHtml;
+ const modelLinksText = modelLinks.length
+ ? `\n\nModels too large to attach (links valid for 7 days):\n${modelLinks
+ .map((model) => `${model.filename}: ${model.url}`)
+ .join("\n")}${missingText}`
+ : missingText;
const notesHtml = tiptapToHTML(
(rfq.data?.internalNotes ?? {}) as JSONContent
);
@@ -402,11 +482,15 @@ export const finalizePurchasingRfqAndNotify = defineServiceFn({
html: [
body.replace(/\n/g, "<br>"),
`<br><a href="${link}">${link}</a>`,
+ modelLinksHtml,
notesHtml ? `<br><br>${notesHtml}` : "",
`<br><br>${signature.replace(/\n/g, "<br>")}`
].join(""),
- text: `${body}\n\n${link}\n\n${signature}`,
- attachments,
+ text: `${body}\n\n${link}${modelLinksText}\n\n${signature}`,
+ attachments: [
+ ...attachments.map(({ filename, path }) => ({ filename, path })),
+ ...modelAttachments
+ ],
companyId
});
} catch (err) {
diff --git a/apps/erp/app/modules/purchasing/purchasing.service.ts b/apps/erp/app/modules/purchasing/purchasing.service.ts
index efcb3af251..69d4d2c3c1 100644
--- a/apps/erp/app/modules/purchasing/purchasing.service.ts
+++ b/apps/erp/app/modules/purchasing/purchasing.service.ts
@@ -40,6 +40,7 @@ import {
selectRows
} from "@carbon/database/rows";
import { getNextSequence } from "@carbon/database/sequence";
+import { findStorageObjectBuckets } from "@carbon/database/storage-objects";
import {
convertUnitPrice,
supplierPartCurrency
@@ -47,7 +48,13 @@ import {
import { PurchaseOrderEmail } from "@carbon/documents/email";
import { getPurchaseOrderDisplayId } from "@carbon/documents/pdf";
import { insertAuditLogEntries } from "@carbon/ee/audit.server";
-import { storage } from "@carbon/files";
+import {
+ getCompanyPrivateBucket,
+ getFileExtension,
+ storage,
+ TEMP_STAGING_BUCKET
+} from "@carbon/files";
+import { isModelRawDownloadable } from "@carbon/files/cad";
import { trigger } from "@carbon/jobs";
import { getLogger } from "@carbon/logger";
import {
@@ -862,7 +869,7 @@ export async function getSupplierInteractionLineAttachments(
client: SupabaseClient<Database>,
companyId: string,
lineIds: string[]
-): Promise<{ filename: string; path: string }[]> {
+): Promise<{ filename: string; path: string; size?: number }[]> {
const perLine = await async.map(lineIds, async (lineId) => {
const docs = await getSupplierInteractionLineDocuments(
client,
@@ -881,7 +888,11 @@ export async function getSupplierInteractionLineAttachments(
});
return null;
}
- return { filename: doc.name, path: data.signedUrl };
+ return {
+ filename: doc.name,
+ path: data.signedUrl,
+ size: doc.metadata?.size as number | undefined
+ };
});
});
return perLine
@@ -5883,7 +5894,7 @@ export async function interactionAttachments(
client: SupabaseClient<Database>,
companyId: string,
interactionId: string
-): Promise<{ filename: string; path: string }[]> {
+): Promise<{ filename: string; path: string; size?: number }[]> {
const docs = await getSupplierInteractionDocuments(
client,
companyId,
@@ -5894,7 +5905,8 @@ export async function interactionAttachments(
companyId,
docs.map((doc) => ({
filename: doc.name,
- path: `${companyId}/supplier-interaction/${interactionId}/${doc.name}`
+ path: `${companyId}/supplier-interaction/${interactionId}/${doc.name}`,
+ size: doc.metadata?.size as number | undefined
}))
);
}
@@ -5902,8 +5914,8 @@ export async function interactionAttachments(
export async function signedAttachments(
client: SupabaseClient<Database>,
companyId: string,
- files: { filename: string; path: string }[]
-): Promise<{ filename: string; path: string }[]> {
+ files: { filename: string; path: string; size?: number }[]
+): Promise<{ filename: string; path: string; size?: number }[]> {
const signed = await async.map(files, async (file) => {
const { data, error } = await storage(client)
.company(companyId)
@@ -5915,11 +5927,137 @@ export async function signedAttachments(
});
return null;
}
- return { filename: file.filename, path: data.signedUrl };
+ return { filename: file.filename, path: data.signedUrl, size: file.size };
});
return signed.flatMap((file) => (file ? [file] : []));
}
+/**
+ * The original CAD file of each item's model, found where the model's Download button
+ * finds it: `originalPath`, else a `modelPath` that is still the uploaded file,
+ * in the company bucket or in temp-staging before compaction settles. A model
+ * with no original, or only a compressed `.zst` raw no CAD tool opens, is left
+ * out.
+ */
+export async function getItemModelFiles(
+ client: SupabaseClient<Database>,
+ db: Kysely<KyselyDatabase>,
+ companyId: string,
+ itemIds: string[]
+): Promise<
+ {
+ modelId: string;
+ filename: string;
+ bucket: string;
+ path: string;
+ size: number;
+ }[]
+> {
+ if (itemIds.length === 0) return [];
+ const items = await client
+ .from("item")
+ .select("id, modelUploadId")
+ .in("id", itemIds)
+ .eq("companyId", companyId);
+ const modelByItem = new Map(
+ (items.data ?? []).map((item) => [item.id, item.modelUploadId])
+ );
+ const modelIds = [
+ ...new Set(
+ itemIds.flatMap((id) => {
+ const modelId = modelByItem.get(id);
+ return modelId ? [modelId] : [];
+ })
+ )
+ ];
+ if (items.error || modelIds.length === 0) {
+ if (items.error) {
+ logger.error("Failed to read items for model attachments", {
+ companyId,
+ error: items.error
+ });
+ }
+ return [];
+ }
+ const models = await client
+ .from("modelUpload")
+ .select("id, name, size, modelPath, originalPath")
+ .in("id", modelIds)
+ .eq("companyId", companyId);
+ if (models.error) {
+ logger.error("Failed to read models for attachments", {
+ companyId,
+ error: models.error
+ });
+ return [];
+ }
+
+ const candidates = models.data.flatMap((model) => {
+ const path =
+ model.originalPath ??
+ (model.modelPath && isModelRawDownloadable(model.modelPath)
+ ? model.modelPath
+ : null);
+ if (!path || getFileExtension(path) === "zst") return [];
+ return [{ model, path }];
+ });
+ const buckets = await findStorageObjectBuckets(db, {
+ names: candidates.map((candidate) => candidate.path),
+ buckets: [getCompanyPrivateBucket(companyId), TEMP_STAGING_BUCKET]
+ });
+
+ const byId = new Map(
+ candidates.flatMap(({ model, path }) => {
+ const bucket = buckets.get(path);
+ if (!bucket) return [];
+ const extension = getFileExtension(path);
+ const name = model.name || model.id;
+ const filename = name.toLowerCase().endsWith(`.${extension}`)
+ ? name
+ : `${name}.${extension}`;
+ return [
+ [
+ model.id,
+ {
+ modelId: model.id,
+ filename,
+ bucket,
+ path,
+ size: model.size ?? Number.POSITIVE_INFINITY
+ }
+ ]
+ ] as const;
+ })
+ );
+ return modelIds.flatMap((id) => {
+ const file = byId.get(id);
+ return file ? [file] : [];
+ });
+}
+
+/** A signed link to a file `getOriginalModelFiles` found, valid `seconds`. */
+export async function signOriginalModelFile(
+ client: SupabaseClient<Database>,
+ companyId: string,
+ file: { bucket: string; path: string },
+ seconds: number
+): Promise<string | null> {
+ const bucket =
+ file.bucket === TEMP_STAGING_BUCKET
+ ? storage(client).from(TEMP_STAGING_BUCKET)
+ : storage(client).company(companyId);
+ const { data, error } = await bucket.createSignedUrl(file.path, seconds);
+ if (!data) {
+ logger.error("Failed to sign a model file", {
+ companyId,
+ storagePath: file.path,
+ error
+ });
+ return null;
+ }
+ return data.signedUrl;
+}
+
/** The statuses of records an edit is about to touch, for a lock check. */
export async function statusesOf(
ctx: ServiceContext,
diff --git a/apps/erp/app/routes/api+/mcp+/lib/tool-manifest.digest.json b/apps/erp/app/routes/api+/mcp+/lib/tool-manifest.digest.json
index 08fa44727c..e4bc3916f5 100644
--- a/apps/erp/app/routes/api+/mcp+/lib/tool-manifest.digest.json
+++ b/apps/erp/app/routes/api+/mcp+/lib/tool-manifest.digest.json
@@ -714,7 +714,7 @@
{"name":"production_getActiveJobOperationsByLocation","classification":"READ","schema":"98cf602352a0","response":"a3fa2c06d591","permission":"production:view","paginates":false},
{"name":"production_getActiveProductionEvents","classification":"READ","schema":"31b84d65b2ac","response":"9d447facd100","permission":"production:view","paginates":false},
{"name":"production_getAssemblyComponentMappings","classification":"READ","schema":"dfce1b9bc52e","response":"da74e5f4208a","permission":"production:view","paginates":false},
- {"name":"production_getAssemblyInstruction","classification":"READ","schema":"7f8214d1083f","response":"4080592cc20d","permission":"production:view","paginates":false},
+ {"name":"production_getAssemblyInstruction","classification":"READ","schema":"7f8214d1083f","response":"6c2955045911","permission":"production:view","paginates":false},
{"name":"production_getAssemblyInstructions","classification":"READ","schema":"ad4033782f45","response":"79381095f84d","permission":"production:view","paginates":true},
{"name":"production_getAssemblyInstructionsForItem","classification":"READ","schema":"30ab89ff5be9","response":"89a844d50556","permission":"production:view","paginates":false},
{"name":"production_getAssemblyInstructionStepMaterials","classification":"READ","schema":"c478d26d5ff3","response":"89a5f52bebf8","permission":"production:view","paginates":false},
diff --git a/apps/erp/app/routes/x+/assembly+/$id.tsx b/apps/erp/app/routes/x+/assembly+/$id.tsx
index 3c6f025bb6..7f0d33846f 100644
--- a/apps/erp/app/routes/x+/assembly+/$id.tsx
+++ b/apps/erp/app/routes/x+/assembly+/$id.tsx
@@ -30,6 +30,7 @@ import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";
import {
data,
+ Link,
useFetcher,
useLoaderData,
useParams,
@@ -237,6 +238,13 @@ export default function AssemblyInstructionRoute() {
// steps in rather than animating fallback paths the plan is about to replace.
const isPlanning = isAssemblyPlanRunning(planJob);
+ // Steps name the model's node ids, so they cannot follow the part onto a
+ // new model (a re-push from CAD, a new upload): offer a fresh instruction.
+ const currentModelUploadId = instruction.item?.modelUploadId;
+ const isModelOutdated =
+ Boolean(currentModelUploadId) &&
+ currentModelUploadId !== instruction.modelUploadId;
+
// null = the default below (the first row of the list).
const [selectedStepId, setSelectedStepId] = useState<string | null>(null);
const [draftComponentNodeIds, setDraftComponentNodeIds] = useState<
@@ -677,6 +685,21 @@ export default function AssemblyInstructionRoute() {
<div className="flex h-[calc(100dvh-var(--topbar-height)-var(--header-height)-var(--content-inset))] w-full flex-col">
{isPhone ? <AssemblyInstructionOverviewHero /> : null}
<div className="relative min-h-0 w-full flex-1 bg-card">
+ {isModelOutdated && instruction.itemId && (
+ <div className="absolute left-3 top-3 z-10 flex max-w-[calc(100%-1.5rem)] items-center gap-2 rounded-full border border-border bg-card px-3 py-1.5 shadow-lg">
+ <span className="text-xs font-medium text-foreground">
+ {t`The part has a newer model than this instruction.`}
+ </span>
+ {permissions.can("create", "production") && (
+ <Link
+ to={`${path.to.newAssemblyInstruction}?itemId=${instruction.itemId}`}
+ className="whitespace-nowrap text-xs text-muted-foreground underline-offset-2 hover:text-foreground hover:underline"
+ >
+ {t`New instruction`}
+ </Link>
+ )}
+ </div>
+ )}
{glbPath && graphPath && isPlanning && (
<div className="absolute left-1/2 top-3 z-10 flex -translate-x-1/2 items-center gap-2 rounded-full border border-border bg-card px-3 py-1.5 shadow-lg">
<Spinner className="h-3.5 w-3.5" />
diff --git a/crates/converter/src/glb.rs b/crates/converter/src/glb.rs
index 8c17d26ab4..b44007d69f 100644
--- a/crates/converter/src/glb.rs
+++ b/crates/converter/src/glb.rs
@@ -11,7 +11,6 @@
use crate::graph::{AssemblyNode, PartMesh};
use gltf::json;
use json::validation::{Checked::Valid, USize64};
-use std::borrow::Cow;
use std::collections::HashMap;
const DEFAULT_COLOR: [f32; 4] = [0.65, 0.65, 0.65, 1.0];
@@ -329,20 +328,74 @@ pub fn write_glb(root: &AssemblyNode) -> Vec<u8> {
};
let json_bytes = json::serialize::to_vec(&gltf_root).unwrap();
- let bin = if b.blob.is_empty() {
- None
- } else {
- Some(Cow::Owned(b.blob))
- };
+ layout_glb(&json_bytes, b.blob)
+}
- let glb = gltf::binary::Glb {
- header: gltf::binary::Header {
- magic: *b"glTF",
- version: 2,
- length: 0,
- },
- json: Cow::Owned(json_bytes),
- bin,
- };
- glb.to_vec().unwrap()
+/// Lay out a GLB (header, JSON chunk, BIN chunk) in the BIN buffer's own
+/// allocation: the header and JSON are shifted in ahead of the binary data, so
+/// the model is never held twice. `gltf::binary::Glb::to_vec` copies the whole
+/// buffer into a new one; this writes the same bytes.
+fn layout_glb(json: &[u8], mut bin: Vec<u8>) -> Vec<u8> {
+ const JSON_CHUNK: u32 = 0x4E4F_534A;
+ const BIN_CHUNK: u32 = 0x004E_4942;
+ let pad = |len: usize| (4 - len % 4) % 4;
+ let (json_pad, bin_pad) = (pad(json.len()), pad(bin.len()));
+ let has_bin = !bin.is_empty();
+ let prefix_len = 12 + 8 + json.len() + json_pad + if has_bin { 8 } else { 0 };
+ let total = prefix_len + bin.len() + bin_pad;
+
+ let mut prefix = Vec::with_capacity(prefix_len);
+ prefix.extend_from_slice(b"glTF");
+ prefix.extend_from_slice(&2u32.to_le_bytes());
+ prefix.extend_from_slice(&(total as u32).to_le_bytes());
+ prefix.extend_from_slice(&((json.len() + json_pad) as u32).to_le_bytes());
+ prefix.extend_from_slice(&JSON_CHUNK.to_le_bytes());
+ prefix.extend_from_slice(json);
+ prefix.resize(prefix.len() + json_pad, b' ');
+ if has_bin {
+ prefix.extend_from_slice(&((bin.len() + bin_pad) as u32).to_le_bytes());
+ prefix.extend_from_slice(&BIN_CHUNK.to_le_bytes());
+ }
+
+ bin.reserve_exact(prefix_len + bin_pad);
+ bin.resize(bin.len() + bin_pad, 0);
+ bin.splice(0..0, prefix);
+ bin
+}
+
+#[cfg(test)]
+mod layout_glb_tests {
+ use super::layout_glb;
+ use std::borrow::Cow;
+
+ fn reference(json: &[u8], bin: &[u8]) -> Vec<u8> {
+ gltf::binary::Glb {
+ header: gltf::binary::Header {
+ magic: *b"glTF",
+ version: 2,
+ length: 0,
+ },
+ json: Cow::Borrowed(json),
+ bin: (!bin.is_empty()).then_some(Cow::Borrowed(bin)),
+ }
+ .to_vec()
+ .unwrap()
+ }
+
+ #[test]
+ fn writes_the_bytes_gltf_writes_at_every_padding() {
+ let json = br#"{"asset":{"version":"2.0"}}"#;
+ for json_len in 25..=28 {
+ for bin_len in [0, 1, 2, 3, 4, 5, 1023] {
+ let json = &json[..json_len.min(json.len())];
+ let bin: Vec<u8> = (0..bin_len).map(|i| i as u8).collect();
+ assert_eq!(
+ layout_glb(json, bin.clone()),
+ reference(json, &bin),
+ "json {} bytes, bin {bin_len} bytes",
+ json.len()
+ );
+ }
+ }
+ }
}
diff --git a/docs/content/docs/reference/supplier-quotes.mdx b/docs/content/docs/reference/supplier-quotes.mdx
index 8b747d6bb2..45eb4f8732 100644
--- a/docs/content/docs/reference/supplier-quotes.mdx
+++ b/docs/content/docs/reference/supplier-quotes.mdx
@@ -9,7 +9,7 @@ Each RFQ exchange stores one quote per supplier. You can compare the responses a
## Where a quote comes from
-Most quotes are the response half of an RFQ. You send a purchasing RFQ to several suppliers, and each supplier's reply becomes its own supplier quote, all hanging off the same request. A quote can also be entered directly, without a preceding RFQ, when you already have pricing to record.
+Most quotes are the response half of an RFQ. You send a purchasing RFQ to several suppliers, and each supplier's reply becomes its own supplier quote, all hanging off the same request. The RFQ email carries the files attached to the RFQ and its lines, plus each part's original CAD file (the file you uploaded or pushed from CAD). Models go in as attachments while the email stays under 25 MB; the rest are download links in the email that work for 7 days. A quote can also be entered directly, without a preceding RFQ, when you already have pricing to record.
Either way the quote lives under a **supplier interaction**, the umbrella record that ties this supplier's quote, RFQ, and any resulting purchase order together so you can trace the whole exchange in one place.
diff --git a/packages/ee/src/onshape/lib/client.ts b/packages/ee/src/onshape/lib/client.ts
index f88b449858..778c1f138c 100644
--- a/packages/ee/src/onshape/lib/client.ts
+++ b/packages/ee/src/onshape/lib/client.ts
@@ -111,19 +111,14 @@ export interface OnshapeCompany {
[key: string]: unknown;
}
-// The only export formats Carbon ingests: GLTF for models (compressed to a
-// viewer-renderable GLB before attaching) and PDF for drawings. Onshape's API
-// supports more (STEP, PARASOLID, IGES, ...) but they are deliberately not
-// accepted here — real assemblies export to multi-GB STEP files, and Onshape
-// stays the CAD system of record.
-export type OnshapeModelTranslationFormat = "GLTF";
+// The only export formats Carbon ingests: STEP for models and PDF for
+// drawings. A STEP model is what a manual upload is: the assembler builds the
+// viewer GLB from it, and assembly instructions can convert and plan it. A
+// mesh export (GLTF) could do neither, and left no STEP to download.
+export type OnshapeModelTranslationFormat = "STEP";
export type OnshapeDrawingTranslationFormat = "PDF";
-// Tessellation presets Onshape accepts for mesh exports (mirrors the UI's
-// resolution picker). Mesh translations fail without one.
-export type OnshapeMeshResolution = "coarse" | "medium" | "fine";
-
-// Async translation job (GLTF / PDF export). requestState transitions
+// Async translation job (STEP / PDF export). requestState transitions
// ACTIVE -> DONE | FAILED. When storeInDocument=false the result is fetched via
// resultExternalDataIds; when true, via resultElementIds (a blob element).
export interface OnshapeTranslation {
@@ -296,6 +291,25 @@ export class OnshapeClient {
}
}
+ /**
+ * Where a translation result downloads from and the bearer to send, for a
+ * caller that downloads it elsewhere (the assembler's `fetch`, so a large
+ * export never passes through this process). The token is the one this
+ * client holds: build the client right before handing it on. Counted as a
+ * live call, since the download is one.
+ */
+ externalDataDownload(
+ documentId: string,
+ foreignId: string
+ ): { url: string; authorization: string } {
+ const path = `/api/v10/documents/d/${documentId}/externaldata/${foreignId}`;
+ void this.countLiveCall(path);
+ return {
+ url: `${this.baseUrl.replace(/\/+$/, "")}${path}`,
+ authorization: `Bearer ${this.accessToken}`
+ };
+ }
+
/** Counts in Redis `onshape:api-calls:<year>`; never awaited. */
private async countLiveCall(path: string) {
try {
@@ -682,7 +696,6 @@ export class OnshapeClient {
formatName?: OnshapeModelTranslationFormat;
storeInDocument?: boolean;
configuration?: string;
- resolution?: OnshapeMeshResolution;
// FLAGGED: single-part export support unverified. Omit to export the whole
// Part Studio; the reliable documented path is a whole-Part-Studio translation.
partIds?: string;
@@ -693,12 +706,8 @@ export class OnshapeClient {
"POST",
`/api/v10/partstudios/d/${documentId}/${options.wvm ?? "v"}/${versionId}/e/${elementId}/translations`,
{
- formatName: options.formatName ?? "GLTF",
+ formatName: options.formatName ?? "STEP",
storeInDocument: options.storeInDocument ?? false,
- // Mesh exports (GLTF) REQUIRE tessellation detail — without it Onshape
- // fails the translation with "Invalid GLTF detail parameters were
- // specified" (verified live). "medium" mirrors the Onshape UI default.
- resolution: options.resolution ?? "medium",
...(options.configuration
? { configuration: options.configuration }
: {}),
@@ -715,7 +724,6 @@ export class OnshapeClient {
formatName?: OnshapeModelTranslationFormat;
storeInDocument?: boolean;
configuration?: string;
- resolution?: OnshapeMeshResolution;
wvm?: "w" | "v";
} = {}
): Promise<OnshapeTranslation> {
@@ -723,10 +731,8 @@ export class OnshapeClient {
"POST",
`/api/v10/assemblies/d/${documentId}/${options.wvm ?? "v"}/${versionId}/e/${elementId}/translations`,
{
- formatName: options.formatName ?? "GLTF",
+ formatName: options.formatName ?? "STEP",
storeInDocument: options.storeInDocument ?? false,
- // Same requirement as the Part Studio path — see comment there.
- resolution: options.resolution ?? "medium",
...(options.configuration
? { configuration: options.configuration }
: {})
@@ -761,7 +767,7 @@ export class OnshapeClient {
);
}
- // Binary download for storeInDocument=false results (GLTF/PDF bytes). Uses the
+ // Binary download for storeInDocument=false results (STEP/PDF bytes). Uses the
// axios instance directly with arraybuffer — the shared `request` helper is
// JSON-oriented and would corrupt binary. `maxBytes` bounds the download via
// axios maxContentLength: when Onshape sends Content-Length the request
@@ -821,7 +827,7 @@ export class OnshapeClient {
}
// Stream external data to a file on disk — for results too large to buffer
- // in memory (e.g. a multi-GB GLTF export destined for compression, not
+ // in memory (e.g. a multi-GB STEP export destined for compression, not
// attachment). Aborts with OnshapeAssetTooLargeError as soon as the
// Content-Length header (or the byte count, when the header is absent)
// crosses `maxBytes`. Returns the number of bytes written.
diff --git a/packages/ee/src/onshape/lib/oauth.ts b/packages/ee/src/onshape/lib/oauth.ts
index f845d1f6f7..7db08b7cce 100644
--- a/packages/ee/src/onshape/lib/oauth.ts
+++ b/packages/ee/src/onshape/lib/oauth.ts
@@ -43,7 +43,7 @@ export type OnshapeOAuthConfig = {
baseUrl: string;
};
-// Read for models/revisions/documents; Write to create translation (GLTF/PDF
+// Read for models/revisions/documents; Write to create translation (STEP/PDF
// export) jobs and manage the release webhook subscription. Both must be
// granted to the OAuth application (the dev portal for the public app, the
// Enterprise's Developer settings for a private one), or Onshape refuses the
diff --git a/packages/jobs/AGENTS.md b/packages/jobs/AGENTS.md
index a5800fff15..6761c51f52 100644
--- a/packages/jobs/AGENTS.md
+++ b/packages/jobs/AGENTS.md
@@ -59,6 +59,9 @@ pnpm --filter @carbon/jobs plan:company -- --company <id> --user <id> # MRP +
| `ramp-sweep` | `0 * * * *` | Dispatch Ramp sync for every active install |
| `oee-sweep` | `*/2 * * * *` | Sends one `carbon/oee-sync` per (company, OEE integration) that is active and has at least 1 `workCenterDevice`. OEE providers have no webhooks, so this poll is the only input |
| `oee-sync` | `carbon/oee-sync` (concurrency 1 per company; `singleton` with `mode: "skip"` per company and integration, so an event that arrives while a run is live is dropped) | Syncs every mapped device of one OEE integration in ONE `step.run` (`syncOeeDevice`, `oee-sync-device.ts`): reads the provider's state changes from `lastEventAt − 10 minutes` (24 hours before the mapping on a first sync), stores them in `machineStateChange`, then under `lockWorkCenterDevice` reads the loads (`workCenterLoad`), maintenance block periods and recorded machine time in a bounded window, runs `planMachineTime` and writes Machine `productionEvent` / `unattributedMachineTime` rows; it clears `workCenterDevice.unplannedPressAt` and deletes closed unattributed rows shorter than `minimumStateSeconds`. A failed device gets `lastSyncError` and keeps its cursor; the others continue, except on `OeeProviderUnavailableError` (network failure, timeout, 5xx), which stops the run. Skipped (no error) when the company is not entitled, the integration is inactive or the key is empty. After each device commits, posts the Machine events its sync ended (`endedEventIds` → `postEndedMachineEvents`, `post-production-event` as `userId "system"`); a posting failure is logged, never fails the device. See `.claude/rules/oee-provider.md` |
+| `onshape-element-sync` | `carbon/onshape-element-sync` (`step.invoke`d by `onshape-backfill`, one per model item) | One Onshape element's export onto an item, as `runOnshapeElementSync`'s resumable steps: skip when the source's model exists, start the model and drawing translations together, poll with `step.sleep`, `step.invoke` `onshape-fetch`, attach. Concurrency 1 per item. See `.claude/rules/onshape-panel.md` |
+| `onshape-drawing-sync` | `carbon/onshape-drawing-sync` (`step.invoke`d by `onshape-backfill`, one per released drawing) | One released Onshape drawing as a PDF on its model item, as `runOnshapeDrawingSync`'s resumable steps: translate, poll with `step.sleep`, attach. Concurrency 1 per item |
+| `onshape-fetch` | `carbon/onshape-fetch` (`step.invoke`d by the element sync) | The assembler's `fetch` copies one finished Onshape translation into temp-staging. Its own function so that only it holds `ASSEMBLER_CONCURRENCY` (Inngest counts every executing step of a function against its keys); an export past the upload limit returns `{ tooLarge: true }` |
| `mount-publish` | `carbon/mount-publish` | One company's push to Mount: a step per batch of 200 until nothing is stale, a batch publishes nothing, or 50 batches; progress and outcome in `companyIntegration.metadata.lastPublish.{entityType}`, which the integration page reads |
| `mount-sweep` | `30 2 * * *` | Dispatch a scheduled `mount-publish` for every active Mount install |
| `workflow-run` | `carbon/workflow-run.queued` | Execute one owner-scoped workflow graph |
diff --git a/packages/jobs/src/inngest/functions/integrations/index.ts b/packages/jobs/src/inngest/functions/integrations/index.ts
index 03d43ad019..52f4df4079 100644
--- a/packages/jobs/src/inngest/functions/integrations/index.ts
+++ b/packages/jobs/src/inngest/functions/integrations/index.ts
@@ -15,6 +15,11 @@ export { mountSweepFunction } from "./mount-sweep";
export { oeeSweepFunction } from "./oee-sweep";
export { oeeSyncFunction } from "./oee-sync";
export { onshapeBackfillFunction } from "./onshape-backfill";
+export {
+ onshapeDrawingSyncFunction,
+ onshapeElementSyncFunction
+} from "./onshape-element-sync";
+export { onshapeFetchFunction } from "./onshape-fetch";
export { onshapePanelSyncFunction } from "./onshape-panel-sync";
export { onshapeRevisionSyncFunction } from "./onshape-revision-sync";
export { paperlessPartsFunction } from "./paperless-parts";
diff --git a/packages/jobs/src/inngest/functions/integrations/onshape-attach.test.ts b/packages/jobs/src/inngest/functions/integrations/onshape-attach.test.ts
index cd4fe21315..3af017b855 100644
--- a/packages/jobs/src/inngest/functions/integrations/onshape-attach.test.ts
+++ b/packages/jobs/src/inngest/functions/integrations/onshape-attach.test.ts
@@ -2,13 +2,12 @@
// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,
// including ports, remain AGPLv3; serving them over a network requires releasing their source.
-import { openAsBlob } from "node:fs";
import { beforeEach, describe, expect, it, vi } from "vitest";
-import { attachOnshapeAssetsToItem } from "./onshape-attach";
+import {
+ type AttachOnshapeAssetsInput,
+ attachOnshapeAssetsToItem
+} from "./onshape-attach";
-vi.mock("node:fs", () => ({
- openAsBlob: vi.fn(async () => new Blob(["selected part geometry"]))
-}));
vi.mock("../tasks/assembler-client", () => ({
resolveModelSourceBucket: vi.fn(async () => "temp-staging")
}));
@@ -50,6 +49,7 @@ function database() {
const calls: Call[] = [];
const objects = new Map<string, Blob>();
const uploads: string[] = [];
+ const moves: string[] = [];
const copies: string[] = [];
const failures: { table: string; operation: string; error: QueryError }[] =
[];
@@ -136,7 +136,27 @@ function database() {
copies.push(target);
return { error: null };
},
- remove: async (_paths: string[]) => ({ error: null })
+ move: async (from: string, to: string) => {
+ const [source, target] = [`${bucket}/${from}`, `${bucket}/${to}`];
+ if (!objects.has(source)) {
+ return { error: { message: "Object not found" } };
+ }
+ if (objects.has(target)) {
+ return { error: { message: "The resource already exists" } };
+ }
+ moves.push(target);
+ objects.set(target, objects.get(source)!);
+ objects.delete(source);
+ return { data: { message: "Successfully moved" }, error: null };
+ },
+ info: async (path: string) =>
+ objects.has(`${bucket}/${path}`)
+ ? { data: { name: path }, error: null }
+ : { data: null, error: { message: "Object not found" } },
+ remove: async (paths: string[]) => {
+ for (const path of paths) objects.delete(`${bucket}/${path}`);
+ return { data: [], error: null };
+ }
};
}
}
@@ -149,34 +169,49 @@ function database() {
calls,
objects,
uploads,
+ moves,
copies,
failures
};
}
+const STAGED = "company/models/onshape-fetch-t1.step";
+
const input = {
companyId: "company",
createdBy: "user",
itemId: "item",
sourceDocument: "Part" as const,
model: {
- fileName: "SADDLE.A.gltf",
- localPath: "/unused.gltf",
+ fileName: "SADDLE.A.step",
+ stagedPath: STAGED,
size: 22,
+ contentHash: "content-1",
sourceId: "onshape-part-v2"
}
};
+/** Stage the export (as the assembler's fetch would), then attach it. */
+function attach(
+ db: ReturnType<typeof database>,
+ args: AttachOnshapeAssetsInput,
+ bytes = "selected part geometry"
+) {
+ if (args.model) {
+ db.objects.set(`temp-staging/${args.model.stagedPath}`, new Blob([bytes]));
+ }
+ return attachOnshapeAssetsToItem(db.client, args);
+}
+
beforeEach(() => {
vi.clearAllMocks();
- vi.mocked(openAsBlob).mockResolvedValue(new Blob(["selected part geometry"]));
});
describe("immutable released-part attachments", () => {
it("replaces a bad generation while keeping item data and the prior model intact", async () => {
const db = database();
const prior = structuredClone(db.tables.modelUpload[0]);
- const result = await attachOnshapeAssetsToItem(db.client, input);
+ const result = await attach(db, input);
expect(result.modelUploadId).toBe(input.model.sourceId);
expect(db.tables.item[0]).toEqual({
id: "item",
@@ -187,7 +222,7 @@ describe("immutable released-part attachments", () => {
expect(db.tables.modelUpload[0]).toEqual(prior);
expect(db.tables.modelUpload[1]).toMatchObject({
id: input.model.sourceId,
- modelPath: "company/models/onshape-part-v2.gltf",
+ modelPath: "company/models/onshape-part-v2.step",
size: 22,
originalSize: 22
});
@@ -198,22 +233,22 @@ describe("immutable released-part attachments", () => {
it("replays without overwriting a compacted raw, optimized preview or thumbnail", async () => {
const db = database();
- await attachOnshapeAssetsToItem(db.client, input);
+ await attach(db, input);
const current = db.tables.modelUpload.find(
(row) => row.id === input.model.sourceId
)!;
Object.assign(current, {
- modelPath: "company/models/onshape-part-v2.gltf.zst",
+ modelPath: "company/models/onshape-part-v2.step.zst",
optimizeStatus: "Success",
optimizedModelPath: "new.glb",
thumbnailPath: "new.png"
});
const snapshot = structuredClone(current);
- const uploadCount = db.uploads.length;
- await attachOnshapeAssetsToItem(db.client, input);
+ const uploadCount = db.moves.length;
+ await attach(db, input);
expect(db.tables.modelUpload).toHaveLength(2);
expect(current).toEqual(snapshot);
- expect(db.uploads).toHaveLength(uploadCount);
+ expect(db.moves).toHaveLength(uploadCount);
});
it("recovers a failed item link using the already-created source model", async () => {
@@ -223,21 +258,16 @@ describe("immutable released-part attachments", () => {
operation: "update",
error: { message: "link unavailable" }
});
- await expect(attachOnshapeAssetsToItem(db.client, input)).rejects.toThrow(
- /link/i
- );
- const result = await attachOnshapeAssetsToItem(db.client, input);
+ await expect(attach(db, input)).rejects.toThrow(/link/i);
+ const result = await attach(db, input);
expect(result.modelUploadId).toBe(input.model.sourceId);
expect(db.tables.modelUpload).toHaveLength(2);
- expect(db.uploads).toHaveLength(1);
+ expect(db.moves).toHaveLength(1);
});
it("allows concurrent redeliveries without duplicate model rows or overwriting bytes", async () => {
const db = database();
- const results = await Promise.all([
- attachOnshapeAssetsToItem(db.client, input),
- attachOnshapeAssetsToItem(db.client, input)
- ]);
+ const results = await Promise.all([attach(db, input), attach(db, input)]);
expect(results.map((r) => r.modelUploadId)).toEqual([
input.model.sourceId,
input.model.sourceId
@@ -256,7 +286,7 @@ describe("immutable released-part attachments", () => {
it("preserves a genuinely different manual model as a document", async () => {
const db = database();
withManualPriorModel(db, "manual-prototype.glb");
- const result = await attachOnshapeAssetsToItem(db.client, input);
+ const result = await attach(db, input);
expect(result.preservedPriorModelAsDocument).toBe(true);
expect(db.copies).toEqual(["company/parts/item/manual-prototype.glb"]);
expect(db.tables.document).toHaveLength(1);
@@ -267,10 +297,10 @@ describe("immutable released-part attachments", () => {
// Same filename as the incoming release — filename is not provenance, so the
// manual model must still be preserved rather than silently relinked away.
withManualPriorModel(db, input.model.fileName);
- const result = await attachOnshapeAssetsToItem(db.client, input);
+ const result = await attach(db, input);
expect(result.modelUploadId).toBe(input.model.sourceId);
expect(result.preservedPriorModelAsDocument).toBe(true);
- expect(db.copies).toEqual(["company/parts/item/SADDLE.A.gltf"]);
+ expect(db.copies).toEqual(["company/parts/item/SADDLE.A.step"]);
expect(db.tables.document).toHaveLength(1);
});
@@ -281,11 +311,9 @@ describe("immutable released-part attachments", () => {
operation: "select",
error: { message: "database unavailable" }
});
- await expect(attachOnshapeAssetsToItem(db.client, input)).rejects.toThrow(
- /lookup/i
- );
+ await expect(attach(db, input)).rejects.toThrow(/lookup/i);
expect(db.tables.item[0]!.modelUploadId).toBe("onshape-legacy");
- expect(db.uploads).toEqual([]);
+ expect(db.moves).toEqual([]);
});
it("refuses a source ID belonging to another company", async () => {
@@ -296,38 +324,48 @@ describe("immutable released-part attachments", () => {
name: input.model.fileName,
modelPath: "foreign.gltf"
});
- await expect(attachOnshapeAssetsToItem(db.client, input)).rejects.toThrow();
+ await expect(attach(db, input)).rejects.toThrow();
expect(db.tables.item[0]!.modelUploadId).toBe("onshape-legacy");
expect(db.tables.modelUpload[1]!.modelPath).toBe("foreign.gltf");
});
- it("recovers an upload completed before the model row insert failed", async () => {
+ it("recovers a move completed before the model row insert failed", async () => {
const db = database();
db.failures.push({
table: "modelUpload",
operation: "insert",
error: { code: "08006", message: "connection lost" }
});
- await expect(attachOnshapeAssetsToItem(db.client, input)).rejects.toThrow(
- /insert/
- );
+ await expect(attach(db, input)).rejects.toThrow(/insert/);
expect(db.tables.item[0]!.modelUploadId).toBe("onshape-legacy");
- const uploaded = db.objects.get(
- "temp-staging/company/models/onshape-part-v2.gltf"
+ const moved = db.objects.get(
+ "temp-staging/company/models/onshape-part-v2.step"
);
+ expect(moved).toBeDefined();
+ // The step's retry: the staged object is already gone, the final one stays.
await attachOnshapeAssetsToItem(db.client, input);
expect(
- db.objects.get("temp-staging/company/models/onshape-part-v2.gltf")
- ).toBe(uploaded);
+ db.objects.get("temp-staging/company/models/onshape-part-v2.step")
+ ).toBe(moved);
expect(db.tables.modelUpload).toHaveLength(2);
+ expect(db.tables.item[0]!.modelUploadId).toBe(input.model.sourceId);
+ });
+
+ it("refuses to attach a model whose staged export is missing", async () => {
+ const db = database();
+ await expect(attachOnshapeAssetsToItem(db.client, input)).rejects.toThrow(
+ /move/
+ );
+ expect(db.tables.modelUpload).toHaveLength(1);
+ expect(db.tables.item[0]!.modelUploadId).toBe("onshape-legacy");
});
it("uses a separate model for a changed source and retains manual image overrides", async () => {
const db = database();
db.tables.item[0]!.thumbnailPath = "company/thumbnails/item/manual.png";
- await attachOnshapeAssetsToItem(db.client, input);
+ await attach(db, input);
const firstSource = structuredClone(db.tables.modelUpload[1]);
- const result = await attachOnshapeAssetsToItem(db.client, {
+ const result = await attach(db, {
...input,
model: { ...input.model, sourceId: "onshape-another-part" }
});
@@ -343,7 +381,7 @@ describe("immutable released-part attachments", () => {
it("rejects an invalid or conflicting immutable identity", async () => {
const db = database();
await expect(
- attachOnshapeAssetsToItem(db.client, {
+ attach(db, {
...input,
model: { ...input.model, sourceId: "../unsafe" }
})
@@ -354,10 +392,8 @@ describe("immutable released-part attachments", () => {
name: "wrong-model.gltf",
modelPath: "wrong.gltf"
});
- await expect(attachOnshapeAssetsToItem(db.client, input)).rejects.toThrow(
- /identity/
- );
- expect(db.uploads).toEqual([]);
+ await expect(attach(db, input)).rejects.toThrow(/identity/);
+ expect(db.moves).toEqual([]);
expect(db.tables.item[0]!.modelUploadId).toBe("onshape-legacy");
});
@@ -365,7 +401,7 @@ describe("immutable released-part attachments", () => {
const db = database();
const { sourceId: _sourceId, ...model } = input.model;
const prior = structuredClone(db.tables.modelUpload[0]);
- const first = await attachOnshapeAssetsToItem(db.client, {
+ const first = await attach(db, {
...input,
model
});
@@ -373,33 +409,32 @@ describe("immutable released-part attachments", () => {
expect(db.tables.modelUpload[0]).toEqual(prior);
expect(db.tables.modelUpload[1]).toMatchObject({
id: first.modelUploadId,
- modelPath: `company/models/${first.modelUploadId}.gltf`
+ modelPath: `company/models/${first.modelUploadId}.step`
});
expect(db.tables.item[0]!.modelUploadId).toBe(first.modelUploadId);
expect(db.tables.document).toEqual([]);
- const again = await attachOnshapeAssetsToItem(db.client, {
+ const again = await attach(db, {
...input,
model
});
expect(again.modelUploadId).toBe(first.modelUploadId);
expect(db.tables.modelUpload).toHaveLength(2);
- expect(db.uploads).toHaveLength(1);
+ expect(db.moves).toHaveLength(1);
});
it("gives changed bytes a new model, so no file keyed by the old one is reused", async () => {
const db = database();
const { sourceId: _sourceId, ...model } = input.model;
- const first = await attachOnshapeAssetsToItem(db.client, {
+ const first = await attach(db, {
...input,
model
});
const firstRow = structuredClone(db.tables.modelUpload[1]);
- vi.mocked(openAsBlob).mockResolvedValue(new Blob(["changed geometry"]));
- const changed = await attachOnshapeAssetsToItem(db.client, {
+ const changed = await attach(db, {
...input,
- model
+ model: { ...model, contentHash: "content-2" }
});
expect(changed.modelUploadId).not.toBe(first.modelUploadId);
expect(db.tables.modelUpload).toHaveLength(3);
@@ -414,7 +449,7 @@ describe("immutable released-part attachments", () => {
const { sourceId: _sourceId, ...model } = input.model;
// A row the in-place path wrote: a plain id, the export's own file name.
withManualPriorModel(db, model.fileName);
- const result = await attachOnshapeAssetsToItem(db.client, {
+ const result = await attach(db, {
...input,
model
});
@@ -426,7 +461,7 @@ describe("immutable released-part attachments", () => {
it("keeps every item/model read and update company-scoped", async () => {
const db = database();
- await attachOnshapeAssetsToItem(db.client, input);
+ await attach(db, input);
for (const call of db.calls.filter(
(call) =>
["item", "modelUpload"].includes(call.table) &&
diff --git a/packages/jobs/src/inngest/functions/integrations/onshape-attach.ts b/packages/jobs/src/inngest/functions/integrations/onshape-attach.ts
index 1d95fa35b2..bdd996fdd1 100644
--- a/packages/jobs/src/inngest/functions/integrations/onshape-attach.ts
+++ b/packages/jobs/src/inngest/functions/integrations/onshape-attach.ts
@@ -3,7 +3,6 @@
// including ports, remain AGPLv3; serving them over a network requires releasing their source.
import { createHash } from "node:crypto";
-import { openAsBlob } from "node:fs";
import type { Database } from "@carbon/database";
import {
getCompanyPrivateBucket,
@@ -18,10 +17,11 @@ import { resolveModelSourceBucket } from "../tasks/assembler-client";
// @carbon/jobs (not @carbon/ee): it needs the service-role client + document
// writes, and the release-sync/backfill Inngest functions (its callers) live here.
//
-// The caller (release-sync job) is responsible for:
+// The caller (the Onshape sync pipeline) is responsible for:
// - resolving `itemId` by matching the Onshape part number + revision against
// item.readableIdWithRevision (LINK-ONLY: skip if no match, do NOT create);
-// - downloading the GLTF/PDF from Onshape (OnshapeClient export methods).
+// - staging the STEP export (the assembler's `fetch` puts it in temp-staging)
+// and downloading drawing PDFs.
// A new modelUpload row starts the model pipeline itself (the
// `queue_model_pipeline` statement handler), so no caller sends model-optimize.
@@ -33,12 +33,14 @@ export interface OnshapeAssetFile {
bytes: Uint8Array;
}
-// Raw model export on disk. Streamed into storage via openAsBlob — a
-// whole-vehicle GLTF export reaches 1.7GB and must never be buffered in memory.
+// A raw model export already in temp-staging, put there by whoever fetched it
+// (the assembler's `fetch`, or the no-assembler fallback). Never read here: a
+// whole-vehicle STEP export reaches several GB.
export interface OnshapeModelFile {
fileName: string;
- localPath: string;
+ stagedPath: string; // key in TEMP_STAGING_BUCKET
size: number;
+ contentHash: string; // of the bytes, from whoever staged them
// Stable ID derived by the exporter from the exact released source + its
// selection generation. An ID identifies immutable bytes, never a filename.
sourceId?: string;
@@ -49,7 +51,10 @@ export interface AttachOnshapeAssetsInput {
createdBy: string; // userId for audit (the Onshape integration installer)
itemId: string; // resolved Carbon item (caller guarantees it exists)
sourceDocument: DocumentSourceType; // e.g. "Part"
- model?: OnshapeModelFile; // raw GLTF -> item's modelUpload (optimized by the assembler)
+ model?: OnshapeModelFile; // raw STEP -> item's modelUpload (optimized by the assembler)
+ // A model the sync found already exported (same released source): link it,
+ // nothing to move. Exclusive with `model`.
+ existingModelId?: string;
documents?: OnshapeAssetFile[]; // drawing PDFs -> item documents
}
@@ -59,10 +64,6 @@ export interface AttachOnshapeAssetsResult {
preservedPriorModelAsDocument: boolean;
}
-function modelContentType(extension: string): string {
- return extension === "glb" ? "model/gltf-binary" : "model/gltf+json";
-}
-
function fileExtension(fileName: string): string {
const lastDot = fileName.lastIndexOf(".");
return lastDot >= 0 ? fileName.slice(lastDot + 1).toLowerCase() : "";
@@ -117,30 +118,29 @@ async function ensureImmutableModel(
}
return result.data;
};
- if (await lookup()) return modelId;
+ const staging = carbon.storage.from(TEMP_STAGING_BUCKET);
+ if (await lookup()) {
+ // Already attached: the staged copy is a duplicate of its bytes.
+ await staging.remove([input.model.stagedPath]);
+ return modelId;
+ }
- const extension = fileExtension(input.model.fileName) || "gltf";
+ // The stem must be the model id (the artifacts route derives the id from
+ // the file name), so the staged object moves to its final key.
+ const extension = fileExtension(input.model.fileName) || "step";
const modelPath = `${input.companyId}/models/${modelId}.${extension}`;
- const contentType = modelContentType(extension);
- const rawBlob = await openAsBlob(input.model.localPath, {
- type: contentType
- });
- const uploaded = await carbon.storage
- .from(TEMP_STAGING_BUCKET)
- .upload(modelPath, rawBlob, { upsert: false, contentType });
- // A concurrent redelivery (or a retry after upload but before DB insert) can
- // already own these immutable bytes. Never overwrite them. Both callers then
- // converge through the modelUpload primary key below.
- if (
- uploaded.error &&
- !(
- "statusCode" in uploaded.error &&
- String(uploaded.error.statusCode) === "409"
- )
- ) {
- throw new Error(
- `attachOnshapeAssetsToItem: model upload failed: ${uploaded.error.message}`
- );
+ const moved = await staging.move(input.model.stagedPath, modelPath);
+ // A concurrent redelivery, or a retry after the move but before the insert,
+ // already moved these immutable bytes: the final object is what counts.
+ // Never overwrite it. Both callers then converge on the primary key below.
+ if (moved.error) {
+ const landed = await staging.info(modelPath);
+ if (landed.error) {
+ throw new Error(
+ `attachOnshapeAssetsToItem: model move failed: ${moved.error.message}`
+ );
+ }
+ await staging.remove([input.model.stagedPath]);
}
const inserted = await carbon
.from("modelUpload")
@@ -172,19 +172,21 @@ async function ensureImmutableModel(
// Changed bytes get a new model: every derived file (the compacted raw, the
// preview, the assembly graph) is keyed by the model id, and a durable copy is
// never overwritten, so refreshing a model in place kept the old geometry.
-async function contentSourceId(
+// The bytes' hash comes from whoever staged them, so nothing reads them again.
+export function contentSourceId(
companyId: string,
itemId: string,
- model: OnshapeModelFile
-): Promise<string> {
+ model: Pick<OnshapeModelFile, "fileName" | "contentHash">
+): string {
const hash = createHash("sha256").update(
- JSON.stringify(["content-v1", companyId, itemId, model.fileName])
+ JSON.stringify([
+ "content-v2",
+ companyId,
+ itemId,
+ model.fileName,
+ model.contentHash
+ ])
);
- // Streamed from disk: an export can be larger than memory.
- const reader = (await openAsBlob(model.localPath)).stream().getReader();
- for (let read = await reader.read(); !read.done; read = await reader.read()) {
- hash.update(read.value);
- }
return `onshape-${hash.digest("hex")}`;
}
@@ -323,7 +325,8 @@ export async function attachOnshapeAssetsToItem(
// (path stem == modelUpload.id — the artifacts route derives the id from the
// filename); inserting the row starts the optimise that produces the viewer
// GLB.
- if (input.model) {
+ const model = input.model;
+ if (model || input.existingModelId) {
// Resolve the current model before linking a released source. Item identity
// and its manufacturing records are unchanged; only its model pointer moves.
const currentItem = await carbon
@@ -355,12 +358,13 @@ export async function attachOnshapeAssetsToItem(
}
const priorModel = priorResult?.data ?? null;
- modelUploadId = await ensureImmutableModel(
- carbon,
- { companyId, createdBy, model: input.model },
- input.model.sourceId ??
- (await contentSourceId(companyId, itemId, input.model))
- );
+ modelUploadId =
+ input.existingModelId ??
+ (await ensureImmutableModel(
+ carbon,
+ { companyId, createdBy, model: model! },
+ model!.sourceId ?? contentSourceId(companyId, itemId, model!)
+ ));
if (modelUploadId !== priorModelId) {
// Preserve a genuinely different prior model (e.g. a manual upload) as a
@@ -381,8 +385,9 @@ export async function attachOnshapeAssetsToItem(
// not re-listed as a document.
const priorIsOnshapeGeneration =
(priorModel?.id ?? "").startsWith("onshape-") ||
- (input.model.sourceId === undefined &&
- priorModel?.name === input.model.fileName);
+ (model !== undefined &&
+ model.sourceId === undefined &&
+ priorModel?.name === model.fileName);
if (priorModel?.modelPath && !priorIsOnshapeGeneration) {
const preservedName = stripSpecialCharacters(
priorModel.name ?? `prior-model-${priorModel.id}`
diff --git a/packages/jobs/src/inngest/functions/integrations/onshape-backfill.ts b/packages/jobs/src/inngest/functions/integrations/onshape-backfill.ts
index 3260c43b24..89b4a5bf46 100644
--- a/packages/jobs/src/inngest/functions/integrations/onshape-backfill.ts
+++ b/packages/jobs/src/inngest/functions/integrations/onshape-backfill.ts
@@ -4,24 +4,23 @@
import { getCarbonServiceRole } from "@carbon/auth/client.server";
import type { Database } from "@carbon/database";
-import {
- getOnshapeClient,
- getOnshapeIntegration,
- OnshapeApiError,
- OnshapeAssetTooLargeError
-} from "@carbon/ee/onshape";
+import { getOnshapeClient, getOnshapeIntegration } from "@carbon/ee/onshape";
import type { SupabaseClient } from "@supabase/supabase-js";
-import { RetryAfterError } from "inngest";
import { z } from "zod";
import { inngest } from "../../client";
+import {
+ onshapeDrawingSyncFunction,
+ onshapeElementSyncFunction
+} from "./onshape-element-sync";
import {
escapeLikePattern,
releaseKey,
sharedNumberSuffix
} from "./onshape-matching";
-import {
- syncOnshapeDrawingAssetsToItem,
- syncOnshapeElementAssetsToItem
+import { withRateLimitRetry } from "./onshape-rate-limit";
+import type {
+ SyncOnshapeDrawingInput,
+ SyncOnshapeElementInput
} from "./onshape-sync-element";
// Backfill / reconcile: pull released Onshape assets onto existing Carbon items.
@@ -80,39 +79,8 @@ export interface OnshapeBackfillPageResult {
nextCursor: string | null; // Onshape `next` cursor URL for the following page
}
-const RATE_LIMIT_DEFAULT_WAIT_SECONDS = 60;
-// Clamp Onshape's Retry-After so a bad/huge value can't schedule an absurd wait.
-const RATE_LIMIT_MAX_WAIT_SECONDS = 300;
const MAX_CONSECUTIVE_FAILURES = 5;
-// On a 429, surface it to Inngest as a RetryAfterError rather than blocking the
-// step with an in-process sleep. Inngest SUSPENDS the function — releasing its
-// compute window and the per-company concurrency slot — and reschedules it after
-// the delay; the memoized steps mean it resumes at the first unfinished item, and
-// every export/attach is idempotent so a re-run is safe. The wait honors Onshape's
-// Retry-After (default 60s), clamped to a sane maximum. Anything else rethrows.
-export async function withRateLimitRetry<T>(
- operation: () => Promise<T>,
- label: string
-): Promise<T> {
- try {
- return await operation();
- } catch (error) {
- if (error instanceof OnshapeApiError && error.status === 429) {
- const waitSeconds = Math.min(
- error.retryAfterSeconds ?? RATE_LIMIT_DEFAULT_WAIT_SECONDS,
- RATE_LIMIT_MAX_WAIT_SECONDS
- );
- throw new RetryAfterError(
- `onshape: rate limited on ${label}; retrying after ${waitSeconds}s`,
- waitSeconds * 1000,
- { cause: error }
- );
- }
- throw error;
- }
-}
-
// Shared gate for the Onshape asset-sync jobs: run only when the integration is
// active AND asset sync is enabled. One definition so the backfill and go-forward
// gates can't silently drift apart.
@@ -361,64 +329,41 @@ export async function matchOnshapeBackfillPage(
return result;
}
-// One matched export+attach — the body of a per-item Inngest step. An export
-// that exceeds Carbon's upload limits returns `skippedTooLarge` instead of
-// throwing: the skip is permanent (a retry can't shrink the asset), so it must
-// not fail the step and burn retries/quota.
-export async function syncOnshapeBackfillWorkItem(
- carbon: CarbonClient,
+// What a matched drawing exports: the `onshape-drawing-sync` run's input.
+export function backfillDrawingInput(
input: Pick<OnshapeBackfillInput, "companyId" | "userId">,
workItem: OnshapeBackfillWorkItem
-): Promise<{
- modelUploadId: string | null;
- skippedTooLarge?: boolean;
-}> {
- try {
- if (workItem.kind === "drawing") {
- const attached = await withRateLimitRetry(
- () =>
- syncOnshapeDrawingAssetsToItem(carbon, {
- companyId: input.companyId,
- userId: input.userId,
- itemId: workItem.itemId,
- sourceDocument: "Part",
- documentId: workItem.documentId,
- versionId: workItem.versionId,
- drawingElementId: workItem.elementId,
- assetBaseName: workItem.assetBaseName
- }),
- workItem.label
- );
- return { modelUploadId: attached.modelUploadId };
- }
+): SyncOnshapeDrawingInput {
+ return {
+ companyId: input.companyId,
+ userId: input.userId,
+ itemId: workItem.itemId,
+ sourceDocument: "Part",
+ documentId: workItem.documentId,
+ versionId: workItem.versionId,
+ drawingElementId: workItem.elementId,
+ assetBaseName: workItem.assetBaseName
+ };
+}
- const attached = await withRateLimitRetry(
- () =>
- syncOnshapeElementAssetsToItem(carbon, {
- companyId: input.companyId,
- userId: input.userId,
- itemId: workItem.itemId,
- sourceDocument: "Part", // v1: released items are parts/assemblies
- documentId: workItem.documentId,
- versionId: workItem.versionId,
- modelElementId: workItem.elementId,
- modelElementKind: workItem.modelElementKind ?? "partstudio",
- partId: workItem.partId,
- configuration: workItem.configuration,
- assetBaseName: workItem.assetBaseName
- }),
- workItem.label
- );
- return { modelUploadId: attached.modelUploadId };
- } catch (syncError) {
- if (syncError instanceof OnshapeAssetTooLargeError) {
- console.warn(
- `syncOnshapeBackfillWorkItem: skipping oversized ${workItem.label}: ${syncError.message}`
- );
- return { modelUploadId: null, skippedTooLarge: true };
- }
- throw syncError;
- }
+// What a matched model exports: the `onshape-element-sync` run's input.
+export function backfillElementInput(
+ input: Pick<OnshapeBackfillInput, "companyId" | "userId">,
+ workItem: OnshapeBackfillWorkItem
+): SyncOnshapeElementInput {
+ return {
+ companyId: input.companyId,
+ userId: input.userId,
+ itemId: workItem.itemId,
+ sourceDocument: "Part", // v1: released items are parts/assemblies
+ documentId: workItem.documentId,
+ versionId: workItem.versionId,
+ modelElementId: workItem.elementId,
+ modelElementKind: workItem.modelElementKind ?? "partstudio",
+ partId: workItem.partId,
+ configuration: workItem.configuration,
+ assetBaseName: workItem.assetBaseName
+ };
}
// --- Inngest function -------------------------------------------------------
@@ -438,11 +383,12 @@ const OnshapeBackfillPayloadSchema = z.object({
export const onshapeBackfillFunction = inngest.createFunction(
{
id: "onshape-backfill",
- // Higher than the usual 3: a 429 now reschedules the run via RetryAfterError
- // (withRateLimitRetry), and that reschedule counts against this budget. A big
- // first-time backfill can hit the rate limit a few times, so give it headroom
- // to ride those out before giving up (a failed run resumes cleanly on re-run —
- // already-synced items are skipped).
+ // Higher than the usual 3: a 429 reschedules the run via RetryAfterError
+ // (withRateLimitRetry), and that reschedule counts against this budget. It
+ // covers the backfill's own listing steps; each item's export runs in the
+ // invoked onshape-element-sync / onshape-drawing-sync, which carry their own
+ // budget of 10 (a failed run resumes cleanly on re-run — already-synced
+ // items are skipped).
retries: 10,
// One backfill per company at a time — stops a double-click (or a full run
// overlapping an incremental reconcile) from racing on the "already synced"
@@ -505,10 +451,29 @@ export const onshapeBackfillFunction = inngest.createFunction(
// and keep going unless failures look systemic.
for (const [workIndex, workItem] of pageResult.workItems.entries()) {
try {
- const attached = await step.run(
- `sync-page-${pageIndex}-item-${workIndex}`,
- () => syncOnshapeBackfillWorkItem(carbon, input, workItem)
- );
+ const stepId = `sync-page-${pageIndex}-item-${workIndex}`;
+ // A model runs as its own `onshape-element-sync`: its polls,
+ // sleeps and fetch are that run's steps, not this one's.
+ const attached =
+ workItem.kind === "drawing"
+ ? await step
+ .invoke(stepId, {
+ function: onshapeDrawingSyncFunction,
+ data: backfillDrawingInput(input, workItem)
+ })
+ .then((synced) => ({
+ modelUploadId: synced.modelUploadId,
+ skippedTooLarge: synced.tooLarge
+ }))
+ : await step
+ .invoke(stepId, {
+ function: onshapeElementSyncFunction,
+ data: backfillElementInput(input, workItem)
+ })
+ .then((synced) => ({
+ modelUploadId: synced.modelUploadId,
+ skippedTooLarge: synced.tooLarge
+ }));
consecutiveFailures = 0;
if (attached.skippedTooLarge) {
totals.skippedTooLarge++;
diff --git a/packages/jobs/src/inngest/functions/integrations/onshape-element-sync.ts b/packages/jobs/src/inngest/functions/integrations/onshape-element-sync.ts
new file mode 100644
index 0000000000..a6a8f8e9bd
--- /dev/null
+++ b/packages/jobs/src/inngest/functions/integrations/onshape-element-sync.ts
@@ -0,0 +1,68 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,
+// including ports, remain AGPLv3; serving them over a network requires releasing their source.
+
+import { getCarbonServiceRole } from "@carbon/auth/client.server";
+import type { OnshapeOAuthIntegrationId } from "@carbon/ee/onshape/integration-id";
+import { inngest } from "../../client";
+import {
+ ONSHAPE_CHECKPOINTING,
+ runOnshapeDrawingSync,
+ runOnshapeElementSync
+} from "./onshape-sync-element";
+
+/**
+ * One element's export as its own run, for callers that sync many elements
+ * (the backfill `step.invoke`s it per item): each element's polls, sleeps and
+ * fetch are this run's steps, so a long backfill stays under the per-run step
+ * limit. One run per item at a time.
+ */
+export const onshapeElementSyncFunction = inngest.createFunction(
+ {
+ id: "onshape-element-sync",
+ checkpointing: ONSHAPE_CHECKPOINTING,
+ // As the backfill's: a 429 reschedules the step through RetryAfterError,
+ // and each reschedule counts against this budget.
+ retries: 10,
+ concurrency: { key: "event.data.itemId", limit: 1 }
+ },
+ { event: "carbon/onshape-element-sync" },
+ async ({ event, step }) =>
+ runOnshapeElementSync(
+ step,
+ getCarbonServiceRole(),
+ {
+ ...event.data,
+ integrationId: event.data.integrationId as
+ | OnshapeOAuthIntegrationId
+ | undefined
+ },
+ "element"
+ )
+);
+
+/** One released drawing's PDF export as its own run (the backfill
+ * `step.invoke`s it per drawing), for the same reason as the element sync. */
+export const onshapeDrawingSyncFunction = inngest.createFunction(
+ {
+ id: "onshape-drawing-sync",
+ checkpointing: ONSHAPE_CHECKPOINTING,
+ // As the backfill's: a 429 reschedules the step through RetryAfterError,
+ // and each reschedule counts against this budget.
+ retries: 10,
+ concurrency: { key: "event.data.itemId", limit: 1 }
+ },
+ { event: "carbon/onshape-drawing-sync" },
+ async ({ event, step }) =>
+ runOnshapeDrawingSync(
+ step,
+ getCarbonServiceRole(),
+ {
+ ...event.data,
+ integrationId: event.data.integrationId as
+ | OnshapeOAuthIntegrationId
+ | undefined
+ },
+ "drawing"
+ )
+);
diff --git a/packages/jobs/src/inngest/functions/integrations/onshape-fetch.test.ts b/packages/jobs/src/inngest/functions/integrations/onshape-fetch.test.ts
new file mode 100644
index 0000000000..e38ea11993
--- /dev/null
+++ b/packages/jobs/src/inngest/functions/integrations/onshape-fetch.test.ts
@@ -0,0 +1,106 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,
+// including ports, remain AGPLv3; serving them over a network requires releasing their source.
+
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import { fetchWithAssembler } from "./onshape-fetch";
+
+const mocks = vi.hoisted(() => ({
+ runAssemblerJob: vi.fn(),
+ externalDataDownload: vi.fn()
+}));
+vi.mock("@carbon/ee/onshape", () => ({
+ getOnshapeClient: vi.fn(async () => ({
+ client: { externalDataDownload: mocks.externalDataDownload }
+ }))
+}));
+vi.mock("@carbon/utils", () => ({
+ getFileSizeLimit: () => ({ bytes: 100000 })
+}));
+vi.mock("@carbon/auth/client.server", () => ({
+ getCarbonServiceRole: vi.fn()
+}));
+vi.mock("../../client", () => ({
+ inngest: { createFunction: (...args: unknown[]) => args }
+}));
+vi.mock("../tasks/assembler-client", () => {
+ class AssemblerJobError extends Error {
+ constructor(
+ message: string,
+ readonly code?: string
+ ) {
+ super(message);
+ }
+ }
+ return {
+ ASSEMBLER_CONCURRENCY: [],
+ AssemblerJobError,
+ runAssemblerJob: mocks.runAssemblerJob,
+ signUploadUrls: vi.fn(async () => ({ raw: "https://storage.test/put" }))
+ };
+});
+
+const step = { run: vi.fn(), waitForEvent: vi.fn() };
+const carbon = {
+ storage: { from: () => ({}) }
+} as unknown as Parameters<typeof fetchWithAssembler>[1];
+const input = {
+ companyId: "company",
+ userId: "user",
+ translationId: "model-t",
+ documentId: "export-document",
+ foreignId: "file-1",
+ stagedPath: "company/models/onshape-fetch-model-t.step"
+};
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ mocks.externalDataDownload.mockReturnValue({
+ url: "https://cad.onshape.test/api/v10/documents/d/export-document/externaldata/file-1",
+ authorization: "Bearer onshape-token"
+ });
+ mocks.runAssemblerJob.mockResolvedValue({
+ result: { contentHash: "xxh3-hash", outputs: { raw: { bytes: 13 } } },
+ stats: {}
+ });
+});
+
+describe("assembler fetch of an Onshape export", () => {
+ it("sends Onshape's download and bearer, capped at the upload limit", async () => {
+ expect(await fetchWithAssembler(step, carbon, input)).toEqual({
+ stagedPath: input.stagedPath,
+ size: 13,
+ contentHash: "xxh3-hash"
+ });
+ const spec = mocks.runAssemblerJob.mock.calls[0]![1];
+ expect(spec).toMatchObject({
+ action: "fetch",
+ jobId: "onshape-fetch-model-t"
+ });
+ expect(await spec.buildBody()).toEqual({
+ source: {
+ url: expect.stringContaining("/externaldata/file-1"),
+ authorization: "Bearer onshape-token"
+ },
+ maxBytes: 100000,
+ output: { path: input.stagedPath, contentType: "application/step" }
+ });
+ });
+
+ it("returns tooLarge for an export past the limit, and rethrows anything else", async () => {
+ const { AssemblerJobError } = await import("../tasks/assembler-client");
+ mocks.runAssemblerJob.mockRejectedValueOnce(
+ new AssemblerJobError("too large", "LIMIT_EXCEEDED")
+ );
+ expect(await fetchWithAssembler(step, carbon, input)).toEqual({
+ tooLarge: true
+ });
+
+ mocks.runAssemblerJob.mockRejectedValueOnce(
+ new AssemblerJobError("source unreadable", "READ_FAILED")
+ );
+ await expect(fetchWithAssembler(step, carbon, input)).rejects.toThrow(
+ "source unreadable"
+ );
+ });
+});
diff --git a/packages/jobs/src/inngest/functions/integrations/onshape-fetch.ts b/packages/jobs/src/inngest/functions/integrations/onshape-fetch.ts
new file mode 100644
index 0000000000..4762ab6f77
--- /dev/null
+++ b/packages/jobs/src/inngest/functions/integrations/onshape-fetch.ts
@@ -0,0 +1,130 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,
+// including ports, remain AGPLv3; serving them over a network requires releasing their source.
+
+import { getCarbonServiceRole } from "@carbon/auth/client.server";
+import type { Database } from "@carbon/database";
+import { getOnshapeClient } from "@carbon/ee/onshape";
+import type { OnshapeOAuthIntegrationId } from "@carbon/ee/onshape/integration-id";
+import { TEMP_STAGING_BUCKET } from "@carbon/files";
+import { getFileSizeLimit } from "@carbon/utils";
+import type { SupabaseClient } from "@supabase/supabase-js";
+import { NonRetriableError } from "inngest";
+import { inngest } from "../../client";
+import {
+ ASSEMBLER_CONCURRENCY,
+ AssemblerJobError,
+ runAssemblerJob,
+ type StepTools,
+ signUploadUrls
+} from "../tasks/assembler-client";
+
+// The raw model cap is the temp-staging cap (2.5 GB), the limit a manual
+// upload has: an export past it is skipped permanently.
+export const RAW_MODEL_MAX_BYTES = getFileSizeLimit("CAD_MODEL_UPLOAD").bytes;
+
+// How long the assembler may take to copy one export into staging.
+const FETCH_MAX_WAIT_MS = 30 * 60 * 1000;
+
+export type StagedModel = {
+ stagedPath: string;
+ size: number;
+ contentHash: string;
+};
+
+export type OnshapeFetchInput = {
+ companyId: string;
+ userId: string;
+ integrationId?: OnshapeOAuthIntegrationId;
+ translationId: string;
+ documentId: string;
+ foreignId: string;
+ stagedPath: string;
+};
+
+/**
+ * Have the assembler copy one finished Onshape translation into temp-staging
+ * (`fetch` action), so the export never passes through this process. Its
+ * own function so that it alone takes the shared assembler concurrency: the
+ * element sync that invokes it spends its other steps on Onshape.
+ */
+export async function fetchWithAssembler(
+ step: StepTools,
+ carbon: SupabaseClient<Database>,
+ input: OnshapeFetchInput
+): Promise<StagedModel | { tooLarge: true }> {
+ try {
+ const job = await runAssemblerJob(step, {
+ idPrefix: "fetch",
+ action: "fetch",
+ jobId: `onshape-fetch-${input.translationId}`,
+ maxWaitMs: FETCH_MAX_WAIT_MS,
+ logger: console,
+ // Inside the submit step, so every (re)submit sends a fresh token.
+ buildBody: async () => {
+ const onshape = await getOnshapeClient(
+ carbon,
+ input.companyId,
+ input.userId,
+ input.integrationId
+ );
+ if (onshape.error || !onshape.client) {
+ throw new Error(
+ `getOnshapeClient failed: ${onshape.error ?? "no client"}`
+ );
+ }
+ const download = onshape.client.externalDataDownload(
+ input.documentId,
+ input.foreignId
+ );
+ return {
+ source: { url: download.url, authorization: download.authorization },
+ maxBytes: RAW_MODEL_MAX_BYTES,
+ output: { path: input.stagedPath, contentType: "application/step" }
+ };
+ },
+ mintUploadUrls: () =>
+ signUploadUrls({
+ raw: {
+ bucket: carbon.storage.from(TEMP_STAGING_BUCKET),
+ path: input.stagedPath
+ }
+ })
+ });
+ const result = job.result as {
+ contentHash?: string;
+ outputs?: { raw?: { bytes?: number } };
+ } | null;
+ if (!result?.contentHash) {
+ throw new NonRetriableError("assembler fetch returned no content hash");
+ }
+ return {
+ stagedPath: input.stagedPath,
+ size: result.outputs?.raw?.bytes ?? 0,
+ contentHash: result.contentHash
+ };
+ } catch (error) {
+ // Decided here: an error class does not survive the invoke back to the
+ // caller, a returned value does.
+ if (error instanceof AssemblerJobError && error.code === "LIMIT_EXCEEDED") {
+ return { tooLarge: true };
+ }
+ throw error;
+ }
+}
+
+export const onshapeFetchFunction = inngest.createFunction(
+ {
+ id: "onshape-fetch",
+ retries: 3,
+ concurrency: ASSEMBLER_CONCURRENCY
+ },
+ { event: "carbon/onshape-fetch" },
+ async ({ event, step }) =>
+ fetchWithAssembler(step, getCarbonServiceRole(), {
+ ...event.data,
+ integrationId: event.data.integrationId as
+ | OnshapeOAuthIntegrationId
+ | undefined
+ })
+);
diff --git a/packages/jobs/src/inngest/functions/integrations/onshape-panel-sync.ts b/packages/jobs/src/inngest/functions/integrations/onshape-panel-sync.ts
index 2d070df0a2..25d0015d70 100644
--- a/packages/jobs/src/inngest/functions/integrations/onshape-panel-sync.ts
+++ b/packages/jobs/src/inngest/functions/integrations/onshape-panel-sync.ts
@@ -7,8 +7,9 @@ import { ONSHAPE_V2_INTEGRATION_ID } from "@carbon/ee/onshape/integration-id";
import { z } from "zod";
import { inngest } from "../../client";
import {
- syncOnshapeDrawingAssetsToItem,
- syncOnshapeElementAssetsToItem
+ ONSHAPE_CHECKPOINTING,
+ runOnshapeDrawingSync,
+ runOnshapeElementSync
} from "./onshape-sync-element";
/**
@@ -34,6 +35,7 @@ const OnshapePanelSyncPayloadSchema = z.object({
export const onshapePanelSyncFunction = inngest.createFunction(
{
id: "onshape-panel-sync",
+ checkpointing: ONSHAPE_CHECKPOINTING,
retries: 1,
concurrency: { key: "event.data.itemId", limit: 1 }
},
@@ -46,8 +48,10 @@ export const onshapePanelSyncFunction = inngest.createFunction(
if (elementKind === "drawing") {
// Release pushes only; no model, so no optimize or thumbnail.
- return step.run("sync-drawing-assets", () =>
- syncOnshapeDrawingAssetsToItem(carbon, {
+ return runOnshapeDrawingSync(
+ step,
+ carbon,
+ {
companyId: payload.companyId,
userId: payload.userId,
// The panel pushes on its own connection.
@@ -59,12 +63,17 @@ export const onshapePanelSyncFunction = inngest.createFunction(
sourceWvm: payload.wvm,
drawingElementId: payload.elementId,
assetBaseName: payload.assetBaseName
- })
+ },
+ "drawing"
);
}
- const result = await step.run("sync-element-assets", () =>
- syncOnshapeElementAssetsToItem(carbon, {
+ // A new model row starts its own optimise, which also renders the
+ // thumbnail; an unchanged export reuses its model.
+ return runOnshapeElementSync(
+ step,
+ carbon,
+ {
companyId: payload.companyId,
userId: payload.userId,
integrationId: ONSHAPE_V2_INTEGRATION_ID,
@@ -79,11 +88,8 @@ export const onshapePanelSyncFunction = inngest.createFunction(
modelElementId: payload.elementId,
modelElementKind: elementKind,
assetBaseName: payload.assetBaseName
- })
+ },
+ "element"
);
-
- // A new model row starts its own optimise, which also renders the
- // thumbnail; an unchanged export reuses its model.
- return result;
}
);
diff --git a/packages/jobs/src/inngest/functions/integrations/onshape-rate-limit.ts b/packages/jobs/src/inngest/functions/integrations/onshape-rate-limit.ts
new file mode 100644
index 0000000000..1335f420e0
--- /dev/null
+++ b/packages/jobs/src/inngest/functions/integrations/onshape-rate-limit.ts
@@ -0,0 +1,38 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,
+// including ports, remain AGPLv3; serving them over a network requires releasing their source.
+
+import { OnshapeApiError } from "@carbon/ee/onshape";
+import { RetryAfterError } from "inngest";
+
+const RATE_LIMIT_DEFAULT_WAIT_SECONDS = 60;
+// Clamp Onshape's Retry-After so a bad/huge value can't schedule an absurd wait.
+const RATE_LIMIT_MAX_WAIT_SECONDS = 300;
+
+// On a 429, surface it to Inngest as a RetryAfterError rather than blocking the
+// step with an in-process sleep. Inngest SUSPENDS the function — releasing its
+// compute window and the per-company concurrency slot — and reschedules it after
+// the delay; the memoized steps mean it resumes at the first unfinished item, and
+// every export/attach is idempotent so a re-run is safe. The wait honors Onshape's
+// Retry-After (default 60s), clamped to a sane maximum. Anything else rethrows.
+export async function withRateLimitRetry<T>(
+ operation: () => Promise<T>,
+ label: string
+): Promise<T> {
+ try {
+ return await operation();
+ } catch (error) {
+ if (error instanceof OnshapeApiError && error.status === 429) {
+ const waitSeconds = Math.min(
+ error.retryAfterSeconds ?? RATE_LIMIT_DEFAULT_WAIT_SECONDS,
+ RATE_LIMIT_MAX_WAIT_SECONDS
+ );
+ throw new RetryAfterError(
+ `onshape: rate limited on ${label}; retrying after ${waitSeconds}s`,
+ waitSeconds * 1000,
+ { cause: error }
+ );
+ }
+ throw error;
+ }
+}
diff --git a/packages/jobs/src/inngest/functions/integrations/onshape-revision-sync.test.ts b/packages/jobs/src/inngest/functions/integrations/onshape-revision-sync.test.ts
index 5fdd448d1f..bac64859dd 100644
--- a/packages/jobs/src/inngest/functions/integrations/onshape-revision-sync.test.ts
+++ b/packages/jobs/src/inngest/functions/integrations/onshape-revision-sync.test.ts
@@ -4,12 +4,12 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
import {
- matchOnshapeBackfillPage,
- syncOnshapeBackfillWorkItem
+ backfillElementInput,
+ matchOnshapeBackfillPage
} from "./onshape-backfill";
import {
type OnshapeRevisionSyncInput,
- runOnshapeRevisionSync
+ resolveOnshapeRevision
} from "./onshape-revision-sync";
const mocks = vi.hoisted(() => ({
@@ -30,9 +30,12 @@ vi.mock("../../client", () => ({
inngest: { createFunction: (...args: unknown[]) => args }
}));
vi.mock("./onshape-sync-element", () => ({
- syncOnshapeElementAssetsToItem: mocks.sync,
- syncOnshapeDrawingAssetsToItem: mocks.drawing
+ ONSHAPE_CHECKPOINTING: {},
+ runOnshapeElementSync: mocks.sync,
+ runOnshapeDrawingSync: mocks.drawing
}));
+vi.mock("./onshape-element-sync", () => ({ onshapeElementSyncFunction: {} }));
+vi.mock("../tasks/assembler-client", () => ({ ASSEMBLER_CONCURRENCY: [] }));
const input: OnshapeRevisionSyncInput = {
companyId: "carbon-company",
@@ -75,13 +78,14 @@ function database(
return query;
}),
in: vi.fn().mockReturnThis(),
+ ilike: vi.fn().mockReturnThis(),
maybeSingle: vi.fn(async () => ({ error: null, data: items[0] ?? null })),
then: (resolve: (value: unknown) => unknown) =>
resolve({ error: null, data: items })
};
return {
client: { from: vi.fn(() => query) } as unknown as Parameters<
- typeof runOnshapeRevisionSync
+ typeof resolveOnshapeRevision
>[0],
filters
};
@@ -100,21 +104,17 @@ beforeEach(() => {
describe("release identity", () => {
it("passes the exact released part/configuration to the existing item", async () => {
const db = database();
- expect(await runOnshapeRevisionSync(db.client, input)).toMatchObject({
- synced: true,
- itemId: "existing-item"
- });
- expect(mocks.sync).toHaveBeenCalledWith(
- db.client,
- expect.objectContaining({
+ expect(await resolveOnshapeRevision(db.client, input)).toMatchObject({
+ itemId: "existing-item",
+ element: {
itemId: "existing-item",
documentId: "document",
versionId: "version",
modelElementId: "studio",
partId: "saddle-part",
configuration: "Size=Large"
- })
- );
+ }
+ });
expect(db.filters).toContainEqual(["companyId", "carbon-company"]);
expect(db.filters).toContainEqual(["readableIdWithRevision", "SADDLE.A"]);
expect(db.filters).toContainEqual(["type", "Part"]);
@@ -134,12 +134,11 @@ describe("release identity", () => {
items: [{ ...released, ...mismatch }]
});
expect(
- await runOnshapeRevisionSync(database().client, input)
+ await resolveOnshapeRevision(database().client, input)
).toMatchObject({
synced: false,
skippedReason: "revision-not-found"
});
- expect(mocks.sync).not.toHaveBeenCalled();
}
);
@@ -148,7 +147,7 @@ describe("release identity", () => {
items: [released, { ...released, id: "other", partId: "other-part" }]
});
expect(
- await runOnshapeRevisionSync(database().client, {
+ await resolveOnshapeRevision(database().client, {
...input,
revisionId: undefined
})
@@ -156,19 +155,44 @@ describe("release identity", () => {
synced: false,
skippedReason: "ambiguous-revision"
});
- expect(mocks.sync).not.toHaveBeenCalled();
});
it("does not silently match an imported blank-revision item to revision A", async () => {
const db = database([]);
- const result = await runOnshapeRevisionSync(db.client, input);
+ const result = await resolveOnshapeRevision(db.client, input);
expect(result).toMatchObject({
synced: false,
skippedReason: "no-matching-item",
releaseKey: "SADDLE.A"
});
expect(db.filters).toContainEqual(["readableIdWithRevision", "SADDLE.A"]);
- expect(mocks.sync).not.toHaveBeenCalled();
+ });
+});
+
+describe("released drawings", () => {
+ it("resolves a drawing to the model item sharing its number, exporting nothing yet", async () => {
+ mocks.getRevisions.mockResolvedValue({
+ items: [{ ...released, partNumber: "DRW-SADDLE", elementType: 2 }]
+ });
+ const result = await resolveOnshapeRevision(
+ database([
+ {
+ id: "model-item",
+ readableIdWithRevision: "PRT-SADDLE.A",
+ modelUploadId: null
+ }
+ ]).client,
+ { ...input, partNumber: "DRW-SADDLE", elementType: 2 }
+ );
+ expect(result).toMatchObject({
+ itemId: "model-item",
+ drawing: {
+ itemId: "model-item",
+ drawingElementId: "studio",
+ assetBaseName: "PRT-SADDLE.A"
+ }
+ });
+ expect(mocks.drawing).not.toHaveBeenCalled();
});
});
@@ -213,14 +237,10 @@ describe("backfill identity", () => {
partId: "saddle-part",
configuration: "Size=Large"
});
- await syncOnshapeBackfillWorkItem(db.client, input, page.workItems[0]!);
- expect(mocks.sync).toHaveBeenCalledWith(
- db.client,
- expect.objectContaining({
- partId: "saddle-part",
- configuration: "Size=Large"
- })
- );
+ expect(backfillElementInput(input, page.workItems[0]!)).toMatchObject({
+ partId: "saddle-part",
+ configuration: "Size=Large"
+ });
});
it("does not use a full backfill to replace existing models", async () => {
diff --git a/packages/jobs/src/inngest/functions/integrations/onshape-revision-sync.ts b/packages/jobs/src/inngest/functions/integrations/onshape-revision-sync.ts
index a060bbc460..b14213cb0a 100644
--- a/packages/jobs/src/inngest/functions/integrations/onshape-revision-sync.ts
+++ b/packages/jobs/src/inngest/functions/integrations/onshape-revision-sync.ts
@@ -4,26 +4,26 @@
import { getCarbonServiceRole } from "@carbon/auth/client.server";
import type { Database } from "@carbon/database";
-import {
- getOnshapeClient,
- OnshapeAssetTooLargeError
-} from "@carbon/ee/onshape";
+import { getOnshapeClient } from "@carbon/ee/onshape";
import type { SupabaseClient } from "@supabase/supabase-js";
import { z } from "zod";
import { inngest } from "../../client";
import {
isOnshapeAssetSyncEnabled,
- resolveOnshapeCompanyId,
- withRateLimitRetry
+ resolveOnshapeCompanyId
} from "./onshape-backfill";
import {
escapeLikePattern,
releaseKey,
sharedNumberSuffix
} from "./onshape-matching";
+import { withRateLimitRetry } from "./onshape-rate-limit";
import {
- syncOnshapeDrawingAssetsToItem,
- syncOnshapeElementAssetsToItem
+ ONSHAPE_CHECKPOINTING,
+ runOnshapeDrawingSync,
+ runOnshapeElementSync,
+ type SyncOnshapeDrawingInput,
+ type SyncOnshapeElementInput
} from "./onshape-sync-element";
// Go-forward sync: one released Onshape revision ->
@@ -75,14 +75,35 @@ function modelKindForElementType(
return null;
}
-export async function runOnshapeRevisionSync(
+/** A released model to export onto the item it matched. */
+export interface OnshapeRevisionModel {
+ element: SyncOnshapeElementInput;
+ itemId: string;
+ releaseKey: string;
+}
+
+/** A released drawing to export onto the model item sharing its number. */
+export interface OnshapeRevisionDrawing {
+ drawing: SyncOnshapeDrawingInput;
+ itemId: string;
+ releaseKey?: string;
+}
+
+/**
+ * Resolve one released revision to what to do with it: a final result (a
+ * skip, or a drawing already attached), or the model to export onto its item.
+ * The export is not done here: it runs as the pipeline's own steps.
+ */
+export async function resolveOnshapeRevision(
carbon: CarbonClient,
input: OnshapeRevisionSyncInput
-): Promise<OnshapeRevisionSyncResult> {
+): Promise<
+ OnshapeRevisionSyncResult | OnshapeRevisionModel | OnshapeRevisionDrawing
+> {
const onshape = await getOnshapeClient(carbon, input.companyId, input.userId);
if (onshape.error || !onshape.client) {
throw new Error(
- `runOnshapeRevisionSync: getOnshapeClient failed: ${
+ `resolveOnshapeRevision: getOnshapeClient failed: ${
onshape.error ?? "no client"
}`
);
@@ -141,7 +162,7 @@ export async function runOnshapeRevisionSync(
.ilike("readableId", `%${escapeLikePattern(suffix)}`);
if (candidates.error) {
throw new Error(
- `runOnshapeRevisionSync: drawing item match query failed: ${candidates.error.message}`
+ `resolveOnshapeRevision: drawing item match query failed: ${candidates.error.message}`
);
}
const items = candidates.data ?? [];
@@ -160,8 +181,10 @@ export async function runOnshapeRevisionSync(
if (!target) {
return { synced: false, skippedReason: "no-matching-item" };
}
- try {
- const attached = await syncOnshapeDrawingAssetsToItem(carbon, {
+ return {
+ itemId: target.id,
+ releaseKey: target.readableIdWithRevision ?? undefined,
+ drawing: {
companyId: input.companyId,
userId: input.userId,
itemId: target.id,
@@ -170,26 +193,11 @@ export async function runOnshapeRevisionSync(
versionId: input.versionId,
drawingElementId: input.elementId,
assetBaseName: target.readableIdWithRevision ?? undefined
- });
- return {
- synced: true,
- itemId: target.id,
- modelUploadId: attached.modelUploadId,
- releaseKey: target.readableIdWithRevision ?? undefined
- };
- } catch (syncError) {
- if (syncError instanceof OnshapeAssetTooLargeError) {
- // Permanent: a retry can't shrink the export. Skip, don't fail.
- console.warn(
- `runOnshapeRevisionSync: skipping oversized drawing ${input.partNumber}: ${syncError.message}`
- );
- return { synced: false, skippedReason: "asset-too-large" };
}
- throw syncError;
- }
+ };
}
- // MODEL (elementType 0 = part studio, 1 = assembly): export compressed GLB + attach.
+ // MODEL (elementType 0 = part studio, 1 = assembly): export STEP + attach.
const modelElementKind = modelKindForElementType(input.elementType);
if (!modelElementKind) {
return { synced: false, skippedReason: "unknown-element" };
@@ -207,7 +215,7 @@ export async function runOnshapeRevisionSync(
.maybeSingle();
if (carbonItem.error) {
throw new Error(
- `runOnshapeRevisionSync: item match query failed: ${carbonItem.error.message}`
+ `resolveOnshapeRevision: item match query failed: ${carbonItem.error.message}`
);
}
if (!carbonItem.data) {
@@ -218,9 +226,10 @@ export async function runOnshapeRevisionSync(
};
}
- let attached: Awaited<ReturnType<typeof syncOnshapeElementAssetsToItem>>;
- try {
- attached = await syncOnshapeElementAssetsToItem(carbon, {
+ return {
+ itemId: carbonItem.data.id,
+ releaseKey: key,
+ element: {
companyId: input.companyId,
userId: input.userId,
itemId: carbonItem.data.id,
@@ -232,29 +241,7 @@ export async function runOnshapeRevisionSync(
partId: releasedRevision.partId,
configuration: releasedRevision.configuration,
assetBaseName: key
- });
- } catch (syncError) {
- if (syncError instanceof OnshapeAssetTooLargeError) {
- // Permanent: a retry can't shrink the export. Skip, don't fail. The
- // drawing PDF (a separate DRW element/event) still attaches normally.
- console.warn(
- `runOnshapeRevisionSync: skipping oversized model ${key}: ${syncError.message}`
- );
- return {
- synced: false,
- skippedReason: "asset-too-large",
- releaseKey: key
- };
}
- throw syncError;
- }
-
- return {
- synced: true,
- itemId: carbonItem.data.id,
- modelUploadId: attached.modelUploadId,
- thumbnailAttached: attached.thumbnailAttached,
- releaseKey: key
};
}
@@ -281,6 +268,7 @@ const OnshapeRevisionSyncPayloadSchema = z.object({
export const onshapeRevisionSyncFunction = inngest.createFunction(
{
id: "onshape-revision-sync",
+ checkpointing: ONSHAPE_CHECKPOINTING,
retries: 3,
idempotency: "event.data.messageId",
// One in-flight sync per released element; different elements run in parallel.
@@ -302,17 +290,56 @@ export const onshapeRevisionSyncFunction = inngest.createFunction(
return { skipped: true as const };
}
- // Wrap in the 429 backoff (same as the backfill's per-item syncs) so a rate
- // limit during export/poll/download backs off instead of bubbling out.
- const result = await step.run("sync-revision", () =>
+ // Wrap in the 429 backoff (same as the pipeline's own steps) so a rate
+ // limit during the lookup backs off instead of bubbling out.
+ const resolved = await step.run("resolve-revision", () =>
withRateLimitRetry(
- () => runOnshapeRevisionSync(carbon, payload),
+ () => resolveOnshapeRevision(carbon, payload),
`revision ${payload.partNumber}`
)
);
+ if ("drawing" in resolved) {
+ const attached = await runOnshapeDrawingSync(
+ step,
+ carbon,
+ resolved.drawing,
+ "drawing"
+ );
+ // An oversized PDF is permanent: a retry can't shrink the export.
+ return attached.tooLarge
+ ? { synced: false, skippedReason: "asset-too-large" as const }
+ : {
+ synced: true,
+ itemId: resolved.itemId,
+ modelUploadId: attached.modelUploadId,
+ releaseKey: resolved.releaseKey
+ };
+ }
+ if (!("element" in resolved)) return resolved;
// The sync stores the RAW Onshape export. A new model row starts the
// optimise that builds the viewer GLB and the thumbnail.
- return result;
+ const attached = await runOnshapeElementSync(
+ step,
+ carbon,
+ resolved.element,
+ "element"
+ );
+ if (attached.tooLarge) {
+ // Permanent: a retry can't shrink the export. Skip, don't fail. The
+ // drawing PDF (a separate DRW element/event) still attaches normally.
+ return {
+ synced: false,
+ skippedReason: "asset-too-large" as const,
+ releaseKey: resolved.releaseKey
+ };
+ }
+ return {
+ synced: true,
+ itemId: resolved.itemId,
+ modelUploadId: attached.modelUploadId,
+ thumbnailAttached: attached.thumbnailAttached,
+ releaseKey: resolved.releaseKey
+ };
}
);
diff --git a/packages/jobs/src/inngest/functions/integrations/onshape-sync-element.test.ts b/packages/jobs/src/inngest/functions/integrations/onshape-sync-element.test.ts
index 29bd73873b..5808677806 100644
--- a/packages/jobs/src/inngest/functions/integrations/onshape-sync-element.test.ts
+++ b/packages/jobs/src/inngest/functions/integrations/onshape-sync-element.test.ts
@@ -5,21 +5,31 @@
import { writeFile } from "node:fs/promises";
import { beforeEach, describe, expect, it, vi } from "vitest";
import type { SyncOnshapeElementInput } from "./onshape-sync-element";
-import { syncOnshapeElementAssetsToItem } from "./onshape-sync-element";
+import {
+ runOnshapeDrawingSync,
+ runOnshapeElementSync
+} from "./onshape-sync-element";
const mocks = vi.hoisted(() => ({
client: {
createPartStudioTranslation: vi.fn(),
createAssemblyTranslation: vi.fn(),
+ createDrawingTranslation: vi.fn(),
getTranslation: vi.fn(),
+ downloadExternalData: vi.fn(),
downloadExternalDataToFile: vi.fn(),
+ externalDataDownload: vi.fn(),
getElementThumbnail: vi.fn()
},
attach: vi.fn(),
- thumbnail: vi.fn()
+ thumbnail: vi.fn(),
+ assemblerEnabled: vi.fn(),
+ invoke: vi.fn(),
+ existingModel: null as { id: string; name: string } | null
}));
vi.mock("@carbon/ee/onshape", () => ({
- getOnshapeClient: vi.fn(async () => ({ client: mocks.client }))
+ getOnshapeClient: vi.fn(async () => ({ client: mocks.client })),
+ OnshapeAssetTooLargeError: class extends Error {}
}));
vi.mock("@carbon/utils", () => ({
getFileSizeLimit: () => ({ bytes: 100000 })
@@ -28,6 +38,34 @@ vi.mock("./onshape-attach", () => ({
attachOnshapeAssetsToItem: mocks.attach,
attachModelThumbnail: mocks.thumbnail
}));
+vi.mock("../tasks/assembler-client", () => ({
+ assemblerEnabled: mocks.assemblerEnabled
+}));
+vi.mock("./onshape-fetch", () => ({
+ onshapeFetchFunction: { id: "onshape-fetch" },
+ RAW_MODEL_MAX_BYTES: 100000
+}));
+
+// Runs each step at once, in order: the pipeline's logic, not Inngest's.
+const step = {
+ run: async (_id: string, fn: () => unknown) => fn(),
+ sleep: vi.fn(async () => undefined),
+ invoke: mocks.invoke
+};
+
+const carbon = {
+ from: () => {
+ const query = {
+ select: () => query,
+ eq: () => query,
+ maybeSingle: async () => ({ data: mocks.existingModel, error: null })
+ };
+ return query;
+ },
+ storage: {
+ from: () => ({ upload: vi.fn(async () => ({ data: {}, error: null })) })
+ }
+} as unknown as Parameters<typeof runOnshapeElementSync>[1];
const input = {
companyId: "company",
@@ -42,49 +80,70 @@ const input = {
configuration: "Size=Large;Finish=Matte",
assetBaseName: "SADDLE.A"
} as const;
-const carbon = {} as Parameters<typeof syncOnshapeElementAssetsToItem>[0];
+
+const sync = (args: SyncOnshapeElementInput = input) =>
+ runOnshapeElementSync(step, carbon, args, "element");
beforeEach(() => {
vi.clearAllMocks();
- mocks.client.createPartStudioTranslation.mockResolvedValue({
- id: "translation"
- });
- mocks.client.createAssemblyTranslation.mockResolvedValue({
- id: "translation"
- });
- mocks.client.getTranslation.mockResolvedValue({
- id: "translation",
+ mocks.existingModel = null;
+ mocks.assemblerEnabled.mockReturnValue(false);
+ mocks.client.createPartStudioTranslation.mockResolvedValue({ id: "model-t" });
+ mocks.client.createAssemblyTranslation.mockResolvedValue({ id: "model-t" });
+ mocks.client.createDrawingTranslation.mockImplementation(
+ async (_d: string, _v: string, elementId: string) => ({
+ id: `drawing-${elementId}`
+ })
+ );
+ mocks.client.getTranslation.mockImplementation(async (id: string) => ({
+ id,
requestState: "DONE",
resultDocumentId: "export-document",
- resultExternalDataIds: ["file"]
- });
+ resultExternalDataIds: [`file-${id}`]
+ }));
mocks.client.downloadExternalDataToFile.mockImplementation(
- async (_document, _file, path) => writeFile(path, "selected geometry")
+ async (_document: string, _file: string, path: string) =>
+ writeFile(path, "ISO-10303-21;")
);
+ mocks.client.downloadExternalData.mockResolvedValue(new ArrayBuffer(4));
+ mocks.client.externalDataDownload.mockReturnValue({
+ url: "https://cad.onshape.test/api/v10/documents/d/export-document/externaldata/file",
+ authorization: "Bearer onshape-token"
+ });
mocks.client.getElementThumbnail.mockResolvedValue(new ArrayBuffer(1));
mocks.attach.mockResolvedValue({
modelUploadId: "new-model",
- documentIds: []
+ documentIds: [],
+ preservedPriorModelAsDocument: false
});
});
+const attachedModel = () => mocks.attach.mock.calls.at(-1)![1].model;
+
describe("released model exports", () => {
- it("exports only the released part in its released configuration", async () => {
- await syncOnshapeElementAssetsToItem(carbon, input);
+ it("exports only the released part, in its configuration, as STEP", async () => {
+ await sync();
expect(mocks.client.createPartStudioTranslation).toHaveBeenCalledWith(
input.documentId,
input.versionId,
input.modelElementId,
expect.objectContaining({
+ formatName: "STEP",
partIds: "saddle-only",
configuration: input.configuration
})
);
expect(mocks.client.createAssemblyTranslation).not.toHaveBeenCalled();
+ // A STEP raw is what lets an assembly instruction convert the model.
+ expect(attachedModel()).toMatchObject({
+ fileName: "SADDLE.A.step",
+ stagedPath: "company/models/onshape-fetch-model-t.step",
+ contentHash: expect.stringMatching(/^sha256:[0-9a-f]{64}$/)
+ });
});
it("never attaches a whole-studio thumbnail to a part", async () => {
- const result = await syncOnshapeElementAssetsToItem(carbon, input);
+ const result = await sync();
expect(mocks.client.getElementThumbnail).not.toHaveBeenCalled();
expect(mocks.thumbnail).not.toHaveBeenCalled();
expect(result.thumbnailAttached).toBe(false);
@@ -97,21 +156,18 @@ describe("released model exports", () => {
...input,
partId
} as unknown as SyncOnshapeElementInput;
- await expect(
- syncOnshapeElementAssetsToItem(carbon, invalid)
- ).rejects.toThrow(/part/i);
+ await expect(sync(invalid)).rejects.toThrow(/part/i);
expect(mocks.client.createPartStudioTranslation).not.toHaveBeenCalled();
expect(mocks.attach).not.toHaveBeenCalled();
}
);
it("keeps whole-assembly exports and forwards their configuration", async () => {
- const assembly = {
+ const result = await sync({
...input,
- modelElementKind: "assembly" as const,
+ modelElementKind: "assembly",
partId: undefined
- };
- const result = await syncOnshapeElementAssetsToItem(carbon, assembly);
+ });
expect(mocks.client.createAssemblyTranslation).toHaveBeenCalledWith(
input.documentId,
input.versionId,
@@ -125,7 +181,7 @@ describe("released model exports", () => {
});
it("retains the inexpensive element thumbnail for an unconfigured assembly", async () => {
- const result = await syncOnshapeElementAssetsToItem(carbon, {
+ const result = await sync({
...input,
modelElementKind: "assembly",
partId: undefined,
@@ -142,7 +198,7 @@ describe("released model exports", () => {
{ ...input, partId: "other-part" },
{ ...input, configuration: "Size=Small" }
]) {
- await syncOnshapeElementAssetsToItem(carbon, variation);
+ await sync(variation);
}
const ids = mocks.attach.mock.calls.map(([, args]) => args.model.sourceId);
expect(ids[0]).toEqual(expect.any(String));
@@ -151,17 +207,13 @@ describe("released model exports", () => {
});
it("gives a workspace export a new generation when the part changes", async () => {
- const workspace = {
- ...input,
- sourceWvm: "w" as const,
- versionId: "workspace-1"
- };
+ const workspace = { ...input, sourceWvm: "w" as const, versionId: "ws-1" };
for (const variation of [
{ ...workspace, sourceMicroversionId: "mv-1" },
{ ...workspace, sourceMicroversionId: "mv-1" },
{ ...workspace, sourceMicroversionId: "mv-2" }
]) {
- await syncOnshapeElementAssetsToItem(carbon, variation);
+ await sync(variation);
}
const ids = mocks.attach.mock.calls.map(([, args]) => args.model.sourceId);
expect(ids[0]).toBe(ids[1]);
@@ -169,12 +221,120 @@ describe("released model exports", () => {
});
it("gives a workspace export with no microversion no fixed generation", async () => {
- await syncOnshapeElementAssetsToItem(carbon, {
- ...input,
- sourceWvm: "w",
- versionId: "workspace-1"
+ await sync({ ...input, sourceWvm: "w", versionId: "ws-1" });
+ expect(attachedModel().sourceId).toBeUndefined();
+ });
+});
+
+describe("export economy", () => {
+ it("skips the export entirely when this source's model already exists", async () => {
+ mocks.existingModel = { id: "onshape-existing", name: "SADDLE.A.step" };
+ await sync();
+ expect(mocks.client.createPartStudioTranslation).not.toHaveBeenCalled();
+ expect(mocks.client.downloadExternalDataToFile).not.toHaveBeenCalled();
+ expect(mocks.attach.mock.calls[0]![1]).toMatchObject({
+ existingModelId: "onshape-existing"
});
- const ids = mocks.attach.mock.calls.map(([, args]) => args.model.sourceId);
- expect(ids).toEqual([undefined]);
+ });
+
+ it("starts the drawing translations with the model's, before waiting on any", async () => {
+ await sync({ ...input, drawingElementIds: ["drw-1", "drw-2"] });
+ const firstPoll = mocks.client.getTranslation.mock.invocationCallOrder[0]!;
+ for (const create of [
+ mocks.client.createPartStudioTranslation,
+ mocks.client.createDrawingTranslation
+ ]) {
+ for (const order of create.mock.invocationCallOrder) {
+ expect(order).toBeLessThan(firstPoll);
+ }
+ }
+ expect(mocks.client.createDrawingTranslation).toHaveBeenCalledTimes(2);
+ });
+
+ it("sleeps between polls while a translation is still running", async () => {
+ mocks.client.getTranslation
+ .mockResolvedValueOnce({ id: "model-t", requestState: "ACTIVE" })
+ .mockResolvedValueOnce({ id: "model-t", requestState: "ACTIVE" });
+ await sync();
+ expect(step.sleep).toHaveBeenCalledTimes(2);
+ expect(mocks.attach).toHaveBeenCalledOnce();
+ });
+});
+
+describe("with the assembler", () => {
+ beforeEach(() => {
+ mocks.assemblerEnabled.mockReturnValue(true);
+ mocks.invoke.mockResolvedValue({
+ stagedPath: "company/models/onshape-fetch-model-t.step",
+ size: 13,
+ contentHash: "xxh3-hash"
+ });
+ });
+
+ it("hands the fetch to its own run; nothing is downloaded here", async () => {
+ await sync();
+ expect(mocks.client.downloadExternalDataToFile).not.toHaveBeenCalled();
+ expect(mocks.invoke).toHaveBeenCalledWith("element-fetch", {
+ function: { id: "onshape-fetch" },
+ data: expect.objectContaining({
+ translationId: "model-t",
+ documentId: "export-document",
+ foreignId: "file-model-t",
+ stagedPath: "company/models/onshape-fetch-model-t.step"
+ })
+ });
+ expect(attachedModel()).toMatchObject({
+ size: 13,
+ contentHash: "xxh3-hash"
+ });
+ });
+
+ it("skips an export the fetch found past the upload limit", async () => {
+ mocks.invoke.mockResolvedValue({ tooLarge: true });
+ const result = await sync();
+ expect(result.tooLarge).toBe(true);
+ expect(mocks.attach).not.toHaveBeenCalled();
+ });
+});
+
+describe("released drawing exports", () => {
+ const drawing = {
+ companyId: "company",
+ userId: "user",
+ itemId: "saddle-item",
+ sourceDocument: "Part" as const,
+ documentId: "released-document",
+ versionId: "released-version",
+ drawingElementId: "drw-1",
+ assetBaseName: "SADDLE.A"
+ };
+
+ it("translates, waits with step.sleep, then attaches the PDF", async () => {
+ mocks.client.getTranslation.mockResolvedValueOnce({
+ id: "drawing-drw-1",
+ requestState: "ACTIVE"
+ });
+ await runOnshapeDrawingSync(step, carbon, drawing, "drawing");
+ expect(mocks.client.createDrawingTranslation).toHaveBeenCalledOnce();
+ expect(step.sleep).toHaveBeenCalledOnce();
+ expect(mocks.attach.mock.calls[0]![1]).toMatchObject({
+ itemId: "saddle-item",
+ documents: [{ fileName: "SADDLE.A.pdf" }]
+ });
+ });
+
+ it("skips a PDF past the document limit without failing", async () => {
+ const { OnshapeAssetTooLargeError } = await import("@carbon/ee/onshape");
+ mocks.client.downloadExternalData.mockRejectedValue(
+ new OnshapeAssetTooLargeError("too large")
+ );
+ const result = await runOnshapeDrawingSync(
+ step,
+ carbon,
+ drawing,
+ "drawing"
+ );
+ expect(result.tooLarge).toBe(true);
+ expect(mocks.attach).not.toHaveBeenCalled();
});
});
diff --git a/packages/jobs/src/inngest/functions/integrations/onshape-sync-element.ts b/packages/jobs/src/inngest/functions/integrations/onshape-sync-element.ts
index 3e9c281812..fb9fc63d27 100644
--- a/packages/jobs/src/inngest/functions/integrations/onshape-sync-element.ts
+++ b/packages/jobs/src/inngest/functions/integrations/onshape-sync-element.ts
@@ -3,27 +3,39 @@
// including ports, remain AGPLv3; serving them over a network requires releasing their source.
import { createHash } from "node:crypto";
+import { openAsBlob } from "node:fs";
import { mkdtemp, rm, stat } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
import type { Database } from "@carbon/database";
import type { OnshapeClient, OnshapeTranslation } from "@carbon/ee/onshape";
-import { getOnshapeClient } from "@carbon/ee/onshape";
+import {
+ getOnshapeClient,
+ OnshapeAssetTooLargeError
+} from "@carbon/ee/onshape";
import type { OnshapeOAuthIntegrationId } from "@carbon/ee/onshape/integration-id";
+import { TEMP_STAGING_BUCKET } from "@carbon/files";
import { getFileSizeLimit } from "@carbon/utils";
import type { SupabaseClient } from "@supabase/supabase-js";
+import { NonRetriableError } from "inngest";
+import { assemblerEnabled } from "../tasks/assembler-client";
import {
type AttachOnshapeAssetsResult,
attachModelThumbnail,
- attachOnshapeAssetsToItem,
- type OnshapeModelFile
+ attachOnshapeAssetsToItem
} from "./onshape-attach";
+import {
+ type OnshapeFetchInput,
+ onshapeFetchFunction,
+ RAW_MODEL_MAX_BYTES,
+ type StagedModel
+} from "./onshape-fetch";
+import { withRateLimitRetry } from "./onshape-rate-limit";
-// Export→download→attach for ONE Onshape element, released or in a workspace.
-// Wires the OnshapeClient export methods (@carbon/ee) to the Carbon-side attach
-// helper. Flow: create translation -> poll to DONE -> download from
-// resultDocumentId/resultExternalDataIds -> attach. Poll-with-backoff (real
-// completions take seconds); no translation.complete webhook needed.
+// Export→stage→attach for ONE Onshape element, released or in a workspace
+// (`runOnshapeElementSync`), and the PDF export of one released drawing.
+// Poll-with-backoff (real completions take seconds); no translation.complete
+// webhook needed.
//
// Callers (the release-sync and backfill jobs, and onshape-panel-sync) resolve
// itemId and the documentId/version-or-workspace/elementId of the geometry,
@@ -63,255 +75,511 @@ const POLL_MAX_DELAY_MS = 15000;
// cap is the temp-staging cap (2.5GB); exports past it are skipped permanently
// (drawing PDFs still attach — they are separate elements). Output size is the
// assembler's problem, not ours.
-const RAW_MODEL_MAX_BYTES = getFileSizeLimit("CAD_MODEL_UPLOAD").bytes;
const DOCUMENT_MAX_BYTES = getFileSizeLimit("DOCUMENT_UPLOAD").bytes;
-async function waitForTranslation(
- client: OnshapeClient,
- translationId: string
-): Promise<OnshapeTranslation> {
- let delay = POLL_INITIAL_DELAY_MS;
- for (let attempt = 0; attempt < POLL_MAX_ATTEMPTS; attempt++) {
- const translation = await client.getTranslation(translationId);
- if (translation.requestState === "DONE") {
- return translation;
+/**
+ * Checkpointing for the functions that run this pipeline: consecutive steps
+ * (existing → translate → first poll; drawings → attach → thumbnail) run in
+ * one request instead of a round trip each. Every step here is a short Onshape
+ * call or storage move. `maxRuntime` is far below the ERP's 300 s Vercel limit
+ * because a step that starts at the end of the window gets only the rest of
+ * the request: at 60 s a late step still has ~240 s. Not set client-wide,
+ * where single steps run for minutes (MRP per company, backups).
+ */
+export const ONSHAPE_CHECKPOINTING = { maxRuntime: "60s" } as const;
+
+/** The Inngest step tools the pipeline needs. */
+export type ElementSyncStep = {
+ run: (id: string, fn: () => unknown) => Promise<any>;
+ sleep: (id: string, duration: number) => Promise<unknown>;
+ invoke: (
+ id: string,
+ opts: { function: typeof onshapeFetchFunction; data: OnshapeFetchInput }
+ ) => Promise<any>;
+};
+
+export type ElementSyncResult = AttachOnshapeAssetsResult & {
+ thumbnailAttached: boolean;
+ /** The export is past Carbon's upload limit: a permanent skip, not a fault. */
+ tooLarge?: boolean;
+};
+
+/** A translation Onshape finished: where its result downloads from. */
+type FinishedTranslation = {
+ id: string;
+ documentId: string;
+ foreignId: string;
+ name: string | null;
+};
+
+/**
+ * Export one element's model (and any drawings) from Onshape onto an item, as
+ * resumable steps:
+ *
+ * 1. `existing` — a released part's model id is known before any export; when
+ * that model already exists the export is skipped entirely.
+ * 2. `translate` — start the model and every drawing translation at once.
+ * 3. `poll-n` / `sleep-n` — wait for all of them; nothing holds a function
+ * between polls.
+ * 4. `fetch` — the assembler copies the STEP straight from Onshape into
+ * temp-staging (`fetch` action), so the export never passes through this
+ * process. With no assembler configured, one step downloads and stages it.
+ * 5. `drawings` — download and attach the PDFs.
+ * 6. `attach` — move the staged STEP to its model key, insert the
+ * `modelUpload` row (which starts the optimise) and link the item.
+ * 7. `thumbnail` — Onshape's own thumbnail, for an unconfigured assembly.
+ *
+ * A retry resumes at the step that failed, so a late failure never re-runs a
+ * translation (Onshape's API quota is yearly). Step ids are namespaced by
+ * `prefix`. The STEP is what a manual upload is: the assembler builds the
+ * viewer GLB, compaction keeps the original in the company bucket, and an
+ * assembly instruction can convert and plan it.
+ */
+export async function runOnshapeElementSync(
+ step: ElementSyncStep,
+ carbon: CarbonClient,
+ input: SyncOnshapeElementInput,
+ prefix: string
+): Promise<ElementSyncResult> {
+ const label = input.assetBaseName ?? input.modelElementId;
+
+ const planned: {
+ sourceId: string | null;
+ existing: { id: string; name: string | null } | null;
+ } = await step.run(`${prefix}-existing`, async () => {
+ assertSelection(input);
+ const sourceId = partSourceId(input);
+ if (!sourceId) return { sourceId: null, existing: null };
+ const row = await carbon
+ .from("modelUpload")
+ .select("id, name")
+ .eq("id", sourceId)
+ .eq("companyId", input.companyId)
+ .maybeSingle();
+ if (row.error) {
+ throw new Error(`existing model lookup failed: ${row.error.message}`);
}
- if (translation.requestState === "FAILED") {
- throw new Error(
- `Onshape translation ${translationId} FAILED: ${
- translation.failureReason ?? "unknown"
- }`
- );
+ return {
+ sourceId,
+ existing: row.data ? { id: row.data.id, name: row.data.name } : null
+ };
+ });
+
+ const started: {
+ model: string | null;
+ drawings: { elementId: string; id: string }[];
+ } = await step.run(`${prefix}-translate`, () =>
+ withRateLimitRetry(async () => {
+ const client = await onshapeClient(carbon, input);
+ const [model, drawings] = await Promise.all([
+ planned.existing ? null : startModelTranslation(client, input),
+ Promise.all(
+ (input.drawingElementIds ?? []).map(async (elementId) => ({
+ elementId,
+ id: (
+ await client.createDrawingTranslation(
+ input.documentId,
+ input.versionId,
+ elementId,
+ {
+ formatName: "PDF",
+ storeInDocument: false,
+ wvm: input.sourceWvm ?? "v"
+ }
+ )
+ ).id
+ }))
+ )
+ ]);
+ return { model: model?.id ?? null, drawings };
+ }, `translate ${label}`)
+ );
+
+ const finished = await waitForTranslations(
+ step,
+ carbon,
+ input,
+ label,
+ prefix,
+ [started.model, ...started.drawings.map((d) => d.id)].flatMap((id) =>
+ id ? [id] : []
+ )
+ );
+
+ const modelTranslation = started.model ? finished[started.model] : null;
+ const baseName =
+ input.assetBaseName ??
+ modelTranslation?.name ??
+ planned.existing?.name?.replace(/\.step$/i, "") ??
+ "model";
+
+ let staged: StagedModel | null = null;
+ if (modelTranslation) {
+ const stagedPath = `${input.companyId}/models/onshape-fetch-${modelTranslation.id}.step`;
+ // The fetch runs as its own `onshape-fetch` run: it alone holds the
+ // shared assembler concurrency, not this run's Onshape polls.
+ const fetched: StagedModel | { tooLarge: true } = assemblerEnabled()
+ ? await step.invoke(`${prefix}-fetch`, {
+ function: onshapeFetchFunction,
+ data: {
+ companyId: input.companyId,
+ userId: input.userId,
+ integrationId: input.integrationId,
+ translationId: modelTranslation.id,
+ documentId: modelTranslation.documentId,
+ foreignId: modelTranslation.foreignId,
+ stagedPath
+ }
+ })
+ : await step.run(`${prefix}-download`, () =>
+ withRateLimitRetry(
+ () =>
+ downloadToStaging(carbon, input, modelTranslation, stagedPath),
+ `download ${label}`
+ )
+ );
+ if ("tooLarge" in fetched) {
+ console.warn(`onshape sync: skipping oversized model ${label}`);
+ return {
+ modelUploadId: null,
+ documentIds: [],
+ preservedPriorModelAsDocument: false,
+ thumbnailAttached: false,
+ tooLarge: true
+ };
}
- await new Promise((resolve) => setTimeout(resolve, delay));
- delay = Math.min(delay * 1.5, POLL_MAX_DELAY_MS);
+ staged = fetched;
}
- throw new Error(
- `Onshape translation ${translationId} did not finish after ${POLL_MAX_ATTEMPTS} polls`
+
+ const drawingDocumentIds: string[] =
+ started.drawings.length === 0
+ ? []
+ : await step.run(`${prefix}-drawings`, () =>
+ withRateLimitRetry(async () => {
+ const client = await onshapeClient(carbon, input);
+ const documents = (
+ await Promise.all(
+ started.drawings.map(async ({ elementId, id }) => {
+ const pdf = await downloadPdf(client, finished[id]!);
+ return pdf
+ ? [{ fileName: `${baseName}-${elementId}.pdf`, bytes: pdf }]
+ : [];
+ })
+ )
+ ).flat();
+ if (documents.length === 0) return [];
+ const attached = await attachOnshapeAssetsToItem(carbon, {
+ companyId: input.companyId,
+ createdBy: input.userId,
+ itemId: input.itemId,
+ sourceDocument: input.sourceDocument,
+ documents
+ });
+ return attached.documentIds;
+ }, `drawings ${label}`)
+ );
+
+ const attached: AttachOnshapeAssetsResult = await step.run(
+ `${prefix}-attach`,
+ () =>
+ attachOnshapeAssetsToItem(carbon, {
+ companyId: input.companyId,
+ createdBy: input.userId,
+ itemId: input.itemId,
+ sourceDocument: input.sourceDocument,
+ ...(staged
+ ? {
+ model: {
+ fileName: `${baseName}.step`,
+ ...staged,
+ sourceId: planned.sourceId ?? undefined
+ }
+ }
+ : { existingModelId: planned.existing!.id })
+ })
);
+
+ // The element-thumbnail endpoint cannot select a part or configuration.
+ // Keep it only for a new model of an unconfigured assembly. All other
+ // thumbnails are rendered from the selected model by the optimise itself.
+ const thumbnailAttached: boolean =
+ attached.modelUploadId !== null &&
+ staged !== null &&
+ input.modelElementKind === "assembly" &&
+ (!input.configuration || input.configuration.toLowerCase() === "default")
+ ? await step.run(`${prefix}-thumbnail`, () =>
+ attachOnshapeThumbnail(carbon, input, attached.modelUploadId!, label)
+ )
+ : false;
+
+ return {
+ ...attached,
+ documentIds: [...drawingDocumentIds, ...attached.documentIds],
+ thumbnailAttached
+ };
}
-async function downloadTranslationBytes(
- client: OnshapeClient,
- translation: OnshapeTranslation,
- maxBytes: number
-): Promise<Uint8Array> {
- const foreignId = translation.resultExternalDataIds?.[0];
- const documentId = translation.resultDocumentId;
- if (!foreignId || !documentId) {
- throw new Error(
- `Onshape translation ${translation.id} DONE but has no resultExternalDataIds/resultDocumentId`
- );
+/** Who the Onshape calls are made as. */
+type OnshapeCredentials = Pick<
+ SyncOnshapeElementInput,
+ "companyId" | "userId" | "integrationId"
+>;
+
+async function onshapeClient(
+ carbon: CarbonClient,
+ input: OnshapeCredentials
+): Promise<OnshapeClient> {
+ const onshape = await getOnshapeClient(
+ carbon,
+ input.companyId,
+ input.userId,
+ input.integrationId
+ );
+ if (onshape.error || !onshape.client) {
+ throw new Error(`getOnshapeClient failed: ${onshape.error ?? "no client"}`);
}
- // Throws OnshapeAssetTooLargeError past the cap — callers treat that as a
- // permanent skip (retrying cannot shrink the asset).
- const buffer = await client.downloadExternalData(documentId, foreignId, {
- maxBytes
- });
- return new Uint8Array(buffer);
+ return onshape.client;
}
-// The one and only model export path: export GLTF from Onshape and stream it
-// to disk (a whole-vehicle export can be >1.5GB — it is never buffered in
-// memory). The raw export is attached as-is; the assembler pipeline
-// ("carbon/model-optimize", started by the new model row) turns it into the
-// meshopt-compressed viewer GLB, so no local compression happens here. STEP
-// export was deliberately dropped: real assemblies produce multi-GB STEP
-// files, and Onshape stays the CAD system of record. Throws
-// OnshapeAssetTooLargeError (from the download helper) past the raw cap;
-// callers treat that as a permanent skip.
-async function exportRawGltfModel(
- client: OnshapeClient,
- input: SyncOnshapeElementInput,
- scratchDir: string
-): Promise<OnshapeModelFile> {
- // Missing selection previously exported the entire studio. Fail closed:
- // a release asset is one part, never an implicit list or whole-studio export.
+// Missing selection previously exported the entire studio. Fail closed: a
+// release asset is one part, never an implicit list or whole-studio export.
+function assertSelection(input: SyncOnshapeElementInput) {
if (
input.modelElementKind === "partstudio" &&
(typeof input.partId !== "string" ||
!input.partId.trim() ||
/[,\s]/.test(input.partId))
) {
- throw new Error(
+ throw new NonRetriableError(
"An individual Onshape release requires exactly one partId"
);
}
if (input.configuration != null && typeof input.configuration !== "string") {
- throw new Error("Invalid released Onshape configuration");
+ throw new NonRetriableError("Invalid released Onshape configuration");
}
- const configuration = input.configuration ?? undefined;
- const gltfTranslation =
- input.modelElementKind === "assembly"
- ? await client.createAssemblyTranslation(
- input.documentId,
- input.versionId,
- input.modelElementId,
- {
- formatName: "GLTF",
- storeInDocument: false,
- configuration,
- wvm: input.sourceWvm ?? "v"
- }
- )
- : await client.createPartStudioTranslation(
- input.documentId,
- input.versionId,
- input.modelElementId,
- {
- formatName: "GLTF",
- storeInDocument: false,
- configuration,
- partIds: input.partId!,
- wvm: input.sourceWvm ?? "v"
- }
- );
- const gltfDone = await waitForTranslation(client, gltfTranslation.id);
- const baseName =
- input.assetBaseName ??
- (typeof gltfDone.name === "string" ? gltfDone.name : "model");
- const foreignId = gltfDone.resultExternalDataIds?.[0];
- const resultDocumentId = gltfDone.resultDocumentId;
- if (!foreignId || !resultDocumentId) {
- throw new Error(
- `Onshape GLTF translation ${gltfDone.id} DONE but has no resultExternalDataIds/resultDocumentId`
+}
+
+// Immutable generation: old optimizer/thumbnail/compact jobs can only finish
+// against their old model ID. Replays of this exact released source share one
+// ID; a different part/configuration cannot reuse its artifacts. A whole
+// assembly, or a workspace part with no microversion, has no fixed source to
+// name; the attach names it by its bytes instead. The tag changed with the
+// export format: a GLTF generation of the same source already holds the
+// "selected-part-v1" id, and reusing it would fail the attach's identity check.
+export function partSourceId(input: SyncOnshapeElementInput): string | null {
+ if (
+ input.modelElementKind !== "partstudio" ||
+ (input.sourceWvm === "w" && !input.sourceMicroversionId)
+ ) {
+ return null;
+ }
+ return `onshape-${createHash("sha256")
+ .update(
+ JSON.stringify([
+ "selected-part-step-v1",
+ input.companyId,
+ input.itemId,
+ input.documentId,
+ input.versionId,
+ input.modelElementId,
+ input.partId,
+ input.configuration ?? "",
+ ...(input.sourceWvm === "w" ? [input.sourceMicroversionId] : [])
+ ])
+ )
+ .digest("hex")
+ .slice(0, 40)}`;
+}
+
+function startModelTranslation(
+ client: OnshapeClient,
+ input: SyncOnshapeElementInput
+) {
+ const options = {
+ formatName: "STEP" as const,
+ storeInDocument: false,
+ configuration: input.configuration ?? undefined,
+ wvm: input.sourceWvm ?? "v"
+ };
+ return input.modelElementKind === "assembly"
+ ? client.createAssemblyTranslation(
+ input.documentId,
+ input.versionId,
+ input.modelElementId,
+ options
+ )
+ : client.createPartStudioTranslation(
+ input.documentId,
+ input.versionId,
+ input.modelElementId,
+ { ...options, partIds: input.partId! }
+ );
+}
+
+/** Poll every translation together until all are done, sleeping (as a step,
+ * holding nothing) between polls. A failed translation fails the sync. */
+async function waitForTranslations(
+ step: Pick<ElementSyncStep, "run" | "sleep">,
+ carbon: CarbonClient,
+ input: OnshapeCredentials,
+ label: string,
+ prefix: string,
+ ids: string[]
+): Promise<Record<string, FinishedTranslation>> {
+ const finished: Record<string, FinishedTranslation> = {};
+ let delay = POLL_INITIAL_DELAY_MS;
+ for (let attempt = 0; ; attempt++) {
+ const waiting = ids.filter((id) => !finished[id]);
+ if (waiting.length === 0) return finished;
+ if (attempt >= POLL_MAX_ATTEMPTS) {
+ throw new NonRetriableError(
+ `Onshape translations ${waiting.join(", ")} did not finish after ${POLL_MAX_ATTEMPTS} polls`
+ );
+ }
+ const polled: (FinishedTranslation | null)[] = await step.run(
+ `${prefix}-poll-${attempt}`,
+ () =>
+ withRateLimitRetry(async () => {
+ const client = await onshapeClient(carbon, input);
+ return Promise.all(
+ waiting.map(async (id) =>
+ finishedTranslation(await client.getTranslation(id))
+ )
+ );
+ }, `poll ${label}`)
);
+ for (const translation of polled) {
+ if (translation) finished[translation.id] = translation;
+ }
+ if (ids.every((id) => finished[id])) return finished;
+ await step.sleep(`${prefix}-sleep-${attempt}`, delay);
+ delay = Math.min(delay * 1.5, POLL_MAX_DELAY_MS);
}
+}
- const gltfPath = join(scratchDir, "model.gltf");
- await client.downloadExternalDataToFile(
- resultDocumentId,
- foreignId,
- gltfPath,
- { maxBytes: RAW_MODEL_MAX_BYTES }
- );
- const { size } = await stat(gltfPath);
+function finishedTranslation(
+ translation: OnshapeTranslation
+): FinishedTranslation | null {
+ if (translation.requestState === "FAILED") {
+ throw new NonRetriableError(
+ `Onshape translation ${translation.id} FAILED: ${translation.failureReason ?? "unknown"}`
+ );
+ }
+ if (translation.requestState !== "DONE") return null;
+ const foreignId = translation.resultExternalDataIds?.[0];
+ const documentId = translation.resultDocumentId;
+ if (!foreignId || !documentId) {
+ throw new NonRetriableError(
+ `Onshape translation ${translation.id} DONE but has no resultExternalDataIds/resultDocumentId`
+ );
+ }
return {
- fileName: `${baseName}.gltf`,
- localPath: gltfPath,
- size,
- // Immutable generation: old optimizer/thumbnail/compact jobs can only
- // finish against their old model ID. Replays of this exact released source
- // share one ID; a different part/configuration cannot reuse its artifacts.
- // A whole assembly, or a workspace part with no microversion, has no fixed
- // source to name; the attach names it by its bytes instead.
- sourceId:
- input.modelElementKind === "partstudio" &&
- (input.sourceWvm !== "w" || input.sourceMicroversionId)
- ? `onshape-${createHash("sha256")
- .update(
- JSON.stringify([
- "selected-part-v1",
- input.companyId,
- input.itemId,
- input.documentId,
- input.versionId,
- input.modelElementId,
- input.partId,
- configuration ?? "",
- ...(input.sourceWvm === "w" ? [input.sourceMicroversionId] : [])
- ])
- )
- .digest("hex")
- .slice(0, 40)}`
- : undefined
+ id: translation.id,
+ documentId,
+ foreignId,
+ name: typeof translation.name === "string" ? translation.name : null
};
}
-export async function syncOnshapeElementAssetsToItem(
+/** No assembler configured: download the export here and stage it. Hashes the
+ * bytes as they are read back for the upload, so the file is read once. */
+async function downloadToStaging(
carbon: CarbonClient,
- input: SyncOnshapeElementInput
-): Promise<AttachOnshapeAssetsResult & { thumbnailAttached: boolean }> {
- const onshape = await getOnshapeClient(
- carbon,
- input.companyId,
- input.userId,
- input.integrationId
- );
- if (onshape.error || !onshape.client) {
- throw new Error(`getOnshapeClient failed: ${onshape.error ?? "no client"}`);
+ input: SyncOnshapeElementInput,
+ translation: FinishedTranslation,
+ stagedPath: string
+): Promise<StagedModel | { tooLarge: true }> {
+ const client = await onshapeClient(carbon, input);
+ const scratchDir = await mkdtemp(join(tmpdir(), "onshape-step-"));
+ try {
+ const localPath = join(scratchDir, "model.step");
+ try {
+ await client.downloadExternalDataToFile(
+ translation.documentId,
+ translation.foreignId,
+ localPath,
+ { maxBytes: RAW_MODEL_MAX_BYTES }
+ );
+ } catch (error) {
+ if (error instanceof OnshapeAssetTooLargeError) return { tooLarge: true };
+ throw error;
+ }
+ const { size } = await stat(localPath);
+ const hash = createHash("sha256");
+ const blob = await openAsBlob(localPath, { type: "application/step" });
+ const reader = blob.stream().getReader();
+ for (
+ let read = await reader.read();
+ !read.done;
+ read = await reader.read()
+ ) {
+ hash.update(read.value);
+ }
+ const uploaded = await carbon.storage
+ .from(TEMP_STAGING_BUCKET)
+ .upload(stagedPath, blob, {
+ upsert: true,
+ contentType: "application/step"
+ });
+ if (uploaded.error) {
+ throw new Error(`staging the model failed: ${uploaded.error.message}`);
+ }
+ return { stagedPath, size, contentHash: `sha256:${hash.digest("hex")}` };
+ } finally {
+ await rm(scratchDir, { recursive: true, force: true });
}
- const client = onshape.client;
+}
- const scratchDir = await mkdtemp(join(tmpdir(), "onshape-gltf-"));
+/** A drawing's PDF, or null (logged) when it is past the document limit. */
+async function downloadPdf(
+ client: OnshapeClient,
+ translation: FinishedTranslation
+): Promise<Uint8Array | null> {
try {
- // Raw GLTF is the only model export (STEP was deliberately dropped — see
- // exportRawGltfModel). The assembler pipeline does the compression; a new
- // model row starts it.
- // Throws OnshapeAssetTooLargeError past the raw cap; callers treat that as
- // a permanent skip.
- const model = await exportRawGltfModel(client, input, scratchDir);
- const baseName = model.fileName.replace(/\.gltf$/, "");
-
- // Drawings -> PDF (optional; same translation flow, not yet exercised
- // against a live DRAWING element).
- const documents: { fileName: string; bytes: Uint8Array }[] = [];
- for (const drawingElementId of input.drawingElementIds ?? []) {
- const pdfTranslation = await client.createDrawingTranslation(
- input.documentId,
- input.versionId,
- drawingElementId,
- {
- formatName: "PDF",
- storeInDocument: false,
- wvm: input.sourceWvm ?? "v"
- }
- );
- const pdfDone = await waitForTranslation(client, pdfTranslation.id);
- const pdfBytes = await downloadTranslationBytes(
- client,
- pdfDone,
- DOCUMENT_MAX_BYTES
+ const buffer = await client.downloadExternalData(
+ translation.documentId,
+ translation.foreignId,
+ { maxBytes: DOCUMENT_MAX_BYTES }
+ );
+ return new Uint8Array(buffer);
+ } catch (error) {
+ if (error instanceof OnshapeAssetTooLargeError) {
+ console.warn(
+ `onshape sync: skipping oversized drawing ${translation.id}`
);
- documents.push({
- fileName: `${baseName}-${drawingElementId}.pdf`,
- bytes: pdfBytes
- });
+ return null;
}
+ throw error;
+ }
+}
- const attached = await attachOnshapeAssetsToItem(carbon, {
+async function attachOnshapeThumbnail(
+ carbon: CarbonClient,
+ input: SyncOnshapeElementInput,
+ modelUploadId: string,
+ label: string
+): Promise<boolean> {
+ try {
+ const client = await onshapeClient(carbon, input);
+ const thumbnail = await client.getElementThumbnail(
+ input.documentId,
+ input.versionId,
+ input.modelElementId,
+ "300x300",
+ input.sourceWvm ?? "v"
+ );
+ await attachModelThumbnail(carbon, {
companyId: input.companyId,
- createdBy: input.userId,
- itemId: input.itemId,
- sourceDocument: input.sourceDocument,
- model,
- documents
+ modelUploadId,
+ pngBytes: new Uint8Array(thumbnail)
});
-
- // The element-thumbnail endpoint cannot select a part or configuration.
- // Keep it only for unconfigured assemblies. All other thumbnails are
- // rendered from the selected model by the optimise itself.
- let thumbnailAttached = false;
- if (
- attached.modelUploadId &&
- input.modelElementKind === "assembly" &&
- (!input.configuration || input.configuration.toLowerCase() === "default")
- ) {
- try {
- const thumbnail = await client.getElementThumbnail(
- input.documentId,
- input.versionId,
- input.modelElementId,
- "300x300",
- input.sourceWvm ?? "v"
- );
- await attachModelThumbnail(carbon, {
- companyId: input.companyId,
- modelUploadId: attached.modelUploadId,
- pngBytes: new Uint8Array(thumbnail)
- });
- thumbnailAttached = true;
- } catch (thumbnailError) {
- console.warn(
- `syncOnshapeElementAssetsToItem: Onshape thumbnail fetch failed for ${baseName}; the optimise renders one`,
- thumbnailError
- );
- }
- }
-
- return { ...attached, thumbnailAttached };
- } finally {
- await rm(scratchDir, { recursive: true, force: true });
+ return true;
+ } catch (thumbnailError) {
+ console.warn(
+ `onshape sync: Onshape thumbnail fetch failed for ${label}; the optimise renders one`,
+ thumbnailError
+ );
+ return false;
}
}
@@ -328,46 +596,72 @@ export interface SyncOnshapeDrawingInput {
sourceWvm?: "w" | "v"; // path segment for the drawing translation; default "v"
}
+export type DrawingSyncResult = AttachOnshapeAssetsResult & {
+ /** The PDF is past the document upload limit: a permanent skip. */
+ tooLarge?: boolean;
+};
+
// Export ONE released Onshape DRAWING element as a PDF and attach it as a document
-// on the given Carbon item. Drawings are released as their own elements (DRW-xxxx,
-// elementType 2) separate from the model, so the caller resolves which item the
-// drawing belongs to (by shared part number) and passes it here. No model is
-// touched — only a PDF document is added/updated (idempotent via the attach
-// helper's replace-not-append rule).
-export async function syncOnshapeDrawingAssetsToItem(
+// on the given Carbon item, as resumable steps like the element sync's:
+// `translate`, `poll-n` / `sleep-n` (holding no function between polls), then
+// `attach` (download the PDF and record it). Drawings are released as their own
+// elements (DRW-xxxx, elementType 2) separate from the model, so the caller
+// resolves which item the drawing belongs to (by shared part number) and passes
+// it here. No model is touched — only a PDF document is added/updated
+// (idempotent via the attach helper's replace-not-append rule).
+export async function runOnshapeDrawingSync(
+ step: Pick<ElementSyncStep, "run" | "sleep">,
carbon: CarbonClient,
- input: SyncOnshapeDrawingInput
-): Promise<AttachOnshapeAssetsResult> {
- const onshape = await getOnshapeClient(
+ input: SyncOnshapeDrawingInput,
+ prefix: string
+): Promise<DrawingSyncResult> {
+ const label = input.assetBaseName ?? input.drawingElementId;
+ const translationId: string = await step.run(`${prefix}-translate`, () =>
+ withRateLimitRetry(async () => {
+ const client = await onshapeClient(carbon, input);
+ const translation = await client.createDrawingTranslation(
+ input.documentId,
+ input.versionId,
+ input.drawingElementId,
+ {
+ formatName: "PDF",
+ storeInDocument: false,
+ wvm: input.sourceWvm ?? "v"
+ }
+ );
+ return translation.id;
+ }, `translate ${label}`)
+ );
+ const finished = await waitForTranslations(
+ step,
carbon,
- input.companyId,
- input.userId,
- input.integrationId
+ input,
+ label,
+ prefix,
+ [translationId]
);
- if (onshape.error || !onshape.client) {
- throw new Error(`getOnshapeClient failed: ${onshape.error ?? "no client"}`);
- }
- const client = onshape.client;
+ const translation = finished[translationId]!;
- const pdfTranslation = await client.createDrawingTranslation(
- input.documentId,
- input.versionId,
- input.drawingElementId,
- { formatName: "PDF", storeInDocument: false, wvm: input.sourceWvm ?? "v" }
- );
- const pdfDone = await waitForTranslation(client, pdfTranslation.id);
- const pdfBytes = await downloadTranslationBytes(
- client,
- pdfDone,
- DOCUMENT_MAX_BYTES
+ return step.run(`${prefix}-attach`, () =>
+ withRateLimitRetry(async (): Promise<DrawingSyncResult> => {
+ const client = await onshapeClient(carbon, input);
+ const pdf = await downloadPdf(client, translation);
+ if (!pdf) {
+ return {
+ modelUploadId: null,
+ documentIds: [],
+ preservedPriorModelAsDocument: false,
+ tooLarge: true
+ };
+ }
+ const baseName = input.assetBaseName ?? translation.name ?? "drawing";
+ return attachOnshapeAssetsToItem(carbon, {
+ companyId: input.companyId,
+ createdBy: input.userId,
+ itemId: input.itemId,
+ sourceDocument: input.sourceDocument,
+ documents: [{ fileName: `${baseName}.pdf`, bytes: pdf }]
+ });
+ }, `attach ${label}`)
);
- const baseName = input.assetBaseName ?? pdfDone.name ?? "drawing";
-
- return attachOnshapeAssetsToItem(carbon, {
- companyId: input.companyId,
- createdBy: input.userId,
- itemId: input.itemId,
- sourceDocument: input.sourceDocument,
- documents: [{ fileName: `${baseName}.pdf`, bytes: pdfBytes }]
- });
}
diff --git a/packages/jobs/src/inngest/functions/tasks/assembler-client.test.ts b/packages/jobs/src/inngest/functions/tasks/assembler-client.test.ts
index e430c83620..4aa012fafa 100644
--- a/packages/jobs/src/inngest/functions/tasks/assembler-client.test.ts
+++ b/packages/jobs/src/inngest/functions/tasks/assembler-client.test.ts
@@ -73,7 +73,8 @@ describe("decideJobStep", () => {
});
expect(decideJobStep(upload, state({ resubmits: 2 }))).toEqual({
kind: "fail",
- message: "upload failed"
+ message: "upload failed",
+ code: "UPLOAD_FAILED"
});
});
@@ -87,7 +88,11 @@ describe("decideJobStep", () => {
},
state()
)
- ).toEqual({ kind: "fail", message: "cannot fit" });
+ ).toEqual({
+ kind: "fail",
+ message: "cannot fit",
+ code: "cannot_fit_budget"
+ });
});
it("resubmits a job the service lost, then gives up", () => {
@@ -117,8 +122,7 @@ describe("pollAssemblerJobOnce", () => {
);
return pollAssemblerJobOnce({
jobId: "optimize-m1",
- baseUrl: "http://assembler.test",
- mintUploadUrls: async () => ({})
+ baseUrl: "http://assembler.test"
});
};
diff --git a/packages/jobs/src/inngest/functions/tasks/assembler-client.ts b/packages/jobs/src/inngest/functions/tasks/assembler-client.ts
index 942fb4215f..ff4dfb7717 100644
--- a/packages/jobs/src/inngest/functions/tasks/assembler-client.ts
+++ b/packages/jobs/src/inngest/functions/tasks/assembler-client.ts
@@ -30,8 +30,7 @@ import { getJobDatabaseClient } from "../../../db";
// job between slices. See .ai/specs/2026-07-15-assembler-deployment.md.
// Submits and polls are short; a tight per-request timeout catches an
-// unreachable service. A poll may upload a parked output, which is why it is
-// not shorter.
+// unreachable service.
const REQUEST_TIMEOUT_MS = 60 * 1000;
// One wait for the completion callback. Between slices the run polls, which
// catches a callback that fired while no wait was registered.
@@ -248,7 +247,7 @@ function errorMessage(error: ErrorBody, fallback: string): string {
* honoring Retry-After; a genuine outage / permanent rejection fails fast.
*/
export async function submitAssemblerJob(opts: {
- action: "convert" | "optimize" | "plan" | "compact" | "thumbnail";
+ action: AssemblerAction;
jobId: string;
body: unknown;
logger: { warn: (msg: string, meta?: unknown) => void };
@@ -335,31 +334,20 @@ export type JobOutcome =
/**
* One GET /v1/jobs/{id} poll; it answers at once (the run waits between polls in
- * `waitForEvent`, which holds no concurrency slot). Mints fresh signed upload
- * URLs (late-mint) for this poll via `mintUploadUrls` and sends them in
- * X-Carbon-Upload-Urls, so the service PUTs a parked output with seconds-old
- * tokens.
+ * `waitForEvent`, which holds no concurrency slot).
*/
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<JobOutcome> {
- const { jobId, mintUploadUrls } = opts;
+ const { jobId } = 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}`, {
- headers,
+ headers: assemblerAuthHeaders,
signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS)
});
} catch {
@@ -441,7 +429,7 @@ async function cancelAssemblerJob(
// 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 = {
+export type StepTools = {
run: (id: string, fn: () => unknown) => Promise<any>;
waitForEvent: (
id: string,
@@ -451,19 +439,21 @@ type StepTools = {
/**
* Failures a resubmit can fix: the source or an output could not travel, the
- * service could not start the job, or it gave no reason. Any other failure is
- * the input's, and a resubmit only repeats it.
+ * service could not start the job, the process running it died
+ * (`WORKER_LOST`: its lease ran out), or it gave no reason. Any other failure
+ * is the input's, and a resubmit only repeats it.
*/
const TRANSIENT_FAILURES = new Set([
"READ_FAILED",
"UPLOAD_FAILED",
"BUSY",
- "DISPATCH_FAILED"
+ "DISPATCH_FAILED",
+ "WORKER_LOST"
]);
export type JobDecision =
| { kind: "return"; result: Json; stats: Json }
- | { kind: "fail"; message: string }
+ | { kind: "fail"; message: string; code?: string }
| { kind: "resubmit"; reason: string }
| { kind: "wait"; runningSince: number | null };
@@ -495,7 +485,11 @@ export function decideJobStep(
!outcome.code || TRANSIENT_FAILURES.has(outcome.code.toUpperCase());
return transient && canResubmit
? { kind: "resubmit", reason: outcome.error }
- : { kind: "fail", message: outcome.error };
+ : {
+ kind: "fail",
+ message: outcome.error,
+ ...(outcome.code ? { code: outcome.code } : {})
+ };
}
case "lost":
return canResubmit
@@ -526,6 +520,25 @@ export function decideJobStep(
}
}
+export type AssemblerAction =
+ | "convert"
+ | "optimize"
+ | "plan"
+ | "compact"
+ | "thumbnail"
+ | "fetch";
+
+/** A job the service could not finish, with its error code when it gave one
+ * (e.g. `LIMIT_EXCEEDED`), so a caller can tell a permanent skip from a fault. */
+export class AssemblerJobError extends NonRetriableError {
+ readonly code?: string;
+ constructor(message: string, code?: string) {
+ super(message);
+ this.name = "AssemblerJobError";
+ this.code = code;
+ }
+}
+
type AssemblerLogger = {
warn: (msg: string, meta?: unknown) => void;
info: (msg: string, meta?: unknown) => void;
@@ -534,17 +547,52 @@ type AssemblerLogger = {
type AssemblerJobSpec = {
/** Namespaces this job's Inngest step ids (a caller may run several). */
idPrefix: string;
- action: "convert" | "optimize" | "plan" | "compact" | "thumbnail";
+ action: AssemblerAction;
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). */
+ /** Sign one upload URL per output the action writes (`signUploadUrls`);
+ * called at every (re)submit, so a resubmit gets fresh URLs. */
mintUploadUrls: () => Promise<Record<string, string>>;
/** How long the job may run once the service starts it. */
maxWaitMs: number;
logger: AssemblerLogger;
};
+/** A storage bucket that can sign an upload URL: `storage(client).company(id)`
+ * or `client.storage.from(bucket)`. */
+type UploadBucket = {
+ createSignedUploadUrl: (
+ path: string,
+ options: { upsert: boolean }
+ ) => Promise<{
+ data: { signedUrl: string } | null;
+ error: { message: string } | null;
+ }>;
+};
+
+/**
+ * Sign one upload URL per output, keyed by the output name the action writes.
+ * Throws when any URL cannot be signed: the service fails a job with
+ * `UPLOAD_FAILED` when an output has no URL, after doing all of its work.
+ */
+export async function signUploadUrls(
+ targets: Record<string, { bucket: UploadBucket; path: string }>
+): Promise<Record<string, string>> {
+ const signed = await Promise.all(
+ Object.entries(targets).map(async ([name, { bucket, path }]) => {
+ const upload = await bucket.createSignedUploadUrl(path, { upsert: true });
+ if (!upload.data) {
+ throw new Error(
+ `Failed to sign the ${name} upload URL for ${path}: ${upload.error?.message ?? "no URL"}`
+ );
+ }
+ return [name, internalizeStorageUrl(upload.data.signedUrl)] as const;
+ })
+ );
+ return Object.fromEntries(signed);
+}
+
/** The completion-webhook URL minted into the job spec at submit. */
function callbackUrl(jobId: string): string {
return `${ERP_URL}/api/assembler/callback?token=${assemblerCallbackToken(SESSION_SECRET ?? "", jobId)}`;
@@ -600,7 +648,7 @@ export async function runAssemblerJob(
const polled: { outcome: JobOutcome; now: number } = await step.run(
`${idPrefix}-poll-${slice}`,
async () => ({
- outcome: await pollAssemblerJobOnce({ jobId, mintUploadUrls, baseUrl }),
+ outcome: await pollAssemblerJobOnce({ jobId, baseUrl }),
now: Date.now()
})
);
@@ -640,7 +688,7 @@ export async function runAssemblerJob(
cancelAssemblerJob(jobId, baseUrl, logger)
);
}
- throw new NonRetriableError(decision.message);
+ throw new AssemblerJobError(decision.message, decision.code);
}
resubmits += 1;
runningSince = null;
diff --git a/packages/jobs/src/inngest/functions/tasks/assembly-convert.ts b/packages/jobs/src/inngest/functions/tasks/assembly-convert.ts
index 4ecc690c06..91d61d1d19 100644
--- a/packages/jobs/src/inngest/functions/tasks/assembly-convert.ts
+++ b/packages/jobs/src/inngest/functions/tasks/assembly-convert.ts
@@ -15,7 +15,8 @@ import {
internalizeStorageUrl,
requireModelSourceBucket,
runAssemblerJob,
- signSourceUrl
+ signSourceUrl,
+ signUploadUrls
} from "./assembler-client";
import {
getModelUpload,
@@ -93,8 +94,6 @@ export const assemblyConvertFunction = inngest.createFunction(
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, {
@@ -147,22 +146,12 @@ export const assemblyConvertFunction = inngest.createFunction(
}
};
},
- mintUploadUrls: async () => {
- const client = getCarbonServiceRole();
- const [glbUpload, graphUpload] = await Promise.all([
- storage(client)
- .company(companyId)
- .createSignedUploadUrl(glbPath, { upsert: true }),
- storage(client)
- .company(companyId)
- .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;
+ mintUploadUrls: () => {
+ const bucket = storage(getCarbonServiceRole()).company(companyId);
+ return signUploadUrls({
+ glb: { bucket, path: glbPath },
+ graph: { bucket, path: graphPath }
+ });
}
});
const componentCount =
diff --git a/packages/jobs/src/inngest/functions/tasks/assembly-plan.ts b/packages/jobs/src/inngest/functions/tasks/assembly-plan.ts
index f86714eb41..2d723ac7ba 100644
--- a/packages/jobs/src/inngest/functions/tasks/assembly-plan.ts
+++ b/packages/jobs/src/inngest/functions/tasks/assembly-plan.ts
@@ -15,7 +15,8 @@ import {
internalizeStorageUrl,
requireModelSourceBucket,
runAssemblerJob,
- signSourceUrl
+ signSourceUrl,
+ signUploadUrls
} from "./assembler-client";
import { getModelUpload, insertPlanJob, updatePlanJobs } from "./model-rows";
import { loadPlanUnits } from "./plan-units";
@@ -194,44 +195,22 @@ export const assemblyPlanFunction = inngest.createFunction(
: {})
};
},
- mintUploadUrls: async () => {
- const client = getCarbonServiceRole();
- const upload = await storage(client)
- .company(companyId)
- .createSignedUploadUrl(planPath, { upsert: true });
- const urls: Record<string, string> = {};
- if (upload.data)
- urls.plan = internalizeStorageUrl(upload.data.signedUrl);
- return urls;
- }
+ mintUploadUrls: () =>
+ signUploadUrls({
+ plan: {
+ bucket: storage(getCarbonServiceRole()).company(companyId),
+ path: planPath
+ }
+ })
});
- const planResult = (plan.result ?? {}) as {
- planPath?: string;
- plan?: AssemblyPlan | null;
- };
- const donePlanPath = planResult.planPath ?? planPath;
- const inlinePlan = planResult.plan ?? null;
+ const donePlanPath =
+ (plan.result as { planPath?: string } | null)?.planPath ?? planPath;
const stats: Json = plan.stats;
- // Persist: flip the row to the pointer the service reported. A legacy
- // 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.
+ // Persist: flip the row to the pointer the service reported. Guarded by
+ // status=Processing so a cancel/racing-retry no-ops.
await step.run("persist-plan", async () => {
- const client = getCarbonServiceRole();
- if (inlinePlan) {
- const upload = await storage(client)
- .company(companyId)
- .upload(donePlanPath, JSON.stringify(inlinePlan), {
- contentType: "application/json",
- upsert: true
- });
- if (upload.error) {
- throw new Error(
- `Failed to upload plan.json: ${upload.error.message}`
- );
- }
- }
await updatePlanJobs(
companyId,
{ id: job.id, statuses: ["Processing"] },
@@ -240,24 +219,19 @@ export const assemblyPlanFunction = inngest.createFunction(
});
// Re-motion: preserve step order, refresh each step's motion from the new
- // plan (Done steps kept, titles/typed fields untouched). The plan lives in
- // storage now (offloaded), so download it unless the legacy inline path
- // already has it in memory.
+ // plan (Done steps kept, titles/typed fields untouched).
if (reMotionFor) {
await step.run("update-step-motions", async () => {
const client = getCarbonServiceRole();
- let plan = inlinePlan;
- if (!plan) {
- const download = await storage(client)
- .company(companyId)
- .download(donePlanPath);
- if (!download.data) {
- throw new Error(
- `Failed to download plan.json for re-motion: ${download.error.message}`
- );
- }
- plan = JSON.parse(await download.data.text()) as AssemblyPlan;
+ const download = await storage(client)
+ .company(companyId)
+ .download(donePlanPath);
+ if (!download.data) {
+ throw new Error(
+ `Failed to download plan.json for re-motion: ${download.error.message}`
+ );
}
+ const plan = JSON.parse(await download.data.text()) as AssemblyPlan;
await updateAssemblyStepMotionsFromPlan(client, {
assemblyInstructionId: reMotionFor,
plan,
diff --git a/packages/jobs/src/inngest/functions/tasks/model-compact.ts b/packages/jobs/src/inngest/functions/tasks/model-compact.ts
index f27c75e6bc..4ed0109331 100644
--- a/packages/jobs/src/inngest/functions/tasks/model-compact.ts
+++ b/packages/jobs/src/inngest/functions/tasks/model-compact.ts
@@ -15,7 +15,8 @@ import {
internalizeStorageUrl,
resolveModelSourceBucket,
runAssemblerJob,
- signSourceUrl
+ signSourceUrl,
+ signUploadUrls
} from "./assembler-client";
import {
getModelUpload,
@@ -253,15 +254,13 @@ export const modelCompactFunction = inngest.createFunction(
output: { path: target.path }
};
},
- mintUploadUrls: async () => {
- const upload = await getCarbonServiceRole()
- .storage.from(TEMP_STAGING_BUCKET)
- .createSignedUploadUrl(target.path, { upsert: true });
- const urls: Record<string, string> = {};
- if (upload.data)
- urls.raw = internalizeStorageUrl(upload.data.signedUrl);
- return urls;
- }
+ mintUploadUrls: () =>
+ signUploadUrls({
+ raw: {
+ bucket: getCarbonServiceRole().storage.from(TEMP_STAGING_BUCKET),
+ path: target.path
+ }
+ })
});
const compactedSize =
(compact.stats as { outputBytes?: number } | null)?.outputBytes ?? null;
diff --git a/packages/jobs/src/inngest/functions/tasks/model-optimize.ts b/packages/jobs/src/inngest/functions/tasks/model-optimize.ts
index 3b5cfc1815..f124676b04 100644
--- a/packages/jobs/src/inngest/functions/tasks/model-optimize.ts
+++ b/packages/jobs/src/inngest/functions/tasks/model-optimize.ts
@@ -15,7 +15,8 @@ import {
internalizeStorageUrl,
requireModelSourceBucket,
runAssemblerJob,
- signSourceUrl
+ signSourceUrl,
+ signUploadUrls
} from "./assembler-client";
import {
compactTarget,
@@ -190,28 +191,21 @@ export const modelOptimizeFunction = inngest.createFunction(
// quality omitted → the service applies its size-adaptive policy.
};
},
- mintUploadUrls: async () => {
+ mintUploadUrls: () => {
const client = getCarbonServiceRole();
- const [glb, thumbnail, raw] = await Promise.all([
- storage(client)
- .company(companyId)
- .createSignedUploadUrl(optimizedPath, { upsert: true }),
- storage(client)
- .company(companyId)
- .createSignedUploadUrl(thumbnailPath, { upsert: true }),
- compact
- ? client.storage
- .from(TEMP_STAGING_BUCKET)
- .createSignedUploadUrl(compact.path, { upsert: true })
- : null
- ]);
- const urls: Record<string, string> = {};
- if (glb.data) urls.glb = internalizeStorageUrl(glb.data.signedUrl);
- if (thumbnail.data) {
- urls.thumbnail = internalizeStorageUrl(thumbnail.data.signedUrl);
- }
- if (raw?.data) urls.raw = internalizeStorageUrl(raw.data.signedUrl);
- return urls;
+ const bucket = storage(client).company(companyId);
+ return signUploadUrls({
+ glb: { bucket, path: optimizedPath },
+ thumbnail: { bucket, path: thumbnailPath },
+ ...(compact
+ ? {
+ raw: {
+ bucket: client.storage.from(TEMP_STAGING_BUCKET),
+ path: compact.path
+ }
+ }
+ : {})
+ });
}
});
const outputs =
diff --git a/packages/jobs/src/inngest/functions/tasks/model-thumbnail.ts b/packages/jobs/src/inngest/functions/tasks/model-thumbnail.ts
index 2173b4c036..4337ab8a2a 100644
--- a/packages/jobs/src/inngest/functions/tasks/model-thumbnail.ts
+++ b/packages/jobs/src/inngest/functions/tasks/model-thumbnail.ts
@@ -10,7 +10,8 @@ import {
ASSEMBLER_CONCURRENCY,
assemblerEnabled,
internalizeStorageUrl,
- runAssemblerJob
+ runAssemblerJob,
+ signUploadUrls
} from "./assembler-client";
import { getModelUpload, updateModelUpload } from "./model-rows";
@@ -94,23 +95,18 @@ export const modelThumbnailFunction = inngest.createFunction(
output: { path: thumbnailPath, ...(direction && { direction }) }
};
},
- mintUploadUrls: async () => {
- const client = getCarbonServiceRole();
- const upload = await storage(client)
- .company(companyId)
- .createSignedUploadUrl(thumbnailPath, { upsert: true });
- if (upload.error) {
- throw new Error(
- `Failed to sign thumbnail upload URL: ${upload.error.message}`
- );
- }
- return { thumbnail: internalizeStorageUrl(upload.data.signedUrl) };
- }
+ mintUploadUrls: () =>
+ signUploadUrls({
+ thumbnail: {
+ bucket: storage(getCarbonServiceRole()).company(companyId),
+ path: thumbnailPath
+ }
+ })
});
await step.run("persist", async () => {
const client = getCarbonServiceRole();
- // The upload goes through a late-minted URL: confirm it landed before repointing.
+ // Confirm the upload landed before repointing.
const uploaded = await storage(client)
.company(companyId)
.info(thumbnailPath);
diff --git a/packages/jobs/src/inngest/index.ts b/packages/jobs/src/inngest/index.ts
index 1d69e935be..1fe854e84d 100644
--- a/packages/jobs/src/inngest/index.ts
+++ b/packages/jobs/src/inngest/index.ts
@@ -48,6 +48,9 @@ import {
oeeSweepFunction,
oeeSyncFunction,
onshapeBackfillFunction,
+ onshapeDrawingSyncFunction,
+ onshapeElementSyncFunction,
+ onshapeFetchFunction,
onshapePanelSyncFunction,
onshapeRevisionSyncFunction,
paperlessPartsFunction,
@@ -194,6 +197,9 @@ export const functions = [
mountPublishFunction,
mountSweepFunction,
onshapeBackfillFunction,
+ onshapeDrawingSyncFunction,
+ onshapeElementSyncFunction,
+ onshapeFetchFunction,
onshapePanelSyncFunction,
onshapeRevisionSyncFunction,
rampSyncFunction,
diff --git a/packages/lib/src/events.ts b/packages/lib/src/events.ts
index 3df1840dd4..80cece16e6 100644
--- a/packages/lib/src/events.ts
+++ b/packages/lib/src/events.ts
@@ -688,6 +688,57 @@ export type Events = {
};
};
+ // One Onshape element's export onto an item (step.invoked by the backfill)
+ "carbon/onshape-element-sync": {
+ data: {
+ companyId: string;
+ userId: string;
+ integrationId?: string;
+ itemId: string;
+ sourceDocument: "Part";
+ documentId: string;
+ versionId: string;
+ sourceWvm?: "w" | "v";
+ sourceMicroversionId?: string;
+ modelElementId: string;
+ modelElementKind: "partstudio" | "assembly";
+ partId?: string | null;
+ configuration?: string | null;
+ drawingElementIds?: string[];
+ assetBaseName?: string;
+ };
+ };
+
+ // One released Onshape drawing's PDF onto an item (step.invoked by the backfill)
+ "carbon/onshape-drawing-sync": {
+ data: {
+ companyId: string;
+ userId: string;
+ integrationId?: string;
+ itemId: string;
+ sourceDocument: "Part";
+ documentId: string;
+ versionId: string;
+ drawingElementId: string;
+ assetBaseName?: string;
+ sourceWvm?: "w" | "v";
+ };
+ };
+
+ // The assembler copies one finished Onshape translation into staging
+ // (step.invoked by the element sync)
+ "carbon/onshape-fetch": {
+ data: {
+ companyId: string;
+ userId: string;
+ integrationId?: string;
+ translationId: string;
+ documentId: string;
+ foreignId: string;
+ stagedPath: string;
+ };
+ };
+
// Onshape released-asset backfill / reconcile
"carbon/onshape-backfill": {
data: {
diff --git a/packages/locale/locales/de/erp.po b/packages/locale/locales/de/erp.po
index 3a4bfe6e40..aeaddd6609 100644
--- a/packages/locale/locales/de/erp.po
+++ b/packages/locale/locales/de/erp.po
@@ -14193,6 +14193,9 @@ msgstr "Neue IC-Transaktion"
msgid "New Inspection Plan"
msgstr "Neuer Prüfplan"
+msgid "New instruction"
+msgstr ""
+
msgid "New Inventory Count"
msgstr "Neue Bestandszählung"
@@ -23248,6 +23251,9 @@ msgstr "Die Übersteuerung wird bei Aktivierung beibehalten und im Änderungspro
msgid "The parent-child chain of tracked entities — what a unit was built from and what it became."
msgstr "Die Eltern-Kind-Kette der verfolgten Einheiten – was eine Einheit aus gebaut wurde und was sie wurde."
+msgid "The part has a newer model than this instruction."
+msgstr ""
+
msgid "The part is manufactured as its own job when the parent that needs it is built."
msgstr "Der Teil wird als eigener Auftrag hergestellt, wenn das Elternteil, das es benötigt, gebaut wird."
diff --git a/packages/locale/locales/en/erp.po b/packages/locale/locales/en/erp.po
index 2b48abdaa0..9e97bb1ee4 100644
--- a/packages/locale/locales/en/erp.po
+++ b/packages/locale/locales/en/erp.po
@@ -14193,6 +14193,9 @@ msgstr "New IC Transaction"
msgid "New Inspection Plan"
msgstr "New Inspection Plan"
+msgid "New instruction"
+msgstr "New instruction"
+
msgid "New Inventory Count"
msgstr "New Inventory Count"
@@ -23248,6 +23251,9 @@ msgstr "The override is kept at activation and recorded in the audit log with it
msgid "The parent-child chain of tracked entities — what a unit was built from and what it became."
msgstr "The parent-child chain of tracked entities — what a unit was built from and what it became."
+msgid "The part has a newer model than this instruction."
+msgstr "The part has a newer model than this instruction."
+
msgid "The part is manufactured as its own job when the parent that needs it is built."
msgstr "The part is manufactured as its own job when the parent that needs it is built."
diff --git a/packages/locale/locales/es/erp.po b/packages/locale/locales/es/erp.po
index fbed5a960d..4a4384e0a3 100644
--- a/packages/locale/locales/es/erp.po
+++ b/packages/locale/locales/es/erp.po
@@ -14193,6 +14193,9 @@ msgstr "Nueva Transacción IC"
msgid "New Inspection Plan"
msgstr "Nuevo plan de inspección"
+msgid "New instruction"
+msgstr ""
+
msgid "New Inventory Count"
msgstr "Nuevo Conteo de Inventario"
@@ -23248,6 +23251,9 @@ msgstr "La sobrescritura se mantiene en la activación y se registra en el regis
msgid "The parent-child chain of tracked entities — what a unit was built from and what it became."
msgstr "La cadena padre-hijo de entidades rastreadas - de qué se construyó una unidad y en qué se convirtió."
+msgid "The part has a newer model than this instruction."
+msgstr ""
+
msgid "The part is manufactured as its own job when the parent that needs it is built."
msgstr "La parte se fabrica como su propio trabajo cuando se construye el padre que la necesita."
diff --git a/packages/locale/locales/fr/erp.po b/packages/locale/locales/fr/erp.po
index 158417145a..d7227a3646 100644
--- a/packages/locale/locales/fr/erp.po
+++ b/packages/locale/locales/fr/erp.po
@@ -14193,6 +14193,9 @@ msgstr "Nouvelle Transaction IC"
msgid "New Inspection Plan"
msgstr "Nouveau plan de contrôle"
+msgid "New instruction"
+msgstr ""
+
msgid "New Inventory Count"
msgstr "Nouveau Décompte d'Inventaire"
@@ -23248,6 +23251,9 @@ msgstr "La substitution est conservée à l'activation et enregistrée dans le j
msgid "The parent-child chain of tracked entities — what a unit was built from and what it became."
msgstr "La chaîne parent-enfant des entités suivies - ce dont une unité a été construite et ce qu'elle est devenue."
+msgid "The part has a newer model than this instruction."
+msgstr ""
+
msgid "The part is manufactured as its own job when the parent that needs it is built."
msgstr "La pièce est fabriquée comme son propre travail quand le parent qui en a besoin est construit."
diff --git a/packages/locale/locales/hi/erp.po b/packages/locale/locales/hi/erp.po
index 040d7774fd..f5eba58477 100644
--- a/packages/locale/locales/hi/erp.po
+++ b/packages/locale/locales/hi/erp.po
@@ -14193,6 +14193,9 @@ msgstr "नया IC लेनदेन"
msgid "New Inspection Plan"
msgstr "नई निरीक्षण योजना"
+msgid "New instruction"
+msgstr ""
+
msgid "New Inventory Count"
msgstr "नई इन्वेंटरी गणना"
@@ -23248,6 +23251,9 @@ msgstr "ओवरराइड को सक्रियण में रखा
msgid "The parent-child chain of tracked entities — what a unit was built from and what it became."
msgstr "ट्रैक किए गए इकाइयों की मातृ-बाल श्रृंखला - एक इकाई किस चीज़ से बनाई गई थी और यह क्या बन गई।"
+msgid "The part has a newer model than this instruction."
+msgstr ""
+
msgid "The part is manufactured as its own job when the parent that needs it is built."
msgstr "जब माता-पिता जो इसकी आवश्यकता है वह बनाया जाता है तब भाग अपनी स्वयं की नौकरी के रूप में निर्मित होता है।"
diff --git a/packages/locale/locales/it/erp.po b/packages/locale/locales/it/erp.po
index 6ecb0a1524..77e806e34e 100644
--- a/packages/locale/locales/it/erp.po
+++ b/packages/locale/locales/it/erp.po
@@ -14193,6 +14193,9 @@ msgstr "Nuova Transazione IC"
msgid "New Inspection Plan"
msgstr "Nuovo Piano di controllo"
+msgid "New instruction"
+msgstr ""
+
msgid "New Inventory Count"
msgstr "Nuovo Conteggio Inventario"
@@ -23248,6 +23251,9 @@ msgstr "La forzatura è mantenuta all'attivazione e registrata nel registro di a
msgid "The parent-child chain of tracked entities — what a unit was built from and what it became."
msgstr "La catena padre-figlio delle entità monitorate - di cosa è stata costruita un'unità e cosa è diventata."
+msgid "The part has a newer model than this instruction."
+msgstr ""
+
msgid "The part is manufactured as its own job when the parent that needs it is built."
msgstr "La parte viene fabbricata come suo proprio lavoro quando il genitore che la necessita è costruito."
diff --git a/packages/locale/locales/ja/erp.po b/packages/locale/locales/ja/erp.po
index c56e7b9e0e..c0b64b99dd 100644
--- a/packages/locale/locales/ja/erp.po
+++ b/packages/locale/locales/ja/erp.po
@@ -14193,6 +14193,9 @@ msgstr "新しいIC取引"
msgid "New Inspection Plan"
msgstr "新しい検査計画"
+msgid "New instruction"
+msgstr ""
+
msgid "New Inventory Count"
msgstr "新しい在庫数"
@@ -23248,6 +23251,9 @@ msgstr "上書きは有効化時に保持され、その理由とともに監査
msgid "The parent-child chain of tracked entities — what a unit was built from and what it became."
msgstr "追跡されたエンティティの親子チェーン—ユニットが何から構築され、それが何になったか。"
+msgid "The part has a newer model than this instruction."
+msgstr ""
+
msgid "The part is manufactured as its own job when the parent that needs it is built."
msgstr "必要な親が構築される場合、部品は独自のジョブとして製造されます。"
diff --git a/packages/locale/locales/ko/erp.po b/packages/locale/locales/ko/erp.po
index 3afb325dcf..d14369daac 100644
--- a/packages/locale/locales/ko/erp.po
+++ b/packages/locale/locales/ko/erp.po
@@ -14193,6 +14193,9 @@ msgstr "신규 IC 거래"
msgid "New Inspection Plan"
msgstr "새 검사 계획"
+msgid "New instruction"
+msgstr ""
+
msgid "New Inventory Count"
msgstr "신규 재고 실사"
@@ -23248,6 +23251,9 @@ msgstr "재정의는 활성화 시 유지되며 그 이유와 함께 감사 로
msgid "The parent-child chain of tracked entities — what a unit was built from and what it became."
msgstr "추적 개체의 상하위 연결 관계로, 해당 유닛이 무엇으로부터 만들어졌고 무엇이 되었는지를 나타냅니다."
+msgid "The part has a newer model than this instruction."
+msgstr ""
+
msgid "The part is manufactured as its own job when the parent that needs it is built."
msgstr "상위 품목이 제작될 때 이 품목은 별도의 작업으로 제조됩니다."
diff --git a/packages/locale/locales/pl/erp.po b/packages/locale/locales/pl/erp.po
index 5aa1c106bb..e32806f7ef 100644
--- a/packages/locale/locales/pl/erp.po
+++ b/packages/locale/locales/pl/erp.po
@@ -14193,6 +14193,9 @@ msgstr "Nowa Transakcja IC"
msgid "New Inspection Plan"
msgstr "Nowy Plan kontroli"
+msgid "New instruction"
+msgstr ""
+
msgid "New Inventory Count"
msgstr "Nowa inwentaryzacja"
@@ -23248,6 +23251,9 @@ msgstr "Nadpisanie jest zachowywane w momencie aktywacji i rejestrowane w dzienn
msgid "The parent-child chain of tracked entities — what a unit was built from and what it became."
msgstr "Łańcuch parent-child śledzonych jednostek - z czego jednostka została zbudowana i czym się stała."
+msgid "The part has a newer model than this instruction."
+msgstr ""
+
msgid "The part is manufactured as its own job when the parent that needs it is built."
msgstr "Część jest wytwarzana jako swoje własne zadanie, gdy rodzic, który jej potrzebuje, jest zbudowany."
diff --git a/packages/locale/locales/pt/erp.po b/packages/locale/locales/pt/erp.po
index c719a08618..935faf76ad 100644
--- a/packages/locale/locales/pt/erp.po
+++ b/packages/locale/locales/pt/erp.po
@@ -14193,6 +14193,9 @@ msgstr "Nova Transação IC"
msgid "New Inspection Plan"
msgstr "Novo Plano de Inspeção"
+msgid "New instruction"
+msgstr ""
+
msgid "New Inventory Count"
msgstr "Novo Inventário"
@@ -23248,6 +23251,9 @@ msgstr "A sobrescrita é mantida na ativação e registrada no log de auditoria
msgid "The parent-child chain of tracked entities — what a unit was built from and what it became."
msgstr "A cadeia pai-filho de entidades rastreadas - a partir do que uma unidade foi construída e no que se tornou."
+msgid "The part has a newer model than this instruction."
+msgstr ""
+
msgid "The part is manufactured as its own job when the parent that needs it is built."
msgstr "A peça é fabricada como seu próprio trabalho quando o pai que a necessita é construído."
diff --git a/packages/locale/locales/ru/erp.po b/packages/locale/locales/ru/erp.po
index aeaff95bf8..9a41b231f2 100644
--- a/packages/locale/locales/ru/erp.po
+++ b/packages/locale/locales/ru/erp.po
@@ -14193,6 +14193,9 @@ msgstr "Новая транзакция IC"
msgid "New Inspection Plan"
msgstr "Новый план контроля"
+msgid "New instruction"
+msgstr ""
+
msgid "New Inventory Count"
msgstr "Новый подсчет инвентаря"
@@ -23248,6 +23251,9 @@ msgstr "Переопределение сохраняется при актив
msgid "The parent-child chain of tracked entities — what a unit was built from and what it became."
msgstr "Цепь родитель-потомок отслеживаемых объектов — из чего была построена единица и чем она стала."
+msgid "The part has a newer model than this instruction."
+msgstr ""
+
msgid "The part is manufactured as its own job when the parent that needs it is built."
msgstr "Деталь производится как собственное задание, когда производится родитель, который ее нужен."
diff --git a/packages/locale/locales/tr/erp.po b/packages/locale/locales/tr/erp.po
index 5ce323c9f8..8461494533 100644
--- a/packages/locale/locales/tr/erp.po
+++ b/packages/locale/locales/tr/erp.po
@@ -14193,6 +14193,9 @@ msgstr "Yeni IC İşlemi"
msgid "New Inspection Plan"
msgstr "Yeni kontrol planı"
+msgid "New instruction"
+msgstr ""
+
msgid "New Inventory Count"
msgstr "Yeni Envanter Sayımı"
@@ -23248,6 +23251,9 @@ msgstr "Geçersiz kılma, etkinleştirildiğinde tutulur ve sebebi ile birlikte
msgid "The parent-child chain of tracked entities — what a unit was built from and what it became."
msgstr "İzlenen varlıkların parent-child zinciri - bir birim neyin dışında inşa edilmiş ve ne olmuş."
+msgid "The part has a newer model than this instruction."
+msgstr ""
+
msgid "The part is manufactured as its own job when the parent that needs it is built."
msgstr "Parça, ihtiyacı olan üst öğe inşa edildiğinde kendi işi olarak üretilir."
diff --git a/packages/locale/locales/zh/erp.po b/packages/locale/locales/zh/erp.po
index 89e9ddc874..ccb2010425 100644
--- a/packages/locale/locales/zh/erp.po
+++ b/packages/locale/locales/zh/erp.po
@@ -14193,6 +14193,9 @@ msgstr "新IC事务"
msgid "New Inspection Plan"
msgstr "新检验计划"
+msgid "New instruction"
+msgstr ""
+
msgid "New Inventory Count"
msgstr "新建库存盘点"
@@ -23248,6 +23251,9 @@ msgstr "覆盖在激活时保持,并在审计日志中记录其原因。"
msgid "The parent-child chain of tracked entities — what a unit was built from and what it became."
msgstr "跟踪实体的父子链 - 一个单位从什么构成以及它变成了什么。"
+msgid "The part has a newer model than this instruction."
+msgstr ""
+
msgid "The part is manufactured as its own job when the parent that needs it is built."
msgstr "当需要该零件的父级被构造时,该零件被制造为其自己的工作。"
diff --git a/packages/utils/src/tiptap.ts b/packages/utils/src/tiptap.ts
index 1531869b69..145722a6cb 100644
--- a/packages/utils/src/tiptap.ts
+++ b/packages/utils/src/tiptap.ts
@@ -192,7 +192,7 @@ function tiptapInlineToHTML(node: JSONContent): string {
return "";
}
-function escapeHTMLChars(str: string): string {
+export function escapeHTMLChars(str: string): string {
return str
.replace(/&/g, "&amp;")
.replace(/</g, "&lt;")