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