Skip to main content

cortexkit_bus_testkit/
config.rs

1use crate::RigError;
2use serde_json::{json, Value};
3use std::{
4    collections::BTreeMap,
5    path::{Path, PathBuf},
6};
7
8/// A module the private subc daemon spawns and supervises, like a production module entry in subc.jsonc. Environment entries augment the daemon's inherited
9/// environment; do not override its isolated XDG homes.
10#[derive(Clone, Debug)]
11pub struct Module {
12    pub id: String,
13    pub program: PathBuf,
14    pub args: Vec<String>,
15    pub env: BTreeMap<String, String>,
16    pub reserved: bool,
17    pub enabled: bool,
18}
19
20impl Module {
21    pub fn new(id: impl Into<String>, program: impl Into<PathBuf>) -> Self {
22        Self {
23            id: id.into(),
24            program: program.into(),
25            args: vec![],
26            env: BTreeMap::new(),
27            reserved: false,
28            enabled: true,
29        }
30    }
31}
32
33/// Build JSON (also valid JSONC) with a reserved ckbus and caller-supplied modules.
34/// All program paths are staged copies, even when a module is initially disabled.
35pub fn subc_config(
36    ck_bus: &Path,
37    ckbus_env: &[(String, String)],
38    modules: &[Module],
39) -> Result<String, RigError> {
40    let mut entries = serde_json::Map::new();
41    entries.insert(
42        "ckbus".into(),
43        json!({
44            "program": cortexkit_test_support::ckdev_binary(ck_bus), "args": [],
45            "env": ckbus_env.iter().cloned().collect::<BTreeMap<_, _>>(),
46            "enabled": true, "reserved": true, "protocol": "subc", "drain_timeout_ms": 2000,
47            "health": {"on_degraded": "report", "on_failing": "report"},
48        }),
49    );
50    for module in modules {
51        if module.id.is_empty() || entries.contains_key(&module.id) {
52            return Err(RigError::Invalid(format!(
53                "empty or duplicate module id {:?}",
54                module.id
55            )));
56        }
57        entries.insert(module.id.clone(), json!({
58            "program": cortexkit_test_support::ckdev_binary(&module.program), "args": module.args,
59            "env": module.env, "reserved": module.reserved, "enabled": module.enabled,
60            "protocol": "subc", "drain_timeout_ms": 2000,
61        }));
62    }
63    serde_json::to_string_pretty(
64        &json!({"version": 1, "port": 0, "modules": Value::Object(entries)}),
65    )
66    .map_err(|error| RigError::Invalid(error.to_string()))
67}