Coverage Report

Created: 2026-11-29 00:57

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/build/source/nativelink-error/src/lib.rs
Line
Count
Source
1
// Copyright 2024 Trace Machina, Inc. All rights reserved.
2
//
3
// Licensed under the Functional Source License, Version 1.1, Apache 2.0 Future License (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
//    See LICENSE file for details
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
15
use core::convert::Into;
16
use core::str::Utf8Error;
17
use std::sync::{MutexGuard, PoisonError};
18
19
use nativelink_metric::{
20
    MetricFieldData, MetricKind, MetricPublishKnownKindData, MetricsComponent,
21
};
22
use prost_types::TimestampError;
23
use serde::{Deserialize, Serialize};
24
use tokio::sync::AcquireError;
25
// Reexport of tonic's error codes which we use as "nativelink_error::Code".
26
pub use tonic::Code;
27
28
#[macro_export]
29
macro_rules! make_err {
30
    ($code:expr, $($arg:tt)+) => {{
31
        $crate::Error::new(
32
            $code,
33
            format!("{}", format_args!($($arg)+)),
34
        )
35
    }};
36
}
37
38
#[macro_export]
39
macro_rules! make_input_err {
40
    ($($arg:tt)+) => {{
41
        $crate::make_err!($crate::Code::InvalidArgument, $($arg)+)
42
    }};
43
}
44
45
#[macro_export]
46
macro_rules! error_if {
47
    ($cond:expr, $($arg:tt)+) => {{
48
        if $cond {
49
            Err($crate::make_err!($crate::Code::InvalidArgument, $($arg)+))?;
50
        }
51
    }};
52
}
53
54
/// Typed metadata that travels with an [`Error`].
55
///
56
/// Used in place of string-parsing error messages when the producer
57
/// has structured information the consumer needs to act on. The
58
/// motivating case is missing-blob errors from `fast_slow_store` —
59
/// `to_execute_response` reads [`ErrorContext::MissingDigest`] and
60
/// surfaces a `FAILED_PRECONDITION` with a `PreconditionFailure`
61
/// detail naming the digest, which Bazel auto-retries on.
62
///
63
/// Default is [`ErrorContext::None`]; existing call sites that
64
/// construct [`Error`] via `make_err!` / `Error::new` do not need to
65
/// be updated.
66
#[derive(Default, Debug, Eq, PartialEq, Clone, Serialize, Deserialize)]
67
pub enum ErrorContext {
68
    #[default]
69
    None,
70
    /// The error refers to a specific CAS blob that could not be
71
    /// located. `hash` and `size` together form the digest the client
72
    /// should re-upload; see [`missing_blob_subject`] for the subject.
73
    MissingDigest {
74
        hash: String,
75
        size: i64,
76
        /// The lowercase digest function name the subject has to carry,
77
        /// for example `blake3`. `None` when it is omitted, which `REv2`
78
        /// requires for MD5, MURMUR3, SHA1, SHA256, SHA384, SHA512 and VSO.
79
        #[serde(default, skip_serializing_if = "Option::is_none")]
80
        digest_function: Option<String>,
81
    },
82
}
83
84
/// The `REv2` subject of a `MISSING` `PreconditionFailure` violation:
85
/// `blobs/{digest_function/}{hash}/{size}`, formatted like a
86
/// `ByteStream.Read` resource name without the instance name. The digest
87
/// function segment is present exactly when `digest_function` is `Some`.
88
#[must_use]
89
14
pub fn missing_blob_subject(digest_function: Option<&str>, hash: &str, size: i64) -> String {
90
14
    match digest_function {
91
2
        Some(digest_function) => format!("blobs/{digest_function}/{hash}/{size}"),
92
12
        None => format!("blobs/{hash}/{size}"),
93
    }
94
14
}
95
96
#[derive(Eq, PartialEq, Clone, Serialize, Deserialize)]
97
pub struct Error {
98
    #[serde(with = "CodeDef")]
99
    pub code: Code,
100
    pub messages: Vec<String>,
101
    #[serde(default, skip_serializing_if = "ErrorContext::is_none")]
102
    pub context: ErrorContext,
103
}
104
105
impl core::fmt::Debug for Error {
106
461
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
107
461
        let mut builder = f.debug_struct("Error");
108
461
        builder.field("code", &self.code);
109
461
        if !self.messages.is_empty() {
110
461
            builder.field("messages", &self.messages);
111
461
        
}0
112
461
        if !self.context.is_none() {
113
5
            builder.field("context", &self.context);
114
456
        }
115
461
        builder.finish()
116
461
    }
117
}
118
119
impl ErrorContext {
120
    #[inline]
121
    #[must_use]
122
2.41k
    pub const fn is_none(&self) -> bool {
123
2.41k
        
matches!5
(self, Self::None)
124
2.41k
    }
125
}
126
127
impl MetricsComponent for Error {
128
1
    fn publish(
129
1
        &self,
130
1
        kind: MetricKind,
131
1
        field_metadata: MetricFieldData,
132
1
    ) -> Result<MetricPublishKnownKindData, nativelink_metric::Error> {
133
1
        self.to_string().publish(kind, field_metadata)
134
1
    }
135
}
136
137
impl Error {
138
    #[must_use]
139
6.40k
    pub const fn new_with_messages(code: Code, messages: Vec<String>) -> Self {
140
6.40k
        Self {
141
6.40k
            code,
142
6.40k
            messages,
143
6.40k
            context: ErrorContext::None,
144
6.40k
        }
145
6.40k
    }
146
147
    #[must_use]
148
5.70k
    pub fn new(code: Code, msg: String) -> Self {
149
5.70k
        if msg.is_empty() {
150
0
            Self::new_with_messages(code, vec![])
151
        } else {
152
5.70k
            Self::new_with_messages(code, vec![msg])
153
        }
154
5.70k
    }
155
156
    #[must_use]
157
695
    pub fn from_std_err(code: Code, mut err: &dyn core::error::Error) -> Self {
158
695
        let mut messages = vec![format!("{err}")];
159
702
        while let Some(
src7
) = err.source() {
160
7
            messages.push(format!("{src}"));
161
7
            err = src;
162
7
        }
163
695
        messages.reverse();
164
695
        Self::new_with_messages(code, messages)
165
695
    }
166
167
    #[inline]
168
    #[must_use]
169
802
    pub fn append<S: Into<String>>(mut self, msg: S) -> Self {
170
802
        self.messages.push(msg.into());
171
802
        self
172
802
    }
173
174
    #[inline]
175
    #[must_use]
176
27
    pub fn with_context(mut self, context: ErrorContext) -> Self {
177
27
        self.context = context;
178
27
        self
179
27
    }
180
181
    #[must_use]
182
13
    pub fn merge<E: Into<Self>>(mut self, other: E) -> Self {
183
13
        let mut other: Self = other.into();
184
        // This will help with knowing which messages are tied to different errors.
185
13
        self.messages.push("---".to_string());
186
13
        self.messages.append(&mut other.messages);
187
13
        self
188
13
    }
189
190
    #[must_use]
191
59
    pub fn merge_option<T: Into<Self>, U: Into<Self>>(
192
59
        this: Option<T>,
193
59
        other: Option<U>,
194
59
    ) -> Option<Self> {
195
59
        if let Some(
this13
) = this {
196
13
            if let Some(
other1
) = other {
197
1
                return Some(this.into().merge(other));
198
12
            }
199
12
            return Some(this.into());
200
46
        }
201
46
        other.map(Into::into)
202
59
    }
203
204
    #[must_use]
205
1
    pub fn to_std_err(self) -> std::io::Error {
206
1
        std::io::Error::new(self.code.into_error_kind(), self.messages.join(" : "))
207
1
    }
208
209
    #[must_use]
210
2.53k
    pub fn message_string(&self) -> String {
211
2.53k
        self.messages.join(" : ")
212
2.53k
    }
213
}
214
215
impl core::error::Error for Error {}
216
217
impl From<Error> for nativelink_proto::google::rpc::Status {
218
315
    fn from(val: Error) -> Self {
219
315
        Self {
220
315
            code: val.code as i32,
221
315
            message: val.message_string(),
222
315
            details: vec![],
223
315
        }
224
315
    }
225
}
226
227
impl From<nativelink_proto::google::rpc::Status> for Error {
228
266
    fn from(val: nativelink_proto::google::rpc::Status) -> Self {
229
266
        let context = missing_digest_from_details(&val.details);
230
266
        Self {
231
266
            code: val.code.into(),
232
266
            messages: vec![val.message],
233
266
            context,
234
266
        }
235
266
    }
236
}
237
238
/// The `REv2` missing-blob violation in a status's details, as the
239
/// [`ErrorContext`] that produced it. A status that crosses a gRPC hop
240
/// (a CAS forwarding `Execute` to a separate scheduler) would otherwise
241
/// lose it, and with it the `PreconditionFailure` the client needs to
242
/// upload the blob again and retry.
243
266
fn missing_digest_from_details(details: &[prost_types::Any]) -> ErrorContext {
244
    const PRECONDITION_FAILURE: &str = "type.googleapis.com/google.rpc.PreconditionFailure";
245
266
    details
246
266
        .iter()
247
266
        .filter(|any| 
any.type_url2
==
PRECONDITION_FAILURE2
)
248
266
        .filter_map(|any| 
{2
249
2
            <nativelink_proto::google::rpc::PreconditionFailure as prost::Message>::decode(
250
2
                any.value.as_slice(),
251
            )
252
2
            .ok()
253
2
        })
254
266
        .flat_map(|failure| failure.violations)
255
266
        .filter(|violation| 
violation.r#type2
==
"MISSING"2
)
256
266
        .find_map(|violation| 
{2
257
2
            let rest = violation.subject.strip_prefix("blobs/")
?0
;
258
            // `{digest_function/}{hash}/{size}`: read from the right, since
259
            // the digest function segment is optional.
260
2
            let mut parts = rest.rsplitn(3, '/');
261
2
            let size = parts.next()
?0
.parse().ok()
?0
;
262
2
            let hash = parts.next()
?0
.to_string();
263
2
            let digest_function = parts.next().map(str::to_string);
264
2
            Some(ErrorContext::MissingDigest {
265
2
                hash,
266
2
                size,
267
2
                digest_function,
268
2
            })
269
2
        })
270
266
        .unwrap_or_default()
271
266
}
272
273
impl core::fmt::Display for Error {
274
153
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
275
        // A manual impl to reduce the noise of frequently empty fields.
276
153
        let mut builder = f.debug_struct("Error");
277
278
153
        builder.field("code", &self.code);
279
280
153
        if !self.messages.is_empty() {
281
153
            builder.field("messages", &self.messages);
282
153
        
}0
283
284
153
        builder.finish()
285
153
    }
286
}
287
288
impl From<prost::DecodeError> for Error {
289
2
    fn from(err: prost::DecodeError) -> Self {
290
2
        Self::from_std_err(Code::Internal, &err)
291
2
    }
292
}
293
294
impl From<prost::EncodeError> for Error {
295
0
    fn from(err: prost::EncodeError) -> Self {
296
0
        Self::from_std_err(Code::Internal, &err)
297
0
    }
298
}
299
300
impl From<prost::UnknownEnumValue> for Error {
301
0
    fn from(err: prost::UnknownEnumValue) -> Self {
302
0
        Self::from_std_err(Code::Internal, &err)
303
0
    }
304
}
305
306
impl From<core::num::TryFromIntError> for Error {
307
1
    fn from(err: core::num::TryFromIntError) -> Self {
308
1
        Self::from_std_err(Code::InvalidArgument, &err)
309
1
    }
310
}
311
312
impl From<tokio::task::JoinError> for Error {
313
1
    fn from(err: tokio::task::JoinError) -> Self {
314
1
        Self::from_std_err(Code::Internal, &err)
315
1
    }
316
}
317
318
impl<T> From<PoisonError<MutexGuard<'_, T>>> for Error {
319
0
    fn from(err: PoisonError<MutexGuard<'_, T>>) -> Self {
320
0
        Self::from_std_err(Code::Internal, &err)
321
0
    }
322
}
323
324
impl From<serde_json5::Error> for Error {
325
1
    fn from(err: serde_json5::Error) -> Self {
326
1
        match err {
327
1
            serde_json5::Error::Message { msg, location } => {
328
1
                if let Some(has_location) = location {
329
1
                    make_err!(
330
1
                        Code::Internal,
331
                        "line {}, column {} - {}",
332
                        has_location.line,
333
                        has_location.column,
334
                        msg
335
                    )
336
                } else {
337
0
                    Self::new(Code::Internal, msg)
338
                }
339
            }
340
        }
341
1
    }
342
}
343
344
impl From<core::num::ParseIntError> for Error {
345
2
    fn from(err: core::num::ParseIntError) -> Self {
346
2
        Self::from_std_err(Code::InvalidArgument, &err)
347
2
    }
348
}
349
350
impl From<core::convert::Infallible> for Error {
351
0
    fn from(_err: core::convert::Infallible) -> Self {
352
        // Infallible is an error type that can never happen.
353
0
        unreachable!();
354
    }
355
}
356
357
impl From<TimestampError> for Error {
358
0
    fn from(err: TimestampError) -> Self {
359
0
        Self::from_std_err(Code::InvalidArgument, &err)
360
0
    }
361
}
362
363
impl From<AcquireError> for Error {
364
0
    fn from(err: AcquireError) -> Self {
365
0
        Self::from_std_err(Code::Internal, &err)
366
0
    }
367
}
368
369
impl From<Utf8Error> for Error {
370
0
    fn from(err: Utf8Error) -> Self {
371
0
        Self::from_std_err(Code::Internal, &err)
372
0
    }
373
}
374
375
#[cfg(target_os = "linux")]
376
impl From<caps::errors::CapsError> for Error {
377
0
    fn from(err: caps::errors::CapsError) -> Self {
378
0
        Self::from_std_err(Code::Internal, &err)
379
0
    }
380
}
381
382
impl From<std::io::Error> for Error {
383
1.38k
    fn from(err: std::io::Error) -> Self {
384
1.38k
        Self {
385
1.38k
            code: err.kind().into_code(),
386
1.38k
            messages: vec![err.to_string()],
387
1.38k
            context: ErrorContext::None,
388
1.38k
        }
389
1.38k
    }
390
}
391
392
impl From<redis::RedisError> for Error {
393
610
    fn from(error: redis::RedisError) -> Self {
394
        use redis::ErrorKind::{
395
            AuthenticationFailed, ClusterConnectionNotFound, EmptySentinelList, Extension,
396
            InvalidClientConfig, Io as IoError, MasterNameNotFoundBySentinel,
397
            NoValidReplicasFoundBySentinel, Parse as ParseError, RESP3NotSupported, Server,
398
            UnexpectedReturnType,
399
        };
400
        use redis::ServerErrorKind::{
401
            BusyLoading, ClusterDown, MasterDown, NoPerm, ReadOnly, TryAgain,
402
        };
403
404
        // Conversions here are based on https://grpc.github.io/grpc/core/md_doc_statuscodes.html.
405
        //
406
        // The distinction that matters most is retryable vs not. These statuses
407
        // reach REAPI clients directly, and Bazel treats INVALID_ARGUMENT as
408
        // permanent: it fails the build instantly rather than retrying. So
409
        // anything caused by the state of the Redis deployment — a failover in
410
        // progress, a dropped connection, a node still loading its dataset —
411
        // must NOT land there, or a routine blip becomes a failed CI run.
412
610
        let code = match error.kind() {
413
3
            AuthenticationFailed | Server(NoPerm) => Code::PermissionDenied,
414
415
            // Topology in flux. Sentinel failover makes these normal and
416
            // brief: the master moved and the client has not caught up yet.
417
            // Surfacing MasterNameNotFoundBySentinel as INVALID_ARGUMENT is
418
            // what turned a 1-2 minute sentinel failover into a dead build.
419
            MasterNameNotFoundBySentinel
420
            | NoValidReplicasFoundBySentinel
421
            | ClusterConnectionNotFound
422
            | Server(ClusterDown | MasterDown | TryAgain | BusyLoading | ReadOnly) => {
423
27
                Code::Unavailable
424
            }
425
426
            // A timeout is worth distinguishing from a dead connection, but
427
            // both are transient and both are retryable.
428
            IoError => {
429
551
                if error.is_timeout() {
430
10
                    Code::DeadlineExceeded
431
                } else {
432
541
                    Code::Unavailable
433
                }
434
            }
435
436
            // Genuine misconfiguration by the operator — retrying cannot help.
437
4
            InvalidClientConfig | EmptySentinelList | RESP3NotSupported => Code::InvalidArgument,
438
439
            // Server-side or protocol faults. Not the caller's argument, so
440
            // not InvalidArgument: a malformed reply is our problem or the
441
            // server's, and it is at least worth a retry.
442
2
            ParseError | UnexpectedReturnType => Code::Internal,
443
444
            // A server at its maxmemory with noeviction refuses every write
445
            // with OOM. The client knows no kind for it, so it arrives as an
446
            // extension code; it is the server out of room, nothing wrong
447
            // with the command.
448
8
            Extension if error.code() == Some("OOM"
)5
=>
Code::ResourceExhausted5
,
449
450
18
            _ => Code::Unknown,
451
        };
452
453
610
        let kind = error.kind();
454
610
        make_err!(code, "{kind:?}: {error}")
455
610
    }
456
}
457
458
impl From<tonic::Status> for Error {
459
231
    fn from(status: tonic::Status) -> Self {
460
        // tonic codes a mid-stream transport/`hyper` failure (a connection reset
461
        // or broken pipe during a large streaming write) as `Code::Unknown`
462
        // with message "transport error". But a broken connection is transient
463
        // and retryable — the gRPC status model reserves `UNKNOWN` for genuinely
464
        // unmapped errors and codes transport failures `UNAVAILABLE`. Left as
465
        // `Unknown`, such a blip falls outside both our own `Retrier`'s and most
466
        // clients' retry sets, so a retryable failure becomes terminal and
467
        // cacheable uploads are silently dropped. Remap transport-originated
468
        // `Unknown` to `Unavailable`.
469
231
        let code = if status.code() == Code::Unknown && 
is_transport_status8
(
&status8
) {
470
4
            Code::Unavailable
471
        } else {
472
227
            status.code()
473
        };
474
231
        Self::new(code, status.to_string())
475
231
    }
476
}
477
478
/// Whether a `tonic::Status` originates from a transport-layer failure (a
479
/// reset/broken connection), which tonic surfaces as `Code::Unknown`.
480
///
481
/// tonic's own `Status::from_error` already maps the failures it recognizes
482
/// (for example a connect refusal) to `Unavailable`; the `Unknown` shape
483
/// arises for transport errors it does not, and for statuses that crossed a
484
/// process boundary. Detection is downcast-first: precise when the concrete
485
/// transport error is still reachable in the source chain; falls back to the
486
/// message otherwise.
487
8
fn is_transport_status(status: &tonic::Status) -> bool {
488
8
    let mut source = std::error::Error::source(status);
489
12
    while let Some(
err5
) = source {
490
5
        if err.is::<tonic::transport::Error>() {
491
1
            return true;
492
4
        }
493
4
        source = err.source();
494
    }
495
    // Fallback for a `Status` reconstructed from the wire, where the concrete
496
    // transport error is no longer in the source chain and only the message
497
    // survives. `tonic::transport::Error` renders as exactly "transport
498
    // error" (no detail suffix), and this crate's own `From<Error> for
499
    // Status` re-encodes a proxied one as "transport error : <appended
500
    // context>". Anchor to those two shapes — an unanchored `contains` would
501
    // reclassify any app-level `Unknown` whose message merely mentions
502
    // "transport error" as retryable `Unavailable`.
503
7
    let msg = status.message();
504
7
    msg == "transport error" || 
msg5
.
starts_with5
("transport error : ")
505
8
}
506
507
impl From<Error> for tonic::Status {
508
288
    fn from(val: Error) -> Self {
509
288
        Self::new(val.code, val.messages.join(" : "))
510
288
    }
511
}
512
513
impl From<walkdir::Error> for Error {
514
1
    fn from(err: walkdir::Error) -> Self {
515
1
        Self::from_std_err(Code::Internal, &err)
516
1
    }
517
}
518
519
impl From<uuid::Error> for Error {
520
0
    fn from(err: uuid::Error) -> Self {
521
0
        Self::from_std_err(Code::Internal, &err)
522
0
    }
523
}
524
525
impl From<rustls_pki_types::pem::Error> for Error {
526
0
    fn from(err: rustls_pki_types::pem::Error) -> Self {
527
0
        Self::from_std_err(Code::Internal, &err)
528
0
    }
529
}
530
531
impl From<tokio::time::error::Elapsed> for Error {
532
0
    fn from(err: tokio::time::error::Elapsed) -> Self {
533
0
        Self::from_std_err(Code::DeadlineExceeded, &err)
534
0
    }
535
}
536
537
impl From<url::ParseError> for Error {
538
0
    fn from(err: url::ParseError) -> Self {
539
0
        Self::from_std_err(Code::Internal, &err)
540
0
    }
541
}
542
543
impl From<mongodb::error::Error> for Error {
544
0
    fn from(err: mongodb::error::Error) -> Self {
545
0
        Self::from_std_err(Code::Internal, &err)
546
0
    }
547
}
548
549
impl From<reqwest::Error> for Error {
550
0
    fn from(err: reqwest::Error) -> Self {
551
0
        Self::from_std_err(Code::Internal, &err)
552
0
    }
553
}
554
555
impl From<zip::result::ZipError> for Error {
556
0
    fn from(err: zip::result::ZipError) -> Self {
557
0
        Self::from_std_err(Code::Internal, &err)
558
0
    }
559
}
560
561
impl From<std::ffi::NulError> for Error {
562
0
    fn from(err: std::ffi::NulError) -> Self {
563
0
        Self::from_std_err(Code::Internal, &err)
564
0
    }
565
}
566
567
impl From<base64::DecodeError> for Error {
568
0
    fn from(err: base64::DecodeError) -> Self {
569
0
        Self::from_std_err(Code::Internal, &err)
570
0
    }
571
}
572
573
impl From<jiff::Error> for Error {
574
0
    fn from(err: jiff::Error) -> Self {
575
0
        Self::from_std_err(Code::Internal, &err)
576
0
    }
577
}
578
579
pub trait ResultExt<T> {
580
    /// # Errors
581
    ///
582
    /// Will return `Err` if we can't convert the error.
583
    fn err_tip_with_code<F, S>(self, tip_fn: F) -> Result<T, Error>
584
    where
585
        Self: Sized,
586
        S: ToString,
587
        F: (FnOnce(&Error) -> (Code, S)) + Sized;
588
589
    /// # Errors
590
    ///
591
    /// Will return `Err` if we can't convert the error.
592
    #[inline]
593
31.0M
    fn err_tip<F, S>(self, tip_fn: F) -> Result<T, Error>
594
31.0M
    where
595
31.0M
        Self: Sized,
596
31.0M
        S: ToString,
597
31.0M
        F: (FnOnce() -> S) + Sized,
598
    {
599
31.0M
        self.err_tip_with_code(|e| (
e.code4.16k
,
tip_fn()4.16k
))
600
31.0M
    }
601
602
    /// # Errors
603
    ///
604
    /// Will return `Err` if we can't merge the errors.
605
0
    fn merge<U>(self, _other: Result<U, Error>) -> Result<U, Error>
606
0
    where
607
0
        Self: Sized,
608
    {
609
0
        unreachable!();
610
    }
611
}
612
613
impl<T, E: Into<Error>> ResultExt<T> for Result<T, E> {
614
    #[inline]
615
28.2M
    fn err_tip_with_code<F, S>(self, tip_fn: F) -> Result<T, Error>
616
28.2M
    where
617
28.2M
        Self: Sized,
618
28.2M
        S: ToString,
619
28.2M
        F: (FnOnce(&Error) -> (Code, S)) + Sized,
620
    {
621
28.2M
        self.map_err(|e| 
{3.47k
622
3.47k
            let mut error: Error = e.into();
623
3.47k
            let (code, message) = tip_fn(&error);
624
3.47k
            error.code = code;
625
3.47k
            error.messages.push(message.to_string());
626
3.47k
            error
627
3.47k
        })
628
28.2M
    }
629
630
71.6k
    fn merge<U>(self, other: Result<U, Error>) -> Result<U, Error>
631
71.6k
    where
632
71.6k
        Self: Sized,
633
    {
634
71.6k
        if let Err(
e395
) = self {
635
395
            let mut e: Error = e.into();
636
395
            if let Err(
other_err205
) = other {
637
205
                let mut other_err: Error = other_err;
638
205
                // This will help with knowing which messages are tied to different errors.
639
205
                e.messages.push("---".to_string());
640
205
                e.messages.append(&mut other_err.messages);
641
205
            
}190
642
395
            return Err(e);
643
71.2k
        }
644
71.2k
        other
645
71.6k
    }
646
}
647
648
impl<T> ResultExt<T> for Option<T> {
649
    #[inline]
650
2.84M
    fn err_tip_with_code<F, S>(self, tip_fn: F) -> Result<T, Error>
651
2.84M
    where
652
2.84M
        Self: Sized,
653
2.84M
        S: ToString,
654
2.84M
        F: (FnOnce(&Error) -> (Code, S)) + Sized,
655
    {
656
2.84M
        self.ok_or_else(|| 
{780
657
780
            let mut error = Error {
658
780
                code: Code::Internal,
659
780
                messages: vec![],
660
780
                context: ErrorContext::None,
661
780
            };
662
780
            let (code, message) = tip_fn(&error);
663
780
            error.code = code;
664
780
            error.messages.push(message.to_string());
665
780
            error
666
780
        })
667
2.84M
    }
668
}
669
670
trait CodeExt {
671
    fn into_error_kind(self) -> std::io::ErrorKind;
672
}
673
674
impl CodeExt for Code {
675
1
    fn into_error_kind(self) -> std::io::ErrorKind {
676
1
        match self {
677
0
            Self::Aborted => std::io::ErrorKind::Interrupted,
678
0
            Self::AlreadyExists => std::io::ErrorKind::AlreadyExists,
679
0
            Self::DeadlineExceeded => std::io::ErrorKind::TimedOut,
680
0
            Self::InvalidArgument => std::io::ErrorKind::InvalidInput,
681
0
            Self::NotFound => std::io::ErrorKind::NotFound,
682
0
            Self::PermissionDenied => std::io::ErrorKind::PermissionDenied,
683
0
            Self::Unavailable => std::io::ErrorKind::ConnectionRefused,
684
1
            _ => std::io::ErrorKind::Other,
685
        }
686
1
    }
687
}
688
689
trait ErrorKindExt {
690
    fn into_code(self) -> Code;
691
}
692
693
impl ErrorKindExt for std::io::ErrorKind {
694
1.38k
    fn into_code(self) -> Code {
695
1.38k
        match self {
696
1.37k
            Self::NotFound => Code::NotFound,
697
1
            Self::PermissionDenied => Code::PermissionDenied,
698
            Self::ConnectionRefused | Self::ConnectionReset | Self::ConnectionAborted => {
699
1
                Code::Unavailable
700
            }
701
1
            Self::AlreadyExists => Code::AlreadyExists,
702
0
            Self::InvalidInput | Self::InvalidData => Code::InvalidArgument,
703
0
            Self::TimedOut => Code::DeadlineExceeded,
704
0
            Self::Interrupted => Code::Aborted,
705
            Self::NotConnected
706
            | Self::AddrInUse
707
            | Self::AddrNotAvailable
708
            | Self::BrokenPipe
709
            | Self::WouldBlock
710
            | Self::WriteZero
711
            | Self::Other
712
3
            | Self::UnexpectedEof => Code::Internal,
713
3
            _ => Code::Unknown,
714
        }
715
1.38k
    }
716
}
717
718
// Serde definition for tonic::Code. See: https://serde.rs/remote-derive.html
719
#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
720
#[serde(remote = "Code")]
721
pub enum CodeDef {
722
    Ok = 0,
723
    Cancelled = 1,
724
    Unknown = 2,
725
    InvalidArgument = 3,
726
    DeadlineExceeded = 4,
727
    NotFound = 5,
728
    AlreadyExists = 6,
729
    PermissionDenied = 7,
730
    ResourceExhausted = 8,
731
    FailedPrecondition = 9,
732
    Aborted = 10,
733
    OutOfRange = 11,
734
    Unimplemented = 12,
735
    Internal = 13,
736
    Unavailable = 14,
737
    DataLoss = 15,
738
    Unauthenticated = 16,
739
    // NOTE: Additional codes must be added to stores.rs in ErrorCodes and also
740
    // in both match statements in retry.rs.
741
}