Skip to main content

sapphire_framework_bridge_api/
settings.rs

1//! Schema and value types of the settings registry.
2//!
3//! A setting is addressed by its key (its TOML path in a scope's `config.toml`) and
4//! described by a [`SettingDef`]: its [`Kind`], the [`Scope`]s it may live in, and
5//! whether a change applies live or needs a restart. This module is types only, so the
6//! bridge, the app servers and the CLIs can share it without sharing a store.
7
8use std::fmt;
9use std::net::SocketAddr;
10use std::str::FromStr;
11
12use serde::{Deserialize, Serialize};
13
14/// Where a setting is stored. Ordered as declared: device, workgroup, workspace.
15#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
16#[serde(rename_all = "snake_case")]
17pub enum Scope {
18    /// This machine only.
19    Device,
20    /// Shared by every member of a workgroup.
21    Workgroup,
22    /// One workspace.
23    Workspace,
24}
25
26impl fmt::Display for Scope {
27    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
28        f.write_str(match self {
29            Scope::Device => "device",
30            Scope::Workgroup => "workgroup",
31            Scope::Workspace => "workspace",
32        })
33    }
34}
35
36impl FromStr for Scope {
37    type Err = String;
38
39    fn from_str(s: &str) -> Result<Self, String> {
40        match s {
41            "device" => Ok(Scope::Device),
42            "workgroup" => Ok(Scope::Workgroup),
43            "workspace" => Ok(Scope::Workspace),
44            other => Err(format!(
45                "unknown scope `{other}` (expected device, workgroup or workspace)"
46            )),
47        }
48    }
49}
50
51/// The type of a setting's value, and so what it accepts.
52#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
53#[serde(rename_all = "snake_case")]
54pub enum Kind {
55    /// `true`/`false`, also written `on`/`off`.
56    Bool,
57    /// An integer within `min..=max`.
58    Int {
59        /// Smallest accepted value.
60        min: i64,
61        /// Largest accepted value.
62        max: i64,
63    },
64    /// One of a fixed set of strings.
65    Enum {
66        /// The accepted strings.
67        choices: Vec<String>,
68    },
69    /// Free text.
70    String {
71        /// Reject the empty string.
72        non_empty: bool,
73    },
74    /// An `http` or `https` URL.
75    Url,
76    /// A filesystem path.
77    Path,
78    /// A `host:port` socket address.
79    SocketAddr,
80    /// A list of items of one kind.
81    List {
82        /// The kind of every item.
83        item: Box<Kind>,
84    },
85    /// A credential: device-scope, never read back, never taken from text on a command line.
86    Secret,
87}
88
89/// When a changed setting takes effect.
90#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
91#[serde(rename_all = "snake_case")]
92pub enum Apply {
93    /// Picked up by the running process.
94    Live,
95    /// Needs a restart.
96    Restart,
97}
98
99/// A typed setting value.
100///
101/// Untagged on the wire, so a JSON `5` is `Int` and `[1,2]` is a list of `Int`.
102#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
103#[serde(untagged)]
104pub enum Value {
105    /// A boolean.
106    Bool(bool),
107    /// An integer.
108    Int(i64),
109    /// A string (also URLs, paths, addresses, enum choices).
110    String(String),
111    /// A list.
112    List(Vec<Value>),
113}
114
115impl fmt::Display for Value {
116    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
117        match self {
118            Value::Bool(b) => write!(f, "{b}"),
119            Value::Int(i) => write!(f, "{i}"),
120            Value::String(s) => f.write_str(s),
121            Value::List(items) => {
122                for (i, item) in items.iter().enumerate() {
123                    if i > 0 {
124                        f.write_str(",")?;
125                    }
126                    write!(f, "{item}")?;
127                }
128                Ok(())
129            }
130        }
131    }
132}
133
134/// Which process owns a setting: the one that stores, validates and applies it.
135#[derive(
136    Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize,
137)]
138#[serde(rename_all = "snake_case")]
139pub enum Process {
140    /// The bridge.
141    #[default]
142    Bridge,
143    /// The app server.
144    App,
145}
146
147/// The top-level names the app server's framework keeps for itself, whether or not it
148/// defines keys there: an application declares its own top-level names beside these, never
149/// one of them. Adding a name here is a breaking change.
150pub const SERVER_NAMES: [&str; 5] = ["http", "update", "sync", "retrieve", "workspace"];
151
152/// The registry's description of one setting.
153#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
154pub struct SettingDef {
155    /// The TOML path, e.g. `embed.remote.endpoint`.
156    pub key: String,
157    /// What the value must look like.
158    pub kind: Kind,
159    /// The scopes it may be set in; the first is its home.
160    pub scopes: Vec<Scope>,
161    /// Whether a device may override a value set in a wider scope.
162    pub overridable: bool,
163    /// When a change takes effect.
164    pub apply: Apply,
165    /// The value in effect when no scope sets it.
166    pub default: Option<Value>,
167    /// The heading it is listed under.
168    pub section: String,
169    /// One-line help text.
170    pub doc: String,
171    /// The process that owns it; an older peer's definitions read as the bridge's.
172    #[serde(default)]
173    pub process: Process,
174}
175
176impl SettingDef {
177    /// The scope the setting normally lives in.
178    pub fn home(&self) -> Scope {
179        self.scopes[0]
180    }
181
182    /// Whether the setting may be set in `scope`: its home, any other listed scope, or
183    /// `Device` when it is overridable.
184    pub fn allows(&self, scope: Scope) -> bool {
185        scope == self.home()
186            || (scope == Scope::Device && self.overridable)
187            || self.scopes.contains(&scope)
188    }
189}
190
191/// Whether a secret has a value; the value itself is never exposed.
192#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
193#[serde(rename_all = "snake_case")]
194pub enum SecretState {
195    /// A value is stored.
196    Set,
197    /// Nothing is stored.
198    Unset,
199}
200
201/// What `get`/`list` report for a key.
202#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
203#[serde(rename_all = "snake_case")]
204pub enum EntryValue {
205    /// The effective value.
206    Value(Value),
207    /// A secret: only whether it is set.
208    Secret(SecretState),
209    /// No value and no default.
210    Unset,
211}
212
213/// Where the effective value came from.
214#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
215#[serde(rename_all = "snake_case")]
216pub enum Origin {
217    /// Set in this scope.
218    Scope(Scope),
219    /// The registry default.
220    Default,
221}
222
223/// One setting as reported to a client.
224#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
225pub struct Entry {
226    /// The setting's key.
227    pub key: String,
228    /// Its effective value.
229    pub value: EntryValue,
230    /// Where that value came from.
231    pub origin: Origin,
232    /// A restart-only change has been written but is not yet in effect.
233    pub pending_restart: bool,
234    /// Extra remark for the user (e.g. an unknown key kept in the file).
235    pub note: Option<String>,
236}
237
238impl Kind {
239    /// Parse user text into a value of this kind, then [`check`](Kind::check) it.
240    pub fn parse(&self, text: &str) -> Result<Value, String> {
241        let value = match self {
242            Kind::Bool => match text {
243                "true" | "on" => Value::Bool(true),
244                "false" | "off" => Value::Bool(false),
245                _ => return Err("not a boolean (expected one of true, false, on, off)".into()),
246            },
247            Kind::Int { .. } => Value::Int(
248                text.trim()
249                    .parse::<i64>()
250                    .map_err(|_| "not an integer".to_string())?,
251            ),
252            Kind::Enum { .. } | Kind::String { .. } | Kind::Url | Kind::Path | Kind::SocketAddr => {
253                Value::String(text.to_string())
254            }
255            Kind::List { item } => Value::List(
256                split_list(text)
257                    .iter()
258                    .map(|part| item.parse(part))
259                    .collect::<Result<_, _>>()?,
260            ),
261            Kind::Secret => {
262                return Err(
263                    "a secret cannot be given as text; read it with --stdin or a prompt".into(),
264                );
265            }
266        };
267        self.check(&value)?;
268        Ok(value)
269    }
270
271    /// Check an already-typed value against this kind.
272    pub fn check(&self, value: &Value) -> Result<(), String> {
273        match (self, value) {
274            (Kind::Bool, Value::Bool(_)) => Ok(()),
275            (Kind::Int { min, max }, Value::Int(i)) => {
276                if (*min..=*max).contains(i) {
277                    Ok(())
278                } else {
279                    Err(format!("out of range (expected {min}..={max})"))
280                }
281            }
282            (Kind::Enum { choices }, Value::String(s)) => {
283                if choices.contains(s) {
284                    Ok(())
285                } else {
286                    Err(format!("not one of the choices ({})", choices.join(", ")))
287                }
288            }
289            (Kind::String { non_empty }, Value::String(s)) => {
290                if *non_empty && s.is_empty() {
291                    Err("must not be empty".into())
292                } else {
293                    Ok(())
294                }
295            }
296            (Kind::Url, Value::String(s)) => {
297                let rest = s
298                    .strip_prefix("http://")
299                    .or_else(|| s.strip_prefix("https://"));
300                match rest {
301                    Some(rest) if !rest.is_empty() => Ok(()),
302                    _ => Err("not an http or https URL".into()),
303                }
304            }
305            (Kind::Path, Value::String(s)) => {
306                if std::path::Path::new(s).as_os_str().is_empty() {
307                    Err("path must not be empty".into())
308                } else {
309                    Ok(())
310                }
311            }
312            (Kind::SocketAddr, Value::String(s)) => s
313                .parse::<SocketAddr>()
314                .map(|_| ())
315                .map_err(|_| "not a host:port socket address".to_string()),
316            (Kind::List { item }, Value::List(items)) => {
317                items.iter().try_for_each(|v| item.check(v))
318            }
319            (Kind::Secret, Value::String(_)) => Ok(()),
320            // A secret's value is never shown, not even a wrong one.
321            (Kind::Secret, _) => Err("a secret must be a string".into()),
322            // Error text never carries the value: it reaches logs, the GUI and CLI output.
323            (kind, _) => Err(format!("has the wrong type (expected {})", kind.name())),
324        }
325    }
326
327    /// A short name for this kind, for error text.
328    fn name(&self) -> &'static str {
329        match self {
330            Kind::Bool => "bool",
331            Kind::Int { .. } => "integer",
332            Kind::Enum { .. } => "choice",
333            Kind::String { .. } => "string",
334            Kind::Url => "URL",
335            Kind::Path => "path",
336            Kind::SocketAddr => "socket address",
337            Kind::List { .. } => "list",
338            Kind::Secret => "secret",
339        }
340    }
341}
342
343/// Split list text: a comma-separated string or a TOML-style `["a", "b"]` array.
344fn split_list(text: &str) -> Vec<String> {
345    let text = text.trim();
346    let text = text
347        .strip_prefix('[')
348        .and_then(|t| t.strip_suffix(']'))
349        .unwrap_or(text);
350    if text.trim().is_empty() {
351        return Vec::new();
352    }
353    text.split(',')
354        .map(|part| {
355            let part = part.trim();
356            part.strip_prefix('"')
357                .and_then(|p| p.strip_suffix('"'))
358                .unwrap_or(part)
359                .to_string()
360        })
361        .collect()
362}
363
364/// The keys of the GUI's settings: stored by the bridge, read by the apps' windows.
365pub mod gui {
366    /// Light, dark, or the system's.
367    pub const THEME_PREFERENCE: &str = "gui.theme.preference";
368    /// How far apart text and background are.
369    pub const THEME_CONTRAST: &str = "gui.theme.contrast";
370    /// The accent: one of [`ACCENT_CHOICES`].
371    pub const THEME_ACCENT: &str = "gui.theme.accent";
372    /// A custom accent's hue, in whole degrees.
373    pub const THEME_ACCENT_HUE: &str = "gui.theme.accent_hue";
374    /// A custom accent's chroma, in thousandths.
375    pub const THEME_ACCENT_CHROMA: &str = "gui.theme.accent_chroma";
376    /// The accent's values: `default`, one of the theme's colours by name, or `custom`, whose
377    /// hue and chroma are [`THEME_ACCENT_HUE`] and [`THEME_ACCENT_CHROMA`].
378    pub const ACCENT_CHOICES: [&str; 10] = [
379        "default", "neutral", "red", "orange", "yellow", "green", "cyan", "blue", "purple",
380        "custom",
381    ];
382    /// The language of the apps' windows: `system`, or a language tag such as `ja` or
383    /// `en-US`.
384    pub const LOCALE: &str = "gui.locale";
385    /// Every theme key.
386    pub const THEME_KEYS: [&str; 5] = [
387        THEME_PREFERENCE,
388        THEME_CONTRAST,
389        THEME_ACCENT,
390        THEME_ACCENT_HUE,
391        THEME_ACCENT_CHROMA,
392    ];
393}
394
395#[cfg(test)]
396mod tests {
397    use super::*;
398
399    #[test]
400    fn a_wrong_typed_secret_is_not_echoed() {
401        let value = Value::List(vec![Value::String("hunter2-sekrit".into())]);
402        let err = Kind::Secret.check(&value).unwrap_err();
403        assert!(!err.contains("hunter2"), "{err}");
404        let err = Kind::Secret.check(&Value::Int(424242)).unwrap_err();
405        assert!(!err.contains("424242"), "{err}");
406    }
407
408    #[test]
409    fn a_rejected_value_is_not_echoed() {
410        let list = Kind::List {
411            item: Box::new(Kind::Url),
412        };
413        let parsed = [
414            (Kind::Bool, "MARKER-42"),
415            (Kind::Int { min: 1, max: 10 }, "MARKER-42"),
416            (Kind::Int { min: 1, max: 10 }, "4242424"),
417            (
418                Kind::Enum {
419                    choices: vec!["a".into()],
420                },
421                "MARKER-42",
422            ),
423            (Kind::Url, "MARKER-42"),
424            (Kind::SocketAddr, "MARKER-42"),
425            (list, "MARKER-42"),
426        ];
427        for (kind, text) in parsed {
428            let err = kind.parse(text).unwrap_err();
429            assert!(!err.contains(text), "{kind:?}: {err}");
430        }
431        let checked = [
432            (Kind::Int { min: 1, max: 10 }, Value::Int(4242424)),
433            (Kind::Bool, Value::String("MARKER-42".into())),
434            (
435                Kind::Int { min: 1, max: 10 },
436                Value::String("MARKER-42".into()),
437            ),
438            (
439                Kind::Enum {
440                    choices: vec!["a".into()],
441                },
442                Value::List(vec![Value::String("MARKER-42".into())]),
443            ),
444        ];
445        for (kind, value) in checked {
446            let err = kind.check(&value).unwrap_err();
447            assert!(!err.contains("MARKER-42"), "{kind:?}: {err}");
448            assert!(!err.contains("4242424"), "{kind:?}: {err}");
449            assert!(
450                !err.contains("choices"),
451                "names the kind, not its Debug: {err}"
452            );
453        }
454    }
455
456    fn def(key: &str, home: Scope) -> SettingDef {
457        SettingDef {
458            key: key.into(),
459            kind: Kind::Bool,
460            scopes: vec![home],
461            overridable: false,
462            apply: Apply::Live,
463            default: None,
464            section: "test".into(),
465            doc: "test".into(),
466            process: Process::Bridge,
467        }
468    }
469
470    #[test]
471    fn an_older_def_reads_as_the_bridges() {
472        let json = r#"{"key":"a.b","kind":"bool","scopes":["device"],"overridable":false,
473            "apply":"live","default":null,"section":"s","doc":"d"}"#;
474        let def: SettingDef = serde_json::from_str(json).unwrap();
475        assert_eq!(def.process, Process::Bridge);
476        assert_eq!(serde_json::to_value(Process::App).unwrap(), "app");
477    }
478
479    #[test]
480    fn bools_accept_on_off_true_false() {
481        for (t, v) in [
482            ("true", true),
483            ("on", true),
484            ("false", false),
485            ("off", false),
486        ] {
487            assert_eq!(Kind::Bool.parse(t).unwrap(), Value::Bool(v));
488        }
489        assert!(
490            Kind::Bool
491                .parse("yes")
492                .unwrap_err()
493                .contains("true, false, on, off")
494        );
495    }
496    #[test]
497    fn ints_name_their_range() {
498        let k = Kind::Int { min: 64, max: 2048 };
499        assert_eq!(k.parse("1024").unwrap(), Value::Int(1024));
500        assert!(k.parse("32").unwrap_err().contains("64..=2048"));
501    }
502    #[test]
503    fn enums_list_their_choices() {
504        let k = Kind::Enum {
505            choices: vec!["q8_0".into(), "f16".into()],
506        };
507        assert!(k.parse("q4").unwrap_err().contains("q8_0, f16"));
508    }
509    #[test]
510    fn urls_are_http_only() {
511        assert!(Kind::Url.parse("https://a.example").is_ok());
512        assert!(Kind::Url.parse("ftp://a.example").is_err());
513    }
514    #[test]
515    fn lists_take_commas_or_a_toml_array() {
516        let k = Kind::List {
517            item: Box::new(Kind::Url),
518        };
519        let want = Value::List(vec![
520            Value::String("https://a".into()),
521            Value::String("https://b".into()),
522        ]);
523        assert_eq!(k.parse("https://a,https://b").unwrap(), want);
524        assert_eq!(k.parse(r#"["https://a", "https://b"]"#).unwrap(), want);
525        assert_eq!(k.parse("").unwrap(), Value::List(vec![]));
526    }
527    #[test]
528    fn secrets_are_never_parsed_from_text() {
529        assert!(
530            Kind::Secret
531                .parse("sk-123")
532                .unwrap_err()
533                .contains("--stdin")
534        );
535    }
536    #[test]
537    fn device_is_allowed_only_when_overridable() {
538        let mut d = def("embed.remote.model", Scope::Workgroup);
539        assert!(!d.allows(Scope::Device));
540        d.overridable = true;
541        assert!(d.allows(Scope::Device));
542    }
543    #[test]
544    fn values_round_trip_through_json() {
545        let v = Value::List(vec![Value::Int(1), Value::Int(2)]);
546        let json = serde_json::to_string(&v).unwrap();
547        assert_eq!(json, "[1,2]");
548        assert_eq!(serde_json::from_str::<Value>(&json).unwrap(), v);
549        for v in [Value::Bool(true), Value::Int(-7), Value::String("x".into())] {
550            let back: Value = serde_json::from_str(&serde_json::to_string(&v).unwrap()).unwrap();
551            assert_eq!(back, v);
552        }
553    }
554    #[test]
555    fn scopes_display_and_parse() {
556        for s in [Scope::Device, Scope::Workgroup, Scope::Workspace] {
557            assert_eq!(s.to_string().parse::<Scope>().unwrap(), s);
558        }
559        assert_eq!(Scope::Device.to_string(), "device");
560        assert!("nope".parse::<Scope>().is_err());
561    }
562    #[test]
563    fn check_validates_typed_values() {
564        let k = Kind::Int { min: 1, max: 3 };
565        assert!(k.check(&Value::Int(2)).is_ok());
566        assert!(k.check(&Value::Int(9)).is_err());
567        assert!(k.check(&Value::Bool(true)).is_err());
568        assert!(
569            Kind::String { non_empty: true }
570                .check(&Value::String(String::new()))
571                .is_err()
572        );
573        assert!(Kind::SocketAddr.parse("127.0.0.1:80").is_ok());
574        assert!(Kind::SocketAddr.parse("nope").is_err());
575        assert!(Kind::Secret.check(&Value::String("x".into())).is_ok());
576    }
577    #[test]
578    fn the_crate_stays_free_of_framework_crates() {
579        let manifest = include_str!("../Cargo.toml");
580        let deps = manifest.split("[dependencies]").nth(1).unwrap();
581        assert!(!deps.contains("sapphire-framework-"));
582    }
583}