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