use std::fmt::Write as _;
use std::path::PathBuf;
use std::sync::Arc;
use corundum_framework_service::{Environment, ServiceCommand, SystemManager};
use sapphire_backend::protocol as proto;
use sapphire_bridge_client::BridgeClient;
use sapphire_ipc::{ClientInfo, Endpoint};
use crate::AppServer;
use crate::error::{Error, Result};
use crate::selection::SelectionFile;
use crate::settings::{AppSettings, Settings};
use sapphire_workspace::AppContext;
mod config;
pub use config::{AppConfigCommand, AppScopeFlags};
pub use sapphire_backend::protocol::{StatusReport, StatusRow};
#[derive(Debug, clap::Subcommand)]
pub enum FrameworkCommand {
Serve,
Status,
#[command(subcommand)]
Service(ServiceCommand),
Update(AppUpdateArgs),
#[command(subcommand)]
Workspace(WorkspaceCommand),
#[command(subcommand)]
ApiKey(corundum_framework_keys::KeyCommand),
#[command(hide = true)]
ExternalDevice(LegacyExternalDevice),
#[command(subcommand)]
Config(AppConfigCommand),
#[cfg(feature = "mcp")]
Mcp,
}
impl FrameworkCommand {
pub async fn dispatch<A, F>(
self,
ctx: &'static AppContext,
owner: A,
build: F,
version: &'static str,
) -> Result<i32>
where
A: AppSettings + Clone,
F: Fn(&Settings) -> AppServer,
{
let app = ctx.app_name;
let server = |owner: A| -> Result<AppServer> {
Ok(build(&settings_or_defaults(ctx, Arc::new(owner))?))
};
match self {
FrameworkCommand::Serve => {
crate::serve_restarting(ctx, owner, build).await?;
Ok(0)
}
FrameworkCommand::Status => {
let endpoint = Endpoint::for_app(app)?;
run_status(&endpoint, app, version).await
}
FrameworkCommand::Service(command) => {
let spec = server(owner)?.service_spec();
command
.run(&spec, &Environment::detect(), &SystemManager)
.map_err(Error::from)
}
FrameworkCommand::Update(args) => {
let server = server(owner)?;
let own = match server.release_source() {
Some(source) => {
sapphire_framework_update::run(&args.update, source, app, version)
.await
.map_err(Error::from)
}
None => {
println!("{app} does not say where its releases are");
Ok(1)
}
};
let bridge = if args.no_bridge {
0
} else {
update_bridge(&args.update).await?
};
Ok(own?.max(bridge))
}
FrameworkCommand::Config(command) => config::config(ctx, owner, command, version).await,
FrameworkCommand::Workspace(command) => command.dispatch(app, version).await,
FrameworkCommand::ApiKey(command) => {
api_key(ctx, &server(owner)?.profiles().list(), command)
}
FrameworkCommand::ExternalDevice(legacy) => {
eprintln!("warning: `external-device` is renamed to `api-key`");
if !legacy.app.is_empty() {
eprintln!(
"API keys are per workspace now, not per application: `--app` is not taken"
);
return Ok(2);
}
api_key(ctx, &server(owner)?.profiles().list(), legacy.command)
}
#[cfg(feature = "mcp")]
FrameworkCommand::Mcp => {
server(owner)?.serve_mcp_stdio(version).await?;
Ok(0)
}
}
}
}
fn settings_or_defaults(ctx: &AppContext, owner: Arc<dyn AppSettings>) -> Result<Settings> {
match Settings::load(ctx, Arc::clone(&owner)) {
Ok(settings) => Ok(settings),
Err(err) => {
let file = Settings::device_file(ctx)
.map_or_else(|| "the settings".to_owned(), |f| f.display().to_string());
eprintln!("warning: could not read {file} ({err}); going on with the default settings");
Settings::defaults(ctx, owner)
}
}
}
#[derive(Clone, Debug, Default, clap::Args)]
pub struct AppUpdateArgs {
#[command(flatten)]
pub update: sapphire_framework_update::UpdateArgs,
#[arg(long)]
pub no_bridge: bool,
}
const BRIDGE_BINARY: &str = "sapphire-bridge";
const BRIDGE_RELEASES: &str = "https://github.com/sapphire-turtle/sapphire-framework/releases";
fn find_on_path(name: &str, path: Option<&std::ffi::OsStr>) -> Option<PathBuf> {
let file = format!("{name}{}", std::env::consts::EXE_SUFFIX);
std::env::split_paths(path?)
.map(|dir| dir.join(&file))
.find(|candidate| candidate.is_file())
}
pub async fn update_bridge(args: &sapphire_framework_update::UpdateArgs) -> Result<i32> {
match find_on_path(BRIDGE_BINARY, std::env::var_os("PATH").as_deref()) {
Some(exe) => run_bridge_update(&exe, args).await,
None => {
println!("{BRIDGE_BINARY} is not on PATH; not updating it");
Ok(0)
}
}
}
async fn run_bridge_update(
exe: &std::path::Path,
args: &sapphire_framework_update::UpdateArgs,
) -> Result<i32> {
let knows_update = tokio::process::Command::new(exe)
.args(["update", "--help"])
.stdout(std::process::Stdio::null())
.stderr(std::process::Stdio::null())
.status()
.await?
.success();
if !knows_update {
println!(
"{} cannot update itself; install the newest from {BRIDGE_RELEASES}",
exe.display()
);
return Ok(1);
}
let mut command = tokio::process::Command::new(exe);
command.arg("update");
if args.check {
command.arg("--check");
}
if args.yes {
command.arg("--yes");
}
let status = command.status().await?;
Ok(status.code().unwrap_or(1))
}
#[derive(Debug, clap::Subcommand)]
pub enum WorkspaceCommand {
Init {
dir: Option<PathBuf>,
#[arg(long)]
sync: bool,
#[arg(long, value_name = "NAME|ID", requires = "sync")]
remote_workspace: Option<String>,
},
Select {
dir: Option<PathBuf>,
#[arg(long)]
sync: bool,
},
#[command(subcommand)]
Sync(WorkspaceSyncCommand),
Show,
Move {
dir: PathBuf,
},
Remove {
#[arg(long)]
delete: bool,
},
}
impl WorkspaceCommand {
pub async fn dispatch(self, app: &'static str, version: &'static str) -> Result<i32> {
match self {
WorkspaceCommand::Init {
dir,
sync,
remote_workspace,
} => workspace_init(app, version, dir, sync, remote_workspace).await,
WorkspaceCommand::Select { dir, sync } => {
workspace_select(app, version, dir, sync).await
}
WorkspaceCommand::Sync(command) => workspace_sync(app, version, command).await,
WorkspaceCommand::Show => workspace_show(app, version).await,
WorkspaceCommand::Move { dir } => workspace_move(app, version, dir).await,
WorkspaceCommand::Remove { delete } => workspace_remove(app, version, delete).await,
}
}
}
#[derive(Debug, clap::Subcommand)]
pub enum WorkspaceSyncCommand {
Enable,
Disable,
Status,
}
#[derive(Debug, clap::Args)]
pub struct LegacyExternalDevice {
#[arg(long = "app", global = true, hide = true)]
app: Vec<String>,
#[command(subcommand)]
command: corundum_framework_keys::KeyCommand,
}
fn api_key(
ctx: &AppContext,
profiles: &[sapphire_framework_keys::Profile],
command: corundum_framework_keys::KeyCommand,
) -> Result<i32> {
let Some(selection) = SelectionFile::for_app(ctx).load(ctx.app_name)? else {
eprintln!(
"{} serves no workspace yet: choose one with `{} workspace select <dir>`",
ctx.app_name, ctx.app_name
);
return Ok(1);
};
if !selection.root.join(format!(".{}", ctx.app_name)).is_dir() {
eprintln!(
"the workspace at {} is not reachable: bring it back, or choose another with `{} workspace select <dir>`",
selection.root.display(),
ctx.app_name
);
return Ok(1);
}
let run = sapphire_framework_keys::open_store(ctx.app_name, &selection.root)
.and_then(|mut store| command.run(&mut store, profiles));
match run {
Ok(code) => Ok(code),
Err(err) => {
eprintln!("{err}");
Ok(1)
}
}
}
async fn workspace_init(
app: &'static str,
version: &'static str,
dir: Option<PathBuf>,
sync: bool,
remote_workspace: Option<String>,
) -> Result<i32> {
let endpoint = Endpoint::for_app(app)?;
let client_info = ClientInfo {
kind: "cli".to_owned(),
version: version.to_owned(),
api: proto::API_VERSION,
app_api: None,
pid: std::process::id(),
};
let Some((client, _)) = sapphire_ipc::connect_or_absent(&endpoint, app, client_info).await?
else {
println!("no {app} server is running");
return Ok(1);
};
let dir = workspace_dir(app, dir)?;
if let Some(selector) = remote_workspace {
std::fs::create_dir_all(&dir)?;
let mapped: proto::SyncEnableResult = client
.call(
proto::SYNC_MAP,
proto::SyncMapParams {
workspace: selector.clone(),
dir: dir.clone(),
},
)
.await?;
println!(
"initialized {app} workspace in {} from {selector}",
dir.display()
);
println!(
"the {app} server now serves it, syncing as {}",
mapped.workspace_id
);
return Ok(0);
}
let result: proto::WorkspaceInitResult = client
.call(proto::WORKSPACE_INIT, proto::WorkspaceInitParams { dir })
.await?;
if result.created {
println!("initialized {app} workspace in {}", result.root.display());
} else {
println!(
"{} already exists (workspace {})",
result.root.display(),
result.workspace_id
);
}
println!("the {app} server now serves {}", result.root.display());
if sync {
enable_sync(&client).await?;
}
Ok(0)
}
async fn enable_sync(client: &sapphire_ipc::Client) -> Result<()> {
let enabled: proto::SyncEnableResult = client
.call(proto::SYNC_ENABLE, serde_json::json!({}))
.await?;
let status: proto::SyncStatusResult = client
.call(proto::SYNC_STATUS, serde_json::json!({}))
.await
.unwrap_or(proto::SyncStatusResult {
enabled: true,
workspace_id: Some(enabled.workspace_id),
..proto::SyncStatusResult::not_synced()
});
println!(
"syncing as {} ({} peer{})",
enabled.workspace_id,
status.peers,
if status.peers == 1 { "" } else { "s" }
);
Ok(())
}
async fn workspace_sync(
app: &'static str,
version: &'static str,
command: WorkspaceSyncCommand,
) -> Result<i32> {
let Some(client) = connect_app(app, version).await? else {
return Ok(1);
};
match command {
WorkspaceSyncCommand::Enable => enable_sync(&client).await?,
WorkspaceSyncCommand::Disable => {
let _: proto::Ack = client
.call(proto::SYNC_DISABLE, serde_json::json!({}))
.await?;
println!("sync is off for the {app} workspace on this host; it keeps its sync id");
}
WorkspaceSyncCommand::Status => {
let status: proto::SyncStatusResult = client
.call(proto::SYNC_STATUS, serde_json::json!({}))
.await?;
for line in describe_sync(&status) {
println!("{line}");
}
}
}
Ok(0)
}
fn describe_sync(status: &proto::SyncStatusResult) -> Vec<String> {
let mut lines = vec![format!(
"sync: {}",
if status.enabled { "on" } else { "off" }
)];
if let Some(id) = status.workspace_id {
lines.push(format!("workspace id: {id}"));
}
if status.enabled {
lines.push(format!(
"peers: {}{}",
status.peers,
if matches!(status.topology, proto::Topology::Star { .. }) {
" (star)"
} else {
""
}
));
lines.push(format!(
"bridge: {}",
if status.bridge_available {
"reachable"
} else {
"not reachable"
}
));
}
if let Some(paused) = &status.paused {
lines.push(format!("paused: {paused}"));
}
if let Some(error) = &status.last_error {
lines.push(format!("last error: {error}"));
}
lines
}
pub async fn render_workspace(client: &sapphire_ipc::Client, out: &mut String) -> Result<i32> {
let current: proto::WorkspaceCurrentResult = client
.call(proto::WORKSPACE_CURRENT, serde_json::json!({}))
.await?;
let Some(ws) = current.workspace else {
writeln!(
out,
"no workspace yet; run `workspace init <dir>` or `workspace select <dir>`"
)
.expect("writing to a String cannot fail");
return Ok(1);
};
writeln!(out, "{} {}", ws.root.display(), describe_state(&ws))
.expect("writing to a String cannot fail");
Ok(0)
}
fn describe_state(ws: &proto::CurrentWorkspace) -> String {
let state = if !ws.reachable {
"unreachable"
} else if ws.sync.enabled {
"synced"
} else {
"not synced"
};
let star = if matches!(ws.sync.topology, proto::Topology::Star { .. }) {
" (star)"
} else {
""
};
let pending = match &ws.sync.embedding {
Some(e) if e.pending > 0 => format!(", embedding {} pending", e.pending),
_ => String::new(),
};
format!("{state}{star}{pending}")
}
fn workspace_dir(app: &str, dir: Option<PathBuf>) -> std::io::Result<PathBuf> {
Ok(match dir {
Some(dir) => std::env::current_dir()?.join(dir),
None => sapphire_workspace::default_workspace_dir(app),
})
}
async fn connect_app(app: &str, version: &str) -> Result<Option<sapphire_ipc::Client>> {
let client = try_connect_app(app, version).await?;
if client.is_none() {
println!("no {app} server is running");
}
Ok(client)
}
async fn try_connect_app(app: &str, version: &str) -> Result<Option<sapphire_ipc::Client>> {
let endpoint = Endpoint::for_app(app)?;
let client_info = ClientInfo {
kind: "cli".to_owned(),
version: version.to_owned(),
api: proto::API_VERSION,
app_api: None,
pid: std::process::id(),
};
let client = sapphire_ipc::connect_or_absent(&endpoint, app, client_info).await?;
Ok(client.map(|(c, _)| c))
}
async fn workspace_select(
app: &'static str,
version: &'static str,
dir: Option<PathBuf>,
sync: bool,
) -> Result<i32> {
let Some(client) = connect_app(app, version).await? else {
return Ok(1);
};
let dir = workspace_dir(app, dir)?;
let ws: proto::CurrentWorkspace = client
.call(
proto::WORKSPACE_SELECT,
proto::WorkspaceSelectParams { dir },
)
.await?;
println!("{} {}", ws.root.display(), describe_state(&ws));
if sync && !ws.sync.enabled {
enable_sync(&client).await?;
}
Ok(0)
}
async fn workspace_move(app: &'static str, version: &'static str, dir: PathBuf) -> Result<i32> {
let Some(client) = connect_app(app, version).await? else {
return Ok(1);
};
let dir = std::env::current_dir()?.join(dir);
let ws: proto::CurrentWorkspace = client
.call(proto::WORKSPACE_MOVE, proto::WorkspaceMoveParams { dir })
.await?;
println!("{} {}", ws.root.display(), describe_state(&ws));
Ok(0)
}
async fn workspace_remove(app: &'static str, version: &'static str, delete: bool) -> Result<i32> {
let Some(client) = connect_app(app, version).await? else {
return Ok(1);
};
let _: proto::Ack = client
.call(
proto::WORKSPACE_REMOVE,
proto::WorkspaceRemoveParams { delete },
)
.await?;
println!(
"{}",
if delete {
"removed and deleted"
} else {
"removed; the files stay"
}
);
Ok(0)
}
async fn workspace_show(app: &'static str, version: &'static str) -> Result<i32> {
let Some(client) = connect_app(app, version).await? else {
return Ok(1);
};
let mut out = String::new();
let code = render_workspace_show(Arc::new(client), app, &mut out).await?;
for line in out.lines() {
println!("{line}");
}
Ok(code)
}
#[doc(hidden)]
pub async fn render_workspace_show(
client: Arc<sapphire_ipc::Client>,
app: &str,
out: &mut String,
) -> Result<i32> {
let code = render_workspace(&client, out).await?;
let bridge = BridgeClient::relayed(client, sapphire_ipc::runtime_dir()?);
let workspaces = match bridge.workspaces().await {
Ok(workspaces) => workspaces,
Err(sapphire_ipc::Error::NotRunning(_)) => {
writeln!(out, "no sapphire-bridge is running")
.expect("writing to a String cannot fail");
return Ok(code);
}
Err(error) => return Err(error.into()),
};
let mine: Vec<_> = workspaces
.workspaces
.into_iter()
.filter(|w| w.app_name == app)
.collect();
if !mine.is_empty() {
writeln!(out).expect("writing to a String cannot fail");
writeln!(out, "in the workgroup:").expect("writing to a String cannot fail");
for workspace in mine {
writeln!(out, "{} {}", workspace.name, workspace.workspace_id)
.expect("writing to a String cannot fail");
}
}
Ok(code)
}
async fn run_status(endpoint: &Endpoint, app: &str, version: &str) -> Result<i32> {
let mut out = String::new();
let code = run_status_into(endpoint, app, version, &mut out).await?;
for line in out.lines() {
println!("{line}");
}
Ok(code)
}
async fn run_status_into(
endpoint: &Endpoint,
app: &str,
version: &str,
out: &mut String,
) -> Result<i32> {
let client_info = ClientInfo {
kind: "cli".to_owned(),
version: version.to_owned(),
api: proto::API_VERSION,
app_api: None,
pid: std::process::id(),
};
let Some((client, _)) = sapphire_ipc::connect_or_absent(endpoint, app, client_info).await?
else {
writeln!(out, "no {app} server is running").expect("writing to a String cannot fail");
return Ok(1);
};
let report: StatusReport = client
.call(
sapphire_backend::protocol::SERVER_INFO,
serde_json::json!({}),
)
.await?;
writeln!(out, "running: {}", report.running).expect("writing to a String cannot fail");
if let Some(version) = &report.version {
writeln!(out, "version: {version}").expect("writing to a String cannot fail");
}
if let Some(pid) = report.pid {
writeln!(out, "pid: {pid}").expect("writing to a String cannot fail");
}
if let Some(managed_by) = &report.managed_by {
writeln!(out, "managed_by: {managed_by:?}").expect("writing to a String cannot fail");
}
for row in &report.app {
writeln!(out, "{}: {}", row.name, row.value).expect("writing to a String cannot fail");
}
let update: Option<proto::UpdateStatus> = client
.call(proto::SERVER_UPDATE, serde_json::json!({}))
.await
.ok();
for line in describe_update(app, version, report.version.as_deref(), update.as_ref()) {
writeln!(out, "{line}").expect("writing to a String cannot fail");
}
Ok(0)
}
fn describe_update(
app: &str,
installed: &str,
running: Option<&str>,
update: Option<&proto::UpdateStatus>,
) -> Vec<String> {
let parse = |v: &str| semver::Version::parse(v).ok();
let installed_v = parse(installed);
let mut lines = Vec::new();
if let Some(update) = update.filter(|u| u.enabled) {
match (&update.latest, &update.last_error) {
(Some(latest), _) => {
let newer = match (parse(&latest.version), &installed_v) {
(Some(latest), Some(installed)) => latest > *installed,
_ => update.update_available,
};
if newer {
lines.push(format!(
"update: {} is available ({})",
latest.version, latest.url
));
} else {
lines.push(format!(
"update: up to date (latest release {})",
latest.version
));
}
}
(None, Some(error)) => lines.push(format!("update: could not check: {error}")),
(None, None) => lines.push("update: not checked yet".to_owned()),
}
}
if let (Some(running), Some(installed)) = (running.and_then(parse), installed_v)
&& installed > running
{
lines.push(format!(
"restart: needed: {installed} is installed but {running} is running; restart the {app} service"
));
}
lines
}
#[cfg(test)]
mod tests {
use super::*;
use clap::Parser;
#[derive(Parser)]
struct Probe {
#[command(subcommand)]
command: Command,
}
#[derive(Debug, clap::Subcommand)]
enum Command {
Greet,
#[command(flatten)]
Framework(FrameworkCommand),
}
#[derive(Parser)]
struct DesktopProbe {
#[command(subcommand)]
command: Option<Command>,
}
#[test]
fn a_desktop_binary_takes_the_same_verbs_or_none() {
let probe = DesktopProbe::try_parse_from(["app"]).unwrap();
assert!(probe.command.is_none());
let probe = DesktopProbe::try_parse_from(["app", "serve"]).unwrap();
assert!(matches!(
probe.command,
Some(Command::Framework(FrameworkCommand::Serve))
));
let probe = DesktopProbe::try_parse_from(["app", "greet"]).unwrap();
assert!(matches!(probe.command, Some(Command::Greet)));
assert!(Probe::try_parse_from(["app"]).is_err());
}
#[test]
fn app_and_framework_commands_parse_side_by_side() {
let probe = Probe::try_parse_from(["app", "greet"]).unwrap();
assert!(matches!(probe.command, Command::Greet));
let probe = Probe::try_parse_from(["app", "serve"]).unwrap();
assert!(matches!(
probe.command,
Command::Framework(FrameworkCommand::Serve)
));
let probe = Probe::try_parse_from(["app", "status"]).unwrap();
assert!(matches!(
probe.command,
Command::Framework(FrameworkCommand::Status)
));
}
#[cfg(feature = "mcp")]
#[test]
fn the_mcp_command_parses_beside_the_apps() {
let probe = Probe::try_parse_from(["app", "mcp"]).unwrap();
assert!(matches!(
probe.command,
Command::Framework(FrameworkCommand::Mcp)
));
}
#[test]
fn the_update_command_parses_with_and_without_the_bridge() {
let probe = Probe::try_parse_from(["app", "update", "--check", "-y"]).unwrap();
let Command::Framework(FrameworkCommand::Update(args)) = probe.command else {
panic!("not update");
};
assert!(args.update.check && args.update.yes && !args.no_bridge);
let probe = Probe::try_parse_from(["app", "update", "--no-bridge"]).unwrap();
let Command::Framework(FrameworkCommand::Update(args)) = probe.command else {
panic!("not update");
};
assert!(args.no_bridge);
}
#[test]
fn the_bridge_is_found_in_the_first_directory_of_path_that_has_it() {
let tmp = tempfile::tempdir().unwrap();
let (empty, first, second) = (
tmp.path().join("empty"),
tmp.path().join("first"),
tmp.path().join("second"),
);
let file = format!("sapphire-bridge{}", std::env::consts::EXE_SUFFIX);
for dir in [&empty, &first, &second] {
std::fs::create_dir(dir).unwrap();
}
std::fs::write(first.join(&file), b"").unwrap();
std::fs::write(second.join(&file), b"").unwrap();
let path = std::env::join_paths([&empty, &first, &second]).unwrap();
assert_eq!(
find_on_path("sapphire-bridge", Some(&path)),
Some(first.join(&file))
);
let path = std::env::join_paths([&empty]).unwrap();
assert_eq!(find_on_path("sapphire-bridge", Some(&path)), None);
assert_eq!(find_on_path("sapphire-bridge", None), None);
}
#[cfg(unix)]
fn script(dir: &std::path::Path, name: &str, body: &str) -> PathBuf {
use std::os::unix::fs::PermissionsExt;
let path = dir.join(name);
std::fs::write(&path, format!("#!/bin/sh\n{body}\n")).unwrap();
std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o755)).unwrap();
path
}
#[cfg(unix)]
#[tokio::test]
async fn the_bridge_runs_its_own_update_with_the_apps_flags() {
let tmp = tempfile::tempdir().unwrap();
let log = tmp.path().join("args");
let exe = script(
tmp.path(),
"bridge",
&format!(
r#"case "$*" in *--help*) exit 0;; esac; echo "$@" > {}; exit 1"#,
log.display()
),
);
let args = sapphire_framework_update::UpdateArgs {
check: true,
yes: true,
};
assert_eq!(run_bridge_update(&exe, &args).await.unwrap(), 1);
assert_eq!(
std::fs::read_to_string(&log).unwrap().trim(),
"update --check --yes"
);
}
#[cfg(unix)]
#[tokio::test]
async fn a_bridge_without_update_is_not_run() {
let tmp = tempfile::tempdir().unwrap();
let runs = tmp.path().join("runs");
let exe = script(
tmp.path(),
"bridge",
&format!(r#"echo "$*" >> {}; exit 2"#, runs.display()),
);
let code = run_bridge_update(&exe, &Default::default()).await.unwrap();
assert_eq!(code, 1);
assert_eq!(
std::fs::read_to_string(&runs).unwrap(),
"update --help\n",
"only the probe ran"
);
}
#[test]
fn the_service_subcommands_parse() {
for args in [
vec!["app", "service", "install"],
vec!["app", "service", "uninstall"],
vec!["app", "service", "status"],
] {
assert!(Probe::try_parse_from(&args).is_ok(), "{args:?}");
}
}
#[test]
fn the_workspace_commands_parse() {
for args in [
vec!["app", "workspace", "init"],
vec!["app", "workspace", "init", "papers"],
vec!["app", "workspace", "init", "--sync"],
vec!["app", "workspace", "show"],
vec!["app", "workspace", "select", "papers"],
vec!["app", "workspace", "select", "--sync"],
vec!["app", "workspace", "select", "papers", "--sync"],
vec!["app", "workspace", "sync", "enable"],
vec!["app", "workspace", "sync", "disable"],
vec!["app", "workspace", "sync", "status"],
vec![
"app",
"workspace",
"init",
"--sync",
"--remote-workspace=Ledger",
],
vec![
"app",
"workspace",
"init",
"papers",
"--sync",
"--remote-workspace",
"Ledger",
],
vec!["app", "workspace", "move", "../papers"],
vec!["app", "workspace", "remove"],
vec!["app", "workspace", "remove", "--delete"],
] {
assert!(Probe::try_parse_from(&args).is_ok(), "{args:?}");
}
}
#[test]
fn a_remote_workspace_needs_sync() {
let args = ["app", "workspace", "init", "--remote-workspace=Ledger"];
assert!(Probe::try_parse_from(args).is_err());
}
#[test]
fn bare_invocation_prints_the_help() {
#[derive(Parser)]
#[command(arg_required_else_help = true)]
struct Bare {
#[command(subcommand)]
command: Command,
}
let err = Bare::try_parse_from(["app"]).err().unwrap();
assert_eq!(
err.kind(),
clap::error::ErrorKind::DisplayHelpOnMissingArgumentOrSubcommand
);
}
}
#[cfg(test)]
mod status_tests {
use super::*;
use sapphire_workspace::AppContext;
static CTX: AppContext = AppContext::new("sapphire-statustest");
async fn wait_until_listening(endpoint: &Endpoint) {
let deadline = tokio::time::Instant::now() + std::time::Duration::from_secs(5);
while !sapphire_ipc::probe(endpoint).await.unwrap() {
assert!(
tokio::time::Instant::now() < deadline,
"the server never started listening"
);
tokio::time::sleep(std::time::Duration::from_millis(10)).await;
}
}
#[tokio::test]
async fn status_reports_no_server_when_none_is_running() {
let tmp = tempfile::tempdir().unwrap();
let endpoint = sapphire_ipc::Endpoint::in_dir("status-test", tmp.path().to_path_buf());
let code = run_status(&endpoint, "status-test", "0.0.0").await.unwrap();
assert_eq!(code, 1, "no server is a non-zero exit");
}
fn update(latest: Option<&str>, error: Option<&str>) -> proto::UpdateStatus {
proto::UpdateStatus {
enabled: true,
latest: latest.map(|version| proto::ReleaseInfo {
version: version.to_owned(),
url: format!("https://example.invalid/v{version}"),
}),
update_available: false,
last_error: error.map(str::to_owned),
}
}
#[test]
fn status_names_a_newer_release_and_nothing_when_up_to_date() {
let lines = describe_update(
"app",
"0.19.0",
Some("0.19.0"),
Some(&update(Some("0.20.0"), None)),
);
assert_eq!(
lines,
vec!["update: 0.20.0 is available (https://example.invalid/v0.20.0)"]
);
let lines = describe_update(
"app",
"0.19.0",
Some("0.19.0"),
Some(&update(Some("0.19.0"), None)),
);
assert_eq!(lines, vec!["update: up to date (latest release 0.19.0)"]);
}
#[test]
fn status_asks_for_a_restart_when_the_installed_server_is_newer_than_the_running_one() {
let lines = describe_update(
"app",
"0.20.0",
Some("0.19.0"),
Some(&update(Some("0.20.0"), None)),
);
assert_eq!(
lines,
vec![
"update: up to date (latest release 0.20.0)",
"restart: needed: 0.20.0 is installed but 0.19.0 is running; restart the app service",
]
);
let lines = describe_update("app", "0.20.0", Some("0.19.0"), None);
assert_eq!(lines.len(), 1);
assert!(lines[0].starts_with("restart: needed"));
}
#[test]
fn status_says_why_a_check_failed_and_nothing_when_checks_are_off() {
let lines = describe_update(
"app",
"0.19.0",
Some("0.19.0"),
Some(&update(None, Some("offline"))),
);
assert_eq!(lines, vec!["update: could not check: offline"]);
let off = proto::UpdateStatus::default();
assert!(describe_update("app", "0.19.0", Some("0.19.0"), Some(&off)).is_empty());
}
#[tokio::test(flavor = "multi_thread")]
async fn status_shows_a_newer_release_the_server_found() {
let tmp = tempfile::tempdir().unwrap();
let endpoint = sapphire_ipc::Endpoint::in_dir("status-test", tmp.path().to_path_buf());
let api = crate::update::stub::one_response(
"200 OK",
r#"[{"tag_name":"v0.20.0","html_url":"https://example.invalid/v0.20.0"}]"#,
)
.await;
let server = AppServer::new(&CTX, "0.19.0")
.endpoint(endpoint.clone())
.selection_file(tmp.path().join("workspace.toml"))
.releases(crate::ReleaseSource::github("o", "r").api_base(api));
let handle = tokio::spawn(async move { server.run().await });
wait_until_listening(&endpoint).await;
let deadline = tokio::time::Instant::now() + std::time::Duration::from_secs(10);
let out = loop {
let mut out = String::new();
run_status_into(&endpoint, CTX.app_name, "0.19.0", &mut out)
.await
.unwrap();
if !out.contains("not checked yet") {
break out;
}
assert!(
tokio::time::Instant::now() < deadline,
"never checked: {out}"
);
tokio::time::sleep(std::time::Duration::from_millis(50)).await;
};
assert!(
out.contains("update: 0.20.0 is available (https://example.invalid/v0.20.0)"),
"output was: {out}"
);
assert!(!out.contains("restart:"), "output was: {out}");
let (client, _) = sapphire_ipc::connect_or_absent(
&endpoint,
CTX.app_name,
sapphire_ipc::ClientInfo {
kind: "test".into(),
version: "0.19.0".into(),
api: sapphire_backend::protocol::API_VERSION,
app_api: None,
pid: std::process::id(),
},
)
.await
.unwrap()
.expect("the server is listening");
let _: serde_json::Value = client
.call(sapphire_ipc::SHUTDOWN_METHOD, serde_json::json!({}))
.await
.unwrap();
handle.await.unwrap().unwrap();
}
#[tokio::test(flavor = "multi_thread")]
async fn status_shows_the_extension_rows_of_a_running_server() {
let tmp = tempfile::tempdir().unwrap();
let endpoint = sapphire_ipc::Endpoint::in_dir("status-test", tmp.path().to_path_buf());
let server = AppServer::new(&CTX, "0.0.0")
.endpoint(endpoint.clone())
.selection_file(tmp.path().join("workspace.toml"))
.status_rows(std::sync::Arc::new(|| {
vec![StatusRow {
name: "sync".into(),
value: "on".into(),
}]
}));
let handle = tokio::spawn(async move { server.run().await });
wait_until_listening(&endpoint).await;
let mut out = String::new();
let code = run_status_into(&endpoint, CTX.app_name, "0.0.0", &mut out)
.await
.unwrap();
assert_eq!(code, 0);
assert!(out.contains("running: true"), "output was: {out}");
assert!(out.contains("sync: on"), "output was: {out}");
let (client, _) = sapphire_ipc::connect_or_absent(
&endpoint,
CTX.app_name,
sapphire_ipc::ClientInfo {
kind: "test".into(),
version: "0.0.0".into(),
api: sapphire_backend::protocol::API_VERSION,
app_api: None,
pid: std::process::id(),
},
)
.await
.unwrap()
.expect("the server is listening");
let _: serde_json::Value = client
.call(sapphire_ipc::SHUTDOWN_METHOD, serde_json::json!({}))
.await
.unwrap();
handle.await.unwrap().unwrap();
}
}
#[cfg(test)]
mod service_spec_tests {
use super::*;
use sapphire_workspace::AppContext;
static CTX: AppContext = AppContext::new("sapphire-servicetest");
#[test]
fn the_generated_spec_runs_the_server_not_the_cli() {
let spec = AppServer::new(&CTX, "0.0.0").service_spec();
assert_eq!(spec.args, vec!["serve".to_owned()]);
}
#[test]
fn the_generated_spec_retires_the_first_label() {
let spec = AppServer::new(&CTX, "0.0.0").service_spec();
assert_eq!(
spec.legacy_labels,
[format!("net.fireturtle.sapphire.{}", CTX.app_name)]
);
}
#[test]
fn the_generated_spec_names_this_application() {
let spec = AppServer::new(&CTX, "0.0.0").service_spec();
assert_eq!(spec.app_name, CTX.app_name);
}
#[test]
fn the_generated_spec_describes_the_server() {
let spec = AppServer::new(&CTX, "0.0.0").service_spec();
assert!(
spec.description.contains(CTX.app_name),
"the unit's description should name the application: {:?}",
spec.description
);
assert!(spec.description.contains("0.0.0"));
}
}