Skip to main content

webserver_base/webserver/
pages.rs

1//! Page declarations that produce both the route table and the sitemap.
2//!
3//! A page is declared once, so the two cannot drift, and leaving one out of the
4//! sitemap is something you type ([`Pages::unlisted`]) rather than forget.
5//!
6//! Only pages live here — API routes, WebSocket upgrades and static file
7//! services stay ordinary axum.
8
9use std::collections::HashMap;
10use std::sync::Arc;
11
12use axum::extract::State;
13use axum::response::{IntoResponse, Response};
14use axum::routing::{MethodRouter, get};
15use axum_extra::routing::RouterExt;
16use chrono::{DateTime, Utc};
17use serde::Serialize;
18use serde_json::Value;
19use tracing::error;
20
21use crate::sitemap::SitemapUrl;
22use crate::templates::PageTemplateData;
23
24use super::error::WebServerError;
25use super::state::WebServerState;
26
27/// Whether a page appears in `sitemap.xml`.
28#[derive(Debug, Clone)]
29enum Listing {
30    Listed(Vec<SitemapUrl>),
31    Unlisted,
32}
33
34/// How a page produces its response.
35enum PageKind<S> {
36    /// Pure declaration — no handler function exists.
37    Static {
38        page: Arc<PageTemplateData>,
39        data: Arc<Value>,
40    },
41    /// An ordinary axum handler.
42    Dynamic(Box<MethodRouter<WebServerState<S>>>),
43}
44
45struct PageEntry<S> {
46    path: String,
47    kind: PageKind<S>,
48    listing: Listing,
49}
50
51/// The pages a site serves.
52#[derive(Default)]
53pub struct Pages<S = ()> {
54    entries: Vec<PageEntry<S>>,
55}
56
57impl<S> Pages<S>
58where
59    S: Clone + Send + Sync + 'static,
60{
61    /// An empty declaration.
62    #[must_use]
63    pub fn new() -> Self {
64        Self {
65            entries: Vec::new(),
66        }
67    }
68
69    /// A page with no logic: no handler function exists.
70    ///
71    /// Its route comes from the page's own
72    /// [`page_url`](PageTemplateData::page_url), and `data` is serialized once
73    /// at boot. Anything that varies per request needs
74    /// [`Pages::dynamic_page`].
75    ///
76    /// # Panics
77    ///
78    /// If `data` cannot be serialized.
79    #[must_use]
80    pub fn static_page<A>(mut self, page: PageTemplateData, data: A) -> Self
81    where
82        A: Serialize,
83    {
84        let path: String = page.page_url().to_string();
85        let value: Value = serde_json::to_value(data).unwrap_or_else(|error| {
86            panic!("static page `{path}` has unserializable data: {error}")
87        });
88
89        self.entries.push(PageEntry {
90            listing: Listing::Listed(vec![SitemapUrl::new(&path)]),
91            path,
92            kind: PageKind::Static {
93                page: Arc::new(page),
94                data: Arc::new(value),
95            },
96        });
97        self
98    }
99
100    /// A page backed by an ordinary axum handler. For a parameterised path use
101    /// [`Pages::dynamic_page_group`].
102    #[must_use]
103    pub fn dynamic_page(
104        mut self,
105        path: impl Into<String>,
106        handler: MethodRouter<WebServerState<S>>,
107    ) -> Self {
108        let path: String = path.into();
109        self.entries.push(PageEntry {
110            listing: Listing::Listed(vec![SitemapUrl::new(&path)]),
111            path,
112            kind: PageKind::Dynamic(Box::new(handler)),
113        });
114        self
115    }
116
117    /// One handler serving many URLs, with those URLs supplied for the sitemap.
118    ///
119    /// The list is built where the route is declared, so adding a blog post
120    /// cannot leave the sitemap behind.
121    #[must_use]
122    pub fn dynamic_page_group<I>(
123        mut self,
124        path: impl Into<String>,
125        handler: MethodRouter<WebServerState<S>>,
126        urls: I,
127    ) -> Self
128    where
129        I: IntoIterator<Item = SitemapUrl>,
130    {
131        self.entries.push(PageEntry {
132            path: path.into(),
133            kind: PageKind::Dynamic(Box::new(handler)),
134            listing: Listing::Listed(urls.into_iter().collect()),
135        });
136        self
137    }
138
139    /// Keeps the most recently declared page out of the sitemap.
140    #[must_use]
141    pub fn unlisted(mut self) -> Self {
142        if let Some(entry) = self.entries.last_mut() {
143            entry.listing = Listing::Unlisted;
144        }
145        self
146    }
147
148    /// Sets `<lastmod>` on the most recently declared page.
149    #[must_use]
150    pub fn with_last_modified(mut self, last_modified: DateTime<Utc>) -> Self {
151        self.map_last_urls(|url| url.with_last_modified(last_modified));
152        self
153    }
154
155    /// Adds `<image:image>` entries to the most recently declared page.
156    #[must_use]
157    pub fn extend_images<I, T>(mut self, images: I) -> Self
158    where
159        I: IntoIterator<Item = T>,
160        T: Into<String>,
161    {
162        let images: Vec<String> = images.into_iter().map(Into::into).collect();
163        self.map_last_urls(|url| url.extend_images(images.iter().cloned()));
164        self
165    }
166
167    fn map_last_urls<F>(&mut self, mut transform: F)
168    where
169        F: FnMut(SitemapUrl) -> SitemapUrl,
170    {
171        if let Some(entry) = self.entries.last_mut()
172            && let Listing::Listed(urls) = &mut entry.listing
173        {
174            for url in urls.iter_mut() {
175                *url = transform(url.clone());
176            }
177        }
178    }
179
180    /// Every route path that was declared, listed or not.
181    ///
182    /// Used to prove the feed advertises a page the site actually serves; an
183    /// unlisted page still counts, because it is still routed.
184    #[must_use]
185    pub fn paths(&self) -> Vec<&str> {
186        self.entries
187            .iter()
188            .map(|entry| entry.path.as_str())
189            .collect()
190    }
191
192    /// How many pages were declared.
193    #[must_use]
194    pub fn len(&self) -> usize {
195        self.entries.len()
196    }
197
198    /// Whether nothing was declared.
199    #[must_use]
200    pub fn is_empty(&self) -> bool {
201        self.entries.is_empty()
202    }
203
204    /// Every URL that belongs in the sitemap.
205    ///
206    /// # Errors
207    ///
208    /// [`WebServerError::DynamicPagePathHasParameters`] if a listed page's path
209    /// contains a route parameter, which cannot be resolved to one URL.
210    /// Every asset path the declared pages reference.
211    ///
212    /// Static pages only: a dynamic page builds its `PageTemplateData` per
213    /// request, so there is nothing to inspect at boot.
214    #[must_use]
215    pub fn declared_assets(&self) -> Vec<String> {
216        self.entries
217            .iter()
218            .filter_map(|entry| match &entry.kind {
219                PageKind::Static { page, .. } => Some(page.declared_assets()),
220                PageKind::Dynamic(_) => None,
221            })
222            .flatten()
223            .collect()
224    }
225
226    /// Every listed page as a sitemap entry.
227    ///
228    /// # Errors
229    ///
230    /// [`WebServerError::DynamicPagePathHasParameters`] if a listed page's path
231    /// contains a route parameter, which cannot become a single sitemap URL.
232    pub fn sitemap_urls(&self) -> Result<Vec<SitemapUrl>, WebServerError> {
233        let mut urls: Vec<SitemapUrl> = Vec::new();
234
235        for entry in &self.entries {
236            let Listing::Listed(entry_urls) = &entry.listing else {
237                continue;
238            };
239            for url in entry_urls {
240                if has_route_parameter(url.path()) {
241                    return Err(WebServerError::DynamicPagePathHasParameters {
242                        path: entry.path.clone(),
243                    });
244                }
245                urls.push(url.clone());
246            }
247        }
248
249        Ok(urls)
250    }
251
252    /// Turns every declaration into routes.
253    ///
254    /// Each page also answers its opposite trailing-slash form with a 308 to
255    /// the declared path, query kept, for every method. The redirect is matched
256    /// by pattern, before any layer on the page's method router runs, so a
257    /// guard or a handler's 404 still answers at the canonical URL.
258    ///
259    /// # Errors
260    ///
261    /// [`WebServerError::DuplicatePagePath`] if two pages share a path, or
262    /// differ only by a trailing slash.
263    pub(super) fn into_router(self) -> Result<axum::Router<WebServerState<S>>, WebServerError> {
264        let mut declared: HashMap<&str, &str> = HashMap::new();
265        for entry in &self.entries {
266            if let Some(first) = declared.insert(without_trailing_slash(&entry.path), &entry.path) {
267                return Err(WebServerError::DuplicatePagePath {
268                    first: first.to_string(),
269                    second: entry.path.clone(),
270                });
271            }
272        }
273
274        let mut router: axum::Router<WebServerState<S>> = axum::Router::new();
275
276        for entry in self.entries {
277            let method_router: MethodRouter<WebServerState<S>> = match entry.kind {
278                PageKind::Static { page, data } => static_page_handler(page, data),
279                PageKind::Dynamic(handler) => *handler,
280            };
281            router = if has_trailing_slash_alias(&entry.path) {
282                router.route_with_tsr(&entry.path, method_router)
283            } else {
284                router.route(&entry.path, method_router)
285            };
286        }
287
288        Ok(router)
289    }
290}
291
292/// The path with one trailing slash removed, so `/blog` and `/blog/` collide.
293fn without_trailing_slash(path: &str) -> &str {
294    path.strip_suffix('/').unwrap_or(path)
295}
296
297/// Whether a page also answers its opposite trailing-slash form.
298///
299/// Not `/`, which has no other form, and not a wildcard, which already matches
300/// any suffix and cannot be followed by a slash.
301fn has_trailing_slash_alias(path: &str) -> bool {
302    path != "/" && !path.contains("{*")
303}
304
305/// Builds the handler for a page that has no handler function.
306fn static_page_handler<S>(
307    page: Arc<PageTemplateData>,
308    data: Arc<Value>,
309) -> MethodRouter<WebServerState<S>>
310where
311    S: Clone + Send + Sync + 'static,
312{
313    get(move |State(state): State<WebServerState<S>>| {
314        let page: Arc<PageTemplateData> = Arc::clone(&page);
315        let data: Arc<Value> = Arc::clone(&data);
316        async move { render_or_500(&state, &page, &data) }
317    })
318}
319
320/// Renders a declared page, turning a failure into a 500.
321pub(super) fn render_or_500<S>(
322    state: &WebServerState<S>,
323    page: &PageTemplateData,
324    data: &Value,
325) -> Response {
326    match state.render(page, data) {
327        Ok(html) => html.into_response(),
328        Err(error) => {
329            error!("failed to render `{}`: {error}", page.page_url());
330            error.into_response()
331        }
332    }
333}
334
335/// Whether an axum path pattern matches more than one URL.
336fn has_route_parameter(path: &str) -> bool {
337    path.contains(':') || path.contains('*') || path.contains('{')
338}
339
340#[cfg(test)]
341mod tests {
342
343    use chrono::TimeZone;
344
345    use crate::sitemap::SitemapUrl;
346    use crate::templates::PageTemplateData;
347    use crate::webserver::error::WebServerError;
348
349    use super::{Pages, has_route_parameter};
350
351    #[test]
352    fn a_static_page_takes_its_route_from_its_page_url() {
353        let pages: Pages = Pages::new()
354            .static_page(PageTemplateData::new("home", "Home", "/"), ())
355            .static_page(PageTemplateData::new("music", "Music", "/music"), ());
356
357        let expected_len: usize = 2;
358        let actual_len: usize = pages.len();
359        assert_eq!(expected_len, actual_len);
360
361        let expected_paths: Vec<String> = vec![String::from("/"), String::from("/music")];
362        let actual_paths: Vec<String> = pages
363            .sitemap_urls()
364            .expect("no parameters")
365            .iter()
366            .map(|url| url.path().to_string())
367            .collect();
368        assert_eq!(expected_paths, actual_paths);
369    }
370
371    #[test]
372    fn unlisted_keeps_a_page_routed_but_out_of_the_sitemap() {
373        let pages: Pages = Pages::new()
374            .static_page(PageTemplateData::new("home", "Home", "/"), ())
375            .static_page(PageTemplateData::new("secret", "Secret", "/secret"), ())
376            .unlisted();
377
378        let expected_routes: usize = 2;
379        let actual_routes: usize = pages.len();
380        assert_eq!(expected_routes, actual_routes);
381
382        let expected_listed: Vec<String> = vec![String::from("/")];
383        let actual_listed: Vec<String> = pages
384            .sitemap_urls()
385            .expect("no parameters")
386            .iter()
387            .map(|url| url.path().to_string())
388            .collect();
389        assert_eq!(expected_listed, actual_listed);
390    }
391
392    #[test]
393    fn a_group_lists_the_urls_it_was_given_not_its_pattern() {
394        let pages: Pages = Pages::new().dynamic_page_group(
395            "/blog/{slug}",
396            axum::routing::get(|| async { "post" }),
397            [
398                SitemapUrl::new("/blog/first"),
399                SitemapUrl::new("/blog/second"),
400            ],
401        );
402
403        let expected: Vec<String> = vec![String::from("/blog/first"), String::from("/blog/second")];
404        let actual: Vec<String> = pages
405            .sitemap_urls()
406            .expect("concrete urls")
407            .iter()
408            .map(|url| url.path().to_string())
409            .collect();
410        assert_eq!(expected, actual);
411    }
412
413    #[test]
414    fn a_parameterised_path_cannot_be_declared_as_a_single_page() {
415        let pages: Pages =
416            Pages::new().dynamic_page("/blog/{slug}", axum::routing::get(|| async { "post" }));
417
418        let error: WebServerError = pages
419            .sitemap_urls()
420            .expect_err("one pattern is not one url");
421        assert!(matches!(
422            error,
423            WebServerError::DynamicPagePathHasParameters { ref path } if path == "/blog/{slug}"
424        ));
425    }
426
427    #[test]
428    fn a_parameterised_path_is_fine_once_it_is_unlisted() {
429        let pages: Pages = Pages::new()
430            .dynamic_page(
431                "/og/{version}/{file}",
432                axum::routing::get(|| async { "card" }),
433            )
434            .unlisted();
435
436        let expected: usize = 0;
437        let actual: usize = pages.sitemap_urls().expect("unlisted").len();
438        assert_eq!(expected, actual);
439    }
440
441    #[test]
442    fn sitemap_modifiers_apply_to_the_page_just_declared() {
443        let modified: chrono::DateTime<chrono::Utc> = chrono::Utc
444            .with_ymd_and_hms(2026, 3, 4, 5, 6, 7)
445            .single()
446            .expect("a real instant");
447
448        let pages: Pages = Pages::new()
449            .static_page(PageTemplateData::new("home", "Home", "/"), ())
450            .static_page(PageTemplateData::new("blog", "Blog", "/blog"), ())
451            .with_last_modified(modified);
452
453        let urls: Vec<SitemapUrl> = pages.sitemap_urls().expect("no parameters");
454
455        assert_eq!(None, urls[0].last_modified());
456        assert_eq!(Some(modified), urls[1].last_modified());
457
458        let expected_path: String = String::from("/blog");
459        let actual_path: String = urls[1].path().to_string();
460        assert_eq!(expected_path, actual_path);
461    }
462
463    #[test]
464    fn route_parameters_are_recognised_in_every_axum_spelling() {
465        assert!(has_route_parameter("/blog/{slug}"));
466        assert!(has_route_parameter("/blog/{slug}"));
467        assert!(has_route_parameter("/files/{*path}"));
468        assert!(!has_route_parameter("/blog"));
469        assert!(!has_route_parameter("/"));
470    }
471
472    #[test]
473    fn declarations_actually_build_a_router() {
474        // Route syntax is validated when axum registers the path, not when this
475        // module compiles — so the router has to actually be built here.
476        let pages: Pages = Pages::new()
477            .static_page(PageTemplateData::new("home", "Home", "/"), ())
478            .dynamic_page("/blog", axum::routing::get(|| async { "index" }))
479            .dynamic_page_group(
480                "/blog/{slug}",
481                axum::routing::get(|| async { "post" }),
482                [SitemapUrl::new("/blog/first")],
483            )
484            .unlisted();
485
486        let _router: axum::Router<crate::webserver::WebServerState> =
487            pages.into_router().expect("no duplicate paths");
488    }
489
490    #[test]
491    fn a_declaration_starts_empty() {
492        let pages: Pages = Pages::new();
493
494        let expected: bool = true;
495        let actual: bool = pages.is_empty();
496        assert_eq!(expected, actual);
497    }
498
499    #[test]
500    fn declared_assets_are_collected_from_static_pages_for_boot_validation() {
501        let pages: Pages = Pages::new().static_page(
502            PageTemplateData::new("blog", "Blog", "/blog")
503                .extend_style_sheets(["static/stylesheet/blog.css"])
504                .with_social_image("static/image/social/blog.webp"),
505            (),
506        );
507
508        let declared: Vec<String> = pages.declared_assets();
509        assert!(declared.contains(&String::from("static/stylesheet/blog.css")));
510        assert!(declared.contains(&String::from("static/image/social/blog.webp")));
511    }
512}