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;
16#[cfg(google_cloud_unstable_storage_bidi)]
17use crate::builder::storage::OpenAppendableObject;
18use crate::builder::storage::ReadObject;
19#[cfg(google_cloud_unstable_storage_bidi)]
20use crate::builder::storage::ReopenAppendableObject;
21use crate::builder::storage::WriteObject;
22use crate::read_resume_policy::ReadResumePolicy;
23use crate::storage::bidi::{GrpcClient, OpenObject};
24use crate::storage::common_options::CommonOptions;
25use crate::streaming_source::Payload;
26use base64::Engine;
27use base64::prelude::BASE64_STANDARD;
28use gaxi::http::HttpRequestBuilder;
29use gaxi::options::{ClientConfig, Credentials};
30use google_cloud_auth::credentials::Builder as CredentialsBuilder;
31use google_cloud_gax::client_builder::{Error as BuilderError, Result as BuilderResult};
32use std::sync::Arc;
33
34/// Implements a client for the Cloud Storage API.
35///
36/// # Example
37/// ```
38/// # async fn sample() -> anyhow::Result<()> {
39/// # use google_cloud_storage::client::Storage;
40/// let client = Storage::builder().build().await?;
41/// // use `client` to make requests to Cloud Storage.
42/// # Ok(()) }
43/// ```
44///
45/// # Configuration
46///
47/// To configure `Storage` use the `with_*` methods in the type returned
48/// by [builder()][Storage::builder]. The default configuration should
49/// work for most applications. Common configuration changes include
50///
51/// * [with_endpoint()]: by default this client uses the global default endpoint
52/// (`https://storage.googleapis.com`). Applications using regional
53/// endpoints or running in restricted networks (e.g. a network configured
54/// with [Private Google Access with VPC Service Controls]) may want to
55/// override this default.
56/// * [with_credentials()]: by default this client uses
57/// [Application Default Credentials]. Applications using custom
58/// authentication may need to override this default.
59///
60/// # Pooling and Cloning
61///
62/// `Storage` holds a connection pool internally, it is advised to
63/// create one and then reuse it. You do not need to wrap `Storage` in
64/// an [Rc](std::rc::Rc) or [Arc] to reuse it, because it already uses an `Arc`
65/// internally.
66///
67/// # Service Description
68///
69/// The Cloud Storage API allows applications to read and write data through
70/// the abstractions of buckets and objects. For a description of these
71/// abstractions please see <https://cloud.google.com/storage/docs>.
72///
73/// Resources are named as follows:
74///
75/// - Projects are referred to as they are defined by the Resource Manager API,
76/// using strings like `projects/123456` or `projects/my-string-id`.
77///
78/// - Buckets are named using string names of the form:
79/// `projects/{project}/buckets/{bucket}`
80/// For globally unique buckets, `_` may be substituted for the project.
81///
82/// - Objects are uniquely identified by their name along with the name of the
83/// bucket they belong to, as separate strings in this API. For example:
84/// ```no_rust
85/// bucket = "projects/_/buckets/my-bucket"
86/// object = "my-object/with/a/folder-like/name"
87/// ```
88/// Note that object names can contain `/` characters, which are treated as
89/// any other character (no special directory semantics).
90///
91/// [with_endpoint()]: ClientBuilder::with_endpoint
92/// [with_credentials()]: ClientBuilder::with_credentials
93/// [Private Google Access with VPC Service Controls]: https://cloud.google.com/vpc-service-controls/docs/private-connectivity
94/// [Application Default Credentials]: https://cloud.google.com/docs/authentication#adc
95#[derive(Clone, Debug)]
96pub struct Storage<S = crate::stub::DefaultStorage>
97where
98 S: crate::stub::Storage + 'static,
99{
100 stub: std::sync::Arc<S>,
101 options: RequestOptions,
102}
103
104#[derive(Clone, Debug)]
105pub(crate) struct StorageInner {
106 pub client: gaxi::http::ReqwestClient,
107 pub options: RequestOptions,
108 pub grpc: GrpcClient,
109}
110
111impl Storage {
112 /// Returns a builder for [Storage].
113 ///
114 /// # Example
115 /// ```
116 /// # use google_cloud_storage::client::Storage;
117 /// # async fn sample() -> anyhow::Result<()> {
118 /// let client = Storage::builder().build().await?;
119 /// # Ok(()) }
120 /// ```
121 pub fn builder() -> ClientBuilder {
122 ClientBuilder::new()
123 }
124}
125
126impl<S> Storage<S>
127where
128 S: crate::storage::stub::Storage + 'static,
129{
130 /// Creates a new client from the provided stub.
131 ///
132 /// The most common case for calling this function is in tests mocking the
133 /// client's behavior.
134 pub fn from_stub(stub: impl Into<std::sync::Arc<S>>) -> Self {
135 Self {
136 stub: stub.into(),
137 options: RequestOptions::new(),
138 }
139 }
140
141 /// Write an object with data from any data source.
142 ///
143 /// # Example
144 /// ```
145 /// # use google_cloud_storage::client::Storage;
146 /// # async fn sample(client: &Storage) -> anyhow::Result<()> {
147 /// let response = client
148 /// .write_object("projects/_/buckets/my-bucket", "my-object", "hello world")
149 /// .send_buffered()
150 /// .await?;
151 /// println!("response details={response:?}");
152 /// # Ok(()) }
153 /// ```
154 ///
155 /// # Example
156 /// ```
157 /// # use google_cloud_storage::client::Storage;
158 /// # async fn sample(client: &Storage) -> anyhow::Result<()> {
159 /// let response = client
160 /// .write_object("projects/_/buckets/my-bucket", "my-object", "hello world")
161 /// .send_unbuffered()
162 /// .await?;
163 /// println!("response details={response:?}");
164 /// # Ok(()) }
165 /// ```
166 ///
167 /// You can use many different types as the payload. For example, a string,
168 /// a [bytes::Bytes], a [tokio::fs::File], or a custom type that implements
169 /// the [StreamingSource] trait.
170 ///
171 /// If your data source also implements [Seek], prefer [send_unbuffered()]
172 /// to start the write. Otherwise use [send_buffered()].
173 ///
174 /// # Parameters
175 /// * `bucket` - the bucket name containing the object. In
176 /// `projects/_/buckets/{bucket_id}` format.
177 /// * `object` - the object name.
178 /// * `payload` - the object data.
179 ///
180 /// [Seek]: crate::streaming_source::Seek
181 /// [StreamingSource]: crate::streaming_source::StreamingSource
182 /// [send_buffered()]: crate::builder::storage::WriteObject::send_buffered
183 /// [send_unbuffered()]: crate::builder::storage::WriteObject::send_unbuffered
184 pub fn write_object<B, O, T, P>(&self, bucket: B, object: O, payload: T) -> WriteObject<P, S>
185 where
186 B: Into<String>,
187 O: Into<String>,
188 T: Into<Payload<P>>,
189 {
190 WriteObject::new(
191 self.stub.clone(),
192 bucket,
193 object,
194 payload,
195 self.options.clone(),
196 )
197 }
198
199 /// Reads the contents of an object.
200 ///
201 /// # Example
202 /// ```
203 /// # use google_cloud_storage::client::Storage;
204 /// # async fn sample(client: &Storage) -> anyhow::Result<()> {
205 /// let mut resp = client
206 /// .read_object("projects/_/buckets/my-bucket", "my-object")
207 /// .send()
208 /// .await?;
209 /// let mut contents = Vec::new();
210 /// while let Some(chunk) = resp.next().await.transpose()? {
211 /// contents.extend_from_slice(&chunk);
212 /// }
213 /// println!("object contents={:?}", bytes::Bytes::from_owner(contents));
214 /// # Ok(()) }
215 /// ```
216 ///
217 /// # Parameters
218 /// * `bucket` - the bucket name containing the object. In
219 /// `projects/_/buckets/{bucket_id}` format.
220 /// * `object` - the object name.
221 pub fn read_object<B, O>(&self, bucket: B, object: O) -> ReadObject<S>
222 where
223 B: Into<String>,
224 O: Into<String>,
225 {
226 ReadObject::new(self.stub.clone(), bucket, object, self.options.clone())
227 }
228
229 /// Opens an object to read its contents using concurrent ranged reads.
230 ///
231 /// # Example
232 /// ```
233 /// # use google_cloud_storage::client::Storage;
234 /// # async fn sample(client: &Storage) -> anyhow::Result<()> {
235 /// use google_cloud_storage::model_ext::ReadRange;
236 /// let descriptor = client
237 /// .open_object("projects/_/buckets/my-bucket", "my-object")
238 /// .send()
239 /// .await?;
240 /// // Print the object metadata
241 /// println!("metadata = {:?}", descriptor.object());
242 /// // Read 2000 bytes starting at offset 1000.
243 /// let mut reader = descriptor.read_range(ReadRange::segment(1000, 2000)).await;
244 /// let mut contents = Vec::new();
245 /// while let Some(chunk) = reader.next().await.transpose()? {
246 /// contents.extend_from_slice(&chunk);
247 /// }
248 /// println!("range contents={:?}", bytes::Bytes::from_owner(contents));
249 /// // `descriptor` can be used to read more ranges, concurrently if needed.
250 /// # Ok(()) }
251 /// ```
252 ///
253 /// # Example: open and read in a single RPC
254 /// ```
255 /// # use google_cloud_storage::client::Storage;
256 /// # async fn sample(client: &Storage) -> anyhow::Result<()> {
257 /// use google_cloud_storage::model_ext::ReadRange;
258 /// let (descriptor, mut reader) = client
259 /// .open_object("projects/_/buckets/my-bucket", "my-object")
260 /// .send_and_read(ReadRange::segment(1000, 2000))
261 /// .await?;
262 /// // `descriptor` can be used to read more ranges.
263 /// # Ok(()) }
264 /// ```
265 ///
266 /// <div class="warning">
267 /// The APIs used by this method are only enabled for some projects and
268 /// buckets. Contact your account team to enable this API.
269 /// </div>
270 ///
271 /// # Parameters
272 /// * `bucket` - the bucket name containing the object. In
273 /// `projects/_/buckets/{bucket_id}` format.
274 /// * `object` - the object name.
275 pub fn open_object<B, O>(&self, bucket: B, object: O) -> OpenObject<S>
276 where
277 B: Into<String>,
278 O: Into<String>,
279 {
280 OpenObject::new(self.stub.clone(), bucket, object, self.options.clone())
281 }
282
283 #[cfg(google_cloud_unstable_storage_bidi)]
284 #[cfg_attr(docsrs, doc(cfg(feature = "unstable-stream")))]
285 /// Opens a new appendable object for exclusive appends.
286 ///
287 /// This method allows you to incrementally append data to a single object.
288 ///
289 /// # Example
290 /// ```
291 /// # use google_cloud_storage::client::Storage;
292 /// # async fn sample(client: &Storage) -> anyhow::Result<()> {
293 /// let mut writer = client
294 /// .open_appendable_object("projects/_/buckets/my-bucket", "my-object")
295 /// .send()
296 /// .await?;
297 ///
298 /// writer.append("hello ").await?;
299 /// writer.append("world").await?;
300 /// writer.flush().await?;
301 ///
302 /// let object = writer.finalize().await?;
303 /// println!("Finalized object size: {:?}", object.size);
304 /// # Ok(()) }
305 /// ```
306 ///
307 /// # Parameters
308 /// * `bucket` - the bucket name containing the object. In
309 /// `projects/_/buckets/{bucket_id}` format.
310 /// * `object` - the object name.
311 pub fn open_appendable_object<B, O>(&self, bucket: B, object: O) -> OpenAppendableObject<S>
312 where
313 B: Into<String>,
314 O: Into<String>,
315 {
316 OpenAppendableObject::new(self.stub.clone(), bucket, object, self.options.clone())
317 }
318
319 #[cfg(google_cloud_unstable_storage_bidi)]
320 #[cfg_attr(docsrs, doc(cfg(feature = "unstable-stream")))]
321 /// Reopens an existing appendable object for exclusive appends.
322 ///
323 /// # Example
324 /// ```
325 /// # use google_cloud_storage::client::Storage;
326 /// # async fn sample(client: &Storage) -> anyhow::Result<()> {
327 /// let mut writer = client
328 /// .reopen_appendable_object("projects/_/buckets/my-bucket", "my-object", 12345)
329 /// .send()
330 /// .await?;
331 ///
332 /// writer.append("more bytes").await?;
333 /// writer.flush().await?;
334 /// # Ok(()) }
335 /// ```
336 ///
337 /// # Parameters
338 /// * `bucket` - the bucket name containing the object. In
339 /// `projects/_/buckets/{bucket_id}` format.
340 /// * `object` - the object name.
341 /// * `generation` - the object generation.
342 pub fn reopen_appendable_object<B, O>(
343 &self,
344 bucket: B,
345 object: O,
346 generation: i64,
347 ) -> ReopenAppendableObject<S>
348 where
349 B: Into<String>,
350 O: Into<String>,
351 {
352 ReopenAppendableObject::new(
353 self.stub.clone(),
354 bucket,
355 object,
356 generation,
357 self.options.clone(),
358 )
359 }
360}
361
362impl Storage {
363 pub(crate) async fn new(builder: ClientBuilder) -> BuilderResult<Self> {
364 let tracing = builder.config.tracing;
365 let inner = StorageInner::from_parts(builder).await?;
366 let options = inner.options.clone();
367 let stub = crate::storage::transport::Storage::new(Arc::new(inner), tracing);
368 Ok(Self { stub, options })
369 }
370}
371
372impl StorageInner {
373 /// Builds a client assuming `config.cred` and `config.endpoint` are initialized, panics otherwise.
374 pub(self) fn new(
375 client: gaxi::http::ReqwestClient,
376 options: RequestOptions,
377 grpc: GrpcClient,
378 ) -> Self {
379 Self {
380 client,
381 options,
382 grpc,
383 }
384 }
385
386 pub(self) async fn from_parts(builder: ClientBuilder) -> BuilderResult<Self> {
387 let (mut config, options) = builder.into_parts()?;
388 config.disable_automatic_decompression = true;
389 config.disable_follow_redirects = true;
390
391 let client = gaxi::http::ReqwestClient::new(config.clone(), super::DEFAULT_HOST).await?;
392 let client = if gaxi::options::tracing_enabled(&config) {
393 client.with_instrumentation(&super::info::INSTRUMENTATION)
394 } else {
395 client
396 };
397 let grpc = if gaxi::options::tracing_enabled(&config) {
398 GrpcClient::new_with_instrumentation(
399 config,
400 super::DEFAULT_HOST,
401 &super::info::INSTRUMENTATION,
402 )
403 .await?
404 } else {
405 GrpcClient::new(config, super::DEFAULT_HOST).await?
406 };
407
408 let inner = StorageInner::new(client, options, grpc);
409 Ok(inner)
410 }
411}
412
413/// A builder for [Storage].
414///
415/// ```
416/// # use google_cloud_storage::client::Storage;
417/// # async fn sample() -> anyhow::Result<()> {
418/// let builder = Storage::builder();
419/// let client = builder
420/// .with_endpoint("https://storage.googleapis.com")
421/// .build()
422/// .await?;
423/// # Ok(()) }
424/// ```
425pub struct ClientBuilder {
426 // Common options for all clients (generated or not).
427 pub(crate) config: ClientConfig,
428 // Specific options for the storage client. `RequestOptions` also requires
429 // these, it makes sense to share them.
430 common_options: CommonOptions,
431}
432
433impl ClientBuilder {
434 pub(crate) fn new() -> Self {
435 let mut config = ClientConfig::default();
436 config.retry_policy = Some(Arc::new(crate::retry_policy::storage_default()));
437 config.backoff_policy = Some(Arc::new(crate::backoff_policy::default()));
438 {
439 let count = std::thread::available_parallelism().ok();
440 config.grpc_subchannel_count = Some(count.map(|x| x.get()).unwrap_or(1));
441 }
442 let common_options = CommonOptions::new();
443 Self {
444 config,
445 common_options,
446 }
447 }
448
449 /// Creates a new client.
450 ///
451 /// # Example
452 /// ```
453 /// # use google_cloud_storage::client::Storage;
454 /// # async fn sample() -> anyhow::Result<()> {
455 /// let client = Storage::builder().build().await?;
456 /// # Ok(()) }
457 /// ```
458 pub async fn build(self) -> BuilderResult<Storage> {
459 Storage::new(self).await
460 }
461
462 /// Sets the endpoint.
463 ///
464 /// # Example
465 /// ```
466 /// # use google_cloud_storage::client::Storage;
467 /// # async fn sample() -> anyhow::Result<()> {
468 /// let client = Storage::builder()
469 /// .with_endpoint("https://private.googleapis.com")
470 /// .build()
471 /// .await?;
472 /// # Ok(()) }
473 /// ```
474 pub fn with_endpoint<V: Into<String>>(mut self, v: V) -> Self {
475 self.config.endpoint = Some(v.into());
476 self
477 }
478
479 /// Configure the universe domain.
480 ///
481 /// The universe domain is the default service domain for a given cloud universe.
482 /// The default value is "googleapis.com".
483 ///
484 /// # Example
485 /// ```
486 /// # use google_cloud_storage::client::Storage;
487 /// # async fn sample() -> anyhow::Result<()> {
488 /// let client = Storage::builder()
489 /// .with_universe_domain("googleapis.com")
490 /// .build()
491 /// .await?;
492 /// # Ok(()) }
493 /// ```
494 pub fn with_universe_domain<V: Into<String>>(mut self, v: V) -> Self {
495 self.config.universe_domain = Some(v.into());
496 self
497 }
498
499 /// Configures the authentication credentials.
500 ///
501 /// Google Cloud Storage requires authentication for most buckets. Use this
502 /// method to change the credentials used by the client. More information
503 /// about valid credentials types can be found in the [google-cloud-auth]
504 /// crate documentation.
505 ///
506 /// # Example
507 /// ```
508 /// # use google_cloud_storage::client::Storage;
509 /// # async fn sample() -> anyhow::Result<()> {
510 /// use google_cloud_auth::credentials::mds;
511 /// let client = Storage::builder()
512 /// .with_credentials(
513 /// mds::Builder::default()
514 /// .with_scopes(["https://www.googleapis.com/auth/cloud-platform.read-only"])
515 /// .build()?)
516 /// .build()
517 /// .await?;
518 /// # Ok(()) }
519 /// ```
520 ///
521 /// [google-cloud-auth]: https://docs.rs/google-cloud-auth
522 pub fn with_credentials<V: Into<Credentials>>(mut self, v: V) -> Self {
523 self.config.cred = Some(v.into());
524 self
525 }
526
527 /// Configure the retry policy.
528 ///
529 /// The client libraries can automatically retry operations that fail. The
530 /// retry policy controls what errors are considered retryable, sets limits
531 /// on the number of attempts or the time trying to make attempts.
532 ///
533 /// # Example
534 /// ```
535 /// # use google_cloud_storage::client::Storage;
536 /// # async fn sample() -> anyhow::Result<()> {
537 /// use google_cloud_gax::retry_policy::{AlwaysRetry, RetryPolicyExt};
538 /// let client = Storage::builder()
539 /// .with_retry_policy(AlwaysRetry.with_attempt_limit(3))
540 /// .build()
541 /// .await?;
542 /// # Ok(()) }
543 /// ```
544 pub fn with_retry_policy<V: Into<google_cloud_gax::retry_policy::RetryPolicyArg>>(
545 mut self,
546 v: V,
547 ) -> Self {
548 self.config.retry_policy = Some(v.into().into());
549 self
550 }
551
552 /// Configure the retry backoff policy.
553 ///
554 /// The client libraries can automatically retry operations that fail. The
555 /// backoff policy controls how long to wait in between retry attempts.
556 ///
557 /// # Example
558 /// ```
559 /// # use google_cloud_storage::client::Storage;
560 /// # async fn sample() -> anyhow::Result<()> {
561 /// use google_cloud_gax::exponential_backoff::ExponentialBackoff;
562 /// use std::time::Duration;
563 /// let policy = ExponentialBackoff::default();
564 /// let client = Storage::builder()
565 /// .with_backoff_policy(policy)
566 /// .build()
567 /// .await?;
568 /// # Ok(()) }
569 /// ```
570 pub fn with_backoff_policy<V: Into<google_cloud_gax::backoff_policy::BackoffPolicyArg>>(
571 mut self,
572 v: V,
573 ) -> Self {
574 self.config.backoff_policy = Some(v.into().into());
575 self
576 }
577
578 /// Configure the retry throttler.
579 ///
580 /// Advanced applications may want to configure a retry throttler to
581 /// [Address Cascading Failures] and when [Handling Overload] conditions.
582 /// The client libraries throttle their retry loop, using a policy to
583 /// control the throttling algorithm. Use this method to fine tune or
584 /// customize the default retry throtler.
585 ///
586 /// [Handling Overload]: https://sre.google/sre-book/handling-overload/
587 /// [Address Cascading Failures]: https://sre.google/sre-book/addressing-cascading-failures/
588 ///
589 /// # Example
590 /// ```
591 /// # use google_cloud_storage::client::Storage;
592 /// # async fn sample() -> anyhow::Result<()> {
593 /// use google_cloud_gax::retry_throttler::AdaptiveThrottler;
594 /// let client = Storage::builder()
595 /// .with_retry_throttler(AdaptiveThrottler::default())
596 /// .build()
597 /// .await?;
598 /// # Ok(()) }
599 /// ```
600 pub fn with_retry_throttler<V: Into<google_cloud_gax::retry_throttler::RetryThrottlerArg>>(
601 mut self,
602 v: V,
603 ) -> Self {
604 self.config.retry_throttler = v.into().into();
605 self
606 }
607
608 /// Sets the payload size threshold to switch from single-shot to resumable uploads.
609 ///
610 /// # Example
611 /// ```
612 /// # use google_cloud_storage::client::Storage;
613 /// # async fn sample() -> anyhow::Result<()> {
614 /// let client = Storage::builder()
615 /// .with_resumable_upload_threshold(0_usize) // Forces a resumable upload.
616 /// .build()
617 /// .await?;
618 /// let response = client
619 /// .write_object("projects/_/buckets/my-bucket", "my-object", "hello world")
620 /// .send_buffered()
621 /// .await?;
622 /// println!("response details={response:?}");
623 /// # Ok(()) }
624 /// ```
625 ///
626 /// The client library can write objects using [single-shot] or [resumable]
627 /// uploads. For small objects, single-shot uploads offer better
628 /// performance, as they require a single HTTP transfer. For larger objects,
629 /// the additional request latency is not significant, and resumable uploads
630 /// offer better recovery on errors.
631 ///
632 /// The library automatically selects resumable uploads when the payload is
633 /// equal to or larger than this option. For smaller writes the client
634 /// library uses single-shot uploads.
635 ///
636 /// The exact threshold depends on where the application is deployed and
637 /// destination bucket location with respect to where the application is
638 /// running. The library defaults should work well in most cases, but some
639 /// applications may benefit from fine-tuning.
640 ///
641 /// [single-shot]: https://cloud.google.com/storage/docs/uploading-objects
642 /// [resumable]: https://cloud.google.com/storage/docs/resumable-uploads
643 pub fn with_resumable_upload_threshold<V: Into<usize>>(mut self, v: V) -> Self {
644 self.common_options.resumable_upload_threshold = v.into();
645 self
646 }
647
648 /// Changes the buffer size for some resumable uploads.
649 ///
650 /// # Example
651 /// ```
652 /// # use google_cloud_storage::client::Storage;
653 /// # async fn sample() -> anyhow::Result<()> {
654 /// let client = Storage::builder()
655 /// .with_resumable_upload_buffer_size(32 * 1024 * 1024_usize)
656 /// .build()
657 /// .await?;
658 /// let response = client
659 /// .write_object("projects/_/buckets/my-bucket", "my-object", "hello world")
660 /// .send_buffered()
661 /// .await?;
662 /// println!("response details={response:?}");
663 /// # Ok(()) }
664 /// ```
665 ///
666 /// When performing [resumable uploads] from sources without [Seek] the
667 /// client library needs to buffer data in memory until it is persisted by
668 /// the service. Otherwise the data would be lost if the upload is
669 /// interrupted. Applications may want to tune this buffer size:
670 ///
671 /// - Use smaller buffer sizes to support more concurrent writes in the
672 /// same application.
673 /// - Use larger buffer sizes for better throughput. Sending many small
674 /// buffers stalls the writer until the client receives a successful
675 /// response from the service.
676 ///
677 /// Keep in mind that there are diminishing returns on using larger buffers.
678 ///
679 /// [resumable uploads]: https://cloud.google.com/storage/docs/resumable-uploads
680 /// [Seek]: crate::streaming_source::Seek
681 pub fn with_resumable_upload_buffer_size<V: Into<usize>>(mut self, v: V) -> Self {
682 self.common_options.resumable_upload_buffer_size = v.into();
683 self
684 }
685
686 /// Configure the resume policy for object reads.
687 ///
688 /// The Cloud Storage client library can automatically resume a read request
689 /// that is interrupted by a transient error. Applications may want to
690 /// limit the number of read attempts, or may wish to expand the type
691 /// of errors treated as retryable.
692 ///
693 /// # Example
694 /// ```
695 /// # use google_cloud_storage::client::Storage;
696 /// # async fn sample() -> anyhow::Result<()> {
697 /// use google_cloud_storage::read_resume_policy::{AlwaysResume, ReadResumePolicyExt};
698 /// let client = Storage::builder()
699 /// .with_read_resume_policy(AlwaysResume.with_attempt_limit(3))
700 /// .build()
701 /// .await?;
702 /// # Ok(()) }
703 /// ```
704 pub fn with_read_resume_policy<V>(mut self, v: V) -> Self
705 where
706 V: ReadResumePolicy + 'static,
707 {
708 self.common_options.read_resume_policy = Arc::new(v);
709 self
710 }
711
712 /// Configure the number of subchannels used by the client.
713 ///
714 /// # Example
715 /// ```
716 /// # use google_cloud_storage::client::Storage;
717 /// # async fn sample() -> anyhow::Result<()> {
718 /// // By default the client uses `count` subchannels.
719 /// let count = std::thread::available_parallelism()?.get();
720 /// let client = Storage::builder()
721 /// .with_grpc_subchannel_count(std::cmp::max(1, count / 2))
722 /// .build()
723 /// .await?;
724 /// # Ok(()) }
725 /// ```
726 ///
727 /// gRPC-based clients may exhibit high latency if many requests need to be
728 /// demuxed over a single HTTP/2 connection (often called a *subchannel* in gRPC).
729 /// Consider using more subchannels if your application makes many
730 /// concurrent requests. Consider using fewer subchannels if your
731 /// application needs the file descriptors for other purposes.
732 ///
733 /// Keep in mind that Google Cloud limits the number of concurrent RPCs in
734 /// a single connection to about 100.
735 pub fn with_grpc_subchannel_count(mut self, v: usize) -> Self {
736 self.config.grpc_subchannel_count = Some(v);
737 self
738 }
739
740 /// Enables observability signals for the client.
741 ///
742 /// # Example
743 /// ```
744 /// # use google_cloud_storage::client::Storage;
745 /// # async fn sample() -> anyhow::Result<()> {
746 /// let client = Storage::builder()
747 /// .with_tracing()
748 /// .build()
749 /// .await?;
750 /// // For observing traces and logs, you must also enable a tracing subscriber in your `main` function,
751 /// // for example:
752 /// // tracing_subscriber::fmt::init();
753 /// // For observing metrics, you must also install an OpenTelemetry meter provider in your `main` function,
754 /// // for example:
755 /// // opentelemetry::global::set_meter_provider(provider.clone());
756 /// # Ok(()) }
757 /// ```
758 ///
759 /// <div class="warning">
760 ///
761 /// Observability signals at any level may contain sensitive data such as resource names (bucket
762 /// and object names), full URLs, and error messages.
763 ///
764 /// Before configuring subscribers or exporters for traces and logs, review the contents of the
765 /// spans and consult the [tracing] framework documentation to set up filters and formatters to
766 /// prevent leaking sensitive information, depending on your intended use case.
767 ///
768 /// [OpenTelemetry Semantic Conventions]: https://opentelemetry.io/docs/concepts/semantic-conventions/
769 /// [tracing]: https://docs.rs/tracing/latest/tracing/
770 ///
771 /// </div>
772 ///
773 /// The libraries are instrumented to generate the following signals:
774 ///
775 /// 1. `INFO` spans for each logical client request. Typically a single method call in the client
776 /// struct gets such a span.
777 /// 1. A histogram metric measuring the elapsed time for each logical client request.
778 /// 1. `WARN` logs for each logical client requests that fail.
779 /// 1. `INFO` spans for each low-level attempt RPC attempt. Typically a single method in the client
780 /// struct gets one such span, but there may be more if the library had to retry the RPC.
781 /// 1. `DEBUG` logs for each low-level attempt that fails.
782 ///
783 /// These spans and logs follow [OpenTelemetry Semantic Conventions] with additional Google
784 /// Cloud attributes. Both the spans and logs and are should be suitable for production
785 /// monitoring.
786 ///
787 /// The libraries also have `DEBUG` spans for each request, these include the full request body,
788 /// and the full response body for successful requests, and the full error message, with
789 /// details, for failed requests. Consider the contents of these requests and responses before
790 /// enabling them in production environments, as the request or responses may include sensitive
791 /// data. These `DEBUG` spans use the `google_cloud_storage::tracing` as their target and the
792 /// method name as the span name. You can use the name and/or target to set up your filters.
793 ///
794 /// # More information
795 ///
796 /// The [Enable logging] guide shows you how to initialize a subscriber to
797 /// log events to the console.
798 ///
799 /// [Enable logging]: https://docs.cloud.google.com/rust/enable-logging
800 /// [tracing]: https://docs.rs/tracing
801 pub fn with_tracing(mut self) -> Self {
802 self.config.tracing = true;
803 self
804 }
805
806 /// Injects a global custom header for all HTTP and gRPC requests made by this client.
807 ///
808 /// Global custom headers serve as client-wide defaults. To configure headers for a single
809 /// request, use [`RequestOptionsBuilder::with_custom_header`](google_cloud_gax::options::RequestOptionsBuilder::with_custom_header)
810 /// instead. Request-level headers override global headers when keys conflict.
811 /// Like request-level headers, global headers cannot overwrite reserved system headers.
812 ///
813 /// # Example
814 /// ```
815 /// # use google_cloud_storage::client::Storage;
816 /// # async fn sample() -> anyhow::Result<()> {
817 /// use http::header::{HeaderName, HeaderValue};
818 ///
819 /// let client = Storage::builder()
820 /// .with_custom_header(
821 /// HeaderName::from_static("x-custom-client-id"),
822 /// HeaderValue::from_static("my-app-v1"),
823 /// )
824 /// .build()
825 /// .await?;
826 /// # Ok(()) }
827 /// ```
828 ///
829 /// ### Repeated Headers
830 ///
831 /// Under HTTP RFC 9110 (Section 5.3), standard repeated headers (e.g. `Cache-Control`, `Accept`, or `Allow`)
832 /// are defined as comma-separated lists. Callers can supply repeated values natively as a single
833 /// comma-separated [`HeaderValue`]:
834 ///
835 /// ```
836 /// # use google_cloud_storage::client::Storage;
837 /// # async fn sample() -> anyhow::Result<()> {
838 /// use http::header::{HeaderName, HeaderValue};
839 ///
840 /// let client = Storage::builder()
841 /// .with_custom_header(
842 /// HeaderName::from_static("cache-control"),
843 /// HeaderValue::from_static("no-cache, no-store"),
844 /// )
845 /// .build()
846 /// .await?;
847 /// # Ok(()) }
848 /// ```
849 ///
850 /// [`HeaderValue`]: http::header::HeaderValue
851 pub fn with_custom_header(
852 mut self,
853 name: http::header::HeaderName,
854 value: http::header::HeaderValue,
855 ) -> Self {
856 let mut headers = self
857 .config
858 .extensions
859 .get::<http::HeaderMap>()
860 .cloned()
861 .unwrap_or_default();
862 headers.insert(name, value);
863 self.config.extensions.insert(headers);
864 self
865 }
866
867 pub(crate) fn apply_default_credentials(&mut self) -> BuilderResult<()> {
868 if self.config.cred.is_some() {
869 return Ok(());
870 };
871 let default = CredentialsBuilder::default()
872 .build()
873 .map_err(BuilderError::cred)?;
874 self.config.cred = Some(default);
875 Ok(())
876 }
877
878 pub(crate) fn apply_default_endpoint(&mut self) -> BuilderResult<()> {
879 let _ = self
880 .config
881 .endpoint
882 .get_or_insert_with(|| super::DEFAULT_HOST.to_string());
883 Ok(())
884 }
885
886 // Breaks the builder into its parts, with defaults applied.
887 pub(crate) fn into_parts(
888 mut self,
889 ) -> google_cloud_gax::client_builder::Result<(ClientConfig, RequestOptions)> {
890 self.apply_default_credentials()?;
891 self.apply_default_endpoint()?;
892 let request_options =
893 RequestOptions::new_with_client_config(&self.config, self.common_options);
894 Ok((self.config, request_options))
895 }
896}
897
898/// The set of characters to percent-encode.
899///
900/// We encode everything except RFC 3986 [unreserved]
901/// characters (`ALPHA`, `DIGIT`, `-`, `.`, `_`, `~`).
902///
903/// Encoding `%`, `\`, and other special ASCII characters prevents the service
904/// from decoding `%XX` sequences in object names and keeps URL parsers and HTTP
905/// clients from rewriting the path.
906///
907/// [unreserved]: https://datatracker.ietf.org/doc/html/rfc3986#section-2.3
908pub(crate) const ENCODED_CHARS: percent_encoding::AsciiSet = percent_encoding::NON_ALPHANUMERIC
909 .remove(b'-')
910 .remove(b'.')
911 .remove(b'_')
912 .remove(b'~');
913
914/// Percent-encodes a string using [`ENCODED_CHARS`].
915pub(crate) fn enc(value: &str) -> String {
916 percent_encoding::utf8_percent_encode(value, &ENCODED_CHARS).to_string()
917}
918
919pub(crate) fn apply_customer_supplied_encryption_headers(
920 builder: HttpRequestBuilder,
921 common_object_request_params: &Option<crate::model::CommonObjectRequestParams>,
922) -> HttpRequestBuilder {
923 common_object_request_params.iter().fold(builder, |b, v| {
924 b.header(
925 "x-goog-encryption-algorithm",
926 v.encryption_algorithm.clone(),
927 )
928 .header(
929 "x-goog-encryption-key",
930 BASE64_STANDARD.encode(v.encryption_key_bytes.clone()),
931 )
932 .header(
933 "x-goog-encryption-key-sha256",
934 BASE64_STANDARD.encode(v.encryption_key_sha256_bytes.clone()),
935 )
936 })
937}
938
939#[cfg(test)]
940pub(crate) mod tests {
941 use super::*;
942 use google_cloud_auth::credentials::anonymous::Builder as Anonymous;
943 use google_cloud_gax::retry_result::RetryResult;
944 use google_cloud_gax::retry_state::RetryState;
945 use pretty_assertions::assert_eq;
946 use std::{sync::Arc, time::Duration};
947
948 #[test]
949 fn default_settings() {
950 let builder = ClientBuilder::new().with_credentials(Anonymous::new().build());
951 let config = builder.config;
952 assert!(config.retry_policy.is_some(), "{config:?}");
953 assert!(config.backoff_policy.is_some(), "{config:?}");
954 {
955 assert!(
956 config.grpc_subchannel_count.is_some_and(|v| v >= 1),
957 "{config:?}"
958 );
959 }
960 }
961
962 #[test]
963 fn subchannel_count() {
964 let builder = ClientBuilder::new()
965 .with_credentials(Anonymous::new().build())
966 .with_grpc_subchannel_count(42);
967 let config = builder.config;
968 assert!(
969 config.grpc_subchannel_count.is_some_and(|v| v == 42),
970 "{config:?}"
971 );
972 }
973
974 #[test]
975 fn universe_domain() {
976 let builder = ClientBuilder::new()
977 .with_credentials(Anonymous::new().build())
978 .with_universe_domain("my-universe.com");
979 let config = builder.config;
980 assert_eq!(
981 config.universe_domain.as_deref(),
982 Some("my-universe.com"),
983 "{config:?}"
984 );
985 }
986
987 #[derive(Debug)]
988 struct DummyStorage;
989
990 impl crate::storage::stub::Storage for DummyStorage {}
991
992 #[test]
993 fn from_stub_accepts_both_raw_and_arc() {
994 let stub = DummyStorage;
995 let _client = Storage::<DummyStorage>::from_stub(stub);
996
997 let stub_arc = std::sync::Arc::new(DummyStorage);
998 let _client_arc = Storage::<DummyStorage>::from_stub(stub_arc);
999 }
1000
1001 #[test]
1002 fn test_client_builder_with_custom_header() {
1003 use http::header::{HeaderName, HeaderValue};
1004 let name = HeaderName::from_static("x-custom-global");
1005 let value = HeaderValue::from_static("global-value");
1006 let builder = ClientBuilder::new()
1007 .with_credentials(Anonymous::new().build())
1008 .with_custom_header(name.clone(), value.clone());
1009 let headers = builder.config.extensions.get::<http::HeaderMap>().unwrap();
1010 assert_eq!(headers.get(&name).unwrap(), &value);
1011 }
1012
1013 #[test]
1014 fn from_stub_allows_sharing_stub() {
1015 let stub_arc = std::sync::Arc::new(DummyStorage);
1016
1017 let _client1 = Storage::<DummyStorage>::from_stub(stub_arc.clone());
1018 let _client2 = Storage::<DummyStorage>::from_stub(stub_arc);
1019 }
1020
1021 pub(crate) fn test_builder() -> ClientBuilder {
1022 ClientBuilder::new()
1023 .with_credentials(Anonymous::new().build())
1024 .with_endpoint("http://private.googleapis.com")
1025 .with_universe_domain("googleapis.com")
1026 .with_backoff_policy(
1027 google_cloud_gax::exponential_backoff::ExponentialBackoffBuilder::new()
1028 .with_initial_delay(Duration::from_millis(1))
1029 .with_maximum_delay(Duration::from_millis(2))
1030 .build()
1031 .expect("hard coded policy should build correctly"),
1032 )
1033 }
1034
1035 /// This is used by the request builder tests.
1036 pub(crate) async fn test_inner_client(builder: ClientBuilder) -> Arc<StorageInner> {
1037 let inner = StorageInner::from_parts(builder)
1038 .await
1039 .expect("creating an test inner client succeeds");
1040 Arc::new(inner)
1041 }
1042
1043 mockall::mock! {
1044 #[derive(Debug)]
1045 pub RetryThrottler {}
1046
1047 impl google_cloud_gax::retry_throttler::RetryThrottler for RetryThrottler {
1048 fn throttle_retry_attempt(&self) -> bool;
1049 fn on_retry_failure(&mut self, flow: &RetryResult);
1050 fn on_success(&mut self);
1051 }
1052 }
1053
1054 mockall::mock! {
1055 #[derive(Debug)]
1056 pub RetryPolicy {}
1057
1058 impl google_cloud_gax::retry_policy::RetryPolicy for RetryPolicy {
1059 fn on_error(&self, state: &RetryState, error: google_cloud_gax::error::Error) -> RetryResult;
1060 }
1061 }
1062
1063 mockall::mock! {
1064 #[derive(Debug)]
1065 pub BackoffPolicy {}
1066
1067 impl google_cloud_gax::backoff_policy::BackoffPolicy for BackoffPolicy {
1068 fn on_failure(&self, state: &RetryState) -> std::time::Duration;
1069 }
1070 }
1071
1072 mockall::mock! {
1073 #[derive(Debug)]
1074 pub ReadResumePolicy {}
1075
1076 impl crate::read_resume_policy::ReadResumePolicy for ReadResumePolicy {
1077 fn on_error(&self, query: &crate::read_resume_policy::ResumeQuery, error: google_cloud_gax::error::Error) -> crate::read_resume_policy::ResumeResult;
1078 }
1079 }
1080
1081 #[test]
1082 fn enc_only_keeps_unreserved_ascii() {
1083 // Arrange
1084 let input: String = (0_u8..=0x7F).map(char::from).collect();
1085 let want: String = (0_u8..=0x7F)
1086 .map(|b| {
1087 if b.is_ascii_alphanumeric() || b"-._~".contains(&b) {
1088 char::from(b).to_string()
1089 } else {
1090 format!("%{b:02X}")
1091 }
1092 })
1093 .collect();
1094 // Act
1095 let got = enc(&input);
1096 // Assert
1097 assert_eq!(got, want);
1098 }
1099
1100 #[test]
1101 fn enc_non_ascii_as_utf8() {
1102 // Arrange
1103 let input = "test-\u{e9} \u{1F600}";
1104 // Act
1105 let got = enc(input);
1106 // Assert
1107 assert_eq!(got, "test-%C3%A9%20%F0%9F%98%80");
1108 }
1109}