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 jiff::Timestamp;
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: Timestamp) -> 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    /// The patterns of the 308 redirects [`Self::into_router`] adds: each
253    /// page's opposite trailing-slash form. Matched exactly, never as a prefix.
254    pub(super) fn redirect_routes(&self) -> Vec<String> {
255        self.entries
256            .iter()
257            .filter(|entry| has_trailing_slash_alias(&entry.path))
258            .map(|entry| match entry.path.strip_suffix('/') {
259                Some(without) => without.to_owned(),
260                None => format!("{}/", entry.path),
261            })
262            .collect()
263    }
264
265    /// Turns every declaration into routes.
266    ///
267    /// Each page also answers its opposite trailing-slash form with a 308 to
268    /// the declared path, query kept, for every method. The redirect is matched
269    /// by pattern, before any layer on the page's method router runs, so a
270    /// guard or a handler's 404 still answers at the canonical URL.
271    ///
272    /// # Errors
273    ///
274    /// [`WebServerError::DuplicatePagePath`] if two pages share a path, or
275    /// differ only by a trailing slash.
276    pub(super) fn into_router(self) -> Result<axum::Router<WebServerState<S>>, WebServerError> {
277        let mut declared: HashMap<&str, &str> = HashMap::new();
278        for entry in &self.entries {
279            if let Some(first) = declared.insert(without_trailing_slash(&entry.path), &entry.path) {
280                return Err(WebServerError::DuplicatePagePath {
281                    first: first.to_string(),
282                    second: entry.path.clone(),
283                });
284            }
285        }
286
287        let mut router: axum::Router<WebServerState<S>> = axum::Router::new();
288
289        for entry in self.entries {
290            let method_router: MethodRouter<WebServerState<S>> = match entry.kind {
291                PageKind::Static { page, data } => static_page_handler(page, data),
292                PageKind::Dynamic(handler) => *handler,
293            };
294            router = if has_trailing_slash_alias(&entry.path) {
295                router.route_with_tsr(&entry.path, method_router)
296            } else {
297                router.route(&entry.path, method_router)
298            };
299        }
300
301        Ok(router)
302    }
303}
304
305/// The path with one trailing slash removed, so `/blog` and `/blog/` collide.
306fn without_trailing_slash(path: &str) -> &str {
307    path.strip_suffix('/').unwrap_or(path)
308}
309
310/// Whether a page also answers its opposite trailing-slash form.
311///
312/// Not `/`, which has no other form, and not a wildcard, which already matches
313/// any suffix and cannot be followed by a slash.
314fn has_trailing_slash_alias(path: &str) -> bool {
315    path != "/" && !path.contains("{*")
316}
317
318/// Builds the handler for a page that has no handler function.
319fn static_page_handler<S>(
320    page: Arc<PageTemplateData>,
321    data: Arc<Value>,
322) -> MethodRouter<WebServerState<S>>
323where
324    S: Clone + Send + Sync + 'static,
325{
326    get(move |State(state): State<WebServerState<S>>| {
327        let page: Arc<PageTemplateData> = Arc::clone(&page);
328        let data: Arc<Value> = Arc::clone(&data);
329        async move { render_or_500(&state, &page, &data) }
330    })
331}
332
333/// Renders a declared page, turning a failure into a 500.
334pub(super) fn render_or_500<S>(
335    state: &WebServerState<S>,
336    page: &PageTemplateData,
337    data: &Value,
338) -> Response {
339    match state.render(page, data) {
340        Ok(html) => html.into_response(),
341        Err(error) => {
342            error!("failed to render `{}`: {error}", page.page_url());
343            error.into_response()
344        }
345    }
346}
347
348/// Whether an axum path pattern matches more than one URL.
349fn has_route_parameter(path: &str) -> bool {
350    path.contains(':') || path.contains('*') || path.contains('{')
351}
352
353#[cfg(test)]
354mod tests {
355
356    use crate::sitemap::SitemapUrl;
357    use crate::templates::PageTemplateData;
358    use crate::webserver::error::WebServerError;
359
360    use super::{Pages, has_route_parameter};
361
362    #[test]
363    fn a_static_page_takes_its_route_from_its_page_url() {
364        let pages: Pages = Pages::new()
365            .static_page(PageTemplateData::new("home", "Home", "/"), ())
366            .static_page(PageTemplateData::new("music", "Music", "/music"), ());
367
368        let expected_len: usize = 2;
369        let actual_len: usize = pages.len();
370        assert_eq!(expected_len, actual_len);
371
372        let expected_paths: Vec<String> = vec![String::from("/"), String::from("/music")];
373        let actual_paths: Vec<String> = pages
374            .sitemap_urls()
375            .expect("no parameters")
376            .iter()
377            .map(|url| url.path().to_string())
378            .collect();
379        assert_eq!(expected_paths, actual_paths);
380    }
381
382    #[test]
383    fn unlisted_keeps_a_page_routed_but_out_of_the_sitemap() {
384        let pages: Pages = Pages::new()
385            .static_page(PageTemplateData::new("home", "Home", "/"), ())
386            .static_page(PageTemplateData::new("secret", "Secret", "/secret"), ())
387            .unlisted();
388
389        let expected_routes: usize = 2;
390        let actual_routes: usize = pages.len();
391        assert_eq!(expected_routes, actual_routes);
392
393        let expected_listed: Vec<String> = vec![String::from("/")];
394        let actual_listed: Vec<String> = pages
395            .sitemap_urls()
396            .expect("no parameters")
397            .iter()
398            .map(|url| url.path().to_string())
399            .collect();
400        assert_eq!(expected_listed, actual_listed);
401    }
402
403    #[test]
404    fn a_group_lists_the_urls_it_was_given_not_its_pattern() {
405        let pages: Pages = Pages::new().dynamic_page_group(
406            "/blog/{slug}",
407            axum::routing::get(|| async { "post" }),
408            [
409                SitemapUrl::new("/blog/first"),
410                SitemapUrl::new("/blog/second"),
411            ],
412        );
413
414        let expected: Vec<String> = vec![String::from("/blog/first"), String::from("/blog/second")];
415        let actual: Vec<String> = pages
416            .sitemap_urls()
417            .expect("concrete urls")
418            .iter()
419            .map(|url| url.path().to_string())
420            .collect();
421        assert_eq!(expected, actual);
422    }
423
424    #[test]
425    fn a_parameterised_path_cannot_be_declared_as_a_single_page() {
426        let pages: Pages =
427            Pages::new().dynamic_page("/blog/{slug}", axum::routing::get(|| async { "post" }));
428
429        let error: WebServerError = pages
430            .sitemap_urls()
431            .expect_err("one pattern is not one url");
432        assert!(matches!(
433            error,
434            WebServerError::DynamicPagePathHasParameters { ref path } if path == "/blog/{slug}"
435        ));
436    }
437
438    #[test]
439    fn a_parameterised_path_is_fine_once_it_is_unlisted() {
440        let pages: Pages = Pages::new()
441            .dynamic_page(
442                "/og/{version}/{file}",
443                axum::routing::get(|| async { "card" }),
444            )
445            .unlisted();
446
447        let expected: usize = 0;
448        let actual: usize = pages.sitemap_urls().expect("unlisted").len();
449        assert_eq!(expected, actual);
450    }
451
452    #[test]
453    fn sitemap_modifiers_apply_to_the_page_just_declared() {
454        let modified: jiff::Timestamp = "2026-03-04T05:06:07Z".parse().expect("a real instant");
455
456        let pages: Pages = Pages::new()
457            .static_page(PageTemplateData::new("home", "Home", "/"), ())
458            .static_page(PageTemplateData::new("blog", "Blog", "/blog"), ())
459            .with_last_modified(modified);
460
461        let urls: Vec<SitemapUrl> = pages.sitemap_urls().expect("no parameters");
462
463        assert_eq!(None, urls[0].last_modified());
464        assert_eq!(Some(modified), urls[1].last_modified());
465
466        let expected_path: String = String::from("/blog");
467        let actual_path: String = urls[1].path().to_string();
468        assert_eq!(expected_path, actual_path);
469    }
470
471    #[test]
472    fn route_parameters_are_recognised_in_every_axum_spelling() {
473        assert!(has_route_parameter("/blog/{slug}"));
474        assert!(has_route_parameter("/blog/{slug}"));
475        assert!(has_route_parameter("/files/{*path}"));
476        assert!(!has_route_parameter("/blog"));
477        assert!(!has_route_parameter("/"));
478    }
479
480    #[test]
481    fn declarations_actually_build_a_router() {
482        // Route syntax is validated when axum registers the path, not when this
483        // module compiles — so the router has to actually be built here.
484        let pages: Pages = Pages::new()
485            .static_page(PageTemplateData::new("home", "Home", "/"), ())
486            .dynamic_page("/blog", axum::routing::get(|| async { "index" }))
487            .dynamic_page_group(
488                "/blog/{slug}",
489                axum::routing::get(|| async { "post" }),
490                [SitemapUrl::new("/blog/first")],
491            )
492            .unlisted();
493
494        let _router: axum::Router<crate::webserver::WebServerState> =
495            pages.into_router().expect("no duplicate paths");
496    }
497
498    #[test]
499    fn a_declaration_starts_empty() {
500        let pages: Pages = Pages::new();
501
502        let expected: bool = true;
503        let actual: bool = pages.is_empty();
504        assert_eq!(expected, actual);
505    }
506
507    #[test]
508    fn declared_assets_are_collected_from_static_pages_for_boot_validation() {
509        let pages: Pages = Pages::new().static_page(
510            PageTemplateData::new("blog", "Blog", "/blog")
511                .extend_style_sheets(["static/stylesheet/blog.css"])
512                .with_social_image("static/image/social/blog.webp"),
513            (),
514        );
515
516        let declared: Vec<String> = pages.declared_assets();
517        assert!(declared.contains(&String::from("static/stylesheet/blog.css")));
518        assert!(declared.contains(&String::from("static/image/social/blog.webp")));
519    }
520}