use super::catalogue::{artifact_ref, context_schema, document_info, obj};
use super::ops::Caller;
use super::wire::{ApiError, Effects};
use super::CadService;
use crate::script_sdk::{Guide, ServiceEntry, Surface, Target};
use crate::tools::{ToolSet, ToolSpec};
use serde_json::{json, Value};
use std::time::Duration;
const MAX_REPLY: usize = 12 << 20;
const MAX_RESULT_WAIT_MS: u64 = 600_000;
fn open(props: Value, required: &[&str]) -> Value {
json!({ "type": "object", "properties": props, "required": required, "additionalProperties": true })
}
fn text() -> Value {
json!({ "type": "string" })
}
fn count() -> Value {
json!({ "type": "integer", "minimum": 0 })
}
pub fn service_entries(catalogue: &super::catalogue::Catalogue) -> Vec<ServiceEntry> {
let mut info = document_info();
info["properties"]["busy"] = json!({ "type": "boolean", "description": "an accepted operation on this document has not finished" });
let nullable = |schema: Value| json!({ "anyOf": [schema, { "type": "null" }] });
let manifest = || json!({ "type": "object", "description": "Optional: this server's manifest identity is used when omitted." });
let retention = open(json!({ "scope": text(), "epoch": text(), "retainUntil": nullable(text()), "terminalRetentionMs": count(), "artifactRetentionMs": count() }), &["scope", "epoch"]);
let admission = |extra: Value, required: &[&str]| {
let mut props = json!({ "operationId": text(), "acceptedAt": text(), "context": nullable(context_schema()), "state": { "enum": ["queued", "running", "evaluating", "committing", "succeeded", "failed", "cancelled"] }, "sequence": text(), "retention": retention.clone() });
for (k, v) in extra.as_object().cloned().unwrap_or_default() { props[k] = v; }
let mut all = vec!["operationId", "acceptedAt", "context", "state", "sequence", "retention"];
all.extend_from_slice(required);
open(props, &all)
};
let status = admission(json!({
"command": text(),
"cancellation": obj(json!({ "requested": { "type": "boolean" }, "effectiveNow": { "type": "boolean" }, "nonPreemptible": { "type": "boolean" } }), &["requested", "effectiveNow", "nonPreemptible"]),
"progress": open(json!({ "stage": text(), "summary": text() }), &["stage", "summary"]),
}), &["command", "cancellation", "progress"]);
let mut created = document_info();
created["properties"]["operationId"] = text();
created["properties"]["state"] = json!({ "const": "succeeded" });
created["properties"]["effects"] = json!({ "type": "object", "description": "the operation's effects: disposition and the documents it changed" });
created["required"] = json!(["context", "title", "lifecycle", "dirty", "operationId", "state", "effects"]);
let step = json!({ "const": "model/step" });
let export = catalogue.get("cad.inputs.exportOptions").expect("the catalogue declares cad.inputs.exportOptions");
let commands = |execution: &str| -> String {
catalogue.descriptors.iter().filter(|d| d.execution == execution).map(|d| {
format!(" `{}`: {} args {} -> output {}.", d.path, d.summary.trim_end_matches('.'), crate::declarations::ts_type(&d.input_schema), crate::declarations::ts_type(&d.output_schema))
}).collect()
};
let entry = |namespace, action, doc: &str, input_schema, output_schema, grants: &[&'static str], read_only| ServiceEntry { namespace, action, method: "", doc: doc.to_string(), input_schema, output_schema, grants: grants.to_vec(), read_only, destructive: false };
let mut entries = vec![
entry("document", "list",
"The open documents this program may read, each with its context ({documentId, expectedRevision}), title, lifecycle, dirty and busy.",
obj(json!({}), &[]), obj(json!({ "documents": { "type": "array", "items": info.clone() } }), &["documents"]), &["document.read"][..], true),
entry("document", "get",
"One open document by its identity: its current context, title, lifecycle, dirty and busy.",
obj(json!({ "documentId": text() }), &["documentId"]), info.clone(), &["document.read"][..], true),
entry("document", "create",
"Create a new, empty millimetre part document behind the visible one and wait for it. Answers its DocumentInfo (its `context` is what the next write names) with the operation that made it: operationId, state and effects. One accepted operation, start to finish.",
catalogue.get("cad.documents.create").expect("the catalogue declares cad.documents.create").input_schema.clone(), created, &["document.create", "operation.read"][..], false),
entry("document", "bind",
"Check a document context: answers the document's DocumentInfo when it is open at exactly that revision, and fails with revision_conflict (carrying the current context) when it has moved on. It changes nothing.",
context_schema(), info, &["document.read"][..], true),
entry("artifacts", "read",
"Read a chunk of an artifact's bytes as base64 (offset defaults to 0; limit to the default chunk).",
obj(json!({ "artifactId": text(), "offset": count(), "limit": { "type": "integer", "minimum": 1 } }), &["artifactId"]),
obj(json!({ "artifact": artifact_ref(), "offset": count(), "bytesBase64": text(), "eof": { "type": "boolean" } }), &["artifact", "offset", "bytesBase64", "eof"]), &["artifact.read"][..], true),
entry("artifacts", "create",
"Create a STEP artifact from bytes (bytesBase64) or, for the local user, from a file on the host (path): exactly one of the two.",
obj(json!({ "mediaType": step.clone(), "bytesBase64": text(), "path": text() }), &["mediaType"]), artifact_ref(), &["artifact.write"][..], false),
entry("artifacts", "begin",
"Start a chunked upload of a STEP artifact larger than one request: its byte length and SHA-256. Answers the uploadId and the largest chunk.",
obj(json!({ "mediaType": step, "byteLength": count(), "sha256": { "type": "string", "pattern": "^[0-9a-f]{64}$" } }), &["mediaType", "byteLength", "sha256"]),
obj(json!({ "uploadId": text(), "maxChunkBytes": count(), "expiresAt": text() }), &["uploadId", "maxChunkBytes", "expiresAt"]), &["artifact.write"][..], false),
entry("artifacts", "append",
"Append the next chunk of an upload; offset is where the upload stands.",
obj(json!({ "uploadId": text(), "offset": count(), "bytesBase64": text() }), &["uploadId", "offset", "bytesBase64"]),
obj(json!({ "uploadId": text(), "received": count(), "byteLength": count() }), &["uploadId", "received", "byteLength"]), &["artifact.write"][..], false),
entry("artifacts", "commit",
"Finish an upload: the bytes must be exactly the declared length and digest. Answers the artifact.",
obj(json!({ "uploadId": text() }), &["uploadId"]), artifact_ref(), &["artifact.write"][..], false),
entry("operations", "issueKey",
"Issue an idempotency key for one command submission. A lost reply is recovered by resubmitting the SAME key and request.",
obj(json!({ "purpose": { "const": "command", "default": "command" } }), &[]),
obj(json!({ "key": text(), "firstAdmissionExpiresAt": text() }), &["key", "firstAdmissionExpiresAt"]), &["operation.read"][..], false),
entry("operations", "submit",
&format!("Submit one catalogue command as an operation. `context` is the document it acts on, {{documentId, expectedRevision}} (null for cad.documents.create); a write answers the document's new context in its output. Answers the admission at once: wait for the outcome with sdk.operations.result({{operationId, wait_ms}}). The commands:{}", commands("operation")),
obj(json!({ "command": text(), "args": { "type": "object" }, "context": nullable(context_schema()), "idempotencyKey": { "type": "string", "description": "from sdk.operations.issueKey" }, "manifest": manifest() }), &["command", "args", "context", "idempotencyKey"]),
admission(json!({}), &[]), &["operation.read"][..], false),
entry("operations", "status",
"An operation's state, cancellation and progress; with afterSequence, whether it changed since.",
obj(json!({ "operationId": text(), "afterSequence": text() }), &["operationId"]),
obj(json!({ "changed": { "type": "boolean" }, "status": status.clone() }), &["changed", "status"]), &["operation.read"][..], true),
entry("operations", "result",
"An operation's terminal result: state (succeeded, failed, cancelled), effects, geometry, output and error. With wait_ms it waits up to that long for the operation to finish; while it has not, the call fails with not_ready.",
obj(json!({ "operationId": text(), "wait_ms": { "type": "integer", "minimum": 0, "maximum": MAX_RESULT_WAIT_MS } }), &["operationId"]),
open(json!({ "operationId": text(), "state": { "enum": ["succeeded", "failed", "cancelled"] }, "sequence": text(), "accepted": { "const": true }, "finishedAt": text(), "effects": { "type": "object" }, "geometry": { "type": "object" }, "output": {}, "error": {}, "retention": retention.clone() }), &["operationId", "state", "sequence", "finishedAt", "effects", "output", "error"]), &["operation.read"][..], true),
entry("operations", "cancel",
"Ask an accepted operation to stop. Answers what the request could still do: requested, cancelled_before_start, too_late or already_terminal.",
obj(json!({ "operationId": text() }), &["operationId"]),
obj(json!({ "operationId": text(), "disposition": { "enum": ["requested", "cancelled_before_start", "too_late", "already_terminal"] }, "status": status }), &["operationId", "disposition", "status"]), &["operation.cancel"][..], false),
entry("commands", "query",
&format!("Run a catalogue query command inline, at the document's current revision. Answers {{context, output}}. The commands:{}", commands("query")),
obj(json!({ "command": { "const": "cad.model.inspect" }, "args": obj(json!({}), &[]), "context": context_schema(), "manifest": manifest() }), &["command", "context"]),
obj(json!({ "context": context_schema(), "output": catalogue.get("cad.model.inspect").expect("the catalogue declares cad.model.inspect").output_schema.clone() }), &["context", "output"]), &["document.read"][..], true),
entry("inputs", "exportOptions", export.documentation, export.input_schema.clone(), export.output_schema.clone(), &[][..], false),
];
for e in &mut entries {
e.method = match (e.namespace, e.action) {
("document", "list") => "cad.documents.list",
("document", "get") => "cad.documents.get",
("document", "create") => "cad.documents.create",
("document", "bind") => "cad.documents.bind",
("artifacts", "read") => "cad.artifacts.read",
("artifacts", "create") => "cad.artifacts.create",
("artifacts", "begin") => "cad.artifacts.begin",
("artifacts", "append") => "cad.artifacts.append",
("artifacts", "commit") => "cad.artifacts.commit",
("operations", "issueKey") => "cad.operations.issueKey",
("operations", "submit") => "cad.operations.submit",
("operations", "status") => "cad.operations.status",
("operations", "result") => "cad.operations.result",
("operations", "cancel") => "cad.operations.cancel",
("commands", "query") => "cad.commands.query",
_ => "cad.inputs.exportOptions",
};
}
for d in catalogue.descriptors.iter().filter(|d| d.document_scope == "one") {
let Some((namespace, action)) = typed_path(d.path) else { continue };
let operation = d.execution == "operation";
let mut input_schema = d.input_schema.clone();
input_schema["properties"]["context"] = context_schema();
let mut required = vec![json!("context")];
required.extend(input_schema["required"].as_array().cloned().unwrap_or_default());
input_schema["required"] = Value::Array(required);
let mut output_schema = d.output_schema.clone();
let mut grants: Vec<&'static str> = d.required_capabilities.to_vec();
if operation {
output_schema["properties"]["operationId"] = text();
output_schema["properties"]["state"] = json!({ "const": "succeeded" });
output_schema["properties"]["effects"] = json!({ "type": "object", "description": "the operation's effects: disposition and the documents it changed" });
if let Some(required) = output_schema["required"].as_array_mut() { required.extend([json!("operationId"), json!("state"), json!("effects")]); }
grants.push("operation.read");
}
let how = if operation {
"`context` names the document and the revision the caller expects. One accepted operation, start to finish: it answers the command's output with the operation that made it (operationId, state, effects), or throws its error. A write's output carries the document's next `context`."
} else {
"`context` names the document. An ordered read, run inline: it answers the command's output, tagged with the document's current context."
};
entries.push(ServiceEntry {
namespace, action, method: d.path,
doc: format!("{} {} {how}", d.summary, d.documentation),
input_schema, output_schema, grants,
read_only: !operation,
destructive: d.effect_classes.contains(&"document_lifecycle"),
});
}
entries
}
pub fn typed_path(command: &'static str) -> Option<(&'static str, &'static str)> {
let (group, verb) = command.strip_prefix("cad.")?.split_once('.')?;
Some((if group == "documents" { "document" } else { group }, verb))
}
pub struct Legacy {
pub old: &'static str,
pub new: &'static str,
pub reason: &'static str,
pub service: bool,
}
const NESTED: &str = "a program cannot start or inspect executions (no nested executions); use the `run` tool";
pub const LEGACY: &[Legacy] = &[
Legacy { old: "cad.inputs.exportOptions", new: "sdk.inputs.exportOptions", reason: "", service: true },
Legacy { old: "cad.discovery.search", new: "", reason: "discovery is the `sdk` tool, not a script function: sdk({query})", service: true },
Legacy { old: "cad.discovery.describe", new: "", reason: "discovery is the `sdk` tool, not a script function: sdk({topic: \"<namespace>.<action>\"})", service: true },
Legacy { old: "cad.docs.list", new: "", reason: "discovery is the `sdk` tool, not a script function: sdk({}) lists the guides", service: false },
Legacy { old: "cad.docs.read", new: "", reason: "discovery is the `sdk` tool, not a script function: sdk({topic: \"guide.<name>\"}) returns a guide; a brep:// reference is read with MCP resources/read", service: false },
Legacy { old: "cad.docs.sdk", new: "", reason: "discovery is the `sdk` tool, not a script function: sdk({topic: \"<namespace>\"}) lists a namespace, sdk({topic: \"<namespace>.<action>\"}) gives a signature", service: false },
Legacy { old: "cad.session.summary", new: "", reason: "it was SDK-side JavaScript and no SDK source is sent to a worker: read sdk.document.docs_list({}) and sdk.history.listing({})", service: false },
Legacy { old: "cad.documents.list", new: "sdk.document.list", reason: "", service: true },
Legacy { old: "cad.documents.get", new: "sdk.document.get", reason: "", service: true },
Legacy { old: "cad.documents.create", new: "sdk.document.create", reason: "", service: false },
Legacy { old: "cad.documents.bind", new: "sdk.document.bind", reason: "", service: false },
Legacy { old: "cad.documents.close", new: "sdk.document.close", reason: "", service: false },
Legacy { old: "cad.sketch.create", new: "sdk.sketch.create", reason: "", service: false },
Legacy { old: "cad.solids.extrude", new: "sdk.solids.extrude", reason: "", service: false },
Legacy { old: "cad.files.export", new: "sdk.files.export", reason: "", service: false },
Legacy { old: "cad.files.import", new: "sdk.files.import", reason: "", service: false },
Legacy { old: "cad.model.inspect", new: "sdk.model.inspect", reason: "", service: false },
Legacy { old: "cad.operations.issueKey", new: "sdk.operations.issueKey", reason: "", service: true },
Legacy { old: "cad.operations.submit", new: "sdk.operations.submit", reason: "", service: true },
Legacy { old: "cad.operations.status", new: "sdk.operations.status", reason: "", service: true },
Legacy { old: "cad.operations.result", new: "sdk.operations.result", reason: "", service: true },
Legacy { old: "cad.operations.cancel", new: "sdk.operations.cancel", reason: "", service: true },
Legacy { old: "cad.commands.query", new: "sdk.commands.query", reason: "", service: true },
Legacy { old: "cad.code.submit", new: "", reason: NESTED, service: true },
Legacy { old: "cad.code.status", new: "", reason: NESTED, service: true },
Legacy { old: "cad.code.result", new: "", reason: NESTED, service: true },
Legacy { old: "cad.code.cancel", new: "", reason: NESTED, service: true },
Legacy { old: "cad.artifacts.read", new: "sdk.artifacts.read", reason: "", service: true },
Legacy { old: "cad.artifacts.create", new: "sdk.artifacts.create", reason: "", service: true },
Legacy { old: "cad.artifacts.begin", new: "sdk.artifacts.begin", reason: "", service: true },
Legacy { old: "cad.artifacts.append", new: "sdk.artifacts.append", reason: "", service: true },
Legacy { old: "cad.artifacts.commit", new: "sdk.artifacts.commit", reason: "", service: true },
Legacy { old: "cad.internal.awaitOperation", new: "", reason: "it was the SDK's own bridge call: sdk.operations.result({operationId, wait_ms}) waits for an operation", service: false },
Legacy { old: "cad.internal.pause", new: "", reason: "it was the SDK's own bridge call (its backoff between overloaded submissions)", service: false },
];
pub fn effects_possible(method: &str) -> bool {
!matches!(method, "document.list" | "document.get" | "document.bind" | "artifacts.read" | "operations.issueKey" | "operations.status" | "operations.result" | "operations.cancel" | "commands.query" | "inputs.exportOptions" | "model.inspect")
}
pub fn may_have_effects(method: &str) -> bool {
effects_possible(method)
}
pub(crate) fn signature(schema: &Value) -> String {
fields(schema)
}
fn tool_refusal(error: &str, spec: &ToolSpec) -> String {
let argument_error = ["unknown field", "missing field", "invalid type", "unknown variant", "there are no fields"].iter().any(|m| error.contains(m));
if !argument_error || error.contains(" takes {") { return error.to_string(); }
format!("{error} โ sdk.{} takes {}", crate::script_sdk::path_of(spec.group, &spec.name), fields(&spec.input_schema))
}
pub(crate) fn fields(schema: &Value) -> String {
let Some(props) = schema.get("properties").and_then(Value::as_object).filter(|p| !p.is_empty()) else { return "{} (no arguments)".into() };
let required: Vec<&str> = schema["required"].as_array().into_iter().flatten().filter_map(Value::as_str).collect();
let mut out = Vec::new();
let mut len = 0;
for (name, p) in props {
let ty = match &p["type"] {
Value::String(t) => t.clone(),
Value::Array(ts) => ts.iter().filter_map(Value::as_str).collect::<Vec<_>>().join("|"),
_ if p.get("enum").is_some() => p["enum"].as_array().into_iter().flatten().take(6).map(|v| v.to_string()).collect::<Vec<_>>().join("|"),
_ => "any".into(),
};
let field = format!("{name}{}: {ty}", if required.contains(&name.as_str()) { "" } else { "?" });
len += field.len() + 2;
if len > 600 { out.push("โฆ".to_string()); break; }
out.push(field);
}
format!("{{{}}}", out.join(", "))
}
fn receipt(result: &Value) -> Value {
let mut output = result["output"].clone();
if let Some(fields) = output.as_object_mut() {
for key in ["operationId", "state", "effects"] {
fields.insert(key.into(), result[key].clone());
}
}
output
}
fn error_of(record: &Value, operation: &str) -> ApiError {
const CODES: &[&str] = &[
"invalid_arguments", "unsupported_version", "manifest_mismatch", "method_unknown", "capability_denied", "document_unknown",
"document_closed", "document_not_active", "document_busy", "document_mismatch", "revision_conflict", "overloaded",
"idempotency_conflict", "idempotency_expired", "operation_unknown", "handle_epoch_mismatch", "not_ready", "cancelled",
"geometry_refused", "evaluation_failed", "job_failed", "deadline_exceeded", "resource_limit", "external_io_failed",
"artifact_unknown", "artifact_expired", "host_stopping", "host_stopped", "internal_error",
];
const PHASES: &[&str] = &["validation", "authorization", "admission", "queue", "running", "evaluation", "commit", "external_io", "lookup", "completion"];
let known = |list: &[&'static str], value: &Value, otherwise| list.iter().copied().find(|c| value.as_str() == Some(*c)).unwrap_or(otherwise);
let mut error = ApiError::new(known(CODES, &record["code"], "job_failed"), known(PHASES, &record["phase"], "running"), record["message"].as_str().unwrap_or("the operation did not succeed")).op(operation);
error.effects = Effects {
disposition: known(&["none", "committed", "partial", "unknown"], &record["effects"]["disposition"], "unknown"),
documents: record["effects"]["documents"].as_array().cloned().unwrap_or_default(),
external: record["effects"]["external"].as_array().cloned().unwrap_or_default(),
};
error.retry = known(&["do_not_retry", "query_operation", "retry_same_key_within_retention", "inspect_then_new_submission"], &record["retry"], error.retry);
if !record["context"].is_null() { error.context = Some(record["context"].clone()); }
error
}
fn string<'a>(req: &'a Value, key: &str) -> Result<&'a str, ApiError> {
req.get(key).and_then(Value::as_str).ok_or_else(|| ApiError::new("invalid_arguments", "validation", format!("{key} is required")))
}
fn only(req: &Value, allowed: &[&str]) -> Result<(), ApiError> {
let obj = req.as_object().ok_or_else(|| ApiError::new("invalid_arguments", "validation", "the request must be an object"))?;
if let Some(k) = obj.keys().find(|k| !allowed.contains(&k.as_str())) {
let takes = if allowed.is_empty() { "it takes no fields".to_string() } else { format!("it takes {{{}}}", allowed.join(", ")) };
return Err(ApiError::new("invalid_arguments", "validation", format!("unknown field `{k}`; {takes}")));
}
Ok(())
}
enum Found {
Tool(Box<ToolSpec>),
Service(&'static str),
}
impl CadService {
pub fn surface<'a>(&'a self, tools: &'a ToolSet, state: Option<&'a crate::server::ServerState>) -> Surface<'a> {
let skills = state.map_or(crate::skills::Catalogue::embedded(), |s| s.skills());
let guides = skills.skills.iter().map(|s| Guide { name: s.name, description: s.description, text: s.text }).collect();
Surface::new(&tools.specs, &self.services, guides)
}
pub fn script_names(&self, caller: &Caller) -> Vec<String> {
let state = self.server_state();
let granted = |tools: &ToolSet| self.surface(tools, state.as_deref()).granted(|g| caller.grants.has(g)).names();
let Some(state) = &state else { return granted(&ToolSet::default()) };
if let Ok(set) = state.tools.try_read() { return granted(&set); }
match tokio::runtime::Handle::try_current() {
Err(_) => granted(&state.tools.blocking_read()),
Ok(handle) if handle.runtime_flavor() == tokio::runtime::RuntimeFlavor::MultiThread => {
tokio::task::block_in_place(|| granted(&handle.block_on(state.tools.read())))
}
Ok(_) => loop {
if let Ok(set) = state.tools.try_read() { break granted(&set); }
std::thread::yield_now();
},
}
}
pub async fn script_known(&self, caller: &Caller, method: &str) -> bool {
let state = self.server_state();
let empty = ToolSet::default();
let guard = match &state { Some(state) => Some(state.tools.read().await), None => None };
self.surface(guard.as_deref().unwrap_or(&empty), None).get(method).is_some_and(|entry| entry.grants().iter().all(|g| caller.grants.has(g)))
}
pub async fn script_call(&self, caller: &Caller, method: &str, body: Value) -> Result<Value, ApiError> {
if body.to_string().len() > 1 << 20 {
return Err(ApiError::new("resource_limit", "validation", "the request is larger than 1 MiB"));
}
let state = self.server_state();
let found = {
let empty = ToolSet::default();
let guard = match &state { Some(state) => Some(state.tools.read().await), None => None };
let surface = self.surface(guard.as_deref().unwrap_or(&empty), None);
match surface.get(method) {
Some(entry) => match entry.grants().iter().find(|g| !caller.grants.has(g)) {
Some(missing) => return Err(ApiError::new("capability_denied", "authorization", format!("sdk.{} needs `{missing}`, which this program was not granted", entry.path()))),
None => match entry.target {
Target::Tool(spec) => Found::Tool(Box::new(spec.clone())),
Target::Service(service) => Found::Service(service.method),
},
},
None => return Err(ApiError::new("method_unknown", "lookup", surface.granted(|g| caller.grants.has(g)).unknown(method))),
}
};
let value = match found {
Found::Tool(spec) => self.call_tool(caller, &spec, body).await?,
Found::Service(service) => self.call_service(caller, service, body).await?,
};
let size = value.to_string().len();
if size > MAX_REPLY {
return Err(ApiError::new("resource_limit", "evaluation", format!("sdk.{method}'s result is {size} bytes, more than a script can take ({MAX_REPLY}); ask for less (a filter, a page, one entity)")));
}
Ok(value)
}
async fn call_tool(&self, caller: &Caller, spec: &ToolSpec, args: Value) -> Result<Value, ApiError> {
if let Some(message) = crate::script_sdk::undeclared_context(&spec.name, &spec.input_schema, &args) {
return Err(ApiError::new("invalid_arguments", "validation", message));
}
let result = if spec.group == "files" {
match spec.name.strip_prefix("files_").ok_or_else(|| "invalid file method".to_string()).and_then(|op| crate::files::operation_request(op, args)) {
Ok(request) => self.files.call(self, caller, request).await,
Err(error) => Err(error),
}
} else {
(spec.handler)(args).await
};
let out = result.map_err(|e| {
let mut error = ApiError::from_app(&tool_refusal(&e, spec), "evaluation");
if error.code == "evaluation_failed" { error.effects = Effects::unknown(); }
error
})?;
let mut value = out.json;
if !out.images.is_empty() {
let mut refs = Vec::new();
for image in out.images {
refs.push(self.artifacts.create(caller.owner(), image.mime, image.png)?);
}
match value.as_object_mut() {
Some(o) => { o.insert("images".into(), Value::Array(refs)); }
None => value = json!({ "value": value, "images": refs }),
}
}
Ok(value)
}
async fn operate(&self, caller: &Caller, command: &str, args: Value, context: Value) -> Result<Value, ApiError> {
let key = self.ops.issue_key(caller, &json!({ "purpose": "command" }))?["key"].clone();
let request = json!({ "manifest": self.catalogue.identity(), "command": command, "args": args, "context": context, "idempotencyKey": key });
let mut attempt = 0u32;
let admission = loop {
match self.ops.submit(caller, &request) {
Ok(admission) => break admission,
Err(e) if e.code == "overloaded" && attempt < 20 => {
tokio::time::sleep(Duration::from_millis((100u64 << attempt.min(4)).min(1000))).await;
attempt += 1;
}
Err(e) => return Err(e),
}
};
let id = admission["operationId"].as_str().unwrap_or_default().to_string();
let result = self.operation_result(caller, &json!({ "operationId": id }), None).await?;
if result["state"] != "succeeded" {
return Err(error_of(&result["error"], &id));
}
Ok(receipt(&result))
}
async fn operation_result(&self, caller: &Caller, req: &Value, deadline: Option<std::time::Instant>) -> Result<Value, ApiError> {
let mut delay = 25;
loop {
match self.ops.result(caller, req) {
Err(e) if e.code == "not_ready" && deadline.is_none_or(|d| std::time::Instant::now() < d) => {
tokio::time::sleep(Duration::from_millis(delay)).await;
delay = (delay * 2).min(250);
}
other => return other,
}
}
}
pub(crate) async fn call_service(&self, caller: &Caller, method: &str, mut req: Value) -> Result<Value, ApiError> {
if matches!(method, "cad.operations.submit" | "cad.commands.query") && req.is_object() && req.get("manifest").is_none_or(Value::is_null) {
req["manifest"] = self.catalogue.identity();
}
let req = &req;
match method {
"cad.inputs.exportOptions" => self.code.export_options(caller, req).await,
"cad.documents.list" => {
only(req, &[])?;
self.ops.documents(caller, None).await
}
"cad.documents.get" => {
only(req, &["documentId"])?;
self.ops.documents(caller, Some(string(req, "documentId")?)).await
}
"cad.documents.create" => self.operate(caller, "cad.documents.create", req.clone(), Value::Null).await,
"cad.documents.bind" => {
only(req, &["documentId", "expectedRevision"])?;
let (document, expected) = super::wire::document_context(req)?;
let info = self.ops.documents(caller, Some(&document)).await?;
let current = info["context"]["expectedRevision"].as_str().unwrap_or_default();
if current != expected {
return Err(ApiError::new("revision_conflict", "admission", format!("the document is at revision {current}, not {expected}")).context(info["context"].clone()));
}
Ok(info)
}
"cad.operations.issueKey" => {
only(req, &["purpose"])?;
self.ops.issue_key(caller, &json!({ "purpose": req.get("purpose").cloned().unwrap_or(json!("command")) }))
}
"cad.operations.submit" => self.ops.submit(caller, req),
"cad.operations.status" => self.ops.status(caller, req),
"cad.operations.result" => {
only(req, &["operationId", "wait_ms"])?;
let wait = match req.get("wait_ms") {
None => 0,
Some(v) => v.as_u64().filter(|ms| *ms <= MAX_RESULT_WAIT_MS).ok_or_else(|| ApiError::new("invalid_arguments", "validation", format!("wait_ms must be an integer from 0 to {MAX_RESULT_WAIT_MS}")))?,
};
let lookup = json!({ "operationId": req.get("operationId") });
self.operation_result(caller, &lookup, Some(std::time::Instant::now() + Duration::from_millis(wait))).await
}
"cad.operations.cancel" => self.ops.cancel(caller, req),
"cad.commands.query" => self.ops.query(caller, req).await,
"cad.artifacts.read" => {
caller.require(&["artifact.read"])?;
only(req, &["artifactId", "offset", "limit"])?;
let offset = req.get("offset").map_or(Some(0), Value::as_u64).ok_or_else(|| ApiError::new("invalid_arguments", "validation", "offset must be a non-negative integer"))?;
let limit = match req.get("limit") {
None => None,
Some(v) => Some(v.as_u64().ok_or_else(|| ApiError::new("invalid_arguments", "validation", "limit must be a positive integer"))? as usize),
};
self.artifacts.read(&caller.owner(), string(req, "artifactId")?, offset as usize, limit)
}
"cad.artifacts.create" => {
caller.require(&["artifact.write"])?;
only(req, &["mediaType", "bytesBase64", "path"])?;
if string(req, "mediaType")? != "model/step" {
return Err(ApiError::new("invalid_arguments", "validation", "mediaType must be model/step"));
}
let bytes = match (req.get("bytesBase64"), req.get("path").and_then(Value::as_str)) {
(None, Some(path)) => {
caller.require(&["host.files.read"])?;
let len = std::fs::metadata(path).map_err(|e| ApiError::new("invalid_arguments", "external_io", format!("{path}: {e}")))?.len();
if len > super::artifacts::MAX_ARTIFACT as u64 {
return Err(ApiError::new("resource_limit", "external_io", format!("{path} is larger than {} bytes", super::artifacts::MAX_ARTIFACT)));
}
std::fs::read(path).map_err(|e| ApiError::new("invalid_arguments", "external_io", format!("{path}: {e}")))?
}
(Some(_), None) => {
use base64::Engine as _;
base64::engine::general_purpose::STANDARD
.decode(string(req, "bytesBase64")?)
.map_err(|e| ApiError::new("invalid_arguments", "validation", format!("bytesBase64: {e}")))?
}
_ => return Err(ApiError::new("invalid_arguments", "validation", "give exactly one of bytesBase64 and path")),
};
self.artifacts.create(caller.owner(), "model/step", bytes)
}
"cad.artifacts.begin" => {
caller.require(&["artifact.write"])?;
only(req, &["mediaType", "byteLength", "sha256"])?;
if string(req, "mediaType")? != "model/step" {
return Err(ApiError::new("invalid_arguments", "validation", "mediaType must be model/step"));
}
let length = req.get("byteLength").and_then(Value::as_u64).ok_or_else(|| ApiError::new("invalid_arguments", "validation", "byteLength is required"))?;
self.artifacts.begin(caller.owner(), "model/step", length as usize, string(req, "sha256")?)
}
"cad.artifacts.append" => {
caller.require(&["artifact.write"])?;
only(req, &["uploadId", "offset", "bytesBase64"])?;
let offset = req.get("offset").and_then(Value::as_u64).ok_or_else(|| ApiError::new("invalid_arguments", "validation", "offset is required"))?;
use base64::Engine as _;
let bytes = base64::engine::general_purpose::STANDARD
.decode(string(req, "bytesBase64")?)
.map_err(|e| ApiError::new("invalid_arguments", "validation", format!("bytesBase64: {e}")))?;
self.artifacts.append(&caller.owner(), string(req, "uploadId")?, offset as usize, bytes)
}
"cad.artifacts.commit" => {
caller.require(&["artifact.write"])?;
only(req, &["uploadId"])?;
self.artifacts.commit(&caller.owner(), string(req, "uploadId")?)
}
other => {
let descriptor = self.catalogue.get(other).filter(|d| d.document_scope == "one")
.ok_or_else(|| ApiError::new("method_unknown", "lookup", format!("no service function `{other}`")))?;
let mut args = req.clone();
let fields = args.as_object_mut().ok_or_else(|| ApiError::new("invalid_arguments", "validation", "the request must be an object"))?;
let context = fields.remove("context").filter(|c| !c.is_null())
.ok_or_else(|| ApiError::new("invalid_arguments", "validation", format!("context is required: the document `{other}` acts on, {{documentId, expectedRevision}} (sdk.document.create and every write answer one)")))?;
if descriptor.execution == "query" {
let answer = self.ops.query(caller, &json!({ "manifest": self.catalogue.identity(), "command": other, "args": args, "context": context })).await?;
Ok(answer["output"].clone())
} else {
self.operate(caller, descriptor.path, args, context).await
}
}
}
}
}