1use 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
45pub struct CloudflareInvalidator {
56 zone_id: String,
59 api_token: String,
61 tenant_hosts: HashMap<String, Vec<String>>,
65 default_host: Option<String>,
68 scheme: String,
72 http: Arc<rustango::http_client::HttpClient>,
76 api_base: String,
80}
81
82impl CloudflareInvalidator {
83 #[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 #[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 #[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 #[must_use]
138 pub fn with_scheme(mut self, scheme: impl Into<String>) -> Self {
139 self.scheme = scheme.into();
140 self
141 }
142
143 #[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 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 const MAX_FILES_PER_REQUEST: usize = 30;
179
180 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 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 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 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 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 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 #[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 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 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 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 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 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 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}