Skip to main content

rustango_cms/
cache_gcp.rs

1//! Google Cloud CDN purge backend for
2//! [`crate::cache_invalidate::PageCacheInvalidator`].
3//!
4//! Wires the per-page cache-invalidation hook to Cloud CDN's
5//! [`urlMaps.invalidateCache`] Compute Engine API. After a CMS save
6//! the public URL is dropped from the Cloud CDN edge so the next
7//! request regenerates against the freshly-saved markup instead of
8//! waiting for the cache TTL.
9//!
10//! ## Usage
11//!
12//! Behind the `cache_gcp` feature. Cloud CDN authenticates against
13//! the Compute Engine management API with a short-lived OAuth2 bearer
14//! token, so the invalidator takes an [`AccessTokenSource`] (use
15//! [`StaticToken`](crate::cache_invalidate::StaticToken) for scripts/tests; implement the trait against the
16//! GCE metadata server for a long-running server):
17//!
18//! ```ignore
19//! use std::sync::Arc;
20//! use rustango_cms::cache_gcp::GoogleCloudCdnInvalidator;
21//! use rustango_cms::cache_invalidate::StaticToken;
22//!
23//! let inv = GoogleCloudCdnInvalidator::new(
24//!     "my-gcp-project",
25//!     "my-url-map",
26//!     Arc::new(StaticToken(std::env::var("GCP_ACCESS_TOKEN").unwrap())),
27//! )
28//! .with_origin_host("acme.example.com");
29//!
30//! let router = rustango_cms::admin::router_with_invalidator(
31//!     tera.clone(),
32//!     Arc::new(inv),
33//! );
34//! ```
35//!
36//! The token's principal needs `compute.urlMaps.invalidateCache` on
37//! the target URL map. Failures are logged through `tracing` at WARN;
38//! the calling admin handler doesn't propagate the error
39//! (cache-invalidation is best-effort by trait contract).
40//!
41//! Cloud CDN invalidation is **per-path** — one API call per `path`
42//! (optionally scoped to a `host`) — so there's no bulk endpoint to
43//! override; the default [`PageCacheInvalidator::invalidate_urls`]
44//! loop applies. Subtree purges use Cloud CDN's `/*` path glob.
45//!
46//! [`urlMaps.invalidateCache`]: https://cloud.google.com/compute/docs/reference/rest/v1/urlMaps/invalidateCache
47
48use std::collections::HashMap;
49use std::sync::Arc;
50use std::time::Duration;
51
52use async_trait::async_trait;
53use serde::Serialize;
54
55use crate::cache_invalidate::{AccessTokenSource, PageCacheInvalidator};
56
57/// Cloud CDN purge backend. Construct with [`Self::new`]; chain
58/// `.with_*` configuration before installing on the admin router.
59pub struct GoogleCloudCdnInvalidator {
60    /// GCP project id the URL map lives in.
61    project: String,
62    /// URL map fronting the backend the CMS is served from. Each
63    /// invalidation drops cached entries for this map.
64    url_map: String,
65    /// Supplies the OAuth2 bearer token for the Compute Engine API.
66    token: Arc<dyn AccessTokenSource>,
67    /// Tenant-slug → list of public hosts. Cloud CDN scopes an
68    /// invalidation to a `host` when given one, so the same path is
69    /// purged for every registered host. Most deploys map each tenant
70    /// to one host.
71    tenant_hosts: HashMap<String, Vec<String>>,
72    /// Default-when-no-tenant-mapping host. When neither a per-tenant
73    /// nor a default host is set, the invalidation is issued with no
74    /// `host` (drops the path across the whole URL map).
75    default_host: Option<String>,
76    /// Reuses [`rustango::http_client::HttpClient`] for the outbound
77    /// POST so we inherit framework-wide retry + timeout behaviour.
78    http: Arc<rustango::http_client::HttpClient>,
79    /// Override of the API base URL — production points at
80    /// `https://compute.googleapis.com`; tests point at httpmock.
81    api_base: String,
82}
83
84impl GoogleCloudCdnInvalidator {
85    /// Build a fresh invalidator. The HTTP client uses the framework's
86    /// default 10-second timeout + exponential-backoff retry policy.
87    ///
88    /// # Panics
89    /// If the framework HTTP client cannot be constructed (no TLS
90    /// backend, etc.) — a startup-time failure where crashing loudly
91    /// beats silently dropping every purge.
92    #[must_use]
93    pub fn new(
94        project: impl Into<String>,
95        url_map: impl Into<String>,
96        token: Arc<dyn AccessTokenSource>,
97    ) -> Self {
98        let http = rustango::http_client::HttpClient::builder()
99            .timeout(Duration::from_secs(10))
100            .build()
101            .expect("build http client for Google Cloud CDN invalidator");
102        Self {
103            project: project.into(),
104            url_map: url_map.into(),
105            token,
106            tenant_hosts: HashMap::new(),
107            default_host: None,
108            http: Arc::new(http),
109            api_base: "https://compute.googleapis.com".to_owned(),
110        }
111    }
112
113    /// Single-tenant convenience — every invalidation scopes to
114    /// `host` regardless of tenant slug.
115    #[must_use]
116    pub fn with_origin_host(mut self, host: impl Into<String>) -> Self {
117        self.default_host = Some(host.into());
118        self
119    }
120
121    /// Register an additional public host for `tenant_slug`. The same
122    /// path is purged once per registered host.
123    #[must_use]
124    pub fn with_tenant_host(
125        mut self,
126        tenant_slug: impl Into<String>,
127        host: impl Into<String>,
128    ) -> Self {
129        self.tenant_hosts
130            .entry(tenant_slug.into())
131            .or_default()
132            .push(host.into());
133        self
134    }
135
136    /// Override the API base URL. Used by tests to point at an
137    /// httpmock server; production keeps the default.
138    #[must_use]
139    pub fn with_api_base(mut self, api_base: impl Into<String>) -> Self {
140        self.api_base = api_base.into();
141        self
142    }
143
144    /// Hosts to scope an invalidation to for `tenant_slug`: the
145    /// per-tenant list, else the default (as a 1-elem list), else a
146    /// single `None` meaning "no host scope" (whole URL map).
147    fn hosts_for(&self, tenant_slug: &str) -> Vec<Option<&str>> {
148        if let Some(hosts) = self.tenant_hosts.get(tenant_slug) {
149            return hosts.iter().map(|h| Some(h.as_str())).collect();
150        }
151        match self.default_host.as_deref() {
152            Some(h) => vec![Some(h)],
153            None => vec![None],
154        }
155    }
156
157    /// POST one `invalidateCache` for `(path, host?)`. Best-effort:
158    /// logs at WARN + returns on any failure.
159    async fn invalidate(&self, path: &str, host: Option<&str>) {
160        let Some(token) = self.token.token().await else {
161            tracing::warn!(
162                target: "rustango_cms::cache_invalidate",
163                "gcp purge: no access token available — skipping"
164            );
165            return;
166        };
167        #[derive(Serialize)]
168        struct Body<'a> {
169            path: &'a str,
170            #[serde(skip_serializing_if = "Option::is_none")]
171            host: Option<&'a str>,
172        }
173        let url = format!(
174            "{}/compute/v1/projects/{}/global/urlMaps/{}/invalidateCache",
175            self.api_base, self.project, self.url_map
176        );
177        let req = self.http.post(url.as_str());
178        let req = match req.header("authorization", format!("Bearer {token}")) {
179            Ok(r) => r,
180            Err(e) => {
181                tracing::warn!(
182                    target: "rustango_cms::cache_invalidate",
183                    error = %e,
184                    "gcp purge: header build failed"
185                );
186                return;
187            }
188        };
189        let req = match req.json(&Body { path, host }) {
190            Ok(r) => r,
191            Err(e) => {
192                tracing::warn!(
193                    target: "rustango_cms::cache_invalidate",
194                    error = %e,
195                    "gcp purge: body serialise failed"
196                );
197                return;
198            }
199        };
200        match req.send().await {
201            Ok(resp) if resp.status().is_success() => {
202                tracing::debug!(
203                    target: "rustango_cms::cache_invalidate",
204                    status = %resp.status(), %path,
205                    "gcp purge ok"
206                );
207            }
208            Ok(resp) => tracing::warn!(
209                target: "rustango_cms::cache_invalidate",
210                status = %resp.status(), %path,
211                "gcp purge: non-2xx response"
212            ),
213            Err(e) => tracing::warn!(
214                target: "rustango_cms::cache_invalidate",
215                error = %e, %path,
216                "gcp purge: network failure"
217            ),
218        }
219    }
220}
221
222#[async_trait]
223impl PageCacheInvalidator for GoogleCloudCdnInvalidator {
224    async fn invalidate_url(&self, tenant: &rustango::tenancy::TenantSlug, url_path: &str) {
225        for host in self.hosts_for(&tenant.slug) {
226            self.invalidate(url_path, host).await;
227        }
228    }
229
230    async fn invalidate_subtree(&self, tenant: &rustango::tenancy::TenantSlug, url_path: &str) {
231        // Cloud CDN accepts a trailing `/*` glob on the path to drop
232        // the page + every descendant in one call.
233        let glob = format!("{}/*", url_path.trim_end_matches('/'));
234        for host in self.hosts_for(&tenant.slug) {
235            self.invalidate(&glob, host).await;
236        }
237    }
238}
239
240#[cfg(test)]
241mod tests {
242    use super::*;
243    use crate::cache_invalidate::StaticToken;
244    use httpmock::Method::POST;
245    use httpmock::MockServer;
246
247    fn inv(base: String) -> GoogleCloudCdnInvalidator {
248        GoogleCloudCdnInvalidator::new("proj", "umap", Arc::new(StaticToken("tok".to_owned())))
249            .with_api_base(base)
250    }
251
252    #[tokio::test]
253    async fn invalidate_url_posts_path_and_host() {
254        let server = MockServer::start();
255        let mock = server.mock(|when, then| {
256            when.method(POST)
257                .path("/compute/v1/projects/proj/global/urlMaps/umap/invalidateCache")
258                .header("authorization", "Bearer tok")
259                .json_body_includes(r#"{"path": "/about", "host": "example.com"}"#);
260            then.status(200).body(r#"{"status": "DONE"}"#);
261        });
262        inv(server.base_url())
263            .with_origin_host("example.com")
264            .invalidate_url(&rustango::tenancy::TenantSlug::new(1, "acme"), "/about")
265            .await;
266        mock.assert();
267    }
268
269    #[tokio::test]
270    async fn no_host_omits_host_field() {
271        let server = MockServer::start();
272        let mock = server.mock(|when, then| {
273            when.method(POST)
274                .path("/compute/v1/projects/proj/global/urlMaps/umap/invalidateCache")
275                .json_body_includes(r#"{"path": "/about"}"#);
276            then.status(200).body(r#"{"status": "DONE"}"#);
277        });
278        // No origin host registered → host field omitted entirely.
279        inv(server.base_url())
280            .invalidate_url(&rustango::tenancy::TenantSlug::new(1, "acme"), "/about")
281            .await;
282        mock.assert();
283    }
284
285    #[tokio::test]
286    async fn per_tenant_hosts_fan_out() {
287        let server = MockServer::start();
288        let mock = server.mock(|when, then| {
289            when.method(POST);
290            then.status(200).body(r#"{"status": "DONE"}"#);
291        });
292        inv(server.base_url())
293            .with_tenant_host("acme", "acme.example.com")
294            .with_tenant_host("acme", "acme.com")
295            .invalidate_url(&rustango::tenancy::TenantSlug::new(1, "acme"), "/pricing")
296            .await;
297        assert_eq!(mock.calls(), 2, "one invalidateCache per registered host");
298    }
299
300    #[tokio::test]
301    async fn subtree_appends_glob() {
302        let server = MockServer::start();
303        let mock = server.mock(|when, then| {
304            when.method(POST)
305                .json_body_includes(r#"{"path": "/blog/*"}"#);
306            then.status(200).body(r#"{"status": "DONE"}"#);
307        });
308        inv(server.base_url())
309            .with_origin_host("example.com")
310            .invalidate_subtree(&rustango::tenancy::TenantSlug::new(1, "acme"), "/blog")
311            .await;
312        mock.assert();
313    }
314
315    #[tokio::test]
316    async fn non_2xx_doesnt_panic() {
317        let server = MockServer::start();
318        let _mock = server.mock(|when, then| {
319            when.method(POST);
320            then.status(403).body(r#"{"error": {"code": 403}}"#);
321        });
322        inv(server.base_url())
323            .with_origin_host("example.com")
324            .invalidate_url(&rustango::tenancy::TenantSlug::new(1, "acme"), "/about")
325            .await;
326    }
327
328    /// A token source returning `None` (e.g. expired + refresh failed)
329    /// must skip the POST, not panic.
330    #[tokio::test]
331    async fn missing_token_skips_request() {
332        struct NoToken;
333        #[async_trait]
334        impl AccessTokenSource for NoToken {
335            async fn token(&self) -> Option<String> {
336                None
337            }
338        }
339        let server = MockServer::start();
340        let mock = server.mock(|when, then| {
341            when.method(POST);
342            then.status(200);
343        });
344        GoogleCloudCdnInvalidator::new("proj", "umap", Arc::new(NoToken))
345            .with_origin_host("example.com")
346            .with_api_base(server.base_url())
347            .invalidate_url(&rustango::tenancy::TenantSlug::new(1, "acme"), "/about")
348            .await;
349        assert_eq!(mock.calls(), 0, "no token should mean no HTTP");
350    }
351}