google_cloud_storage/storage/client.rs
1// Copyright 2025 Google LLC
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// https://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15use super::request_options::RequestOptions;
16use crate::Error;
17use crate::builder::storage::ReadObject;
18use crate::builder::storage::WriteObject;
19use crate::read_resume_policy::ReadResumePolicy;
20use crate::storage::bidi::OpenObject;
21use crate::storage::common_options::CommonOptions;
22use crate::streaming_source::Payload;
23use base64::Engine;
24use base64::prelude::BASE64_STANDARD;
25use gaxi::http::reqwest::RequestBuilder;
26use gaxi::options::{ClientConfig, Credentials};
27use google_cloud_auth::credentials::{Builder as CredentialsBuilder, CacheableResource};
28use google_cloud_gax::client_builder::{Error as BuilderError, Result as BuilderResult};
29use http::Extensions;
30use std::sync::Arc;
31
32/// Implements a client for the Cloud Storage API.
33///
34/// # Example
35/// ```
36/// # async fn sample() -> anyhow::Result<()> {
37/// # use google_cloud_storage::client::Storage;
38/// let client = Storage::builder().build().await?;
39/// // use `client` to make requests to Cloud Storage.
40/// # Ok(()) }
41/// ```
42///
43/// # Configuration
44///
45/// To configure `Storage` use the `with_*` methods in the type returned
46/// by [builder()][Storage::builder]. The default configuration should
47/// work for most applications. Common configuration changes include
48///
49/// * [with_endpoint()]: by default this client uses the global default endpoint
50/// (`https://storage.googleapis.com`). Applications using regional
51/// endpoints or running in restricted networks (e.g. a network configured
52/// with [Private Google Access with VPC Service Controls]) may want to
53/// override this default.
54/// * [with_credentials()]: by default this client uses
55/// [Application Default Credentials]. Applications using custom
56/// authentication may need to override this default.
57///
58/// # Pooling and Cloning
59///
60/// `Storage` holds a connection pool internally, it is advised to
61/// create one and then reuse it. You do not need to wrap `Storage` in
62/// an [Rc](std::rc::Rc) or [Arc] to reuse it, because it already uses an `Arc`
63/// internally.
64///
65/// # Service Description
66///
67/// The Cloud Storage API allows applications to read and write data through
68/// the abstractions of buckets and objects. For a description of these
69/// abstractions please see <https://cloud.google.com/storage/docs>.
70///
71/// Resources are named as follows:
72///
73/// - Projects are referred to as they are defined by the Resource Manager API,
74/// using strings like `projects/123456` or `projects/my-string-id`.
75///
76/// - Buckets are named using string names of the form:
77/// `projects/{project}/buckets/{bucket}`
78/// For globally unique buckets, `_` may be substituted for the project.
79///
80/// - Objects are uniquely identified by their name along with the name of the
81/// bucket they belong to, as separate strings in this API. For example:
82/// ```no_rust
83/// bucket = "projects/_/buckets/my-bucket"
84/// object = "my-object/with/a/folder-like/name"
85/// ```
86/// Note that object names can contain `/` characters, which are treated as
87/// any other character (no special directory semantics).
88///
89/// [with_endpoint()]: ClientBuilder::with_endpoint
90/// [with_credentials()]: ClientBuilder::with_credentials
91/// [Private Google Access with VPC Service Controls]: https://cloud.google.com/vpc-service-controls/docs/private-connectivity
92/// [Application Default Credentials]: https://cloud.google.com/docs/authentication#adc
93#[derive(Clone, Debug)]
94pub struct Storage<S = crate::stub::DefaultStorage>
95where
96 S: crate::stub::Storage + 'static,
97{
98 stub: std::sync::Arc<S>,
99 options: RequestOptions,
100}
101
102#[derive(Clone, Debug)]
103pub(crate) struct StorageInner {
104 pub client: gaxi::http::ReqwestClient,
105 pub cred: Credentials,
106 pub options: RequestOptions,
107 pub grpc: gaxi::grpc::Client,
108}
109
110impl Storage {
111 /// Returns a builder for [Storage].
112 ///
113 /// # Example
114 /// ```
115 /// # use google_cloud_storage::client::Storage;
116 /// # async fn sample() -> anyhow::Result<()> {
117 /// let client = Storage::builder().build().await?;
118 /// # Ok(()) }
119 /// ```
120 pub fn builder() -> ClientBuilder {
121 ClientBuilder::new()
122 }
123}
124
125impl<S> Storage<S>
126where
127 S: crate::storage::stub::Storage + 'static,
128{
129 /// Creates a new client from the provided stub.
130 ///
131 /// The most common case for calling this function is in tests mocking the
132 /// client's behavior.
133 pub fn from_stub(stub: S) -> Self
134 where
135 S: super::stub::Storage + 'static,
136 {
137 Self {
138 stub: std::sync::Arc::new(stub),
139 options: RequestOptions::new(),
140 }
141 }
142
143 /// Write an object with data from any data source.
144 ///
145 /// # Example
146 /// ```
147 /// # use google_cloud_storage::client::Storage;
148 /// # async fn sample(client: &Storage) -> anyhow::Result<()> {
149 /// let response = client
150 /// .write_object("projects/_/buckets/my-bucket", "my-object", "hello world")
151 /// .send_buffered()
152 /// .await?;
153 /// println!("response details={response:?}");
154 /// # Ok(()) }
155 /// ```
156 ///
157 /// # Example
158 /// ```
159 /// # use google_cloud_storage::client::Storage;
160 /// # async fn sample(client: &Storage) -> anyhow::Result<()> {
161 /// let response = client
162 /// .write_object("projects/_/buckets/my-bucket", "my-object", "hello world")
163 /// .send_unbuffered()
164 /// .await?;
165 /// println!("response details={response:?}");
166 /// # Ok(()) }
167 /// ```
168 ///
169 /// You can use many different types as the payload. For example, a string,
170 /// a [bytes::Bytes], a [tokio::fs::File], or a custom type that implements
171 /// the [StreamingSource] trait.
172 ///
173 /// If your data source also implements [Seek], prefer [send_unbuffered()]
174 /// to start the write. Otherwise use [send_buffered()].
175 ///
176 /// # Parameters
177 /// * `bucket` - the bucket name containing the object. In
178 /// `projects/_/buckets/{bucket_id}` format.
179 /// * `object` - the object name.
180 /// * `payload` - the object data.
181 ///
182 /// [Seek]: crate::streaming_source::Seek
183 /// [StreamingSource]: crate::streaming_source::StreamingSource
184 /// [send_buffered()]: crate::builder::storage::WriteObject::send_buffered
185 /// [send_unbuffered()]: crate::builder::storage::WriteObject::send_unbuffered
186 pub fn write_object<B, O, T, P>(&self, bucket: B, object: O, payload: T) -> WriteObject<P, S>
187 where
188 B: Into<String>,
189 O: Into<String>,
190 T: Into<Payload<P>>,
191 {
192 WriteObject::new(
193 self.stub.clone(),
194 bucket,
195 object,
196 payload,
197 self.options.clone(),
198 )
199 }
200
201 /// Reads the contents of an object.
202 ///
203 /// # Example
204 /// ```
205 /// # use google_cloud_storage::client::Storage;
206 /// # async fn sample(client: &Storage) -> anyhow::Result<()> {
207 /// let mut resp = client
208 /// .read_object("projects/_/buckets/my-bucket", "my-object")
209 /// .send()
210 /// .await?;
211 /// let mut contents = Vec::new();
212 /// while let Some(chunk) = resp.next().await.transpose()? {
213 /// contents.extend_from_slice(&chunk);
214 /// }
215 /// println!("object contents={:?}", bytes::Bytes::from_owner(contents));
216 /// # Ok(()) }
217 /// ```
218 ///
219 /// # Parameters
220 /// * `bucket` - the bucket name containing the object. In
221 /// `projects/_/buckets/{bucket_id}` format.
222 /// * `object` - the object name.
223 pub fn read_object<B, O>(&self, bucket: B, object: O) -> ReadObject<S>
224 where
225 B: Into<String>,
226 O: Into<String>,
227 {
228 ReadObject::new(self.stub.clone(), bucket, object, self.options.clone())
229 }
230
231 /// Opens an object to read its contents using concurrent ranged reads.
232 ///
233 /// # Example
234 /// ```
235 /// # use google_cloud_storage::client::Storage;
236 /// # async fn sample(client: &Storage) -> anyhow::Result<()> {
237 /// use google_cloud_storage::model_ext::ReadRange;
238 /// let descriptor = client
239 /// .open_object("projects/_/buckets/my-bucket", "my-object")
240 /// .send()
241 /// .await?;
242 /// // Print the object metadata
243 /// println!("metadata = {:?}", descriptor.object());
244 /// // Read 2000 bytes starting at offset 1000.
245 /// let mut reader = descriptor.read_range(ReadRange::segment(1000, 2000)).await;
246 /// let mut contents = Vec::new();
247 /// while let Some(chunk) = reader.next().await.transpose()? {
248 /// contents.extend_from_slice(&chunk);
249 /// }
250 /// println!("range contents={:?}", bytes::Bytes::from_owner(contents));
251 /// // `descriptor` can be used to read more ranges, concurrently if needed.
252 /// # Ok(()) }
253 /// ```
254 ///
255 /// # Example: open and read in a single RPC
256 /// ```
257 /// # use google_cloud_storage::client::Storage;
258 /// # async fn sample(client: &Storage) -> anyhow::Result<()> {
259 /// use google_cloud_storage::model_ext::ReadRange;
260 /// let (descriptor, mut reader) = client
261 /// .open_object("projects/_/buckets/my-bucket", "my-object")
262 /// .send_and_read(ReadRange::segment(1000, 2000))
263 /// .await?;
264 /// // `descriptor` can be used to read more ranges.
265 /// # Ok(()) }
266 /// ```
267 ///
268 /// <div class="warning">
269 /// The APIs used by this method are only enabled for some projects and
270 /// buckets. Contact your account team to enable this API.
271 /// </div>
272 ///
273 /// # Parameters
274 /// * `bucket` - the bucket name containing the object. In
275 /// `projects/_/buckets/{bucket_id}` format.
276 /// * `object` - the object name.
277 pub fn open_object<B, O>(&self, bucket: B, object: O) -> OpenObject<S>
278 where
279 B: Into<String>,
280 O: Into<String>,
281 {
282 OpenObject::new(
283 bucket.into(),
284 object.into(),
285 self.stub.clone(),
286 self.options.clone(),
287 )
288 }
289}
290
291impl Storage {
292 pub(crate) async fn new(builder: ClientBuilder) -> BuilderResult<Self> {
293 let inner = StorageInner::from_parts(builder).await?;
294 let options = inner.options.clone();
295 let stub = crate::storage::transport::Storage::new(Arc::new(inner));
296 Ok(Self { stub, options })
297 }
298}
299
300impl StorageInner {
301 /// Builds a client assuming `config.cred` and `config.endpoint` are initialized, panics otherwise.
302 pub(self) fn new(
303 client: gaxi::http::ReqwestClient,
304 cred: Credentials,
305 options: RequestOptions,
306 grpc: gaxi::grpc::Client,
307 ) -> Self {
308 Self {
309 client,
310 cred,
311 options,
312 grpc,
313 }
314 }
315
316 pub(self) async fn from_parts(builder: ClientBuilder) -> BuilderResult<Self> {
317 let (mut config, options) = builder.into_parts()?;
318 config.disable_automatic_decompression = true;
319 let cred = config
320 .cred
321 .clone()
322 .expect("into_parts() assigns default credentials");
323
324 let client = gaxi::http::ReqwestClient::new(config.clone(), super::DEFAULT_HOST).await?;
325
326 let inner = StorageInner::new(
327 client,
328 cred,
329 options,
330 gaxi::grpc::Client::new(config, super::DEFAULT_HOST).await?,
331 );
332 Ok(inner)
333 }
334
335 // Helper method to apply authentication headers to the request builder.
336 pub async fn apply_auth_headers(
337 &self,
338 builder: RequestBuilder,
339 ) -> crate::Result<RequestBuilder> {
340 let cached_auth_headers = self
341 .cred
342 .headers(Extensions::new())
343 .await
344 .map_err(Error::authentication)?;
345
346 let auth_headers = match cached_auth_headers {
347 CacheableResource::New { data, .. } => data,
348 CacheableResource::NotModified => {
349 unreachable!("headers are not cached");
350 }
351 };
352
353 let builder = builder.headers(auth_headers);
354 Ok(builder)
355 }
356}
357
358/// A builder for [Storage].
359///
360/// ```
361/// # use google_cloud_storage::client::Storage;
362/// # async fn sample() -> anyhow::Result<()> {
363/// let builder = Storage::builder();
364/// let client = builder
365/// .with_endpoint("https://storage.googleapis.com")
366/// .build()
367/// .await?;
368/// # Ok(()) }
369/// ```
370pub struct ClientBuilder {
371 // Common options for all clients (generated or not).
372 pub(crate) config: ClientConfig,
373 // Specific options for the storage client. `RequestOptions` also requires
374 // these, it makes sense to share them.
375 common_options: CommonOptions,
376}
377
378impl ClientBuilder {
379 pub(crate) fn new() -> Self {
380 let mut config = ClientConfig::default();
381 config.retry_policy = Some(Arc::new(crate::retry_policy::storage_default()));
382 config.backoff_policy = Some(Arc::new(crate::backoff_policy::default()));
383 {
384 let count = std::thread::available_parallelism().ok();
385 config.grpc_subchannel_count = Some(count.map(|x| x.get()).unwrap_or(1));
386 }
387 let common_options = CommonOptions::new();
388 Self {
389 config,
390 common_options,
391 }
392 }
393
394 /// Creates a new client.
395 ///
396 /// # Example
397 /// ```
398 /// # use google_cloud_storage::client::Storage;
399 /// # async fn sample() -> anyhow::Result<()> {
400 /// let client = Storage::builder().build().await?;
401 /// # Ok(()) }
402 /// ```
403 pub async fn build(self) -> BuilderResult<Storage> {
404 Storage::new(self).await
405 }
406
407 /// Sets the endpoint.
408 ///
409 /// # Example
410 /// ```
411 /// # use google_cloud_storage::client::Storage;
412 /// # async fn sample() -> anyhow::Result<()> {
413 /// let client = Storage::builder()
414 /// .with_endpoint("https://private.googleapis.com")
415 /// .build()
416 /// .await?;
417 /// # Ok(()) }
418 /// ```
419 pub fn with_endpoint<V: Into<String>>(mut self, v: V) -> Self {
420 self.config.endpoint = Some(v.into());
421 self
422 }
423
424 /// Configures the authentication credentials.
425 ///
426 /// Google Cloud Storage requires authentication for most buckets. Use this
427 /// method to change the credentials used by the client. More information
428 /// about valid credentials types can be found in the [google-cloud-auth]
429 /// crate documentation.
430 ///
431 /// # Example
432 /// ```
433 /// # use google_cloud_storage::client::Storage;
434 /// # async fn sample() -> anyhow::Result<()> {
435 /// use google_cloud_auth::credentials::mds;
436 /// let client = Storage::builder()
437 /// .with_credentials(
438 /// mds::Builder::default()
439 /// .with_scopes(["https://www.googleapis.com/auth/cloud-platform.read-only"])
440 /// .build()?)
441 /// .build()
442 /// .await?;
443 /// # Ok(()) }
444 /// ```
445 ///
446 /// [google-cloud-auth]: https://docs.rs/google-cloud-auth
447 pub fn with_credentials<V: Into<Credentials>>(mut self, v: V) -> Self {
448 self.config.cred = Some(v.into());
449 self
450 }
451
452 /// Configure the retry policy.
453 ///
454 /// The client libraries can automatically retry operations that fail. The
455 /// retry policy controls what errors are considered retryable, sets limits
456 /// on the number of attempts or the time trying to make attempts.
457 ///
458 /// # Example
459 /// ```
460 /// # use google_cloud_storage::client::Storage;
461 /// # async fn sample() -> anyhow::Result<()> {
462 /// use google_cloud_gax::retry_policy::{AlwaysRetry, RetryPolicyExt};
463 /// let client = Storage::builder()
464 /// .with_retry_policy(AlwaysRetry.with_attempt_limit(3))
465 /// .build()
466 /// .await?;
467 /// # Ok(()) }
468 /// ```
469 pub fn with_retry_policy<V: Into<google_cloud_gax::retry_policy::RetryPolicyArg>>(
470 mut self,
471 v: V,
472 ) -> Self {
473 self.config.retry_policy = Some(v.into().into());
474 self
475 }
476
477 /// Configure the retry backoff policy.
478 ///
479 /// The client libraries can automatically retry operations that fail. The
480 /// backoff policy controls how long to wait in between retry attempts.
481 ///
482 /// # Example
483 /// ```
484 /// # use google_cloud_storage::client::Storage;
485 /// # async fn sample() -> anyhow::Result<()> {
486 /// use google_cloud_gax::exponential_backoff::ExponentialBackoff;
487 /// use std::time::Duration;
488 /// let policy = ExponentialBackoff::default();
489 /// let client = Storage::builder()
490 /// .with_backoff_policy(policy)
491 /// .build()
492 /// .await?;
493 /// # Ok(()) }
494 /// ```
495 pub fn with_backoff_policy<V: Into<google_cloud_gax::backoff_policy::BackoffPolicyArg>>(
496 mut self,
497 v: V,
498 ) -> Self {
499 self.config.backoff_policy = Some(v.into().into());
500 self
501 }
502
503 /// Configure the retry throttler.
504 ///
505 /// Advanced applications may want to configure a retry throttler to
506 /// [Address Cascading Failures] and when [Handling Overload] conditions.
507 /// The client libraries throttle their retry loop, using a policy to
508 /// control the throttling algorithm. Use this method to fine tune or
509 /// customize the default retry throtler.
510 ///
511 /// [Handling Overload]: https://sre.google/sre-book/handling-overload/
512 /// [Address Cascading Failures]: https://sre.google/sre-book/addressing-cascading-failures/
513 ///
514 /// # Example
515 /// ```
516 /// # use google_cloud_storage::client::Storage;
517 /// # async fn sample() -> anyhow::Result<()> {
518 /// use google_cloud_gax::retry_throttler::AdaptiveThrottler;
519 /// let client = Storage::builder()
520 /// .with_retry_throttler(AdaptiveThrottler::default())
521 /// .build()
522 /// .await?;
523 /// # Ok(()) }
524 /// ```
525 pub fn with_retry_throttler<V: Into<google_cloud_gax::retry_throttler::RetryThrottlerArg>>(
526 mut self,
527 v: V,
528 ) -> Self {
529 self.config.retry_throttler = v.into().into();
530 self
531 }
532
533 /// Sets the payload size threshold to switch from single-shot to resumable uploads.
534 ///
535 /// # Example
536 /// ```
537 /// # use google_cloud_storage::client::Storage;
538 /// # async fn sample() -> anyhow::Result<()> {
539 /// let client = Storage::builder()
540 /// .with_resumable_upload_threshold(0_usize) // Forces a resumable upload.
541 /// .build()
542 /// .await?;
543 /// let response = client
544 /// .write_object("projects/_/buckets/my-bucket", "my-object", "hello world")
545 /// .send_buffered()
546 /// .await?;
547 /// println!("response details={response:?}");
548 /// # Ok(()) }
549 /// ```
550 ///
551 /// The client library can write objects using [single-shot] or [resumable]
552 /// uploads. For small objects, single-shot uploads offer better
553 /// performance, as they require a single HTTP transfer. For larger objects,
554 /// the additional request latency is not significant, and resumable uploads
555 /// offer better recovery on errors.
556 ///
557 /// The library automatically selects resumable uploads when the payload is
558 /// equal to or larger than this option. For smaller writes the client
559 /// library uses single-shot uploads.
560 ///
561 /// The exact threshold depends on where the application is deployed and
562 /// destination bucket location with respect to where the application is
563 /// running. The library defaults should work well in most cases, but some
564 /// applications may benefit from fine-tuning.
565 ///
566 /// [single-shot]: https://cloud.google.com/storage/docs/uploading-objects
567 /// [resumable]: https://cloud.google.com/storage/docs/resumable-uploads
568 pub fn with_resumable_upload_threshold<V: Into<usize>>(mut self, v: V) -> Self {
569 self.common_options.resumable_upload_threshold = v.into();
570 self
571 }
572
573 /// Changes the buffer size for some resumable uploads.
574 ///
575 /// # Example
576 /// ```
577 /// # use google_cloud_storage::client::Storage;
578 /// # async fn sample() -> anyhow::Result<()> {
579 /// let client = Storage::builder()
580 /// .with_resumable_upload_buffer_size(32 * 1024 * 1024_usize)
581 /// .build()
582 /// .await?;
583 /// let response = client
584 /// .write_object("projects/_/buckets/my-bucket", "my-object", "hello world")
585 /// .send_buffered()
586 /// .await?;
587 /// println!("response details={response:?}");
588 /// # Ok(()) }
589 /// ```
590 ///
591 /// When performing [resumable uploads] from sources without [Seek] the
592 /// client library needs to buffer data in memory until it is persisted by
593 /// the service. Otherwise the data would be lost if the upload is
594 /// interrupted. Applications may want to tune this buffer size:
595 ///
596 /// - Use smaller buffer sizes to support more concurrent writes in the
597 /// same application.
598 /// - Use larger buffer sizes for better throughput. Sending many small
599 /// buffers stalls the writer until the client receives a successful
600 /// response from the service.
601 ///
602 /// Keep in mind that there are diminishing returns on using larger buffers.
603 ///
604 /// [resumable uploads]: https://cloud.google.com/storage/docs/resumable-uploads
605 /// [Seek]: crate::streaming_source::Seek
606 pub fn with_resumable_upload_buffer_size<V: Into<usize>>(mut self, v: V) -> Self {
607 self.common_options.resumable_upload_buffer_size = v.into();
608 self
609 }
610
611 /// Configure the resume policy for object reads.
612 ///
613 /// The Cloud Storage client library can automatically resume a read request
614 /// that is interrupted by a transient error. Applications may want to
615 /// limit the number of read attempts, or may wish to expand the type
616 /// of errors treated as retryable.
617 ///
618 /// # Example
619 /// ```
620 /// # use google_cloud_storage::client::Storage;
621 /// # async fn sample() -> anyhow::Result<()> {
622 /// use google_cloud_storage::read_resume_policy::{AlwaysResume, ReadResumePolicyExt};
623 /// let client = Storage::builder()
624 /// .with_read_resume_policy(AlwaysResume.with_attempt_limit(3))
625 /// .build()
626 /// .await?;
627 /// # Ok(()) }
628 /// ```
629 pub fn with_read_resume_policy<V>(mut self, v: V) -> Self
630 where
631 V: ReadResumePolicy + 'static,
632 {
633 self.common_options.read_resume_policy = Arc::new(v);
634 self
635 }
636
637 /// Configure the number of subchannels used by the client.
638 ///
639 /// # Example
640 /// ```
641 /// # use google_cloud_storage::client::Storage;
642 /// # async fn sample() -> anyhow::Result<()> {
643 /// // By default the client uses `count` subchannels.
644 /// let count = std::thread::available_parallelism()?.get();
645 /// let client = Storage::builder()
646 /// .with_grpc_subchannel_count(std::cmp::max(1, count / 2))
647 /// .build()
648 /// .await?;
649 /// # Ok(()) }
650 /// ```
651 ///
652 /// gRPC-based clients may exhibit high latency if many requests need to be
653 /// demuxed over a single HTTP/2 connection (often called a *subchannel* in gRPC).
654 /// Consider using more subchannels if your application makes many
655 /// concurrent requests. Consider using fewer subchannels if your
656 /// application needs the file descriptors for other purposes.
657 ///
658 /// Keep in mind that Google Cloud limits the number of concurrent RPCs in
659 /// a single connection to about 100.
660 pub fn with_grpc_subchannel_count(mut self, v: usize) -> Self {
661 self.config.grpc_subchannel_count = Some(v);
662 self
663 }
664
665 pub(crate) fn apply_default_credentials(&mut self) -> BuilderResult<()> {
666 if self.config.cred.is_some() {
667 return Ok(());
668 };
669 let default = CredentialsBuilder::default()
670 .build()
671 .map_err(BuilderError::cred)?;
672 self.config.cred = Some(default);
673 Ok(())
674 }
675
676 pub(crate) fn apply_default_endpoint(&mut self) -> BuilderResult<()> {
677 let _ = self
678 .config
679 .endpoint
680 .get_or_insert_with(|| super::DEFAULT_HOST.to_string());
681 Ok(())
682 }
683
684 // Breaks the builder into its parts, with defaults applied.
685 pub(crate) fn into_parts(
686 mut self,
687 ) -> google_cloud_gax::client_builder::Result<(ClientConfig, RequestOptions)> {
688 self.apply_default_credentials()?;
689 self.apply_default_endpoint()?;
690 let request_options =
691 RequestOptions::new_with_client_config(&self.config, self.common_options);
692 Ok((self.config, request_options))
693 }
694}
695
696/// The set of characters that are percent encoded.
697///
698/// This set is defined at https://cloud.google.com/storage/docs/request-endpoints#encoding:
699///
700/// Encode the following characters when they appear in either the object name
701/// or query string of a request URL:
702/// !, #, $, &, ', (, ), *, +, ,, /, :, ;, =, ?, @, [, ], and space characters.
703pub(crate) const ENCODED_CHARS: percent_encoding::AsciiSet = percent_encoding::CONTROLS
704 .add(b'!')
705 .add(b'#')
706 .add(b'$')
707 .add(b'&')
708 .add(b'\'')
709 .add(b'(')
710 .add(b')')
711 .add(b'*')
712 .add(b'+')
713 .add(b',')
714 .add(b'/')
715 .add(b':')
716 .add(b';')
717 .add(b'=')
718 .add(b'?')
719 .add(b'@')
720 .add(b'[')
721 .add(b']')
722 .add(b' ');
723
724/// Percent encode a string.
725///
726/// To ensure compatibility certain characters need to be encoded when they appear
727/// in either the object name or query string of a request URL.
728pub(crate) fn enc(value: &str) -> String {
729 percent_encoding::utf8_percent_encode(value, &ENCODED_CHARS).to_string()
730}
731
732pub(crate) fn apply_customer_supplied_encryption_headers(
733 builder: RequestBuilder,
734 common_object_request_params: &Option<crate::model::CommonObjectRequestParams>,
735) -> RequestBuilder {
736 common_object_request_params.iter().fold(builder, |b, v| {
737 b.header(
738 "x-goog-encryption-algorithm",
739 v.encryption_algorithm.clone(),
740 )
741 .header(
742 "x-goog-encryption-key",
743 BASE64_STANDARD.encode(v.encryption_key_bytes.clone()),
744 )
745 .header(
746 "x-goog-encryption-key-sha256",
747 BASE64_STANDARD.encode(v.encryption_key_sha256_bytes.clone()),
748 )
749 })
750}
751
752#[cfg(test)]
753pub(crate) mod tests {
754 use super::*;
755 use google_cloud_auth::credentials::anonymous::Builder as Anonymous;
756 use google_cloud_gax::retry_result::RetryResult;
757 use google_cloud_gax::retry_state::RetryState;
758 use std::{sync::Arc, time::Duration};
759
760 #[test]
761 fn default_settings() {
762 let builder = ClientBuilder::new().with_credentials(Anonymous::new().build());
763 let config = builder.config;
764 assert!(config.retry_policy.is_some(), "{config:?}");
765 assert!(config.backoff_policy.is_some(), "{config:?}");
766 {
767 assert!(
768 config.grpc_subchannel_count.is_some_and(|v| v >= 1),
769 "{config:?}"
770 );
771 }
772 }
773
774 #[test]
775 fn subchannel_count() {
776 let builder = ClientBuilder::new()
777 .with_credentials(Anonymous::new().build())
778 .with_grpc_subchannel_count(42);
779 let config = builder.config;
780 assert!(
781 config.grpc_subchannel_count.is_some_and(|v| v == 42),
782 "{config:?}"
783 );
784 }
785
786 pub(crate) fn test_builder() -> ClientBuilder {
787 ClientBuilder::new()
788 .with_credentials(Anonymous::new().build())
789 .with_endpoint("http://private.googleapis.com")
790 .with_backoff_policy(
791 google_cloud_gax::exponential_backoff::ExponentialBackoffBuilder::new()
792 .with_initial_delay(Duration::from_millis(1))
793 .with_maximum_delay(Duration::from_millis(2))
794 .build()
795 .expect("hard coded policy should build correctly"),
796 )
797 }
798
799 /// This is used by the request builder tests.
800 pub(crate) async fn test_inner_client(builder: ClientBuilder) -> Arc<StorageInner> {
801 let inner = StorageInner::from_parts(builder)
802 .await
803 .expect("creating an test inner client succeeds");
804 Arc::new(inner)
805 }
806
807 mockall::mock! {
808 #[derive(Debug)]
809 pub RetryThrottler {}
810
811 impl google_cloud_gax::retry_throttler::RetryThrottler for RetryThrottler {
812 fn throttle_retry_attempt(&self) -> bool;
813 fn on_retry_failure(&mut self, flow: &RetryResult);
814 fn on_success(&mut self);
815 }
816 }
817
818 mockall::mock! {
819 #[derive(Debug)]
820 pub RetryPolicy {}
821
822 impl google_cloud_gax::retry_policy::RetryPolicy for RetryPolicy {
823 fn on_error(&self, state: &RetryState, error: google_cloud_gax::error::Error) -> RetryResult;
824 }
825 }
826
827 mockall::mock! {
828 #[derive(Debug)]
829 pub BackoffPolicy {}
830
831 impl google_cloud_gax::backoff_policy::BackoffPolicy for BackoffPolicy {
832 fn on_failure(&self, state: &RetryState) -> std::time::Duration;
833 }
834 }
835
836 mockall::mock! {
837 #[derive(Debug)]
838 pub ReadResumePolicy {}
839
840 impl crate::read_resume_policy::ReadResumePolicy for ReadResumePolicy {
841 fn on_error(&self, query: &crate::read_resume_policy::ResumeQuery, error: google_cloud_gax::error::Error) -> crate::read_resume_policy::ResumeResult;
842 }
843 }
844}