Skip to main content

rustango_cms/
feed.rs

1//! Per-page-type RSS 2.0 + Atom 1.0 feeds —
2//! "syndication on demand", powered by [`rustango::syndication`].
3//!
4//! ## Opt-in
5//!
6//! A [`crate::PageTypeHandler`] joins the feed surface by overriding
7//! [`crate::PageTypeHandler::feed_kind`] to return `Some("slug")`.
8//! The slug is the URL path segment under `/feed/<slug>/...`:
9//!
10//! ```ignore
11//! impl PageTypeHandler for ArticlePage {
12//!     // …
13//!     fn feed_kind(&self) -> Option<&'static str> { Some("articles") }
14//! }
15//! ```
16//!
17//! Then `/feed/articles/rss.xml` and `/feed/articles/atom.xml`
18//! enumerate every published, indexable [`crate::Page`] whose
19//! `page_type_id` resolves to that handler, newest first.
20//!
21//! ## Content mapping
22//!
23//! | Feed field         | CMS source                                              |
24//! | ------------------ | ------------------------------------------------------- |
25//! | `<title>`          | `page.title`                                            |
26//! | `<link>` / `<id>`  | `https?://<host><page.url_path>` (Host-derived; see [`crate::sitemap`] for the scheme/host logic) |
27//! | `<description>`    | `page.seo_description` (falls back to empty)            |
28//! | `<pubDate>` / `<updated>` | `page.published_at` (falls back to `updated_at`)  |
29//!
30//! Excludes pages with `robots_index = false` (mirroring the
31//! sitemap exclusion) and locale variants (canonical row only).
32//!
33//! ## Feed metadata
34//!
35//! `<channel>`-level title is derived from `tenant.org.display_name`;
36//! description is a generic "Latest `<handler verbose_name>`" line.
37//! Neither is overridable per tenant: the feed does not read
38//! `SiteSetting` rows.
39
40use axum::extract::Path;
41use axum::http::{header, HeaderMap, StatusCode};
42use axum::response::{IntoResponse, Response};
43use rustango::core::Column as _;
44use rustango::extractors::Tenant;
45use rustango::sql::FetcherPool as _;
46use rustango::syndication::{render_atom, render_rss, Feed, FeedItem};
47
48use crate::page::Page;
49
50/// Most items a feed carries. Readers poll feeds on a timer, so an
51/// uncapped feed made every poll load and serialise the type's whole
52/// history; syndication convention is the latest 10-50.
53pub const FEED_MAX_ITEMS: i64 = 50;
54
55/// The newest published, indexable, non-variant pages of `type_id` an
56/// anonymous reader may see, at most [`FEED_MAX_ITEMS`].
57async fn feed_pages(
58    pool: &rustango::sql::Pool,
59    type_id: i64,
60) -> Result<Vec<Page>, rustango::sql::ExecError> {
61    let qs = Page::objects()
62        .where_(Page::page_type_id.eq(type_id))
63        .where_(Page::status.eq("published"))
64        .where_(Page::robots_index.eq(true))
65        .where_(Page::locale_variant_of.is_null());
66    crate::view_restriction::only_anonymous_visible(pool, qs)
67        .await
68        .order_by(&[("published_at", true)])
69        .limit(FEED_MAX_ITEMS)
70        .fetch(pool)
71        .await
72}
73use crate::page_type::registered_handlers;
74use crate::page_type_model::PageType;
75
76/// `GET /feed/{kind}/rss.xml`
77pub async fn handle_feed_rss(t: Tenant, headers: HeaderMap, Path(kind): Path<String>) -> Response {
78    match build_feed(&t, &headers, &kind).await {
79        Ok(feed) => xml_response(render_rss(&feed), "application/rss+xml; charset=utf-8"),
80        Err(FeedError::NotFound) => not_found(&kind),
81        Err(FeedError::Db(e)) => {
82            tracing::error!(error = %e, kind = %kind, "feed: db error");
83            (StatusCode::INTERNAL_SERVER_ERROR, "feed unavailable").into_response()
84        }
85    }
86}
87
88/// `GET /feed/{kind}/atom.xml`
89pub async fn handle_feed_atom(t: Tenant, headers: HeaderMap, Path(kind): Path<String>) -> Response {
90    match build_feed(&t, &headers, &kind).await {
91        Ok(feed) => xml_response(render_atom(&feed), "application/atom+xml; charset=utf-8"),
92        Err(FeedError::NotFound) => not_found(&kind),
93        Err(FeedError::Db(e)) => {
94            tracing::error!(error = %e, kind = %kind, "feed: db error");
95            (StatusCode::INTERNAL_SERVER_ERROR, "feed unavailable").into_response()
96        }
97    }
98}
99
100#[derive(Debug)]
101enum FeedError {
102    /// No registered `PageTypeHandler` claims this kind slug.
103    NotFound,
104    Db(rustango::sql::ExecError),
105}
106
107impl From<rustango::sql::ExecError> for FeedError {
108    fn from(e: rustango::sql::ExecError) -> Self {
109        Self::Db(e)
110    }
111}
112
113async fn build_feed(t: &Tenant, headers: &HeaderMap, kind: &str) -> Result<Feed, FeedError> {
114    // Resolve the slug → handler. Linear scan over the inventory —
115    // registration count is small (typically <20).
116    let handler = registered_handlers()
117        .find(|h| h.feed_kind() == Some(kind))
118        .ok_or(FeedError::NotFound)?;
119
120    // Look up the matching `cms_page_type` row to get its id.
121    let type_name = handler.type_name();
122    let mut types: Vec<PageType> = PageType::objects()
123        .where_(PageType::type_name.eq(type_name.to_owned()))
124        .fetch(t.pool())
125        .await?;
126    let Some(pt) = types.pop() else {
127        return Err(FeedError::NotFound);
128    };
129    let Some(type_id) = pt.id.get().copied() else {
130        return Err(FeedError::NotFound);
131    };
132
133    let pages = feed_pages(t.pool(), type_id).await?;
134
135    let base = crate::sitemap::base_url(headers);
136    let items: Vec<FeedItem> = pages.iter().map(|p| page_to_item(&base, p)).collect();
137
138    Ok(Feed {
139        title: format!("{} — {}", t.org.display_name, handler.verbose_name()),
140        link: format!("{base}/"),
141        description: format!("Latest {}.", handler.verbose_name().to_lowercase()),
142        language: None,
143        last_build_date: items.iter().filter_map(|i| i.pub_date).max(),
144        items,
145    })
146}
147
148fn page_to_item(base: &str, p: &Page) -> FeedItem {
149    let path = if p.url_path.is_empty() {
150        "/".to_owned()
151    } else {
152        p.url_path.clone()
153    };
154    let link = format!("{base}{path}");
155    let pub_date = match p.published_at {
156        Some(ts) => Some(ts),
157        None => match p.updated_at {
158            rustango::sql::Auto::Set(ts) => Some(ts),
159            _ => None,
160        },
161    };
162    let mut item = FeedItem::new(p.title.clone(), link.clone()).with_guid(link);
163    if !p.seo_description.is_empty() {
164        item = item.with_description(p.seo_description.clone());
165    }
166    if let Some(ts) = pub_date {
167        item = item.with_pub_date(ts);
168    }
169    item
170}
171
172fn xml_response(xml: String, content_type: &'static str) -> Response {
173    (StatusCode::OK, [(header::CONTENT_TYPE, content_type)], xml).into_response()
174}
175
176fn not_found(kind: &str) -> Response {
177    (
178        StatusCode::NOT_FOUND,
179        format!("no feed registered for kind `{kind}`"),
180    )
181        .into_response()
182}
183
184/// Build a single [`FeedItem`] for `page` against `base_url` (e.g.
185/// `"https://example.com"`). Exposed for tests that don't want to
186/// build a full `Feed`; production callers route through
187/// `handle_feed_rss` / `handle_feed_atom`.
188#[doc(hidden)]
189pub fn _item_from_page(base: &str, page: &Page) -> FeedItem {
190    page_to_item(base, page)
191}
192
193#[cfg(all(test, feature = "sqlite"))]
194mod tests {
195    use super::*;
196    use rustango::core::Model as _;
197    use rustango::sql::Auto;
198
199    async fn setup() -> (rustango::sql::Pool, i64) {
200        let pool = rustango::sql::Pool::connect("sqlite::memory:")
201            .await
202            .expect("pool");
203        for schema in [
204            &PageType::SCHEMA,
205            &crate::media::MediaCollection::SCHEMA,
206            &crate::media::Media::SCHEMA,
207            &crate::theme::Theme::SCHEMA,
208            &Page::SCHEMA,
209            &crate::view_restriction::PageViewRestriction::SCHEMA,
210        ] {
211            let sql = rustango::migrate::ddl::create_table_if_not_exists_sql_with_dialect(
212                pool.dialect(),
213                schema,
214            );
215            for stmt in sql.split(';').map(str::trim).filter(|s| !s.is_empty()) {
216                rustango::sql::raw_execute_pool(&pool, stmt, Vec::new())
217                    .await
218                    .expect("ddl");
219            }
220        }
221        let mut pt = PageType {
222            id: Auto::Unset,
223            app_label: "cms".into(),
224            type_name: "Post".into(),
225            verbose_name: "Post".into(),
226            default_template: "p.html".into(),
227            view_mode: "auto".into(),
228            is_creatable: true,
229            allowed_parent_types: serde_json::json!([]),
230            allowed_child_types: serde_json::json!([]),
231            workflow: String::new(),
232            created_at: Auto::Unset,
233            updated_at: Auto::Unset,
234        };
235        pt.save(&pool).await.expect("type");
236        let type_id = pt.id.get().copied().expect("type id");
237        (pool, type_id)
238    }
239
240    /// Save a published, indexable page at `path`; returns its id.
241    async fn page(
242        pool: &rustango::sql::Pool,
243        type_id: i64,
244        title: &str,
245        path: &str,
246        published_at: chrono::DateTime<chrono::Utc>,
247    ) -> i64 {
248        let mut p = Page {
249            id: Auto::Unset,
250            page_type_id: type_id,
251            title: title.to_owned(),
252            slug: title.to_owned(),
253            path: path.to_owned(),
254            url_path: format!("/{title}"),
255            preview_path: String::new(),
256            template_override: String::new(),
257            depth: i32::try_from(path.matches('/').count()).unwrap_or(1),
258            parent_id: None,
259            locale_variant_of: None,
260            alias_of: None,
261            theme_id: None,
262            sort_order: 0,
263            status: "published".into(),
264            published_at: Some(published_at),
265            last_published_at: None,
266            go_live_at: None,
267            expire_at: None,
268            seo_title: String::new(),
269            seo_description: String::new(),
270            robots_index: true,
271            sitemap_priority: 0.5,
272            show_in_menus: true,
273            og_title: String::new(),
274            og_description: String::new(),
275            og_image_media_id: None,
276            twitter_card: "summary".into(),
277            notification_pre_published_sent: false,
278            created_at: Auto::Unset,
279            updated_at: Auto::Unset,
280        };
281        p.save(pool).await.expect("page");
282        p.id.get().copied().expect("page id")
283    }
284
285    /// A type with more pages than the cap yields the newest cap.
286    #[tokio::test]
287    async fn a_feed_carries_only_the_newest_items() {
288        let (pool, type_id) = setup().await;
289        let start = chrono::Utc::now() - chrono::Duration::days(1);
290        let total = FEED_MAX_ITEMS + 10;
291        for n in 0..total {
292            let path = format!("{:04x}/", n + 1);
293            page(&pool, type_id, &format!("p{n}"), &path, start + chrono::Duration::minutes(n)).await;
294        }
295        let pages = feed_pages(&pool, type_id).await.expect("feed pages");
296        assert_eq!(pages.len() as i64, FEED_MAX_ITEMS);
297        assert_eq!(pages[0].title, format!("p{}", total - 1), "newest first");
298    }
299
300    /// A members-only page and its subtree stay out of the feed.
301    #[tokio::test]
302    async fn a_feed_leaves_out_restricted_pages() {
303        let (pool, type_id) = setup().await;
304        let now = chrono::Utc::now();
305        page(&pool, type_id, "open", "0001/", now).await;
306        let gated = page(&pool, type_id, "gated", "0002/", now).await;
307        page(&pool, type_id, "gated-child", "0002/0001/", now).await;
308        let mut r = crate::view_restriction::PageViewRestriction {
309            id: Auto::Unset,
310            page_id: gated,
311            kind: crate::view_restriction::RestrictionKind::Login.as_str().to_owned(),
312            password_hash: String::new(),
313            group_ids: serde_json::json!([]),
314            codenames: serde_json::json!([]),
315            created_at: Auto::Unset,
316            updated_at: Auto::Unset,
317        };
318        r.save(&pool).await.expect("restriction");
319        let titles: Vec<String> = feed_pages(&pool, type_id)
320            .await
321            .expect("feed pages")
322            .into_iter()
323            .map(|p| p.title)
324            .collect();
325        assert_eq!(titles, ["open"]);
326    }
327}