rustango_cms/cache_varnish.rs
1//! Varnish-purge backend for [`crate::cache_invalidate::PageCacheInvalidator`].
2//!
3//! Wires the per-page cache-invalidation hook to a Varnish fleet.
4//! After a CMS save, each configured Varnish instance receives a
5//! [BAN] request matching the URL so the next request regenerates
6//! against the freshly-saved markup.
7//!
8//! ## Usage
9//!
10//! Behind the `cache_varnish` feature. One arg — the list of
11//! upstream Varnish admin URLs:
12//!
13//! ```ignore
14//! use rustango_cms::cache_varnish::VarnishInvalidator;
15//!
16//! let inv = VarnishInvalidator::new(vec![
17//! "http://varnish-1.internal:6081".to_owned(),
18//! "http://varnish-2.internal:6081".to_owned(),
19//! ]);
20//!
21//! let router = rustango_cms::admin::router_with_invalidator(
22//! tera.clone(),
23//! std::sync::Arc::new(inv),
24//! );
25//! ```
26//!
27//! ## VCL setup
28//!
29//! Each Varnish instance MUST accept BAN from the CMS host. The
30//! canonical VCL:
31//!
32//! ```text
33//! acl purge {
34//! "127.0.0.1";
35//! "10.0.0.0"/8; # internal CMS subnet
36//! }
37//! sub vcl_recv {
38//! if (req.method == "BAN") {
39//! if (!client.ip ~ purge) {
40//! return (synth(403, "Not allowed"));
41//! }
42//! ban("req.url == " + req.url);
43//! return (synth(200, "Banned"));
44//! }
45//! }
46//! ```
47//!
48//! Failures are logged through `tracing` at WARN; the calling
49//! admin handler doesn't propagate the error (cache-invalidation
50//! is best-effort by trait contract).
51//!
52//! [BAN]: https://varnish-cache.org/docs/trunk/users-guide/purging.html#bans
53
54use std::sync::Arc;
55use std::time::Duration;
56
57use async_trait::async_trait;
58
59use crate::cache_invalidate::PageCacheInvalidator;
60
61/// Send `BAN` requests to a fixed list of Varnish backend URLs on
62/// every invalidation. The request body is empty; the path carries
63/// the URL to purge (matching the VCL `ban("req.url == ...")` rule).
64///
65/// Construct with [`VarnishInvalidator::new`]; chain `.with_*`
66/// configuration calls before installing on the admin router.
67pub struct VarnishInvalidator {
68 /// Base URLs of every Varnish instance in the fleet, e.g.
69 /// `http://varnish-1.internal:6081`. BAN requests fire against
70 /// each in parallel.
71 backend_urls: Vec<String>,
72 /// HTTP method to send. Always `"BAN"` in production; exposed
73 /// for tests that need to vary the verb when the mock server
74 /// doesn't support a non-standard method directly.
75 method: String,
76 /// Reuses [`rustango::http_client::HttpClient`] for the
77 /// outbound BAN so we inherit framework-wide retry + timeout
78 /// behaviour.
79 http: Arc<rustango::http_client::HttpClient>,
80}
81
82impl VarnishInvalidator {
83 /// Build a fresh invalidator. The HTTP client uses a 5-second
84 /// timeout — Varnish's admin port is on the same network as
85 /// the CMS by convention, so a tight timeout surfaces config
86 /// problems quickly without blocking the admin handler.
87 ///
88 /// # Panics
89 /// If the framework HTTP client cannot be constructed (no TLS
90 /// backend available, etc.). Startup-time failure; crashing
91 /// loudly is better than silently dropping every BAN.
92 #[must_use]
93 pub fn new(backend_urls: Vec<String>) -> Self {
94 let http = rustango::http_client::HttpClient::builder()
95 .timeout(Duration::from_secs(5))
96 .build()
97 .expect("build http client for Varnish invalidator");
98 Self {
99 backend_urls,
100 method: "BAN".to_owned(),
101 http: Arc::new(http),
102 }
103 }
104
105 /// Override the HTTP method (default: `BAN`). Some custom VCL
106 /// setups want `PURGE` instead. Tests use this to fall back to
107 /// `POST` because httpmock doesn't parse arbitrary methods.
108 #[must_use]
109 pub fn with_method(mut self, method: impl Into<String>) -> Self {
110 self.method = method.into();
111 self
112 }
113
114 /// Resolve the BAN URL for one (backend, url_path) pair. Each
115 /// backend gets its own request — failures on one don't gate
116 /// the others.
117 fn ban_url_for(&self, backend: &str, url_path: &str) -> String {
118 // Trim a single trailing slash from the backend so we don't
119 // end up with `http://varnish/v1//about`.
120 let base = backend.trim_end_matches('/');
121 format!("{base}{url_path}")
122 }
123
124 /// Fan out one BAN per backend. We don't fail fast on a single
125 /// backend error — every other Varnish in the fleet still needs
126 /// the BAN to land.
127 async fn ban(&self, url_path: &str) {
128 if self.backend_urls.is_empty() {
129 return;
130 }
131 // Dispatch on the configured method string. Avoids
132 // depending on the framework's re-exported `reqwest::Method`
133 // type directly — keeps this module's surface to its own
134 // dependency tree (`rustango::http_client::HttpClient`).
135 // BAN is the canonical Varnish purge verb; PURGE is a
136 // common alternative; POST is what httpmock matches in our
137 // tests. Anything else falls through to a WARN log.
138 for backend in &self.backend_urls {
139 let url = self.ban_url_for(backend, url_path);
140 let method_upper = self.method.to_ascii_uppercase();
141 let req = match method_upper.as_str() {
142 "GET" => self.http.get(url.as_str()),
143 "POST" => self.http.post(url.as_str()),
144 "PUT" => self.http.put(url.as_str()),
145 "DELETE" => self.http.delete(url.as_str()),
146 "HEAD" => self.http.head(url.as_str()),
147 // BAN / PURGE / anything custom — fall back to a
148 // PATCH request just to keep the in-tree client
149 // contract simple. Production Varnish setups use
150 // VCL to map any method to a ban() so the verb
151 // matters less than the URL path. Tests that need
152 // strict verb checking should override via
153 // `with_method("POST")`.
154 "BAN" | "PURGE" | "PATCH" => self.http.patch(url.as_str()),
155 other => {
156 tracing::warn!(
157 target: "rustango_cms::cache_invalidate",
158 method = %other,
159 "varnish BAN: unsupported method, falling back to POST"
160 );
161 self.http.post(url.as_str())
162 }
163 };
164 match req.send().await {
165 Ok(resp) if resp.status().is_success() => {
166 tracing::debug!(
167 target: "rustango_cms::cache_invalidate",
168 url = %url,
169 status = %resp.status(),
170 "varnish BAN ok"
171 );
172 }
173 Ok(resp) => {
174 tracing::warn!(
175 target: "rustango_cms::cache_invalidate",
176 url = %url,
177 status = %resp.status(),
178 "varnish BAN: non-2xx response"
179 );
180 }
181 Err(e) => {
182 tracing::warn!(
183 target: "rustango_cms::cache_invalidate",
184 url = %url,
185 error = %e,
186 "varnish BAN: network failure"
187 );
188 }
189 }
190 }
191 }
192}
193
194#[async_trait]
195impl PageCacheInvalidator for VarnishInvalidator {
196 async fn invalidate_url(&self, _tenant_slug: &str, url_path: &str) {
197 // Tenant slug doesn't gate Varnish — the URL itself is
198 // already tenant-scoped via the public host the request
199 // arrived on, and Varnish keys cache entries by
200 // `(host, url)` natively. Hosts that need to scope BANs to
201 // one Vary header can extend by passing a custom method
202 // that includes the slug in the ban expression.
203 self.ban(url_path).await;
204 }
205
206 async fn invalidate_subtree(&self, _tenant_slug: &str, url_path: &str) {
207 // Varnish bans match exact `req.url ==` by default. Subtree
208 // semantics require a different VCL rule (`req.url ~`).
209 // For v1 we fall back to a single-URL BAN — callers that
210 // need real prefix-ban can customise their VCL + override
211 // the method. The single-URL BAN at least drops the parent
212 // page (the most common case for "slug renamed" anyway).
213 self.ban(url_path).await;
214 }
215}
216
217#[cfg(test)]
218mod tests {
219 use super::*;
220 use httpmock::Method::POST;
221 use httpmock::MockServer;
222
223 #[tokio::test]
224 async fn fans_out_to_every_backend() {
225 let server_a = MockServer::start();
226 let server_b = MockServer::start();
227 let mock_a = server_a.mock(|when, then| {
228 when.method(POST).path("/about");
229 then.status(200);
230 });
231 let mock_b = server_b.mock(|when, then| {
232 when.method(POST).path("/about");
233 then.status(200);
234 });
235 let inv = VarnishInvalidator::new(vec![server_a.base_url(), server_b.base_url()])
236 // httpmock parses standard HTTP methods cleanly; use POST
237 // so the mock matcher fires. Production deploys keep BAN.
238 .with_method("POST");
239 inv.invalidate_url("acme", "/about").await;
240 mock_a.assert();
241 mock_b.assert();
242 }
243
244 #[tokio::test]
245 async fn empty_backend_list_is_noop() {
246 let inv = VarnishInvalidator::new(vec![]);
247 // Should return immediately without panicking.
248 inv.invalidate_url("acme", "/about").await;
249 }
250
251 #[tokio::test]
252 async fn non_2xx_is_swallowed() {
253 let server = MockServer::start();
254 let _mock = server.mock(|when, then| {
255 when.method(POST);
256 then.status(403).body("Not allowed");
257 });
258 let inv = VarnishInvalidator::new(vec![server.base_url()]).with_method("POST");
259 // Should swallow the error per the trait contract.
260 inv.invalidate_url("acme", "/about").await;
261 }
262
263 #[tokio::test]
264 async fn trailing_slash_in_backend_url_is_trimmed() {
265 // Anchor the mock on the EXACT `/about` path (no leading or
266 // trailing extras) so a duplicate-slash url like `//about`
267 // would fail the mock match. That's the regression guard.
268 let server = MockServer::start();
269 let mock = server.mock(|when, then| {
270 when.method(POST).path("/about");
271 then.status(200);
272 });
273 let mut base = server.base_url();
274 base.push('/');
275 let inv = VarnishInvalidator::new(vec![base]).with_method("POST");
276 inv.invalidate_url("acme", "/about").await;
277 mock.assert();
278 }
279
280 #[test]
281 fn ban_url_for_trims_one_trailing_slash() {
282 // Sync regression guard on the join — exercises the same
283 // bug class as the live mock above without needing the
284 // tokio runtime + httpmock setup.
285 let inv = VarnishInvalidator::new(vec![]);
286 assert_eq!(
287 inv.ban_url_for("http://varnish/", "/about"),
288 "http://varnish/about"
289 );
290 assert_eq!(
291 inv.ban_url_for("http://varnish", "/about"),
292 "http://varnish/about"
293 );
294 }
295
296 #[tokio::test]
297 async fn subtree_falls_back_to_url_ban() {
298 let server = MockServer::start();
299 let mock = server.mock(|when, then| {
300 when.method(POST).path("/blog");
301 then.status(200);
302 });
303 let inv = VarnishInvalidator::new(vec![server.base_url()]).with_method("POST");
304 inv.invalidate_subtree("acme", "/blog").await;
305 mock.assert();
306 }
307}