Skip to main content

rustango_cms/
site.rs

1//! Sites — one tenant, several hostnames, each with its own root page.
2//!
3//! The framework's registry answers "which tenant owns this hostname"
4//! ([`rustango::tenancy::OrgHost`]). This answers the next question: once
5//! we are inside the tenant, **which part of the page tree** does that
6//! hostname serve?
7//!
8//! ## How a request finds its page
9//!
10//! Without a site mapping the resolver anchors on the conventional
11//! empty-slug root, so anything else is reachable only under its own
12//! path — `/site-b/about`. Mapping a hostname to that page makes it
13//! answer at `siteb.com/about` instead.
14//!
15//! The mapped page need not be a root. The prefix is only ever its
16//! `url_path`, so `/campaigns/spring` binds to a hostname exactly as a
17//! root does.
18//!
19//! The translation is done at the edges rather than in the stored data:
20//!
21//! * on the way **in**, the request path is prefixed with the site root's
22//!   `url_path` before lookup;
23//! * on the way **out**, that prefix is stripped from generated links.
24//!
25//! `url_path` therefore stays tenant-absolute and `tree_ops` is untouched.
26//! The alternative — storing site-relative paths — means moving a page
27//! between sites rewrites every descendant's URL, and two roots would be
28//! free to collide on `/about` with nothing to tell them apart.
29
30use chrono::{DateTime, Utc};
31use rustango::core::Column as _;
32use rustango::sql::{Auto, ExecError, FetcherPool as _, Pool};
33use rustango::Model;
34use serde::{Deserialize, Serialize};
35
36use crate::page::Page;
37
38/// A hostname bound to a root page within this tenant.
39#[derive(Model, Debug, Clone, Serialize, Deserialize)]
40#[rustango(
41    table = "cms_site",
42    app = "cms",
43    display = "hostname",
44    admin(
45        list_display = "hostname, root_page_id, created_at",
46        ordering = "hostname"
47    )
48)]
49pub struct Site {
50    #[rustango(primary_key)]
51    pub id: Auto<i64>,
52
53    /// Lowercase bare host, matching what the registry stores. Unique
54    /// within the tenant — one hostname cannot serve two roots, or the
55    /// request would have no defined answer.
56    ///
57    /// Not unique *globally*: that is the registry's job, and duplicating
58    /// the constraint here would let the two disagree.
59    #[rustango(max_length = 255, unique, index)]
60    pub hostname: String,
61
62    /// The page this hostname serves as its root. Any page qualifies,
63    /// not only a tree root. Several hostnames may share one page —
64    /// that is how an alias domain works.
65    #[rustango(fk = "cms_page", on = "id", index)]
66    pub root_page_id: i64,
67
68    #[rustango(auto_now_add)]
69    pub created_at: Auto<DateTime<Utc>>,
70}
71
72/// Prefix a public request path with the site root's path.
73///
74/// Free function rather than a method so the translation can be tested
75/// without constructing a `Page` — the prefix is the only input that
76/// matters, and a fixture page would just be noise around it.
77#[must_use]
78pub fn to_lookup_path(prefix: &str, request_path: &str) -> String {
79    if prefix.is_empty() {
80        return request_path.to_owned();
81    }
82    // `/` on a prefixed site means the site root itself.
83    if request_path == "/" || request_path.is_empty() {
84        return prefix.to_owned();
85    }
86    format!("{prefix}{request_path}")
87}
88
89/// Strip the site root's prefix from a tenant-absolute `url_path`.
90///
91/// A page outside this site keeps its absolute path: it is genuinely not
92/// reachable here, and silently rewriting it would produce a link that
93/// 404s rather than one that obviously points elsewhere.
94#[must_use]
95pub fn to_public_path(prefix: &str, url_path: &str) -> String {
96    if prefix.is_empty() {
97        return url_path.to_owned();
98    }
99    match url_path.strip_prefix(prefix) {
100        Some("") => "/".to_owned(),
101        Some(rest) if rest.starts_with('/') => rest.to_owned(),
102        // `"/site-bxyz"` starts with `"/site-b"` textually but is a
103        // different subtree — a prefix match is only real on a boundary.
104        _ => url_path.to_owned(),
105    }
106}
107
108/// The URL prefix `hostname` serves under.
109///
110/// `""` — the conventional root, and therefore every request on a site
111/// that has never mapped a hostname. That is the whole non-breaking
112/// story: no mapping, no prefix, paths pass through exactly as before.
113/// Otherwise the mapped root's `url_path` with no trailing slash,
114/// ready to concatenate: `"/shop"`.
115///
116/// The unmapped case costs one indexed point lookup and stops there —
117/// the conventional root's own `url_path` is `/`, so there is nothing
118/// to learn from fetching it.
119///
120/// A mapping whose page has been deleted also yields `""`. Falling back
121/// beats 500ing: the domain stays up, and the admin flags the row.
122///
123/// # Errors
124/// Driver / query failures.
125pub async fn prefix_for_host(pool: &Pool, hostname: &str) -> Result<String, ExecError> {
126    Ok(root_for_host(pool, hostname)
127        .await?
128        .map(|root| root.url_path.trim_end_matches('/').to_owned())
129        .unwrap_or_default())
130}
131
132/// The page `hostname` is mapped to serve, or `None` when it serves the
133/// default root (no mapping, or one whose page has been deleted).
134///
135/// # Errors
136/// Driver / query failures.
137pub async fn root_for_host(pool: &Pool, hostname: &str) -> Result<Option<Page>, ExecError> {
138    let host = hostname.trim().to_ascii_lowercase();
139    if host.is_empty() {
140        return Ok(None);
141    }
142    let Some(site): Option<Site> = Site::objects()
143        .where_(Site::hostname.eq(host))
144        .first(pool)
145        .await?
146    else {
147        return Ok(None);
148    };
149    let root: Option<Page> = Page::objects()
150        .where_(Page::id.eq(site.root_page_id))
151        .first(pool)
152        .await?;
153    if root.is_none() {
154        tracing::warn!(
155            target: "rustango_cms::site",
156            hostname = %hostname, root_page_id = site.root_page_id,
157            "site maps to a missing root page; serving the default root"
158        );
159    }
160    Ok(root)
161}
162
163/// The hostnames rooted at `root_page_id`.
164///
165/// Used to refuse deleting a page a live domain points at. Silently
166/// dropping the mapping instead would leave a domain quietly serving a
167/// different site, which is the kind of change that is only noticed by
168/// visitors.
169///
170/// # Errors
171/// Driver / query failures.
172pub async fn hosts_for_root(pool: &Pool, root_page_id: i64) -> Result<Vec<String>, ExecError> {
173    let rows: Vec<Site> = Site::objects()
174        .where_(Site::root_page_id.eq(root_page_id))
175        .order_by(&[("hostname", false)])
176        .fetch(pool)
177        .await?;
178    Ok(rows.into_iter().map(|s| s.hostname).collect())
179}
180
181/// Every site mapping, newest hostname order, for the admin.
182///
183/// # Errors
184/// Driver / query failures.
185pub async fn all(pool: &Pool) -> Result<Vec<Site>, ExecError> {
186    Site::objects()
187        .order_by(&[("hostname", false)])
188        .fetch(pool)
189        .await
190}
191
192#[cfg(test)]
193mod tests {
194    use super::{to_lookup_path as lookup, to_public_path as public};
195
196    #[test]
197    fn the_default_root_passes_paths_through_untouched() {
198        assert_eq!(lookup("", "/about"), "/about");
199        assert_eq!(lookup("", "/"), "/");
200        assert_eq!(public("", "/about"), "/about");
201    }
202
203    #[test]
204    fn a_prefixed_site_maps_its_root_to_slash() {
205        assert_eq!(lookup("/site-b", "/"), "/site-b");
206        assert_eq!(lookup("/site-b", ""), "/site-b");
207        assert_eq!(public("/site-b", "/site-b"), "/");
208    }
209
210    #[test]
211    fn a_prefixed_site_translates_both_ways() {
212        assert_eq!(lookup("/site-b", "/about"), "/site-b/about");
213        assert_eq!(lookup("/site-b", "/about/team"), "/site-b/about/team");
214        assert_eq!(public("/site-b", "/site-b/about"), "/about");
215        assert_eq!(public("/site-b", "/site-b/about/team"), "/about/team");
216    }
217
218    /// Round-tripping is the property the whole scheme rests on: what a
219    /// visitor asks for must come back as the same public link.
220    #[test]
221    fn lookup_and_public_round_trip() {
222        for prefix in ["", "/site-b", "/deep/nested"] {
223            for path in ["/", "/about", "/about/team"] {
224                let absolute = lookup(prefix, path);
225                assert_eq!(
226                    public(prefix, &absolute),
227                    path,
228                    "round trip failed for prefix {prefix:?} path {path:?}"
229                );
230            }
231        }
232    }
233
234    /// A textual prefix match is not a subtree match. `/site-bravo` is a
235    /// different root that merely starts with the same characters, and
236    /// rewriting it to `ravo` would invent a URL that 404s.
237    #[test]
238    fn a_sibling_root_sharing_a_name_prefix_is_not_rewritten() {
239        assert_eq!(public("/site-b", "/site-bravo/about"), "/site-bravo/about");
240    }
241
242    /// A page on another site keeps its absolute path — an honest link
243    /// somewhere else beats a rewritten one that goes nowhere.
244    #[test]
245    fn a_page_outside_this_site_keeps_its_absolute_path() {
246        assert_eq!(public("/site-b", "/other/page"), "/other/page");
247        assert_eq!(public("/site-b", "/"), "/");
248    }
249}