Skip to main content

saluki_app/
bootstrap.rs

1//! Bootstrap utilities.
2
3use metrics::Level;
4use saluki_core::runtime::Supervisor;
5use saluki_error::{ErrorContext as _, GenericError};
6use tracing::warn;
7
8use crate::{
9    logging::{initialize_logging, LoggingConfiguration, LoggingGuard},
10    metrics::{initialize_metrics, level_name},
11    tls::initialize_tls,
12};
13
14/// The result of running [`AppBootstrapper::bootstrap`].
15///
16/// Bundles together the [`BootstrapGuard`] that must be held for the lifetime of the application with the
17/// [`Supervisor`] that drives the background workers spawned during bootstrap. Callers must arrange for the
18/// supervisor to be run (either directly or by adding it to a parent supervisor) for those workers to make
19/// progress.
20pub struct Bootstrap {
21    /// Supervisor populated with workers for all background async tasks created during bootstrap.
22    pub supervisor: Supervisor,
23
24    /// Drop guard for resources acquired during bootstrap.
25    pub guard: BootstrapGuard,
26}
27
28/// A drop guard for ensuring deferred cleanup of resources acquired during bootstrap.
29pub struct BootstrapGuard {
30    logging_guard: LoggingGuard,
31}
32
33impl BootstrapGuard {
34    /// Returns a reference to the [`LoggingGuard`].
35    ///
36    /// Use this to obtain a [`LoggingOverrideController`][crate::logging::LoggingOverrideController] clone (via
37    /// [`LoggingGuard::controller`]) for downstream callers that drive runtime filter changes.
38    pub fn logging(&self) -> &LoggingGuard {
39        &self.logging_guard
40    }
41
42    /// Returns a mutable reference to the [`LoggingGuard`].
43    ///
44    /// Use this to swap the entire logging configuration (outputs, format, level) via [`LoggingGuard::reload`].
45    pub fn logging_mut(&mut self) -> &mut LoggingGuard {
46        &mut self.logging_guard
47    }
48}
49
50/// Early application initialization.
51///
52/// This helper type is used to configure the various low-level shared resources required by the application, such as
53/// the logging and metrics subsystems.
54pub struct AppBootstrapper {
55    logging_config: LoggingConfiguration,
56    metrics_prefix: String,
57    metrics_default_level: Level,
58    metrics_minimum_level: Level,
59}
60
61impl AppBootstrapper {
62    /// Creates a new `AppBootstrapper`.
63    ///
64    /// The bootstrapper is initialized with a [`simple`][LoggingConfiguration::simple] logging configuration. Callers
65    /// that have application-specific logging requirements should follow up with
66    /// [`with_logging_configuration`][Self::with_logging_configuration] to override this default.
67    pub fn new() -> Self {
68        Self {
69            logging_config: LoggingConfiguration::simple(),
70            metrics_prefix: "saluki".to_string(),
71            metrics_default_level: Level::INFO,
72            metrics_minimum_level: Level::ERROR,
73        }
74    }
75
76    /// Sets the prefix to use for internal metrics.
77    ///
78    /// Defaults to `saluki`.
79    pub fn with_metrics_prefix<S: Into<String>>(mut self, prefix: S) -> Self {
80        self.metrics_prefix = prefix.into();
81        self
82    }
83
84    /// Sets the default filter level for internal metrics.
85    ///
86    /// Metrics whose level is more verbose than this default are filtered out at flush time. The default also drives
87    /// the level that the filter is restored to whenever a runtime override is reset.
88    ///
89    /// Defaults to [`Level::INFO`].
90    pub fn with_metrics_default_level(mut self, level: Level) -> Self {
91        self.metrics_default_level = level;
92        self
93    }
94
95    /// Sets the least verbose filter level for internal metrics.
96    ///
97    /// This keeps internal metrics that the application relies on from being filtered out:
98    ///
99    /// - a default level that's less verbose than this is raised to it at bootstrap, with a warning
100    /// - a runtime override that's less verbose than this is rejected
101    ///
102    /// Defaults to [`Level::ERROR`], which allows any level.
103    pub fn with_metrics_minimum_level(mut self, level: Level) -> Self {
104        self.metrics_minimum_level = level;
105        self
106    }
107
108    /// Sets the logging configuration to use during bootstrap.
109    ///
110    /// Replaces the [`simple`][LoggingConfiguration::simple] default that [`new`][Self::new] installs.
111    pub fn with_logging_configuration(mut self, logging_config: LoggingConfiguration) -> Self {
112        self.logging_config = logging_config;
113        self
114    }
115
116    /// Executes the bootstrap operation, initializing all configured subsystems.
117    ///
118    /// Returns a [`Bootstrap`] containing both a [`BootstrapGuard`] (which must be held until the application is
119    /// ready to shut down) and a [`Supervisor`] populated with workers for all background async tasks created
120    /// during bootstrap. Callers must arrange for the supervisor to run (typically by adding it to a parent
121    /// supervisor or calling [`Supervisor::run_with_shutdown`]) for those workers to make progress.
122    ///
123    /// # Errors
124    ///
125    /// If any of the bootstrap steps fail, an error will be returned.
126    pub async fn bootstrap(self) -> Result<Bootstrap, GenericError> {
127        // Initialize the logging subsystem first, since we want to make it possible to get any logs from the rest of
128        // the bootstrap process.
129        let (logging_guard, logging_supervisor) = initialize_logging(self.logging_config)
130            .await
131            .error_context("Failed to initialize logging subsystem.")?;
132
133        // Initialize everything else.
134        initialize_tls().error_context("Failed to initialize TLS subsystem.")?;
135
136        let metrics_default_level = floor_metrics_level(self.metrics_default_level, self.metrics_minimum_level);
137        if metrics_default_level != self.metrics_default_level {
138            warn!(
139                "Configured metrics level `{}` is less verbose than the minimum level `{}`. Using `{}` instead.",
140                level_name(self.metrics_default_level),
141                level_name(self.metrics_minimum_level),
142                level_name(metrics_default_level),
143            );
144        }
145        let metrics_supervisor =
146            initialize_metrics(self.metrics_prefix, metrics_default_level, self.metrics_minimum_level)
147                .await
148                .error_context("Failed to initialize metrics subsystem.")?;
149
150        // Build our combined supervisor for all bootstrap-related workers.
151        let mut supervisor =
152            Supervisor::new("app-bootstrap").error_context("Failed to construct app bootstrap supervisor.")?;
153        supervisor.add_worker(logging_supervisor);
154        supervisor.add_worker(metrics_supervisor);
155
156        Ok(Bootstrap {
157            supervisor,
158            guard: BootstrapGuard { logging_guard },
159        })
160    }
161}
162
163/// Returns `level`, raised to `minimum` when it's less verbose than that.
164fn floor_metrics_level(level: Level, minimum: Level) -> Level {
165    if level > minimum {
166        minimum
167    } else {
168        level
169    }
170}
171
172#[cfg(test)]
173mod tests {
174    use metrics::Level;
175
176    use super::floor_metrics_level;
177
178    #[test]
179    fn metrics_default_level_is_raised_to_the_minimum() {
180        // Levels at or more verbose than the minimum are used as given.
181        for level in [Level::TRACE, Level::DEBUG, Level::INFO] {
182            assert_eq!(floor_metrics_level(level, Level::INFO), level);
183        }
184
185        // Less verbose levels would filter out metrics the application relies on, so they're raised to the minimum.
186        for level in [Level::WARN, Level::ERROR] {
187            assert_eq!(floor_metrics_level(level, Level::INFO), Level::INFO);
188        }
189
190        // The default minimum allows any level.
191        assert_eq!(floor_metrics_level(Level::ERROR, Level::ERROR), Level::ERROR);
192    }
193}