Skip to main content

sapphire_framework_server/command/
config.rs

1//! `<app> config` (#314): this application's settings and the bridge's, by key.
2//!
3//! With the app server running, every command goes to it over the app connection
4//! (`config.*`, which it answers merged with the bridge's), and a write reports which
5//! process awaits a restart; `--restart` restarts them, the bridge first. With no server
6//! running, the command reads and writes this application's files itself, with the same
7//! checks; the bridge's keys then need `sapphire-bridge config`.
8//!
9//! See `docs/superpowers/specs/2026-10-22-app-settings-design.md`, "`<app> config`".
10
11use std::sync::Arc;
12use std::time::Duration;
13
14use sapphire_backend::protocol as proto;
15use sapphire_bridge_client::BridgeClient;
16use sapphire_framework_settings::{Op, Process, Registry, Scope, SettingDef, apply, get, list};
17use sapphire_ipc::{ClientInfo, Endpoint};
18use sapphire_workspace::AppContext;
19
20use crate::error::{Error, Result};
21use crate::settings::AppSettings;
22
23/// `config …`: the settings, by key.
24#[derive(Debug, clap::Subcommand)]
25pub enum AppConfigCommand {
26    /// List settings and their values.
27    List {
28        /// Which scope's file to list.
29        #[command(flatten)]
30        scope: AppScopeFlags,
31        /// Say where each value comes from.
32        #[arg(long)]
33        show_origin: bool,
34    },
35    /// Show one setting.
36    Get {
37        /// The setting's key.
38        key: String,
39    },
40    /// Set settings: `key=value`..., or one secret key alone (prompted, or `--stdin`).
41    Set {
42        /// `key=value` pairs; a secret's key is given alone.
43        #[arg(required = true)]
44        entries: Vec<String>,
45        /// Which scope's file to write (default: each key's own).
46        #[command(flatten)]
47        scope: AppScopeFlags,
48        /// Read a secret from standard input even on a terminal.
49        #[arg(long)]
50        stdin: bool,
51        /// Restart what the change waits for afterwards — the bridge, then this
52        /// application's server — and wait until they are back.
53        #[arg(long)]
54        restart: bool,
55    },
56    /// Remove settings (or every setting under a prefix), going back to the defaults.
57    Unset {
58        /// The keys, or prefixes of several keys.
59        #[arg(required = true)]
60        keys: Vec<String>,
61        /// Which scope's file to remove from (default: each key's own).
62        #[command(flatten)]
63        scope: AppScopeFlags,
64        /// Restart what the change waits for afterwards — the bridge, then this
65        /// application's server — and wait until they are back.
66        #[arg(long)]
67        restart: bool,
68    },
69}
70
71/// The scope flags of an application's `config`: at most one of them.
72#[derive(Debug, Clone, Copy, clap::Args)]
73pub struct AppScopeFlags {
74    /// This device's file.
75    #[arg(long, conflicts_with_all = ["workgroup", "workspace"])]
76    device: bool,
77    /// The workgroup's file (the bridge's settings only).
78    #[arg(long, conflicts_with = "workspace")]
79    workgroup: bool,
80    /// The selected workspace's file (this application's settings only).
81    #[arg(long)]
82    workspace: bool,
83}
84
85impl AppScopeFlags {
86    /// The scope the flags name; `None` when none is given.
87    pub fn scope(&self) -> Option<Scope> {
88        if self.device {
89            Some(Scope::Device)
90        } else if self.workgroup {
91            Some(Scope::Workgroup)
92        } else if self.workspace {
93            Some(Scope::Workspace)
94        } else {
95            None
96        }
97    }
98}
99
100/// What `list` prints under the server's keys when the bridge's are missing.
101const BRIDGE_NOT_SHOWN: &str = "sapphire-bridge is not running; its settings are not shown";
102
103/// How long `--restart` waits for the app server to answer again.
104const RESTART_TIMEOUT: Duration = Duration::from_secs(30);
105
106/// How often it looks.
107const RESTART_POLL: Duration = Duration::from_millis(100);
108
109/// `config …`: through the running server, or — when none runs — on this application's
110/// files, with `owner`'s settings beside the framework's.
111pub(super) async fn config<A: AppSettings + Clone>(
112    ctx: &'static AppContext,
113    owner: A,
114    command: AppConfigCommand,
115    version: &str,
116) -> Result<i32> {
117    let app = ctx.app_name;
118    let Some(client) = super::try_connect_app(app, version).await? else {
119        // Only `list` speaks of the bridge, and only to say whether it runs.
120        let bridge_running = matches!(command, AppConfigCommand::List { .. })
121            && sapphire_ipc::probe(&Endpoint::for_bridge()?)
122                .await
123                .unwrap_or(false);
124        let printed = offline(ctx, Arc::new(owner), command, bridge_running)?;
125        for line in printed.out {
126            println!("{line}");
127        }
128        for line in printed.err {
129            eprintln!("{line}");
130        }
131        return Ok(printed.code);
132    };
133    online(Arc::new(client), app, version, command).await
134}
135
136// ── online ──────────────────────────────────────────────────────────────────
137
138/// A write's result, or — when the batch was rejected and its keys named — `None` after
139/// printing the error and one `{key}: {message}` line per key.
140fn rejected_batch<T>(result: sapphire_ipc::Result<T>) -> Option<sapphire_ipc::Result<T>> {
141    use sapphire_bridge_client::ConfigFieldErrorsExt;
142    if let Err(err @ sapphire_ipc::Error::Rpc(rpc)) = &result
143        && let Some(fields) = sapphire_bridge_api::ConfigFieldErrors::from_rpc(rpc)
144    {
145        eprintln!("{err}");
146        for line in fields.lines() {
147            eprintln!("{line}");
148        }
149        return None;
150    }
151    Some(result)
152}
153
154/// `config …` over `client`, the app server's connection.
155async fn online(
156    client: Arc<sapphire_ipc::Client>,
157    app: &str,
158    version: &str,
159    command: AppConfigCommand,
160) -> Result<i32> {
161    let bridge = BridgeClient::relayed(Arc::clone(&client), sapphire_ipc::runtime_dir()?);
162    let (written, restart, schema) = match command {
163        AppConfigCommand::List { scope, show_origin } => {
164            let entries = bridge.config_list(scope.scope()).await?.entries;
165            for line in sapphire_bridge_api::describe_entries(&entries, show_origin) {
166                println!("{line}");
167            }
168            // The workspace scope is the server's alone: nothing of the bridge's is missing.
169            if scope.scope() != Some(Scope::Workspace)
170                && !has_bridge(&bridge.config_schema().await?.settings)
171            {
172                println!("{BRIDGE_NOT_SHOWN}");
173            }
174            return Ok(0);
175        }
176        AppConfigCommand::Get { key } => {
177            let lines = match bridge.config_get(&key).await {
178                Ok(entry) => sapphire_bridge_api::describe_entries(&[entry], false),
179                Err(sapphire_ipc::Error::NotRunning(_)) => {
180                    eprintln!(
181                        "unknown setting {key} (or sapphire-bridge, which may know it, is not running)"
182                    );
183                    return Ok(1);
184                }
185                // On stderr: `$(<app> config get k)` must not take it for the value.
186                Err(err) => {
187                    eprintln!("{err}");
188                    return Ok(1);
189                }
190            };
191            for line in lines {
192                println!("{line}");
193            }
194            return Ok(0);
195        }
196        AppConfigCommand::Set {
197            entries,
198            scope,
199            stdin,
200            restart,
201        } => {
202            let schema = bridge.config_schema().await?.settings;
203            // Checked here, not left to the server: `parse_entries` needs each key's kind to
204            // read `key=value`, so a key missing from the schema would fail as unknown before
205            // the server could say that the bridge, which may know it, is not running.
206            if !has_bridge(&schema)
207                && let Some(key) = entries
208                    .iter()
209                    .map(|e| e.split_once('=').map_or(e.as_str(), |(key, _)| key))
210                    .find(|key| !schema.iter().any(|d| d.key == *key))
211            {
212                return Err(Error::Config(format!(
213                    "unknown setting {key} (or sapphire-bridge, which may know it, is not running)"
214                )));
215            }
216            let entries = sapphire_bridge_api::parse_entries(&schema, &entries, stdin)
217                .map_err(Error::Config)?;
218            (
219                {
220                    let result = bridge.config_set(scope.scope(), entries).await;
221                    let Some(result) = rejected_batch(result) else {
222                        return Ok(1);
223                    };
224                    result?
225                },
226                restart,
227                Some(schema),
228            )
229        }
230        AppConfigCommand::Unset {
231            keys,
232            scope,
233            restart,
234        } => (
235            {
236                let result = bridge.config_unset(scope.scope(), keys).await;
237                let Some(result) = rejected_batch(result) else {
238                    return Ok(1);
239                };
240                result?
241            },
242            restart,
243            None,
244        ),
245    };
246
247    // Which process each pending key waits on, through the schema; a key it does not list
248    // is the bridge's, as an older bridge's definitions are.
249    let schema = match schema {
250        Some(schema) => schema,
251        None => bridge.config_schema().await?.settings,
252    };
253    let waits_on = |process: Process| {
254        written.pending_restart.iter().any(|key| {
255            schema
256                .iter()
257                .find(|d| d.key == *key)
258                .map_or(Process::Bridge, |d| d.process)
259                == process
260        })
261    };
262    let (bridge_waits, app_waits) = (waits_on(Process::Bridge), waits_on(Process::App));
263    if !restart {
264        if bridge_waits {
265            println!("restart required: sapphire-bridge");
266        }
267        if app_waits {
268            println!("restart required: {app} server");
269        }
270        return Ok(0);
271    }
272    if !bridge_waits && !app_waits {
273        println!("nothing awaits a restart");
274        return Ok(0);
275    }
276    // The bridge first: the app server's restart would only reconnect to the old one.
277    if bridge_waits {
278        // Relayed, the call returns once the new bridge answers.
279        bridge.restart().await?;
280        println!("sapphire-bridge restarted");
281    }
282    if app_waits {
283        restart_app_server(&client, app, version).await?;
284        println!("the {app} server restarted");
285    }
286    Ok(0)
287}
288
289/// Whether `schema` holds any of the bridge's settings: it does whenever the bridge
290/// answered the server.
291fn has_bridge(schema: &[SettingDef]) -> bool {
292    schema.iter().any(|d| d.process == Process::Bridge)
293}
294
295/// Ask the app server `client` is connected to to restart, and wait until it is back.
296///
297/// "Back" is two facts in order: the connection that asked has closed — the old server
298/// stopped serving it — and a new connection to the endpoint answers `server.info`.
299async fn restart_app_server(client: &sapphire_ipc::Client, app: &str, version: &str) -> Result<()> {
300    let _: proto::Ack = client
301        .call(proto::SERVER_RESTART, serde_json::json!({}))
302        .await?;
303    let endpoint = Endpoint::for_app(app)?;
304    let came_back = async {
305        client.closed().await;
306        loop {
307            if answers(&endpoint, app, version).await {
308                return;
309            }
310            tokio::time::sleep(RESTART_POLL).await;
311        }
312    };
313    tokio::time::timeout(RESTART_TIMEOUT, came_back)
314        .await
315        .map_err(|_| {
316            Error::Config(format!(
317                "the {app} server did not come back within {} s",
318                RESTART_TIMEOUT.as_secs()
319            ))
320        })
321}
322
323/// Whether the server at `endpoint` answers `server.info` on a new connection.
324async fn answers(endpoint: &Endpoint, app: &str, version: &str) -> bool {
325    let info = ClientInfo {
326        kind: "cli".to_owned(),
327        version: version.to_owned(),
328        api: proto::API_VERSION,
329        app_api: None,
330        pid: std::process::id(),
331    };
332    let Ok(Some((client, _))) = sapphire_ipc::connect_or_absent(endpoint, app, info).await else {
333        return false;
334    };
335    client
336        .call::<_, proto::StatusReport>(proto::SERVER_INFO, serde_json::json!({}))
337        .await
338        .is_ok()
339}
340
341// ── offline ─────────────────────────────────────────────────────────────────
342
343/// What an offline `config` command prints, and its exit code.
344#[derive(Debug)]
345struct Printed {
346    /// The exit code.
347    code: i32,
348    /// Lines for stdout: the answer.
349    out: Vec<String>,
350    /// Lines for stderr: why there is no answer.
351    err: Vec<String>,
352}
353
354impl Printed {
355    fn ok(out: Vec<String>) -> Printed {
356        Printed {
357            code: 0,
358            out,
359            err: Vec::new(),
360        }
361    }
362
363    fn failed(err: String) -> Printed {
364        Printed {
365            code: 1,
366            out: Vec::new(),
367            err: vec![err],
368        }
369    }
370}
371
372/// Carry out `command` on `ctx`'s application's files, with `owner`'s settings beside the
373/// framework's: what to print, and the exit code.
374///
375/// The files are opened as the server opens them — `server.toml` migrated first — but the
376/// checks a starting server runs do not stop the command, so it can repair a file the
377/// server refuses: `list` and `get` answer and add the checks' error as a warning, and a
378/// write is accepted when the edited files pass the owners' checks. A file that does not
379/// parse at all is an error naming it. `bridge_running` says which line `list` ends with.
380fn offline(
381    ctx: &'static AppContext,
382    owner: Arc<dyn AppSettings>,
383    command: AppConfigCommand,
384    bridge_running: bool,
385) -> Result<Printed> {
386    let app = ctx.app_name;
387    // Checked before anything is written: the user asked for a restart, and a write that
388    // took effect with none would be a surprise.
389    if let AppConfigCommand::Set { restart: true, .. }
390    | AppConfigCommand::Unset { restart: true, .. } = command
391    {
392        return Ok(Printed::failed(format!(
393            "the {app} server is not running; nothing to restart"
394        )));
395    }
396    let (reg, checked) = crate::settings::open_unchecked(ctx, owner)?;
397    let reg = &reg;
398    // Read-only commands answer anyway, saying what a starting server would refuse.
399    let warning = match (&command, checked) {
400        (AppConfigCommand::List { .. } | AppConfigCommand::Get { .. }, Err(e)) => {
401            Some(format!("warning: the {app} server would not start: {e}"))
402        }
403        _ => None,
404    };
405    let warned = |mut printed: Printed| {
406        printed.err.splice(0..0, warning.clone());
407        printed
408    };
409    let bridge_key = |key: &str| {
410        Printed::failed(format!(
411            "the {app} server is not running; start it, or use sapphire-bridge config for {key}"
412        ))
413    };
414    let written = || {
415        Ok(Printed::ok(vec![format!(
416            "the {app} server is not running; it applies these settings when it starts"
417        )]))
418    };
419    match command {
420        AppConfigCommand::List { scope, show_origin } => {
421            // The workgroup scope is the bridge's alone.
422            let entries = match scope.scope() {
423                Some(Scope::Workgroup) => Vec::new(),
424                scope => list(reg, scope, None)?,
425            };
426            let mut out = sapphire_bridge_api::describe_entries(&entries, show_origin);
427            // The bridge's settings reach this command through the server alone.
428            if scope.scope() != Some(Scope::Workspace) {
429                out.push(if bridge_running {
430                    format!("start the {app} server to see sapphire-bridge's settings")
431                } else {
432                    BRIDGE_NOT_SHOWN.to_owned()
433                });
434            }
435            Ok(warned(Printed::ok(out)))
436        }
437        AppConfigCommand::Get { key } => {
438            if reg.def(&key).is_err() {
439                return Ok(warned(bridge_key(&key)));
440            }
441            Ok(warned(match get(reg, &key) {
442                Ok(entry) => Printed::ok(sapphire_bridge_api::describe_entries(&[entry], false)),
443                Err(err) => Printed::failed(err.to_string()),
444            }))
445        }
446        AppConfigCommand::Set {
447            entries,
448            scope,
449            stdin,
450            restart: _,
451        } => {
452            let keys = entries
453                .iter()
454                .map(|e| e.split_once('=').map_or(e.as_str(), |(key, _)| key));
455            if let Some(key) = keys.into_iter().find(|key| !own(reg, key)) {
456                return Ok(bridge_key(key));
457            }
458            let entries = sapphire_bridge_api::parse_entries(&reg.schema(), &entries, stdin)
459                .map_err(Error::Config)?;
460            let ops = entries
461                .into_iter()
462                .map(|e| Op::Set {
463                    key: e.key,
464                    value: e.value,
465                })
466                .collect();
467            apply(reg, scope.scope(), ops)?;
468            written()
469        }
470        AppConfigCommand::Unset { keys, scope, .. } => {
471            if let Some(key) = keys.iter().find(|key| !own(reg, key)) {
472                return Ok(bridge_key(key));
473            }
474            let ops = keys.into_iter().map(|key| Op::Unset { key }).collect();
475            apply(reg, scope.scope(), ops)?;
476            written()
477        }
478    }
479}
480
481/// Whether `key` is this server's: a key its registry knows, or a prefix of keys it knows.
482fn own(reg: &Registry, key: &str) -> bool {
483    reg.def(key).is_ok() || !reg.under(key).is_empty()
484}
485
486#[cfg(test)]
487mod tests {
488    use super::*;
489    use clap::Parser;
490
491    #[derive(Parser)]
492    struct Probe {
493        #[command(subcommand)]
494        command: AppConfigCommand,
495    }
496
497    fn parse(args: &[&str]) -> std::result::Result<AppConfigCommand, clap::Error> {
498        Probe::try_parse_from(std::iter::once("config").chain(args.iter().copied()))
499            .map(|p| p.command)
500    }
501
502    #[test]
503    fn each_scope_flag_names_its_scope() {
504        for (flag, scope) in [
505            ("--device", Some(Scope::Device)),
506            ("--workgroup", Some(Scope::Workgroup)),
507            ("--workspace", Some(Scope::Workspace)),
508        ] {
509            let AppConfigCommand::List { scope: flags, .. } = parse(&["list", flag]).unwrap()
510            else {
511                panic!("not list");
512            };
513            assert_eq!(flags.scope(), scope, "{flag}");
514        }
515        let AppConfigCommand::List { scope, .. } = parse(&["list"]).unwrap() else {
516            panic!("not list");
517        };
518        assert_eq!(scope.scope(), None);
519    }
520
521    #[test]
522    fn the_scope_flags_exclude_each_other() {
523        for pair in [
524            ["--device", "--workgroup"],
525            ["--device", "--workspace"],
526            ["--workgroup", "--workspace"],
527        ] {
528            assert!(parse(&["list", pair[0], pair[1]]).is_err(), "{pair:?}");
529        }
530    }
531
532    #[test]
533    fn set_and_unset_take_restart() {
534        assert!(matches!(
535            parse(&["set", "a.b=1", "--restart", "--workspace"]).unwrap(),
536            AppConfigCommand::Set { restart: true, .. }
537        ));
538        assert!(matches!(
539            parse(&["unset", "a.b", "--restart"]).unwrap(),
540            AppConfigCommand::Unset { restart: true, .. }
541        ));
542        assert!(parse(&["set"]).is_err(), "set needs an entry");
543    }
544}