1use std::sync::Arc;
50use std::time::Duration;
51
52use async_trait::async_trait;
53use serde::Serialize;
54
55use crate::cache_invalidate::{AccessTokenSource, PageCacheInvalidator};
56
57pub struct AzureCdnInvalidator {
60 subscription_id: String,
61 resource_group: String,
62 profile: String,
63 endpoint: String,
64 token: Arc<dyn AccessTokenSource>,
66 http: Arc<rustango::http_client::HttpClient>,
69 api_base: String,
72 api_version: String,
74}
75
76impl AzureCdnInvalidator {
77 const MAX_PATHS_PER_REQUEST: usize = 50;
81
82 #[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 #[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 #[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 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 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 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 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 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 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}