arche 4.11.0

An opinionated backend foundation for Axum applications, providing batteries-included integrations for cloud services, databases, authentication, middleware, and logging.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
use percent_encoding::{AsciiSet, NON_ALPHANUMERIC, utf8_percent_encode};
use serde::{Deserialize, Serialize};
use serde_json::json;

use crate::config::{resolve_optional_string, resolve_required_string};
use crate::error::AppError;
use crate::gcp::client::GcpClient;
use crate::gcp::token::ServiceAccountKey;

pub use crate::config::gcp::{GcpCdnConfig, GcpCdnConfigBuilder};

pub const CDN_SCOPE: &str = "https://www.googleapis.com/auth/compute";
const DEFAULT_COMPUTE_BASE_URL: &str = "https://compute.googleapis.com";

const PATH_SEGMENT: &AsciiSet = &NON_ALPHANUMERIC
    .remove(b'-')
    .remove(b'.')
    .remove(b'_')
    .remove(b'~');

pub async fn get_cdn_client(
    sa_key: Option<ServiceAccountKey>,
    sa_path: Option<String>,
    config: impl Into<Option<GcpCdnConfig>>,
) -> Result<GcpCdnClient, AppError> {
    let resolved = resolve_cdn_config(config.into().unwrap_or_default())?;
    let gcp = GcpClient::new(sa_key, sa_path, [CDN_SCOPE]).await?;
    Ok(GcpCdnClient::new(
        gcp,
        resolved.project_id,
        resolved.default_url_map,
        resolved.base_url,
    ))
}

#[derive(Debug)]
struct ResolvedCdnConfig {
    project_id: String,
    default_url_map: Option<String>,
    base_url: Option<String>,
}

fn resolve_cdn_config(config: GcpCdnConfig) -> Result<ResolvedCdnConfig, AppError> {
    Ok(ResolvedCdnConfig {
        project_id: resolve_required_string(config.project_id, "GCP_CDN_PROJECT_ID", "project_id")?,
        default_url_map: resolve_optional_string(config.url_map, "GCP_CDN_URL_MAP"),
        base_url: resolve_optional_string(config.compute_base_url, "GCP_CDN_BASE_URL"),
    })
}

#[derive(Debug, Clone, Serialize)]
pub struct InvalidationOperation {
    pub id: String,
    /// Operation name — pass this to `invalidation_status` to poll progress.
    pub name: String,
    /// Operation status: `PENDING`, `RUNNING`, or `DONE`.
    pub status: String,
    /// Best-effort progress, 0..=100.
    pub progress: Option<i32>,
    pub start_time: Option<String>,
    pub end_time: Option<String>,
    /// Joined error messages if the operation reported failures.
    pub error: Option<String>,
}

#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
struct OperationWire {
    #[serde(default)]
    id: Option<String>,
    #[serde(default)]
    name: Option<String>,
    #[serde(default)]
    status: Option<String>,
    #[serde(default)]
    progress: Option<i32>,
    #[serde(default)]
    start_time: Option<String>,
    #[serde(default)]
    end_time: Option<String>,
    #[serde(default)]
    error: Option<OperationErrorBlock>,
}

#[derive(Deserialize)]
struct OperationErrorBlock {
    #[serde(default)]
    errors: Vec<OperationErrorItem>,
}

#[derive(Deserialize)]
struct OperationErrorItem {
    #[serde(default)]
    code: Option<String>,
    #[serde(default)]
    message: Option<String>,
}

impl From<OperationWire> for InvalidationOperation {
    fn from(w: OperationWire) -> Self {
        let error = w.error.and_then(|e| {
            let parts: Vec<String> = e
                .errors
                .into_iter()
                .filter_map(|item| match (item.code, item.message) {
                    (Some(c), Some(m)) => Some(format!("{c}: {m}")),
                    (Some(c), None) => Some(c),
                    (None, Some(m)) => Some(m),
                    (None, None) => None,
                })
                .collect();
            if parts.is_empty() {
                None
            } else {
                Some(parts.join("; "))
            }
        });
        Self {
            id: w.id.unwrap_or_default(),
            name: w.name.unwrap_or_default(),
            status: w.status.unwrap_or_default(),
            progress: w.progress,
            start_time: w.start_time,
            end_time: w.end_time,
            error,
        }
    }
}

#[derive(Debug, Deserialize)]
struct CdnErrorEnvelope {
    error: CdnErrorBody,
}

#[derive(Debug, Deserialize)]
struct CdnErrorBody {
    #[serde(default)]
    status: Option<String>,
    #[serde(default)]
    message: Option<String>,
}

/// Cloud CDN invalidation client.
///
/// Currently scoped to **global** URL maps and global operations. Regional
/// URL maps (`/regions/{region}/urlMaps/...`) are not supported by this client;
/// invalidation against one will return a 404.
#[derive(Clone)]
pub struct GcpCdnClient {
    gcp: GcpClient,
    project_id: String,
    default_url_map: Option<String>,
    base_url: String,
}

impl GcpCdnClient {
    pub fn new(
        gcp: GcpClient,
        project_id: String,
        default_url_map: Option<String>,
        base_url: Option<String>,
    ) -> Self {
        let base_url = base_url
            .unwrap_or_else(|| DEFAULT_COMPUTE_BASE_URL.to_string())
            .trim_end_matches('/')
            .to_string();
        Self {
            gcp,
            project_id,
            default_url_map,
            base_url,
        }
    }

    fn resolve_url_map(&self, url_map: Option<&str>, op: &str) -> Result<String, AppError> {
        url_map
            .map(|s| s.to_string())
            .or_else(|| self.default_url_map.clone())
            .ok_or_else(|| {
                AppError::bad_request(
                    None,
                    Some(format!(
                        "Cloud CDN {op}: url_map not provided and no default configured"
                    )),
                    None,
                )
            })
    }

    /// Invalidate cached content for `path` on the URL map.
    ///
    /// `path` must start with `/` and may use `*` as a suffix wildcard
    /// (e.g. `/static/*`). Pass `host` to scope the invalidation to a single
    /// hostname routed by the URL map.
    ///
    /// Returns the operation; poll its `name` with `invalidation_status` to
    /// follow progress until `status == "DONE"`.
    pub async fn invalidate(
        &self,
        url_map: Option<&str>,
        path: &str,
        host: Option<&str>,
    ) -> Result<InvalidationOperation, AppError> {
        let url_map = self.resolve_url_map(url_map, "invalidate")?;

        if path.is_empty() {
            return Err(AppError::bad_request(
                None,
                Some("Cloud CDN invalidate: path must not be empty".to_string()),
                None,
            ));
        }

        let url = format!(
            "{}/compute/v1/projects/{}/global/urlMaps/{}/invalidateCache",
            self.base_url,
            utf8_percent_encode(&self.project_id, PATH_SEGMENT),
            utf8_percent_encode(&url_map, PATH_SEGMENT),
        );

        let mut body = json!({ "path": path });
        if let Some(h) = host {
            body["host"] = json!(h);
        }

        let resp = self
            .gcp
            .post(&url)
            .await?
            .json(&body)
            .send()
            .await
            .map_err(|e| {
                AppError::dependency_failed("gcp-cdn", format!("invalidate request failed: {e}"))
            })?;

        let wire: OperationWire = handle_response(resp, "invalidate").await?;
        Ok(wire.into())
    }

    /// Poll an invalidation operation by `name` (the value returned in
    /// `InvalidationOperation::name` from `invalidate`).
    pub async fn invalidation_status(
        &self,
        operation_name: &str,
    ) -> Result<InvalidationOperation, AppError> {
        if operation_name.is_empty() {
            return Err(AppError::bad_request(
                None,
                Some("Cloud CDN invalidation_status: operation_name must not be empty".to_string()),
                None,
            ));
        }

        let url = format!(
            "{}/compute/v1/projects/{}/global/operations/{}",
            self.base_url,
            utf8_percent_encode(&self.project_id, PATH_SEGMENT),
            utf8_percent_encode(operation_name, PATH_SEGMENT),
        );

        let resp = self.gcp.get(&url).await?.send().await.map_err(|e| {
            AppError::dependency_failed(
                "gcp-cdn",
                format!("invalidation_status request failed: {e}"),
            )
        })?;

        let wire: OperationWire = handle_response(resp, "invalidation_status").await?;
        Ok(wire.into())
    }
}

async fn handle_response<T: for<'de> Deserialize<'de>>(
    resp: reqwest::Response,
    op: &str,
) -> Result<T, AppError> {
    let status = resp.status();
    let bytes = resp.bytes().await.map_err(|e| {
        AppError::dependency_failed("gcp-cdn", format!("failed reading {op} response body: {e}"))
    })?;

    if !status.is_success() {
        return Err(AppError::dependency_failed(
            "gcp-cdn",
            format!("{op} returned HTTP {status}: {}", parse_cdn_error(&bytes)),
        ));
    }

    serde_json::from_slice::<T>(&bytes).map_err(|e| {
        AppError::dependency_failed("gcp-cdn", format!("failed to parse {op} response: {e}"))
    })
}

fn parse_cdn_error(body: &[u8]) -> String {
    serde_json::from_slice::<CdnErrorEnvelope>(body)
        .ok()
        .map(|env| match (env.error.status, env.error.message) {
            (Some(s), Some(m)) => format!("{s}: {m}"),
            (Some(s), None) => s,
            (None, Some(m)) => m,
            (None, None) => String::new(),
        })
        .filter(|s| !s.is_empty())
        .unwrap_or_else(|| String::from_utf8_lossy(body).into_owned())
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::sync::{LazyLock, Mutex, MutexGuard};

    static ENV_LOCK: LazyLock<Mutex<()>> = LazyLock::new(|| Mutex::new(()));

    fn env_guard() -> MutexGuard<'static, ()> {
        ENV_LOCK.lock().unwrap_or_else(|p| p.into_inner())
    }

    const ENV_VARS: &[&str] = &["GCP_CDN_PROJECT_ID", "GCP_CDN_URL_MAP", "GCP_CDN_BASE_URL"];

    fn clear_cdn_env() {
        for k in ENV_VARS {
            unsafe { std::env::remove_var(k) };
        }
    }

    #[test]
    fn resolve_cdn_config_errors_when_project_id_missing() {
        let _g = env_guard();
        clear_cdn_env();
        let err = resolve_cdn_config(GcpCdnConfig::default()).unwrap_err();
        assert!(
            format!("{err:?}").contains("project_id"),
            "expected project_id in error, got: {err:?}"
        );
    }

    #[test]
    fn resolve_cdn_config_reads_from_env_when_unset() {
        let _g = env_guard();
        clear_cdn_env();
        unsafe {
            std::env::set_var("GCP_CDN_PROJECT_ID", "from-env");
            std::env::set_var("GCP_CDN_URL_MAP", "env-map");
            std::env::set_var("GCP_CDN_BASE_URL", "https://env.test");
        }
        let resolved = resolve_cdn_config(GcpCdnConfig::default()).unwrap();
        clear_cdn_env();
        assert_eq!(resolved.project_id, "from-env");
        assert_eq!(resolved.default_url_map.as_deref(), Some("env-map"));
        assert_eq!(resolved.base_url.as_deref(), Some("https://env.test"));
    }

    #[test]
    fn resolve_cdn_config_explicit_overrides_env() {
        let _g = env_guard();
        clear_cdn_env();
        unsafe {
            std::env::set_var("GCP_CDN_PROJECT_ID", "from-env");
            std::env::set_var("GCP_CDN_URL_MAP", "env-map");
        }
        let resolved = resolve_cdn_config(
            GcpCdnConfig::builder()
                .project_id("explicit-proj")
                .url_map("explicit-map")
                .compute_base_url("https://explicit.test")
                .build(),
        )
        .unwrap();
        clear_cdn_env();
        assert_eq!(resolved.project_id, "explicit-proj");
        assert_eq!(resolved.default_url_map.as_deref(), Some("explicit-map"));
        assert_eq!(resolved.base_url.as_deref(), Some("https://explicit.test"));
    }

    #[test]
    fn parse_cdn_error_extracts_status_and_message() {
        let body = br#"{"error":{"code":403,"status":"PERMISSION_DENIED","message":"missing compute.urlMaps.invalidateCache"}}"#;
        assert_eq!(
            parse_cdn_error(body),
            "PERMISSION_DENIED: missing compute.urlMaps.invalidateCache"
        );
    }

    #[test]
    fn parse_cdn_error_falls_back_to_raw_body() {
        assert_eq!(parse_cdn_error(b"not json"), "not json");
    }

    #[test]
    fn operation_wire_to_invalidation_operation_joins_errors() {
        let wire: OperationWire = serde_json::from_str(
            r#"{
                "id": "5678",
                "name": "operation-xyz",
                "status": "DONE",
                "progress": 100,
                "startTime": "2024-01-01T00:00:00Z",
                "endTime": "2024-01-01T00:00:30Z",
                "error": {
                    "errors": [
                        {"code": "RESOURCE_NOT_FOUND", "message": "URL map missing"},
                        {"code": "QUOTA_EXCEEDED"}
                    ]
                }
            }"#,
        )
        .expect("parse");
        let op: InvalidationOperation = wire.into();
        assert_eq!(op.id, "5678");
        assert_eq!(op.name, "operation-xyz");
        assert_eq!(op.status, "DONE");
        assert_eq!(op.progress, Some(100));
        assert_eq!(
            op.error.as_deref(),
            Some("RESOURCE_NOT_FOUND: URL map missing; QUOTA_EXCEEDED")
        );
    }

    #[test]
    fn operation_wire_no_error_yields_none() {
        let wire: OperationWire =
            serde_json::from_str(r#"{"id":"1","name":"op","status":"PENDING"}"#).expect("parse");
        let op: InvalidationOperation = wire.into();
        assert!(op.error.is_none());
    }

    const TEST_PRIVATE_KEY: &str = "-----BEGIN PRIVATE KEY-----
MIIEvwIBADANBgkqhkiG9w0BAQEFAASCBKkwggSlAgEAAoIBAQCYyK/iTxWeNWSb
aS/yPPBIQ+jDbGyb8pt2ycklw7wEgaIdUvZgDeC57QENCg5lgs+g6OPRRsQY9fFG
lE6wKlZ4Zgq9kzRFjIAjXZkvD/H7bqlUdX0DlJXlYwMnGj2BR3DDbNQuRSlK4gWa
ZN5SYSVaBHsr3c89nN3GJH6IgikypsRc0mOEwbUdULs09ahSai7D7bSCCvCS5Jed
jAk10NqIMYMGjhlKpOWA+WcnHXpATSHtfampJq0s77bJej4MyQbGFims5XuuDmJ7
AF5rR4BndaRfaN323DLiKgR+UQKRMrhmBpyR35Yj/0pmo1XM713N4SLny1lq/oRH
9jAr2TPvAgMBAAECggEAL0w9iulhr2MnHKeBJNQxrKV9SvZnXxXJhAou36aLL7fz
+HEE/bJ+J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xHPR05r+guL
/ICg2hMWnxEem3Foq/KGLFjGYnE1I1gM/4CPOYtGkLcx1FfaE4Y7Cv3fonA5CcLL
/XuwcOxx4KaoCDZK4kU0/Lsw8A==
-----END PRIVATE KEY-----
";

    async fn test_client(default_url_map: Option<&str>) -> GcpCdnClient {
        let sa = ServiceAccountKey::new("test@example.iam.gserviceaccount.com", TEST_PRIVATE_KEY);
        let gcp = GcpClient::new(Some(sa), None, [CDN_SCOPE])
            .await
            .expect("test gcp client");
        GcpCdnClient::new(
            gcp,
            "p".to_string(),
            default_url_map.map(String::from),
            None,
        )
    }

    #[tokio::test]
    async fn resolve_url_map_uses_default_when_per_call_missing() {
        let client = test_client(Some("default-map")).await;
        let resolved = client.resolve_url_map(None, "invalidate").unwrap();
        assert_eq!(resolved, "default-map");
    }

    #[tokio::test]
    async fn resolve_url_map_prefers_per_call_value() {
        let client = test_client(Some("default-map")).await;
        let resolved = client
            .resolve_url_map(Some("override"), "invalidate")
            .unwrap();
        assert_eq!(resolved, "override");
    }

    #[tokio::test]
    async fn resolve_url_map_errors_when_no_default_or_per_call() {
        let client = test_client(None).await;
        let err = client.resolve_url_map(None, "invalidate").unwrap_err();
        assert!(format!("{err:?}").contains("url_map"));
    }

    #[tokio::test]
    async fn new_client_strips_trailing_slash_from_base_url() {
        let sa = ServiceAccountKey::new("test@example.iam.gserviceaccount.com", TEST_PRIVATE_KEY);
        let gcp = GcpClient::new(Some(sa), None, [CDN_SCOPE])
            .await
            .expect("test gcp client");
        let client = GcpCdnClient::new(
            gcp,
            "p".to_string(),
            None,
            Some("https://compute.googleapis.com/".to_string()),
        );
        assert_eq!(client.base_url, "https://compute.googleapis.com");
    }
}