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 corundum_framework_service::ServiceSpec;
29use sapphire_backend::protocol as proto;
30use sapphire_ipc::{Endpoint, ManagedBy, Router, ServerInfo, serve};
31use sapphire_workspace::AppContext;
32use tokio::sync::Notify;
33
34use crate::restart::Exit;
35
36/// How long a server's shutdown waits for its open connections to wind down on their own.
37///
38/// The shutdown acknowledgement is one of those connections; a moment is all a well-behaved
39/// client needs. Whatever still holds on after this is cancelled, so a connection kept open
40/// past shutdown cannot pin the router — and through it the sync runtime's replica stores —
41/// after the server has answered its own shutdown call.
42const SERVE_GRACE: Duration = Duration::from_secs(2);
43
44pub mod api_keys;
45mod command;
46mod config;
47mod config_methods;
48mod current;
49mod error;
50mod events;
51#[cfg(feature = "metrics")]
52mod exporter;
53mod handlers;
54mod host;
55#[cfg(feature = "http")]
56mod http;
57mod instrument;
58mod relay;
59mod restart;
60mod selection;
61mod settings;
62pub mod sync;
63#[cfg(test)]
64mod test_support;
65mod update;
66
67pub use command::{
68    AppConfigCommand, AppScopeFlags, AppUpdateArgs, FrameworkCommand, LegacyExternalDevice,
69    StatusReport, StatusRow, WorkspaceCommand, WorkspaceSyncCommand, render_workspace,
70    render_workspace_show,
71};
72pub use config::{
73    HttpConfig, HttpMcpConfig, HttpMetricsConfig, SERVER_CONFIG_FILE, ServerConfig, UpdateConfig,
74};
75pub use current::Current;
76pub use error::{Error, Result};
77pub use events::subscribe_method;
78pub use handlers::workspace_router;
79pub use host::WorkspaceHost;
80pub use restart::serve_restarting;
81pub use sapphire_framework_settings::{
82    Apply, FieldError, Kind, Process, Scope, SettingDef, Staged, Value,
83};
84pub use sapphire_framework_update::{ReleaseSource, UpdateArgs};
85pub use selection::{SELECTION_FILE, Selection, SelectionFile};
86pub use settings::{AppFiles, AppSettings, FromValue, HttpEndpoint, Settings};
87pub use sync::{BackfillTiming, BridgeConnector, SyncRuntime, SyncStatus, sync_router};
88
89/// The MCP tools an application serves, and how (feature `mcp`).
90#[cfg(feature = "mcp")]
91pub use sapphire_framework_mcp as mcp;
92
93/// The `metrics` crate, for an application's own metrics: the macros it records with, and
94/// the types [`AppServer::metrics_collector`] sets them from.
95pub use metrics;
96
97/// An application's server.
98pub struct AppServer {
99    ctx: &'static AppContext,
100    version: &'static str,
101    endpoint: Option<Endpoint>,
102    /// Where `workspace.toml` lives; `None` is the config directory's.
103    selection_file: Option<PathBuf>,
104    host: Arc<WorkspaceHost>,
105    sync: Option<Arc<SyncRuntime>>,
106    /// How the relay reaches the bridge when there is no sync runtime to share; `None` is
107    /// the host's own bridge.
108    bridge_connector: Option<BridgeConnector>,
109    extend: Option<Box<dyn FnOnce(Router) -> Router + Send>>,
110    /// The application's own status rows, shown after the framework's in `status` and in
111    /// the `server.info` report.
112    status_rows: Option<Arc<dyn Fn() -> Vec<StatusRow> + Send + Sync>>,
113    /// The version of the application's own API, reported in the handshake.
114    app_api: Option<u32>,
115    /// The framework's settings, when given rather than read from `config.toml`.
116    config: Option<ServerConfig>,
117    /// The settings `config.*` reads and writes, and `config` comes from unless given;
118    /// `None` reads the framework's alone when `run` starts.
119    pub(crate) settings: Option<Settings>,
120    /// Where the application's releases are published: what the server looks for newer
121    /// ones in, and what `update` installs from.
122    releases: Option<ReleaseSource>,
123    /// Whether `run` stops on SIGTERM and ctrl-c. Off where the server is not the process's
124    /// own (a phone app hosting it in-process).
125    signals: bool,
126    /// What the application sets on every scrape of `/metrics`. Kept in a build without
127    /// feature `metrics` too, so the builder method needs no gate; `run` never calls them there.
128    metrics_collectors: Vec<Arc<dyn Fn() + Send + Sync>>,
129    /// Where the HTTP listener binds when `config.toml` does not say.
130    #[cfg(feature = "http")]
131    http_listen: Option<std::net::SocketAddr>,
132    /// The application's own HTTP routes.
133    #[cfg(feature = "http")]
134    http_routes: Option<axum::Router>,
135    /// The application's switchable HTTP endpoints, by name.
136    #[cfg(feature = "http")]
137    http_endpoints: Vec<(String, axum::Router)>,
138    /// How the HTTP routes check a token; `None`: the served workspace's API keys.
139    #[cfg(feature = "http")]
140    http_auth: Option<sapphire_framework_keys::AuthConfig>,
141    /// The profiles an API key may act as, and what each may do.
142    key_profiles: sapphire_framework_keys::KeyProfiles,
143    /// The application's MCP handler, for the `mcp` subcommand and `/mcp`.
144    #[cfg(feature = "mcp")]
145    mcp: sapphire_framework_mcp::McpService,
146}
147
148/// The SIGTERM end of the server's select loop, in a shape every platform shares.
149///
150/// [`AppServer::run`]'s select arm awaits `recv()` on one of these, exactly as the
151/// plan writes it for Unix. Unix backs it with the `SignalKind::terminate()`
152/// stream; Windows has no SIGTERM, so there the future never resolves and the arm
153/// exists for the macro's sake and never fires. Without the common shape the arm
154/// would need a `#[cfg]` of its own, which tokio's `select!` rejects once the
155/// attribute removes the arm.
156#[cfg(unix)]
157struct Sigterm(tokio::signal::unix::Signal);
158
159/// The never-firing stand-in for the Unix `Sigterm` where there is no SIGTERM.
160#[cfg(not(unix))]
161struct Sigterm;
162
163impl Sigterm {
164    /// The stream a server that listens for signals awaits SIGTERM on.
165    ///
166    /// Registered before the listener binds, so a signal arriving the instant the socket
167    /// is up is queued by tokio instead of killing the process with the default handler.
168    /// SIGINT is listened to only through `ctrl_c` (which swallows the default handler on
169    /// both platforms): a Unix `SignalKind::interrupt()` stream would double-fire for ^C.
170    fn register() -> Result<Option<Sigterm>> {
171        #[cfg(unix)]
172        return Ok(Some(Sigterm::new()?));
173        #[cfg(not(unix))]
174        return Ok(Some(Sigterm));
175    }
176}
177
178#[cfg(unix)]
179impl Sigterm {
180    /// Register interest in SIGTERM: see [`register`](Self::register).
181    fn new() -> Result<Self> {
182        Ok(Self(tokio::signal::unix::signal(
183            tokio::signal::unix::SignalKind::terminate(),
184        )?))
185    }
186
187    /// Wait for the next SIGTERM.
188    ///
189    /// Never returns `None`: the stream is infinite, as its documentation states.
190    async fn recv(&mut self) {
191        self.0.recv().await;
192    }
193}
194
195#[cfg(not(unix))]
196impl Sigterm {
197    /// A future that is never ready — the arm awaits it for the macro's sake only.
198    ///
199    /// There is no `new`: this platform has no SIGTERM to register interest in, so
200    /// [`register`](Self::register) makes the unit value directly.
201    async fn recv(&mut self) {
202        std::future::pending::<()>().await
203    }
204}
205
206/// The file the selected workspace is kept in: at `path` when a fixture moved it, in the
207/// config directory otherwise.
208fn selection_at(ctx: &AppContext, path: Option<PathBuf>) -> SelectionFile {
209    match path {
210        Some(path) => SelectionFile::at(path),
211        None => SelectionFile::for_app(ctx),
212    }
213}
214
215/// ctrl-c, when the server listens for signals; never otherwise.
216async fn interrupted(signals: bool) {
217    if signals {
218        // An error means no handler could be installed: nothing will arrive.
219        if tokio::signal::ctrl_c().await.is_ok() {
220            return;
221        }
222    }
223    std::future::pending::<()>().await
224}
225
226/// SIGTERM, when the server listens for signals; never otherwise.
227async fn terminated(sigterm: &mut Option<Sigterm>) {
228    match sigterm {
229        Some(sigterm) => sigterm.recv().await,
230        None => std::future::pending::<()>().await,
231    }
232}
233
234impl AppServer {
235    /// A server for `ctx`'s application, reporting `version` in its handshake.
236    pub fn new(ctx: &'static AppContext, version: &'static str) -> AppServer {
237        AppServer {
238            ctx,
239            version,
240            endpoint: None,
241            selection_file: None,
242            host: Arc::new(WorkspaceHost::new(ctx)),
243            sync: None,
244            bridge_connector: None,
245            extend: None,
246            status_rows: None,
247            app_api: None,
248            config: None,
249            settings: None,
250            releases: None,
251            signals: true,
252            metrics_collectors: Vec::new(),
253            #[cfg(feature = "http")]
254            http_listen: None,
255            #[cfg(feature = "http")]
256            http_routes: None,
257            #[cfg(feature = "http")]
258            http_endpoints: Vec::new(),
259            #[cfg(feature = "http")]
260            http_auth: None,
261            key_profiles: sapphire_framework_keys::KeyProfiles::standard(),
262            #[cfg(feature = "mcp")]
263            mcp: sapphire_framework_mcp::McpService::framework(),
264        }
265    }
266
267    /// The application this server serves, as its [`AppContext`] names it.
268    pub fn app_name(&self) -> &'static str {
269        self.ctx.app_name
270    }
271
272    /// Listen somewhere other than the application's default endpoint. Used by tests.
273    pub fn endpoint(mut self, endpoint: Endpoint) -> AppServer {
274        self.endpoint = Some(endpoint);
275        self
276    }
277
278    /// Stop on SIGTERM and ctrl-c (`true`, the default), or leave signals to the process.
279    ///
280    /// A host that runs the server inside a larger process — a phone app, with the bridge
281    /// and the GUI beside it — turns this off: the signals are the process's to handle,
282    /// and the server stops when the task running it is dropped.
283    pub fn signals(mut self, on: bool) -> AppServer {
284        self.signals = on;
285        self
286    }
287
288    /// Report `version` as the application's own API version in the handshake: the major
289    /// of the application's API crate, which carries the methods it adds with
290    /// [`extend`](Self::extend). A client that calls those methods names the version it
291    /// expects, and the handshake refuses a server that speaks another.
292    pub fn app_api(mut self, version: u32) -> AppServer {
293        self.app_api = Some(version);
294        self
295    }
296
297    /// Use `config` rather than the one `<config dir>/config.toml` gives: for fixtures.
298    /// `config.*` still reads and writes the file.
299    pub fn config(mut self, config: ServerConfig) -> AppServer {
300        self.config = Some(config);
301        self
302    }
303
304    /// Serve the application's settings `app` beside the framework's, read now: for
305    /// fixtures. Called after [`selection_file`](Self::selection_file), whose selected
306    /// workspace holds the workspace scope.
307    #[cfg(feature = "test-util")]
308    #[doc(hidden)]
309    pub fn app_settings(mut self, app: Arc<dyn AppSettings>) -> Result<AppServer> {
310        let selection = self.selection();
311        self.settings = Some(Settings::load_with(self.ctx, app, selection)?);
312        Ok(self)
313    }
314
315    /// The settings `config.*` serves, once [`app_settings`](Self::app_settings) has read
316    /// them: for fixtures.
317    #[cfg(feature = "test-util")]
318    #[doc(hidden)]
319    pub fn settings(&self) -> Option<&Settings> {
320        self.settings.as_ref()
321    }
322
323    /// The endpoint this server listens on: the one [`endpoint`](Self::endpoint) gave, or
324    /// the application's own.
325    fn endpoint_or_default(&self) -> Result<Endpoint> {
326        match &self.endpoint {
327            Some(e) => Ok(e.clone()),
328            None => Ok(Endpoint::for_app(self.ctx.app_name)?),
329        }
330    }
331
332    /// The file the selected workspace is kept in.
333    #[cfg(feature = "test-util")]
334    fn selection(&self) -> SelectionFile {
335        selection_at(self.ctx, self.selection_file.clone())
336    }
337
338    /// Where the HTTP listener binds unless `config.toml` says otherwise: the application's
339    /// own port. Without it, a host that serves anything over HTTP names the address in
340    /// `[http] listen`.
341    #[cfg(feature = "http")]
342    pub fn http_listen(mut self, addr: std::net::SocketAddr) -> AppServer {
343        self.http_listen = Some(addr);
344        self
345    }
346
347    /// Serve the application's own HTTP routes on the server's listener, behind the same
348    /// API key's token as `/mcp`. The routes are served whenever they are given;
349    /// `/mcp` only when `config.toml` turns it on. For routes a setting turns on and off,
350    /// see [`http_endpoint`](Self::http_endpoint).
351    ///
352    /// Every route but `/metrics` is behind the token. While `[http.metrics]` is on, the
353    /// public `/metrics` answers first, so an application route at `/metrics` is shadowed.
354    #[cfg(feature = "http")]
355    pub fn http(mut self, routes: axum::Router) -> AppServer {
356        self.http_routes = Some(routes);
357        self
358    }
359
360    /// Serve `routes` at `/<name>` on the server's listener, behind the same token as
361    /// `/mcp`, while `http.<name>.enabled` is on; it is off by default.
362    ///
363    /// `name` is one the application's settings declare
364    /// ([`AppSettings::http_endpoints`]), which gives the switch its help text: one they
365    /// do not declare stops [`run`](Self::run) with an error.
366    #[cfg(feature = "http")]
367    pub fn http_endpoint(mut self, name: impl Into<String>, routes: axum::Router) -> AppServer {
368        self.http_endpoints.push((name.into(), routes));
369        self
370    }
371
372    /// Check HTTP tokens with `auth` rather than with the served workspace's API keys: for
373    /// fixtures, or for an application whose own [`Verifier`](sapphire_framework_keys::Verifier)
374    /// wraps [`api_keys::WorkspaceKeyVerifier`] to map a key to something of its own.
375    #[cfg(feature = "http")]
376    pub fn http_auth(mut self, auth: sapphire_framework_keys::AuthConfig) -> AppServer {
377        self.http_auth = Some(auth);
378        self
379    }
380
381    /// The profiles an API key may act as, and the access each gives: the framework's
382    /// `read-only`, `read-write` and `admin` unless the application has its own
383    /// (sapphire-agent's room profiles). `api-key add --profile` takes one of them, and the
384    /// HTTP routes hold a key to its access: a read-only key calls only `/mcp`'s read-only
385    /// tools, and only `GET` the application's routes.
386    pub fn key_profiles(mut self, profiles: sapphire_framework_keys::KeyProfiles) -> AppServer {
387        self.key_profiles = profiles;
388        self
389    }
390
391    /// The profiles an API key may act as ([`key_profiles`](Self::key_profiles)).
392    pub fn profiles(&self) -> &sapphire_framework_keys::KeyProfiles {
393        &self.key_profiles
394    }
395
396    /// Answer MCP with the application's own handler, rather than the framework's tools
397    /// alone: on stdio for the `mcp` subcommand, and at `/mcp` when `config.toml` turns it
398    /// on.
399    #[cfg(feature = "mcp")]
400    pub fn mcp(mut self, service: sapphire_framework_mcp::McpService) -> AppServer {
401        self.mcp = service;
402        self
403    }
404
405    /// Serve the application's MCP tools on this process's stdio, until the agent closes
406    /// it: the `mcp` subcommand.
407    ///
408    /// This is the client side: the tools reach the running server over its IPC endpoint,
409    /// as the CLI does, and nothing here starts one.
410    #[cfg(feature = "mcp")]
411    pub async fn serve_mcp_stdio(self, version: &'static str) -> Result<()> {
412        let endpoint = match self.endpoint {
413            Some(e) => e,
414            None => Endpoint::for_app(self.ctx.app_name)?,
415        };
416        let ctx = sapphire_framework_mcp::ToolContext::dial(
417            self.ctx.app_name,
418            version,
419            self.app_api,
420            endpoint,
421        );
422        self.mcp
423            .serve_stdio(ctx)
424            .await
425            .map_err(|e| Error::Mcp(e.to_string()))
426    }
427
428    /// Keep the selected workspace (`workspace.toml`) at `path` rather than in the
429    /// application's config directory: for fixtures that run several hosts in one process.
430    pub fn selection_file(mut self, path: PathBuf) -> AppServer {
431        self.selection_file = Some(path);
432        self
433    }
434
435    /// Serve `sync.enable`, `sync.disable`, `sync.map` and `sync.status`, and keep a replica
436    /// of the workspace in step with its files while it is synced.
437    ///
438    /// Without this the server has no sync at all: an application that does not call it
439    /// never talks to the bridge. The runtime is built by the caller because it needs the
440    /// bridge connection, which is the caller's to open and to close.
441    pub fn sync(mut self, runtime: Arc<SyncRuntime>) -> AppServer {
442        // The runtime re-indexes what a session writes, and the index belongs to this host:
443        // tell it where the workspace lives before anything can arrive.
444        runtime.set_host(Arc::clone(&self.host));
445        self.sync = Some(runtime);
446        self
447    }
448
449    /// Sync through the host's `sapphire-bridge`: [`sync`](Self::sync) with a runtime that
450    /// reaches the bridge itself, and reaches it again whenever it is lost (#244).
451    ///
452    /// [`run`](Self::run) makes the first attempt. No bridge running is not fatal — the
453    /// server serves without sync and picks the bridge up once it starts, and `sync.*`
454    /// answers that it is not connected meanwhile — but any other failure, such as a bridge
455    /// of another API version, stops the start.
456    pub fn sync_via_bridge(self) -> Result<AppServer> {
457        let runtime = SyncRuntime::connecting(
458            self.ctx,
459            BridgeConnector::standard(self.ctx.app_name, self.version),
460            std::env::current_exe()?,
461            ManagedBy::Service,
462        );
463        Ok(self.sync(Arc::new(runtime)))
464    }
465
466    /// Reach the bridge with `connector` for the relayed `bridge.*`, `embed.*` and
467    /// `config.*` methods, rather than at the host's standard
468    /// endpoint.
469    ///
470    /// Used only without [`sync`](Self::sync): a server with a sync runtime relays over the
471    /// runtime's connection. The connection is made on the first relayed call, and made
472    /// again on the next call after it drops.
473    pub fn bridge_connector(mut self, connector: BridgeConnector) -> AppServer {
474        self.bridge_connector = Some(connector);
475        self
476    }
477
478    /// The application's own rows for the status report: shown after the framework's
479    /// `running` / `version` / `pid` / `managed_by` lines.
480    ///
481    /// The closure is called once per report, so an application's rows may read live
482    /// state; the CLI's `status` and the IPC `server.info` method render the same call's
483    /// output.
484    pub fn status_rows(mut self, rows: Arc<dyn Fn() -> Vec<StatusRow> + Send + Sync>) -> AppServer {
485        self.status_rows = Some(rows);
486        self
487    }
488
489    /// Set the application's own gauges on every scrape of `/metrics`.
490    ///
491    /// `collect` runs once per scrape, after the framework has refreshed its own state and
492    /// before the response is rendered; collectors run in the order they were added. It runs
493    /// inside the async `/metrics` handler, so keep it cheap and non-blocking — read values
494    /// already held rather than doing I/O or waiting on a lock — and it must not panic. Set
495    /// state with `sapphire_framework::metrics::gauge!`, and prefix each name with the
496    /// application's own, as in `sapphire_journal_entries`, so it cannot collide with the
497    /// framework's `sapphire_*` names. Labels carry no identifiers, paths or names: the
498    /// endpoint is served without a token, so anything in a label is public.
499    ///
500    /// A build without feature `metrics`, or a server whose `config.toml` leaves
501    /// `[http.metrics]` off, never calls it.
502    pub fn metrics_collector(mut self, collect: Arc<dyn Fn() + Send + Sync>) -> AppServer {
503        self.metrics_collectors.push(collect);
504        self
505    }
506
507    /// Where this application's releases are published.
508    ///
509    /// The server looks there for newer ones once at start and once a day after, unless
510    /// `config.toml` says `[update] check = false`; `status` and the GUI show what it found.
511    /// The `update` command installs from there, when `source` names the release's
512    /// [asset](ReleaseSource::asset).
513    pub fn releases(mut self, source: ReleaseSource) -> AppServer {
514        self.releases = Some(source);
515        self
516    }
517
518    /// Where this application's releases are published, if it said.
519    pub fn release_source(&self) -> Option<&ReleaseSource> {
520        self.releases.as_ref()
521    }
522
523    /// What this application's service is: the arguments a service manager starts it with.
524    ///
525    /// `["serve"]`: a service manager starts the executable directly with
526    /// [`FrameworkCommand::Serve`](crate::FrameworkCommand::Serve) — the bare invocation
527    /// prints the help in the CLI version and opens the window in the desktop one. A CLI
528    /// that wants its service installed hands this to
529    /// [`ServiceCommand`](corundum_framework_service::ServiceCommand), which registers the
530    /// running executable (the AppImage, inside one).
531    pub fn service_spec(&self) -> ServiceSpec {
532        ServiceSpec {
533            app_name: self.ctx.app_name,
534            description: format!("{} server {}", self.ctx.app_name, self.version),
535            args: vec!["serve".to_owned()],
536            // The first label sapphire registered on macOS; corundum retires its own
537            // earlier one (net.sapphire-turtle.<app>) by itself (#385).
538            legacy_labels: vec![format!("net.fireturtle.sapphire.{}", self.ctx.app_name)],
539            post_install: None,
540        }
541    }
542
543    /// Add the application's own methods.
544    pub fn extend(mut self, f: impl FnOnce(Router) -> Router + Send + 'static) -> AppServer {
545        self.extend = Some(Box::new(f));
546        self
547    }
548
549    /// The workspace this server has open. An application's own handlers use it to reach
550    /// the workspace the same way the framework's do: [`WorkspaceHost::backend`].
551    pub fn host(&self) -> &Arc<WorkspaceHost> {
552        &self.host
553    }
554
555    /// The sync runtime, once [`sync`](Self::sync) or [`sync_via_bridge`](Self::sync_via_bridge)
556    /// has set one (#250): for an application's own code that reads sync state — status
557    /// rows, or which device is the workspace's primary.
558    pub fn sync_runtime(&self) -> Option<&Arc<SyncRuntime>> {
559        self.sync.as_ref()
560    }
561
562    /// Listen until told to stop, or until a signal arrives.
563    ///
564    /// A server run this way answers `server.restart` with an error: nothing would bring it
565    /// back. [`serve_restarting`] runs one that can.
566    pub async fn run(self) -> Result<()> {
567        // Before anything is bound: a mistake in the application, not in the files.
568        #[cfg(feature = "http")]
569        undeclared_endpoints(self.settings.as_ref(), &self.http_endpoints)?;
570        let endpoint = self.endpoint_or_default()?;
571        // The app's log file, held for as long as this server serves: the guard's drop
572        // flushes the writer thread, so the last lines of a clean shutdown land in the file.
573        // The subscriber itself was installed by `ctx.init`; this is what routes the file
574        // layer at `<data dir>/logs/`.
575        let _log = sapphire_workspace::logging::install(self.ctx)?;
576        // Registered before the bind: see `Sigterm::register`.
577        let mut sigterm = if self.signals {
578            Sigterm::register()?
579        } else {
580            None
581        };
582        #[cfg(unix)]
583        let mut listener = sapphire_ipc::bind(&endpoint).await?;
584        #[cfg(windows)]
585        let mut listener = sapphire_ipc::bind(&endpoint)?;
586        let exit = self.serve_on(&mut listener, None, &mut sigterm).await;
587        drop(listener); // removes the socket file on Unix
588        debug_assert!(
589            !matches!(exit, Ok(Exit::Restart)),
590            "nothing can ask for one"
591        );
592        exit.map(|_| ())
593    }
594
595    /// Serve on `listener` until told to stop, a signal arrives, or `restart` fires.
596    ///
597    /// `restart` is what `server.restart` fires; `None` answers it with an error.
598    /// `sigterm` is the caller's, so it outlives one server: see [`serve_restarting`].
599    /// The listener, the log and the process stay with the caller; everything else this
600    /// server started is stopped before it returns — on [`Exit::Restart`] down to the last
601    /// task that held the sync runtime, so the next server's runtime can open the replica
602    /// store.
603    pub(crate) async fn serve_on(
604        self,
605        listener: &mut sapphire_ipc::Listener,
606        restart: Option<Arc<Notify>>,
607        sigterm: &mut Option<Sigterm>,
608    ) -> Result<Exit> {
609        let AppServer {
610            ctx,
611            version,
612            endpoint: _,
613            selection_file,
614            host,
615            sync,
616            bridge_connector,
617            extend,
618            status_rows,
619            app_api,
620            config,
621            settings,
622            releases,
623            signals,
624            metrics_collectors,
625            #[cfg(feature = "http")]
626            http_listen,
627            #[cfg(feature = "http")]
628            http_routes,
629            #[cfg(feature = "http")]
630            http_endpoints,
631            #[cfg(feature = "http")]
632            http_auth,
633            key_profiles,
634            #[cfg(feature = "mcp")]
635            mcp,
636        } = self;
637        // Only the HTTP routes check a key.
638        #[cfg(not(feature = "http"))]
639        let _ = key_profiles;
640        // Without the exporter nothing scrapes, so there is nothing to call them from.
641        #[cfg(not(feature = "metrics"))]
642        let _ = metrics_collectors;
643
644        // A server is always-on from here on: only `serve` and the service manager start
645        // one, and the service manager starts it for keeps. There is no spawned mode left
646        // to report.
647        let info = ServerInfo {
648            version: version.to_owned(),
649            api: proto::API_VERSION,
650            app_api,
651            pid: std::process::id(),
652            managed_by: ManagedBy::Service,
653        };
654
655        let file = selection_at(ctx, selection_file);
656        // A context whose config directory was never resolved has no file to read, and
657        // gets the defaults — as it gets no log file — and no settings of its own to serve.
658        let settings = match settings {
659            Some(settings) => Some(settings),
660            None if ctx.try_config_dir().is_some() => {
661                Some(Settings::load_with(ctx, Arc::new(()), file.clone())?)
662            }
663            None => None,
664        };
665        let config = match (config, &settings) {
666            (Some(config), _) => config,
667            (None, Some(settings)) => ServerConfig::from_settings(settings)?,
668            (None, None) => ServerConfig::default(),
669        };
670        #[cfg(feature = "http")]
671        undeclared_endpoints(settings.as_ref(), &http_endpoints)?;
672        #[cfg(feature = "http")]
673        let http_routes = http_endpoints
674            .into_iter()
675            .filter(|(name, _)| config.http.endpoints.contains(name))
676            .fold(http_routes, |routes, (name, endpoint)| {
677                let endpoint = axum::Router::new().nest(&format!("/{name}"), endpoint);
678                Some(match routes {
679                    Some(routes) => routes.merge(endpoint),
680                    None => endpoint,
681                })
682            });
683        // A read-only key may only `GET` the application's routes; `/mcp`, all `POST`,
684        // checks each tool instead.
685        #[cfg(feature = "http")]
686        let http_routes = http_routes.map(sapphire_framework_keys::read_only_by_method);
687        #[cfg(not(feature = "mcp"))]
688        if config.http.mcp.enabled {
689            tracing::warn!(
690                "config.toml turns MCP over HTTP on, but this build of {} has no MCP",
691                ctx.app_name
692            );
693        }
694        #[cfg(not(feature = "metrics"))]
695        if config.http.metrics.enabled {
696            tracing::warn!(
697                "config.toml turns metrics on, but this build of {} has no metrics",
698                ctx.app_name
699            );
700        }
701
702        let (stop_tx, mut stop_rx) = tokio::sync::watch::channel(false);
703
704        // What `server.update` answers; the looking task fills it in once the server serves.
705        let update_status = update::SharedStatus::default();
706        let update_check = releases.filter(|_| config.update.check);
707
708        // The first attempt to reach the bridge, before the selected workspace comes back
709        // and asks it for sync.
710        if let Some(runtime) = &sync {
711            runtime.connect().await?;
712        }
713
714        // Workspace keys follow the selection and the marker's `config.toml` as sync or an
715        // edit changes it.
716        let mut current = Current::new(ctx, Arc::clone(&host), sync.clone(), file);
717        if let Some(settings) = &settings {
718            current = current.with_settings(settings.clone());
719        }
720        if let Some(runtime) = &sync {
721            runtime.set_settings(settings.clone());
722        }
723        let current = Arc::new(current);
724        // Back to the workspace this host had, before the first client can ask for it.
725        let restoring = current.restore().await;
726
727        let mut router = subscribe_method(
728            Arc::clone(&host),
729            current::current_methods(Arc::clone(&current), workspace_router(Arc::clone(&current))),
730        );
731        if sync.is_some() {
732            // `sync_router` is applied *under* the application's own methods so a later
733            // `extend` can still replace one, and after `subscribe_method` so the
734            // `workspace.*` namespace is complete.
735            router = sync_router(Arc::clone(&current), router);
736        }
737        // The bridge's client-facing methods, over the sync runtime's connection when there
738        // is one. Like `sync_router`, under the application's own methods.
739        let link = match &sync {
740            Some(runtime) => relay::BridgeLink::Sync(Arc::clone(runtime)),
741            None => relay::BridgeLink::own(
742                bridge_connector
743                    .unwrap_or_else(|| BridgeConnector::standard(ctx.app_name, version)),
744            ),
745        };
746        let relay = Arc::new(relay::Relay::new(link));
747        router = Arc::clone(&relay).routes(router);
748        // `config.*`: this server's settings merged with the bridge's. Without settings of
749        // its own, the bridge's alone, relayed.
750        router = match settings {
751            Some(settings) => config_methods::routes(router, settings, relay),
752            None => relay.routes_for(router, sapphire_bridge_api::ANSWERED_BY_APP_SERVER),
753        };
754        // `server.info` answers the typed [`StatusReport`] — the same shape the CLI's
755        // `status` renders — so the CLI and a future GUI read one record. The rows come
756        // from the application's builder, called once per report.
757        router = router
758            .method(proto::SERVER_INFO, {
759                let info = info.clone();
760                let status_rows = status_rows.clone();
761                move |_| {
762                    let info = info.clone();
763                    let status_rows = status_rows.clone();
764                    async move {
765                        let app = status_rows.as_ref().map(|rows| rows()).unwrap_or_default();
766                        let report = StatusReport {
767                            running: true,
768                            version: Some(info.version),
769                            pid: Some(info.pid),
770                            managed_by: Some(match info.managed_by {
771                                ManagedBy::Service => proto::ManagedBy::Service,
772                                ManagedBy::Spawned => proto::ManagedBy::Spawned,
773                            }),
774                            app,
775                        };
776                        serde_json::to_value(report)
777                            .map_err(|e| sapphire_ipc::RpcError::internal(e.to_string()))
778                    }
779                }
780            })
781            .method(proto::SERVER_UPDATE, {
782                let update_status = Arc::clone(&update_status);
783                move |_| {
784                    let status = update_status.lock().expect("update status lock").clone();
785                    async move {
786                        serde_json::to_value(status)
787                            .map_err(|e| sapphire_ipc::RpcError::internal(e.to_string()))
788                    }
789                }
790            })
791            .method(proto::SERVER_RESTART, {
792                let restart = restart.clone();
793                move |_| {
794                    let answer = restart::request(restart.clone());
795                    async move {
796                        answer?;
797                        serde_json::to_value(proto::Ack {})
798                            .map_err(|e| sapphire_ipc::RpcError::internal(e.to_string()))
799                    }
800                }
801            })
802            .method(sapphire_ipc::SHUTDOWN_METHOD, {
803                let stop_tx = stop_tx.clone();
804                move |_| {
805                    let stop_tx = stop_tx.clone();
806                    async move {
807                        let _ = stop_tx.send(true);
808                        serde_json::to_value(proto::Ack {})
809                            .map_err(|e| sapphire_ipc::RpcError::internal(e.to_string()))
810                    }
811                }
812            });
813        if let Some(extend) = extend {
814            router = extend(router);
815        }
816        let router = Arc::new(router);
817
818        // The caller's SIGTERM stream, unless this server leaves signals to the process.
819        let mut no_sigterm = None;
820        let sigterm = if signals { sigterm } else { &mut no_sigterm };
821        // What `server.restart` fires; never, where there is no restarting.
822        let restarted = async {
823            match &restart {
824                Some(restart) => restart.notified().await,
825                None => std::future::pending().await,
826            }
827        };
828        tokio::pin!(restarted);
829        let mut exit = Exit::Stopped;
830
831        let mut connections = tokio::task::JoinSet::new();
832
833        // The HTTP listener, when anything is served over it. Started with the IPC socket
834        // bound, for the same reason as the sync tasks below. `/mcp`'s tools reach this
835        // server the way the `mcp` subcommand's do — over IPC — on an in-process connection
836        // served like any other. `/metrics` is the one public route, served without a token.
837        #[cfg(feature = "http")]
838        let http_stop = tokio_util::sync::CancellationToken::new();
839        #[cfg(feature = "http")]
840        let http_task = {
841            #[cfg(feature = "mcp")]
842            let routes = if config.http.mcp.enabled {
843                let (ours, theirs) = sapphire_ipc::Connection::pair();
844                {
845                    let router = Arc::clone(&router);
846                    let info = info.clone();
847                    let app = ctx.app_name;
848                    connections.spawn(async move {
849                        let _ = serve(theirs, router, app, info).await;
850                    });
851                }
852                let client_info = sapphire_ipc::ClientInfo {
853                    kind: sapphire_framework_mcp::CLIENT_KIND.to_owned(),
854                    version: version.to_owned(),
855                    api: proto::API_VERSION,
856                    app_api,
857                    pid: std::process::id(),
858                };
859                let (client, _) =
860                    sapphire_ipc::Client::handshake(ours, ctx.app_name, client_info).await?;
861                let tools = sapphire_framework_mcp::ToolContext::connected(
862                    ctx.app_name,
863                    version,
864                    Arc::new(client),
865                );
866                let mcp_routes =
867                    mcp.http_router(tools, &config.http.allowed_hosts, http_stop.child_token());
868                Some(match http_routes {
869                    Some(routes) => routes.merge(mcp_routes),
870                    None => mcp_routes,
871                })
872            } else {
873                http_routes
874            };
875            #[cfg(not(feature = "mcp"))]
876            let routes = http_routes;
877            #[cfg(feature = "metrics")]
878            let public = if config.http.metrics.enabled
879                && let Some(handle) = exporter::install()
880            {
881                metrics::gauge!(
882                    instrument::BUILD_INFO,
883                    "app" => ctx.app_name,
884                    "version" => version,
885                )
886                .set(1.0);
887                let scrape = Arc::new(exporter::Scrape {
888                    process: metrics_process::Collector::default(),
889                    current: Arc::clone(&current),
890                    update: Arc::clone(&update_status),
891                    collectors: metrics_collectors,
892                });
893                Some(exporter::routes(handle, scrape))
894            } else {
895                None
896            };
897            #[cfg(not(feature = "metrics"))]
898            let public: Option<axum::Router> = None;
899            match (
900                routes.is_some() || public.is_some(),
901                config.http.listen.or(http_listen),
902            ) {
903                (false, _) => None,
904                (true, None) => {
905                    tracing::error!(
906                        "nothing to bind HTTP to: set `[http] listen` in {SERVER_CONFIG_FILE}"
907                    );
908                    None
909                }
910                (true, Some(addr)) => {
911                    let auth = http_auth.unwrap_or_else(|| {
912                        sapphire_framework_keys::AuthConfig::new(Arc::new(
913                            api_keys::WorkspaceKeyVerifier::for_app(ctx)
914                                .profiles(key_profiles.clone()),
915                        ))
916                    });
917                    http::start(addr, routes, public, auth, http_stop.clone()).await
918                }
919            }
920        };
921
922        // The watcher, the bridge announcement loop, the dialer and the bridge connection, if
923        // sync is on. Started only once the socket is bound, so an early `?` above cannot
924        // leave tasks running for a server that never served. All of them are allowed to
925        // fail: only sync stops when they do, and the app server keeps serving files
926        // (spec §10). They are aborted with the server.
927        let sync_tasks = match &sync {
928            Some(runtime) => {
929                let driver = Arc::clone(runtime);
930                let announcements = tokio::spawn(async move {
931                    if let Err(err) = driver.run().await {
932                        tracing::warn!("the bridge announcement loop ended: {err}");
933                    }
934                });
935                let changing = Arc::clone(runtime);
936                let watching = tokio::spawn(async move {
937                    if let Err(err) = changing.watch_changes().await {
938                        tracing::warn!("the file watcher ended: {err}");
939                    }
940                });
941                // The dialer is what keeps a session open after the initial exchange, so a
942                // commit reaches a peer without waiting for the next one (spec §4.2).
943                let dialling = Arc::clone(runtime);
944                let dialling = tokio::spawn(async move {
945                    if let Err(err) = dialling.dial_loop().await {
946                        tracing::warn!("the live dial loop ended: {err}");
947                    }
948                });
949                // Reaching the bridge again whenever it is lost (#244).
950                let connected = tokio::spawn(Arc::clone(runtime).keep_connected());
951                Some([announcements, watching, dialling, connected])
952            }
953            None => None,
954        };
955
956        // Looking for newer releases, once the socket is bound for the same reason. Ends
957        // with the server, when this is dropped.
958        let _update_checking = update_check.and_then(|check| {
959            update::start(check, ctx.app_name, version, Arc::clone(&update_status))
960        });
961
962        loop {
963            tokio::select! {
964                changed = stop_rx.changed() => {
965                    if changed.is_err() || *stop_rx.borrow() {
966                        break;
967                    }
968                }
969                _ = interrupted(signals) => {
970                    tracing::info!("interrupted; shutting down");
971                    break;
972                }
973                _ = terminated(sigterm) => {
974                    tracing::info!("terminated; shutting down");
975                    break;
976                }
977                () = &mut restarted => {
978                    tracing::info!("stopping to restart");
979                    exit = Exit::Restart;
980                    break;
981                }
982                accepted = listener.accept() => {
983                    let conn = accepted?;
984                    // Moved into the task, so the connection stops counting as open when it
985                    // ends, or when the reaping below aborts it.
986                    let counted = instrument::IpcConnection::open();
987                    let router = Arc::clone(&router);
988                    let app = ctx.app_name;
989                    let info = info.clone();
990                    connections.spawn(async move {
991                        let _counted = counted;
992                        let _ = serve(conn, router, app, info).await;
993                    });
994                }
995            }
996        }
997
998        // Awaited, not only aborted: the restoring task holds `Current`, and with it the
999        // sync runtime, until it is dropped — which a restart must see done before the
1000        // next server opens the replica store.
1001        if let Some(restoring) = restoring {
1002            restoring.abort();
1003            let _ = restoring.await;
1004        }
1005        // HTTP first: its sessions hold a connection to this server, which the reaping
1006        // below waits for. Awaited after the abort too, for the same reason as above.
1007        #[cfg(feature = "http")]
1008        {
1009            http_stop.cancel();
1010            if let Some((_, mut task)) = http_task
1011                && tokio::time::timeout(SERVE_GRACE, &mut task).await.is_err()
1012            {
1013                tracing::debug!("the HTTP listener did not stop in time");
1014                task.abort();
1015                let _ = task.await;
1016            }
1017        }
1018        if let Some(tasks) = sync_tasks {
1019            // Each loop pins the sync runtime, and with it the replica stores. An aborted task
1020            // is only dropped once its current poll returns — which, mid-scan, can take a
1021            // while — so wait for that rather than return with a loop still holding a store
1022            // the next server in this process would fail to open (#235).
1023            for task in tasks {
1024                task.abort();
1025                let _ = task.await;
1026            }
1027        }
1028        if let Some(runtime) = &sync {
1029            // The first dials after an enable pin the runtime the same way, and so do the
1030            // inbound sessions, the live-session readers and the embedding passes.
1031            runtime.stop_dials().await;
1032            runtime.stop_background().await;
1033            // Close every live sync session. A session's reader task holds the replica, and
1034            // the session itself sits in the runtime's table until it is cleared, so leaving
1035            // one open pins the runtime — and the redb replica stores in it — after the
1036            // server is gone (spec §2.2: cancellation is disconnection).
1037            runtime.drop_connections().await;
1038        }
1039        host.close();
1040        // The listener is the caller's: it stays bound, and a client that connects now waits
1041        // in its backlog for the next server of a restart.
1042
1043        // Reap the per-connection serve tasks. Each one pins the router, the router pins
1044        // the sync runtime, and the runtime's replica stores are redb databases that stay
1045        // locked until the last pin is dropped — a server that left them running would
1046        // lock its own successor out of its state (spec §2.2: cancellation is
1047        // disconnection). Connections get a grace period to wind down on their own — the
1048        // shutdown acknowledgement among them — then the rest are cancelled: a client
1049        // that keeps its connection open past shutdown is holding a server that is gone.
1050        let _ = tokio::time::timeout(SERVE_GRACE, async {
1051            while connections.join_next().await.is_some() {}
1052        })
1053        .await;
1054        connections.abort_all();
1055        while connections.join_next().await.is_some() {}
1056        // Everything else of this server — the router, the relay, `Current`, the host and
1057        // the sync runtime — goes as this returns, before a restart builds the next one.
1058        Ok(exit)
1059    }
1060}
1061
1062/// An error for the first of `endpoints` the settings do not declare: it has no switch to
1063/// turn it on.
1064#[cfg(feature = "http")]
1065fn undeclared_endpoints(
1066    settings: Option<&Settings>,
1067    endpoints: &[(String, axum::Router)],
1068) -> Result<()> {
1069    let Some(settings) = settings else {
1070        return Ok(());
1071    };
1072    match endpoints.iter().find(|(name, _)| {
1073        settings
1074            .registry()
1075            .def(&settings::endpoint_key(name))
1076            .is_err()
1077    }) {
1078        Some((name, _)) => Err(Error::Config(format!(
1079            "the HTTP endpoint `{name}` is not one the application's settings declare"
1080        ))),
1081        None => Ok(()),
1082    }
1083}
1084
1085#[cfg(test)]
1086mod tests {
1087    use super::*;
1088    use sapphire_ipc::{ClientInfo, Endpoint, ManagedBy};
1089    use sapphire_workspace::{AppContext, AppKind};
1090    use std::ffi::OsString;
1091
1092    use crate::test_support;
1093
1094    static CTX: AppContext = AppContext::new("sapphire-appservertest");
1095
1096    /// The env vars `init_ctx` writes, in the order the guard restores them.
1097    const DIR_VARS: [&str; 3] = [
1098        "SAPPHIRE_APPSERVERTEST_CACHE_DIR",
1099        "SAPPHIRE_APPSERVERTEST_DATA_DIR",
1100        "SAPPHIRE_APPSERVERTEST_CONFIG_DIR",
1101    ];
1102
1103    fn client_info() -> ClientInfo {
1104        ClientInfo {
1105            kind: "test".into(),
1106            version: "0.0.0".into(),
1107            api: sapphire_backend::protocol::API_VERSION,
1108            app_api: None,
1109            pid: std::process::id(),
1110        }
1111    }
1112
1113    /// Point the context's directories at `tmp` and restore the previous values (present
1114    /// or absent) when dropped — including while unwinding from a panic. Without the
1115    /// unconditional restore, a panicking assertion would leave the variables pointing at
1116    /// a temp directory the test then deletes, and the context of a later test would
1117    /// resolve into the void.
1118    struct EnvGuard {
1119        previous: [Option<OsString>; 3],
1120        _lock: std::sync::MutexGuard<'static, ()>,
1121    }
1122
1123    impl EnvGuard {
1124        /// Write the three directory vars while holding the environment lock.
1125        fn set(lock: std::sync::MutexGuard<'static, ()>, tmp: &std::path::Path) -> EnvGuard {
1126            let previous = DIR_VARS.map(std::env::var_os);
1127            let dirs = ["cache", "data", "config"].map(|cat| tmp.join(cat));
1128            // SAFETY (via `test_support::set`): `lock` serialises every read and write of
1129            // the process environment in this test binary — the `host`, `handlers` and
1130            // `events` modules' tests share the same lock — and it is held until `drop`
1131            // has restored the old values.
1132            for (name, dir) in DIR_VARS.iter().zip(dirs) {
1133                test_support::set(name, &dir);
1134            }
1135            EnvGuard {
1136                previous,
1137                _lock: lock,
1138            }
1139        }
1140    }
1141
1142    impl Drop for EnvGuard {
1143        fn drop(&mut self) {
1144            // SAFETY: `self._lock` still serialises the environment; it is dropped only
1145            // after this method returns.
1146            for (name, previous) in DIR_VARS.iter().zip(self.previous.iter_mut()) {
1147                match previous.take() {
1148                    Some(value) => unsafe { std::env::set_var(name, value) },
1149                    None => test_support::remove(name),
1150                }
1151            }
1152        }
1153    }
1154
1155    /// Everything one test needs, held for the test's whole body.
1156    ///
1157    /// `_tmp` is declared before `_env` so the scratch tree is deleted while the
1158    /// environment lock is still held: a sibling test that wakes on the lock must never
1159    /// observe the tree mid-deletion, nor env vars pointing at a deleted directory.
1160    struct Fixture {
1161        _tmp: tempfile::TempDir,
1162        _env: EnvGuard,
1163        endpoint: Endpoint,
1164    }
1165
1166    /// A listening endpoint in a scratch directory, with the context's directories
1167    /// pointed at the same scratch tree.
1168    ///
1169    /// The caller must keep the fixture (and with it the environment lock) alive for the
1170    /// whole test: the static [`CTX`] is first-writer-wins, so while one test runs, every
1171    /// other test that would re-point the context's directories must wait.
1172    fn prepared() -> Fixture {
1173        let lock = test_support::lock();
1174        let tmp = tempfile::tempdir().unwrap();
1175        let env = EnvGuard::set(lock, tmp.path());
1176        CTX.init(AppKind::Server);
1177        let endpoint = Endpoint::in_dir("sapphire-appservertest", tmp.path().to_path_buf());
1178        Fixture {
1179            _tmp: tmp,
1180            _env: env,
1181            endpoint,
1182        }
1183    }
1184
1185    /// Wait until something is listening on `endpoint`.
1186    ///
1187    /// `tokio::spawn(server.run())` only schedules the server; without this wait a fast
1188    /// `connect_or_absent` probe can run before `run` has bound the socket, and with
1189    /// nothing listening that single unlucky probe is the whole test failing.
1190    async fn wait_until_listening(endpoint: &Endpoint) {
1191        let deadline = tokio::time::Instant::now() + Duration::from_secs(5);
1192        while !sapphire_ipc::probe(endpoint).await.unwrap() {
1193            assert!(
1194                tokio::time::Instant::now() < deadline,
1195                "the server never started listening"
1196            );
1197            tokio::time::sleep(Duration::from_millis(10)).await;
1198        }
1199    }
1200
1201    /// A running server writes its log file: the framework's `logging` module
1202    /// routes the app's log to `<data dir>/logs/app.log`, and `run()` holds the
1203    /// guard for as long as it serves. The event is emitted by this test — the
1204    /// subscriber and the file layer are the process's, installed by `CTX.init`
1205    /// and `run` — so what lands in the file is exactly what a journald-less
1206    /// host would otherwise never see.
1207    #[test]
1208    fn the_runtime_sync_via_bridge_mounts_is_the_applications_to_read() {
1209        // #250: an application reads sync state (status rows, placement) from the
1210        // runtime `sync_via_bridge` built, rather than building its own to keep one.
1211        assert!(AppServer::new(&CTX, "0.0.0").sync_runtime().is_none());
1212        let server = AppServer::new(&CTX, "0.0.0").sync_via_bridge().unwrap();
1213        let runtime = server.sync_runtime().expect("a runtime");
1214        assert!(!runtime.is_connected(), "nothing connects before `run`");
1215    }
1216
1217    #[tokio::test(flavor = "multi_thread")]
1218    async fn a_running_server_writes_its_log_file() {
1219        let f = prepared();
1220        let endpoint = f.endpoint.clone();
1221        let server = AppServer::new(&CTX, "0.0.0").endpoint(endpoint.clone());
1222        let handle = tokio::spawn(async move { server.run().await });
1223        wait_until_listening(&endpoint).await;
1224
1225        tracing::info!("the server is serving, and this line belongs in its log");
1226
1227        let (client, _) = sapphire_ipc::connect_or_absent(&endpoint, CTX.app_name, client_info())
1228            .await
1229            .unwrap()
1230            .expect("the server is listening");
1231        let _: serde_json::Value = client
1232            .call(sapphire_ipc::SHUTDOWN_METHOD, serde_json::json!({}))
1233            .await
1234            .unwrap();
1235        // The guard flushes as `run` unwinds; awaiting it is what makes the
1236        // file complete before it is read.
1237        handle.await.unwrap().unwrap();
1238
1239        let text = std::fs::read_to_string(CTX.log_dir().join("app.log")).unwrap();
1240        assert!(
1241            text.contains("the server is serving, and this line belongs in its log"),
1242            "{text}"
1243        );
1244    }
1245
1246    #[tokio::test(flavor = "multi_thread")]
1247    async fn a_server_reports_itself_as_service_managed() {
1248        let f = prepared();
1249        let endpoint = f.endpoint.clone();
1250        let server = AppServer::new(&CTX, "0.0.0").endpoint(endpoint.clone());
1251        let handle = tokio::spawn(async move { server.run().await });
1252        wait_until_listening(&endpoint).await;
1253
1254        let (client, info) =
1255            sapphire_ipc::connect_or_absent(&endpoint, CTX.app_name, client_info())
1256                .await
1257                .unwrap()
1258                .expect("the server is listening");
1259        assert_eq!(info.managed_by, ManagedBy::Service);
1260
1261        let _: serde_json::Value = client
1262            .call(sapphire_ipc::SHUTDOWN_METHOD, serde_json::json!({}))
1263            .await
1264            .unwrap();
1265        handle.await.unwrap().unwrap();
1266    }
1267
1268    #[tokio::test(flavor = "multi_thread")]
1269    async fn a_server_reports_its_app_api_and_the_handshake_gates_on_it() {
1270        let f = prepared();
1271        let endpoint = f.endpoint.clone();
1272        let server = AppServer::new(&CTX, "0.0.0")
1273            .endpoint(endpoint.clone())
1274            .app_api(7);
1275        let handle = tokio::spawn(async move { server.run().await });
1276        wait_until_listening(&endpoint).await;
1277
1278        let wants = |app_api| ClientInfo {
1279            app_api,
1280            ..client_info()
1281        };
1282        let err = sapphire_ipc::connect_or_absent(&endpoint, CTX.app_name, wants(Some(8)))
1283            .await
1284            .unwrap_err();
1285        assert!(
1286            matches!(
1287                err,
1288                sapphire_ipc::Error::AppApiVersionMismatch {
1289                    running: Some(7),
1290                    ours: 8,
1291                    ..
1292                }
1293            ),
1294            "{err:?}"
1295        );
1296
1297        let (client, info) =
1298            sapphire_ipc::connect_or_absent(&endpoint, CTX.app_name, wants(Some(7)))
1299                .await
1300                .unwrap()
1301                .expect("the server is listening");
1302        assert_eq!(info.app_api, Some(7));
1303
1304        let _: serde_json::Value = client
1305            .call(sapphire_ipc::SHUTDOWN_METHOD, serde_json::json!({}))
1306            .await
1307            .unwrap();
1308        handle.await.unwrap().unwrap();
1309    }
1310
1311    #[tokio::test(flavor = "multi_thread")]
1312    async fn a_running_server_answers_server_info() {
1313        let f = prepared();
1314        let endpoint = f.endpoint.clone();
1315
1316        let server = AppServer::new(&CTX, "1.2.3").endpoint(endpoint.clone());
1317        let handle = tokio::spawn(async move { server.run().await });
1318        wait_until_listening(&endpoint).await;
1319
1320        let (client, info) = sapphire_ipc::connect_or_absent(
1321            &endpoint,
1322            CTX.app_name,
1323            ClientInfo {
1324                version: "1.2.3".into(),
1325                ..client_info()
1326            },
1327        )
1328        .await
1329        .unwrap()
1330        .expect("the server is listening");
1331        assert_eq!(info.version, "1.2.3");
1332
1333        // `server.info` answers the whole typed report, not the bare handshake record:
1334        // the CLI reads one shape, and so would a GUI.
1335        let report: StatusReport = client
1336            .call(
1337                sapphire_backend::protocol::SERVER_INFO,
1338                serde_json::json!({}),
1339            )
1340            .await
1341            .unwrap();
1342        assert!(report.running);
1343        assert_eq!(report.version.as_deref(), Some("1.2.3"));
1344        assert_eq!(report.pid, Some(std::process::id()));
1345        assert_eq!(report.managed_by, Some(proto::ManagedBy::Service));
1346        assert!(report.app.is_empty(), "no status rows were configured");
1347
1348        let _: serde_json::Value = client
1349            .call(sapphire_ipc::SHUTDOWN_METHOD, serde_json::json!({}))
1350            .await
1351            .unwrap();
1352        handle.await.unwrap().unwrap();
1353    }
1354
1355    #[tokio::test(flavor = "multi_thread")]
1356    async fn shutdown_stops_the_server() {
1357        let f = prepared();
1358        let endpoint = f.endpoint.clone();
1359
1360        let server = AppServer::new(&CTX, "0.0.0").endpoint(endpoint.clone());
1361        let handle = tokio::spawn(async move { server.run().await });
1362        wait_until_listening(&endpoint).await;
1363
1364        let (client, _) = sapphire_ipc::connect_or_absent(&endpoint, CTX.app_name, client_info())
1365            .await
1366            .unwrap()
1367            .expect("the server is listening");
1368        let _: serde_json::Value = client
1369            .call(sapphire_ipc::SHUTDOWN_METHOD, serde_json::json!({}))
1370            .await
1371            .unwrap();
1372
1373        tokio::time::timeout(Duration::from_secs(5), handle)
1374            .await
1375            .expect("the server must stop")
1376            .unwrap()
1377            .unwrap();
1378        assert!(!sapphire_ipc::probe(&endpoint).await.unwrap());
1379    }
1380
1381    #[tokio::test(flavor = "multi_thread")]
1382    async fn an_application_can_add_its_own_methods() {
1383        let f = prepared();
1384        let endpoint = f.endpoint.clone();
1385
1386        let server = AppServer::new(&CTX, "0.0.0")
1387            .endpoint(endpoint.clone())
1388            .extend(|r| {
1389                r.method("sapphire-appservertest.greet", |_| async move {
1390                    Ok(serde_json::json!("hello"))
1391                })
1392            });
1393        let handle = tokio::spawn(async move { server.run().await });
1394        wait_until_listening(&endpoint).await;
1395
1396        let (client, _) = sapphire_ipc::connect_or_absent(&endpoint, CTX.app_name, client_info())
1397            .await
1398            .unwrap()
1399            .expect("the server is listening");
1400        let greeting: String = client
1401            .call("sapphire-appservertest.greet", serde_json::json!({}))
1402            .await
1403            .unwrap();
1404        assert_eq!(greeting, "hello");
1405
1406        let _: serde_json::Value = client
1407            .call(sapphire_ipc::SHUTDOWN_METHOD, serde_json::json!({}))
1408            .await
1409            .unwrap();
1410        handle.await.unwrap().unwrap();
1411    }
1412
1413    #[tokio::test(flavor = "multi_thread")]
1414    async fn workspace_init_creates_the_marker() {
1415        let f = prepared();
1416        let endpoint = f.endpoint.clone();
1417        let server = AppServer::new(&CTX, "0.0.0").endpoint(endpoint.clone());
1418        let handle = tokio::spawn(async move { server.run().await });
1419        wait_until_listening(&endpoint).await;
1420        let (client, _) = sapphire_ipc::connect_or_absent(&endpoint, CTX.app_name, client_info())
1421            .await
1422            .unwrap()
1423            .unwrap();
1424
1425        let dir = tempfile::tempdir().unwrap();
1426        let result: proto::WorkspaceInitResult = client
1427            .call(
1428                proto::WORKSPACE_INIT,
1429                proto::WorkspaceInitParams {
1430                    dir: dir.path().to_owned(),
1431                },
1432            )
1433            .await
1434            .unwrap();
1435        assert!(result.created);
1436        assert!(dir.path().join(format!(".{}", CTX.app_name)).is_dir());
1437
1438        // Idempotent: the second init is a success that did not create.
1439        let again: proto::WorkspaceInitResult = client
1440            .call(
1441                proto::WORKSPACE_INIT,
1442                proto::WorkspaceInitParams {
1443                    dir: dir.path().to_owned(),
1444                },
1445            )
1446            .await
1447            .unwrap();
1448        assert!(!again.created);
1449
1450        let _: serde_json::Value = client
1451            .call(sapphire_ipc::SHUTDOWN_METHOD, serde_json::json!({}))
1452            .await
1453            .unwrap();
1454        handle.await.unwrap().unwrap();
1455    }
1456
1457    #[tokio::test(flavor = "multi_thread")]
1458    async fn server_info_carries_the_app_rows() {
1459        let f = prepared();
1460        let endpoint = f.endpoint.clone();
1461        let server = AppServer::new(&CTX, "0.0.0")
1462            .endpoint(endpoint.clone())
1463            .status_rows(std::sync::Arc::new(|| {
1464                vec![StatusRow {
1465                    name: "sync".into(),
1466                    value: "enabled".into(),
1467                }]
1468            }));
1469        let handle = tokio::spawn(async move { server.run().await });
1470        wait_until_listening(&endpoint).await;
1471        let (client, _) = sapphire_ipc::connect_or_absent(&endpoint, CTX.app_name, client_info())
1472            .await
1473            .unwrap()
1474            .unwrap();
1475        let report: StatusReport = client
1476            .call(
1477                sapphire_backend::protocol::SERVER_INFO,
1478                serde_json::json!({}),
1479            )
1480            .await
1481            .unwrap();
1482        assert!(report.running);
1483        assert_eq!(report.app.len(), 1);
1484        assert_eq!(report.app[0].name, "sync");
1485
1486        let _: serde_json::Value = client
1487            .call(sapphire_ipc::SHUTDOWN_METHOD, serde_json::json!({}))
1488            .await
1489            .unwrap();
1490        handle.await.unwrap().unwrap();
1491    }
1492}