Skip to main content

scopedb_client/
error.rs

1// Copyright 2024 ScopeDB, Inc.
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//     http://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 std::fmt;
16use std::sync::Arc;
17use std::time::Duration;
18
19use reqwest::StatusCode;
20use uuid::Uuid;
21
22use crate::AppendAdmissionResult;
23use crate::AppendDeliveryOutcome;
24use crate::AppendDeliveryReport;
25use crate::AppendErrorDetails;
26use crate::AppendOutcome;
27use crate::AppendTrySendError;
28use crate::AppendWriteReport;
29use crate::CatalogMutationOutcome;
30use crate::StatementErrorDetails;
31
32/// Broad failure category for [`Error`].
33///
34/// Combine with [`Error::operation`] for the failed SDK operation and [`Error::is_retryable`] for
35/// retry safety.
36#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
37#[non_exhaustive]
38pub enum ErrorKind {
39    /// Invalid configuration, input data, or query arguments.
40    InvalidInput,
41    /// Missing or invalid authentication credentials.
42    Unauthenticated,
43    /// Insufficient permissions for the operation.
44    PermissionDenied,
45    /// Referenced resource or statement execution does not exist.
46    NotFound,
47    /// Version precondition or concurrent state conflict.
48    Conflict,
49    /// Request rate or local admission buffer limit reached.
50    RateLimited,
51    /// Service or transport is temporarily unavailable.
52    Unavailable,
53    /// Client or server deadline expired.
54    Timeout,
55    /// Statement execution reached a cancelled terminal state.
56    Cancelled,
57    /// Response body, headers, or result cells violated the protocol contract.
58    InvalidResponse,
59    /// Aggregate operation left input unconfirmed; inspect the attached report on [`Error`].
60    Incomplete,
61    /// Stream is closed and no longer accepts rows.
62    Closed,
63    /// Unclassified server or internal SDK error.
64    Internal,
65}
66
67/// Public SDK operation that produced an [`Error`].
68#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
69#[non_exhaustive]
70pub enum ErrorOperation {
71    /// Building a [`Client`](crate::Client).
72    BuildClient,
73    /// Building an [`AppendWriter`](crate::AppendWriter).
74    BuildAppendWriter,
75    /// Building an [`AppendStream`](crate::AppendStream).
76    BuildAppendStream,
77    /// Single-batch table append request, including retries.
78    Append,
79    /// Finite-slice write through [`AppendWriter::write`](crate::AppendWriter::write).
80    WriteRows,
81    /// Local row admission into an [`AppendStream`](crate::AppendStream).
82    AdmitRows,
83    /// Flushing an [`AppendStream`](crate::AppendStream).
84    Flush,
85    /// Shutting down an [`AppendStream`](crate::AppendStream).
86    Shutdown,
87    /// Submitting a [`Statement`](crate::Statement).
88    SubmitStatement,
89    /// Executing a statement to completion (`query`, `execute`, or `Table::drop`).
90    ExecuteStatement,
91    /// Refreshing a [`StatementHandle`](crate::StatementHandle).
92    RefreshStatement,
93    /// Waiting on a [`StatementHandle`](crate::StatementHandle).
94    WaitStatement,
95    /// Cancelling a [`StatementHandle`](crate::StatementHandle).
96    CancelStatement,
97    /// Reading a catalog snapshot.
98    ReadCatalog,
99    /// Applying or previewing a catalog definition.
100    ApplyCatalog,
101    /// Deleting or previewing deletion of a catalog resource.
102    DeleteCatalog,
103    /// Decoding a [`ResultSet`](crate::ResultSet) into typed rows or objects.
104    DecodeResult,
105    /// Parsing a [`DataType`](crate::DataType) name.
106    ParseDataType,
107}
108
109impl ErrorKind {
110    /// Returns the stable snake-case label used in logs and metrics.
111    pub const fn as_str(self) -> &'static str {
112        match self {
113            Self::InvalidInput => "invalid_input",
114            Self::Unauthenticated => "unauthenticated",
115            Self::PermissionDenied => "permission_denied",
116            Self::NotFound => "not_found",
117            Self::Conflict => "conflict",
118            Self::RateLimited => "rate_limited",
119            Self::Unavailable => "unavailable",
120            Self::Timeout => "timeout",
121            Self::Cancelled => "cancelled",
122            Self::InvalidResponse => "invalid_response",
123            Self::Incomplete => "incomplete",
124            Self::Closed => "closed",
125            Self::Internal => "internal",
126        }
127    }
128
129    pub(crate) fn from_http(status: StatusCode) -> Self {
130        match status.as_u16() {
131            400 | 405 | 413 | 422 => Self::InvalidInput,
132            401 => Self::Unauthenticated,
133            403 => Self::PermissionDenied,
134            404 => Self::NotFound,
135            409 | 412 => Self::Conflict,
136            408 | 504 => Self::Timeout,
137            429 => Self::RateLimited,
138            500 => Self::Internal,
139            502 | 503 => Self::Unavailable,
140            _ if status.is_server_error() => Self::Unavailable,
141            _ => Self::Internal,
142        }
143    }
144
145    pub(crate) fn from_statement_code(code: &str) -> Self {
146        match code {
147            "bad_request" | "invalid_request" | "payload_too_large" => Self::InvalidInput,
148            "not_found" => Self::NotFound,
149            "unauthorized" => Self::Unauthenticated,
150            "conflict" | "precondition_failed" => Self::Conflict,
151            "too_many_requests" => Self::RateLimited,
152            "service_unavailable" | "unavailable" => Self::Unavailable,
153            "statement_timeout" | "request_timeout" | "timeout" => Self::Timeout,
154            _ => Self::Internal,
155        }
156    }
157}
158
159impl ErrorOperation {
160    /// Returns the stable snake-case label used in logs and metrics.
161    pub const fn as_str(self) -> &'static str {
162        match self {
163            Self::BuildClient => "build_client",
164            Self::BuildAppendWriter => "build_append_writer",
165            Self::BuildAppendStream => "build_append_stream",
166            Self::Append => "append",
167            Self::WriteRows => "write_rows",
168            Self::AdmitRows => "admit_rows",
169            Self::Flush => "flush",
170            Self::Shutdown => "shutdown",
171            Self::SubmitStatement => "submit_statement",
172            Self::ExecuteStatement => "execute_statement",
173            Self::RefreshStatement => "refresh_statement",
174            Self::WaitStatement => "wait_statement",
175            Self::CancelStatement => "cancel_statement",
176            Self::ReadCatalog => "read_catalog",
177            Self::ApplyCatalog => "apply_catalog",
178            Self::DeleteCatalog => "delete_catalog",
179            Self::DecodeResult => "decode_result",
180            Self::ParseDataType => "parse_data_type",
181        }
182    }
183}
184
185impl fmt::Display for ErrorKind {
186    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
187        f.write_str(self.as_str())
188    }
189}
190
191impl fmt::Display for ErrorOperation {
192    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
193        f.write_str(self.as_str())
194    }
195}
196
197/// Reason an in-flight append request was interrupted on the client.
198#[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
199#[serde(rename_all = "snake_case")]
200#[non_exhaustive]
201pub enum WriteErrorReason {
202    /// A client or transport deadline expired.
203    Timeout,
204}
205
206impl fmt::Display for WriteErrorReason {
207    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
208        f.write_str(match self {
209            Self::Timeout => "timeout",
210        })
211    }
212}
213
214/// Client-side interruption details for an append request.
215///
216/// When `outcome` is [`AppendOutcome::Ambiguous`], the request may have committed on the server.
217#[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
218#[non_exhaustive]
219pub struct WriteErrorDetails {
220    pub reason: WriteErrorReason,
221    pub outcome: AppendOutcome,
222}
223
224#[derive(Debug, Default, Clone)]
225struct RetryFacts {
226    transient: bool,
227    exhausted: bool,
228    retries: usize,
229}
230
231#[derive(Debug, Default, Clone)]
232struct ErrorDiagnostics {
233    code: Option<String>,
234    details: Option<serde_json::Value>,
235    http_status: Option<StatusCode>,
236    request_id: Option<String>,
237    retry_after: Option<Duration>,
238    server_retryable: Option<bool>,
239    context: Vec<(&'static str, String)>,
240}
241
242#[derive(Debug, Clone)]
243enum FailureDetails {
244    Admission(Arc<AppendTrySendError>),
245    Append {
246        details: AppendErrorDetails,
247        interruption: Option<WriteErrorDetails>,
248    },
249    Statement {
250        id: Option<Uuid>,
251        details: Option<StatementErrorDetails>,
252        submitted: bool,
253    },
254    Catalog(CatalogMutationOutcome),
255}
256
257#[derive(Debug, Clone)]
258enum AppendProgress {
259    Admission(AppendAdmissionResult),
260    Write {
261        input_index: Option<usize>,
262        report: AppendWriteReport,
263    },
264    Delivery(AppendDeliveryReport),
265}
266
267/// Failure returned by an SDK operation, carrying recovery data and server diagnostics.
268#[doc = include_str!("../docs/errors.md")]
269#[derive(Clone)]
270pub struct Error {
271    kind: ErrorKind,
272    message: String,
273    operation: ErrorOperation,
274    retry: RetryFacts,
275    diagnostics: Option<Box<ErrorDiagnostics>>,
276    failure: Option<Box<FailureDetails>>,
277    progress: Option<Box<AppendProgress>>,
278    source: Option<Arc<dyn std::error::Error + Send + Sync>>,
279}
280
281impl Error {
282    /// Returns the failure category.
283    pub fn kind(&self) -> ErrorKind {
284        self.kind
285    }
286
287    /// Returns the operation-level error message.
288    pub fn message(&self) -> &str {
289        &self.message
290    }
291
292    /// Returns the server error code, if the server supplied one.
293    ///
294    /// This is the response body's string category, such as `too_many_requests`.
295    /// Use [`http_status`](Self::http_status) for the HTTP status and
296    /// [`append_details`](Self::append_details) for an append's commit outcome.
297    pub fn code(&self) -> Option<&str> {
298        self.diagnostics
299            .as_deref()
300            .and_then(|d| d.code.as_deref())
301            .or_else(|| self.statement_details().map(|d| d.code.as_str()))
302    }
303
304    /// Returns the structured server error details from the last failed response.
305    pub fn details(&self) -> Option<&serde_json::Value> {
306        self.diagnostics
307            .as_deref()
308            .and_then(|d| d.details.as_ref())
309            .or_else(|| self.statement_details().and_then(|d| d.details.as_ref()))
310    }
311
312    /// Returns the HTTP status code from the last failed response.
313    pub fn http_status(&self) -> Option<StatusCode> {
314        self.diagnostics.as_deref().and_then(|d| d.http_status)
315    }
316
317    /// Returns the server request ID, if present.
318    pub fn request_id(&self) -> Option<&str> {
319        self.diagnostics
320            .as_deref()
321            .and_then(|d| d.request_id.as_deref())
322    }
323
324    /// Returns the server `Retry-After` delay, if present.
325    pub fn retry_after(&self) -> Option<Duration> {
326        self.diagnostics.as_deref().and_then(|d| d.retry_after)
327    }
328
329    /// Returns table-append failure details across all attempts of the failed request.
330    ///
331    /// `status` remains [`AppendOutcome::Ambiguous`] if any attempt had an ambiguous
332    /// outcome, even when a later attempt failed definitely. `row_errors`
333    /// come from the last failed response.
334    pub fn append_details(&self) -> Option<&AppendErrorDetails> {
335        match self.failure.as_deref() {
336            Some(FailureDetails::Append { details, .. }) => Some(details),
337            _ => None,
338        }
339    }
340
341    /// Returns client-side timeout details when an append attempt timed out.
342    pub fn write_details(&self) -> Option<&WriteErrorDetails> {
343        match self.failure.as_deref() {
344            Some(FailureDetails::Append { interruption, .. }) => interruption.as_ref(),
345            _ => None,
346        }
347    }
348
349    /// Returns the commit outcome of a failed catalog mutation.
350    ///
351    /// Returns [`CatalogMutationOutcome::Unknown`] when the mutation may have
352    /// committed, [`CatalogMutationOutcome::Rejected`] when the server rejected
353    /// it without committing, or `None` for reads, dry runs, and local
354    /// validation errors.
355    pub fn catalog_outcome(&self) -> Option<CatalogMutationOutcome> {
356        match self.failure.as_deref() {
357            Some(FailureDetails::Catalog(outcome)) => Some(*outcome),
358            _ => None,
359        }
360    }
361
362    /// Returns the statement ID associated with a failed statement operation.
363    ///
364    /// Pass this ID to [`Client::statement_handle`](crate::Client::statement_handle) to inspect or
365    /// wait on the execution after a lost submission response or post-submission
366    /// read failure.
367    pub fn statement_id(&self) -> Option<Uuid> {
368        match self.failure.as_deref() {
369            Some(FailureDetails::Statement { id, .. }) => *id,
370            _ => None,
371        }
372    }
373
374    /// Returns structured error details for a statement that terminated in
375    /// [`StatementStatus::Failed`](crate::StatementStatus::Failed).
376    pub fn statement_details(&self) -> Option<&StatementErrorDetails> {
377        match self.failure.as_deref() {
378            Some(FailureDetails::Statement { details, .. }) => details.as_ref(),
379            _ => None,
380        }
381    }
382
383    /// Returns the underlying [`AppendTrySendError`] when converted into [`Error`].
384    pub fn try_send_error(&self) -> Option<&AppendTrySendError> {
385        match self.failure.as_deref() {
386            Some(FailureDetails::Admission(error)) => Some(error.as_ref()),
387            _ => None,
388        }
389    }
390
391    /// Returns admission progress for a failed
392    /// [`AppendStream::send_all`](crate::AppendStream::send_all) call.
393    ///
394    /// Admitted rows remain owned by the stream. Use `flush()` or `shutdown()`
395    /// to observe their delivery.
396    pub fn append_admission(&self) -> Option<&AppendAdmissionResult> {
397        match self.progress.as_deref() {
398            Some(AppendProgress::Admission(result)) => Some(result),
399            _ => None,
400        }
401    }
402
403    /// Returns the per-batch report for a failed
404    /// [`AppendWriter::write`](crate::AppendWriter::write) call.
405    pub fn append_write_report(&self) -> Option<&AppendWriteReport> {
406        match self.progress.as_deref() {
407            Some(AppendProgress::Write { report, .. }) => Some(report),
408            _ => None,
409        }
410    }
411
412    /// Returns the input slice index of the row that failed local encoding in
413    /// [`AppendWriter::write`](crate::AppendWriter::write).
414    ///
415    /// For server-side row validation errors, map
416    /// [`AppendRowError::row_index`](crate::AppendRowError::row_index)
417    /// with [`AppendRequestResult::input_index`](crate::AppendRequestResult::input_index).
418    pub fn append_input_index(&self) -> Option<usize> {
419        match self.progress.as_deref() {
420            Some(AppendProgress::Write { input_index, .. }) => *input_index,
421            _ => None,
422        }
423    }
424
425    /// Returns the terminal delivery report for a failed
426    /// [`AppendStream::flush`](crate::AppendStream::flush) or
427    /// [`AppendStream::shutdown`](crate::AppendStream::shutdown).
428    pub fn append_delivery_report(&self) -> Option<&AppendDeliveryReport> {
429        match self.progress.as_deref() {
430            Some(AppendProgress::Delivery(report)) => Some(report),
431            _ => None,
432        }
433    }
434
435    /// Returns whether repeating the failed SDK call as-is is safe and useful.
436    ///
437    /// Returns `false` for unknown write outcomes, aggregate progress reports,
438    /// and submitted SQL execution errors. Transient status-read failures can
439    /// be retried on the existing statement handle.
440    pub fn is_retryable(&self) -> bool {
441        if !self.retry.transient
442            || self.retry.exhausted
443            || self.progress.is_some()
444            || self.kind == ErrorKind::Closed
445            || self.catalog_outcome() == Some(CatalogMutationOutcome::Unknown)
446            || self
447                .append_details()
448                .is_some_and(|details| details.status == AppendOutcome::Ambiguous)
449        {
450            return false;
451        }
452        if matches!(
453            self.operation,
454            ErrorOperation::SubmitStatement | ErrorOperation::ExecuteStatement
455        ) {
456            let submitted = matches!(
457                self.failure.as_deref(),
458                Some(FailureDetails::Statement {
459                    submitted: true,
460                    ..
461                })
462            );
463            return !submitted
464                && self.http_status().is_some_and(|status| {
465                    status.is_client_error() && status != StatusCode::REQUEST_TIMEOUT
466                });
467        }
468        true
469    }
470
471    /// Returns the SDK operation that failed.
472    pub fn operation(&self) -> ErrorOperation {
473        self.operation
474    }
475
476    /// Returns whether a retryable append request exhausted its configured retry limit.
477    pub fn retry_exhausted(&self) -> bool {
478        self.retry.exhausted
479    }
480
481    /// Returns the number of retry attempts made by the failed append request.
482    pub fn retries(&self) -> usize {
483        self.retry.retries
484    }
485
486    pub(crate) fn new(
487        kind: ErrorKind,
488        operation: ErrorOperation,
489        message: impl Into<String>,
490    ) -> Self {
491        Self {
492            kind,
493            operation,
494            message: message.into(),
495            retry: RetryFacts::default(),
496            diagnostics: None,
497            failure: None,
498            progress: None,
499            source: None,
500        }
501    }
502
503    pub(crate) fn with_context(mut self, key: &'static str, value: impl ToString) -> Self {
504        self.diagnostics_mut()
505            .context
506            .push((key, value.to_string()));
507        self
508    }
509
510    /// Sets the underlying cause.
511    ///
512    /// # Panics
513    /// Panics if a source is already present.
514    pub(crate) fn set_source(
515        mut self,
516        source: impl std::error::Error + Send + Sync + 'static,
517    ) -> Self {
518        assert!(self.source.is_none(), "the source error has been set");
519        self.source = Some(Arc::new(source));
520        self
521    }
522
523    pub(crate) fn with_operation(mut self, operation: ErrorOperation) -> Self {
524        self.operation = operation;
525        self
526    }
527
528    pub(crate) fn is_transient(&self) -> bool {
529        self.retry.transient
530    }
531
532    pub(crate) fn with_transient_failure(mut self, transient: bool) -> Self {
533        self.retry.transient = transient;
534        self
535    }
536
537    pub(crate) fn with_retry_history(mut self, retries: usize, exhausted: bool) -> Self {
538        self.retry.exhausted = exhausted;
539        self.retry.retries = retries;
540        self
541    }
542
543    pub(crate) fn after_submission(mut self) -> Self {
544        if let Some(FailureDetails::Statement { submitted, .. }) = self.failure.as_deref_mut() {
545            *submitted = true;
546        }
547        self
548    }
549
550    pub(crate) fn for_closed_stream(mut self) -> Self {
551        self.kind = ErrorKind::Closed;
552        self.operation = ErrorOperation::AdmitRows;
553        self
554    }
555
556    pub(crate) fn with_append_admission(mut self, accepted_rows: u64) -> Self {
557        self.operation = ErrorOperation::AdmitRows;
558        if accepted_rows > 0 {
559            self.kind = ErrorKind::Incomplete;
560        }
561        self.progress = Some(Box::new(AppendProgress::Admission(AppendAdmissionResult {
562            accepted_rows,
563        })));
564        self
565    }
566
567    pub(crate) fn with_append_write(
568        mut self,
569        report: AppendWriteReport,
570        input_index: Option<usize>,
571    ) -> Self {
572        self.operation = ErrorOperation::WriteRows;
573        if !report.batches().is_empty() {
574            self.kind = ErrorKind::Incomplete;
575        }
576        self.progress = Some(Box::new(AppendProgress::Write {
577            report,
578            input_index,
579        }));
580        self
581    }
582
583    pub(crate) fn with_append_delivery(mut self, report: AppendDeliveryReport) -> Self {
584        if report.outcome != AppendDeliveryOutcome::Succeeded {
585            self.kind = ErrorKind::Incomplete;
586        }
587        self.progress = Some(Box::new(AppendProgress::Delivery(report)));
588        self
589    }
590
591    pub(crate) fn set_append_details(mut self, details: AppendErrorDetails) -> Self {
592        match self.failure.as_deref_mut() {
593            Some(FailureDetails::Append {
594                details: current, ..
595            }) => *current = details,
596            None => {
597                self.failure = Some(Box::new(FailureDetails::Append {
598                    details,
599                    interruption: None,
600                }))
601            }
602            _ => unreachable!("append details belong to an append failure"),
603        }
604        self
605    }
606
607    pub(crate) fn set_write_timeout(mut self) -> Self {
608        self.kind = ErrorKind::Timeout;
609        match self.failure.as_deref_mut() {
610            Some(FailureDetails::Append { interruption, .. }) => {
611                *interruption = Some(WriteErrorDetails {
612                    reason: WriteErrorReason::Timeout,
613                    outcome: AppendOutcome::Ambiguous,
614                })
615            }
616            _ => unreachable!("write interruption belongs to an append failure"),
617        }
618        self
619    }
620
621    pub(crate) fn set_catalog_outcome(mut self, outcome: CatalogMutationOutcome) -> Self {
622        self.failure = Some(Box::new(FailureDetails::Catalog(outcome)));
623        self
624    }
625
626    pub(crate) fn set_statement_id(mut self, id: Uuid) -> Self {
627        match self.failure.as_deref_mut() {
628            Some(FailureDetails::Statement { id: current, .. }) => *current = Some(id),
629            None => {
630                self.failure = Some(Box::new(FailureDetails::Statement {
631                    id: Some(id),
632                    details: None,
633                    submitted: false,
634                }))
635            }
636            _ => unreachable!("statement ID belongs to a statement failure"),
637        }
638        self
639    }
640
641    pub(crate) fn set_statement_details(mut self, details: StatementErrorDetails) -> Self {
642        match self.failure.as_deref_mut() {
643            Some(FailureDetails::Statement {
644                details: current, ..
645            }) => *current = Some(details),
646            None => {
647                self.failure = Some(Box::new(FailureDetails::Statement {
648                    id: None,
649                    details: Some(details),
650                    submitted: true,
651                }))
652            }
653            _ => unreachable!("statement details belong to a statement failure"),
654        }
655        self
656    }
657
658    pub(crate) fn set_http_status(mut self, status: StatusCode) -> Self {
659        self.diagnostics_mut().http_status = Some(status);
660        self
661    }
662    pub(crate) fn set_request_id(mut self, id: String) -> Self {
663        self.diagnostics_mut().request_id = Some(id);
664        self
665    }
666    pub(crate) fn set_retry_after(mut self, delay: Duration) -> Self {
667        self.diagnostics_mut().retry_after = Some(delay);
668        self
669    }
670    pub(crate) fn set_server_retryable(mut self, retryable: Option<bool>) -> Self {
671        self.diagnostics_mut().server_retryable = retryable;
672        self
673    }
674    pub(crate) fn server_retryable(&self) -> Option<bool> {
675        self.diagnostics.as_deref().and_then(|d| d.server_retryable)
676    }
677    pub(crate) fn set_api_error(
678        mut self,
679        code: Option<String>,
680        details: Option<serde_json::Value>,
681    ) -> Self {
682        if code.is_some() || details.is_some() {
683            let diagnostics = self.diagnostics_mut();
684            diagnostics.code = code;
685            diagnostics.details = details;
686        }
687        self
688    }
689    fn diagnostics_mut(&mut self) -> &mut ErrorDiagnostics {
690        self.diagnostics.get_or_insert_with(Default::default)
691    }
692}
693
694impl From<AppendTrySendError> for Error {
695    fn from(error: AppendTrySendError) -> Self {
696        let (kind, transient) = match &error {
697            AppendTrySendError::BufferFull => (ErrorKind::RateLimited, true),
698            AppendTrySendError::CircuitOpen => (ErrorKind::Unavailable, true),
699            AppendTrySendError::Closed => (ErrorKind::Closed, false),
700            _ => (ErrorKind::InvalidInput, false),
701        };
702        let message = match &error {
703            AppendTrySendError::Serialization(_) => "failed to serialize append row".to_string(),
704            _ => error.to_string(),
705        };
706        let mut failure =
707            Self::new(kind, ErrorOperation::AdmitRows, message).with_transient_failure(transient);
708        failure.failure = Some(Box::new(FailureDetails::Admission(Arc::new(error))));
709        failure
710    }
711}
712
713impl fmt::Display for Error {
714    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
715        write!(
716            f,
717            "{} failed [{}]: {}",
718            self.operation, self.kind, self.message
719        )?;
720        if let Some(diagnostics) = &self.diagnostics {
721            for (key, value) in &diagnostics.context {
722                write!(f, ", {key}: {value}")?;
723            }
724        }
725        if let Some(code) = self.code() {
726            write!(f, ", code: {code}")?;
727        }
728        if let Some(id) = self.statement_id() {
729            write!(f, ", statement_id: {id}")?;
730        }
731        if let Some(status) = self.http_status() {
732            write!(f, ", http_status: {}", status.as_u16())?;
733        }
734        if let Some(id) = self.request_id() {
735            write!(f, ", request_id: {id}")?;
736        }
737        if let Some(delay) = self.retry_after() {
738            write!(f, ", retry_after: {delay:?}")?;
739        }
740        if let Some(details) = self.append_details() {
741            write!(f, ", append_outcome: {}", details.status)?;
742        }
743        if let Some(details) = self.write_details() {
744            write!(
745                f,
746                ", write_reason: {}, write_outcome: {}",
747                details.reason, details.outcome
748            )?;
749        }
750        if let Some(outcome) = self.catalog_outcome() {
751            write!(f, ", catalog_outcome: {outcome:?}")?;
752        }
753        if let Some(admission) = self.append_admission() {
754            write!(f, ", accepted_rows: {}", admission.accepted_rows)?;
755        }
756        if let Some(report) = self.append_write_report() {
757            write!(
758                f,
759                ", committed_rows: {}, input_rows: {}, outcome: {:?}, unsubmitted: {:?}",
760                report.committed_rows(),
761                report.input_rows(),
762                report.outcome(),
763                report.unsubmitted()
764            )?;
765        }
766        if let Some(report) = self.append_delivery_report() {
767            write!(
768                f,
769                ", committed_rows: {}, accepted_rows: {}, ambiguous_rows: {}, outcome: {:?}",
770                report.committed_rows, report.accepted_rows, report.ambiguous_rows, report.outcome
771            )?;
772        }
773        Ok(())
774    }
775}
776
777impl fmt::Debug for Error {
778    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
779        if f.alternate() {
780            return f
781                .debug_struct("Error")
782                .field("kind", &self.kind)
783                .field("message", &self.message)
784                .field("operation", &self.operation)
785                .field("retry", &self.retry)
786                .field("diagnostics", &self.diagnostics)
787                .field("failure", &self.failure)
788                .field("progress", &self.progress)
789                .field("source", &self.source)
790                .finish();
791        }
792        write!(f, "{self}")?;
793        let mut cause = std::error::Error::source(self);
794        while let Some(error) = cause {
795            write!(f, "\n  caused by: {error}")?;
796            cause = error.source();
797        }
798        Ok(())
799    }
800}
801
802impl std::error::Error for Error {
803    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
804        self.source
805            .as_ref()
806            .map(|source| source.as_ref() as _)
807            .or_else(|| self.try_send_error().and_then(std::error::Error::source))
808    }
809}