Skip to main content

sapphire_framework_server/
config.rs

1//! The server's own settings: `<config dir>/server.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`. Every setting is off or empty by
5//! default, and a missing file is all defaults. The server reads the file when it starts.
6//!
7//! ```toml
8//! [http]
9//! # Where the HTTP listener binds. Overrides the application's default address.
10//! listen = "127.0.0.1:3173"
11//! # The Host names clients use beyond loopback (a LAN name, a Tailscale name).
12//! allowed_hosts = ["box.tailnet.ts.net"]
13//!
14//! [mcp]
15//! # Serve the application's MCP tools at /mcp, behind an external device's token.
16//! http = true
17//!
18//! [update]
19//! # Do not ask GitHub for newer releases of this application. On by default, for an
20//! # application that names where its releases are.
21//! check = false
22//! ```
23
24use std::net::SocketAddr;
25use std::path::{Path, PathBuf};
26
27use sapphire_workspace::AppContext;
28use serde::{Deserialize, Serialize};
29
30use crate::error::{Error, Result};
31
32/// The file's name inside the application's config directory.
33pub const SERVER_CONFIG_FILE: &str = "server.toml";
34
35/// What `server.toml` holds.
36#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
37#[serde(deny_unknown_fields)]
38pub struct ServerConfig {
39    /// The HTTP listener.
40    #[serde(default)]
41    pub http: HttpConfig,
42    /// MCP over HTTP.
43    #[serde(default)]
44    pub mcp: McpConfig,
45    /// Looking for newer releases.
46    #[serde(default)]
47    pub update: UpdateConfig,
48}
49
50/// The `[http]` table: the listener every HTTP route shares.
51///
52/// The listener binds only when something is served over it. Every route on it is behind
53/// an external device's bearer token (`sapphire-framework-keys`).
54#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
55#[serde(deny_unknown_fields)]
56pub struct HttpConfig {
57    /// Where to bind. `None` is the application's default address, if it has one.
58    #[serde(default, skip_serializing_if = "Option::is_none")]
59    pub listen: Option<SocketAddr>,
60    /// The `Host` names clients reach the server by, beyond loopback.
61    #[serde(default, skip_serializing_if = "Vec::is_empty")]
62    pub allowed_hosts: Vec<String>,
63}
64
65/// The `[mcp]` table.
66#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
67#[serde(deny_unknown_fields)]
68pub struct McpConfig {
69    /// Serve the application's MCP tools at `/mcp` on the HTTP listener. Off by default.
70    #[serde(default)]
71    pub http: bool,
72}
73
74/// The `[update]` table.
75#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
76#[serde(deny_unknown_fields)]
77pub struct UpdateConfig {
78    /// Ask the application's release page for newer releases, once at start and once a
79    /// day. On by default; it does nothing for an application that names no release page.
80    #[serde(default = "UpdateConfig::default_check")]
81    pub check: bool,
82}
83
84impl UpdateConfig {
85    fn default_check() -> bool {
86        true
87    }
88}
89
90impl Default for UpdateConfig {
91    fn default() -> Self {
92        UpdateConfig { check: true }
93    }
94}
95
96impl ServerConfig {
97    /// `ctx`'s application's file; `None` while its config directory is unresolved.
98    pub fn path_for_app(ctx: &AppContext) -> Option<PathBuf> {
99        ctx.try_config_dir().map(|dir| dir.join(SERVER_CONFIG_FILE))
100    }
101
102    /// `ctx`'s application's settings. A context whose config directory was never resolved
103    /// has no file to read, and gets the defaults — as it gets no log file.
104    pub fn load_for_app(ctx: &AppContext) -> Result<ServerConfig> {
105        match ServerConfig::path_for_app(ctx) {
106            Some(path) => ServerConfig::load(&path),
107            None => Ok(ServerConfig::default()),
108        }
109    }
110
111    /// Read the file at `path`; a missing file is all defaults.
112    ///
113    /// A file that does not parse is an error rather than defaults: a host that asked for
114    /// something and got nothing would not find out why.
115    pub fn load(path: &Path) -> Result<ServerConfig> {
116        match std::fs::read_to_string(path) {
117            Ok(text) => {
118                toml::from_str(&text).map_err(|e| Error::Config(format!("{}: {e}", path.display())))
119            }
120            Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(ServerConfig::default()),
121            Err(e) => Err(Error::Io(e)),
122        }
123    }
124}
125
126#[cfg(test)]
127mod tests {
128    use super::*;
129
130    #[test]
131    fn a_missing_file_is_all_defaults_and_mcp_is_off() {
132        let tmp = tempfile::TempDir::new().unwrap();
133        let config = ServerConfig::load(&tmp.path().join(SERVER_CONFIG_FILE)).unwrap();
134        assert_eq!(config, ServerConfig::default());
135        assert!(!config.mcp.http);
136        assert_eq!(config.http.listen, None);
137        assert!(config.update.check);
138    }
139
140    #[test]
141    fn the_file_turns_the_update_check_off() {
142        let tmp = tempfile::TempDir::new().unwrap();
143        let path = tmp.path().join(SERVER_CONFIG_FILE);
144        std::fs::write(&path, "[update]\ncheck = false\n").unwrap();
145        assert!(!ServerConfig::load(&path).unwrap().update.check);
146        std::fs::write(&path, "[update]\n").unwrap();
147        assert!(ServerConfig::load(&path).unwrap().update.check);
148    }
149
150    #[test]
151    fn the_file_turns_mcp_on_and_names_the_listener() {
152        let tmp = tempfile::TempDir::new().unwrap();
153        let path = tmp.path().join(SERVER_CONFIG_FILE);
154        std::fs::write(
155            &path,
156            "[http]\nlisten = \"127.0.0.1:3173\"\nallowed_hosts = [\"box.example\"]\n\n[mcp]\nhttp = true\n",
157        )
158        .unwrap();
159        let config = ServerConfig::load(&path).unwrap();
160        assert!(config.mcp.http);
161        assert_eq!(config.http.listen, Some("127.0.0.1:3173".parse().unwrap()));
162        assert_eq!(config.http.allowed_hosts, vec!["box.example".to_owned()]);
163    }
164
165    #[test]
166    fn a_misspelt_setting_is_an_error_not_a_default() {
167        let tmp = tempfile::TempDir::new().unwrap();
168        let path = tmp.path().join(SERVER_CONFIG_FILE);
169        std::fs::write(&path, "[mcp]\nhtpp = true\n").unwrap();
170        assert!(ServerConfig::load(&path).is_err());
171    }
172}