google-cloud-gax 1.9.1

Google Cloud Client Libraries for Rust
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
// Copyright 2025 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

//! Provide types for client construction.
//!
//! Some applications need to construct clients with custom configuration, for
//! example, they may need to override the endpoint or the authentication
//! credentials. The Google Cloud client libraries for Rust use a generic
//! builder type to provide such functionality. The types in this module
//! implement the client builders.
//!
//! Applications should not create builders directly, instead each client type
//! defines a `builder()` function to obtain the correct type of builder.
//!
//! ## Example: create a client with the default configuration.
//!
//! ```
//! # use google_cloud_gax::client_builder::examples;
//! # use google_cloud_gax::client_builder::Result;
//! # async fn sample() -> anyhow::Result<()> {
//! pub use examples::Client; // Placeholder for examples
//! let client = Client::builder().build().await?;
//! # Ok(()) }
//! ```
//!
//! ## Example: create a client with a different endpoint
//!
//! ```
//! # use google_cloud_gax::client_builder::examples;
//! # use google_cloud_gax::client_builder::Result;
//! # async fn sample() -> anyhow::Result<()> {
//! pub use examples::Client; // Placeholder for examples
//! let client = Client::builder()
//!     .with_endpoint("https://private.googleapis.com")
//!     .build().await?;
//! # Ok(()) }
//! ```

use crate::backoff_policy::{BackoffPolicy, BackoffPolicyArg};
use crate::polling_backoff_policy::{PollingBackoffPolicy, PollingBackoffPolicyArg};
use crate::polling_error_policy::{PollingErrorPolicy, PollingErrorPolicyArg};
use crate::retry_policy::{RetryPolicy, RetryPolicyArg};
use crate::retry_throttler::{RetryThrottlerArg, SharedRetryThrottler};
use std::sync::Arc;

/// The result type for this module.
pub type Result<T> = std::result::Result<T, Error>;

/// Indicates a problem while constructing a client.
///
/// # Examples
/// ```
/// # use google_cloud_gax::client_builder::examples;
/// use google_cloud_gax::client_builder::Error as Error;
/// use examples::Client; // Placeholder for examples
/// # async fn sample() -> Result<(), Error> {
/// let client = match Client::builder().build().await {
///     Ok(c) => c,
///     Err(e) if e.is_default_credentials() => {
///         println!("error during client initialization: {e}");
///         println!("troubleshoot using https://cloud.google.com/docs/authentication/client-libraries");
///         return Err(e);
///     }
///     Err(e) => {
///         println!("error during client initialization {e}");
///         return Err(e);
///     }
/// };
/// # Ok(()) }
/// ```
#[derive(thiserror::Error, Debug)]
#[error(transparent)]
pub struct Error(ErrorKind);

impl Error {
    /// If true, the client could not initialize the default credentials.
    pub fn is_default_credentials(&self) -> bool {
        matches!(&self.0, ErrorKind::DefaultCredentials(_))
    }

    /// If true, the client could not initialize the transport client.
    pub fn is_transport(&self) -> bool {
        matches!(&self.0, ErrorKind::Transport(_))
    }

    /// Not part of the public API, subject to change without notice.
    #[cfg_attr(not(feature = "_internal-semver"), doc(hidden))]
    pub fn cred<T: Into<BoxError>>(source: T) -> Self {
        Self(ErrorKind::DefaultCredentials(source.into()))
    }

    /// Not part of the public API, subject to change without notice.
    #[cfg_attr(not(feature = "_internal-semver"), doc(hidden))]
    pub fn transport<T: Into<BoxError>>(source: T) -> Self {
        Self(ErrorKind::Transport(source.into()))
    }
}

#[derive(thiserror::Error, Debug)]
enum ErrorKind {
    #[error("could not create default credentials")]
    DefaultCredentials(#[source] BoxError),
    #[error("could not initialize transport client")]
    Transport(#[source] BoxError),
}

type BoxError = Box<dyn std::error::Error + Send + Sync + 'static>;

/// A generic builder for clients.
///
/// In the Google Cloud client libraries for Rust a "client" represents a
/// connection to a specific service. Each client library defines one or more
/// client types. All the clients are initialized using a `ClientBuilder`.
///
/// Applications obtain a builder with the correct generic types using the
/// `builder()` method on each client:
/// ```
/// # use google_cloud_gax::client_builder::examples;
/// # use google_cloud_gax::client_builder::Result;
/// # async fn sample() -> anyhow::Result<()> {
/// use examples::Client; // Placeholder for examples
/// let builder = Client::builder();
/// # Ok(()) }
/// ```
///
/// To create a client with the default configuration just invoke the
/// `.build()` method:
/// ```
/// # use google_cloud_gax::client_builder::examples;
/// # use google_cloud_gax::client_builder::Result;
/// # async fn sample() -> anyhow::Result<()> {
/// use examples::Client; // Placeholder for examples
/// let client = Client::builder().build().await?;
/// # Ok(()) }
/// ```
///
/// As usual, the builder offers several method to configure the client, and a
/// `.build()` method to construct the client:
/// ```
/// # use google_cloud_gax::client_builder::examples;
/// # use google_cloud_gax::client_builder::Result;
/// # async fn sample() -> anyhow::Result<()> {
/// use examples::Client; // Placeholder for examples
/// let client = Client::builder()
///     .with_endpoint("http://private.googleapis.com")
///     .build().await?;
/// # Ok(()) }
/// ```
#[derive(Clone, Debug)]
pub struct ClientBuilder<F, Cr> {
    config: internal::ClientConfig<Cr>,
    factory: F,
}

impl<F, Cr> ClientBuilder<F, Cr> {
    /// Creates a new client.
    ///
    /// ```
    /// # use google_cloud_gax::client_builder::examples;
    /// # use google_cloud_gax::client_builder::Result;
    /// # async fn sample() -> anyhow::Result<()> {
    /// use examples::Client; // Placeholder for examples
    /// let client = Client::builder()
    ///     .build().await?;
    /// # Ok(()) }
    /// ```
    pub async fn build<C>(self) -> Result<C>
    where
        F: internal::ClientFactory<Client = C, Credentials = Cr>,
    {
        self.factory.build(self.config).await
    }

    /// Sets the endpoint.
    ///
    /// ```
    /// # use google_cloud_gax::client_builder::examples;
    /// # use google_cloud_gax::client_builder::Result;
    /// # async fn sample() -> anyhow::Result<()> {
    /// use examples::Client; // Placeholder for examples
    /// let client = Client::builder()
    ///     .with_endpoint("http://private.googleapis.com")
    ///     .build().await?;
    /// # Ok(()) }
    /// ```
    pub fn with_endpoint<V: Into<String>>(mut self, v: V) -> Self {
        self.config.endpoint = Some(v.into());
        self
    }

    /// Enables observability signals for the client.
    ///
    /// # Example
    /// ```
    /// # use google_cloud_gax::client_builder::examples;
    /// # use google_cloud_gax::client_builder::Result;
    /// # async fn sample() -> anyhow::Result<()> {
    /// use examples::Client; // Placeholder for examples
    /// let client = Client::builder()
    ///     .with_tracing()
    ///     .build().await?;
    /// // For observing traces and logs, you must also enable a tracing subscriber in your `main` function,
    /// // for example:
    /// //     tracing_subscriber::fmt::init();
    /// // For observing metrics, you must also install an OpenTelemetry meter provider in your `main` function,
    /// // for example:
    /// //     opentelemetry::global::set_meter_provider(provider.clone());
    /// # Ok(()) }
    /// ```
    ///
    /// <div class="warning">
    ///
    /// Observability signals at any level may contain sensitive data such as resource names, full
    /// URLs, and error messages.
    ///
    /// Before configuring subscribers or exporters for traces and logs, review the contents of the
    /// spans and consult the [tracing] framework documentation to set up filters and formatters to
    /// prevent leaking sensitive information, depending on your intended use case.
    ///
    /// [OpenTelemetry Semantic Conventions]: https://opentelemetry.io/docs/concepts/semantic-conventions/
    /// [tracing]: https://docs.rs/tracing/latest/tracing/
    ///
    /// </div>
    ///
    /// The libraries are instrumented to generate the following signals:
    ///
    /// 1. `INFO` spans for each logical client request. Typically a single method call in the client
    ///    struct gets such a span.
    /// 1. A histogram metric measuring the elapsed time for each logical client request.
    /// 1. `WARN` logs for each logical client requests that fail.
    /// 1. `INFO` spans for each low-level attempt RPC attempt. Typically a single method in the client
    ///    struct gets one such span, but there may be more if the library had to retry the RPC.
    /// 1. `DEBUG` logs for each low-level attempt that fails.
    ///
    /// These spans and logs follow [OpenTelemetry Semantic Conventions] with additional Google
    /// Cloud attributes. Both the spans and logs and are should be suitable for production
    /// monitoring.
    ///
    /// The libraries also have `DEBUG` spans for each request, these include the full request body,
    /// and the full response body for successful requests, and the full error message, with
    /// details, for failed requests. Consider the contents of these requests and responses before
    /// enabling them in production environments, as the request or responses may include sensitive
    /// data. These `DEBUG` spans use the client library crate followed by `::tracing` as their
    /// target and the method name as the span name. You can use the name and/or target to set up
    /// your filters.
    ///
    /// # More information
    ///
    /// The [Enable logging] guide shows you how to initialize a subscriber to
    /// log events to the console.
    ///
    /// [Enable logging]: https://docs.cloud.google.com/rust/enable-logging
    pub fn with_tracing(mut self) -> Self {
        self.config.tracing = true;
        self
    }

    /// Configure the authentication credentials.
    ///
    /// Most Google Cloud services require authentication, though some services
    /// allow for anonymous access, and some services provide emulators where
    /// no authentication is required. More information about valid credentials
    /// types can be found in the [google-cloud-auth] crate documentation.
    ///
    /// ```
    /// # use google_cloud_gax::client_builder::examples;
    /// # use google_cloud_gax::client_builder::Result;
    /// # async fn sample() -> anyhow::Result<()> {
    /// use examples::Client; // Placeholder for examples
    /// // Placeholder, normally use google_cloud_auth::credentials
    /// use examples::credentials;
    /// let client = Client::builder()
    ///     .with_credentials(
    ///         credentials::mds::Builder::new()
    ///             .scopes(["https://www.googleapis.com/auth/cloud-platform.read-only"])
    ///             .build())
    ///     .build().await?;
    /// # Ok(()) }
    /// ```
    ///
    /// [google-cloud-auth]: https://docs.rs/google-cloud-auth
    pub fn with_credentials<T: Into<Cr>>(mut self, v: T) -> Self {
        self.config.cred = Some(v.into());
        self
    }

    /// Configure the universe domain.
    ///
    /// The universe domain is the default service domain for a given cloud universe.
    /// The default value is "googleapis.com".
    // TODO(#3646): Make this public and let example run when universe domain support is done.
    #[allow(dead_code)]
    pub(crate) fn with_universe_domain<V: Into<String>>(mut self, v: V) -> Self {
        self.config.universe_domain = Some(v.into());
        self
    }

    /// Configure the retry policy.
    ///
    /// The client libraries can automatically retry operations that fail. The
    /// retry policy controls what errors are considered retryable, sets limits
    /// on the number of attempts or the time trying to make attempts.
    ///
    /// ```
    /// # use google_cloud_gax::client_builder::examples;
    /// # use google_cloud_gax as gax;
    /// # use google_cloud_gax::client_builder::Result;
    /// # async fn sample() -> anyhow::Result<()> {
    /// use examples::Client; // Placeholder for examples
    /// use gax::retry_policy::{AlwaysRetry, RetryPolicyExt};
    /// let client = Client::builder()
    ///     .with_retry_policy(AlwaysRetry.with_attempt_limit(3))
    ///     .build().await?;
    /// # Ok(()) }
    /// ```
    pub fn with_retry_policy<V: Into<RetryPolicyArg>>(mut self, v: V) -> Self {
        self.config.retry_policy = Some(v.into().into());
        self
    }

    /// Configure the retry backoff policy.
    ///
    /// The client libraries can automatically retry operations that fail. The
    /// backoff policy controls how long to wait in between retry attempts.
    ///
    /// ```
    /// # use google_cloud_gax::client_builder::examples;
    /// # use google_cloud_gax as gax;
    /// # use google_cloud_gax::client_builder::Result;
    /// # async fn sample() -> anyhow::Result<()> {
    /// use examples::Client; // Placeholder for examples
    /// use gax::exponential_backoff::ExponentialBackoff;
    /// use std::time::Duration;
    /// let policy = ExponentialBackoff::default();
    /// let client = Client::builder()
    ///     .with_backoff_policy(policy)
    ///     .build().await?;
    /// # Ok(()) }
    /// ```
    pub fn with_backoff_policy<V: Into<BackoffPolicyArg>>(mut self, v: V) -> Self {
        self.config.backoff_policy = Some(v.into().into());
        self
    }

    /// Configure the retry throttler.
    ///
    /// Advanced applications may want to configure a retry throttler to
    /// [Address Cascading Failures] and when [Handling Overload] conditions.
    /// The client libraries throttle their retry loop, using a policy to
    /// control the throttling algorithm. Use this method to fine tune or
    /// customize the default retry throtler.
    ///
    /// [Handling Overload]: https://sre.google/sre-book/handling-overload/
    /// [Address Cascading Failures]: https://sre.google/sre-book/addressing-cascading-failures/
    ///
    /// ```
    /// # use google_cloud_gax::client_builder::examples;
    /// # use google_cloud_gax as gax;
    /// # use google_cloud_gax::client_builder::Result;
    /// # async fn sample() -> anyhow::Result<()> {
    /// use examples::Client; // Placeholder for examples
    /// use gax::retry_throttler::AdaptiveThrottler;
    /// let client = Client::builder()
    ///     .with_retry_throttler(AdaptiveThrottler::default())
    ///     .build().await?;
    /// # Ok(()) }
    /// ```
    pub fn with_retry_throttler<V: Into<RetryThrottlerArg>>(mut self, v: V) -> Self {
        self.config.retry_throttler = v.into().into();
        self
    }

    /// Configure the polling error policy.
    ///
    /// Some clients support long-running operations, the client libraries can
    /// automatically poll these operations until they complete. Polling may
    /// fail due to transient errors and applications may want to continue the
    /// polling loop despite such errors. The polling error policy controls
    /// which errors are treated as recoverable, and may limit the number
    /// of attempts and/or the total time polling the operation.
    ///
    /// ```
    /// # use google_cloud_gax::client_builder::examples;
    /// # use google_cloud_gax as gax;
    /// # use google_cloud_gax::client_builder::Result;
    /// # async fn sample() -> anyhow::Result<()> {
    /// use examples::Client; // Placeholder for examples
    /// use gax::polling_error_policy::Aip194Strict;
    /// use gax::polling_error_policy::PollingErrorPolicyExt;
    /// use std::time::Duration;
    /// let client = Client::builder()
    ///     .with_polling_error_policy(Aip194Strict
    ///         .with_time_limit(Duration::from_secs(15 * 60))
    ///         .with_attempt_limit(50))
    ///     .build().await?;
    /// # Ok(()) }
    /// ```
    pub fn with_polling_error_policy<V: Into<PollingErrorPolicyArg>>(mut self, v: V) -> Self {
        self.config.polling_error_policy = Some(v.into().0);
        self
    }

    /// Configure the polling backoff policy.
    ///
    /// Some clients support long-running operations, the client libraries can
    /// automatically poll these operations until they complete. The polling
    /// backoff policy controls how long the client waits between polling
    /// attempts.
    ///
    /// ```
    /// # use google_cloud_gax::client_builder::examples;
    /// # use google_cloud_gax as gax;
    /// # use google_cloud_gax::client_builder::Result;
    /// # async fn sample() -> anyhow::Result<()> {
    /// use examples::Client; // Placeholder for examples
    /// use gax::exponential_backoff::ExponentialBackoff;
    /// use std::time::Duration;
    /// let policy = ExponentialBackoff::default();
    /// let client = Client::builder()
    ///     .with_polling_backoff_policy(policy)
    ///     .build().await?;
    /// # Ok(()) }
    /// ```
    pub fn with_polling_backoff_policy<V: Into<PollingBackoffPolicyArg>>(mut self, v: V) -> Self {
        self.config.polling_backoff_policy = Some(v.into().0);
        self
    }
}

#[cfg_attr(not(feature = "_internal-semver"), doc(hidden))]
pub mod internal {
    use super::*;

    pub trait ClientFactory {
        type Client;
        type Credentials;
        fn build(
            self,
            config: internal::ClientConfig<Self::Credentials>,
        ) -> impl Future<Output = Result<Self::Client>>;
    }

    pub fn new_builder<F, Cr, C>(factory: F) -> super::ClientBuilder<F, Cr>
    where
        F: ClientFactory<Client = C, Credentials = Cr>,
    {
        super::ClientBuilder {
            factory,
            config: ClientConfig::default(),
        }
    }

    /// Configure a client.
    ///
    /// A client represents a connection to a Google Cloud Service. Each service
    /// has one or more client types. The default configuration for each client
    /// should work for most applications. But some applications may need to
    /// override the default endpoint, the default authentication credentials,
    /// the retry policies, and/or other behaviors of the client.
    #[derive(Clone, Debug)]
    #[non_exhaustive]
    pub struct ClientConfig<Cr> {
        pub endpoint: Option<String>,
        pub universe_domain: Option<String>,
        pub cred: Option<Cr>,
        pub tracing: bool,
        pub retry_policy: Option<Arc<dyn RetryPolicy>>,
        pub backoff_policy: Option<Arc<dyn BackoffPolicy>>,
        pub retry_throttler: SharedRetryThrottler,
        pub polling_error_policy: Option<Arc<dyn PollingErrorPolicy>>,
        pub polling_backoff_policy: Option<Arc<dyn PollingBackoffPolicy>>,
        pub disable_automatic_decompression: bool,
        pub disable_follow_redirects: bool,
        pub grpc_subchannel_count: Option<usize>,
        pub grpc_request_buffer_capacity: Option<usize>,
        pub grpc_max_header_list_size: Option<u32>,
    }

    impl<Cr> std::default::Default for ClientConfig<Cr> {
        fn default() -> Self {
            use crate::retry_throttler::AdaptiveThrottler;
            use std::sync::{Arc, Mutex};
            Self {
                endpoint: None,
                universe_domain: None,
                cred: None,
                tracing: false,
                retry_policy: None,
                backoff_policy: None,
                retry_throttler: Arc::new(Mutex::new(AdaptiveThrottler::default())),
                polling_error_policy: None,
                polling_backoff_policy: None,
                disable_automatic_decompression: false,
                disable_follow_redirects: false,
                grpc_subchannel_count: None,
                grpc_request_buffer_capacity: None,
                grpc_max_header_list_size: None,
            }
        }
    }

    /// Configure automatic decompression.
    ///
    /// By default, the client libraries automatically decompress responses.
    /// Internal users can disable this behavior if they need to access the raw
    /// compressed bytes.
    pub fn with_automatic_decompression<F, Cr>(
        mut builder: super::ClientBuilder<F, Cr>,
        v: bool,
    ) -> super::ClientBuilder<F, Cr> {
        builder.config.disable_automatic_decompression = !v;
        builder
    }

    /// Configure HTTP redirects.
    ///
    /// By default, the client libraries automatically follow HTTP redirects.
    /// Internal users can disable this behavior if they need to handle redirects
    /// manually (e.g. for 308 Resume Incomplete).
    pub fn with_follow_redirects<F, Cr>(
        mut builder: super::ClientBuilder<F, Cr>,
        v: bool,
    ) -> super::ClientBuilder<F, Cr> {
        builder.config.disable_follow_redirects = !v;
        builder
    }
}

#[doc(hidden)]
pub mod examples {
    //! This module contains helper types used in the rustdoc examples.
    //!
    //! The examples require relatively complex types to be useful.

    type Config = super::internal::ClientConfig<Credentials>;
    use super::Result;

    /// A client type for use in examples.
    ///
    /// This type is used in examples as a placeholder for a real client. It
    /// does not work, but illustrates how to use `ClientBuilder`.
    #[allow(dead_code)]
    pub struct Client(Config);
    impl Client {
        /// Create a builder to initialize new instances of this client.
        pub fn builder() -> client::Builder {
            super::internal::new_builder(client::Factory)
        }

        async fn new(config: super::internal::ClientConfig<Credentials>) -> Result<Self> {
            Ok(Self(config))
        }
    }
    mod client {
        pub type Builder = super::super::ClientBuilder<Factory, super::Credentials>;
        pub struct Factory;
        impl super::super::internal::ClientFactory for Factory {
            type Credentials = super::Credentials;
            type Client = super::Client;
            async fn build(
                self,
                config: crate::client_builder::internal::ClientConfig<Self::Credentials>,
            ) -> super::Result<Self::Client> {
                Self::Client::new(config).await
            }
        }
    }

    #[derive(Clone, Debug, Default, PartialEq)]
    pub struct Credentials {
        pub scopes: Vec<String>,
    }

    pub mod credentials {
        pub mod mds {
            #[derive(Clone, Default)]
            pub struct Builder(super::super::Credentials);
            impl Builder {
                pub fn new() -> Self {
                    Self(super::super::Credentials::default())
                }
                pub fn build(self) -> super::super::Credentials {
                    self.0
                }
                pub fn scopes<I, V>(mut self, iter: I) -> Self
                where
                    I: IntoIterator<Item = V>,
                    V: Into<String>,
                {
                    self.0.scopes = iter.into_iter().map(|v| v.into()).collect();
                    self
                }
            }
        }
    }

    // We use the examples as scaffolding for the tests.
    #[cfg(test)]
    mod tests {
        use super::*;

        #[tokio::test]
        async fn build_default() {
            let client = Client::builder().build().await.unwrap();
            let config = client.0;
            assert_eq!(config.endpoint, None);
            assert_eq!(config.cred, None);
            assert!(!config.tracing);
            assert!(
                format!("{:?}", &config).contains("AdaptiveThrottler"),
                "{config:?}"
            );
            assert!(config.retry_policy.is_none(), "{config:?}");
            assert!(config.backoff_policy.is_none(), "{config:?}");
            assert!(config.polling_error_policy.is_none(), "{config:?}");
            assert!(config.polling_backoff_policy.is_none(), "{config:?}");
            assert!(!config.disable_automatic_decompression, "{config:?}");
            assert!(!config.disable_follow_redirects, "{config:?}");
        }

        #[tokio::test]
        async fn endpoint() {
            let client = Client::builder()
                .with_endpoint("http://example.com")
                .build()
                .await
                .unwrap();
            let config = client.0;
            assert_eq!(config.endpoint.as_deref(), Some("http://example.com"));
        }

        #[tokio::test]
        async fn tracing() {
            let client = Client::builder().with_tracing().build().await.unwrap();
            let config = client.0;
            assert!(config.tracing);
        }

        #[tokio::test]
        async fn automatic_decompression() {
            let client = Client::builder();
            let client = super::super::internal::with_automatic_decompression(client, false)
                .build()
                .await
                .unwrap();
            let config = client.0;
            assert!(config.disable_automatic_decompression);

            let client = Client::builder();
            let client = super::super::internal::with_automatic_decompression(client, true)
                .build()
                .await
                .unwrap();
            let config = client.0;
            assert!(!config.disable_automatic_decompression);
        }

        #[tokio::test]
        async fn follow_redirects() {
            let client = Client::builder();
            let client = super::super::internal::with_follow_redirects(client, false)
                .build()
                .await
                .unwrap();
            let config = client.0;
            assert!(config.disable_follow_redirects);

            let client = Client::builder();
            let client = super::super::internal::with_follow_redirects(client, true)
                .build()
                .await
                .unwrap();
            let config = client.0;
            assert!(!config.disable_follow_redirects);
        }

        #[tokio::test]
        async fn credentials() {
            let client = Client::builder()
                .with_credentials(
                    credentials::mds::Builder::new()
                        .scopes(["test-scope"])
                        .build(),
                )
                .build()
                .await
                .unwrap();
            let config = client.0;
            let cred = config.cred.unwrap();
            assert_eq!(cred.scopes, vec!["test-scope".to_string()]);
        }

        #[tokio::test]
        async fn universe_domain() {
            let client = Client::builder()
                .with_universe_domain("some-universe-domain.com")
                .build()
                .await
                .unwrap();
            let config = client.0;
            assert_eq!(
                config.universe_domain,
                Some("some-universe-domain.com".to_string())
            );
        }

        #[tokio::test]
        async fn retry_policy() {
            use crate::retry_policy::RetryPolicyExt;
            let client = Client::builder()
                .with_retry_policy(crate::retry_policy::AlwaysRetry.with_attempt_limit(3))
                .build()
                .await
                .unwrap();
            let config = client.0;
            assert!(config.retry_policy.is_some(), "{config:?}");
        }

        #[tokio::test]
        async fn backoff_policy() {
            let client = Client::builder()
                .with_backoff_policy(crate::exponential_backoff::ExponentialBackoff::default())
                .build()
                .await
                .unwrap();
            let config = client.0;
            assert!(config.backoff_policy.is_some(), "{config:?}");
        }

        #[tokio::test]
        async fn retry_throttler() {
            use crate::retry_throttler::CircuitBreaker;
            let client = Client::builder()
                .with_retry_throttler(CircuitBreaker::default())
                .build()
                .await
                .unwrap();
            let config = client.0;
            assert!(
                format!("{:?}", &config).contains("CircuitBreaker"),
                "{config:?}"
            );
        }

        #[tokio::test]
        async fn polling_error_policy() {
            use crate::polling_error_policy::PollingErrorPolicyExt;
            let client = Client::builder()
                .with_polling_error_policy(
                    crate::polling_error_policy::AlwaysContinue.with_attempt_limit(3),
                )
                .build()
                .await
                .unwrap();
            let config = client.0;
            assert!(config.polling_error_policy.is_some(), "{config:?}");
        }

        #[tokio::test]
        async fn polling_backoff_policy() {
            let client = Client::builder()
                .with_polling_backoff_policy(
                    crate::exponential_backoff::ExponentialBackoff::default(),
                )
                .build()
                .await
                .unwrap();
            let config = client.0;
            assert!(config.polling_backoff_policy.is_some(), "{config:?}");
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::error::Error as _;

    #[test]
    fn error_credentials() {
        let source = wkt::TimestampError::OutOfRange;
        let error = Error::cred(source);
        assert!(error.is_default_credentials(), "{error:?}");
        assert!(error.to_string().contains("default credentials"), "{error}");
        let got = error
            .source()
            .and_then(|e| e.downcast_ref::<wkt::TimestampError>());
        assert!(
            matches!(got, Some(wkt::TimestampError::OutOfRange)),
            "{error:?}"
        );
    }

    #[test]
    fn transport() {
        let source = wkt::TimestampError::OutOfRange;
        let error = Error::transport(source);
        assert!(error.is_transport(), "{error:?}");
        assert!(error.to_string().contains("transport client"), "{error}");
        let got = error
            .source()
            .and_then(|e| e.downcast_ref::<wkt::TimestampError>());
        assert!(
            matches!(got, Some(wkt::TimestampError::OutOfRange)),
            "{error:?}"
        );
    }
}