Skip to main content

webserver_base/webserver/
not_found.rs

1//! The data a frontend's router-fallback 404 renders with.
2//!
3//! The 404 itself — template, status, URL, `noindex` — is the library's. Only
4//! its `{{app}}` is the project's, and only for the fallback: a handler that
5//! matched its route passes its own to
6//! [`WebServerState::not_found`](super::WebServerState::not_found).
7
8use std::future::Future;
9use std::pin::Pin;
10use std::sync::Arc;
11
12use axum::http::Uri;
13use serde::Serialize;
14use serde_json::Value;
15use tracing::error;
16
17use super::state::WebServerState;
18
19type Hook<S> =
20    dyn Fn(WebServerState<S>, Uri) -> Pin<Box<dyn Future<Output = Value> + Send>> + Send + Sync;
21
22/// What the router-fallback 404 shows as `{{app}}`.
23///
24/// `{{site}}` is already on it, so most sites need [`NotFound::none`]. Reach
25/// for [`NotFound::with`] when the 404 should depend on what was asked for —
26/// a "did you mean" link, the latest posts.
27pub struct NotFound<S = ()> {
28    hook: Option<Arc<Hook<S>>>,
29}
30
31impl<S> NotFound<S>
32where
33    S: Clone + Send + Sync + 'static,
34{
35    /// `{{app}}` is `null`.
36    #[must_use]
37    pub const fn none() -> Self {
38        Self { hook: None }
39    }
40
41    /// `{{app}}` is whatever `hook` returns for the requested URI.
42    ///
43    /// Runs on every unmatched request, bots' probes included, so keep it
44    /// cheap. Data that fails to serialize is reported and rendered as `null`
45    /// rather than failing the request.
46    #[must_use]
47    pub fn with<F, Fut, A>(hook: F) -> Self
48    where
49        F: Fn(WebServerState<S>, Uri) -> Fut + Send + Sync + 'static,
50        Fut: Future<Output = A> + Send + 'static,
51        A: Serialize,
52    {
53        Self {
54            hook: Some(Arc::new(move |state: WebServerState<S>, uri: Uri| {
55                let data: Fut = hook(state, uri);
56                Box::pin(async move { to_value_or_null(&data.await) })
57            })),
58        }
59    }
60
61    /// The `{{app}}` for a request to `uri`.
62    pub(super) async fn data(&self, state: WebServerState<S>, uri: Uri) -> Value {
63        match &self.hook {
64            None => Value::Null,
65            Some(hook) => hook(state, uri).await,
66        }
67    }
68}
69
70impl<S> Clone for NotFound<S> {
71    fn clone(&self) -> Self {
72        Self {
73            hook: self.hook.clone(),
74        }
75    }
76}
77
78impl<S> Default for NotFound<S>
79where
80    S: Clone + Send + Sync + 'static,
81{
82    fn default() -> Self {
83        Self::none()
84    }
85}
86
87fn to_value_or_null<A>(data: &A) -> Value
88where
89    A: Serialize,
90{
91    serde_json::to_value(data).unwrap_or_else(|serialize_error| {
92        error!("the 404 hook's data is unserializable, rendering with null: {serialize_error}");
93        Value::Null
94    })
95}