brokkr-ctl blender: a Rust CLI that sends typed intents to the live add-on's store and reads receipts and the snapshot
Workspace member brokkr-ctl; cultcache-rs moves to [workspace.dependencies] at the daemon's existing rev. Writes only blender/commands/<id>; intents are attributed or refused; exit code derives from the receipt. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
561562626f
commit
68e1b654dd
7 changed files with 859 additions and 2 deletions
|
|
@ -1,6 +1,10 @@
|
|||
[workspace]
|
||||
resolver = "2"
|
||||
members = [
|
||||
"brokkr-daemon"
|
||||
"brokkr-daemon",
|
||||
"brokkr-ctl",
|
||||
]
|
||||
|
||||
[workspace.dependencies]
|
||||
cultcache-rs = { git = "https://github.com/GameCult/CultLib.git", rev = "baf4ecf78fae634fafef956d3b85420162c074bb", package = "cultcache-rs" }
|
||||
|
||||
|
|
|
|||
14
brokkr-ctl/Cargo.toml
Normal file
14
brokkr-ctl/Cargo.toml
Normal file
|
|
@ -0,0 +1,14 @@
|
|||
[package]
|
||||
name = "brokkr-ctl"
|
||||
version = "0.1.0"
|
||||
edition = "2024"
|
||||
publish = false
|
||||
|
||||
[dependencies]
|
||||
anyhow = "1"
|
||||
cultcache-rs = { workspace = true }
|
||||
serde_json = "1"
|
||||
uuid = { version = "1", features = ["v4"] }
|
||||
|
||||
[dev-dependencies]
|
||||
tempfile = "3"
|
||||
588
brokkr-ctl/src/blender.rs
Normal file
588
brokkr-ctl/src/blender.rs
Normal file
|
|
@ -0,0 +1,588 @@
|
|||
//! `brokkr-ctl blender`: a caller of the Blender add-on's store. It writes one intent
|
||||
//! document per `send` and reads receipts and the host snapshot. The add-on decides.
|
||||
|
||||
use anyhow::{Context, Result, anyhow, bail};
|
||||
use cultcache_rs::{CacheBackingStore, CultCacheEnvelope, SingleFileMessagePackBackingStore};
|
||||
use serde_json::{Map, Value};
|
||||
use std::path::PathBuf;
|
||||
use std::thread;
|
||||
use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
|
||||
|
||||
pub const INTENT_SCHEMA: &str = "brokkr.blender.command_intent.v0";
|
||||
pub const RECEIPT_SCHEMA: &str = "brokkr.blender.command_receipt.v0";
|
||||
pub const SNAPSHOT_SCHEMA: &str = "brokkr.blender.host_snapshot.v0";
|
||||
const INTENT_PREFIX: &str = "blender/commands/";
|
||||
const RECEIPT_PREFIX: &str = "blender/receipts/";
|
||||
const SNAPSHOT_KEY: &str = "blender/host/current";
|
||||
const RESERVED: [&str; 5] = ["schema", "commandId", "action", "requestedBy", "note"];
|
||||
const DEFAULT_TIMEOUT_SECS: f64 = 60.0;
|
||||
const POLL: Duration = Duration::from_millis(200);
|
||||
|
||||
/// What a receipt (or its absence) says; the exit code derives from it and from nothing else.
|
||||
pub enum Outcome {
|
||||
Accepted,
|
||||
Failed,
|
||||
Stopped,
|
||||
Timeout,
|
||||
}
|
||||
|
||||
impl Outcome {
|
||||
pub fn code(&self) -> i32 {
|
||||
match self {
|
||||
Outcome::Accepted => 0,
|
||||
Outcome::Failed => 2,
|
||||
Outcome::Stopped => 3,
|
||||
Outcome::Timeout => 4,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn from_status(status: &str) -> Outcome {
|
||||
match status {
|
||||
"accepted" => Outcome::Accepted,
|
||||
"stopped" => Outcome::Stopped,
|
||||
_ => Outcome::Failed, // denied, failed, and any status this tool does not know
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct Options {
|
||||
store: Option<PathBuf>,
|
||||
agent: Option<String>,
|
||||
note: String,
|
||||
sets: Vec<String>,
|
||||
no_wait: bool,
|
||||
timeout: Option<f64>,
|
||||
last: Option<usize>,
|
||||
positional: Vec<String>,
|
||||
}
|
||||
|
||||
fn parse(args: &[String]) -> Result<Options> {
|
||||
let mut options = Options::default();
|
||||
let mut iter = args.iter();
|
||||
while let Some(arg) = iter.next() {
|
||||
let mut value = |name: &str| {
|
||||
iter.next()
|
||||
.cloned()
|
||||
.ok_or_else(|| anyhow!("{name} needs a value"))
|
||||
};
|
||||
match arg.as_str() {
|
||||
"--store" => options.store = Some(PathBuf::from(value("--store")?)),
|
||||
"--agent" => options.agent = Some(value("--agent")?),
|
||||
"--note" => options.note = value("--note")?,
|
||||
"--set" => options.sets.push(value("--set")?),
|
||||
"--no-wait" => options.no_wait = true,
|
||||
"--timeout" => {
|
||||
let raw = value("--timeout")?;
|
||||
let secs: f64 = raw
|
||||
.parse()
|
||||
.map_err(|_| anyhow!("--timeout wants seconds, got {raw:?}"))?;
|
||||
if !secs.is_finite() || secs < 0.0 {
|
||||
bail!("--timeout wants a non-negative number of seconds");
|
||||
}
|
||||
options.timeout = Some(secs);
|
||||
}
|
||||
"--last" => {
|
||||
let raw = value("--last")?;
|
||||
options.last = Some(
|
||||
raw.parse()
|
||||
.map_err(|_| anyhow!("--last wants a count, got {raw:?}"))?,
|
||||
);
|
||||
}
|
||||
flag if flag.starts_with("--") => bail!("unknown option {flag}"),
|
||||
_ => options.positional.push(arg.clone()),
|
||||
}
|
||||
}
|
||||
Ok(options)
|
||||
}
|
||||
|
||||
/// Runs one `blender` subcommand and returns the process exit code.
|
||||
pub fn run(args: &[String]) -> Result<i32> {
|
||||
let Some((sub, rest)) = args.split_first() else {
|
||||
print!("{}", group_help());
|
||||
return Ok(1);
|
||||
};
|
||||
if matches!(sub.as_str(), "--help" | "-h" | "help") {
|
||||
print!("{}", group_help());
|
||||
return Ok(0);
|
||||
}
|
||||
if rest.iter().any(|arg| arg == "--help" || arg == "-h") {
|
||||
print!("{}", if sub == "send" { send_help() } else { group_help() });
|
||||
return Ok(0);
|
||||
}
|
||||
let options = parse(rest)?;
|
||||
match sub.as_str() {
|
||||
"send" => send(&options),
|
||||
"wait" => {
|
||||
let id = one_positional(&options, "wait <commandId>")?;
|
||||
let store = open_store(&options)?;
|
||||
wait_for_receipt(&store, id, timeout(&options))
|
||||
}
|
||||
"receipts" => receipts(&open_store(&options)?, options.last),
|
||||
"status" => status(&open_store(&options)?),
|
||||
other => bail!("unknown subcommand {other:?}; try `brokkr-ctl blender --help`"),
|
||||
}
|
||||
}
|
||||
|
||||
fn one_positional<'a>(options: &'a Options, usage: &str) -> Result<&'a str> {
|
||||
match options.positional.as_slice() {
|
||||
[one] => Ok(one),
|
||||
_ => bail!("usage: brokkr-ctl blender {usage}"),
|
||||
}
|
||||
}
|
||||
|
||||
fn timeout(options: &Options) -> Duration {
|
||||
Duration::from_secs_f64(options.timeout.unwrap_or(DEFAULT_TIMEOUT_SECS))
|
||||
}
|
||||
|
||||
/// The add-on creates its store; naming a path that is not there is a typo, not a request
|
||||
/// to make a second store.
|
||||
fn open_store(options: &Options) -> Result<SingleFileMessagePackBackingStore> {
|
||||
let path = options
|
||||
.store
|
||||
.clone()
|
||||
.or_else(|| std::env::var_os("BROKKR_BLENDER_STORE").map(PathBuf::from))
|
||||
.ok_or_else(|| anyhow!("no store: pass --store <path> or set BROKKR_BLENDER_STORE"))?;
|
||||
if !path.is_file() {
|
||||
bail!("store {} does not exist; the add-on creates it", path.display());
|
||||
}
|
||||
// The store library stages writes beside the file and fails on a bare file name.
|
||||
Ok(SingleFileMessagePackBackingStore::new(std::path::absolute(path)?))
|
||||
}
|
||||
|
||||
fn requested_by(options: &Options) -> Result<String> {
|
||||
let instance = std::env::var("EUREKA_INSTANCE").unwrap_or_default();
|
||||
let agent = options
|
||||
.agent
|
||||
.clone()
|
||||
.or_else(|| std::env::var("BROKKR_AGENT").ok())
|
||||
.unwrap_or_default();
|
||||
if instance.trim().is_empty() || agent.trim().is_empty() {
|
||||
bail!("an intent must be attributed: set EUREKA_INSTANCE and pass --agent or set BROKKR_AGENT");
|
||||
}
|
||||
Ok(format!("{}/{}", instance.trim(), agent.trim()))
|
||||
}
|
||||
|
||||
fn build_intent(
|
||||
action: &str,
|
||||
command_id: &str,
|
||||
requested_by: &str,
|
||||
note: &str,
|
||||
sets: &[String],
|
||||
) -> Result<Value> {
|
||||
if action.is_empty() || !action.chars().all(|c| c.is_ascii_alphanumeric()) {
|
||||
bail!("action must be letters and digits, e.g. createObject");
|
||||
}
|
||||
let mut map = Map::new();
|
||||
for set in sets {
|
||||
let (key, raw) = set
|
||||
.split_once('=')
|
||||
.ok_or_else(|| anyhow!("--set wants key=json, got {set:?}"))?;
|
||||
if key.is_empty() || RESERVED.contains(&key) {
|
||||
bail!("--set cannot name {key:?}: it is written by brokkr-ctl");
|
||||
}
|
||||
let value: Value = serde_json::from_str(raw)
|
||||
.with_context(|| format!("--set {key}: {raw:?} is not JSON (strings need quotes)"))?;
|
||||
map.insert(key.to_string(), value);
|
||||
}
|
||||
map.insert("schema".into(), INTENT_SCHEMA.into());
|
||||
map.insert("commandId".into(), command_id.into());
|
||||
map.insert("action".into(), action.into());
|
||||
map.insert("requestedBy".into(), requested_by.into());
|
||||
map.insert("note".into(), note.into());
|
||||
Ok(Value::Object(map))
|
||||
}
|
||||
|
||||
fn send(options: &Options) -> Result<i32> {
|
||||
let action = one_positional(options, "send <action> [--set key=json]...")?;
|
||||
let requested_by = requested_by(options)?;
|
||||
let mut store = open_store(options)?;
|
||||
let command_id = uuid::Uuid::new_v4().simple().to_string();
|
||||
let intent = build_intent(action, &command_id, &requested_by, &options.note, &options.sets)?;
|
||||
store.push(&CultCacheEnvelope {
|
||||
key: format!("{INTENT_PREFIX}{command_id}"),
|
||||
r#type: INTENT_SCHEMA.to_string(),
|
||||
payload: serde_json::to_vec(&intent)?,
|
||||
stored_at: iso_now(),
|
||||
schema_id: Some(INTENT_SCHEMA.to_string()),
|
||||
})?;
|
||||
println!("commandId: {command_id}");
|
||||
if options.no_wait {
|
||||
return Ok(0);
|
||||
}
|
||||
wait_for_receipt(&store, &command_id, timeout(options))
|
||||
}
|
||||
|
||||
fn read_receipt(store: &SingleFileMessagePackBackingStore, id: &str) -> Result<Option<Value>> {
|
||||
let key = format!("{RECEIPT_PREFIX}{id}");
|
||||
for envelope in store.pull_all()? {
|
||||
if envelope.key == key && envelope.r#type == RECEIPT_SCHEMA {
|
||||
return Ok(Some(decode(&envelope)?));
|
||||
}
|
||||
}
|
||||
Ok(None)
|
||||
}
|
||||
|
||||
fn wait_for_receipt(
|
||||
store: &SingleFileMessagePackBackingStore,
|
||||
id: &str,
|
||||
limit: Duration,
|
||||
) -> Result<i32> {
|
||||
let started = Instant::now();
|
||||
loop {
|
||||
if let Some(receipt) = read_receipt(store, id)? {
|
||||
print_fields(&receipt);
|
||||
let status = receipt.get("status").and_then(Value::as_str).unwrap_or("");
|
||||
return Ok(Outcome::from_status(status).code());
|
||||
}
|
||||
if started.elapsed() >= limit {
|
||||
println!("status: timeout");
|
||||
return Ok(Outcome::Timeout.code());
|
||||
}
|
||||
thread::sleep(POLL);
|
||||
}
|
||||
}
|
||||
|
||||
fn receipts(store: &SingleFileMessagePackBackingStore, last: Option<usize>) -> Result<i32> {
|
||||
let mut found = Vec::new();
|
||||
for envelope in store.pull_all()? {
|
||||
if envelope.key.starts_with(RECEIPT_PREFIX) && envelope.r#type == RECEIPT_SCHEMA {
|
||||
found.push(decode(&envelope)?);
|
||||
}
|
||||
}
|
||||
found.sort_by_key(|receipt| {
|
||||
receipt
|
||||
.get("observedAt")
|
||||
.and_then(Value::as_str)
|
||||
.unwrap_or("")
|
||||
.to_string()
|
||||
});
|
||||
let skip = last.map_or(0, |n| found.len().saturating_sub(n));
|
||||
for (index, receipt) in found.iter().skip(skip).enumerate() {
|
||||
if index > 0 {
|
||||
println!();
|
||||
}
|
||||
print_fields(receipt);
|
||||
}
|
||||
Ok(0)
|
||||
}
|
||||
|
||||
fn status(store: &SingleFileMessagePackBackingStore) -> Result<i32> {
|
||||
for envelope in store.pull_all()? {
|
||||
if envelope.key == SNAPSHOT_KEY && envelope.r#type == SNAPSHOT_SCHEMA {
|
||||
let snapshot = decode(&envelope)?;
|
||||
for key in [
|
||||
"observedAt",
|
||||
"blenderVersion",
|
||||
"projectPath",
|
||||
"mode",
|
||||
"activeScene",
|
||||
"activeObjectName",
|
||||
"selectedObjectNames",
|
||||
"objectCount",
|
||||
"sink",
|
||||
] {
|
||||
if let Some(value) = snapshot.get(key) {
|
||||
print_field(key, value);
|
||||
}
|
||||
}
|
||||
return Ok(0);
|
||||
}
|
||||
}
|
||||
bail!("the store holds no host snapshot yet; is the add-on's server running?")
|
||||
}
|
||||
|
||||
fn decode(envelope: &CultCacheEnvelope) -> Result<Value> {
|
||||
serde_json::from_slice(&envelope.payload)
|
||||
.with_context(|| format!("{} is not a JSON map payload", envelope.key))
|
||||
}
|
||||
|
||||
fn print_fields(value: &Value) {
|
||||
match value.as_object() {
|
||||
Some(map) => map.iter().for_each(|(key, value)| print_field(key, value)),
|
||||
None => println!("value: {value}"),
|
||||
}
|
||||
}
|
||||
|
||||
fn print_field(key: &str, value: &Value) {
|
||||
match value {
|
||||
Value::String(text) => println!("{key}: {text}"),
|
||||
other => println!("{key}: {other}"),
|
||||
}
|
||||
}
|
||||
|
||||
/// UTC, microseconds, `+00:00`: the form the Python node stamps.
|
||||
fn iso_now() -> String {
|
||||
let now = SystemTime::now().duration_since(UNIX_EPOCH).unwrap_or_default();
|
||||
iso_from(now.as_secs() as i64, now.subsec_micros())
|
||||
}
|
||||
|
||||
fn iso_from(secs: i64, micros: u32) -> String {
|
||||
let days = secs.div_euclid(86_400);
|
||||
let rem = secs.rem_euclid(86_400);
|
||||
// Howard Hinnant's civil_from_days.
|
||||
let z = days + 719_468;
|
||||
let era = z.div_euclid(146_097);
|
||||
let doe = z.rem_euclid(146_097);
|
||||
let yoe = (doe - doe / 1_460 + doe / 36_524 - doe / 146_096) / 365;
|
||||
let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
|
||||
let mp = (5 * doy + 2) / 153;
|
||||
let day = doy - (153 * mp + 2) / 5 + 1;
|
||||
let month = if mp < 10 { mp + 3 } else { mp - 9 };
|
||||
let year = yoe + era * 400 + i64::from(month <= 2);
|
||||
format!(
|
||||
"{year:04}-{month:02}-{day:02}T{:02}:{:02}:{:02}.{micros:06}+00:00",
|
||||
rem / 3_600,
|
||||
rem % 3_600 / 60,
|
||||
rem % 60
|
||||
)
|
||||
}
|
||||
|
||||
pub fn group_help() -> String {
|
||||
"\
|
||||
brokkr-ctl blender: send typed intents to the live Blender add-on and read what it did.
|
||||
|
||||
send <action> [--set key=json]... [--note text] [--agent name] [--no-wait] [--timeout secs]
|
||||
Write one intent, then wait for its receipt and print it. `send --help` lists actions.
|
||||
wait <commandId> [--timeout secs] Wait for a receipt and print it.
|
||||
receipts [--last n] Print stored receipts, oldest first.
|
||||
status Print the host snapshot summary.
|
||||
|
||||
Every command needs --store <path> or $BROKKR_BLENDER_STORE (the add-on's .ccmp).
|
||||
send needs $EUREKA_INSTANCE and --agent or $BROKKR_AGENT; requestedBy is '<instance>/<agent>'.
|
||||
Output is 'key: value' lines. Exit: 0 accepted, 2 denied or failed, 3 stopped, 4 timeout,
|
||||
1 usage or store error. brokkr-ctl validates nothing about an action: the add-on does, and
|
||||
its refusal comes back in the receipt.
|
||||
"
|
||||
.to_string()
|
||||
}
|
||||
|
||||
pub fn send_help() -> String {
|
||||
let mut text = String::from(
|
||||
"\
|
||||
brokkr-ctl blender send <action> [--set key=json]... [--note text] [--agent name] [--no-wait] [--timeout secs]
|
||||
|
||||
--set takes JSON: --set objectType='\"MESH\"' --set location='[0,0,1]'. brokkr-ctl writes schema,
|
||||
commandId, action, requestedBy and note itself; --set cannot name them. Fields below are what the
|
||||
add-on reads; it validates them and refuses in the receipt. Targets also accept objectName.
|
||||
|
||||
actions:
|
||||
",
|
||||
);
|
||||
for (action, fields) in ACTIONS {
|
||||
text.push_str(&format!(" {action}\n"));
|
||||
for (name, kind, note) in *fields {
|
||||
text.push_str(&format!(" {name}: {kind} {note}\n"));
|
||||
}
|
||||
}
|
||||
text
|
||||
}
|
||||
|
||||
type Field = (&'static str, &'static str, &'static str);
|
||||
|
||||
/// Help text only: what the add-on's `execute_command` dispatches and reads at the base commit.
|
||||
const ACTIONS: &[(&str, &[Field])] = &[
|
||||
(
|
||||
"createObject",
|
||||
&[
|
||||
("objectType", "string", "MESH | LIGHT | CAMERA | EMPTY (default EMPTY)"),
|
||||
("name", "string", ""),
|
||||
("location", "[x,y,z]", ""),
|
||||
("size", "number", "MESH"),
|
||||
("meshType", "string", "CUBE"),
|
||||
("lightType", "string", "LIGHT"),
|
||||
("emptyDisplayType", "string", "EMPTY"),
|
||||
],
|
||||
),
|
||||
("deleteObject", &[("targetObjectName", "string", "")]),
|
||||
(
|
||||
"setObjectTransform",
|
||||
&[
|
||||
("targetObjectName", "string", ""),
|
||||
("location", "[x,y,z]", ""),
|
||||
("rotationEuler", "[x,y,z]", "radians"),
|
||||
("scale", "[x,y,z]", ""),
|
||||
],
|
||||
),
|
||||
(
|
||||
"setObjectVisibility",
|
||||
&[("targetObjectName", "string", ""), ("visible", "bool", "")],
|
||||
),
|
||||
(
|
||||
"setObjectParent",
|
||||
&[
|
||||
("targetObjectName", "string", ""),
|
||||
("parentObjectName", "string", "empty clears the parent"),
|
||||
],
|
||||
),
|
||||
(
|
||||
"setObjectCustomProperty",
|
||||
&[
|
||||
("targetObjectName", "string", ""),
|
||||
("propertyName", "string", ""),
|
||||
("value", "json", ""),
|
||||
],
|
||||
),
|
||||
(
|
||||
"selectObject",
|
||||
&[("targetObjectName", "string", ""), ("clearSelection", "bool", "default true")],
|
||||
),
|
||||
(
|
||||
"assignMaterial",
|
||||
&[
|
||||
("targetObjectName", "string", ""),
|
||||
("materialName", "string", ""),
|
||||
("color", "[r,g,b] or [r,g,b,a]", "linear, 0..1"),
|
||||
],
|
||||
),
|
||||
(
|
||||
"importGltf",
|
||||
&[("filepath", "string", "inside the add-on's import directory")],
|
||||
),
|
||||
(
|
||||
"exportGltf",
|
||||
&[
|
||||
("filepath", "string", ".glb or .gltf inside the add-on's output directory"),
|
||||
("extras", "bool", ""),
|
||||
("yUp", "bool", ""),
|
||||
("applyModifiers", "bool", ""),
|
||||
("selection", "[string]", "object names"),
|
||||
],
|
||||
),
|
||||
(
|
||||
"setCamera",
|
||||
&[
|
||||
("targetObjectName", "string", ""),
|
||||
("lens", "number", "mm"),
|
||||
("cameraType", "string", ""),
|
||||
("orthoScale", "number", ""),
|
||||
("clipStart", "number", ""),
|
||||
("clipEnd", "number", ""),
|
||||
("panoramaType", "string", ""),
|
||||
("active", "bool", "make it the scene camera"),
|
||||
],
|
||||
),
|
||||
(
|
||||
"setLight",
|
||||
&[
|
||||
("targetObjectName", "string", ""),
|
||||
("energy", "number", ""),
|
||||
("color", "[r,g,b]", "linear, 0..1"),
|
||||
("lightType", "string", ""),
|
||||
],
|
||||
),
|
||||
(
|
||||
"setWorld",
|
||||
&[
|
||||
("worldName", "string", ""),
|
||||
("color", "[r,g,b]", "linear, 0..1"),
|
||||
("strength", "number", ""),
|
||||
],
|
||||
),
|
||||
(
|
||||
"renderStill",
|
||||
&[
|
||||
("outputPath", "string", "inside the add-on's output directory"),
|
||||
("engine", "string", ""),
|
||||
("resolutionX", "integer", ""),
|
||||
("resolutionY", "integer", ""),
|
||||
("cameraName", "string", ""),
|
||||
],
|
||||
),
|
||||
(
|
||||
"createNodeGroup",
|
||||
&[
|
||||
("treeKey", "string", ""),
|
||||
("interface", "[{inOut,name,type,default?}]", "types: Geometry Float Int Bool Vector"),
|
||||
],
|
||||
),
|
||||
(
|
||||
"addNode",
|
||||
&[
|
||||
("treeKey", "string", ""),
|
||||
("id", "string", "brokkr's key for the node"),
|
||||
("blIdname", "string", "GeometryNode*, FunctionNode* or ShaderNode*"),
|
||||
("location", "[x,y]", ""),
|
||||
("label", "string", ""),
|
||||
("properties", "object", "enum, bool, int or float node settings"),
|
||||
("inputs", "object", "unlinked input defaults"),
|
||||
],
|
||||
),
|
||||
("removeNode", &[("treeKey", "string", ""), ("id", "string", "")]),
|
||||
(
|
||||
"linkSockets",
|
||||
&[
|
||||
("treeKey", "string", ""),
|
||||
("fromNode", "string", ""),
|
||||
("fromSocket", "string", ""),
|
||||
("toNode", "string", ""),
|
||||
("toSocket", "string", ""),
|
||||
],
|
||||
),
|
||||
(
|
||||
"unlinkSockets",
|
||||
&[
|
||||
("treeKey", "string", ""),
|
||||
("toNode", "string", ""),
|
||||
("toSocket", "string", ""),
|
||||
("fromNode", "string", "optional"),
|
||||
("fromSocket", "string", "optional"),
|
||||
],
|
||||
),
|
||||
(
|
||||
"addModifier",
|
||||
&[
|
||||
("objectName", "string", ""),
|
||||
("treeKey", "string", ""),
|
||||
("modifierName", "string", "default Brokkr GeoNodes"),
|
||||
],
|
||||
),
|
||||
(
|
||||
"removeModifier",
|
||||
&[("objectName", "string", ""), ("modifierName", "string", "")],
|
||||
),
|
||||
(
|
||||
"setModifierInput",
|
||||
&[
|
||||
("objectName", "string", ""),
|
||||
("modifierName", "string", ""),
|
||||
("socket", "string", "identifier or unique interface name"),
|
||||
("value", "json", "Float, Int, Bool or Vector"),
|
||||
],
|
||||
),
|
||||
];
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn iso_matches_the_python_form() {
|
||||
assert_eq!(iso_from(0, 0), "1970-01-01T00:00:00.000000+00:00");
|
||||
assert_eq!(iso_from(1_795_800_558, 813_099), "2026-11-27T17:29:18.813099+00:00");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn intent_carries_reserved_fields_and_refuses_overrides() {
|
||||
let sets = vec!["objectType=\"MESH\"".to_string(), "location=[0,0,1]".to_string()];
|
||||
let intent = build_intent("createObject", "abc", "nibu/hands", "n", &sets).unwrap();
|
||||
assert_eq!(intent["requestedBy"], "nibu/hands");
|
||||
assert_eq!(intent["objectType"], "MESH");
|
||||
assert_eq!(intent["location"][2], 1);
|
||||
for bad in ["requestedBy=\"x\"", "commandId=\"x\"", "action=\"x\"", "novalue", "k=notjson"] {
|
||||
assert!(
|
||||
build_intent("createObject", "abc", "a/b", "", &[bad.to_string()]).is_err(),
|
||||
"{bad}"
|
||||
);
|
||||
}
|
||||
assert!(build_intent("../x", "abc", "a/b", "", &[]).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn statuses_map_to_exit_codes() {
|
||||
for (status, code) in [("accepted", 0), ("denied", 2), ("failed", 2), ("stopped", 3), ("weird", 2)] {
|
||||
assert_eq!(Outcome::from_status(status).code(), code, "{status}");
|
||||
}
|
||||
assert_eq!(Outcome::Timeout.code(), 4);
|
||||
}
|
||||
}
|
||||
24
brokkr-ctl/src/main.rs
Normal file
24
brokkr-ctl/src/main.rs
Normal file
|
|
@ -0,0 +1,24 @@
|
|||
//! brokkr-ctl: command-line hands for Brokkr's creative-tool surfaces.
|
||||
|
||||
mod blender;
|
||||
|
||||
fn main() {
|
||||
let args: Vec<String> = std::env::args().skip(1).collect();
|
||||
let code = match args.split_first() {
|
||||
Some((group, rest)) if group == "blender" => blender::run(rest),
|
||||
Some((flag, _)) if matches!(flag.as_str(), "--help" | "-h" | "help") => {
|
||||
print!(
|
||||
"brokkr-ctl <group> ...\n\ngroups:\n blender send intents to the live Blender add-on (`brokkr-ctl blender --help`)\n"
|
||||
);
|
||||
Ok(0)
|
||||
}
|
||||
_ => Err(anyhow::anyhow!("usage: brokkr-ctl blender <send|wait|receipts|status> ...")),
|
||||
};
|
||||
match code {
|
||||
Ok(code) => std::process::exit(code),
|
||||
Err(error) => {
|
||||
eprintln!("error: {error:#}");
|
||||
std::process::exit(1);
|
||||
}
|
||||
}
|
||||
}
|
||||
154
brokkr-ctl/tests/cli.rs
Normal file
154
brokkr-ctl/tests/cli.rs
Normal file
|
|
@ -0,0 +1,154 @@
|
|||
//! brokkr-ctl against a real single-file store, read back through cultcache-rs.
|
||||
|
||||
use cultcache_rs::{CacheBackingStore, CultCacheEnvelope, SingleFileMessagePackBackingStore};
|
||||
use serde_json::{Value, json};
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::{Command, Output};
|
||||
|
||||
const INTENT: &str = "brokkr.blender.command_intent.v0";
|
||||
const RECEIPT: &str = "brokkr.blender.command_receipt.v0";
|
||||
|
||||
fn envelope(schema: &str, key: &str, payload: &Value) -> CultCacheEnvelope {
|
||||
CultCacheEnvelope {
|
||||
key: key.to_string(),
|
||||
r#type: schema.to_string(),
|
||||
payload: serde_json::to_vec(payload).unwrap(),
|
||||
stored_at: "2026-11-27T00:00:00.000000+00:00".to_string(),
|
||||
schema_id: Some(schema.to_string()),
|
||||
}
|
||||
}
|
||||
|
||||
/// A store the way the add-on leaves it: a file that already exists, holding other records.
|
||||
fn store_with_receipts(dir: &Path, statuses: &[(&str, &str)]) -> PathBuf {
|
||||
let path = dir.join("blender-editor.ccmp");
|
||||
let mut store = SingleFileMessagePackBackingStore::new(&path);
|
||||
for (id, status) in statuses {
|
||||
let receipt = json!({"schema": RECEIPT, "commandId": id, "status": status, "observedAt": "2026-11-27T00:00:00+00:00"});
|
||||
store
|
||||
.push(&envelope(RECEIPT, &format!("blender/receipts/{id}"), &receipt))
|
||||
.unwrap();
|
||||
}
|
||||
path
|
||||
}
|
||||
|
||||
fn ctl(store: &Path, args: &[&str], instance: Option<&str>) -> Output {
|
||||
let mut command = Command::new(env!("CARGO_BIN_EXE_brokkr-ctl"));
|
||||
command
|
||||
.arg("blender")
|
||||
.args(args)
|
||||
.arg("--store")
|
||||
.arg(store)
|
||||
.env_remove("BROKKR_AGENT")
|
||||
.env_remove("BROKKR_BLENDER_STORE")
|
||||
.env_remove("EUREKA_INSTANCE");
|
||||
if let Some(instance) = instance {
|
||||
command.env("EUREKA_INSTANCE", instance);
|
||||
}
|
||||
command.output().unwrap()
|
||||
}
|
||||
|
||||
fn stdout(output: &Output) -> String {
|
||||
String::from_utf8_lossy(&output.stdout).into_owned()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn send_writes_a_pullable_intent() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let path = store_with_receipts(dir.path(), &[("seed", "accepted")]);
|
||||
let output = ctl(
|
||||
&path,
|
||||
&["send", "createObject", "--set", "objectType=\"MESH\"", "--set", "location=[0,0,1]", "--note", "a cube", "--agent", "hands", "--no-wait"],
|
||||
Some("nibu"),
|
||||
);
|
||||
assert_eq!(output.status.code(), Some(0), "{}", String::from_utf8_lossy(&output.stderr));
|
||||
let id = stdout(&output).trim().strip_prefix("commandId: ").unwrap().to_string();
|
||||
assert_eq!(id.len(), 32);
|
||||
|
||||
let envelopes = SingleFileMessagePackBackingStore::new(&path).pull_all().unwrap();
|
||||
let intent = envelopes
|
||||
.iter()
|
||||
.find(|e| e.key == format!("blender/commands/{id}"))
|
||||
.expect("intent key");
|
||||
assert_eq!(intent.r#type, INTENT);
|
||||
assert_eq!(intent.schema_id.as_deref(), Some(INTENT));
|
||||
let payload: Value = serde_json::from_slice(&intent.payload).unwrap();
|
||||
assert_eq!(
|
||||
payload,
|
||||
json!({"schema": INTENT, "commandId": id, "action": "createObject", "requestedBy": "nibu/hands",
|
||||
"note": "a cube", "objectType": "MESH", "location": [0, 0, 1]})
|
||||
);
|
||||
assert!(envelopes.iter().any(|e| e.key == "blender/receipts/seed"), "other records survive the write");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_intent_without_instance_or_agent_is_refused_and_writes_nothing() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let path = store_with_receipts(dir.path(), &[("seed", "accepted")]);
|
||||
let before = std::fs::read(&path).unwrap();
|
||||
for (instance, agent) in [(None, Some("hands")), (Some("nibu"), None), (None, None), (Some(" "), Some("hands"))] {
|
||||
let mut args = vec!["send", "createObject", "--no-wait"];
|
||||
if let Some(agent) = agent {
|
||||
args.extend(["--agent", agent]);
|
||||
}
|
||||
let output = ctl(&path, &args, instance);
|
||||
assert_eq!(output.status.code(), Some(1), "{instance:?} {agent:?}");
|
||||
}
|
||||
assert_eq!(std::fs::read(&path).unwrap(), before);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_missing_store_is_not_created() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let path = dir.path().join("nope.ccmp");
|
||||
let output = ctl(&path, &["send", "createObject", "--agent", "hands", "--no-wait"], Some("nibu"));
|
||||
assert_eq!(output.status.code(), Some(1));
|
||||
assert!(!path.exists());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn exit_code_follows_the_receipt() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let path = store_with_receipts(
|
||||
dir.path(),
|
||||
&[("a", "accepted"), ("d", "denied"), ("f", "failed"), ("s", "stopped")],
|
||||
);
|
||||
for (id, code) in [("a", 0), ("d", 2), ("f", 2), ("s", 3)] {
|
||||
let output = ctl(&path, &["wait", id, "--timeout", "5"], None);
|
||||
assert_eq!(output.status.code(), Some(code), "{id}");
|
||||
assert!(stdout(&output).contains(&format!("commandId: {id}")));
|
||||
}
|
||||
let output = ctl(&path, &["wait", "missing", "--timeout", "0.3"], None);
|
||||
assert_eq!(output.status.code(), Some(4));
|
||||
assert!(stdout(&output).contains("status: timeout"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn receipts_lists_the_last_n_oldest_first() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let path = store_with_receipts(dir.path(), &[("a", "accepted"), ("b", "failed")]);
|
||||
let output = ctl(&path, &["receipts"], None);
|
||||
assert_eq!(output.status.code(), Some(0));
|
||||
let text = stdout(&output);
|
||||
assert!(text.contains("commandId: a") && text.contains("commandId: b"));
|
||||
let one = ctl(&path, &["receipts", "--last", "1"], None);
|
||||
assert!(!stdout(&one).contains("commandId: a"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn status_without_a_snapshot_is_a_store_error() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let path = store_with_receipts(dir.path(), &[("a", "accepted")]);
|
||||
assert_eq!(ctl(&path, &["status"], None).status.code(), Some(1));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn send_help_lists_the_actions() {
|
||||
let output = Command::new(env!("CARGO_BIN_EXE_brokkr-ctl"))
|
||||
.args(["blender", "send", "--help"])
|
||||
.output()
|
||||
.unwrap();
|
||||
let text = stdout(&output);
|
||||
for action in ["createObject", "renderStill", "setModifierInput", "exportGltf"] {
|
||||
assert!(text.contains(action), "{action}");
|
||||
}
|
||||
}
|
||||
|
|
@ -6,7 +6,7 @@ publish = false
|
|||
|
||||
[dependencies]
|
||||
anyhow = "1"
|
||||
cultcache-rs = { git = "https://github.com/GameCult/CultLib.git", rev = "baf4ecf78fae634fafef956d3b85420162c074bb", package = "cultcache-rs" }
|
||||
cultcache-rs = { workspace = true }
|
||||
rmp-serde = "1.3"
|
||||
serde = { version = "1", features = ["derive"] }
|
||||
serde_json = "1"
|
||||
|
|
|
|||
73
surfaces/blender/tests/test_brokkr_ctl_interop.py
Normal file
73
surfaces/blender/tests/test_brokkr_ctl_interop.py
Normal file
|
|
@ -0,0 +1,73 @@
|
|||
"""brokkr-ctl writes an intent a cultmesh-py node pulls as the same dict, and reads a node's receipt.
|
||||
|
||||
No Blender. Needs CultLib's Python packages (CULTLIB_PACKAGES, the packages directory) and the built
|
||||
binary (BROKKR_CTL, the path to brokkr-ctl or brokkr-ctl.exe); skipped when either is missing.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import types
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
|
||||
ADDON = Path(__file__).resolve().parents[1] / "brokkr_bridge"
|
||||
package = types.ModuleType("brokkr_bridge")
|
||||
package.__path__ = [str(ADDON)]
|
||||
sys.modules.setdefault("brokkr_bridge", package)
|
||||
|
||||
from brokkr_bridge import blender_target as bt # noqa: E402
|
||||
|
||||
PACKAGES = os.environ.get("CULTLIB_PACKAGES", "")
|
||||
CTL = os.environ.get("BROKKR_CTL", "")
|
||||
|
||||
|
||||
@unittest.skipUnless(PACKAGES and Path(PACKAGES).is_dir(), "set CULTLIB_PACKAGES to CultLib's packages directory")
|
||||
@unittest.skipUnless(CTL and Path(CTL).is_file(), "set BROKKR_CTL to the built brokkr-ctl binary")
|
||||
class BrokkrCtlInterop(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.tmp = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(self.tmp.cleanup)
|
||||
self.store = str(Path(self.tmp.name) / "blender-editor.ccmp")
|
||||
self.cultmesh, self.cultcache = bt._load_cultmesh(PACKAGES)
|
||||
self.node = self.cultmesh.CultMesh.start_node(self.store, runtime_id="addon")
|
||||
self.intent = self.cultcache.define_document_type(bt.COMMAND_INTENT_SCHEMA)
|
||||
self.receipt = self.cultcache.define_document_type(bt.COMMAND_RECEIPT_SCHEMA)
|
||||
self.node.database.register_document(self.intent)
|
||||
self.node.database.register_document(self.receipt)
|
||||
# The add-on's own first write is what creates its store file.
|
||||
self.node.database.put(self.receipt, "blender/receipts/seed", {
|
||||
"schema": bt.COMMAND_RECEIPT_SCHEMA, "commandId": "seed", "status": "accepted"})
|
||||
|
||||
def ctl(self, *args):
|
||||
env = dict(os.environ, EUREKA_INSTANCE="nibu")
|
||||
env.pop("BROKKR_AGENT", None)
|
||||
return subprocess.run([CTL, "blender", *args, "--store", self.store], env=env,
|
||||
capture_output=True, text=True, timeout=60)
|
||||
|
||||
def test_a_node_pulls_the_intent_as_the_dict_ctl_wrote(self):
|
||||
sent = self.ctl("send", "createObject", "--set", 'objectType="MESH"', "--set", "location=[0,0,1]",
|
||||
"--note", "a cube", "--agent", "hands", "--no-wait")
|
||||
self.assertEqual(sent.returncode, 0, sent.stderr)
|
||||
command_id = sent.stdout.split("commandId:")[1].split()[0]
|
||||
self.node.database.pull()
|
||||
got = self.node.database.snapshot()[bt.COMMAND_INTENT_SCHEMA][f"blender/commands/{command_id}"]
|
||||
self.assertEqual(got, {
|
||||
"schema": bt.COMMAND_INTENT_SCHEMA, "commandId": command_id, "action": "createObject",
|
||||
"requestedBy": "nibu/hands", "note": "a cube", "objectType": "MESH", "location": [0, 0, 1]})
|
||||
# The node's own earlier record is still there after the Rust whole-store write.
|
||||
self.assertIn("blender/receipts/seed", self.node.database.snapshot()[bt.COMMAND_RECEIPT_SCHEMA])
|
||||
|
||||
def test_ctl_reads_a_receipt_the_node_wrote(self):
|
||||
self.node.database.put(self.receipt, "blender/receipts/r1", {
|
||||
"schema": bt.COMMAND_RECEIPT_SCHEMA, "commandId": "r1", "action": "createObject",
|
||||
"status": "failed", "message": "refused"})
|
||||
waited = self.ctl("wait", "r1", "--timeout", "5")
|
||||
self.assertEqual(waited.returncode, 2, waited.stderr)
|
||||
self.assertIn("message: refused", waited.stdout)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
Loading…
Reference in a new issue