1use 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#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
37#[non_exhaustive]
38pub enum ErrorKind {
39 InvalidInput,
41 Unauthenticated,
43 PermissionDenied,
45 NotFound,
47 Conflict,
49 RateLimited,
51 Unavailable,
53 Timeout,
55 Cancelled,
57 InvalidResponse,
59 Incomplete,
61 Closed,
63 Internal,
65}
66
67#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
69#[non_exhaustive]
70pub enum ErrorOperation {
71 BuildClient,
73 BuildAppendWriter,
75 BuildAppendStream,
77 Append,
79 WriteRows,
81 AdmitRows,
83 Flush,
85 Shutdown,
87 SubmitStatement,
89 ExecuteStatement,
91 RefreshStatement,
93 WaitStatement,
95 CancelStatement,
97 ReadCatalog,
99 ApplyCatalog,
101 DeleteCatalog,
103 DecodeResult,
105 ParseDataType,
107}
108
109impl ErrorKind {
110 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 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#[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
199#[serde(rename_all = "snake_case")]
200#[non_exhaustive]
201pub enum WriteErrorReason {
202 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#[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#[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 pub fn kind(&self) -> ErrorKind {
284 self.kind
285 }
286
287 pub fn message(&self) -> &str {
289 &self.message
290 }
291
292 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 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 pub fn http_status(&self) -> Option<StatusCode> {
314 self.diagnostics.as_deref().and_then(|d| d.http_status)
315 }
316
317 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 pub fn retry_after(&self) -> Option<Duration> {
326 self.diagnostics.as_deref().and_then(|d| d.retry_after)
327 }
328
329 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 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 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 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 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 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 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 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 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 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 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 pub fn operation(&self) -> ErrorOperation {
473 self.operation
474 }
475
476 pub fn retry_exhausted(&self) -> bool {
478 self.retry.exhausted
479 }
480
481 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 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}