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 kind: ErrorKind,
239 context: ErrorContext,
240 config_error: Option<Arc<ConfigError>>,
241 source: Option<Arc<dyn StdError + Send + Sync + 'static>>,
242 retry_report: Option<Arc<crate::api::retry::RetryReport>>,
243 #[cfg(feature = "http-client")]
244 http_response_head: Option<Arc<crate::api::http::HttpResponseHead>>,
245}
246
247impl NetError {
248 pub fn from_http_status(status: http::StatusCode) -> Self {
250 let mut context = ErrorContext::default();
251 context.http_status = Some(status);
252 Self::new(ErrorKind::HttpStatus).with_context(context)
253 }
254 pub(crate) fn new(kind: ErrorKind) -> Self {
255 Self {
256 kind,
257 context: ErrorContext::default(),
258 config_error: None,
259 source: None,
260 retry_report: None,
261 #[cfg(feature = "http-client")]
262 http_response_head: None,
263 }
264 }
265
266 pub(crate) fn with_source(kind: ErrorKind, source: impl Into<BoxError>) -> Self {
267 let source: BoxError = source.into();
268 Self {
269 source: Some(Arc::from(source)),
270 ..Self::new(kind)
271 }
272 }
273
274 pub(crate) fn with_context(mut self, context: ErrorContext) -> Self {
275 self.context = context;
276 self
277 }
278
279 pub(crate) fn with_stage(mut self, stage: ErrorStage) -> Self {
280 self.context.stage = Some(stage);
281 self
282 }
283
284 #[cfg(feature = "http-client")]
285 pub(crate) fn with_http_request_id(
286 mut self,
287 request_id: crate::api::http::HttpRequestId,
288 ) -> Self {
289 self.context.http_request_id = Some(request_id);
290 self
291 }
292
293 pub(crate) fn config(field: impl Into<String>, reason: impl Into<String>) -> Self {
294 ConfigError::new(field, reason).into()
295 }
296
297 #[cfg(feature = "http-client")]
298 pub(crate) fn with_http_attempt(mut self, attempt: u32) -> Self {
299 self.context.http_attempt = Some(attempt);
300 self
301 }
302
303 #[cfg(feature = "http-client")]
304 pub(crate) fn with_timeout_phase(mut self, phase: crate::api::http::TimeoutPhase) -> Self {
305 self.context.http_timeout_phase = Some(phase);
306 self
307 }
308
309 #[cfg(feature = "ws-client")]
310 pub(crate) fn with_ws_timeout_phase(mut self, phase: crate::ws::WsTimeoutPhase) -> Self {
311 self.context.ws_timeout_phase = Some(phase);
312 self
313 }
314
315 pub(crate) fn input(field: impl Into<String>, reason: impl Into<String>) -> Self {
316 Self {
317 config_error: Some(Arc::new(ConfigError::new(field, reason))),
318 ..Self::new(ErrorKind::InvalidInput).with_stage(ErrorStage::RequestBuild)
319 }
320 }
321
322 pub(crate) fn from_poison<T>(_: std::sync::PoisonError<T>) -> Self {
323 Self::new(ErrorKind::Internal)
326 }
327
328 pub fn kind(&self) -> ErrorKind {
330 self.kind
331 }
332
333 pub fn context(&self) -> &ErrorContext {
335 &self.context
336 }
337
338 pub fn retry_report(&self) -> Option<&crate::api::retry::RetryReport> {
343 self.retry_report.as_deref()
344 }
345
346 pub(crate) fn with_retry_report(mut self, report: crate::api::retry::RetryReport) -> Self {
347 self.retry_report = Some(Arc::new(report));
348 self
349 }
350
351 #[cfg(feature = "http-client")]
357 pub fn timeout_phase(&self) -> Option<crate::api::http::TimeoutPhase> {
358 self.context.http_timeout_phase
359 }
360
361 #[cfg(feature = "ws-client")]
366 pub fn ws_timeout_phase(&self) -> Option<crate::ws::WsTimeoutPhase> {
367 self.context.ws_timeout_phase
368 }
369
370 pub fn http_status(&self) -> Option<http::StatusCode> {
372 self.context.http_status
373 }
374
375 #[cfg(feature = "http-client")]
382 pub fn http_response_head(&self) -> Option<&crate::api::http::HttpResponseHead> {
383 self.http_response_head.as_deref()
384 }
385
386 #[cfg(feature = "http-client")]
387 pub(crate) fn with_http_response_head(
388 mut self,
389 head: crate::api::http::HttpResponseHead,
390 ) -> Self {
391 self.context.http_status = Some(head.status);
392 self.http_response_head = Some(Arc::new(head));
393 self
394 }
395
396 pub fn config_error(&self) -> Option<&ConfigError> {
398 self.config_error.as_deref()
399 }
400
401 pub fn io_kind(&self) -> Option<std::io::ErrorKind> {
403 let mut source = self.source();
404 for _ in 0..64 {
407 let error = source?;
408 if let Some(io) = error.downcast_ref::<std::io::Error>() {
409 return Some(io.kind());
410 }
411 source = error.source();
412 }
413 None
414 }
415
416 pub fn protocol(source: impl Into<BoxError>) -> Self {
418 Self::with_source(ErrorKind::Protocol, source)
419 }
420
421 pub fn provider(source: impl Into<BoxError>) -> Self {
423 Self::with_source(ErrorKind::ProviderFailed, source).with_stage(ErrorStage::Provider)
424 }
425}
426
427impl fmt::Debug for NetError {
428 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
429 formatter
430 .debug_struct("NetError")
431 .field("kind", &self.kind)
432 .field("context", &self.context)
433 .field("config_error", &self.config_error)
434 .field("has_source", &self.source.is_some())
435 .field("retry_report", &self.retry_report)
436 .finish()
437 }
438}
439
440impl fmt::Display for NetError {
441 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
442 write!(formatter, "{:?}", self.kind)?;
443 if let Some(stage) = self.context.stage {
444 write!(formatter, " at {stage:?}")?;
445 }
446 if let Some(status) = self.context.http_status {
447 write!(formatter, " (HTTP {})", status.as_u16())?;
448 }
449 Ok(())
450 }
451}
452
453impl StdError for NetError {
454 fn source(&self) -> Option<&(dyn StdError + 'static)> {
455 self.source
456 .as_deref()
457 .map(|source| source as &(dyn StdError + 'static))
458 }
459}
460
461impl From<ErrorKind> for NetError {
462 fn from(kind: ErrorKind) -> Self {
463 Self::new(kind)
464 }
465}
466
467impl From<std::io::Error> for NetError {
468 fn from(source: std::io::Error) -> Self {
469 Self::with_source(ErrorKind::Io, source)
470 }
471}
472
473#[derive(Clone)]
474pub struct ConfigError {
476 field: String,
477 reason: String,
478}
479
480impl ConfigError {
481 fn new(field: impl Into<String>, reason: impl Into<String>) -> Self {
482 Self {
483 field: field.into(),
484 reason: reason.into(),
485 }
486 }
487
488 pub fn field(&self) -> &str {
490 &self.field
491 }
492
493 pub fn reason(&self) -> &str {
495 &self.reason
496 }
497}
498
499impl fmt::Debug for ConfigError {
500 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
501 formatter
502 .debug_struct("ConfigError")
503 .field("field_bytes", &self.field.len())
504 .field("reason_bytes", &self.reason.len())
505 .finish()
506 }
507}
508
509impl fmt::Display for ConfigError {
510 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
511 formatter.write_str("invalid configuration")
512 }
513}
514
515impl StdError for ConfigError {}
516
517impl From<ConfigError> for NetError {
518 fn from(value: ConfigError) -> Self {
519 let detail = Arc::new(value);
520 Self {
521 config_error: Some(Arc::clone(&detail)),
522 source: Some(detail),
523 ..Self::new(ErrorKind::InvalidConfig).with_stage(ErrorStage::Configuration)
524 }
525 }
526}
527
528impl From<crate::api::retry::RetryConfigError> for NetError {
529 fn from(source: crate::api::retry::RetryConfigError) -> Self {
530 let detail = ConfigError::new(source.field(), source.reason());
531 Self {
532 config_error: Some(Arc::new(detail)),
533 ..Self::with_source(ErrorKind::InvalidConfig, source)
534 .with_stage(ErrorStage::Configuration)
535 }
536 }
537}
538
539pub struct EnqueueError<T> {
541 value: T,
542 error: NetError,
543}
544
545impl<T> EnqueueError<T> {
546 pub(crate) fn new(value: T, error: NetError) -> Self {
547 Self { value, error }
548 }
549
550 pub fn error(&self) -> &NetError {
552 &self.error
553 }
554
555 pub fn value(&self) -> &T {
557 &self.value
558 }
559
560 pub fn into_parts(self) -> (T, NetError) {
562 (self.value, self.error)
563 }
564
565 pub fn into_inner(self) -> T {
567 self.value
568 }
569
570 pub fn into_error(self) -> NetError {
572 self.error
573 }
574}
575
576impl<T> fmt::Debug for EnqueueError<T> {
577 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
578 formatter
579 .debug_struct("EnqueueError")
580 .field("error", &self.error)
581 .finish_non_exhaustive()
582 }
583}
584
585impl<T> fmt::Display for EnqueueError<T> {
586 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
587 write!(formatter, "enqueue failed: {}", self.error)
588 }
589}
590
591impl<T: Send + Sync + 'static> StdError for EnqueueError<T> {
592 fn source(&self) -> Option<&(dyn StdError + 'static)> {
593 Some(&self.error)
594 }
595}
596
597impl<T> From<EnqueueError<T>> for NetError {
598 fn from(value: EnqueueError<T>) -> Self {
599 value.into_error()
600 }
601}
602
603#[non_exhaustive]
604#[derive(Clone, Debug)]
605pub enum ReceiveError {
607 Lagged {
609 skipped: u64,
611 },
612 Failed(NetError),
614}
615
616impl fmt::Display for ReceiveError {
617 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
618 match self {
619 Self::Lagged { skipped } => {
620 write!(formatter, "receiver lagged; skipped {skipped} observations")
621 }
622 Self::Failed(error) => write!(formatter, "receive failed: {error}"),
623 }
624 }
625}
626
627impl StdError for ReceiveError {
628 fn source(&self) -> Option<&(dyn StdError + 'static)> {
629 match self {
630 Self::Lagged { .. } => None,
631 Self::Failed(error) => Some(error),
632 }
633 }
634}
635
636impl From<ReceiveError> for NetError {
637 fn from(value: ReceiveError) -> Self {
638 match value {
639 value @ ReceiveError::Lagged { .. } => {
640 Self::with_source(ErrorKind::ObservationLagged, value)
641 .with_stage(ErrorStage::Receive)
642 }
643 ReceiveError::Failed(error) => error,
644 }
645 }
646}
647
648#[non_exhaustive]
649#[derive(Clone, Debug)]
650pub enum TryReceiveError {
652 Empty,
654 Closed,
656 Lagged {
658 skipped: u64,
660 },
661 Failed(NetError),
663}
664
665impl fmt::Display for TryReceiveError {
666 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
667 match self {
668 Self::Empty => formatter.write_str("receiver is empty"),
669 Self::Closed => formatter.write_str("receiver is closed"),
670 Self::Lagged { skipped } => {
671 write!(formatter, "receiver lagged; skipped {skipped} observations")
672 }
673 Self::Failed(error) => write!(formatter, "receive failed: {error}"),
674 }
675 }
676}
677
678impl StdError for TryReceiveError {
679 fn source(&self) -> Option<&(dyn StdError + 'static)> {
680 match self {
681 Self::Failed(error) => Some(error),
682 Self::Empty | Self::Closed | Self::Lagged { .. } => None,
683 }
684 }
685}
686
687impl fmt::Display for crate::common::CommonError {
688 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
689 formatter.write_str(match self {
690 Self::None => "unknown engine failure",
691 Self::RuntimeError => "engine runtime unavailable",
692 Self::PostError => "engine queue closed",
693 })
694 }
695}
696
697impl StdError for crate::common::CommonError {}
698
699impl From<crate::common::CommonError> for NetError {
700 fn from(value: crate::common::CommonError) -> Self {
701 let kind = match value {
702 crate::common::CommonError::None => ErrorKind::Internal,
703 crate::common::CommonError::RuntimeError => ErrorKind::RuntimeUnavailable,
704 crate::common::CommonError::PostError => ErrorKind::QueueClosed,
705 };
706 Self::with_source(kind, value).with_stage(ErrorStage::Runtime)
707 }
708}
709
710#[cfg(feature = "ws-client")]
711impl From<tokio_tungstenite::tungstenite::Error> for NetError {
712 fn from(value: tokio_tungstenite::tungstenite::Error) -> Self {
713 use tokio_tungstenite::tungstenite::error::{CapacityError, UrlError};
714 use tokio_tungstenite::tungstenite::Error;
715
716 let mut context = ErrorContext::default();
717 let kind = match &value {
718 Error::ConnectionClosed | Error::AlreadyClosed => ErrorKind::Closed,
719 Error::Io(error) => {
720 context.stage = crate::module::transport::tls_error_stage(error);
721 if context.stage.is_some() {
722 ErrorKind::Tls
723 } else {
724 ErrorKind::Io
725 }
726 }
727 Error::Tls(_) => {
728 context.stage = Some(ErrorStage::Tls);
729 ErrorKind::Tls
730 }
731 Error::Capacity(CapacityError::MessageTooLong { .. }) => ErrorKind::ItemTooLarge,
732 Error::Capacity(CapacityError::TooManyHeaders) => ErrorKind::ResourceExhausted,
733 Error::Protocol(_) | Error::Utf8(_) | Error::AttackAttempt => ErrorKind::Protocol,
734 Error::HttpFormat(_) => ErrorKind::Protocol,
737 Error::Url(UrlError::UnableToConnect(_)) => {
738 context.stage = Some(ErrorStage::Tcp);
739 ErrorKind::Io
740 }
741 Error::Url(UrlError::TlsFeatureNotEnabled) => {
742 context.stage = Some(ErrorStage::Configuration);
743 ErrorKind::InvalidConfig
744 }
745 Error::Url(
746 UrlError::NoHostName
747 | UrlError::UnsupportedUrlScheme
748 | UrlError::EmptyHostName
749 | UrlError::NoPathOrQuery,
750 ) => {
751 context.stage = Some(ErrorStage::RequestBuild);
752 ErrorKind::InvalidInput
753 }
754 Error::Http(response) => {
755 context.stage = Some(ErrorStage::Upgrade);
756 context.http_status = Some(response.status());
757 ErrorKind::HandshakeRejected
758 }
759 Error::WriteBufferFull(_) => {
760 return Self::new(ErrorKind::DeliveryUnknown).with_stage(ErrorStage::Write);
765 }
766 };
767 Self::with_source(kind, value).with_context(context)
768 }
769}
770
771#[cfg(test)]
772mod tests {
773 use super::*;
774 use std::sync::atomic::{AtomicUsize, Ordering};
775
776 type TestResult<T = ()> = std::result::Result<T, BoxError>;
777
778 fn check(condition: bool, message: &str) -> TestResult {
779 if condition {
780 Ok(())
781 } else {
782 Err(std::io::Error::other(message).into())
783 }
784 }
785
786 struct InputWithoutDebug {
787 payload: String,
788 drops: Arc<AtomicUsize>,
789 }
790
791 impl Drop for InputWithoutDebug {
792 fn drop(&mut self) {
793 self.drops.fetch_add(1, Ordering::SeqCst);
794 }
795 }
796
797 fn rejected(drops: &Arc<AtomicUsize>) -> EnqueueError<InputWithoutDebug> {
798 EnqueueError::new(
799 InputWithoutDebug {
800 payload: "unaccepted-payload-secret".into(),
801 drops: Arc::clone(drops),
802 },
803 NetError::new(ErrorKind::QueueFull),
804 )
805 }
806
807 #[test]
808 fn enqueue_recovery_preserves_ownership_without_requiring_debug() -> TestResult {
809 let drops = Arc::new(AtomicUsize::new(0));
810 let failure = rejected(&drops);
811 check(
812 failure.error().kind() == ErrorKind::QueueFull,
813 "enqueue classification",
814 )?;
815 check(
816 failure.value().payload == "unaccepted-payload-secret",
817 "borrow original input",
818 )?;
819 check(
820 !format!("{failure} {failure:?}").contains("payload-secret"),
821 "input must not enter default formatting",
822 )?;
823 check(
824 failure.source().is_some(),
825 "enqueue source must be its admission error",
826 )?;
827 let (input, error) = failure.into_parts();
828 check(
829 input.payload == "unaccepted-payload-secret" && error.kind() == ErrorKind::QueueFull,
830 "recover input with cause",
831 )?;
832 check(
833 drops.load(Ordering::SeqCst) == 0,
834 "recovery must not drop the input",
835 )?;
836 drop(input);
837 check(
838 drops.load(Ordering::SeqCst) == 1,
839 "recovered input must drop once",
840 )?;
841 let input = rejected(&drops).into_inner();
842 check(
843 input.payload == "unaccepted-payload-secret",
844 "recover input alone",
845 )?;
846 drop(input);
847 let error = rejected(&drops).into_error();
848 check(
849 error.kind() == ErrorKind::QueueFull && drops.load(Ordering::SeqCst) == 3,
850 "error-only conversion must drop unaccepted input",
851 )?;
852 Ok(())
853 }
854
855 #[test]
856 fn enqueue_question_mark_discards_input_and_preserves_the_error() -> TestResult {
857 fn propagate(drops: &Arc<AtomicUsize>) -> Result<()> {
858 Err(rejected(drops))?;
859 Ok(())
860 }
861 let drops = Arc::new(AtomicUsize::new(0));
862 let error = propagate(&drops)
863 .err()
864 .ok_or_else(|| std::io::Error::other("admission error missing"))?;
865 check(
866 error.kind() == ErrorKind::QueueFull,
867 "question-mark classification",
868 )?;
869 check(
870 drops.load(Ordering::SeqCst) == 1,
871 "question mark deliberately discards unaccepted input",
872 )
873 }
874
875 #[test]
876 fn configuration_details_are_explicitly_readable_but_never_default_formatted() -> TestResult {
877 let error = NetError::config("private-field-secret", "private-value-secret");
878 let detail = error
879 .config_error()
880 .ok_or_else(|| std::io::Error::other("config detail missing"))?;
881 check(
882 detail.field() == "private-field-secret" && detail.reason() == "private-value-secret",
883 "explicit config getters",
884 )?;
885 check(
886 error.kind() == ErrorKind::InvalidConfig
887 && error.context().stage == Some(ErrorStage::Configuration),
888 "configuration origin",
889 )?;
890 check(
891 error
892 .source()
893 .and_then(|source| source.downcast_ref::<ConfigError>())
894 .is_some(),
895 "config source must remain structured",
896 )?;
897 check(
898 !format!("{error} {error:?} {detail} {detail:?}").contains("secret"),
899 "configuration strings must be redacted",
900 )?;
901 fn propagate() -> Result<()> {
902 Err(ConfigError::new("queue.capacity", "must be nonzero"))?;
903 Ok(())
904 }
905 let propagated = propagate()
906 .err()
907 .ok_or_else(|| std::io::Error::other("config error did not propagate"))?;
908 check(
909 propagated.config_error().map(ConfigError::field) == Some("queue.capacity"),
910 "question-mark config details",
911 )
912 }
913
914 #[test]
915 fn common_errors_retain_the_original_engine_source() -> TestResult {
916 for (source, kind) in [
917 (crate::common::CommonError::None, ErrorKind::Internal),
918 (
919 crate::common::CommonError::RuntimeError,
920 ErrorKind::RuntimeUnavailable,
921 ),
922 (
923 crate::common::CommonError::PostError,
924 ErrorKind::QueueClosed,
925 ),
926 ] {
927 let error = NetError::from(source);
928 check(
929 error.kind() == kind && error.context().stage == Some(ErrorStage::Runtime),
930 "common error category and stage",
931 )?;
932 check(
933 error
934 .source()
935 .and_then(|source| source.downcast_ref::<crate::common::CommonError>())
936 .copied()
937 == Some(source),
938 "original common source",
939 )?;
940 }
941 Ok(())
942 }
943
944 #[test]
945 fn retry_report_preserves_error_identity_context_and_source() -> TestResult {
946 use crate::api::retry::{RetryReport, RetryStopReason};
947
948 let report = RetryReport {
949 attempts: 3,
950 retry_count: 2,
951 transport_sends: 4,
952 elapsed: std::time::Duration::from_millis(30),
953 stop_reason: Some(RetryStopReason::AttemptsExhausted),
954 };
955 let error = NetError::with_source(
956 ErrorKind::Io,
957 std::io::Error::new(std::io::ErrorKind::ConnectionReset, "private-source"),
958 )
959 .with_context(ErrorContext {
960 stage: Some(ErrorStage::Receive),
961 http_status: Some(http::StatusCode::OK),
962 ..Default::default()
963 })
964 .with_retry_report(report);
965 let cloned = error.clone();
966 check(
967 cloned.kind() == ErrorKind::Io
968 && cloned.context().stage == Some(ErrorStage::Receive)
969 && cloned.context().http_status == Some(http::StatusCode::OK)
970 && cloned.io_kind() == Some(std::io::ErrorKind::ConnectionReset),
971 "attaching a report must preserve the failure and received status",
972 )?;
973 let attached = cloned
974 .retry_report()
975 .ok_or_else(|| std::io::Error::other("retry report missing after clone"))?;
976 check(
977 attached.attempts == 3
978 && attached.retry_count == 2
979 && attached.transport_sends == 4
980 && attached.stop_reason == Some(RetryStopReason::AttemptsExhausted),
981 "cloning an error must retain retry statistics",
982 )?;
983 check(
984 !format!("{error:?} {error}").contains("private-source"),
985 "retry reports must not expose source text in default formatting",
986 )
987 }
988
989 #[test]
990 fn retry_configuration_errors_support_question_mark_without_losing_details() -> TestResult {
991 fn configure() -> Result<()> {
992 crate::api::retry::RetrySchedule::builder()
993 .max_attempts(0)
994 .build()?;
995 Ok(())
996 }
997 let error = match configure() {
998 Err(error) => error,
999 Ok(()) => return Err(std::io::Error::other("invalid configuration accepted").into()),
1000 };
1001 check(
1002 error.kind() == ErrorKind::InvalidConfig
1003 && error.context().stage == Some(ErrorStage::Configuration)
1004 && error.config_error().map(ConfigError::field) == Some("max_attempts"),
1005 "retry config conversion must retain field and origin",
1006 )?;
1007 check(
1008 error
1009 .source()
1010 .and_then(|source| source.downcast_ref::<crate::api::retry::RetryConfigError>())
1011 .is_some(),
1012 "retry config conversion must retain the original structured source",
1013 )
1014 }
1015
1016 #[cfg(feature = "ws-client")]
1017 #[test]
1018 fn websocket_timeout_phase_survives_delivery_wrapping_clone_and_retry_report() -> TestResult {
1019 use crate::ws::WsTimeoutPhase;
1020 for phase in [
1021 WsTimeoutPhase::Admission,
1022 WsTimeoutPhase::Write,
1023 WsTimeoutPhase::Response,
1024 WsTimeoutPhase::Attempt,
1025 WsTimeoutPhase::Total,
1026 ] {
1027 let source = NetError::from(ErrorKind::TimedOut)
1028 .with_stage(ErrorStage::Write)
1029 .with_ws_timeout_phase(phase);
1030 let context = source.context().clone();
1031 let error = NetError::with_source(ErrorKind::DeliveryUnknown, source)
1032 .with_context(context)
1033 .with_retry_report(crate::api::retry::RetryReport::new())
1034 .clone();
1035 check(
1036 error.ws_timeout_phase() == Some(phase),
1037 "delivery wrapper lost the WebSocket budget phase",
1038 )?;
1039 check(
1040 error
1041 .source()
1042 .and_then(|source| source.downcast_ref::<NetError>())
1043 .is_some_and(|source| {
1044 source.kind() == ErrorKind::TimedOut
1045 && source.ws_timeout_phase() == Some(phase)
1046 }),
1047 "original timeout cause lost its phase",
1048 )?;
1049 check(
1050 error.retry_report().is_some(),
1051 "timeout report lost during clone",
1052 )?;
1053 }
1054 Ok(())
1055 }
1056
1057 #[test]
1058 fn cyclic_application_sources_cannot_make_io_kind_loop_forever() -> TestResult {
1059 #[derive(Debug)]
1060 struct Cyclic;
1061 impl fmt::Display for Cyclic {
1062 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
1063 formatter.write_str("cyclic")
1064 }
1065 }
1066 impl StdError for Cyclic {
1067 fn source(&self) -> Option<&(dyn StdError + 'static)> {
1068 Some(self)
1069 }
1070 }
1071 check(
1072 NetError::provider(Cyclic).io_kind().is_none(),
1073 "cyclic source has no I/O category",
1074 )
1075 }
1076
1077 #[cfg(feature = "ws-client")]
1078 #[test]
1079 fn websocket_context_retains_details_but_redacts_peer_reason() -> TestResult {
1080 use crate::ws::{HandshakeDiagnostic, HandshakeDiagnosticKind, IoEndKind, PeerClose};
1081 use tokio_tungstenite::tungstenite::protocol::{frame::coding::CloseCode, CloseFrame};
1082
1083 let frame = CloseFrame {
1084 code: CloseCode::Normal,
1085 reason: "peer-credential-secret".into(),
1086 };
1087 let context = ErrorContext {
1088 stage: Some(ErrorStage::Receive),
1089 http_status: Some(http::StatusCode::UNAUTHORIZED),
1090 diagnostic: Some(HandshakeDiagnostic::new(
1091 HandshakeDiagnosticKind::HttpRejected,
1092 )),
1093 peer_close: Some(PeerClose::from_frame(Some(&frame))?),
1094 io_end: Some(IoEndKind::PeerClose),
1095 ..Default::default()
1096 };
1097 let error = NetError::with_source(
1098 ErrorKind::Protocol,
1099 std::io::Error::other("source-credential-secret"),
1100 )
1101 .with_context(context)
1102 .with_stage(ErrorStage::Close);
1103 let cloned = error.clone();
1104 check(
1105 cloned.context().stage == Some(ErrorStage::Close)
1106 && cloned.context().http_status == Some(http::StatusCode::UNAUTHORIZED)
1107 && cloned.context().io_end == Some(IoEndKind::PeerClose),
1108 "stage changes must preserve other contextual facts",
1109 )?;
1110 check(
1111 cloned
1112 .context()
1113 .peer_close
1114 .as_ref()
1115 .map(|value| value.reason.as_str())
1116 == Some("peer-credential-secret"),
1117 "explicit peer close access must preserve the received reason",
1118 )?;
1119 check(
1120 cloned
1121 .context()
1122 .diagnostic
1123 .as_ref()
1124 .map(|value| value.kind())
1125 == Some(HandshakeDiagnosticKind::HttpRejected),
1126 "diagnostic must survive error cloning",
1127 )?;
1128 check(
1129 !format!("{error} {error:?} {:?}", error.context()).contains("credential-secret"),
1130 "context formatting must omit peer and source strings",
1131 )
1132 }
1133}
1134
1135#[cfg(all(test, feature = "ws-client"))]
1136#[path = "identity_context_tests.rs"]
1137mod identity_context_tests;