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;
32
33/// How long a server's shutdown waits for its open connections to wind down on their own.
34///
35/// The shutdown acknowledgement is one of those connections; a moment is all a well-behaved
36/// client needs. Whatever still holds on after this is cancelled, so a connection kept open
37/// past shutdown cannot pin the router — and through it the sync runtime's replica stores —
38/// after the server has answered its own shutdown call.
39const SERVE_GRACE: Duration = Duration::from_secs(2);
40
41mod command;
42mod config;
43mod current;
44mod error;
45mod events;
46mod handlers;
47mod host;
48#[cfg(feature = "http")]
49mod http;
50mod selection;
51pub mod sync;
52#[cfg(test)]
53mod test_support;
54mod update;
55
56pub use command::{
57    AppUpdateArgs, DeviceCommand, FrameworkCommand, StatusReport, StatusRow, WorkgroupCommand,
58    WorkspaceCommand, WorkspaceSyncCommand, render_workspace,
59};
60pub use config::{HttpConfig, McpConfig, SERVER_CONFIG_FILE, ServerConfig, UpdateConfig};
61pub use current::Current;
62pub use error::{Error, Result};
63pub use events::subscribe_method;
64pub use handlers::workspace_router;
65pub use host::WorkspaceHost;
66pub use sapphire_framework_update::{ReleaseSource, UpdateArgs};
67pub use selection::{SELECTION_FILE, Selection, SelectionFile};
68pub use sync::{BackfillTiming, BridgeConnector, SyncRuntime, SyncStatus, sync_router};
69
70/// The MCP tools an application serves, and how (feature `mcp`).
71#[cfg(feature = "mcp")]
72pub use sapphire_framework_mcp as mcp;
73
74/// An application's server.
75pub struct AppServer {
76    ctx: &'static AppContext,
77    version: &'static str,
78    endpoint: Option<Endpoint>,
79    /// Where `workspace.toml` lives; `None` is the config directory's.
80    selection_file: Option<PathBuf>,
81    host: Arc<WorkspaceHost>,
82    sync: Option<Arc<SyncRuntime>>,
83    extend: Option<Box<dyn FnOnce(Router) -> Router + Send>>,
84    /// The application's own status rows, shown after the framework's in `status` and in
85    /// the `server.info` report.
86    status_rows: Option<Arc<dyn Fn() -> Vec<StatusRow> + Send + Sync>>,
87    /// The version of the application's own API, reported in the handshake.
88    app_api: Option<u32>,
89    /// `server.toml`'s settings, when given rather than read from the config directory.
90    config: Option<ServerConfig>,
91    /// Where the application's releases are published: what the server looks for newer
92    /// ones in, and what `update` installs from.
93    releases: Option<ReleaseSource>,
94    /// Where the HTTP listener binds when `server.toml` does not say.
95    #[cfg(feature = "http")]
96    http_listen: Option<std::net::SocketAddr>,
97    /// The application's own HTTP routes.
98    #[cfg(feature = "http")]
99    http_routes: Option<axum::Router>,
100    /// How the HTTP routes check a token; `None` asks the bridge.
101    #[cfg(feature = "http")]
102    http_auth: Option<sapphire_framework_keys::AuthConfig>,
103    /// The application's MCP handler, for the `mcp` subcommand and `/mcp`.
104    #[cfg(feature = "mcp")]
105    mcp: sapphire_framework_mcp::McpService,
106}
107
108/// The SIGTERM end of the server's select loop, in a shape every platform shares.
109///
110/// [`AppServer::run`]'s select arm awaits `recv()` on one of these, exactly as the
111/// plan writes it for Unix. Unix backs it with the `SignalKind::terminate()`
112/// stream; Windows has no SIGTERM, so there the future never resolves and the arm
113/// exists for the macro's sake and never fires. Without the common shape the arm
114/// would need a `#[cfg]` of its own, which tokio's `select!` rejects once the
115/// attribute removes the arm.
116#[cfg(unix)]
117struct Sigterm(tokio::signal::unix::Signal);
118
119/// The never-firing stand-in for the Unix `Sigterm` where there is no SIGTERM.
120#[cfg(not(unix))]
121struct Sigterm;
122
123#[cfg(unix)]
124impl Sigterm {
125    /// Register interest in SIGTERM.
126    ///
127    /// Called before the listener binds, so a signal arriving the instant the
128    /// socket is up is queued by tokio instead of killing the process with the
129    /// default handler.
130    fn new() -> Result<Self> {
131        Ok(Self(tokio::signal::unix::signal(
132            tokio::signal::unix::SignalKind::terminate(),
133        )?))
134    }
135
136    /// Wait for the next SIGTERM.
137    ///
138    /// Never returns `None`: the stream is infinite, as its documentation states.
139    async fn recv(&mut self) {
140        self.0.recv().await;
141    }
142}
143
144#[cfg(not(unix))]
145impl Sigterm {
146    /// A future that is never ready — the arm awaits it for the macro's sake only.
147    ///
148    /// There is no `new`: this platform has no SIGTERM to register interest in, so
149    /// the loop binds the unit value directly.
150    async fn recv(&mut self) {
151        std::future::pending::<()>().await
152    }
153}
154
155impl AppServer {
156    /// A server for `ctx`'s application, reporting `version` in its handshake.
157    pub fn new(ctx: &'static AppContext, version: &'static str) -> AppServer {
158        AppServer {
159            ctx,
160            version,
161            endpoint: None,
162            selection_file: None,
163            host: Arc::new(WorkspaceHost::new(ctx)),
164            sync: None,
165            extend: None,
166            status_rows: None,
167            app_api: None,
168            config: None,
169            releases: None,
170            #[cfg(feature = "http")]
171            http_listen: None,
172            #[cfg(feature = "http")]
173            http_routes: None,
174            #[cfg(feature = "http")]
175            http_auth: None,
176            #[cfg(feature = "mcp")]
177            mcp: sapphire_framework_mcp::McpService::framework(),
178        }
179    }
180
181    /// The application this server serves, as its [`AppContext`] names it.
182    ///
183    /// [`FrameworkCommand`](crate::FrameworkCommand) reads it to build the CLI's endpoint,
184    /// so an application never passes its own name twice.
185    pub fn app_name(&self) -> &'static str {
186        self.ctx.app_name
187    }
188
189    /// Listen somewhere other than the application's default endpoint. Used by tests.
190    pub fn endpoint(mut self, endpoint: Endpoint) -> AppServer {
191        self.endpoint = Some(endpoint);
192        self
193    }
194
195    /// Report `version` as the application's own API version in the handshake: the major
196    /// of the application's API crate, which carries the methods it adds with
197    /// [`extend`](Self::extend). A client that calls those methods names the version it
198    /// expects, and the handshake refuses a server that speaks another.
199    pub fn app_api(mut self, version: u32) -> AppServer {
200        self.app_api = Some(version);
201        self
202    }
203
204    /// Use `config` rather than reading `<config dir>/server.toml`: for fixtures.
205    pub fn config(mut self, config: ServerConfig) -> AppServer {
206        self.config = Some(config);
207        self
208    }
209
210    /// Where the HTTP listener binds unless `server.toml` says otherwise: the application's
211    /// own port. Without it, a host that serves anything over HTTP names the address in
212    /// `[http] listen`.
213    #[cfg(feature = "http")]
214    pub fn http_listen(mut self, addr: std::net::SocketAddr) -> AppServer {
215        self.http_listen = Some(addr);
216        self
217    }
218
219    /// Serve the application's own HTTP routes on the server's listener, behind the same
220    /// external-device token as `/mcp`. The routes are served whenever they are given;
221    /// `/mcp` only when `server.toml` turns it on.
222    #[cfg(feature = "http")]
223    pub fn http(mut self, routes: axum::Router) -> AppServer {
224        self.http_routes = Some(routes);
225        self
226    }
227
228    /// Check HTTP tokens with `auth` rather than with the bridge: for fixtures.
229    #[cfg(feature = "http")]
230    pub fn http_auth(mut self, auth: sapphire_framework_keys::AuthConfig) -> AppServer {
231        self.http_auth = Some(auth);
232        self
233    }
234
235    /// Answer MCP with the application's own handler, rather than the framework's tools
236    /// alone: on stdio for the `mcp` subcommand, and at `/mcp` when `server.toml` turns it
237    /// on.
238    #[cfg(feature = "mcp")]
239    pub fn mcp(mut self, service: sapphire_framework_mcp::McpService) -> AppServer {
240        self.mcp = service;
241        self
242    }
243
244    /// Serve the application's MCP tools on this process's stdio, until the agent closes
245    /// it: the `mcp` subcommand.
246    ///
247    /// This is the client side: the tools reach the running server over its IPC endpoint,
248    /// as the CLI does, and nothing here starts one.
249    #[cfg(feature = "mcp")]
250    pub async fn serve_mcp_stdio(self, version: &'static str) -> Result<()> {
251        let endpoint = match self.endpoint {
252            Some(e) => e,
253            None => Endpoint::for_app(self.ctx.app_name)?,
254        };
255        let ctx = sapphire_framework_mcp::ToolContext::dial(
256            self.ctx.app_name,
257            version,
258            self.app_api,
259            endpoint,
260        );
261        self.mcp
262            .serve_stdio(ctx)
263            .await
264            .map_err(|e| Error::Mcp(e.to_string()))
265    }
266
267    /// Keep the selected workspace (`workspace.toml`) at `path` rather than in the
268    /// application's config directory: for fixtures that run several hosts in one process.
269    pub fn selection_file(mut self, path: PathBuf) -> AppServer {
270        self.selection_file = Some(path);
271        self
272    }
273
274    /// Serve `sync.enable`, `sync.disable`, `sync.map` and `sync.status`, and keep a replica
275    /// of the workspace in step with its files while it is synced.
276    ///
277    /// Without this the server has no sync at all: an application that does not call it
278    /// never talks to the bridge. The runtime is built by the caller because it needs the
279    /// bridge connection, which is the caller's to open and to close.
280    pub fn sync(mut self, runtime: Arc<SyncRuntime>) -> AppServer {
281        // The runtime re-indexes what a session writes, and the index belongs to this host:
282        // tell it where the workspace lives before anything can arrive.
283        runtime.set_host(Arc::clone(&self.host));
284        self.sync = Some(runtime);
285        self
286    }
287
288    /// Sync through the host's `sapphire-bridge`: [`sync`](Self::sync) with a runtime that
289    /// reaches the bridge itself, and reaches it again whenever it is lost (#244).
290    ///
291    /// [`run`](Self::run) makes the first attempt. No bridge running is not fatal — the
292    /// server serves without sync and picks the bridge up once it starts, and `sync.*`
293    /// answers that it is not connected meanwhile — but any other failure, such as a bridge
294    /// of another API version, stops the start.
295    pub fn sync_via_bridge(self) -> Result<AppServer> {
296        let runtime = SyncRuntime::connecting(
297            self.ctx,
298            BridgeConnector::standard(self.ctx.app_name, self.version),
299            std::env::current_exe()?,
300            ManagedBy::Service,
301        );
302        Ok(self.sync(Arc::new(runtime)))
303    }
304
305    /// The application's own rows for the status report: shown after the framework's
306    /// `running` / `version` / `pid` / `managed_by` lines.
307    ///
308    /// The closure is called once per report, so an application's rows may read live
309    /// state; the CLI's `status` and the IPC `server.info` method render the same call's
310    /// output.
311    pub fn status_rows(mut self, rows: Arc<dyn Fn() -> Vec<StatusRow> + Send + Sync>) -> AppServer {
312        self.status_rows = Some(rows);
313        self
314    }
315
316    /// Where this application's releases are published.
317    ///
318    /// The server looks there for newer ones once at start and once a day after, unless
319    /// `server.toml` says `[update] check = false`; `status` and the GUI show what it found.
320    /// The `update` command installs from there, when `source` names the release's
321    /// [asset](ReleaseSource::asset).
322    pub fn releases(mut self, source: ReleaseSource) -> AppServer {
323        self.releases = Some(source);
324        self
325    }
326
327    /// Where this application's releases are published, if it said.
328    pub fn release_source(&self) -> Option<&ReleaseSource> {
329        self.releases.as_ref()
330    }
331
332    /// What this application's service is: the arguments a service manager starts it with.
333    ///
334    /// `["serve"]`: a service manager starts the executable directly with
335    /// [`FrameworkCommand::Serve`](crate::FrameworkCommand::Serve) — the bare invocation
336    /// only prints the help. A CLI that wants its
337    /// service installed hands this to
338    /// [`ServiceCommand`](sapphire_framework_service::ServiceCommand).
339    pub fn service_spec(&self) -> ServiceSpec {
340        ServiceSpec {
341            app_name: self.ctx.app_name,
342            description: format!("{} server {}", self.ctx.app_name, self.version),
343            args: vec!["serve".to_owned()],
344            post_install: None,
345        }
346    }
347
348    /// Add the application's own methods.
349    pub fn extend(mut self, f: impl FnOnce(Router) -> Router + Send + 'static) -> AppServer {
350        self.extend = Some(Box::new(f));
351        self
352    }
353
354    /// The workspace this server has open. An application's own handlers use it to reach
355    /// the workspace the same way the framework's do: [`WorkspaceHost::backend`].
356    pub fn host(&self) -> &Arc<WorkspaceHost> {
357        &self.host
358    }
359
360    /// The sync runtime, once [`sync`](Self::sync) or [`sync_via_bridge`](Self::sync_via_bridge)
361    /// has set one (#250): for an application's own code that reads sync state — status
362    /// rows, or which device is the workspace's primary.
363    pub fn sync_runtime(&self) -> Option<&Arc<SyncRuntime>> {
364        self.sync.as_ref()
365    }
366
367    /// Listen until told to stop, or until a signal arrives.
368    pub async fn run(self) -> Result<()> {
369        let AppServer {
370            ctx,
371            version,
372            endpoint,
373            selection_file,
374            host,
375            sync,
376            extend,
377            status_rows,
378            app_api,
379            config,
380            releases,
381            #[cfg(feature = "http")]
382            http_listen,
383            #[cfg(feature = "http")]
384            http_routes,
385            #[cfg(feature = "http")]
386            http_auth,
387            #[cfg(feature = "mcp")]
388            mcp,
389        } = self;
390
391        let endpoint = match endpoint {
392            Some(e) => e,
393            None => Endpoint::for_app(ctx.app_name)?,
394        };
395        // A server is always-on from here on: only `serve` and the service manager start
396        // one, and the service manager starts it for keeps. There is no spawned mode left
397        // to report.
398        let info = ServerInfo {
399            version: version.to_owned(),
400            api: proto::API_VERSION,
401            app_api,
402            pid: std::process::id(),
403            managed_by: ManagedBy::Service,
404        };
405
406        // The app's log file, held for as long as this server serves: the guard's
407        // drop flushes the writer thread, so the last lines of a clean shutdown land
408        // in the file. The subscriber itself was installed by `ctx.init`; this is what
409        // routes the file layer at `<data dir>/logs/`.
410        let _log = sapphire_workspace::logging::install(ctx)?;
411
412        let config = match config {
413            Some(config) => config,
414            None => ServerConfig::load_for_app(ctx)?,
415        };
416        #[cfg(not(feature = "mcp"))]
417        if config.mcp.http {
418            tracing::warn!(
419                "server.toml turns MCP over HTTP on, but this build of {} has no MCP",
420                ctx.app_name
421            );
422        }
423
424        let (stop_tx, mut stop_rx) = tokio::sync::watch::channel(false);
425
426        // What `server.update` answers; the looking task fills it in once the server serves.
427        let update_status = update::SharedStatus::default();
428        let update_check = releases.filter(|_| config.update.check);
429
430        // The first attempt to reach the bridge, before the selected workspace comes back
431        // and asks it for sync.
432        if let Some(runtime) = &sync {
433            runtime.connect().await?;
434        }
435
436        let file = match selection_file {
437            Some(path) => SelectionFile::at(path),
438            None => SelectionFile::for_app(ctx),
439        };
440        let current = Arc::new(Current::new(ctx, Arc::clone(&host), sync.clone(), file));
441        // Back to the workspace this host had, before the first client can ask for it.
442        let restoring = current.restore().await;
443
444        let mut router = subscribe_method(
445            Arc::clone(&host),
446            current::current_methods(Arc::clone(&current), workspace_router(Arc::clone(&current))),
447        );
448        if sync.is_some() {
449            // `sync_router` is applied *under* the application's own methods so a later
450            // `extend` can still replace one, and after `subscribe_method` so the
451            // `workspace.*` namespace is complete.
452            router = sync_router(Arc::clone(&current), router);
453        }
454        // `server.info` answers the typed [`StatusReport`] — the same shape the CLI's
455        // `status` renders — so the CLI and a future GUI read one record. The rows come
456        // from the application's builder, called once per report.
457        router = router
458            .method(proto::SERVER_INFO, {
459                let info = info.clone();
460                let status_rows = status_rows.clone();
461                move |_| {
462                    let info = info.clone();
463                    let status_rows = status_rows.clone();
464                    async move {
465                        let app = status_rows.as_ref().map(|rows| rows()).unwrap_or_default();
466                        let report = StatusReport {
467                            running: true,
468                            version: Some(info.version),
469                            pid: Some(info.pid),
470                            managed_by: Some(match info.managed_by {
471                                ManagedBy::Service => proto::ManagedBy::Service,
472                                ManagedBy::Spawned => proto::ManagedBy::Spawned,
473                            }),
474                            app,
475                        };
476                        serde_json::to_value(report)
477                            .map_err(|e| sapphire_ipc::RpcError::internal(e.to_string()))
478                    }
479                }
480            })
481            .method(proto::SERVER_UPDATE, {
482                let update_status = Arc::clone(&update_status);
483                move |_| {
484                    let status = update_status.lock().expect("update status lock").clone();
485                    async move {
486                        serde_json::to_value(status)
487                            .map_err(|e| sapphire_ipc::RpcError::internal(e.to_string()))
488                    }
489                }
490            })
491            .method(sapphire_ipc::SHUTDOWN_METHOD, {
492                let stop_tx = stop_tx.clone();
493                move |_| {
494                    let stop_tx = stop_tx.clone();
495                    async move {
496                        let _ = stop_tx.send(true);
497                        serde_json::to_value(proto::Ack {})
498                            .map_err(|e| sapphire_ipc::RpcError::internal(e.to_string()))
499                    }
500                }
501            });
502        if let Some(extend) = extend {
503            router = extend(router);
504        }
505        let router = Arc::new(router);
506
507        // Registered before the bind, so a SIGTERM arriving the instant the socket is up
508        // cannot fall through to the default handler and kill the process. SIGINT is
509        // listened to only through `ctrl_c` (which swallows the default handler on both
510        // platforms): a Unix `SignalKind::interrupt()` stream would double-fire for ^C.
511        #[cfg(unix)]
512        let mut sigterm = Sigterm::new()?;
513        #[cfg(not(unix))]
514        let mut sigterm = Sigterm;
515
516        #[cfg(unix)]
517        let listener = sapphire_ipc::bind(&endpoint).await?;
518        #[cfg(windows)]
519        let mut listener = sapphire_ipc::bind(&endpoint)?;
520
521        let mut connections = tokio::task::JoinSet::new();
522
523        // The HTTP listener, when anything is served over it. Started once the IPC socket
524        // is bound, for the same reason as the sync tasks below. `/mcp`'s tools reach this
525        // server the way the `mcp` subcommand's do — over IPC — on an in-process connection
526        // served like any other.
527        #[cfg(feature = "http")]
528        let http_stop = tokio_util::sync::CancellationToken::new();
529        #[cfg(feature = "http")]
530        let _http = {
531            let mut routes = http_routes;
532            #[cfg(feature = "mcp")]
533            if config.mcp.http {
534                let (ours, theirs) = sapphire_ipc::Connection::pair();
535                {
536                    let router = Arc::clone(&router);
537                    let info = info.clone();
538                    let app = ctx.app_name;
539                    connections.spawn(async move {
540                        let _ = serve(theirs, router, app, info).await;
541                    });
542                }
543                let client_info = sapphire_ipc::ClientInfo {
544                    kind: sapphire_framework_mcp::CLIENT_KIND.to_owned(),
545                    version: version.to_owned(),
546                    api: proto::API_VERSION,
547                    app_api,
548                    pid: std::process::id(),
549                };
550                let (client, _) =
551                    sapphire_ipc::Client::handshake(ours, ctx.app_name, client_info).await?;
552                let tools = sapphire_framework_mcp::ToolContext::connected(
553                    ctx.app_name,
554                    version,
555                    Arc::new(client),
556                );
557                let mcp_routes =
558                    mcp.http_router(tools, &config.http.allowed_hosts, http_stop.child_token());
559                routes = Some(match routes {
560                    Some(routes) => routes.merge(mcp_routes),
561                    None => mcp_routes,
562                });
563            }
564            match (routes, config.http.listen.or(http_listen)) {
565                (None, _) => None,
566                (Some(_), None) => {
567                    tracing::error!(
568                        "nothing to bind HTTP to: set `[http] listen` in {SERVER_CONFIG_FILE}"
569                    );
570                    None
571                }
572                (Some(routes), Some(addr)) => {
573                    let auth = http_auth.unwrap_or_else(|| {
574                        sapphire_framework_keys::AuthConfig::new(Arc::new(
575                            sapphire_framework_keys::BridgeVerifier::new(ctx.app_name, version),
576                        ))
577                    });
578                    http::start(addr, routes, auth, http_stop.clone()).await
579                }
580            }
581        };
582
583        // The watcher, the bridge announcement loop, the dialer and the bridge connection, if
584        // sync is on. Started only once the socket is bound, so an early `?` above cannot
585        // leave tasks running for a server that never served. All of them are allowed to
586        // fail: only sync stops when they do, and the app server keeps serving files
587        // (spec §10). They are aborted with the server.
588        let _sync_tasks = match &sync {
589            Some(runtime) => {
590                let driver = Arc::clone(runtime);
591                let announcements = tokio::spawn(async move {
592                    if let Err(err) = driver.run().await {
593                        tracing::warn!("the bridge announcement loop ended: {err}");
594                    }
595                });
596                let changing = Arc::clone(runtime);
597                let watching = tokio::spawn(async move {
598                    if let Err(err) = changing.watch_changes().await {
599                        tracing::warn!("the file watcher ended: {err}");
600                    }
601                });
602                // The dialer is what keeps a session open after the initial exchange, so a
603                // commit reaches a peer without waiting for the next one (spec §4.2).
604                let dialling = Arc::clone(runtime);
605                let dialling = tokio::spawn(async move {
606                    if let Err(err) = dialling.dial_loop().await {
607                        tracing::warn!("the live dial loop ended: {err}");
608                    }
609                });
610                // Reaching the bridge again whenever it is lost (#244).
611                let connected = tokio::spawn(Arc::clone(runtime).keep_connected());
612                Some([announcements, watching, dialling, connected])
613            }
614            None => None,
615        };
616
617        // Looking for newer releases, once the socket is bound for the same reason. Ends
618        // with the server, when this is dropped.
619        let _update_checking = update_check.and_then(|check| {
620            update::start(check, ctx.app_name, version, Arc::clone(&update_status))
621        });
622
623        loop {
624            tokio::select! {
625                changed = stop_rx.changed() => {
626                    if changed.is_err() || *stop_rx.borrow() {
627                        break;
628                    }
629                }
630                _ = tokio::signal::ctrl_c() => {
631                    tracing::info!("interrupted; shutting down");
632                    break;
633                }
634                _ = sigterm.recv() => {
635                    tracing::info!("terminated; shutting down");
636                    break;
637                }
638                accepted = listener.accept() => {
639                    let conn = accepted?;
640                    let router = Arc::clone(&router);
641                    let app = ctx.app_name;
642                    let info = info.clone();
643                    connections.spawn(async move {
644                        let _ = serve(conn, router, app, info).await;
645                    });
646                }
647            }
648        }
649
650        if let Some(restoring) = restoring {
651            restoring.abort();
652        }
653        // HTTP first: its sessions hold a connection to this server, which the reaping
654        // below waits for.
655        #[cfg(feature = "http")]
656        {
657            http_stop.cancel();
658            if let Some((_, mut task)) = _http
659                && tokio::time::timeout(SERVE_GRACE, &mut task).await.is_err()
660            {
661                tracing::debug!("the HTTP listener did not stop in time");
662                task.abort();
663            }
664        }
665        if let Some(tasks) = _sync_tasks {
666            // Each loop pins the sync runtime, and with it the replica stores. An aborted task
667            // is only dropped once its current poll returns — which, mid-scan, can take a
668            // while — so wait for that rather than return with a loop still holding a store
669            // the next server in this process would fail to open (#235).
670            for task in tasks {
671                task.abort();
672                let _ = task.await;
673            }
674        }
675        if let Some(runtime) = &sync {
676            // The first dials after an enable pin the runtime the same way, and so do the
677            // inbound sessions, the live-session readers and the embedding passes.
678            runtime.stop_dials().await;
679            runtime.stop_background().await;
680            // Close every live sync session. A session's reader task holds the replica, and
681            // the session itself sits in the runtime's table until it is cleared, so leaving
682            // one open pins the runtime — and the redb replica stores in it — after the
683            // server is gone (spec §2.2: cancellation is disconnection).
684            runtime.drop_connections().await;
685        }
686        host.close();
687        drop(listener); // removes the socket file on Unix
688
689        // Reap the per-connection serve tasks. Each one pins the router, the router pins
690        // the sync runtime, and the runtime's replica stores are redb databases that stay
691        // locked until the last pin is dropped — a server that left them running would
692        // lock its own successor out of its state (spec §2.2: cancellation is
693        // disconnection). Connections get a grace period to wind down on their own — the
694        // shutdown acknowledgement among them — then the rest are cancelled: a client
695        // that keeps its connection open past shutdown is holding a server that is gone.
696        let _ = tokio::time::timeout(SERVE_GRACE, async {
697            while connections.join_next().await.is_some() {}
698        })
699        .await;
700        connections.abort_all();
701        while connections.join_next().await.is_some() {}
702        Ok(())
703    }
704}
705
706#[cfg(test)]
707mod tests {
708    use super::*;
709    use sapphire_ipc::{ClientInfo, Endpoint, ManagedBy};
710    use sapphire_workspace::{AppContext, AppKind};
711    use std::ffi::OsString;
712
713    use crate::test_support;
714
715    static CTX: AppContext = AppContext::new("sapphire-appservertest");
716
717    /// The env vars `init_ctx` writes, in the order the guard restores them.
718    const DIR_VARS: [&str; 3] = [
719        "SAPPHIRE_APPSERVERTEST_CACHE_DIR",
720        "SAPPHIRE_APPSERVERTEST_DATA_DIR",
721        "SAPPHIRE_APPSERVERTEST_CONFIG_DIR",
722    ];
723
724    fn client_info() -> ClientInfo {
725        ClientInfo {
726            kind: "test".into(),
727            version: "0.0.0".into(),
728            api: sapphire_backend::protocol::API_VERSION,
729            app_api: None,
730            pid: std::process::id(),
731        }
732    }
733
734    /// Point the context's directories at `tmp` and restore the previous values (present
735    /// or absent) when dropped — including while unwinding from a panic. Without the
736    /// unconditional restore, a panicking assertion would leave the variables pointing at
737    /// a temp directory the test then deletes, and the context of a later test would
738    /// resolve into the void.
739    struct EnvGuard {
740        previous: [Option<OsString>; 3],
741        _lock: std::sync::MutexGuard<'static, ()>,
742    }
743
744    impl EnvGuard {
745        /// Write the three directory vars while holding the environment lock.
746        fn set(lock: std::sync::MutexGuard<'static, ()>, tmp: &std::path::Path) -> EnvGuard {
747            let previous = DIR_VARS.map(std::env::var_os);
748            let dirs = ["cache", "data", "config"].map(|cat| tmp.join(cat));
749            // SAFETY (via `test_support::set`): `lock` serialises every read and write of
750            // the process environment in this test binary — the `host`, `handlers` and
751            // `events` modules' tests share the same lock — and it is held until `drop`
752            // has restored the old values.
753            for (name, dir) in DIR_VARS.iter().zip(dirs) {
754                test_support::set(name, &dir);
755            }
756            EnvGuard {
757                previous,
758                _lock: lock,
759            }
760        }
761    }
762
763    impl Drop for EnvGuard {
764        fn drop(&mut self) {
765            // SAFETY: `self._lock` still serialises the environment; it is dropped only
766            // after this method returns.
767            for (name, previous) in DIR_VARS.iter().zip(self.previous.iter_mut()) {
768                match previous.take() {
769                    Some(value) => unsafe { std::env::set_var(name, value) },
770                    None => test_support::remove(name),
771                }
772            }
773        }
774    }
775
776    /// Everything one test needs, held for the test's whole body.
777    ///
778    /// `_tmp` is declared before `_env` so the scratch tree is deleted while the
779    /// environment lock is still held: a sibling test that wakes on the lock must never
780    /// observe the tree mid-deletion, nor env vars pointing at a deleted directory.
781    struct Fixture {
782        _tmp: tempfile::TempDir,
783        _env: EnvGuard,
784        endpoint: Endpoint,
785    }
786
787    /// A listening endpoint in a scratch directory, with the context's directories
788    /// pointed at the same scratch tree.
789    ///
790    /// The caller must keep the fixture (and with it the environment lock) alive for the
791    /// whole test: the static [`CTX`] is first-writer-wins, so while one test runs, every
792    /// other test that would re-point the context's directories must wait.
793    fn prepared() -> Fixture {
794        let lock = test_support::lock();
795        let tmp = tempfile::tempdir().unwrap();
796        let env = EnvGuard::set(lock, tmp.path());
797        CTX.init(AppKind::Server);
798        let endpoint = Endpoint::in_dir("sapphire-appservertest", tmp.path().to_path_buf());
799        Fixture {
800            _tmp: tmp,
801            _env: env,
802            endpoint,
803        }
804    }
805
806    /// Wait until something is listening on `endpoint`.
807    ///
808    /// `tokio::spawn(server.run())` only schedules the server; without this wait a fast
809    /// `connect_or_absent` probe can run before `run` has bound the socket, and with
810    /// nothing listening that single unlucky probe is the whole test failing.
811    async fn wait_until_listening(endpoint: &Endpoint) {
812        let deadline = tokio::time::Instant::now() + Duration::from_secs(5);
813        while !sapphire_ipc::probe(endpoint).await.unwrap() {
814            assert!(
815                tokio::time::Instant::now() < deadline,
816                "the server never started listening"
817            );
818            tokio::time::sleep(Duration::from_millis(10)).await;
819        }
820    }
821
822    /// A running server writes its log file: the framework's `logging` module
823    /// routes the app's log to `<data dir>/logs/app.log`, and `run()` holds the
824    /// guard for as long as it serves. The event is emitted by this test — the
825    /// subscriber and the file layer are the process's, installed by `CTX.init`
826    /// and `run` — so what lands in the file is exactly what a journald-less
827    /// host would otherwise never see.
828    #[test]
829    fn the_runtime_sync_via_bridge_mounts_is_the_applications_to_read() {
830        // #250: an application reads sync state (status rows, placement) from the
831        // runtime `sync_via_bridge` built, rather than building its own to keep one.
832        assert!(AppServer::new(&CTX, "0.0.0").sync_runtime().is_none());
833        let server = AppServer::new(&CTX, "0.0.0").sync_via_bridge().unwrap();
834        let runtime = server.sync_runtime().expect("a runtime");
835        assert!(!runtime.is_connected(), "nothing connects before `run`");
836    }
837
838    #[tokio::test(flavor = "multi_thread")]
839    async fn a_running_server_writes_its_log_file() {
840        let f = prepared();
841        let endpoint = f.endpoint.clone();
842        let server = AppServer::new(&CTX, "0.0.0").endpoint(endpoint.clone());
843        let handle = tokio::spawn(async move { server.run().await });
844        wait_until_listening(&endpoint).await;
845
846        tracing::info!("the server is serving, and this line belongs in its log");
847
848        let (client, _) = sapphire_ipc::connect_or_absent(&endpoint, CTX.app_name, client_info())
849            .await
850            .unwrap()
851            .expect("the server is listening");
852        let _: serde_json::Value = client
853            .call(sapphire_ipc::SHUTDOWN_METHOD, serde_json::json!({}))
854            .await
855            .unwrap();
856        // The guard flushes as `run` unwinds; awaiting it is what makes the
857        // file complete before it is read.
858        handle.await.unwrap().unwrap();
859
860        let text = std::fs::read_to_string(CTX.log_dir().join("app.log")).unwrap();
861        assert!(
862            text.contains("the server is serving, and this line belongs in its log"),
863            "{text}"
864        );
865    }
866
867    #[tokio::test(flavor = "multi_thread")]
868    async fn a_server_reports_itself_as_service_managed() {
869        let f = prepared();
870        let endpoint = f.endpoint.clone();
871        let server = AppServer::new(&CTX, "0.0.0").endpoint(endpoint.clone());
872        let handle = tokio::spawn(async move { server.run().await });
873        wait_until_listening(&endpoint).await;
874
875        let (client, info) =
876            sapphire_ipc::connect_or_absent(&endpoint, CTX.app_name, client_info())
877                .await
878                .unwrap()
879                .expect("the server is listening");
880        assert_eq!(info.managed_by, ManagedBy::Service);
881
882        let _: serde_json::Value = client
883            .call(sapphire_ipc::SHUTDOWN_METHOD, serde_json::json!({}))
884            .await
885            .unwrap();
886        handle.await.unwrap().unwrap();
887    }
888
889    #[tokio::test(flavor = "multi_thread")]
890    async fn a_server_reports_its_app_api_and_the_handshake_gates_on_it() {
891        let f = prepared();
892        let endpoint = f.endpoint.clone();
893        let server = AppServer::new(&CTX, "0.0.0")
894            .endpoint(endpoint.clone())
895            .app_api(7);
896        let handle = tokio::spawn(async move { server.run().await });
897        wait_until_listening(&endpoint).await;
898
899        let wants = |app_api| ClientInfo {
900            app_api,
901            ..client_info()
902        };
903        let err = sapphire_ipc::connect_or_absent(&endpoint, CTX.app_name, wants(Some(8)))
904            .await
905            .unwrap_err();
906        assert!(
907            matches!(
908                err,
909                sapphire_ipc::Error::AppApiVersionMismatch {
910                    running: Some(7),
911                    ours: 8,
912                    ..
913                }
914            ),
915            "{err:?}"
916        );
917
918        let (client, info) =
919            sapphire_ipc::connect_or_absent(&endpoint, CTX.app_name, wants(Some(7)))
920                .await
921                .unwrap()
922                .expect("the server is listening");
923        assert_eq!(info.app_api, Some(7));
924
925        let _: serde_json::Value = client
926            .call(sapphire_ipc::SHUTDOWN_METHOD, serde_json::json!({}))
927            .await
928            .unwrap();
929        handle.await.unwrap().unwrap();
930    }
931
932    #[tokio::test(flavor = "multi_thread")]
933    async fn a_running_server_answers_server_info() {
934        let f = prepared();
935        let endpoint = f.endpoint.clone();
936
937        let server = AppServer::new(&CTX, "1.2.3").endpoint(endpoint.clone());
938        let handle = tokio::spawn(async move { server.run().await });
939        wait_until_listening(&endpoint).await;
940
941        let (client, info) = sapphire_ipc::connect_or_absent(
942            &endpoint,
943            CTX.app_name,
944            ClientInfo {
945                version: "1.2.3".into(),
946                ..client_info()
947            },
948        )
949        .await
950        .unwrap()
951        .expect("the server is listening");
952        assert_eq!(info.version, "1.2.3");
953
954        // `server.info` answers the whole typed report, not the bare handshake record:
955        // the CLI reads one shape, and so would a GUI.
956        let report: StatusReport = client
957            .call(
958                sapphire_backend::protocol::SERVER_INFO,
959                serde_json::json!({}),
960            )
961            .await
962            .unwrap();
963        assert!(report.running);
964        assert_eq!(report.version.as_deref(), Some("1.2.3"));
965        assert_eq!(report.pid, Some(std::process::id()));
966        assert_eq!(report.managed_by, Some(proto::ManagedBy::Service));
967        assert!(report.app.is_empty(), "no status rows were configured");
968
969        let _: serde_json::Value = client
970            .call(sapphire_ipc::SHUTDOWN_METHOD, serde_json::json!({}))
971            .await
972            .unwrap();
973        handle.await.unwrap().unwrap();
974    }
975
976    #[tokio::test(flavor = "multi_thread")]
977    async fn shutdown_stops_the_server() {
978        let f = prepared();
979        let endpoint = f.endpoint.clone();
980
981        let server = AppServer::new(&CTX, "0.0.0").endpoint(endpoint.clone());
982        let handle = tokio::spawn(async move { server.run().await });
983        wait_until_listening(&endpoint).await;
984
985        let (client, _) = sapphire_ipc::connect_or_absent(&endpoint, CTX.app_name, client_info())
986            .await
987            .unwrap()
988            .expect("the server is listening");
989        let _: serde_json::Value = client
990            .call(sapphire_ipc::SHUTDOWN_METHOD, serde_json::json!({}))
991            .await
992            .unwrap();
993
994        tokio::time::timeout(Duration::from_secs(5), handle)
995            .await
996            .expect("the server must stop")
997            .unwrap()
998            .unwrap();
999        assert!(!sapphire_ipc::probe(&endpoint).await.unwrap());
1000    }
1001
1002    #[tokio::test(flavor = "multi_thread")]
1003    async fn an_application_can_add_its_own_methods() {
1004        let f = prepared();
1005        let endpoint = f.endpoint.clone();
1006
1007        let server = AppServer::new(&CTX, "0.0.0")
1008            .endpoint(endpoint.clone())
1009            .extend(|r| {
1010                r.method("sapphire-appservertest.greet", |_| async move {
1011                    Ok(serde_json::json!("hello"))
1012                })
1013            });
1014        let handle = tokio::spawn(async move { server.run().await });
1015        wait_until_listening(&endpoint).await;
1016
1017        let (client, _) = sapphire_ipc::connect_or_absent(&endpoint, CTX.app_name, client_info())
1018            .await
1019            .unwrap()
1020            .expect("the server is listening");
1021        let greeting: String = client
1022            .call("sapphire-appservertest.greet", serde_json::json!({}))
1023            .await
1024            .unwrap();
1025        assert_eq!(greeting, "hello");
1026
1027        let _: serde_json::Value = client
1028            .call(sapphire_ipc::SHUTDOWN_METHOD, serde_json::json!({}))
1029            .await
1030            .unwrap();
1031        handle.await.unwrap().unwrap();
1032    }
1033
1034    #[tokio::test(flavor = "multi_thread")]
1035    async fn workspace_init_creates_the_marker() {
1036        let f = prepared();
1037        let endpoint = f.endpoint.clone();
1038        let server = AppServer::new(&CTX, "0.0.0").endpoint(endpoint.clone());
1039        let handle = tokio::spawn(async move { server.run().await });
1040        wait_until_listening(&endpoint).await;
1041        let (client, _) = sapphire_ipc::connect_or_absent(&endpoint, CTX.app_name, client_info())
1042            .await
1043            .unwrap()
1044            .unwrap();
1045
1046        let dir = tempfile::tempdir().unwrap();
1047        let result: proto::WorkspaceInitResult = client
1048            .call(
1049                proto::WORKSPACE_INIT,
1050                proto::WorkspaceInitParams {
1051                    dir: dir.path().to_owned(),
1052                },
1053            )
1054            .await
1055            .unwrap();
1056        assert!(result.created);
1057        assert!(dir.path().join(format!(".{}", CTX.app_name)).is_dir());
1058
1059        // Idempotent: the second init is a success that did not create.
1060        let again: proto::WorkspaceInitResult = client
1061            .call(
1062                proto::WORKSPACE_INIT,
1063                proto::WorkspaceInitParams {
1064                    dir: dir.path().to_owned(),
1065                },
1066            )
1067            .await
1068            .unwrap();
1069        assert!(!again.created);
1070
1071        let _: serde_json::Value = client
1072            .call(sapphire_ipc::SHUTDOWN_METHOD, serde_json::json!({}))
1073            .await
1074            .unwrap();
1075        handle.await.unwrap().unwrap();
1076    }
1077
1078    #[tokio::test(flavor = "multi_thread")]
1079    async fn server_info_carries_the_app_rows() {
1080        let f = prepared();
1081        let endpoint = f.endpoint.clone();
1082        let server = AppServer::new(&CTX, "0.0.0")
1083            .endpoint(endpoint.clone())
1084            .status_rows(std::sync::Arc::new(|| {
1085                vec![StatusRow {
1086                    name: "sync".into(),
1087                    value: "enabled".into(),
1088                }]
1089            }));
1090        let handle = tokio::spawn(async move { server.run().await });
1091        wait_until_listening(&endpoint).await;
1092        let (client, _) = sapphire_ipc::connect_or_absent(&endpoint, CTX.app_name, client_info())
1093            .await
1094            .unwrap()
1095            .unwrap();
1096        let report: StatusReport = client
1097            .call(
1098                sapphire_backend::protocol::SERVER_INFO,
1099                serde_json::json!({}),
1100            )
1101            .await
1102            .unwrap();
1103        assert!(report.running);
1104        assert_eq!(report.app.len(), 1);
1105        assert_eq!(report.app[0].name, "sync");
1106
1107        let _: serde_json::Value = client
1108            .call(sapphire_ipc::SHUTDOWN_METHOD, serde_json::json!({}))
1109            .await
1110            .unwrap();
1111        handle.await.unwrap().unwrap();
1112    }
1113}