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