Skip to main content

sapphire_framework_server/
lib.rs

1//! The app server skeleton.
2//!
3//! An application builds one of these, adds its own methods, and runs it. Everything a
4//! sapphire app needs on the server side — owning its workspace, answering `workspace.*`,
5//! pushing events — is here. A server serves one workspace at a time (#215): see
6//! [`Current`].
7//!
8//! See `docs/superpowers/specs/2026-09-16-process-architecture-design.md` §4.
9//!
10//! ```rust,ignore
11//! static CTX: AppContext = AppContext::new("sapphire-journal");
12//!
13//! AppServer::new(&CTX, env!("CARGO_PKG_VERSION"))
14//!     .extend(|router| router.method("journal.create_entry", create_entry))
15//!     .run()
16//!     .await?;
17//! ```
18//!
19//! Application methods are named `<app>.<method>`. The framework owns `workspace.*` and
20//! `server.*`; anything else is the application's.
21
22#![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
33/// How long a server's shutdown waits for its open connections to wind down on their own.
34///
35/// The shutdown acknowledgement is one of those connections; a moment is all a well-behaved
36/// client needs. Whatever still holds on after this is cancelled, so a connection kept open
37/// past shutdown cannot pin the router — and through it the sync runtime's replica stores —
38/// after the server has answered its own shutdown call.
39const 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
64/// An application's server.
65pub struct AppServer {
66    ctx: &'static AppContext,
67    version: &'static str,
68    endpoint: Option<Endpoint>,
69    /// Where `workspace.toml` lives; `None` is the config directory's.
70    selection_file: Option<PathBuf>,
71    host: Arc<WorkspaceHost>,
72    sync: Option<Arc<SyncRuntime>>,
73    extend: Option<Box<dyn FnOnce(Router) -> Router + Send>>,
74    /// The application's own status rows, shown after the framework's in `status` and in
75    /// the `server.info` report.
76    status_rows: Option<Arc<dyn Fn() -> Vec<StatusRow> + Send + Sync>>,
77    /// The version of the application's own API, reported in the handshake.
78    app_api: Option<u32>,
79}
80
81/// The SIGTERM end of the server's select loop, in a shape every platform shares.
82///
83/// [`AppServer::run`]'s select arm awaits `recv()` on one of these, exactly as the
84/// plan writes it for Unix. Unix backs it with the `SignalKind::terminate()`
85/// stream; Windows has no SIGTERM, so there the future never resolves and the arm
86/// exists for the macro's sake and never fires. Without the common shape the arm
87/// would need a `#[cfg]` of its own, which tokio's `select!` rejects once the
88/// attribute removes the arm.
89#[cfg(unix)]
90struct Sigterm(tokio::signal::unix::Signal);
91
92/// The never-firing stand-in for the Unix `Sigterm` where there is no SIGTERM.
93#[cfg(not(unix))]
94struct Sigterm;
95
96#[cfg(unix)]
97impl Sigterm {
98    /// Register interest in SIGTERM.
99    ///
100    /// Called before the listener binds, so a signal arriving the instant the
101    /// socket is up is queued by tokio instead of killing the process with the
102    /// default handler.
103    fn new() -> Result<Self> {
104        Ok(Self(tokio::signal::unix::signal(
105            tokio::signal::unix::SignalKind::terminate(),
106        )?))
107    }
108
109    /// Wait for the next SIGTERM.
110    ///
111    /// Never returns `None`: the stream is infinite, as its documentation states.
112    async fn recv(&mut self) {
113        self.0.recv().await;
114    }
115}
116
117#[cfg(not(unix))]
118impl Sigterm {
119    /// A future that is never ready — the arm awaits it for the macro's sake only.
120    ///
121    /// There is no `new`: this platform has no SIGTERM to register interest in, so
122    /// the loop binds the unit value directly.
123    async fn recv(&mut self) {
124        std::future::pending::<()>().await
125    }
126}
127
128impl AppServer {
129    /// A server for `ctx`'s application, reporting `version` in its handshake.
130    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    /// The application this server serves, as its [`AppContext`] names it.
145    ///
146    /// [`FrameworkCommand`](crate::FrameworkCommand) reads it to build the CLI's endpoint,
147    /// so an application never passes its own name twice.
148    pub fn app_name(&self) -> &'static str {
149        self.ctx.app_name
150    }
151
152    /// Listen somewhere other than the application's default endpoint. Used by tests.
153    pub fn endpoint(mut self, endpoint: Endpoint) -> AppServer {
154        self.endpoint = Some(endpoint);
155        self
156    }
157
158    /// Report `version` as the application's own API version in the handshake: the major
159    /// of the application's API crate, which carries the methods it adds with
160    /// [`extend`](Self::extend). A client that calls those methods names the version it
161    /// expects, and the handshake refuses a server that speaks another.
162    pub fn app_api(mut self, version: u32) -> AppServer {
163        self.app_api = Some(version);
164        self
165    }
166
167    /// Keep the selected workspace (`workspace.toml`) at `path` rather than in the
168    /// application's config directory: for fixtures that run several hosts in one process.
169    pub fn selection_file(mut self, path: PathBuf) -> AppServer {
170        self.selection_file = Some(path);
171        self
172    }
173
174    /// Serve `sync.enable`, `sync.disable`, `sync.map` and `sync.status`, and keep a replica
175    /// of the workspace in step with its files while it is synced.
176    ///
177    /// Without this the server has no sync at all: an application that does not call it
178    /// never talks to the bridge. The runtime is built by the caller because it needs the
179    /// bridge connection, which is the caller's to open and to close.
180    pub fn sync(mut self, runtime: Arc<SyncRuntime>) -> AppServer {
181        // The runtime re-indexes what a session writes, and the index belongs to this host:
182        // tell it where the workspace lives before anything can arrive.
183        runtime.set_host(Arc::clone(&self.host));
184        self.sync = Some(runtime);
185        self
186    }
187
188    /// The application's own rows for the status report: shown after the framework's
189    /// `running` / `version` / `pid` / `managed_by` lines.
190    ///
191    /// The closure is called once per report, so an application's rows may read live
192    /// state; the CLI's `status` and the IPC `server.info` method render the same call's
193    /// output.
194    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    /// What this application's service is: the arguments a service manager starts it with.
200    ///
201    /// `["serve"]`: a service manager starts the executable directly, and the executable's
202    /// bare invocation is `serve` — the subcommand-less default of
203    /// [`FrameworkCommand::Serve`](crate::FrameworkCommand::Serve). A CLI that wants its
204    /// service installed hands this to
205    /// [`ServiceCommand`](sapphire_framework_service::ServiceCommand).
206    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    /// Add the application's own methods.
216    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    /// The workspace this server has open. An application's own handlers use it to reach
222    /// the workspace the same way the framework's do: [`WorkspaceHost::backend`].
223    pub fn host(&self) -> &Arc<WorkspaceHost> {
224        &self.host
225    }
226
227    /// Listen until told to stop, or until a signal arrives.
228    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        // A server is always-on from here on: only `serve` and the service manager start
246        // one, and the service manager starts it for keeps. There is no spawned mode left
247        // to report.
248        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        // The app's log file, held for as long as this server serves: the guard's
257        // drop flushes the writer thread, so the last lines of a clean shutdown land
258        // in the file. The subscriber itself was installed by `ctx.init`; this is what
259        // routes the file layer at `<data dir>/logs/`.
260        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        // Back to the workspace this host had, before the first client can ask for it.
270        let restoring = current.restore().await;
271
272        let mut router = subscribe_method(
273            Arc::clone(&host),
274            current::current_methods(Arc::clone(&current), workspace_router(Arc::clone(&current))),
275        );
276        if sync.is_some() {
277            // `sync_router` is applied *under* the application's own methods so a later
278            // `extend` can still replace one, and after `subscribe_method` so the
279            // `workspace.*` namespace is complete.
280            router = sync_router(Arc::clone(&current), router);
281        }
282        // `server.info` answers the typed [`StatusReport`] — the same shape the CLI's
283        // `status` renders — so the CLI and a future GUI read one record. The rows come
284        // from the application's builder, called once per report.
285        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        // Registered before the bind, so a SIGTERM arriving the instant the socket is up
326        // cannot fall through to the default handler and kill the process. SIGINT is
327        // listened to only through `ctrl_c` (which swallows the default handler on both
328        // platforms): a Unix `SignalKind::interrupt()` stream would double-fire for ^C.
329        #[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        // The watcher, the bridge announcement loop and the dialer, if sync is on. Started
340        // only once the socket is bound, so an early `?` above cannot leave tasks running for
341        // a server that never served. All three are allowed to fail: only sync stops when
342        // they do, and the app server keeps serving files (spec §10). They are aborted with
343        // the server.
344        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                // The dialer is what keeps a session open after the initial exchange, so a
359                // commit reaches a peer without waiting for the next one (spec §4.2).
360                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            // Close every live sync session. A session's reader task holds the replica, and
409            // the session itself sits in the runtime's table until it is cleared, so leaving
410            // one open pins the runtime — and the redb replica stores in it — after the
411            // server is gone (spec §2.2: cancellation is disconnection).
412            runtime.drop_connections().await;
413        }
414        host.close();
415        drop(listener); // removes the socket file on Unix
416
417        // Reap the per-connection serve tasks. Each one pins the router, the router pins
418        // the sync runtime, and the runtime's replica stores are redb databases that stay
419        // locked until the last pin is dropped — a server that left them running would
420        // lock its own successor out of its state (spec §2.2: cancellation is
421        // disconnection). Connections get a grace period to wind down on their own — the
422        // shutdown acknowledgement among them — then the rest are cancelled: a client
423        // that keeps its connection open past shutdown is holding a server that is gone.
424        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    /// The env vars `init_ctx` writes, in the order the guard restores them.
446    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    /// Point the context's directories at `tmp` and restore the previous values (present
463    /// or absent) when dropped — including while unwinding from a panic. Without the
464    /// unconditional restore, a panicking assertion would leave the variables pointing at
465    /// a temp directory the test then deletes, and the context of a later test would
466    /// resolve into the void.
467    struct EnvGuard {
468        previous: [Option<OsString>; 3],
469        _lock: std::sync::MutexGuard<'static, ()>,
470    }
471
472    impl EnvGuard {
473        /// Write the three directory vars while holding the environment lock.
474        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            // SAFETY (via `test_support::set`): `lock` serialises every read and write of
478            // the process environment in this test binary — the `host`, `handlers` and
479            // `events` modules' tests share the same lock — and it is held until `drop`
480            // has restored the old values.
481            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            // SAFETY: `self._lock` still serialises the environment; it is dropped only
494            // after this method returns.
495            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    /// Everything one test needs, held for the test's whole body.
505    ///
506    /// `_tmp` is declared before `_env` so the scratch tree is deleted while the
507    /// environment lock is still held: a sibling test that wakes on the lock must never
508    /// observe the tree mid-deletion, nor env vars pointing at a deleted directory.
509    struct Fixture {
510        _tmp: tempfile::TempDir,
511        _env: EnvGuard,
512        endpoint: Endpoint,
513    }
514
515    /// A listening endpoint in a scratch directory, with the context's directories
516    /// pointed at the same scratch tree.
517    ///
518    /// The caller must keep the fixture (and with it the environment lock) alive for the
519    /// whole test: the static [`CTX`] is first-writer-wins, so while one test runs, every
520    /// other test that would re-point the context's directories must wait.
521    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    /// Wait until something is listening on `endpoint`.
535    ///
536    /// `tokio::spawn(server.run())` only schedules the server; without this wait a fast
537    /// `connect_or_absent` probe can run before `run` has bound the socket, and with
538    /// nothing listening that single unlucky probe is the whole test failing.
539    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    /// A running server writes its log file: the framework's `logging` module
551    /// routes the app's log to `<data dir>/logs/app.log`, and `run()` holds the
552    /// guard for as long as it serves. The event is emitted by this test — the
553    /// subscriber and the file layer are the process's, installed by `CTX.init`
554    /// and `run` — so what lands in the file is exactly what a journald-less
555    /// host would otherwise never see.
556    #[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        // The guard flushes as `run` unwinds; awaiting it is what makes the
575        // file complete before it is read.
576        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        // `server.info` answers the whole typed report, not the bare handshake record:
673        // the CLI reads one shape, and so would a GUI.
674        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        // Idempotent: the second init is a success that did not create.
778        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}