google_cloud_gax/error/
core_error.rs

1// Copyright 2024 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::CredentialsError;
16use super::rpc::Status;
17use http::HeaderMap;
18use std::error::Error as StdError;
19
20type BoxError = Box<dyn StdError + Send + Sync>;
21
22/// The core error returned by all client libraries.
23///
24/// The client libraries report errors from multiple sources. For example, the
25/// service may return an error, the transport may be unable to create the
26/// necessary connection to make a request, the request may timeout before a
27/// response is received, the retry policy may be exhausted, or the library may
28/// be unable to format the request due to invalid or missing application
29/// application inputs.
30///
31/// Most applications will just return the error or log it, without any further
32/// action. However, some applications may need to interrogate the error
33/// details. This type offers a series of predicates to determine the error
34/// kind. The type also offers accessors to query the most common error details.
35/// Applications can query the error [source][std::error::Error::source] for
36/// deeper information.
37///
38/// # Example
39/// ```
40/// use google_cloud_gax::error::Error;
41/// match example_function() {
42///     Err(e) if matches!(e.status(), Some(_)) => {
43///         println!("service error {e}, debug using {:?}", e.status().unwrap());
44///     },
45///     Err(e) if e.is_timeout() => { println!("not enough time {e}"); },
46///     Err(e) => { println!("some other error {e}"); },
47///     Ok(_) => { println!("success, how boring"); },
48/// }
49///
50/// fn example_function() -> Result<String, Error> {
51///     // ... details omitted ...
52///     # use google_cloud_gax::error::rpc::{Code, Status};
53///     # Err(Error::service(Status::default().set_code(Code::NotFound).set_message("NOT FOUND")))
54/// }
55/// ```
56#[derive(Debug)]
57pub struct Error {
58    kind: ErrorKind,
59    source: Option<BoxError>,
60}
61
62impl Error {
63    /// Creates an error with the information returned by Google Cloud services.
64    ///
65    /// # Example
66    /// ```
67    /// use google_cloud_gax::error::Error;
68    /// use google_cloud_gax::error::rpc::{Code, Status};
69    /// let status = Status::default().set_code(Code::NotFound).set_message("NOT FOUND");
70    /// let error = Error::service(status.clone());
71    /// assert_eq!(error.status(), Some(&status));
72    /// ```
73    pub fn service(status: Status) -> Self {
74        let details = ServiceDetails {
75            status,
76            status_code: None,
77            headers: None,
78        };
79        Self {
80            kind: ErrorKind::Service(Box::new(details)),
81            source: None,
82        }
83    }
84
85    /// Creates an error representing a timeout.
86    ///
87    /// # Example
88    /// ```
89    /// use std::error::Error as _;
90    /// use google_cloud_gax::error::Error;
91    /// let error = Error::timeout("simulated timeout");
92    /// assert!(error.is_timeout());
93    /// assert!(error.source().is_some());
94    /// ```
95    pub fn timeout<T: Into<BoxError>>(source: T) -> Self {
96        Self {
97            kind: ErrorKind::Timeout,
98            source: Some(source.into()),
99        }
100    }
101
102    /// The request could not be completed before its deadline.
103    ///
104    /// This is always a client-side generated error. Note that the request may
105    /// or may not have started, and it may or may not complete in the service.
106    /// If the request mutates any state in the service, it may or may not be
107    /// safe to attempt the request again.
108    ///
109    /// # Troubleshooting
110    ///
111    /// The most common cause of this problem is setting a timeout value that is
112    /// based on the observed latency when the service is not under load.
113    /// Consider increasing the timeout value to handle temporary latency
114    /// increases too.
115    ///
116    /// It could also indicate a congestion in the network, a service outage, or
117    /// a service that is under load and will take time to scale up.
118    pub fn is_timeout(&self) -> bool {
119        matches!(self.kind, ErrorKind::Timeout)
120    }
121
122    /// Creates an error representing an exhausted policy.
123    ///
124    /// # Example
125    /// ```
126    /// use std::error::Error as _;
127    /// use google_cloud_gax::error::Error;
128    /// let error = Error::exhausted("too many retry attempts");
129    /// assert!(error.is_exhausted());
130    /// assert!(error.source().is_some());
131    /// ```
132    pub fn exhausted<T: Into<BoxError>>(source: T) -> Self {
133        Self {
134            kind: ErrorKind::Exhausted,
135            source: Some(source.into()),
136        }
137    }
138
139    /// The request could not complete be before the retry policy expired.
140    ///
141    /// This is always a client-side generated error, but it may be the result
142    /// of multiple errors received from the service.
143    ///
144    /// # Troubleshooting
145    ///
146    /// The most common cause of this problem is a transient problem that lasts
147    /// longer than your retry policy. For example, your retry policy may
148    /// effectively be exhausted after a few seconds, but some services may take
149    /// minutes to recover.
150    ///
151    /// If your application can tolerate longer recovery times then extend the
152    /// retry policy. Otherwise consider recovery at a higher level, such as
153    /// seeking human intervention, switching the workload to a different
154    /// location, failing the batch job and starting from a previous checkpoint,
155    /// or even presenting an error to the application user.
156    pub fn is_exhausted(&self) -> bool {
157        matches!(self.kind, ErrorKind::Exhausted)
158    }
159
160    /// Not part of the public API, subject to change without notice.
161    ///
162    /// Creates an error representing a deserialization problem.
163    ///
164    /// Applications should have no need to use this function. The exception
165    /// could be mocks, but this error is too rare to merit mocks. If you are
166    /// writing a mock that extracts values from [wkt::Any], consider using
167    /// `.expect()` calls instead.
168    ///
169    /// # Example
170    /// ```
171    /// use std::error::Error as _;
172    /// use google_cloud_gax::error::Error;
173    /// let error = Error::deser("simulated problem");
174    /// assert!(error.is_deserialization());
175    /// assert!(error.source().is_some());
176    /// ```
177    #[cfg_attr(not(feature = "_internal-semver"), doc(hidden))]
178    pub fn deser<T: Into<BoxError>>(source: T) -> Self {
179        Self {
180            kind: ErrorKind::Deserialization,
181            source: Some(source.into()),
182        }
183    }
184
185    /// The response could not be deserialized.
186    ///
187    /// This is always a client-side generated error. Note that the request may
188    /// or may not have started, and it may or may not complete in the service.
189    /// If the request mutates any state in the service, it may or may not be
190    /// safe to attempt the request again.
191    ///
192    /// # Troubleshooting
193    ///
194    /// The most common cause for deserialization problems are bugs in the
195    /// client library and (rarely) bugs in the service.
196    ///
197    /// When using gRPC services, and if the response includes a [wkt::Any]
198    /// field, the client library may not be able to handle unknown types within
199    /// the `Any`. In all services we know of, this should not happen, but it is
200    /// impossible to prepare the client library for breaking changes in the
201    /// service. Upgrading to the latest version of the client library may be
202    /// the only possible fix.
203    ///
204    /// Beyond this issue with `Any`, while the client libraries are designed to
205    /// handle all valid responses, including unknown fields and unknown
206    /// enumeration values, it is possible that the client library has a bug.
207    /// Please [open an issue] if you run in to this problem. Include any
208    /// instructions on how to reproduce the problem. If you cannot use, or
209    /// prefer not to use, GitHub to discuss this problem, then contact
210    /// [Google Cloud support].
211    ///
212    /// [open an issue]: https://github.com/googleapis/google-cloud-rust/issues/new/choose
213    /// [Google Cloud support]: https://cloud.google.com/support
214    pub fn is_deserialization(&self) -> bool {
215        matches!(self.kind, ErrorKind::Deserialization)
216    }
217
218    /// Not part of the public API, subject to change without notice.
219    ///
220    /// Creates an error representing a serialization problem.
221    ///
222    /// Applications should have no need to use this function. The exception
223    /// could be mocks, but this error is too rare to merit mocks. If you are
224    /// writing a mock that stores values into [wkt::Any], consider using
225    /// `.expect()` calls instead.
226    ///
227    /// # Example
228    /// ```
229    /// use std::error::Error as _;
230    /// use google_cloud_gax::error::Error;
231    /// let error = Error::ser("simulated problem");
232    /// assert!(error.is_serialization());
233    /// assert!(error.source().is_some());
234    /// ```
235    #[cfg_attr(not(feature = "_internal-semver"), doc(hidden))]
236    pub fn ser<T: Into<BoxError>>(source: T) -> Self {
237        Self {
238            kind: ErrorKind::Serialization,
239            source: Some(source.into()),
240        }
241    }
242
243    /// The request could not be serialized.
244    ///
245    /// This is always a client-side generated error, generated before the
246    /// request is made. This error is never transient: the serialization is
247    /// deterministic (modulo out of memory conditions), and will fail on future
248    /// attempts with the same input data.
249    ///
250    /// # Troubleshooting
251    ///
252    /// Most client libraries use HTTP and JSON as the transport, though some
253    /// client libraries use gRPC for some, or all RPCs.
254    ///
255    /// The most common cause for serialization problems is using an unknown
256    /// enum value name with a gRPC-based RPC. gRPC requires integer enum
257    /// values, while JSON accepts both. The client libraries convert **known**
258    /// enum value names to their integer representation, but unknown values
259    /// cannot be sent over gRPC. Verify the enum value is valid, and if so:
260    /// - try using an integer value instead of the enum name, or
261    /// - upgrade the client library: newer versions should include the new
262    ///   value.
263    ///
264    /// In all other cases please [open an issue]. While we do not expect these
265    /// problems to be common, we would like to hear if they are so we can
266    /// prevent them. If you cannot use a public issue tracker, contact
267    /// [Google Cloud support].
268    ///
269    /// A less common cause for serialization problems may be an out of memory
270    /// condition, or any other runtime error. Use `format!("{:?}", ...)` to
271    /// examine the error as it should include the original problem.
272    ///
273    /// Finally, sending a [wkt::Any] with a gRPC-based client is unsupported.
274    /// As of this writing, no client libraries sends `Any` via gRPC, but this
275    /// could be a problem in the future.
276    ///
277    /// [open an issue]: https://github.com/googleapis/google-cloud-rust/issues/new/choose
278    /// [Google Cloud support]: https://cloud.google.com/support
279    pub fn is_serialization(&self) -> bool {
280        matches!(self.kind, ErrorKind::Serialization)
281    }
282
283    /// The [Status] payload associated with this error.
284    ///
285    /// # Examples
286    /// ```
287    /// use google_cloud_gax::error::{Error, rpc::{Code, Status}};
288    /// let error = Error::service(Status::default().set_code(Code::NotFound));
289    /// if let Some(status) = error.status() {
290    ///     if status.code == Code::NotFound {
291    ///         println!("cannot find the thing, more details in {:?}", status.details);
292    ///     }
293    /// }
294    /// ```
295    ///
296    /// Google Cloud services return a detailed `Status` message including a
297    /// numeric code for the error type, a human-readable message, and a
298    /// sequence of details which may include localization messages, or more
299    /// information about what caused the failure.
300    ///
301    /// See [AIP-193] for background information about the error model in Google
302    /// Cloud services.
303    ///
304    /// # Troubleshooting
305    ///
306    /// As this error type is typically created by the service, troubleshooting
307    /// this problem typically involves reading the service documentation to
308    /// root cause the problem.
309    ///
310    /// Some services include additional details about the error, sometimes
311    /// including what fields are missing or have bad values in the
312    /// [Status::details] vector. The `std::fmt::Debug` format will include
313    /// such details.
314    ///
315    /// With that said, review the status [Code][crate::error::rpc::Code]
316    /// documentation. The description of the status codes provides a good
317    /// starting point.
318    ///
319    /// [AIP-193]: https://google.aip.dev/193
320    pub fn status(&self) -> Option<&Status> {
321        match &self.kind {
322            ErrorKind::Service(d) => Some(&d.as_ref().status),
323            _ => None,
324        }
325    }
326
327    /// The HTTP status code, if any, associated with this error.
328    ///
329    /// # Example
330    /// ```
331    /// use google_cloud_gax::error::{Error, rpc::{Code, Status}};
332    /// let e = search_for_thing("the thing");
333    /// if let Some(code) = e.http_status_code() {
334    ///     if code == 404 {
335    ///         println!("cannot find the thing, more details in {e}");
336    ///     }
337    /// }
338    ///
339    /// fn search_for_thing(name: &str) -> Error {
340    ///     # Error::http(400, http::HeaderMap::new(), bytes::Bytes::from_static(b"NOT FOUND"))
341    /// }
342    /// ```
343    ///
344    /// Sometimes the error is generated before it reaches any Google Cloud
345    /// service. For example, your proxy or the Google load balancers may
346    /// generate errors without the detailed payload described in [AIP-193].
347    /// In such cases the client library returns the status code, headers, and
348    /// http payload.
349    ///
350    /// Note that `http_status_code()`, `http_headers()`, `http_payload()`, and
351    /// `status()` are represented as different fields, because they may be
352    /// set in some errors but not others.
353    ///
354    /// [AIP-193]: https://google.aip.dev/193
355    pub fn http_status_code(&self) -> Option<u16> {
356        match &self.kind {
357            ErrorKind::Transport(d) => d.as_ref().status_code,
358            ErrorKind::Service(d) => d.as_ref().status_code,
359            _ => None,
360        }
361    }
362
363    /// The headers, if any, associated with this error.
364    ///
365    /// # Example
366    /// ```
367    /// use google_cloud_gax::error::{Error, rpc::{Code, Status}};
368    /// let e = search_for_thing("the thing");
369    /// if let Some(headers) = e.http_headers() {
370    ///     if let Some(id) = headers.get("x-guploader-uploadid") {
371    ///         println!("this can speed up troubleshooting for the Google Cloud Storage support team {id:?}");
372    ///     }
373    /// }
374    ///
375    /// fn search_for_thing(name: &str) -> Error {
376    ///     # let mut map = http::HeaderMap::new();
377    ///     # map.insert("x-guploader-uploadid", http::HeaderValue::from_static("placeholder"));
378    ///     # Error::http(400, map, bytes::Bytes::from_static(b"NOT FOUND"))
379    /// }
380    /// ```
381    ///
382    /// Sometimes the error may have headers associated with it. Some services
383    /// include information useful for troubleshooting in the response headers.
384    /// Over gRPC this is called `metadata`, the Google Cloud client libraries
385    /// for Rust normalize this to a [http::HeaderMap].
386    ///
387    /// Many errors do not have this information, e.g. errors detected before
388    /// the request is set, or timeouts. Some RPCs also return "partial"
389    /// errors, which do not include such information.
390    ///
391    /// Note that `http_status_code()`, `http_headers()`, `http_payload()`, and
392    /// `status()` are represented as different fields, because they may be
393    /// set in some errors but not others.
394    pub fn http_headers(&self) -> Option<&http::HeaderMap> {
395        match &self.kind {
396            ErrorKind::Transport(d) => d.as_ref().headers.as_ref(),
397            ErrorKind::Service(d) => d.as_ref().headers.as_ref(),
398            _ => None,
399        }
400    }
401
402    /// The payload, if any, associated with this error.
403    ///
404    /// # Example
405    /// ```
406    /// use google_cloud_gax::error::{Error, rpc::{Code, Status}};
407    /// let e = search_for_thing("the thing");
408    /// if let Some(payload) = e.http_payload() {
409    ///    println!("the error included some extra payload {payload:?}");
410    /// }
411    ///
412    /// fn search_for_thing(name: &str) -> Error {
413    ///     # Error::http(400, http::HeaderMap::new(), bytes::Bytes::from_static(b"NOT FOUND"))
414    /// }
415    /// ```
416    ///
417    /// Sometimes the error may contain a payload that is useful for
418    /// troubleshooting.
419    ///
420    /// Note that `http_status_code()`, `http_headers()`, `http_payload()`, and
421    /// `status()` are represented as different fields, because they may be
422    /// set in some errors but not others.
423    pub fn http_payload(&self) -> Option<&bytes::Bytes> {
424        match &self.kind {
425            ErrorKind::Transport(d) => d.payload.as_ref(),
426            _ => None,
427        }
428    }
429
430    /// Not part of the public API, subject to change without notice.
431    ///
432    /// Create service errors including transport metadata.
433    #[cfg_attr(not(feature = "_internal-semver"), doc(hidden))]
434    pub fn service_with_http_metadata(
435        status: Status,
436        status_code: Option<u16>,
437        headers: Option<http::HeaderMap>,
438    ) -> Self {
439        let details = ServiceDetails {
440            status_code,
441            headers,
442            status,
443        };
444        let kind = ErrorKind::Service(Box::new(details));
445        Self { kind, source: None }
446    }
447
448    /// Not part of the public API, subject to change without notice.
449    ///
450    /// Cannot find a valid HTTP binding to make the request.
451    ///
452    /// This indicates the request is missing required parameters, or the
453    /// required parameters do not have a valid format.
454    #[cfg_attr(not(feature = "_internal-semver"), doc(hidden))]
455    pub fn binding<T: Into<BoxError>>(source: T) -> Self {
456        Self {
457            kind: ErrorKind::Binding,
458            source: Some(source.into()),
459        }
460    }
461
462    // TODO(#2316) - update the troubleshooting text.
463    /// Not part of the public API, subject to change without notice.
464    ///
465    /// If true, the request was missing required parameters or the parameters
466    /// did not match any of the expected formats.
467    ///
468    /// # Troubleshooting
469    ///
470    /// Typically this indicates a problem in the application. A required field
471    /// in the request builder was not initialized or the format of the field
472    /// does not match the expectations.
473    ///
474    /// We are working to improve the messages in these errors to make them
475    /// self-explanatory, until bug [#2316] is fixed, please consult the service
476    /// REST API documentation.
477    ///
478    /// [#2316]: https://github.com/googleapis/google-cloud-rust/issues/2316
479    #[cfg_attr(not(feature = "_internal-semver"), doc(hidden))]
480    pub fn is_binding(&self) -> bool {
481        matches!(&self.kind, ErrorKind::Binding)
482    }
483
484    /// Not part of the public API, subject to change without notice.
485    ///
486    /// Cannot create the authentication headers.
487    #[cfg_attr(not(feature = "_internal-semver"), doc(hidden))]
488    pub fn authentication(source: CredentialsError) -> Self {
489        Self {
490            kind: ErrorKind::Authentication,
491            source: Some(source.into()),
492        }
493    }
494
495    /// Not part of the public API, subject to change without notice.
496    ///
497    /// Could not create the authentication headers before sending the request.
498    ///
499    /// # Troubleshooting
500    ///
501    /// Typically this indicates a misconfigured authentication environment for
502    /// your application. Very rarely, this may indicate a failure to contact
503    /// the HTTP services used to create [access tokens].
504    ///
505    /// If you are using the default [Credentials], the
506    /// [Authenticate for using client libraries] guide includes good
507    /// information on how to set up your environment for authentication.
508    ///
509    /// If you have configured custom `Credentials`, consult the documentation
510    /// for the specific credential type you used.
511    ///
512    /// [Credentials]: https://docs.rs/google-cloud-auth/latest/google_cloud_auth/credentials/struct.Credentials.html
513    /// [Authenticate for using client libraries]: https://cloud.google.com/docs/authentication/client-libraries
514    /// [access tokens]: https://cloud.google.com/docs/authentication/token-types
515    #[cfg_attr(not(feature = "_internal-semver"), doc(hidden))]
516    pub fn is_authentication(&self) -> bool {
517        matches!(self.kind, ErrorKind::Authentication)
518    }
519
520    /// Not part of the public API, subject to change without notice.
521    ///
522    /// A problem reported by the transport layer.
523    #[cfg_attr(not(feature = "_internal-semver"), doc(hidden))]
524    pub fn http(status_code: u16, headers: HeaderMap, payload: bytes::Bytes) -> Self {
525        let details = TransportDetails {
526            status_code: Some(status_code),
527            headers: Some(headers),
528            payload: Some(payload),
529        };
530        let kind = ErrorKind::Transport(Box::new(details));
531        Self { kind, source: None }
532    }
533
534    /// Not part of the public API, subject to change without notice.
535    ///
536    /// A problem in the transport layer without a full HTTP response.
537    ///
538    /// Examples include: a broken connection after the request is sent, or a
539    /// any HTTP error that did not include a status code or other headers.
540    #[cfg_attr(not(feature = "_internal-semver"), doc(hidden))]
541    pub fn io<T: Into<BoxError>>(source: T) -> Self {
542        let details = TransportDetails {
543            status_code: None,
544            headers: None,
545            payload: None,
546        };
547        Self {
548            kind: ErrorKind::Transport(Box::new(details)),
549            source: Some(source.into()),
550        }
551    }
552
553    /// Not part of the public API, subject to change without notice.
554    ///
555    /// A problem in the transport layer without a full HTTP response.
556    ///
557    /// Examples include read or write problems, and broken connections.
558    ///
559    /// # Troubleshooting
560    ///
561    /// This indicates a problem completing the request. This type of error is
562    /// rare, but includes crashes and restarts on proxies and load balancers.
563    /// It could indicate a bug in the client library, if it tried to use a
564    /// stale connection that had been closed by the service.
565    ///
566    /// Most often, the solution is to use the right retry policy. This may
567    /// involve changing your request to be idempotent, or configuring the
568    /// policy to retry non-idempotent failures.
569    #[cfg_attr(not(feature = "_internal-semver"), doc(hidden))]
570    pub fn is_io(&self) -> bool {
571        matches!(
572        &self.kind,
573        ErrorKind::Transport(d) if matches!(**d, TransportDetails {
574            status_code: None,
575            headers: None,
576            payload: None,
577            ..
578        }))
579    }
580
581    /// Not part of the public API, subject to change without notice.
582    ///
583    /// A problem reported by the transport layer.
584    #[cfg_attr(not(feature = "_internal-semver"), doc(hidden))]
585    pub fn transport<T: Into<BoxError>>(headers: HeaderMap, source: T) -> Self {
586        let details = TransportDetails {
587            headers: Some(headers),
588            status_code: None,
589            payload: None,
590        };
591        Self {
592            kind: ErrorKind::Transport(Box::new(details)),
593            source: Some(source.into()),
594        }
595    }
596
597    /// Not part of the public API, subject to change without notice.
598    ///
599    /// A problem in the transport layer.
600    ///
601    /// Examples include errors in a proxy, load balancer, or other network
602    /// element generated before the service is able to send a full response.
603    ///
604    /// # Troubleshooting
605    ///
606    /// This indicates that the request did not reach the service. Most commonly
607    /// the problem are invalid or mismatched request parameters that route
608    /// the request to the wrong backend.
609    ///
610    /// In this regard, this is similar to the [is_binding][Error::is_binding]
611    /// errors, except that the client library was unable to detect the problem
612    /// locally.
613    ///
614    /// An increasingly common cause for this error is trying to use regional
615    /// resources (e.g. `projects/my-project/locations/us-central1/secrets/my-secret`)
616    /// while using the default, non-regional endpoint. Some services require
617    /// using regional endpoints (e.g.
618    /// `https://secretmanager.us-central1.rep.googleapis.com`) to access such
619    /// resources.
620    #[cfg_attr(not(feature = "_internal-semver"), doc(hidden))]
621    pub fn is_transport(&self) -> bool {
622        matches!(&self.kind, ErrorKind::Transport { .. })
623    }
624
625    /// The error was generated before the RPC started and is transient.
626    #[cfg_attr(not(feature = "_internal-semver"), doc(hidden))]
627    pub fn is_transient_and_before_rpc(&self) -> bool {
628        if !matches!(&self.kind, ErrorKind::Authentication) {
629            return false;
630        }
631        self.source
632            .as_ref()
633            .and_then(|e| e.downcast_ref::<CredentialsError>())
634            .map(|e| e.is_transient())
635            .unwrap_or(false)
636    }
637}
638
639impl std::fmt::Display for Error {
640    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
641        match (&self.kind, &self.source) {
642            (ErrorKind::Binding, Some(e)) => {
643                write!(f, "cannot find a matching binding to send the request: {e}")
644            }
645            (ErrorKind::Serialization, Some(e)) => write!(f, "cannot serialize the request {e}"),
646            (ErrorKind::Deserialization, Some(e)) => {
647                write!(f, "cannot deserialize the response {e}")
648            }
649            (ErrorKind::Authentication, Some(e)) => {
650                write!(f, "cannot create the authentication headers {e}")
651            }
652            (ErrorKind::Timeout, Some(e)) => {
653                write!(f, "the request exceeded the request deadline {e}")
654            }
655            (ErrorKind::Exhausted, Some(e)) => {
656                write!(f, "{e}")
657            }
658            (ErrorKind::Transport(details), _) => details.display(self.source(), f),
659            (ErrorKind::Service(d), _) => {
660                write!(
661                    f,
662                    "the service reports an error with code {} described as: {}",
663                    d.status.code, d.status.message
664                )
665            }
666            (_, None) => unreachable!("no constructor allows this"),
667        }
668    }
669}
670
671impl std::error::Error for Error {
672    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
673        self.source
674            .as_ref()
675            .map(|e| e.as_ref() as &dyn std::error::Error)
676    }
677}
678
679/// The type of error held by an [Error] instance.
680#[derive(Debug)]
681enum ErrorKind {
682    Binding,
683    Serialization,
684    Deserialization,
685    Authentication,
686    Timeout,
687    Exhausted,
688    Transport(Box<TransportDetails>),
689    Service(Box<ServiceDetails>),
690}
691
692#[derive(Debug)]
693struct TransportDetails {
694    status_code: Option<u16>,
695    headers: Option<HeaderMap>,
696    payload: Option<bytes::Bytes>,
697}
698
699impl TransportDetails {
700    fn display(
701        &self,
702        source: Option<&(dyn StdError + 'static)>,
703        f: &mut std::fmt::Formatter<'_>,
704    ) -> std::fmt::Result {
705        match (source, &self) {
706            (
707                _,
708                TransportDetails {
709                    status_code: Some(code),
710                    payload: Some(p),
711                    ..
712                },
713            ) => {
714                if let Ok(message) = std::str::from_utf8(p.as_ref()) {
715                    write!(f, "the HTTP transport reports a [{code}] error: {message}")
716                } else {
717                    write!(f, "the HTTP transport reports a [{code}] error: {p:?}")
718                }
719            }
720            (Some(source), _) => {
721                write!(f, "the transport reports an error: {source}")
722            }
723            (None, _) => unreachable!("no Error constructor allows this"),
724        }
725    }
726}
727
728#[derive(Debug)]
729struct ServiceDetails {
730    status_code: Option<u16>,
731    headers: Option<HeaderMap>,
732    status: Status,
733}
734
735#[cfg(test)]
736mod tests {
737    use super::*;
738    use crate::error::CredentialsError;
739    use crate::error::rpc::Code;
740    use std::error::Error as StdError;
741
742    #[test]
743    fn service() {
744        let status = Status::default()
745            .set_code(Code::NotFound)
746            .set_message("NOT FOUND");
747        let error = Error::service(status.clone());
748        assert!(error.source().is_none(), "{error:?}");
749        assert_eq!(error.status(), Some(&status));
750        assert!(error.to_string().contains("NOT FOUND"), "{error}");
751        assert!(error.to_string().contains(Code::NotFound.name()), "{error}");
752        assert!(!error.is_transient_and_before_rpc(), "{error:?}");
753    }
754
755    #[test]
756    fn timeout() {
757        let source = wkt::TimestampError::OutOfRange;
758        let error = Error::timeout(source);
759        assert!(error.is_timeout(), "{error:?}");
760        assert!(error.source().is_some(), "{error:?}");
761        let got = error
762            .source()
763            .and_then(|e| e.downcast_ref::<wkt::TimestampError>());
764        assert!(
765            matches!(got, Some(wkt::TimestampError::OutOfRange)),
766            "{error:?}"
767        );
768        let source = wkt::TimestampError::OutOfRange;
769        assert!(error.to_string().contains(&source.to_string()), "{error}");
770        assert!(!error.is_transient_and_before_rpc(), "{error:?}");
771
772        assert!(error.http_headers().is_none(), "{error:?}");
773        assert!(error.http_status_code().is_none(), "{error:?}");
774        assert!(error.http_payload().is_none(), "{error:?}");
775        assert!(error.status().is_none(), "{error:?}");
776    }
777
778    #[test]
779    fn exhausted() {
780        let source = wkt::TimestampError::OutOfRange;
781        let error = Error::exhausted(source);
782        assert!(error.is_exhausted(), "{error:?}");
783        assert!(error.source().is_some(), "{error:?}");
784        let got = error
785            .source()
786            .and_then(|e| e.downcast_ref::<wkt::TimestampError>());
787        assert!(
788            matches!(got, Some(wkt::TimestampError::OutOfRange)),
789            "{error:?}"
790        );
791        let source = wkt::TimestampError::OutOfRange;
792        assert!(error.to_string().contains(&source.to_string()), "{error}");
793        assert!(!error.is_transient_and_before_rpc(), "{error:?}");
794
795        assert!(error.http_headers().is_none(), "{error:?}");
796        assert!(error.http_status_code().is_none(), "{error:?}");
797        assert!(error.http_payload().is_none(), "{error:?}");
798        assert!(error.status().is_none(), "{error:?}");
799    }
800
801    #[test]
802    fn serialization() {
803        let source = wkt::TimestampError::OutOfRange;
804        let error = Error::deser(source);
805        assert!(error.is_deserialization(), "{error:?}");
806        let got = error
807            .source()
808            .and_then(|e| e.downcast_ref::<wkt::TimestampError>());
809        assert!(
810            matches!(got, Some(wkt::TimestampError::OutOfRange)),
811            "{error:?}"
812        );
813        let source = wkt::TimestampError::OutOfRange;
814        assert!(error.to_string().contains(&source.to_string()), "{error}");
815        assert!(!error.is_transient_and_before_rpc(), "{error:?}");
816    }
817
818    #[test]
819    fn service_with_http_metadata() {
820        let status = Status::default()
821            .set_code(Code::NotFound)
822            .set_message("NOT FOUND");
823        let status_code = 404_u16;
824        let headers = {
825            let mut headers = http::HeaderMap::new();
826            headers.insert(
827                "content-type",
828                http::HeaderValue::from_static("application/json"),
829            );
830            headers
831        };
832        let error = Error::service_with_http_metadata(
833            status.clone(),
834            Some(status_code),
835            Some(headers.clone()),
836        );
837        assert_eq!(error.status(), Some(&status));
838        assert!(error.to_string().contains("NOT FOUND"), "{error}");
839        assert!(error.to_string().contains(Code::NotFound.name()), "{error}");
840        assert_eq!(error.http_status_code(), Some(status_code));
841        assert_eq!(error.http_headers(), Some(&headers));
842        assert!(error.http_payload().is_none(), "{error:?}");
843        assert!(!error.is_transient_and_before_rpc(), "{error:?}");
844    }
845
846    #[test]
847    fn binding() {
848        let source = wkt::TimestampError::OutOfRange;
849        let error = Error::binding(source);
850        assert!(error.is_binding(), "{error:?}");
851        assert!(error.source().is_some(), "{error:?}");
852        let got = error
853            .source()
854            .and_then(|e| e.downcast_ref::<wkt::TimestampError>());
855        assert!(
856            matches!(got, Some(wkt::TimestampError::OutOfRange)),
857            "{error:?}"
858        );
859        let source = wkt::TimestampError::OutOfRange;
860        assert!(error.to_string().contains(&source.to_string()), "{error}");
861        assert!(!error.is_transient_and_before_rpc(), "{error:?}");
862
863        assert!(error.status().is_none(), "{error:?}");
864        assert!(error.http_status_code().is_none(), "{error:?}");
865        assert!(error.http_headers().is_none(), "{error:?}");
866        assert!(error.http_payload().is_none(), "{error:?}");
867    }
868
869    #[test]
870    fn ser() {
871        let source = wkt::TimestampError::OutOfRange;
872        let error = Error::ser(source);
873        assert!(error.is_serialization(), "{error:?}");
874        assert!(error.source().is_some(), "{error:?}");
875        let got = error
876            .source()
877            .and_then(|e| e.downcast_ref::<wkt::TimestampError>());
878        assert!(
879            matches!(got, Some(wkt::TimestampError::OutOfRange)),
880            "{error:?}"
881        );
882        let source = wkt::TimestampError::OutOfRange;
883        assert!(error.to_string().contains(&source.to_string()), "{error}");
884        assert!(!error.is_transient_and_before_rpc(), "{error:?}");
885    }
886
887    #[test]
888    fn auth_transient() {
889        let source = CredentialsError::from_msg(true, "test-message");
890        let error = Error::authentication(source);
891        assert!(error.is_authentication(), "{error:?}");
892        assert!(error.source().is_some(), "{error:?}");
893        let got = error
894            .source()
895            .and_then(|e| e.downcast_ref::<CredentialsError>());
896        assert!(matches!(got, Some(c) if c.is_transient()), "{error:?}");
897        assert!(error.to_string().contains("test-message"), "{error}");
898        assert!(error.is_transient_and_before_rpc(), "{error:?}");
899    }
900
901    #[test]
902    fn auth_not_transient() {
903        let source = CredentialsError::from_msg(false, "test-message");
904        let error = Error::authentication(source);
905        assert!(error.is_authentication(), "{error:?}");
906        assert!(error.source().is_some(), "{error:?}");
907        let got = error
908            .source()
909            .and_then(|e| e.downcast_ref::<CredentialsError>());
910        assert!(matches!(got, Some(c) if !c.is_transient()), "{error:?}");
911        assert!(error.to_string().contains("test-message"), "{error}");
912        assert!(!error.is_transient_and_before_rpc(), "{error:?}");
913    }
914
915    #[test]
916    fn http() {
917        let status_code = 404_u16;
918        let headers = {
919            let mut headers = http::HeaderMap::new();
920            headers.insert(
921                "content-type",
922                http::HeaderValue::from_static("application/json"),
923            );
924            headers
925        };
926        let payload = bytes::Bytes::from_static(b"NOT FOUND");
927        let error = Error::http(status_code, headers.clone(), payload.clone());
928        assert!(error.is_transport(), "{error:?}");
929        assert!(!error.is_io(), "{error:?}");
930        assert!(error.source().is_none(), "{error:?}");
931        assert!(error.status().is_none(), "{error:?}");
932        assert!(error.to_string().contains("NOT FOUND"), "{error}");
933        assert!(error.to_string().contains("404"), "{error}");
934        assert_eq!(error.http_status_code(), Some(status_code));
935        assert_eq!(error.http_headers(), Some(&headers));
936        assert_eq!(error.http_payload(), Some(&payload));
937        assert!(!error.is_transient_and_before_rpc(), "{error:?}");
938    }
939
940    #[test]
941    fn http_binary() {
942        let status_code = 404_u16;
943        let headers = {
944            let mut headers = http::HeaderMap::new();
945            headers.insert(
946                "content-type",
947                http::HeaderValue::from_static("application/json"),
948            );
949            headers
950        };
951        let payload = bytes::Bytes::from_static(&[0xFF, 0xFF]);
952        let error = Error::http(status_code, headers.clone(), payload.clone());
953        assert!(error.is_transport(), "{error:?}");
954        assert!(!error.is_io(), "{error:?}");
955        assert!(error.source().is_none(), "{error:?}");
956        assert!(error.status().is_none(), "{error:?}");
957        assert!(
958            error.to_string().contains(&format! {"{payload:?}"}),
959            "{error}"
960        );
961        assert!(error.to_string().contains("404"), "{error}");
962        assert_eq!(error.http_status_code(), Some(status_code));
963        assert_eq!(error.http_headers(), Some(&headers));
964        assert_eq!(error.http_payload(), Some(&payload));
965        assert!(!error.is_transient_and_before_rpc(), "{error:?}");
966    }
967
968    #[test]
969    fn io() {
970        let source = wkt::TimestampError::OutOfRange;
971        let error = Error::io(source);
972        assert!(error.is_transport(), "{error:?}");
973        assert!(error.is_io(), "{error:?}");
974        assert!(error.status().is_none(), "{error:?}");
975        let got = error
976            .source()
977            .and_then(|e| e.downcast_ref::<wkt::TimestampError>());
978        assert!(
979            matches!(got, Some(wkt::TimestampError::OutOfRange)),
980            "{error:?}"
981        );
982        let source = wkt::TimestampError::OutOfRange;
983        assert!(error.to_string().contains(&source.to_string()), "{error}");
984        assert!(!error.is_transient_and_before_rpc(), "{error:?}");
985    }
986
987    #[test]
988    fn transport() {
989        let headers = {
990            let mut headers = http::HeaderMap::new();
991            headers.insert(
992                "content-type",
993                http::HeaderValue::from_static("application/json"),
994            );
995            headers
996        };
997        let source = wkt::TimestampError::OutOfRange;
998        let error = Error::transport(headers.clone(), source);
999        assert!(error.is_transport(), "{error:?}");
1000        assert!(!error.is_io(), "{error:?}");
1001        assert!(error.status().is_none(), "{error:?}");
1002        let source = wkt::TimestampError::OutOfRange;
1003        assert!(error.to_string().contains(&source.to_string()), "{error}");
1004        assert!(error.http_status_code().is_none(), "{error:?}");
1005        assert_eq!(error.http_headers(), Some(&headers));
1006        assert!(error.http_payload().is_none(), "{error:?}");
1007        assert!(!error.is_transient_and_before_rpc(), "{error:?}");
1008    }
1009}