Skip to main content

rustango_cms/
page_view.rs

1//! What a page type serves on its public URL, and how `Accept` picks.
2//!
3//! Most page types render a Tera template. Some — feeds a CRM consumes,
4//! endpoints that only ever answer machines — have no template at all
5//! and exist purely to return JSON. Before this module that was
6//! unsayable: [`crate::page_type::PageTypeHandler::default_template`]
7//! is a required `&'static str`, and `render_inner` hands whatever it
8//! finds straight to Tera, so a blank template is a 500.
9//!
10//! Two enums, deliberately distinct:
11//!
12//! - [`PageViewMode`] is what the operator *declares* and what the
13//!   `cms_page_type.view_mode` column stores. `Auto` is the default and
14//!   means "work it out from the template".
15//! - [`PageViewKind`] is what [`resolve_kind`] *decides*, and it is the
16//!   only thing the renderer branches on.
17//!
18//! ## `Auto` never opens a JSON view on a page that has a template
19//!
20//! It would be tempting to make `Auto` mean "negotiate on everything".
21//! That would silently publish a JSON representation of every page's
22//! `extension` + `builder` values on every existing site the moment
23//! this ships — including hosts that deliberately never mounted
24//! [`crate::api::router`]. So `Auto` + a template is HTML-only and
25//! ignores `Accept` entirely. Since every existing `cms_page_type` row
26//! has a non-empty `default_template`, the upgrade is a no-op. Serving
27//! JSON from a page that also renders HTML is opt-in via
28//! [`PageViewMode::Api`].
29
30use serde::{Deserialize, Serialize};
31
32/// The declared mode, stored in `cms_page_type.view_mode`.
33#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
34#[serde(rename_all = "snake_case")]
35pub enum PageViewMode {
36    /// Derive from the template: blank means JSON-only, otherwise HTML.
37    #[default]
38    Auto,
39    /// Force the template path; `Accept` is ignored.
40    Html,
41    /// Serve JSON at the page's own URL. When the type *also* has a
42    /// template, that template still answers `Accept: text/html`.
43    Api,
44}
45
46impl PageViewMode {
47    #[must_use]
48    pub fn as_str(self) -> &'static str {
49        match self {
50            Self::Auto => "auto",
51            Self::Html => "html",
52            Self::Api => "api",
53        }
54    }
55
56    /// Lenient by design — anything unrecognised reads as [`Self::Auto`].
57    ///
58    /// Unlike [`crate::view_restriction::RestrictionKind::parse`] this
59    /// returns `Self`, not `Option<Self>`: during a rolling deploy an
60    /// older binary can meet a row written by a newer one, and falling
61    /// back to the "behave exactly as before" mode is strictly safer
62    /// than erroring on a page request.
63    #[must_use]
64    pub fn parse(raw: &str) -> Self {
65        match raw.trim() {
66            "html" => Self::Html,
67            "api" => Self::Api,
68            _ => Self::Auto,
69        }
70    }
71}
72
73/// What a page type can actually serve, once the declared mode and the
74/// template have been reconciled. This is what the renderer branches on.
75#[derive(Debug, Clone, Copy, PartialEq, Eq)]
76pub enum PageViewKind {
77    /// Template only. No JSON representation exists; `Accept` is ignored.
78    Html,
79    /// JSON only — there is no usable template. Served whatever the
80    /// client asks for, because it is the sole representation.
81    ApiOnly,
82    /// Both representations exist; negotiate on `Accept`.
83    ApiWithTemplate,
84    /// `view_mode = "html"` was declared but the template is blank.
85    /// Nothing is renderable — a misconfiguration, not a mode.
86    Unrenderable,
87}
88
89impl PageViewKind {
90    /// Whether this kind can produce a JSON body at all.
91    #[must_use]
92    pub fn serves_json(self) -> bool {
93        matches!(self, Self::ApiOnly | Self::ApiWithTemplate)
94    }
95
96    /// Whether a Tera template will be rendered for this kind.
97    #[must_use]
98    pub fn serves_html(self) -> bool {
99        matches!(self, Self::Html | Self::ApiWithTemplate)
100    }
101}
102
103/// Reconcile a declared mode with the template actually on the row.
104///
105/// Pure and synchronous. It reads the **stored strings**, not the
106/// handler, for the same reason `render_inner` renders
107/// `pt.default_template` rather than `handler.default_template()`: the
108/// column is the runtime source of truth, UI-created page types have no
109/// handler at all, and keeping it pure makes the whole decision table
110/// unit-testable without a pool.
111#[must_use]
112pub fn resolve_kind(view_mode: &str, default_template: &str) -> PageViewKind {
113    let has_template = !default_template.trim().is_empty();
114    match (PageViewMode::parse(view_mode), has_template) {
115        (PageViewMode::Auto, true) => PageViewKind::Html,
116        // The autodetect: no template and nothing declared ⇒ JSON.
117        (PageViewMode::Auto, false) => PageViewKind::ApiOnly,
118        (PageViewMode::Api, true) => PageViewKind::ApiWithTemplate,
119        (PageViewMode::Api, false) => PageViewKind::ApiOnly,
120        (PageViewMode::Html, true) => PageViewKind::Html,
121        (PageViewMode::Html, false) => PageViewKind::Unrenderable,
122    }
123}
124
125/// [`resolve_kind`] over a loaded registry row.
126#[must_use]
127pub fn kind_for(row: &crate::page_type_model::PageType) -> PageViewKind {
128    resolve_kind(&row.view_mode, &row.default_template)
129}
130
131/// The coarse media-type preference distilled from an `Accept` header.
132#[derive(Debug, Clone, Copy, PartialEq, Eq)]
133pub enum Accept {
134    /// The client asked for HTML, or asked for both and tied.
135    Html,
136    /// The client asked for JSON more strongly than HTML.
137    Json,
138    /// No usable preference — `*/*`, a missing header, or nothing we
139    /// recognise. Each [`PageViewKind`] picks its own canonical answer.
140    Any,
141}
142
143/// Parse an `Accept` header into a coarse preference.
144///
145/// Deliberately *not* the `accept.contains("application/json")` check
146/// used by the admin's own `fetch()` helpers
147/// (`crate::admin::handlers::wants_json_response`). That test is fine
148/// for a request the admin JS made itself, but wrong on a public URL:
149/// it flips to JSON on `text/html, application/json;q=0.1`, where the
150/// client clearly prefers HTML, and it treats `application/json;q=0` —
151/// an explicit *refusal* — as a request for JSON.
152///
153/// Quality values are honoured, `q=0` rejects a type outright, and a
154/// more specific range outranks a wildcard at equal `q`. **A tie goes
155/// to HTML**, so a browser sending `text/html,…,*/*;q=0.8` can never be
156/// handed a JSON body.
157#[must_use]
158pub fn parse_accept(raw: Option<&str>) -> Accept {
159    // (quality, specificity) — specificity 2 = exact type, 1 = subtype
160    // wildcard. `*/*` scores neither: it means "anything", which is
161    // `Any`, not a vote for either side.
162    let mut best_json: Option<(f32, u8)> = None;
163    let mut best_html: Option<(f32, u8)> = None;
164
165    for entry in raw.unwrap_or("").split(',') {
166        let mut parts = entry.split(';');
167        let Some(range) = parts.next() else { continue };
168        let range = range.trim().to_ascii_lowercase();
169        if range.is_empty() {
170            continue;
171        }
172
173        let mut q = 1.0_f32;
174        for param in parts {
175            let param = param.trim();
176            if let Some(v) = param.strip_prefix("q=") {
177                // A malformed q is not a reason to reject the entry —
178                // fall back to the default rather than erroring.
179                q = v.trim().parse::<f32>().unwrap_or(1.0).clamp(0.0, 1.0);
180            }
181        }
182        // `q=0` means "I will not accept this".
183        if q <= 0.0 {
184            continue;
185        }
186
187        let scored = match range.as_str() {
188            "application/json" => Some((&mut best_json, 2u8)),
189            "application/*" => Some((&mut best_json, 1)),
190            "text/html" | "application/xhtml+xml" => Some((&mut best_html, 2)),
191            "text/*" => Some((&mut best_html, 1)),
192            _ => None,
193        };
194        if let Some((slot, specificity)) = scored {
195            let candidate = (q, specificity);
196            if slot.is_none_or(|current| candidate > current) {
197                *slot = Some(candidate);
198            }
199        }
200    }
201
202    match (best_json, best_html) {
203        (None, None) => Accept::Any,
204        (Some(_), None) => Accept::Json,
205        (None, Some(_)) => Accept::Html,
206        // Ties go to HTML.
207        (Some(j), Some(h)) => {
208            if j > h {
209                Accept::Json
210            } else {
211                Accept::Html
212            }
213        }
214    }
215}
216
217#[cfg(test)]
218mod tests {
219    use super::*;
220
221    #[test]
222    fn mode_round_trips_and_unknown_reads_as_auto() {
223        for m in [PageViewMode::Auto, PageViewMode::Html, PageViewMode::Api] {
224            assert_eq!(PageViewMode::parse(m.as_str()), m);
225        }
226        // Forward-compat: a mode written by a newer binary must not
227        // break an older one mid-rollout.
228        assert_eq!(PageViewMode::parse("both"), PageViewMode::Auto);
229        assert_eq!(PageViewMode::parse(""), PageViewMode::Auto);
230        assert_eq!(PageViewMode::parse("  api  "), PageViewMode::Api);
231    }
232
233    #[test]
234    fn auto_derives_the_kind_from_the_template() {
235        assert_eq!(resolve_kind("auto", "page.html"), PageViewKind::Html);
236        assert_eq!(resolve_kind("auto", ""), PageViewKind::ApiOnly);
237        // Whitespace counts as blank — matches `DbSchemaPageType::from_row`.
238        assert_eq!(resolve_kind("auto", "   "), PageViewKind::ApiOnly);
239    }
240
241    #[test]
242    fn an_explicit_mode_overrides_the_autodetect() {
243        assert_eq!(
244            resolve_kind("api", "page.html"),
245            PageViewKind::ApiWithTemplate
246        );
247        assert_eq!(resolve_kind("api", ""), PageViewKind::ApiOnly);
248        assert_eq!(resolve_kind("html", "page.html"), PageViewKind::Html);
249        // Declared HTML with nothing to render: a real misconfiguration,
250        // and the state that shows "Preview is not available".
251        assert_eq!(resolve_kind("html", ""), PageViewKind::Unrenderable);
252    }
253
254    #[test]
255    fn an_unknown_mode_behaves_exactly_as_before() {
256        // The whole point of the lenient parse: an existing row, or one
257        // from a newer binary, must keep rendering its template.
258        assert_eq!(resolve_kind("", "page.html"), PageViewKind::Html);
259        assert_eq!(resolve_kind("someday", "page.html"), PageViewKind::Html);
260    }
261
262    #[test]
263    fn browsers_always_get_html() {
264        // The real strings, verbatim.
265        let chrome = "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,\
266                      image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7";
267        assert_eq!(parse_accept(Some(chrome)), Accept::Html);
268        let safari = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";
269        assert_eq!(parse_accept(Some(safari)), Accept::Html);
270    }
271
272    #[test]
273    fn wildcards_and_absent_headers_express_no_preference() {
274        assert_eq!(parse_accept(None), Accept::Any);
275        assert_eq!(parse_accept(Some("")), Accept::Any);
276        assert_eq!(parse_accept(Some("*/*")), Accept::Any);
277    }
278
279    #[test]
280    fn json_clients_get_json() {
281        assert_eq!(parse_accept(Some("application/json")), Accept::Json);
282        // axios' default.
283        assert_eq!(
284            parse_accept(Some("application/json, text/plain, */*")),
285            Accept::Json
286        );
287        assert_eq!(parse_accept(Some("application/*")), Accept::Json);
288    }
289
290    #[test]
291    fn quality_values_decide_and_a_tie_goes_to_html() {
292        assert_eq!(
293            parse_accept(Some("text/html;q=0.5, application/json;q=0.9")),
294            Accept::Json
295        );
296        // The case a `contains("application/json")` check gets wrong.
297        assert_eq!(
298            parse_accept(Some("application/json;q=0.1, text/html")),
299            Accept::Html
300        );
301        // Equal q: HTML wins, so a browser is never handed JSON.
302        assert_eq!(
303            parse_accept(Some("application/json, text/html")),
304            Accept::Html
305        );
306    }
307
308    #[test]
309    fn q_zero_is_a_refusal_not_a_request() {
310        // The second case a `contains()` check gets wrong.
311        assert_eq!(parse_accept(Some("application/json;q=0")), Accept::Any);
312        assert_eq!(
313            parse_accept(Some("application/json;q=0, text/html")),
314            Accept::Html
315        );
316    }
317
318    #[test]
319    fn malformed_input_never_panics() {
320        for raw in ["))((", "text/html;q=notanumber", ";;;", ",,,", "q=1"] {
321            let _ = parse_accept(Some(raw));
322        }
323        assert_eq!(parse_accept(Some("text/html;q=notanumber")), Accept::Html);
324    }
325
326    #[test]
327    fn kinds_report_what_they_can_serve() {
328        assert!(PageViewKind::ApiOnly.serves_json());
329        assert!(!PageViewKind::ApiOnly.serves_html());
330        assert!(PageViewKind::ApiWithTemplate.serves_json());
331        assert!(PageViewKind::ApiWithTemplate.serves_html());
332        assert!(!PageViewKind::Html.serves_json());
333        assert!(!PageViewKind::Unrenderable.serves_json());
334        assert!(!PageViewKind::Unrenderable.serves_html());
335    }
336}