Skip to main content

sapphire_framework_server/
command.rs

1//! The framework-provided half of an application's CLI.
2
3use std::fmt::Write as _;
4use std::path::PathBuf;
5
6use sapphire_backend::protocol as proto;
7use sapphire_bridge_api::{
8    DevicePrioritySetParams, DeviceRetireParams, InviteParams, JoinParams, WorkgroupCreateParams,
9};
10use sapphire_bridge_client::BridgeClient;
11use sapphire_framework_service::{Environment, ServiceCommand, SystemManager};
12use sapphire_ipc::{ClientInfo, Endpoint};
13
14use crate::AppServer;
15use crate::error::{Error, Result};
16
17pub use sapphire_backend::protocol::{StatusReport, StatusRow};
18
19/// The framework's commands, flattened into an application's CLI (spec decision 2).
20///
21/// An application composes these beside its own verbs by giving its subcommand enum a
22/// `#[command(flatten)] Framework(FrameworkCommand)` variant, so every verb — the app's and
23/// the framework's — sits at the same top level. The parse tests below pin that shape.
24#[derive(Debug, Default, clap::Subcommand)]
25pub enum FrameworkCommand {
26    /// Run the server in this process until SIGTERM or SIGINT (the bare invocation).
27    #[default]
28    Serve,
29    /// Report whether a server is running, and which version.
30    Status,
31    /// Install, remove or report this application's operating-system service.
32    #[command(subcommand)]
33    Service(ServiceCommand),
34    /// Create, select, show and map this application's workspace. The server serves one
35    /// at a time.
36    #[command(subcommand)]
37    Workspace(WorkspaceCommand),
38    /// Found, show or join the workgroup this device belongs to.
39    #[command(subcommand)]
40    Workgroup(WorkgroupCommand),
41    /// List the workgroup's devices, invite one or retire one.
42    #[command(subcommand)]
43    Device(DeviceCommand),
44    /// Show or change the embedding models (the workgroup's local and remote one), this
45    /// device's switches, and its API key. Needs the running bridge.
46    #[command(subcommand)]
47    Embedding(sapphire_bridge_api::EmbeddingCommand),
48    /// Add, list, retire, restore and rotate the workgroup's external devices — clients
49    /// that reach this application with a key. `add` allows this application unless told
50    /// otherwise. Needs the running bridge.
51    #[command(subcommand)]
52    ExternalDevice(sapphire_bridge_api::ExternalDeviceCommand),
53}
54
55impl FrameworkCommand {
56    /// Carry out the command, returning the process exit code.
57    ///
58    /// The application matches its own variants first, then hands the framework's here;
59    /// the app name and the service spec come from `server` itself.
60    pub async fn dispatch(self, server: AppServer, version: &'static str) -> Result<i32> {
61        match self {
62            FrameworkCommand::Serve => {
63                server.run().await?;
64                Ok(0)
65            }
66            FrameworkCommand::Status => crate::command::status(&server, version).await,
67            FrameworkCommand::Service(command) => {
68                let spec = server.service_spec();
69                command
70                    .run(&spec, &Environment::detect(), &SystemManager)
71                    .map_err(Error::from)
72            }
73            FrameworkCommand::Workspace(command) => {
74                command.dispatch(server.app_name(), version).await
75            }
76            FrameworkCommand::Workgroup(command) => command.dispatch(version).await,
77            FrameworkCommand::Device(command) => command.dispatch(version).await,
78            FrameworkCommand::Embedding(command) => embedding(command, version).await,
79            FrameworkCommand::ExternalDevice(command) => {
80                external_device(command, server.app_name(), version).await
81            }
82        }
83    }
84}
85
86/// The `workspace` subcommands (#215: one workspace per server).
87///
88/// `init`, `select` and `map`'s write go to the app's server over IPC, because the server
89/// owns the marker directories, the sync ids and which workspace it serves; `show` asks the
90/// server for its workspace and then the bridge for the workgroup's ledger; `map`'s
91/// selector resolution is the workgroup's word, so it goes to the bridge first. These are
92/// the only verbs that take a path: everything else acts on the server's workspace.
93#[derive(Debug, clap::Subcommand)]
94pub enum WorkspaceCommand {
95    /// Create this app's workspace home in the given directory, and switch the server to it.
96    Init {
97        /// Where the workspace root goes. Defaults to the current directory.
98        dir: Option<PathBuf>,
99        /// Also start syncing it, which publishes it into the workgroup ledger.
100        #[arg(long)]
101        sync: bool,
102    },
103    /// Switch the server to an existing workspace of this app.
104    Select {
105        /// The workspace's root. Defaults to the current directory.
106        dir: Option<PathBuf>,
107    },
108    /// Show the server's workspace, then the workgroup's workspaces of this app.
109    Show,
110    /// Bring a workspace the workgroup knows to a local directory, and switch to it.
111    Map {
112        /// The workspace, by name or id, as the workgroup lists it.
113        selector: String,
114        /// The local directory to map it to. Defaults to the current one.
115        dir: Option<PathBuf>,
116    },
117}
118
119impl WorkspaceCommand {
120    /// Carry out the command, returning the process exit code.
121    ///
122    /// `app` names the endpoint to open (`Endpoint::for_app`); `version` is this
123    /// process's own, for the handshake.
124    pub async fn dispatch(self, app: &'static str, version: &'static str) -> Result<i32> {
125        match self {
126            WorkspaceCommand::Init { dir, sync } => workspace_init(app, version, dir, sync).await,
127            WorkspaceCommand::Select { dir } => workspace_select(app, version, dir).await,
128            WorkspaceCommand::Show => workspace_show(app, version).await,
129            WorkspaceCommand::Map { selector, dir } => {
130                workspace_map(app, version, &selector, dir).await
131            }
132        }
133    }
134}
135
136/// The `workgroup` subcommands.
137///
138/// The workgroup's ledger is the bridge's business end to end, so these go to the bridge's
139/// endpoint directly, including `create`, which goes through the running bridge.
140#[derive(Debug, clap::Subcommand)]
141pub enum WorkgroupCommand {
142    /// Found a workgroup on this host.
143    Create {
144        /// The workgroup's name.
145        name: String,
146        /// This host's device name inside it.
147        #[arg(long)]
148        device_name: String,
149    },
150    /// Show the workgroup this host belongs to.
151    List,
152    /// Join the workgroup a ticket names.
153    Join {
154        /// The ticket the inviting device printed.
155        ticket: String,
156        /// The name this device will carry. Defaults to this host's name.
157        #[arg(long)]
158        device_name: Option<String>,
159    },
160}
161
162impl WorkgroupCommand {
163    /// Carry out the command, returning the process exit code.
164    pub async fn dispatch(self, version: &'static str) -> Result<i32> {
165        match self {
166            WorkgroupCommand::Create { name, device_name } => {
167                let client = connect_running(version).await?;
168                let created = client
169                    .workgroup_create(WorkgroupCreateParams { name, device_name })
170                    .await?;
171                println!(
172                    "created workgroup {} ({}); this device is {}",
173                    created.name, created.workgroup_id, created.device_id
174                );
175                Ok(0)
176            }
177            WorkgroupCommand::List => {
178                let client = connect_running(version).await?;
179                match client.status().await?.workgroup {
180                    Some(workgroup) => {
181                        println!("{} ({})", workgroup.name, workgroup.workgroup_id);
182                        Ok(0)
183                    }
184                    None => {
185                        println!("this host has not joined a workgroup");
186                        Ok(1)
187                    }
188                }
189            }
190            WorkgroupCommand::Join {
191                ticket,
192                device_name,
193            } => {
194                let client = connect_running(version).await?;
195                let joined = client
196                    .join(JoinParams {
197                        ticket,
198                        device_name,
199                    })
200                    .await?;
201                println!(
202                    "joined workgroup {} ({}); this device is {}",
203                    joined.workgroup_name, joined.workgroup_id, joined.device_id
204                );
205                Ok(0)
206            }
207        }
208    }
209}
210
211/// The `device` subcommands.
212///
213/// The ledger's word for taking a device out is `retire` — a device id is written into
214/// synced content and must keep resolving, so its record stays as a tombstone — and this
215/// command goes through the running bridge to retire a device.
216#[derive(Debug, clap::Subcommand)]
217pub enum DeviceCommand {
218    /// List the workgroup's devices, and which are reachable.
219    List,
220    /// Create an invite ticket for a device that is about to join.
221    Invite {
222        /// What the joining device will be called.
223        #[arg(long)]
224        name: String,
225        /// How long the invite stays good, in seconds.
226        #[arg(long)]
227        ttl: Option<u64>,
228        /// The workgroup to invite into, by name or id.
229        #[arg(long)]
230        workgroup: Option<String>,
231    },
232    /// Retire a device, so it may no longer connect.
233    Retire {
234        /// The device's name or id.
235        selector: String,
236    },
237    /// Show or set a device's election priority (0-255; 0 = never primary or secondary).
238    /// The election is non-preemptive: raising a priority does not move a role already held.
239    Priority {
240        /// The device's name or id.
241        selector: String,
242        /// The new priority. Omit to show the current one.
243        priority: Option<u8>,
244    },
245}
246
247impl DeviceCommand {
248    /// Carry out the command, returning the process exit code.
249    pub async fn dispatch(self, version: &'static str) -> Result<i32> {
250        match self {
251            DeviceCommand::List => {
252                let client = connect_running(version).await?;
253                let peers = client.peers().await?;
254                if peers.peers.is_empty() {
255                    println!("no devices");
256                    return Ok(0);
257                }
258                for peer in peers.peers {
259                    println!(
260                        "{} {} p{}{}{}",
261                        peer.name,
262                        peer.device_id,
263                        peer.priority,
264                        peer.availability
265                            .map(|a| format!(" a{a}"))
266                            .unwrap_or_default(),
267                        if peer.connected { " (online)" } else { "" }
268                    );
269                }
270                Ok(0)
271            }
272            DeviceCommand::Invite {
273                name,
274                ttl,
275                workgroup,
276            } => {
277                let client = connect_running(version).await?;
278                let invite = client
279                    .invite(InviteParams {
280                        name,
281                        ttl,
282                        workgroup,
283                    })
284                    .await?;
285                // The ticket on its own line, and nothing else on it: this is the one
286                // output a user pipes to the joining device.
287                println!("{}", invite.ticket);
288                Ok(0)
289            }
290            DeviceCommand::Retire { selector } => {
291                let client = connect_running(version).await?;
292                let retired = client
293                    .device_retire(DeviceRetireParams { selector })
294                    .await?;
295                println!("retired device {} ({})", retired.name, retired.device_id);
296                Ok(0)
297            }
298            DeviceCommand::Priority { selector, priority } => {
299                let client = connect_running(version).await?;
300                match priority {
301                    Some(priority) => {
302                        let set = client
303                            .device_priority_set(DevicePrioritySetParams { selector, priority })
304                            .await?;
305                        println!("{} ({}) priority {}", set.name, set.device_id, set.priority);
306                    }
307                    None => {
308                        let peers = client.peers().await?;
309                        match peers
310                            .peers
311                            .iter()
312                            .find(|p| p.name == selector || p.device_id.to_string() == selector)
313                        {
314                            Some(p) => {
315                                println!("{} ({}) priority {}", p.name, p.device_id, p.priority)
316                            }
317                            None => {
318                                println!("no device {selector:?}");
319                                return Ok(1);
320                            }
321                        }
322                    }
323                }
324                Ok(0)
325            }
326        }
327    }
328}
329
330/// Connect to the running bridge, or fail with the message the command layer prints.
331///
332/// One wrapper for every arm that talks to the bridge: the error's text is what the
333/// `main` prints, so the absence case reads "no sapphire-bridge is running" without each
334/// arm repeating it.
335async fn connect_running(version: &str) -> Result<BridgeClient> {
336    BridgeClient::connect_running("cli", version)
337        .await
338        .map_err(Error::from)
339}
340
341/// `embedding …`: always through the running bridge, whose files these are.
342async fn embedding(command: sapphire_bridge_api::EmbeddingCommand, version: &str) -> Result<i32> {
343    // Connect first: `key set` asks for the key, which is pointless with no bridge to take it.
344    let client = connect_running(version).await?;
345    let request = command.request()?;
346    let report = client.embed_request(request).await?;
347    for line in sapphire_bridge_api::describe(&report) {
348        println!("{line}");
349    }
350    Ok(0)
351}
352
353/// `external-device …`: always through the running bridge, which owns the ledger.
354async fn external_device(
355    command: sapphire_bridge_api::ExternalDeviceCommand,
356    app: &str,
357    version: &str,
358) -> Result<i32> {
359    let client = connect_running(version).await?;
360    let outcome = client
361        .external_device_request(command.request(Some(app)))
362        .await?;
363    for line in sapphire_bridge_api::describe_external_outcome(&outcome) {
364        println!("{line}");
365    }
366    Ok(0)
367}
368
369/// `workspace init`: the server does the creating, over IPC.
370///
371/// The server owns the marker, the registry and the sync ids, so a workspace created
372/// here is one the server already knows and a GUI sharing the registry sees. Nothing is
373/// listening → the one line and exit 1; nothing is ever started (Global Constraints).
374/// `--sync` rides the server's existing `sync.enable` path on the same connection, and
375/// its state is printed after, so an unjoined host's "no workgroup knows it yet" is
376/// plain.
377async fn workspace_init(
378    app: &'static str,
379    version: &'static str,
380    dir: Option<PathBuf>,
381    sync: bool,
382) -> Result<i32> {
383    let endpoint = Endpoint::for_app(app)?;
384    let client_info = ClientInfo {
385        kind: "cli".to_owned(),
386        version: version.to_owned(),
387        api: proto::API_VERSION,
388        app_api: None,
389        pid: std::process::id(),
390    };
391    let Some((client, _)) = sapphire_ipc::connect_or_absent(&endpoint, app, client_info).await?
392    else {
393        println!("no {app} server is running");
394        return Ok(1);
395    };
396
397    // Resolved here: the server's cwd is not the user's.
398    let dir = std::env::current_dir()?.join(dir.unwrap_or_else(|| PathBuf::from(".")));
399    let result: proto::WorkspaceInitResult = client
400        .call(proto::WORKSPACE_INIT, proto::WorkspaceInitParams { dir })
401        .await?;
402    if result.created {
403        println!("initialized {app} workspace in {}", result.root.display());
404    } else {
405        println!(
406            "{} already exists (workspace {})",
407            result.root.display(),
408            result.workspace_id
409        );
410    }
411    println!("the {app} server now serves {}", result.root.display());
412
413    if sync {
414        let enabled: proto::SyncEnableResult = client
415            .call(proto::SYNC_ENABLE, serde_json::json!({}))
416            .await?;
417        // Never fails on account of the bridge: the workspace is synced either way, and
418        // the status is the user's word for what the workgroup does not know yet.
419        let status: proto::SyncStatusResult = client
420            .call(proto::SYNC_STATUS, serde_json::json!({}))
421            .await
422            .unwrap_or(proto::SyncStatusResult {
423                enabled: true,
424                workspace_id: Some(enabled.workspace_id),
425                ..proto::SyncStatusResult::not_synced()
426            });
427        println!(
428            "syncing as {} ({} peer{})",
429            enabled.workspace_id,
430            status.peers,
431            if status.peers == 1 { "" } else { "s" }
432        );
433    }
434    Ok(0)
435}
436
437/// Render the server's workspace as the CLI prints it: `root state`.
438///
439/// Public so the integration tests can capture it; `workspace show` writes it to standard
440/// output.
441pub async fn render_workspace(client: &sapphire_ipc::Client, out: &mut String) -> Result<i32> {
442    let current: proto::WorkspaceCurrentResult = client
443        .call(proto::WORKSPACE_CURRENT, serde_json::json!({}))
444        .await?;
445    let Some(ws) = current.workspace else {
446        writeln!(
447            out,
448            "no workspace yet; run `workspace init <dir>` or `workspace select <dir>`"
449        )
450        .expect("writing to a String cannot fail");
451        return Ok(1);
452    };
453    writeln!(out, "{} {}", ws.root.display(), describe_state(&ws))
454        .expect("writing to a String cannot fail");
455    Ok(0)
456}
457
458/// `synced (star), embedding 3 pending` and the like.
459fn describe_state(ws: &proto::CurrentWorkspace) -> String {
460    let state = if !ws.reachable {
461        "unreachable"
462    } else if ws.sync.enabled {
463        "synced"
464    } else {
465        "not synced"
466    };
467    let star = if matches!(ws.sync.topology, proto::Topology::Star { .. }) {
468        " (star)"
469    } else {
470        ""
471    };
472    let pending = match &ws.sync.embedding {
473        Some(e) if e.pending > 0 => format!(", embedding {} pending", e.pending),
474        _ => String::new(),
475    };
476    format!("{state}{star}{pending}")
477}
478
479/// Connect to `app`'s server, or say none is running.
480async fn connect_app(app: &str, version: &str) -> Result<Option<sapphire_ipc::Client>> {
481    let endpoint = Endpoint::for_app(app)?;
482    let client_info = ClientInfo {
483        kind: "cli".to_owned(),
484        version: version.to_owned(),
485        api: proto::API_VERSION,
486        app_api: None,
487        pid: std::process::id(),
488    };
489    let client = sapphire_ipc::connect_or_absent(&endpoint, app, client_info).await?;
490    if client.is_none() {
491        println!("no {app} server is running");
492    }
493    Ok(client.map(|(c, _)| c))
494}
495
496/// `workspace select`: switch the server to an existing workspace.
497async fn workspace_select(
498    app: &'static str,
499    version: &'static str,
500    dir: Option<PathBuf>,
501) -> Result<i32> {
502    let Some(client) = connect_app(app, version).await? else {
503        return Ok(1);
504    };
505    // Resolved here: the server's cwd is not the user's.
506    let dir = std::env::current_dir()?.join(dir.unwrap_or_else(|| PathBuf::from(".")));
507    let ws: proto::CurrentWorkspace = client
508        .call(
509            proto::WORKSPACE_SELECT,
510            proto::WorkspaceSelectParams { dir },
511        )
512        .await?;
513    println!("{} {}", ws.root.display(), describe_state(&ws));
514    Ok(0)
515}
516
517/// `workspace show`: the server's workspace, then the workgroup's workspaces of this app.
518///
519/// The workgroup's ledger is the bridge's to answer, and the bridge being down is not the
520/// server half's failure: the ledger's absence is one line, and the exit is the server
521/// half's.
522async fn workspace_show(app: &'static str, version: &'static str) -> Result<i32> {
523    let Some(client) = connect_app(app, version).await? else {
524        return Ok(1);
525    };
526    let mut out = String::new();
527    let code = render_workspace(&client, &mut out).await?;
528    for line in out.lines() {
529        println!("{line}");
530    }
531
532    let Some(client) = BridgeClient::connect_running("cli", version).await.ok() else {
533        println!("no sapphire-bridge is running");
534        return Ok(code);
535    };
536    let workspaces = client.workspaces().await.map_err(Error::from)?;
537    let mine: Vec<_> = workspaces
538        .workspaces
539        .into_iter()
540        .filter(|w| w.app_name == app)
541        .collect();
542    if !mine.is_empty() {
543        println!();
544        println!("in the workgroup:");
545        for workspace in mine {
546            println!("{} {}", workspace.name, workspace.workspace_id);
547        }
548    }
549    Ok(code)
550}
551
552/// `workspace map`: the bridge resolves the selector, the server takes the write.
553///
554/// The resolution is the workgroup's word (which workspace, by what id), the write is the
555/// server's (`sync.map` places the id and starts the replica). The bridge is required —
556/// without it there is nothing to resolve against, so exit 1 — and so is the server,
557/// because the write and the replica are its.
558async fn workspace_map(
559    app: &'static str,
560    version: &'static str,
561    selector: &str,
562    dir: Option<PathBuf>,
563) -> Result<i32> {
564    let Some(client) = BridgeClient::connect_running("cli", version).await.ok() else {
565        println!("no sapphire-bridge is running");
566        return Ok(1);
567    };
568    let workspaces = client.workspaces().await.map_err(Error::from)?;
569    let wanted = workspaces
570        .workspaces
571        .iter()
572        // A name is the user-facing handle; the id is the exact one.
573        .find(|w| w.name == selector || w.workspace_id.to_string() == selector)
574        .ok_or_else(|| Error::UnknownWorkspaceName(selector.to_owned()))?;
575
576    let endpoint = Endpoint::for_app(app)?;
577    let client_info = ClientInfo {
578        kind: "cli".to_owned(),
579        version: version.to_owned(),
580        api: proto::API_VERSION,
581        app_api: None,
582        pid: std::process::id(),
583    };
584    let Some((client, _)) = sapphire_ipc::connect_or_absent(&endpoint, app, client_info).await?
585    else {
586        println!("no {app} server is running");
587        return Ok(1);
588    };
589
590    let dir = std::env::current_dir()?.join(dir.unwrap_or_else(|| PathBuf::from(".")));
591    let mapped: proto::SyncEnableResult = client
592        .call(
593            proto::SYNC_MAP,
594            proto::SyncMapParams {
595                workspace: wanted.workspace_id.to_string(),
596                dir,
597            },
598        )
599        .await?;
600    println!(
601        "mapped {} as {}; the {app} server now serves it",
602        wanted.name, mapped.workspace_id
603    );
604    Ok(0)
605}
606
607/// The status command's face: render and return the exit code, going to the process's
608/// standard output.
609async fn status(server: &AppServer, version: &str) -> Result<i32> {
610    let endpoint = Endpoint::for_app(server.app_name())?;
611    run_status(&endpoint, server.app_name(), version).await
612}
613
614/// Probe, handshake and call `SERVER_INFO` in one go, or report absence.
615///
616/// Every step the CLI needs — liveness and the API gate — is inside
617/// [`connect_or_absent`], so the command is that call plus one `SERVER_INFO` round trip.
618/// The API gate doubles as the liveness check here: a live server of another API version
619/// is `ApiVersionMismatch`, which names both API versions and advises upgrading and
620/// restarting the service. The report goes through [`run_status_into`] so tests can
621/// capture it.
622async fn run_status(endpoint: &Endpoint, app: &str, version: &str) -> Result<i32> {
623    let mut out = String::new();
624    let code = run_status_into(endpoint, app, version, &mut out).await?;
625    for line in out.lines() {
626        println!("{line}");
627    }
628    Ok(code)
629}
630
631/// [`run_status`], writing the rendered lines into `out` instead of the process's
632/// standard output.
633async fn run_status_into(
634    endpoint: &Endpoint,
635    app: &str,
636    version: &str,
637    out: &mut String,
638) -> Result<i32> {
639    let client_info = ClientInfo {
640        kind: "cli".to_owned(),
641        version: version.to_owned(),
642        api: proto::API_VERSION,
643        app_api: None,
644        pid: std::process::id(),
645    };
646    let Some((client, _)) = sapphire_ipc::connect_or_absent(endpoint, app, client_info).await?
647    else {
648        // Nothing is listening: the framework's half is only the one line, and the
649        // application's rows are skipped (there is no server to have configured them).
650        writeln!(out, "no {app} server is running").expect("writing to a String cannot fail");
651        return Ok(1);
652    };
653    let report: StatusReport = client
654        .call(
655            sapphire_backend::protocol::SERVER_INFO,
656            serde_json::json!({}),
657        )
658        .await?;
659    writeln!(out, "running: {}", report.running).expect("writing to a String cannot fail");
660    if let Some(version) = &report.version {
661        writeln!(out, "version: {version}").expect("writing to a String cannot fail");
662    }
663    if let Some(pid) = report.pid {
664        writeln!(out, "pid: {pid}").expect("writing to a String cannot fail");
665    }
666    if let Some(managed_by) = &report.managed_by {
667        writeln!(out, "managed_by: {managed_by:?}").expect("writing to a String cannot fail");
668    }
669    for row in &report.app {
670        writeln!(out, "{}: {}", row.name, row.value).expect("writing to a String cannot fail");
671    }
672    Ok(0)
673}
674#[cfg(test)]
675mod tests {
676    use super::*;
677    use clap::Parser;
678
679    /// The composition every app binary uses: an app-owned subcommand enum whose framework
680    /// verbs ride in on a flattened variant (spec decision 2).
681    ///
682    /// clap 4 rejects `#[command(flatten)]` on a struct field beside a
683    /// `#[command(subcommand)]` field — two subcommand enums cannot share one level, and a
684    /// flattened field must implement `clap::Args`, which the `Subcommand` derive does not
685    /// provide. The plan's Risks section names this probe as the decision, and the flat
686    /// fallback is what it decided: one subcommand enum, every verb at the top level.
687    #[derive(Parser)]
688    struct Probe {
689        #[command(subcommand)]
690        command: Command,
691    }
692
693    #[derive(Debug, clap::Subcommand)]
694    enum Command {
695        /// An app-specific verb that must parse beside the framework's.
696        Greet,
697        #[command(flatten)]
698        Framework(FrameworkCommand),
699    }
700
701    #[test]
702    fn app_and_framework_commands_parse_side_by_side() {
703        let probe = Probe::try_parse_from(["app", "greet"]).unwrap();
704        assert!(matches!(probe.command, Command::Greet));
705        let probe = Probe::try_parse_from(["app", "serve"]).unwrap();
706        assert!(matches!(
707            probe.command,
708            Command::Framework(FrameworkCommand::Serve)
709        ));
710        let probe = Probe::try_parse_from(["app", "status"]).unwrap();
711        assert!(matches!(
712            probe.command,
713            Command::Framework(FrameworkCommand::Status)
714        ));
715    }
716
717    #[test]
718    fn the_service_subcommands_parse() {
719        for args in [
720            vec!["app", "service", "install"],
721            vec!["app", "service", "uninstall"],
722            vec!["app", "service", "status"],
723        ] {
724            assert!(Probe::try_parse_from(&args).is_ok(), "{args:?}");
725        }
726    }
727
728    #[test]
729    fn the_workspace_and_bridge_commands_parse() {
730        for args in [
731            vec!["app", "workspace", "init"],
732            vec!["app", "workspace", "init", "papers"],
733            vec!["app", "workspace", "init", "--sync"],
734            vec!["app", "workspace", "show"],
735            vec!["app", "workspace", "select", "papers"],
736            vec!["app", "workspace", "map", "papers", "papers-remote"],
737            vec![
738                "app",
739                "workgroup",
740                "create",
741                "--device-name",
742                "laptop",
743                "home",
744            ],
745            vec!["app", "workgroup", "list"],
746            vec![
747                "app",
748                "workgroup",
749                "join",
750                "--device-name",
751                "laptop",
752                "TICKET",
753            ],
754            vec!["app", "device", "list"],
755            vec!["app", "device", "invite", "--name", "phone"],
756            vec!["app", "device", "retire", "phone"],
757        ] {
758            assert!(Probe::try_parse_from(&args).is_ok(), "{args:?}");
759        }
760    }
761
762    #[test]
763    fn bare_invocation_defaults_to_serve() {
764        // <app> with no subcommand at all means serve (spec decision 1). An app CLI
765        // achieves it by `Option<Command>` and handing the framework's default here; this
766        // probe pins the framework half.
767        #[derive(Parser)]
768        struct Bare {
769            #[command(subcommand)]
770            command: Option<Command>,
771        }
772        let bare = Bare::try_parse_from(["app"]).unwrap();
773        assert!(bare.command.is_none());
774        assert!(matches!(
775            FrameworkCommand::default(),
776            FrameworkCommand::Serve
777        ));
778    }
779}
780
781#[cfg(test)]
782mod status_tests {
783    use super::*;
784    use sapphire_workspace::AppContext;
785
786    static CTX: AppContext = AppContext::new("sapphire-statustest");
787
788    /// Wait until something is listening on `endpoint`.
789    ///
790    /// `tokio::spawn(server.run())` only schedules the server; without this wait a fast
791    /// `run_status` probe can run before `run` has bound the socket, and with nothing
792    /// listening that single unlucky probe is the whole test failing.
793    async fn wait_until_listening(endpoint: &Endpoint) {
794        let deadline = tokio::time::Instant::now() + std::time::Duration::from_secs(5);
795        while !sapphire_ipc::probe(endpoint).await.unwrap() {
796            assert!(
797                tokio::time::Instant::now() < deadline,
798                "the server never started listening"
799            );
800            tokio::time::sleep(std::time::Duration::from_millis(10)).await;
801        }
802    }
803
804    #[tokio::test]
805    async fn status_reports_no_server_when_none_is_running() {
806        let tmp = tempfile::tempdir().unwrap();
807        let endpoint = sapphire_ipc::Endpoint::in_dir("status-test", tmp.path().to_path_buf());
808        let code = run_status(&endpoint, "status-test", "0.0.0").await.unwrap();
809        assert_eq!(code, 1, "no server is a non-zero exit");
810    }
811
812    #[tokio::test(flavor = "multi_thread")]
813    async fn status_shows_the_extension_rows_of_a_running_server() {
814        let tmp = tempfile::tempdir().unwrap();
815        let endpoint = sapphire_ipc::Endpoint::in_dir("status-test", tmp.path().to_path_buf());
816        let server = AppServer::new(&CTX, "0.0.0")
817            .endpoint(endpoint.clone())
818            // This context's directories are never initialised here.
819            .selection_file(tmp.path().join("workspace.toml"))
820            .status_rows(std::sync::Arc::new(|| {
821                vec![StatusRow {
822                    name: "sync".into(),
823                    value: "on".into(),
824                }]
825            }));
826        let handle = tokio::spawn(async move { server.run().await });
827        wait_until_listening(&endpoint).await;
828
829        // The report goes through the sink face so the rendering is asserted, not just
830        // the exit code.
831        let mut out = String::new();
832        let code = run_status_into(&endpoint, CTX.app_name, "0.0.0", &mut out)
833            .await
834            .unwrap();
835        assert_eq!(code, 0);
836        assert!(out.contains("running: true"), "output was: {out}");
837        assert!(out.contains("sync: on"), "output was: {out}");
838
839        let (client, _) = sapphire_ipc::connect_or_absent(
840            &endpoint,
841            CTX.app_name,
842            sapphire_ipc::ClientInfo {
843                kind: "test".into(),
844                version: "0.0.0".into(),
845                api: sapphire_backend::protocol::API_VERSION,
846                app_api: None,
847                pid: std::process::id(),
848            },
849        )
850        .await
851        .unwrap()
852        .expect("the server is listening");
853        let _: serde_json::Value = client
854            .call(sapphire_ipc::SHUTDOWN_METHOD, serde_json::json!({}))
855            .await
856            .unwrap();
857        handle.await.unwrap().unwrap();
858    }
859}
860
861#[cfg(test)]
862mod service_spec_tests {
863    use super::*;
864    use sapphire_workspace::AppContext;
865
866    static CTX: AppContext = AppContext::new("sapphire-servicetest");
867
868    #[test]
869    fn the_generated_spec_runs_the_server_not_the_cli() {
870        // A service manager starts the executable directly, and the executable's bare
871        // invocation is `serve`: the unit's argv must be exactly that, so the server that
872        // starts has no CLI verbs on its command line to misparse.
873        let spec = AppServer::new(&CTX, "0.0.0").service_spec();
874        assert_eq!(spec.args, vec!["serve".to_owned()]);
875    }
876
877    #[test]
878    fn the_generated_spec_names_this_application() {
879        let spec = AppServer::new(&CTX, "0.0.0").service_spec();
880        assert_eq!(spec.app_name, CTX.app_name);
881    }
882
883    #[test]
884    fn the_generated_spec_describes_the_server() {
885        let spec = AppServer::new(&CTX, "0.0.0").service_spec();
886        assert!(
887            spec.description.contains(CTX.app_name),
888            "the unit's description should name the application: {:?}",
889            spec.description
890        );
891        assert!(spec.description.contains("0.0.0"));
892    }
893}