Skip to main content

liminal_server/server/
runtime.rs

1use std::path::Path;
2use std::sync::Arc;
3
4use crate::ServerError;
5use crate::cluster::{self, ClusterHandle};
6use crate::config::file::load_config;
7use crate::config::types::{ClusterConfig, ServiceProfile};
8use crate::health::{ReadinessState, SharedReadinessState, start_health_server};
9use crate::server::connection::ConnectionSupervisor;
10use crate::server::connection::WebSocketListener;
11use crate::server::connection::services::{
12    ChannelCluster, LiminalConnectionServices, build_connection_services,
13};
14use crate::server::listener::ServerListener;
15use crate::server::shutdown::{ShutdownHandle, register_signal_handlers, run_shutdown_sequence};
16
17/// Starts the server deployment wrapper for the supplied configuration path.
18///
19/// # Errors
20///
21/// Returns [`ServerError`] when a later server lifecycle phase fails.
22pub fn run(config_path: &Path) -> Result<(), ServerError> {
23    if config_path.as_os_str().is_empty() {
24        return Err(ServerError::ConfigLoad {
25            message: "configuration path is empty".to_owned(),
26        });
27    }
28
29    let config = load_config(config_path)?;
30
31    // Enable metrics for this process before the health server accepts scrapes,
32    // so `/metrics` renders the server families. Standalone liminal library users
33    // never call this, so the registry gate stays off for them.
34    crate::metrics::init();
35
36    let readiness = SharedReadinessState::new(ReadinessState::default());
37    let health_server = start_health_server(config.health_listen_address, readiness.clone())?;
38    let shutdown_handle = ShutdownHandle::new();
39    let signal_registration = register_signal_handlers(shutdown_handle.clone())?;
40
41    // The configured [auth] token must ride along here: these call sites build
42    // services themselves (full mode reaches the shared channel cluster first;
43    // the worker front door builds no cluster at all) and so cannot use
44    // `from_config`, which is the only other place the token is wired.
45    let auth_token = config
46        .auth
47        .as_ref()
48        .map(|auth| auth.token.clone().into_bytes());
49
50    // D2: the service profile selects which connection-services stack is built.
51    // Full mode is byte-for-byte the previous construction path (build services,
52    // reach the shared channel cluster, start clustering when configured). The
53    // worker front door constructs the connection supervisor over the
54    // capability-scoped adapter and NOTHING else — no channel/conversation/haematite
55    // services, and therefore no distribution cluster (config validation rejects a
56    // `[cluster]` section under this profile, so none can be present here).
57    let (connection_supervisor, cluster_handle) = match config.services.profile()? {
58        ServiceProfile::Full => {
59            let services = Arc::new(LiminalConnectionServices::from_config(&config)?);
60            // Publish the participant's refused-load record onto the health
61            // endpoint. It happens HERE and not at `start_health_server`
62            // because the endpoint binds before the participant exists —
63            // liveness has to be answerable while the rest of the server is
64            // still being built. Boot has already recorded every conversation
65            // it refused by the time `from_config` returns, so the first scrape
66            // after this line sees the complete boot answer. The worker-front-
67            // door profile configures no participant and installs nothing, and
68            // the route reports that rather than an empty refusal set.
69            if let Some(record) = services.unloadable_conversation_record() {
70                health_server.install_unloadable_record(record);
71            }
72            let channel_cluster = services.channel_cluster().clone();
73            let connection_supervisor = ConnectionSupervisor::with_fatal_shutdown(
74                services,
75                auth_token,
76                config.limits,
77                shutdown_handle.clone(),
78            )?;
79
80            // SRV-005: start clustering on the channel-supervisor scheduler when a
81            // [cluster] section is configured. The returned handle owns the inbound
82            // distribution listener and the membership poll loop; it must outlive the
83            // server and is torn down in the shutdown sequence below.
84            readiness.set_cluster_configured(config.cluster.is_some());
85            let cluster_handle = match config.cluster.as_ref() {
86                Some(cluster_config) => {
87                    Some(start_cluster(&channel_cluster, cluster_config, &readiness)?)
88                }
89                None => None,
90            };
91            (connection_supervisor, cluster_handle)
92        }
93        ServiceProfile::WorkerFrontDoor => {
94            let services = build_connection_services(&config)?;
95            let connection_supervisor = ConnectionSupervisor::with_fatal_shutdown(
96                services,
97                auth_token,
98                config.limits,
99                shutdown_handle.clone(),
100            )?;
101            readiness.set_cluster_configured(false);
102            (connection_supervisor, None)
103        }
104    };
105
106    // P0 #56 R4: readiness now reports whether the server can ADMIT, not just
107    // whether it finished starting. It is installed here rather than at
108    // `SharedReadinessState::new` above because the health endpoint binds before
109    // the supervisor exists — liveness has to be answerable while the rest of
110    // the server is still being built — so the authority that owns the answer
111    // is not available until now.
112    readiness.track_admission(connection_supervisor.admission_readiness());
113
114    let mut listener = ServerListener::bind(&config, connection_supervisor)?;
115    // LP-WS-TRANSPORT R1.1: the sibling WebSocket acceptor is explicit opt-in.
116    // Absent `[websocket]` binds nothing — no HTTP surface exists at all — and
117    // a bind failure fails startup BEFORE readiness reports the listeners
118    // bound, exactly like the main listener.
119    let mut websocket_listener = match config.websocket.as_ref() {
120        Some(websocket_config) => Some(WebSocketListener::bind(
121            websocket_config,
122            listener.supervisor(),
123        )?),
124        None => None,
125    };
126    readiness.set_config_loaded(true);
127    readiness.set_listener_bound(true);
128
129    tracing::debug!(
130        config_path = %config_path.display(),
131        listen_address = %config.listen_address,
132        health_listen_address = %health_server.local_addr(),
133        "liminal server configuration validated"
134    );
135
136    tracing::info!(
137        listen_address = %listener.local_addr(),
138        health_listen_address = %health_server.local_addr(),
139        "liminal server started"
140    );
141
142    shutdown_handle.wait();
143    readiness.set_listener_bound(false);
144
145    // Tear the cluster down before draining connections: stop accepting peer
146    // links and halt the membership poll loop. Each node shuts down independently
147    // (no cluster-wide coordinated shutdown — that boundary belongs to SRV-004).
148    if let Some(mut cluster_handle) = cluster_handle {
149        cluster_handle.shutdown();
150    }
151
152    let supervisor = listener.supervisor();
153    let shutdown_result = run_shutdown_sequence(
154        &mut listener,
155        websocket_listener.as_mut(),
156        &supervisor,
157        config.drain_timeout(),
158    );
159    let participant_fatal = supervisor.participant_service_fatal();
160    drop(websocket_listener);
161    drop(signal_registration);
162    health_server.shutdown()?;
163    shutdown_result?;
164    participant_fatal?.map_or(Ok(()), |fatal| {
165        Err(ServerError::ParticipantServiceFatal { fatal })
166    })
167}
168
169/// Starts clustering on the shared channel supervisor's scheduler (SRV-005).
170///
171/// Installs the cluster `sync` as the supervisor's [`ClusterObserver`] so channel
172/// subscribe/unsubscribe/publish events drive process-group membership and
173/// cross-node fan-out.
174///
175/// On the success path this marks cluster membership as established on `readiness`
176/// (G2) via [`cluster::start`]'s `on_established` hook, so a clustered server's
177/// `/ready` endpoint transitions from 503 to 200 once the cluster stack is up.
178/// Every early return here (missing resolver, listener bind failure, no reachable
179/// seed) leaves the flag unset, so `/ready` stays 503.
180fn start_cluster(
181    channel_cluster: &ChannelCluster,
182    cluster_config: &ClusterConfig,
183    readiness: &SharedReadinessState,
184) -> Result<ClusterHandle, ServerError> {
185    let resolver = channel_cluster
186        .resolver()
187        .cloned()
188        .ok_or_else(|| ServerError::ClusterJoin {
189            message: "clustering configured but channel supervisor has no distribution resolver"
190                .to_owned(),
191        })?;
192    let scheduler = channel_cluster.supervisor().scheduler();
193    let supervisor = channel_cluster.supervisor().clone();
194    let readiness = readiness.clone();
195    cluster::start(
196        &scheduler,
197        resolver,
198        cluster_config,
199        move |sync| {
200            supervisor.install_observer(Arc::new(sync));
201        },
202        move || readiness.set_cluster_membership_established(true),
203    )
204}
205
206#[cfg(test)]
207mod tests {
208    use std::net::SocketAddr;
209
210    use super::{ChannelCluster, ClusterConfig, SharedReadinessState, start_cluster};
211    use crate::ServerError;
212    use crate::health::{ClusterReadiness, ReadinessCondition, ReadinessState, readiness_check};
213    use crate::server::connection::services::LiminalConnectionServices;
214
215    /// A channel cluster with NO distribution resolver — the shape produced when a
216    /// server was built without a `[cluster]` section. `start_cluster` must reject
217    /// it before touching `cluster::start`, so its `on_established` hook never runs.
218    fn unclustered_channel_cluster() -> Result<ChannelCluster, ServerError> {
219        Ok(LiminalConnectionServices::empty()?
220            .channel_cluster()
221            .clone())
222    }
223
224    fn clustered_but_unmet_readiness() -> SharedReadinessState {
225        SharedReadinessState::new(ReadinessState::new(
226            true,
227            true,
228            ClusterReadiness::Configured {
229                membership_established: false,
230            },
231        ))
232    }
233
234    fn sample_cluster_config() -> Result<ClusterConfig, Box<dyn std::error::Error>> {
235        let listen_address: SocketAddr = "127.0.0.1:0".parse()?;
236        Ok(ClusterConfig {
237            node_name: "node-under-test@127.0.0.1".to_owned(),
238            listen_address,
239            seed_nodes: Vec::new(),
240            cookie: "runtime-test-cookie".to_owned(),
241        })
242    }
243
244    #[test]
245    fn failed_cluster_start_leaves_membership_unestablished()
246    -> Result<(), Box<dyn std::error::Error>> {
247        let readiness = clustered_but_unmet_readiness();
248        let channel_cluster = unclustered_channel_cluster()?;
249        let config = sample_cluster_config()?;
250
251        // Missing-resolver failure path: start_cluster returns Err before the
252        // established hook can fire.
253        let result = start_cluster(&channel_cluster, &config, &readiness);
254        assert!(
255            result.is_err(),
256            "start_cluster must fail without a distribution resolver"
257        );
258
259        // The readiness flag stays unset, so /ready still lists the unmet gate.
260        let status = readiness_check(&readiness.snapshot());
261        assert!(
262            !status.ready,
263            "readiness must remain not-ready after a failed start"
264        );
265        assert!(
266            status
267                .unmet_conditions
268                .contains(&ReadinessCondition::ClusterMembershipEstablished),
269            "cluster membership gate must stay unmet after a failed start"
270        );
271
272        Ok(())
273    }
274}