Skip to main content

rustango_cms/
cache_cloudflare.rs

1//! Cloudflare-purge backend for [`crate::cache_invalidate::PageCacheInvalidator`].
2//!
3//! Wires the per-page cache-invalidation hook to Cloudflare's
4//! [purge_cache] API. After a CMS save, the public URL is dropped
5//! from Cloudflare's edge cache so the next request regenerates
6//! against the freshly-saved markup instead of waiting for the
7//! cache TTL to elapse.
8//!
9//! ## Usage
10//!
11//! Behind the `cache_cloudflare` feature. Two args:
12//!
13//! ```ignore
14//! use rustango_cms::cache_cloudflare::CloudflareInvalidator;
15//!
16//! let inv = CloudflareInvalidator::new(
17//!     std::env::var("CLOUDFLARE_ZONE_ID").unwrap(),
18//!     std::env::var("CLOUDFLARE_API_TOKEN").unwrap(),
19//! )
20//! .with_origin_host("acme.example.com");
21//!
22//! let router = rustango_cms::admin::router_with_invalidator(
23//!     tera.clone(),
24//!     std::sync::Arc::new(inv),
25//! );
26//! ```
27//!
28//! The token needs `Zone:Cache Purge:Edit` on the target zone —
29//! [token-permissions]. Failures are logged through `tracing`
30//! at WARN; the calling admin handler doesn't propagate the error
31//! (cache-invalidation is best-effort by trait contract).
32//!
33//! [purge_cache]: https://developers.cloudflare.com/api/operations/zone-purge
34//! [token-permissions]: https://developers.cloudflare.com/fundamentals/api/get-started/create-token/
35
36use std::collections::HashMap;
37use std::sync::Arc;
38use std::time::Duration;
39
40use async_trait::async_trait;
41use serde::Serialize;
42
43use crate::cache_invalidate::PageCacheInvalidator;
44
45/// Build absolute URLs the public router is serving by joining the
46/// tenant's public host with the supplied url_path. Cloudflare's
47/// purge API accepts full URLs (`https://example.com/about/`) and
48/// drops the matching edge entry on every PoP. Per-tenant deploys
49/// typically map one tenant to one origin host; multi-host setups
50/// can register the additional hosts via
51/// [`CloudflareInvalidator::with_tenant_host`].
52///
53/// Construct with [`CloudflareInvalidator::new`]; chain `.with_*`
54/// configuration calls before installing on the admin router.
55pub struct CloudflareInvalidator {
56    /// Cloudflare zone id the URLs live under. Pulled from the
57    /// dashboard or `cloudflare-cli zone list`.
58    zone_id: String,
59    /// API token with `Zone:Cache Purge:Edit` scoped to `zone_id`.
60    api_token: String,
61    /// Tenant-slug → list of public origin hosts. Most deploys map
62    /// each tenant to one host; register additional ones here if
63    /// the same content is served under multiple domains.
64    tenant_hosts: HashMap<String, Vec<String>>,
65    /// Default-when-no-tenant-mapping origin host. Set via
66    /// [`Self::with_origin_host`]. Useful for single-tenant deploys.
67    default_host: Option<String>,
68    /// HTTPS / HTTP scheme to prepend to the URL. Defaults to
69    /// `https` since Cloudflare-fronted origins are TLS-only in
70    /// practice; expose a setter for the unusual dev case.
71    scheme: String,
72    /// Reuses [`rustango::http_client::HttpClient`] for the
73    /// outbound POST so we inherit framework-wide retry + timeout
74    /// behaviour.
75    http: Arc<rustango::http_client::HttpClient>,
76    /// Override of the API base URL — production points at
77    /// `https://api.cloudflare.com`; the integration tests point at
78    /// the httpmock server.
79    api_base: String,
80}
81
82impl CloudflareInvalidator {
83    /// Build a fresh invalidator. The HTTP client uses the
84    /// framework's default 10-second timeout + exponential-backoff
85    /// retry policy.
86    ///
87    /// # Panics
88    /// If the framework HTTP client cannot be constructed (no TLS
89    /// backend available, etc.). This is a startup-time failure;
90    /// crashing loudly is better than silently dropping every purge.
91    #[must_use]
92    pub fn new(zone_id: impl Into<String>, api_token: impl Into<String>) -> Self {
93        let http = rustango::http_client::HttpClient::builder()
94            .timeout(Duration::from_secs(10))
95            .build()
96            .expect("build http client for Cloudflare invalidator");
97        Self {
98            zone_id: zone_id.into(),
99            api_token: api_token.into(),
100            tenant_hosts: HashMap::new(),
101            default_host: None,
102            scheme: "https".to_owned(),
103            http: Arc::new(http),
104            api_base: "https://api.cloudflare.com".to_owned(),
105        }
106    }
107
108    /// Single-tenant convenience — every invalidation targets
109    /// `<scheme>://<host><url_path>` regardless of tenant slug.
110    /// Multi-tenant setups should use [`Self::with_tenant_host`]
111    /// instead so each tenant resolves to its own public host(s).
112    #[must_use]
113    pub fn with_origin_host(mut self, host: impl Into<String>) -> Self {
114        self.default_host = Some(host.into());
115        self
116    }
117
118    /// Register an additional public host for `tenant_slug`. The
119    /// same page URL gets purged for every registered host; useful
120    /// when a tenant is served under both `acme.example.com` and a
121    /// vanity domain `acme.com`.
122    #[must_use]
123    pub fn with_tenant_host(
124        mut self,
125        tenant_slug: impl Into<String>,
126        host: impl Into<String>,
127    ) -> Self {
128        self.tenant_hosts
129            .entry(tenant_slug.into())
130            .or_default()
131            .push(host.into());
132        self
133    }
134
135    /// Override the URL scheme (default: `https`). Useful for
136    /// localhost / dev where the public origin is HTTP-only.
137    #[must_use]
138    pub fn with_scheme(mut self, scheme: impl Into<String>) -> Self {
139        self.scheme = scheme.into();
140        self
141    }
142
143    /// Override the Cloudflare API base URL. Used by tests to point
144    /// at an httpmock server; production keeps the default.
145    #[must_use]
146    pub fn with_api_base(mut self, api_base: impl Into<String>) -> Self {
147        self.api_base = api_base.into();
148        self
149    }
150
151    /// Resolve every public URL we need to purge for one
152    /// `(tenant_slug, url_path)` pair. Joins each registered host
153    /// (per-tenant + the fallback `default_host` if any) with the
154    /// path. The path is taken verbatim — Cloudflare's API matches
155    /// exact-URL purges, so callers should pre-normalise (leading
156    /// `/`, no trailing slash for non-root).
157    fn resolve_urls(&self, tenant_slug: &str, url_path: &str) -> Vec<String> {
158        let mut hosts: Vec<&str> = self
159            .tenant_hosts
160            .get(tenant_slug)
161            .map(|v| v.iter().map(String::as_str).collect())
162            .unwrap_or_default();
163        if hosts.is_empty() {
164            if let Some(h) = self.default_host.as_deref() {
165                hosts.push(h);
166            }
167        }
168        hosts
169            .into_iter()
170            .map(|h| format!("{}://{}{}", self.scheme, h, url_path))
171            .collect()
172    }
173
174    /// Max `files` entries per `purge_cache` request. Cloudflare caps
175    /// the Free/Pro/Business tiers at 30 URLs per call; Enterprise
176    /// allows more. We chunk at 30 so a single save spanning many
177    /// descendant URLs works on every plan.
178    const MAX_FILES_PER_REQUEST: usize = 30;
179
180    /// POST to `/client/v4/zones/{zone_id}/purge_cache` with the
181    /// exact-URL `files` list. Best-effort. Chunked at
182    /// [`Self::MAX_FILES_PER_REQUEST`] so large subtree purges don't
183    /// 400 on the non-Enterprise per-request cap. Exposed at
184    /// module scope (vs the trait fn) so the integration tests can
185    /// drive it without juggling an `Arc<dyn Trait>` cast.
186    async fn purge(&self, urls: Vec<String>) {
187        if urls.is_empty() {
188            return;
189        }
190        #[derive(Serialize)]
191        struct Body<'a> {
192            files: &'a [String],
193        }
194        for chunk in urls.chunks(Self::MAX_FILES_PER_REQUEST) {
195            self.send_purge(&Body { files: chunk }, "files").await;
196        }
197    }
198
199    /// Purge by **cache-tag**. Cloudflare Enterprise stamps
200    /// responses with `Cache-Tag` headers; purging a tag drops every
201    /// edge entry carrying it in one call — far cheaper than
202    /// enumerating URLs. The CMS doesn't auto-tag responses, so this
203    /// is a public hook: a host that sets `Cache-Tag` (e.g. per
204    /// page-type or per snippet) calls this after the relevant save.
205    /// No-op on non-Enterprise zones (the API rejects `tags`).
206    pub async fn purge_tags(&self, tags: Vec<String>) {
207        if tags.is_empty() {
208            return;
209        }
210        #[derive(Serialize)]
211        struct Body {
212            tags: Vec<String>,
213        }
214        self.send_purge(&Body { tags }, "tags").await;
215    }
216
217    /// Purge by **URL prefix** — Enterprise-only. Drops every
218    /// edge entry whose URL starts with one of `prefixes`
219    /// (`example.com/blog/`), i.e. a true subtree purge without
220    /// enumerating each descendant. No-op on non-Enterprise zones.
221    pub async fn purge_prefixes(&self, prefixes: Vec<String>) {
222        if prefixes.is_empty() {
223            return;
224        }
225        #[derive(Serialize)]
226        struct Body {
227            prefixes: Vec<String>,
228        }
229        self.send_purge(&Body { prefixes }, "prefixes").await;
230    }
231
232    /// Send one `purge_cache` POST with an arbitrary body shape
233    /// (`files` / `tags` / `prefixes`). `kind` is only for log
234    /// context. Failures are logged at WARN and swallowed per the
235    /// [`PageCacheInvalidator`] best-effort contract.
236    async fn send_purge<B: Serialize>(&self, body: &B, kind: &str) {
237        let url = format!(
238            "{}/client/v4/zones/{}/purge_cache",
239            self.api_base, self.zone_id
240        );
241        let req = self.http.post(url.as_str());
242        let req = match req.header("authorization", format!("Bearer {}", self.api_token)) {
243            Ok(r) => r,
244            Err(e) => {
245                tracing::warn!(
246                    target: "rustango_cms::cache_invalidate",
247                    error = %e, %kind,
248                    "cloudflare purge: header build failed"
249                );
250                return;
251            }
252        };
253        let req = match req.json(body) {
254            Ok(r) => r,
255            Err(e) => {
256                tracing::warn!(
257                    target: "rustango_cms::cache_invalidate",
258                    error = %e, %kind,
259                    "cloudflare purge: body serialise failed"
260                );
261                return;
262            }
263        };
264        match req.send().await {
265            Ok(resp) if resp.status().is_success() => {
266                tracing::debug!(
267                    target: "rustango_cms::cache_invalidate",
268                    status = %resp.status(), %kind,
269                    "cloudflare purge ok"
270                );
271            }
272            Ok(resp) => {
273                tracing::warn!(
274                    target: "rustango_cms::cache_invalidate",
275                    status = %resp.status(), %kind,
276                    "cloudflare purge: non-2xx response"
277                );
278            }
279            Err(e) => {
280                tracing::warn!(
281                    target: "rustango_cms::cache_invalidate",
282                    error = %e, %kind,
283                    "cloudflare purge: network failure"
284                );
285            }
286        }
287    }
288}
289
290#[async_trait]
291impl PageCacheInvalidator for CloudflareInvalidator {
292    async fn invalidate_url(&self, tenant: &rustango::tenancy::TenantSlug, url_path: &str) {
293        self.purge(self.resolve_urls(&tenant.slug, url_path)).await;
294    }
295
296    async fn invalidate_subtree(&self, tenant: &rustango::tenancy::TenantSlug, url_path: &str) {
297        // Cloudflare's `purge_cache` API supports `prefixes` for
298        // subtree purges, but it's an Enterprise-only feature. The
299        // free / Pro / Business tiers only accept exact URLs. Fall
300        // back to a single-URL purge — callers on an Enterprise zone
301        // can call [`Self::purge_prefixes`] explicitly for a true
302        // subtree drop. Keeping the default to the single-URL purge
303        // gives Free/Pro/Business operators a working purge for the
304        // most-common case.
305        self.purge(self.resolve_urls(&tenant.slug, url_path)).await;
306    }
307
308    async fn invalidate_urls(&self, tenant: &rustango::tenancy::TenantSlug, url_paths: &[String]) {
309        // #428 — batch every (path × host) into one `files` array
310        // (chunked by `purge`) instead of one POST per path. A save
311        // that touches a page + its descendants now costs a single
312        // round-trip on the common case (≤30 URLs).
313        let urls: Vec<String> = url_paths
314            .iter()
315            .flat_map(|p| self.resolve_urls(&tenant.slug, p))
316            .collect();
317        self.purge(urls).await;
318    }
319}
320
321#[cfg(test)]
322mod tests {
323    use super::*;
324    use httpmock::Method::POST;
325    use httpmock::MockServer;
326
327    /// Pure-Rust check — the `resolve_urls` build is exercised by
328    /// the live tests below but a sync check keeps the URL-shape
329    /// regression guard cheap.
330    #[test]
331    fn resolve_urls_uses_default_host_when_no_per_tenant() {
332        let inv = CloudflareInvalidator::new("z", "t").with_origin_host("example.com");
333        let urls = inv.resolve_urls("acme", "/about");
334        assert_eq!(urls, vec!["https://example.com/about"]);
335    }
336
337    #[test]
338    fn resolve_urls_per_tenant_overrides_default() {
339        let inv = CloudflareInvalidator::new("z", "t")
340            .with_origin_host("fallback.example.com")
341            .with_tenant_host("acme", "acme.example.com")
342            .with_tenant_host("acme", "acme.com");
343        let urls = inv.resolve_urls("acme", "/pricing");
344        assert!(urls.contains(&"https://acme.example.com/pricing".to_owned()));
345        assert!(urls.contains(&"https://acme.com/pricing".to_owned()));
346        assert!(
347            !urls.contains(&"https://fallback.example.com/pricing".to_owned()),
348            "fallback shouldn't fire when tenant has its own host: {urls:?}"
349        );
350    }
351
352    #[test]
353    fn resolve_urls_no_host_no_urls() {
354        // No default host + no per-tenant registration → empty
355        // list. The purge fn short-circuits before sending.
356        let inv = CloudflareInvalidator::new("z", "t");
357        assert!(inv.resolve_urls("acme", "/about").is_empty());
358    }
359
360    #[test]
361    fn resolve_urls_custom_scheme() {
362        let inv = CloudflareInvalidator::new("z", "t")
363            .with_origin_host("example.com")
364            .with_scheme("http");
365        let urls = inv.resolve_urls("acme", "/about");
366        assert_eq!(urls, vec!["http://example.com/about"]);
367    }
368
369    #[tokio::test]
370    async fn purge_sends_correct_url_and_headers() {
371        let server = MockServer::start();
372        let mock = server.mock(|when, then| {
373            when.method(POST)
374                .path("/client/v4/zones/zone-xyz/purge_cache")
375                .header("authorization", "Bearer secret-token")
376                .header("content-type", "application/json")
377                .json_body_includes(r#"{"files": ["https://example.com/about"]}"#);
378            then.status(200).body(r#"{"success": true}"#);
379        });
380        let inv = CloudflareInvalidator::new("zone-xyz", "secret-token")
381            .with_origin_host("example.com")
382            .with_api_base(server.base_url());
383        inv.invalidate_url(&rustango::tenancy::TenantSlug::new(1, "acme"), "/about").await;
384        mock.assert();
385    }
386
387    #[tokio::test]
388    async fn non_2xx_response_doesnt_panic() {
389        let server = MockServer::start();
390        let _mock = server.mock(|when, then| {
391            when.method(POST);
392            then.status(403).body(
393                r#"{"success": false, "errors": [{"code": 1000, "message": "Invalid token"}]}"#,
394            );
395        });
396        let inv = CloudflareInvalidator::new("z", "bad-token")
397            .with_origin_host("example.com")
398            .with_api_base(server.base_url());
399        // Should swallow the error per the trait contract.
400        inv.invalidate_url(&rustango::tenancy::TenantSlug::new(1, "acme"), "/about").await;
401    }
402
403    #[tokio::test]
404    async fn no_host_no_request_fires() {
405        // Forgetting to register a host shouldn't 500 the admin —
406        // the empty URL list is short-circuited before the POST.
407        let server = MockServer::start();
408        let mock = server.mock(|when, then| {
409            when.method(POST);
410            then.status(200);
411        });
412        let inv = CloudflareInvalidator::new("z", "t").with_api_base(server.base_url());
413        inv.invalidate_url(&rustango::tenancy::TenantSlug::new(1, "acme"), "/about").await;
414        assert_eq!(mock.calls(), 0, "no host registered should mean no HTTP");
415    }
416
417    #[tokio::test]
418    async fn subtree_falls_back_to_url_purge() {
419        // Enterprise-only `prefixes` purge isn't shipped in v1 — the
420        // subtree variant should send the same exact-URL purge as
421        // the single-URL one.
422        let server = MockServer::start();
423        let mock = server.mock(|when, then| {
424            when.method(POST).path("/client/v4/zones/z/purge_cache");
425            then.status(200).body(r#"{"success": true}"#);
426        });
427        let inv = CloudflareInvalidator::new("z", "t")
428            .with_origin_host("example.com")
429            .with_api_base(server.base_url());
430        inv.invalidate_subtree(&rustango::tenancy::TenantSlug::new(1, "acme"), "/blog").await;
431        mock.assert();
432    }
433
434    #[tokio::test]
435    async fn invalidate_urls_batches_into_one_request() {
436        // #428 — three paths must collapse into ONE purge_cache POST
437        // carrying all three exact URLs, not three separate calls.
438        let server = MockServer::start();
439        let mock = server.mock(|when, then| {
440            when.method(POST)
441                .path("/client/v4/zones/z/purge_cache")
442                .json_body_includes(
443                    r#"{"files": ["https://example.com/a", "https://example.com/b", "https://example.com/c"]}"#,
444                );
445            then.status(200).body(r#"{"success": true}"#);
446        });
447        let inv = CloudflareInvalidator::new("z", "t")
448            .with_origin_host("example.com")
449            .with_api_base(server.base_url());
450        inv.invalidate_urls(&rustango::tenancy::TenantSlug::new(1, "acme"), &["/a".to_owned(), "/b".to_owned(), "/c".to_owned()])
451            .await;
452        assert_eq!(mock.calls(), 1, "three paths should batch into one POST");
453    }
454
455    #[tokio::test]
456    async fn invalidate_urls_chunks_over_thirty() {
457        // 31 URLs exceeds the 30-per-request cap → exactly two POSTs.
458        let server = MockServer::start();
459        let mock = server.mock(|when, then| {
460            when.method(POST).path("/client/v4/zones/z/purge_cache");
461            then.status(200).body(r#"{"success": true}"#);
462        });
463        let inv = CloudflareInvalidator::new("z", "t")
464            .with_origin_host("example.com")
465            .with_api_base(server.base_url());
466        let paths: Vec<String> = (0..31).map(|i| format!("/p{i}")).collect();
467        inv.invalidate_urls(&rustango::tenancy::TenantSlug::new(1, "acme"), &paths).await;
468        assert_eq!(mock.calls(), 2, "31 URLs should split into 30 + 1");
469    }
470
471    #[tokio::test]
472    async fn purge_tags_sends_tags_body() {
473        let server = MockServer::start();
474        let mock = server.mock(|when, then| {
475            when.method(POST)
476                .path("/client/v4/zones/z/purge_cache")
477                .header("authorization", "Bearer tok")
478                .json_body_includes(r#"{"tags": ["page-type:blog", "snippet:42"]}"#);
479            then.status(200).body(r#"{"success": true}"#);
480        });
481        let inv = CloudflareInvalidator::new("z", "tok").with_api_base(server.base_url());
482        inv.purge_tags(vec!["page-type:blog".to_owned(), "snippet:42".to_owned()])
483            .await;
484        mock.assert();
485    }
486
487    #[tokio::test]
488    async fn purge_prefixes_sends_prefixes_body() {
489        let server = MockServer::start();
490        let mock = server.mock(|when, then| {
491            when.method(POST)
492                .path("/client/v4/zones/z/purge_cache")
493                .json_body_includes(r#"{"prefixes": ["example.com/blog/"]}"#);
494            then.status(200).body(r#"{"success": true}"#);
495        });
496        let inv = CloudflareInvalidator::new("z", "t").with_api_base(server.base_url());
497        inv.purge_prefixes(vec!["example.com/blog/".to_owned()])
498            .await;
499        mock.assert();
500    }
501
502    #[tokio::test]
503    async fn empty_tag_and_prefix_purges_are_noops() {
504        let server = MockServer::start();
505        let mock = server.mock(|when, then| {
506            when.method(POST);
507            then.status(200);
508        });
509        let inv = CloudflareInvalidator::new("z", "t").with_api_base(server.base_url());
510        inv.purge_tags(vec![]).await;
511        inv.purge_prefixes(vec![]).await;
512        assert_eq!(mock.calls(), 0, "empty lists must not POST");
513    }
514}