diff --git a/brokkr-ctl/Cargo.toml b/brokkr-ctl/Cargo.toml index cff9015..ce74ab3 100644 --- a/brokkr-ctl/Cargo.toml +++ b/brokkr-ctl/Cargo.toml @@ -8,7 +8,7 @@ publish = false anyhow = "1" cultcache-rs = { workspace = true } serde_json = "1" -uuid = { version = "1", features = ["v4"] } +uuid = { version = "1", features = ["v7"] } [dev-dependencies] tempfile = "3" diff --git a/brokkr-ctl/src/blender.rs b/brokkr-ctl/src/blender.rs index d054357..c35148b 100644 --- a/brokkr-ctl/src/blender.rs +++ b/brokkr-ctl/src/blender.rs @@ -15,8 +15,11 @@ 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 DEFAULT_TIMEOUT_SECS: u64 = 60; const POLL: Duration = Duration::from_millis(200); +const MAX_TIMEOUT: Duration = Duration::from_secs(24 * 3600); +/// Even when the file looks unchanged, read it again this often. +const RECHECK: Duration = Duration::from_secs(5); /// What a receipt (or its absence) says; the exit code derives from it and from nothing else. pub enum Outcome { @@ -52,7 +55,8 @@ struct Options { note: String, sets: Vec, no_wait: bool, - timeout: Option, + timeout: Option, + help: bool, last: Option, positional: Vec, } @@ -72,15 +76,20 @@ fn parse(args: &[String]) -> Result { "--note" => options.note = value("--note")?, "--set" => options.sets.push(value("--set")?), "--no-wait" => options.no_wait = true, + "--help" | "-h" => options.help = 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); + options.timeout = Some( + Duration::try_from_secs_f64(secs) + .ok() + .filter(|limit| *limit <= MAX_TIMEOUT) + .ok_or_else(|| { + anyhow!("--timeout wants seconds between 0 and {}", MAX_TIMEOUT.as_secs()) + })?, + ); } "--last" => { let raw = value("--last")?; @@ -106,11 +115,11 @@ pub fn run(args: &[String]) -> Result { print!("{}", group_help()); return Ok(0); } - if rest.iter().any(|arg| arg == "--help" || arg == "-h") { + let options = parse(rest)?; + if options.help { print!("{}", if sub == "send" { send_help() } else { group_help() }); return Ok(0); } - let options = parse(rest)?; match sub.as_str() { "send" => send(&options), "wait" => { @@ -132,7 +141,7 @@ fn one_positional<'a>(options: &'a Options, usage: &str) -> Result<&'a str> { } fn timeout(options: &Options) -> Duration { - Duration::from_secs_f64(options.timeout.unwrap_or(DEFAULT_TIMEOUT_SECS)) + options.timeout.unwrap_or(Duration::from_secs(DEFAULT_TIMEOUT_SECS)) } /// The add-on creates its store; naming a path that is not there is a typo, not a request @@ -143,11 +152,17 @@ fn open_store(options: &Options) -> Result { .clone() .or_else(|| std::env::var_os("BROKKR_BLENDER_STORE").map(PathBuf::from)) .ok_or_else(|| anyhow!("no store: pass --store or set BROKKR_BLENDER_STORE"))?; - if !path.is_file() { - bail!("store {} does not exist; the add-on creates it", path.display()); + // The add-on resolves its store against the blend file; ctl cannot know that, so it takes none. + if !path.is_absolute() { + bail!("store {} must be an absolute path", path.display()); } - // The store library stages writes beside the file and fails on a bare file name. - Ok(SingleFileMessagePackBackingStore::new(std::path::absolute(path)?)) + // A staged replace swaps the path itself, which would turn a link into a diverged copy. + let meta = std::fs::symlink_metadata(&path) + .map_err(|_| anyhow!("store {} does not exist; the add-on creates it", path.display()))?; + if meta.file_type().is_symlink() || !meta.is_file() { + bail!("store {} must be the add-on's regular file, not a link", path.display()); + } + Ok(SingleFileMessagePackBackingStore::new(path)) } fn requested_by(options: &Options) -> Result { @@ -197,7 +212,7 @@ fn send(options: &Options) -> Result { let action = one_positional(options, "send [--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 command_id = uuid::Uuid::now_v7().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}"), @@ -229,7 +244,16 @@ fn wait_for_receipt( limit: Duration, ) -> Result { let started = Instant::now(); + let mut gate = ChangeGate::new(store.path()); loop { + if !gate.should_read() { + if started.elapsed() >= limit { + println!("status: timeout"); + return Ok(Outcome::Timeout.code()); + } + thread::sleep(POLL); + continue; + } if let Some(receipt) = read_receipt(store, id)? { print_fields(&receipt); let status = receipt.get("status").and_then(Value::as_str).unwrap_or(""); @@ -243,6 +267,32 @@ fn wait_for_receipt( } } +/// Polling must not hold the store: a read takes the shared lock and an open handle, and on +/// Windows that can make the add-on's replace fail. So the file's stat is polled and the store +/// is read only after it changed (and every RECHECK as a backstop). +pub struct ChangeGate { + path: PathBuf, + seen: Option<(u64, Option)>, + last_read: Option, +} + +impl ChangeGate { + pub fn new(path: &std::path::Path) -> Self { + Self { path: path.to_path_buf(), seen: None, last_read: None } + } + + pub fn should_read(&mut self) -> bool { + let stamp = std::fs::metadata(&self.path).ok().map(|m| (m.len(), m.modified().ok())); + let stale = self.last_read.is_none_or(|at| at.elapsed() >= RECHECK); + if self.seen.is_none() || stamp != self.seen || stale { + self.seen = stamp; + self.last_read = Some(Instant::now()); + return true; + } + false + } +} + fn receipts(store: &SingleFileMessagePackBackingStore, last: Option) -> Result { let mut found = Vec::new(); for envelope in store.pull_all()? { @@ -578,6 +628,22 @@ mod tests { assert!(build_intent("../x", "abc", "a/b", "", &[]).is_err()); } + #[test] + fn the_gate_reads_first_then_only_after_the_file_changes() { + let dir = std::env::temp_dir().join(format!("brokkr-gate-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let file = dir.join("s.ccmp"); + std::fs::write(&file, b"one").unwrap(); + let mut gate = ChangeGate::new(&file); + assert!(gate.should_read()); + assert!(!gate.should_read()); + assert!(!gate.should_read()); + std::fs::write(&file, b"three").unwrap(); + assert!(gate.should_read()); + assert!(!gate.should_read()); + std::fs::remove_dir_all(&dir).unwrap(); + } + #[test] fn statuses_map_to_exit_codes() { for (status, code) in [("accepted", 0), ("denied", 2), ("failed", 2), ("stopped", 3), ("weird", 2)] { diff --git a/brokkr-ctl/tests/cli.rs b/brokkr-ctl/tests/cli.rs index a9cee07..a6e2ced 100644 --- a/brokkr-ctl/tests/cli.rs +++ b/brokkr-ctl/tests/cli.rs @@ -152,3 +152,171 @@ fn send_help_lists_the_actions() { assert!(text.contains(action), "{action}"); } } + +fn envelope_at(schema: &str, key: &str, payload: &Value) -> CultCacheEnvelope { + envelope(schema, key, payload) +} + +fn push(path: &Path, entries: &[CultCacheEnvelope]) { + let mut store = SingleFileMessagePackBackingStore::new(path); + for entry in entries { + store.push(entry).unwrap(); + } +} + +#[test] +fn intents_sent_in_order_sort_in_send_order() { + let dir = tempfile::tempdir().unwrap(); + let path = store_with_receipts(dir.path(), &[("seed", "accepted")]); + let mut sent = Vec::new(); + for _ in 0..8 { + let output = ctl(&path, &["send", "createObject", "--agent", "hands", "--no-wait"], Some("nibu")); + assert_eq!(output.status.code(), Some(0)); + sent.push(format!("blender/commands/{}", stdout(&output).trim().strip_prefix("commandId: ").unwrap())); + } + let mut sorted = sent.clone(); + sorted.sort(); + assert_eq!(sent, sorted, "the add-on drains by sorted key"); +} + +#[test] +fn an_absurd_timeout_is_a_usage_error_not_a_panic() { + let dir = tempfile::tempdir().unwrap(); + let path = store_with_receipts(dir.path(), &[("a", "accepted")]); + for value in ["1e300", "inf", "nan", "-1", "abc"] { + let output = ctl(&path, &["wait", "x", "--timeout", value], None); + assert_eq!(output.status.code(), Some(1), "{value}"); + } +} + +#[test] +fn help_words_as_option_values_do_not_swallow_the_command() { + let dir = tempfile::tempdir().unwrap(); + let path = store_with_receipts(dir.path(), &[("a", "accepted")]); + let output = ctl( + &path, + &["send", "createObject", "--note", "-h", "--agent", "--help", "--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(); + let found = SingleFileMessagePackBackingStore::new(&path).pull_all().unwrap(); + let intent = found.iter().find(|e| e.key == format!("blender/commands/{id}")).unwrap(); + let payload: Value = serde_json::from_slice(&intent.payload).unwrap(); + assert_eq!(payload["note"], "-h"); + assert_eq!(payload["requestedBy"], "nibu/--help"); + // a real help flag still prints help and sends nothing + let help = ctl(&path, &["send", "createObject", "--help"], Some("nibu")); + assert_eq!(help.status.code(), Some(0)); + assert!(stdout(&help).contains("actions:")); +} + +#[test] +fn a_relative_store_path_is_refused() { + let dir = tempfile::tempdir().unwrap(); + let path = store_with_receipts(dir.path(), &[("a", "accepted")]); + let output = Command::new(env!("CARGO_BIN_EXE_brokkr-ctl")) + .current_dir(dir.path()) + .args(["blender", "receipts", "--store", path.file_name().unwrap().to_str().unwrap()]) + .output() + .unwrap(); + assert_eq!(output.status.code(), Some(1)); + assert!(String::from_utf8_lossy(&output.stderr).contains("absolute")); +} + +#[test] +fn a_symlinked_store_is_refused() { + let dir = tempfile::tempdir().unwrap(); + let path = store_with_receipts(dir.path(), &[("a", "accepted")]); + let link = dir.path().join("link.ccmp"); + #[cfg(windows)] + let made = std::os::windows::fs::symlink_file(&path, &link); + #[cfg(unix)] + let made = std::os::unix::fs::symlink(&path, &link); + if made.is_err() { + eprintln!("skipped: no symlink privilege"); + return; + } + assert_eq!(ctl(&link, &["receipts"], None).status.code(), Some(1)); +} + +#[test] +fn receipts_only_come_from_the_receipt_keys_and_type() { + let dir = tempfile::tempdir().unwrap(); + let path = store_with_receipts(dir.path(), &[("real", "accepted")]); + let fake = json!({"commandId": "fake", "status": "accepted"}); + push( + &path, + &[ + envelope_at(RECEIPT, "elsewhere/fake", &fake), + envelope_at(INTENT, "blender/receipts/wrongtype", &fake), + ], + ); + let listed = stdout(&ctl(&path, &["receipts"], None)); + assert!(listed.contains("commandId: real")); + assert!(!listed.contains("fake"), "{listed}"); + let waited = ctl(&path, &["wait", "wrongtype", "--timeout", "0.3"], None); + assert_eq!(waited.status.code(), Some(4)); +} + +#[test] +fn receipts_sort_by_observed_time_not_by_key() { + let dir = tempfile::tempdir().unwrap(); + let path = store_with_receipts(dir.path(), &[]); + push( + &path, + &[ + envelope_at(RECEIPT, "blender/receipts/a", &json!({"commandId": "a", "observedAt": "2026-11-27T10:00:02+00:00"})), + envelope_at(RECEIPT, "blender/receipts/b", &json!({"commandId": "b", "observedAt": "2026-11-27T10:00:01+00:00"})), + ], + ); + let text = stdout(&ctl(&path, &["receipts"], None)); + assert!(text.find("commandId: b").unwrap() < text.find("commandId: a").unwrap(), "{text}"); +} + +#[test] +fn status_prints_the_snapshot_summary() { + let dir = tempfile::tempdir().unwrap(); + let path = store_with_receipts(dir.path(), &[]); + let snapshot = json!({"mode": "OBJECT", "activeScene": "Scene", "objectCount": 3, "selectedObjectNames": ["Cube"], "sink": {"enabled": true}}); + push(&path, &[envelope_at("brokkr.blender.host_snapshot.v0", "blender/host/current", &snapshot)]); + let output = ctl(&path, &["status"], None); + assert_eq!(output.status.code(), Some(0)); + let text = stdout(&output); + for line in ["mode: OBJECT", "activeScene: Scene", "objectCount: 3", "selectedObjectNames: [\"Cube\"]", "sink: {\"enabled\":true}"] { + assert!(text.contains(line), "{line} in {text}"); + } +} + +/// A pin, not a copy: every action the add-on dispatches is in `send --help`, and every help field +/// name is a string the add-on source mentions. The add-on has no machine-readable action table. +#[test] +fn help_names_every_dispatched_action_and_only_fields_the_addon_mentions() { + let addon = Path::new(env!("CARGO_MANIFEST_DIR")).join("../surfaces/blender/brokkr_bridge"); + let source: String = ["blender_target.py", "node_actions.py", "scene_actions.py"] + .iter() + .map(|file| std::fs::read_to_string(addon.join(file)).unwrap()) + .collect(); + let help = stdout( + &Command::new(env!("CARGO_BIN_EXE_brokkr-ctl")).args(["blender", "send", "--help"]).output().unwrap(), + ); + let mut dispatched: Vec = source + .lines() + .filter_map(|line| line.trim().strip_prefix("if action == \"")) + .filter_map(|rest| rest.split('"').next()) + .map(String::from) + .collect(); + let actions_line = source.lines().find(|l| l.contains("ACTIONS = (\"")).unwrap(); + dispatched.extend(actions_line.split('"').skip(1).step_by(2).map(String::from)); + assert!(dispatched.len() >= 20, "{dispatched:?}"); + let listed: Vec<&str> = help.lines().filter_map(|l| l.strip_prefix(" ")).filter(|l| !l.starts_with(' ')).collect(); + for action in &dispatched { + assert!(listed.contains(&action.as_str()), "help lacks {action}"); + } + for action in &listed { + assert!(dispatched.iter().any(|d| d == action) || *action == "actions:", "help lists unknown {action}"); + } + for field in help.lines().filter_map(|l| l.strip_prefix(" ")).filter_map(|l| l.split(':').next()) { + assert!(source.contains(&format!("\"{field}\"")), "add-on never mentions {field}"); + } +}