Skip to main content

sapphire_framework_server/
lib.rs

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