sapphire_framework_server/
config.rs1use std::collections::BTreeSet;
31use std::net::SocketAddr;
32
33use sapphire_framework_settings::Value;
34use serde::{Deserialize, Serialize};
35
36use crate::error::{Error, Result};
37use crate::settings::{HTTP_NAMES, Settings};
38
39pub const SERVER_CONFIG_FILE: &str = "config.toml";
41
42pub(crate) const MCP_MOVED: &str = "[mcp] http moved to [http.mcp] enabled";
45
46#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
48#[serde(deny_unknown_fields)]
49pub struct ServerConfig {
50 #[serde(default)]
52 pub http: HttpConfig,
53 #[serde(default)]
55 pub update: UpdateConfig,
56}
57
58#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
63#[serde(deny_unknown_fields)]
64pub struct HttpConfig {
65 #[serde(default, skip_serializing_if = "Option::is_none")]
67 pub listen: Option<SocketAddr>,
68 #[serde(default, skip_serializing_if = "Vec::is_empty")]
70 pub allowed_hosts: Vec<String>,
71 #[serde(default, skip_serializing_if = "is_default")]
73 pub mcp: HttpMcpConfig,
74 #[serde(default, skip_serializing_if = "is_default")]
76 pub metrics: HttpMetricsConfig,
77 #[serde(skip)]
80 pub endpoints: BTreeSet<String>,
81}
82
83#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
85#[serde(deny_unknown_fields)]
86pub struct HttpMcpConfig {
87 #[serde(default)]
89 pub enabled: bool,
90}
91
92#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
94#[serde(deny_unknown_fields)]
95pub struct HttpMetricsConfig {
96 #[serde(default)]
98 pub enabled: bool,
99}
100
101fn is_default<T: Default + PartialEq>(value: &T) -> bool {
104 *value == T::default()
105}
106
107#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
109#[serde(deny_unknown_fields)]
110pub struct UpdateConfig {
111 #[serde(default = "UpdateConfig::default_check")]
114 pub check: bool,
115}
116
117impl UpdateConfig {
118 fn default_check() -> bool {
119 true
120 }
121}
122
123impl Default for UpdateConfig {
124 fn default() -> Self {
125 UpdateConfig { check: true }
126 }
127}
128
129impl ServerConfig {
130 pub fn from_settings(settings: &Settings) -> Result<ServerConfig> {
132 let flag = |key: &str, default: bool| match settings.get(key) {
133 None => Ok(default),
134 Some(Value::Bool(b)) => Ok(b),
135 Some(_) => Err(invalid(key)),
136 };
137 let listen = match settings.get("http.listen") {
138 None => None,
139 Some(Value::String(s)) => Some(s.parse().map_err(|_| invalid("http.listen"))?),
140 Some(_) => return Err(invalid("http.listen")),
141 };
142 let allowed_hosts = match settings.get("http.allowed_hosts") {
143 None => Vec::new(),
144 Some(_) => settings
145 .get_as::<Vec<String>>("http.allowed_hosts")
146 .ok_or_else(|| invalid("http.allowed_hosts"))?,
147 };
148 let mut endpoints = BTreeSet::new();
149 for def in settings.registry().schema() {
150 let Some(name) = def
151 .key
152 .strip_prefix("http.")
153 .and_then(|rest| rest.strip_suffix(".enabled"))
154 .filter(|name| !name.contains('.') && !HTTP_NAMES.contains(name))
155 else {
156 continue;
157 };
158 if flag(&def.key, false)? {
159 endpoints.insert(name.to_owned());
160 }
161 }
162 Ok(ServerConfig {
163 http: HttpConfig {
164 listen,
165 allowed_hosts,
166 endpoints,
167 mcp: HttpMcpConfig {
168 enabled: flag("http.mcp.enabled", false)?,
169 },
170 metrics: HttpMetricsConfig {
171 enabled: flag("http.metrics.enabled", false)?,
172 },
173 },
174 update: UpdateConfig {
175 check: flag("update.check", true)?,
176 },
177 })
178 }
179}
180
181fn invalid(key: &str) -> Error {
183 Error::Config(format!(
184 "`{key}` in {SERVER_CONFIG_FILE} does not hold a valid value"
185 ))
186}
187
188#[cfg(test)]
189mod tests {
190 use super::*;
191 use std::sync::Arc;
192
193 fn from_text(text: Option<&str>) -> Result<ServerConfig> {
195 let tmp = tempfile::TempDir::new().unwrap();
196 let ctx = sapphire_workspace::AppContext::new("configtest");
197 ctx.set_config_dir(tmp.path().to_path_buf());
198 if let Some(text) = text {
199 std::fs::write(tmp.path().join(SERVER_CONFIG_FILE), text).unwrap();
200 }
201 ServerConfig::from_settings(&Settings::load(&ctx, Arc::new(()))?)
202 }
203
204 #[test]
205 fn a_missing_file_is_all_defaults_and_mcp_is_off() {
206 let config = from_text(None).unwrap();
207 assert_eq!(config, ServerConfig::default());
208 assert!(!config.http.mcp.enabled);
209 assert!(!config.http.metrics.enabled);
210 assert_eq!(config.http.listen, None);
211 assert!(config.update.check);
212 }
213
214 #[test]
215 fn the_file_turns_the_update_check_off() {
216 assert!(
217 !from_text(Some("[update]\ncheck = false\n"))
218 .unwrap()
219 .update
220 .check
221 );
222 assert!(from_text(Some("[update]\n")).unwrap().update.check);
223 }
224
225 #[test]
226 fn the_file_turns_mcp_on_and_names_the_listener() {
227 let config = from_text(Some(
228 "[http]\nlisten = \"127.0.0.1:3173\"\nallowed_hosts = [\"box.example\"]\n\n[http.mcp]\nenabled = true\n",
229 ))
230 .unwrap();
231 assert!(config.http.mcp.enabled);
232 assert_eq!(config.http.listen, Some("127.0.0.1:3173".parse().unwrap()));
233 assert_eq!(config.http.allowed_hosts, vec!["box.example".to_owned()]);
234 }
235
236 #[test]
237 fn a_misspelt_setting_is_an_error_not_a_default() {
238 assert!(from_text(Some("[http.mcp]\nenabeld = true\n")).is_err());
239 assert!(from_text(Some("[htp]\nlisten = \"127.0.0.1:1\"\n")).is_ok());
241 }
242
243 #[test]
244 fn the_file_turns_metrics_on_under_http() {
245 let config = from_text(Some(
246 "[http]\nlisten = \"127.0.0.1:3173\"\n\n[http.metrics]\nenabled = true\n",
247 ))
248 .unwrap();
249 assert!(config.http.metrics.enabled);
250 assert!(!config.http.mcp.enabled);
251 }
252
253 #[test]
254 fn the_application_keeps_its_own_table() {
255 let config = from_text(Some("[configtest]\nanything = 1\n")).unwrap();
256 assert_eq!(config, ServerConfig::default());
257 }
258}