1use std::error::Error as StdError;
4use std::fmt;
5use std::sync::Arc;
6
7pub type BoxError = Box<dyn StdError + Send + Sync + 'static>;
9pub type Result<T> = std::result::Result<T, NetError>;
11
12#[non_exhaustive]
13#[derive(Clone, Copy, Debug, Eq, PartialEq)]
14pub enum ErrorKind {
19 InvalidInput,
21 InvalidConfig,
23 Io,
25 Dns,
27 Tls,
29 Protocol,
31 HandshakeRejected,
33 ProviderFailed,
35 CallbackPanicked,
37 RuntimeUnavailable,
39 ResourceExhausted,
41 QueueFull,
43 QueueClosed,
45 ItemTooLarge,
47 PendingLimitReached,
49 SubscriptionLimitReached,
51 CallbackOverflow,
53 ControlOverflow,
55 ObservationLagged,
57 NotConnected,
59 NotRunning,
61 Unsupported,
63 SessionAlreadyExists,
65 ConnectionClosing,
67 Closed,
69 EngineDropped,
71 Cancelled,
73 TimedOut,
75 DeadlineExceeded,
77 DeliveryUnknown,
79 RetryExhausted,
81 InvalidPolicy,
83 BodyNotReplayable,
85 DuplicateRequestId,
87 RoutingDisabled,
89 RoutingModeMismatch,
91 ClientAlreadyExists,
93 ClientNotFound,
95 Internal,
97 HttpStatus,
99}
100
101#[non_exhaustive]
102#[derive(Clone, Copy, Debug, Eq, PartialEq)]
103pub enum ErrorStage {
108 Configuration,
110 Provider,
112 RequestBuild,
114 Dns,
116 Tcp,
118 Proxy,
120 ProxyTls,
122 Tls,
124 Upgrade,
126 Admission,
128 Queue,
130 Write,
132 Response,
134 Receive,
136 Heartbeat,
138 Close,
140 Dispatch,
142 NetworkMonitor,
144 Runtime,
146}
147
148#[non_exhaustive]
150#[derive(Clone, Default)]
151pub struct ErrorContext {
152 pub stage: Option<ErrorStage>,
156 #[cfg(feature = "ws-client")]
157 pub client_id: Option<crate::ws::ClientId>,
159 #[cfg(feature = "ws-client")]
160 pub session_id: Option<crate::ws::SessionId>,
162 #[cfg(feature = "ws-client")]
163 pub connection_id: Option<crate::ws::ConnectionId>,
165 #[cfg(feature = "ws-client")]
166 pub attempt_id: Option<crate::ws::AttemptId>,
168 #[cfg(feature = "ws-client")]
169 pub request_id: Option<crate::ws::RequestId>,
171 #[cfg(feature = "ws-client")]
172 pub ws_timeout_phase: Option<crate::ws::WsTimeoutPhase>,
174 pub http_status: Option<http::StatusCode>,
176 #[cfg(feature = "http-client")]
177 pub http_request_id: Option<crate::api::http::HttpRequestId>,
179 #[cfg(feature = "http-client")]
180 pub http_timeout_phase: Option<crate::api::http::TimeoutPhase>,
184 #[cfg(feature = "http-client")]
185 pub http_attempt: Option<u32>,
187 #[cfg(feature = "ws-client")]
188 pub diagnostic: Option<crate::ws::HandshakeDiagnostic>,
190 #[cfg(feature = "ws-client")]
191 pub peer_close: Option<crate::ws::PeerClose>,
193 #[cfg(feature = "ws-client")]
194 pub io_end: Option<crate::ws::IoEndKind>,
196}
197
198impl fmt::Debug for ErrorContext {
199 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
200 let mut output = formatter.debug_struct("ErrorContext");
201 output
202 .field("stage", &self.stage)
203 .field("http_status", &self.http_status);
204 #[cfg(feature = "http-client")]
205 output
206 .field("http_request_id", &self.http_request_id)
207 .field("http_timeout_phase", &self.http_timeout_phase)
208 .field("http_attempt", &self.http_attempt);
209 #[cfg(feature = "ws-client")]
210 output
211 .field("client_id", &self.client_id)
212 .field("session_id", &self.session_id)
213 .field("connection_id", &self.connection_id)
214 .field("attempt_id", &self.attempt_id)
215 .field("ws_timeout_phase", &self.ws_timeout_phase)
216 .field(
217 "request_id_len",
218 &self.request_id.as_ref().map(|id| id.as_str().len()),
219 )
220 .field(
221 "diagnostic_kind",
222 &self.diagnostic.as_ref().map(|value| value.kind()),
223 )
224 .field(
225 "peer_close_code",
226 &self.peer_close.as_ref().map(|value| value.code),
227 )
228 .field("io_end", &self.io_end);
229 output.finish()
230 }
231}
232
233#[derive(Clone)]
237pub struct NetError {
238 #[cfg(feature = "quality-doctor")]
239 quality_ref: Option<crate::quality::QualityReportRef>,
240 kind: ErrorKind,
241 context: ErrorContext,
242 config_error: Option<Arc<ConfigError>>,
243 source: Option<Arc<dyn StdError + Send + Sync + 'static>>,
244 retry_report: Option<Arc<crate::api::retry::RetryReport>>,
245 #[cfg(feature = "http-client")]
246 http_response_head: Option<Arc<crate::api::http::HttpResponseHead>>,
247}
248
249impl NetError {
250 #[cfg(feature = "quality-doctor")]
269 pub fn quality_ref(&self) -> Option<crate::quality::QualityReportRef> {
270 self.quality_ref.clone()
271 }
272
273 #[cfg(feature = "quality-doctor")]
274 pub(crate) fn with_quality_ref(mut self, reference: crate::quality::QualityReportRef) -> Self {
275 self.quality_ref = Some(reference);
276 self
277 }
278
279 pub fn from_http_status(status: http::StatusCode) -> Self {
281 let mut context = ErrorContext::default();
282 context.http_status = Some(status);
283 Self::new(ErrorKind::HttpStatus).with_context(context)
284 }
285 pub(crate) fn new(kind: ErrorKind) -> Self {
286 Self {
287 #[cfg(feature = "quality-doctor")]
288 quality_ref: None,
289 kind,
290 context: ErrorContext::default(),
291 config_error: None,
292 source: None,
293 retry_report: None,
294 #[cfg(feature = "http-client")]
295 http_response_head: None,
296 }
297 }
298
299 pub(crate) fn with_source(kind: ErrorKind, source: impl Into<BoxError>) -> Self {
300 let source: BoxError = source.into();
301 Self {
302 source: Some(Arc::from(source)),
303 ..Self::new(kind)
304 }
305 }
306
307 pub(crate) fn with_context(mut self, context: ErrorContext) -> Self {
308 self.context = context;
309 self
310 }
311
312 pub(crate) fn with_stage(mut self, stage: ErrorStage) -> Self {
313 self.context.stage = Some(stage);
314 self
315 }
316
317 #[cfg(feature = "http-client")]
318 pub(crate) fn with_http_request_id(
319 mut self,
320 request_id: crate::api::http::HttpRequestId,
321 ) -> Self {
322 self.context.http_request_id = Some(request_id);
323 self
324 }
325
326 pub(crate) fn config(field: impl Into<String>, reason: impl Into<String>) -> Self {
327 ConfigError::new(field, reason).into()
328 }
329
330 #[cfg(feature = "http-client")]
331 pub(crate) fn with_http_attempt(mut self, attempt: u32) -> Self {
332 self.context.http_attempt = Some(attempt);
333 self
334 }
335
336 #[cfg(feature = "http-client")]
337 pub(crate) fn with_timeout_phase(mut self, phase: crate::api::http::TimeoutPhase) -> Self {
338 self.context.http_timeout_phase = Some(phase);
339 self
340 }
341
342 #[cfg(feature = "ws-client")]
343 pub(crate) fn with_ws_timeout_phase(mut self, phase: crate::ws::WsTimeoutPhase) -> Self {
344 self.context.ws_timeout_phase = Some(phase);
345 self
346 }
347
348 pub(crate) fn input(field: impl Into<String>, reason: impl Into<String>) -> Self {
349 Self {
350 config_error: Some(Arc::new(ConfigError::new(field, reason))),
351 ..Self::new(ErrorKind::InvalidInput).with_stage(ErrorStage::RequestBuild)
352 }
353 }
354
355 pub(crate) fn from_poison<T>(_: std::sync::PoisonError<T>) -> Self {
356 Self::new(ErrorKind::Internal)
359 }
360
361 pub fn kind(&self) -> ErrorKind {
363 self.kind
364 }
365
366 pub fn context(&self) -> &ErrorContext {
368 &self.context
369 }
370
371 pub fn retry_report(&self) -> Option<&crate::api::retry::RetryReport> {
376 self.retry_report.as_deref()
377 }
378
379 pub(crate) fn with_retry_report(mut self, report: crate::api::retry::RetryReport) -> Self {
380 self.retry_report = Some(Arc::new(report));
381 self
382 }
383
384 #[cfg(feature = "http-client")]
390 pub fn timeout_phase(&self) -> Option<crate::api::http::TimeoutPhase> {
391 self.context.http_timeout_phase
392 }
393
394 #[cfg(feature = "ws-client")]
399 pub fn ws_timeout_phase(&self) -> Option<crate::ws::WsTimeoutPhase> {
400 self.context.ws_timeout_phase
401 }
402
403 pub fn http_status(&self) -> Option<http::StatusCode> {
405 self.context.http_status
406 }
407
408 #[cfg(feature = "http-client")]
415 pub fn http_response_head(&self) -> Option<&crate::api::http::HttpResponseHead> {
416 self.http_response_head.as_deref()
417 }
418
419 #[cfg(feature = "http-client")]
420 pub(crate) fn with_http_response_head(
421 mut self,
422 head: crate::api::http::HttpResponseHead,
423 ) -> Self {
424 self.context.http_status = Some(head.status);
425 self.http_response_head = Some(Arc::new(head));
426 self
427 }
428
429 pub fn config_error(&self) -> Option<&ConfigError> {
431 self.config_error.as_deref()
432 }
433
434 pub fn io_kind(&self) -> Option<std::io::ErrorKind> {
436 let mut source = self.source();
437 for _ in 0..64 {
440 let error = source?;
441 if let Some(io) = error.downcast_ref::<std::io::Error>() {
442 return Some(io.kind());
443 }
444 source = error.source();
445 }
446 None
447 }
448
449 pub fn protocol(source: impl Into<BoxError>) -> Self {
451 Self::with_source(ErrorKind::Protocol, source)
452 }
453
454 pub fn provider(source: impl Into<BoxError>) -> Self {
456 Self::with_source(ErrorKind::ProviderFailed, source).with_stage(ErrorStage::Provider)
457 }
458}
459
460impl fmt::Debug for NetError {
461 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
462 formatter
463 .debug_struct("NetError")
464 .field("kind", &self.kind)
465 .field("context", &self.context)
466 .field("config_error", &self.config_error)
467 .field("has_source", &self.source.is_some())
468 .field("retry_report", &self.retry_report)
469 .finish()
470 }
471}
472
473impl fmt::Display for NetError {
474 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
475 write!(formatter, "{:?}", self.kind)?;
476 if let Some(stage) = self.context.stage {
477 write!(formatter, " at {stage:?}")?;
478 }
479 if let Some(status) = self.context.http_status {
480 write!(formatter, " (HTTP {})", status.as_u16())?;
481 }
482 Ok(())
483 }
484}
485
486impl StdError for NetError {
487 fn source(&self) -> Option<&(dyn StdError + 'static)> {
488 self.source
489 .as_deref()
490 .map(|source| source as &(dyn StdError + 'static))
491 }
492}
493
494impl From<ErrorKind> for NetError {
495 fn from(kind: ErrorKind) -> Self {
496 Self::new(kind)
497 }
498}
499
500impl From<std::io::Error> for NetError {
501 fn from(source: std::io::Error) -> Self {
502 Self::with_source(ErrorKind::Io, source)
503 }
504}
505
506#[derive(Clone)]
507pub struct ConfigError {
509 field: String,
510 reason: String,
511}
512
513impl ConfigError {
514 fn new(field: impl Into<String>, reason: impl Into<String>) -> Self {
515 Self {
516 field: field.into(),
517 reason: reason.into(),
518 }
519 }
520
521 pub fn field(&self) -> &str {
523 &self.field
524 }
525
526 pub fn reason(&self) -> &str {
528 &self.reason
529 }
530}
531
532impl fmt::Debug for ConfigError {
533 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
534 formatter
535 .debug_struct("ConfigError")
536 .field("field_bytes", &self.field.len())
537 .field("reason_bytes", &self.reason.len())
538 .finish()
539 }
540}
541
542impl fmt::Display for ConfigError {
543 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
544 formatter.write_str("invalid configuration")
545 }
546}
547
548impl StdError for ConfigError {}
549
550impl From<ConfigError> for NetError {
551 fn from(value: ConfigError) -> Self {
552 let detail = Arc::new(value);
553 Self {
554 config_error: Some(Arc::clone(&detail)),
555 source: Some(detail),
556 ..Self::new(ErrorKind::InvalidConfig).with_stage(ErrorStage::Configuration)
557 }
558 }
559}
560
561impl From<crate::api::retry::RetryConfigError> for NetError {
562 fn from(source: crate::api::retry::RetryConfigError) -> Self {
563 let detail = ConfigError::new(source.field(), source.reason());
564 Self {
565 config_error: Some(Arc::new(detail)),
566 ..Self::with_source(ErrorKind::InvalidConfig, source)
567 .with_stage(ErrorStage::Configuration)
568 }
569 }
570}
571
572pub struct EnqueueError<T> {
574 value: T,
575 error: NetError,
576}
577
578impl<T> EnqueueError<T> {
579 pub(crate) fn new(value: T, error: NetError) -> Self {
580 Self { value, error }
581 }
582
583 pub fn error(&self) -> &NetError {
585 &self.error
586 }
587
588 pub fn value(&self) -> &T {
590 &self.value
591 }
592
593 pub fn into_parts(self) -> (T, NetError) {
595 (self.value, self.error)
596 }
597
598 pub fn into_inner(self) -> T {
600 self.value
601 }
602
603 pub fn into_error(self) -> NetError {
605 self.error
606 }
607}
608
609impl<T> fmt::Debug for EnqueueError<T> {
610 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
611 formatter
612 .debug_struct("EnqueueError")
613 .field("error", &self.error)
614 .finish_non_exhaustive()
615 }
616}
617
618impl<T> fmt::Display for EnqueueError<T> {
619 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
620 write!(formatter, "enqueue failed: {}", self.error)
621 }
622}
623
624impl<T: Send + Sync + 'static> StdError for EnqueueError<T> {
625 fn source(&self) -> Option<&(dyn StdError + 'static)> {
626 Some(&self.error)
627 }
628}
629
630impl<T> From<EnqueueError<T>> for NetError {
631 fn from(value: EnqueueError<T>) -> Self {
632 value.into_error()
633 }
634}
635
636#[non_exhaustive]
637#[derive(Clone, Debug)]
638pub enum ReceiveError {
640 Lagged {
642 skipped: u64,
644 },
645 Failed(NetError),
647}
648
649impl fmt::Display for ReceiveError {
650 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
651 match self {
652 Self::Lagged { skipped } => {
653 write!(formatter, "receiver lagged; skipped {skipped} observations")
654 }
655 Self::Failed(error) => write!(formatter, "receive failed: {error}"),
656 }
657 }
658}
659
660impl StdError for ReceiveError {
661 fn source(&self) -> Option<&(dyn StdError + 'static)> {
662 match self {
663 Self::Lagged { .. } => None,
664 Self::Failed(error) => Some(error),
665 }
666 }
667}
668
669impl From<ReceiveError> for NetError {
670 fn from(value: ReceiveError) -> Self {
671 match value {
672 value @ ReceiveError::Lagged { .. } => {
673 Self::with_source(ErrorKind::ObservationLagged, value)
674 .with_stage(ErrorStage::Receive)
675 }
676 ReceiveError::Failed(error) => error,
677 }
678 }
679}
680
681#[non_exhaustive]
682#[derive(Clone, Debug)]
683pub enum TryReceiveError {
685 Empty,
687 Closed,
689 Lagged {
691 skipped: u64,
693 },
694 Failed(NetError),
696}
697
698impl fmt::Display for TryReceiveError {
699 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
700 match self {
701 Self::Empty => formatter.write_str("receiver is empty"),
702 Self::Closed => formatter.write_str("receiver is closed"),
703 Self::Lagged { skipped } => {
704 write!(formatter, "receiver lagged; skipped {skipped} observations")
705 }
706 Self::Failed(error) => write!(formatter, "receive failed: {error}"),
707 }
708 }
709}
710
711impl StdError for TryReceiveError {
712 fn source(&self) -> Option<&(dyn StdError + 'static)> {
713 match self {
714 Self::Failed(error) => Some(error),
715 Self::Empty | Self::Closed | Self::Lagged { .. } => None,
716 }
717 }
718}
719
720impl fmt::Display for crate::common::CommonError {
721 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
722 formatter.write_str(match self {
723 Self::None => "unknown engine failure",
724 Self::RuntimeError => "engine runtime unavailable",
725 Self::PostError => "engine queue closed",
726 })
727 }
728}
729
730impl StdError for crate::common::CommonError {}
731
732impl From<crate::common::CommonError> for NetError {
733 fn from(value: crate::common::CommonError) -> Self {
734 let kind = match value {
735 crate::common::CommonError::None => ErrorKind::Internal,
736 crate::common::CommonError::RuntimeError => ErrorKind::RuntimeUnavailable,
737 crate::common::CommonError::PostError => ErrorKind::QueueClosed,
738 };
739 Self::with_source(kind, value).with_stage(ErrorStage::Runtime)
740 }
741}
742
743#[cfg(feature = "ws-client")]
744impl From<tokio_tungstenite::tungstenite::Error> for NetError {
745 fn from(value: tokio_tungstenite::tungstenite::Error) -> Self {
746 use tokio_tungstenite::tungstenite::error::{CapacityError, UrlError};
747 use tokio_tungstenite::tungstenite::Error;
748
749 let mut context = ErrorContext::default();
750 let kind = match &value {
751 Error::ConnectionClosed | Error::AlreadyClosed => ErrorKind::Closed,
752 Error::Io(error) => {
753 context.stage = crate::module::transport::tls_error_stage(error);
754 if context.stage.is_some() {
755 ErrorKind::Tls
756 } else {
757 ErrorKind::Io
758 }
759 }
760 Error::Tls(_) => {
761 context.stage = Some(ErrorStage::Tls);
762 ErrorKind::Tls
763 }
764 Error::Capacity(CapacityError::MessageTooLong { .. }) => ErrorKind::ItemTooLarge,
765 Error::Capacity(CapacityError::TooManyHeaders) => ErrorKind::ResourceExhausted,
766 Error::Protocol(_) | Error::Utf8(_) | Error::AttackAttempt => ErrorKind::Protocol,
767 Error::HttpFormat(_) => ErrorKind::Protocol,
770 Error::Url(UrlError::UnableToConnect(_)) => {
771 context.stage = Some(ErrorStage::Tcp);
772 ErrorKind::Io
773 }
774 Error::Url(UrlError::TlsFeatureNotEnabled) => {
775 context.stage = Some(ErrorStage::Configuration);
776 ErrorKind::InvalidConfig
777 }
778 Error::Url(
779 UrlError::NoHostName
780 | UrlError::UnsupportedUrlScheme
781 | UrlError::EmptyHostName
782 | UrlError::NoPathOrQuery,
783 ) => {
784 context.stage = Some(ErrorStage::RequestBuild);
785 ErrorKind::InvalidInput
786 }
787 Error::Http(response) => {
788 context.stage = Some(ErrorStage::Upgrade);
789 context.http_status = Some(response.status());
790 ErrorKind::HandshakeRejected
791 }
792 Error::WriteBufferFull(_) => {
793 return Self::new(ErrorKind::DeliveryUnknown).with_stage(ErrorStage::Write);
798 }
799 };
800 Self::with_source(kind, value).with_context(context)
801 }
802}
803
804#[cfg(test)]
805mod tests {
806 use super::*;
807 use std::sync::atomic::{AtomicUsize, Ordering};
808
809 type TestResult<T = ()> = std::result::Result<T, BoxError>;
810
811 fn check(condition: bool, message: &str) -> TestResult {
812 if condition {
813 Ok(())
814 } else {
815 Err(std::io::Error::other(message).into())
816 }
817 }
818
819 struct InputWithoutDebug {
820 payload: String,
821 drops: Arc<AtomicUsize>,
822 }
823
824 impl Drop for InputWithoutDebug {
825 fn drop(&mut self) {
826 self.drops.fetch_add(1, Ordering::SeqCst);
827 }
828 }
829
830 fn rejected(drops: &Arc<AtomicUsize>) -> EnqueueError<InputWithoutDebug> {
831 EnqueueError::new(
832 InputWithoutDebug {
833 payload: "unaccepted-payload-secret".into(),
834 drops: Arc::clone(drops),
835 },
836 NetError::new(ErrorKind::QueueFull),
837 )
838 }
839
840 #[test]
841 fn enqueue_recovery_preserves_ownership_without_requiring_debug() -> TestResult {
842 let drops = Arc::new(AtomicUsize::new(0));
843 let failure = rejected(&drops);
844 check(
845 failure.error().kind() == ErrorKind::QueueFull,
846 "enqueue classification",
847 )?;
848 check(
849 failure.value().payload == "unaccepted-payload-secret",
850 "borrow original input",
851 )?;
852 check(
853 !format!("{failure} {failure:?}").contains("payload-secret"),
854 "input must not enter default formatting",
855 )?;
856 check(
857 failure.source().is_some(),
858 "enqueue source must be its admission error",
859 )?;
860 let (input, error) = failure.into_parts();
861 check(
862 input.payload == "unaccepted-payload-secret" && error.kind() == ErrorKind::QueueFull,
863 "recover input with cause",
864 )?;
865 check(
866 drops.load(Ordering::SeqCst) == 0,
867 "recovery must not drop the input",
868 )?;
869 drop(input);
870 check(
871 drops.load(Ordering::SeqCst) == 1,
872 "recovered input must drop once",
873 )?;
874 let input = rejected(&drops).into_inner();
875 check(
876 input.payload == "unaccepted-payload-secret",
877 "recover input alone",
878 )?;
879 drop(input);
880 let error = rejected(&drops).into_error();
881 check(
882 error.kind() == ErrorKind::QueueFull && drops.load(Ordering::SeqCst) == 3,
883 "error-only conversion must drop unaccepted input",
884 )?;
885 Ok(())
886 }
887
888 #[test]
889 fn enqueue_question_mark_discards_input_and_preserves_the_error() -> TestResult {
890 fn propagate(drops: &Arc<AtomicUsize>) -> Result<()> {
891 Err(rejected(drops))?;
892 Ok(())
893 }
894 let drops = Arc::new(AtomicUsize::new(0));
895 let error = propagate(&drops)
896 .err()
897 .ok_or_else(|| std::io::Error::other("admission error missing"))?;
898 check(
899 error.kind() == ErrorKind::QueueFull,
900 "question-mark classification",
901 )?;
902 check(
903 drops.load(Ordering::SeqCst) == 1,
904 "question mark deliberately discards unaccepted input",
905 )
906 }
907
908 #[test]
909 fn configuration_details_are_explicitly_readable_but_never_default_formatted() -> TestResult {
910 let error = NetError::config("private-field-secret", "private-value-secret");
911 let detail = error
912 .config_error()
913 .ok_or_else(|| std::io::Error::other("config detail missing"))?;
914 check(
915 detail.field() == "private-field-secret" && detail.reason() == "private-value-secret",
916 "explicit config getters",
917 )?;
918 check(
919 error.kind() == ErrorKind::InvalidConfig
920 && error.context().stage == Some(ErrorStage::Configuration),
921 "configuration origin",
922 )?;
923 check(
924 error
925 .source()
926 .and_then(|source| source.downcast_ref::<ConfigError>())
927 .is_some(),
928 "config source must remain structured",
929 )?;
930 check(
931 !format!("{error} {error:?} {detail} {detail:?}").contains("secret"),
932 "configuration strings must be redacted",
933 )?;
934 fn propagate() -> Result<()> {
935 Err(ConfigError::new("queue.capacity", "must be nonzero"))?;
936 Ok(())
937 }
938 let propagated = propagate()
939 .err()
940 .ok_or_else(|| std::io::Error::other("config error did not propagate"))?;
941 check(
942 propagated.config_error().map(ConfigError::field) == Some("queue.capacity"),
943 "question-mark config details",
944 )
945 }
946
947 #[test]
948 fn common_errors_retain_the_original_engine_source() -> TestResult {
949 for (source, kind) in [
950 (crate::common::CommonError::None, ErrorKind::Internal),
951 (
952 crate::common::CommonError::RuntimeError,
953 ErrorKind::RuntimeUnavailable,
954 ),
955 (
956 crate::common::CommonError::PostError,
957 ErrorKind::QueueClosed,
958 ),
959 ] {
960 let error = NetError::from(source);
961 check(
962 error.kind() == kind && error.context().stage == Some(ErrorStage::Runtime),
963 "common error category and stage",
964 )?;
965 check(
966 error
967 .source()
968 .and_then(|source| source.downcast_ref::<crate::common::CommonError>())
969 .copied()
970 == Some(source),
971 "original common source",
972 )?;
973 }
974 Ok(())
975 }
976
977 #[test]
978 fn retry_report_preserves_error_identity_context_and_source() -> TestResult {
979 use crate::api::retry::{RetryReport, RetryStopReason};
980
981 let report = RetryReport {
982 attempts: 3,
983 retry_count: 2,
984 transport_sends: 4,
985 elapsed: std::time::Duration::from_millis(30),
986 stop_reason: Some(RetryStopReason::AttemptsExhausted),
987 };
988 let error = NetError::with_source(
989 ErrorKind::Io,
990 std::io::Error::new(std::io::ErrorKind::ConnectionReset, "private-source"),
991 )
992 .with_context(ErrorContext {
993 stage: Some(ErrorStage::Receive),
994 http_status: Some(http::StatusCode::OK),
995 ..Default::default()
996 })
997 .with_retry_report(report);
998 let cloned = error.clone();
999 check(
1000 cloned.kind() == ErrorKind::Io
1001 && cloned.context().stage == Some(ErrorStage::Receive)
1002 && cloned.context().http_status == Some(http::StatusCode::OK)
1003 && cloned.io_kind() == Some(std::io::ErrorKind::ConnectionReset),
1004 "attaching a report must preserve the failure and received status",
1005 )?;
1006 let attached = cloned
1007 .retry_report()
1008 .ok_or_else(|| std::io::Error::other("retry report missing after clone"))?;
1009 check(
1010 attached.attempts == 3
1011 && attached.retry_count == 2
1012 && attached.transport_sends == 4
1013 && attached.stop_reason == Some(RetryStopReason::AttemptsExhausted),
1014 "cloning an error must retain retry statistics",
1015 )?;
1016 check(
1017 !format!("{error:?} {error}").contains("private-source"),
1018 "retry reports must not expose source text in default formatting",
1019 )
1020 }
1021
1022 #[test]
1023 fn retry_configuration_errors_support_question_mark_without_losing_details() -> TestResult {
1024 fn configure() -> Result<()> {
1025 crate::api::retry::RetrySchedule::builder()
1026 .max_attempts(0)
1027 .build()?;
1028 Ok(())
1029 }
1030 let error = match configure() {
1031 Err(error) => error,
1032 Ok(()) => return Err(std::io::Error::other("invalid configuration accepted").into()),
1033 };
1034 check(
1035 error.kind() == ErrorKind::InvalidConfig
1036 && error.context().stage == Some(ErrorStage::Configuration)
1037 && error.config_error().map(ConfigError::field) == Some("max_attempts"),
1038 "retry config conversion must retain field and origin",
1039 )?;
1040 check(
1041 error
1042 .source()
1043 .and_then(|source| source.downcast_ref::<crate::api::retry::RetryConfigError>())
1044 .is_some(),
1045 "retry config conversion must retain the original structured source",
1046 )
1047 }
1048
1049 #[cfg(feature = "ws-client")]
1050 #[test]
1051 fn websocket_timeout_phase_survives_delivery_wrapping_clone_and_retry_report() -> TestResult {
1052 use crate::ws::WsTimeoutPhase;
1053 for phase in [
1054 WsTimeoutPhase::Admission,
1055 WsTimeoutPhase::Write,
1056 WsTimeoutPhase::Response,
1057 WsTimeoutPhase::Attempt,
1058 WsTimeoutPhase::Total,
1059 ] {
1060 let source = NetError::from(ErrorKind::TimedOut)
1061 .with_stage(ErrorStage::Write)
1062 .with_ws_timeout_phase(phase);
1063 let context = source.context().clone();
1064 let error = NetError::with_source(ErrorKind::DeliveryUnknown, source)
1065 .with_context(context)
1066 .with_retry_report(crate::api::retry::RetryReport::new())
1067 .clone();
1068 check(
1069 error.ws_timeout_phase() == Some(phase),
1070 "delivery wrapper lost the WebSocket budget phase",
1071 )?;
1072 check(
1073 error
1074 .source()
1075 .and_then(|source| source.downcast_ref::<NetError>())
1076 .is_some_and(|source| {
1077 source.kind() == ErrorKind::TimedOut
1078 && source.ws_timeout_phase() == Some(phase)
1079 }),
1080 "original timeout cause lost its phase",
1081 )?;
1082 check(
1083 error.retry_report().is_some(),
1084 "timeout report lost during clone",
1085 )?;
1086 }
1087 Ok(())
1088 }
1089
1090 #[test]
1091 fn cyclic_application_sources_cannot_make_io_kind_loop_forever() -> TestResult {
1092 #[derive(Debug)]
1093 struct Cyclic;
1094 impl fmt::Display for Cyclic {
1095 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
1096 formatter.write_str("cyclic")
1097 }
1098 }
1099 impl StdError for Cyclic {
1100 fn source(&self) -> Option<&(dyn StdError + 'static)> {
1101 Some(self)
1102 }
1103 }
1104 check(
1105 NetError::provider(Cyclic).io_kind().is_none(),
1106 "cyclic source has no I/O category",
1107 )
1108 }
1109
1110 #[cfg(feature = "ws-client")]
1111 #[test]
1112 fn websocket_context_retains_details_but_redacts_peer_reason() -> TestResult {
1113 use crate::ws::{HandshakeDiagnostic, HandshakeDiagnosticKind, IoEndKind, PeerClose};
1114 use tokio_tungstenite::tungstenite::protocol::{frame::coding::CloseCode, CloseFrame};
1115
1116 let frame = CloseFrame {
1117 code: CloseCode::Normal,
1118 reason: "peer-credential-secret".into(),
1119 };
1120 let context = ErrorContext {
1121 stage: Some(ErrorStage::Receive),
1122 http_status: Some(http::StatusCode::UNAUTHORIZED),
1123 diagnostic: Some(HandshakeDiagnostic::new(
1124 HandshakeDiagnosticKind::HttpRejected,
1125 )),
1126 peer_close: Some(PeerClose::from_frame(Some(&frame))?),
1127 io_end: Some(IoEndKind::PeerClose),
1128 ..Default::default()
1129 };
1130 let error = NetError::with_source(
1131 ErrorKind::Protocol,
1132 std::io::Error::other("source-credential-secret"),
1133 )
1134 .with_context(context)
1135 .with_stage(ErrorStage::Close);
1136 let cloned = error.clone();
1137 check(
1138 cloned.context().stage == Some(ErrorStage::Close)
1139 && cloned.context().http_status == Some(http::StatusCode::UNAUTHORIZED)
1140 && cloned.context().io_end == Some(IoEndKind::PeerClose),
1141 "stage changes must preserve other contextual facts",
1142 )?;
1143 check(
1144 cloned
1145 .context()
1146 .peer_close
1147 .as_ref()
1148 .map(|value| value.reason.as_str())
1149 == Some("peer-credential-secret"),
1150 "explicit peer close access must preserve the received reason",
1151 )?;
1152 check(
1153 cloned
1154 .context()
1155 .diagnostic
1156 .as_ref()
1157 .map(|value| value.kind())
1158 == Some(HandshakeDiagnosticKind::HttpRejected),
1159 "diagnostic must survive error cloning",
1160 )?;
1161 check(
1162 !format!("{error} {error:?} {:?}", error.context()).contains("credential-secret"),
1163 "context formatting must omit peer and source strings",
1164 )
1165 }
1166}
1167
1168#[cfg(all(test, feature = "ws-client"))]
1169#[path = "identity_context_tests.rs"]
1170mod identity_context_tests;