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 config;
43mod current;
44mod error;
45mod events;
46mod handlers;
47mod host;
48#[cfg(feature = "http")]
49mod http;
50mod selection;
51pub mod sync;
52#[cfg(test)]
53mod test_support;
54
55pub use command::{
56    DeviceCommand, FrameworkCommand, StatusReport, StatusRow, WorkgroupCommand, WorkspaceCommand,
57    render_workspace,
58};
59pub use config::{HttpConfig, McpConfig, SERVER_CONFIG_FILE, ServerConfig};
60pub use current::Current;
61pub use error::{Error, Result};
62pub use events::subscribe_method;
63pub use handlers::workspace_router;
64pub use host::WorkspaceHost;
65pub use selection::{SELECTION_FILE, Selection, SelectionFile};
66pub use sync::{BackfillTiming, SyncRuntime, SyncStatus, sync_router};
67
68/// The MCP tools an application serves, and how (feature `mcp`).
69#[cfg(feature = "mcp")]
70pub use sapphire_framework_mcp as mcp;
71
72/// An application's server.
73pub struct AppServer {
74    ctx: &'static AppContext,
75    version: &'static str,
76    endpoint: Option<Endpoint>,
77    /// Where `workspace.toml` lives; `None` is the config directory's.
78    selection_file: Option<PathBuf>,
79    host: Arc<WorkspaceHost>,
80    sync: Option<Arc<SyncRuntime>>,
81    extend: Option<Box<dyn FnOnce(Router) -> Router + Send>>,
82    /// The application's own status rows, shown after the framework's in `status` and in
83    /// the `server.info` report.
84    status_rows: Option<Arc<dyn Fn() -> Vec<StatusRow> + Send + Sync>>,
85    /// The version of the application's own API, reported in the handshake.
86    app_api: Option<u32>,
87    /// `server.toml`'s settings, when given rather than read from the config directory.
88    config: Option<ServerConfig>,
89    /// Where the HTTP listener binds when `server.toml` does not say.
90    #[cfg(feature = "http")]
91    http_listen: Option<std::net::SocketAddr>,
92    /// The application's own HTTP routes.
93    #[cfg(feature = "http")]
94    http_routes: Option<axum::Router>,
95    /// How the HTTP routes check a token; `None` asks the bridge.
96    #[cfg(feature = "http")]
97    http_auth: Option<sapphire_framework_keys::AuthConfig>,
98    /// The application's MCP handler, for the `mcp` subcommand and `/mcp`.
99    #[cfg(feature = "mcp")]
100    mcp: sapphire_framework_mcp::McpService,
101}
102
103/// The SIGTERM end of the server's select loop, in a shape every platform shares.
104///
105/// [`AppServer::run`]'s select arm awaits `recv()` on one of these, exactly as the
106/// plan writes it for Unix. Unix backs it with the `SignalKind::terminate()`
107/// stream; Windows has no SIGTERM, so there the future never resolves and the arm
108/// exists for the macro's sake and never fires. Without the common shape the arm
109/// would need a `#[cfg]` of its own, which tokio's `select!` rejects once the
110/// attribute removes the arm.
111#[cfg(unix)]
112struct Sigterm(tokio::signal::unix::Signal);
113
114/// The never-firing stand-in for the Unix `Sigterm` where there is no SIGTERM.
115#[cfg(not(unix))]
116struct Sigterm;
117
118#[cfg(unix)]
119impl Sigterm {
120    /// Register interest in SIGTERM.
121    ///
122    /// Called before the listener binds, so a signal arriving the instant the
123    /// socket is up is queued by tokio instead of killing the process with the
124    /// default handler.
125    fn new() -> Result<Self> {
126        Ok(Self(tokio::signal::unix::signal(
127            tokio::signal::unix::SignalKind::terminate(),
128        )?))
129    }
130
131    /// Wait for the next SIGTERM.
132    ///
133    /// Never returns `None`: the stream is infinite, as its documentation states.
134    async fn recv(&mut self) {
135        self.0.recv().await;
136    }
137}
138
139#[cfg(not(unix))]
140impl Sigterm {
141    /// A future that is never ready — the arm awaits it for the macro's sake only.
142    ///
143    /// There is no `new`: this platform has no SIGTERM to register interest in, so
144    /// the loop binds the unit value directly.
145    async fn recv(&mut self) {
146        std::future::pending::<()>().await
147    }
148}
149
150impl AppServer {
151    /// A server for `ctx`'s application, reporting `version` in its handshake.
152    pub fn new(ctx: &'static AppContext, version: &'static str) -> AppServer {
153        AppServer {
154            ctx,
155            version,
156            endpoint: None,
157            selection_file: None,
158            host: Arc::new(WorkspaceHost::new(ctx)),
159            sync: None,
160            extend: None,
161            status_rows: None,
162            app_api: None,
163            config: None,
164            #[cfg(feature = "http")]
165            http_listen: None,
166            #[cfg(feature = "http")]
167            http_routes: None,
168            #[cfg(feature = "http")]
169            http_auth: None,
170            #[cfg(feature = "mcp")]
171            mcp: sapphire_framework_mcp::McpService::framework(),
172        }
173    }
174
175    /// The application this server serves, as its [`AppContext`] names it.
176    ///
177    /// [`FrameworkCommand`](crate::FrameworkCommand) reads it to build the CLI's endpoint,
178    /// so an application never passes its own name twice.
179    pub fn app_name(&self) -> &'static str {
180        self.ctx.app_name
181    }
182
183    /// Listen somewhere other than the application's default endpoint. Used by tests.
184    pub fn endpoint(mut self, endpoint: Endpoint) -> AppServer {
185        self.endpoint = Some(endpoint);
186        self
187    }
188
189    /// Report `version` as the application's own API version in the handshake: the major
190    /// of the application's API crate, which carries the methods it adds with
191    /// [`extend`](Self::extend). A client that calls those methods names the version it
192    /// expects, and the handshake refuses a server that speaks another.
193    pub fn app_api(mut self, version: u32) -> AppServer {
194        self.app_api = Some(version);
195        self
196    }
197
198    /// Use `config` rather than reading `<config dir>/server.toml`: for fixtures.
199    pub fn config(mut self, config: ServerConfig) -> AppServer {
200        self.config = Some(config);
201        self
202    }
203
204    /// Where the HTTP listener binds unless `server.toml` says otherwise: the application's
205    /// own port. Without it, a host that serves anything over HTTP names the address in
206    /// `[http] listen`.
207    #[cfg(feature = "http")]
208    pub fn http_listen(mut self, addr: std::net::SocketAddr) -> AppServer {
209        self.http_listen = Some(addr);
210        self
211    }
212
213    /// Serve the application's own HTTP routes on the server's listener, behind the same
214    /// external-device token as `/mcp`. The routes are served whenever they are given;
215    /// `/mcp` only when `server.toml` turns it on.
216    #[cfg(feature = "http")]
217    pub fn http(mut self, routes: axum::Router) -> AppServer {
218        self.http_routes = Some(routes);
219        self
220    }
221
222    /// Check HTTP tokens with `auth` rather than with the bridge: for fixtures.
223    #[cfg(feature = "http")]
224    pub fn http_auth(mut self, auth: sapphire_framework_keys::AuthConfig) -> AppServer {
225        self.http_auth = Some(auth);
226        self
227    }
228
229    /// Answer MCP with the application's own handler, rather than the framework's tools
230    /// alone: on stdio for the `mcp` subcommand, and at `/mcp` when `server.toml` turns it
231    /// on.
232    #[cfg(feature = "mcp")]
233    pub fn mcp(mut self, service: sapphire_framework_mcp::McpService) -> AppServer {
234        self.mcp = service;
235        self
236    }
237
238    /// Serve the application's MCP tools on this process's stdio, until the agent closes
239    /// it: the `mcp` subcommand.
240    ///
241    /// This is the client side: the tools reach the running server over its IPC endpoint,
242    /// as the CLI does, and nothing here starts one.
243    #[cfg(feature = "mcp")]
244    pub async fn serve_mcp_stdio(self, version: &'static str) -> Result<()> {
245        let endpoint = match self.endpoint {
246            Some(e) => e,
247            None => Endpoint::for_app(self.ctx.app_name)?,
248        };
249        let ctx = sapphire_framework_mcp::ToolContext::dial(
250            self.ctx.app_name,
251            version,
252            self.app_api,
253            endpoint,
254        );
255        self.mcp
256            .serve_stdio(ctx)
257            .await
258            .map_err(|e| Error::Mcp(e.to_string()))
259    }
260
261    /// Keep the selected workspace (`workspace.toml`) at `path` rather than in the
262    /// application's config directory: for fixtures that run several hosts in one process.
263    pub fn selection_file(mut self, path: PathBuf) -> AppServer {
264        self.selection_file = Some(path);
265        self
266    }
267
268    /// Serve `sync.enable`, `sync.disable`, `sync.map` and `sync.status`, and keep a replica
269    /// of the workspace in step with its files while it is synced.
270    ///
271    /// Without this the server has no sync at all: an application that does not call it
272    /// never talks to the bridge. The runtime is built by the caller because it needs the
273    /// bridge connection, which is the caller's to open and to close.
274    pub fn sync(mut self, runtime: Arc<SyncRuntime>) -> AppServer {
275        // The runtime re-indexes what a session writes, and the index belongs to this host:
276        // tell it where the workspace lives before anything can arrive.
277        runtime.set_host(Arc::clone(&self.host));
278        self.sync = Some(runtime);
279        self
280    }
281
282    /// The application's own rows for the status report: shown after the framework's
283    /// `running` / `version` / `pid` / `managed_by` lines.
284    ///
285    /// The closure is called once per report, so an application's rows may read live
286    /// state; the CLI's `status` and the IPC `server.info` method render the same call's
287    /// output.
288    pub fn status_rows(mut self, rows: Arc<dyn Fn() -> Vec<StatusRow> + Send + Sync>) -> AppServer {
289        self.status_rows = Some(rows);
290        self
291    }
292
293    /// What this application's service is: the arguments a service manager starts it with.
294    ///
295    /// `["serve"]`: a service manager starts the executable directly, and the executable's
296    /// bare invocation is `serve` — the subcommand-less default of
297    /// [`FrameworkCommand::Serve`](crate::FrameworkCommand::Serve). A CLI that wants its
298    /// service installed hands this to
299    /// [`ServiceCommand`](sapphire_framework_service::ServiceCommand).
300    pub fn service_spec(&self) -> ServiceSpec {
301        ServiceSpec {
302            app_name: self.ctx.app_name,
303            description: format!("{} server {}", self.ctx.app_name, self.version),
304            args: vec!["serve".to_owned()],
305            post_install: None,
306        }
307    }
308
309    /// Add the application's own methods.
310    pub fn extend(mut self, f: impl FnOnce(Router) -> Router + Send + 'static) -> AppServer {
311        self.extend = Some(Box::new(f));
312        self
313    }
314
315    /// The workspace this server has open. An application's own handlers use it to reach
316    /// the workspace the same way the framework's do: [`WorkspaceHost::backend`].
317    pub fn host(&self) -> &Arc<WorkspaceHost> {
318        &self.host
319    }
320
321    /// Listen until told to stop, or until a signal arrives.
322    pub async fn run(self) -> Result<()> {
323        let AppServer {
324            ctx,
325            version,
326            endpoint,
327            selection_file,
328            host,
329            sync,
330            extend,
331            status_rows,
332            app_api,
333            config,
334            #[cfg(feature = "http")]
335            http_listen,
336            #[cfg(feature = "http")]
337            http_routes,
338            #[cfg(feature = "http")]
339            http_auth,
340            #[cfg(feature = "mcp")]
341            mcp,
342        } = self;
343
344        let endpoint = match endpoint {
345            Some(e) => e,
346            None => Endpoint::for_app(ctx.app_name)?,
347        };
348        // A server is always-on from here on: only `serve` and the service manager start
349        // one, and the service manager starts it for keeps. There is no spawned mode left
350        // to report.
351        let info = ServerInfo {
352            version: version.to_owned(),
353            api: proto::API_VERSION,
354            app_api,
355            pid: std::process::id(),
356            managed_by: ManagedBy::Service,
357        };
358
359        // The app's log file, held for as long as this server serves: the guard's
360        // drop flushes the writer thread, so the last lines of a clean shutdown land
361        // in the file. The subscriber itself was installed by `ctx.init`; this is what
362        // routes the file layer at `<data dir>/logs/`.
363        let _log = sapphire_workspace::logging::install(ctx)?;
364
365        let config = match config {
366            Some(config) => config,
367            None => ServerConfig::load_for_app(ctx)?,
368        };
369        #[cfg(not(feature = "mcp"))]
370        if config.mcp.http {
371            tracing::warn!(
372                "server.toml turns MCP over HTTP on, but this build of {} has no MCP",
373                ctx.app_name
374            );
375        }
376
377        let (stop_tx, mut stop_rx) = tokio::sync::watch::channel(false);
378
379        let file = match selection_file {
380            Some(path) => SelectionFile::at(path),
381            None => SelectionFile::for_app(ctx),
382        };
383        let current = Arc::new(Current::new(ctx, Arc::clone(&host), sync.clone(), file));
384        // Back to the workspace this host had, before the first client can ask for it.
385        let restoring = current.restore().await;
386
387        let mut router = subscribe_method(
388            Arc::clone(&host),
389            current::current_methods(Arc::clone(&current), workspace_router(Arc::clone(&current))),
390        );
391        if sync.is_some() {
392            // `sync_router` is applied *under* the application's own methods so a later
393            // `extend` can still replace one, and after `subscribe_method` so the
394            // `workspace.*` namespace is complete.
395            router = sync_router(Arc::clone(&current), router);
396        }
397        // `server.info` answers the typed [`StatusReport`] — the same shape the CLI's
398        // `status` renders — so the CLI and a future GUI read one record. The rows come
399        // from the application's builder, called once per report.
400        router = router
401            .method(proto::SERVER_INFO, {
402                let info = info.clone();
403                let status_rows = status_rows.clone();
404                move |_| {
405                    let info = info.clone();
406                    let status_rows = status_rows.clone();
407                    async move {
408                        let app = status_rows.as_ref().map(|rows| rows()).unwrap_or_default();
409                        let report = StatusReport {
410                            running: true,
411                            version: Some(info.version),
412                            pid: Some(info.pid),
413                            managed_by: Some(match info.managed_by {
414                                ManagedBy::Service => proto::ManagedBy::Service,
415                                ManagedBy::Spawned => proto::ManagedBy::Spawned,
416                            }),
417                            app,
418                        };
419                        serde_json::to_value(report)
420                            .map_err(|e| sapphire_ipc::RpcError::internal(e.to_string()))
421                    }
422                }
423            })
424            .method(sapphire_ipc::SHUTDOWN_METHOD, {
425                let stop_tx = stop_tx.clone();
426                move |_| {
427                    let stop_tx = stop_tx.clone();
428                    async move {
429                        let _ = stop_tx.send(true);
430                        serde_json::to_value(proto::Ack {})
431                            .map_err(|e| sapphire_ipc::RpcError::internal(e.to_string()))
432                    }
433                }
434            });
435        if let Some(extend) = extend {
436            router = extend(router);
437        }
438        let router = Arc::new(router);
439
440        // Registered before the bind, so a SIGTERM arriving the instant the socket is up
441        // cannot fall through to the default handler and kill the process. SIGINT is
442        // listened to only through `ctrl_c` (which swallows the default handler on both
443        // platforms): a Unix `SignalKind::interrupt()` stream would double-fire for ^C.
444        #[cfg(unix)]
445        let mut sigterm = Sigterm::new()?;
446        #[cfg(not(unix))]
447        let mut sigterm = Sigterm;
448
449        #[cfg(unix)]
450        let listener = sapphire_ipc::bind(&endpoint).await?;
451        #[cfg(windows)]
452        let mut listener = sapphire_ipc::bind(&endpoint)?;
453
454        let mut connections = tokio::task::JoinSet::new();
455
456        // The HTTP listener, when anything is served over it. Started once the IPC socket
457        // is bound, for the same reason as the sync tasks below. `/mcp`'s tools reach this
458        // server the way the `mcp` subcommand's do — over IPC — on an in-process connection
459        // served like any other.
460        #[cfg(feature = "http")]
461        let http_stop = tokio_util::sync::CancellationToken::new();
462        #[cfg(feature = "http")]
463        let _http = {
464            let mut routes = http_routes;
465            #[cfg(feature = "mcp")]
466            if config.mcp.http {
467                let (ours, theirs) = sapphire_ipc::Connection::pair();
468                {
469                    let router = Arc::clone(&router);
470                    let info = info.clone();
471                    let app = ctx.app_name;
472                    connections.spawn(async move {
473                        let _ = serve(theirs, router, app, info).await;
474                    });
475                }
476                let client_info = sapphire_ipc::ClientInfo {
477                    kind: sapphire_framework_mcp::CLIENT_KIND.to_owned(),
478                    version: version.to_owned(),
479                    api: proto::API_VERSION,
480                    app_api,
481                    pid: std::process::id(),
482                };
483                let (client, _) =
484                    sapphire_ipc::Client::handshake(ours, ctx.app_name, client_info).await?;
485                let tools = sapphire_framework_mcp::ToolContext::connected(
486                    ctx.app_name,
487                    version,
488                    Arc::new(client),
489                );
490                let mcp_routes =
491                    mcp.http_router(tools, &config.http.allowed_hosts, http_stop.child_token());
492                routes = Some(match routes {
493                    Some(routes) => routes.merge(mcp_routes),
494                    None => mcp_routes,
495                });
496            }
497            match (routes, config.http.listen.or(http_listen)) {
498                (None, _) => None,
499                (Some(_), None) => {
500                    tracing::error!(
501                        "nothing to bind HTTP to: set `[http] listen` in {SERVER_CONFIG_FILE}"
502                    );
503                    None
504                }
505                (Some(routes), Some(addr)) => {
506                    let auth = http_auth.unwrap_or_else(|| {
507                        sapphire_framework_keys::AuthConfig::new(Arc::new(
508                            sapphire_framework_keys::BridgeVerifier::new(ctx.app_name, version),
509                        ))
510                    });
511                    http::start(addr, routes, auth, http_stop.clone()).await
512                }
513            }
514        };
515
516        // The watcher, the bridge announcement loop and the dialer, if sync is on. Started
517        // only once the socket is bound, so an early `?` above cannot leave tasks running for
518        // a server that never served. All three are allowed to fail: only sync stops when
519        // they do, and the app server keeps serving files (spec §10). They are aborted with
520        // the server.
521        let _sync_tasks = match &sync {
522            Some(runtime) => {
523                let driver = Arc::clone(runtime);
524                let announcements = tokio::spawn(async move {
525                    if let Err(err) = driver.run().await {
526                        tracing::warn!("the bridge announcement loop ended: {err}");
527                    }
528                });
529                let changing = Arc::clone(runtime);
530                let watching = tokio::spawn(async move {
531                    if let Err(err) = changing.watch_changes().await {
532                        tracing::warn!("the file watcher ended: {err}");
533                    }
534                });
535                // The dialer is what keeps a session open after the initial exchange, so a
536                // commit reaches a peer without waiting for the next one (spec §4.2).
537                let dialling = Arc::clone(runtime);
538                let dialling = tokio::spawn(async move {
539                    if let Err(err) = dialling.dial_loop().await {
540                        tracing::warn!("the live dial loop ended: {err}");
541                    }
542                });
543                Some((announcements, watching, dialling))
544            }
545            None => None,
546        };
547
548        loop {
549            tokio::select! {
550                changed = stop_rx.changed() => {
551                    if changed.is_err() || *stop_rx.borrow() {
552                        break;
553                    }
554                }
555                _ = tokio::signal::ctrl_c() => {
556                    tracing::info!("interrupted; shutting down");
557                    break;
558                }
559                _ = sigterm.recv() => {
560                    tracing::info!("terminated; shutting down");
561                    break;
562                }
563                accepted = listener.accept() => {
564                    let conn = accepted?;
565                    let router = Arc::clone(&router);
566                    let app = ctx.app_name;
567                    let info = info.clone();
568                    connections.spawn(async move {
569                        let _ = serve(conn, router, app, info).await;
570                    });
571                }
572            }
573        }
574
575        if let Some(restoring) = restoring {
576            restoring.abort();
577        }
578        // HTTP first: its sessions hold a connection to this server, which the reaping
579        // below waits for.
580        #[cfg(feature = "http")]
581        {
582            http_stop.cancel();
583            if let Some((_, mut task)) = _http
584                && tokio::time::timeout(SERVE_GRACE, &mut task).await.is_err()
585            {
586                tracing::debug!("the HTTP listener did not stop in time");
587                task.abort();
588            }
589        }
590        if let Some((announcements, watching, dialling)) = _sync_tasks {
591            announcements.abort();
592            watching.abort();
593            dialling.abort();
594        }
595        if let Some(runtime) = &sync {
596            // The first dials after an enable pin the runtime the same way.
597            runtime.stop_dials().await;
598            // Close every live sync session. A session's reader task holds the replica, and
599            // the session itself sits in the runtime's table until it is cleared, so leaving
600            // one open pins the runtime — and the redb replica stores in it — after the
601            // server is gone (spec §2.2: cancellation is disconnection).
602            runtime.drop_connections().await;
603        }
604        host.close();
605        drop(listener); // removes the socket file on Unix
606
607        // Reap the per-connection serve tasks. Each one pins the router, the router pins
608        // the sync runtime, and the runtime's replica stores are redb databases that stay
609        // locked until the last pin is dropped — a server that left them running would
610        // lock its own successor out of its state (spec §2.2: cancellation is
611        // disconnection). Connections get a grace period to wind down on their own — the
612        // shutdown acknowledgement among them — then the rest are cancelled: a client
613        // that keeps its connection open past shutdown is holding a server that is gone.
614        let _ = tokio::time::timeout(SERVE_GRACE, async {
615            while connections.join_next().await.is_some() {}
616        })
617        .await;
618        connections.abort_all();
619        while connections.join_next().await.is_some() {}
620        Ok(())
621    }
622}
623
624#[cfg(test)]
625mod tests {
626    use super::*;
627    use sapphire_ipc::{ClientInfo, Endpoint, ManagedBy};
628    use sapphire_workspace::{AppContext, AppKind};
629    use std::ffi::OsString;
630
631    use crate::test_support;
632
633    static CTX: AppContext = AppContext::new("sapphire-appservertest");
634
635    /// The env vars `init_ctx` writes, in the order the guard restores them.
636    const DIR_VARS: [&str; 3] = [
637        "SAPPHIRE_APPSERVERTEST_CACHE_DIR",
638        "SAPPHIRE_APPSERVERTEST_DATA_DIR",
639        "SAPPHIRE_APPSERVERTEST_CONFIG_DIR",
640    ];
641
642    fn client_info() -> ClientInfo {
643        ClientInfo {
644            kind: "test".into(),
645            version: "0.0.0".into(),
646            api: sapphire_backend::protocol::API_VERSION,
647            app_api: None,
648            pid: std::process::id(),
649        }
650    }
651
652    /// Point the context's directories at `tmp` and restore the previous values (present
653    /// or absent) when dropped — including while unwinding from a panic. Without the
654    /// unconditional restore, a panicking assertion would leave the variables pointing at
655    /// a temp directory the test then deletes, and the context of a later test would
656    /// resolve into the void.
657    struct EnvGuard {
658        previous: [Option<OsString>; 3],
659        _lock: std::sync::MutexGuard<'static, ()>,
660    }
661
662    impl EnvGuard {
663        /// Write the three directory vars while holding the environment lock.
664        fn set(lock: std::sync::MutexGuard<'static, ()>, tmp: &std::path::Path) -> EnvGuard {
665            let previous = DIR_VARS.map(std::env::var_os);
666            let dirs = ["cache", "data", "config"].map(|cat| tmp.join(cat));
667            // SAFETY (via `test_support::set`): `lock` serialises every read and write of
668            // the process environment in this test binary — the `host`, `handlers` and
669            // `events` modules' tests share the same lock — and it is held until `drop`
670            // has restored the old values.
671            for (name, dir) in DIR_VARS.iter().zip(dirs) {
672                test_support::set(name, &dir);
673            }
674            EnvGuard {
675                previous,
676                _lock: lock,
677            }
678        }
679    }
680
681    impl Drop for EnvGuard {
682        fn drop(&mut self) {
683            // SAFETY: `self._lock` still serialises the environment; it is dropped only
684            // after this method returns.
685            for (name, previous) in DIR_VARS.iter().zip(self.previous.iter_mut()) {
686                match previous.take() {
687                    Some(value) => unsafe { std::env::set_var(name, value) },
688                    None => test_support::remove(name),
689                }
690            }
691        }
692    }
693
694    /// Everything one test needs, held for the test's whole body.
695    ///
696    /// `_tmp` is declared before `_env` so the scratch tree is deleted while the
697    /// environment lock is still held: a sibling test that wakes on the lock must never
698    /// observe the tree mid-deletion, nor env vars pointing at a deleted directory.
699    struct Fixture {
700        _tmp: tempfile::TempDir,
701        _env: EnvGuard,
702        endpoint: Endpoint,
703    }
704
705    /// A listening endpoint in a scratch directory, with the context's directories
706    /// pointed at the same scratch tree.
707    ///
708    /// The caller must keep the fixture (and with it the environment lock) alive for the
709    /// whole test: the static [`CTX`] is first-writer-wins, so while one test runs, every
710    /// other test that would re-point the context's directories must wait.
711    fn prepared() -> Fixture {
712        let lock = test_support::lock();
713        let tmp = tempfile::tempdir().unwrap();
714        let env = EnvGuard::set(lock, tmp.path());
715        CTX.init(AppKind::Server);
716        let endpoint = Endpoint::in_dir("sapphire-appservertest", tmp.path().to_path_buf());
717        Fixture {
718            _tmp: tmp,
719            _env: env,
720            endpoint,
721        }
722    }
723
724    /// Wait until something is listening on `endpoint`.
725    ///
726    /// `tokio::spawn(server.run())` only schedules the server; without this wait a fast
727    /// `connect_or_absent` probe can run before `run` has bound the socket, and with
728    /// nothing listening that single unlucky probe is the whole test failing.
729    async fn wait_until_listening(endpoint: &Endpoint) {
730        let deadline = tokio::time::Instant::now() + Duration::from_secs(5);
731        while !sapphire_ipc::probe(endpoint).await.unwrap() {
732            assert!(
733                tokio::time::Instant::now() < deadline,
734                "the server never started listening"
735            );
736            tokio::time::sleep(Duration::from_millis(10)).await;
737        }
738    }
739
740    /// A running server writes its log file: the framework's `logging` module
741    /// routes the app's log to `<data dir>/logs/app.log`, and `run()` holds the
742    /// guard for as long as it serves. The event is emitted by this test — the
743    /// subscriber and the file layer are the process's, installed by `CTX.init`
744    /// and `run` — so what lands in the file is exactly what a journald-less
745    /// host would otherwise never see.
746    #[tokio::test(flavor = "multi_thread")]
747    async fn a_running_server_writes_its_log_file() {
748        let f = prepared();
749        let endpoint = f.endpoint.clone();
750        let server = AppServer::new(&CTX, "0.0.0").endpoint(endpoint.clone());
751        let handle = tokio::spawn(async move { server.run().await });
752        wait_until_listening(&endpoint).await;
753
754        tracing::info!("the server is serving, and this line belongs in its log");
755
756        let (client, _) = sapphire_ipc::connect_or_absent(&endpoint, CTX.app_name, client_info())
757            .await
758            .unwrap()
759            .expect("the server is listening");
760        let _: serde_json::Value = client
761            .call(sapphire_ipc::SHUTDOWN_METHOD, serde_json::json!({}))
762            .await
763            .unwrap();
764        // The guard flushes as `run` unwinds; awaiting it is what makes the
765        // file complete before it is read.
766        handle.await.unwrap().unwrap();
767
768        let text = std::fs::read_to_string(CTX.log_dir().join("app.log")).unwrap();
769        assert!(
770            text.contains("the server is serving, and this line belongs in its log"),
771            "{text}"
772        );
773    }
774
775    #[tokio::test(flavor = "multi_thread")]
776    async fn a_server_reports_itself_as_service_managed() {
777        let f = prepared();
778        let endpoint = f.endpoint.clone();
779        let server = AppServer::new(&CTX, "0.0.0").endpoint(endpoint.clone());
780        let handle = tokio::spawn(async move { server.run().await });
781        wait_until_listening(&endpoint).await;
782
783        let (client, info) =
784            sapphire_ipc::connect_or_absent(&endpoint, CTX.app_name, client_info())
785                .await
786                .unwrap()
787                .expect("the server is listening");
788        assert_eq!(info.managed_by, ManagedBy::Service);
789
790        let _: serde_json::Value = client
791            .call(sapphire_ipc::SHUTDOWN_METHOD, serde_json::json!({}))
792            .await
793            .unwrap();
794        handle.await.unwrap().unwrap();
795    }
796
797    #[tokio::test(flavor = "multi_thread")]
798    async fn a_server_reports_its_app_api_and_the_handshake_gates_on_it() {
799        let f = prepared();
800        let endpoint = f.endpoint.clone();
801        let server = AppServer::new(&CTX, "0.0.0")
802            .endpoint(endpoint.clone())
803            .app_api(7);
804        let handle = tokio::spawn(async move { server.run().await });
805        wait_until_listening(&endpoint).await;
806
807        let wants = |app_api| ClientInfo {
808            app_api,
809            ..client_info()
810        };
811        let err = sapphire_ipc::connect_or_absent(&endpoint, CTX.app_name, wants(Some(8)))
812            .await
813            .unwrap_err();
814        assert!(
815            matches!(
816                err,
817                sapphire_ipc::Error::AppApiVersionMismatch {
818                    running: Some(7),
819                    ours: 8,
820                    ..
821                }
822            ),
823            "{err:?}"
824        );
825
826        let (client, info) =
827            sapphire_ipc::connect_or_absent(&endpoint, CTX.app_name, wants(Some(7)))
828                .await
829                .unwrap()
830                .expect("the server is listening");
831        assert_eq!(info.app_api, Some(7));
832
833        let _: serde_json::Value = client
834            .call(sapphire_ipc::SHUTDOWN_METHOD, serde_json::json!({}))
835            .await
836            .unwrap();
837        handle.await.unwrap().unwrap();
838    }
839
840    #[tokio::test(flavor = "multi_thread")]
841    async fn a_running_server_answers_server_info() {
842        let f = prepared();
843        let endpoint = f.endpoint.clone();
844
845        let server = AppServer::new(&CTX, "1.2.3").endpoint(endpoint.clone());
846        let handle = tokio::spawn(async move { server.run().await });
847        wait_until_listening(&endpoint).await;
848
849        let (client, info) = sapphire_ipc::connect_or_absent(
850            &endpoint,
851            CTX.app_name,
852            ClientInfo {
853                version: "1.2.3".into(),
854                ..client_info()
855            },
856        )
857        .await
858        .unwrap()
859        .expect("the server is listening");
860        assert_eq!(info.version, "1.2.3");
861
862        // `server.info` answers the whole typed report, not the bare handshake record:
863        // the CLI reads one shape, and so would a GUI.
864        let report: StatusReport = client
865            .call(
866                sapphire_backend::protocol::SERVER_INFO,
867                serde_json::json!({}),
868            )
869            .await
870            .unwrap();
871        assert!(report.running);
872        assert_eq!(report.version.as_deref(), Some("1.2.3"));
873        assert_eq!(report.pid, Some(std::process::id()));
874        assert_eq!(report.managed_by, Some(proto::ManagedBy::Service));
875        assert!(report.app.is_empty(), "no status rows were configured");
876
877        let _: serde_json::Value = client
878            .call(sapphire_ipc::SHUTDOWN_METHOD, serde_json::json!({}))
879            .await
880            .unwrap();
881        handle.await.unwrap().unwrap();
882    }
883
884    #[tokio::test(flavor = "multi_thread")]
885    async fn shutdown_stops_the_server() {
886        let f = prepared();
887        let endpoint = f.endpoint.clone();
888
889        let server = AppServer::new(&CTX, "0.0.0").endpoint(endpoint.clone());
890        let handle = tokio::spawn(async move { server.run().await });
891        wait_until_listening(&endpoint).await;
892
893        let (client, _) = sapphire_ipc::connect_or_absent(&endpoint, CTX.app_name, client_info())
894            .await
895            .unwrap()
896            .expect("the server is listening");
897        let _: serde_json::Value = client
898            .call(sapphire_ipc::SHUTDOWN_METHOD, serde_json::json!({}))
899            .await
900            .unwrap();
901
902        tokio::time::timeout(Duration::from_secs(5), handle)
903            .await
904            .expect("the server must stop")
905            .unwrap()
906            .unwrap();
907        assert!(!sapphire_ipc::probe(&endpoint).await.unwrap());
908    }
909
910    #[tokio::test(flavor = "multi_thread")]
911    async fn an_application_can_add_its_own_methods() {
912        let f = prepared();
913        let endpoint = f.endpoint.clone();
914
915        let server = AppServer::new(&CTX, "0.0.0")
916            .endpoint(endpoint.clone())
917            .extend(|r| {
918                r.method("sapphire-appservertest.greet", |_| async move {
919                    Ok(serde_json::json!("hello"))
920                })
921            });
922        let handle = tokio::spawn(async move { server.run().await });
923        wait_until_listening(&endpoint).await;
924
925        let (client, _) = sapphire_ipc::connect_or_absent(&endpoint, CTX.app_name, client_info())
926            .await
927            .unwrap()
928            .expect("the server is listening");
929        let greeting: String = client
930            .call("sapphire-appservertest.greet", serde_json::json!({}))
931            .await
932            .unwrap();
933        assert_eq!(greeting, "hello");
934
935        let _: serde_json::Value = client
936            .call(sapphire_ipc::SHUTDOWN_METHOD, serde_json::json!({}))
937            .await
938            .unwrap();
939        handle.await.unwrap().unwrap();
940    }
941
942    #[tokio::test(flavor = "multi_thread")]
943    async fn workspace_init_creates_the_marker_and_tells_the_registry() {
944        let f = prepared();
945        let endpoint = f.endpoint.clone();
946        let server = AppServer::new(&CTX, "0.0.0").endpoint(endpoint.clone());
947        let handle = tokio::spawn(async move { server.run().await });
948        wait_until_listening(&endpoint).await;
949        let (client, _) = sapphire_ipc::connect_or_absent(&endpoint, CTX.app_name, client_info())
950            .await
951            .unwrap()
952            .unwrap();
953
954        let dir = tempfile::tempdir().unwrap();
955        let result: proto::WorkspaceInitResult = client
956            .call(
957                proto::WORKSPACE_INIT,
958                proto::WorkspaceInitParams {
959                    dir: dir.path().to_owned(),
960                },
961            )
962            .await
963            .unwrap();
964        assert!(result.created);
965        assert!(dir.path().join(format!(".{}", CTX.app_name)).is_dir());
966
967        // Idempotent: the second init is a success that did not create.
968        let again: proto::WorkspaceInitResult = client
969            .call(
970                proto::WORKSPACE_INIT,
971                proto::WorkspaceInitParams {
972                    dir: dir.path().to_owned(),
973                },
974            )
975            .await
976            .unwrap();
977        assert!(!again.created);
978
979        let _: serde_json::Value = client
980            .call(sapphire_ipc::SHUTDOWN_METHOD, serde_json::json!({}))
981            .await
982            .unwrap();
983        handle.await.unwrap().unwrap();
984    }
985
986    #[tokio::test(flavor = "multi_thread")]
987    async fn server_info_carries_the_app_rows() {
988        let f = prepared();
989        let endpoint = f.endpoint.clone();
990        let server = AppServer::new(&CTX, "0.0.0")
991            .endpoint(endpoint.clone())
992            .status_rows(std::sync::Arc::new(|| {
993                vec![StatusRow {
994                    name: "sync".into(),
995                    value: "enabled".into(),
996                }]
997            }));
998        let handle = tokio::spawn(async move { server.run().await });
999        wait_until_listening(&endpoint).await;
1000        let (client, _) = sapphire_ipc::connect_or_absent(&endpoint, CTX.app_name, client_info())
1001            .await
1002            .unwrap()
1003            .unwrap();
1004        let report: StatusReport = client
1005            .call(
1006                sapphire_backend::protocol::SERVER_INFO,
1007                serde_json::json!({}),
1008            )
1009            .await
1010            .unwrap();
1011        assert!(report.running);
1012        assert_eq!(report.app.len(), 1);
1013        assert_eq!(report.app[0].name, "sync");
1014
1015        let _: serde_json::Value = client
1016            .call(sapphire_ipc::SHUTDOWN_METHOD, serde_json::json!({}))
1017            .await
1018            .unwrap();
1019        handle.await.unwrap().unwrap();
1020    }
1021}