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.drop_connections().await;
413 }
414 host.close();
415 drop(listener); let _ = tokio::time::timeout(SERVE_GRACE, async {
425 while connections.join_next().await.is_some() {}
426 })
427 .await;
428 connections.abort_all();
429 while connections.join_next().await.is_some() {}
430 Ok(())
431 }
432}
433
434#[cfg(test)]
435mod tests {
436 use super::*;
437 use sapphire_ipc::{ClientInfo, Endpoint, ManagedBy};
438 use sapphire_workspace::{AppContext, AppKind};
439 use std::ffi::OsString;
440
441 use crate::test_support;
442
443 static CTX: AppContext = AppContext::new("sapphire-appservertest");
444
445 const DIR_VARS: [&str; 3] = [
447 "SAPPHIRE_APPSERVERTEST_CACHE_DIR",
448 "SAPPHIRE_APPSERVERTEST_DATA_DIR",
449 "SAPPHIRE_APPSERVERTEST_CONFIG_DIR",
450 ];
451
452 fn client_info() -> ClientInfo {
453 ClientInfo {
454 kind: "test".into(),
455 version: "0.0.0".into(),
456 api: sapphire_backend::protocol::API_VERSION,
457 app_api: None,
458 pid: std::process::id(),
459 }
460 }
461
462 struct EnvGuard {
468 previous: [Option<OsString>; 3],
469 _lock: std::sync::MutexGuard<'static, ()>,
470 }
471
472 impl EnvGuard {
473 fn set(lock: std::sync::MutexGuard<'static, ()>, tmp: &std::path::Path) -> EnvGuard {
475 let previous = DIR_VARS.map(std::env::var_os);
476 let dirs = ["cache", "data", "config"].map(|cat| tmp.join(cat));
477 for (name, dir) in DIR_VARS.iter().zip(dirs) {
482 test_support::set(name, &dir);
483 }
484 EnvGuard {
485 previous,
486 _lock: lock,
487 }
488 }
489 }
490
491 impl Drop for EnvGuard {
492 fn drop(&mut self) {
493 for (name, previous) in DIR_VARS.iter().zip(self.previous.iter_mut()) {
496 match previous.take() {
497 Some(value) => unsafe { std::env::set_var(name, value) },
498 None => test_support::remove(name),
499 }
500 }
501 }
502 }
503
504 struct Fixture {
510 _tmp: tempfile::TempDir,
511 _env: EnvGuard,
512 endpoint: Endpoint,
513 }
514
515 fn prepared() -> Fixture {
522 let lock = test_support::lock();
523 let tmp = tempfile::tempdir().unwrap();
524 let env = EnvGuard::set(lock, tmp.path());
525 CTX.init(AppKind::Server);
526 let endpoint = Endpoint::in_dir("sapphire-appservertest", tmp.path().to_path_buf());
527 Fixture {
528 _tmp: tmp,
529 _env: env,
530 endpoint,
531 }
532 }
533
534 async fn wait_until_listening(endpoint: &Endpoint) {
540 let deadline = tokio::time::Instant::now() + Duration::from_secs(5);
541 while !sapphire_ipc::probe(endpoint).await.unwrap() {
542 assert!(
543 tokio::time::Instant::now() < deadline,
544 "the server never started listening"
545 );
546 tokio::time::sleep(Duration::from_millis(10)).await;
547 }
548 }
549
550 #[tokio::test(flavor = "multi_thread")]
557 async fn a_running_server_writes_its_log_file() {
558 let f = prepared();
559 let endpoint = f.endpoint.clone();
560 let server = AppServer::new(&CTX, "0.0.0").endpoint(endpoint.clone());
561 let handle = tokio::spawn(async move { server.run().await });
562 wait_until_listening(&endpoint).await;
563
564 tracing::info!("the server is serving, and this line belongs in its log");
565
566 let (client, _) = sapphire_ipc::connect_or_absent(&endpoint, CTX.app_name, client_info())
567 .await
568 .unwrap()
569 .expect("the server is listening");
570 let _: serde_json::Value = client
571 .call(sapphire_ipc::SHUTDOWN_METHOD, serde_json::json!({}))
572 .await
573 .unwrap();
574 handle.await.unwrap().unwrap();
577
578 let text = std::fs::read_to_string(CTX.log_dir().join("app.log")).unwrap();
579 assert!(
580 text.contains("the server is serving, and this line belongs in its log"),
581 "{text}"
582 );
583 }
584
585 #[tokio::test(flavor = "multi_thread")]
586 async fn a_server_reports_itself_as_service_managed() {
587 let f = prepared();
588 let endpoint = f.endpoint.clone();
589 let server = AppServer::new(&CTX, "0.0.0").endpoint(endpoint.clone());
590 let handle = tokio::spawn(async move { server.run().await });
591 wait_until_listening(&endpoint).await;
592
593 let (client, info) =
594 sapphire_ipc::connect_or_absent(&endpoint, CTX.app_name, client_info())
595 .await
596 .unwrap()
597 .expect("the server is listening");
598 assert_eq!(info.managed_by, ManagedBy::Service);
599
600 let _: serde_json::Value = client
601 .call(sapphire_ipc::SHUTDOWN_METHOD, serde_json::json!({}))
602 .await
603 .unwrap();
604 handle.await.unwrap().unwrap();
605 }
606
607 #[tokio::test(flavor = "multi_thread")]
608 async fn a_server_reports_its_app_api_and_the_handshake_gates_on_it() {
609 let f = prepared();
610 let endpoint = f.endpoint.clone();
611 let server = AppServer::new(&CTX, "0.0.0")
612 .endpoint(endpoint.clone())
613 .app_api(7);
614 let handle = tokio::spawn(async move { server.run().await });
615 wait_until_listening(&endpoint).await;
616
617 let wants = |app_api| ClientInfo {
618 app_api,
619 ..client_info()
620 };
621 let err = sapphire_ipc::connect_or_absent(&endpoint, CTX.app_name, wants(Some(8)))
622 .await
623 .unwrap_err();
624 assert!(
625 matches!(
626 err,
627 sapphire_ipc::Error::AppApiVersionMismatch {
628 running: Some(7),
629 ours: 8,
630 ..
631 }
632 ),
633 "{err:?}"
634 );
635
636 let (client, info) =
637 sapphire_ipc::connect_or_absent(&endpoint, CTX.app_name, wants(Some(7)))
638 .await
639 .unwrap()
640 .expect("the server is listening");
641 assert_eq!(info.app_api, Some(7));
642
643 let _: serde_json::Value = client
644 .call(sapphire_ipc::SHUTDOWN_METHOD, serde_json::json!({}))
645 .await
646 .unwrap();
647 handle.await.unwrap().unwrap();
648 }
649
650 #[tokio::test(flavor = "multi_thread")]
651 async fn a_running_server_answers_server_info() {
652 let f = prepared();
653 let endpoint = f.endpoint.clone();
654
655 let server = AppServer::new(&CTX, "1.2.3").endpoint(endpoint.clone());
656 let handle = tokio::spawn(async move { server.run().await });
657 wait_until_listening(&endpoint).await;
658
659 let (client, info) = sapphire_ipc::connect_or_absent(
660 &endpoint,
661 CTX.app_name,
662 ClientInfo {
663 version: "1.2.3".into(),
664 ..client_info()
665 },
666 )
667 .await
668 .unwrap()
669 .expect("the server is listening");
670 assert_eq!(info.version, "1.2.3");
671
672 let report: StatusReport = client
675 .call(
676 sapphire_backend::protocol::SERVER_INFO,
677 serde_json::json!({}),
678 )
679 .await
680 .unwrap();
681 assert!(report.running);
682 assert_eq!(report.version.as_deref(), Some("1.2.3"));
683 assert_eq!(report.pid, Some(std::process::id()));
684 assert_eq!(report.managed_by, Some(proto::ManagedBy::Service));
685 assert!(report.app.is_empty(), "no status rows were configured");
686
687 let _: serde_json::Value = client
688 .call(sapphire_ipc::SHUTDOWN_METHOD, serde_json::json!({}))
689 .await
690 .unwrap();
691 handle.await.unwrap().unwrap();
692 }
693
694 #[tokio::test(flavor = "multi_thread")]
695 async fn shutdown_stops_the_server() {
696 let f = prepared();
697 let endpoint = f.endpoint.clone();
698
699 let server = AppServer::new(&CTX, "0.0.0").endpoint(endpoint.clone());
700 let handle = tokio::spawn(async move { server.run().await });
701 wait_until_listening(&endpoint).await;
702
703 let (client, _) = sapphire_ipc::connect_or_absent(&endpoint, CTX.app_name, client_info())
704 .await
705 .unwrap()
706 .expect("the server is listening");
707 let _: serde_json::Value = client
708 .call(sapphire_ipc::SHUTDOWN_METHOD, serde_json::json!({}))
709 .await
710 .unwrap();
711
712 tokio::time::timeout(Duration::from_secs(5), handle)
713 .await
714 .expect("the server must stop")
715 .unwrap()
716 .unwrap();
717 assert!(!sapphire_ipc::probe(&endpoint).await.unwrap());
718 }
719
720 #[tokio::test(flavor = "multi_thread")]
721 async fn an_application_can_add_its_own_methods() {
722 let f = prepared();
723 let endpoint = f.endpoint.clone();
724
725 let server = AppServer::new(&CTX, "0.0.0")
726 .endpoint(endpoint.clone())
727 .extend(|r| {
728 r.method("sapphire-appservertest.greet", |_| async move {
729 Ok(serde_json::json!("hello"))
730 })
731 });
732 let handle = tokio::spawn(async move { server.run().await });
733 wait_until_listening(&endpoint).await;
734
735 let (client, _) = sapphire_ipc::connect_or_absent(&endpoint, CTX.app_name, client_info())
736 .await
737 .unwrap()
738 .expect("the server is listening");
739 let greeting: String = client
740 .call("sapphire-appservertest.greet", serde_json::json!({}))
741 .await
742 .unwrap();
743 assert_eq!(greeting, "hello");
744
745 let _: serde_json::Value = client
746 .call(sapphire_ipc::SHUTDOWN_METHOD, serde_json::json!({}))
747 .await
748 .unwrap();
749 handle.await.unwrap().unwrap();
750 }
751
752 #[tokio::test(flavor = "multi_thread")]
753 async fn workspace_init_creates_the_marker_and_tells_the_registry() {
754 let f = prepared();
755 let endpoint = f.endpoint.clone();
756 let server = AppServer::new(&CTX, "0.0.0").endpoint(endpoint.clone());
757 let handle = tokio::spawn(async move { server.run().await });
758 wait_until_listening(&endpoint).await;
759 let (client, _) = sapphire_ipc::connect_or_absent(&endpoint, CTX.app_name, client_info())
760 .await
761 .unwrap()
762 .unwrap();
763
764 let dir = tempfile::tempdir().unwrap();
765 let result: proto::WorkspaceInitResult = client
766 .call(
767 proto::WORKSPACE_INIT,
768 proto::WorkspaceInitParams {
769 dir: dir.path().to_owned(),
770 },
771 )
772 .await
773 .unwrap();
774 assert!(result.created);
775 assert!(dir.path().join(format!(".{}", CTX.app_name)).is_dir());
776
777 let again: proto::WorkspaceInitResult = client
779 .call(
780 proto::WORKSPACE_INIT,
781 proto::WorkspaceInitParams {
782 dir: dir.path().to_owned(),
783 },
784 )
785 .await
786 .unwrap();
787 assert!(!again.created);
788
789 let _: serde_json::Value = client
790 .call(sapphire_ipc::SHUTDOWN_METHOD, serde_json::json!({}))
791 .await
792 .unwrap();
793 handle.await.unwrap().unwrap();
794 }
795
796 #[tokio::test(flavor = "multi_thread")]
797 async fn server_info_carries_the_app_rows() {
798 let f = prepared();
799 let endpoint = f.endpoint.clone();
800 let server = AppServer::new(&CTX, "0.0.0")
801 .endpoint(endpoint.clone())
802 .status_rows(std::sync::Arc::new(|| {
803 vec![StatusRow {
804 name: "sync".into(),
805 value: "enabled".into(),
806 }]
807 }));
808 let handle = tokio::spawn(async move { server.run().await });
809 wait_until_listening(&endpoint).await;
810 let (client, _) = sapphire_ipc::connect_or_absent(&endpoint, CTX.app_name, client_info())
811 .await
812 .unwrap()
813 .unwrap();
814 let report: StatusReport = client
815 .call(
816 sapphire_backend::protocol::SERVER_INFO,
817 serde_json::json!({}),
818 )
819 .await
820 .unwrap();
821 assert!(report.running);
822 assert_eq!(report.app.len(), 1);
823 assert_eq!(report.app[0].name, "sync");
824
825 let _: serde_json::Value = client
826 .call(sapphire_ipc::SHUTDOWN_METHOD, serde_json::json!({}))
827 .await
828 .unwrap();
829 handle.await.unwrap().unwrap();
830 }
831}