Skip to main content

reddb_server/service_cli/
server_bootstrap.rs

1//! The single server bootstrap path (issue #2133).
2//!
3//! `red server` / `red replica` used to fan out into eight near-identical
4//! `run_*_server` functions. They collapse here into one shape detection, one
5//! [`TransportSet`] of listener descriptors, and one [`BootedNode`] that binds
6//! and serves them. The per-shape differences that were observable to an
7//! operator stay observable, but as data on the descriptors instead of eight
8//! code paths: which sibling listeners a shape attaches, which listener is
9//! fatal, and when each port opens relative to the DB.
10
11use std::future::Future;
12use std::pin::Pin;
13
14use super::*;
15use crate::server::tls::{self, HttpTlsProfile};
16use crate::transport::{
17    TransportDescriptor, TransportKind, TransportReadiness, TransportRole, TransportSet,
18};
19
20/// The server shapes `red server` can be asked for. The shape decides which
21/// listeners exist, which one is fatal, and the OS thread name — exactly the
22/// split the eight `run_*_server` functions encoded.
23#[derive(Debug, Clone, Copy, PartialEq, Eq)]
24enum ServerShape {
25    Router,
26    Dual,
27    Grpc,
28    Http,
29    Wire,
30    WireTls,
31    Postgres,
32}
33
34impl ServerShape {
35    fn detect(config: &ServerCommandConfig) -> Option<Self> {
36        if config.router_bind_addr.is_some() {
37            return Some(Self::Router);
38        }
39        match (
40            config.grpc_bind_addr.is_some(),
41            config.http_bind_addr.is_some(),
42        ) {
43            (true, true) => Some(Self::Dual),
44            (true, false) => Some(Self::Grpc),
45            (false, true) => Some(Self::Http),
46            (false, false) if config.wire_bind_addr.is_some() => Some(Self::Wire),
47            (false, false) if config.wire_tls_bind_addr.is_some() => Some(Self::WireTls),
48            (false, false) if config.pg_bind_addr.is_some() => Some(Self::Postgres),
49            (false, false) => None,
50        }
51    }
52
53    const fn thread_name(self) -> &'static str {
54        match self {
55            Self::Router => "red-server-router",
56            Self::Dual => "red-server-dual",
57            Self::Grpc => "red-server-grpc",
58            Self::Http => "red-server-http",
59            Self::Wire => "red-server-wire",
60            Self::WireTls => "red-server-wire-tls",
61            Self::Postgres => "red-server-pg-wire",
62        }
63    }
64}
65
66/// How a failed bind is treated, per the pre-#2133 runner that owned it.
67#[derive(Debug, Clone, Copy, PartialEq, Eq)]
68enum BindPolicy {
69    /// Losing the port ends the boot whether or not the operator named it.
70    Fatal,
71    /// Issue #545: fatal when the operator named the port, degraded when the
72    /// address came from a default.
73    ExplicitFatal,
74    /// Sibling listeners that used to bind inside a detached task, where a
75    /// contested port was logged and the node kept serving.
76    Degrade,
77}
78
79/// Per-transport TLS material resolved before the bind.
80enum PreparedTransport {
81    Plain,
82    HttpTls {
83        server_config: Arc<rustls::ServerConfig>,
84        mtls: bool,
85    },
86    GrpcTls(crate::GrpcTlsOptions),
87    WireTls(crate::wire::WireTlsConfig),
88    Postgres(Option<crate::wire::WireTlsConfig>),
89}
90
91struct BoundTransport {
92    descriptor: TransportDescriptor,
93    /// `None` only for the Unix-socket RedWire descriptor, whose listener
94    /// binds the socket itself.
95    listener: Option<TcpListener>,
96    prepared: PreparedTransport,
97}
98
99/// Everything a transport's serve future needs from the booted node.
100struct ServeContext {
101    config: ServerCommandConfig,
102    runtime: RedDBRuntime,
103    auth_store: Arc<AuthStore>,
104    readiness: TransportReadiness,
105    rt_config: RuntimeConfig,
106    worker_threads: usize,
107    /// Issue #2140: one gRPC server per node, so the plain and TLS gRPC
108    /// listeners share a single `Arc<PreparedRegistry>` and a prepared_id
109    /// minted on one socket resolves on the other. `None` when the node
110    /// carries no gRPC transport.
111    grpc_server: Option<RedDBGrpcServer>,
112}
113
114type TransportFuture = Pin<Box<dyn Future<Output = Result<(), String>> + Send>>;
115
116/// A fully initialized node whose HTTP / gRPC listeners are already bound.
117/// Calling [`BootedNode::run`] opens the remaining listeners and serves them
118/// all on the same runtime.
119pub struct BootedNode {
120    config: ServerCommandConfig,
121    http_tls_profile: HttpTlsProfile,
122    runtime: RedDBRuntime,
123    auth_store: Arc<AuthStore>,
124    tokio_runtime: tokio::runtime::Runtime,
125    /// Listeners bound before the DB opened.
126    front: Vec<BoundTransport>,
127    /// Descriptors the pre-#2133 runners only bound once the DB was up.
128    deferred: Vec<TransportDescriptor>,
129    readiness: TransportReadiness,
130    rt_config: RuntimeConfig,
131    worker_threads: usize,
132    _backup_tasks: Option<BackupTasksHandle>,
133    _telemetry_guard: Option<crate::telemetry::TelemetryGuard>,
134}
135
136impl BootedNode {
137    fn boot(config: ServerCommandConfig) -> Result<Self, String> {
138        let Some(shape) = ServerShape::detect(&config) else {
139            return Err("at least one server bind address must be configured".to_string());
140        };
141        let transport_set = transport_set(&config);
142        let http_tls_profile = HttpTlsProfile::from_env()?;
143        if http_tls_profile != HttpTlsProfile::Default
144            && !transport_set
145                .descriptors()
146                .iter()
147                .any(|descriptor| descriptor.kind == TransportKind::Https)
148        {
149            return Err(
150                "REDDB_HTTP_TLS_PROFILE needs an active HTTPS listener (--http-tls-bind)".into(),
151            );
152        }
153        warn_plaintext_listeners(&config, &transport_set);
154
155        // Phase 1 — the HTTP and gRPC listeners the pre-#2133 runners bound
156        // before opening the DB, so an explicit port collision fails the boot
157        // before any recovery work starts.
158        let mut readiness = TransportReadiness::default();
159        let mut front = Vec::new();
160        let mut deferred = Vec::new();
161        for descriptor in transport_set.descriptors() {
162            if !matches!(descriptor.kind, TransportKind::Http | TransportKind::Grpc) {
163                deferred.push(descriptor.clone());
164                continue;
165            }
166            let listener = bind_listener_for_startup(
167                &mut readiness,
168                descriptor.kind.as_str(),
169                &descriptor.bind_addr,
170                descriptor.explicit,
171            )?;
172            front.push(BoundTransport {
173                descriptor: descriptor.clone(),
174                listener,
175                prepared: PreparedTransport::Plain,
176            });
177        }
178        resolve_degraded_front_binds(shape, &config, &mut front)?;
179
180        let db_options = config.to_db_options()?;
181        let rt_config = detect_runtime_config();
182        let worker_threads = config.workers.unwrap_or(rt_config.suggested_workers);
183        let tokio_runtime = tokio::runtime::Builder::new_multi_thread()
184            .enable_all()
185            .worker_threads(worker_threads)
186            .thread_stack_size(rt_config.stack_size)
187            .build()
188            .map_err(|err| format!("tokio runtime: {err}"))?;
189        let (runtime, auth_store, telemetry_guard) =
190            build_runtime_and_auth_store(&config, db_options.clone())?;
191        let backup_tasks = spawn_backup_tasks_if_configured(&db_options, &runtime);
192
193        // `RED_ADMIN_BIND` / `RED_METRICS_BIND` serve an HTTP surface, so only
194        // the shapes that already owned one honoured them.
195        if matches!(
196            shape,
197            ServerShape::Router | ServerShape::Dual | ServerShape::Http
198        ) {
199            spawn_admin_metrics_listeners(&runtime, &auth_store);
200        }
201
202        Ok(Self {
203            config,
204            http_tls_profile,
205            runtime,
206            auth_store,
207            tokio_runtime,
208            front,
209            deferred,
210            readiness,
211            rt_config,
212            worker_threads,
213            _backup_tasks: backup_tasks,
214            _telemetry_guard: telemetry_guard,
215        })
216    }
217
218    /// Open the deferred listeners, attach every transport to the node's tokio
219    /// runtime, and park on the shape's primary transport.
220    pub fn run(mut self) -> Result<(), String> {
221        let signal_runtime = self.runtime.clone();
222        let http_tls_profile = self.http_tls_profile;
223        let front = std::mem::take(&mut self.front);
224        let deferred = std::mem::take(&mut self.deferred);
225        let mut readiness = std::mem::take(&mut self.readiness);
226        let mut context = ServeContext {
227            config: self.config.clone(),
228            runtime: self.runtime.clone(),
229            auth_store: self.auth_store.clone(),
230            readiness: TransportReadiness::default(),
231            rt_config: self.rt_config.clone(),
232            worker_threads: self.worker_threads,
233            grpc_server: None,
234        };
235
236        self.tokio_runtime.block_on(async move {
237            spawn_lifecycle_signal_handler(signal_runtime).await;
238
239            // Phase 2 — the listeners the pre-#2133 runners opened only once
240            // the DB was up, so an orchestration probe cannot flip ready off a
241            // SYN backlog while recovery is still running.
242            let mut transports = front;
243            for descriptor in deferred {
244                if let Some(bound) = bind_deferred_transport(
245                    &context.config,
246                    &mut readiness,
247                    descriptor,
248                    http_tls_profile,
249                )? {
250                    transports.push(bound);
251                }
252            }
253
254            // Every listener is accounted for now, so the HTTP surfaces built
255            // below snapshot a complete `/health` transport view.
256            context.readiness = readiness;
257            let shared_grpc = build_shared_grpc_server(&context, &transports);
258            context.grpc_server = shared_grpc;
259            let mut primary: Option<TransportFuture> = None;
260            for bound in transports {
261                let kind = bound.descriptor.kind;
262                let role = bound.descriptor.role;
263                let future = serve_transport(bound, &context)?;
264                match role {
265                    TransportRole::Primary => primary = Some(future),
266                    TransportRole::Secondary => {
267                        tokio::spawn(async move {
268                            if let Err(err) = future.await {
269                                log_listener_exit(kind, &err);
270                            }
271                        });
272                    }
273                }
274            }
275
276            let Some(primary) = primary else {
277                return Err("no server transport started".to_string());
278            };
279            primary.await
280        })
281    }
282}
283
284/// Build the canonical descriptor set for one server command.
285pub fn transport_set(config: &ServerCommandConfig) -> TransportSet {
286    let Some(shape) = ServerShape::detect(config) else {
287        return TransportSet::default();
288    };
289
290    let mut descriptors = Vec::new();
291    match shape {
292        // Issue #933: the router demuxes HTTP, gRPC and RedWire off one port,
293        // so no sibling listener is attached to this shape.
294        ServerShape::Router => push(
295            &mut descriptors,
296            TransportKind::Router,
297            &config.router_bind_addr,
298            config.router_bind_explicit,
299            TransportRole::Primary,
300        ),
301        ServerShape::Dual => {
302            push(
303                &mut descriptors,
304                TransportKind::Http,
305                &config.http_bind_addr,
306                config.http_bind_explicit,
307                TransportRole::Secondary,
308            );
309            push(
310                &mut descriptors,
311                TransportKind::Grpc,
312                &config.grpc_bind_addr,
313                config.grpc_bind_explicit,
314                TransportRole::Primary,
315            );
316            push_wire_family(&mut descriptors, config);
317            push(
318                &mut descriptors,
319                TransportKind::Https,
320                &config.http_tls_bind_addr,
321                true,
322                TransportRole::Secondary,
323            );
324            push(
325                &mut descriptors,
326                TransportKind::GrpcTls,
327                &config.grpc_tls_bind_addr,
328                true,
329                TransportRole::Secondary,
330            );
331        }
332        // The gRPC-only shape never looked at `--http-tls-bind`.
333        ServerShape::Grpc => {
334            push(
335                &mut descriptors,
336                TransportKind::Grpc,
337                &config.grpc_bind_addr,
338                config.grpc_bind_explicit,
339                TransportRole::Primary,
340            );
341            push_wire_family(&mut descriptors, config);
342            push(
343                &mut descriptors,
344                TransportKind::GrpcTls,
345                &config.grpc_tls_bind_addr,
346                true,
347                TransportRole::Secondary,
348            );
349        }
350        // The HTTP-only shape never looked at `--grpc-tls-bind`.
351        ServerShape::Http => {
352            push(
353                &mut descriptors,
354                TransportKind::Http,
355                &config.http_bind_addr,
356                config.http_bind_explicit,
357                TransportRole::Primary,
358            );
359            push_wire_family(&mut descriptors, config);
360            push(
361                &mut descriptors,
362                TransportKind::Https,
363                &config.http_tls_bind_addr,
364                true,
365                TransportRole::Secondary,
366            );
367        }
368        // The wire shapes carried the PG sibling only. `--http-tls-bind` and
369        // `--grpc-tls-bind` were ignored outright, validation included, and
370        // the plaintext / TLS wire flags never coexisted.
371        ServerShape::Wire => {
372            push(
373                &mut descriptors,
374                TransportKind::Wire,
375                &config.wire_bind_addr,
376                config.wire_bind_explicit,
377                TransportRole::Primary,
378            );
379            push(
380                &mut descriptors,
381                TransportKind::Postgres,
382                &config.pg_bind_addr,
383                true,
384                TransportRole::Secondary,
385            );
386        }
387        ServerShape::WireTls => {
388            push(
389                &mut descriptors,
390                TransportKind::WireTls,
391                &config.wire_tls_bind_addr,
392                true,
393                TransportRole::Primary,
394            );
395            push(
396                &mut descriptors,
397                TransportKind::Postgres,
398                &config.pg_bind_addr,
399                true,
400                TransportRole::Secondary,
401            );
402        }
403        ServerShape::Postgres => push(
404            &mut descriptors,
405            TransportKind::Postgres,
406            &config.pg_bind_addr,
407            true,
408            TransportRole::Primary,
409        ),
410    }
411    TransportSet::new(descriptors)
412}
413
414/// Initialize one node and bind its front transports before serving.
415pub fn bootstrap_server(config: ServerCommandConfig) -> Result<BootedNode, String> {
416    BootedNode::boot(config)
417}
418
419/// The only process-level server run path.
420pub fn run_server(config: ServerCommandConfig) -> Result<(), String> {
421    let Some(shape) = ServerShape::detect(&config) else {
422        return Err("at least one server bind address must be configured".to_string());
423    };
424    let handle = thread::Builder::new()
425        .name(shape.thread_name().to_string())
426        .stack_size(8 * 1024 * 1024)
427        .spawn(move || bootstrap_server(config)?.run())
428        .map_err(|err| format!("failed to spawn server thread: {err}"))?;
429
430    match handle.join() {
431        Ok(result) => result,
432        Err(_) => Err("server thread panicked".to_string()),
433    }
434}
435
436fn push(
437    descriptors: &mut Vec<TransportDescriptor>,
438    kind: TransportKind,
439    bind_addr: &Option<String>,
440    explicit: bool,
441    role: TransportRole,
442) {
443    if let Some(bind_addr) = bind_addr.clone() {
444        descriptors.push(TransportDescriptor::new(kind, bind_addr, explicit, role));
445    }
446}
447
448/// The RedWire and PG-Wire listeners every HTTP/gRPC shape attached to its
449/// node alongside its own transport.
450fn push_wire_family(descriptors: &mut Vec<TransportDescriptor>, config: &ServerCommandConfig) {
451    push(
452        descriptors,
453        TransportKind::Wire,
454        &config.wire_bind_addr,
455        config.wire_bind_explicit,
456        TransportRole::Secondary,
457    );
458    push(
459        descriptors,
460        TransportKind::WireTls,
461        &config.wire_tls_bind_addr,
462        true,
463        TransportRole::Secondary,
464    );
465    push(
466        descriptors,
467        TransportKind::Postgres,
468        &config.pg_bind_addr,
469        true,
470        TransportRole::Secondary,
471    );
472}
473
474/// Apply the pre-#2133 rules for an HTTP/gRPC front bind that degraded away: a
475/// shape whose own listener is gone cannot boot, and the dual shape falls back
476/// to parking on HTTP when only gRPC lost its port.
477fn resolve_degraded_front_binds(
478    shape: ServerShape,
479    config: &ServerCommandConfig,
480    front: &mut Vec<BoundTransport>,
481) -> Result<(), String> {
482    let bound = |kind: TransportKind| {
483        front
484            .iter()
485            .any(|transport| transport.descriptor.kind == kind && transport.listener.is_some())
486    };
487    let http_bound = bound(TransportKind::Http);
488    let grpc_bound = bound(TransportKind::Grpc);
489
490    match shape {
491        ServerShape::Http if !http_bound => {
492            return Err(format!(
493                "no HTTP listener started; implicit bind {} failed",
494                config.http_bind_addr.as_deref().unwrap_or_default()
495            ));
496        }
497        ServerShape::Grpc if !grpc_bound => {
498            return Err(format!(
499                "no gRPC listener started; implicit bind {} failed",
500                config.grpc_bind_addr.as_deref().unwrap_or_default()
501            ));
502        }
503        ServerShape::Dual if !http_bound && !grpc_bound => {
504            return Err("no listener started; implicit HTTP and gRPC binds failed".to_string());
505        }
506        ServerShape::Dual if !grpc_bound => {
507            for transport in front.iter_mut() {
508                if transport.descriptor.kind == TransportKind::Http {
509                    transport.descriptor.role = TransportRole::Primary;
510                }
511            }
512        }
513        _ => {}
514    }
515
516    front.retain(|transport| transport.listener.is_some());
517    Ok(())
518}
519
520const fn bind_policy(descriptor: &TransportDescriptor) -> BindPolicy {
521    if matches!(descriptor.role, TransportRole::Primary) {
522        return BindPolicy::Fatal;
523    }
524    match descriptor.kind {
525        // reddb-io/rio-lair#255: an explicit `--wire-tls-bind` must never
526        // degrade into "healthy HTTP, dead TLS".
527        TransportKind::WireTls => BindPolicy::Fatal,
528        TransportKind::Wire => BindPolicy::ExplicitFatal,
529        _ => BindPolicy::Degrade,
530    }
531}
532
533/// Resolve a descriptor's TLS material and open its listener, inside the tokio
534/// runtime and after the DB is up.
535fn bind_deferred_transport(
536    config: &ServerCommandConfig,
537    readiness: &mut TransportReadiness,
538    descriptor: TransportDescriptor,
539    http_tls_profile: HttpTlsProfile,
540) -> Result<Option<BoundTransport>, String> {
541    let transport = descriptor.kind.as_str();
542    let prepared = match descriptor.kind {
543        TransportKind::Https => {
544            let tls_config = resolve_http_tls_config(config)?;
545            let server_config =
546                tls::build_server_config_with_profile(&tls_config, http_tls_profile)
547                    .map_err(|err| format!("HTTP TLS: {err}"))?;
548            PreparedTransport::HttpTls {
549                server_config,
550                mtls: tls_config.client_ca_path.is_some(),
551            }
552        }
553        TransportKind::GrpcTls => match resolve_grpc_tls_options(config) {
554            Ok(options) => PreparedTransport::GrpcTls(options),
555            Err(err) => {
556                let reason = format!("gRPC TLS config error: {err}");
557                readiness.failed(
558                    transport,
559                    &descriptor.bind_addr,
560                    descriptor.explicit,
561                    reason,
562                );
563                tracing::error!(
564                    target: "reddb::security",
565                    transport = "grpc",
566                    err = %err,
567                    "gRPC TLS config error; TLS listener will not start"
568                );
569                return Ok(None);
570            }
571        },
572        TransportKind::WireTls => match resolve_wire_tls_config(config) {
573            Ok(tls) => PreparedTransport::WireTls(tls),
574            Err(err) => {
575                let reason = format!("redwire TLS config error: {err}");
576                readiness.failed(
577                    transport,
578                    &descriptor.bind_addr,
579                    descriptor.explicit,
580                    reason.clone(),
581                );
582                tracing::error!(
583                    transport = "wire-tls",
584                    bind = %descriptor.bind_addr,
585                    error = %err,
586                    "fatal explicit redwire TLS config error"
587                );
588                return Err(format!("explicit {reason}"));
589            }
590        },
591        TransportKind::Postgres => PreparedTransport::Postgres(resolve_pg_wire_tls(config)),
592        _ => PreparedTransport::Plain,
593    };
594
595    // A `unix://` or absolute-path RedWire address is a Unix socket; that
596    // listener binds the socket itself.
597    #[cfg(unix)]
598    if descriptor.kind == TransportKind::Wire
599        && (descriptor.bind_addr.starts_with("unix://") || descriptor.bind_addr.starts_with('/'))
600    {
601        readiness.active(transport, &descriptor.bind_addr, descriptor.explicit);
602        return Ok(Some(BoundTransport {
603            descriptor,
604            listener: None,
605            prepared,
606        }));
607    }
608
609    let policy =
610        if descriptor.kind == TransportKind::Https && http_tls_profile != HttpTlsProfile::Default {
611            BindPolicy::Fatal
612        } else {
613            bind_policy(&descriptor)
614        };
615    let listener = match policy {
616        BindPolicy::Fatal => Some(bind_fatal_listener(readiness, &descriptor)?),
617        BindPolicy::ExplicitFatal => bind_listener_for_startup(
618            readiness,
619            transport,
620            &descriptor.bind_addr,
621            descriptor.explicit,
622        )?,
623        BindPolicy::Degrade => bind_degrading_listener(readiness, &descriptor),
624    };
625    let Some(listener) = listener else {
626        return Ok(None);
627    };
628    Ok(Some(BoundTransport {
629        descriptor,
630        listener: Some(listener),
631        prepared,
632    }))
633}
634
635/// Bind a listener whose loss ends the boot whether or not the operator named
636/// the port — the shape has nothing left to serve without it.
637fn bind_fatal_listener(
638    readiness: &mut TransportReadiness,
639    descriptor: &TransportDescriptor,
640) -> Result<TcpListener, String> {
641    match bind_listener_for_startup(
642        readiness,
643        descriptor.kind.as_str(),
644        &descriptor.bind_addr,
645        descriptor.explicit,
646    ) {
647        Ok(Some(listener)) => Ok(listener),
648        // An implicit default that degraded away: promote the reason the #545
649        // recorder just captured into the fatal error.
650        Ok(None) => Err(readiness
651            .failed
652            .last()
653            .map(|failure| failure.reason.clone())
654            .unwrap_or_else(|| {
655                format!(
656                    "{} listener bind {} failed",
657                    descriptor.kind.as_str(),
658                    descriptor.bind_addr
659                )
660            })),
661        Err(err) => Err(err),
662    }
663}
664
665/// Bind a sibling listener that pre-#2133 opened inside a detached task: a
666/// contested port is logged and recorded, and the node keeps serving.
667fn bind_degrading_listener(
668    readiness: &mut TransportReadiness,
669    descriptor: &TransportDescriptor,
670) -> Option<TcpListener> {
671    let transport = descriptor.kind.as_str();
672    match TcpListener::bind(&descriptor.bind_addr) {
673        Ok(listener) => {
674            readiness.active(transport, &descriptor.bind_addr, descriptor.explicit);
675            Some(listener)
676        }
677        Err(err) => {
678            let reason = format!("{transport} listener bind {}: {err}", descriptor.bind_addr);
679            readiness.failed(
680                transport,
681                &descriptor.bind_addr,
682                descriptor.explicit,
683                reason,
684            );
685            tracing::error!(
686                transport,
687                bind = %descriptor.bind_addr,
688                error = %err,
689                "non-fatal listener bind failure; listener degraded"
690            );
691            None
692        }
693    }
694}
695
696/// Build the node's single gRPC server, shared by its plain and TLS gRPC
697/// listeners (issue #2140). Constructing one server per listener would give
698/// each its own `PreparedRegistry`, so a prepared_id minted on the plain port
699/// would not resolve on the TLS port. Returns `None` when the node carries no
700/// gRPC transport, so non-gRPC shapes build no server at all.
701fn build_shared_grpc_server(
702    context: &ServeContext,
703    transports: &[BoundTransport],
704) -> Option<RedDBGrpcServer> {
705    let bind_addr = transports
706        .iter()
707        .find(|bound| bound.descriptor.kind == TransportKind::Grpc)
708        .or_else(|| {
709            transports
710                .iter()
711                .find(|bound| bound.descriptor.kind == TransportKind::GrpcTls)
712        })
713        .map(|bound| bound.descriptor.bind_addr.clone())?;
714    Some(RedDBGrpcServer::with_options(
715        context.runtime.clone(),
716        GrpcServerOptions {
717            bind_addr,
718            tls: None,
719        },
720        context.auth_store.clone(),
721    ))
722}
723
724/// Build the future that serves one bound transport for the node's lifetime.
725fn serve_transport(
726    bound: BoundTransport,
727    context: &ServeContext,
728) -> Result<TransportFuture, String> {
729    let ServeContext {
730        config,
731        runtime,
732        auth_store,
733        readiness,
734        rt_config,
735        worker_threads,
736        grpc_server,
737    } = context;
738    let bind_addr = bound.descriptor.bind_addr.clone();
739
740    match (bound.descriptor.kind, bound.listener, bound.prepared) {
741        (TransportKind::Router, Some(listener), PreparedTransport::Plain) => {
742            let http_server =
743                build_http_server(runtime.clone(), auth_store.clone(), bind_addr.clone());
744            let http_server = apply_http_limits(http_server, config, runtime);
745            let http_server = apply_ui_bundle(http_server, config)?;
746            let grpc_server = RedDBGrpcServer::with_options(
747                runtime.clone(),
748                GrpcServerOptions {
749                    bind_addr: bind_addr.clone(),
750                    tls: None,
751                },
752                auth_store.clone(),
753            );
754            let wire_runtime = Arc::new(runtime.clone());
755            let cpus = rt_config.available_cpus;
756            let workers = *worker_threads;
757            Ok(Box::pin(async move {
758                tracing::info!(
759                    bind = %bind_addr,
760                    cpus,
761                    workers,
762                    "router bootstrapping"
763                );
764                serve_tcp_router(InProcessRouterConfig {
765                    listener,
766                    bind_addr,
767                    http_server,
768                    grpc_server,
769                    wire_runtime,
770                })
771                .await
772                .map_err(|err| err.to_string())
773            }))
774        }
775        (TransportKind::Http, Some(listener), PreparedTransport::Plain) => {
776            let server = build_http_server_with_transport_readiness(
777                runtime.clone(),
778                auth_store.clone(),
779                bind_addr.clone(),
780                readiness.clone(),
781            );
782            let server = apply_http_limits(server, config, runtime);
783            let server = apply_ui_bundle(server, config)?;
784            Ok(Box::pin(async move {
785                tracing::info!(transport = "http", bind = %bind_addr, "listener online");
786                join_http_thread(server.serve_in_background_on(listener)).await
787            }))
788        }
789        (
790            TransportKind::Https,
791            Some(listener),
792            PreparedTransport::HttpTls {
793                server_config,
794                mtls,
795            },
796        ) => {
797            let server = build_http_server(runtime.clone(), auth_store.clone(), bind_addr.clone());
798            let server = apply_http_limits(server, config, runtime);
799            Ok(Box::pin(async move {
800                tracing::info!(
801                    transport = "https",
802                    bind = %bind_addr,
803                    mtls = %mtls,
804                    "TLS listener online"
805                );
806                join_http_thread(server.serve_tls_in_background_on(listener, server_config)).await
807            }))
808        }
809        (TransportKind::Grpc, Some(listener), PreparedTransport::Plain) => {
810            let server =
811                shared_grpc_server(grpc_server)?.with_listener_options(GrpcServerOptions {
812                    bind_addr: bind_addr.clone(),
813                    tls: None,
814                });
815            let cpus = rt_config.available_cpus;
816            let workers = *worker_threads;
817            Ok(Box::pin(async move {
818                tracing::info!(
819                    transport = "grpc",
820                    bind = %bind_addr,
821                    cpus,
822                    workers,
823                    "listener online"
824                );
825                server
826                    .serve_on(listener)
827                    .await
828                    .map_err(|err| err.to_string())
829            }))
830        }
831        (TransportKind::GrpcTls, Some(listener), PreparedTransport::GrpcTls(tls)) => {
832            // Issue #2140: the same server instance the plain gRPC listener
833            // serves, so both sockets share one `Arc<PreparedRegistry>`.
834            let server =
835                shared_grpc_server(grpc_server)?.with_listener_options(GrpcServerOptions {
836                    bind_addr: bind_addr.clone(),
837                    tls: Some(tls),
838                });
839            Ok(Box::pin(async move {
840                tracing::info!(transport = "grpc+tls", bind = %bind_addr, "listener online");
841                server
842                    .serve_on(listener)
843                    .await
844                    .map_err(|err| err.to_string())
845            }))
846        }
847        (TransportKind::Wire, listener, PreparedTransport::Plain) => {
848            let wire_runtime = Arc::new(runtime.clone());
849            Ok(Box::pin(async move {
850                // `start_redwire_listener_on` never logged itself online; the
851                // #545 readiness record is this transport's only signal.
852                #[cfg(unix)]
853                if listener.is_none() {
854                    return crate::wire::redwire::listener::start_redwire_unix_listener(
855                        &bind_addr,
856                        wire_runtime,
857                    )
858                    .await
859                    .map_err(|err| err.to_string());
860                }
861                let listener = into_tokio_listener(
862                    listener.expect("TCP wire descriptor carries a bound listener"),
863                )?;
864                crate::wire::redwire::listener::start_redwire_listener_on(listener, wire_runtime)
865                    .await
866                    .map_err(|err| err.to_string())
867            }))
868        }
869        (TransportKind::WireTls, Some(listener), PreparedTransport::WireTls(tls)) => {
870            let wire_runtime = Arc::new(runtime.clone());
871            Ok(Box::pin(async move {
872                let listener = into_tokio_listener(listener)?;
873                // `start_redwire_tls_listener_on` does not log for itself, and
874                // issues #1588 / #545 pin this exact line as the wire-TLS
875                // readiness probe.
876                tracing::info!(transport = "redwire+tls", bind = %bind_addr, "listener online");
877                crate::wire::start_redwire_tls_listener_on(listener, wire_runtime, &tls)
878                    .await
879                    .map_err(|err| err.to_string())
880            }))
881        }
882        (TransportKind::Postgres, Some(listener), PreparedTransport::Postgres(tls)) => {
883            let pg_runtime = Arc::new(runtime.clone());
884            Ok(Box::pin(async move {
885                let listener = into_tokio_listener(listener)?;
886                let pg_config = crate::wire::PgWireConfig {
887                    bind_addr,
888                    tls,
889                    ..Default::default()
890                };
891                crate::wire::start_pg_wire_listener_on(listener, pg_config, pg_runtime)
892                    .await
893                    .map_err(|err| err.to_string())
894            }))
895        }
896        _ => Err("transport descriptor preparation mismatch".to_string()),
897    }
898}
899
900/// Clone the node's shared gRPC server for one listener. Absent only if a gRPC
901/// transport reached [`serve_transport`] without one being built.
902fn shared_grpc_server(server: &Option<RedDBGrpcServer>) -> Result<RedDBGrpcServer, String> {
903    server
904        .clone()
905        .ok_or_else(|| "gRPC transport served without a bootstrapped gRPC server".to_string())
906}
907
908/// Hand a listener bound during bootstrap over to tokio.
909fn into_tokio_listener(listener: TcpListener) -> Result<tokio::net::TcpListener, String> {
910    listener
911        .set_nonblocking(true)
912        .map_err(|err| err.to_string())?;
913    tokio::net::TcpListener::from_std(listener).map_err(|err| err.to_string())
914}
915
916/// Park on a background HTTP/HTTPS server thread without holding a tokio
917/// worker.
918async fn join_http_thread(handle: thread::JoinHandle<std::io::Result<()>>) -> Result<(), String> {
919    match tokio::task::spawn_blocking(move || handle.join()).await {
920        Ok(Ok(Ok(()))) => Err("HTTP server exited unexpectedly".to_string()),
921        Ok(Ok(Err(err))) => Err(err.to_string()),
922        Ok(Err(_)) => Err("HTTP server thread panicked".to_string()),
923        Err(join_err) => Err(format!("HTTP server monitor task failed: {join_err}")),
924    }
925}
926
927/// Pre-#2133 wording for a sibling listener whose accept loop exited.
928fn log_listener_exit(kind: TransportKind, err: &str) {
929    match kind {
930        TransportKind::Wire => tracing::error!(err, "redwire listener error"),
931        TransportKind::WireTls => tracing::error!(err, "redwire+tls listener error"),
932        TransportKind::Postgres => tracing::error!(err, "pg wire listener error"),
933        TransportKind::GrpcTls => {
934            tracing::error!(transport = "grpc+tls", err, "gRPC TLS listener error")
935        }
936        _ => tracing::error!(transport = kind.as_str(), err, "listener error"),
937    }
938}
939
940/// Announce every listener that will accept connections from beyond the
941/// host without TLS. Plaintext is still the default, so an operator who
942/// never configured a certificate has never been told that credentials
943/// and data cross the network in clear.
944fn warn_plaintext_listeners(config: &ServerCommandConfig, transports: &TransportSet) {
945    let postgres_tls_configured = config.wire_tls_bind_addr.is_some()
946        || (config.wire_tls_cert.is_some() && config.wire_tls_key.is_some());
947    for descriptor in transports.descriptors() {
948        if !plaintext_listener_needs_warning(descriptor, postgres_tls_configured) {
949            continue;
950        }
951        let message = format!(
952            "⚠ {} listener on {} is plaintext and reachable beyond this host — \
953             credentials and data cross the network in clear; configure TLS or \
954             bind to loopback behind a TLS-terminating proxy",
955            descriptor.kind.as_str(),
956            descriptor.bind_addr
957        );
958        eprintln!("{message}");
959        tracing::warn!(
960            target: "reddb::security",
961            transport = descriptor.kind.as_str(),
962            bind = %descriptor.bind_addr,
963            "{message}"
964        );
965    }
966}
967
968fn plaintext_listener_needs_warning(
969    descriptor: &TransportDescriptor,
970    postgres_tls_configured: bool,
971) -> bool {
972    let plaintext = match descriptor.kind {
973        TransportKind::Router | TransportKind::Http | TransportKind::Grpc | TransportKind::Wire => {
974            true
975        }
976        // Postgres negotiates TLS on the same bind.
977        TransportKind::Postgres => !postgres_tls_configured,
978        TransportKind::Https | TransportKind::GrpcTls | TransportKind::WireTls => false,
979    };
980    plaintext && !crate::transport::is_loopback_bind(&descriptor.bind_addr)
981}
982
983#[cfg(test)]
984mod tests {
985    use super::*;
986
987    #[test]
988    fn plaintext_listener_warnings_are_independent_of_parallel_tls() {
989        for (kind, bind, expected) in [
990            (TransportKind::Http, "0.0.0.0:5000", true),
991            (TransportKind::Https, "0.0.0.0:5443", false),
992            (TransportKind::Http, "127.0.0.1:5000", false),
993            (TransportKind::Router, "0.0.0.0:5050", true),
994            (TransportKind::Postgres, "0.0.0.0:5432", false),
995        ] {
996            let descriptor =
997                TransportDescriptor::new(kind, bind.to_string(), true, TransportRole::Secondary);
998            assert_eq!(
999                plaintext_listener_needs_warning(&descriptor, true),
1000                expected
1001            );
1002        }
1003    }
1004}