use std::collections::BTreeSet;
use std::net::SocketAddr;
use sapphire_framework_settings::Value;
use serde::{Deserialize, Serialize};
use crate::error::{Error, Result};
use crate::settings::{HTTP_NAMES, Settings};
pub const SERVER_CONFIG_FILE: &str = "config.toml";
pub(crate) const MCP_MOVED: &str = "[mcp] http moved to [http.mcp] enabled";
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct ServerConfig {
#[serde(default)]
pub http: HttpConfig,
#[serde(default)]
pub update: UpdateConfig,
}
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct HttpConfig {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub listen: Option<SocketAddr>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub allowed_hosts: Vec<String>,
#[serde(default, skip_serializing_if = "is_default")]
pub mcp: HttpMcpConfig,
#[serde(default, skip_serializing_if = "is_default")]
pub metrics: HttpMetricsConfig,
#[serde(skip)]
pub endpoints: BTreeSet<String>,
}
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct HttpMcpConfig {
#[serde(default)]
pub enabled: bool,
}
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct HttpMetricsConfig {
#[serde(default)]
pub enabled: bool,
}
fn is_default<T: Default + PartialEq>(value: &T) -> bool {
*value == T::default()
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct UpdateConfig {
#[serde(default = "UpdateConfig::default_check")]
pub check: bool,
}
impl UpdateConfig {
fn default_check() -> bool {
true
}
}
impl Default for UpdateConfig {
fn default() -> Self {
UpdateConfig { check: true }
}
}
impl ServerConfig {
pub fn from_settings(settings: &Settings) -> Result<ServerConfig> {
let flag = |key: &str, default: bool| match settings.get(key) {
None => Ok(default),
Some(Value::Bool(b)) => Ok(b),
Some(_) => Err(invalid(key)),
};
let listen = match settings.get("http.listen") {
None => None,
Some(Value::String(s)) => Some(s.parse().map_err(|_| invalid("http.listen"))?),
Some(_) => return Err(invalid("http.listen")),
};
let allowed_hosts = match settings.get("http.allowed_hosts") {
None => Vec::new(),
Some(_) => settings
.get_as::<Vec<String>>("http.allowed_hosts")
.ok_or_else(|| invalid("http.allowed_hosts"))?,
};
let mut endpoints = BTreeSet::new();
for def in settings.registry().schema() {
let Some(name) = def
.key
.strip_prefix("http.")
.and_then(|rest| rest.strip_suffix(".enabled"))
.filter(|name| !name.contains('.') && !HTTP_NAMES.contains(name))
else {
continue;
};
if flag(&def.key, false)? {
endpoints.insert(name.to_owned());
}
}
Ok(ServerConfig {
http: HttpConfig {
listen,
allowed_hosts,
endpoints,
mcp: HttpMcpConfig {
enabled: flag("http.mcp.enabled", false)?,
},
metrics: HttpMetricsConfig {
enabled: flag("http.metrics.enabled", false)?,
},
},
update: UpdateConfig {
check: flag("update.check", true)?,
},
})
}
}
fn invalid(key: &str) -> Error {
Error::Config(format!(
"`{key}` in {SERVER_CONFIG_FILE} does not hold a valid value"
))
}
#[cfg(test)]
mod tests {
use super::*;
use std::sync::Arc;
fn from_text(text: Option<&str>) -> Result<ServerConfig> {
let tmp = tempfile::TempDir::new().unwrap();
let ctx = sapphire_workspace::AppContext::new("configtest");
ctx.set_config_dir(tmp.path().to_path_buf());
if let Some(text) = text {
std::fs::write(tmp.path().join(SERVER_CONFIG_FILE), text).unwrap();
}
ServerConfig::from_settings(&Settings::load(&ctx, Arc::new(()))?)
}
#[test]
fn a_missing_file_is_all_defaults_and_mcp_is_off() {
let config = from_text(None).unwrap();
assert_eq!(config, ServerConfig::default());
assert!(!config.http.mcp.enabled);
assert!(!config.http.metrics.enabled);
assert_eq!(config.http.listen, None);
assert!(config.update.check);
}
#[test]
fn the_file_turns_the_update_check_off() {
assert!(
!from_text(Some("[update]\ncheck = false\n"))
.unwrap()
.update
.check
);
assert!(from_text(Some("[update]\n")).unwrap().update.check);
}
#[test]
fn the_file_turns_mcp_on_and_names_the_listener() {
let config = from_text(Some(
"[http]\nlisten = \"127.0.0.1:3173\"\nallowed_hosts = [\"box.example\"]\n\n[http.mcp]\nenabled = true\n",
))
.unwrap();
assert!(config.http.mcp.enabled);
assert_eq!(config.http.listen, Some("127.0.0.1:3173".parse().unwrap()));
assert_eq!(config.http.allowed_hosts, vec!["box.example".to_owned()]);
}
#[test]
fn a_misspelt_setting_is_an_error_not_a_default() {
assert!(from_text(Some("[http.mcp]\nenabeld = true\n")).is_err());
assert!(from_text(Some("[htp]\nlisten = \"127.0.0.1:1\"\n")).is_ok());
}
#[test]
fn the_file_turns_metrics_on_under_http() {
let config = from_text(Some(
"[http]\nlisten = \"127.0.0.1:3173\"\n\n[http.metrics]\nenabled = true\n",
))
.unwrap();
assert!(config.http.metrics.enabled);
assert!(!config.http.mcp.enabled);
}
#[test]
fn the_application_keeps_its_own_table() {
let config = from_text(Some("[configtest]\nanything = 1\n")).unwrap();
assert_eq!(config, ServerConfig::default());
}
}