Skip to content

SolidCraft: an open-source parametric 3D CAD application built in pure Rust. Desktop, web, and automation through MCP.

Split schema contracts per command file and add shared field types (#2829) (#3558)

Matthew Knutson453c6bcb142d
diff --git a/crates/engine/src/cmd/face.rs b/crates/engine/src/cmd/face.rs
index 0eb29b2753..baac95b5fb 100644
--- a/crates/engine/src/cmd/face.rs
+++ b/crates/engine/src/cmd/face.rs
@@ -63,14 +63,30 @@ pub(super) fn face_is_planar(s: &Session, p: Vec3) -> Option<bool> {
/// The point is in the frame of the command's other picks: the component's own when
/// they were mapped into it, else the world's.
pub(super) fn face_ref(s: &Session, v: &Value, body: Option<&str>, cmd: &str) -> Result<Vec3> {
+ match face_ref_form(v).map_err(|why| bad(cmd, why))? {
+ FaceRefForm::Point(p) => Ok(p),
+ FaceRefForm::Name(name) => {
+ let st = if crate::frames::mapped() { s.model.state() } else { s.world_state() };
+ solidcraft_doc::naming::named_face_point(&st, body, name).map_err(|why| bad(cmd, why))
+ }
+ }
+}
+
+/// A face reference as given, before it is looked up: see [`face_ref`].
+pub(crate) enum FaceRefForm<'a> {
+ Point(Vec3),
+ Name(&'a str),
+}
+
+/// What [`face_ref`] reads `v` as, without the design: a point, or a name of 1…512 bytes.
+pub(crate) fn face_ref_form(v: &Value) -> std::result::Result<FaceRefForm<'_>, &'static str> {
if let Some(name) = v.as_str() {
if name.is_empty() || name.len() > 512 {
- return Err(bad(cmd, "a face name is 1…512 characters"));
+ return Err("a face name is 1…512 characters");
}
- let st = if crate::frames::mapped() { s.model.state() } else { s.world_state() };
- return solidcraft_doc::naming::named_face_point(&st, body, name).map_err(|why| bad(cmd, why));
+ return Ok(FaceRefForm::Name(name));
}
- vec3(v).or_else(|| v.get("point").and_then(vec3)).ok_or_else(|| bad(cmd, "a face is a point [x, y, z] on it, or its name from model.faces"))
+ vec3(v).or_else(|| v.get("point").and_then(vec3)).map(FaceRefForm::Point).ok_or("a face is a point [x, y, z] on it, or its name from model.faces")
}
/// The body face under a point: (mesh, face index, distance, body).
diff --git a/crates/engine/src/cmd/features.rs b/crates/engine/src/cmd/features.rs
index ceba6a01d9..8f9d762c66 100644
--- a/crates/engine/src/cmd/features.rs
+++ b/crates/engine/src/cmd/features.rs
@@ -11,7 +11,8 @@ use solidcraft_geom::Vec3;
use super::{CommandSpec, not_in_sketch};
use crate::params::{bad, bool_, expr, req_expr, str_, string_list, vec2, vec3};
-use crate::schema::{BoxParams, ExtrudeParams, FeatureResult, TypedContract, output_schema_for};
+use crate::schema::features::{BoxParams, ExtrudeParams, FeatureResult};
+use crate::schema::{TypedContract, output_schema_for};
use crate::{EngineError, Result, Session};
const BOX_CONTRACT: TypedContract<BoxParams> = TypedContract::new();
@@ -241,11 +242,7 @@ pub(super) fn operation(p: &Value, cmd: &str) -> Result<Operation> {
/// The sketch a feature uses: `sketch` param, the active sketch, or the last sketch.
pub(super) fn feature_sketch(s: &Session, p: &Value, cmd: &str) -> Result<u64> {
if let Some(v) = p.get("sketch") {
- let key = match v {
- Value::Number(n) => n.to_string(),
- Value::String(x) => x.clone(),
- _ => return Err(bad(cmd, "`sketch` must be an id or name")),
- };
+ let key = sketch_key(Some(v)).ok_or_else(|| bad(cmd, "`sketch` must be an id or name"))?;
let f = s.doc.find_feature(&key).ok_or_else(|| bad(cmd, format!("no sketch `{key}`")))?;
return match f.kind {
FeatureKind::Sketch { .. } => Ok(f.id),
@@ -970,45 +967,64 @@ fn edge_points(s: &Session, p: &Value, cmd: &str) -> Result<Vec<Vec3>> {
let mut candidates: Option<Vec<(f64, Vec<solidcraft_kernel::EdgeInfo>)>> = None;
let mut out = Vec::new();
for e in a {
- if let Some(pt) = vec3(e).or_else(|| e.get("point").and_then(vec3)) {
- let bodies = candidates.get_or_insert_with(|| {
- // Mesh bodies have no edges to pick: rounding one is refused later, saying why.
- st.bodies
- .iter()
- .filter(|b| named.is_none_or(|n| b.name == n) && !b.body.is_mesh())
- .filter_map(|b| {
- let size = b.body.size();
- b.body.edges((size * 2e-3).max(1e-3)).ok().map(|edges| (size, edges))
- })
- .collect()
- });
- let mut nearest = f64::INFINITY;
- let on_edge = bodies.iter().any(|(size, edges)| {
- let d = edges
- .iter()
- .flat_map(|e| e.points.windows(2))
- .filter_map(|w| Some(pt.dist_to_segment(*w.first()?, *w.get(1)?)))
- .fold(f64::INFINITY, f64::min);
- nearest = nearest.min(d);
- d <= size * 0.05 + 1e-3
- });
- if !on_edge && !bodies.is_empty() {
- let far = if nearest.is_finite() { format!("the nearest edge is {nearest:.3} mm away") } else { "there is no edge".to_string() };
- return Err(bad(cmd, format!("no edge at [{}, {}, {}]: {far}", pt.x, pt.y, pt.z)));
+ let pt = match edge_ref_form(e).map_err(|why| bad(cmd, why))? {
+ EdgeRefForm::Point(pt) => pt,
+ EdgeRefForm::Index { body, index } => {
+ let idx = index as usize;
+ let b = st.body(body).ok_or_else(|| bad(cmd, format!("no body `{body}`")))?;
+ let tol = (b.body.size() * 2e-3).max(1e-3);
+ let edges = b.body.edges(tol)?;
+ out.push(edges.get(idx).ok_or_else(|| bad(cmd, format!("{body} has no edge {idx}")))?.mid);
+ continue;
}
- out.push(pt);
- continue;
+ };
+ let bodies = candidates.get_or_insert_with(|| {
+ // Mesh bodies have no edges to pick: rounding one is refused later, saying why.
+ st.bodies
+ .iter()
+ .filter(|b| named.is_none_or(|n| b.name == n) && !b.body.is_mesh())
+ .filter_map(|b| {
+ let size = b.body.size();
+ b.body.edges((size * 2e-3).max(1e-3)).ok().map(|edges| (size, edges))
+ })
+ .collect()
+ });
+ let mut nearest = f64::INFINITY;
+ let on_edge = bodies.iter().any(|(size, edges)| {
+ let d = edges
+ .iter()
+ .flat_map(|e| e.points.windows(2))
+ .filter_map(|w| Some(pt.dist_to_segment(*w.first()?, *w.get(1)?)))
+ .fold(f64::INFINITY, f64::min);
+ nearest = nearest.min(d);
+ d <= size * 0.05 + 1e-3
+ });
+ if !on_edge && !bodies.is_empty() {
+ let far = if nearest.is_finite() { format!("the nearest edge is {nearest:.3} mm away") } else { "there is no edge".to_string() };
+ return Err(bad(cmd, format!("no edge at [{}, {}, {}]: {far}", pt.x, pt.y, pt.z)));
}
- let body = e.get("body").and_then(Value::as_str).ok_or_else(|| bad(cmd, "an edge is a point [x,y,z], {point} or {body, index}"))?;
- let idx = e.get("index").and_then(Value::as_u64).ok_or_else(|| bad(cmd, "edge `index` must be a number"))? as usize;
- let b = st.body(body).ok_or_else(|| bad(cmd, format!("no body `{body}`")))?;
- let tol = (b.body.size() * 2e-3).max(1e-3);
- let edges = b.body.edges(tol)?;
- out.push(edges.get(idx).ok_or_else(|| bad(cmd, format!("{body} has no edge {idx}")))?.mid);
+ out.push(pt);
}
Ok(out)
}
+/// An edge reference as given, before it is looked up: see [`edge_points`].
+pub(crate) enum EdgeRefForm<'a> {
+ Point(Vec3),
+ Index { body: &'a str, index: u64 },
+}
+
+/// What [`edge_points`] reads one edge as, without the design: a point on it (`[x, y, z]` or
+/// `{point}`), else `{body, index}`.
+pub(crate) fn edge_ref_form(e: &Value) -> std::result::Result<EdgeRefForm<'_>, &'static str> {
+ if let Some(pt) = vec3(e).or_else(|| e.get("point").and_then(vec3)) {
+ return Ok(EdgeRefForm::Point(pt));
+ }
+ let body = e.get("body").and_then(Value::as_str).ok_or("an edge is a point [x,y,z], {point} or {body, index}")?;
+ let index = e.get("index").and_then(Value::as_u64).ok_or("edge `index` must be a number")?;
+ Ok(EdgeRefForm::Index { body, index })
+}
+
/// Press Pull: a face moves along its normal (an extrude that joins outward or cuts inward); an
/// edge is rounded (a fillet).
fn press_pull(s: &mut Session, p: &Value) -> Result<Value> {
@@ -1920,17 +1936,22 @@ fn draft(s: &mut Session, p: &Value) -> Result<Value> {
}
pub(super) fn sketch_id(s: &Session, v: Option<&Value>, cmd: &str, what: &str) -> Result<u64> {
- let key = match v {
- Some(Value::Number(n)) => n.to_string(),
- Some(Value::String(x)) => x.clone(),
- _ => return Err(bad(cmd, format!("`{what}` must be a sketch id or name"))),
- };
+ let key = sketch_key(v).ok_or_else(|| bad(cmd, format!("`{what}` must be a sketch id or name")))?;
match s.doc.find_feature(&key) {
Some(f) if matches!(f.kind, FeatureKind::Sketch { .. }) => Ok(f.id),
_ => Err(bad(cmd, format!("no sketch `{key}`"))),
}
}
+/// The key [`sketch_id`] and [`feature_sketch`] look a sketch up by: an id (a number) or a name.
+pub(crate) fn sketch_key(v: Option<&Value>) -> Option<String> {
+ match v {
+ Some(Value::Number(n)) => Some(n.to_string()),
+ Some(Value::String(x)) => Some(x.clone()),
+ _ => None,
+ }
+}
+
fn sweep(s: &mut Session, p: &Value) -> Result<Value> {
let cmd = "solid.sweep";
let sketch = feature_sketch(s, p, cmd)?;
diff --git a/crates/engine/src/cmd/inspect.rs b/crates/engine/src/cmd/inspect.rs
index db25052dce..76394f1134 100644
--- a/crates/engine/src/cmd/inspect.rs
+++ b/crates/engine/src/cmd/inspect.rs
@@ -49,7 +49,7 @@ pub static COMMANDS: &[CommandSpec] = &[
.noundo()
.doc_only()
.contract(&DESCRIBE_CONTRACT)
- .output(crate::schema::output_schema_for::<crate::schema::DescribeResult>)
+ .output(crate::schema::output_schema_for::<crate::schema::inspect::DescribeResult>)
.params("command: a command id. Returns {id, label, params, input, output} (and param_warnings in the warn parameter-check mode): the command's parameter documentation and, once the command has a typed contract, the JSON Schemas (2020-12) of its parameters and of a successful result (null otherwise). Read-only."),
];
@@ -326,13 +326,13 @@ fn model_faces(s: &mut Session, p: &Value) -> Result<Value> {
Ok(json!({"body": b.name, "faces": faces}))
}
-const DESCRIBE_CONTRACT: crate::schema::TypedContract<crate::schema::DescribeParams> = crate::schema::TypedContract::new();
+const DESCRIBE_CONTRACT: crate::schema::TypedContract<crate::schema::inspect::DescribeParams> = crate::schema::TypedContract::new();
/// A command's prose documentation and, for converted commands, its schemas.
fn describe(_s: &mut Session, p: &Value) -> Result<Value> {
let id = p.get("command").and_then(Value::as_str).ok_or_else(|| crate::params::bad("engine.describe", "`command` must be a command id"))?;
let spec = super::find_command(id).ok_or_else(|| crate::EngineError::UnknownCommand(id.to_string()))?;
- let reply = crate::schema::DescribeResult {
+ let reply = crate::schema::inspect::DescribeResult {
id: spec.id.to_string(),
label: spec.label.to_string(),
params: spec.params.to_string(),
diff --git a/crates/engine/src/cmd/mod.rs b/crates/engine/src/cmd/mod.rs
index 9e8f0623e0..1b692d75c1 100644
--- a/crates/engine/src/cmd/mod.rs
+++ b/crates/engine/src/cmd/mod.rs
@@ -35,7 +35,9 @@ mod edit;
mod face;
mod features;
mod features_more;
+pub(crate) use face::{FaceRefForm, face_ref_form};
pub(crate) use features::profiles as feature_profiles;
+pub(crate) use features::{EdgeRefForm, edge_ref_form, sketch_key};
pub use features::{auto_operation, extrude_reach};
pub use sketch_modify::trim_piece;
mod component_link;
diff --git a/crates/engine/src/schema/check.rs b/crates/engine/src/schema/check.rs
index a98883e848..251bb78068 100644
--- a/crates/engine/src/schema/check.rs
+++ b/crates/engine/src/schema/check.rs
@@ -129,6 +129,23 @@ pub(crate) fn whole(message: impl std::fmt::Display) -> String {
format!("{WHOLE}{message}")
}
+/// Marks a deserializer's message that carries its own path: an error from a flattened
+/// `FeatureCommon`, which serde can't locate. The path (one of its field names) and the error
+/// follow as JSON.
+const LOCATED: char = '\u{2}';
+
+/// `e`, an error deserializing a flattened `FeatureCommon`, as a deserializer's message that
+/// keeps its path, for [`parse_issue`].
+pub(crate) fn located(e: &serde_path_to_error::Error<serde_json::Error>) -> String {
+ let located = serde_json::to_string(&(error_path(e), e.inner().to_string())).unwrap_or_default();
+ format!("{LOCATED}{located}")
+}
+
+fn error_path(e: &serde_path_to_error::Error<serde_json::Error>) -> String {
+ let path = e.path().to_string();
+ if path == "." { String::new() } else { path }
+}
+
/// The top-level property names of a schema, following `allOf`/`anyOf`/`oneOf` and `$ref`s
/// into the root's `$defs`.
pub(crate) fn schema_keys(root: &Value) -> BTreeSet<String> {
@@ -207,10 +224,15 @@ fn nearest(key: &str, allowed: &BTreeSet<String>) -> Option<String> {
}
/// A deserialization failure as an issue, in the engine's style.
-fn parse_issue(e: &serde_path_to_error::Error<serde_json::Error>) -> Issue {
- let path = e.path().to_string();
- let path = if path == "." { String::new() } else { path };
+pub(crate) fn parse_issue(e: &serde_path_to_error::Error<serde_json::Error>) -> Issue {
+ let path = error_path(e);
let inner = e.inner().to_string();
+ // An error from a flattened `FeatureCommon`: its field continues the path.
+ let (path, inner) = match inner.strip_prefix(LOCATED).and_then(|r| serde_json::from_str::<(String, String)>(r).ok()) {
+ Some((field, inner)) if path.is_empty() => (field, inner),
+ Some((field, inner)) => (format!("{path}.{field}"), inner),
+ None => (path, inner),
+ };
if let Some(complete) = inner.strip_prefix(WHOLE) {
// The handler's own message, which names the caller's value: in full up to a generous
// cap, since the contract also checks keys the handler ignores (`side` without `thin`).
@@ -218,7 +240,7 @@ fn parse_issue(e: &serde_path_to_error::Error<serde_json::Error>) -> Issue {
}
let message = if let Some(field) = inner.strip_prefix("missing field `").and_then(|r| r.split('`').next()) {
let at = if path.is_empty() { field.to_string() } else { format!("{path}.{field}") };
- return Issue { path: at.clone(), message: format!("`{at}` is required"), suggestion: None };
+ return Issue { path: at.clone(), message: truncate(&format!("`{at}` is required"), MAX_MESSAGE_LEN), suggestion: None };
} else if path.is_empty() {
inner
} else if inner.starts_with("must ") {
diff --git a/crates/engine/src/schema/commands.rs b/crates/engine/src/schema/features.rs
similarity index 85%
rename from crates/engine/src/schema/commands.rs
rename to crates/engine/src/schema/features.rs
index c9d7920d08..32f89bcda2 100644
--- a/crates/engine/src/schema/commands.rs
+++ b/crates/engine/src/schema/features.rs
@@ -1,4 +1,4 @@
-//! The converted commands' parameter contracts and result types.
+//! Contracts and result types for the commands in `cmd/features.rs`.
//!
//! Field doc comments are the schemas' descriptions. Keys the handlers read only in some
//! situations (`sketch` without `face`, the thin-wall keys with `thin: true`) are optional
@@ -7,7 +7,6 @@
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
-use serde_json::Value;
use super::types::{
AngleExpr, ConventionParam, DirectionParam, ExtentKeyword, ExtrudeOperation, FacesParam, FromPoint, IdOrName, LengthExpr, OperationParam, Point3,
@@ -161,39 +160,6 @@ pub struct ExtrudeParams {
pub thickness2: Option<LengthExpr>,
}
-/// Which command to describe.
-#[derive(Debug, Deserialize, JsonSchema)]
-#[schemars(deny_unknown_fields)]
-pub struct DescribeParams {
- /// The command's id, such as `solid.extrude`.
- #[serde(deserialize_with = "command_id")]
- pub command: String,
-}
-
-/// A command id, with the `engine.describe` handler's message for anything else.
-fn command_id<'de, D: serde::Deserializer<'de>>(d: D) -> Result<String, D::Error> {
- match Value::deserialize(d)? {
- Value::String(s) => Ok(s),
- _ => Err(serde::de::Error::custom("must be a command id")),
- }
-}
-
-/// What `engine.describe` returns.
-#[derive(Debug, Serialize, JsonSchema)]
-pub struct DescribeResult {
- pub id: String,
- pub label: String,
- /// The command's parameter documentation, as prose.
- pub params: String,
- /// The parameters' JSON Schema, or `null` when the command has no contract yet.
- pub input: Option<Value>,
- /// The successful result's JSON Schema, or `null` when not described yet.
- pub output: Option<Value>,
- /// In the warn parameter-check mode: what the call's parameters got wrong.
- #[serde(default, skip_serializing_if = "Vec::is_empty")]
- pub param_warnings: Vec<String>,
-}
-
/// What a feature command returns.
#[derive(Debug, Serialize, JsonSchema)]
pub struct FeatureResult {
@@ -218,3 +184,7 @@ pub struct FeatureResult {
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub param_warnings: Vec<String>,
}
+
+#[cfg(test)]
+#[path = "features_tests.rs"]
+mod tests;
diff --git a/crates/engine/src/schema/features_tests.rs b/crates/engine/src/schema/features_tests.rs
new file mode 100644
index 0000000000..80b497368a
--- /dev/null
+++ b/crates/engine/src/schema/features_tests.rs
@@ -0,0 +1,127 @@
+use serde_json::{Value, json};
+
+use super::{BoxParams, ExtrudeParams, FeatureResult};
+use crate::Session;
+use crate::schema::tests::{assert_keys, assert_strict_keeps_todays_errors, conforms, sketch_rectangle};
+use crate::schema::{ParamCheck, input_schema_for, output_schema_for};
+
+#[test]
+fn schemas_and_the_key_check_agree() {
+ assert_keys(
+ input_schema_for::<BoxParams>(),
+ &["body_name", "body_names", "center", "corner", "height", "length", "name", "operation", "participants", "targets", "width"],
+ );
+ assert_keys(
+ input_schema_for::<ExtrudeParams>(),
+ &[
+ "body",
+ "body_name",
+ "body_names",
+ "convention",
+ "curves",
+ "direction",
+ "distance",
+ "distance2",
+ "extent",
+ "face",
+ "face_body",
+ "faces",
+ "from",
+ "name",
+ "operation",
+ "participants",
+ "profiles",
+ "side",
+ "sketch",
+ "start_offset",
+ "taper",
+ "targets",
+ "thickness",
+ "thickness2",
+ "thin",
+ "through_all",
+ "to",
+ "to_offset",
+ ],
+ );
+}
+
+#[test]
+fn strict_keeps_todays_errors() {
+ assert_strict_keeps_todays_errors(&[
+ ("solid.box", json!({"length": 5, "width": 5, "height": 5, "operation": "bogus"})),
+ ("solid.box", json!({"length": true, "width": 5, "height": 5})),
+ ("solid.box", json!({"length": 5, "width": 5, "height": 5, "corner": [1, 2]})),
+ ("solid.extrude", json!({"distance": 5, "operation": "bogus"})),
+ ("solid.extrude", json!({"distance": 5, "direction": "sideways"})),
+ ("solid.extrude", json!({"distance": 5, "direction": "SIDEWAYS"})),
+ ("solid.extrude", json!({"distance": 5, "profiles": [{"point": [1]}]})),
+ ("solid.extrude", json!({"distance": 5, "profiles": [["l1"], 7]})),
+ ("solid.extrude", json!({"distance": 5, "profiles": []})),
+ ("solid.extrude", json!({"distance": 5, "profiles": [true]})),
+ ("solid.extrude", json!({"distance": 5, "faces": []})),
+ ("solid.extrude", json!({"distance": 5, "faces": null})),
+ ("solid.extrude", json!({"distance": 5, "faces": [[1, 2]]})),
+ ("solid.extrude", json!({"distance": 5, "profiles": {"offset_boundaries": ["a", "a"]}})),
+ ("solid.extrude", json!({"distance": 5, "thin": true, "thickness": 1, "side": "middle"})),
+ ("solid.extrude", json!({"distance": 5, "thin": "true"})),
+ ("solid.extrude", json!({"distance": 5, "to": [1, 2]})),
+ ("solid.extrude", json!({"distance": 5, "from": "x"})),
+ ("solid.extrude", json!({"distance": 5, "sketch": true})),
+ ("solid.extrude", json!({"distance": 5, "convention": "per_side"})),
+ ("solid.extrude", json!({"distance": " "})),
+ ("solid.extrude", json!({"distance": 5, "operation": "x".repeat(1000)})),
+ ]);
+}
+
+#[test]
+fn feature_result_serializes_like_the_old_reply() {
+ for (warning, ms) in [(None, None), (Some("a Boolean needed a retry".to_string()), Some(12.5)), (None, Some(0.0)), (None, Some(1.0 / 3.0))] {
+ let old = json!({"feature": 7, "name": "Box1", "bodies": ["A", "B"], "created_bodies": ["B"], "changed_bodies": [],
+ "removed_bodies": ["C"], "warning": warning, "ms": ms});
+ let new = FeatureResult {
+ feature: 7,
+ name: "Box1".into(),
+ bodies: vec!["A".into(), "B".into()],
+ created_bodies: vec!["B".into()],
+ changed_bodies: vec![],
+ removed_bodies: vec!["C".into()],
+ warning: warning.clone(),
+ ms,
+ param_warnings: vec![],
+ };
+ assert_eq!(serde_json::to_value(&new).ok(), Some(old));
+ }
+}
+
+#[test]
+fn replies_match_the_output_schema() {
+ let schema = output_schema_for::<FeatureResult>();
+ let schema = schema.as_value();
+ let required: Vec<&str> = schema.get("required").and_then(Value::as_array).into_iter().flatten().filter_map(Value::as_str).collect();
+ assert!(!required.contains(&"param_warnings"));
+ let mut s = Session::default();
+ sketch_rectangle(&mut s);
+ s.param_check = ParamCheck::Warn;
+ let replies = [
+ s.execute("solid.box", &json!({"length": 5, "width": 5, "height": 5, "corner": [20, 0, 0]})),
+ s.execute("solid.extrude", &json!({"distance": 5, "operation": "join"})),
+ s.execute("solid.box", &json!({"length": 5, "width": 5, "height": 5, "colour": "red"})),
+ ];
+ for r in replies {
+ let r = r.unwrap_or_else(|e| panic!("{e}"));
+ assert!(conforms(schema, schema, &r), "{r} doesn't match {schema}");
+ }
+ // The check itself catches a wrong type, a wrong item type and a missing key. (The output
+ // schema leaves other keys open, so a new result key doesn't break clients.)
+ let ok = json!({"feature": 1, "name": "Box1", "bodies": [], "created_bodies": [], "changed_bodies": [], "removed_bodies": [], "warning": null, "ms": null});
+ assert!(conforms(schema, schema, &ok));
+ for (k, v) in [("feature", json!("1")), ("bodies", json!([1])), ("warning", json!(5)), ("ms", json!("1"))] {
+ let mut bad = ok.clone();
+ bad[k] = v;
+ assert!(!conforms(schema, schema, &bad), "{bad}");
+ }
+ let mut bad = ok.clone();
+ bad.as_object_mut().map(|o| o.remove("name"));
+ assert!(!conforms(schema, schema, &bad), "{bad}");
+}
diff --git a/crates/engine/src/schema/inspect.rs b/crates/engine/src/schema/inspect.rs
new file mode 100644
index 0000000000..fc732e4f0d
--- /dev/null
+++ b/crates/engine/src/schema/inspect.rs
@@ -0,0 +1,42 @@
+//! Contracts and result types for the commands in `cmd/inspect.rs`.
+
+use schemars::JsonSchema;
+use serde::{Deserialize, Serialize};
+use serde_json::Value;
+
+/// Which command to describe.
+#[derive(Debug, Deserialize, JsonSchema)]
+#[schemars(deny_unknown_fields)]
+pub struct DescribeParams {
+ /// The command's id, such as `solid.extrude`.
+ #[serde(deserialize_with = "command_id")]
+ pub command: String,
+}
+
+/// A command id, with the `engine.describe` handler's message for anything else.
+fn command_id<'de, D: serde::Deserializer<'de>>(d: D) -> Result<String, D::Error> {
+ match Value::deserialize(d)? {
+ Value::String(s) => Ok(s),
+ _ => Err(serde::de::Error::custom("must be a command id")),
+ }
+}
+
+/// What `engine.describe` returns.
+#[derive(Debug, Serialize, JsonSchema)]
+pub struct DescribeResult {
+ pub id: String,
+ pub label: String,
+ /// The command's parameter documentation, as prose.
+ pub params: String,
+ /// The parameters' JSON Schema, or `null` when the command has no contract yet.
+ pub input: Option<Value>,
+ /// The successful result's JSON Schema, or `null` when not described yet.
+ pub output: Option<Value>,
+ /// In the warn parameter-check mode: what the call's parameters got wrong.
+ #[serde(default, skip_serializing_if = "Vec::is_empty")]
+ pub param_warnings: Vec<String>,
+}
+
+#[cfg(test)]
+#[path = "inspect_tests.rs"]
+mod tests;
diff --git a/crates/engine/src/schema/inspect_tests.rs b/crates/engine/src/schema/inspect_tests.rs
new file mode 100644
index 0000000000..9c0ef91f94
--- /dev/null
+++ b/crates/engine/src/schema/inspect_tests.rs
@@ -0,0 +1,36 @@
+use serde_json::json;
+
+use super::DescribeParams;
+use crate::Session;
+use crate::schema::input_schema_for;
+use crate::schema::tests::{assert_keys, assert_strict_keeps_todays_errors};
+
+#[test]
+fn schemas_and_the_key_check_agree() {
+ assert_keys(input_schema_for::<DescribeParams>(), &["command"]);
+}
+
+#[test]
+fn strict_keeps_todays_errors() {
+ assert_strict_keeps_todays_errors(&[
+ ("engine.describe", json!({"command": 5})),
+ ("engine.describe", json!({"command": null})),
+ ("engine.describe", json!({"command": "solid.extrud"})),
+ ]);
+}
+
+#[test]
+fn describe_returns_both_schemas() {
+ let mut s = Session::default();
+ let d = s.execute("engine.describe", &json!({"command": "solid.box"})).unwrap_or_else(|e| panic!("{e}"));
+ assert_eq!(d["id"], "solid.box");
+ assert!(d["input"]["properties"].get("length").is_some());
+ assert!(d["output"]["properties"].get("created_bodies").is_some());
+ // Its own output schema lists the warnings warn mode can add.
+ let own = s.execute("engine.describe", &json!({"command": "engine.describe"})).unwrap_or_else(|e| panic!("{e}"));
+ assert!(own["output"]["properties"].get("param_warnings").is_some(), "{own}");
+ let d = s.execute("engine.describe", &json!({"command": "solid.revolve"})).unwrap_or_else(|e| panic!("{e}"));
+ assert!(d["input"].is_null() && d["output"].is_null(), "unconverted commands have no schemas yet");
+ let e = s.execute("engine.describe", &json!({"command": "solid.extrud"})).err().map(|e| e.to_string());
+ assert!(e.as_deref().is_some_and(|e| e.contains("did you mean `solid.extrude`")), "{e:?}");
+}
diff --git a/crates/engine/src/schema/mod.rs b/crates/engine/src/schema/mod.rs
index 3ca5105276..266d5fa87c 100644
--- a/crates/engine/src/schema/mod.rs
+++ b/crates/engine/src/schema/mod.rs
@@ -22,15 +22,22 @@
//! more lenient (a value of the wrong type read as if the key were absent), the contract is the
//! stricter of the two; that difference is what warn and strict surface.
//!
-//! To convert a command: declare its parameters type in `commands.rs` (and its reply type, for
-//! an output schema), give its `CommandSpec` `checked!(…)`, `.contract(…)` and `.output(…)` as
-//! `solid.extrude` does, and add it to `schemas_and_the_key_check_agree` and, for messages it
-//! already gives, `strict_keeps_todays_errors`. Then run the whole test suite with the audit
-//! recorder (see `record.rs`): a call that succeeds today but breaks the contract is either a
-//! form the contract is missing or a caller's mistake.
+//! Contracts live in one module per command file: `features.rs` for `cmd/features.rs`,
+//! `inspect.rs` for `cmd/inspect.rs`, and so on, each with its own tests (`features_tests.rs`),
+//! so conversions of different command files touch different files (apart from a new
+//! module's line below).
+//!
+//! To convert a command: declare its parameters type in the module for its command file (and
+//! its reply type, for an output schema), creating the module if it is the file's first
+//! contract, from the shared types in [`types`] (the keys every feature takes come from
+//! [`FeatureCommon`], which `solid.box` and `solid.extrude` predate); give its `CommandSpec`
+//! `checked!(…)`, `.contract(…)` and `.output(…)` as `solid.extrude` does; and add it to that
+//! module's `schemas_and_the_key_check_agree` and, for messages it already gives,
+//! `strict_keeps_todays_errors`. Then run the whole test suite with the audit recorder (see
+//! `record.rs`): a call that succeeds today but breaks the contract is either a form the
+//! contract is missing or a caller's mistake.
mod check;
-mod commands;
#[cfg_attr(target_arch = "wasm32", path = "record_wasm.rs")]
mod record;
mod types;
@@ -38,8 +45,11 @@ mod types;
#[cfg(test)]
mod tests;
+// The contracts, by command file.
+pub mod features;
+pub mod inspect;
+
pub use check::{Contract, Issue, ParamCheck, TypedContract, input_schema_for, output_schema_for, run_checked};
-pub use commands::{BoxParams, DescribeParams, DescribeResult, ExtrudeParams, FeatureResult};
pub use types::*;
/// A command's `run` that checks the call against `$contract` before running `$handler`
diff --git a/crates/engine/src/schema/tests.rs b/crates/engine/src/schema/tests.rs
index 390c4eaab0..aa5ef6aea8 100644
--- a/crates/engine/src/schema/tests.rs
+++ b/crates/engine/src/schema/tests.rs
@@ -1,7 +1,12 @@
+//! Tests of the shared types and the checking machinery, and helpers for the per-module tests
+//! (`features_tests.rs`, …).
+
+use schemars::Schema;
use serde::de::DeserializeOwned;
use serde_json::{Value, json};
use super::check::schema_keys;
+use super::features::{BoxParams, ExtrudeParams};
use super::*;
use crate::Session;
@@ -159,54 +164,6 @@ fn shape_problems_are_issues() {
assert!(messages(&c.check(&Value::Object(many))).iter().any(|m| m.starts_with("too many parameters")));
}
-#[test]
-fn schemas_and_the_key_check_agree() {
- for (schema, fields) in [
- (
- input_schema_for::<BoxParams>(),
- vec!["body_name", "body_names", "center", "corner", "height", "length", "name", "operation", "participants", "targets", "width"],
- ),
- (
- input_schema_for::<ExtrudeParams>(),
- vec![
- "body",
- "body_name",
- "body_names",
- "convention",
- "curves",
- "direction",
- "distance",
- "distance2",
- "extent",
- "face",
- "face_body",
- "faces",
- "from",
- "name",
- "operation",
- "participants",
- "profiles",
- "side",
- "sketch",
- "start_offset",
- "taper",
- "targets",
- "thickness",
- "thickness2",
- "thin",
- "through_all",
- "to",
- "to_offset",
- ],
- ),
- ] {
- let v = schema.as_value();
- assert_eq!(schema_keys(v).into_iter().collect::<Vec<_>>(), fields);
- assert_eq!(v.get("additionalProperties"), Some(&json!(false)), "the schema refuses unknown keys too");
- assert_eq!(v.get("$schema").and_then(Value::as_str), Some("https://json-schema.org/draft/2020-12/schema"));
- }
-}
-
#[test]
fn present_null_is_refused_but_absent_is_fine() {
let base = json!({"length": 5, "width": 5, "height": 5});
@@ -228,7 +185,7 @@ fn present_null_is_refused_but_absent_is_fine() {
}
}
-fn sketch_rectangle(s: &mut Session) {
+pub(super) fn sketch_rectangle(s: &mut Session) {
for (id, p) in [
("sketch.create", json!({"plane": "XY"})),
("sketch.rectangle.center", json!({"center": [0, 0], "corner": [10, 10]})),
@@ -302,32 +259,12 @@ fn the_level_survives_a_new_design() {
assert_eq!(s.scratch().param_check, ParamCheck::Strict);
}
-#[test]
-fn feature_result_serializes_like_the_old_reply() {
- for (warning, ms) in [(None, None), (Some("a Boolean needed a retry".to_string()), Some(12.5)), (None, Some(0.0)), (None, Some(1.0 / 3.0))] {
- let old = json!({"feature": 7, "name": "Box1", "bodies": ["A", "B"], "created_bodies": ["B"], "changed_bodies": [],
- "removed_bodies": ["C"], "warning": warning, "ms": ms});
- let new = FeatureResult {
- feature: 7,
- name: "Box1".into(),
- bodies: vec!["A".into(), "B".into()],
- created_bodies: vec!["B".into()],
- changed_bodies: vec![],
- removed_bodies: vec!["C".into()],
- warning: warning.clone(),
- ms,
- param_warnings: vec![],
- };
- assert_eq!(serde_json::to_value(&new).ok(), Some(old));
- }
-}
-
/// Whether `v` conforms to `node` of the schema `root`, for the keywords these schemas use
/// apart from `pattern`: `type`, `properties`, `required`, `additionalProperties: false`,
/// `items`, `minItems`, `maxItems`, `uniqueItems`, `enum`, `minLength`, `maxLength`, `minimum`,
/// `maximum`, `exclusiveMinimum`, `exclusiveMaximum`, `anyOf`, `not` and `$ref`. (`integer`
/// here is what serde reads as one, so `1.0` is not.)
-fn conforms(root: &Value, node: &Value, v: &Value) -> bool {
+pub(super) fn conforms(root: &Value, node: &Value, v: &Value) -> bool {
if let Some(name) = node.get("$ref").and_then(Value::as_str).and_then(|r| r.strip_prefix("#/$defs/")) {
return root.get("$defs").and_then(|d| d.get(name)).is_some_and(|t| conforms(root, t, v));
}
@@ -410,38 +347,6 @@ fn conforms(root: &Value, node: &Value, v: &Value) -> bool {
true
}
-#[test]
-fn replies_match_the_output_schema() {
- let schema = output_schema_for::<FeatureResult>();
- let schema = schema.as_value();
- let required: Vec<&str> = schema.get("required").and_then(Value::as_array).into_iter().flatten().filter_map(Value::as_str).collect();
- assert!(!required.contains(&"param_warnings"));
- let mut s = Session::default();
- sketch_rectangle(&mut s);
- s.param_check = ParamCheck::Warn;
- let replies = [
- s.execute("solid.box", &json!({"length": 5, "width": 5, "height": 5, "corner": [20, 0, 0]})),
- s.execute("solid.extrude", &json!({"distance": 5, "operation": "join"})),
- s.execute("solid.box", &json!({"length": 5, "width": 5, "height": 5, "colour": "red"})),
- ];
- for r in replies {
- let r = r.unwrap_or_else(|e| panic!("{e}"));
- assert!(conforms(schema, schema, &r), "{r} doesn't match {schema}");
- }
- // The check itself catches a wrong type, a wrong item type and a missing key. (The output
- // schema leaves other keys open, so a new result key doesn't break clients.)
- let ok = json!({"feature": 1, "name": "Box1", "bodies": [], "created_bodies": [], "changed_bodies": [], "removed_bodies": [], "warning": null, "ms": null});
- assert!(conforms(schema, schema, &ok));
- for (k, v) in [("feature", json!("1")), ("bodies", json!([1])), ("warning", json!(5)), ("ms", json!("1"))] {
- let mut bad = ok.clone();
- bad[k] = v;
- assert!(!conforms(schema, schema, &bad), "{bad}");
- }
- let mut bad = ok.clone();
- bad.as_object_mut().map(|o| o.remove("name"));
- assert!(!conforms(schema, schema, &bad), "{bad}");
-}
-
#[cfg(not(target_arch = "wasm32"))]
#[test]
fn the_recorder_keeps_a_bounded_number_of_signatures() {
@@ -459,22 +364,6 @@ fn the_recorder_keeps_a_bounded_number_of_signatures() {
assert_eq!(seen.len(), 3);
}
-#[test]
-fn describe_returns_both_schemas() {
- let mut s = Session::default();
- let d = s.execute("engine.describe", &json!({"command": "solid.box"})).unwrap_or_else(|e| panic!("{e}"));
- assert_eq!(d["id"], "solid.box");
- assert!(d["input"]["properties"].get("length").is_some());
- assert!(d["output"]["properties"].get("created_bodies").is_some());
- // Its own output schema lists the warnings warn mode can add.
- let own = s.execute("engine.describe", &json!({"command": "engine.describe"})).unwrap_or_else(|e| panic!("{e}"));
- assert!(own["output"]["properties"].get("param_warnings").is_some(), "{own}");
- let d = s.execute("engine.describe", &json!({"command": "solid.revolve"})).unwrap_or_else(|e| panic!("{e}"));
- assert!(d["input"].is_null() && d["output"].is_null(), "unconverted commands have no schemas yet");
- let e = s.execute("engine.describe", &json!({"command": "solid.extrud"})).err().map(|e| e.to_string());
- assert!(e.as_deref().is_some_and(|e| e.contains("did you mean `solid.extrude`")), "{e:?}");
-}
-
/// The profiles schema and the contract agree on every listed case; the schema is deliberately
/// narrower on non-text curve ids and loops past the outer one (and describes the app's
/// `whole_boundaries` selection only by its `type`).
@@ -554,43 +443,29 @@ fn recorder_lines_have_the_documented_shape() {
assert_eq!(super::record::enabled(), cfg!(feature = "param-audit") && set);
}
+/// A contract's input schema lists exactly `fields` (sorted) as its keys, refuses other keys
+/// and declares draft 2020-12. Each module's `schemas_and_the_key_check_agree` calls this for
+/// its contracts, so their keys change only on purpose. (Whether the keys are the ones the
+/// handler reads is what the audit run checks.)
+pub(super) fn assert_keys(schema: Schema, fields: &[&str]) {
+ let v = schema.as_value();
+ assert_eq!(schema_keys(v).into_iter().collect::<Vec<_>>(), fields);
+ assert_eq!(v.get("additionalProperties"), Some(&json!(false)), "the schema refuses unknown keys too");
+ assert_eq!(v.get("$schema").and_then(Value::as_str), Some("https://json-schema.org/draft/2020-12/schema"));
+}
+
/// A call that already fails gets the same error in strict as with the check off, apart from
/// the missing-key, missing-instead-of-wrong-type, non-object, profile-index, 10,000-item and
-/// over-4-KB messages the report lists.
-#[test]
-fn strict_keeps_todays_errors() {
- let cases = [
- ("solid.box", json!({"length": 5, "width": 5, "height": 5, "operation": "bogus"})),
- ("solid.box", json!({"length": true, "width": 5, "height": 5})),
- ("solid.box", json!({"length": 5, "width": 5, "height": 5, "corner": [1, 2]})),
- ("solid.extrude", json!({"distance": 5, "operation": "bogus"})),
- ("solid.extrude", json!({"distance": 5, "direction": "sideways"})),
- ("solid.extrude", json!({"distance": 5, "direction": "SIDEWAYS"})),
- ("solid.extrude", json!({"distance": 5, "profiles": [{"point": [1]}]})),
- ("solid.extrude", json!({"distance": 5, "profiles": [["l1"], 7]})),
- ("solid.extrude", json!({"distance": 5, "profiles": []})),
- ("solid.extrude", json!({"distance": 5, "profiles": [true]})),
- ("solid.extrude", json!({"distance": 5, "faces": []})),
- ("solid.extrude", json!({"distance": 5, "faces": null})),
- ("solid.extrude", json!({"distance": 5, "faces": [[1, 2]]})),
- ("solid.extrude", json!({"distance": 5, "profiles": {"offset_boundaries": ["a", "a"]}})),
- ("solid.extrude", json!({"distance": 5, "thin": true, "thickness": 1, "side": "middle"})),
- ("solid.extrude", json!({"distance": 5, "thin": "true"})),
- ("solid.extrude", json!({"distance": 5, "to": [1, 2]})),
- ("solid.extrude", json!({"distance": 5, "from": "x"})),
- ("solid.extrude", json!({"distance": 5, "sketch": true})),
- ("solid.extrude", json!({"distance": 5, "convention": "per_side"})),
- ("solid.extrude", json!({"distance": " "})),
- ("solid.extrude", json!({"distance": 5, "operation": "x".repeat(1000)})),
- ("engine.describe", json!({"command": 5})),
- ("engine.describe", json!({"command": null})),
- ("engine.describe", json!({"command": "solid.extrud"})),
- ];
+/// over-4-KB messages the report lists, and a list of picks where one finds nothing in the
+/// design and a later one is malformed (the handler fails on the first, strict on the second).
+/// Each module's `strict_keeps_todays_errors` calls this with its commands' cases; each runs
+/// after `sketch_rectangle`.
+pub(super) fn assert_strict_keeps_todays_errors(cases: &[(&str, Value)]) {
for (id, p) in cases {
let error = |level: ParamCheck| {
let mut s = Session { param_check: level, ..Session::default() };
sketch_rectangle(&mut s);
- s.execute(id, &p).err().map(|e| e.to_string())
+ s.execute(id, p).err().map(|e| e.to_string())
};
let off = error(ParamCheck::Off);
assert!(off.is_some(), "{p} should fail today");
@@ -601,7 +476,10 @@ fn strict_keeps_todays_errors() {
/// Every `default` in the input schemas is a value its own property schema allows.
#[test]
fn schema_defaults_are_valid() {
- for root in [input_schema_for::<BoxParams>(), input_schema_for::<ExtrudeParams>()] {
+ let contracts: Vec<_> = crate::cmd::command_specs().into_iter().filter_map(|c| c.contract).collect();
+ assert!(contracts.len() >= 3);
+ for c in contracts {
+ let root = c.input_schema();
let root = root.as_value();
for (key, property) in root["properties"].as_object().into_iter().flatten() {
if let Some(d) = property.get("default") {
@@ -631,3 +509,235 @@ fn long_values_in_handler_messages_are_capped() {
let w = r["param_warnings"][0].as_str().unwrap_or_default();
assert!(w.starts_with("unknown side `xxx") && w.len() <= 4096 + "…".len(), "{} bytes", w.len());
}
+
+/// The pick types accept what the pick readers accept. (Comparing a type with the helper it
+/// calls only guards against the two drifting apart; the schema comparisons and the handler
+/// tests below are the real checks.)
+#[test]
+fn face_and_edge_refs_match_the_pick_readers() {
+ let long = "f".repeat(513);
+ // 171 three-byte characters are 513 bytes, too long for the reader; the schema's maxLength
+ // counts characters, so it can't say this.
+ let wide = "面".repeat(171);
+ let face_schema = input_schema_for::<FaceRef>();
+ let face_schema = face_schema.as_value();
+ let edge_schema = input_schema_for::<EdgeRef>();
+ let edge_schema = edge_schema.as_value();
+ for v in [
+ json!([1, 2, 3]),
+ json!({"x": 1, "y": 2, "z": 3}),
+ json!({"point": [1, 2, 3]}),
+ json!({"point": {"x": 1, "y": 2, "z": 3}}),
+ json!({"x": "a", "point": [1, 2, 3]}),
+ json!("F3:1"),
+ json!(""),
+ json!(long),
+ json!([1, 2]),
+ json!([1e9, 0, 0]),
+ json!({"point": [1, 2]}),
+ json!({"body": "A", "index": 0}),
+ json!({"body": "A", "index": u64::MAX}),
+ json!({"body": "A", "index": -1}),
+ json!({"body": 5, "index": 0}),
+ json!({"body": "A"}),
+ json!({"point": "x", "body": "A", "index": 2}),
+ json!(null),
+ json!(5),
+ json!(true),
+ ] {
+ let face = crate::cmd::face_ref_form(&v).is_ok();
+ assert_eq!(parse::<FaceRef>(v.clone()).is_some(), face, "{v}");
+ assert_eq!(conforms(face_schema, face_schema, &v), face, "face {v}");
+ let edge = crate::cmd::edge_ref_form(&v).is_ok();
+ assert_eq!(parse::<EdgeRef>(v.clone()).is_some(), edge, "{v}");
+ assert_eq!(conforms(edge_schema, edge_schema, &v), edge, "edge {v}");
+ }
+ // Where the schemas can't follow the readers: a name's cap is in bytes, and an index of
+ // `1.0`, which the reader refuses, is an integer to JSON Schema (`conforms` reads integers
+ // as serde does, so it agrees with the reader here; a standard validator would not).
+ assert!(parse::<FaceRef>(json!(wide)).is_none() && conforms(face_schema, face_schema, &json!(wide)));
+ assert!(parse::<EdgeRef>(json!({"body": "A", "index": 1.0})).is_none());
+ assert_eq!(edge_schema["anyOf"][2]["properties"]["index"]["type"], "integer");
+ assert_eq!(parse::<EdgeRef>(json!({"body": "A", "index": 4})), Some(EdgeRef::Index { body: "A".into(), index: 4 }));
+ assert_eq!(parse::<FaceRef>(json!({"point": [1, 2, 3]})), Some(FaceRef::Point(solidcraft_geom::Vec3::new(1.0, 2.0, 3.0))));
+}
+
+/// The pick lists take 1 to 1000 picks, as `face_points` and `edge_points` do, and so do their
+/// schemas.
+#[test]
+fn pick_lists_match_the_list_readers() {
+ let faces = input_schema_for::<FaceRefs>();
+ let faces = faces.as_value();
+ let edges = input_schema_for::<EdgeRefs>();
+ let edges = edges.as_value();
+ let point = json!([1, 2, 3]);
+ for (v, accepted) in [
+ (json!([point]), true),
+ (json!(vec![point.clone(); 1000]), true),
+ (json!([point, {"point": [4, 5, 6]}]), true),
+ (json!([]), false),
+ (json!(vec![point.clone(); 1001]), false),
+ (json!([point, [1, 2]]), false),
+ (json!(point), false),
+ (json!(null), false),
+ (json!("F1"), false),
+ ] {
+ assert_eq!(parse::<FaceRefs>(v.clone()).is_some(), accepted, "{v}");
+ assert_eq!(conforms(faces, faces, &v), accepted, "faces {v}");
+ assert_eq!(parse::<EdgeRefs>(v.clone()).is_some(), accepted, "{v}");
+ assert_eq!(conforms(edges, edges, &v), accepted, "edges {v}");
+ }
+ // Names are faces, not edges; `{body, index}` is an edge, not a face.
+ let mixed = json!(["F1", {"body": "A", "index": 0}]);
+ assert!(parse::<FaceRefs>(json!(["F1"])).is_some() && parse::<EdgeRefs>(json!(["F1"])).is_none());
+ assert!(parse::<FaceRefs>(mixed.clone()).is_none() && !conforms(faces, faces, &mixed));
+ assert_eq!(parse::<EdgeRefs>(json!([{"body": "A", "index": 0}])).map(|e| e.0.len()), Some(1));
+}
+
+#[test]
+fn sketch_refs_match_sketch_id() {
+ let schema = input_schema_for::<SketchRef>();
+ let schema = schema.as_value();
+ for v in [json!(3), json!(2.5), json!(-1), json!("Profile"), json!(""), json!(null), json!(true), json!([1]), json!({"id": 1})] {
+ let sketch = crate::cmd::sketch_key(Some(&v));
+ assert_eq!(parse::<SketchRef>(v.clone()).map(|s| s.0), sketch, "{v}");
+ assert_eq!(conforms(schema, schema, &v), sketch.is_some(), "{v}");
+ }
+}
+
+/// A contract built from the shared types, as a converted feature command's would be: the pick
+/// keys refuse `null`, as their readers do.
+#[derive(Debug, serde::Deserialize, schemars::JsonSchema)]
+#[schemars(deny_unknown_fields)]
+#[allow(dead_code)]
+struct Probe {
+ radius: LengthExpr,
+ #[serde(default, deserialize_with = "present")]
+ #[schemars(with = "FaceRefs")]
+ faces: Option<FaceRefs>,
+ #[serde(default, deserialize_with = "present")]
+ #[schemars(with = "EdgeRefs")]
+ edges: Option<EdgeRefs>,
+ #[serde(default, deserialize_with = "present")]
+ #[schemars(with = "SketchRef")]
+ path_sketch: Option<SketchRef>,
+ #[serde(flatten, deserialize_with = "feature_common")]
+ common: FeatureCommon,
+}
+
+#[test]
+fn feature_common_flattens_into_a_contract() {
+ let c = TypedContract::<Probe>::new();
+ assert_keys(input_schema_for::<Probe>(), &["body_name", "body_names", "edges", "faces", "name", "participants", "path_sketch", "radius"]);
+ let ok = c.check(&json!({"radius": 1, "name": "Round", "body_name": "B", "body_names": ["B", "C"], "participants": "A"}));
+ assert!(ok.is_empty(), "{ok:?}");
+ assert!(c.check(&json!({"radius": 1, "name": null, "participants": null})).is_empty(), "null is absent, as for `str_`");
+ let parsed: Option<Probe> = parse(json!({"radius": 1, "name": "Round", "participants": ["A", "B"]}));
+ assert_eq!(parsed.map(|p| p.common.participants), Some(Some(StringList(vec!["A".into(), "B".into()]))));
+ // Messages and paths name the key, as for the parent's own fields.
+ for (p, path, message) in [
+ (json!({"radius": 1, "name": 5}), "name", "`name` must be text"),
+ (json!({"radius": 1, "body_name": [1]}), "body_name", "`body_name` must be text"),
+ (json!({"radius": 1, "participants": 5}), "participants", "`participants` must be a name or a list of names"),
+ (json!({"radius": 1, "body_names": vec!["x"; 10_001]}), "body_names", "`body_names` must have at most 10000 items"),
+ (json!({"radius": 1, "bodyname": "x"}), "bodyname", "unknown key `bodyname`; did you mean `body_name`?"),
+ (json!({"radius": 1, "faces": null}), "faces", "`faces` must be a list of points or face names"),
+ (json!({"radius": 1, "edges": null}), "edges", "`edges` must be a list"),
+ (json!({"radius": 1, "path_sketch": null}), "path_sketch", "`path_sketch` must be a sketch id or name"),
+ (json!({"name": "x"}), "radius", "`radius` is required"),
+ // The flattened keys are read after the parent's own, whatever their order.
+ (json!({"name": 5}), "radius", "`radius` is required"),
+ (json!({"body_name": 5, "radius": true}), "radius", "`radius` must be a number or an expression"),
+ ] {
+ let issues = c.check(&p);
+ assert_eq!(messages(&issues), vec![message], "{p}");
+ assert_eq!(issues.first().map(|i| i.path.as_str()), Some(path), "{p}");
+ }
+}
+
+/// A flattened `FeatureCommon`'s errors are located below wherever its parent is.
+#[test]
+fn feature_common_errors_keep_their_place() {
+ #[derive(Debug, serde::Deserialize, schemars::JsonSchema)]
+ #[allow(dead_code)]
+ struct Outer {
+ options: Probe,
+ #[serde(default)]
+ list: Vec<Probe>,
+ }
+ let c = TypedContract::<Outer>::new();
+ let probe = json!({"radius": 1});
+ for (p, path, message) in [
+ (json!({"options": {"radius": 1, "name": 5}}), "options.name", "`options.name` must be text"),
+ (
+ json!({"options": probe, "list": [probe, {"radius": 1, "participants": 5}]}),
+ "list[1].participants",
+ "`list[1].participants` must be a name or a list of names",
+ ),
+ (json!({"options": probe, "list": [{"radius": 1, "faces": []}]}), "list[0].faces", "select 1…1000 faces"),
+ ] {
+ let issues = c.check(&p);
+ assert_eq!(messages(&issues), vec![message], "{p}");
+ assert_eq!(issues.first().map(|i| i.path.as_str()), Some(path), "{p}");
+ }
+}
+
+/// The pick types refuse what the handlers refuse, with the handlers' messages.
+#[test]
+fn shared_types_keep_the_handlers_messages() {
+ let c = TypedContract::<Probe>::new();
+ let mut s = Session::default();
+ s.execute("solid.box", &json!({"length": 10, "width": 10, "height": 10})).unwrap_or_else(|e| panic!("{e}"));
+ sketch_rectangle(&mut s);
+ for (id, p, probe) in [
+ ("solid.shell", json!({"thickness": 1, "faces": 5}), json!({"faces": 5})),
+ ("solid.shell", json!({"thickness": 1, "faces": null}), json!({"faces": null})),
+ ("solid.shell", json!({"thickness": 1, "faces": []}), json!({"faces": []})),
+ ("solid.shell", json!({"thickness": 1, "faces": [true]}), json!({"faces": [true]})),
+ ("solid.shell", json!({"thickness": 1, "faces": [""]}), json!({"faces": [""]})),
+ ("solid.fillet", json!({"radius": 1, "edges": {}}), json!({"edges": {}})),
+ ("solid.fillet", json!({"radius": 1, "edges": vec![[0, 0, 0]; 1001]}), json!({"edges": vec![[0, 0, 0]; 1001]})),
+ ("solid.fillet", json!({"radius": 1, "edges": [[1, 2]]}), json!({"edges": [[1, 2]]})),
+ ("solid.fillet", json!({"radius": 1, "edges": [{"body": "Body1", "index": "0"}]}), json!({"edges": [{"body": "Body1", "index": "0"}]})),
+ ("solid.sweep", json!({"path_sketch": true, "path": ["l1"]}), json!({"path_sketch": true})),
+ ("solid.sweep", json!({"path_sketch": null, "path": ["l1"]}), json!({"path_sketch": null})),
+ ] {
+ let mut probe = probe;
+ probe["radius"] = json!(1);
+ let issue = messages(&c.check(&probe)).into_iter().next().unwrap_or_default();
+ let today = s.execute(id, &p).err().map(|e| e.to_string());
+ assert_eq!(today, Some(crate::params::bad(id, issue).to_string()), "{id} {p}");
+ }
+}
+
+/// The lookups that follow the shape checks the pick types share with the handlers: picks
+/// by `{body, index}` and sketches by name still find the design, and still fail in order, one
+/// pick at a time.
+#[test]
+fn picks_are_still_looked_up_one_at_a_time() {
+ let mut s = Session::default();
+ s.execute("solid.box", &json!({"length": 10, "width": 10, "height": 10})).unwrap_or_else(|e| panic!("{e}"));
+ let error = |s: &mut Session, id: &str, p: Value| s.execute(id, &p).err().map(|e| e.to_string()).unwrap_or_default();
+ let fillet = |edges: Value| json!({"radius": 1, "edges": edges});
+ assert_eq!(
+ error(&mut s, "solid.fillet", fillet(json!([{"body": "Nope", "index": 0}, [1, 2]]))),
+ "invalid parameters for `solid.fillet`: no body `Nope`"
+ );
+ assert_eq!(
+ error(&mut s, "solid.fillet", fillet(json!([{"body": "Body1", "index": 999}]))),
+ "invalid parameters for `solid.fillet`: Body1 has no edge 999"
+ );
+ let far = error(&mut s, "solid.fillet", fillet(json!([[100, 100, 100], [1, 2]])));
+ assert!(far.starts_with("invalid parameters for `solid.fillet`: no edge at [100, 100, 100]"), "{far}");
+ let unknown = error(&mut s, "solid.shell", json!({"thickness": 1, "faces": ["NoSuchFace"]}));
+ assert!(!unknown.is_empty());
+ assert_eq!(error(&mut s, "solid.shell", json!({"thickness": 1, "faces": ["NoSuchFace", true]})), unknown, "the name is looked up first");
+ sketch_rectangle(&mut s);
+ assert_eq!(
+ error(&mut s, "solid.sweep", json!({"path_sketch": "Nope", "path": ["l1"]})),
+ "invalid parameters for `solid.sweep`: no sketch `Nope`"
+ );
+ assert_eq!(error(&mut s, "solid.extrude", json!({"distance": 5, "sketch": "Nope"})), "invalid parameters for `solid.extrude`: no sketch `Nope`");
+ let r = s.execute("solid.fillet", &fillet(json!([{"body": "Body1", "index": 0}]))).unwrap_or_else(|e| panic!("{e}"));
+ assert_eq!(r["changed_bodies"], json!(["Body1"]), "{r}");
+}
diff --git a/crates/engine/src/schema/types.rs b/crates/engine/src/schema/types.rs
index 519641f585..6cc26ba6d2 100644
--- a/crates/engine/src/schema/types.rs
+++ b/crates/engine/src/schema/types.rs
@@ -583,3 +583,201 @@ impl JsonSchema for ProfilesParam {
})
}
}
+
+/// A face given to a command, as `face::face_ref` reads it: a point on the face (`[x, y, z]`,
+/// `{x, y, z}` or `{point}`) or its name as `model.faces` lists it (1 to 512 bytes; the
+/// schema's `maxLength` counts characters, so it can't say bytes). Whether it finds a face is
+/// checked by the handler, which has the design. (Not `solidcraft_doc::FacePick`, the stored
+/// pick.)
+#[derive(Clone, Debug, PartialEq)]
+pub enum FaceRef {
+ Point(Vec3),
+ Name(String),
+}
+
+impl<'de> Deserialize<'de> for FaceRef {
+ fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
+ match crate::cmd::face_ref_form(&Value::deserialize(d)?) {
+ Ok(crate::cmd::FaceRefForm::Point(p)) => Ok(FaceRef::Point(p)),
+ Ok(crate::cmd::FaceRefForm::Name(n)) => Ok(FaceRef::Name(n.to_string())),
+ Err(why) => Err(D::Error::custom(whole(why))),
+ }
+ }
+}
+
+impl JsonSchema for FaceRef {
+ fn schema_name() -> Cow<'static, str> {
+ "FaceRef".into()
+ }
+ fn json_schema(generator: &mut SchemaGenerator) -> Schema {
+ let point = generator.subschema_for::<Point3>();
+ json_schema!({
+ "description": "A face: a point in mm on it ([x, y, z], {\"x\", \"y\", \"z\"} or {\"point\": [x, y, z]}), or its name as model.faces lists it (at most 512 bytes of UTF-8).",
+ "anyOf": [
+ point,
+ {"type": "object", "properties": {"point": point}, "required": ["point"]},
+ {"type": "string", "minLength": 1, "maxLength": 512}
+ ]
+ })
+ }
+}
+
+/// An edge given to a fillet or chamfer, as `features::edge_points` reads it: a point on the
+/// edge (`[x, y, z]`, `{x, y, z}` or `{point}`), else `{body, index}` in the body's edge order.
+/// The index is whole-number JSON, as `Value::as_u64` reads it: JSON Schema also counts `1.0`
+/// as an integer, which the reader refuses. Whether it finds an edge is checked by the handler,
+/// which has the design. (Not `solidcraft_doc::EdgeRef`, the stored edge position.)
+#[derive(Clone, Debug, PartialEq)]
+pub enum EdgeRef {
+ Point(Vec3),
+ Index { body: String, index: u64 },
+}
+
+impl<'de> Deserialize<'de> for EdgeRef {
+ fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
+ match crate::cmd::edge_ref_form(&Value::deserialize(d)?) {
+ Ok(crate::cmd::EdgeRefForm::Point(p)) => Ok(EdgeRef::Point(p)),
+ Ok(crate::cmd::EdgeRefForm::Index { body, index }) => Ok(EdgeRef::Index { body: body.to_string(), index }),
+ Err(why) => Err(D::Error::custom(whole(why))),
+ }
+ }
+}
+
+impl JsonSchema for EdgeRef {
+ fn schema_name() -> Cow<'static, str> {
+ "EdgeRef".into()
+ }
+ fn json_schema(generator: &mut SchemaGenerator) -> Schema {
+ let point = generator.subschema_for::<Point3>();
+ json_schema!({
+ "description": "An edge: a point in mm on it ([x, y, z], {\"x\", \"y\", \"z\"} or {\"point\": [x, y, z]}), or {\"body\", \"index\"} in the body's edge order (an index written without a fraction).",
+ "anyOf": [
+ point,
+ {"type": "object", "properties": {"point": point}, "required": ["point"]},
+ {
+ "type": "object",
+ "properties": {"body": {"type": "string"}, "index": {"type": "integer", "minimum": 0, "maximum": u64::MAX}},
+ "required": ["body", "index"]
+ }
+ ]
+ })
+ }
+}
+
+/// A list of 1 to 1000 picks, with the handler's messages for the list itself. Like the handler,
+/// it refuses `null`: an optional field of this type takes `present`.
+///
+/// The handler looks each pick up in the design before reading the next, so a call with a pick
+/// that finds nothing and a later malformed one fails today on the first and in strict on the
+/// second.
+macro_rules! pick_list {
+ ($(#[$doc:meta])* $name:ident, $item:ty, $not_list:literal, $count:literal, $description:literal) => {
+ $(#[$doc])*
+ #[derive(Clone, Debug, PartialEq)]
+ pub struct $name(pub Vec<$item>);
+
+ impl<'de> Deserialize<'de> for $name {
+ fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
+ let v = Value::deserialize(d)?;
+ let items = v.as_array().ok_or_else(|| D::Error::custom(whole($not_list)))?;
+ if items.is_empty() || items.len() > 1000 {
+ return Err(D::Error::custom(whole($count)));
+ }
+ items.iter().map(|item| <$item>::deserialize(item).map_err(D::Error::custom)).collect::<Result<_, _>>().map($name)
+ }
+ }
+
+ impl JsonSchema for $name {
+ fn schema_name() -> Cow<'static, str> {
+ stringify!($name).into()
+ }
+ fn json_schema(generator: &mut SchemaGenerator) -> Schema {
+ let item = generator.subschema_for::<$item>();
+ json_schema!({"description": $description, "type": "array", "items": item, "minItems": 1, "maxItems": 1000})
+ }
+ }
+ };
+}
+
+pick_list!(
+ /// The `faces` of `solid.shell`, `solid.draft`, `solid.offset_face`, `solid.split_face` and
+ /// `face.delete`, as `features::face_points` reads them. (Extrude's `faces` is a
+ /// [`FacesParam`].)
+ FaceRefs,
+ FaceRef,
+ "`faces` must be a list of points or face names",
+ "select 1…1000 faces",
+ "The faces, 1 to 1000."
+);
+pick_list!(
+ /// The `edges` of `solid.fillet` and `solid.chamfer`, as `features::edge_points` reads them.
+ EdgeRefs,
+ EdgeRef,
+ "`edges` must be a list",
+ "select 1…1000 edges",
+ "The edges, 1 to 1000."
+);
+
+/// A sketch referred to by its feature id (a number) or its name, as `features::sketch_id` reads
+/// it, with its message for a top-level key (`path_sketch`, `solid.split_face`'s `sketch`…);
+/// for a nested one (a section's `sketch`) the message names the key as `sections[0].sketch`
+/// where the handler says `sections[].sketch`. The `sketch` that `features::feature_sketch`
+/// reads (extrude's, revolve's…) has another message and is an [`IdOrName`]. Where the reader
+/// refuses `null`, an optional field of this type takes `present`. Whether a sketch has that id
+/// or name is checked by the handler.
+#[derive(Clone, Debug, PartialEq)]
+pub struct SketchRef(pub String);
+
+impl<'de> Deserialize<'de> for SketchRef {
+ fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
+ crate::cmd::sketch_key(Some(&Value::deserialize(d)?)).map(SketchRef).ok_or_else(|| D::Error::custom("must be a sketch id or name"))
+ }
+}
+
+impl JsonSchema for SketchRef {
+ fn schema_name() -> Cow<'static, str> {
+ "SketchRef".into()
+ }
+ fn json_schema(_: &mut SchemaGenerator) -> Schema {
+ json_schema!({"description": "A sketch's feature id (a number) or its name.", "type": ["number", "string"]})
+ }
+}
+
+/// The keys `features::add_feature` reads for every feature command, whatever else it takes:
+/// the feature's name, the new bodies' names and the bodies taking part. A feature command's
+/// parameters include it with
+///
+/// ```ignore
+/// #[serde(flatten, deserialize_with = "feature_common")]
+/// pub common: FeatureCommon,
+/// ```
+///
+/// Two keys `add_feature` also reads aren't here. `targets` it reads only for primitives; the
+/// other commands that read it are the ones that combine bodies. `operation` it reads for every
+/// feature (a cut where the active component has no bodies takes part in all of them), but only
+/// the commands that combine bodies take one; those declare it with their own type
+/// ([`OperationParam`] or [`ExtrudeOperation`]), and for the rest it is a caller's mistake.
+#[derive(Clone, Debug, Default, PartialEq, Deserialize, JsonSchema)]
+pub struct FeatureCommon {
+ /// The feature's name in the timeline.
+ #[serde(default)]
+ pub name: Option<String>,
+ /// The new body's name.
+ #[serde(default)]
+ pub body_name: Option<String>,
+ /// Names for the new bodies, in order.
+ #[serde(default)]
+ pub body_names: Option<StringList>,
+ /// The bodies taking part; overrides the default scope.
+ #[serde(default)]
+ pub participants: Option<StringList>,
+}
+
+/// Deserializes a flattened [`FeatureCommon`] from the keys the parent doesn't take, and reports
+/// a problem as if its fields were the parent's own, with the key in the message and in the
+/// issue's path (serde's flatten otherwise loses the key). serde reads a flattened field after
+/// all the parent's own, so its problems come after theirs, including a missing key.
+pub fn feature_common<'de, D: Deserializer<'de>>(d: D) -> Result<FeatureCommon, D::Error> {
+ let v = Value::deserialize(d)?;
+ serde_path_to_error::deserialize(&v).map_err(|e| D::Error::custom(super::check::located(&e)))
+}