Skip to main content

opendal_service_gcs/
backend.rs

1// Licensed to the Apache Software Foundation (ASF) under one
2// or more contributor license agreements.  See the NOTICE file
3// distributed with this work for additional information
4// regarding copyright ownership.  The ASF licenses this file
5// to you under the Apache License, Version 2.0 (the
6// "License"); you may not use this file except in compliance
7// with the License.  You may obtain a copy of the License at
8//
9//   http://www.apache.org/licenses/LICENSE-2.0
10//
11// Unless required by applicable law or agreed to in writing,
12// software distributed under the License is distributed on an
13// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14// KIND, either express or implied.  See the License for the
15// specific language governing permissions and limitations
16// under the License.
17
18use std::fmt::Debug;
19use std::sync::Arc;
20
21use log::debug;
22use reqsign_core::Context;
23use reqsign_core::Env as _;
24use reqsign_core::OsEnv;
25use reqsign_core::ProvideCredential;
26use reqsign_core::ProvideCredentialChain;
27use reqsign_core::Signer;
28use reqsign_core::StaticEnv;
29use reqsign_file_read_tokio::TokioFileRead;
30use reqsign_google::Credential;
31use reqsign_google::DefaultCredentialProvider;
32use reqsign_google::FileCredentialProvider;
33use reqsign_google::RequestSigner;
34use reqsign_google::StaticCredentialProvider;
35use reqsign_google::TokenCredentialProvider;
36use reqsign_google::VmMetadataCredentialProvider;
37
38use super::GCS_SCHEME;
39use super::config::GcsConfig;
40use super::copier::GcsCopier;
41use super::core::constants::GCS_REWRITE_MAX_CHUNK_SIZE;
42use super::core::constants::GCS_REWRITE_MIN_CHUNK_SIZE;
43use super::core::parse_error;
44use super::core::*;
45use super::deleter::GcsDeleter;
46use super::lister::GcsLister;
47use super::reader::*;
48use super::writer::GcsWriter;
49use super::writer::GcsWriters;
50use opendal_core::raw::*;
51use opendal_core::*;
52
53const DEFAULT_GCS_ENDPOINT: &str = "https://storage.googleapis.com";
54const DEFAULT_GCS_SCOPE: &str = "https://www.googleapis.com/auth/devstorage.read_write";
55
56/// [Google Cloud Storage](https://cloud.google.com/storage) services support.
57#[doc = include_str!("docs.md")]
58#[derive(Default)]
59pub struct GcsBuilder {
60    pub(super) config: GcsConfig,
61    pub(super) credential_provider_chain: Option<ProvideCredentialChain<Credential>>,
62}
63
64impl Debug for GcsBuilder {
65    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
66        f.debug_struct("GcsBuilder")
67            .field("config", &self.config)
68            .finish_non_exhaustive()
69    }
70}
71
72impl GcsBuilder {
73    /// set the working directory root of backend
74    pub fn root(mut self, root: &str) -> Self {
75        self.config.root = if root.is_empty() {
76            None
77        } else {
78            Some(root.to_string())
79        };
80
81        self
82    }
83
84    /// set the container's name
85    pub fn bucket(mut self, bucket: &str) -> Self {
86        self.config.bucket = bucket.to_string();
87        self
88    }
89
90    /// set the GCS service scope
91    ///
92    /// If not set, we will use `https://www.googleapis.com/auth/devstorage.read_write`.
93    ///
94    /// # Valid scope examples
95    ///
96    /// - read-only: `https://www.googleapis.com/auth/devstorage.read_only`
97    /// - read-write: `https://www.googleapis.com/auth/devstorage.read_write`
98    /// - full-control: `https://www.googleapis.com/auth/devstorage.full_control`
99    ///
100    /// Reference: [Cloud Storage authentication](https://cloud.google.com/storage/docs/authentication)
101    pub fn scope(mut self, scope: &str) -> Self {
102        if !scope.is_empty() {
103            self.config.scope = Some(scope.to_string())
104        };
105        self
106    }
107
108    /// Set the GCS service account.
109    ///
110    /// service account will be used for fetch token from vm metadata.
111    /// If not set, we will try to fetch with `default` service account.
112    pub fn service_account(mut self, service_account: &str) -> Self {
113        if !service_account.is_empty() {
114            self.config.service_account = Some(service_account.to_string())
115        };
116        self
117    }
118
119    /// set the endpoint GCS service uses
120    pub fn endpoint(mut self, endpoint: &str) -> Self {
121        if !endpoint.is_empty() {
122            self.config.endpoint = Some(endpoint.to_string())
123        };
124        self
125    }
126
127    /// set the base64 hashed credentials string used for OAuth2 authentication.
128    ///
129    /// this method allows to specify the credentials directly as a base64 hashed string.
130    /// alternatively, you can use `credential_path()` to provide the local path to a credentials file.
131    /// we will use one of `credential` and `credential_path` to complete the OAuth2 authentication.
132    ///
133    /// Reference: [Google Cloud Storage Authentication](https://cloud.google.com/docs/authentication).
134    pub fn credential(mut self, credential: &str) -> Self {
135        if !credential.is_empty() {
136            self.config.credential = Some(credential.to_string())
137        };
138        self
139    }
140
141    /// set the local path to credentials file which is used for OAuth2 authentication.
142    ///
143    /// credentials file contains the original credentials that have not been base64 hashed.
144    /// we will use one of `credential` and `credential_path` to complete the OAuth2 authentication.
145    ///
146    /// Reference: [Google Cloud Storage Authentication](https://cloud.google.com/docs/authentication).
147    pub fn credential_path(mut self, path: &str) -> Self {
148        if !path.is_empty() {
149            self.config.credential_path = Some(path.to_string())
150        };
151        self
152    }
153
154    /// Specify a customized credential provider used by this service.
155    ///
156    /// This provider will be pushed to the front of credential chain.
157    pub fn credential_provider(
158        mut self,
159        provider: impl ProvideCredential<Credential = Credential> + 'static,
160    ) -> Self {
161        let chain = self.credential_provider_chain.unwrap_or_default();
162        self.credential_provider_chain = Some(chain.push_front(provider));
163        self
164    }
165
166    /// Specify a customized credential provider chain used by this service.
167    ///
168    /// This chain will be pushed to the front of default chain.
169    pub fn credential_provider_chain(mut self, chain: ProvideCredentialChain<Credential>) -> Self {
170        self.credential_provider_chain = Some(chain);
171        self
172    }
173
174    /// Provide the OAuth2 token to use.
175    pub fn token(mut self, token: String) -> Self {
176        self.config.token = Some(token);
177        self
178    }
179
180    /// Disable attempting to load credentials from the GCE metadata server.
181    pub fn disable_vm_metadata(mut self) -> Self {
182        self.config.disable_vm_metadata = true;
183        self
184    }
185
186    /// Disable loading configuration from the environment.
187    pub fn disable_config_load(mut self) -> Self {
188        self.config.disable_config_load = true;
189        self
190    }
191
192    /// Set the predefined acl for GCS.
193    ///
194    /// Available values are:
195    /// - `authenticatedRead`
196    /// - `bucketOwnerFullControl`
197    /// - `bucketOwnerRead`
198    /// - `private`
199    /// - `projectPrivate`
200    /// - `publicRead`
201    pub fn predefined_acl(mut self, acl: &str) -> Self {
202        if !acl.is_empty() {
203            self.config.predefined_acl = Some(acl.to_string())
204        };
205        self
206    }
207
208    /// Set the default storage class for GCS.
209    ///
210    /// Available values are:
211    /// - `STANDARD`
212    /// - `NEARLINE`
213    /// - `COLDLINE`
214    /// - `ARCHIVE`
215    pub fn default_storage_class(mut self, class: &str) -> Self {
216        if !class.is_empty() {
217            self.config.default_storage_class = Some(class.to_string())
218        };
219        self
220    }
221
222    /// Skip signature will skip loading credentials and signing requests.
223    ///
224    /// This is typically used for buckets which are open to the public or GCS
225    /// storage emulators.
226    pub fn skip_signature(mut self) -> Self {
227        self.config.skip_signature = true;
228        self
229    }
230
231    /// Allow anonymous requests.
232    #[deprecated(
233        since = "0.57.0",
234        note = "Please use `skip_signature` instead of `allow_anonymous`"
235    )]
236    pub fn allow_anonymous(self) -> Self {
237        self.skip_signature()
238    }
239}
240
241impl Builder for GcsBuilder {
242    type Config = GcsConfig;
243
244    fn build(self) -> Result<impl Service> {
245        debug!("backend build started: {self:?}");
246
247        #[allow(deprecated)]
248        let skip_signature = self.config.skip_signature || self.config.allow_anonymous;
249
250        let root = normalize_root(&self.config.root.unwrap_or_default());
251        debug!("backend use root {root}");
252
253        // Handle endpoint and bucket name
254        let bucket = match self.config.bucket.is_empty() {
255            false => Ok(&self.config.bucket),
256            true => Err(
257                Error::new(ErrorKind::ConfigInvalid, "The bucket is misconfigured")
258                    .with_operation("Builder::build")
259                    .with_context("service", GCS_SCHEME),
260            ),
261        }?;
262
263        // TODO: server side encryption
264
265        let endpoint = self
266            .config
267            .endpoint
268            .clone()
269            .unwrap_or_else(|| DEFAULT_GCS_ENDPOINT.to_string());
270        debug!("backend use endpoint: {endpoint}");
271
272        let scope = self
273            .config
274            .scope
275            .clone()
276            .unwrap_or_else(|| DEFAULT_GCS_SCOPE.to_string());
277
278        let os_env = OsEnv;
279        let mut envs = os_env.vars();
280        envs.insert("GOOGLE_SCOPE".to_string(), scope.clone());
281
282        let ctx = Context::new()
283            .with_file_read(TokioFileRead)
284            .with_env(StaticEnv {
285                home_dir: os_env.home_dir(),
286                envs,
287            });
288
289        let mut default_credential = DefaultCredentialProvider::builder();
290        #[cfg(target_arch = "wasm32")]
291        {
292            default_credential = default_credential.no_env().no_well_known();
293        }
294
295        if self.config.disable_config_load {
296            default_credential = default_credential.no_env().no_well_known();
297        }
298
299        if self.config.disable_vm_metadata || self.config.service_account.is_some() {
300            default_credential = default_credential.no_vm_metadata();
301        }
302
303        let mut credential_chain = ProvideCredentialChain::new().push(default_credential.build());
304
305        if !self.config.disable_vm_metadata
306            && let Some(service_account) = self.config.service_account.as_deref()
307        {
308            credential_chain = credential_chain.push(
309                VmMetadataCredentialProvider::new()
310                    .with_scope(&scope)
311                    .with_service_account(service_account),
312            );
313        }
314
315        if let Some(path) = self.config.credential_path.as_deref() {
316            credential_chain =
317                credential_chain.push_front(FileCredentialProvider::new(path).with_scope(&scope));
318        }
319
320        if let Some(content) = self.config.credential.as_deref()
321            && let Ok(provider) = StaticCredentialProvider::from_base64(content)
322        {
323            credential_chain = credential_chain.push_front(provider.with_scope(&scope));
324        }
325
326        if let Some(token) = self.config.token.as_deref() {
327            credential_chain = credential_chain.push_front(TokenCredentialProvider::new(token));
328        }
329
330        if let Some(customized_credential_chain) = self.credential_provider_chain {
331            credential_chain = credential_chain.push_front(customized_credential_chain);
332        }
333
334        let sign_ctx = ctx;
335        let signer = Signer::new(
336            sign_ctx.clone(),
337            credential_chain,
338            RequestSigner::new("storage").with_scope(&scope),
339        );
340
341        let info = ServiceInfo::new(GCS_SCHEME, &root, bucket);
342        let capability = Capability {
343            stat: true,
344            stat_with_if_match: true,
345            stat_with_if_none_match: true,
346
347            read: true,
348            read_with_suffix: true,
349
350            read_with_if_match: true,
351            read_with_if_none_match: true,
352
353            write: true,
354            write_can_empty: true,
355            write_can_multi: true,
356            write_with_cache_control: true,
357            write_with_content_type: true,
358            write_with_content_encoding: true,
359            write_with_user_metadata: true,
360            write_with_if_not_exists: true,
361
362            // The min multipart size of Gcs is 5 MiB.
363            //
364            // ref: <https://cloud.google.com/storage/docs/xml-api/put-object-multipart>
365            write_multi_min_size: Some(5 * 1024 * 1024),
366            // The max multipart size of Gcs is 5 GiB.
367            //
368            // ref: <https://cloud.google.com/storage/docs/xml-api/put-object-multipart>
369            write_multi_max_size: if cfg!(target_pointer_width = "64") {
370                Some(5 * 1024 * 1024 * 1024)
371            } else {
372                Some(usize::MAX)
373            },
374
375            delete: true,
376            delete_max_size: Some(100),
377
378            copy: true,
379            copy_can_multi: true,
380            // GCS rewrite requires maxBytesRewrittenPerCall to be an
381            // integral multiple of 1 MiB if specified.
382            //
383            // ref: <https://cloud.google.com/storage/docs/json_api/v1/objects/rewrite>
384            copy_multi_min_size: Some(GCS_REWRITE_MIN_CHUNK_SIZE),
385            copy_multi_max_size: Some(GCS_REWRITE_MAX_CHUNK_SIZE),
386
387            list: true,
388            list_with_limit: true,
389            list_with_start_after: true,
390            list_with_recursive: true,
391
392            presign: true,
393            presign_stat: true,
394            presign_read: true,
395            presign_write: true,
396
397            shared: true,
398
399            ..Default::default()
400        };
401
402        let backend = GcsBackend {
403            core: Arc::new(GcsCore {
404                info,
405                capability,
406                endpoint,
407                bucket: bucket.to_string(),
408                root,
409                signer,
410                sign_ctx,
411                predefined_acl: self.config.predefined_acl.clone(),
412                default_storage_class: self.config.default_storage_class.clone(),
413                skip_signature,
414            }),
415        };
416
417        Ok(backend)
418    }
419}
420
421/// GCS storage backend
422#[derive(Clone, Debug)]
423pub struct GcsBackend {
424    pub(crate) core: Arc<GcsCore>,
425}
426
427impl Service for GcsBackend {
428    type Reader = oio::StreamReader<GcsReader>;
429    type Writer = GcsWriters;
430    type Lister = oio::PageLister<GcsLister>;
431    type Deleter = oio::BatchDeleter<GcsDeleter>;
432    type Copier = GcsCopier;
433
434    fn info(&self) -> ServiceInfo {
435        self.core.info.clone()
436    }
437
438    fn capability(&self) -> Capability {
439        self.core.capability
440    }
441
442    async fn create_dir(
443        &self,
444        _ctx: &OperationContext,
445        _path: &str,
446        _args: OpCreateDir,
447    ) -> Result<RpCreateDir> {
448        Err(Error::new(
449            ErrorKind::Unsupported,
450            "operation is not supported",
451        ))
452    }
453
454    async fn stat(&self, ctx: &OperationContext, path: &str, args: OpStat) -> Result<RpStat> {
455        let resp = self.core.gcs_get_object_metadata(ctx, path, &args).await?;
456
457        if !resp.status().is_success() {
458            return Err(parse_error(resp));
459        }
460
461        let slc = resp.into_body();
462        let m = GcsCore::build_metadata_from_object_response(path, slc)?;
463
464        Ok(RpStat::new(m))
465    }
466    fn read(&self, ctx: &OperationContext, path: &str, args: OpRead) -> Result<Self::Reader> {
467        let output: oio::StreamReader<GcsReader> = {
468            Ok(oio::StreamReader::new(GcsReader::new(
469                self.clone(),
470                ctx.clone(),
471                path,
472                args,
473            )))
474        }?;
475
476        Ok(output)
477    }
478
479    fn write(&self, ctx: &OperationContext, path: &str, args: OpWrite) -> Result<Self::Writer> {
480        let output: GcsWriters = {
481            let concurrent = args.concurrent();
482            let w = GcsWriter::new(self.core.clone(), ctx.clone(), path, args);
483            // Multipart uploads schedule work through the operation executor
484            // supplied by the caller.
485            let w = oio::MultipartWriter::new(ctx.executor().clone(), w, concurrent);
486
487            Ok(w)
488        }?;
489
490        Ok(output)
491    }
492
493    fn delete(&self, ctx: &OperationContext) -> Result<Self::Deleter> {
494        let output: oio::BatchDeleter<GcsDeleter> = {
495            Ok(oio::BatchDeleter::new(
496                GcsDeleter::new(self.core.clone(), ctx.clone()),
497                self.core.capability.delete_max_size,
498            ))
499        }?;
500
501        Ok(output)
502    }
503
504    fn list(&self, ctx: &OperationContext, path: &str, args: OpList) -> Result<Self::Lister> {
505        let output: oio::PageLister<GcsLister> = {
506            let l = GcsLister::new(
507                self.core.clone(),
508                ctx.clone(),
509                path,
510                args.recursive(),
511                args.limit(),
512                args.start_after(),
513            );
514
515            Ok(oio::PageLister::new(l))
516        }?;
517
518        Ok(output)
519    }
520
521    fn copy(
522        &self,
523        ctx: &OperationContext,
524        from: &str,
525        to: &str,
526        args: OpCopy,
527        opts: OpCopier,
528    ) -> Result<Self::Copier> {
529        let output: GcsCopier = {
530            let copier = GcsCopier::new(self.core.clone(), ctx.clone(), from, to, args, opts);
531            Ok(copier)
532        }?;
533
534        Ok(output)
535    }
536
537    async fn rename(
538        &self,
539        _ctx: &OperationContext,
540        _from: &str,
541        _to: &str,
542        _args: OpRename,
543    ) -> Result<RpRename> {
544        Err(Error::new(
545            ErrorKind::Unsupported,
546            "operation is not supported",
547        ))
548    }
549
550    async fn presign(
551        &self,
552        ctx: &OperationContext,
553        path: &str,
554        args: OpPresign,
555    ) -> Result<RpPresign> {
556        // We will not send this request out, just for signing.
557        let req = match args.operation() {
558            PresignOperation::Stat(v) => self.core.gcs_head_object_xml_request(path, v),
559            PresignOperation::Read(range, v) => {
560                self.core.gcs_get_object_xml_request(path, *range, v)
561            }
562            PresignOperation::Write(v) => {
563                self.core
564                    .gcs_insert_object_xml_request(path, v, Buffer::new())
565            }
566            PresignOperation::Delete(_) => Err(Error::new(
567                ErrorKind::Unsupported,
568                "operation is not supported",
569            )),
570            _ => Err(Error::new(
571                ErrorKind::Unsupported,
572                "operation is not supported",
573            )),
574        };
575        let req = req?;
576        let req = self.core.sign_query(ctx, req, args.expire()).await?;
577
578        // We don't need this request anymore, consume it directly.
579        let (parts, _) = req.into_parts();
580
581        Ok(RpPresign::new(PresignedRequest::new(
582            parts.method,
583            parts.uri,
584            parts.headers,
585        )))
586    }
587}