Skip to main content

webserver_base/webserver/
bootstrap.rs

1//! Process start-up, in the one order that works.
2
3use std::future::Future;
4
5use super::shutdown::Shutdown;
6
7/// Runs `body` with observability, a runtime, and signal handling set up.
8///
9/// The ordering is the point: observability on the main thread first (so the
10/// Sentry hub reaches the runtime's workers), then the runtime, then one signal
11/// listener whose [`Shutdown`] handle is passed to `body`, then the guard drops
12/// after `body` returns — flushing errors raised during the shutdown itself.
13///
14/// The application still owns `main`, so it can start as many servers as it
15/// likes.
16///
17/// It also owns the build-tool subcommands, so no project has to declare a
18/// second binary or write a line of glue to reach them:
19///
20/// ```text
21/// $ my-server gen-static-assets    # icons, then hash everything but scripts
22/// $ my-server gen-static-scripts   # hash the built JavaScript
23/// $ my-server                      # serve
24/// ```
25///
26/// Those two exit before any runtime or error monitoring starts. They still
27/// read `WSB_ENVIRONMENT`, because `main` resolves it before calling in — set
28/// it to `local` in the build stage.
29///
30/// ```no_run
31/// use webserver_base::{WebServer, WebServerError, bootstrap};
32///
33/// fn main() -> Result<(), WebServerError> {
34///     bootstrap!(|shutdown| async move { WebServer::from_env()?.run(shutdown).await })
35/// }
36/// ```
37///
38/// # Errors
39///
40/// Whatever `body` returns. `bootstrap` adds no failure of its own.
41///
42/// # Panics
43///
44/// If the Tokio runtime cannot be built. There is no useful way to continue,
45/// and no server to report it to yet.
46pub fn bootstrap_with_release<F, Fut, T, E>(
47    #[cfg_attr(
48        not(feature = "observability"),
49        expect(unused_variables, reason = "only the Sentry release reads it")
50    )]
51    release: &str,
52    body: F,
53) -> Result<T, E>
54where
55    F: FnOnce(Shutdown) -> Fut,
56    Fut: Future<Output = Result<T, E>>,
57    E: From<super::error::WebServerError>,
58{
59    // Build-tool modes run and exit before the runtime, before error
60    // monitoring, and before anything binds a port. Handling them here is what
61    // lets every project reach the static-asset pipeline through its own server
62    // binary, with no shim binary and no duplicated glue.
63    if let Some(phase) = std::env::args()
64        .nth(1)
65        .as_deref()
66        .and_then(crate::assets::Phase::from_subcommand)
67    {
68        match crate::assets::generate_static_assets(phase) {
69            Ok(()) => std::process::exit(0),
70            Err(error) => {
71                eprintln!("{error}");
72                std::process::exit(1);
73            }
74        }
75    }
76
77    // Resolved here rather than in every `main`: it is the same three lines in
78    // every project, and one of them is easy to get in the wrong order.
79    #[cfg(feature = "observability")]
80    let _guard: crate::observability::ObservabilityGuard = {
81        let environment: crate::Environment = crate::Environment::from_env()
82            .map_err(|error| E::from(super::error::WebServerError::from(error)))?;
83        crate::observability::Observability::from_env(environment)
84            .map_err(|error| E::from(super::error::WebServerError::from(error)))?
85            .with_release(release)
86            .init()
87    };
88
89    let runtime: tokio::runtime::Runtime = tokio::runtime::Builder::new_multi_thread()
90        .enable_all()
91        .build()
92        .expect("failed to build the tokio runtime");
93
94    runtime.block_on(async move {
95        let shutdown: Shutdown = Shutdown::listen();
96        body(shutdown).await
97    })
98    // `_guard` drops here, after the drain.
99}
100
101/// Starts a server, naming the running build from the *calling* crate.
102///
103/// A macro rather than a function because the release string has to come from
104/// the application's own `CARGO_PKG_NAME` and `CARGO_PKG_VERSION`, and those are
105/// resolved where the code is written. Called from inside this library — as
106/// `sentry::release_name!()` does — every project would report the same
107/// release, and Sentry could not tell one site's deploys from another's.
108///
109/// ```no_run
110/// use webserver_base::{WebServer, WebServerError, bootstrap};
111///
112/// fn main() -> Result<(), WebServerError> {
113///     bootstrap!(|shutdown| async move { WebServer::from_env()?.run(shutdown).await })
114/// }
115/// ```
116#[macro_export]
117macro_rules! bootstrap {
118    ($body:expr) => {
119        $crate::webserver::bootstrap_with_release(
120            concat!(env!("CARGO_PKG_NAME"), "@", env!("CARGO_PKG_VERSION")),
121            $body,
122        )
123    };
124}