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 WorkspaceSyncCommand, 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, BridgeConnector, 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 sync_via_bridge(self) -> Result<AppServer> {
290 let runtime = SyncRuntime::connecting(
291 self.ctx,
292 BridgeConnector::standard(self.ctx.app_name, self.version),
293 std::env::current_exe()?,
294 ManagedBy::Service,
295 );
296 Ok(self.sync(Arc::new(runtime)))
297 }
298
299 pub fn status_rows(mut self, rows: Arc<dyn Fn() -> Vec<StatusRow> + Send + Sync>) -> AppServer {
306 self.status_rows = Some(rows);
307 self
308 }
309
310 pub fn service_spec(&self) -> ServiceSpec {
318 ServiceSpec {
319 app_name: self.ctx.app_name,
320 description: format!("{} server {}", self.ctx.app_name, self.version),
321 args: vec!["serve".to_owned()],
322 post_install: None,
323 }
324 }
325
326 pub fn extend(mut self, f: impl FnOnce(Router) -> Router + Send + 'static) -> AppServer {
328 self.extend = Some(Box::new(f));
329 self
330 }
331
332 pub fn host(&self) -> &Arc<WorkspaceHost> {
335 &self.host
336 }
337
338 pub async fn run(self) -> Result<()> {
340 let AppServer {
341 ctx,
342 version,
343 endpoint,
344 selection_file,
345 host,
346 sync,
347 extend,
348 status_rows,
349 app_api,
350 config,
351 #[cfg(feature = "http")]
352 http_listen,
353 #[cfg(feature = "http")]
354 http_routes,
355 #[cfg(feature = "http")]
356 http_auth,
357 #[cfg(feature = "mcp")]
358 mcp,
359 } = self;
360
361 let endpoint = match endpoint {
362 Some(e) => e,
363 None => Endpoint::for_app(ctx.app_name)?,
364 };
365 let info = ServerInfo {
369 version: version.to_owned(),
370 api: proto::API_VERSION,
371 app_api,
372 pid: std::process::id(),
373 managed_by: ManagedBy::Service,
374 };
375
376 let _log = sapphire_workspace::logging::install(ctx)?;
381
382 let config = match config {
383 Some(config) => config,
384 None => ServerConfig::load_for_app(ctx)?,
385 };
386 #[cfg(not(feature = "mcp"))]
387 if config.mcp.http {
388 tracing::warn!(
389 "server.toml turns MCP over HTTP on, but this build of {} has no MCP",
390 ctx.app_name
391 );
392 }
393
394 let (stop_tx, mut stop_rx) = tokio::sync::watch::channel(false);
395
396 if let Some(runtime) = &sync {
399 runtime.connect().await?;
400 }
401
402 let file = match selection_file {
403 Some(path) => SelectionFile::at(path),
404 None => SelectionFile::for_app(ctx),
405 };
406 let current = Arc::new(Current::new(ctx, Arc::clone(&host), sync.clone(), file));
407 let restoring = current.restore().await;
409
410 let mut router = subscribe_method(
411 Arc::clone(&host),
412 current::current_methods(Arc::clone(¤t), workspace_router(Arc::clone(¤t))),
413 );
414 if sync.is_some() {
415 router = sync_router(Arc::clone(¤t), router);
419 }
420 router = router
424 .method(proto::SERVER_INFO, {
425 let info = info.clone();
426 let status_rows = status_rows.clone();
427 move |_| {
428 let info = info.clone();
429 let status_rows = status_rows.clone();
430 async move {
431 let app = status_rows.as_ref().map(|rows| rows()).unwrap_or_default();
432 let report = StatusReport {
433 running: true,
434 version: Some(info.version),
435 pid: Some(info.pid),
436 managed_by: Some(match info.managed_by {
437 ManagedBy::Service => proto::ManagedBy::Service,
438 ManagedBy::Spawned => proto::ManagedBy::Spawned,
439 }),
440 app,
441 };
442 serde_json::to_value(report)
443 .map_err(|e| sapphire_ipc::RpcError::internal(e.to_string()))
444 }
445 }
446 })
447 .method(sapphire_ipc::SHUTDOWN_METHOD, {
448 let stop_tx = stop_tx.clone();
449 move |_| {
450 let stop_tx = stop_tx.clone();
451 async move {
452 let _ = stop_tx.send(true);
453 serde_json::to_value(proto::Ack {})
454 .map_err(|e| sapphire_ipc::RpcError::internal(e.to_string()))
455 }
456 }
457 });
458 if let Some(extend) = extend {
459 router = extend(router);
460 }
461 let router = Arc::new(router);
462
463 #[cfg(unix)]
468 let mut sigterm = Sigterm::new()?;
469 #[cfg(not(unix))]
470 let mut sigterm = Sigterm;
471
472 #[cfg(unix)]
473 let listener = sapphire_ipc::bind(&endpoint).await?;
474 #[cfg(windows)]
475 let mut listener = sapphire_ipc::bind(&endpoint)?;
476
477 let mut connections = tokio::task::JoinSet::new();
478
479 #[cfg(feature = "http")]
484 let http_stop = tokio_util::sync::CancellationToken::new();
485 #[cfg(feature = "http")]
486 let _http = {
487 let mut routes = http_routes;
488 #[cfg(feature = "mcp")]
489 if config.mcp.http {
490 let (ours, theirs) = sapphire_ipc::Connection::pair();
491 {
492 let router = Arc::clone(&router);
493 let info = info.clone();
494 let app = ctx.app_name;
495 connections.spawn(async move {
496 let _ = serve(theirs, router, app, info).await;
497 });
498 }
499 let client_info = sapphire_ipc::ClientInfo {
500 kind: sapphire_framework_mcp::CLIENT_KIND.to_owned(),
501 version: version.to_owned(),
502 api: proto::API_VERSION,
503 app_api,
504 pid: std::process::id(),
505 };
506 let (client, _) =
507 sapphire_ipc::Client::handshake(ours, ctx.app_name, client_info).await?;
508 let tools = sapphire_framework_mcp::ToolContext::connected(
509 ctx.app_name,
510 version,
511 Arc::new(client),
512 );
513 let mcp_routes =
514 mcp.http_router(tools, &config.http.allowed_hosts, http_stop.child_token());
515 routes = Some(match routes {
516 Some(routes) => routes.merge(mcp_routes),
517 None => mcp_routes,
518 });
519 }
520 match (routes, config.http.listen.or(http_listen)) {
521 (None, _) => None,
522 (Some(_), None) => {
523 tracing::error!(
524 "nothing to bind HTTP to: set `[http] listen` in {SERVER_CONFIG_FILE}"
525 );
526 None
527 }
528 (Some(routes), Some(addr)) => {
529 let auth = http_auth.unwrap_or_else(|| {
530 sapphire_framework_keys::AuthConfig::new(Arc::new(
531 sapphire_framework_keys::BridgeVerifier::new(ctx.app_name, version),
532 ))
533 });
534 http::start(addr, routes, auth, http_stop.clone()).await
535 }
536 }
537 };
538
539 let _sync_tasks = match &sync {
545 Some(runtime) => {
546 let driver = Arc::clone(runtime);
547 let announcements = tokio::spawn(async move {
548 if let Err(err) = driver.run().await {
549 tracing::warn!("the bridge announcement loop ended: {err}");
550 }
551 });
552 let changing = Arc::clone(runtime);
553 let watching = tokio::spawn(async move {
554 if let Err(err) = changing.watch_changes().await {
555 tracing::warn!("the file watcher ended: {err}");
556 }
557 });
558 let dialling = Arc::clone(runtime);
561 let dialling = tokio::spawn(async move {
562 if let Err(err) = dialling.dial_loop().await {
563 tracing::warn!("the live dial loop ended: {err}");
564 }
565 });
566 let connected = tokio::spawn(Arc::clone(runtime).keep_connected());
568 Some([announcements, watching, dialling, connected])
569 }
570 None => None,
571 };
572
573 loop {
574 tokio::select! {
575 changed = stop_rx.changed() => {
576 if changed.is_err() || *stop_rx.borrow() {
577 break;
578 }
579 }
580 _ = tokio::signal::ctrl_c() => {
581 tracing::info!("interrupted; shutting down");
582 break;
583 }
584 _ = sigterm.recv() => {
585 tracing::info!("terminated; shutting down");
586 break;
587 }
588 accepted = listener.accept() => {
589 let conn = accepted?;
590 let router = Arc::clone(&router);
591 let app = ctx.app_name;
592 let info = info.clone();
593 connections.spawn(async move {
594 let _ = serve(conn, router, app, info).await;
595 });
596 }
597 }
598 }
599
600 if let Some(restoring) = restoring {
601 restoring.abort();
602 }
603 #[cfg(feature = "http")]
606 {
607 http_stop.cancel();
608 if let Some((_, mut task)) = _http
609 && tokio::time::timeout(SERVE_GRACE, &mut task).await.is_err()
610 {
611 tracing::debug!("the HTTP listener did not stop in time");
612 task.abort();
613 }
614 }
615 if let Some(tasks) = _sync_tasks {
616 for task in tasks {
621 task.abort();
622 let _ = task.await;
623 }
624 }
625 if let Some(runtime) = &sync {
626 runtime.stop_dials().await;
629 runtime.stop_background().await;
630 runtime.drop_connections().await;
635 }
636 host.close();
637 drop(listener); let _ = tokio::time::timeout(SERVE_GRACE, async {
647 while connections.join_next().await.is_some() {}
648 })
649 .await;
650 connections.abort_all();
651 while connections.join_next().await.is_some() {}
652 Ok(())
653 }
654}
655
656#[cfg(test)]
657mod tests {
658 use super::*;
659 use sapphire_ipc::{ClientInfo, Endpoint, ManagedBy};
660 use sapphire_workspace::{AppContext, AppKind};
661 use std::ffi::OsString;
662
663 use crate::test_support;
664
665 static CTX: AppContext = AppContext::new("sapphire-appservertest");
666
667 const DIR_VARS: [&str; 3] = [
669 "SAPPHIRE_APPSERVERTEST_CACHE_DIR",
670 "SAPPHIRE_APPSERVERTEST_DATA_DIR",
671 "SAPPHIRE_APPSERVERTEST_CONFIG_DIR",
672 ];
673
674 fn client_info() -> ClientInfo {
675 ClientInfo {
676 kind: "test".into(),
677 version: "0.0.0".into(),
678 api: sapphire_backend::protocol::API_VERSION,
679 app_api: None,
680 pid: std::process::id(),
681 }
682 }
683
684 struct EnvGuard {
690 previous: [Option<OsString>; 3],
691 _lock: std::sync::MutexGuard<'static, ()>,
692 }
693
694 impl EnvGuard {
695 fn set(lock: std::sync::MutexGuard<'static, ()>, tmp: &std::path::Path) -> EnvGuard {
697 let previous = DIR_VARS.map(std::env::var_os);
698 let dirs = ["cache", "data", "config"].map(|cat| tmp.join(cat));
699 for (name, dir) in DIR_VARS.iter().zip(dirs) {
704 test_support::set(name, &dir);
705 }
706 EnvGuard {
707 previous,
708 _lock: lock,
709 }
710 }
711 }
712
713 impl Drop for EnvGuard {
714 fn drop(&mut self) {
715 for (name, previous) in DIR_VARS.iter().zip(self.previous.iter_mut()) {
718 match previous.take() {
719 Some(value) => unsafe { std::env::set_var(name, value) },
720 None => test_support::remove(name),
721 }
722 }
723 }
724 }
725
726 struct Fixture {
732 _tmp: tempfile::TempDir,
733 _env: EnvGuard,
734 endpoint: Endpoint,
735 }
736
737 fn prepared() -> Fixture {
744 let lock = test_support::lock();
745 let tmp = tempfile::tempdir().unwrap();
746 let env = EnvGuard::set(lock, tmp.path());
747 CTX.init(AppKind::Server);
748 let endpoint = Endpoint::in_dir("sapphire-appservertest", tmp.path().to_path_buf());
749 Fixture {
750 _tmp: tmp,
751 _env: env,
752 endpoint,
753 }
754 }
755
756 async fn wait_until_listening(endpoint: &Endpoint) {
762 let deadline = tokio::time::Instant::now() + Duration::from_secs(5);
763 while !sapphire_ipc::probe(endpoint).await.unwrap() {
764 assert!(
765 tokio::time::Instant::now() < deadline,
766 "the server never started listening"
767 );
768 tokio::time::sleep(Duration::from_millis(10)).await;
769 }
770 }
771
772 #[tokio::test(flavor = "multi_thread")]
779 async fn a_running_server_writes_its_log_file() {
780 let f = prepared();
781 let endpoint = f.endpoint.clone();
782 let server = AppServer::new(&CTX, "0.0.0").endpoint(endpoint.clone());
783 let handle = tokio::spawn(async move { server.run().await });
784 wait_until_listening(&endpoint).await;
785
786 tracing::info!("the server is serving, and this line belongs in its log");
787
788 let (client, _) = sapphire_ipc::connect_or_absent(&endpoint, CTX.app_name, client_info())
789 .await
790 .unwrap()
791 .expect("the server is listening");
792 let _: serde_json::Value = client
793 .call(sapphire_ipc::SHUTDOWN_METHOD, serde_json::json!({}))
794 .await
795 .unwrap();
796 handle.await.unwrap().unwrap();
799
800 let text = std::fs::read_to_string(CTX.log_dir().join("app.log")).unwrap();
801 assert!(
802 text.contains("the server is serving, and this line belongs in its log"),
803 "{text}"
804 );
805 }
806
807 #[tokio::test(flavor = "multi_thread")]
808 async fn a_server_reports_itself_as_service_managed() {
809 let f = prepared();
810 let endpoint = f.endpoint.clone();
811 let server = AppServer::new(&CTX, "0.0.0").endpoint(endpoint.clone());
812 let handle = tokio::spawn(async move { server.run().await });
813 wait_until_listening(&endpoint).await;
814
815 let (client, info) =
816 sapphire_ipc::connect_or_absent(&endpoint, CTX.app_name, client_info())
817 .await
818 .unwrap()
819 .expect("the server is listening");
820 assert_eq!(info.managed_by, ManagedBy::Service);
821
822 let _: serde_json::Value = client
823 .call(sapphire_ipc::SHUTDOWN_METHOD, serde_json::json!({}))
824 .await
825 .unwrap();
826 handle.await.unwrap().unwrap();
827 }
828
829 #[tokio::test(flavor = "multi_thread")]
830 async fn a_server_reports_its_app_api_and_the_handshake_gates_on_it() {
831 let f = prepared();
832 let endpoint = f.endpoint.clone();
833 let server = AppServer::new(&CTX, "0.0.0")
834 .endpoint(endpoint.clone())
835 .app_api(7);
836 let handle = tokio::spawn(async move { server.run().await });
837 wait_until_listening(&endpoint).await;
838
839 let wants = |app_api| ClientInfo {
840 app_api,
841 ..client_info()
842 };
843 let err = sapphire_ipc::connect_or_absent(&endpoint, CTX.app_name, wants(Some(8)))
844 .await
845 .unwrap_err();
846 assert!(
847 matches!(
848 err,
849 sapphire_ipc::Error::AppApiVersionMismatch {
850 running: Some(7),
851 ours: 8,
852 ..
853 }
854 ),
855 "{err:?}"
856 );
857
858 let (client, info) =
859 sapphire_ipc::connect_or_absent(&endpoint, CTX.app_name, wants(Some(7)))
860 .await
861 .unwrap()
862 .expect("the server is listening");
863 assert_eq!(info.app_api, Some(7));
864
865 let _: serde_json::Value = client
866 .call(sapphire_ipc::SHUTDOWN_METHOD, serde_json::json!({}))
867 .await
868 .unwrap();
869 handle.await.unwrap().unwrap();
870 }
871
872 #[tokio::test(flavor = "multi_thread")]
873 async fn a_running_server_answers_server_info() {
874 let f = prepared();
875 let endpoint = f.endpoint.clone();
876
877 let server = AppServer::new(&CTX, "1.2.3").endpoint(endpoint.clone());
878 let handle = tokio::spawn(async move { server.run().await });
879 wait_until_listening(&endpoint).await;
880
881 let (client, info) = sapphire_ipc::connect_or_absent(
882 &endpoint,
883 CTX.app_name,
884 ClientInfo {
885 version: "1.2.3".into(),
886 ..client_info()
887 },
888 )
889 .await
890 .unwrap()
891 .expect("the server is listening");
892 assert_eq!(info.version, "1.2.3");
893
894 let report: StatusReport = client
897 .call(
898 sapphire_backend::protocol::SERVER_INFO,
899 serde_json::json!({}),
900 )
901 .await
902 .unwrap();
903 assert!(report.running);
904 assert_eq!(report.version.as_deref(), Some("1.2.3"));
905 assert_eq!(report.pid, Some(std::process::id()));
906 assert_eq!(report.managed_by, Some(proto::ManagedBy::Service));
907 assert!(report.app.is_empty(), "no status rows were configured");
908
909 let _: serde_json::Value = client
910 .call(sapphire_ipc::SHUTDOWN_METHOD, serde_json::json!({}))
911 .await
912 .unwrap();
913 handle.await.unwrap().unwrap();
914 }
915
916 #[tokio::test(flavor = "multi_thread")]
917 async fn shutdown_stops_the_server() {
918 let f = prepared();
919 let endpoint = f.endpoint.clone();
920
921 let server = AppServer::new(&CTX, "0.0.0").endpoint(endpoint.clone());
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 _: serde_json::Value = client
930 .call(sapphire_ipc::SHUTDOWN_METHOD, serde_json::json!({}))
931 .await
932 .unwrap();
933
934 tokio::time::timeout(Duration::from_secs(5), handle)
935 .await
936 .expect("the server must stop")
937 .unwrap()
938 .unwrap();
939 assert!(!sapphire_ipc::probe(&endpoint).await.unwrap());
940 }
941
942 #[tokio::test(flavor = "multi_thread")]
943 async fn an_application_can_add_its_own_methods() {
944 let f = prepared();
945 let endpoint = f.endpoint.clone();
946
947 let server = AppServer::new(&CTX, "0.0.0")
948 .endpoint(endpoint.clone())
949 .extend(|r| {
950 r.method("sapphire-appservertest.greet", |_| async move {
951 Ok(serde_json::json!("hello"))
952 })
953 });
954 let handle = tokio::spawn(async move { server.run().await });
955 wait_until_listening(&endpoint).await;
956
957 let (client, _) = sapphire_ipc::connect_or_absent(&endpoint, CTX.app_name, client_info())
958 .await
959 .unwrap()
960 .expect("the server is listening");
961 let greeting: String = client
962 .call("sapphire-appservertest.greet", serde_json::json!({}))
963 .await
964 .unwrap();
965 assert_eq!(greeting, "hello");
966
967 let _: serde_json::Value = client
968 .call(sapphire_ipc::SHUTDOWN_METHOD, serde_json::json!({}))
969 .await
970 .unwrap();
971 handle.await.unwrap().unwrap();
972 }
973
974 #[tokio::test(flavor = "multi_thread")]
975 async fn workspace_init_creates_the_marker_and_tells_the_registry() {
976 let f = prepared();
977 let endpoint = f.endpoint.clone();
978 let server = AppServer::new(&CTX, "0.0.0").endpoint(endpoint.clone());
979 let handle = tokio::spawn(async move { server.run().await });
980 wait_until_listening(&endpoint).await;
981 let (client, _) = sapphire_ipc::connect_or_absent(&endpoint, CTX.app_name, client_info())
982 .await
983 .unwrap()
984 .unwrap();
985
986 let dir = tempfile::tempdir().unwrap();
987 let result: proto::WorkspaceInitResult = client
988 .call(
989 proto::WORKSPACE_INIT,
990 proto::WorkspaceInitParams {
991 dir: dir.path().to_owned(),
992 },
993 )
994 .await
995 .unwrap();
996 assert!(result.created);
997 assert!(dir.path().join(format!(".{}", CTX.app_name)).is_dir());
998
999 let again: proto::WorkspaceInitResult = client
1001 .call(
1002 proto::WORKSPACE_INIT,
1003 proto::WorkspaceInitParams {
1004 dir: dir.path().to_owned(),
1005 },
1006 )
1007 .await
1008 .unwrap();
1009 assert!(!again.created);
1010
1011 let _: serde_json::Value = client
1012 .call(sapphire_ipc::SHUTDOWN_METHOD, serde_json::json!({}))
1013 .await
1014 .unwrap();
1015 handle.await.unwrap().unwrap();
1016 }
1017
1018 #[tokio::test(flavor = "multi_thread")]
1019 async fn server_info_carries_the_app_rows() {
1020 let f = prepared();
1021 let endpoint = f.endpoint.clone();
1022 let server = AppServer::new(&CTX, "0.0.0")
1023 .endpoint(endpoint.clone())
1024 .status_rows(std::sync::Arc::new(|| {
1025 vec![StatusRow {
1026 name: "sync".into(),
1027 value: "enabled".into(),
1028 }]
1029 }));
1030 let handle = tokio::spawn(async move { server.run().await });
1031 wait_until_listening(&endpoint).await;
1032 let (client, _) = sapphire_ipc::connect_or_absent(&endpoint, CTX.app_name, client_info())
1033 .await
1034 .unwrap()
1035 .unwrap();
1036 let report: StatusReport = client
1037 .call(
1038 sapphire_backend::protocol::SERVER_INFO,
1039 serde_json::json!({}),
1040 )
1041 .await
1042 .unwrap();
1043 assert!(report.running);
1044 assert_eq!(report.app.len(), 1);
1045 assert_eq!(report.app[0].name, "sync");
1046
1047 let _: serde_json::Value = client
1048 .call(sapphire_ipc::SHUTDOWN_METHOD, serde_json::json!({}))
1049 .await
1050 .unwrap();
1051 handle.await.unwrap().unwrap();
1052 }
1053}