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 current;
43mod error;
44mod events;
45mod handlers;
46mod host;
47mod selection;
48pub mod sync;
49#[cfg(test)]
50mod test_support;
51
52pub use command::{
53 DeviceCommand, FrameworkCommand, StatusReport, StatusRow, WorkgroupCommand, WorkspaceCommand,
54 render_workspace,
55};
56pub use current::Current;
57pub use error::{Error, Result};
58pub use events::subscribe_method;
59pub use handlers::workspace_router;
60pub use host::WorkspaceHost;
61pub use selection::{SELECTION_FILE, Selection, SelectionFile};
62pub use sync::{BackfillTiming, SyncRuntime, SyncStatus, sync_router};
63
64pub struct AppServer {
66 ctx: &'static AppContext,
67 version: &'static str,
68 endpoint: Option<Endpoint>,
69 selection_file: Option<PathBuf>,
71 host: Arc<WorkspaceHost>,
72 sync: Option<Arc<SyncRuntime>>,
73 extend: Option<Box<dyn FnOnce(Router) -> Router + Send>>,
74 status_rows: Option<Arc<dyn Fn() -> Vec<StatusRow> + Send + Sync>>,
77 app_api: Option<u32>,
79}
80
81#[cfg(unix)]
90struct Sigterm(tokio::signal::unix::Signal);
91
92#[cfg(not(unix))]
94struct Sigterm;
95
96#[cfg(unix)]
97impl Sigterm {
98 fn new() -> Result<Self> {
104 Ok(Self(tokio::signal::unix::signal(
105 tokio::signal::unix::SignalKind::terminate(),
106 )?))
107 }
108
109 async fn recv(&mut self) {
113 self.0.recv().await;
114 }
115}
116
117#[cfg(not(unix))]
118impl Sigterm {
119 async fn recv(&mut self) {
124 std::future::pending::<()>().await
125 }
126}
127
128impl AppServer {
129 pub fn new(ctx: &'static AppContext, version: &'static str) -> AppServer {
131 AppServer {
132 ctx,
133 version,
134 endpoint: None,
135 selection_file: None,
136 host: Arc::new(WorkspaceHost::new(ctx)),
137 sync: None,
138 extend: None,
139 status_rows: None,
140 app_api: None,
141 }
142 }
143
144 pub fn app_name(&self) -> &'static str {
149 self.ctx.app_name
150 }
151
152 pub fn endpoint(mut self, endpoint: Endpoint) -> AppServer {
154 self.endpoint = Some(endpoint);
155 self
156 }
157
158 pub fn app_api(mut self, version: u32) -> AppServer {
163 self.app_api = Some(version);
164 self
165 }
166
167 pub fn selection_file(mut self, path: PathBuf) -> AppServer {
170 self.selection_file = Some(path);
171 self
172 }
173
174 pub fn sync(mut self, runtime: Arc<SyncRuntime>) -> AppServer {
181 runtime.set_host(Arc::clone(&self.host));
184 self.sync = Some(runtime);
185 self
186 }
187
188 pub fn status_rows(mut self, rows: Arc<dyn Fn() -> Vec<StatusRow> + Send + Sync>) -> AppServer {
195 self.status_rows = Some(rows);
196 self
197 }
198
199 pub fn service_spec(&self) -> ServiceSpec {
207 ServiceSpec {
208 app_name: self.ctx.app_name,
209 description: format!("{} server {}", self.ctx.app_name, self.version),
210 args: vec!["serve".to_owned()],
211 post_install: None,
212 }
213 }
214
215 pub fn extend(mut self, f: impl FnOnce(Router) -> Router + Send + 'static) -> AppServer {
217 self.extend = Some(Box::new(f));
218 self
219 }
220
221 pub fn host(&self) -> &Arc<WorkspaceHost> {
224 &self.host
225 }
226
227 pub async fn run(self) -> Result<()> {
229 let AppServer {
230 ctx,
231 version,
232 endpoint,
233 selection_file,
234 host,
235 sync,
236 extend,
237 status_rows,
238 app_api,
239 } = self;
240
241 let endpoint = match endpoint {
242 Some(e) => e,
243 None => Endpoint::for_app(ctx.app_name)?,
244 };
245 let info = ServerInfo {
249 version: version.to_owned(),
250 api: proto::API_VERSION,
251 app_api,
252 pid: std::process::id(),
253 managed_by: ManagedBy::Service,
254 };
255
256 let _log = sapphire_workspace::logging::install(ctx)?;
261
262 let (stop_tx, mut stop_rx) = tokio::sync::watch::channel(false);
263
264 let file = match selection_file {
265 Some(path) => SelectionFile::at(path),
266 None => SelectionFile::for_app(ctx),
267 };
268 let current = Arc::new(Current::new(ctx, Arc::clone(&host), sync.clone(), file));
269 let restoring = current.restore().await;
271
272 let mut router = subscribe_method(
273 Arc::clone(&host),
274 current::current_methods(Arc::clone(¤t), workspace_router(Arc::clone(¤t))),
275 );
276 if sync.is_some() {
277 router = sync_router(Arc::clone(¤t), router);
281 }
282 router = router
286 .method(proto::SERVER_INFO, {
287 let info = info.clone();
288 let status_rows = status_rows.clone();
289 move |_| {
290 let info = info.clone();
291 let status_rows = status_rows.clone();
292 async move {
293 let app = status_rows.as_ref().map(|rows| rows()).unwrap_or_default();
294 let report = StatusReport {
295 running: true,
296 version: Some(info.version),
297 pid: Some(info.pid),
298 managed_by: Some(match info.managed_by {
299 ManagedBy::Service => proto::ManagedBy::Service,
300 ManagedBy::Spawned => proto::ManagedBy::Spawned,
301 }),
302 app,
303 };
304 serde_json::to_value(report)
305 .map_err(|e| sapphire_ipc::RpcError::internal(e.to_string()))
306 }
307 }
308 })
309 .method(sapphire_ipc::SHUTDOWN_METHOD, {
310 let stop_tx = stop_tx.clone();
311 move |_| {
312 let stop_tx = stop_tx.clone();
313 async move {
314 let _ = stop_tx.send(true);
315 serde_json::to_value(proto::Ack {})
316 .map_err(|e| sapphire_ipc::RpcError::internal(e.to_string()))
317 }
318 }
319 });
320 if let Some(extend) = extend {
321 router = extend(router);
322 }
323 let router = Arc::new(router);
324
325 #[cfg(unix)]
330 let mut sigterm = Sigterm::new()?;
331 #[cfg(not(unix))]
332 let mut sigterm = Sigterm;
333
334 #[cfg(unix)]
335 let listener = sapphire_ipc::bind(&endpoint).await?;
336 #[cfg(windows)]
337 let mut listener = sapphire_ipc::bind(&endpoint)?;
338
339 let _sync_tasks = match &sync {
345 Some(runtime) => {
346 let driver = Arc::clone(runtime);
347 let announcements = tokio::spawn(async move {
348 if let Err(err) = driver.run().await {
349 tracing::warn!("the bridge announcement loop ended: {err}");
350 }
351 });
352 let changing = Arc::clone(runtime);
353 let watching = tokio::spawn(async move {
354 if let Err(err) = changing.watch_changes().await {
355 tracing::warn!("the file watcher ended: {err}");
356 }
357 });
358 let dialling = Arc::clone(runtime);
361 let dialling = tokio::spawn(async move {
362 if let Err(err) = dialling.dial_loop().await {
363 tracing::warn!("the live dial loop ended: {err}");
364 }
365 });
366 Some((announcements, watching, dialling))
367 }
368 None => None,
369 };
370
371 let mut connections = tokio::task::JoinSet::new();
372 loop {
373 tokio::select! {
374 changed = stop_rx.changed() => {
375 if changed.is_err() || *stop_rx.borrow() {
376 break;
377 }
378 }
379 _ = tokio::signal::ctrl_c() => {
380 tracing::info!("interrupted; shutting down");
381 break;
382 }
383 _ = sigterm.recv() => {
384 tracing::info!("terminated; shutting down");
385 break;
386 }
387 accepted = listener.accept() => {
388 let conn = accepted?;
389 let router = Arc::clone(&router);
390 let app = ctx.app_name;
391 let info = info.clone();
392 connections.spawn(async move {
393 let _ = serve(conn, router, app, info).await;
394 });
395 }
396 }
397 }
398
399 if let Some(restoring) = restoring {
400 restoring.abort();
401 }
402 if let Some((announcements, watching, dialling)) = _sync_tasks {
403 announcements.abort();
404 watching.abort();
405 dialling.abort();
406 }
407 if let Some(runtime) = &sync {
408 runtime.stop_dials().await;
410 runtime.drop_connections().await;
415 }
416 host.close();
417 drop(listener); let _ = tokio::time::timeout(SERVE_GRACE, async {
427 while connections.join_next().await.is_some() {}
428 })
429 .await;
430 connections.abort_all();
431 while connections.join_next().await.is_some() {}
432 Ok(())
433 }
434}
435
436#[cfg(test)]
437mod tests {
438 use super::*;
439 use sapphire_ipc::{ClientInfo, Endpoint, ManagedBy};
440 use sapphire_workspace::{AppContext, AppKind};
441 use std::ffi::OsString;
442
443 use crate::test_support;
444
445 static CTX: AppContext = AppContext::new("sapphire-appservertest");
446
447 const DIR_VARS: [&str; 3] = [
449 "SAPPHIRE_APPSERVERTEST_CACHE_DIR",
450 "SAPPHIRE_APPSERVERTEST_DATA_DIR",
451 "SAPPHIRE_APPSERVERTEST_CONFIG_DIR",
452 ];
453
454 fn client_info() -> ClientInfo {
455 ClientInfo {
456 kind: "test".into(),
457 version: "0.0.0".into(),
458 api: sapphire_backend::protocol::API_VERSION,
459 app_api: None,
460 pid: std::process::id(),
461 }
462 }
463
464 struct EnvGuard {
470 previous: [Option<OsString>; 3],
471 _lock: std::sync::MutexGuard<'static, ()>,
472 }
473
474 impl EnvGuard {
475 fn set(lock: std::sync::MutexGuard<'static, ()>, tmp: &std::path::Path) -> EnvGuard {
477 let previous = DIR_VARS.map(std::env::var_os);
478 let dirs = ["cache", "data", "config"].map(|cat| tmp.join(cat));
479 for (name, dir) in DIR_VARS.iter().zip(dirs) {
484 test_support::set(name, &dir);
485 }
486 EnvGuard {
487 previous,
488 _lock: lock,
489 }
490 }
491 }
492
493 impl Drop for EnvGuard {
494 fn drop(&mut self) {
495 for (name, previous) in DIR_VARS.iter().zip(self.previous.iter_mut()) {
498 match previous.take() {
499 Some(value) => unsafe { std::env::set_var(name, value) },
500 None => test_support::remove(name),
501 }
502 }
503 }
504 }
505
506 struct Fixture {
512 _tmp: tempfile::TempDir,
513 _env: EnvGuard,
514 endpoint: Endpoint,
515 }
516
517 fn prepared() -> Fixture {
524 let lock = test_support::lock();
525 let tmp = tempfile::tempdir().unwrap();
526 let env = EnvGuard::set(lock, tmp.path());
527 CTX.init(AppKind::Server);
528 let endpoint = Endpoint::in_dir("sapphire-appservertest", tmp.path().to_path_buf());
529 Fixture {
530 _tmp: tmp,
531 _env: env,
532 endpoint,
533 }
534 }
535
536 async fn wait_until_listening(endpoint: &Endpoint) {
542 let deadline = tokio::time::Instant::now() + Duration::from_secs(5);
543 while !sapphire_ipc::probe(endpoint).await.unwrap() {
544 assert!(
545 tokio::time::Instant::now() < deadline,
546 "the server never started listening"
547 );
548 tokio::time::sleep(Duration::from_millis(10)).await;
549 }
550 }
551
552 #[tokio::test(flavor = "multi_thread")]
559 async fn a_running_server_writes_its_log_file() {
560 let f = prepared();
561 let endpoint = f.endpoint.clone();
562 let server = AppServer::new(&CTX, "0.0.0").endpoint(endpoint.clone());
563 let handle = tokio::spawn(async move { server.run().await });
564 wait_until_listening(&endpoint).await;
565
566 tracing::info!("the server is serving, and this line belongs in its log");
567
568 let (client, _) = sapphire_ipc::connect_or_absent(&endpoint, CTX.app_name, client_info())
569 .await
570 .unwrap()
571 .expect("the server is listening");
572 let _: serde_json::Value = client
573 .call(sapphire_ipc::SHUTDOWN_METHOD, serde_json::json!({}))
574 .await
575 .unwrap();
576 handle.await.unwrap().unwrap();
579
580 let text = std::fs::read_to_string(CTX.log_dir().join("app.log")).unwrap();
581 assert!(
582 text.contains("the server is serving, and this line belongs in its log"),
583 "{text}"
584 );
585 }
586
587 #[tokio::test(flavor = "multi_thread")]
588 async fn a_server_reports_itself_as_service_managed() {
589 let f = prepared();
590 let endpoint = f.endpoint.clone();
591 let server = AppServer::new(&CTX, "0.0.0").endpoint(endpoint.clone());
592 let handle = tokio::spawn(async move { server.run().await });
593 wait_until_listening(&endpoint).await;
594
595 let (client, info) =
596 sapphire_ipc::connect_or_absent(&endpoint, CTX.app_name, client_info())
597 .await
598 .unwrap()
599 .expect("the server is listening");
600 assert_eq!(info.managed_by, ManagedBy::Service);
601
602 let _: serde_json::Value = client
603 .call(sapphire_ipc::SHUTDOWN_METHOD, serde_json::json!({}))
604 .await
605 .unwrap();
606 handle.await.unwrap().unwrap();
607 }
608
609 #[tokio::test(flavor = "multi_thread")]
610 async fn a_server_reports_its_app_api_and_the_handshake_gates_on_it() {
611 let f = prepared();
612 let endpoint = f.endpoint.clone();
613 let server = AppServer::new(&CTX, "0.0.0")
614 .endpoint(endpoint.clone())
615 .app_api(7);
616 let handle = tokio::spawn(async move { server.run().await });
617 wait_until_listening(&endpoint).await;
618
619 let wants = |app_api| ClientInfo {
620 app_api,
621 ..client_info()
622 };
623 let err = sapphire_ipc::connect_or_absent(&endpoint, CTX.app_name, wants(Some(8)))
624 .await
625 .unwrap_err();
626 assert!(
627 matches!(
628 err,
629 sapphire_ipc::Error::AppApiVersionMismatch {
630 running: Some(7),
631 ours: 8,
632 ..
633 }
634 ),
635 "{err:?}"
636 );
637
638 let (client, info) =
639 sapphire_ipc::connect_or_absent(&endpoint, CTX.app_name, wants(Some(7)))
640 .await
641 .unwrap()
642 .expect("the server is listening");
643 assert_eq!(info.app_api, Some(7));
644
645 let _: serde_json::Value = client
646 .call(sapphire_ipc::SHUTDOWN_METHOD, serde_json::json!({}))
647 .await
648 .unwrap();
649 handle.await.unwrap().unwrap();
650 }
651
652 #[tokio::test(flavor = "multi_thread")]
653 async fn a_running_server_answers_server_info() {
654 let f = prepared();
655 let endpoint = f.endpoint.clone();
656
657 let server = AppServer::new(&CTX, "1.2.3").endpoint(endpoint.clone());
658 let handle = tokio::spawn(async move { server.run().await });
659 wait_until_listening(&endpoint).await;
660
661 let (client, info) = sapphire_ipc::connect_or_absent(
662 &endpoint,
663 CTX.app_name,
664 ClientInfo {
665 version: "1.2.3".into(),
666 ..client_info()
667 },
668 )
669 .await
670 .unwrap()
671 .expect("the server is listening");
672 assert_eq!(info.version, "1.2.3");
673
674 let report: StatusReport = client
677 .call(
678 sapphire_backend::protocol::SERVER_INFO,
679 serde_json::json!({}),
680 )
681 .await
682 .unwrap();
683 assert!(report.running);
684 assert_eq!(report.version.as_deref(), Some("1.2.3"));
685 assert_eq!(report.pid, Some(std::process::id()));
686 assert_eq!(report.managed_by, Some(proto::ManagedBy::Service));
687 assert!(report.app.is_empty(), "no status rows were configured");
688
689 let _: serde_json::Value = client
690 .call(sapphire_ipc::SHUTDOWN_METHOD, serde_json::json!({}))
691 .await
692 .unwrap();
693 handle.await.unwrap().unwrap();
694 }
695
696 #[tokio::test(flavor = "multi_thread")]
697 async fn shutdown_stops_the_server() {
698 let f = prepared();
699 let endpoint = f.endpoint.clone();
700
701 let server = AppServer::new(&CTX, "0.0.0").endpoint(endpoint.clone());
702 let handle = tokio::spawn(async move { server.run().await });
703 wait_until_listening(&endpoint).await;
704
705 let (client, _) = sapphire_ipc::connect_or_absent(&endpoint, CTX.app_name, client_info())
706 .await
707 .unwrap()
708 .expect("the server is listening");
709 let _: serde_json::Value = client
710 .call(sapphire_ipc::SHUTDOWN_METHOD, serde_json::json!({}))
711 .await
712 .unwrap();
713
714 tokio::time::timeout(Duration::from_secs(5), handle)
715 .await
716 .expect("the server must stop")
717 .unwrap()
718 .unwrap();
719 assert!(!sapphire_ipc::probe(&endpoint).await.unwrap());
720 }
721
722 #[tokio::test(flavor = "multi_thread")]
723 async fn an_application_can_add_its_own_methods() {
724 let f = prepared();
725 let endpoint = f.endpoint.clone();
726
727 let server = AppServer::new(&CTX, "0.0.0")
728 .endpoint(endpoint.clone())
729 .extend(|r| {
730 r.method("sapphire-appservertest.greet", |_| async move {
731 Ok(serde_json::json!("hello"))
732 })
733 });
734 let handle = tokio::spawn(async move { server.run().await });
735 wait_until_listening(&endpoint).await;
736
737 let (client, _) = sapphire_ipc::connect_or_absent(&endpoint, CTX.app_name, client_info())
738 .await
739 .unwrap()
740 .expect("the server is listening");
741 let greeting: String = client
742 .call("sapphire-appservertest.greet", serde_json::json!({}))
743 .await
744 .unwrap();
745 assert_eq!(greeting, "hello");
746
747 let _: serde_json::Value = client
748 .call(sapphire_ipc::SHUTDOWN_METHOD, serde_json::json!({}))
749 .await
750 .unwrap();
751 handle.await.unwrap().unwrap();
752 }
753
754 #[tokio::test(flavor = "multi_thread")]
755 async fn workspace_init_creates_the_marker_and_tells_the_registry() {
756 let f = prepared();
757 let endpoint = f.endpoint.clone();
758 let server = AppServer::new(&CTX, "0.0.0").endpoint(endpoint.clone());
759 let handle = tokio::spawn(async move { server.run().await });
760 wait_until_listening(&endpoint).await;
761 let (client, _) = sapphire_ipc::connect_or_absent(&endpoint, CTX.app_name, client_info())
762 .await
763 .unwrap()
764 .unwrap();
765
766 let dir = tempfile::tempdir().unwrap();
767 let result: proto::WorkspaceInitResult = client
768 .call(
769 proto::WORKSPACE_INIT,
770 proto::WorkspaceInitParams {
771 dir: dir.path().to_owned(),
772 },
773 )
774 .await
775 .unwrap();
776 assert!(result.created);
777 assert!(dir.path().join(format!(".{}", CTX.app_name)).is_dir());
778
779 let again: proto::WorkspaceInitResult = client
781 .call(
782 proto::WORKSPACE_INIT,
783 proto::WorkspaceInitParams {
784 dir: dir.path().to_owned(),
785 },
786 )
787 .await
788 .unwrap();
789 assert!(!again.created);
790
791 let _: serde_json::Value = client
792 .call(sapphire_ipc::SHUTDOWN_METHOD, serde_json::json!({}))
793 .await
794 .unwrap();
795 handle.await.unwrap().unwrap();
796 }
797
798 #[tokio::test(flavor = "multi_thread")]
799 async fn server_info_carries_the_app_rows() {
800 let f = prepared();
801 let endpoint = f.endpoint.clone();
802 let server = AppServer::new(&CTX, "0.0.0")
803 .endpoint(endpoint.clone())
804 .status_rows(std::sync::Arc::new(|| {
805 vec![StatusRow {
806 name: "sync".into(),
807 value: "enabled".into(),
808 }]
809 }));
810 let handle = tokio::spawn(async move { server.run().await });
811 wait_until_listening(&endpoint).await;
812 let (client, _) = sapphire_ipc::connect_or_absent(&endpoint, CTX.app_name, client_info())
813 .await
814 .unwrap()
815 .unwrap();
816 let report: StatusReport = client
817 .call(
818 sapphire_backend::protocol::SERVER_INFO,
819 serde_json::json!({}),
820 )
821 .await
822 .unwrap();
823 assert!(report.running);
824 assert_eq!(report.app.len(), 1);
825 assert_eq!(report.app[0].name, "sync");
826
827 let _: serde_json::Value = client
828 .call(sapphire_ipc::SHUTDOWN_METHOD, serde_json::json!({}))
829 .await
830 .unwrap();
831 handle.await.unwrap().unwrap();
832 }
833}