Skip to main content

sapphire_framework_server/
config.rs

1//! The server's own settings: `http.*` and `update.check` in `<config dir>/config.toml`.
2//!
3//! What a server offers beyond its IPC endpoint is the host's choice, so it lives in the
4//! application's config directory beside `workspace.toml`, with the application's own
5//! device settings (#314). Every setting is off or empty by default, and a missing file is
6//! all defaults. The server reads them when it starts, through [`Settings`]; the file used
7//! to be `server.toml`, which the server moves over once.
8//!
9//! ```toml
10//! [http]
11//! # Where the HTTP listener binds. Overrides the application's default address.
12//! listen = "127.0.0.1:3173"
13//! # The Host names clients use beyond loopback (a LAN name, a Tailscale name).
14//! allowed_hosts = ["box.tailnet.ts.net"]
15//!
16//! [http.mcp]
17//! # Serve the application's MCP tools at /mcp, behind an external device's token.
18//! enabled = true
19//!
20//! [http.metrics]
21//! # Serve Prometheus metrics at /metrics, without a token (counts and states only).
22//! enabled = true
23//!
24//! [update]
25//! # Do not ask GitHub for newer releases of this application. On by default, for an
26//! # application that names where its releases are.
27//! check = false
28//! ```
29
30use std::net::SocketAddr;
31
32use sapphire_framework_settings::Value;
33use serde::{Deserialize, Serialize};
34
35use crate::error::{Error, Result};
36use crate::settings::Settings;
37
38/// The device settings file's name inside the application's config directory.
39pub const SERVER_CONFIG_FILE: &str = "config.toml";
40
41/// Where the old `[mcp] http` went: `deny_unknown_fields` alone would only say that `mcp`
42/// is unknown.
43pub(crate) const MCP_MOVED: &str = "[mcp] http moved to [http.mcp] enabled";
44
45/// The server's settings, as `config.toml` holds them.
46#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
47#[serde(deny_unknown_fields)]
48pub struct ServerConfig {
49    /// The HTTP listener.
50    #[serde(default)]
51    pub http: HttpConfig,
52    /// Looking for newer releases.
53    #[serde(default)]
54    pub update: UpdateConfig,
55}
56
57/// The `[http]` table: the listener every HTTP route shares.
58///
59/// The listener binds only when something is served over it. Every route on it but
60/// `/metrics` is behind an external device's bearer token (`sapphire-framework-keys`).
61#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
62#[serde(deny_unknown_fields)]
63pub struct HttpConfig {
64    /// Where to bind. `None` is the application's default address, if it has one.
65    #[serde(default, skip_serializing_if = "Option::is_none")]
66    pub listen: Option<SocketAddr>,
67    /// The `Host` names clients reach the server by, beyond loopback.
68    #[serde(default, skip_serializing_if = "Vec::is_empty")]
69    pub allowed_hosts: Vec<String>,
70    /// MCP over HTTP.
71    #[serde(default, skip_serializing_if = "is_default")]
72    pub mcp: HttpMcpConfig,
73    /// Prometheus metrics over HTTP.
74    #[serde(default, skip_serializing_if = "is_default")]
75    pub metrics: HttpMetricsConfig,
76}
77
78/// The `[http.mcp]` table.
79#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
80#[serde(deny_unknown_fields)]
81pub struct HttpMcpConfig {
82    /// Serve the application's MCP tools at `/mcp` on the HTTP listener. Off by default.
83    #[serde(default)]
84    pub enabled: bool,
85}
86
87/// The `[http.metrics]` table.
88#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
89#[serde(deny_unknown_fields)]
90pub struct HttpMetricsConfig {
91    /// Serve Prometheus metrics at `/metrics` on the HTTP listener. Off by default.
92    #[serde(default)]
93    pub enabled: bool,
94}
95
96/// Serde's `skip_serializing_if` wants a function, and a table that is all defaults is
97/// not worth writing out.
98fn is_default<T: Default + PartialEq>(value: &T) -> bool {
99    *value == T::default()
100}
101
102/// The `[update]` table.
103#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
104#[serde(deny_unknown_fields)]
105pub struct UpdateConfig {
106    /// Ask the application's release page for newer releases, once at start and once a
107    /// day. On by default; it does nothing for an application that names no release page.
108    #[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    /// The framework's settings out of `settings`, as they were when it was read.
126    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
161/// A framework setting whose value is not one it takes; the value itself is not repeated.
162fn 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    /// The server config a `config.toml` of `text` (none for `None`) reads as.
174    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        // A table of another name may be the application's own: the file is shared.
220        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}