Skip to content

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

Typed schemas for the design properties commands (part of #2829) (#10920)

semmelrindeed3510a91fa8
diff --git a/crates/engine/src/cmd/metadata.rs b/crates/engine/src/cmd/metadata.rs
index 96e5d37606..2d33cc929f 100644
--- a/crates/engine/src/cmd/metadata.rs
+++ b/crates/engine/src/cmd/metadata.rs
@@ -10,28 +10,52 @@ use solidcraft_doc::metadata::{self, BOM_TYPE, MAX_KEYS, Owner};
use super::CommandSpec;
use crate::params::{bad, str_};
+use crate::schema::metadata::{MetadataParams, MetadataRemoveParams, MetadataRemoveResult, MetadataResult, MetadataSetParams, MetadataSetResult};
+use crate::schema::{TypedContract, output_schema_for};
use crate::{Result, Session};
+const READ_CONTRACT: TypedContract<MetadataParams> = TypedContract::new();
+const SET_CONTRACT: TypedContract<MetadataSetParams> = TypedContract::new();
+const REMOVE_CONTRACT: TypedContract<MetadataRemoveParams> = TypedContract::new();
+
pub static COMMANDS: &[CommandSpec] = &[
- CommandSpec::new("document.metadata", "Design Properties", read).icon("settings").noundo().doc_only().params(
- "→ metadata: the design's metadata object as saved (other tools' keys too); properties: each of SolidCraft's design \
- properties (project, part number, revision…), its text or null (absent, or not text)",
- ),
- CommandSpec::new("document.metadata.set", "Change Design Properties", set).icon("settings").doc_only().params(
- "key and value, or values: {key: value, …} (all or nothing, one undo step). SolidCraft's keys, the ones document.metadata's \
- properties lists, take text (\"\" or null removes); another tool's data goes under its reverse-DNS key such as \
- com.example.tool (an object; null removes) → metadata, changed: [keys]",
- ),
- CommandSpec::new("document.metadata.remove", "Remove Design Property", remove)
+ CommandSpec::new("document.metadata", "Design Properties", crate::checked!("document.metadata", read))
+ .icon("settings")
+ .noundo()
+ .doc_only()
+ .contract(&READ_CONTRACT)
+ .output(output_schema_for::<MetadataResult>)
+ .params(
+ "→ metadata: the design's metadata object as saved (other tools' keys too); properties: each of SolidCraft's design \
+ properties (project, part number, revision…), its text or null (absent, or not text)",
+ ),
+ CommandSpec::new("document.metadata.set", "Change Design Properties", crate::checked!("document.metadata.set", set))
+ .icon("settings")
+ .doc_only()
+ .contract(&SET_CONTRACT)
+ .output(output_schema_for::<MetadataSetResult>)
+ .params(
+ "key and value, or values: {key: value, …} (all or nothing, one undo step). SolidCraft's keys, the ones document.metadata's \
+ properties lists, take text (\"\" or null removes); another tool's data goes under its reverse-DNS key such as \
+ com.example.tool (an object; null removes) → metadata, changed: [keys]",
+ ),
+ CommandSpec::new("document.metadata.remove", "Remove Design Property", crate::checked!("document.metadata.remove", remove))
.icon("delete")
.doc_only()
+ .contract(&REMOVE_CONTRACT)
+ .output(output_schema_for::<MetadataRemoveResult>)
.params("key, or keys: [keys] (any key, also one another tool wrote) → metadata, removed: [keys that were there]"),
];
+/// A reply built from its schema's type, so the two can't drift apart.
+fn reply(cmd: &str, r: impl serde::Serialize) -> Result<Value> {
+ serde_json::to_value(r).map_err(|e| bad(cmd, e.to_string()))
+}
+
fn read(s: &mut Session, _: &Value) -> Result<Value> {
let m = &s.doc.metadata;
let properties: Map<String, Value> = metadata::keys(Owner::Design).map(|k| (k.name.to_string(), json!(m.text(k.name)))).collect();
- Ok(json!({"metadata": m, "properties": properties}))
+ reply("document.metadata", MetadataResult { metadata: m.0.clone(), properties })
}
fn set(s: &mut Session, p: &Value) -> Result<Value> {
@@ -60,7 +84,7 @@ fn set(s: &mut Session, p: &Value) -> Result<Value> {
if next != s.doc.metadata {
s.doc_mut().metadata = next;
}
- Ok(json!({"metadata": s.doc.metadata, "changed": changed}))
+ reply(cmd, MetadataSetResult { metadata: s.doc.metadata.0.clone(), changed, param_warnings: Vec::new() })
}
fn remove(s: &mut Session, p: &Value) -> Result<Value> {
@@ -84,7 +108,8 @@ fn remove(s: &mut Session, p: &Value) -> Result<Value> {
m.remove(k);
}
}
- Ok(json!({"metadata": s.doc.metadata, "removed": removed}))
+ let removed = removed.into_iter().map(str::to_string).collect();
+ reply(cmd, MetadataRemoveResult { metadata: s.doc.metadata.0.clone(), removed, param_warnings: Vec::new() })
}
#[cfg(test)]
diff --git a/crates/engine/src/schema/metadata.rs b/crates/engine/src/schema/metadata.rs
new file mode 100644
index 0000000000..f30b02303f
--- /dev/null
+++ b/crates/engine/src/schema/metadata.rs
@@ -0,0 +1,84 @@
+//! Contracts and result types for the commands in `cmd/metadata.rs`.
+
+use schemars::JsonSchema;
+use serde::{Deserialize, Serialize};
+use serde_json::{Map, Value};
+
+/// Read the design's properties: its `metadata` object as saved, and SolidCraft's own design
+/// properties (project, part number, revision…) as text.
+#[derive(Debug, Deserialize, JsonSchema)]
+#[schemars(deny_unknown_fields)]
+pub struct MetadataParams {}
+
+/// What `document.metadata` returns.
+#[derive(Debug, Serialize, JsonSchema)]
+pub struct MetadataResult {
+ /// The design's metadata object as saved, other tools' keys included.
+ pub metadata: Map<String, Value>,
+ /// Each of SolidCraft's design properties, by key: its text, or null when it is absent or
+ /// not text.
+ pub properties: Map<String, Value>,
+}
+
+/// Change design properties in one undo step: `key` and `value`, or `values` for several at
+/// once (all or nothing). A change that sets what is already there makes no undo step.
+#[derive(Debug, Deserialize, JsonSchema)]
+#[schemars(deny_unknown_fields)]
+pub struct MetadataSetParams {
+ /// The property to set: one of SolidCraft's keys (the ones `document.metadata`'s
+ /// `properties` lists), which take text, or another tool's reverse-DNS key such as
+ /// `com.example.tool`, which takes an object. `bom_type` is a component's property and is
+ /// refused here. Needs `value`; not with `values`.
+ #[serde(default)]
+ pub key: Option<String>,
+ /// The value for `key`: text for SolidCraft's keys, an object for another tool's. `""` or
+ /// null removes the key. Required with `key`.
+ #[serde(default)]
+ #[schemars(with = "Value")]
+ pub value: Option<Value>,
+ /// Several properties at once, `{key: value, …}`, at most 256 keys, each as `key` and
+ /// `value` take them. Not with `key`.
+ #[serde(default)]
+ pub values: Option<Map<String, Value>>,
+}
+
+/// What `document.metadata.set` returns.
+#[derive(Debug, Serialize, JsonSchema)]
+pub struct MetadataSetResult {
+ /// The design's metadata object after the change.
+ pub metadata: Map<String, Value>,
+ /// The keys whose value changed, in key order.
+ pub changed: Vec<String>,
+ /// 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>,
+}
+
+/// Remove design properties in one undo step: `key`, or `keys` for several. Any key can go,
+/// also one another tool wrote; a key that isn't there is left out of `removed`.
+#[derive(Debug, Deserialize, JsonSchema)]
+#[schemars(deny_unknown_fields)]
+pub struct MetadataRemoveParams {
+ /// The property to remove. Not with `keys`.
+ #[serde(default)]
+ pub key: Option<String>,
+ /// The properties to remove, at most 256. Not with `key`.
+ #[serde(default)]
+ pub keys: Option<Vec<String>>,
+}
+
+/// What `document.metadata.remove` returns.
+#[derive(Debug, Serialize, JsonSchema)]
+pub struct MetadataRemoveResult {
+ /// The design's metadata object after the change.
+ pub metadata: Map<String, Value>,
+ /// The keys that were there and are removed, each once, in the order asked.
+ pub removed: Vec<String>,
+ /// 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 = "metadata_tests.rs"]
+mod tests;
diff --git a/crates/engine/src/schema/metadata_tests.rs b/crates/engine/src/schema/metadata_tests.rs
new file mode 100644
index 0000000000..c4c7699c7b
--- /dev/null
+++ b/crates/engine/src/schema/metadata_tests.rs
@@ -0,0 +1,54 @@
+use serde_json::{Value, json};
+
+use super::{MetadataParams, MetadataRemoveParams, MetadataRemoveResult, MetadataResult, MetadataSetParams, MetadataSetResult};
+use crate::Session;
+use crate::schema::tests::{assert_keys, assert_strict_keeps_todays_errors, conforms};
+use crate::schema::{ParamCheck, input_schema_for, output_schema_for};
+
+#[test]
+fn schemas_and_the_key_check_agree() {
+ assert_keys(input_schema_for::<MetadataParams>(), &[]);
+ assert_keys(input_schema_for::<MetadataSetParams>(), &["key", "value", "values"]);
+ assert_keys(input_schema_for::<MetadataRemoveParams>(), &["key", "keys"]);
+}
+
+#[test]
+fn strict_keeps_todays_errors() {
+ assert_strict_keeps_todays_errors(&[
+ ("document.metadata.set", json!({"key": 5, "value": "Gearbox"})),
+ ("document.metadata.remove", json!({"key": 5})),
+ ]);
+}
+
+/// Every form of the three commands, in Warn: each reply matches its output schema and carries
+/// no warning; a misspelt key's warning still matches.
+#[test]
+fn replies_match_the_output_schema() {
+ let mut s = Session { param_check: ParamCheck::Warn, ..Session::default() };
+ let mut run = |id: &str, p: Value| s.execute(id, &p).unwrap_or_else(|e| panic!("{id} {p}: {e}"));
+ let matches = |schema: schemars::Schema, reply: &Value| {
+ let schema = schema.as_value();
+ assert!(conforms(schema, schema, reply), "{reply} doesn't match {schema}");
+ };
+ let set = |reply: &Value| matches(output_schema_for::<MetadataSetResult>(), reply);
+ let remove = |reply: &Value| matches(output_schema_for::<MetadataRemoveResult>(), reply);
+ let calls = [
+ ("document.metadata.set", json!({"values": {"author": "Jane Doe", "com.acme.shop": {"shop_id": 88123}}})),
+ ("document.metadata.set", json!({"key": "project", "value": "Gearbox"})),
+ ("document.metadata.set", json!({"key": "project", "value": null})),
+ ("document.metadata.remove", json!({"keys": ["author", "author", "not.there"]})),
+ ("document.metadata.remove", json!({"key": "com.acme.shop"})),
+ ];
+ for (id, p) in calls {
+ let reply = run(id, p.clone());
+ assert!(reply.get("param_warnings").is_none(), "{id} {p}: {reply}");
+ if id == "document.metadata.set" { set(&reply) } else { remove(&reply) }
+ }
+ run("document.metadata.set", json!({"key": "part_number", "value": "ACME-1042"}));
+ let read = run("document.metadata", json!({}));
+ assert_eq!(read["properties"]["part_number"], "ACME-1042");
+ matches(output_schema_for::<MetadataResult>(), &read);
+ let warned = run("document.metadata.set", json!({"key": "author", "value": "J", "valeu": 1}));
+ assert!(warned["param_warnings"].as_array().is_some_and(|w| !w.is_empty()), "{warned}");
+ set(&warned);
+}
diff --git a/crates/engine/src/schema/mod.rs b/crates/engine/src/schema/mod.rs
index a0b17878e2..a065bd650e 100644
--- a/crates/engine/src/schema/mod.rs
+++ b/crates/engine/src/schema/mod.rs
@@ -70,6 +70,7 @@ pub mod joints;
pub mod libraries;
pub mod mass_properties;
pub mod material_properties;
+pub mod metadata;
pub mod motion;
pub mod panels;
pub mod print_face;
diff --git a/crates/engine/src/schema/unconverted.txt b/crates/engine/src/schema/unconverted.txt
index 018ef6d57c..46f048b6ec 100644
--- a/crates/engine/src/schema/unconverted.txt
+++ b/crates/engine/src/schema/unconverted.txt
@@ -55,9 +55,6 @@ doc.recover
doc.recovery_discard
doc.recovery_list
document.inspect
-document.metadata
-document.metadata.remove
-document.metadata.set
engine.commands
explode.create
explode.delete