Skip to main content

rustango_cms/api/
changes.rs

1//! `GET /api/v2/changes/` — has anything moved?
2//!
3//! `?updated_since=` lets a client fetch only what changed *in one
4//! collection*, but it still has to ask every collection to find out
5//! whether any of them did. A dynamic frontend polling pages, images,
6//! documents, snippets and menus pays five full list responses per tick
7//! to discover, almost always, that nothing happened.
8//!
9//! This is the cheap tick: one small response saying, per collection,
10//! how many rows the caller can see and when one of them last changed.
11//! A client keeps the previous answer and re-fetches only the
12//! collections whose entry moved — with `?updated_since=` set to the
13//! `latest` it already held.
14//!
15//! ## Why `count` and not just `latest`
16//!
17//! A deletion moves no timestamp. Without the count, a client that had
18//! cached a page would keep serving it forever after an editor removed
19//! it, because `latest` never advanced. The pair — "how many, and how
20//! recent" — catches additions, edits and removals between them.
21//!
22//! It is not a push feed and does not pretend to be: there is no SSE or
23//! WebSocket here, and a client still decides its own cadence. What it
24//! removes is the cost of asking.
25//!
26//! ## Cost
27//!
28//! **Viewer-aware, and therefore not free.** The counts must reflect what
29//! *this* caller may see, or the endpoint would report that a member-only
30//! page exists to someone who cannot read it — so it runs the same
31//! visibility filters the list endpoints do. Roughly the cost of one list
32//! request, replacing five.
33
34use axum::response::{IntoResponse, Response};
35use axum::Json;
36use chrono::{DateTime, Utc};
37use rustango::core::Column as _;
38use rustango::extractors::{SessionUser, Tenant};
39use rustango::sql::{CounterPool as _, FetcherPool as _};
40
41use crate::media::Media;
42use crate::navigation::{Menu, MenuItem};
43use crate::page::{Page, PageStatus};
44use crate::snippet::Snippet;
45
46/// `GET /api/v2/changes/`
47pub async fn changes(
48    tenant: Tenant,
49    SessionUser(session_user): SessionUser,
50    rustango::tenancy::member_auth::CurrentMember(member): rustango::tenancy::member_auth::CurrentMember,
51    crate::api::auth::BearerMember(bearer): crate::api::auth::BearerMember,
52) -> Response {
53    let viewer = member.as_ref().or(bearer.as_ref()).or(session_user.as_ref());
54    match changes_inner(tenant.pool(), viewer).await {
55        Ok(resp) => resp,
56        Err(e) => {
57            tracing::error!(target: "rustango_cms::api", error = %e, "changes failed");
58            crate::api::error::ApiError::internal().into_response()
59        }
60    }
61}
62
63/// One collection's fingerprint.
64fn entry(count: usize, latest: Option<DateTime<Utc>>) -> serde_json::Value {
65    serde_json::json!({
66        "count": count,
67        "latest": latest.map(|t| t.to_rfc3339()),
68    })
69}
70
71/// The most recent of a set of optional timestamps.
72fn newest(times: impl Iterator<Item = Option<DateTime<Utc>>>) -> Option<DateTime<Utc>> {
73    times.flatten().max()
74}
75
76fn to_usize(n: i64) -> usize {
77    usize::try_from(n).unwrap_or(0)
78}
79
80/// `(count, newest upload)` of the images (`images = true`) or other
81/// media the viewer may see: those outside the `denied` collections.
82async fn media_fingerprint(
83    pool: &rustango::sql::Pool,
84    denied: &[i64],
85    images: bool,
86) -> Result<(usize, Option<DateTime<Utc>>), rustango::sql::ExecError> {
87    let listed = || {
88        let qs = Media::objects();
89        let qs = if images {
90            qs.where_(Media::kind.eq("image".to_owned()))
91        } else {
92            qs.where_(Media::kind.ne("image".to_owned()))
93        };
94        if denied.is_empty() {
95            qs
96        } else {
97            qs.where_(
98                Media::collection_id
99                    .is_null()
100                    .or(Media::collection_id.not_in(denied.iter().copied())),
101            )
102        }
103    };
104    let count = listed().count(pool).await?;
105    let latest = listed()
106        .order_by(&[("uploaded_at", true)])
107        .first(pool)
108        .await?
109        .and_then(|m| m.uploaded_at.get().copied());
110    Ok((to_usize(count), latest))
111}
112
113pub async fn changes_inner(
114    pool: &rustango::sql::Pool,
115    viewer: Option<&rustango::tenancy::auth::User>,
116) -> Result<Response, rustango::sql::ExecError> {
117    // ---- pages: the same public set the list endpoint serves ----------
118    let mut pages: Vec<Page> = Page::objects()
119        .where_(Page::status.is_in([
120            PageStatus::Published.as_str().to_owned(),
121            PageStatus::Archived.as_str().to_owned(),
122        ]))
123        .fetch(pool)
124        .await?;
125    pages.retain(|p| p.locale_variant_of.is_none());
126    let triples: Vec<(i64, String, i64)> = pages
127        .iter()
128        .map(|p| {
129            (
130                p.id.get().copied().unwrap_or_default(),
131                p.path.clone(),
132                p.page_type_id,
133            )
134        })
135        .collect();
136    let denied = crate::view_restriction::denied_page_ids(pool, viewer, &triples).await;
137    pages.retain(|p| !denied.contains(&p.id.get().copied().unwrap_or_default()));
138
139    // ---- media: gated collections excluded, as in the listings --------
140    // Counted in SQL (#647): every row of five tables used to be loaded
141    // just to count it, on an endpoint built to be polled anonymously.
142    // The collections table is small; the media table need not be read.
143    let collection_ids: Vec<i64> = crate::media::MediaCollection::objects()
144        .fetch(pool)
145        .await?
146        .iter()
147        .filter_map(|c| c.id.get().copied())
148        .collect();
149    let denied: Vec<i64> =
150        crate::collection_view_restriction::denied_collection_ids(pool, viewer, &collection_ids)
151            .await
152            .into_iter()
153            .collect();
154    let (images, documents) = (
155        media_fingerprint(pool, &denied, true).await?,
156        media_fingerprint(pool, &denied, false).await?,
157    );
158
159    let snippets = (
160        Snippet::objects().count(pool).await?,
161        Snippet::objects()
162            .order_by(&[("updated_at", true)])
163            .first(pool)
164            .await?
165            .and_then(|s| s.updated_at.get().copied()),
166    );
167
168    // Menus carry no `updated_at`, so their items' absence of one leaves
169    // `latest` null — the count is what moves when an editor adds or
170    // removes a menu or an item, which is the signal a navbar needs.
171    let menus = Menu::objects().count(pool).await? + MenuItem::objects().count(pool).await?;
172
173    Ok(Json(serde_json::json!({
174        "meta": {
175            "checked_at": Utc::now().to_rfc3339(),
176            // Spelled out so a client does not have to infer the contract
177            // from behaviour.
178            "usage": "Re-fetch a collection when its `count` or `latest` \
179                      differs from the values you hold, passing the \
180                      `latest` you held as `?updated_since=`.",
181        },
182        "collections": {
183            "pages": entry(
184                pages.len(),
185                newest(pages.iter().map(|p| p.updated_at.get().copied())),
186            ),
187            "images": entry(images.0, images.1),
188            "documents": entry(documents.0, documents.1),
189            "snippets": entry(to_usize(snippets.0), snippets.1),
190            "menus": entry(to_usize(menus), None),
191        },
192    }))
193    .into_response())
194}
195
196#[cfg(test)]
197mod tests {
198    use super::*;
199
200    fn t(s: &str) -> Option<DateTime<Utc>> {
201        Some(DateTime::parse_from_rfc3339(s).unwrap().with_timezone(&Utc))
202    }
203
204    #[test]
205    fn newest_picks_the_latest_and_ignores_missing() {
206        let got = newest(
207            [t("2026-01-01T00:00:00Z"), None, t("2026-06-01T00:00:00Z")].into_iter(),
208        );
209        assert_eq!(got, t("2026-06-01T00:00:00Z"));
210    }
211
212    #[test]
213    fn newest_of_nothing_is_none() {
214        assert_eq!(newest(std::iter::empty()), None);
215        assert_eq!(newest([None, None].into_iter()), None);
216    }
217
218    #[test]
219    fn an_entry_carries_both_halves_of_the_signal() {
220        // `count` is what catches a deletion, which moves no timestamp.
221        let e = entry(3, t("2026-01-01T00:00:00Z"));
222        assert_eq!(e["count"], 3);
223        assert!(e["latest"].is_string());
224
225        let empty = entry(0, None);
226        assert_eq!(empty["count"], 0);
227        assert!(empty["latest"].is_null());
228    }
229}