rustango_cms/cache_invalidate.rs
1//! Targeted page-cache invalidation hook.
2//!
3//! The public router (see [`crate::router()`]) layers
4//! [`rustango::cache_page::CachePageLayer`] in front of CMS page
5//! responses; that layer is TTL-based and emits the response under
6//! a key derived from `(method, path, host, vary-on)`. After an
7//! admin save the public response is stale until the TTL elapses.
8//!
9//! This module defines a [`PageCacheInvalidator`] trait that the
10//! host app can register on the admin state (`crate::admin::AdminState`). When
11//! present, every admin handler that mutates a page URL fires the
12//! invalidator on the affected URLs. Hosts that don't register one
13//! keep the old TTL-only behavior — the trait is purely opt-in.
14//!
15//! Two built-in invalidators ship:
16//!
17//! - [`BoxedCacheInvalidator`] — purges through
18//! [`CachePageLayer::invalidate`](rustango::cache_page::CachePageLayer::invalidate).
19//! Use when the admin handler holds an `Arc<BoxedCache>` to the same
20//! cache the public layer is using.
21//! - [`Noop`] — does nothing. Returned from `default()` so the
22//! trait object can be unconditionally invoked from handler code
23//! without `Option` plumbing.
24
25use std::sync::Arc;
26
27use async_trait::async_trait;
28use rustango::cache::BoxedCache;
29use rustango::cache_page::{CachePageLayer, PageKey};
30use rustango::tenancy::TenantSlug;
31
32/// Hook called by admin handlers after a page-content mutation.
33/// Implementations should fan out to whatever cache backend the
34/// public router uses (in-memory `CachePageLayer`, Cloudflare,
35/// Varnish, …) and drop the keys identified by the URL list.
36///
37/// Failures are intentionally swallowed by the handler (cache
38/// invalidation is best-effort; a stale render is worse than a
39/// failed save). Implementations should log internally.
40#[async_trait]
41pub trait PageCacheInvalidator: Send + Sync + 'static {
42 /// Drop the cache entry for the public render of `url_path` on
43 /// the given tenant (slug and org id, as the page cache keys it).
44 /// Hosts pass the unprefixed page URL — the implementation appends
45 /// the configured URL prefix + host(s) before computing the cache key.
46 async fn invalidate_url(&self, tenant: &TenantSlug, url_path: &str);
47
48 /// Drop every cache entry whose URL starts with `url_path` /
49 /// (the page itself + every descendant). Called after a slug
50 /// rename, a move, or a subtree delete.
51 async fn invalidate_subtree(&self, tenant: &TenantSlug, url_path: &str) {
52 // Default: fan out by enumerating the explicit URL list at
53 // the call site. Implementations that can do efficient
54 // prefix purges (Cloudflare wildcard purge, Redis SCAN +
55 // DEL on the key pattern) should override.
56 self.invalidate_url(tenant, url_path).await;
57 }
58
59 /// Drop the cache entries for many page URLs at once. The
60 /// default loops over [`Self::invalidate_url`] — preserving the
61 /// per-URL behavior — but backends with a bulk-purge API
62 /// (Cloudflare `files`, Azure CDN `contentPaths`) should override
63 /// this to issue a single request instead of N. The purge fan-out
64 /// in [`crate::task_queue::purge_urls`] calls this so a batch
65 /// backend collapses a multi-URL save into one round-trip.
66 async fn invalidate_urls(&self, tenant: &TenantSlug, url_paths: &[String]) {
67 for url in url_paths {
68 self.invalidate_url(tenant, url).await;
69 }
70 }
71}
72
73/// Supplies the OAuth2 bearer token for the cloud-CDN backends that
74/// authenticate against a Google / Azure management API.
75///
76/// Both APIs take a short-lived (~1h) access token. Production
77/// deployments should implement this against their environment's
78/// token endpoint — the GCE/GKE metadata server, a workload-identity
79/// exchange, or a refreshing `gcloud auth` / `az account` helper — so
80/// the token is renewed before it expires. `None` means "no token
81/// available right now"; the purge is then skipped (best-effort, per
82/// the [`PageCacheInvalidator`] contract).
83#[async_trait]
84pub trait AccessTokenSource: Send + Sync + 'static {
85 /// Return a fresh bearer token, or `None` to skip the purge.
86 async fn token(&self) -> Option<String>;
87}
88
89/// Fixed bearer token. Fine for one-shot scripts, short-lived jobs,
90/// and tests; **not** for a long-running server, where the token will
91/// expire (~1h) — implement [`AccessTokenSource`] against your token
92/// endpoint instead so it refreshes.
93#[derive(Debug, Clone)]
94pub struct StaticToken(pub String);
95
96#[async_trait]
97impl AccessTokenSource for StaticToken {
98 async fn token(&self) -> Option<String> {
99 Some(self.0.clone())
100 }
101}
102
103/// No-op invalidator returned from [`Arc<dyn PageCacheInvalidator>::default`].
104/// Lets handler code call `invalidator.invalidate_url(...).await`
105/// without `if let Some(...) = ...` plumbing when the host hasn't
106/// registered a real one.
107#[derive(Default, Debug, Clone, Copy)]
108pub struct Noop;
109
110#[async_trait]
111impl PageCacheInvalidator for Noop {
112 async fn invalidate_url(&self, _tenant: &TenantSlug, _url_path: &str) {}
113}
114
115/// Convenience constructor — returns an `Arc<dyn PageCacheInvalidator>`
116/// pointing at [`Noop`].
117#[must_use]
118pub fn noop() -> Arc<dyn PageCacheInvalidator> {
119 Arc::new(Noop)
120}
121
122/// Register an after-commit purge of `url_paths` for the enclosing
123/// [`rustango::sql::atomic`] block. The purge fires **only if
124/// the transaction commits** — on rollback the queued callback is
125/// dropped and nothing is evicted, so a failed save can never knock a
126/// still-valid entry out of the public cache.
127///
128/// `on_commit` callbacks are synchronous; the (async) purge is
129/// therefore driven on a detached `tokio::spawn` task, so the admin
130/// response isn't blocked on the purge round-trips.
131///
132/// Inside that task the purge goes through
133/// [`crate::task_queue::purge_urls`]: when a background queue is
134/// configured it dispatches a **retriable** `CachePurgeJob`; otherwise
135/// it purges **inline** in list order (the original behavior).
136///
137/// No-op (registers nothing) when `url_paths` is empty.
138///
139/// # Panics
140/// Panics if called outside an `atomic` scope — the callback would
141/// never fire. See [`rustango::sql::on_commit`].
142pub fn invalidate_urls_on_commit(
143 invalidator: Arc<dyn PageCacheInvalidator>,
144 tenant: TenantSlug,
145 url_paths: Vec<String>,
146) {
147 if url_paths.is_empty() {
148 return;
149 }
150 rustango::sql::on_commit(move || {
151 rustango::__private_runtime::tokio::spawn(async move {
152 crate::task_queue::purge_urls(invalidator, tenant, url_paths).await;
153 });
154 });
155}
156
157/// Built-in invalidator over the same [`BoxedCache`] the public
158/// [`CachePageLayer`] uses. Keys come from the framework's own
159/// [`CachePageLayer::invalidate`], which purges every cached variant of
160/// a path (any query, any vary value), under the tenant it is given.
161pub struct BoxedCacheInvalidator {
162 /// Keyed like the public layer: same cache and `key_prefix`.
163 layer: CachePageLayer,
164 /// Tenant slug → public Host header values that should be
165 /// invalidated. Most apps map each tenant to one host; some
166 /// (apex + subdomain) supply multiple. If a tenant slug isn't
167 /// in the map, the invalidator falls back to `default_hosts`.
168 hosts_by_tenant: std::collections::HashMap<String, Vec<String>>,
169 /// Fallback host list (used when a tenant isn't named in the
170 /// map). Useful for single-tenant deployments where every URL
171 /// lives under the same Host.
172 default_hosts: Vec<String>,
173 /// Vary-on header values for the exact entry deleted with each path.
174 vary_values: Vec<(String, String)>,
175}
176
177impl BoxedCacheInvalidator {
178 /// Build a new invalidator targeting `cache` with the public
179 /// router's `key_prefix`.
180 #[must_use]
181 pub fn new(cache: BoxedCache, key_prefix: impl Into<String>) -> Self {
182 Self {
183 layer: CachePageLayer::new(cache).key_prefix(key_prefix),
184 hosts_by_tenant: std::collections::HashMap::new(),
185 default_hosts: Vec::new(),
186 vary_values: Vec::new(),
187 }
188 }
189
190 /// Map a tenant slug to one or more Host header values. Both
191 /// `acme.localhost` and `acme.localhost:8090` should be added
192 /// when the same site is reachable via both.
193 #[must_use]
194 pub fn with_tenant_hosts(
195 mut self,
196 tenant_slug: impl Into<String>,
197 hosts: impl IntoIterator<Item = String>,
198 ) -> Self {
199 self.hosts_by_tenant
200 .insert(tenant_slug.into(), hosts.into_iter().collect());
201 self
202 }
203
204 /// Fallback host list — used when a tenant slug isn't in the
205 /// per-tenant map. Set this in single-tenant deployments where
206 /// every CMS URL lives under the same Host.
207 #[must_use]
208 pub fn with_default_hosts(mut self, hosts: impl IntoIterator<Item = String>) -> Self {
209 self.default_hosts = hosts.into_iter().collect();
210 self
211 }
212
213 /// Mirror the public layer's `vary_on(...)` declarations. The path's
214 /// every variant is purged anyway; these pick the exact entry that is
215 /// also deleted at once.
216 #[must_use]
217 pub fn with_vary_values(mut self, pairs: impl IntoIterator<Item = (String, String)>) -> Self {
218 self.vary_values = pairs.into_iter().collect();
219 let names: Vec<String> = self.vary_values.iter().map(|(n, _)| n.clone()).collect();
220 self.layer = self.layer.vary_on(&names);
221 self
222 }
223
224 /// The page keys to purge for `url_path` on `tenant`.
225 fn pages_for(&self, tenant: &TenantSlug, url_path: &str) -> Vec<PageKey> {
226 self.hosts_by_tenant
227 .get(&tenant.slug)
228 .unwrap_or(&self.default_hosts)
229 .iter()
230 .map(|host| {
231 let mut page = PageKey::new(url_path, host.as_str()).tenant(tenant);
232 for (name, value) in &self.vary_values {
233 page = page.vary(name, value.as_str());
234 }
235 page
236 })
237 .collect()
238 }
239}
240
241#[async_trait]
242impl PageCacheInvalidator for BoxedCacheInvalidator {
243 async fn invalidate_url(&self, tenant: &TenantSlug, url_path: &str) {
244 let pages = self.pages_for(tenant, url_path);
245 if pages.is_empty() {
246 tracing::debug!(
247 target: "rustango_cms::cache_invalidate",
248 tenant = %tenant.slug,
249 "no hosts configured — skipping cache invalidation"
250 );
251 return;
252 }
253 match self.layer.invalidate(&pages).await {
254 Ok(()) => tracing::debug!(
255 target: "rustango_cms::cache_invalidate",
256 tenant = %tenant.slug,
257 path = %url_path,
258 "purged"
259 ),
260 Err(e) => tracing::warn!(
261 target: "rustango_cms::cache_invalidate",
262 tenant = %tenant.slug,
263 path = %url_path,
264 error = %e,
265 "cache purge failed (continuing — TTL will catch up)"
266 ),
267 }
268 }
269}
270
271#[cfg(test)]
272mod on_commit_tests {
273 use super::*;
274
275 #[test]
276 fn empty_url_list_is_a_noop_outside_atomic() {
277 // No URLs → returns before touching `on_commit`, so it must not
278 // panic even though we're not inside an `atomic` scope.
279 invalidate_urls_on_commit(noop(), TenantSlug::new(1, "acme"), vec![]);
280 }
281
282 #[test]
283 #[should_panic(expected = "on_commit")]
284 fn non_empty_outside_atomic_panics() {
285 // A non-empty list registers an `on_commit` callback, which the
286 // framework rejects outside an `atomic` scope — proof the helper
287 // is wired to the commit hook (and won't silently drop a purge).
288 invalidate_urls_on_commit(noop(), TenantSlug::new(1, "acme"), vec!["/about".to_owned()]);
289 }
290}
291
292// Behavioral commit/rollback coverage runs against a serverless
293// SQLite-in-memory pool, so it's gated on the `sqlite` feature:
294// cargo test --lib --no-default-features --features sqlite on_commit_db
295#[cfg(all(test, feature = "sqlite"))]
296mod on_commit_db_tests {
297 use super::*;
298 use rustango::sql::Pool;
299 use std::sync::Mutex;
300
301 /// Records every purged URL so the test can assert the after-commit
302 /// fan-out (and its absence on rollback).
303 struct Recorder(Arc<Mutex<Vec<String>>>);
304
305 #[async_trait]
306 impl PageCacheInvalidator for Recorder {
307 async fn invalidate_url(&self, _tenant: &rustango::tenancy::TenantSlug, url_path: &str) {
308 self.0
309 .lock()
310 .expect("recorder mutex")
311 .push(url_path.to_owned());
312 }
313 }
314
315 async fn mem_pool() -> Pool {
316 Pool::connect("sqlite::memory:")
317 .await
318 .expect("sqlite in-memory pool")
319 }
320
321 /// The purge runs on a detached task; yield until it records at
322 /// least `n` URLs (bounded so a regression fails instead of hangs).
323 async fn wait_until(urls: &Arc<Mutex<Vec<String>>>, n: usize) -> Vec<String> {
324 for _ in 0..5000 {
325 {
326 let g = urls.lock().expect("recorder mutex");
327 if g.len() >= n {
328 return g.clone();
329 }
330 }
331 tokio::task::yield_now().await;
332 }
333 urls.lock().expect("recorder mutex").clone()
334 }
335
336 #[tokio::test]
337 async fn commit_fires_the_purge_in_order() {
338 let pool = mem_pool().await;
339 let urls = Arc::new(Mutex::new(Vec::new()));
340 let inv: Arc<dyn PageCacheInvalidator> = Arc::new(Recorder(urls.clone()));
341
342 rustango::atomic!(&pool, |_tx| {
343 invalidate_urls_on_commit(
344 inv.clone(),
345 TenantSlug::new(1, "acme"),
346 vec!["/about".to_owned(), "/news".to_owned()],
347 );
348 assert_eq!(rustango::sql::on_commit_pending(), 1, "one callback queued");
349 Ok::<(), rustango::sql::ExecError>(())
350 })
351 .await
352 .expect("atomic commit");
353
354 assert_eq!(
355 wait_until(&urls, 2).await,
356 vec!["/about".to_owned(), "/news".to_owned()]
357 );
358 }
359
360 #[tokio::test]
361 async fn rollback_drops_the_purge() {
362 let pool = mem_pool().await;
363 let urls = Arc::new(Mutex::new(Vec::new()));
364 let inv: Arc<dyn PageCacheInvalidator> = Arc::new(Recorder(urls.clone()));
365
366 let res = rustango::atomic!(&pool, |_tx| {
367 invalidate_urls_on_commit(inv.clone(), TenantSlug::new(1, "acme"), vec!["/about".to_owned()]);
368 assert_eq!(
369 rustango::sql::on_commit_pending(),
370 1,
371 "callback queued pre-rollback"
372 );
373 Err::<(), rustango::sql::ExecError>(rustango::sql::ExecError::EmptyReturning)
374 })
375 .await;
376 assert!(res.is_err(), "atomic should roll back");
377
378 // Give any (erroneously) spawned task room to run, then assert
379 // nothing was purged — the callback must have been dropped.
380 for _ in 0..50 {
381 tokio::task::yield_now().await;
382 }
383 assert!(
384 urls.lock().expect("recorder mutex").is_empty(),
385 "rollback must not purge"
386 );
387 }
388}