Skip to main content

kellnr_storage/
gcs_storage.rs

1use std::time::Duration;
2
3use async_trait::async_trait;
4use bytes::Bytes;
5use futures_util::StreamExt;
6use kellnr_settings::Settings;
7use object_store::gcp::{GoogleCloudStorage, GoogleCloudStorageBuilder};
8use object_store::path::Path;
9use object_store::{ClientOptions, ObjectStore, ObjectStoreExt, PutMode};
10
11use crate::storage::{ObjectWithMeta, Storage};
12use crate::storage_error::StorageError;
13
14pub struct GCSStorage(GoogleCloudStorage);
15
16#[async_trait]
17impl Storage for GCSStorage {
18    async fn get(&self, key: &str) -> Result<Bytes, StorageError> {
19        self.storage()
20            .get(&Self::try_path_from(key)?)
21            .await?
22            .bytes()
23            .await
24            .map_err(StorageError::from)
25    }
26
27    async fn get_with_meta(&self, key: &str) -> Result<ObjectWithMeta, StorageError> {
28        let result = self.storage().get(&Self::try_path_from(key)?).await?;
29        let e_tag = result.meta.e_tag.clone();
30        let last_modified = result.meta.last_modified;
31        let bytes = result.bytes().await?;
32        Ok(ObjectWithMeta {
33            bytes,
34            e_tag,
35            last_modified,
36        })
37    }
38
39    async fn put(&self, key: &str, object: Bytes) -> Result<(), StorageError> {
40        self.storage()
41            .put_opts(
42                &Self::try_path_from(key)?,
43                object.into(),
44                PutMode::Create.into(),
45            )
46            .await?;
47        Ok(())
48    }
49
50    async fn put_overwrite(&self, key: &str, object: Bytes) -> Result<(), StorageError> {
51        self.storage()
52            .put_opts(
53                &Self::try_path_from(key)?,
54                object.into(),
55                PutMode::Overwrite.into(),
56            )
57            .await?;
58        Ok(())
59    }
60
61    async fn delete(&self, key: &str) -> Result<(), StorageError> {
62        let path = Self::try_path_from(key)?;
63        self.storage().delete(&path).await?;
64        Ok(())
65    }
66
67    async fn exists(&self, key: &str) -> Result<bool, StorageError> {
68        let path = Self::try_path_from(key)?;
69        self.storage()
70            .head(&path)
71            .await
72            .map(|_| true)
73            .or_else(|e| match e {
74                object_store::Error::NotFound { .. } => Ok(false),
75                _ => Err(StorageError::from(e)),
76            })
77    }
78
79    async fn list(&self, prefix: &str) -> Result<Vec<String>, StorageError> {
80        let prefix = if prefix.is_empty() {
81            None
82        } else {
83            Some(Self::try_path_from(prefix)?)
84        };
85        let mut stream = self.storage().list(prefix.as_ref());
86        let mut keys = Vec::new();
87        while let Some(meta) = stream.next().await {
88            keys.push(meta?.location.to_string());
89        }
90        Ok(keys)
91    }
92}
93
94impl GCSStorage {
95    fn try_path_from(key: &str) -> Result<Path, object_store::path::Error> {
96        Path::from_url_path(key)
97    }
98
99    fn storage(&self) -> &GoogleCloudStorage {
100        &self.0
101    }
102}
103
104impl TryFrom<(&str, &Settings)> for GCSStorage {
105    type Error = StorageError;
106
107    fn try_from((bucket, settings): (&str, &Settings)) -> Result<Self, Self::Error> {
108        // NOTE: `with_client_options` replaces the builder's internal ClientOptions entirely
109        // (see the same note in `s3_storage.rs`). `GoogleCloudStorageBuilder::default()`
110        // sets `allow_http(true)`, so overriding it here without carrying the setting over
111        // would make any `http://` endpoint override (e.g. fake-gcs-server in tests) fail
112        // instantly with a client-side "builder error" (reqwest's scheme check), before any
113        // request is even sent.
114        let client_options = ClientOptions::new()
115            .with_connect_timeout(Duration::from_secs(settings.gcs.connect_timeout_seconds))
116            .with_timeout(Duration::from_secs(settings.gcs.request_timeout_seconds))
117            .with_allow_http(settings.gcs.allow_http);
118
119        let mut gcs = if settings.gcs.skip_signature {
120            // Unauthenticated target (e.g. fake-gcs-server in tests). `from_env()` would
121            // still perform real Application Default Credentials discovery (gcloud ADC file
122            // / metadata server) inside `build()`, and `with_skip_signature` alone doesn't
123            // skip the OAuth2 token fetch on the PUT path (object_store 0.14's PUT request
124            // path doesn't consult `skip_signature`, only GET/DELETE/HEAD do). A
125            // `disable_oauth` service account key makes every credential provider return a
126            // static empty bearer token with no network calls at all, which is what
127            // object_store's own test suite uses against fake-gcs-server.
128            const FAKE_SERVICE_ACCOUNT_KEY: &str = r#"{"private_key":"unused","private_key_id":"unused","client_email":"unused@example.com","disable_oauth":true}"#;
129            GoogleCloudStorageBuilder::new()
130                .with_service_account_key(FAKE_SERVICE_ACCOUNT_KEY)
131                .with_skip_signature(true)
132        } else {
133            GoogleCloudStorageBuilder::from_env()
134        };
135        if let Some(endpoint) = &settings.gcs.endpoint {
136            gcs = gcs.with_base_url(endpoint);
137        }
138        let gcs = gcs
139            .with_bucket_name(bucket)
140            .with_client_options(client_options);
141        Ok(Self(gcs.build()?))
142    }
143}