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            // The first dials after an enable pin the runtime the same way.
409            runtime.stop_dials().await;
410            // Close every live sync session. A session's reader task holds the replica, and
411            // the session itself sits in the runtime's table until it is cleared, so leaving
412            // one open pins the runtime — and the redb replica stores in it — after the
413            // server is gone (spec §2.2: cancellation is disconnection).
414            runtime.drop_connections().await;
415        }
416        host.close();
417        drop(listener); // removes the socket file on Unix
418
419        // Reap the per-connection serve tasks. Each one pins the router, the router pins
420        // the sync runtime, and the runtime's replica stores are redb databases that stay
421        // locked until the last pin is dropped — a server that left them running would
422        // lock its own successor out of its state (spec §2.2: cancellation is
423        // disconnection). Connections get a grace period to wind down on their own — the
424        // shutdown acknowledgement among them — then the rest are cancelled: a client
425        // that keeps its connection open past shutdown is holding a server that is gone.
426        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    /// The env vars `init_ctx` writes, in the order the guard restores them.
448    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    /// Point the context's directories at `tmp` and restore the previous values (present
465    /// or absent) when dropped — including while unwinding from a panic. Without the
466    /// unconditional restore, a panicking assertion would leave the variables pointing at
467    /// a temp directory the test then deletes, and the context of a later test would
468    /// resolve into the void.
469    struct EnvGuard {
470        previous: [Option<OsString>; 3],
471        _lock: std::sync::MutexGuard<'static, ()>,
472    }
473
474    impl EnvGuard {
475        /// Write the three directory vars while holding the environment lock.
476        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            // SAFETY (via `test_support::set`): `lock` serialises every read and write of
480            // the process environment in this test binary — the `host`, `handlers` and
481            // `events` modules' tests share the same lock — and it is held until `drop`
482            // has restored the old values.
483            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            // SAFETY: `self._lock` still serialises the environment; it is dropped only
496            // after this method returns.
497            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    /// Everything one test needs, held for the test's whole body.
507    ///
508    /// `_tmp` is declared before `_env` so the scratch tree is deleted while the
509    /// environment lock is still held: a sibling test that wakes on the lock must never
510    /// observe the tree mid-deletion, nor env vars pointing at a deleted directory.
511    struct Fixture {
512        _tmp: tempfile::TempDir,
513        _env: EnvGuard,
514        endpoint: Endpoint,
515    }
516
517    /// A listening endpoint in a scratch directory, with the context's directories
518    /// pointed at the same scratch tree.
519    ///
520    /// The caller must keep the fixture (and with it the environment lock) alive for the
521    /// whole test: the static [`CTX`] is first-writer-wins, so while one test runs, every
522    /// other test that would re-point the context's directories must wait.
523    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    /// Wait until something is listening on `endpoint`.
537    ///
538    /// `tokio::spawn(server.run())` only schedules the server; without this wait a fast
539    /// `connect_or_absent` probe can run before `run` has bound the socket, and with
540    /// nothing listening that single unlucky probe is the whole test failing.
541    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    /// A running server writes its log file: the framework's `logging` module
553    /// routes the app's log to `<data dir>/logs/app.log`, and `run()` holds the
554    /// guard for as long as it serves. The event is emitted by this test — the
555    /// subscriber and the file layer are the process's, installed by `CTX.init`
556    /// and `run` — so what lands in the file is exactly what a journald-less
557    /// host would otherwise never see.
558    #[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        // The guard flushes as `run` unwinds; awaiting it is what makes the
577        // file complete before it is read.
578        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        // `server.info` answers the whole typed report, not the bare handshake record:
675        // the CLI reads one shape, and so would a GUI.
676        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        // Idempotent: the second init is a success that did not create.
780        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}