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    /// 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 chrono::TimeZone;
357
358    use crate::sitemap::SitemapUrl;
359    use crate::templates::PageTemplateData;
360    use crate::webserver::error::WebServerError;
361
362    use super::{Pages, has_route_parameter};
363
364    #[test]
365    fn a_static_page_takes_its_route_from_its_page_url() {
366        let pages: Pages = Pages::new()
367            .static_page(PageTemplateData::new("home", "Home", "/"), ())
368            .static_page(PageTemplateData::new("music", "Music", "/music"), ());
369
370        let expected_len: usize = 2;
371        let actual_len: usize = pages.len();
372        assert_eq!(expected_len, actual_len);
373
374        let expected_paths: Vec<String> = vec![String::from("/"), String::from("/music")];
375        let actual_paths: Vec<String> = pages
376            .sitemap_urls()
377            .expect("no parameters")
378            .iter()
379            .map(|url| url.path().to_string())
380            .collect();
381        assert_eq!(expected_paths, actual_paths);
382    }
383
384    #[test]
385    fn unlisted_keeps_a_page_routed_but_out_of_the_sitemap() {
386        let pages: Pages = Pages::new()
387            .static_page(PageTemplateData::new("home", "Home", "/"), ())
388            .static_page(PageTemplateData::new("secret", "Secret", "/secret"), ())
389            .unlisted();
390
391        let expected_routes: usize = 2;
392        let actual_routes: usize = pages.len();
393        assert_eq!(expected_routes, actual_routes);
394
395        let expected_listed: Vec<String> = vec![String::from("/")];
396        let actual_listed: Vec<String> = pages
397            .sitemap_urls()
398            .expect("no parameters")
399            .iter()
400            .map(|url| url.path().to_string())
401            .collect();
402        assert_eq!(expected_listed, actual_listed);
403    }
404
405    #[test]
406    fn a_group_lists_the_urls_it_was_given_not_its_pattern() {
407        let pages: Pages = Pages::new().dynamic_page_group(
408            "/blog/{slug}",
409            axum::routing::get(|| async { "post" }),
410            [
411                SitemapUrl::new("/blog/first"),
412                SitemapUrl::new("/blog/second"),
413            ],
414        );
415
416        let expected: Vec<String> = vec![String::from("/blog/first"), String::from("/blog/second")];
417        let actual: Vec<String> = pages
418            .sitemap_urls()
419            .expect("concrete urls")
420            .iter()
421            .map(|url| url.path().to_string())
422            .collect();
423        assert_eq!(expected, actual);
424    }
425
426    #[test]
427    fn a_parameterised_path_cannot_be_declared_as_a_single_page() {
428        let pages: Pages =
429            Pages::new().dynamic_page("/blog/{slug}", axum::routing::get(|| async { "post" }));
430
431        let error: WebServerError = pages
432            .sitemap_urls()
433            .expect_err("one pattern is not one url");
434        assert!(matches!(
435            error,
436            WebServerError::DynamicPagePathHasParameters { ref path } if path == "/blog/{slug}"
437        ));
438    }
439
440    #[test]
441    fn a_parameterised_path_is_fine_once_it_is_unlisted() {
442        let pages: Pages = Pages::new()
443            .dynamic_page(
444                "/og/{version}/{file}",
445                axum::routing::get(|| async { "card" }),
446            )
447            .unlisted();
448
449        let expected: usize = 0;
450        let actual: usize = pages.sitemap_urls().expect("unlisted").len();
451        assert_eq!(expected, actual);
452    }
453
454    #[test]
455    fn sitemap_modifiers_apply_to_the_page_just_declared() {
456        let modified: chrono::DateTime<chrono::Utc> = chrono::Utc
457            .with_ymd_and_hms(2026, 3, 4, 5, 6, 7)
458            .single()
459            .expect("a real instant");
460
461        let pages: Pages = Pages::new()
462            .static_page(PageTemplateData::new("home", "Home", "/"), ())
463            .static_page(PageTemplateData::new("blog", "Blog", "/blog"), ())
464            .with_last_modified(modified);
465
466        let urls: Vec<SitemapUrl> = pages.sitemap_urls().expect("no parameters");
467
468        assert_eq!(None, urls[0].last_modified());
469        assert_eq!(Some(modified), urls[1].last_modified());
470
471        let expected_path: String = String::from("/blog");
472        let actual_path: String = urls[1].path().to_string();
473        assert_eq!(expected_path, actual_path);
474    }
475
476    #[test]
477    fn route_parameters_are_recognised_in_every_axum_spelling() {
478        assert!(has_route_parameter("/blog/{slug}"));
479        assert!(has_route_parameter("/blog/{slug}"));
480        assert!(has_route_parameter("/files/{*path}"));
481        assert!(!has_route_parameter("/blog"));
482        assert!(!has_route_parameter("/"));
483    }
484
485    #[test]
486    fn declarations_actually_build_a_router() {
487        // Route syntax is validated when axum registers the path, not when this
488        // module compiles — so the router has to actually be built here.
489        let pages: Pages = Pages::new()
490            .static_page(PageTemplateData::new("home", "Home", "/"), ())
491            .dynamic_page("/blog", axum::routing::get(|| async { "index" }))
492            .dynamic_page_group(
493                "/blog/{slug}",
494                axum::routing::get(|| async { "post" }),
495                [SitemapUrl::new("/blog/first")],
496            )
497            .unlisted();
498
499        let _router: axum::Router<crate::webserver::WebServerState> =
500            pages.into_router().expect("no duplicate paths");
501    }
502
503    #[test]
504    fn a_declaration_starts_empty() {
505        let pages: Pages = Pages::new();
506
507        let expected: bool = true;
508        let actual: bool = pages.is_empty();
509        assert_eq!(expected, actual);
510    }
511
512    #[test]
513    fn declared_assets_are_collected_from_static_pages_for_boot_validation() {
514        let pages: Pages = Pages::new().static_page(
515            PageTemplateData::new("blog", "Blog", "/blog")
516                .extend_style_sheets(["static/stylesheet/blog.css"])
517                .with_social_image("static/image/social/blog.webp"),
518            (),
519        );
520
521        let declared: Vec<String> = pages.declared_assets();
522        assert!(declared.contains(&String::from("static/stylesheet/blog.css")));
523        assert!(declared.contains(&String::from("static/image/social/blog.webp")));
524    }
525}