Skip to main content

robonix_executor/
config.rs

1// SPDX-License-Identifier: MulanPSL-2.0
2// Author: wheatfox <wheatfox17@icloud.com>
3//
4// Executor config — same three-source resolution as pilot:
5//   compiled defaults < YAML at $ROBONIX_CONFIG_PATH < CLI flags / env.
6
7use anyhow::{Context, Result, bail};
8use clap::Parser;
9use serde::Deserialize;
10use std::collections::HashSet;
11use std::path::{Path, PathBuf};
12
13pub const DEFAULT_EXECUTOR_PROVIDER_ID: &str = "executor";
14pub const EXECUTOR_NAMESPACE: &str = "robonix/system/executor";
15pub const DEFAULT_ATLAS_ENDPOINT: &str = "127.0.0.1:50051";
16pub const DEFAULT_LISTEN: &str = "127.0.0.1:50061";
17
18/// Resolved startup settings for Executor connections, identity, and verification.
19#[derive(Debug, Clone)]
20pub struct ExecutorConfig {
21    /// Atlas endpoint used for registration and capability discovery.
22    pub atlas_endpoint: String,
23    /// Socket address on which Executor serves its gRPC capabilities.
24    pub listen: String,
25    /// Executor's registered provider ID, also used as its consumer identity.
26    pub id: String,
27    /// Timing and routing rules for verifying successful capability results.
28    pub verification: VerificationConfig,
29}
30
31/// Executor-wide verification timing plus capability-specific routes.
32#[derive(Debug, Clone, Default, Deserialize, PartialEq)]
33pub struct VerificationConfig {
34    /// Allow capability execution to continue while matched rules verify.
35    #[serde(default)]
36    pub overlap: bool,
37    /// Rules matching completed calls to the verifier that checks their results.
38    #[serde(default)]
39    pub rules: Vec<VerificationRule>,
40}
41
42/// Route one completed capability call to a verifier provider.
43#[derive(Debug, Clone, Deserialize, PartialEq)]
44pub struct VerificationRule {
45    /// Contract ID of the capability calls whose results should be verified.
46    pub target_contract_id: String,
47    /// Optional provider restriction; omission matches any provider of the contract.
48    #[serde(default)]
49    pub target_provider_id: Option<String>,
50    /// Provider implementing the shared verification contract for matched calls.
51    pub verifier_provider_id: String,
52    /// Extra JSON object passed to the verifier alongside the original call context.
53    #[serde(default = "empty_json_object")]
54    pub verifier_args: serde_json::Value,
55}
56
57fn empty_json_object() -> serde_json::Value {
58    serde_json::json!({})
59}
60
61/// CLI and environment inputs used to configure Executor startup and logging.
62#[derive(Parser, Debug)]
63#[command(
64    name = "robonix-executor",
65    about = "Robonix Executor — tool-call dispatch runtime"
66)]
67pub struct Args {
68    /// Atlas control-plane endpoint. Also reads `ROBONIX_ATLAS` (the var rbnx /
69    /// the Python API / liaison use) as an alias; see `env_atlas`.
70    #[arg(long, env = "ROBONIX_ATLAS_ENDPOINT")]
71    pub atlas: Option<String>,
72
73    /// Address the SystemExecutor gRPC service binds to.
74    #[arg(long, env = "ROBONIX_EXECUTOR_LISTEN")]
75    pub listen: Option<String>,
76
77    /// Override executor's id (singleton; rarely needed).
78    #[arg(long, env = "ROBONIX_EXECUTOR_PROVIDER_ID")]
79    pub id: Option<String>,
80
81    /// Optional YAML config file (rbnx writes this; CLI/env still override).
82    #[arg(long, env = "ROBONIX_CONFIG_PATH")]
83    pub config: Option<PathBuf>,
84
85    /// Log level for this component (`debug`/`info`/`warn`/`error`). Sets the
86    /// scribe log-file floor; falls back to `SCRIBE_FILE_LEVEL` / `info`.
87    /// Normally arrives inside `--config-json`, not as a standalone flag.
88    #[arg(long)]
89    pub log: Option<String>,
90
91    /// The component's `system.executor` manifest block, serialized to JSON by
92    /// rbnx and passed as one arg (`--config-json '{…}'`). Parsed by the binary
93    /// itself — see `robonix_scribe::init_from_config`, which reads the `log`
94    /// key from it so the manifest's per-component level reaches the log.
95    #[arg(long)]
96    pub config_json: Option<String>,
97}
98
99/// Optional YAML settings used when higher-priority startup inputs are absent.
100#[derive(Default, Deserialize)]
101struct FileConfig {
102    /// Atlas connection endpoint supplied by the YAML file.
103    #[serde(default)]
104    atlas_endpoint: Option<String>,
105    /// Executor gRPC bind address supplied by the YAML file.
106    #[serde(default)]
107    listen: Option<String>,
108    /// Executor provider ID supplied by the YAML file.
109    #[serde(default)]
110    id: Option<String>,
111    /// Verification settings used when the manifest block does not supply them.
112    #[serde(default)]
113    verification: Option<VerificationConfig>,
114}
115
116/// Executor settings decoded from the manifest block passed through `--config-json`.
117#[derive(Default, Deserialize)]
118struct ManifestConfig {
119    /// Manifest verification settings, which take precedence over YAML settings.
120    #[serde(default)]
121    verification: Option<VerificationConfig>,
122}
123
124impl ExecutorConfig {
125    /// Resolve connection settings from the existing CLI/env/YAML sources and
126    /// verification rules from the manifest block, falling back to YAML.
127    pub fn resolve(args: Args) -> Result<Self> {
128        let file_cfg: FileConfig = match &args.config {
129            Some(path) => load_yaml(path)?,
130            None => FileConfig::default(),
131        };
132        let manifest_cfg: ManifestConfig = match args.config_json.as_deref() {
133            Some(raw) => serde_json::from_str(raw).context("parse Executor --config-json")?,
134            None => ManifestConfig::default(),
135        };
136        let mut verification = manifest_cfg
137            .verification
138            .or(file_cfg.verification)
139            .unwrap_or_default();
140        verification.rules = validate_verification_rules(verification.rules)?;
141        Ok(Self {
142            atlas_endpoint: args
143                .atlas
144                .or_else(env_atlas)
145                .or(file_cfg.atlas_endpoint)
146                .unwrap_or_else(|| DEFAULT_ATLAS_ENDPOINT.to_string()),
147            listen: args
148                .listen
149                .or(file_cfg.listen)
150                .unwrap_or_else(|| DEFAULT_LISTEN.to_string()),
151            id: args
152                .id
153                .or(file_cfg.id)
154                .unwrap_or_else(|| DEFAULT_EXECUTOR_PROVIDER_ID.to_string()),
155            verification,
156        })
157    }
158}
159
160/// Normalize identifiers and reject ambiguous rules before Executor starts.
161fn validate_verification_rules(rules: Vec<VerificationRule>) -> Result<Vec<VerificationRule>> {
162    let mut seen = HashSet::new();
163    let mut normalized = Vec::with_capacity(rules.len());
164    for mut rule in rules {
165        rule.target_contract_id = rule.target_contract_id.trim().to_string();
166        rule.verifier_provider_id = rule.verifier_provider_id.trim().to_string();
167        rule.target_provider_id = rule
168            .target_provider_id
169            .map(|value| value.trim().to_string())
170            .filter(|value| !value.is_empty());
171        if rule.target_contract_id.is_empty() {
172            bail!("verification target_contract_id must not be empty");
173        }
174        if rule.verifier_provider_id.is_empty() {
175            bail!(
176                "verification verifier_provider_id must not be empty for '{}'",
177                rule.target_contract_id
178            );
179        }
180        if !rule.verifier_args.is_object() {
181            bail!(
182                "verification verifier_args must be a JSON object for '{}'",
183                rule.target_contract_id
184            );
185        }
186        let key = (
187            rule.target_contract_id.clone(),
188            rule.target_provider_id.clone(),
189        );
190        if !seen.insert(key) {
191            bail!(
192                "duplicate verification rule for contract '{}' and provider '{}'",
193                rule.target_contract_id,
194                rule.target_provider_id.as_deref().unwrap_or("*")
195            );
196        }
197        normalized.push(rule);
198    }
199    Ok(normalized)
200}
201
202/// Read the `ROBONIX_ATLAS` env var as an atlas-endpoint alias.
203///
204/// rbnx, the Python API, and liaison all configure the atlas endpoint via
205/// `ROBONIX_ATLAS`, while executor/pilot historically only honored
206/// `ROBONIX_ATLAS_ENDPOINT` (the clap `env`). Accepting `ROBONIX_ATLAS` here as
207/// well means a single env var configures every component. Without it, setting
208/// only `ROBONIX_ATLAS` left executor silently falling back to
209/// `DEFAULT_ATLAS_ENDPOINT` (127.0.0.1:50051) — it would then dial the wrong
210/// atlas and log 127.0.0.1 even after the operator "changed" the endpoint.
211/// Empty values are ignored so an exported-but-blank var doesn't shadow later
212/// sources.
213fn env_atlas() -> Option<String> {
214    std::env::var("ROBONIX_ATLAS")
215        .ok()
216        .filter(|v| !v.is_empty())
217}
218
219fn load_yaml(path: &Path) -> Result<FileConfig> {
220    let raw = std::fs::read_to_string(path)
221        .with_context(|| format!("read executor config '{}'", path.display()))?;
222    serde_yaml::from_str(&raw)
223        .with_context(|| format!("parse executor config '{}'", path.display()))
224}
225
226#[cfg(test)]
227mod tests {
228    use super::*;
229
230    fn args(config_json: Option<&str>) -> Args {
231        Args {
232            atlas: None,
233            listen: None,
234            id: None,
235            config: None,
236            log: None,
237            config_json: config_json.map(str::to_string),
238        }
239    }
240
241    #[test]
242    fn parses_manifest_verification_rules() {
243        let cfg = ExecutorConfig::resolve(args(Some(
244            r#"{
245                "verification": {
246                    "overlap": true,
247                    "rules": [{
248                        "target_contract_id": "robonix/service/navigation/navigate",
249                        "verifier_provider_id": "scene_verifier",
250                        "verifier_args": {"scene_provider_id": "scene"}
251                    }]
252                }
253            }"#,
254        )))
255        .unwrap();
256        assert_eq!(cfg.verification.rules.len(), 1);
257        assert!(cfg.verification.overlap);
258        assert_eq!(
259            cfg.verification.rules[0].verifier_args["scene_provider_id"],
260            "scene"
261        );
262    }
263
264    /// Verification configs that omit overlap retain synchronous behavior.
265    #[test]
266    fn verification_overlap_defaults_to_false() {
267        let cfg = ExecutorConfig::resolve(args(Some(
268            r#"{
269                "verification": {
270                    "rules": [{
271                        "target_contract_id": "cap/a",
272                        "verifier_provider_id": "verifier"
273                    }]
274                }
275            }"#,
276        )))
277        .unwrap();
278
279        assert!(!cfg.verification.overlap);
280    }
281
282    #[test]
283    fn explicit_empty_manifest_rules_disable_defaults() {
284        let cfg =
285            ExecutorConfig::resolve(args(Some(r#"{"verification": {"rules": []}}"#))).unwrap();
286        assert!(cfg.verification.rules.is_empty());
287    }
288
289    #[test]
290    fn rejects_duplicate_rules_at_the_same_specificity() {
291        let error = ExecutorConfig::resolve(args(Some(
292            r#"{
293                "verification": {"rules": [
294                    {"target_contract_id":"cap/a","verifier_provider_id":"v1"},
295                    {"target_contract_id":"cap/a","verifier_provider_id":"v2"}
296                ]}
297            }"#,
298        )))
299        .unwrap_err();
300        assert!(error.to_string().contains("duplicate verification rule"));
301    }
302
303    #[test]
304    fn rejects_non_object_verifier_args() {
305        let error = ExecutorConfig::resolve(args(Some(
306            r#"{
307                "verification": {"rules": [{
308                    "target_contract_id":"cap/a",
309                    "verifier_provider_id":"v1",
310                    "verifier_args": ["bad"]
311                }]}
312            }"#,
313        )))
314        .unwrap_err();
315        assert!(error.to_string().contains("must be a JSON object"));
316    }
317}
浙ICP备2023005800号-2 浙公网安备33010902005384号