rustango_cms/
cache_gcp.rs1use 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
57pub struct GoogleCloudCdnInvalidator {
60 project: String,
62 url_map: String,
65 token: Arc<dyn AccessTokenSource>,
67 tenant_hosts: HashMap<String, Vec<String>>,
72 default_host: Option<String>,
76 http: Arc<rustango::http_client::HttpClient>,
79 api_base: String,
82}
83
84impl GoogleCloudCdnInvalidator {
85 #[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 #[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 #[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 #[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 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 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_slug: &str, 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_slug: &str, url_path: &str) {
231 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("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 inv(server.base_url())
280 .invalidate_url("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("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("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("acme", "/about")
325 .await;
326 }
327
328 #[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("acme", "/about")
348 .await;
349 assert_eq!(mock.calls(), 0, "no token should mean no HTTP");
350 }
351}