Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
62 changes: 50 additions & 12 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 4 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -14,4 +14,8 @@ serenity = { version = "0.12", default-features = false, features = ["client", "
uuid = { version = "1", features = ["v4"] }
regex = "1"
anyhow = "1"
reqwest = { version = "0.12", default-features = false, features = ["rustls-tls"] }
rand = "0.8"

[dev-dependencies]
tempfile = "3.27.0"
109 changes: 107 additions & 2 deletions src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -153,8 +153,113 @@ fn expand_env_vars(raw: &str) -> String {
pub fn load_config(path: &Path) -> anyhow::Result<Config> {
let raw = std::fs::read_to_string(path)
.map_err(|e| anyhow::anyhow!("failed to read {}: {e}", path.display()))?;
let expanded = expand_env_vars(&raw);
parse_config(&raw, path.display().to_string().as_str())
}

pub async fn load_config_from_url(url: &str) -> anyhow::Result<Config> {
let client = reqwest::Client::builder()
.timeout(std::time::Duration::from_secs(10))
.build()?;
let resp = client
.get(url)
.send()
.await
.map_err(|e| anyhow::anyhow!("failed to fetch remote config from {url}: {e}"))?;
let status = resp.status();
if !status.is_success() {
anyhow::bail!("remote config request to {url} returned HTTP {status}");
}
let raw = resp
.text()
.await
.map_err(|e| anyhow::anyhow!("failed to read response body from {url}: {e}"))?;
parse_config(&raw, url)
}

fn parse_config(raw: &str, source: &str) -> anyhow::Result<Config> {
let expanded = expand_env_vars(raw);
let config: Config = toml::from_str(&expanded)
.map_err(|e| anyhow::anyhow!("failed to parse {}: {e}", path.display()))?;
.map_err(|e| anyhow::anyhow!("failed to parse config from {source}: {e}"))?;
Ok(config)
}

#[cfg(test)]
mod tests {
use super::*;
use std::io::Write;

const MINIMAL_TOML: &str = r#"
[discord]
bot_token = "test-token"

[agent]
command = "echo"
"#;

#[test]
fn parse_minimal_config() {
let cfg = parse_config(MINIMAL_TOML, "test").unwrap();
assert_eq!(cfg.discord.bot_token, "test-token");
assert_eq!(cfg.agent.command, "echo");
assert_eq!(cfg.pool.max_sessions, 10);
assert!(cfg.reactions.enabled);
}

#[test]
fn expand_env_vars_replaces_known_var() {
std::env::set_var("AB_TEST_VAR", "hello");
let result = expand_env_vars("token=${AB_TEST_VAR}");
assert_eq!(result, "token=hello");
std::env::remove_var("AB_TEST_VAR");
}

#[test]
fn expand_env_vars_unknown_becomes_empty() {
let result = expand_env_vars("token=${AB_NONEXISTENT_12345}");
assert_eq!(result, "token=");
}

#[test]
fn expand_env_vars_in_config() {
std::env::set_var("AB_TEST_TOKEN", "secret-bot-token");
let toml = r#"
[discord]
bot_token = "${AB_TEST_TOKEN}"

[agent]
command = "echo"
"#;
let cfg = parse_config(toml, "test").unwrap();
assert_eq!(cfg.discord.bot_token, "secret-bot-token");
std::env::remove_var("AB_TEST_TOKEN");
}

#[test]
fn parse_invalid_toml_returns_error() {
let result = parse_config("not valid toml {{{}}", "test");
assert!(result.is_err());
assert!(result.unwrap_err().to_string().contains("failed to parse config from test"));
}

#[test]
fn load_config_missing_file_returns_error() {
let result = load_config(Path::new("/tmp/agent-broker-nonexistent.toml"));
assert!(result.is_err());
assert!(result.unwrap_err().to_string().contains("failed to read"));
}

#[test]
fn load_config_from_file() {
let mut tmp = tempfile::NamedTempFile::new().unwrap();
write!(tmp, "{}", MINIMAL_TOML).unwrap();
let cfg = load_config(tmp.path()).unwrap();
assert_eq!(cfg.discord.bot_token, "test-token");
}

#[tokio::test]
async fn load_config_from_url_invalid_host() {
let result = load_config_from_url("https://invalid.test.example/config.toml").await;
assert!(result.is_err());
assert!(result.unwrap_err().to_string().contains("failed to fetch remote config"));
}
}
12 changes: 8 additions & 4 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,12 +19,16 @@ async fn main() -> anyhow::Result<()> {
)
.init();

let config_path = std::env::args()
let config_source = std::env::args()
.nth(1)
.map(PathBuf::from)
.unwrap_or_else(|| PathBuf::from("config.toml"));
.unwrap_or_else(|| "config.toml".into());

let cfg = config::load_config(&config_path)?;
let cfg = if config_source.starts_with("http://") || config_source.starts_with("https://") {
info!(url = %config_source, "fetching remote config");
config::load_config_from_url(&config_source).await?
} else {
config::load_config(&PathBuf::from(&config_source))?
};
info!(
agent_cmd = %cfg.agent.command,
pool_max = cfg.pool.max_sessions,
Expand Down