webserver_base/webserver/
state.rs1use 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#[cfg(feature = "templates")]
23static NO_CACHE_BUSTER: LazyLock<BTreeMap<String, String>> = LazyLock::new(BTreeMap::new);
24
25#[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
62pub(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 #[must_use]
100 pub fn host(&self) -> &str {
101 &self.0.host
102 }
103
104 #[must_use]
106 pub fn port(&self) -> u16 {
107 self.0.port
108 }
109
110 #[must_use]
112 pub fn environment(&self) -> Environment {
113 self.0.environment
114 }
115
116 #[must_use]
127 pub fn shutdown(&self) -> &Shutdown {
128 &self.0.shutdown
129 }
130
131 #[must_use]
133 pub fn app(&self) -> &S {
134 &self.0.app
135 }
136
137 #[cfg(feature = "templates")]
139 #[must_use]
140 pub fn base_template_data(&self) -> Option<&BaseTemplateData> {
141 self.0.base.as_ref()
142 }
143
144 #[cfg(feature = "templates")]
146 #[must_use]
147 pub fn templates(&self) -> Option<&TemplateRegistry<'static>> {
148 self.0.templates.as_ref()
149 }
150
151 #[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 #[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 #[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 #[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 #[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 crate::assets::mark_never_cached(response.headers_mut());
234 response
235 }
236
237 #[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}