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, update_bridge,
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), and only a file signed with sapphire-turtle's key
513    /// ([`UPDATE_PUBKEY`](sapphire_framework_update::UPDATE_PUBKEY)), unless `source` names
514    /// another ([`ReleaseSource::pubkey`]) (#402). The release must carry `<file>.sig`:
515    /// sapphire-turtle/.github's `release-binary.yml` with `sign: true`.
516    pub fn releases(mut self, source: ReleaseSource) -> AppServer {
517        self.releases = Some(match source.update_pubkey() {
518            Some(_) => source,
519            None => source.pubkey(sapphire_framework_update::UPDATE_PUBKEY),
520        });
521        self
522    }
523
524    /// Where this application's releases are published, if it said.
525    pub fn release_source(&self) -> Option<&ReleaseSource> {
526        self.releases.as_ref()
527    }
528
529    /// What this application's service is: the arguments a service manager starts it with.
530    ///
531    /// `["serve"]`: a service manager starts the executable directly with
532    /// [`FrameworkCommand::Serve`](crate::FrameworkCommand::Serve) — the bare invocation
533    /// prints the help in the CLI version and opens the window in the desktop one. A CLI
534    /// that wants its service installed hands this to
535    /// [`ServiceCommand`](corundum_framework_service::ServiceCommand), which registers the
536    /// running executable (the AppImage, inside one).
537    pub fn service_spec(&self) -> ServiceSpec {
538        app_service_spec(self.ctx.app_name, self.version)
539    }
540
541    /// Add the application's own methods.
542    pub fn extend(mut self, f: impl FnOnce(Router) -> Router + Send + 'static) -> AppServer {
543        self.extend = Some(Box::new(f));
544        self
545    }
546
547    /// The workspace this server has open. An application's own handlers use it to reach
548    /// the workspace the same way the framework's do: [`WorkspaceHost::backend`].
549    pub fn host(&self) -> &Arc<WorkspaceHost> {
550        &self.host
551    }
552
553    /// The sync runtime, once [`sync`](Self::sync) or [`sync_via_bridge`](Self::sync_via_bridge)
554    /// has set one (#250): for an application's own code that reads sync state — status
555    /// rows, or which device is the workspace's primary.
556    pub fn sync_runtime(&self) -> Option<&Arc<SyncRuntime>> {
557        self.sync.as_ref()
558    }
559
560    /// Listen until told to stop, or until a signal arrives.
561    ///
562    /// A server run this way answers `server.restart` with an error: nothing would bring it
563    /// back. [`serve_restarting`] runs one that can.
564    pub async fn run(self) -> Result<()> {
565        // Before anything is bound: a mistake in the application, not in the files.
566        #[cfg(feature = "http")]
567        undeclared_endpoints(self.settings.as_ref(), &self.http_endpoints)?;
568        let endpoint = self.endpoint_or_default()?;
569        // The app's log file, held for as long as this server serves: the guard's drop
570        // flushes the writer thread, so the last lines of a clean shutdown land in the file.
571        // The subscriber itself was installed by `ctx.init`; this is what routes the file
572        // layer at `<data dir>/logs/`.
573        let _log = sapphire_workspace::logging::install(self.ctx)?;
574        // Registered before the bind: see `Sigterm::register`.
575        let mut sigterm = if self.signals {
576            Sigterm::register()?
577        } else {
578            None
579        };
580        #[cfg(unix)]
581        let mut listener = sapphire_ipc::bind(&endpoint).await?;
582        #[cfg(windows)]
583        let mut listener = sapphire_ipc::bind(&endpoint)?;
584        let exit = self.serve_on(&mut listener, None, &mut sigterm).await;
585        drop(listener); // removes the socket file on Unix
586        debug_assert!(
587            !matches!(exit, Ok(Exit::Restart)),
588            "nothing can ask for one"
589        );
590        exit.map(|_| ())
591    }
592
593    /// Serve on `listener` until told to stop, a signal arrives, or `restart` fires.
594    ///
595    /// `restart` is what `server.restart` fires; `None` answers it with an error.
596    /// `sigterm` is the caller's, so it outlives one server: see [`serve_restarting`].
597    /// The listener, the log and the process stay with the caller; everything else this
598    /// server started is stopped before it returns — on [`Exit::Restart`] down to the last
599    /// task that held the sync runtime, so the next server's runtime can open the replica
600    /// store.
601    pub(crate) async fn serve_on(
602        self,
603        listener: &mut sapphire_ipc::Listener,
604        restart: Option<Arc<Notify>>,
605        sigterm: &mut Option<Sigterm>,
606    ) -> Result<Exit> {
607        let AppServer {
608            ctx,
609            version,
610            endpoint: _,
611            selection_file,
612            host,
613            sync,
614            bridge_connector,
615            extend,
616            status_rows,
617            app_api,
618            config,
619            settings,
620            releases,
621            signals,
622            metrics_collectors,
623            #[cfg(feature = "http")]
624            http_listen,
625            #[cfg(feature = "http")]
626            http_routes,
627            #[cfg(feature = "http")]
628            http_endpoints,
629            #[cfg(feature = "http")]
630            http_auth,
631            key_profiles,
632            #[cfg(feature = "mcp")]
633            mcp,
634        } = self;
635        // Only the HTTP routes check a key.
636        #[cfg(not(feature = "http"))]
637        let _ = key_profiles;
638        // Without the exporter nothing scrapes, so there is nothing to call them from.
639        #[cfg(not(feature = "metrics"))]
640        let _ = metrics_collectors;
641
642        // A server is always-on from here on: only `serve` and the service manager start
643        // one, and the service manager starts it for keeps. There is no spawned mode left
644        // to report.
645        let info = ServerInfo {
646            version: version.to_owned(),
647            api: proto::API_VERSION,
648            app_api,
649            pid: std::process::id(),
650            managed_by: ManagedBy::Service,
651        };
652
653        let file = selection_at(ctx, selection_file);
654        // A context whose config directory was never resolved has no file to read, and
655        // gets the defaults — as it gets no log file — and no settings of its own to serve.
656        let settings = match settings {
657            Some(settings) => Some(settings),
658            None if ctx.try_config_dir().is_some() => {
659                Some(Settings::load_with(ctx, Arc::new(()), file.clone())?)
660            }
661            None => None,
662        };
663        let config = match (config, &settings) {
664            (Some(config), _) => config,
665            (None, Some(settings)) => ServerConfig::from_settings(settings)?,
666            (None, None) => ServerConfig::default(),
667        };
668        #[cfg(feature = "http")]
669        undeclared_endpoints(settings.as_ref(), &http_endpoints)?;
670        #[cfg(feature = "http")]
671        let http_routes = http_endpoints
672            .into_iter()
673            .filter(|(name, _)| config.http.endpoints.contains(name))
674            .fold(http_routes, |routes, (name, endpoint)| {
675                let endpoint = axum::Router::new().nest(&format!("/{name}"), endpoint);
676                Some(match routes {
677                    Some(routes) => routes.merge(endpoint),
678                    None => endpoint,
679                })
680            });
681        // A read-only key may only `GET` the application's routes; `/mcp`, all `POST`,
682        // checks each tool instead.
683        #[cfg(feature = "http")]
684        let http_routes = http_routes.map(sapphire_framework_keys::read_only_by_method);
685        #[cfg(not(feature = "mcp"))]
686        if config.http.mcp.enabled {
687            tracing::warn!(
688                "config.toml turns MCP over HTTP on, but this build of {} has no MCP",
689                ctx.app_name
690            );
691        }
692        #[cfg(not(feature = "metrics"))]
693        if config.http.metrics.enabled {
694            tracing::warn!(
695                "config.toml turns metrics on, but this build of {} has no metrics",
696                ctx.app_name
697            );
698        }
699
700        let (stop_tx, mut stop_rx) = tokio::sync::watch::channel(false);
701
702        // What `server.update` answers; the looking task fills it in once the server serves.
703        let update_status = update::SharedStatus::default();
704        let update_check = releases.filter(|_| config.update.check);
705
706        // The first attempt to reach the bridge, before the selected workspace comes back
707        // and asks it for sync.
708        if let Some(runtime) = &sync {
709            runtime.connect().await?;
710        }
711
712        // Workspace keys follow the selection and the marker's `config.toml` as sync or an
713        // edit changes it.
714        let mut current = Current::new(ctx, Arc::clone(&host), sync.clone(), file);
715        if let Some(settings) = &settings {
716            current = current.with_settings(settings.clone());
717        }
718        if let Some(runtime) = &sync {
719            runtime.set_settings(settings.clone());
720        }
721        let current = Arc::new(current);
722        // Back to the workspace this host had, before the first client can ask for it.
723        let restoring = current.restore().await;
724
725        let mut router = subscribe_method(
726            Arc::clone(&host),
727            current::current_methods(Arc::clone(&current), workspace_router(Arc::clone(&current))),
728        );
729        if sync.is_some() {
730            // `sync_router` is applied *under* the application's own methods so a later
731            // `extend` can still replace one, and after `subscribe_method` so the
732            // `workspace.*` namespace is complete.
733            router = sync_router(Arc::clone(&current), router);
734        }
735        // The bridge's client-facing methods, over the sync runtime's connection when there
736        // is one. Like `sync_router`, under the application's own methods.
737        let link = match &sync {
738            Some(runtime) => relay::BridgeLink::Sync(Arc::clone(runtime)),
739            None => relay::BridgeLink::own(
740                bridge_connector
741                    .unwrap_or_else(|| BridgeConnector::standard(ctx.app_name, version)),
742            ),
743        };
744        let relay = Arc::new(relay::Relay::new(link));
745        router = Arc::clone(&relay).routes(router);
746        // `config.*`: this server's settings merged with the bridge's. Without settings of
747        // its own, the bridge's alone, relayed.
748        router = match settings {
749            Some(settings) => config_methods::routes(router, settings, relay),
750            None => relay.routes_for(router, sapphire_bridge_api::ANSWERED_BY_APP_SERVER),
751        };
752        // `server.info` answers the typed [`StatusReport`] — the same shape the CLI's
753        // `status` renders — so the CLI and a future GUI read one record. The rows come
754        // from the application's builder, called once per report.
755        router = router
756            .method(proto::SERVER_INFO, {
757                let info = info.clone();
758                let status_rows = status_rows.clone();
759                move |_| {
760                    let info = info.clone();
761                    let status_rows = status_rows.clone();
762                    async move {
763                        let app = status_rows.as_ref().map(|rows| rows()).unwrap_or_default();
764                        let report = StatusReport {
765                            running: true,
766                            version: Some(info.version),
767                            pid: Some(info.pid),
768                            managed_by: Some(match info.managed_by {
769                                ManagedBy::Service => proto::ManagedBy::Service,
770                                ManagedBy::Spawned => proto::ManagedBy::Spawned,
771                            }),
772                            app,
773                        };
774                        serde_json::to_value(report)
775                            .map_err(|e| sapphire_ipc::RpcError::internal(e.to_string()))
776                    }
777                }
778            })
779            .method(proto::SERVER_UPDATE, {
780                let update_status = Arc::clone(&update_status);
781                move |_| {
782                    let status = update_status.lock().expect("update status lock").clone();
783                    async move {
784                        serde_json::to_value(status)
785                            .map_err(|e| sapphire_ipc::RpcError::internal(e.to_string()))
786                    }
787                }
788            })
789            .method(proto::SERVER_RESTART, {
790                let restart = restart.clone();
791                move |_| {
792                    let answer = restart::request(restart.clone());
793                    async move {
794                        answer?;
795                        serde_json::to_value(proto::Ack {})
796                            .map_err(|e| sapphire_ipc::RpcError::internal(e.to_string()))
797                    }
798                }
799            })
800            .method(sapphire_ipc::SHUTDOWN_METHOD, {
801                let stop_tx = stop_tx.clone();
802                move |_| {
803                    let stop_tx = stop_tx.clone();
804                    async move {
805                        let _ = stop_tx.send(true);
806                        serde_json::to_value(proto::Ack {})
807                            .map_err(|e| sapphire_ipc::RpcError::internal(e.to_string()))
808                    }
809                }
810            });
811        if let Some(extend) = extend {
812            router = extend(router);
813        }
814        let router = Arc::new(router);
815
816        // The caller's SIGTERM stream, unless this server leaves signals to the process.
817        let mut no_sigterm = None;
818        let sigterm = if signals { sigterm } else { &mut no_sigterm };
819        // What `server.restart` fires; never, where there is no restarting.
820        let restarted = async {
821            match &restart {
822                Some(restart) => restart.notified().await,
823                None => std::future::pending().await,
824            }
825        };
826        tokio::pin!(restarted);
827        let mut exit = Exit::Stopped;
828
829        let mut connections = tokio::task::JoinSet::new();
830
831        // The HTTP listener, when anything is served over it. Started with the IPC socket
832        // bound, for the same reason as the sync tasks below. `/mcp`'s tools reach this
833        // server the way the `mcp` subcommand's do — over IPC — on an in-process connection
834        // served like any other. `/metrics` is the one public route, served without a token.
835        #[cfg(feature = "http")]
836        let http_stop = tokio_util::sync::CancellationToken::new();
837        #[cfg(feature = "http")]
838        let http_task = {
839            #[cfg(feature = "mcp")]
840            let routes = if config.http.mcp.enabled {
841                let (ours, theirs) = sapphire_ipc::Connection::pair();
842                {
843                    let router = Arc::clone(&router);
844                    let info = info.clone();
845                    let app = ctx.app_name;
846                    connections.spawn(async move {
847                        let _ = serve(theirs, router, app, info).await;
848                    });
849                }
850                let client_info = sapphire_ipc::ClientInfo {
851                    kind: sapphire_framework_mcp::CLIENT_KIND.to_owned(),
852                    version: version.to_owned(),
853                    api: proto::API_VERSION,
854                    app_api,
855                    pid: std::process::id(),
856                };
857                let (client, _) =
858                    sapphire_ipc::Client::handshake(ours, ctx.app_name, client_info).await?;
859                let tools = sapphire_framework_mcp::ToolContext::connected(
860                    ctx.app_name,
861                    version,
862                    Arc::new(client),
863                );
864                let mcp_routes =
865                    mcp.http_router(tools, &config.http.allowed_hosts, http_stop.child_token());
866                Some(match http_routes {
867                    Some(routes) => routes.merge(mcp_routes),
868                    None => mcp_routes,
869                })
870            } else {
871                http_routes
872            };
873            #[cfg(not(feature = "mcp"))]
874            let routes = http_routes;
875            #[cfg(feature = "metrics")]
876            let public = if config.http.metrics.enabled
877                && let Some(handle) = exporter::install()
878            {
879                metrics::gauge!(
880                    instrument::BUILD_INFO,
881                    "app" => ctx.app_name,
882                    "version" => version,
883                )
884                .set(1.0);
885                let scrape = Arc::new(exporter::Scrape {
886                    process: metrics_process::Collector::default(),
887                    current: Arc::clone(&current),
888                    update: Arc::clone(&update_status),
889                    collectors: metrics_collectors,
890                });
891                Some(exporter::routes(handle, scrape))
892            } else {
893                None
894            };
895            #[cfg(not(feature = "metrics"))]
896            let public: Option<axum::Router> = None;
897            match (
898                routes.is_some() || public.is_some(),
899                config.http.listen.or(http_listen),
900            ) {
901                (false, _) => None,
902                (true, None) => {
903                    tracing::error!(
904                        "nothing to bind HTTP to: set `[http] listen` in {SERVER_CONFIG_FILE}"
905                    );
906                    None
907                }
908                (true, Some(addr)) => {
909                    let auth = http_auth.unwrap_or_else(|| {
910                        sapphire_framework_keys::AuthConfig::new(Arc::new(
911                            api_keys::WorkspaceKeyVerifier::for_app(ctx)
912                                .profiles(key_profiles.clone()),
913                        ))
914                    });
915                    http::start(addr, routes, public, auth, http_stop.clone()).await
916                }
917            }
918        };
919
920        // The watcher, the bridge announcement loop, the dialer and the bridge connection, if
921        // sync is on. Started only once the socket is bound, so an early `?` above cannot
922        // leave tasks running for a server that never served. All of them are allowed to
923        // fail: only sync stops when they do, and the app server keeps serving files
924        // (spec §10). They are aborted with the server.
925        let sync_tasks = match &sync {
926            Some(runtime) => {
927                let driver = Arc::clone(runtime);
928                let announcements = tokio::spawn(async move {
929                    if let Err(err) = driver.run().await {
930                        tracing::warn!("the bridge announcement loop ended: {err}");
931                    }
932                });
933                let changing = Arc::clone(runtime);
934                let watching = tokio::spawn(async move {
935                    if let Err(err) = changing.watch_changes().await {
936                        tracing::warn!("the file watcher ended: {err}");
937                    }
938                });
939                // The dialer is what keeps a session open after the initial exchange, so a
940                // commit reaches a peer without waiting for the next one (spec §4.2).
941                let dialling = Arc::clone(runtime);
942                let dialling = tokio::spawn(async move {
943                    if let Err(err) = dialling.dial_loop().await {
944                        tracing::warn!("the live dial loop ended: {err}");
945                    }
946                });
947                // Reaching the bridge again whenever it is lost (#244).
948                let connected = tokio::spawn(Arc::clone(runtime).keep_connected());
949                Some([announcements, watching, dialling, connected])
950            }
951            None => None,
952        };
953
954        // Looking for newer releases, once the socket is bound for the same reason. Ends
955        // with the server, when this is dropped.
956        let _update_checking = update_check.and_then(|check| {
957            update::start(check, ctx.app_name, version, Arc::clone(&update_status))
958        });
959
960        loop {
961            tokio::select! {
962                changed = stop_rx.changed() => {
963                    if changed.is_err() || *stop_rx.borrow() {
964                        break;
965                    }
966                }
967                _ = interrupted(signals) => {
968                    tracing::info!("interrupted; shutting down");
969                    break;
970                }
971                _ = terminated(sigterm) => {
972                    tracing::info!("terminated; shutting down");
973                    break;
974                }
975                () = &mut restarted => {
976                    tracing::info!("stopping to restart");
977                    exit = Exit::Restart;
978                    break;
979                }
980                accepted = listener.accept() => {
981                    let conn = accepted?;
982                    // Moved into the task, so the connection stops counting as open when it
983                    // ends, or when the reaping below aborts it.
984                    let counted = instrument::IpcConnection::open();
985                    let router = Arc::clone(&router);
986                    let app = ctx.app_name;
987                    let info = info.clone();
988                    connections.spawn(async move {
989                        let _counted = counted;
990                        let _ = serve(conn, router, app, info).await;
991                    });
992                }
993            }
994        }
995
996        // Awaited, not only aborted: the restoring task holds `Current`, and with it the
997        // sync runtime, until it is dropped — which a restart must see done before the
998        // next server opens the replica store.
999        if let Some(restoring) = restoring {
1000            restoring.abort();
1001            let _ = restoring.await;
1002        }
1003        // HTTP first: its sessions hold a connection to this server, which the reaping
1004        // below waits for. Awaited after the abort too, for the same reason as above.
1005        #[cfg(feature = "http")]
1006        {
1007            http_stop.cancel();
1008            if let Some((_, mut task)) = http_task
1009                && tokio::time::timeout(SERVE_GRACE, &mut task).await.is_err()
1010            {
1011                tracing::debug!("the HTTP listener did not stop in time");
1012                task.abort();
1013                let _ = task.await;
1014            }
1015        }
1016        if let Some(tasks) = sync_tasks {
1017            // Each loop pins the sync runtime, and with it the replica stores. An aborted task
1018            // is only dropped once its current poll returns — which, mid-scan, can take a
1019            // while — so wait for that rather than return with a loop still holding a store
1020            // the next server in this process would fail to open (#235).
1021            for task in tasks {
1022                task.abort();
1023                let _ = task.await;
1024            }
1025        }
1026        if let Some(runtime) = &sync {
1027            // The first dials after an enable pin the runtime the same way, and so do the
1028            // inbound sessions, the live-session readers and the embedding passes.
1029            runtime.stop_dials().await;
1030            runtime.stop_background().await;
1031            // Close every live sync session. A session's reader task holds the replica, and
1032            // the session itself sits in the runtime's table until it is cleared, so leaving
1033            // one open pins the runtime — and the redb replica stores in it — after the
1034            // server is gone (spec §2.2: cancellation is disconnection).
1035            runtime.drop_connections().await;
1036        }
1037        host.close();
1038        // The listener is the caller's: it stays bound, and a client that connects now waits
1039        // in its backlog for the next server of a restart.
1040
1041        // Reap the per-connection serve tasks. Each one pins the router, the router pins
1042        // the sync runtime, and the runtime's replica stores are redb databases that stay
1043        // locked until the last pin is dropped — a server that left them running would
1044        // lock its own successor out of its state (spec §2.2: cancellation is
1045        // disconnection). Connections get a grace period to wind down on their own — the
1046        // shutdown acknowledgement among them — then the rest are cancelled: a client
1047        // that keeps its connection open past shutdown is holding a server that is gone.
1048        let _ = tokio::time::timeout(SERVE_GRACE, async {
1049            while connections.join_next().await.is_some() {}
1050        })
1051        .await;
1052        connections.abort_all();
1053        while connections.join_next().await.is_some() {}
1054        // Everything else of this server — the router, the relay, `Current`, the host and
1055        // the sync runtime — goes as this returns, before a restart builds the next one.
1056        Ok(exit)
1057    }
1058}
1059
1060/// An error for the first of `endpoints` the settings do not declare: it has no switch to
1061/// turn it on.
1062#[cfg(feature = "http")]
1063fn undeclared_endpoints(
1064    settings: Option<&Settings>,
1065    endpoints: &[(String, axum::Router)],
1066) -> Result<()> {
1067    let Some(settings) = settings else {
1068        return Ok(());
1069    };
1070    match endpoints.iter().find(|(name, _)| {
1071        settings
1072            .registry()
1073            .def(&settings::endpoint_key(name))
1074            .is_err()
1075    }) {
1076        Some((name, _)) => Err(Error::Config(format!(
1077            "the HTTP endpoint `{name}` is not one the application's settings declare"
1078        ))),
1079        None => Ok(()),
1080    }
1081}
1082
1083/// The app server's service for `app_name` at `version`: what [`AppServer::service_spec`]
1084/// returns, for a desktop package to name its service without an `AppServer` (#357).
1085///
1086/// `["serve"]`, under the label sapphire first registered on macOS; corundum retires its own
1087/// earlier one (net.sapphire-turtle.<app>) by itself (#385).
1088pub fn app_service_spec(app_name: &'static str, version: &str) -> ServiceSpec {
1089    ServiceSpec {
1090        app_name,
1091        description: format!("{app_name} server {version}"),
1092        args: vec!["serve".to_owned()],
1093        legacy_labels: vec![format!("net.fireturtle.sapphire.{app_name}")],
1094        post_install: None,
1095    }
1096}
1097
1098#[cfg(test)]
1099mod tests {
1100    use super::*;
1101    use sapphire_ipc::{ClientInfo, Endpoint, ManagedBy};
1102    use sapphire_workspace::{AppContext, AppKind};
1103    use std::ffi::OsString;
1104
1105    use crate::test_support;
1106
1107    static CTX: AppContext = AppContext::new("sapphire-appservertest");
1108
1109    /// The env vars `init_ctx` writes, in the order the guard restores them.
1110    const DIR_VARS: [&str; 3] = [
1111        "SAPPHIRE_APPSERVERTEST_CACHE_DIR",
1112        "SAPPHIRE_APPSERVERTEST_DATA_DIR",
1113        "SAPPHIRE_APPSERVERTEST_CONFIG_DIR",
1114    ];
1115
1116    fn client_info() -> ClientInfo {
1117        ClientInfo {
1118            kind: "test".into(),
1119            version: "0.0.0".into(),
1120            api: sapphire_backend::protocol::API_VERSION,
1121            app_api: None,
1122            pid: std::process::id(),
1123        }
1124    }
1125
1126    /// Point the context's directories at `tmp` and restore the previous values (present
1127    /// or absent) when dropped — including while unwinding from a panic. Without the
1128    /// unconditional restore, a panicking assertion would leave the variables pointing at
1129    /// a temp directory the test then deletes, and the context of a later test would
1130    /// resolve into the void.
1131    struct EnvGuard {
1132        previous: [Option<OsString>; 3],
1133        _lock: std::sync::MutexGuard<'static, ()>,
1134    }
1135
1136    impl EnvGuard {
1137        /// Write the three directory vars while holding the environment lock.
1138        fn set(lock: std::sync::MutexGuard<'static, ()>, tmp: &std::path::Path) -> EnvGuard {
1139            let previous = DIR_VARS.map(std::env::var_os);
1140            let dirs = ["cache", "data", "config"].map(|cat| tmp.join(cat));
1141            // SAFETY (via `test_support::set`): `lock` serialises every read and write of
1142            // the process environment in this test binary — the `host`, `handlers` and
1143            // `events` modules' tests share the same lock — and it is held until `drop`
1144            // has restored the old values.
1145            for (name, dir) in DIR_VARS.iter().zip(dirs) {
1146                test_support::set(name, &dir);
1147            }
1148            EnvGuard {
1149                previous,
1150                _lock: lock,
1151            }
1152        }
1153    }
1154
1155    impl Drop for EnvGuard {
1156        fn drop(&mut self) {
1157            // SAFETY: `self._lock` still serialises the environment; it is dropped only
1158            // after this method returns.
1159            for (name, previous) in DIR_VARS.iter().zip(self.previous.iter_mut()) {
1160                match previous.take() {
1161                    Some(value) => unsafe { std::env::set_var(name, value) },
1162                    None => test_support::remove(name),
1163                }
1164            }
1165        }
1166    }
1167
1168    /// Everything one test needs, held for the test's whole body.
1169    ///
1170    /// `_tmp` is declared before `_env` so the scratch tree is deleted while the
1171    /// environment lock is still held: a sibling test that wakes on the lock must never
1172    /// observe the tree mid-deletion, nor env vars pointing at a deleted directory.
1173    struct Fixture {
1174        _tmp: tempfile::TempDir,
1175        _env: EnvGuard,
1176        endpoint: Endpoint,
1177    }
1178
1179    /// A listening endpoint in a scratch directory, with the context's directories
1180    /// pointed at the same scratch tree.
1181    ///
1182    /// The caller must keep the fixture (and with it the environment lock) alive for the
1183    /// whole test: the static [`CTX`] is first-writer-wins, so while one test runs, every
1184    /// other test that would re-point the context's directories must wait.
1185    fn prepared() -> Fixture {
1186        let lock = test_support::lock();
1187        let tmp = tempfile::tempdir().unwrap();
1188        let env = EnvGuard::set(lock, tmp.path());
1189        CTX.init(AppKind::Server);
1190        let endpoint = Endpoint::in_dir("sapphire-appservertest", tmp.path().to_path_buf());
1191        Fixture {
1192            _tmp: tmp,
1193            _env: env,
1194            endpoint,
1195        }
1196    }
1197
1198    /// Wait until something is listening on `endpoint`.
1199    ///
1200    /// `tokio::spawn(server.run())` only schedules the server; without this wait a fast
1201    /// `connect_or_absent` probe can run before `run` has bound the socket, and with
1202    /// nothing listening that single unlucky probe is the whole test failing.
1203    async fn wait_until_listening(endpoint: &Endpoint) {
1204        let deadline = tokio::time::Instant::now() + Duration::from_secs(5);
1205        while !sapphire_ipc::probe(endpoint).await.unwrap() {
1206            assert!(
1207                tokio::time::Instant::now() < deadline,
1208                "the server never started listening"
1209            );
1210            tokio::time::sleep(Duration::from_millis(10)).await;
1211        }
1212    }
1213
1214    /// A running server writes its log file: the framework's `logging` module
1215    /// routes the app's log to `<data dir>/logs/app.log`, and `run()` holds the
1216    /// guard for as long as it serves. The event is emitted by this test — the
1217    /// subscriber and the file layer are the process's, installed by `CTX.init`
1218    /// and `run` — so what lands in the file is exactly what a journald-less
1219    /// host would otherwise never see.
1220    #[test]
1221    fn the_runtime_sync_via_bridge_mounts_is_the_applications_to_read() {
1222        // #250: an application reads sync state (status rows, placement) from the
1223        // runtime `sync_via_bridge` built, rather than building its own to keep one.
1224        assert!(AppServer::new(&CTX, "0.0.0").sync_runtime().is_none());
1225        let server = AppServer::new(&CTX, "0.0.0").sync_via_bridge().unwrap();
1226        let runtime = server.sync_runtime().expect("a runtime");
1227        assert!(!runtime.is_connected(), "nothing connects before `run`");
1228    }
1229
1230    #[tokio::test(flavor = "multi_thread")]
1231    async fn a_running_server_writes_its_log_file() {
1232        let f = prepared();
1233        let endpoint = f.endpoint.clone();
1234        let server = AppServer::new(&CTX, "0.0.0").endpoint(endpoint.clone());
1235        let handle = tokio::spawn(async move { server.run().await });
1236        wait_until_listening(&endpoint).await;
1237
1238        tracing::info!("the server is serving, and this line belongs in its log");
1239
1240        let (client, _) = sapphire_ipc::connect_or_absent(&endpoint, CTX.app_name, client_info())
1241            .await
1242            .unwrap()
1243            .expect("the server is listening");
1244        let _: serde_json::Value = client
1245            .call(sapphire_ipc::SHUTDOWN_METHOD, serde_json::json!({}))
1246            .await
1247            .unwrap();
1248        // The guard flushes as `run` unwinds; awaiting it is what makes the
1249        // file complete before it is read.
1250        handle.await.unwrap().unwrap();
1251
1252        let text = std::fs::read_to_string(CTX.log_dir().join("app.log")).unwrap();
1253        assert!(
1254            text.contains("the server is serving, and this line belongs in its log"),
1255            "{text}"
1256        );
1257    }
1258
1259    #[tokio::test(flavor = "multi_thread")]
1260    async fn a_server_reports_itself_as_service_managed() {
1261        let f = prepared();
1262        let endpoint = f.endpoint.clone();
1263        let server = AppServer::new(&CTX, "0.0.0").endpoint(endpoint.clone());
1264        let handle = tokio::spawn(async move { server.run().await });
1265        wait_until_listening(&endpoint).await;
1266
1267        let (client, info) =
1268            sapphire_ipc::connect_or_absent(&endpoint, CTX.app_name, client_info())
1269                .await
1270                .unwrap()
1271                .expect("the server is listening");
1272        assert_eq!(info.managed_by, ManagedBy::Service);
1273
1274        let _: serde_json::Value = client
1275            .call(sapphire_ipc::SHUTDOWN_METHOD, serde_json::json!({}))
1276            .await
1277            .unwrap();
1278        handle.await.unwrap().unwrap();
1279    }
1280
1281    #[tokio::test(flavor = "multi_thread")]
1282    async fn a_server_reports_its_app_api_and_the_handshake_gates_on_it() {
1283        let f = prepared();
1284        let endpoint = f.endpoint.clone();
1285        let server = AppServer::new(&CTX, "0.0.0")
1286            .endpoint(endpoint.clone())
1287            .app_api(7);
1288        let handle = tokio::spawn(async move { server.run().await });
1289        wait_until_listening(&endpoint).await;
1290
1291        let wants = |app_api| ClientInfo {
1292            app_api,
1293            ..client_info()
1294        };
1295        let err = sapphire_ipc::connect_or_absent(&endpoint, CTX.app_name, wants(Some(8)))
1296            .await
1297            .unwrap_err();
1298        assert!(
1299            matches!(
1300                err,
1301                sapphire_ipc::Error::AppApiVersionMismatch {
1302                    running: Some(7),
1303                    ours: 8,
1304                    ..
1305                }
1306            ),
1307            "{err:?}"
1308        );
1309
1310        let (client, info) =
1311            sapphire_ipc::connect_or_absent(&endpoint, CTX.app_name, wants(Some(7)))
1312                .await
1313                .unwrap()
1314                .expect("the server is listening");
1315        assert_eq!(info.app_api, Some(7));
1316
1317        let _: serde_json::Value = client
1318            .call(sapphire_ipc::SHUTDOWN_METHOD, serde_json::json!({}))
1319            .await
1320            .unwrap();
1321        handle.await.unwrap().unwrap();
1322    }
1323
1324    #[tokio::test(flavor = "multi_thread")]
1325    async fn a_running_server_answers_server_info() {
1326        let f = prepared();
1327        let endpoint = f.endpoint.clone();
1328
1329        let server = AppServer::new(&CTX, "1.2.3").endpoint(endpoint.clone());
1330        let handle = tokio::spawn(async move { server.run().await });
1331        wait_until_listening(&endpoint).await;
1332
1333        let (client, info) = sapphire_ipc::connect_or_absent(
1334            &endpoint,
1335            CTX.app_name,
1336            ClientInfo {
1337                version: "1.2.3".into(),
1338                ..client_info()
1339            },
1340        )
1341        .await
1342        .unwrap()
1343        .expect("the server is listening");
1344        assert_eq!(info.version, "1.2.3");
1345
1346        // `server.info` answers the whole typed report, not the bare handshake record:
1347        // the CLI reads one shape, and so would a GUI.
1348        let report: StatusReport = client
1349            .call(
1350                sapphire_backend::protocol::SERVER_INFO,
1351                serde_json::json!({}),
1352            )
1353            .await
1354            .unwrap();
1355        assert!(report.running);
1356        assert_eq!(report.version.as_deref(), Some("1.2.3"));
1357        assert_eq!(report.pid, Some(std::process::id()));
1358        assert_eq!(report.managed_by, Some(proto::ManagedBy::Service));
1359        assert!(report.app.is_empty(), "no status rows were configured");
1360
1361        let _: serde_json::Value = client
1362            .call(sapphire_ipc::SHUTDOWN_METHOD, serde_json::json!({}))
1363            .await
1364            .unwrap();
1365        handle.await.unwrap().unwrap();
1366    }
1367
1368    #[tokio::test(flavor = "multi_thread")]
1369    async fn shutdown_stops_the_server() {
1370        let f = prepared();
1371        let endpoint = f.endpoint.clone();
1372
1373        let server = AppServer::new(&CTX, "0.0.0").endpoint(endpoint.clone());
1374        let handle = tokio::spawn(async move { server.run().await });
1375        wait_until_listening(&endpoint).await;
1376
1377        let (client, _) = sapphire_ipc::connect_or_absent(&endpoint, CTX.app_name, client_info())
1378            .await
1379            .unwrap()
1380            .expect("the server is listening");
1381        let _: serde_json::Value = client
1382            .call(sapphire_ipc::SHUTDOWN_METHOD, serde_json::json!({}))
1383            .await
1384            .unwrap();
1385
1386        tokio::time::timeout(Duration::from_secs(5), handle)
1387            .await
1388            .expect("the server must stop")
1389            .unwrap()
1390            .unwrap();
1391        assert!(!sapphire_ipc::probe(&endpoint).await.unwrap());
1392    }
1393
1394    #[tokio::test(flavor = "multi_thread")]
1395    async fn an_application_can_add_its_own_methods() {
1396        let f = prepared();
1397        let endpoint = f.endpoint.clone();
1398
1399        let server = AppServer::new(&CTX, "0.0.0")
1400            .endpoint(endpoint.clone())
1401            .extend(|r| {
1402                r.method("sapphire-appservertest.greet", |_| async move {
1403                    Ok(serde_json::json!("hello"))
1404                })
1405            });
1406        let handle = tokio::spawn(async move { server.run().await });
1407        wait_until_listening(&endpoint).await;
1408
1409        let (client, _) = sapphire_ipc::connect_or_absent(&endpoint, CTX.app_name, client_info())
1410            .await
1411            .unwrap()
1412            .expect("the server is listening");
1413        let greeting: String = client
1414            .call("sapphire-appservertest.greet", serde_json::json!({}))
1415            .await
1416            .unwrap();
1417        assert_eq!(greeting, "hello");
1418
1419        let _: serde_json::Value = client
1420            .call(sapphire_ipc::SHUTDOWN_METHOD, serde_json::json!({}))
1421            .await
1422            .unwrap();
1423        handle.await.unwrap().unwrap();
1424    }
1425
1426    #[tokio::test(flavor = "multi_thread")]
1427    async fn workspace_init_creates_the_marker() {
1428        let f = prepared();
1429        let endpoint = f.endpoint.clone();
1430        let server = AppServer::new(&CTX, "0.0.0").endpoint(endpoint.clone());
1431        let handle = tokio::spawn(async move { server.run().await });
1432        wait_until_listening(&endpoint).await;
1433        let (client, _) = sapphire_ipc::connect_or_absent(&endpoint, CTX.app_name, client_info())
1434            .await
1435            .unwrap()
1436            .unwrap();
1437
1438        let dir = tempfile::tempdir().unwrap();
1439        let result: 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!(result.created);
1449        assert!(dir.path().join(format!(".{}", CTX.app_name)).is_dir());
1450
1451        // Idempotent: the second init is a success that did not create.
1452        let again: proto::WorkspaceInitResult = client
1453            .call(
1454                proto::WORKSPACE_INIT,
1455                proto::WorkspaceInitParams {
1456                    dir: dir.path().to_owned(),
1457                },
1458            )
1459            .await
1460            .unwrap();
1461        assert!(!again.created);
1462
1463        let _: serde_json::Value = client
1464            .call(sapphire_ipc::SHUTDOWN_METHOD, serde_json::json!({}))
1465            .await
1466            .unwrap();
1467        handle.await.unwrap().unwrap();
1468    }
1469
1470    #[tokio::test(flavor = "multi_thread")]
1471    async fn server_info_carries_the_app_rows() {
1472        let f = prepared();
1473        let endpoint = f.endpoint.clone();
1474        let server = AppServer::new(&CTX, "0.0.0")
1475            .endpoint(endpoint.clone())
1476            .status_rows(std::sync::Arc::new(|| {
1477                vec![StatusRow {
1478                    name: "sync".into(),
1479                    value: "enabled".into(),
1480                }]
1481            }));
1482        let handle = tokio::spawn(async move { server.run().await });
1483        wait_until_listening(&endpoint).await;
1484        let (client, _) = sapphire_ipc::connect_or_absent(&endpoint, CTX.app_name, client_info())
1485            .await
1486            .unwrap()
1487            .unwrap();
1488        let report: StatusReport = client
1489            .call(
1490                sapphire_backend::protocol::SERVER_INFO,
1491                serde_json::json!({}),
1492            )
1493            .await
1494            .unwrap();
1495        assert!(report.running);
1496        assert_eq!(report.app.len(), 1);
1497        assert_eq!(report.app[0].name, "sync");
1498
1499        let _: serde_json::Value = client
1500            .call(sapphire_ipc::SHUTDOWN_METHOD, serde_json::json!({}))
1501            .await
1502            .unwrap();
1503        handle.await.unwrap().unwrap();
1504    }
1505}