Skip to main content

webserver_base/webserver/
state.rs

1//! The one context every handler receives.
2
3use std::sync::Arc;
4
5use crate::environment::Environment;
6
7use super::shutdown::Shutdown;
8
9#[cfg(feature = "templates")]
10use {
11    super::error::WebServerError,
12    crate::templates::{BaseTemplateData, PageTemplateData, TemplateData, TemplateRegistry},
13    axum::http::StatusCode,
14    axum::response::{Html, IntoResponse, Response},
15    serde::Serialize,
16    std::collections::BTreeMap,
17    std::sync::LazyLock,
18    tracing::error,
19};
20
21/// Stands in for the asset map when the `assets` kit is off.
22#[cfg(feature = "templates")]
23static NO_CACHE_BUSTER: LazyLock<BTreeMap<String, String>> = LazyLock::new(BTreeMap::new);
24
25/// Everything a handler can reach: the server's configuration and kits, plus
26/// the application's state as `S`.
27///
28/// One generic, not two — page data is passed to
29/// [`render`](WebServerState::render) per call. Cloning is an `Arc` bump.
30///
31/// ```ignore
32/// type Ctx = State<WebServerState<Arc<AppState>>>;
33/// ```
34#[derive(Debug)]
35pub struct WebServerState<S = ()>(Arc<Inner<S>>);
36
37impl<S> Clone for WebServerState<S> {
38    fn clone(&self) -> Self {
39        Self(Arc::clone(&self.0))
40    }
41}
42
43#[derive(Debug)]
44struct Inner<S> {
45    host: String,
46    port: u16,
47    environment: Environment,
48    shutdown: Shutdown,
49
50    #[cfg(feature = "templates")]
51    base: Option<BaseTemplateData>,
52    #[cfg(feature = "templates")]
53    templates: Option<TemplateRegistry<'static>>,
54    #[cfg(feature = "webserver")]
55    cache_buster: Option<crate::assets::CacheBuster>,
56    #[cfg(feature = "templates")]
57    frontend: Option<crate::templates::FrontendRuntime>,
58
59    app: S,
60}
61
62/// The pieces [`WebServerState::new`] assembles.
63pub(super) struct StateParts<S> {
64    pub(super) host: String,
65    pub(super) port: u16,
66    pub(super) environment: Environment,
67    pub(super) shutdown: Shutdown,
68    #[cfg(feature = "templates")]
69    pub(super) base: Option<BaseTemplateData>,
70    #[cfg(feature = "templates")]
71    pub(super) templates: Option<TemplateRegistry<'static>>,
72    #[cfg(feature = "webserver")]
73    pub(super) cache_buster: Option<crate::assets::CacheBuster>,
74    #[cfg(feature = "templates")]
75    pub(super) frontend: Option<crate::templates::FrontendRuntime>,
76    pub(super) app: S,
77}
78
79impl<S> WebServerState<S> {
80    pub(super) fn new(parts: StateParts<S>) -> Self {
81        Self(Arc::new(Inner {
82            host: parts.host,
83            port: parts.port,
84            environment: parts.environment,
85            shutdown: parts.shutdown,
86            #[cfg(feature = "templates")]
87            base: parts.base,
88            #[cfg(feature = "templates")]
89            templates: parts.templates,
90            #[cfg(feature = "webserver")]
91            cache_buster: parts.cache_buster,
92            #[cfg(feature = "templates")]
93            frontend: parts.frontend,
94            app: parts.app,
95        }))
96    }
97
98    /// The host this server bound to.
99    #[must_use]
100    pub fn host(&self) -> &str {
101        &self.0.host
102    }
103
104    /// The port this server bound to.
105    #[must_use]
106    pub fn port(&self) -> u16 {
107        self.0.port
108    }
109
110    /// Which deployment this is.
111    #[must_use]
112    pub fn environment(&self) -> Environment {
113        self.0.environment
114    }
115
116    /// The shutdown handle. Clone it into a socket loop to close cleanly:
117    ///
118    /// ```ignore
119    /// tokio::select! {
120    ///     message = socket.recv() => { /* … */ }
121    ///     () = state.shutdown().clone().recv() => {
122    ///         socket.send(Message::Close(None)).await.ok();
123    ///     }
124    /// }
125    /// ```
126    #[must_use]
127    pub fn shutdown(&self) -> &Shutdown {
128        &self.0.shutdown
129    }
130
131    /// The application's own state.
132    #[must_use]
133    pub fn app(&self) -> &S {
134        &self.0.app
135    }
136
137    /// The per-server template data, if `.templates(..)` was called.
138    #[cfg(feature = "templates")]
139    #[must_use]
140    pub fn base_template_data(&self) -> Option<&BaseTemplateData> {
141        self.0.base.as_ref()
142    }
143
144    /// The template registry, if `.templates(..)` was called.
145    #[cfg(feature = "templates")]
146    #[must_use]
147    pub fn templates(&self) -> Option<&TemplateRegistry<'static>> {
148        self.0.templates.as_ref()
149    }
150
151    /// The asset cache, if `.assets(..)` was called.
152    #[cfg(feature = "webserver")]
153    #[must_use]
154    pub fn cache_buster(&self) -> Option<&crate::assets::CacheBuster> {
155        self.0.cache_buster.as_ref()
156    }
157
158    /// The content-hashed path for an asset, or the original path when the
159    /// `assets` kit is not in use.
160    #[cfg(feature = "webserver")]
161    #[must_use]
162    pub fn asset(&self, original_asset_file_path: &str) -> String {
163        self.0.cache_buster.as_ref().map_or_else(
164            || original_asset_file_path.to_string(),
165            |cache_buster| cache_buster.get_file(original_asset_file_path),
166        )
167    }
168
169    /// The per-server frontend data, if `.frontend(..)` was called.
170    #[cfg(feature = "templates")]
171    #[must_use]
172    pub fn frontend_runtime(&self) -> Option<&crate::templates::FrontendRuntime> {
173        self.0.frontend.as_ref()
174    }
175
176    /// Renders `page` with `data` as its `{{app}}`. Pass `()` for none.
177    ///
178    /// # Errors
179    ///
180    /// [`WebServerError::TemplatesNotConfigured`] without `.templates(..)`, or
181    /// [`WebServerError::Template`] if the render fails.
182    #[cfg(feature = "templates")]
183    pub fn render<A>(
184        &self,
185        page: &PageTemplateData,
186        data: A,
187    ) -> Result<Html<String>, WebServerError>
188    where
189        A: Serialize,
190    {
191        let (Some(base), Some(registry)) = (self.0.base.as_ref(), self.0.templates.as_ref()) else {
192            return Err(WebServerError::TemplatesNotConfigured);
193        };
194
195        let template_data: TemplateData<'_, A> = TemplateData::assemble(
196            base,
197            page,
198            self.0.frontend.as_ref(),
199            self.0.environment,
200            self.cache_buster_map(),
201            data,
202        )?;
203
204        Ok(Html(registry.render(page.template(), &template_data)?))
205    }
206
207    /// The site's 404 page, with `data` as its `{{app}}` and a real 404 status.
208    ///
209    /// For a handler whose route matched but whose resource does not exist —
210    /// an unknown slug. It is the same page the router fallback serves, so the
211    /// two cannot drift. Without `.frontend(..)` it is a bare `404`; a failed
212    /// render is a 500, never a panic. Never cached, whichever it is.
213    #[cfg(feature = "templates")]
214    pub fn not_found<A>(&self, data: A) -> Response
215    where
216        A: Serialize,
217    {
218        if self.0.templates.is_none() {
219            return super::server::plain_not_found_response();
220        }
221
222        let page: &PageTemplateData = crate::templates::not_found_page();
223        let mut response: Response = match self.render(page, data) {
224            Ok(html) => (StatusCode::NOT_FOUND, html).into_response(),
225            Err(render_error) => {
226                error!("failed to render the 404 page: {render_error}");
227                render_error.into_response()
228            }
229        };
230        // Stamped here, not left to the never-cache layer: the router fallback
231        // sits outside it, and a cacheable 404 can outlive the deploy that
232        // makes its URL real.
233        crate::assets::mark_never_cached(response.headers_mut());
234        response
235    }
236
237    /// The asset map, empty when the `assets` kit is off.
238    #[cfg(feature = "templates")]
239    fn cache_buster_map(&self) -> &BTreeMap<String, String> {
240        #[cfg(feature = "webserver")]
241        {
242            self.0
243                .cache_buster
244                .as_ref()
245                .map_or(&NO_CACHE_BUSTER, crate::assets::CacheBuster::cache)
246        }
247        #[cfg(not(feature = "webserver"))]
248        {
249            &NO_CACHE_BUSTER
250        }
251    }
252}