use std::sync::Arc;
use async_trait::async_trait;
use rustango::cache::BoxedCache;
#[async_trait]
pub trait PageCacheInvalidator: Send + Sync + 'static {
async fn invalidate_url(&self, tenant_slug: &str, url_path: &str);
async fn invalidate_subtree(&self, tenant_slug: &str, url_path: &str) {
self.invalidate_url(tenant_slug, url_path).await;
}
async fn invalidate_urls(&self, tenant_slug: &str, url_paths: &[String]) {
for url in url_paths {
self.invalidate_url(tenant_slug, url).await;
}
}
}
#[async_trait]
pub trait AccessTokenSource: Send + Sync + 'static {
async fn token(&self) -> Option<String>;
}
#[derive(Debug, Clone)]
pub struct StaticToken(pub String);
#[async_trait]
impl AccessTokenSource for StaticToken {
async fn token(&self) -> Option<String> {
Some(self.0.clone())
}
}
#[derive(Default, Debug, Clone, Copy)]
pub struct Noop;
#[async_trait]
impl PageCacheInvalidator for Noop {
async fn invalidate_url(&self, _tenant_slug: &str, _url_path: &str) {}
}
#[must_use]
pub fn noop() -> Arc<dyn PageCacheInvalidator> {
Arc::new(Noop)
}
pub fn invalidate_urls_on_commit(
invalidator: Arc<dyn PageCacheInvalidator>,
tenant_slug: String,
url_paths: Vec<String>,
) {
if url_paths.is_empty() {
return;
}
rustango::sql::on_commit(move || {
rustango::__private_runtime::tokio::spawn(async move {
crate::task_queue::purge_urls(invalidator, tenant_slug, url_paths).await;
});
});
}
pub struct BoxedCacheInvalidator {
cache: BoxedCache,
key_prefix: String,
hosts_by_tenant: std::collections::HashMap<String, Vec<String>>,
default_hosts: Vec<String>,
vary_values: Vec<(String, String)>,
}
impl BoxedCacheInvalidator {
#[must_use]
pub fn new(cache: BoxedCache, key_prefix: impl Into<String>) -> Self {
Self {
cache,
key_prefix: key_prefix.into(),
hosts_by_tenant: std::collections::HashMap::new(),
default_hosts: Vec::new(),
vary_values: Vec::new(),
}
}
#[must_use]
pub fn with_tenant_hosts(
mut self,
tenant_slug: impl Into<String>,
hosts: impl IntoIterator<Item = String>,
) -> Self {
self.hosts_by_tenant
.insert(tenant_slug.into(), hosts.into_iter().collect());
self
}
#[must_use]
pub fn with_default_hosts(mut self, hosts: impl IntoIterator<Item = String>) -> Self {
self.default_hosts = hosts.into_iter().collect();
self
}
#[must_use]
pub fn with_vary_values(mut self, pairs: impl IntoIterator<Item = (String, String)>) -> Self {
self.vary_values = pairs.into_iter().collect();
self
}
fn hosts_for(&self, tenant_slug: &str) -> &[String] {
self.hosts_by_tenant
.get(tenant_slug)
.map(Vec::as_slice)
.unwrap_or(&self.default_hosts)
}
fn compute_key(&self, path: &str, host: &str, tenant_slug: &str) -> String {
use std::fmt::Write as _;
let mut k = String::with_capacity(self.key_prefix.len() + 128);
let _ = write!(&mut k, "{}|", self.key_prefix);
write_lp(&mut k, "GET");
write_lp(&mut k, path);
write_lp(&mut k, "");
write_lp(&mut k, host);
write_lp(&mut k, tenant_slug);
for (name, value) in &self.vary_values {
write_lp(&mut k, name);
write_lp(&mut k, value);
}
k
}
}
fn write_lp(buf: &mut String, s: &str) {
use std::fmt::Write as _;
let _ = write!(buf, "{}:{}|", s.len(), s);
}
#[cfg(test)]
mod key_shape_tests {
use super::*;
use rustango::cache::NullCache;
fn fake_invalidator() -> BoxedCacheInvalidator {
BoxedCacheInvalidator::new(Arc::new(NullCache), "rcms:page")
}
#[test]
fn key_shape_matches_cache_page_layer() {
let inv = fake_invalidator();
let key = inv.compute_key("/about", "acme.localhost:8090", "acme");
assert_eq!(key, "rcms:page|3:GET|6:/about|0:|19:acme.localhost:8090|4:acme|");
}
#[test]
fn key_with_vary_values_appends_pairs() {
let inv = fake_invalidator()
.with_vary_values(vec![("accept-language".to_owned(), "en".to_owned())]);
let key = inv.compute_key("/about", "acme.localhost", "acme");
assert_eq!(
key,
"rcms:page|3:GET|6:/about|0:|14:acme.localhost|4:acme|15:accept-language|2:en|"
);
}
}
#[async_trait]
impl PageCacheInvalidator for BoxedCacheInvalidator {
async fn invalidate_url(&self, tenant_slug: &str, url_path: &str) {
let hosts = self.hosts_for(tenant_slug);
if hosts.is_empty() {
tracing::debug!(
target: "rustango_cms::cache_invalidate",
tenant = %tenant_slug,
"no hosts configured — skipping cache invalidation"
);
return;
}
for host in hosts {
let key = self.compute_key(url_path, host, tenant_slug);
match self.cache.delete(&key).await {
Ok(()) => tracing::debug!(
target: "rustango_cms::cache_invalidate",
%key,
"purged"
),
Err(e) => tracing::warn!(
target: "rustango_cms::cache_invalidate",
%key,
error = %e,
"cache delete failed (continuing — TTL will catch up)"
),
}
}
}
}
#[cfg(test)]
mod on_commit_tests {
use super::*;
#[test]
fn empty_url_list_is_a_noop_outside_atomic() {
invalidate_urls_on_commit(noop(), "acme".to_owned(), vec![]);
}
#[test]
#[should_panic(expected = "on_commit")]
fn non_empty_outside_atomic_panics() {
invalidate_urls_on_commit(noop(), "acme".to_owned(), vec!["/about".to_owned()]);
}
}
#[cfg(all(test, feature = "sqlite"))]
mod on_commit_db_tests {
use super::*;
use rustango::sql::Pool;
use std::sync::Mutex;
struct Recorder(Arc<Mutex<Vec<String>>>);
#[async_trait]
impl PageCacheInvalidator for Recorder {
async fn invalidate_url(&self, _tenant_slug: &str, url_path: &str) {
self.0
.lock()
.expect("recorder mutex")
.push(url_path.to_owned());
}
}
async fn mem_pool() -> Pool {
Pool::connect("sqlite::memory:")
.await
.expect("sqlite in-memory pool")
}
async fn wait_until(urls: &Arc<Mutex<Vec<String>>>, n: usize) -> Vec<String> {
for _ in 0..5000 {
{
let g = urls.lock().expect("recorder mutex");
if g.len() >= n {
return g.clone();
}
}
tokio::task::yield_now().await;
}
urls.lock().expect("recorder mutex").clone()
}
#[tokio::test]
async fn commit_fires_the_purge_in_order() {
let pool = mem_pool().await;
let urls = Arc::new(Mutex::new(Vec::new()));
let inv: Arc<dyn PageCacheInvalidator> = Arc::new(Recorder(urls.clone()));
rustango::atomic!(&pool, |_tx| {
invalidate_urls_on_commit(
inv.clone(),
"acme".to_owned(),
vec!["/about".to_owned(), "/news".to_owned()],
);
assert_eq!(rustango::sql::on_commit_pending(), 1, "one callback queued");
Ok::<(), rustango::sql::ExecError>(())
})
.await
.expect("atomic commit");
assert_eq!(
wait_until(&urls, 2).await,
vec!["/about".to_owned(), "/news".to_owned()]
);
}
#[tokio::test]
async fn rollback_drops_the_purge() {
let pool = mem_pool().await;
let urls = Arc::new(Mutex::new(Vec::new()));
let inv: Arc<dyn PageCacheInvalidator> = Arc::new(Recorder(urls.clone()));
let res = rustango::atomic!(&pool, |_tx| {
invalidate_urls_on_commit(inv.clone(), "acme".to_owned(), vec!["/about".to_owned()]);
assert_eq!(
rustango::sql::on_commit_pending(),
1,
"callback queued pre-rollback"
);
Err::<(), rustango::sql::ExecError>(rustango::sql::ExecError::EmptyReturning)
})
.await;
assert!(res.is_err(), "atomic should roll back");
for _ in 0..50 {
tokio::task::yield_now().await;
}
assert!(
urls.lock().expect("recorder mutex").is_empty(),
"rollback must not purge"
);
}
}