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>(release: &str, body: F) -> Result<T, E>
47where
48 F: FnOnce(Shutdown) -> Fut,
49 Fut: Future<Output = Result<T, E>>,
50 E: From<super::error::WebServerError>,
51{
52 bootstrap_with_release_and(release, |observability: Observability| observability, body)
53}
54
55/// What `configure` is given: the observability [`bootstrap`](crate::bootstrap)
56/// is about to start. Nothing when the `observability` feature is off.
57#[cfg(feature = "observability")]
58pub type Observability = crate::observability::Observability;
59/// What `configure` is given: the observability [`bootstrap`](crate::bootstrap)
60/// is about to start. Nothing when the `observability` feature is off.
61#[cfg(not(feature = "observability"))]
62pub type Observability = ();
63
64/// [`bootstrap_with_release`], with `configure` adjusting the observability
65/// before it starts, e.g. `|o| o.with_traces_sample_rate(rate)`.
66///
67/// # Errors
68///
69/// Whatever `body` returns. `bootstrap_with_release_and` adds no failure of its own.
70///
71/// # Panics
72///
73/// If the Tokio runtime cannot be built.
74pub fn bootstrap_with_release_and<F, Fut, T, E, C>(
75 release: &str,
76 configure: C,
77 body: F,
78) -> Result<T, E>
79where
80 F: FnOnce(Shutdown) -> Fut,
81 Fut: Future<Output = Result<T, E>>,
82 E: From<super::error::WebServerError>,
83 C: FnOnce(Observability) -> Observability,
84{
85 // Build-tool modes run and exit before the runtime, before error
86 // monitoring, and before anything binds a port. Handling them here is what
87 // lets every project reach the static-asset pipeline through its own server
88 // binary, with no shim binary and no duplicated glue.
89 if let Some(phase) = std::env::args()
90 .nth(1)
91 .as_deref()
92 .and_then(crate::assets::Phase::from_subcommand)
93 {
94 match crate::assets::generate_static_assets(phase) {
95 Ok(()) => std::process::exit(0),
96 Err(error) => {
97 eprintln!("{error}");
98 std::process::exit(1);
99 }
100 }
101 }
102
103 // Resolved here rather than in every `main`: it is the same three lines in
104 // every project, and one of them is easy to get in the wrong order.
105 super::telemetry::set_release(release);
106
107 #[cfg(feature = "observability")]
108 let _guard: crate::observability::ObservabilityGuard = {
109 let environment: crate::Environment = crate::Environment::from_env()
110 .map_err(|error| E::from(super::error::WebServerError::from(error)))?;
111 configure(
112 crate::observability::Observability::from_env(environment)
113 .map_err(|error| E::from(super::error::WebServerError::from(error)))?
114 .with_release(release),
115 )
116 .init()
117 };
118 #[cfg(not(feature = "observability"))]
119 drop(configure);
120
121 let runtime: tokio::runtime::Runtime = tokio::runtime::Builder::new_multi_thread()
122 .enable_all()
123 .build()
124 .expect("failed to build the tokio runtime");
125
126 runtime.block_on(async move {
127 let shutdown: Shutdown = Shutdown::listen();
128 body(shutdown).await
129 })
130 // `_guard` drops here, after the drain.
131}
132
133/// Starts a server, naming the running build from the *calling* crate.
134///
135/// A macro rather than a function because the release string has to come from
136/// the application's own `CARGO_PKG_NAME` and `CARGO_PKG_VERSION`, and those are
137/// resolved where the code is written. Called from inside this library — as
138/// `sentry::release_name!()` does — every project would report the same
139/// release, and Sentry could not tell one site's deploys from another's.
140///
141/// ```no_run
142/// use webserver_base::{WebServer, WebServerError, bootstrap};
143///
144/// fn main() -> Result<(), WebServerError> {
145/// bootstrap!(|shutdown| async move { WebServer::from_env()?.run(shutdown).await })
146/// }
147/// ```
148///
149/// To set the server's trace sampling rate (or anything else on
150/// [`Observability`](crate::observability::Observability)), pass a closure
151/// first:
152///
153/// ```ignore
154/// bootstrap!(
155/// |observability| observability.with_traces_sample_rate(TracesSampleRate::ALL),
156/// |shutdown| async move { WebServer::from_env()?.run(shutdown).await }
157/// )
158/// ```
159#[macro_export]
160macro_rules! bootstrap {
161 ($configure:expr, $body:expr) => {
162 $crate::webserver::bootstrap_with_release_and(
163 concat!(env!("CARGO_PKG_NAME"), "@", env!("CARGO_PKG_VERSION")),
164 $configure,
165 $body,
166 )
167 };
168 ($body:expr) => {
169 $crate::webserver::bootstrap_with_release(
170 concat!(env!("CARGO_PKG_NAME"), "@", env!("CARGO_PKG_VERSION")),
171 $body,
172 )
173 };
174}