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;
54mod update;
55
56pub use command::{
57 AppUpdateArgs, DeviceCommand, FrameworkCommand, StatusReport, StatusRow, WorkgroupCommand,
58 WorkspaceCommand, WorkspaceSyncCommand, render_workspace,
59};
60pub use config::{HttpConfig, McpConfig, SERVER_CONFIG_FILE, ServerConfig, UpdateConfig};
61pub use current::Current;
62pub use error::{Error, Result};
63pub use events::subscribe_method;
64pub use handlers::workspace_router;
65pub use host::WorkspaceHost;
66pub use sapphire_framework_update::{ReleaseSource, UpdateArgs};
67pub use selection::{SELECTION_FILE, Selection, SelectionFile};
68pub use sync::{BackfillTiming, BridgeConnector, SyncRuntime, SyncStatus, sync_router};
69
70#[cfg(feature = "mcp")]
72pub use sapphire_framework_mcp as mcp;
73
74pub struct AppServer {
76 ctx: &'static AppContext,
77 version: &'static str,
78 endpoint: Option<Endpoint>,
79 selection_file: Option<PathBuf>,
81 host: Arc<WorkspaceHost>,
82 sync: Option<Arc<SyncRuntime>>,
83 extend: Option<Box<dyn FnOnce(Router) -> Router + Send>>,
84 status_rows: Option<Arc<dyn Fn() -> Vec<StatusRow> + Send + Sync>>,
87 app_api: Option<u32>,
89 config: Option<ServerConfig>,
91 releases: Option<ReleaseSource>,
94 #[cfg(feature = "http")]
96 http_listen: Option<std::net::SocketAddr>,
97 #[cfg(feature = "http")]
99 http_routes: Option<axum::Router>,
100 #[cfg(feature = "http")]
102 http_auth: Option<sapphire_framework_keys::AuthConfig>,
103 #[cfg(feature = "mcp")]
105 mcp: sapphire_framework_mcp::McpService,
106}
107
108#[cfg(unix)]
117struct Sigterm(tokio::signal::unix::Signal);
118
119#[cfg(not(unix))]
121struct Sigterm;
122
123#[cfg(unix)]
124impl Sigterm {
125 fn new() -> Result<Self> {
131 Ok(Self(tokio::signal::unix::signal(
132 tokio::signal::unix::SignalKind::terminate(),
133 )?))
134 }
135
136 async fn recv(&mut self) {
140 self.0.recv().await;
141 }
142}
143
144#[cfg(not(unix))]
145impl Sigterm {
146 async fn recv(&mut self) {
151 std::future::pending::<()>().await
152 }
153}
154
155impl AppServer {
156 pub fn new(ctx: &'static AppContext, version: &'static str) -> AppServer {
158 AppServer {
159 ctx,
160 version,
161 endpoint: None,
162 selection_file: None,
163 host: Arc::new(WorkspaceHost::new(ctx)),
164 sync: None,
165 extend: None,
166 status_rows: None,
167 app_api: None,
168 config: None,
169 releases: None,
170 #[cfg(feature = "http")]
171 http_listen: None,
172 #[cfg(feature = "http")]
173 http_routes: None,
174 #[cfg(feature = "http")]
175 http_auth: None,
176 #[cfg(feature = "mcp")]
177 mcp: sapphire_framework_mcp::McpService::framework(),
178 }
179 }
180
181 pub fn app_name(&self) -> &'static str {
186 self.ctx.app_name
187 }
188
189 pub fn endpoint(mut self, endpoint: Endpoint) -> AppServer {
191 self.endpoint = Some(endpoint);
192 self
193 }
194
195 pub fn app_api(mut self, version: u32) -> AppServer {
200 self.app_api = Some(version);
201 self
202 }
203
204 pub fn config(mut self, config: ServerConfig) -> AppServer {
206 self.config = Some(config);
207 self
208 }
209
210 #[cfg(feature = "http")]
214 pub fn http_listen(mut self, addr: std::net::SocketAddr) -> AppServer {
215 self.http_listen = Some(addr);
216 self
217 }
218
219 #[cfg(feature = "http")]
223 pub fn http(mut self, routes: axum::Router) -> AppServer {
224 self.http_routes = Some(routes);
225 self
226 }
227
228 #[cfg(feature = "http")]
230 pub fn http_auth(mut self, auth: sapphire_framework_keys::AuthConfig) -> AppServer {
231 self.http_auth = Some(auth);
232 self
233 }
234
235 #[cfg(feature = "mcp")]
239 pub fn mcp(mut self, service: sapphire_framework_mcp::McpService) -> AppServer {
240 self.mcp = service;
241 self
242 }
243
244 #[cfg(feature = "mcp")]
250 pub async fn serve_mcp_stdio(self, version: &'static str) -> Result<()> {
251 let endpoint = match self.endpoint {
252 Some(e) => e,
253 None => Endpoint::for_app(self.ctx.app_name)?,
254 };
255 let ctx = sapphire_framework_mcp::ToolContext::dial(
256 self.ctx.app_name,
257 version,
258 self.app_api,
259 endpoint,
260 );
261 self.mcp
262 .serve_stdio(ctx)
263 .await
264 .map_err(|e| Error::Mcp(e.to_string()))
265 }
266
267 pub fn selection_file(mut self, path: PathBuf) -> AppServer {
270 self.selection_file = Some(path);
271 self
272 }
273
274 pub fn sync(mut self, runtime: Arc<SyncRuntime>) -> AppServer {
281 runtime.set_host(Arc::clone(&self.host));
284 self.sync = Some(runtime);
285 self
286 }
287
288 pub fn sync_via_bridge(self) -> Result<AppServer> {
296 let runtime = SyncRuntime::connecting(
297 self.ctx,
298 BridgeConnector::standard(self.ctx.app_name, self.version),
299 std::env::current_exe()?,
300 ManagedBy::Service,
301 );
302 Ok(self.sync(Arc::new(runtime)))
303 }
304
305 pub fn status_rows(mut self, rows: Arc<dyn Fn() -> Vec<StatusRow> + Send + Sync>) -> AppServer {
312 self.status_rows = Some(rows);
313 self
314 }
315
316 pub fn releases(mut self, source: ReleaseSource) -> AppServer {
323 self.releases = Some(source);
324 self
325 }
326
327 pub fn release_source(&self) -> Option<&ReleaseSource> {
329 self.releases.as_ref()
330 }
331
332 pub fn service_spec(&self) -> ServiceSpec {
340 ServiceSpec {
341 app_name: self.ctx.app_name,
342 description: format!("{} server {}", self.ctx.app_name, self.version),
343 args: vec!["serve".to_owned()],
344 post_install: None,
345 }
346 }
347
348 pub fn extend(mut self, f: impl FnOnce(Router) -> Router + Send + 'static) -> AppServer {
350 self.extend = Some(Box::new(f));
351 self
352 }
353
354 pub fn host(&self) -> &Arc<WorkspaceHost> {
357 &self.host
358 }
359
360 pub fn sync_runtime(&self) -> Option<&Arc<SyncRuntime>> {
364 self.sync.as_ref()
365 }
366
367 pub async fn run(self) -> Result<()> {
369 let AppServer {
370 ctx,
371 version,
372 endpoint,
373 selection_file,
374 host,
375 sync,
376 extend,
377 status_rows,
378 app_api,
379 config,
380 releases,
381 #[cfg(feature = "http")]
382 http_listen,
383 #[cfg(feature = "http")]
384 http_routes,
385 #[cfg(feature = "http")]
386 http_auth,
387 #[cfg(feature = "mcp")]
388 mcp,
389 } = self;
390
391 let endpoint = match endpoint {
392 Some(e) => e,
393 None => Endpoint::for_app(ctx.app_name)?,
394 };
395 let info = ServerInfo {
399 version: version.to_owned(),
400 api: proto::API_VERSION,
401 app_api,
402 pid: std::process::id(),
403 managed_by: ManagedBy::Service,
404 };
405
406 let _log = sapphire_workspace::logging::install(ctx)?;
411
412 let config = match config {
413 Some(config) => config,
414 None => ServerConfig::load_for_app(ctx)?,
415 };
416 #[cfg(not(feature = "mcp"))]
417 if config.mcp.http {
418 tracing::warn!(
419 "server.toml turns MCP over HTTP on, but this build of {} has no MCP",
420 ctx.app_name
421 );
422 }
423
424 let (stop_tx, mut stop_rx) = tokio::sync::watch::channel(false);
425
426 let update_status = update::SharedStatus::default();
428 let update_check = releases.filter(|_| config.update.check);
429
430 if let Some(runtime) = &sync {
433 runtime.connect().await?;
434 }
435
436 let file = match selection_file {
437 Some(path) => SelectionFile::at(path),
438 None => SelectionFile::for_app(ctx),
439 };
440 let current = Arc::new(Current::new(ctx, Arc::clone(&host), sync.clone(), file));
441 let restoring = current.restore().await;
443
444 let mut router = subscribe_method(
445 Arc::clone(&host),
446 current::current_methods(Arc::clone(¤t), workspace_router(Arc::clone(¤t))),
447 );
448 if sync.is_some() {
449 router = sync_router(Arc::clone(¤t), router);
453 }
454 router = router
458 .method(proto::SERVER_INFO, {
459 let info = info.clone();
460 let status_rows = status_rows.clone();
461 move |_| {
462 let info = info.clone();
463 let status_rows = status_rows.clone();
464 async move {
465 let app = status_rows.as_ref().map(|rows| rows()).unwrap_or_default();
466 let report = StatusReport {
467 running: true,
468 version: Some(info.version),
469 pid: Some(info.pid),
470 managed_by: Some(match info.managed_by {
471 ManagedBy::Service => proto::ManagedBy::Service,
472 ManagedBy::Spawned => proto::ManagedBy::Spawned,
473 }),
474 app,
475 };
476 serde_json::to_value(report)
477 .map_err(|e| sapphire_ipc::RpcError::internal(e.to_string()))
478 }
479 }
480 })
481 .method(proto::SERVER_UPDATE, {
482 let update_status = Arc::clone(&update_status);
483 move |_| {
484 let status = update_status.lock().expect("update status lock").clone();
485 async move {
486 serde_json::to_value(status)
487 .map_err(|e| sapphire_ipc::RpcError::internal(e.to_string()))
488 }
489 }
490 })
491 .method(sapphire_ipc::SHUTDOWN_METHOD, {
492 let stop_tx = stop_tx.clone();
493 move |_| {
494 let stop_tx = stop_tx.clone();
495 async move {
496 let _ = stop_tx.send(true);
497 serde_json::to_value(proto::Ack {})
498 .map_err(|e| sapphire_ipc::RpcError::internal(e.to_string()))
499 }
500 }
501 });
502 if let Some(extend) = extend {
503 router = extend(router);
504 }
505 let router = Arc::new(router);
506
507 #[cfg(unix)]
512 let mut sigterm = Sigterm::new()?;
513 #[cfg(not(unix))]
514 let mut sigterm = Sigterm;
515
516 #[cfg(unix)]
517 let listener = sapphire_ipc::bind(&endpoint).await?;
518 #[cfg(windows)]
519 let mut listener = sapphire_ipc::bind(&endpoint)?;
520
521 let mut connections = tokio::task::JoinSet::new();
522
523 #[cfg(feature = "http")]
528 let http_stop = tokio_util::sync::CancellationToken::new();
529 #[cfg(feature = "http")]
530 let _http = {
531 let mut routes = http_routes;
532 #[cfg(feature = "mcp")]
533 if config.mcp.http {
534 let (ours, theirs) = sapphire_ipc::Connection::pair();
535 {
536 let router = Arc::clone(&router);
537 let info = info.clone();
538 let app = ctx.app_name;
539 connections.spawn(async move {
540 let _ = serve(theirs, router, app, info).await;
541 });
542 }
543 let client_info = sapphire_ipc::ClientInfo {
544 kind: sapphire_framework_mcp::CLIENT_KIND.to_owned(),
545 version: version.to_owned(),
546 api: proto::API_VERSION,
547 app_api,
548 pid: std::process::id(),
549 };
550 let (client, _) =
551 sapphire_ipc::Client::handshake(ours, ctx.app_name, client_info).await?;
552 let tools = sapphire_framework_mcp::ToolContext::connected(
553 ctx.app_name,
554 version,
555 Arc::new(client),
556 );
557 let mcp_routes =
558 mcp.http_router(tools, &config.http.allowed_hosts, http_stop.child_token());
559 routes = Some(match routes {
560 Some(routes) => routes.merge(mcp_routes),
561 None => mcp_routes,
562 });
563 }
564 match (routes, config.http.listen.or(http_listen)) {
565 (None, _) => None,
566 (Some(_), None) => {
567 tracing::error!(
568 "nothing to bind HTTP to: set `[http] listen` in {SERVER_CONFIG_FILE}"
569 );
570 None
571 }
572 (Some(routes), Some(addr)) => {
573 let auth = http_auth.unwrap_or_else(|| {
574 sapphire_framework_keys::AuthConfig::new(Arc::new(
575 sapphire_framework_keys::BridgeVerifier::new(ctx.app_name, version),
576 ))
577 });
578 http::start(addr, routes, auth, http_stop.clone()).await
579 }
580 }
581 };
582
583 let _sync_tasks = match &sync {
589 Some(runtime) => {
590 let driver = Arc::clone(runtime);
591 let announcements = tokio::spawn(async move {
592 if let Err(err) = driver.run().await {
593 tracing::warn!("the bridge announcement loop ended: {err}");
594 }
595 });
596 let changing = Arc::clone(runtime);
597 let watching = tokio::spawn(async move {
598 if let Err(err) = changing.watch_changes().await {
599 tracing::warn!("the file watcher ended: {err}");
600 }
601 });
602 let dialling = Arc::clone(runtime);
605 let dialling = tokio::spawn(async move {
606 if let Err(err) = dialling.dial_loop().await {
607 tracing::warn!("the live dial loop ended: {err}");
608 }
609 });
610 let connected = tokio::spawn(Arc::clone(runtime).keep_connected());
612 Some([announcements, watching, dialling, connected])
613 }
614 None => None,
615 };
616
617 let _update_checking = update_check.and_then(|check| {
620 update::start(check, ctx.app_name, version, Arc::clone(&update_status))
621 });
622
623 loop {
624 tokio::select! {
625 changed = stop_rx.changed() => {
626 if changed.is_err() || *stop_rx.borrow() {
627 break;
628 }
629 }
630 _ = tokio::signal::ctrl_c() => {
631 tracing::info!("interrupted; shutting down");
632 break;
633 }
634 _ = sigterm.recv() => {
635 tracing::info!("terminated; shutting down");
636 break;
637 }
638 accepted = listener.accept() => {
639 let conn = accepted?;
640 let router = Arc::clone(&router);
641 let app = ctx.app_name;
642 let info = info.clone();
643 connections.spawn(async move {
644 let _ = serve(conn, router, app, info).await;
645 });
646 }
647 }
648 }
649
650 if let Some(restoring) = restoring {
651 restoring.abort();
652 }
653 #[cfg(feature = "http")]
656 {
657 http_stop.cancel();
658 if let Some((_, mut task)) = _http
659 && tokio::time::timeout(SERVE_GRACE, &mut task).await.is_err()
660 {
661 tracing::debug!("the HTTP listener did not stop in time");
662 task.abort();
663 }
664 }
665 if let Some(tasks) = _sync_tasks {
666 for task in tasks {
671 task.abort();
672 let _ = task.await;
673 }
674 }
675 if let Some(runtime) = &sync {
676 runtime.stop_dials().await;
679 runtime.stop_background().await;
680 runtime.drop_connections().await;
685 }
686 host.close();
687 drop(listener); let _ = tokio::time::timeout(SERVE_GRACE, async {
697 while connections.join_next().await.is_some() {}
698 })
699 .await;
700 connections.abort_all();
701 while connections.join_next().await.is_some() {}
702 Ok(())
703 }
704}
705
706#[cfg(test)]
707mod tests {
708 use super::*;
709 use sapphire_ipc::{ClientInfo, Endpoint, ManagedBy};
710 use sapphire_workspace::{AppContext, AppKind};
711 use std::ffi::OsString;
712
713 use crate::test_support;
714
715 static CTX: AppContext = AppContext::new("sapphire-appservertest");
716
717 const DIR_VARS: [&str; 3] = [
719 "SAPPHIRE_APPSERVERTEST_CACHE_DIR",
720 "SAPPHIRE_APPSERVERTEST_DATA_DIR",
721 "SAPPHIRE_APPSERVERTEST_CONFIG_DIR",
722 ];
723
724 fn client_info() -> ClientInfo {
725 ClientInfo {
726 kind: "test".into(),
727 version: "0.0.0".into(),
728 api: sapphire_backend::protocol::API_VERSION,
729 app_api: None,
730 pid: std::process::id(),
731 }
732 }
733
734 struct EnvGuard {
740 previous: [Option<OsString>; 3],
741 _lock: std::sync::MutexGuard<'static, ()>,
742 }
743
744 impl EnvGuard {
745 fn set(lock: std::sync::MutexGuard<'static, ()>, tmp: &std::path::Path) -> EnvGuard {
747 let previous = DIR_VARS.map(std::env::var_os);
748 let dirs = ["cache", "data", "config"].map(|cat| tmp.join(cat));
749 for (name, dir) in DIR_VARS.iter().zip(dirs) {
754 test_support::set(name, &dir);
755 }
756 EnvGuard {
757 previous,
758 _lock: lock,
759 }
760 }
761 }
762
763 impl Drop for EnvGuard {
764 fn drop(&mut self) {
765 for (name, previous) in DIR_VARS.iter().zip(self.previous.iter_mut()) {
768 match previous.take() {
769 Some(value) => unsafe { std::env::set_var(name, value) },
770 None => test_support::remove(name),
771 }
772 }
773 }
774 }
775
776 struct Fixture {
782 _tmp: tempfile::TempDir,
783 _env: EnvGuard,
784 endpoint: Endpoint,
785 }
786
787 fn prepared() -> Fixture {
794 let lock = test_support::lock();
795 let tmp = tempfile::tempdir().unwrap();
796 let env = EnvGuard::set(lock, tmp.path());
797 CTX.init(AppKind::Server);
798 let endpoint = Endpoint::in_dir("sapphire-appservertest", tmp.path().to_path_buf());
799 Fixture {
800 _tmp: tmp,
801 _env: env,
802 endpoint,
803 }
804 }
805
806 async fn wait_until_listening(endpoint: &Endpoint) {
812 let deadline = tokio::time::Instant::now() + Duration::from_secs(5);
813 while !sapphire_ipc::probe(endpoint).await.unwrap() {
814 assert!(
815 tokio::time::Instant::now() < deadline,
816 "the server never started listening"
817 );
818 tokio::time::sleep(Duration::from_millis(10)).await;
819 }
820 }
821
822 #[test]
829 fn the_runtime_sync_via_bridge_mounts_is_the_applications_to_read() {
830 assert!(AppServer::new(&CTX, "0.0.0").sync_runtime().is_none());
833 let server = AppServer::new(&CTX, "0.0.0").sync_via_bridge().unwrap();
834 let runtime = server.sync_runtime().expect("a runtime");
835 assert!(!runtime.is_connected(), "nothing connects before `run`");
836 }
837
838 #[tokio::test(flavor = "multi_thread")]
839 async fn a_running_server_writes_its_log_file() {
840 let f = prepared();
841 let endpoint = f.endpoint.clone();
842 let server = AppServer::new(&CTX, "0.0.0").endpoint(endpoint.clone());
843 let handle = tokio::spawn(async move { server.run().await });
844 wait_until_listening(&endpoint).await;
845
846 tracing::info!("the server is serving, and this line belongs in its log");
847
848 let (client, _) = sapphire_ipc::connect_or_absent(&endpoint, CTX.app_name, client_info())
849 .await
850 .unwrap()
851 .expect("the server is listening");
852 let _: serde_json::Value = client
853 .call(sapphire_ipc::SHUTDOWN_METHOD, serde_json::json!({}))
854 .await
855 .unwrap();
856 handle.await.unwrap().unwrap();
859
860 let text = std::fs::read_to_string(CTX.log_dir().join("app.log")).unwrap();
861 assert!(
862 text.contains("the server is serving, and this line belongs in its log"),
863 "{text}"
864 );
865 }
866
867 #[tokio::test(flavor = "multi_thread")]
868 async fn a_server_reports_itself_as_service_managed() {
869 let f = prepared();
870 let endpoint = f.endpoint.clone();
871 let server = AppServer::new(&CTX, "0.0.0").endpoint(endpoint.clone());
872 let handle = tokio::spawn(async move { server.run().await });
873 wait_until_listening(&endpoint).await;
874
875 let (client, info) =
876 sapphire_ipc::connect_or_absent(&endpoint, CTX.app_name, client_info())
877 .await
878 .unwrap()
879 .expect("the server is listening");
880 assert_eq!(info.managed_by, ManagedBy::Service);
881
882 let _: serde_json::Value = client
883 .call(sapphire_ipc::SHUTDOWN_METHOD, serde_json::json!({}))
884 .await
885 .unwrap();
886 handle.await.unwrap().unwrap();
887 }
888
889 #[tokio::test(flavor = "multi_thread")]
890 async fn a_server_reports_its_app_api_and_the_handshake_gates_on_it() {
891 let f = prepared();
892 let endpoint = f.endpoint.clone();
893 let server = AppServer::new(&CTX, "0.0.0")
894 .endpoint(endpoint.clone())
895 .app_api(7);
896 let handle = tokio::spawn(async move { server.run().await });
897 wait_until_listening(&endpoint).await;
898
899 let wants = |app_api| ClientInfo {
900 app_api,
901 ..client_info()
902 };
903 let err = sapphire_ipc::connect_or_absent(&endpoint, CTX.app_name, wants(Some(8)))
904 .await
905 .unwrap_err();
906 assert!(
907 matches!(
908 err,
909 sapphire_ipc::Error::AppApiVersionMismatch {
910 running: Some(7),
911 ours: 8,
912 ..
913 }
914 ),
915 "{err:?}"
916 );
917
918 let (client, info) =
919 sapphire_ipc::connect_or_absent(&endpoint, CTX.app_name, wants(Some(7)))
920 .await
921 .unwrap()
922 .expect("the server is listening");
923 assert_eq!(info.app_api, Some(7));
924
925 let _: serde_json::Value = client
926 .call(sapphire_ipc::SHUTDOWN_METHOD, serde_json::json!({}))
927 .await
928 .unwrap();
929 handle.await.unwrap().unwrap();
930 }
931
932 #[tokio::test(flavor = "multi_thread")]
933 async fn a_running_server_answers_server_info() {
934 let f = prepared();
935 let endpoint = f.endpoint.clone();
936
937 let server = AppServer::new(&CTX, "1.2.3").endpoint(endpoint.clone());
938 let handle = tokio::spawn(async move { server.run().await });
939 wait_until_listening(&endpoint).await;
940
941 let (client, info) = sapphire_ipc::connect_or_absent(
942 &endpoint,
943 CTX.app_name,
944 ClientInfo {
945 version: "1.2.3".into(),
946 ..client_info()
947 },
948 )
949 .await
950 .unwrap()
951 .expect("the server is listening");
952 assert_eq!(info.version, "1.2.3");
953
954 let report: StatusReport = client
957 .call(
958 sapphire_backend::protocol::SERVER_INFO,
959 serde_json::json!({}),
960 )
961 .await
962 .unwrap();
963 assert!(report.running);
964 assert_eq!(report.version.as_deref(), Some("1.2.3"));
965 assert_eq!(report.pid, Some(std::process::id()));
966 assert_eq!(report.managed_by, Some(proto::ManagedBy::Service));
967 assert!(report.app.is_empty(), "no status rows were configured");
968
969 let _: serde_json::Value = client
970 .call(sapphire_ipc::SHUTDOWN_METHOD, serde_json::json!({}))
971 .await
972 .unwrap();
973 handle.await.unwrap().unwrap();
974 }
975
976 #[tokio::test(flavor = "multi_thread")]
977 async fn shutdown_stops_the_server() {
978 let f = prepared();
979 let endpoint = f.endpoint.clone();
980
981 let server = AppServer::new(&CTX, "0.0.0").endpoint(endpoint.clone());
982 let handle = tokio::spawn(async move { server.run().await });
983 wait_until_listening(&endpoint).await;
984
985 let (client, _) = sapphire_ipc::connect_or_absent(&endpoint, CTX.app_name, client_info())
986 .await
987 .unwrap()
988 .expect("the server is listening");
989 let _: serde_json::Value = client
990 .call(sapphire_ipc::SHUTDOWN_METHOD, serde_json::json!({}))
991 .await
992 .unwrap();
993
994 tokio::time::timeout(Duration::from_secs(5), handle)
995 .await
996 .expect("the server must stop")
997 .unwrap()
998 .unwrap();
999 assert!(!sapphire_ipc::probe(&endpoint).await.unwrap());
1000 }
1001
1002 #[tokio::test(flavor = "multi_thread")]
1003 async fn an_application_can_add_its_own_methods() {
1004 let f = prepared();
1005 let endpoint = f.endpoint.clone();
1006
1007 let server = AppServer::new(&CTX, "0.0.0")
1008 .endpoint(endpoint.clone())
1009 .extend(|r| {
1010 r.method("sapphire-appservertest.greet", |_| async move {
1011 Ok(serde_json::json!("hello"))
1012 })
1013 });
1014 let handle = tokio::spawn(async move { server.run().await });
1015 wait_until_listening(&endpoint).await;
1016
1017 let (client, _) = sapphire_ipc::connect_or_absent(&endpoint, CTX.app_name, client_info())
1018 .await
1019 .unwrap()
1020 .expect("the server is listening");
1021 let greeting: String = client
1022 .call("sapphire-appservertest.greet", serde_json::json!({}))
1023 .await
1024 .unwrap();
1025 assert_eq!(greeting, "hello");
1026
1027 let _: serde_json::Value = client
1028 .call(sapphire_ipc::SHUTDOWN_METHOD, serde_json::json!({}))
1029 .await
1030 .unwrap();
1031 handle.await.unwrap().unwrap();
1032 }
1033
1034 #[tokio::test(flavor = "multi_thread")]
1035 async fn workspace_init_creates_the_marker() {
1036 let f = prepared();
1037 let endpoint = f.endpoint.clone();
1038 let server = AppServer::new(&CTX, "0.0.0").endpoint(endpoint.clone());
1039 let handle = tokio::spawn(async move { server.run().await });
1040 wait_until_listening(&endpoint).await;
1041 let (client, _) = sapphire_ipc::connect_or_absent(&endpoint, CTX.app_name, client_info())
1042 .await
1043 .unwrap()
1044 .unwrap();
1045
1046 let dir = tempfile::tempdir().unwrap();
1047 let result: proto::WorkspaceInitResult = client
1048 .call(
1049 proto::WORKSPACE_INIT,
1050 proto::WorkspaceInitParams {
1051 dir: dir.path().to_owned(),
1052 },
1053 )
1054 .await
1055 .unwrap();
1056 assert!(result.created);
1057 assert!(dir.path().join(format!(".{}", CTX.app_name)).is_dir());
1058
1059 let again: proto::WorkspaceInitResult = client
1061 .call(
1062 proto::WORKSPACE_INIT,
1063 proto::WorkspaceInitParams {
1064 dir: dir.path().to_owned(),
1065 },
1066 )
1067 .await
1068 .unwrap();
1069 assert!(!again.created);
1070
1071 let _: serde_json::Value = client
1072 .call(sapphire_ipc::SHUTDOWN_METHOD, serde_json::json!({}))
1073 .await
1074 .unwrap();
1075 handle.await.unwrap().unwrap();
1076 }
1077
1078 #[tokio::test(flavor = "multi_thread")]
1079 async fn server_info_carries_the_app_rows() {
1080 let f = prepared();
1081 let endpoint = f.endpoint.clone();
1082 let server = AppServer::new(&CTX, "0.0.0")
1083 .endpoint(endpoint.clone())
1084 .status_rows(std::sync::Arc::new(|| {
1085 vec![StatusRow {
1086 name: "sync".into(),
1087 value: "enabled".into(),
1088 }]
1089 }));
1090 let handle = tokio::spawn(async move { server.run().await });
1091 wait_until_listening(&endpoint).await;
1092 let (client, _) = sapphire_ipc::connect_or_absent(&endpoint, CTX.app_name, client_info())
1093 .await
1094 .unwrap()
1095 .unwrap();
1096 let report: StatusReport = client
1097 .call(
1098 sapphire_backend::protocol::SERVER_INFO,
1099 serde_json::json!({}),
1100 )
1101 .await
1102 .unwrap();
1103 assert!(report.running);
1104 assert_eq!(report.app.len(), 1);
1105 assert_eq!(report.app[0].name, "sync");
1106
1107 let _: serde_json::Value = client
1108 .call(sapphire_ipc::SHUTDOWN_METHOD, serde_json::json!({}))
1109 .await
1110 .unwrap();
1111 handle.await.unwrap().unwrap();
1112 }
1113}