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
113/// `(count, newest edit)` of the public pages the viewer may see. With no
114/// view restriction in force for this viewer — the common case — both
115/// come from SQL (#647); otherwise the rows are needed to test each path.
116async fn page_fingerprint(
117    pool: &rustango::sql::Pool,
118    viewer: Option<&rustango::tenancy::auth::User>,
119) -> Result<(usize, Option<DateTime<Utc>>), rustango::sql::ExecError> {
120    let listed = || {
121        Page::objects()
122            .where_(Page::status.is_in([
123                PageStatus::Published.as_str().to_owned(),
124                PageStatus::Archived.as_str().to_owned(),
125            ]))
126            .where_(Page::locale_variant_of.is_null())
127    };
128    let access = crate::view_restriction::access_context(pool, viewer).await;
129    if access.is_unrestricted() {
130        let count = listed().count(pool).await?;
131        let latest = listed()
132            .order_by(&[("updated_at", true)])
133            .first(pool)
134            .await?
135            .and_then(|p| p.updated_at.get().copied());
136        return Ok((to_usize(count), latest));
137    }
138    let pages: Vec<Page> = listed().fetch(pool).await?;
139    let visible: Vec<&Page> = pages.iter().filter(|p| access.can_view(&p.path, p.page_type_id)).collect();
140    Ok((visible.len(), newest(visible.iter().map(|p| p.updated_at.get().copied()))))
141}
142
143pub async fn changes_inner(
144    pool: &rustango::sql::Pool,
145    viewer: Option<&rustango::tenancy::auth::User>,
146) -> Result<Response, rustango::sql::ExecError> {
147    // ---- pages: the same public set the list endpoint serves ----------
148    let pages = page_fingerprint(pool, viewer).await?;
149
150    // ---- media: gated collections excluded, as in the listings --------
151    // Counted in SQL (#647): every row of five tables used to be loaded
152    // just to count it, on an endpoint built to be polled anonymously.
153    // The collections table is small; the media table need not be read.
154    let collection_ids: Vec<i64> = crate::media::MediaCollection::objects()
155        .fetch(pool)
156        .await?
157        .iter()
158        .filter_map(|c| c.id.get().copied())
159        .collect();
160    let denied: Vec<i64> =
161        crate::collection_view_restriction::denied_collection_ids(pool, viewer, &collection_ids)
162            .await
163            .into_iter()
164            .collect();
165    let (images, documents) = (
166        media_fingerprint(pool, &denied, true).await?,
167        media_fingerprint(pool, &denied, false).await?,
168    );
169
170    let snippets = (
171        Snippet::objects().count(pool).await?,
172        Snippet::objects()
173            .order_by(&[("updated_at", true)])
174            .first(pool)
175            .await?
176            .and_then(|s| s.updated_at.get().copied()),
177    );
178
179    // Menus carry no `updated_at`, so their items' absence of one leaves
180    // `latest` null — the count is what moves when an editor adds or
181    // removes a menu or an item, which is the signal a navbar needs.
182    let menus = Menu::objects().count(pool).await? + MenuItem::objects().count(pool).await?;
183
184    Ok(Json(serde_json::json!({
185        "meta": {
186            "checked_at": Utc::now().to_rfc3339(),
187            // Spelled out so a client does not have to infer the contract
188            // from behaviour.
189            "usage": "Re-fetch a collection when its `count` or `latest` \
190                      differs from the values you hold, passing the \
191                      `latest` you held as `?updated_since=`.",
192        },
193        "collections": {
194            "pages": entry(pages.0, pages.1),
195            "images": entry(images.0, images.1),
196            "documents": entry(documents.0, documents.1),
197            "snippets": entry(to_usize(snippets.0), snippets.1),
198            "menus": entry(to_usize(menus), None),
199        },
200    }))
201    .into_response())
202}
203
204#[cfg(test)]
205mod tests {
206    use super::*;
207
208    fn t(s: &str) -> Option<DateTime<Utc>> {
209        Some(DateTime::parse_from_rfc3339(s).unwrap().with_timezone(&Utc))
210    }
211
212    #[test]
213    fn newest_picks_the_latest_and_ignores_missing() {
214        let got = newest(
215            [t("2026-01-01T00:00:00Z"), None, t("2026-06-01T00:00:00Z")].into_iter(),
216        );
217        assert_eq!(got, t("2026-06-01T00:00:00Z"));
218    }
219
220    #[test]
221    fn newest_of_nothing_is_none() {
222        assert_eq!(newest(std::iter::empty()), None);
223        assert_eq!(newest([None, None].into_iter()), None);
224    }
225
226    #[test]
227    fn an_entry_carries_both_halves_of_the_signal() {
228        // `count` is what catches a deletion, which moves no timestamp.
229        let e = entry(3, t("2026-01-01T00:00:00Z"));
230        assert_eq!(e["count"], 3);
231        assert!(e["latest"].is_string());
232
233        let empty = entry(0, None);
234        assert_eq!(empty["count"], 0);
235        assert!(empty["latest"].is_null());
236    }
237}