sapphire-framework-server 0.19.0

App server skeleton for sapphire-framework: owns a workspace's cache and serves it over IPC
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
//! The app server skeleton.
//!
//! An application builds one of these, adds its own methods, and runs it. Everything a
//! sapphire app needs on the server side — owning its workspace, answering `workspace.*`,
//! pushing events — is here. A server serves one workspace at a time (#215): see
//! [`Current`].
//!
//! See `docs/superpowers/specs/2026-09-16-process-architecture-design.md` §4.
//!
//! ```rust,ignore
//! static CTX: AppContext = AppContext::new("sapphire-journal");
//!
//! AppServer::new(&CTX, env!("CARGO_PKG_VERSION"))
//!     .extend(|router| router.method("journal.create_entry", create_entry))
//!     .run()
//!     .await?;
//! ```
//!
//! Application methods are named `<app>.<method>`. The framework owns `workspace.*` and
//! `server.*`; anything else is the application's.

#![warn(missing_docs)]

use std::path::PathBuf;
use std::sync::Arc;
use std::time::Duration;

use sapphire_backend::protocol as proto;
use sapphire_framework_service::ServiceSpec;
use sapphire_ipc::{Endpoint, ManagedBy, Router, ServerInfo, serve};
use sapphire_workspace::AppContext;

/// How long a server's shutdown waits for its open connections to wind down on their own.
///
/// The shutdown acknowledgement is one of those connections; a moment is all a well-behaved
/// client needs. Whatever still holds on after this is cancelled, so a connection kept open
/// past shutdown cannot pin the router — and through it the sync runtime's replica stores —
/// after the server has answered its own shutdown call.
const SERVE_GRACE: Duration = Duration::from_secs(2);

mod command;
mod config;
mod current;
mod error;
mod events;
mod handlers;
mod host;
#[cfg(feature = "http")]
mod http;
mod selection;
pub mod sync;
#[cfg(test)]
mod test_support;

pub use command::{
    DeviceCommand, FrameworkCommand, StatusReport, StatusRow, WorkgroupCommand, WorkspaceCommand,
    WorkspaceSyncCommand, render_workspace,
};
pub use config::{HttpConfig, McpConfig, SERVER_CONFIG_FILE, ServerConfig};
pub use current::Current;
pub use error::{Error, Result};
pub use events::subscribe_method;
pub use handlers::workspace_router;
pub use host::WorkspaceHost;
pub use selection::{SELECTION_FILE, Selection, SelectionFile};
pub use sync::{BackfillTiming, BridgeConnector, SyncRuntime, SyncStatus, sync_router};

/// The MCP tools an application serves, and how (feature `mcp`).
#[cfg(feature = "mcp")]
pub use sapphire_framework_mcp as mcp;

/// An application's server.
pub struct AppServer {
    ctx: &'static AppContext,
    version: &'static str,
    endpoint: Option<Endpoint>,
    /// Where `workspace.toml` lives; `None` is the config directory's.
    selection_file: Option<PathBuf>,
    host: Arc<WorkspaceHost>,
    sync: Option<Arc<SyncRuntime>>,
    extend: Option<Box<dyn FnOnce(Router) -> Router + Send>>,
    /// The application's own status rows, shown after the framework's in `status` and in
    /// the `server.info` report.
    status_rows: Option<Arc<dyn Fn() -> Vec<StatusRow> + Send + Sync>>,
    /// The version of the application's own API, reported in the handshake.
    app_api: Option<u32>,
    /// `server.toml`'s settings, when given rather than read from the config directory.
    config: Option<ServerConfig>,
    /// Where the HTTP listener binds when `server.toml` does not say.
    #[cfg(feature = "http")]
    http_listen: Option<std::net::SocketAddr>,
    /// The application's own HTTP routes.
    #[cfg(feature = "http")]
    http_routes: Option<axum::Router>,
    /// How the HTTP routes check a token; `None` asks the bridge.
    #[cfg(feature = "http")]
    http_auth: Option<sapphire_framework_keys::AuthConfig>,
    /// The application's MCP handler, for the `mcp` subcommand and `/mcp`.
    #[cfg(feature = "mcp")]
    mcp: sapphire_framework_mcp::McpService,
}

/// The SIGTERM end of the server's select loop, in a shape every platform shares.
///
/// [`AppServer::run`]'s select arm awaits `recv()` on one of these, exactly as the
/// plan writes it for Unix. Unix backs it with the `SignalKind::terminate()`
/// stream; Windows has no SIGTERM, so there the future never resolves and the arm
/// exists for the macro's sake and never fires. Without the common shape the arm
/// would need a `#[cfg]` of its own, which tokio's `select!` rejects once the
/// attribute removes the arm.
#[cfg(unix)]
struct Sigterm(tokio::signal::unix::Signal);

/// The never-firing stand-in for the Unix `Sigterm` where there is no SIGTERM.
#[cfg(not(unix))]
struct Sigterm;

#[cfg(unix)]
impl Sigterm {
    /// Register interest in SIGTERM.
    ///
    /// Called before the listener binds, so a signal arriving the instant the
    /// socket is up is queued by tokio instead of killing the process with the
    /// default handler.
    fn new() -> Result<Self> {
        Ok(Self(tokio::signal::unix::signal(
            tokio::signal::unix::SignalKind::terminate(),
        )?))
    }

    /// Wait for the next SIGTERM.
    ///
    /// Never returns `None`: the stream is infinite, as its documentation states.
    async fn recv(&mut self) {
        self.0.recv().await;
    }
}

#[cfg(not(unix))]
impl Sigterm {
    /// A future that is never ready — the arm awaits it for the macro's sake only.
    ///
    /// There is no `new`: this platform has no SIGTERM to register interest in, so
    /// the loop binds the unit value directly.
    async fn recv(&mut self) {
        std::future::pending::<()>().await
    }
}

impl AppServer {
    /// A server for `ctx`'s application, reporting `version` in its handshake.
    pub fn new(ctx: &'static AppContext, version: &'static str) -> AppServer {
        AppServer {
            ctx,
            version,
            endpoint: None,
            selection_file: None,
            host: Arc::new(WorkspaceHost::new(ctx)),
            sync: None,
            extend: None,
            status_rows: None,
            app_api: None,
            config: None,
            #[cfg(feature = "http")]
            http_listen: None,
            #[cfg(feature = "http")]
            http_routes: None,
            #[cfg(feature = "http")]
            http_auth: None,
            #[cfg(feature = "mcp")]
            mcp: sapphire_framework_mcp::McpService::framework(),
        }
    }

    /// The application this server serves, as its [`AppContext`] names it.
    ///
    /// [`FrameworkCommand`](crate::FrameworkCommand) reads it to build the CLI's endpoint,
    /// so an application never passes its own name twice.
    pub fn app_name(&self) -> &'static str {
        self.ctx.app_name
    }

    /// Listen somewhere other than the application's default endpoint. Used by tests.
    pub fn endpoint(mut self, endpoint: Endpoint) -> AppServer {
        self.endpoint = Some(endpoint);
        self
    }

    /// Report `version` as the application's own API version in the handshake: the major
    /// of the application's API crate, which carries the methods it adds with
    /// [`extend`](Self::extend). A client that calls those methods names the version it
    /// expects, and the handshake refuses a server that speaks another.
    pub fn app_api(mut self, version: u32) -> AppServer {
        self.app_api = Some(version);
        self
    }

    /// Use `config` rather than reading `<config dir>/server.toml`: for fixtures.
    pub fn config(mut self, config: ServerConfig) -> AppServer {
        self.config = Some(config);
        self
    }

    /// Where the HTTP listener binds unless `server.toml` says otherwise: the application's
    /// own port. Without it, a host that serves anything over HTTP names the address in
    /// `[http] listen`.
    #[cfg(feature = "http")]
    pub fn http_listen(mut self, addr: std::net::SocketAddr) -> AppServer {
        self.http_listen = Some(addr);
        self
    }

    /// Serve the application's own HTTP routes on the server's listener, behind the same
    /// external-device token as `/mcp`. The routes are served whenever they are given;
    /// `/mcp` only when `server.toml` turns it on.
    #[cfg(feature = "http")]
    pub fn http(mut self, routes: axum::Router) -> AppServer {
        self.http_routes = Some(routes);
        self
    }

    /// Check HTTP tokens with `auth` rather than with the bridge: for fixtures.
    #[cfg(feature = "http")]
    pub fn http_auth(mut self, auth: sapphire_framework_keys::AuthConfig) -> AppServer {
        self.http_auth = Some(auth);
        self
    }

    /// Answer MCP with the application's own handler, rather than the framework's tools
    /// alone: on stdio for the `mcp` subcommand, and at `/mcp` when `server.toml` turns it
    /// on.
    #[cfg(feature = "mcp")]
    pub fn mcp(mut self, service: sapphire_framework_mcp::McpService) -> AppServer {
        self.mcp = service;
        self
    }

    /// Serve the application's MCP tools on this process's stdio, until the agent closes
    /// it: the `mcp` subcommand.
    ///
    /// This is the client side: the tools reach the running server over its IPC endpoint,
    /// as the CLI does, and nothing here starts one.
    #[cfg(feature = "mcp")]
    pub async fn serve_mcp_stdio(self, version: &'static str) -> Result<()> {
        let endpoint = match self.endpoint {
            Some(e) => e,
            None => Endpoint::for_app(self.ctx.app_name)?,
        };
        let ctx = sapphire_framework_mcp::ToolContext::dial(
            self.ctx.app_name,
            version,
            self.app_api,
            endpoint,
        );
        self.mcp
            .serve_stdio(ctx)
            .await
            .map_err(|e| Error::Mcp(e.to_string()))
    }

    /// Keep the selected workspace (`workspace.toml`) at `path` rather than in the
    /// application's config directory: for fixtures that run several hosts in one process.
    pub fn selection_file(mut self, path: PathBuf) -> AppServer {
        self.selection_file = Some(path);
        self
    }

    /// Serve `sync.enable`, `sync.disable`, `sync.map` and `sync.status`, and keep a replica
    /// of the workspace in step with its files while it is synced.
    ///
    /// Without this the server has no sync at all: an application that does not call it
    /// never talks to the bridge. The runtime is built by the caller because it needs the
    /// bridge connection, which is the caller's to open and to close.
    pub fn sync(mut self, runtime: Arc<SyncRuntime>) -> AppServer {
        // The runtime re-indexes what a session writes, and the index belongs to this host:
        // tell it where the workspace lives before anything can arrive.
        runtime.set_host(Arc::clone(&self.host));
        self.sync = Some(runtime);
        self
    }

    /// Sync through the host's `sapphire-bridge`: [`sync`](Self::sync) with a runtime that
    /// reaches the bridge itself, and reaches it again whenever it is lost (#244).
    ///
    /// [`run`](Self::run) makes the first attempt. No bridge running is not fatal — the
    /// server serves without sync and picks the bridge up once it starts, and `sync.*`
    /// answers that it is not connected meanwhile — but any other failure, such as a bridge
    /// of another API version, stops the start.
    pub fn sync_via_bridge(self) -> Result<AppServer> {
        let runtime = SyncRuntime::connecting(
            self.ctx,
            BridgeConnector::standard(self.ctx.app_name, self.version),
            std::env::current_exe()?,
            ManagedBy::Service,
        );
        Ok(self.sync(Arc::new(runtime)))
    }

    /// The application's own rows for the status report: shown after the framework's
    /// `running` / `version` / `pid` / `managed_by` lines.
    ///
    /// The closure is called once per report, so an application's rows may read live
    /// state; the CLI's `status` and the IPC `server.info` method render the same call's
    /// output.
    pub fn status_rows(mut self, rows: Arc<dyn Fn() -> Vec<StatusRow> + Send + Sync>) -> AppServer {
        self.status_rows = Some(rows);
        self
    }

    /// What this application's service is: the arguments a service manager starts it with.
    ///
    /// `["serve"]`: a service manager starts the executable directly, and the executable's
    /// bare invocation is `serve` — the subcommand-less default of
    /// [`FrameworkCommand::Serve`](crate::FrameworkCommand::Serve). A CLI that wants its
    /// service installed hands this to
    /// [`ServiceCommand`](sapphire_framework_service::ServiceCommand).
    pub fn service_spec(&self) -> ServiceSpec {
        ServiceSpec {
            app_name: self.ctx.app_name,
            description: format!("{} server {}", self.ctx.app_name, self.version),
            args: vec!["serve".to_owned()],
            post_install: None,
        }
    }

    /// Add the application's own methods.
    pub fn extend(mut self, f: impl FnOnce(Router) -> Router + Send + 'static) -> AppServer {
        self.extend = Some(Box::new(f));
        self
    }

    /// The workspace this server has open. An application's own handlers use it to reach
    /// the workspace the same way the framework's do: [`WorkspaceHost::backend`].
    pub fn host(&self) -> &Arc<WorkspaceHost> {
        &self.host
    }

    /// Listen until told to stop, or until a signal arrives.
    pub async fn run(self) -> Result<()> {
        let AppServer {
            ctx,
            version,
            endpoint,
            selection_file,
            host,
            sync,
            extend,
            status_rows,
            app_api,
            config,
            #[cfg(feature = "http")]
            http_listen,
            #[cfg(feature = "http")]
            http_routes,
            #[cfg(feature = "http")]
            http_auth,
            #[cfg(feature = "mcp")]
            mcp,
        } = self;

        let endpoint = match endpoint {
            Some(e) => e,
            None => Endpoint::for_app(ctx.app_name)?,
        };
        // A server is always-on from here on: only `serve` and the service manager start
        // one, and the service manager starts it for keeps. There is no spawned mode left
        // to report.
        let info = ServerInfo {
            version: version.to_owned(),
            api: proto::API_VERSION,
            app_api,
            pid: std::process::id(),
            managed_by: ManagedBy::Service,
        };

        // The app's log file, held for as long as this server serves: the guard's
        // drop flushes the writer thread, so the last lines of a clean shutdown land
        // in the file. The subscriber itself was installed by `ctx.init`; this is what
        // routes the file layer at `<data dir>/logs/`.
        let _log = sapphire_workspace::logging::install(ctx)?;

        let config = match config {
            Some(config) => config,
            None => ServerConfig::load_for_app(ctx)?,
        };
        #[cfg(not(feature = "mcp"))]
        if config.mcp.http {
            tracing::warn!(
                "server.toml turns MCP over HTTP on, but this build of {} has no MCP",
                ctx.app_name
            );
        }

        let (stop_tx, mut stop_rx) = tokio::sync::watch::channel(false);

        // The first attempt to reach the bridge, before the selected workspace comes back
        // and asks it for sync.
        if let Some(runtime) = &sync {
            runtime.connect().await?;
        }

        let file = match selection_file {
            Some(path) => SelectionFile::at(path),
            None => SelectionFile::for_app(ctx),
        };
        let current = Arc::new(Current::new(ctx, Arc::clone(&host), sync.clone(), file));
        // Back to the workspace this host had, before the first client can ask for it.
        let restoring = current.restore().await;

        let mut router = subscribe_method(
            Arc::clone(&host),
            current::current_methods(Arc::clone(&current), workspace_router(Arc::clone(&current))),
        );
        if sync.is_some() {
            // `sync_router` is applied *under* the application's own methods so a later
            // `extend` can still replace one, and after `subscribe_method` so the
            // `workspace.*` namespace is complete.
            router = sync_router(Arc::clone(&current), router);
        }
        // `server.info` answers the typed [`StatusReport`] — the same shape the CLI's
        // `status` renders — so the CLI and a future GUI read one record. The rows come
        // from the application's builder, called once per report.
        router = router
            .method(proto::SERVER_INFO, {
                let info = info.clone();
                let status_rows = status_rows.clone();
                move |_| {
                    let info = info.clone();
                    let status_rows = status_rows.clone();
                    async move {
                        let app = status_rows.as_ref().map(|rows| rows()).unwrap_or_default();
                        let report = StatusReport {
                            running: true,
                            version: Some(info.version),
                            pid: Some(info.pid),
                            managed_by: Some(match info.managed_by {
                                ManagedBy::Service => proto::ManagedBy::Service,
                                ManagedBy::Spawned => proto::ManagedBy::Spawned,
                            }),
                            app,
                        };
                        serde_json::to_value(report)
                            .map_err(|e| sapphire_ipc::RpcError::internal(e.to_string()))
                    }
                }
            })
            .method(sapphire_ipc::SHUTDOWN_METHOD, {
                let stop_tx = stop_tx.clone();
                move |_| {
                    let stop_tx = stop_tx.clone();
                    async move {
                        let _ = stop_tx.send(true);
                        serde_json::to_value(proto::Ack {})
                            .map_err(|e| sapphire_ipc::RpcError::internal(e.to_string()))
                    }
                }
            });
        if let Some(extend) = extend {
            router = extend(router);
        }
        let router = Arc::new(router);

        // Registered before the bind, so a SIGTERM arriving the instant the socket is up
        // cannot fall through to the default handler and kill the process. SIGINT is
        // listened to only through `ctrl_c` (which swallows the default handler on both
        // platforms): a Unix `SignalKind::interrupt()` stream would double-fire for ^C.
        #[cfg(unix)]
        let mut sigterm = Sigterm::new()?;
        #[cfg(not(unix))]
        let mut sigterm = Sigterm;

        #[cfg(unix)]
        let listener = sapphire_ipc::bind(&endpoint).await?;
        #[cfg(windows)]
        let mut listener = sapphire_ipc::bind(&endpoint)?;

        let mut connections = tokio::task::JoinSet::new();

        // The HTTP listener, when anything is served over it. Started once the IPC socket
        // is bound, for the same reason as the sync tasks below. `/mcp`'s tools reach this
        // server the way the `mcp` subcommand's do — over IPC — on an in-process connection
        // served like any other.
        #[cfg(feature = "http")]
        let http_stop = tokio_util::sync::CancellationToken::new();
        #[cfg(feature = "http")]
        let _http = {
            let mut routes = http_routes;
            #[cfg(feature = "mcp")]
            if config.mcp.http {
                let (ours, theirs) = sapphire_ipc::Connection::pair();
                {
                    let router = Arc::clone(&router);
                    let info = info.clone();
                    let app = ctx.app_name;
                    connections.spawn(async move {
                        let _ = serve(theirs, router, app, info).await;
                    });
                }
                let client_info = sapphire_ipc::ClientInfo {
                    kind: sapphire_framework_mcp::CLIENT_KIND.to_owned(),
                    version: version.to_owned(),
                    api: proto::API_VERSION,
                    app_api,
                    pid: std::process::id(),
                };
                let (client, _) =
                    sapphire_ipc::Client::handshake(ours, ctx.app_name, client_info).await?;
                let tools = sapphire_framework_mcp::ToolContext::connected(
                    ctx.app_name,
                    version,
                    Arc::new(client),
                );
                let mcp_routes =
                    mcp.http_router(tools, &config.http.allowed_hosts, http_stop.child_token());
                routes = Some(match routes {
                    Some(routes) => routes.merge(mcp_routes),
                    None => mcp_routes,
                });
            }
            match (routes, config.http.listen.or(http_listen)) {
                (None, _) => None,
                (Some(_), None) => {
                    tracing::error!(
                        "nothing to bind HTTP to: set `[http] listen` in {SERVER_CONFIG_FILE}"
                    );
                    None
                }
                (Some(routes), Some(addr)) => {
                    let auth = http_auth.unwrap_or_else(|| {
                        sapphire_framework_keys::AuthConfig::new(Arc::new(
                            sapphire_framework_keys::BridgeVerifier::new(ctx.app_name, version),
                        ))
                    });
                    http::start(addr, routes, auth, http_stop.clone()).await
                }
            }
        };

        // The watcher, the bridge announcement loop, the dialer and the bridge connection, if
        // sync is on. Started only once the socket is bound, so an early `?` above cannot
        // leave tasks running for a server that never served. All of them are allowed to
        // fail: only sync stops when they do, and the app server keeps serving files
        // (spec §10). They are aborted with the server.
        let _sync_tasks = match &sync {
            Some(runtime) => {
                let driver = Arc::clone(runtime);
                let announcements = tokio::spawn(async move {
                    if let Err(err) = driver.run().await {
                        tracing::warn!("the bridge announcement loop ended: {err}");
                    }
                });
                let changing = Arc::clone(runtime);
                let watching = tokio::spawn(async move {
                    if let Err(err) = changing.watch_changes().await {
                        tracing::warn!("the file watcher ended: {err}");
                    }
                });
                // The dialer is what keeps a session open after the initial exchange, so a
                // commit reaches a peer without waiting for the next one (spec §4.2).
                let dialling = Arc::clone(runtime);
                let dialling = tokio::spawn(async move {
                    if let Err(err) = dialling.dial_loop().await {
                        tracing::warn!("the live dial loop ended: {err}");
                    }
                });
                // Reaching the bridge again whenever it is lost (#244).
                let connected = tokio::spawn(Arc::clone(runtime).keep_connected());
                Some([announcements, watching, dialling, connected])
            }
            None => None,
        };

        loop {
            tokio::select! {
                changed = stop_rx.changed() => {
                    if changed.is_err() || *stop_rx.borrow() {
                        break;
                    }
                }
                _ = tokio::signal::ctrl_c() => {
                    tracing::info!("interrupted; shutting down");
                    break;
                }
                _ = sigterm.recv() => {
                    tracing::info!("terminated; shutting down");
                    break;
                }
                accepted = listener.accept() => {
                    let conn = accepted?;
                    let router = Arc::clone(&router);
                    let app = ctx.app_name;
                    let info = info.clone();
                    connections.spawn(async move {
                        let _ = serve(conn, router, app, info).await;
                    });
                }
            }
        }

        if let Some(restoring) = restoring {
            restoring.abort();
        }
        // HTTP first: its sessions hold a connection to this server, which the reaping
        // below waits for.
        #[cfg(feature = "http")]
        {
            http_stop.cancel();
            if let Some((_, mut task)) = _http
                && tokio::time::timeout(SERVE_GRACE, &mut task).await.is_err()
            {
                tracing::debug!("the HTTP listener did not stop in time");
                task.abort();
            }
        }
        if let Some(tasks) = _sync_tasks {
            // Each loop pins the sync runtime, and with it the replica stores. An aborted task
            // is only dropped once its current poll returns — which, mid-scan, can take a
            // while — so wait for that rather than return with a loop still holding a store
            // the next server in this process would fail to open (#235).
            for task in tasks {
                task.abort();
                let _ = task.await;
            }
        }
        if let Some(runtime) = &sync {
            // The first dials after an enable pin the runtime the same way, and so do the
            // inbound sessions, the live-session readers and the embedding passes.
            runtime.stop_dials().await;
            runtime.stop_background().await;
            // Close every live sync session. A session's reader task holds the replica, and
            // the session itself sits in the runtime's table until it is cleared, so leaving
            // one open pins the runtime — and the redb replica stores in it — after the
            // server is gone (spec §2.2: cancellation is disconnection).
            runtime.drop_connections().await;
        }
        host.close();
        drop(listener); // removes the socket file on Unix

        // Reap the per-connection serve tasks. Each one pins the router, the router pins
        // the sync runtime, and the runtime's replica stores are redb databases that stay
        // locked until the last pin is dropped — a server that left them running would
        // lock its own successor out of its state (spec §2.2: cancellation is
        // disconnection). Connections get a grace period to wind down on their own — the
        // shutdown acknowledgement among them — then the rest are cancelled: a client
        // that keeps its connection open past shutdown is holding a server that is gone.
        let _ = tokio::time::timeout(SERVE_GRACE, async {
            while connections.join_next().await.is_some() {}
        })
        .await;
        connections.abort_all();
        while connections.join_next().await.is_some() {}
        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use sapphire_ipc::{ClientInfo, Endpoint, ManagedBy};
    use sapphire_workspace::{AppContext, AppKind};
    use std::ffi::OsString;

    use crate::test_support;

    static CTX: AppContext = AppContext::new("sapphire-appservertest");

    /// The env vars `init_ctx` writes, in the order the guard restores them.
    const DIR_VARS: [&str; 3] = [
        "SAPPHIRE_APPSERVERTEST_CACHE_DIR",
        "SAPPHIRE_APPSERVERTEST_DATA_DIR",
        "SAPPHIRE_APPSERVERTEST_CONFIG_DIR",
    ];

    fn client_info() -> ClientInfo {
        ClientInfo {
            kind: "test".into(),
            version: "0.0.0".into(),
            api: sapphire_backend::protocol::API_VERSION,
            app_api: None,
            pid: std::process::id(),
        }
    }

    /// Point the context's directories at `tmp` and restore the previous values (present
    /// or absent) when dropped — including while unwinding from a panic. Without the
    /// unconditional restore, a panicking assertion would leave the variables pointing at
    /// a temp directory the test then deletes, and the context of a later test would
    /// resolve into the void.
    struct EnvGuard {
        previous: [Option<OsString>; 3],
        _lock: std::sync::MutexGuard<'static, ()>,
    }

    impl EnvGuard {
        /// Write the three directory vars while holding the environment lock.
        fn set(lock: std::sync::MutexGuard<'static, ()>, tmp: &std::path::Path) -> EnvGuard {
            let previous = DIR_VARS.map(std::env::var_os);
            let dirs = ["cache", "data", "config"].map(|cat| tmp.join(cat));
            // SAFETY (via `test_support::set`): `lock` serialises every read and write of
            // the process environment in this test binary — the `host`, `handlers` and
            // `events` modules' tests share the same lock — and it is held until `drop`
            // has restored the old values.
            for (name, dir) in DIR_VARS.iter().zip(dirs) {
                test_support::set(name, &dir);
            }
            EnvGuard {
                previous,
                _lock: lock,
            }
        }
    }

    impl Drop for EnvGuard {
        fn drop(&mut self) {
            // SAFETY: `self._lock` still serialises the environment; it is dropped only
            // after this method returns.
            for (name, previous) in DIR_VARS.iter().zip(self.previous.iter_mut()) {
                match previous.take() {
                    Some(value) => unsafe { std::env::set_var(name, value) },
                    None => test_support::remove(name),
                }
            }
        }
    }

    /// Everything one test needs, held for the test's whole body.
    ///
    /// `_tmp` is declared before `_env` so the scratch tree is deleted while the
    /// environment lock is still held: a sibling test that wakes on the lock must never
    /// observe the tree mid-deletion, nor env vars pointing at a deleted directory.
    struct Fixture {
        _tmp: tempfile::TempDir,
        _env: EnvGuard,
        endpoint: Endpoint,
    }

    /// A listening endpoint in a scratch directory, with the context's directories
    /// pointed at the same scratch tree.
    ///
    /// The caller must keep the fixture (and with it the environment lock) alive for the
    /// whole test: the static [`CTX`] is first-writer-wins, so while one test runs, every
    /// other test that would re-point the context's directories must wait.
    fn prepared() -> Fixture {
        let lock = test_support::lock();
        let tmp = tempfile::tempdir().unwrap();
        let env = EnvGuard::set(lock, tmp.path());
        CTX.init(AppKind::Server);
        let endpoint = Endpoint::in_dir("sapphire-appservertest", tmp.path().to_path_buf());
        Fixture {
            _tmp: tmp,
            _env: env,
            endpoint,
        }
    }

    /// Wait until something is listening on `endpoint`.
    ///
    /// `tokio::spawn(server.run())` only schedules the server; without this wait a fast
    /// `connect_or_absent` probe can run before `run` has bound the socket, and with
    /// nothing listening that single unlucky probe is the whole test failing.
    async fn wait_until_listening(endpoint: &Endpoint) {
        let deadline = tokio::time::Instant::now() + Duration::from_secs(5);
        while !sapphire_ipc::probe(endpoint).await.unwrap() {
            assert!(
                tokio::time::Instant::now() < deadline,
                "the server never started listening"
            );
            tokio::time::sleep(Duration::from_millis(10)).await;
        }
    }

    /// A running server writes its log file: the framework's `logging` module
    /// routes the app's log to `<data dir>/logs/app.log`, and `run()` holds the
    /// guard for as long as it serves. The event is emitted by this test — the
    /// subscriber and the file layer are the process's, installed by `CTX.init`
    /// and `run` — so what lands in the file is exactly what a journald-less
    /// host would otherwise never see.
    #[tokio::test(flavor = "multi_thread")]
    async fn a_running_server_writes_its_log_file() {
        let f = prepared();
        let endpoint = f.endpoint.clone();
        let server = AppServer::new(&CTX, "0.0.0").endpoint(endpoint.clone());
        let handle = tokio::spawn(async move { server.run().await });
        wait_until_listening(&endpoint).await;

        tracing::info!("the server is serving, and this line belongs in its log");

        let (client, _) = sapphire_ipc::connect_or_absent(&endpoint, CTX.app_name, client_info())
            .await
            .unwrap()
            .expect("the server is listening");
        let _: serde_json::Value = client
            .call(sapphire_ipc::SHUTDOWN_METHOD, serde_json::json!({}))
            .await
            .unwrap();
        // The guard flushes as `run` unwinds; awaiting it is what makes the
        // file complete before it is read.
        handle.await.unwrap().unwrap();

        let text = std::fs::read_to_string(CTX.log_dir().join("app.log")).unwrap();
        assert!(
            text.contains("the server is serving, and this line belongs in its log"),
            "{text}"
        );
    }

    #[tokio::test(flavor = "multi_thread")]
    async fn a_server_reports_itself_as_service_managed() {
        let f = prepared();
        let endpoint = f.endpoint.clone();
        let server = AppServer::new(&CTX, "0.0.0").endpoint(endpoint.clone());
        let handle = tokio::spawn(async move { server.run().await });
        wait_until_listening(&endpoint).await;

        let (client, info) =
            sapphire_ipc::connect_or_absent(&endpoint, CTX.app_name, client_info())
                .await
                .unwrap()
                .expect("the server is listening");
        assert_eq!(info.managed_by, ManagedBy::Service);

        let _: serde_json::Value = client
            .call(sapphire_ipc::SHUTDOWN_METHOD, serde_json::json!({}))
            .await
            .unwrap();
        handle.await.unwrap().unwrap();
    }

    #[tokio::test(flavor = "multi_thread")]
    async fn a_server_reports_its_app_api_and_the_handshake_gates_on_it() {
        let f = prepared();
        let endpoint = f.endpoint.clone();
        let server = AppServer::new(&CTX, "0.0.0")
            .endpoint(endpoint.clone())
            .app_api(7);
        let handle = tokio::spawn(async move { server.run().await });
        wait_until_listening(&endpoint).await;

        let wants = |app_api| ClientInfo {
            app_api,
            ..client_info()
        };
        let err = sapphire_ipc::connect_or_absent(&endpoint, CTX.app_name, wants(Some(8)))
            .await
            .unwrap_err();
        assert!(
            matches!(
                err,
                sapphire_ipc::Error::AppApiVersionMismatch {
                    running: Some(7),
                    ours: 8,
                    ..
                }
            ),
            "{err:?}"
        );

        let (client, info) =
            sapphire_ipc::connect_or_absent(&endpoint, CTX.app_name, wants(Some(7)))
                .await
                .unwrap()
                .expect("the server is listening");
        assert_eq!(info.app_api, Some(7));

        let _: serde_json::Value = client
            .call(sapphire_ipc::SHUTDOWN_METHOD, serde_json::json!({}))
            .await
            .unwrap();
        handle.await.unwrap().unwrap();
    }

    #[tokio::test(flavor = "multi_thread")]
    async fn a_running_server_answers_server_info() {
        let f = prepared();
        let endpoint = f.endpoint.clone();

        let server = AppServer::new(&CTX, "1.2.3").endpoint(endpoint.clone());
        let handle = tokio::spawn(async move { server.run().await });
        wait_until_listening(&endpoint).await;

        let (client, info) = sapphire_ipc::connect_or_absent(
            &endpoint,
            CTX.app_name,
            ClientInfo {
                version: "1.2.3".into(),
                ..client_info()
            },
        )
        .await
        .unwrap()
        .expect("the server is listening");
        assert_eq!(info.version, "1.2.3");

        // `server.info` answers the whole typed report, not the bare handshake record:
        // the CLI reads one shape, and so would a GUI.
        let report: StatusReport = client
            .call(
                sapphire_backend::protocol::SERVER_INFO,
                serde_json::json!({}),
            )
            .await
            .unwrap();
        assert!(report.running);
        assert_eq!(report.version.as_deref(), Some("1.2.3"));
        assert_eq!(report.pid, Some(std::process::id()));
        assert_eq!(report.managed_by, Some(proto::ManagedBy::Service));
        assert!(report.app.is_empty(), "no status rows were configured");

        let _: serde_json::Value = client
            .call(sapphire_ipc::SHUTDOWN_METHOD, serde_json::json!({}))
            .await
            .unwrap();
        handle.await.unwrap().unwrap();
    }

    #[tokio::test(flavor = "multi_thread")]
    async fn shutdown_stops_the_server() {
        let f = prepared();
        let endpoint = f.endpoint.clone();

        let server = AppServer::new(&CTX, "0.0.0").endpoint(endpoint.clone());
        let handle = tokio::spawn(async move { server.run().await });
        wait_until_listening(&endpoint).await;

        let (client, _) = sapphire_ipc::connect_or_absent(&endpoint, CTX.app_name, client_info())
            .await
            .unwrap()
            .expect("the server is listening");
        let _: serde_json::Value = client
            .call(sapphire_ipc::SHUTDOWN_METHOD, serde_json::json!({}))
            .await
            .unwrap();

        tokio::time::timeout(Duration::from_secs(5), handle)
            .await
            .expect("the server must stop")
            .unwrap()
            .unwrap();
        assert!(!sapphire_ipc::probe(&endpoint).await.unwrap());
    }

    #[tokio::test(flavor = "multi_thread")]
    async fn an_application_can_add_its_own_methods() {
        let f = prepared();
        let endpoint = f.endpoint.clone();

        let server = AppServer::new(&CTX, "0.0.0")
            .endpoint(endpoint.clone())
            .extend(|r| {
                r.method("sapphire-appservertest.greet", |_| async move {
                    Ok(serde_json::json!("hello"))
                })
            });
        let handle = tokio::spawn(async move { server.run().await });
        wait_until_listening(&endpoint).await;

        let (client, _) = sapphire_ipc::connect_or_absent(&endpoint, CTX.app_name, client_info())
            .await
            .unwrap()
            .expect("the server is listening");
        let greeting: String = client
            .call("sapphire-appservertest.greet", serde_json::json!({}))
            .await
            .unwrap();
        assert_eq!(greeting, "hello");

        let _: serde_json::Value = client
            .call(sapphire_ipc::SHUTDOWN_METHOD, serde_json::json!({}))
            .await
            .unwrap();
        handle.await.unwrap().unwrap();
    }

    #[tokio::test(flavor = "multi_thread")]
    async fn workspace_init_creates_the_marker_and_tells_the_registry() {
        let f = prepared();
        let endpoint = f.endpoint.clone();
        let server = AppServer::new(&CTX, "0.0.0").endpoint(endpoint.clone());
        let handle = tokio::spawn(async move { server.run().await });
        wait_until_listening(&endpoint).await;
        let (client, _) = sapphire_ipc::connect_or_absent(&endpoint, CTX.app_name, client_info())
            .await
            .unwrap()
            .unwrap();

        let dir = tempfile::tempdir().unwrap();
        let result: proto::WorkspaceInitResult = client
            .call(
                proto::WORKSPACE_INIT,
                proto::WorkspaceInitParams {
                    dir: dir.path().to_owned(),
                },
            )
            .await
            .unwrap();
        assert!(result.created);
        assert!(dir.path().join(format!(".{}", CTX.app_name)).is_dir());

        // Idempotent: the second init is a success that did not create.
        let again: proto::WorkspaceInitResult = client
            .call(
                proto::WORKSPACE_INIT,
                proto::WorkspaceInitParams {
                    dir: dir.path().to_owned(),
                },
            )
            .await
            .unwrap();
        assert!(!again.created);

        let _: serde_json::Value = client
            .call(sapphire_ipc::SHUTDOWN_METHOD, serde_json::json!({}))
            .await
            .unwrap();
        handle.await.unwrap().unwrap();
    }

    #[tokio::test(flavor = "multi_thread")]
    async fn server_info_carries_the_app_rows() {
        let f = prepared();
        let endpoint = f.endpoint.clone();
        let server = AppServer::new(&CTX, "0.0.0")
            .endpoint(endpoint.clone())
            .status_rows(std::sync::Arc::new(|| {
                vec![StatusRow {
                    name: "sync".into(),
                    value: "enabled".into(),
                }]
            }));
        let handle = tokio::spawn(async move { server.run().await });
        wait_until_listening(&endpoint).await;
        let (client, _) = sapphire_ipc::connect_or_absent(&endpoint, CTX.app_name, client_info())
            .await
            .unwrap()
            .unwrap();
        let report: StatusReport = client
            .call(
                sapphire_backend::protocol::SERVER_INFO,
                serde_json::json!({}),
            )
            .await
            .unwrap();
        assert!(report.running);
        assert_eq!(report.app.len(), 1);
        assert_eq!(report.app[0].name, "sync");

        let _: serde_json::Value = client
            .call(sapphire_ipc::SHUTDOWN_METHOD, serde_json::json!({}))
            .await
            .unwrap();
        handle.await.unwrap().unwrap();
    }
}