1#![warn(missing_docs)]
23
24use std::path::PathBuf;
25use std::sync::Arc;
26use std::time::Duration;
27
28use sapphire_backend::protocol as proto;
29use sapphire_framework_service::ServiceSpec;
30use sapphire_ipc::{Endpoint, ManagedBy, Router, ServerInfo, serve};
31use sapphire_workspace::AppContext;
32
33const SERVE_GRACE: Duration = Duration::from_secs(2);
40
41mod command;
42mod config;
43mod current;
44mod error;
45mod events;
46mod handlers;
47mod host;
48#[cfg(feature = "http")]
49mod http;
50mod selection;
51pub mod sync;
52#[cfg(test)]
53mod test_support;
54
55pub use command::{
56 DeviceCommand, FrameworkCommand, StatusReport, StatusRow, WorkgroupCommand, WorkspaceCommand,
57 render_workspace,
58};
59pub use config::{HttpConfig, McpConfig, SERVER_CONFIG_FILE, ServerConfig};
60pub use current::Current;
61pub use error::{Error, Result};
62pub use events::subscribe_method;
63pub use handlers::workspace_router;
64pub use host::WorkspaceHost;
65pub use selection::{SELECTION_FILE, Selection, SelectionFile};
66pub use sync::{BackfillTiming, SyncRuntime, SyncStatus, sync_router};
67
68#[cfg(feature = "mcp")]
70pub use sapphire_framework_mcp as mcp;
71
72pub struct AppServer {
74 ctx: &'static AppContext,
75 version: &'static str,
76 endpoint: Option<Endpoint>,
77 selection_file: Option<PathBuf>,
79 host: Arc<WorkspaceHost>,
80 sync: Option<Arc<SyncRuntime>>,
81 extend: Option<Box<dyn FnOnce(Router) -> Router + Send>>,
82 status_rows: Option<Arc<dyn Fn() -> Vec<StatusRow> + Send + Sync>>,
85 app_api: Option<u32>,
87 config: Option<ServerConfig>,
89 #[cfg(feature = "http")]
91 http_listen: Option<std::net::SocketAddr>,
92 #[cfg(feature = "http")]
94 http_routes: Option<axum::Router>,
95 #[cfg(feature = "http")]
97 http_auth: Option<sapphire_framework_keys::AuthConfig>,
98 #[cfg(feature = "mcp")]
100 mcp: sapphire_framework_mcp::McpService,
101}
102
103#[cfg(unix)]
112struct Sigterm(tokio::signal::unix::Signal);
113
114#[cfg(not(unix))]
116struct Sigterm;
117
118#[cfg(unix)]
119impl Sigterm {
120 fn new() -> Result<Self> {
126 Ok(Self(tokio::signal::unix::signal(
127 tokio::signal::unix::SignalKind::terminate(),
128 )?))
129 }
130
131 async fn recv(&mut self) {
135 self.0.recv().await;
136 }
137}
138
139#[cfg(not(unix))]
140impl Sigterm {
141 async fn recv(&mut self) {
146 std::future::pending::<()>().await
147 }
148}
149
150impl AppServer {
151 pub fn new(ctx: &'static AppContext, version: &'static str) -> AppServer {
153 AppServer {
154 ctx,
155 version,
156 endpoint: None,
157 selection_file: None,
158 host: Arc::new(WorkspaceHost::new(ctx)),
159 sync: None,
160 extend: None,
161 status_rows: None,
162 app_api: None,
163 config: None,
164 #[cfg(feature = "http")]
165 http_listen: None,
166 #[cfg(feature = "http")]
167 http_routes: None,
168 #[cfg(feature = "http")]
169 http_auth: None,
170 #[cfg(feature = "mcp")]
171 mcp: sapphire_framework_mcp::McpService::framework(),
172 }
173 }
174
175 pub fn app_name(&self) -> &'static str {
180 self.ctx.app_name
181 }
182
183 pub fn endpoint(mut self, endpoint: Endpoint) -> AppServer {
185 self.endpoint = Some(endpoint);
186 self
187 }
188
189 pub fn app_api(mut self, version: u32) -> AppServer {
194 self.app_api = Some(version);
195 self
196 }
197
198 pub fn config(mut self, config: ServerConfig) -> AppServer {
200 self.config = Some(config);
201 self
202 }
203
204 #[cfg(feature = "http")]
208 pub fn http_listen(mut self, addr: std::net::SocketAddr) -> AppServer {
209 self.http_listen = Some(addr);
210 self
211 }
212
213 #[cfg(feature = "http")]
217 pub fn http(mut self, routes: axum::Router) -> AppServer {
218 self.http_routes = Some(routes);
219 self
220 }
221
222 #[cfg(feature = "http")]
224 pub fn http_auth(mut self, auth: sapphire_framework_keys::AuthConfig) -> AppServer {
225 self.http_auth = Some(auth);
226 self
227 }
228
229 #[cfg(feature = "mcp")]
233 pub fn mcp(mut self, service: sapphire_framework_mcp::McpService) -> AppServer {
234 self.mcp = service;
235 self
236 }
237
238 #[cfg(feature = "mcp")]
244 pub async fn serve_mcp_stdio(self, version: &'static str) -> Result<()> {
245 let endpoint = match self.endpoint {
246 Some(e) => e,
247 None => Endpoint::for_app(self.ctx.app_name)?,
248 };
249 let ctx = sapphire_framework_mcp::ToolContext::dial(
250 self.ctx.app_name,
251 version,
252 self.app_api,
253 endpoint,
254 );
255 self.mcp
256 .serve_stdio(ctx)
257 .await
258 .map_err(|e| Error::Mcp(e.to_string()))
259 }
260
261 pub fn selection_file(mut self, path: PathBuf) -> AppServer {
264 self.selection_file = Some(path);
265 self
266 }
267
268 pub fn sync(mut self, runtime: Arc<SyncRuntime>) -> AppServer {
275 runtime.set_host(Arc::clone(&self.host));
278 self.sync = Some(runtime);
279 self
280 }
281
282 pub fn status_rows(mut self, rows: Arc<dyn Fn() -> Vec<StatusRow> + Send + Sync>) -> AppServer {
289 self.status_rows = Some(rows);
290 self
291 }
292
293 pub fn service_spec(&self) -> ServiceSpec {
301 ServiceSpec {
302 app_name: self.ctx.app_name,
303 description: format!("{} server {}", self.ctx.app_name, self.version),
304 args: vec!["serve".to_owned()],
305 post_install: None,
306 }
307 }
308
309 pub fn extend(mut self, f: impl FnOnce(Router) -> Router + Send + 'static) -> AppServer {
311 self.extend = Some(Box::new(f));
312 self
313 }
314
315 pub fn host(&self) -> &Arc<WorkspaceHost> {
318 &self.host
319 }
320
321 pub async fn run(self) -> Result<()> {
323 let AppServer {
324 ctx,
325 version,
326 endpoint,
327 selection_file,
328 host,
329 sync,
330 extend,
331 status_rows,
332 app_api,
333 config,
334 #[cfg(feature = "http")]
335 http_listen,
336 #[cfg(feature = "http")]
337 http_routes,
338 #[cfg(feature = "http")]
339 http_auth,
340 #[cfg(feature = "mcp")]
341 mcp,
342 } = self;
343
344 let endpoint = match endpoint {
345 Some(e) => e,
346 None => Endpoint::for_app(ctx.app_name)?,
347 };
348 let info = ServerInfo {
352 version: version.to_owned(),
353 api: proto::API_VERSION,
354 app_api,
355 pid: std::process::id(),
356 managed_by: ManagedBy::Service,
357 };
358
359 let _log = sapphire_workspace::logging::install(ctx)?;
364
365 let config = match config {
366 Some(config) => config,
367 None => ServerConfig::load_for_app(ctx)?,
368 };
369 #[cfg(not(feature = "mcp"))]
370 if config.mcp.http {
371 tracing::warn!(
372 "server.toml turns MCP over HTTP on, but this build of {} has no MCP",
373 ctx.app_name
374 );
375 }
376
377 let (stop_tx, mut stop_rx) = tokio::sync::watch::channel(false);
378
379 let file = match selection_file {
380 Some(path) => SelectionFile::at(path),
381 None => SelectionFile::for_app(ctx),
382 };
383 let current = Arc::new(Current::new(ctx, Arc::clone(&host), sync.clone(), file));
384 let restoring = current.restore().await;
386
387 let mut router = subscribe_method(
388 Arc::clone(&host),
389 current::current_methods(Arc::clone(¤t), workspace_router(Arc::clone(¤t))),
390 );
391 if sync.is_some() {
392 router = sync_router(Arc::clone(¤t), router);
396 }
397 router = router
401 .method(proto::SERVER_INFO, {
402 let info = info.clone();
403 let status_rows = status_rows.clone();
404 move |_| {
405 let info = info.clone();
406 let status_rows = status_rows.clone();
407 async move {
408 let app = status_rows.as_ref().map(|rows| rows()).unwrap_or_default();
409 let report = StatusReport {
410 running: true,
411 version: Some(info.version),
412 pid: Some(info.pid),
413 managed_by: Some(match info.managed_by {
414 ManagedBy::Service => proto::ManagedBy::Service,
415 ManagedBy::Spawned => proto::ManagedBy::Spawned,
416 }),
417 app,
418 };
419 serde_json::to_value(report)
420 .map_err(|e| sapphire_ipc::RpcError::internal(e.to_string()))
421 }
422 }
423 })
424 .method(sapphire_ipc::SHUTDOWN_METHOD, {
425 let stop_tx = stop_tx.clone();
426 move |_| {
427 let stop_tx = stop_tx.clone();
428 async move {
429 let _ = stop_tx.send(true);
430 serde_json::to_value(proto::Ack {})
431 .map_err(|e| sapphire_ipc::RpcError::internal(e.to_string()))
432 }
433 }
434 });
435 if let Some(extend) = extend {
436 router = extend(router);
437 }
438 let router = Arc::new(router);
439
440 #[cfg(unix)]
445 let mut sigterm = Sigterm::new()?;
446 #[cfg(not(unix))]
447 let mut sigterm = Sigterm;
448
449 #[cfg(unix)]
450 let listener = sapphire_ipc::bind(&endpoint).await?;
451 #[cfg(windows)]
452 let mut listener = sapphire_ipc::bind(&endpoint)?;
453
454 let mut connections = tokio::task::JoinSet::new();
455
456 #[cfg(feature = "http")]
461 let http_stop = tokio_util::sync::CancellationToken::new();
462 #[cfg(feature = "http")]
463 let _http = {
464 let mut routes = http_routes;
465 #[cfg(feature = "mcp")]
466 if config.mcp.http {
467 let (ours, theirs) = sapphire_ipc::Connection::pair();
468 {
469 let router = Arc::clone(&router);
470 let info = info.clone();
471 let app = ctx.app_name;
472 connections.spawn(async move {
473 let _ = serve(theirs, router, app, info).await;
474 });
475 }
476 let client_info = sapphire_ipc::ClientInfo {
477 kind: sapphire_framework_mcp::CLIENT_KIND.to_owned(),
478 version: version.to_owned(),
479 api: proto::API_VERSION,
480 app_api,
481 pid: std::process::id(),
482 };
483 let (client, _) =
484 sapphire_ipc::Client::handshake(ours, ctx.app_name, client_info).await?;
485 let tools = sapphire_framework_mcp::ToolContext::connected(
486 ctx.app_name,
487 version,
488 Arc::new(client),
489 );
490 let mcp_routes =
491 mcp.http_router(tools, &config.http.allowed_hosts, http_stop.child_token());
492 routes = Some(match routes {
493 Some(routes) => routes.merge(mcp_routes),
494 None => mcp_routes,
495 });
496 }
497 match (routes, config.http.listen.or(http_listen)) {
498 (None, _) => None,
499 (Some(_), None) => {
500 tracing::error!(
501 "nothing to bind HTTP to: set `[http] listen` in {SERVER_CONFIG_FILE}"
502 );
503 None
504 }
505 (Some(routes), Some(addr)) => {
506 let auth = http_auth.unwrap_or_else(|| {
507 sapphire_framework_keys::AuthConfig::new(Arc::new(
508 sapphire_framework_keys::BridgeVerifier::new(ctx.app_name, version),
509 ))
510 });
511 http::start(addr, routes, auth, http_stop.clone()).await
512 }
513 }
514 };
515
516 let _sync_tasks = match &sync {
522 Some(runtime) => {
523 let driver = Arc::clone(runtime);
524 let announcements = tokio::spawn(async move {
525 if let Err(err) = driver.run().await {
526 tracing::warn!("the bridge announcement loop ended: {err}");
527 }
528 });
529 let changing = Arc::clone(runtime);
530 let watching = tokio::spawn(async move {
531 if let Err(err) = changing.watch_changes().await {
532 tracing::warn!("the file watcher ended: {err}");
533 }
534 });
535 let dialling = Arc::clone(runtime);
538 let dialling = tokio::spawn(async move {
539 if let Err(err) = dialling.dial_loop().await {
540 tracing::warn!("the live dial loop ended: {err}");
541 }
542 });
543 Some((announcements, watching, dialling))
544 }
545 None => None,
546 };
547
548 loop {
549 tokio::select! {
550 changed = stop_rx.changed() => {
551 if changed.is_err() || *stop_rx.borrow() {
552 break;
553 }
554 }
555 _ = tokio::signal::ctrl_c() => {
556 tracing::info!("interrupted; shutting down");
557 break;
558 }
559 _ = sigterm.recv() => {
560 tracing::info!("terminated; shutting down");
561 break;
562 }
563 accepted = listener.accept() => {
564 let conn = accepted?;
565 let router = Arc::clone(&router);
566 let app = ctx.app_name;
567 let info = info.clone();
568 connections.spawn(async move {
569 let _ = serve(conn, router, app, info).await;
570 });
571 }
572 }
573 }
574
575 if let Some(restoring) = restoring {
576 restoring.abort();
577 }
578 #[cfg(feature = "http")]
581 {
582 http_stop.cancel();
583 if let Some((_, mut task)) = _http
584 && tokio::time::timeout(SERVE_GRACE, &mut task).await.is_err()
585 {
586 tracing::debug!("the HTTP listener did not stop in time");
587 task.abort();
588 }
589 }
590 if let Some((announcements, watching, dialling)) = _sync_tasks {
591 announcements.abort();
592 watching.abort();
593 dialling.abort();
594 }
595 if let Some(runtime) = &sync {
596 runtime.stop_dials().await;
598 runtime.drop_connections().await;
603 }
604 host.close();
605 drop(listener); let _ = tokio::time::timeout(SERVE_GRACE, async {
615 while connections.join_next().await.is_some() {}
616 })
617 .await;
618 connections.abort_all();
619 while connections.join_next().await.is_some() {}
620 Ok(())
621 }
622}
623
624#[cfg(test)]
625mod tests {
626 use super::*;
627 use sapphire_ipc::{ClientInfo, Endpoint, ManagedBy};
628 use sapphire_workspace::{AppContext, AppKind};
629 use std::ffi::OsString;
630
631 use crate::test_support;
632
633 static CTX: AppContext = AppContext::new("sapphire-appservertest");
634
635 const DIR_VARS: [&str; 3] = [
637 "SAPPHIRE_APPSERVERTEST_CACHE_DIR",
638 "SAPPHIRE_APPSERVERTEST_DATA_DIR",
639 "SAPPHIRE_APPSERVERTEST_CONFIG_DIR",
640 ];
641
642 fn client_info() -> ClientInfo {
643 ClientInfo {
644 kind: "test".into(),
645 version: "0.0.0".into(),
646 api: sapphire_backend::protocol::API_VERSION,
647 app_api: None,
648 pid: std::process::id(),
649 }
650 }
651
652 struct EnvGuard {
658 previous: [Option<OsString>; 3],
659 _lock: std::sync::MutexGuard<'static, ()>,
660 }
661
662 impl EnvGuard {
663 fn set(lock: std::sync::MutexGuard<'static, ()>, tmp: &std::path::Path) -> EnvGuard {
665 let previous = DIR_VARS.map(std::env::var_os);
666 let dirs = ["cache", "data", "config"].map(|cat| tmp.join(cat));
667 for (name, dir) in DIR_VARS.iter().zip(dirs) {
672 test_support::set(name, &dir);
673 }
674 EnvGuard {
675 previous,
676 _lock: lock,
677 }
678 }
679 }
680
681 impl Drop for EnvGuard {
682 fn drop(&mut self) {
683 for (name, previous) in DIR_VARS.iter().zip(self.previous.iter_mut()) {
686 match previous.take() {
687 Some(value) => unsafe { std::env::set_var(name, value) },
688 None => test_support::remove(name),
689 }
690 }
691 }
692 }
693
694 struct Fixture {
700 _tmp: tempfile::TempDir,
701 _env: EnvGuard,
702 endpoint: Endpoint,
703 }
704
705 fn prepared() -> Fixture {
712 let lock = test_support::lock();
713 let tmp = tempfile::tempdir().unwrap();
714 let env = EnvGuard::set(lock, tmp.path());
715 CTX.init(AppKind::Server);
716 let endpoint = Endpoint::in_dir("sapphire-appservertest", tmp.path().to_path_buf());
717 Fixture {
718 _tmp: tmp,
719 _env: env,
720 endpoint,
721 }
722 }
723
724 async fn wait_until_listening(endpoint: &Endpoint) {
730 let deadline = tokio::time::Instant::now() + Duration::from_secs(5);
731 while !sapphire_ipc::probe(endpoint).await.unwrap() {
732 assert!(
733 tokio::time::Instant::now() < deadline,
734 "the server never started listening"
735 );
736 tokio::time::sleep(Duration::from_millis(10)).await;
737 }
738 }
739
740 #[tokio::test(flavor = "multi_thread")]
747 async fn a_running_server_writes_its_log_file() {
748 let f = prepared();
749 let endpoint = f.endpoint.clone();
750 let server = AppServer::new(&CTX, "0.0.0").endpoint(endpoint.clone());
751 let handle = tokio::spawn(async move { server.run().await });
752 wait_until_listening(&endpoint).await;
753
754 tracing::info!("the server is serving, and this line belongs in its log");
755
756 let (client, _) = sapphire_ipc::connect_or_absent(&endpoint, CTX.app_name, client_info())
757 .await
758 .unwrap()
759 .expect("the server is listening");
760 let _: serde_json::Value = client
761 .call(sapphire_ipc::SHUTDOWN_METHOD, serde_json::json!({}))
762 .await
763 .unwrap();
764 handle.await.unwrap().unwrap();
767
768 let text = std::fs::read_to_string(CTX.log_dir().join("app.log")).unwrap();
769 assert!(
770 text.contains("the server is serving, and this line belongs in its log"),
771 "{text}"
772 );
773 }
774
775 #[tokio::test(flavor = "multi_thread")]
776 async fn a_server_reports_itself_as_service_managed() {
777 let f = prepared();
778 let endpoint = f.endpoint.clone();
779 let server = AppServer::new(&CTX, "0.0.0").endpoint(endpoint.clone());
780 let handle = tokio::spawn(async move { server.run().await });
781 wait_until_listening(&endpoint).await;
782
783 let (client, info) =
784 sapphire_ipc::connect_or_absent(&endpoint, CTX.app_name, client_info())
785 .await
786 .unwrap()
787 .expect("the server is listening");
788 assert_eq!(info.managed_by, ManagedBy::Service);
789
790 let _: serde_json::Value = client
791 .call(sapphire_ipc::SHUTDOWN_METHOD, serde_json::json!({}))
792 .await
793 .unwrap();
794 handle.await.unwrap().unwrap();
795 }
796
797 #[tokio::test(flavor = "multi_thread")]
798 async fn a_server_reports_its_app_api_and_the_handshake_gates_on_it() {
799 let f = prepared();
800 let endpoint = f.endpoint.clone();
801 let server = AppServer::new(&CTX, "0.0.0")
802 .endpoint(endpoint.clone())
803 .app_api(7);
804 let handle = tokio::spawn(async move { server.run().await });
805 wait_until_listening(&endpoint).await;
806
807 let wants = |app_api| ClientInfo {
808 app_api,
809 ..client_info()
810 };
811 let err = sapphire_ipc::connect_or_absent(&endpoint, CTX.app_name, wants(Some(8)))
812 .await
813 .unwrap_err();
814 assert!(
815 matches!(
816 err,
817 sapphire_ipc::Error::AppApiVersionMismatch {
818 running: Some(7),
819 ours: 8,
820 ..
821 }
822 ),
823 "{err:?}"
824 );
825
826 let (client, info) =
827 sapphire_ipc::connect_or_absent(&endpoint, CTX.app_name, wants(Some(7)))
828 .await
829 .unwrap()
830 .expect("the server is listening");
831 assert_eq!(info.app_api, Some(7));
832
833 let _: serde_json::Value = client
834 .call(sapphire_ipc::SHUTDOWN_METHOD, serde_json::json!({}))
835 .await
836 .unwrap();
837 handle.await.unwrap().unwrap();
838 }
839
840 #[tokio::test(flavor = "multi_thread")]
841 async fn a_running_server_answers_server_info() {
842 let f = prepared();
843 let endpoint = f.endpoint.clone();
844
845 let server = AppServer::new(&CTX, "1.2.3").endpoint(endpoint.clone());
846 let handle = tokio::spawn(async move { server.run().await });
847 wait_until_listening(&endpoint).await;
848
849 let (client, info) = sapphire_ipc::connect_or_absent(
850 &endpoint,
851 CTX.app_name,
852 ClientInfo {
853 version: "1.2.3".into(),
854 ..client_info()
855 },
856 )
857 .await
858 .unwrap()
859 .expect("the server is listening");
860 assert_eq!(info.version, "1.2.3");
861
862 let report: StatusReport = client
865 .call(
866 sapphire_backend::protocol::SERVER_INFO,
867 serde_json::json!({}),
868 )
869 .await
870 .unwrap();
871 assert!(report.running);
872 assert_eq!(report.version.as_deref(), Some("1.2.3"));
873 assert_eq!(report.pid, Some(std::process::id()));
874 assert_eq!(report.managed_by, Some(proto::ManagedBy::Service));
875 assert!(report.app.is_empty(), "no status rows were configured");
876
877 let _: serde_json::Value = client
878 .call(sapphire_ipc::SHUTDOWN_METHOD, serde_json::json!({}))
879 .await
880 .unwrap();
881 handle.await.unwrap().unwrap();
882 }
883
884 #[tokio::test(flavor = "multi_thread")]
885 async fn shutdown_stops_the_server() {
886 let f = prepared();
887 let endpoint = f.endpoint.clone();
888
889 let server = AppServer::new(&CTX, "0.0.0").endpoint(endpoint.clone());
890 let handle = tokio::spawn(async move { server.run().await });
891 wait_until_listening(&endpoint).await;
892
893 let (client, _) = sapphire_ipc::connect_or_absent(&endpoint, CTX.app_name, client_info())
894 .await
895 .unwrap()
896 .expect("the server is listening");
897 let _: serde_json::Value = client
898 .call(sapphire_ipc::SHUTDOWN_METHOD, serde_json::json!({}))
899 .await
900 .unwrap();
901
902 tokio::time::timeout(Duration::from_secs(5), handle)
903 .await
904 .expect("the server must stop")
905 .unwrap()
906 .unwrap();
907 assert!(!sapphire_ipc::probe(&endpoint).await.unwrap());
908 }
909
910 #[tokio::test(flavor = "multi_thread")]
911 async fn an_application_can_add_its_own_methods() {
912 let f = prepared();
913 let endpoint = f.endpoint.clone();
914
915 let server = AppServer::new(&CTX, "0.0.0")
916 .endpoint(endpoint.clone())
917 .extend(|r| {
918 r.method("sapphire-appservertest.greet", |_| async move {
919 Ok(serde_json::json!("hello"))
920 })
921 });
922 let handle = tokio::spawn(async move { server.run().await });
923 wait_until_listening(&endpoint).await;
924
925 let (client, _) = sapphire_ipc::connect_or_absent(&endpoint, CTX.app_name, client_info())
926 .await
927 .unwrap()
928 .expect("the server is listening");
929 let greeting: String = client
930 .call("sapphire-appservertest.greet", serde_json::json!({}))
931 .await
932 .unwrap();
933 assert_eq!(greeting, "hello");
934
935 let _: serde_json::Value = client
936 .call(sapphire_ipc::SHUTDOWN_METHOD, serde_json::json!({}))
937 .await
938 .unwrap();
939 handle.await.unwrap().unwrap();
940 }
941
942 #[tokio::test(flavor = "multi_thread")]
943 async fn workspace_init_creates_the_marker_and_tells_the_registry() {
944 let f = prepared();
945 let endpoint = f.endpoint.clone();
946 let server = AppServer::new(&CTX, "0.0.0").endpoint(endpoint.clone());
947 let handle = tokio::spawn(async move { server.run().await });
948 wait_until_listening(&endpoint).await;
949 let (client, _) = sapphire_ipc::connect_or_absent(&endpoint, CTX.app_name, client_info())
950 .await
951 .unwrap()
952 .unwrap();
953
954 let dir = tempfile::tempdir().unwrap();
955 let result: proto::WorkspaceInitResult = client
956 .call(
957 proto::WORKSPACE_INIT,
958 proto::WorkspaceInitParams {
959 dir: dir.path().to_owned(),
960 },
961 )
962 .await
963 .unwrap();
964 assert!(result.created);
965 assert!(dir.path().join(format!(".{}", CTX.app_name)).is_dir());
966
967 let again: proto::WorkspaceInitResult = client
969 .call(
970 proto::WORKSPACE_INIT,
971 proto::WorkspaceInitParams {
972 dir: dir.path().to_owned(),
973 },
974 )
975 .await
976 .unwrap();
977 assert!(!again.created);
978
979 let _: serde_json::Value = client
980 .call(sapphire_ipc::SHUTDOWN_METHOD, serde_json::json!({}))
981 .await
982 .unwrap();
983 handle.await.unwrap().unwrap();
984 }
985
986 #[tokio::test(flavor = "multi_thread")]
987 async fn server_info_carries_the_app_rows() {
988 let f = prepared();
989 let endpoint = f.endpoint.clone();
990 let server = AppServer::new(&CTX, "0.0.0")
991 .endpoint(endpoint.clone())
992 .status_rows(std::sync::Arc::new(|| {
993 vec![StatusRow {
994 name: "sync".into(),
995 value: "enabled".into(),
996 }]
997 }));
998 let handle = tokio::spawn(async move { server.run().await });
999 wait_until_listening(&endpoint).await;
1000 let (client, _) = sapphire_ipc::connect_or_absent(&endpoint, CTX.app_name, client_info())
1001 .await
1002 .unwrap()
1003 .unwrap();
1004 let report: StatusReport = client
1005 .call(
1006 sapphire_backend::protocol::SERVER_INFO,
1007 serde_json::json!({}),
1008 )
1009 .await
1010 .unwrap();
1011 assert!(report.running);
1012 assert_eq!(report.app.len(), 1);
1013 assert_eq!(report.app[0].name, "sync");
1014
1015 let _: serde_json::Value = client
1016 .call(sapphire_ipc::SHUTDOWN_METHOD, serde_json::json!({}))
1017 .await
1018 .unwrap();
1019 handle.await.unwrap().unwrap();
1020 }
1021}