Skip to main content

rustango_cms/
cache_azure.rs

1//! Azure CDN purge backend for
2//! [`crate::cache_invalidate::PageCacheInvalidator`].
3//!
4//! Wires the per-page cache-invalidation hook to the Azure CDN
5//! [endpoints purge] management API. After a CMS save the public URL
6//! is dropped from the Azure edge so the next request regenerates
7//! against the freshly-saved markup instead of waiting for the TTL.
8//!
9//! ## Usage
10//!
11//! Behind the `cache_azure` feature. The Azure Resource Manager API
12//! authenticates with a short-lived Azure AD bearer token, so the
13//! invalidator takes an [`AccessTokenSource`] (use [`StaticToken`](crate::cache_invalidate::StaticToken)
14//! for scripts/tests; implement the trait against your managed-identity
15//! / `az account get-access-token` endpoint for a long-running server):
16//!
17//! ```ignore
18//! use std::sync::Arc;
19//! use rustango_cms::cache_azure::AzureCdnInvalidator;
20//! use rustango_cms::cache_invalidate::StaticToken;
21//!
22//! let inv = AzureCdnInvalidator::new(
23//!     "00000000-0000-0000-0000-000000000000", // subscription id
24//!     "my-rg",                                  // resource group
25//!     "my-cdn-profile",                         // profile
26//!     "my-endpoint",                            // endpoint
27//!     Arc::new(StaticToken(std::env::var("AZURE_ACCESS_TOKEN").unwrap())),
28//! );
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 `Microsoft.Cdn/profiles/endpoints/purge/action`
37//! on the endpoint. Failures are logged through `tracing` at WARN; the
38//! calling admin handler doesn't propagate the error
39//! (cache-invalidation is best-effort by trait contract).
40//!
41//! Azure's purge takes a `contentPaths` array, so a multi-URL save is
42//! collapsed into a single request via the
43//! [`PageCacheInvalidator::invalidate_urls`] override. Purges are
44//! path-based (no per-host scope). Subtree purges use Azure's `/*`
45//! path glob.
46//!
47//! [endpoints purge]: https://learn.microsoft.com/rest/api/cdn/endpoints/purge-content
48
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/// Azure CDN purge backend. Construct with [`Self::new`]; chain
58/// `.with_*` configuration before installing on the admin router.
59pub struct AzureCdnInvalidator {
60    subscription_id: String,
61    resource_group: String,
62    profile: String,
63    endpoint: String,
64    /// Supplies the OAuth2 bearer token for the ARM API.
65    token: Arc<dyn AccessTokenSource>,
66    /// Reuses [`rustango::http_client::HttpClient`] for the outbound
67    /// POST so we inherit framework-wide retry + timeout behaviour.
68    http: Arc<rustango::http_client::HttpClient>,
69    /// Override of the API base URL — production points at
70    /// `https://management.azure.com`; tests point at httpmock.
71    api_base: String,
72    /// ARM API version query param.
73    api_version: String,
74}
75
76impl AzureCdnInvalidator {
77    /// Max `contentPaths` per purge request. Azure accepts large
78    /// batches, but we chunk to stay well within request-size limits
79    /// on a big subtree purge.
80    const MAX_PATHS_PER_REQUEST: usize = 50;
81
82    /// Build a fresh invalidator. The HTTP client uses the framework's
83    /// default 10-second timeout + exponential-backoff retry policy.
84    ///
85    /// # Panics
86    /// If the framework HTTP client cannot be constructed (no TLS
87    /// backend, etc.) — a startup-time failure where crashing loudly
88    /// beats silently dropping every purge.
89    #[must_use]
90    pub fn new(
91        subscription_id: impl Into<String>,
92        resource_group: impl Into<String>,
93        profile: impl Into<String>,
94        endpoint: impl Into<String>,
95        token: Arc<dyn AccessTokenSource>,
96    ) -> Self {
97        let http = rustango::http_client::HttpClient::builder()
98            .timeout(Duration::from_secs(10))
99            .build()
100            .expect("build http client for Azure CDN invalidator");
101        Self {
102            subscription_id: subscription_id.into(),
103            resource_group: resource_group.into(),
104            profile: profile.into(),
105            endpoint: endpoint.into(),
106            token,
107            http: Arc::new(http),
108            api_base: "https://management.azure.com".to_owned(),
109            api_version: "2023-05-01".to_owned(),
110        }
111    }
112
113    /// Override the API base URL. Used by tests to point at an
114    /// httpmock server; production keeps the default.
115    #[must_use]
116    pub fn with_api_base(mut self, api_base: impl Into<String>) -> Self {
117        self.api_base = api_base.into();
118        self
119    }
120
121    /// Override the ARM API version (default `2023-05-01`).
122    #[must_use]
123    pub fn with_api_version(mut self, api_version: impl Into<String>) -> Self {
124        self.api_version = api_version.into();
125        self
126    }
127
128    fn purge_url(&self) -> String {
129        format!(
130            "{base}/subscriptions/{sub}/resourceGroups/{rg}/providers/Microsoft.Cdn/profiles/{profile}/endpoints/{endpoint}/purge?api-version={ver}",
131            base = self.api_base,
132            sub = self.subscription_id,
133            rg = self.resource_group,
134            profile = self.profile,
135            endpoint = self.endpoint,
136            ver = self.api_version,
137        )
138    }
139
140    /// POST one `purge` with the given `contentPaths`. Best-effort:
141    /// logs at WARN + returns on any failure.
142    async fn purge(&self, content_paths: &[String]) {
143        if content_paths.is_empty() {
144            return;
145        }
146        let Some(token) = self.token.token().await else {
147            tracing::warn!(
148                target: "rustango_cms::cache_invalidate",
149                "azure purge: no access token available — skipping"
150            );
151            return;
152        };
153        #[derive(Serialize)]
154        #[serde(rename_all = "camelCase")]
155        struct Body<'a> {
156            content_paths: &'a [String],
157        }
158        let url = self.purge_url();
159        for chunk in content_paths.chunks(Self::MAX_PATHS_PER_REQUEST) {
160            let req = self.http.post(url.as_str());
161            let req = match req.header("authorization", format!("Bearer {token}")) {
162                Ok(r) => r,
163                Err(e) => {
164                    tracing::warn!(
165                        target: "rustango_cms::cache_invalidate",
166                        error = %e,
167                        "azure purge: header build failed"
168                    );
169                    return;
170                }
171            };
172            let req = match req.json(&Body {
173                content_paths: chunk,
174            }) {
175                Ok(r) => r,
176                Err(e) => {
177                    tracing::warn!(
178                        target: "rustango_cms::cache_invalidate",
179                        error = %e,
180                        "azure purge: body serialise failed"
181                    );
182                    return;
183                }
184            };
185            match req.send().await {
186                // Azure returns 200 (done) or 202 (accepted, async).
187                Ok(resp) if resp.status().is_success() => tracing::debug!(
188                    target: "rustango_cms::cache_invalidate",
189                    status = %resp.status(),
190                    "azure purge ok"
191                ),
192                Ok(resp) => tracing::warn!(
193                    target: "rustango_cms::cache_invalidate",
194                    status = %resp.status(),
195                    "azure purge: non-2xx response"
196                ),
197                Err(e) => tracing::warn!(
198                    target: "rustango_cms::cache_invalidate",
199                    error = %e,
200                    "azure purge: network failure"
201                ),
202            }
203        }
204    }
205}
206
207#[async_trait]
208impl PageCacheInvalidator for AzureCdnInvalidator {
209    async fn invalidate_url(&self, _tenant: &rustango::tenancy::TenantSlug, url_path: &str) {
210        self.purge(&[url_path.to_owned()]).await;
211    }
212
213    async fn invalidate_subtree(&self, _tenant: &rustango::tenancy::TenantSlug, url_path: &str) {
214        // Azure accepts a trailing `/*` glob to drop the page + every
215        // descendant in one call.
216        let glob = format!("{}/*", url_path.trim_end_matches('/'));
217        self.purge(&[glob]).await;
218    }
219
220    async fn invalidate_urls(&self, _tenant: &rustango::tenancy::TenantSlug, url_paths: &[String]) {
221        // #428 — one purge carrying every path's contentPaths (chunked
222        // by `purge`) instead of one request per path.
223        self.purge(url_paths).await;
224    }
225}
226
227#[cfg(test)]
228mod tests {
229    use super::*;
230    use crate::cache_invalidate::StaticToken;
231    use httpmock::Method::POST;
232    use httpmock::MockServer;
233
234    fn inv(base: String) -> AzureCdnInvalidator {
235        AzureCdnInvalidator::new(
236            "sub-1",
237            "rg-1",
238            "profile-1",
239            "endpoint-1",
240            Arc::new(StaticToken("tok".to_owned())),
241        )
242        .with_api_base(base)
243    }
244
245    #[tokio::test]
246    async fn invalidate_url_posts_content_paths() {
247        let server = MockServer::start();
248        let mock = server.mock(|when, then| {
249            when.method(POST)
250                .path("/subscriptions/sub-1/resourceGroups/rg-1/providers/Microsoft.Cdn/profiles/profile-1/endpoints/endpoint-1/purge")
251                .query_param("api-version", "2023-05-01")
252                .header("authorization", "Bearer tok")
253                .json_body_includes(r#"{"contentPaths": ["/about"]}"#);
254            then.status(200);
255        });
256        inv(server.base_url())
257            .invalidate_url(&rustango::tenancy::TenantSlug::new(1, "acme"), "/about")
258            .await;
259        mock.assert();
260    }
261
262    #[tokio::test]
263    async fn invalidate_urls_batches_into_one_request() {
264        // #428 — three paths must collapse into ONE purge POST.
265        let server = MockServer::start();
266        let mock = server.mock(|when, then| {
267            when.method(POST)
268                .json_body_includes(r#"{"contentPaths": ["/a", "/b", "/c"]}"#);
269            then.status(202);
270        });
271        inv(server.base_url())
272            .invalidate_urls(&rustango::tenancy::TenantSlug::new(1, "acme"), &["/a".to_owned(), "/b".to_owned(), "/c".to_owned()])
273            .await;
274        assert_eq!(mock.calls(), 1, "three paths should batch into one POST");
275    }
276
277    #[tokio::test]
278    async fn subtree_appends_glob() {
279        let server = MockServer::start();
280        let mock = server.mock(|when, then| {
281            when.method(POST)
282                .json_body_includes(r#"{"contentPaths": ["/blog/*"]}"#);
283            then.status(200);
284        });
285        inv(server.base_url())
286            .invalidate_subtree(&rustango::tenancy::TenantSlug::new(1, "acme"), "/blog")
287            .await;
288        mock.assert();
289    }
290
291    #[tokio::test]
292    async fn batches_chunk_over_limit() {
293        // 51 paths exceeds the 50-per-request cap → exactly two POSTs.
294        let server = MockServer::start();
295        let mock = server.mock(|when, then| {
296            when.method(POST);
297            then.status(200);
298        });
299        let paths: Vec<String> = (0..51).map(|i| format!("/p{i}")).collect();
300        inv(server.base_url()).invalidate_urls(&rustango::tenancy::TenantSlug::new(1, "acme"), &paths).await;
301        assert_eq!(mock.calls(), 2, "51 paths should split into 50 + 1");
302    }
303
304    #[tokio::test]
305    async fn non_2xx_doesnt_panic() {
306        let server = MockServer::start();
307        let _mock = server.mock(|when, then| {
308            when.method(POST);
309            then.status(401)
310                .body(r#"{"error": {"code": "AuthenticationFailed"}}"#);
311        });
312        inv(server.base_url())
313            .invalidate_url(&rustango::tenancy::TenantSlug::new(1, "acme"), "/about")
314            .await;
315    }
316
317    #[tokio::test]
318    async fn missing_token_skips_request() {
319        struct NoToken;
320        #[async_trait]
321        impl AccessTokenSource for NoToken {
322            async fn token(&self) -> Option<String> {
323                None
324            }
325        }
326        let server = MockServer::start();
327        let mock = server.mock(|when, then| {
328            when.method(POST);
329            then.status(200);
330        });
331        AzureCdnInvalidator::new("s", "r", "p", "e", Arc::new(NoToken))
332            .with_api_base(server.base_url())
333            .invalidate_url(&rustango::tenancy::TenantSlug::new(1, "acme"), "/about")
334            .await;
335        assert_eq!(mock.calls(), 0, "no token should mean no HTTP");
336    }
337}