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    WorkspaceSyncCommand, 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, BridgeConnector, 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    /// Sync through the host's `sapphire-bridge`: [`sync`](Self::sync) with a runtime that
283    /// reaches the bridge itself, and reaches it again whenever it is lost (#244).
284    ///
285    /// [`run`](Self::run) makes the first attempt. No bridge running is not fatal — the
286    /// server serves without sync and picks the bridge up once it starts, and `sync.*`
287    /// answers that it is not connected meanwhile — but any other failure, such as a bridge
288    /// of another API version, stops the start.
289    pub fn sync_via_bridge(self) -> Result<AppServer> {
290        let runtime = SyncRuntime::connecting(
291            self.ctx,
292            BridgeConnector::standard(self.ctx.app_name, self.version),
293            std::env::current_exe()?,
294            ManagedBy::Service,
295        );
296        Ok(self.sync(Arc::new(runtime)))
297    }
298
299    /// The application's own rows for the status report: shown after the framework's
300    /// `running` / `version` / `pid` / `managed_by` lines.
301    ///
302    /// The closure is called once per report, so an application's rows may read live
303    /// state; the CLI's `status` and the IPC `server.info` method render the same call's
304    /// output.
305    pub fn status_rows(mut self, rows: Arc<dyn Fn() -> Vec<StatusRow> + Send + Sync>) -> AppServer {
306        self.status_rows = Some(rows);
307        self
308    }
309
310    /// What this application's service is: the arguments a service manager starts it with.
311    ///
312    /// `["serve"]`: a service manager starts the executable directly, and the executable's
313    /// bare invocation is `serve` — the subcommand-less default of
314    /// [`FrameworkCommand::Serve`](crate::FrameworkCommand::Serve). A CLI that wants its
315    /// service installed hands this to
316    /// [`ServiceCommand`](sapphire_framework_service::ServiceCommand).
317    pub fn service_spec(&self) -> ServiceSpec {
318        ServiceSpec {
319            app_name: self.ctx.app_name,
320            description: format!("{} server {}", self.ctx.app_name, self.version),
321            args: vec!["serve".to_owned()],
322            post_install: None,
323        }
324    }
325
326    /// Add the application's own methods.
327    pub fn extend(mut self, f: impl FnOnce(Router) -> Router + Send + 'static) -> AppServer {
328        self.extend = Some(Box::new(f));
329        self
330    }
331
332    /// The workspace this server has open. An application's own handlers use it to reach
333    /// the workspace the same way the framework's do: [`WorkspaceHost::backend`].
334    pub fn host(&self) -> &Arc<WorkspaceHost> {
335        &self.host
336    }
337
338    /// Listen until told to stop, or until a signal arrives.
339    pub async fn run(self) -> Result<()> {
340        let AppServer {
341            ctx,
342            version,
343            endpoint,
344            selection_file,
345            host,
346            sync,
347            extend,
348            status_rows,
349            app_api,
350            config,
351            #[cfg(feature = "http")]
352            http_listen,
353            #[cfg(feature = "http")]
354            http_routes,
355            #[cfg(feature = "http")]
356            http_auth,
357            #[cfg(feature = "mcp")]
358            mcp,
359        } = self;
360
361        let endpoint = match endpoint {
362            Some(e) => e,
363            None => Endpoint::for_app(ctx.app_name)?,
364        };
365        // A server is always-on from here on: only `serve` and the service manager start
366        // one, and the service manager starts it for keeps. There is no spawned mode left
367        // to report.
368        let info = ServerInfo {
369            version: version.to_owned(),
370            api: proto::API_VERSION,
371            app_api,
372            pid: std::process::id(),
373            managed_by: ManagedBy::Service,
374        };
375
376        // The app's log file, held for as long as this server serves: the guard's
377        // drop flushes the writer thread, so the last lines of a clean shutdown land
378        // in the file. The subscriber itself was installed by `ctx.init`; this is what
379        // routes the file layer at `<data dir>/logs/`.
380        let _log = sapphire_workspace::logging::install(ctx)?;
381
382        let config = match config {
383            Some(config) => config,
384            None => ServerConfig::load_for_app(ctx)?,
385        };
386        #[cfg(not(feature = "mcp"))]
387        if config.mcp.http {
388            tracing::warn!(
389                "server.toml turns MCP over HTTP on, but this build of {} has no MCP",
390                ctx.app_name
391            );
392        }
393
394        let (stop_tx, mut stop_rx) = tokio::sync::watch::channel(false);
395
396        // The first attempt to reach the bridge, before the selected workspace comes back
397        // and asks it for sync.
398        if let Some(runtime) = &sync {
399            runtime.connect().await?;
400        }
401
402        let file = match selection_file {
403            Some(path) => SelectionFile::at(path),
404            None => SelectionFile::for_app(ctx),
405        };
406        let current = Arc::new(Current::new(ctx, Arc::clone(&host), sync.clone(), file));
407        // Back to the workspace this host had, before the first client can ask for it.
408        let restoring = current.restore().await;
409
410        let mut router = subscribe_method(
411            Arc::clone(&host),
412            current::current_methods(Arc::clone(&current), workspace_router(Arc::clone(&current))),
413        );
414        if sync.is_some() {
415            // `sync_router` is applied *under* the application's own methods so a later
416            // `extend` can still replace one, and after `subscribe_method` so the
417            // `workspace.*` namespace is complete.
418            router = sync_router(Arc::clone(&current), router);
419        }
420        // `server.info` answers the typed [`StatusReport`] — the same shape the CLI's
421        // `status` renders — so the CLI and a future GUI read one record. The rows come
422        // from the application's builder, called once per report.
423        router = router
424            .method(proto::SERVER_INFO, {
425                let info = info.clone();
426                let status_rows = status_rows.clone();
427                move |_| {
428                    let info = info.clone();
429                    let status_rows = status_rows.clone();
430                    async move {
431                        let app = status_rows.as_ref().map(|rows| rows()).unwrap_or_default();
432                        let report = StatusReport {
433                            running: true,
434                            version: Some(info.version),
435                            pid: Some(info.pid),
436                            managed_by: Some(match info.managed_by {
437                                ManagedBy::Service => proto::ManagedBy::Service,
438                                ManagedBy::Spawned => proto::ManagedBy::Spawned,
439                            }),
440                            app,
441                        };
442                        serde_json::to_value(report)
443                            .map_err(|e| sapphire_ipc::RpcError::internal(e.to_string()))
444                    }
445                }
446            })
447            .method(sapphire_ipc::SHUTDOWN_METHOD, {
448                let stop_tx = stop_tx.clone();
449                move |_| {
450                    let stop_tx = stop_tx.clone();
451                    async move {
452                        let _ = stop_tx.send(true);
453                        serde_json::to_value(proto::Ack {})
454                            .map_err(|e| sapphire_ipc::RpcError::internal(e.to_string()))
455                    }
456                }
457            });
458        if let Some(extend) = extend {
459            router = extend(router);
460        }
461        let router = Arc::new(router);
462
463        // Registered before the bind, so a SIGTERM arriving the instant the socket is up
464        // cannot fall through to the default handler and kill the process. SIGINT is
465        // listened to only through `ctrl_c` (which swallows the default handler on both
466        // platforms): a Unix `SignalKind::interrupt()` stream would double-fire for ^C.
467        #[cfg(unix)]
468        let mut sigterm = Sigterm::new()?;
469        #[cfg(not(unix))]
470        let mut sigterm = Sigterm;
471
472        #[cfg(unix)]
473        let listener = sapphire_ipc::bind(&endpoint).await?;
474        #[cfg(windows)]
475        let mut listener = sapphire_ipc::bind(&endpoint)?;
476
477        let mut connections = tokio::task::JoinSet::new();
478
479        // The HTTP listener, when anything is served over it. Started once the IPC socket
480        // is bound, for the same reason as the sync tasks below. `/mcp`'s tools reach this
481        // server the way the `mcp` subcommand's do — over IPC — on an in-process connection
482        // served like any other.
483        #[cfg(feature = "http")]
484        let http_stop = tokio_util::sync::CancellationToken::new();
485        #[cfg(feature = "http")]
486        let _http = {
487            let mut routes = http_routes;
488            #[cfg(feature = "mcp")]
489            if config.mcp.http {
490                let (ours, theirs) = sapphire_ipc::Connection::pair();
491                {
492                    let router = Arc::clone(&router);
493                    let info = info.clone();
494                    let app = ctx.app_name;
495                    connections.spawn(async move {
496                        let _ = serve(theirs, router, app, info).await;
497                    });
498                }
499                let client_info = sapphire_ipc::ClientInfo {
500                    kind: sapphire_framework_mcp::CLIENT_KIND.to_owned(),
501                    version: version.to_owned(),
502                    api: proto::API_VERSION,
503                    app_api,
504                    pid: std::process::id(),
505                };
506                let (client, _) =
507                    sapphire_ipc::Client::handshake(ours, ctx.app_name, client_info).await?;
508                let tools = sapphire_framework_mcp::ToolContext::connected(
509                    ctx.app_name,
510                    version,
511                    Arc::new(client),
512                );
513                let mcp_routes =
514                    mcp.http_router(tools, &config.http.allowed_hosts, http_stop.child_token());
515                routes = Some(match routes {
516                    Some(routes) => routes.merge(mcp_routes),
517                    None => mcp_routes,
518                });
519            }
520            match (routes, config.http.listen.or(http_listen)) {
521                (None, _) => None,
522                (Some(_), None) => {
523                    tracing::error!(
524                        "nothing to bind HTTP to: set `[http] listen` in {SERVER_CONFIG_FILE}"
525                    );
526                    None
527                }
528                (Some(routes), Some(addr)) => {
529                    let auth = http_auth.unwrap_or_else(|| {
530                        sapphire_framework_keys::AuthConfig::new(Arc::new(
531                            sapphire_framework_keys::BridgeVerifier::new(ctx.app_name, version),
532                        ))
533                    });
534                    http::start(addr, routes, auth, http_stop.clone()).await
535                }
536            }
537        };
538
539        // The watcher, the bridge announcement loop, the dialer and the bridge connection, if
540        // sync is on. Started only once the socket is bound, so an early `?` above cannot
541        // leave tasks running for a server that never served. All of them are allowed to
542        // fail: only sync stops when they do, and the app server keeps serving files
543        // (spec §10). They are aborted with the server.
544        let _sync_tasks = match &sync {
545            Some(runtime) => {
546                let driver = Arc::clone(runtime);
547                let announcements = tokio::spawn(async move {
548                    if let Err(err) = driver.run().await {
549                        tracing::warn!("the bridge announcement loop ended: {err}");
550                    }
551                });
552                let changing = Arc::clone(runtime);
553                let watching = tokio::spawn(async move {
554                    if let Err(err) = changing.watch_changes().await {
555                        tracing::warn!("the file watcher ended: {err}");
556                    }
557                });
558                // The dialer is what keeps a session open after the initial exchange, so a
559                // commit reaches a peer without waiting for the next one (spec §4.2).
560                let dialling = Arc::clone(runtime);
561                let dialling = tokio::spawn(async move {
562                    if let Err(err) = dialling.dial_loop().await {
563                        tracing::warn!("the live dial loop ended: {err}");
564                    }
565                });
566                // Reaching the bridge again whenever it is lost (#244).
567                let connected = tokio::spawn(Arc::clone(runtime).keep_connected());
568                Some([announcements, watching, dialling, connected])
569            }
570            None => None,
571        };
572
573        loop {
574            tokio::select! {
575                changed = stop_rx.changed() => {
576                    if changed.is_err() || *stop_rx.borrow() {
577                        break;
578                    }
579                }
580                _ = tokio::signal::ctrl_c() => {
581                    tracing::info!("interrupted; shutting down");
582                    break;
583                }
584                _ = sigterm.recv() => {
585                    tracing::info!("terminated; shutting down");
586                    break;
587                }
588                accepted = listener.accept() => {
589                    let conn = accepted?;
590                    let router = Arc::clone(&router);
591                    let app = ctx.app_name;
592                    let info = info.clone();
593                    connections.spawn(async move {
594                        let _ = serve(conn, router, app, info).await;
595                    });
596                }
597            }
598        }
599
600        if let Some(restoring) = restoring {
601            restoring.abort();
602        }
603        // HTTP first: its sessions hold a connection to this server, which the reaping
604        // below waits for.
605        #[cfg(feature = "http")]
606        {
607            http_stop.cancel();
608            if let Some((_, mut task)) = _http
609                && tokio::time::timeout(SERVE_GRACE, &mut task).await.is_err()
610            {
611                tracing::debug!("the HTTP listener did not stop in time");
612                task.abort();
613            }
614        }
615        if let Some(tasks) = _sync_tasks {
616            // Each loop pins the sync runtime, and with it the replica stores. An aborted task
617            // is only dropped once its current poll returns — which, mid-scan, can take a
618            // while — so wait for that rather than return with a loop still holding a store
619            // the next server in this process would fail to open (#235).
620            for task in tasks {
621                task.abort();
622                let _ = task.await;
623            }
624        }
625        if let Some(runtime) = &sync {
626            // The first dials after an enable pin the runtime the same way, and so do the
627            // inbound sessions, the live-session readers and the embedding passes.
628            runtime.stop_dials().await;
629            runtime.stop_background().await;
630            // Close every live sync session. A session's reader task holds the replica, and
631            // the session itself sits in the runtime's table until it is cleared, so leaving
632            // one open pins the runtime — and the redb replica stores in it — after the
633            // server is gone (spec §2.2: cancellation is disconnection).
634            runtime.drop_connections().await;
635        }
636        host.close();
637        drop(listener); // removes the socket file on Unix
638
639        // Reap the per-connection serve tasks. Each one pins the router, the router pins
640        // the sync runtime, and the runtime's replica stores are redb databases that stay
641        // locked until the last pin is dropped — a server that left them running would
642        // lock its own successor out of its state (spec §2.2: cancellation is
643        // disconnection). Connections get a grace period to wind down on their own — the
644        // shutdown acknowledgement among them — then the rest are cancelled: a client
645        // that keeps its connection open past shutdown is holding a server that is gone.
646        let _ = tokio::time::timeout(SERVE_GRACE, async {
647            while connections.join_next().await.is_some() {}
648        })
649        .await;
650        connections.abort_all();
651        while connections.join_next().await.is_some() {}
652        Ok(())
653    }
654}
655
656#[cfg(test)]
657mod tests {
658    use super::*;
659    use sapphire_ipc::{ClientInfo, Endpoint, ManagedBy};
660    use sapphire_workspace::{AppContext, AppKind};
661    use std::ffi::OsString;
662
663    use crate::test_support;
664
665    static CTX: AppContext = AppContext::new("sapphire-appservertest");
666
667    /// The env vars `init_ctx` writes, in the order the guard restores them.
668    const DIR_VARS: [&str; 3] = [
669        "SAPPHIRE_APPSERVERTEST_CACHE_DIR",
670        "SAPPHIRE_APPSERVERTEST_DATA_DIR",
671        "SAPPHIRE_APPSERVERTEST_CONFIG_DIR",
672    ];
673
674    fn client_info() -> ClientInfo {
675        ClientInfo {
676            kind: "test".into(),
677            version: "0.0.0".into(),
678            api: sapphire_backend::protocol::API_VERSION,
679            app_api: None,
680            pid: std::process::id(),
681        }
682    }
683
684    /// Point the context's directories at `tmp` and restore the previous values (present
685    /// or absent) when dropped — including while unwinding from a panic. Without the
686    /// unconditional restore, a panicking assertion would leave the variables pointing at
687    /// a temp directory the test then deletes, and the context of a later test would
688    /// resolve into the void.
689    struct EnvGuard {
690        previous: [Option<OsString>; 3],
691        _lock: std::sync::MutexGuard<'static, ()>,
692    }
693
694    impl EnvGuard {
695        /// Write the three directory vars while holding the environment lock.
696        fn set(lock: std::sync::MutexGuard<'static, ()>, tmp: &std::path::Path) -> EnvGuard {
697            let previous = DIR_VARS.map(std::env::var_os);
698            let dirs = ["cache", "data", "config"].map(|cat| tmp.join(cat));
699            // SAFETY (via `test_support::set`): `lock` serialises every read and write of
700            // the process environment in this test binary — the `host`, `handlers` and
701            // `events` modules' tests share the same lock — and it is held until `drop`
702            // has restored the old values.
703            for (name, dir) in DIR_VARS.iter().zip(dirs) {
704                test_support::set(name, &dir);
705            }
706            EnvGuard {
707                previous,
708                _lock: lock,
709            }
710        }
711    }
712
713    impl Drop for EnvGuard {
714        fn drop(&mut self) {
715            // SAFETY: `self._lock` still serialises the environment; it is dropped only
716            // after this method returns.
717            for (name, previous) in DIR_VARS.iter().zip(self.previous.iter_mut()) {
718                match previous.take() {
719                    Some(value) => unsafe { std::env::set_var(name, value) },
720                    None => test_support::remove(name),
721                }
722            }
723        }
724    }
725
726    /// Everything one test needs, held for the test's whole body.
727    ///
728    /// `_tmp` is declared before `_env` so the scratch tree is deleted while the
729    /// environment lock is still held: a sibling test that wakes on the lock must never
730    /// observe the tree mid-deletion, nor env vars pointing at a deleted directory.
731    struct Fixture {
732        _tmp: tempfile::TempDir,
733        _env: EnvGuard,
734        endpoint: Endpoint,
735    }
736
737    /// A listening endpoint in a scratch directory, with the context's directories
738    /// pointed at the same scratch tree.
739    ///
740    /// The caller must keep the fixture (and with it the environment lock) alive for the
741    /// whole test: the static [`CTX`] is first-writer-wins, so while one test runs, every
742    /// other test that would re-point the context's directories must wait.
743    fn prepared() -> Fixture {
744        let lock = test_support::lock();
745        let tmp = tempfile::tempdir().unwrap();
746        let env = EnvGuard::set(lock, tmp.path());
747        CTX.init(AppKind::Server);
748        let endpoint = Endpoint::in_dir("sapphire-appservertest", tmp.path().to_path_buf());
749        Fixture {
750            _tmp: tmp,
751            _env: env,
752            endpoint,
753        }
754    }
755
756    /// Wait until something is listening on `endpoint`.
757    ///
758    /// `tokio::spawn(server.run())` only schedules the server; without this wait a fast
759    /// `connect_or_absent` probe can run before `run` has bound the socket, and with
760    /// nothing listening that single unlucky probe is the whole test failing.
761    async fn wait_until_listening(endpoint: &Endpoint) {
762        let deadline = tokio::time::Instant::now() + Duration::from_secs(5);
763        while !sapphire_ipc::probe(endpoint).await.unwrap() {
764            assert!(
765                tokio::time::Instant::now() < deadline,
766                "the server never started listening"
767            );
768            tokio::time::sleep(Duration::from_millis(10)).await;
769        }
770    }
771
772    /// A running server writes its log file: the framework's `logging` module
773    /// routes the app's log to `<data dir>/logs/app.log`, and `run()` holds the
774    /// guard for as long as it serves. The event is emitted by this test — the
775    /// subscriber and the file layer are the process's, installed by `CTX.init`
776    /// and `run` — so what lands in the file is exactly what a journald-less
777    /// host would otherwise never see.
778    #[tokio::test(flavor = "multi_thread")]
779    async fn a_running_server_writes_its_log_file() {
780        let f = prepared();
781        let endpoint = f.endpoint.clone();
782        let server = AppServer::new(&CTX, "0.0.0").endpoint(endpoint.clone());
783        let handle = tokio::spawn(async move { server.run().await });
784        wait_until_listening(&endpoint).await;
785
786        tracing::info!("the server is serving, and this line belongs in its log");
787
788        let (client, _) = sapphire_ipc::connect_or_absent(&endpoint, CTX.app_name, client_info())
789            .await
790            .unwrap()
791            .expect("the server is listening");
792        let _: serde_json::Value = client
793            .call(sapphire_ipc::SHUTDOWN_METHOD, serde_json::json!({}))
794            .await
795            .unwrap();
796        // The guard flushes as `run` unwinds; awaiting it is what makes the
797        // file complete before it is read.
798        handle.await.unwrap().unwrap();
799
800        let text = std::fs::read_to_string(CTX.log_dir().join("app.log")).unwrap();
801        assert!(
802            text.contains("the server is serving, and this line belongs in its log"),
803            "{text}"
804        );
805    }
806
807    #[tokio::test(flavor = "multi_thread")]
808    async fn a_server_reports_itself_as_service_managed() {
809        let f = prepared();
810        let endpoint = f.endpoint.clone();
811        let server = AppServer::new(&CTX, "0.0.0").endpoint(endpoint.clone());
812        let handle = tokio::spawn(async move { server.run().await });
813        wait_until_listening(&endpoint).await;
814
815        let (client, info) =
816            sapphire_ipc::connect_or_absent(&endpoint, CTX.app_name, client_info())
817                .await
818                .unwrap()
819                .expect("the server is listening");
820        assert_eq!(info.managed_by, ManagedBy::Service);
821
822        let _: serde_json::Value = client
823            .call(sapphire_ipc::SHUTDOWN_METHOD, serde_json::json!({}))
824            .await
825            .unwrap();
826        handle.await.unwrap().unwrap();
827    }
828
829    #[tokio::test(flavor = "multi_thread")]
830    async fn a_server_reports_its_app_api_and_the_handshake_gates_on_it() {
831        let f = prepared();
832        let endpoint = f.endpoint.clone();
833        let server = AppServer::new(&CTX, "0.0.0")
834            .endpoint(endpoint.clone())
835            .app_api(7);
836        let handle = tokio::spawn(async move { server.run().await });
837        wait_until_listening(&endpoint).await;
838
839        let wants = |app_api| ClientInfo {
840            app_api,
841            ..client_info()
842        };
843        let err = sapphire_ipc::connect_or_absent(&endpoint, CTX.app_name, wants(Some(8)))
844            .await
845            .unwrap_err();
846        assert!(
847            matches!(
848                err,
849                sapphire_ipc::Error::AppApiVersionMismatch {
850                    running: Some(7),
851                    ours: 8,
852                    ..
853                }
854            ),
855            "{err:?}"
856        );
857
858        let (client, info) =
859            sapphire_ipc::connect_or_absent(&endpoint, CTX.app_name, wants(Some(7)))
860                .await
861                .unwrap()
862                .expect("the server is listening");
863        assert_eq!(info.app_api, Some(7));
864
865        let _: serde_json::Value = client
866            .call(sapphire_ipc::SHUTDOWN_METHOD, serde_json::json!({}))
867            .await
868            .unwrap();
869        handle.await.unwrap().unwrap();
870    }
871
872    #[tokio::test(flavor = "multi_thread")]
873    async fn a_running_server_answers_server_info() {
874        let f = prepared();
875        let endpoint = f.endpoint.clone();
876
877        let server = AppServer::new(&CTX, "1.2.3").endpoint(endpoint.clone());
878        let handle = tokio::spawn(async move { server.run().await });
879        wait_until_listening(&endpoint).await;
880
881        let (client, info) = sapphire_ipc::connect_or_absent(
882            &endpoint,
883            CTX.app_name,
884            ClientInfo {
885                version: "1.2.3".into(),
886                ..client_info()
887            },
888        )
889        .await
890        .unwrap()
891        .expect("the server is listening");
892        assert_eq!(info.version, "1.2.3");
893
894        // `server.info` answers the whole typed report, not the bare handshake record:
895        // the CLI reads one shape, and so would a GUI.
896        let report: StatusReport = client
897            .call(
898                sapphire_backend::protocol::SERVER_INFO,
899                serde_json::json!({}),
900            )
901            .await
902            .unwrap();
903        assert!(report.running);
904        assert_eq!(report.version.as_deref(), Some("1.2.3"));
905        assert_eq!(report.pid, Some(std::process::id()));
906        assert_eq!(report.managed_by, Some(proto::ManagedBy::Service));
907        assert!(report.app.is_empty(), "no status rows were configured");
908
909        let _: serde_json::Value = client
910            .call(sapphire_ipc::SHUTDOWN_METHOD, serde_json::json!({}))
911            .await
912            .unwrap();
913        handle.await.unwrap().unwrap();
914    }
915
916    #[tokio::test(flavor = "multi_thread")]
917    async fn shutdown_stops_the_server() {
918        let f = prepared();
919        let endpoint = f.endpoint.clone();
920
921        let server = AppServer::new(&CTX, "0.0.0").endpoint(endpoint.clone());
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 _: serde_json::Value = client
930            .call(sapphire_ipc::SHUTDOWN_METHOD, serde_json::json!({}))
931            .await
932            .unwrap();
933
934        tokio::time::timeout(Duration::from_secs(5), handle)
935            .await
936            .expect("the server must stop")
937            .unwrap()
938            .unwrap();
939        assert!(!sapphire_ipc::probe(&endpoint).await.unwrap());
940    }
941
942    #[tokio::test(flavor = "multi_thread")]
943    async fn an_application_can_add_its_own_methods() {
944        let f = prepared();
945        let endpoint = f.endpoint.clone();
946
947        let server = AppServer::new(&CTX, "0.0.0")
948            .endpoint(endpoint.clone())
949            .extend(|r| {
950                r.method("sapphire-appservertest.greet", |_| async move {
951                    Ok(serde_json::json!("hello"))
952                })
953            });
954        let handle = tokio::spawn(async move { server.run().await });
955        wait_until_listening(&endpoint).await;
956
957        let (client, _) = sapphire_ipc::connect_or_absent(&endpoint, CTX.app_name, client_info())
958            .await
959            .unwrap()
960            .expect("the server is listening");
961        let greeting: String = client
962            .call("sapphire-appservertest.greet", serde_json::json!({}))
963            .await
964            .unwrap();
965        assert_eq!(greeting, "hello");
966
967        let _: serde_json::Value = client
968            .call(sapphire_ipc::SHUTDOWN_METHOD, serde_json::json!({}))
969            .await
970            .unwrap();
971        handle.await.unwrap().unwrap();
972    }
973
974    #[tokio::test(flavor = "multi_thread")]
975    async fn workspace_init_creates_the_marker_and_tells_the_registry() {
976        let f = prepared();
977        let endpoint = f.endpoint.clone();
978        let server = AppServer::new(&CTX, "0.0.0").endpoint(endpoint.clone());
979        let handle = tokio::spawn(async move { server.run().await });
980        wait_until_listening(&endpoint).await;
981        let (client, _) = sapphire_ipc::connect_or_absent(&endpoint, CTX.app_name, client_info())
982            .await
983            .unwrap()
984            .unwrap();
985
986        let dir = tempfile::tempdir().unwrap();
987        let result: proto::WorkspaceInitResult = client
988            .call(
989                proto::WORKSPACE_INIT,
990                proto::WorkspaceInitParams {
991                    dir: dir.path().to_owned(),
992                },
993            )
994            .await
995            .unwrap();
996        assert!(result.created);
997        assert!(dir.path().join(format!(".{}", CTX.app_name)).is_dir());
998
999        // Idempotent: the second init is a success that did not create.
1000        let again: proto::WorkspaceInitResult = client
1001            .call(
1002                proto::WORKSPACE_INIT,
1003                proto::WorkspaceInitParams {
1004                    dir: dir.path().to_owned(),
1005                },
1006            )
1007            .await
1008            .unwrap();
1009        assert!(!again.created);
1010
1011        let _: serde_json::Value = client
1012            .call(sapphire_ipc::SHUTDOWN_METHOD, serde_json::json!({}))
1013            .await
1014            .unwrap();
1015        handle.await.unwrap().unwrap();
1016    }
1017
1018    #[tokio::test(flavor = "multi_thread")]
1019    async fn server_info_carries_the_app_rows() {
1020        let f = prepared();
1021        let endpoint = f.endpoint.clone();
1022        let server = AppServer::new(&CTX, "0.0.0")
1023            .endpoint(endpoint.clone())
1024            .status_rows(std::sync::Arc::new(|| {
1025                vec![StatusRow {
1026                    name: "sync".into(),
1027                    value: "enabled".into(),
1028                }]
1029            }));
1030        let handle = tokio::spawn(async move { server.run().await });
1031        wait_until_listening(&endpoint).await;
1032        let (client, _) = sapphire_ipc::connect_or_absent(&endpoint, CTX.app_name, client_info())
1033            .await
1034            .unwrap()
1035            .unwrap();
1036        let report: StatusReport = client
1037            .call(
1038                sapphire_backend::protocol::SERVER_INFO,
1039                serde_json::json!({}),
1040            )
1041            .await
1042            .unwrap();
1043        assert!(report.running);
1044        assert_eq!(report.app.len(), 1);
1045        assert_eq!(report.app[0].name, "sync");
1046
1047        let _: serde_json::Value = client
1048            .call(sapphire_ipc::SHUTDOWN_METHOD, serde_json::json!({}))
1049            .await
1050            .unwrap();
1051        handle.await.unwrap().unwrap();
1052    }
1053}