Skip to main content

sapphire_framework_server/
settings.rs

1//! The app server's settings (#314): the framework's keys and the application's, in one
2//! registry.
3//!
4//! The framework owns `http.*` and `update.check`, all on the device and all read once at
5//! start. The application owns the keys under its own name and under the top-level names it
6//! declares, on the device or in the workspace; it says what they are ([`AppSettings`]) and
7//! the framework says where they live:
8//!
9//! | Scope | File |
10//! |---|---|
11//! | Device | `<config dir>/config.toml` |
12//! | Workspace | `{root}/.{app}/config.toml`, of the workspace selected at the time |
13//! | Secrets | `<config dir>/secrets/<key>`, owner-only |
14//!
15//! The device's file is the application's own `config.toml` too: the framework reads and
16//! checks only its own tables (`[http]`, `[update]`) and the application's keys, and a
17//! write changes only the keys it names, leaving everything else in the file as it was.
18//!
19//! `config.toml` replaces `server.toml`, whose layout it keeps: [`migrate`] moves the old
20//! file's tables over once.
21
22use std::collections::BTreeMap;
23use std::path::{Path, PathBuf};
24use std::sync::{Arc, RwLock};
25
26use sapphire_framework_settings::{
27    Apply, FieldError, Kind, Process, Registry, Scope, SettingDef, SettingsOwner, Staged,
28    StartState, Value,
29};
30use sapphire_workspace::AppContext;
31use tokio::sync::watch;
32
33use crate::config::{MCP_MOVED, SERVER_CONFIG_FILE};
34use crate::error::{Error, Result};
35use crate::selection::SelectionFile;
36
37/// The file `config.toml` replaces, and what it is renamed to once migrated.
38const OLD_CONFIG_FILE: &str = "server.toml";
39const OLD_CONFIG_BACKUP: &str = "server.toml.v1";
40
41/// What `workspace()` says with no workspace to put the file in.
42const NO_WORKSPACE: &str = "no workspace is selected";
43
44/// Top-level names the framework keeps for itself, whether or not it defines keys there.
45const FRAMEWORK_NAMES: [&str; 5] = sapphire_framework_settings::SERVER_NAMES;
46
47/// The framework's tables the device file is checked under: the names it defines keys in.
48/// Every other name in the file is the application's business (an application keeps its
49/// own `[workspace]` there, say).
50const CHECKED_NAMES: [&str; 2] = ["http", "update"];
51
52/// The bridge's top-level names: owned by no one here, so no key of this server takes them.
53pub(crate) const BRIDGE_NAMES: [&str; 3] = ["net", "embed", "gui"];
54
55/// An application's own settings: what they are, and a check of the edited files as a
56/// whole.
57///
58/// Every key starts with the application's name and a dot, or with one of the top-level
59/// names it declares ([`names`](AppSettings::names)); it lives on the device or in the
60/// workspace (not in the workgroup), and a secret lives on the device only. Where the files
61/// are is the framework's business. `()` is an application with no settings of its own.
62pub trait AppSettings: Send + Sync + 'static {
63    /// The application's settings, in the order a listing shows them.
64    fn defs(&self) -> Vec<SettingDef>;
65
66    /// The top-level names the application takes beside its own: tables such as
67    /// `anthropic` for `[anthropic]`, or a bare key such as `day_boundary_hour`. None of
68    /// them may be one the framework or the bridge keeps.
69    fn names(&self) -> &[&str] {
70        &[]
71    }
72
73    /// The HTTP endpoints the application serves with
74    /// [`AppServer::http_endpoint`](crate::AppServer::http_endpoint): each gets an
75    /// `http.<name>.enabled` setting, off by default, and is served at `/<name>` only while
76    /// it is on.
77    fn http_endpoints(&self) -> Vec<HttpEndpoint> {
78        Vec::new()
79    }
80
81    /// Check the edited files as a whole, before anything is written; also run once when
82    /// the server starts, against the files as they are.
83    ///
84    /// `files` says where the application's files are; `staged.read(path)` gives a file as
85    /// the write would leave it, falling back to what is on disk for a file the write does
86    /// not touch.
87    fn validate(
88        &self,
89        _files: &AppFiles,
90        _staged: &Staged,
91    ) -> std::result::Result<(), Vec<FieldError>> {
92        Ok(())
93    }
94}
95
96/// An HTTP endpoint an application declares ([`AppSettings::http_endpoints`]).
97#[derive(Clone, Debug, PartialEq, Eq)]
98pub struct HttpEndpoint {
99    /// Its path and its setting's name: served at `/<name>`, turned on by
100    /// `http.<name>.enabled`. Lowercase letters, digits, `-` and `_`.
101    pub name: String,
102    /// What it serves, for its setting's help text.
103    pub doc: String,
104}
105
106impl HttpEndpoint {
107    /// The endpoint `name`, its switch described by `doc`.
108    pub fn new(name: impl Into<String>, doc: impl Into<String>) -> HttpEndpoint {
109        HttpEndpoint {
110            name: name.into(),
111            doc: doc.into(),
112        }
113    }
114
115    /// The setting that turns it on.
116    pub(crate) fn key(&self) -> String {
117        endpoint_key(&self.name)
118    }
119}
120
121/// The setting that turns the endpoint `name` on.
122pub(crate) fn endpoint_key(name: &str) -> String {
123    format!("http.{name}.enabled")
124}
125
126/// The names under `[http]` the framework's own settings take: no endpoint may use them.
127pub(crate) const HTTP_NAMES: [&str; 4] = ["listen", "allowed_hosts", "mcp", "metrics"];
128
129/// Where an application's settings files are, for [`AppSettings::validate`].
130#[derive(Clone, Debug, PartialEq, Eq)]
131pub struct AppFiles {
132    device: PathBuf,
133    workspace: Option<PathBuf>,
134}
135
136impl AppFiles {
137    /// The device's file, `<config dir>/config.toml`.
138    pub fn device(&self) -> &Path {
139        &self.device
140    }
141
142    /// The selected workspace's file, `{root}/.{app}/config.toml`; `None` when no
143    /// workspace is selected.
144    pub fn workspace(&self) -> Option<&Path> {
145        self.workspace.as_deref()
146    }
147}
148
149impl AppSettings for () {
150    fn defs(&self) -> Vec<SettingDef> {
151        Vec::new()
152    }
153}
154
155/// Where the app server's settings live.
156#[derive(Clone, Debug)]
157pub(crate) struct SettingsFiles {
158    config_dir: PathBuf,
159    app_name: &'static str,
160    selection: SelectionFile,
161}
162
163impl SettingsFiles {
164    /// `ctx`'s application's files; an error while its config directory is unresolved.
165    #[cfg(test)]
166    pub(crate) fn for_app(ctx: &AppContext) -> Result<SettingsFiles> {
167        SettingsFiles::with_selection(ctx, SelectionFile::for_app(ctx))
168    }
169
170    /// [`for_app`](Self::for_app), with the selected workspace read from `selection`: the
171    /// server's own, where a fixture moved it.
172    pub(crate) fn with_selection(
173        ctx: &AppContext,
174        selection: SelectionFile,
175    ) -> Result<SettingsFiles> {
176        let config_dir = ctx.try_config_dir().ok_or_else(|| {
177            Error::Config(format!(
178                "{} has no config directory, so no settings",
179                ctx.app_name
180            ))
181        })?;
182        Ok(SettingsFiles {
183            config_dir: config_dir.to_path_buf(),
184            app_name: ctx.app_name,
185            selection,
186        })
187    }
188
189    /// The device's file.
190    pub(crate) fn device(&self) -> PathBuf {
191        self.config_dir.join(SERVER_CONFIG_FILE)
192    }
193
194    /// The selected workspace's file, as the selection is now: a selection that changes
195    /// moves the workspace scope with it.
196    pub(crate) fn workspace(&self) -> Result<PathBuf> {
197        match self.selection.load(self.app_name)? {
198            Some(selection) => Ok(selection
199                .root
200                .join(format!(".{}", self.app_name))
201                .join("config.toml")),
202            None => Err(Error::Config(NO_WORKSPACE.to_owned())),
203        }
204    }
205
206    /// The application's files, as its `validate` is told them now.
207    fn app_files(&self) -> AppFiles {
208        AppFiles {
209            device: self.device(),
210            workspace: self.workspace().ok(),
211        }
212    }
213
214    /// The owner-only file of the secret `key`.
215    pub(crate) fn secret(&self, key: &str) -> PathBuf {
216        self.config_dir.join("secrets").join(key)
217    }
218
219    /// The file of `scope`, as an owner answers it.
220    fn scope_file(&self, scope: Scope) -> sapphire_framework_settings::Result<PathBuf> {
221        match scope {
222            Scope::Device => Ok(self.device()),
223            Scope::Workspace => self
224                .workspace()
225                .map_err(|e| std::io::Error::other(e.to_string()).into()),
226            Scope::Workgroup => Err(std::io::Error::other(format!(
227                "the {} server has no workgroup scope",
228                self.app_name
229            ))
230            .into()),
231        }
232    }
233}
234
235/// The framework's settings, in the order a listing shows them: the application's
236/// `endpoints` get their switches after the framework's own.
237fn framework_defs(endpoints: &[HttpEndpoint]) -> Vec<SettingDef> {
238    let def = |key: &str, kind: Kind, default: Option<Value>, doc: &str| SettingDef {
239        key: key.into(),
240        kind,
241        scopes: vec![Scope::Device],
242        overridable: false,
243        apply: Apply::Restart,
244        default,
245        section: "Server".into(),
246        doc: doc.into(),
247        process: Process::App,
248    };
249    let mut defs = vec![
250        def(
251            "http.listen",
252            Kind::SocketAddr,
253            None,
254            "Where the HTTP listener binds; unset = the application's default address",
255        ),
256        def(
257            "http.allowed_hosts",
258            Kind::List {
259                item: Box::new(Kind::String { non_empty: true }),
260            },
261            None,
262            "The Host names clients reach the server by, beyond loopback",
263        ),
264        def(
265            "http.mcp.enabled",
266            Kind::Bool,
267            Some(Value::Bool(false)),
268            "Serve the application's MCP tools at /mcp, behind an API key's token",
269        ),
270        def(
271            "http.metrics.enabled",
272            Kind::Bool,
273            Some(Value::Bool(false)),
274            "Serve Prometheus metrics at /metrics, without a token",
275        ),
276    ];
277    defs.extend(endpoints.iter().map(|endpoint| {
278        def(
279            &endpoint.key(),
280            Kind::Bool,
281            Some(Value::Bool(false)),
282            &endpoint.doc,
283        )
284    }));
285    defs.push(def(
286        "update.check",
287        Kind::Bool,
288        Some(Value::Bool(true)),
289        "Look for newer releases of the application, at start and once a day",
290    ));
291    defs
292}
293
294/// The framework as a settings owner, with the switches of the application's HTTP
295/// endpoints.
296struct FrameworkOwner {
297    files: SettingsFiles,
298    endpoints: Vec<HttpEndpoint>,
299}
300
301impl SettingsOwner for FrameworkOwner {
302    fn defs(&self) -> Vec<SettingDef> {
303        framework_defs(&self.endpoints)
304    }
305
306    fn file(&self, scope: Scope) -> sapphire_framework_settings::Result<PathBuf> {
307        self.files.scope_file(scope)
308    }
309
310    fn secret_file(&self, key: &str) -> sapphire_framework_settings::Result<PathBuf> {
311        Ok(self.files.secret(key))
312    }
313
314    fn validate(&self, staged: &Staged) -> std::result::Result<(), Vec<FieldError>> {
315        check_device_file(&self.files, staged, &self.endpoints)
316    }
317}
318
319/// The application as a settings owner, in the framework's files.
320struct AppOwner {
321    files: SettingsFiles,
322    app: Arc<dyn AppSettings>,
323}
324
325impl SettingsOwner for AppOwner {
326    fn defs(&self) -> Vec<SettingDef> {
327        self.app
328            .defs()
329            .into_iter()
330            .map(|def| SettingDef {
331                process: Process::App,
332                ..def
333            })
334            .collect()
335    }
336
337    fn file(&self, scope: Scope) -> sapphire_framework_settings::Result<PathBuf> {
338        self.files.scope_file(scope)
339    }
340
341    fn secret_file(&self, key: &str) -> sapphire_framework_settings::Result<PathBuf> {
342        Ok(self.files.secret(key))
343    }
344
345    fn validate(&self, staged: &Staged) -> std::result::Result<(), Vec<FieldError>> {
346        self.app.validate(&self.files.app_files(), staged)
347    }
348}
349
350/// The app server's registry: the framework (owner 0) and the application (owner 1).
351///
352/// A declared name the framework or the bridge keeps, an HTTP endpoint named like one of
353/// the framework's `http.*` settings or badly, an application key outside `<app_name>.`
354/// and the declared names, or one the workgroup may hold, is
355/// [`InvalidDef`](sapphire_framework_settings::Error::InvalidDef).
356pub(crate) fn registry(
357    ctx: &AppContext,
358    files: &SettingsFiles,
359    app: Arc<dyn AppSettings>,
360) -> sapphire_framework_settings::Result<Registry> {
361    let names: Vec<String> = app.names().iter().map(|n| (*n).to_owned()).collect();
362    for name in &names {
363        let invalid = |message: String| sapphire_framework_settings::Error::InvalidDef {
364            key: name.clone(),
365            message,
366        };
367        if name.is_empty() || name.contains('.') {
368            return Err(invalid(
369                "an application's top-level name is one segment, without a dot".to_owned(),
370            ));
371        }
372        if FRAMEWORK_NAMES.contains(&name.as_str()) || BRIDGE_NAMES.contains(&name.as_str()) {
373            return Err(invalid(format!(
374                "`{name}` is kept by the framework, not an application's"
375            )));
376        }
377    }
378    let endpoints = app.http_endpoints();
379    for (i, endpoint) in endpoints.iter().enumerate() {
380        let invalid = |message: String| sapphire_framework_settings::Error::InvalidDef {
381            key: endpoint.key(),
382            message,
383        };
384        let name = endpoint.name.as_str();
385        if name.is_empty()
386            || !name
387                .chars()
388                .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '-' || c == '_')
389        {
390            return Err(invalid(
391                "an endpoint's name is lowercase letters, digits, `-` and `_`".to_owned(),
392            ));
393        }
394        if HTTP_NAMES.contains(&name) {
395            return Err(invalid(format!(
396                "`http.{name}` is the framework's, not an endpoint's"
397            )));
398        }
399        if endpoints[..i].iter().any(|e| e.name == endpoint.name) {
400            return Err(sapphire_framework_settings::Error::Duplicate(
401                endpoint.key(),
402            ));
403        }
404    }
405    let prefix = format!("{}.", ctx.app_name);
406    for def in app.defs() {
407        let invalid = |message: String| sapphire_framework_settings::Error::InvalidDef {
408            key: def.key.clone(),
409            message,
410        };
411        let top = def.key.split('.').next().unwrap_or_default();
412        if !def.key.starts_with(&prefix) && !names.iter().any(|n| n == top) {
413            return Err(invalid(format!(
414                "an application's key starts with `{prefix}` or a top-level name it declares"
415            )));
416        }
417        if def.scopes.contains(&Scope::Workgroup) {
418            return Err(invalid(
419                "an application's key lives on the device or in the workspace, not in the workgroup"
420                    .to_owned(),
421            ));
422        }
423    }
424    // No owner has this index: the bridge's names are reserved against both.
425    const NO_OWNER: usize = usize::MAX;
426    let mut reserved: Vec<(&str, usize)> = FRAMEWORK_NAMES.iter().map(|n| (*n, 0)).collect();
427    reserved.push((ctx.app_name, 1));
428    reserved.extend(names.iter().map(|n| (n.as_str(), 1)));
429    reserved.extend(BRIDGE_NAMES.iter().map(|n| (*n, NO_OWNER)));
430    Registry::new(
431        vec![
432            Arc::new(FrameworkOwner {
433                files: files.clone(),
434                endpoints,
435            }),
436            Arc::new(AppOwner {
437                files: files.clone(),
438                app,
439            }),
440        ],
441        &reserved,
442    )
443}
444
445/// The device file's framework part: the old `[mcp]` table, unknown keys under `[http]` and
446/// `[update]`, and framework values of the wrong kind. Every other table — the
447/// application's own config shares the file — is left alone.
448///
449/// Values are never quoted back: the message names the key and the file only.
450fn check_device_file(
451    files: &SettingsFiles,
452    staged: &Staged,
453    endpoints: &[HttpEndpoint],
454) -> std::result::Result<(), Vec<FieldError>> {
455    let path = files.device();
456    let failure = |key: Option<String>, message: String| FieldError {
457        key,
458        file: Some(path.clone()),
459        message,
460    };
461    let text = match staged.read(&path) {
462        Ok(Some(text)) => text,
463        Ok(None) => return Ok(()),
464        Err(e) => return Err(vec![failure(None, e.to_string())]),
465    };
466    let table = match text.parse::<toml::Table>() {
467        Ok(table) => table,
468        Err(e) => {
469            return Err(vec![failure(
470                None,
471                sapphire_framework_settings::describe_toml_error(&text, e.span(), e.message()),
472            )]);
473        }
474    };
475    let defs = framework_defs(endpoints);
476    let mut errors = Vec::new();
477    for (name, item) in &table {
478        if name == "mcp" {
479            errors.push(failure(None, MCP_MOVED.to_owned()));
480        } else if CHECKED_NAMES.contains(&name.as_str()) {
481            let mut leaves = Vec::new();
482            leaves_of(name.clone(), item, &mut leaves);
483            for (key, value) in leaves {
484                let in_file = format!("in {}", path.display());
485                match defs.iter().find(|d| d.key == key) {
486                    None => errors.push(failure(Some(key), format!("unknown setting {in_file}"))),
487                    Some(def) => {
488                        if !accepts(&def.kind, value) {
489                            errors.push(failure(
490                                Some(key),
491                                format!("the value {in_file} is not a valid one"),
492                            ));
493                        }
494                    }
495                }
496            }
497        }
498    }
499    if errors.is_empty() {
500        Ok(())
501    } else {
502        Err(errors)
503    }
504}
505
506/// Every non-table value under `item`, by its dotted path.
507fn leaves_of<'a>(path: String, item: &'a toml::Value, out: &mut Vec<(String, &'a toml::Value)>) {
508    match item {
509        toml::Value::Table(table) => {
510            for (name, child) in table {
511                leaves_of(format!("{path}.{name}"), child, out);
512            }
513        }
514        other => out.push((path, other)),
515    }
516}
517
518/// Whether a TOML value is one `kind` accepts.
519fn accepts(kind: &Kind, value: &toml::Value) -> bool {
520    to_value(value).is_some_and(|v| kind.check(&v).is_ok())
521}
522
523/// A TOML value as a setting value; floats, datetimes and tables are none.
524fn to_value(value: &toml::Value) -> Option<Value> {
525    match value {
526        toml::Value::String(s) => Some(Value::String(s.clone())),
527        toml::Value::Integer(i) => Some(Value::Int(*i)),
528        toml::Value::Boolean(b) => Some(Value::Bool(*b)),
529        toml::Value::Array(items) => items
530            .iter()
531            .map(to_value)
532            .collect::<Option<_>>()
533            .map(Value::List),
534        _ => None,
535    }
536}
537
538/// Move `<config_dir>/server.toml` into `config.toml`, keeping the old file as
539/// `server.toml.v1`.
540///
541/// With no `config.toml`, the old file's text becomes it unchanged. With one — the
542/// application's own config shares the file — the old file's tables are merged in, the
543/// existing file's comments and content kept: a key it already has wins, with a warning
544/// naming the key. A rename that fails once the new file is written is a warning (the old
545/// file may be held open); the next start merges it again, changing nothing.
546pub(crate) fn migrate(config_dir: &Path) -> Result<()> {
547    let new = config_dir.join(SERVER_CONFIG_FILE);
548    let old = config_dir.join(OLD_CONFIG_FILE);
549    let text = match std::fs::read_to_string(&old) {
550        Ok(text) => text,
551        Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(()),
552        Err(e) => return Err(Error::Io(e)),
553    };
554    let merged = match std::fs::read_to_string(&new) {
555        Ok(existing) => {
556            let mut doc = parse_doc(&new, &existing)?;
557            let from = parse_doc(&old, &text)?;
558            let mut kept = Vec::new();
559            merge_tables(doc.as_table_mut(), from.as_table(), "", &mut kept);
560            for key in kept {
561                tracing::warn!(
562                    "{key} is in both {} and {}; the value in {} is kept",
563                    old.display(),
564                    new.display(),
565                    new.display()
566                );
567            }
568            doc.to_string()
569        }
570        Err(e) if e.kind() == std::io::ErrorKind::NotFound => text,
571        Err(e) => return Err(Error::Io(e)),
572    };
573    sapphire_framework_settings::write_atomic(&new, &merged)?;
574    let backup = config_dir.join(OLD_CONFIG_BACKUP);
575    match std::fs::rename(&old, &backup) {
576        Ok(()) => tracing::info!(
577            "{} moved to {}; the old file is kept as {OLD_CONFIG_BACKUP}",
578            old.display(),
579            new.display()
580        ),
581        Err(e) => tracing::warn!(
582            "{} moved to {}, but it could not be renamed to {OLD_CONFIG_BACKUP}: {e}",
583            old.display(),
584            new.display()
585        ),
586    }
587    Ok(())
588}
589
590/// `text`, the content of `path`, as an editable document.
591fn parse_doc(path: &Path, text: &str) -> Result<toml_edit::DocumentMut> {
592    text.parse::<toml_edit::DocumentMut>().map_err(|e| {
593        sapphire_framework_settings::Error::Unparsable {
594            file: path.to_path_buf(),
595            message: sapphire_framework_settings::describe_toml_error(text, e.span(), e.message()),
596        }
597        .into()
598    })
599}
600
601/// Add to `into` what `from` holds and it does not, table by table; a key both hold keeps
602/// `into`'s value and is pushed, dotted under `prefix`, to `kept`.
603fn merge_tables(
604    into: &mut dyn toml_edit::TableLike,
605    from: &dyn toml_edit::TableLike,
606    prefix: &str,
607    kept: &mut Vec<String>,
608) {
609    for (name, item) in from.iter() {
610        let key = if prefix.is_empty() {
611            name.to_owned()
612        } else {
613            format!("{prefix}.{name}")
614        };
615        match into.get_mut(name) {
616            None => {
617                let mut item = item.clone();
618                unplace(&mut item);
619                into.insert(name, item);
620            }
621            Some(existing) => match (existing.as_table_like_mut(), item.as_table_like()) {
622                (Some(existing), Some(item)) => merge_tables(existing, item, &key, kept),
623                _ => kept.push(key),
624            },
625        }
626    }
627}
628
629/// Clear the positions a table brought from its own document, so it is written after what
630/// the document it joins already holds.
631fn unplace(item: &mut toml_edit::Item) {
632    fn table(table: &mut toml_edit::Table) {
633        table.set_position(None);
634        for (_, child) in table.iter_mut() {
635            unplace(child);
636        }
637    }
638    match item {
639        toml_edit::Item::Table(t) => table(t),
640        toml_edit::Item::ArrayOfTables(array) => array.iter_mut().for_each(table),
641        _ => {}
642    }
643}
644
645/// A Rust type a setting's value reads as, for [`Settings::get_as`].
646pub trait FromValue: Sized {
647    /// `value` as this type, or `None` when it is of another kind.
648    fn from_value(value: Value) -> Option<Self>;
649}
650
651impl FromValue for bool {
652    fn from_value(value: Value) -> Option<Self> {
653        match value {
654            Value::Bool(b) => Some(b),
655            _ => None,
656        }
657    }
658}
659
660impl FromValue for i64 {
661    fn from_value(value: Value) -> Option<Self> {
662        match value {
663            Value::Int(i) => Some(i),
664            _ => None,
665        }
666    }
667}
668
669impl FromValue for String {
670    fn from_value(value: Value) -> Option<Self> {
671        match value {
672            Value::String(s) => Some(s),
673            _ => None,
674        }
675    }
676}
677
678impl FromValue for Vec<String> {
679    fn from_value(value: Value) -> Option<Self> {
680        match value {
681            Value::List(items) => items.into_iter().map(String::from_value).collect(),
682            _ => None,
683        }
684    }
685}
686
687/// The app server's settings as the running server sees them: a cheap, clonable handle.
688///
689/// Keys that apply on a restart keep the values they had when the server started; keys
690/// that apply live follow every write, a change of the selected workspace and a change sync
691/// or an edit makes to its `config.toml`, and [`changed`](Self::changed) announces it.
692///
693/// A key that applies on a restart is pending while its value differs from the one the
694/// server started with, so switching to a workspace whose file holds another value for a
695/// workspace key of that kind makes it pending too.
696#[derive(Clone)]
697pub struct Settings {
698    inner: Arc<Inner>,
699}
700
701struct Inner {
702    registry: Registry,
703    start: StartState,
704    /// Effective values, secrets and unset keys left out.
705    values: RwLock<BTreeMap<String, Value>>,
706    changed: watch::Sender<u64>,
707}
708
709impl std::fmt::Debug for Settings {
710    // Never the values: they are the user's.
711    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
712        f.debug_struct("Settings").finish_non_exhaustive()
713    }
714}
715
716impl Settings {
717    /// Read `ctx`'s application's settings: migrate `server.toml`, build the registry,
718    /// check the device file and the application's files, and read every value.
719    pub(crate) fn load(ctx: &AppContext, app: Arc<dyn AppSettings>) -> Result<Settings> {
720        Settings::load_with(ctx, app, SelectionFile::for_app(ctx))
721    }
722
723    /// [`load`](Self::load), with the selected workspace — and so the workspace scope's
724    /// file — read from `selection`.
725    pub(crate) fn load_with(
726        ctx: &AppContext,
727        app: Arc<dyn AppSettings>,
728        selection: SelectionFile,
729    ) -> Result<Settings> {
730        let files = SettingsFiles::with_selection(ctx, selection)?;
731        migrate(&files.config_dir)?;
732        let registry = registry(ctx, &files, Arc::clone(&app))?;
733        startup_check(&files, &*app)?;
734        let values = read(&registry)?;
735        let start = StartState::capture(&registry)?;
736        Ok(Settings {
737            inner: Arc::new(Inner {
738                registry,
739                start,
740                values: RwLock::new(values),
741                changed: watch::channel(0).0,
742            }),
743        })
744    }
745
746    /// Every key at its default, with no file read, migrated or checked: for the commands
747    /// that must work whatever the files hold (`update`, `service`, `mcp`).
748    ///
749    /// The registry still points at the usual files, but nothing here opens them. An error
750    /// only when the application's own definitions break the registry's rules.
751    pub(crate) fn defaults(ctx: &AppContext, app: Arc<dyn AppSettings>) -> Result<Settings> {
752        let config_dir = ctx
753            .try_config_dir()
754            .map(Path::to_path_buf)
755            .unwrap_or_default();
756        let files = SettingsFiles {
757            selection: SelectionFile::at(config_dir.join(crate::selection::SELECTION_FILE)),
758            config_dir,
759            app_name: ctx.app_name,
760        };
761        let registry = registry(ctx, &files, app)?;
762        let values = registry
763            .schema()
764            .into_iter()
765            .filter(|def| def.kind != Kind::Secret)
766            .filter_map(|def| def.default.map(|value| (def.key, value)))
767            .collect();
768        Ok(Settings {
769            inner: Arc::new(Inner {
770                registry,
771                start: StartState::default(),
772                values: RwLock::new(values),
773                changed: watch::channel(0).0,
774            }),
775        })
776    }
777
778    /// The config directory's `config.toml`, where the device's settings are: for a message
779    /// about them. `None` while the directory is unresolved.
780    pub(crate) fn device_file(ctx: &AppContext) -> Option<PathBuf> {
781        ctx.try_config_dir().map(|dir| dir.join(SERVER_CONFIG_FILE))
782    }
783
784    /// The effective value of `key`: `None` for a secret, an unset key or an unknown one.
785    pub fn get(&self, key: &str) -> Option<Value> {
786        self.inner
787            .values
788            .read()
789            .unwrap_or_else(|e| e.into_inner())
790            .get(key)
791            .cloned()
792    }
793
794    /// The effective value of `key` as `T`; `None` as for [`get`](Self::get), or when the
795    /// value is of another kind.
796    pub fn get_as<T: FromValue>(&self, key: &str) -> Option<T> {
797        self.get(key).and_then(T::from_value)
798    }
799
800    /// Bumped whenever the effective value of a key that applies live changes: after a
801    /// write, a change of the selected workspace, or a change to its `config.toml`.
802    pub fn changed(&self) -> watch::Receiver<u64> {
803        self.inner.changed.subscribe()
804    }
805
806    /// Read the files again after a write, a change of selection or a change to the
807    /// workspace's file: live keys take their new values, and [`changed`](Self::changed)
808    /// is bumped if any did; restart keys keep their start values. Synchronous, and holding
809    /// its lock only while it swaps the values in, so any caller may run it.
810    pub(crate) fn refresh(&self) -> Result<()> {
811        let new = read(&self.inner.registry)?;
812        let mut values = self.inner.values.write().unwrap_or_else(|e| e.into_inner());
813        let mut any = false;
814        for def in self.inner.registry.schema() {
815            if def.apply != Apply::Live || values.get(&def.key) == new.get(&def.key) {
816                continue;
817            }
818            any = true;
819            match new.get(&def.key) {
820                Some(value) => values.insert(def.key, value.clone()),
821                None => values.remove(&def.key),
822            };
823        }
824        drop(values);
825        if any {
826            self.inner.changed.send_modify(|n| *n = n.wrapping_add(1));
827        }
828        Ok(())
829    }
830
831    /// The registry the server reads and writes through.
832    pub(crate) fn registry(&self) -> &Registry {
833        &self.inner.registry
834    }
835
836    /// The restart keys' values at start, to tell which writes wait for a restart.
837    pub(crate) fn start(&self) -> &StartState {
838        &self.inner.start
839    }
840}
841
842/// The checks a server runs on the files as they are before it starts: the device file's
843/// framework part and the application's `validate`.
844fn startup_check(files: &SettingsFiles, app: &dyn AppSettings) -> Result<()> {
845    let mut errors = Vec::new();
846    for result in [
847        check_device_file(files, &Staged::default(), &app.http_endpoints()),
848        app.validate(&files.app_files(), &Staged::default()),
849    ] {
850        if let Err(e) = result {
851            errors.extend(e);
852        }
853    }
854    if errors.is_empty() {
855        Ok(())
856    } else {
857        Err(sapphire_framework_settings::Error::Rejected(errors).into())
858    }
859}
860
861/// `ctx`'s registry, `server.toml` migrated, with the outcome of the checks a starting
862/// server runs kept apart rather than failing: for the offline `config`, which must be able
863/// to repair a file those checks refuse. A write still goes through the owners' checks of
864/// the edited files.
865pub(crate) fn open_unchecked(
866    ctx: &AppContext,
867    app: Arc<dyn AppSettings>,
868) -> Result<(Registry, Result<()>)> {
869    let files = SettingsFiles::with_selection(ctx, SelectionFile::for_app(ctx))?;
870    migrate(&files.config_dir)?;
871    let registry = registry(ctx, &files, Arc::clone(&app))?;
872    let checked = startup_check(&files, &*app);
873    Ok((registry, checked))
874}
875
876/// Every key's effective value, secrets and unset keys left out.
877fn read(registry: &Registry) -> Result<BTreeMap<String, Value>> {
878    Ok(sapphire_framework_settings::list(registry, None, None)?
879        .into_iter()
880        .filter_map(|entry| match entry.value {
881            sapphire_framework_settings::EntryValue::Value(value) => Some((entry.key, value)),
882            _ => None,
883        })
884        .collect())
885}
886
887#[cfg(test)]
888mod tests {
889    use super::*;
890    use crate::config::ServerConfig;
891    use crate::selection::Selection;
892    use sapphire_framework_settings::{Op, apply};
893    use sapphire_workspace::AppContext;
894    use std::path::Path;
895    use std::sync::Arc;
896
897    const APP: &str = "settingstest";
898
899    /// A context of its own for each test, its config directory in `tmp`.
900    fn context(tmp: &Path) -> AppContext {
901        let ctx = AppContext::new(APP);
902        let dir = tmp.join("config");
903        std::fs::create_dir_all(&dir).unwrap();
904        ctx.set_config_dir(dir);
905        ctx
906    }
907
908    struct TestApp(Vec<SettingDef>);
909
910    impl AppSettings for TestApp {
911        fn defs(&self) -> Vec<SettingDef> {
912            self.0.clone()
913        }
914    }
915
916    fn app_def(key: &str, kind: Kind, scopes: Vec<Scope>, apply: Apply) -> SettingDef {
917        SettingDef {
918            key: key.into(),
919            kind,
920            scopes,
921            overridable: false,
922            apply,
923            default: None,
924            section: "Test".into(),
925            doc: "test".into(),
926            // Left as the default on purpose: the framework marks the app's defs.
927            process: Process::Bridge,
928        }
929    }
930
931    fn one(def: SettingDef) -> Arc<dyn AppSettings> {
932        Arc::new(TestApp(vec![def]))
933    }
934
935    /// An application with top-level names of its own.
936    struct Named(&'static [&'static str], Vec<SettingDef>);
937
938    impl AppSettings for Named {
939        fn defs(&self) -> Vec<SettingDef> {
940            self.1.clone()
941        }
942
943        fn names(&self) -> &[&str] {
944            self.0
945        }
946    }
947
948    fn set(key: &str, value: Value) -> Op {
949        Op::Set {
950            key: key.into(),
951            value,
952        }
953    }
954
955    fn select(ctx: &AppContext, root: &Path) {
956        std::fs::create_dir_all(root).unwrap();
957        SelectionFile::for_app(ctx)
958            .save(&Selection {
959                root: root.to_path_buf(),
960                sync: false,
961            })
962            .unwrap();
963    }
964
965    #[test]
966    fn server_toml_becomes_config_toml() {
967        let tmp = tempfile::tempdir().unwrap();
968        let text = "# mine\n[update]\ncheck = false\n";
969        std::fs::write(tmp.path().join("server.toml"), text).unwrap();
970        migrate(tmp.path()).unwrap();
971        assert_eq!(
972            std::fs::read_to_string(tmp.path().join("config.toml")).unwrap(),
973            text
974        );
975        assert_eq!(
976            std::fs::read_to_string(tmp.path().join("server.toml.v1")).unwrap(),
977            text
978        );
979        assert!(!tmp.path().join("server.toml").exists());
980        // Once done, it is done.
981        migrate(tmp.path()).unwrap();
982        assert!(!tmp.path().join("server.toml").exists());
983    }
984
985    /// Every log line `f` writes, at any level.
986    fn logged(f: impl FnOnce()) -> String {
987        use std::sync::Mutex;
988        #[derive(Clone, Default)]
989        struct Captured(Arc<Mutex<Vec<u8>>>);
990        impl std::io::Write for Captured {
991            fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
992                self.0.lock().unwrap().extend_from_slice(buf);
993                Ok(buf.len())
994            }
995            fn flush(&mut self) -> std::io::Result<()> {
996                Ok(())
997            }
998        }
999        let captured = Captured::default();
1000        let writer = captured.clone();
1001        let subscriber = tracing_subscriber::fmt()
1002            .with_writer(move || writer.clone())
1003            .with_ansi(false)
1004            .finish();
1005        tracing::subscriber::with_default(subscriber, f);
1006        String::from_utf8(captured.0.lock().unwrap().clone()).unwrap()
1007    }
1008
1009    #[test]
1010    fn server_toml_merges_into_an_existing_config_toml() {
1011        let tmp = tempfile::tempdir().unwrap();
1012        let old = "# old\n[update]\ncheck = false\n\n[http.mcp]\n# mine\nenabled = true\n";
1013        std::fs::write(tmp.path().join("server.toml"), old).unwrap();
1014        let app =
1015            "# the app's own\nsync_interval_minutes = 5\n\n[anthropic]\napi_key = \"x\" # keep\n";
1016        std::fs::write(tmp.path().join("config.toml"), app).unwrap();
1017        let log = logged(|| migrate(tmp.path()).unwrap());
1018        let merged = std::fs::read_to_string(tmp.path().join("config.toml")).unwrap();
1019        assert!(merged.starts_with(app), "{merged}");
1020        let table: toml::Table = merged.parse().unwrap();
1021        assert_eq!(table["update"]["check"].as_bool(), Some(false));
1022        assert_eq!(table["http"]["mcp"]["enabled"].as_bool(), Some(true));
1023        assert_eq!(table["anthropic"]["api_key"].as_str(), Some("x"));
1024        assert!(merged.contains("# mine"), "{merged}");
1025        assert_eq!(
1026            std::fs::read_to_string(tmp.path().join("server.toml.v1")).unwrap(),
1027            old
1028        );
1029        assert!(!tmp.path().join("server.toml").exists());
1030        assert!(!log.contains("WARN"), "{log}");
1031        // Once done, it is done.
1032        migrate(tmp.path()).unwrap();
1033        assert_eq!(
1034            std::fs::read_to_string(tmp.path().join("config.toml")).unwrap(),
1035            merged
1036        );
1037    }
1038
1039    #[test]
1040    fn a_key_config_toml_already_has_wins_with_a_warning() {
1041        let tmp = tempfile::tempdir().unwrap();
1042        std::fs::write(
1043            tmp.path().join("server.toml"),
1044            "[update]\ncheck = false\n[http]\nlisten = \"10.9.8.7:1\"\n",
1045        )
1046        .unwrap();
1047        std::fs::write(tmp.path().join("config.toml"), "[update]\ncheck = true\n").unwrap();
1048        let log = logged(|| migrate(tmp.path()).unwrap());
1049        let table: toml::Table = std::fs::read_to_string(tmp.path().join("config.toml"))
1050            .unwrap()
1051            .parse()
1052            .unwrap();
1053        assert_eq!(table["update"]["check"].as_bool(), Some(true));
1054        assert_eq!(table["http"]["listen"].as_str(), Some("10.9.8.7:1"));
1055        assert!(
1056            log.contains("WARN") && log.contains("update.check"),
1057            "{log}"
1058        );
1059        // The key, never the value.
1060        assert!(!log.contains("false"), "{log}");
1061        assert!(tmp.path().join("server.toml.v1").exists());
1062        assert!(!tmp.path().join("server.toml").exists());
1063    }
1064
1065    #[cfg(unix)]
1066    #[test]
1067    fn a_merge_keeps_config_tomls_permissions() {
1068        use std::os::unix::fs::PermissionsExt;
1069        let tmp = tempfile::tempdir().unwrap();
1070        std::fs::write(tmp.path().join("server.toml"), "[update]\ncheck = false\n").unwrap();
1071        let path = tmp.path().join("config.toml");
1072        std::fs::write(&path, "[anthropic]\napi_key = \"x\"\n").unwrap();
1073        std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o600)).unwrap();
1074        migrate(tmp.path()).unwrap();
1075        let mode = std::fs::metadata(&path).unwrap().permissions().mode();
1076        assert_eq!(mode & 0o777, 0o600);
1077    }
1078
1079    #[test]
1080    fn the_apps_own_tables_are_left_alone() {
1081        let tmp = tempfile::tempdir().unwrap();
1082        let ctx = context(tmp.path());
1083        std::fs::write(
1084            ctx.config_dir().join("config.toml"),
1085            "sync_interval_minutes = 5\n\n[anthropic]\napi_key = \"x\"\n\n\
1086             [workspace]\ndefault = \"a\"\n\n[sync]\nwhatever = true\n\n\
1087             [retrieve]\nk = 1\n\n[cache]\ndir = \"/c\"\n",
1088        )
1089        .unwrap();
1090        let settings = Settings::load(&ctx, Arc::new(())).unwrap();
1091        assert_eq!(settings.get_as::<bool>("update.check"), Some(true));
1092    }
1093
1094    #[test]
1095    fn a_framework_write_keeps_the_apps_own_tables_byte_for_byte() {
1096        let tmp = tempfile::tempdir().unwrap();
1097        let ctx = context(tmp.path());
1098        let path = ctx.config_dir().join("config.toml");
1099        let before = "# sapphire-agent\nsync_interval_minutes = 5 # minutes\n\n\
1100                      [anthropic]\n# the key\napi_key = \"x\"\n\n\
1101                      [http]\n# where\nlisten = \"127.0.0.1:1\"\n\n\
1102                      [matrix]\nhomeserver = \"https://m\" # mine\n";
1103        std::fs::write(&path, before).unwrap();
1104        let settings = Settings::load(&ctx, Arc::new(())).unwrap();
1105        apply(
1106            settings.registry(),
1107            None,
1108            vec![set("http.listen", Value::String("127.0.0.1:2".into()))],
1109        )
1110        .unwrap();
1111        assert_eq!(
1112            std::fs::read_to_string(&path).unwrap(),
1113            before.replace("127.0.0.1:1", "127.0.0.1:2")
1114        );
1115    }
1116
1117    #[test]
1118    fn an_unknown_key_under_http_or_update_is_still_an_error() {
1119        for text in ["[http]\nlisn = 1\n", "[update]\nchekc = true\n"] {
1120            let tmp = tempfile::tempdir().unwrap();
1121            let ctx = context(tmp.path());
1122            std::fs::write(ctx.config_dir().join("config.toml"), text).unwrap();
1123            assert!(Settings::load(&ctx, Arc::new(())).is_err(), "{text}");
1124        }
1125    }
1126
1127    #[test]
1128    fn a_missing_server_toml_migrates_nothing() {
1129        let tmp = tempfile::tempdir().unwrap();
1130        migrate(tmp.path()).unwrap();
1131        assert!(!tmp.path().join("config.toml").exists());
1132    }
1133
1134    #[test]
1135    fn the_old_mcp_table_still_says_where_it_went() {
1136        let tmp = tempfile::tempdir().unwrap();
1137        let ctx = context(tmp.path());
1138        std::fs::write(ctx.config_dir().join("server.toml"), "[mcp]\nhttp = true\n").unwrap();
1139        let err = Settings::load(&ctx, Arc::new(()))
1140            .err()
1141            .unwrap()
1142            .to_string();
1143        assert!(
1144            err.contains("[mcp] http moved to [http.mcp] enabled"),
1145            "{err}"
1146        );
1147        assert!(
1148            err.contains(&ctx.config_dir().join("config.toml").display().to_string()),
1149            "{err}"
1150        );
1151    }
1152
1153    #[test]
1154    fn server_config_comes_from_the_settings() {
1155        let tmp = tempfile::tempdir().unwrap();
1156        let ctx = context(tmp.path());
1157        std::fs::write(
1158            ctx.config_dir().join("config.toml"),
1159            "[http]\nlisten = \"127.0.0.1:9000\"\nallowed_hosts = [\"box.example\"]\n\n\
1160             [http.mcp]\nenabled = true\n\n[update]\ncheck = false\n",
1161        )
1162        .unwrap();
1163        let settings = Settings::load(&ctx, Arc::new(())).unwrap();
1164        let config = ServerConfig::from_settings(&settings).unwrap();
1165        assert_eq!(config.http.listen, Some("127.0.0.1:9000".parse().unwrap()));
1166        assert_eq!(config.http.allowed_hosts, vec!["box.example".to_owned()]);
1167        assert!(config.http.mcp.enabled);
1168        assert!(!config.http.metrics.enabled);
1169        assert!(!config.update.check);
1170    }
1171
1172    #[test]
1173    fn a_misspelt_framework_setting_is_an_error_not_a_default() {
1174        let tmp = tempfile::tempdir().unwrap();
1175        let ctx = context(tmp.path());
1176        std::fs::write(
1177            ctx.config_dir().join("config.toml"),
1178            "[http.mcp]\nenabeld = true\n",
1179        )
1180        .unwrap();
1181        let err = Settings::load(&ctx, Arc::new(()))
1182            .err()
1183            .unwrap()
1184            .to_string();
1185        assert!(err.contains("http.mcp.enabeld"), "{err}");
1186    }
1187
1188    #[test]
1189    fn a_framework_value_of_the_wrong_kind_is_an_error() {
1190        let tmp = tempfile::tempdir().unwrap();
1191        let ctx = context(tmp.path());
1192        std::fs::write(
1193            ctx.config_dir().join("config.toml"),
1194            "[http]\nlisten = \"nowhere\"\n",
1195        )
1196        .unwrap();
1197        let err = Settings::load(&ctx, Arc::new(()))
1198            .err()
1199            .unwrap()
1200            .to_string();
1201        assert!(err.contains("http.listen"), "{err}");
1202    }
1203
1204    #[test]
1205    fn an_app_key_outside_its_name_is_refused() {
1206        let tmp = tempfile::tempdir().unwrap();
1207        let ctx = context(tmp.path());
1208        let files = SettingsFiles::for_app(&ctx).unwrap();
1209        let def = app_def("other.x", Kind::Bool, vec![Scope::Device], Apply::Live);
1210        let err = registry(&ctx, &files, one(def)).err().unwrap();
1211        assert!(
1212            matches!(&err, sapphire_framework_settings::Error::InvalidDef { key, .. } if key == "other.x"),
1213            "{err}"
1214        );
1215    }
1216
1217    #[test]
1218    fn an_app_key_in_the_workgroup_is_refused() {
1219        let tmp = tempfile::tempdir().unwrap();
1220        let ctx = context(tmp.path());
1221        let files = SettingsFiles::for_app(&ctx).unwrap();
1222        for scopes in [
1223            vec![Scope::Workgroup],
1224            vec![Scope::Workspace, Scope::Workgroup],
1225        ] {
1226            let def = app_def("settingstest.x", Kind::Bool, scopes, Apply::Live);
1227            let err = registry(&ctx, &files, one(def)).err().unwrap();
1228            assert!(
1229                matches!(&err, sapphire_framework_settings::Error::InvalidDef { key, .. } if key == "settingstest.x"),
1230                "{err}"
1231            );
1232        }
1233    }
1234
1235    #[test]
1236    fn an_app_key_named_http_is_refused() {
1237        let tmp = tempfile::tempdir().unwrap();
1238        let ctx = context(tmp.path());
1239        let files = SettingsFiles::for_app(&ctx).unwrap();
1240        let def = app_def("http.port", Kind::Bool, vec![Scope::Device], Apply::Live);
1241        assert!(registry(&ctx, &files, one(def)).is_err());
1242    }
1243
1244    #[test]
1245    fn an_app_key_under_a_declared_name_is_taken() {
1246        let tmp = tempfile::tempdir().unwrap();
1247        let ctx = context(tmp.path());
1248        let files = SettingsFiles::for_app(&ctx).unwrap();
1249        let defs = vec![
1250            app_def(
1251                "anthropic.model",
1252                Kind::String { non_empty: true },
1253                vec![Scope::Device],
1254                Apply::Live,
1255            ),
1256            app_def(
1257                "day_boundary_hour",
1258                Kind::Int { min: 0, max: 23 },
1259                vec![Scope::Device],
1260                Apply::Live,
1261            ),
1262            app_def(
1263                "settingstest.x",
1264                Kind::Bool,
1265                vec![Scope::Device],
1266                Apply::Live,
1267            ),
1268        ];
1269        let app = Arc::new(Named(&["anthropic", "day_boundary_hour"], defs));
1270        assert!(registry(&ctx, &files, app).is_ok());
1271    }
1272
1273    #[test]
1274    fn an_app_key_outside_its_names_is_refused() {
1275        let tmp = tempfile::tempdir().unwrap();
1276        let ctx = context(tmp.path());
1277        let files = SettingsFiles::for_app(&ctx).unwrap();
1278        let def = app_def("openai.model", Kind::Bool, vec![Scope::Device], Apply::Live);
1279        let app = Arc::new(Named(&["anthropic"], vec![def]));
1280        let err = registry(&ctx, &files, app).err().unwrap().to_string();
1281        assert!(err.contains("openai.model"), "{err}");
1282    }
1283
1284    #[test]
1285    fn a_declared_name_the_framework_keeps_is_refused() {
1286        let tmp = tempfile::tempdir().unwrap();
1287        let ctx = context(tmp.path());
1288        let files = SettingsFiles::for_app(&ctx).unwrap();
1289        for name in ["http", "sync", "workspace", "embed", "net", "", "a.b"] {
1290            let names: &'static [&'static str] = Box::leak(Box::new([name]));
1291            let app = Arc::new(Named(names, Vec::new()));
1292            assert!(registry(&ctx, &files, app).is_err(), "{name:?}");
1293        }
1294    }
1295
1296    #[test]
1297    fn a_top_level_table_and_key_are_written_and_read() {
1298        let tmp = tempfile::tempdir().unwrap();
1299        let ctx = context(tmp.path());
1300        let defs = vec![
1301            app_def(
1302                "anthropic.model",
1303                Kind::String { non_empty: true },
1304                vec![Scope::Device],
1305                Apply::Live,
1306            ),
1307            app_def(
1308                "day_boundary_hour",
1309                Kind::Int { min: 0, max: 23 },
1310                vec![Scope::Device],
1311                Apply::Live,
1312            ),
1313        ];
1314        let app = Arc::new(Named(&["anthropic", "day_boundary_hour"], defs));
1315        let settings = Settings::load(&ctx, app).unwrap();
1316        apply(
1317            settings.registry(),
1318            None,
1319            vec![
1320                set("anthropic.model", Value::String("m".into())),
1321                set("day_boundary_hour", Value::Int(4)),
1322            ],
1323        )
1324        .unwrap();
1325        settings.refresh().unwrap();
1326        assert_eq!(
1327            settings.get("anthropic.model"),
1328            Some(Value::String("m".into()))
1329        );
1330        assert_eq!(settings.get("day_boundary_hour"), Some(Value::Int(4)));
1331        let text = std::fs::read_to_string(tmp.path().join("config").join("config.toml")).unwrap();
1332        assert!(text.contains("[anthropic]"), "{text}");
1333        assert!(text.contains("day_boundary_hour = 4"), "{text}");
1334    }
1335
1336    /// An application with HTTP endpoints and no other settings.
1337    struct Endpoints(Vec<HttpEndpoint>);
1338
1339    impl AppSettings for Endpoints {
1340        fn defs(&self) -> Vec<SettingDef> {
1341            Vec::new()
1342        }
1343
1344        fn http_endpoints(&self) -> Vec<HttpEndpoint> {
1345            self.0.clone()
1346        }
1347    }
1348
1349    fn endpoints(names: &[&str]) -> Arc<dyn AppSettings> {
1350        Arc::new(Endpoints(
1351            names
1352                .iter()
1353                .map(|n| HttpEndpoint::new(*n, format!("Serve {n}")))
1354                .collect(),
1355        ))
1356    }
1357
1358    #[test]
1359    fn an_endpoint_gets_a_switch_among_the_framework_settings() {
1360        let tmp = tempfile::tempdir().unwrap();
1361        let ctx = context(tmp.path());
1362        let files = SettingsFiles::for_app(&ctx).unwrap();
1363        let reg = registry(&ctx, &files, endpoints(&["acp"])).unwrap();
1364        let schema = reg.schema();
1365        let keys: Vec<_> = schema.iter().map(|d| d.key.as_str()).collect();
1366        assert_eq!(
1367            keys,
1368            vec![
1369                "http.listen",
1370                "http.allowed_hosts",
1371                "http.mcp.enabled",
1372                "http.metrics.enabled",
1373                "http.acp.enabled",
1374                "update.check",
1375            ]
1376        );
1377        let (def, _) = reg.def("http.acp.enabled").unwrap();
1378        assert_eq!(def.default, Some(Value::Bool(false)));
1379        assert_eq!(def.doc, "Serve acp");
1380        assert_eq!(def.section, "Server");
1381    }
1382
1383    #[test]
1384    fn an_endpoint_named_badly_or_twice_is_refused() {
1385        let tmp = tempfile::tempdir().unwrap();
1386        let ctx = context(tmp.path());
1387        let files = SettingsFiles::for_app(&ctx).unwrap();
1388        for names in [
1389            &["mcp"][..],
1390            &["listen"],
1391            &["allowed_hosts"],
1392            &["metrics"],
1393            &[""],
1394            &["a.b"],
1395            &["A"],
1396            &["a/b"],
1397            &["acp", "acp"],
1398        ] {
1399            assert!(
1400                registry(&ctx, &files, endpoints(names)).is_err(),
1401                "{names:?}"
1402            );
1403        }
1404    }
1405
1406    #[test]
1407    fn the_device_file_takes_a_declared_endpoints_switch_only() {
1408        let tmp = tempfile::tempdir().unwrap();
1409        let ctx = context(tmp.path());
1410        let file = tmp.path().join("config").join("config.toml");
1411        std::fs::write(&file, "[http.acp]\nenabled = true\n").unwrap();
1412        let settings = Settings::load(&ctx, endpoints(&["acp"])).unwrap();
1413        let config = ServerConfig::from_settings(&settings).unwrap();
1414        assert_eq!(config.http.endpoints, ["acp".to_owned()].into());
1415
1416        let err = Settings::load(&ctx, endpoints(&[]))
1417            .unwrap_err()
1418            .to_string();
1419        assert!(err.contains("http.acp.enabled"), "{err}");
1420    }
1421
1422    #[test]
1423    fn every_def_is_the_app_servers() {
1424        let tmp = tempfile::tempdir().unwrap();
1425        let ctx = context(tmp.path());
1426        let files = SettingsFiles::for_app(&ctx).unwrap();
1427        let def = app_def(
1428            "settingstest.x",
1429            Kind::Bool,
1430            vec![Scope::Device],
1431            Apply::Live,
1432        );
1433        let reg = registry(&ctx, &files, one(def)).unwrap();
1434        let schema = reg.schema();
1435        assert_eq!(
1436            schema.iter().map(|d| d.key.as_str()).collect::<Vec<_>>(),
1437            vec![
1438                "http.listen",
1439                "http.allowed_hosts",
1440                "http.mcp.enabled",
1441                "http.metrics.enabled",
1442                "update.check",
1443                "settingstest.x",
1444            ]
1445        );
1446        assert!(schema.iter().all(|d| d.process == Process::App));
1447    }
1448
1449    #[test]
1450    fn the_workspace_scope_follows_the_selection() {
1451        let tmp = tempfile::tempdir().unwrap();
1452        let ctx = context(tmp.path());
1453        let def = app_def(
1454            "settingstest.note",
1455            Kind::String { non_empty: false },
1456            vec![Scope::Workspace],
1457            Apply::Live,
1458        );
1459        let settings = Settings::load(&ctx, one(def)).unwrap();
1460        let (a, b) = (tmp.path().join("a"), tmp.path().join("b"));
1461        let file = |root: &Path| root.join(format!(".{APP}")).join("config.toml");
1462
1463        select(&ctx, &a);
1464        apply(
1465            settings.registry(),
1466            None,
1467            vec![set("settingstest.note", Value::String("first".into()))],
1468        )
1469        .unwrap();
1470        select(&ctx, &b);
1471        apply(
1472            settings.registry(),
1473            None,
1474            vec![set("settingstest.note", Value::String("second".into()))],
1475        )
1476        .unwrap();
1477
1478        let a_text = std::fs::read_to_string(file(&a)).unwrap();
1479        let b_text = std::fs::read_to_string(file(&b)).unwrap();
1480        assert!(
1481            a_text.contains("first") && !a_text.contains("second"),
1482            "{a_text}"
1483        );
1484        assert!(b_text.contains("second"), "{b_text}");
1485    }
1486
1487    #[test]
1488    fn no_selection_means_no_workspace_scope() {
1489        let tmp = tempfile::tempdir().unwrap();
1490        let ctx = context(tmp.path());
1491        let files = SettingsFiles::for_app(&ctx).unwrap();
1492        let err = files.workspace().unwrap_err().to_string();
1493        assert_eq!(err, "no workspace is selected");
1494
1495        let def = app_def(
1496            "settingstest.note",
1497            Kind::String { non_empty: false },
1498            vec![Scope::Workspace],
1499            Apply::Live,
1500        );
1501        let settings = Settings::load(&ctx, one(def)).unwrap();
1502        // Reading falls back to the default; writing says why it cannot.
1503        assert_eq!(settings.get("settingstest.note"), None);
1504        let err = apply(
1505            settings.registry(),
1506            None,
1507            vec![set("settingstest.note", Value::String("x".into()))],
1508        )
1509        .unwrap_err()
1510        .to_string();
1511        assert!(err.contains("no workspace is selected"), "{err}");
1512    }
1513
1514    #[test]
1515    fn a_live_change_fires_changed_and_a_restart_change_does_not() {
1516        let tmp = tempfile::tempdir().unwrap();
1517        let ctx = context(tmp.path());
1518        let app = TestApp(vec![
1519            app_def(
1520                "settingstest.live",
1521                Kind::Int { min: 0, max: 10 },
1522                vec![Scope::Device],
1523                Apply::Live,
1524            ),
1525            app_def(
1526                "settingstest.slow",
1527                Kind::Int { min: 0, max: 10 },
1528                vec![Scope::Device],
1529                Apply::Restart,
1530            ),
1531        ]);
1532        let settings = Settings::load(&ctx, Arc::new(app)).unwrap();
1533        let mut changed = settings.changed();
1534
1535        apply(
1536            settings.registry(),
1537            None,
1538            vec![set("settingstest.slow", Value::Int(3))],
1539        )
1540        .unwrap();
1541        settings.refresh().unwrap();
1542        assert!(!changed.has_changed().unwrap());
1543        assert_eq!(
1544            settings.get("settingstest.slow"),
1545            None,
1546            "kept until restart"
1547        );
1548
1549        apply(
1550            settings.registry(),
1551            None,
1552            vec![set("settingstest.live", Value::Int(4))],
1553        )
1554        .unwrap();
1555        settings.refresh().unwrap();
1556        assert!(changed.has_changed().unwrap());
1557        changed.mark_unchanged();
1558        assert_eq!(settings.get_as::<i64>("settingstest.live"), Some(4));
1559        // A clone is the same handle.
1560        assert_eq!(
1561            settings.clone().get("settingstest.live"),
1562            Some(Value::Int(4))
1563        );
1564
1565        // Nothing changed, nothing announced.
1566        settings.refresh().unwrap();
1567        assert!(!changed.has_changed().unwrap());
1568    }
1569
1570    /// `settingstest.a` needs `settingstest.b`: a cross-key rule over the device file.
1571    struct Paired;
1572
1573    impl AppSettings for Paired {
1574        fn defs(&self) -> Vec<SettingDef> {
1575            ["settingstest.a", "settingstest.b"]
1576                .map(|key| app_def(key, Kind::Bool, vec![Scope::Device], Apply::Live))
1577                .into()
1578        }
1579
1580        fn validate(
1581            &self,
1582            files: &AppFiles,
1583            staged: &Staged,
1584        ) -> std::result::Result<(), Vec<FieldError>> {
1585            assert_eq!(files.workspace(), None, "no workspace is selected");
1586            let text = staged.read(files.device()).unwrap().unwrap_or_default();
1587            let table: toml::Table = text.parse().unwrap();
1588            let has = |k: &str| table.get("settingstest").and_then(|t| t.get(k)).is_some();
1589            if has("a") && !has("b") {
1590                return Err(vec![FieldError {
1591                    key: Some("settingstest.a".into()),
1592                    file: Some(files.device().to_path_buf()),
1593                    message: "needs settingstest.b".into(),
1594                }]);
1595            }
1596            Ok(())
1597        }
1598    }
1599
1600    #[test]
1601    fn an_apps_validate_sees_the_files_whole() {
1602        let tmp = tempfile::tempdir().unwrap();
1603        let ctx = context(tmp.path());
1604        let settings = Settings::load(&ctx, Arc::new(Paired)).unwrap();
1605        let reg = settings.registry();
1606
1607        let err = apply(reg, None, vec![set("settingstest.a", Value::Bool(true))])
1608            .unwrap_err()
1609            .to_string();
1610        assert!(err.contains("needs settingstest.b"), "{err}");
1611        assert!(!ctx.config_dir().join("config.toml").exists());
1612
1613        apply(reg, None, vec![set("settingstest.b", Value::Bool(true))]).unwrap();
1614        // `b` is read from the file on disk, untouched by this batch.
1615        apply(reg, None, vec![set("settingstest.a", Value::Bool(true))]).unwrap();
1616        let err = apply(
1617            reg,
1618            None,
1619            vec![Op::Unset {
1620                key: "settingstest.b".into(),
1621            }],
1622        )
1623        .unwrap_err()
1624        .to_string();
1625        assert!(err.contains("needs settingstest.b"), "{err}");
1626    }
1627
1628    #[test]
1629    fn an_unparsable_config_names_the_file() {
1630        let tmp = tempfile::tempdir().unwrap();
1631        let ctx = context(tmp.path());
1632        let path = ctx.config_dir().join("config.toml");
1633        std::fs::write(&path, "this is = = not toml").unwrap();
1634        let err = Settings::load(&ctx, Arc::new(()))
1635            .err()
1636            .unwrap()
1637            .to_string();
1638        assert!(err.contains(&path.display().to_string()), "{err}");
1639    }
1640
1641    #[test]
1642    fn an_unparsable_config_is_never_quoted() {
1643        let tmp = tempfile::tempdir().unwrap();
1644        let ctx = context(tmp.path());
1645        std::fs::write(
1646            ctx.config_dir().join("config.toml"),
1647            "[anthropic]\napi_key = \"hunter2\" x\n",
1648        )
1649        .unwrap();
1650        let err = Settings::load(&ctx, Arc::new(()))
1651            .err()
1652            .unwrap()
1653            .to_string();
1654        assert!(err.contains("line 2"), "{err}");
1655        assert!(!err.contains("hunter2"), "{err}");
1656        // Merging `server.toml` into it says no more.
1657        std::fs::write(
1658            ctx.config_dir().join("server.toml"),
1659            "[update]\ncheck = false\n",
1660        )
1661        .unwrap();
1662        let err = migrate(ctx.config_dir()).unwrap_err().to_string();
1663        assert!(err.contains("line 2") && !err.contains("hunter2"), "{err}");
1664    }
1665
1666    #[test]
1667    fn a_secret_is_never_read_back_and_lives_under_secrets() {
1668        let tmp = tempfile::tempdir().unwrap();
1669        let ctx = context(tmp.path());
1670        let def = app_def(
1671            "settingstest.token",
1672            Kind::Secret,
1673            vec![Scope::Device],
1674            Apply::Live,
1675        );
1676        let settings = Settings::load(&ctx, one(def)).unwrap();
1677        apply(
1678            settings.registry(),
1679            None,
1680            vec![set("settingstest.token", Value::String("hunter2".into()))],
1681        )
1682        .unwrap();
1683        let path = ctx.config_dir().join("secrets").join("settingstest.token");
1684        assert_eq!(std::fs::read_to_string(&path).unwrap(), "hunter2");
1685        #[cfg(unix)]
1686        {
1687            use std::os::unix::fs::PermissionsExt;
1688            let mode = std::fs::metadata(&path).unwrap().permissions().mode();
1689            assert_eq!(mode & 0o777, 0o600);
1690        }
1691        settings.refresh().unwrap();
1692        assert_eq!(settings.get("settingstest.token"), None);
1693    }
1694
1695    #[test]
1696    fn values_convert_to_their_rust_types() {
1697        let tmp = tempfile::tempdir().unwrap();
1698        let ctx = context(tmp.path());
1699        std::fs::write(
1700            ctx.config_dir().join("config.toml"),
1701            "[http]\nallowed_hosts = [\"a\", \"b\"]\n",
1702        )
1703        .unwrap();
1704        let settings = Settings::load(&ctx, Arc::new(())).unwrap();
1705        assert_eq!(settings.get_as::<bool>("update.check"), Some(true));
1706        assert_eq!(
1707            settings.get_as::<Vec<String>>("http.allowed_hosts"),
1708            Some(vec!["a".to_owned(), "b".to_owned()])
1709        );
1710        assert_eq!(
1711            settings.get_as::<String>("update.check"),
1712            None,
1713            "wrong type"
1714        );
1715        assert_eq!(settings.get_as::<i64>("http.listen"), None, "unset");
1716        assert_eq!(settings.get("no.such.key"), None);
1717    }
1718}