1use std::fmt::Write as _;
4use std::path::PathBuf;
5use std::sync::Arc;
6
7use corundum_framework_service::{Environment, ServiceCommand, SystemManager};
8use sapphire_backend::protocol as proto;
9use sapphire_bridge_client::BridgeClient;
10use sapphire_ipc::{ClientInfo, Endpoint};
11
12use crate::AppServer;
13use crate::error::{Error, Result};
14use crate::selection::SelectionFile;
15use crate::settings::{AppSettings, Settings};
16use sapphire_workspace::AppContext;
17
18mod config;
19
20pub use config::{AppConfigCommand, AppScopeFlags};
21
22pub use sapphire_backend::protocol::{StatusReport, StatusRow};
23
24#[derive(Debug, clap::Subcommand)]
48pub enum FrameworkCommand {
49 Serve,
51 Status,
53 #[command(subcommand)]
55 Service(ServiceCommand),
56 Update(AppUpdateArgs),
60 #[command(subcommand)]
63 Workspace(WorkspaceCommand),
64 #[command(subcommand)]
68 ApiKey(corundum_framework_keys::KeyCommand),
69 #[command(hide = true)]
71 ExternalDevice(LegacyExternalDevice),
72 #[command(subcommand)]
75 Config(AppConfigCommand),
76 #[cfg(feature = "mcp")]
79 Mcp,
80}
81
82impl FrameworkCommand {
83 pub async fn dispatch<A, F>(
99 self,
100 ctx: &'static AppContext,
101 owner: A,
102 build: F,
103 version: &'static str,
104 ) -> Result<i32>
105 where
106 A: AppSettings + Clone,
107 F: Fn(&Settings) -> AppServer,
108 {
109 let app = ctx.app_name;
110 let server = |owner: A| -> Result<AppServer> {
114 Ok(build(&settings_or_defaults(ctx, Arc::new(owner))?))
115 };
116 match self {
117 FrameworkCommand::Serve => {
118 crate::serve_restarting(ctx, owner, build).await?;
119 Ok(0)
120 }
121 FrameworkCommand::Status => {
122 let endpoint = Endpoint::for_app(app)?;
123 run_status(&endpoint, app, version).await
124 }
125 FrameworkCommand::Service(command) => {
126 let spec = server(owner)?.service_spec();
127 command
128 .run(&spec, &Environment::detect(), &SystemManager)
129 .map_err(Error::from)
130 }
131 FrameworkCommand::Update(args) => {
132 let server = server(owner)?;
133 let own = match server.release_source() {
134 Some(source) => {
135 sapphire_framework_update::run(&args.update, source, app, version)
136 .await
137 .map_err(Error::from)
138 }
139 None => {
140 println!("{app} does not say where its releases are");
141 Ok(1)
142 }
143 };
144 let bridge = if args.no_bridge {
147 0
148 } else {
149 update_bridge(&args.update).await?
150 };
151 Ok(own?.max(bridge))
152 }
153 FrameworkCommand::Config(command) => config::config(ctx, owner, command, version).await,
154 FrameworkCommand::Workspace(command) => command.dispatch(app, version).await,
155 FrameworkCommand::ApiKey(command) => {
156 api_key(ctx, &server(owner)?.profiles().list(), command)
157 }
158 FrameworkCommand::ExternalDevice(legacy) => {
159 eprintln!("warning: `external-device` is renamed to `api-key`");
160 if !legacy.app.is_empty() {
161 eprintln!(
162 "API keys are per workspace now, not per application: `--app` is not taken"
163 );
164 return Ok(2);
165 }
166 api_key(ctx, &server(owner)?.profiles().list(), legacy.command)
167 }
168 #[cfg(feature = "mcp")]
169 FrameworkCommand::Mcp => {
170 server(owner)?.serve_mcp_stdio(version).await?;
171 Ok(0)
172 }
173 }
174 }
175}
176
177fn settings_or_defaults(ctx: &AppContext, owner: Arc<dyn AppSettings>) -> Result<Settings> {
183 match Settings::load(ctx, Arc::clone(&owner)) {
184 Ok(settings) => Ok(settings),
185 Err(err) => {
186 let file = Settings::device_file(ctx)
187 .map_or_else(|| "the settings".to_owned(), |f| f.display().to_string());
188 eprintln!("warning: could not read {file} ({err}); going on with the default settings");
189 Settings::defaults(ctx, owner)
190 }
191 }
192}
193
194#[derive(Clone, Debug, Default, clap::Args)]
196pub struct AppUpdateArgs {
197 #[command(flatten)]
199 pub update: sapphire_framework_update::UpdateArgs,
200 #[arg(long)]
202 pub no_bridge: bool,
203}
204
205const BRIDGE_BINARY: &str = "sapphire-bridge";
207
208const BRIDGE_RELEASES: &str = "https://github.com/sapphire-turtle/sapphire-framework/releases";
210
211fn find_on_path(name: &str, path: Option<&std::ffi::OsStr>) -> Option<PathBuf> {
213 let file = format!("{name}{}", std::env::consts::EXE_SUFFIX);
214 std::env::split_paths(path?)
215 .map(|dir| dir.join(&file))
216 .find(|candidate| candidate.is_file())
217}
218
219pub async fn update_bridge(args: &sapphire_framework_update::UpdateArgs) -> Result<i32> {
223 match find_on_path(BRIDGE_BINARY, std::env::var_os("PATH").as_deref()) {
224 Some(exe) => run_bridge_update(&exe, args).await,
225 None => {
226 println!("{BRIDGE_BINARY} is not on PATH; not updating it");
227 Ok(0)
228 }
229 }
230}
231
232async fn run_bridge_update(
238 exe: &std::path::Path,
239 args: &sapphire_framework_update::UpdateArgs,
240) -> Result<i32> {
241 let knows_update = tokio::process::Command::new(exe)
243 .args(["update", "--help"])
244 .stdout(std::process::Stdio::null())
245 .stderr(std::process::Stdio::null())
246 .status()
247 .await?
248 .success();
249 if !knows_update {
250 println!(
251 "{} cannot update itself; install the newest from {BRIDGE_RELEASES}",
252 exe.display()
253 );
254 return Ok(1);
255 }
256 let mut command = tokio::process::Command::new(exe);
257 command.arg("update");
258 if args.check {
259 command.arg("--check");
260 }
261 if args.yes {
262 command.arg("--yes");
263 }
264 let status = command.status().await?;
266 Ok(status.code().unwrap_or(1))
267}
268
269#[derive(Debug, clap::Subcommand)]
276pub enum WorkspaceCommand {
277 Init {
279 dir: Option<PathBuf>,
281 #[arg(long)]
283 sync: bool,
284 #[arg(long, value_name = "NAME|ID", requires = "sync")]
287 remote_workspace: Option<String>,
288 },
289 Select {
291 dir: Option<PathBuf>,
293 #[arg(long)]
296 sync: bool,
297 },
298 #[command(subcommand)]
300 Sync(WorkspaceSyncCommand),
301 Show,
303 Move {
305 dir: PathBuf,
307 },
308 Remove {
310 #[arg(long)]
312 delete: bool,
313 },
314}
315
316impl WorkspaceCommand {
317 pub async fn dispatch(self, app: &'static str, version: &'static str) -> Result<i32> {
322 match self {
323 WorkspaceCommand::Init {
324 dir,
325 sync,
326 remote_workspace,
327 } => workspace_init(app, version, dir, sync, remote_workspace).await,
328 WorkspaceCommand::Select { dir, sync } => {
329 workspace_select(app, version, dir, sync).await
330 }
331 WorkspaceCommand::Sync(command) => workspace_sync(app, version, command).await,
332 WorkspaceCommand::Show => workspace_show(app, version).await,
333 WorkspaceCommand::Move { dir } => workspace_move(app, version, dir).await,
334 WorkspaceCommand::Remove { delete } => workspace_remove(app, version, delete).await,
335 }
336 }
337}
338
339#[derive(Debug, clap::Subcommand)]
341pub enum WorkspaceSyncCommand {
342 Enable,
344 Disable,
347 Status,
349}
350
351#[derive(Debug, clap::Args)]
353pub struct LegacyExternalDevice {
354 #[arg(long = "app", global = true, hide = true)]
356 app: Vec<String>,
357 #[command(subcommand)]
358 command: corundum_framework_keys::KeyCommand,
359}
360
361fn api_key(
365 ctx: &AppContext,
366 profiles: &[sapphire_framework_keys::Profile],
367 command: corundum_framework_keys::KeyCommand,
368) -> Result<i32> {
369 let Some(selection) = SelectionFile::for_app(ctx).load(ctx.app_name)? else {
370 eprintln!(
371 "{} serves no workspace yet: choose one with `{} workspace select <dir>`",
372 ctx.app_name, ctx.app_name
373 );
374 return Ok(1);
375 };
376 if !selection.root.join(format!(".{}", ctx.app_name)).is_dir() {
378 eprintln!(
379 "the workspace at {} is not reachable: bring it back, or choose another with `{} workspace select <dir>`",
380 selection.root.display(),
381 ctx.app_name
382 );
383 return Ok(1);
384 }
385 let run = sapphire_framework_keys::open_store(ctx.app_name, &selection.root)
386 .and_then(|mut store| command.run(&mut store, profiles));
387 match run {
388 Ok(code) => Ok(code),
389 Err(err) => {
390 eprintln!("{err}");
391 Ok(1)
392 }
393 }
394}
395
396async fn workspace_init(
409 app: &'static str,
410 version: &'static str,
411 dir: Option<PathBuf>,
412 sync: bool,
413 remote_workspace: Option<String>,
414) -> Result<i32> {
415 let endpoint = Endpoint::for_app(app)?;
416 let client_info = ClientInfo {
417 kind: "cli".to_owned(),
418 version: version.to_owned(),
419 api: proto::API_VERSION,
420 app_api: None,
421 pid: std::process::id(),
422 };
423 let Some((client, _)) = sapphire_ipc::connect_or_absent(&endpoint, app, client_info).await?
424 else {
425 println!("no {app} server is running");
426 return Ok(1);
427 };
428
429 let dir = std::env::current_dir()?.join(dir.unwrap_or_else(|| PathBuf::from(".")));
431 if let Some(selector) = remote_workspace {
432 let mapped: proto::SyncEnableResult = client
433 .call(
434 proto::SYNC_MAP,
435 proto::SyncMapParams {
436 workspace: selector.clone(),
437 dir: dir.clone(),
438 },
439 )
440 .await?;
441 println!(
442 "initialized {app} workspace in {} from {selector}",
443 dir.display()
444 );
445 println!(
446 "the {app} server now serves it, syncing as {}",
447 mapped.workspace_id
448 );
449 return Ok(0);
450 }
451 let result: proto::WorkspaceInitResult = client
452 .call(proto::WORKSPACE_INIT, proto::WorkspaceInitParams { dir })
453 .await?;
454 if result.created {
455 println!("initialized {app} workspace in {}", result.root.display());
456 } else {
457 println!(
458 "{} already exists (workspace {})",
459 result.root.display(),
460 result.workspace_id
461 );
462 }
463 println!("the {app} server now serves {}", result.root.display());
464
465 if sync {
466 enable_sync(&client).await?;
467 }
468 Ok(0)
469}
470
471async fn enable_sync(client: &sapphire_ipc::Client) -> Result<()> {
477 let enabled: proto::SyncEnableResult = client
478 .call(proto::SYNC_ENABLE, serde_json::json!({}))
479 .await?;
480 let status: proto::SyncStatusResult = client
483 .call(proto::SYNC_STATUS, serde_json::json!({}))
484 .await
485 .unwrap_or(proto::SyncStatusResult {
486 enabled: true,
487 workspace_id: Some(enabled.workspace_id),
488 ..proto::SyncStatusResult::not_synced()
489 });
490 println!(
491 "syncing as {} ({} peer{})",
492 enabled.workspace_id,
493 status.peers,
494 if status.peers == 1 { "" } else { "s" }
495 );
496 Ok(())
497}
498
499async fn workspace_sync(
501 app: &'static str,
502 version: &'static str,
503 command: WorkspaceSyncCommand,
504) -> Result<i32> {
505 let Some(client) = connect_app(app, version).await? else {
506 return Ok(1);
507 };
508 match command {
509 WorkspaceSyncCommand::Enable => enable_sync(&client).await?,
510 WorkspaceSyncCommand::Disable => {
511 let _: proto::Ack = client
512 .call(proto::SYNC_DISABLE, serde_json::json!({}))
513 .await?;
514 println!("sync is off for the {app} workspace on this host; it keeps its sync id");
515 }
516 WorkspaceSyncCommand::Status => {
517 let status: proto::SyncStatusResult = client
518 .call(proto::SYNC_STATUS, serde_json::json!({}))
519 .await?;
520 for line in describe_sync(&status) {
521 println!("{line}");
522 }
523 }
524 }
525 Ok(0)
526}
527
528fn describe_sync(status: &proto::SyncStatusResult) -> Vec<String> {
530 let mut lines = vec![format!(
531 "sync: {}",
532 if status.enabled { "on" } else { "off" }
533 )];
534 if let Some(id) = status.workspace_id {
535 lines.push(format!("workspace id: {id}"));
536 }
537 if status.enabled {
538 lines.push(format!(
539 "peers: {}{}",
540 status.peers,
541 if matches!(status.topology, proto::Topology::Star { .. }) {
542 " (star)"
543 } else {
544 ""
545 }
546 ));
547 lines.push(format!(
548 "bridge: {}",
549 if status.bridge_available {
550 "reachable"
551 } else {
552 "not reachable"
553 }
554 ));
555 }
556 if let Some(paused) = &status.paused {
557 lines.push(format!("paused: {paused}"));
558 }
559 if let Some(error) = &status.last_error {
560 lines.push(format!("last error: {error}"));
561 }
562 lines
563}
564
565pub async fn render_workspace(client: &sapphire_ipc::Client, out: &mut String) -> Result<i32> {
570 let current: proto::WorkspaceCurrentResult = client
571 .call(proto::WORKSPACE_CURRENT, serde_json::json!({}))
572 .await?;
573 let Some(ws) = current.workspace else {
574 writeln!(
575 out,
576 "no workspace yet; run `workspace init <dir>` or `workspace select <dir>`"
577 )
578 .expect("writing to a String cannot fail");
579 return Ok(1);
580 };
581 writeln!(out, "{} {}", ws.root.display(), describe_state(&ws))
582 .expect("writing to a String cannot fail");
583 Ok(0)
584}
585
586fn describe_state(ws: &proto::CurrentWorkspace) -> String {
588 let state = if !ws.reachable {
589 "unreachable"
590 } else if ws.sync.enabled {
591 "synced"
592 } else {
593 "not synced"
594 };
595 let star = if matches!(ws.sync.topology, proto::Topology::Star { .. }) {
596 " (star)"
597 } else {
598 ""
599 };
600 let pending = match &ws.sync.embedding {
601 Some(e) if e.pending > 0 => format!(", embedding {} pending", e.pending),
602 _ => String::new(),
603 };
604 format!("{state}{star}{pending}")
605}
606
607async fn connect_app(app: &str, version: &str) -> Result<Option<sapphire_ipc::Client>> {
609 let client = try_connect_app(app, version).await?;
610 if client.is_none() {
611 println!("no {app} server is running");
612 }
613 Ok(client)
614}
615
616async fn try_connect_app(app: &str, version: &str) -> Result<Option<sapphire_ipc::Client>> {
618 let endpoint = Endpoint::for_app(app)?;
619 let client_info = ClientInfo {
620 kind: "cli".to_owned(),
621 version: version.to_owned(),
622 api: proto::API_VERSION,
623 app_api: None,
624 pid: std::process::id(),
625 };
626 let client = sapphire_ipc::connect_or_absent(&endpoint, app, client_info).await?;
627 Ok(client.map(|(c, _)| c))
628}
629
630async fn workspace_select(
632 app: &'static str,
633 version: &'static str,
634 dir: Option<PathBuf>,
635 sync: bool,
636) -> Result<i32> {
637 let Some(client) = connect_app(app, version).await? else {
638 return Ok(1);
639 };
640 let dir = std::env::current_dir()?.join(dir.unwrap_or_else(|| PathBuf::from(".")));
642 let ws: proto::CurrentWorkspace = client
643 .call(
644 proto::WORKSPACE_SELECT,
645 proto::WorkspaceSelectParams { dir },
646 )
647 .await?;
648 println!("{} {}", ws.root.display(), describe_state(&ws));
649 if sync && !ws.sync.enabled {
651 enable_sync(&client).await?;
652 }
653 Ok(0)
654}
655
656async fn workspace_move(app: &'static str, version: &'static str, dir: PathBuf) -> Result<i32> {
658 let Some(client) = connect_app(app, version).await? else {
659 return Ok(1);
660 };
661 let dir = std::env::current_dir()?.join(dir);
663 let ws: proto::CurrentWorkspace = client
664 .call(proto::WORKSPACE_MOVE, proto::WorkspaceMoveParams { dir })
665 .await?;
666 println!("{} {}", ws.root.display(), describe_state(&ws));
667 Ok(0)
668}
669
670async fn workspace_remove(app: &'static str, version: &'static str, delete: bool) -> Result<i32> {
672 let Some(client) = connect_app(app, version).await? else {
673 return Ok(1);
674 };
675 let _: proto::Ack = client
676 .call(
677 proto::WORKSPACE_REMOVE,
678 proto::WorkspaceRemoveParams { delete },
679 )
680 .await?;
681 println!(
682 "{}",
683 if delete {
684 "removed and deleted"
685 } else {
686 "removed; the files stay"
687 }
688 );
689 Ok(0)
690}
691
692async fn workspace_show(app: &'static str, version: &'static str) -> Result<i32> {
698 let Some(client) = connect_app(app, version).await? else {
699 return Ok(1);
700 };
701 let mut out = String::new();
702 let code = render_workspace_show(Arc::new(client), app, &mut out).await?;
703 for line in out.lines() {
704 println!("{line}");
705 }
706 Ok(code)
707}
708
709#[doc(hidden)]
714pub async fn render_workspace_show(
715 client: Arc<sapphire_ipc::Client>,
716 app: &str,
717 out: &mut String,
718) -> Result<i32> {
719 let code = render_workspace(&client, out).await?;
720 let bridge = BridgeClient::relayed(client, sapphire_ipc::runtime_dir()?);
721 let workspaces = match bridge.workspaces().await {
722 Ok(workspaces) => workspaces,
723 Err(sapphire_ipc::Error::NotRunning(_)) => {
724 writeln!(out, "no sapphire-bridge is running")
725 .expect("writing to a String cannot fail");
726 return Ok(code);
727 }
728 Err(error) => return Err(error.into()),
729 };
730 let mine: Vec<_> = workspaces
731 .workspaces
732 .into_iter()
733 .filter(|w| w.app_name == app)
734 .collect();
735 if !mine.is_empty() {
736 writeln!(out).expect("writing to a String cannot fail");
737 writeln!(out, "in the workgroup:").expect("writing to a String cannot fail");
738 for workspace in mine {
739 writeln!(out, "{} {}", workspace.name, workspace.workspace_id)
740 .expect("writing to a String cannot fail");
741 }
742 }
743 Ok(code)
744}
745
746async fn run_status(endpoint: &Endpoint, app: &str, version: &str) -> Result<i32> {
755 let mut out = String::new();
756 let code = run_status_into(endpoint, app, version, &mut out).await?;
757 for line in out.lines() {
758 println!("{line}");
759 }
760 Ok(code)
761}
762
763async fn run_status_into(
766 endpoint: &Endpoint,
767 app: &str,
768 version: &str,
769 out: &mut String,
770) -> Result<i32> {
771 let client_info = ClientInfo {
772 kind: "cli".to_owned(),
773 version: version.to_owned(),
774 api: proto::API_VERSION,
775 app_api: None,
776 pid: std::process::id(),
777 };
778 let Some((client, _)) = sapphire_ipc::connect_or_absent(endpoint, app, client_info).await?
779 else {
780 writeln!(out, "no {app} server is running").expect("writing to a String cannot fail");
783 return Ok(1);
784 };
785 let report: StatusReport = client
786 .call(
787 sapphire_backend::protocol::SERVER_INFO,
788 serde_json::json!({}),
789 )
790 .await?;
791 writeln!(out, "running: {}", report.running).expect("writing to a String cannot fail");
792 if let Some(version) = &report.version {
793 writeln!(out, "version: {version}").expect("writing to a String cannot fail");
794 }
795 if let Some(pid) = report.pid {
796 writeln!(out, "pid: {pid}").expect("writing to a String cannot fail");
797 }
798 if let Some(managed_by) = &report.managed_by {
799 writeln!(out, "managed_by: {managed_by:?}").expect("writing to a String cannot fail");
800 }
801 for row in &report.app {
802 writeln!(out, "{}: {}", row.name, row.value).expect("writing to a String cannot fail");
803 }
804 let update: Option<proto::UpdateStatus> = client
807 .call(proto::SERVER_UPDATE, serde_json::json!({}))
808 .await
809 .ok();
810 for line in describe_update(app, version, report.version.as_deref(), update.as_ref()) {
811 writeln!(out, "{line}").expect("writing to a String cannot fail");
812 }
813 Ok(0)
814}
815
816fn describe_update(
823 app: &str,
824 installed: &str,
825 running: Option<&str>,
826 update: Option<&proto::UpdateStatus>,
827) -> Vec<String> {
828 let parse = |v: &str| semver::Version::parse(v).ok();
829 let installed_v = parse(installed);
830 let mut lines = Vec::new();
831 if let Some(update) = update.filter(|u| u.enabled) {
832 match (&update.latest, &update.last_error) {
833 (Some(latest), _) => {
834 let newer = match (parse(&latest.version), &installed_v) {
835 (Some(latest), Some(installed)) => latest > *installed,
836 _ => update.update_available,
837 };
838 if newer {
839 lines.push(format!(
840 "update: {} is available ({})",
841 latest.version, latest.url
842 ));
843 } else {
844 lines.push(format!(
845 "update: up to date (latest release {})",
846 latest.version
847 ));
848 }
849 }
850 (None, Some(error)) => lines.push(format!("update: could not check: {error}")),
851 (None, None) => lines.push("update: not checked yet".to_owned()),
852 }
853 }
854 if let (Some(running), Some(installed)) = (running.and_then(parse), installed_v)
855 && installed > running
856 {
857 lines.push(format!(
858 "restart: needed: {installed} is installed but {running} is running; restart the {app} service"
859 ));
860 }
861 lines
862}
863#[cfg(test)]
864mod tests {
865 use super::*;
866 use clap::Parser;
867
868 #[derive(Parser)]
877 struct Probe {
878 #[command(subcommand)]
879 command: Command,
880 }
881
882 #[derive(Debug, clap::Subcommand)]
883 enum Command {
884 Greet,
886 #[command(flatten)]
887 Framework(FrameworkCommand),
888 }
889
890 #[derive(Parser)]
892 struct DesktopProbe {
893 #[command(subcommand)]
894 command: Option<Command>,
895 }
896
897 #[test]
898 fn a_desktop_binary_takes_the_same_verbs_or_none() {
899 let probe = DesktopProbe::try_parse_from(["app"]).unwrap();
900 assert!(probe.command.is_none());
901 let probe = DesktopProbe::try_parse_from(["app", "serve"]).unwrap();
902 assert!(matches!(
903 probe.command,
904 Some(Command::Framework(FrameworkCommand::Serve))
905 ));
906 let probe = DesktopProbe::try_parse_from(["app", "greet"]).unwrap();
907 assert!(matches!(probe.command, Some(Command::Greet)));
908 assert!(Probe::try_parse_from(["app"]).is_err());
910 }
911
912 #[test]
913 fn app_and_framework_commands_parse_side_by_side() {
914 let probe = Probe::try_parse_from(["app", "greet"]).unwrap();
915 assert!(matches!(probe.command, Command::Greet));
916 let probe = Probe::try_parse_from(["app", "serve"]).unwrap();
917 assert!(matches!(
918 probe.command,
919 Command::Framework(FrameworkCommand::Serve)
920 ));
921 let probe = Probe::try_parse_from(["app", "status"]).unwrap();
922 assert!(matches!(
923 probe.command,
924 Command::Framework(FrameworkCommand::Status)
925 ));
926 }
927
928 #[cfg(feature = "mcp")]
929 #[test]
930 fn the_mcp_command_parses_beside_the_apps() {
931 let probe = Probe::try_parse_from(["app", "mcp"]).unwrap();
932 assert!(matches!(
933 probe.command,
934 Command::Framework(FrameworkCommand::Mcp)
935 ));
936 }
937
938 #[test]
939 fn the_update_command_parses_with_and_without_the_bridge() {
940 let probe = Probe::try_parse_from(["app", "update", "--check", "-y"]).unwrap();
941 let Command::Framework(FrameworkCommand::Update(args)) = probe.command else {
942 panic!("not update");
943 };
944 assert!(args.update.check && args.update.yes && !args.no_bridge);
945 let probe = Probe::try_parse_from(["app", "update", "--no-bridge"]).unwrap();
946 let Command::Framework(FrameworkCommand::Update(args)) = probe.command else {
947 panic!("not update");
948 };
949 assert!(args.no_bridge);
950 }
951
952 #[test]
953 fn the_bridge_is_found_in_the_first_directory_of_path_that_has_it() {
954 let tmp = tempfile::tempdir().unwrap();
955 let (empty, first, second) = (
956 tmp.path().join("empty"),
957 tmp.path().join("first"),
958 tmp.path().join("second"),
959 );
960 let file = format!("sapphire-bridge{}", std::env::consts::EXE_SUFFIX);
961 for dir in [&empty, &first, &second] {
962 std::fs::create_dir(dir).unwrap();
963 }
964 std::fs::write(first.join(&file), b"").unwrap();
965 std::fs::write(second.join(&file), b"").unwrap();
966 let path = std::env::join_paths([&empty, &first, &second]).unwrap();
967 assert_eq!(
968 find_on_path("sapphire-bridge", Some(&path)),
969 Some(first.join(&file))
970 );
971 let path = std::env::join_paths([&empty]).unwrap();
972 assert_eq!(find_on_path("sapphire-bridge", Some(&path)), None);
973 assert_eq!(find_on_path("sapphire-bridge", None), None);
974 }
975
976 #[cfg(unix)]
978 fn script(dir: &std::path::Path, name: &str, body: &str) -> PathBuf {
979 use std::os::unix::fs::PermissionsExt;
980 let path = dir.join(name);
981 std::fs::write(&path, format!("#!/bin/sh\n{body}\n")).unwrap();
982 std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o755)).unwrap();
983 path
984 }
985
986 #[cfg(unix)]
987 #[tokio::test]
988 async fn the_bridge_runs_its_own_update_with_the_apps_flags() {
989 let tmp = tempfile::tempdir().unwrap();
990 let log = tmp.path().join("args");
991 let exe = script(
994 tmp.path(),
995 "bridge",
996 &format!(
997 r#"case "$*" in *--help*) exit 0;; esac; echo "$@" > {}; exit 1"#,
998 log.display()
999 ),
1000 );
1001 let args = sapphire_framework_update::UpdateArgs {
1002 check: true,
1003 yes: true,
1004 };
1005 assert_eq!(run_bridge_update(&exe, &args).await.unwrap(), 1);
1006 assert_eq!(
1007 std::fs::read_to_string(&log).unwrap().trim(),
1008 "update --check --yes"
1009 );
1010 }
1011
1012 #[cfg(unix)]
1013 #[tokio::test]
1014 async fn a_bridge_without_update_is_not_run() {
1015 let tmp = tempfile::tempdir().unwrap();
1016 let runs = tmp.path().join("runs");
1017 let exe = script(
1019 tmp.path(),
1020 "bridge",
1021 &format!(r#"echo "$*" >> {}; exit 2"#, runs.display()),
1022 );
1023 let code = run_bridge_update(&exe, &Default::default()).await.unwrap();
1024 assert_eq!(code, 1);
1025 assert_eq!(
1026 std::fs::read_to_string(&runs).unwrap(),
1027 "update --help\n",
1028 "only the probe ran"
1029 );
1030 }
1031
1032 #[test]
1033 fn the_service_subcommands_parse() {
1034 for args in [
1035 vec!["app", "service", "install"],
1036 vec!["app", "service", "uninstall"],
1037 vec!["app", "service", "status"],
1038 ] {
1039 assert!(Probe::try_parse_from(&args).is_ok(), "{args:?}");
1040 }
1041 }
1042
1043 #[test]
1044 fn the_workspace_commands_parse() {
1045 for args in [
1046 vec!["app", "workspace", "init"],
1047 vec!["app", "workspace", "init", "papers"],
1048 vec!["app", "workspace", "init", "--sync"],
1049 vec!["app", "workspace", "show"],
1050 vec!["app", "workspace", "select", "papers"],
1051 vec!["app", "workspace", "select", "--sync"],
1052 vec!["app", "workspace", "select", "papers", "--sync"],
1053 vec!["app", "workspace", "sync", "enable"],
1054 vec!["app", "workspace", "sync", "disable"],
1055 vec!["app", "workspace", "sync", "status"],
1056 vec![
1057 "app",
1058 "workspace",
1059 "init",
1060 "--sync",
1061 "--remote-workspace=Ledger",
1062 ],
1063 vec![
1064 "app",
1065 "workspace",
1066 "init",
1067 "papers",
1068 "--sync",
1069 "--remote-workspace",
1070 "Ledger",
1071 ],
1072 vec!["app", "workspace", "move", "../papers"],
1073 vec!["app", "workspace", "remove"],
1074 vec!["app", "workspace", "remove", "--delete"],
1075 ] {
1076 assert!(Probe::try_parse_from(&args).is_ok(), "{args:?}");
1077 }
1078 }
1079
1080 #[test]
1081 fn a_remote_workspace_needs_sync() {
1082 let args = ["app", "workspace", "init", "--remote-workspace=Ledger"];
1083 assert!(Probe::try_parse_from(args).is_err());
1084 }
1085
1086 #[test]
1087 fn bare_invocation_prints_the_help() {
1088 #[derive(Parser)]
1092 #[command(arg_required_else_help = true)]
1093 struct Bare {
1094 #[command(subcommand)]
1095 command: Command,
1096 }
1097 let err = Bare::try_parse_from(["app"]).err().unwrap();
1098 assert_eq!(
1099 err.kind(),
1100 clap::error::ErrorKind::DisplayHelpOnMissingArgumentOrSubcommand
1101 );
1102 }
1103}
1104
1105#[cfg(test)]
1106mod status_tests {
1107 use super::*;
1108 use sapphire_workspace::AppContext;
1109
1110 static CTX: AppContext = AppContext::new("sapphire-statustest");
1111
1112 async fn wait_until_listening(endpoint: &Endpoint) {
1118 let deadline = tokio::time::Instant::now() + std::time::Duration::from_secs(5);
1119 while !sapphire_ipc::probe(endpoint).await.unwrap() {
1120 assert!(
1121 tokio::time::Instant::now() < deadline,
1122 "the server never started listening"
1123 );
1124 tokio::time::sleep(std::time::Duration::from_millis(10)).await;
1125 }
1126 }
1127
1128 #[tokio::test]
1129 async fn status_reports_no_server_when_none_is_running() {
1130 let tmp = tempfile::tempdir().unwrap();
1131 let endpoint = sapphire_ipc::Endpoint::in_dir("status-test", tmp.path().to_path_buf());
1132 let code = run_status(&endpoint, "status-test", "0.0.0").await.unwrap();
1133 assert_eq!(code, 1, "no server is a non-zero exit");
1134 }
1135
1136 fn update(latest: Option<&str>, error: Option<&str>) -> proto::UpdateStatus {
1137 proto::UpdateStatus {
1138 enabled: true,
1139 latest: latest.map(|version| proto::ReleaseInfo {
1140 version: version.to_owned(),
1141 url: format!("https://example.invalid/v{version}"),
1142 }),
1143 update_available: false,
1144 last_error: error.map(str::to_owned),
1145 }
1146 }
1147
1148 #[test]
1149 fn status_names_a_newer_release_and_nothing_when_up_to_date() {
1150 let lines = describe_update(
1151 "app",
1152 "0.19.0",
1153 Some("0.19.0"),
1154 Some(&update(Some("0.20.0"), None)),
1155 );
1156 assert_eq!(
1157 lines,
1158 vec!["update: 0.20.0 is available (https://example.invalid/v0.20.0)"]
1159 );
1160 let lines = describe_update(
1161 "app",
1162 "0.19.0",
1163 Some("0.19.0"),
1164 Some(&update(Some("0.19.0"), None)),
1165 );
1166 assert_eq!(lines, vec!["update: up to date (latest release 0.19.0)"]);
1167 }
1168
1169 #[test]
1170 fn status_asks_for_a_restart_when_the_installed_server_is_newer_than_the_running_one() {
1171 let lines = describe_update(
1174 "app",
1175 "0.20.0",
1176 Some("0.19.0"),
1177 Some(&update(Some("0.20.0"), None)),
1178 );
1179 assert_eq!(
1180 lines,
1181 vec![
1182 "update: up to date (latest release 0.20.0)",
1183 "restart: needed: 0.20.0 is installed but 0.19.0 is running; restart the app service",
1184 ]
1185 );
1186 let lines = describe_update("app", "0.20.0", Some("0.19.0"), None);
1188 assert_eq!(lines.len(), 1);
1189 assert!(lines[0].starts_with("restart: needed"));
1190 }
1191
1192 #[test]
1193 fn status_says_why_a_check_failed_and_nothing_when_checks_are_off() {
1194 let lines = describe_update(
1195 "app",
1196 "0.19.0",
1197 Some("0.19.0"),
1198 Some(&update(None, Some("offline"))),
1199 );
1200 assert_eq!(lines, vec!["update: could not check: offline"]);
1201 let off = proto::UpdateStatus::default();
1202 assert!(describe_update("app", "0.19.0", Some("0.19.0"), Some(&off)).is_empty());
1203 }
1204
1205 #[tokio::test(flavor = "multi_thread")]
1206 async fn status_shows_a_newer_release_the_server_found() {
1207 let tmp = tempfile::tempdir().unwrap();
1208 let endpoint = sapphire_ipc::Endpoint::in_dir("status-test", tmp.path().to_path_buf());
1209 let api = crate::update::stub::one_response(
1210 "200 OK",
1211 r#"[{"tag_name":"v0.20.0","html_url":"https://example.invalid/v0.20.0"}]"#,
1212 )
1213 .await;
1214 let server = AppServer::new(&CTX, "0.19.0")
1215 .endpoint(endpoint.clone())
1216 .selection_file(tmp.path().join("workspace.toml"))
1217 .releases(crate::ReleaseSource::github("o", "r").api_base(api));
1218 let handle = tokio::spawn(async move { server.run().await });
1219 wait_until_listening(&endpoint).await;
1220
1221 let deadline = tokio::time::Instant::now() + std::time::Duration::from_secs(10);
1223 let out = loop {
1224 let mut out = String::new();
1225 run_status_into(&endpoint, CTX.app_name, "0.19.0", &mut out)
1226 .await
1227 .unwrap();
1228 if !out.contains("not checked yet") {
1229 break out;
1230 }
1231 assert!(
1232 tokio::time::Instant::now() < deadline,
1233 "never checked: {out}"
1234 );
1235 tokio::time::sleep(std::time::Duration::from_millis(50)).await;
1236 };
1237 assert!(
1238 out.contains("update: 0.20.0 is available (https://example.invalid/v0.20.0)"),
1239 "output was: {out}"
1240 );
1241 assert!(!out.contains("restart:"), "output was: {out}");
1242
1243 let (client, _) = sapphire_ipc::connect_or_absent(
1244 &endpoint,
1245 CTX.app_name,
1246 sapphire_ipc::ClientInfo {
1247 kind: "test".into(),
1248 version: "0.19.0".into(),
1249 api: sapphire_backend::protocol::API_VERSION,
1250 app_api: None,
1251 pid: std::process::id(),
1252 },
1253 )
1254 .await
1255 .unwrap()
1256 .expect("the server is listening");
1257 let _: serde_json::Value = client
1258 .call(sapphire_ipc::SHUTDOWN_METHOD, serde_json::json!({}))
1259 .await
1260 .unwrap();
1261 handle.await.unwrap().unwrap();
1262 }
1263
1264 #[tokio::test(flavor = "multi_thread")]
1265 async fn status_shows_the_extension_rows_of_a_running_server() {
1266 let tmp = tempfile::tempdir().unwrap();
1267 let endpoint = sapphire_ipc::Endpoint::in_dir("status-test", tmp.path().to_path_buf());
1268 let server = AppServer::new(&CTX, "0.0.0")
1269 .endpoint(endpoint.clone())
1270 .selection_file(tmp.path().join("workspace.toml"))
1272 .status_rows(std::sync::Arc::new(|| {
1273 vec![StatusRow {
1274 name: "sync".into(),
1275 value: "on".into(),
1276 }]
1277 }));
1278 let handle = tokio::spawn(async move { server.run().await });
1279 wait_until_listening(&endpoint).await;
1280
1281 let mut out = String::new();
1284 let code = run_status_into(&endpoint, CTX.app_name, "0.0.0", &mut out)
1285 .await
1286 .unwrap();
1287 assert_eq!(code, 0);
1288 assert!(out.contains("running: true"), "output was: {out}");
1289 assert!(out.contains("sync: on"), "output was: {out}");
1290
1291 let (client, _) = sapphire_ipc::connect_or_absent(
1292 &endpoint,
1293 CTX.app_name,
1294 sapphire_ipc::ClientInfo {
1295 kind: "test".into(),
1296 version: "0.0.0".into(),
1297 api: sapphire_backend::protocol::API_VERSION,
1298 app_api: None,
1299 pid: std::process::id(),
1300 },
1301 )
1302 .await
1303 .unwrap()
1304 .expect("the server is listening");
1305 let _: serde_json::Value = client
1306 .call(sapphire_ipc::SHUTDOWN_METHOD, serde_json::json!({}))
1307 .await
1308 .unwrap();
1309 handle.await.unwrap().unwrap();
1310 }
1311}
1312
1313#[cfg(test)]
1314mod service_spec_tests {
1315 use super::*;
1316 use sapphire_workspace::AppContext;
1317
1318 static CTX: AppContext = AppContext::new("sapphire-servicetest");
1319
1320 #[test]
1321 fn the_generated_spec_runs_the_server_not_the_cli() {
1322 let spec = AppServer::new(&CTX, "0.0.0").service_spec();
1326 assert_eq!(spec.args, vec!["serve".to_owned()]);
1327 }
1328
1329 #[test]
1330 fn the_generated_spec_retires_the_first_label() {
1331 let spec = AppServer::new(&CTX, "0.0.0").service_spec();
1334 assert_eq!(
1335 spec.legacy_labels,
1336 [format!("net.fireturtle.sapphire.{}", CTX.app_name)]
1337 );
1338 }
1339
1340 #[test]
1341 fn the_generated_spec_names_this_application() {
1342 let spec = AppServer::new(&CTX, "0.0.0").service_spec();
1343 assert_eq!(spec.app_name, CTX.app_name);
1344 }
1345
1346 #[test]
1347 fn the_generated_spec_describes_the_server() {
1348 let spec = AppServer::new(&CTX, "0.0.0").service_spec();
1349 assert!(
1350 spec.description.contains(CTX.app_name),
1351 "the unit's description should name the application: {:?}",
1352 spec.description
1353 );
1354 assert!(spec.description.contains("0.0.0"));
1355 }
1356}