Skip to main content

rustango_cms/
fragment_cache.rs

1//! Page-keyed template-fragment caching.
2//!
3//! ## Why there is no `{% rcmscache %}` Tera tag
4//!
5//! A fragment-cache tag would have to be a **block tag** that skips
6//! rendering its body on a cache hit. **Tera cannot express this**: its grammar
7//! is fixed — there is no API to register a custom block statement,
8//! and the one block-shaped extension point, `{% filter foo %}…
9//! {% endfilter %}`, renders the body *first* and then hands the
10//! string to the filter, so it can never *skip* the expensive render.
11//! A template-level cache tag is therefore impossible on this engine.
12//!
13//! ## What you do instead
14//!
15//! Cache the expensive *computation* in Rust — before it reaches the
16//! template — with the framework's
17//! [`rustango::cache_fragment::cached_render`] (re-exported here as
18//! [`cached_render`]). That's exactly how [`crate::auto_menu`] caches
19//! the menu tree. Build the key with [`page_fragment_key`] so it
20//! **auto-invalidates** when the page republishes, and **bypass the
21//! cache while previewing** (pass the live value instead of calling
22//! `cached_render`) so editors always see their unsaved edits.
23//!
24//! ```ignore
25//! use rustango_cms::fragment_cache::{cached_render, page_fragment_key};
26//!
27//! // In host/app code that holds a `cache: BoxedCache` (the same one
28//! // wired into `PublicRouter::cached`) — e.g. a custom route or a
29//! // context builder that has the cache in hand:
30//! let body = if previewing {
31//!     render_related_panel(pool, &page).await           // never cache a preview
32//! } else {
33//!     let key = page_fragment_key(&tenant.org.slug, &page, "related");
34//!     cached_render(cache.as_ref(), &key, Some(ttl), || async {
35//!         render_related_panel(pool, &page).await        // computed once per (page, publish)
36//!     })
37//!     .await
38//! };
39//! ```
40
41pub use rustango::cache_fragment::cached_render;
42
43use crate::page::Page;
44
45/// Cache key for a page-scoped fragment. Encodes the page id + its
46/// publish version stamp, so the key changes — and the old entry is
47/// abandoned — every time the page republishes (no explicit purge
48/// needed). `suffix` distinguishes fragments on the same page (e.g.
49/// `"related"`, `"toc"`, `"sidebar"`).
50///
51/// `tenant_slug` is part of the key because every tenant numbers its
52/// pages from 1: without it, tenants sharing one cache served each
53/// other's fragments for the same page id.
54#[must_use]
55pub fn page_fragment_key(tenant_slug: &str, page: &Page, suffix: &str) -> String {
56    let id = page.id.get().copied().unwrap_or(0);
57    // `last_published_at` moves only on public-visible republish;
58    // fall back to `updated_at`, then 0 for unsaved rows.
59    let stamp = page
60        .last_published_at
61        .or_else(|| page.updated_at.get().copied())
62        .map_or(0, |ts| ts.timestamp());
63    fragment_key(tenant_slug, id, stamp, suffix)
64}
65
66/// Pure key formatter — `cms:frag:<tenant>:<page_id>:<version_stamp>:<suffix>`.
67fn fragment_key(tenant_slug: &str, page_id: i64, version_stamp: i64, suffix: &str) -> String {
68    format!("cms:frag:{tenant_slug}:{page_id}:{version_stamp}:{suffix}")
69}
70
71#[cfg(test)]
72mod tests {
73    use super::*;
74
75    #[test]
76    fn key_shape_includes_id_stamp_suffix() {
77        assert_eq!(
78            fragment_key("acme", 42, 1717545600, "related"),
79            "cms:frag:acme:42:1717545600:related"
80        );
81    }
82
83    #[test]
84    fn stamp_change_changes_the_key() {
85        // A republish (new stamp) yields a distinct key, so the stale
86        // entry is naturally abandoned rather than served.
87        let before = fragment_key("acme", 7, 100, "toc");
88        let after = fragment_key("acme", 7, 200, "toc");
89        assert_ne!(before, after);
90    }
91
92    #[test]
93    fn tenants_never_share_a_fragment_for_the_same_page_id() {
94        assert_ne!(fragment_key("acme", 7, 100, "toc"), fragment_key("globex", 7, 100, "toc"));
95    }
96
97    #[test]
98    fn suffix_isolates_fragments_on_one_page() {
99        assert_ne!(fragment_key("acme", 7, 100, "toc"), fragment_key("acme", 7, 100, "sidebar"));
100    }
101}