Skip to main content

rustango_cms/
resolver.rs

1//! URL → `Page` resolution.
2//!
3//! Two paths:
4//!
5//! 1. **Materialized `url_path` short-circuit**. The
6//!    request URL is normalized (strip trailing slash unless root)
7//!    and looked up directly via `WHERE url_path = ?` — one query
8//!    regardless of tree depth. The `url_path` column is indexed and
9//!    maintained by `tree_ops` on every create / move / slug change.
10//!
11//! 2. **Slug-walk fallback** for cases the materialized lookup
12//!    misses — historical rows from before slice 1, draft-preview
13//!    routes, etc. Walks the slug chain one level at a time
14//!    and filters to the public statuses.
15//!
16//! Both paths serve the **public statuses** — `published` and
17//! `archived` (superseded-but-preserved content). Drafts,
18//! scheduled, and `expired` (takedown) rows stay invisible to anonymous
19//! visitors. The caller reads `page.status` to distinguish the two
20//! served states.
21
22use rustango::core::Column as _;
23use rustango::extractors::Tenant;
24use rustango::sql::FetcherPool as _;
25
26use crate::page::Page;
27use crate::tree_ops::TreeError;
28
29/// Statuses a public page can have. `archived` joins `published`;
30/// `scheduled` is included only so a page whose go-live time has passed is
31/// served before the sweep flips it — [`visible_now`] decides. `expired`
32/// is excluded so takedown still 404s. Owned `String`s for the `is_in` binds.
33///
34/// The query side of "is this page served": filter by these, then keep the
35/// rows [`visible_now`] accepts. Anything that links to or lists served
36/// pages uses the pair, so it agrees with what a visitor gets.
37#[must_use]
38pub fn served_statuses() -> [String; 3] {
39    [
40        crate::page::PageStatus::Published.as_str().to_owned(),
41        crate::page::PageStatus::Archived.as_str().to_owned(),
42        crate::page::PageStatus::Scheduled.as_str().to_owned(),
43    ]
44}
45
46/// Whether a page is public at `now`, judged by its dates rather than by
47/// whether the schedule sweep has run yet: a scheduled page goes
48/// live at `go_live_at`, a published one comes down at `expire_at`.
49#[must_use]
50pub fn visible_now(page: &Page, now: chrono::DateTime<chrono::Utc>) -> bool {
51    use crate::page::PageStatus;
52    let status = page.status.as_str();
53    if status == PageStatus::Archived.as_str() {
54        true
55    } else if status == PageStatus::Published.as_str() {
56        !page.expire_at.is_some_and(|t| t <= now)
57    } else if status == PageStatus::Scheduled.as_str() {
58        page.go_live_at.is_some_and(|t| t <= now)
59            && !page.expire_at.is_some_and(|t| t <= now)
60    } else {
61        false
62    }
63}
64
65/// Normalize a request path into the canonical form stored in
66/// `cms_page.url_path`. Leading slash kept; trailing slash stripped
67/// for non-root URLs. Empty / missing path collapses to `/`. Exposed
68/// for the router's cache-key builder.
69pub fn canonical_request_path(raw: &str) -> String {
70    let trimmed = raw.trim();
71    if trimmed.is_empty() || trimmed == "/" {
72        return "/".to_owned();
73    }
74    let with_leading = if trimmed.starts_with('/') {
75        trimmed.to_owned()
76    } else {
77        format!("/{trimmed}")
78    };
79    let trailing_stripped = with_leading.trim_end_matches('/').to_owned();
80    if trailing_stripped.is_empty() {
81        "/".to_owned()
82    } else {
83        trailing_stripped
84    }
85}
86
87/// Look up the page matching `url_path` directly. One indexed SELECT.
88/// Returns `Ok(None)` when the row is missing OR isn't public
89/// (published / archived). The caller reads `page.status` to tell the
90/// two apart.
91pub async fn resolve_by_url_path(t: &Tenant, url_path: &str) -> Result<Option<Page>, TreeError> {
92    let canon = canonical_request_path(url_path);
93    // Ordered so a duplicate URL (rows saved before #703 made edits
94    // refuse one) always serves the same page: the oldest.
95    let hits: Vec<Page> = Page::objects()
96        .where_(Page::url_path.eq(canon))
97        .where_(Page::status.is_in(served_statuses()))
98        .order_by(&[("id", false)])
99        .fetch(t.pool())
100        .await?;
101    let now = chrono::Utc::now();
102    Ok(hits.into_iter().find(|p| visible_now(p, now)))
103}
104
105/// Walk the URL path one slug at a time. Used as a fallback when the
106/// materialized `url_path` lookup misses (legacy rows, preview
107/// routes, etc.) and for the per-segment ancestry queries that
108/// rendered content depends on.
109pub async fn resolve_by_walk(t: &Tenant, url_path: &str) -> Result<Option<Page>, TreeError> {
110    let segments: Vec<&str> = url_path.split('/').filter(|s| !s.is_empty()).collect();
111
112    let roots: Vec<Page> = Page::objects()
113        .where_(Page::parent_id.is_null())
114        .where_(Page::slug.eq(String::new()))
115        .where_(Page::status.is_in(served_statuses()))
116        .order_by(&[("id", false)])
117        .fetch(t.pool())
118        .await?;
119    let now = chrono::Utc::now();
120    let Some(mut current) = roots.into_iter().find(|p| visible_now(p, now)) else {
121        return Ok(None);
122    };
123
124    for seg in segments {
125        let parent_id = match current.id.get().copied() {
126            Some(id) => id,
127            None => return Ok(None),
128        };
129        let hits: Vec<Page> = Page::objects()
130            .where_(Page::parent_id.eq(parent_id))
131            .where_(Page::slug.eq(seg.to_string()))
132            .where_(Page::status.is_in(served_statuses()))
133            .order_by(&[("id", false)])
134            .fetch(t.pool())
135            .await?;
136        let Some(child) = hits.into_iter().find(|p| visible_now(p, now)) else {
137            return Ok(None);
138        };
139        current = child;
140    }
141    Ok(Some(current))
142}
143
144/// Resolve a request URL to a `Page`. Tries the materialized
145/// `url_path` first (one query); falls back to the slug walk when no
146/// row is found that way (legacy data, in-flight backfills, etc.).
147///
148/// `url_path` should be the request path (e.g. `"/"`, `"/about/"`,
149/// `"/blog/post-1/"`). Leading + trailing slashes are normalized.
150///
151/// # Errors
152/// Driver / query failures.
153pub async fn resolve_path(t: &Tenant, url_path: &str) -> Result<Option<Page>, TreeError> {
154    if let Some(page) = resolve_by_url_path(t, url_path).await? {
155        return Ok(Some(page));
156    }
157    resolve_by_walk(t, url_path).await
158}
159
160/// When [`resolve_path`] misses, walk ancestor prefixes of
161/// `request_path` looking for a `Page` whose registered
162/// `PageTypeHandler::routes()` accepts the remaining suffix. Returns
163/// the matched page + match details on first hit (longest prefix
164/// wins because [`crate::routable::ancestor_prefixes`] orders from
165/// most-specific to root).
166///
167/// Returns `None` when no ancestor + route combination accepts the
168/// request — the router then falls through to its redirect /
169/// 404 path.
170///
171/// # Errors
172/// Driver / query failures from the per-ancestor `Page` lookup.
173pub async fn resolve_routable(
174    t: &Tenant,
175    request_path: &str,
176) -> Result<Option<(Page, crate::routable::RouteMatch)>, TreeError> {
177    let canon = canonical_request_path(request_path);
178    for ancestor in crate::routable::ancestor_prefixes(&canon) {
179        let Some(page) = resolve_by_url_path(t, &ancestor).await? else {
180            continue;
181        };
182        // Pull the handler — fall through to the next ancestor if
183        // the page type doesn't have one registered (a real
184        // misconfiguration; surfacing it as "no route matched"
185        // keeps the failure mode aligned with the slug resolver).
186        let Some(pt_row) = crate::page_type_model::PageType::objects()
187            .where_(crate::page_type_model::PageType::id.eq(page.page_type_id))
188            .first(t.pool())
189            .await?
190        else {
191            continue;
192        };
193        let Some(handler) = crate::page_type::find_handler(&pt_row.type_name) else {
194            continue;
195        };
196        let routes = handler.routes();
197        if routes.is_empty() {
198            continue;
199        }
200        // The suffix is whatever's BELOW the ancestor's url_path. For
201        // root (`/`), strip the leading slash. For deeper ancestors,
202        // skip the ancestor prefix plus its trailing slash.
203        let suffix = if ancestor == "/" {
204            canon.trim_start_matches('/')
205        } else {
206            canon
207                .strip_prefix(&ancestor)
208                .unwrap_or("")
209                .trim_start_matches('/')
210        };
211        if let Some(matched) = crate::routable::match_routes(&routes, suffix) {
212            return Ok(Some((page, matched)));
213        }
214    }
215    Ok(None)
216}
217
218#[cfg(test)]
219mod visible_now_tests {
220    use super::visible_now;
221    use crate::page::{Page, PageStatus};
222    use chrono::{Duration, Utc};
223
224    fn page(status: PageStatus) -> Page {
225        use rustango::sql::Auto;
226        Page {
227            id: Auto::Unset,
228            page_type_id: 1,
229            title: "t".to_owned(),
230            slug: "t".to_owned(),
231            path: "0001/".to_owned(),
232            url_path: "/t".to_owned(),
233            preview_path: String::new(),
234            template_override: String::new(),
235            depth: 1,
236            parent_id: None,
237            locale_variant_of: None,
238            alias_of: None,
239            theme_id: None,
240            sort_order: 0,
241            status: status.as_str().to_owned(),
242            published_at: None,
243            last_published_at: None,
244            go_live_at: None,
245            expire_at: None,
246            seo_title: String::new(),
247            seo_description: String::new(),
248            robots_index: true,
249            sitemap_priority: 0.5,
250            show_in_menus: true,
251            og_title: String::new(),
252            og_description: String::new(),
253            og_image_media_id: None,
254            twitter_card: "summary".to_owned(),
255            notification_pre_published_sent: false,
256            created_at: Auto::Unset,
257            updated_at: Auto::Unset,
258        }
259    }
260
261    #[test]
262    fn a_scheduled_page_is_public_once_its_go_live_time_passes() {
263        let now = Utc::now();
264        let mut p = page(PageStatus::Scheduled);
265        assert!(!visible_now(&p, now), "no go-live time: not public");
266        p.go_live_at = Some(now + Duration::minutes(5));
267        assert!(!visible_now(&p, now));
268        p.go_live_at = Some(now - Duration::minutes(5));
269        assert!(visible_now(&p, now), "due but not yet swept: public");
270    }
271
272    #[test]
273    fn a_published_page_comes_down_at_its_expiry() {
274        let now = Utc::now();
275        let mut p = page(PageStatus::Published);
276        assert!(visible_now(&p, now));
277        p.expire_at = Some(now - Duration::seconds(1));
278        assert!(!visible_now(&p, now), "expired but not yet swept: hidden");
279    }
280
281    #[test]
282    fn drafts_and_expired_pages_are_never_public() {
283        let now = Utc::now();
284        assert!(!visible_now(&page(PageStatus::Draft), now));
285        assert!(!visible_now(&page(PageStatus::Expired), now));
286        assert!(visible_now(&page(PageStatus::Archived), now));
287    }
288}