1use std::error::Error as StdError;
4use std::fmt;
5use std::sync::Arc;
6
7mod network_monitor;
8pub use network_monitor::{NetworkMonitorDiagnostic, NetworkMonitorPhase};
9mod windows_reachability;
10pub use windows_reachability::{WindowsReachabilityDiagnostic, WindowsReachabilityOperation};
11
12pub type BoxError = Box<dyn StdError + Send + Sync + 'static>;
14pub type Result<T> = std::result::Result<T, NetError>;
16
17#[non_exhaustive]
18#[derive(Clone, Copy, Debug, Eq, PartialEq)]
19pub enum ErrorKind {
24 InvalidInput,
26 InvalidConfig,
28 Io,
30 Dns,
32 Tls,
34 Protocol,
36 HandshakeRejected,
38 ProviderFailed,
40 CallbackPanicked,
42 RuntimeUnavailable,
44 ResourceExhausted,
46 QueueFull,
48 QueueClosed,
50 ItemTooLarge,
52 PendingLimitReached,
54 SubscriptionLimitReached,
56 CallbackOverflow,
58 ControlOverflow,
60 ObservationLagged,
62 NotConnected,
64 NotRunning,
66 Unsupported,
68 SessionAlreadyExists,
70 ConnectionClosing,
72 Closed,
74 EngineDropped,
76 Cancelled,
78 TimedOut,
80 DeadlineExceeded,
82 DeliveryUnknown,
84 RetryExhausted,
86 InvalidPolicy,
88 BodyNotReplayable,
90 DuplicateRequestId,
92 RoutingDisabled,
94 RoutingModeMismatch,
96 ClientAlreadyExists,
98 ClientNotFound,
100 Internal,
102 HttpStatus,
104}
105
106#[non_exhaustive]
107#[derive(Clone, Copy, Debug, Eq, PartialEq)]
108pub enum ErrorStage {
113 Configuration,
115 Provider,
117 RequestBuild,
119 Dns,
121 Tcp,
123 Proxy,
125 ProxyTls,
127 Tls,
129 Upgrade,
131 Admission,
133 Queue,
135 Write,
137 Response,
139 Receive,
141 Heartbeat,
143 Close,
145 Dispatch,
147 NetworkMonitor,
149 Runtime,
151}
152
153#[non_exhaustive]
155#[derive(Clone, Default)]
156pub struct ErrorContext {
157 pub stage: Option<ErrorStage>,
161 pub network_monitor: Option<Arc<NetworkMonitorDiagnostic>>,
167 pub windows_reachability: Option<WindowsReachabilityDiagnostic>,
173 #[cfg(feature = "ws-client")]
174 pub client_id: Option<crate::ws::ClientId>,
176 #[cfg(feature = "ws-client")]
177 pub session_id: Option<crate::ws::SessionId>,
179 #[cfg(feature = "ws-client")]
180 pub connection_id: Option<crate::ws::ConnectionId>,
182 #[cfg(feature = "ws-client")]
183 pub attempt_id: Option<crate::ws::AttemptId>,
185 #[cfg(feature = "ws-client")]
186 pub request_id: Option<crate::ws::RequestId>,
188 #[cfg(feature = "ws-client")]
189 pub ws_timeout_phase: Option<crate::ws::WsTimeoutPhase>,
191 pub http_status: Option<http::StatusCode>,
193 #[cfg(feature = "http-client")]
194 pub http_request_id: Option<crate::api::http::HttpRequestId>,
196 #[cfg(feature = "http-client")]
197 pub http_timeout_phase: Option<crate::api::http::TimeoutPhase>,
201 #[cfg(feature = "http-client")]
202 pub http_attempt: Option<u32>,
204 #[cfg(feature = "ws-client")]
205 pub diagnostic: Option<crate::ws::HandshakeDiagnostic>,
207 #[cfg(feature = "ws-client")]
208 pub peer_close: Option<crate::ws::PeerClose>,
210 #[cfg(feature = "ws-client")]
211 pub io_end: Option<crate::ws::IoEndKind>,
213}
214
215impl fmt::Debug for ErrorContext {
216 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
217 let mut output = formatter.debug_struct("ErrorContext");
218 output
219 .field("stage", &self.stage)
220 .field("network_monitor", &self.network_monitor)
221 .field("windows_reachability", &self.windows_reachability)
222 .field("http_status", &self.http_status);
223 #[cfg(feature = "http-client")]
224 output
225 .field("http_request_id", &self.http_request_id)
226 .field("http_timeout_phase", &self.http_timeout_phase)
227 .field("http_attempt", &self.http_attempt);
228 #[cfg(feature = "ws-client")]
229 output
230 .field("client_id", &self.client_id)
231 .field("session_id", &self.session_id)
232 .field("connection_id", &self.connection_id)
233 .field("attempt_id", &self.attempt_id)
234 .field("ws_timeout_phase", &self.ws_timeout_phase)
235 .field(
236 "request_id_len",
237 &self.request_id.as_ref().map(|id| id.as_str().len()),
238 )
239 .field(
240 "diagnostic_kind",
241 &self.diagnostic.as_ref().map(|value| value.kind()),
242 )
243 .field(
244 "peer_close_code",
245 &self.peer_close.as_ref().map(|value| value.code),
246 )
247 .field("io_end", &self.io_end);
248 output.finish()
249 }
250}
251
252#[derive(Clone)]
256pub struct NetError {
257 #[cfg(feature = "quality-doctor")]
258 quality_ref: Option<crate::quality::QualityReportRef>,
259 kind: ErrorKind,
260 #[cfg(feature = "ws-client")]
262 context: Box<ErrorContext>,
263 #[cfg(not(feature = "ws-client"))]
264 context: ErrorContext,
265 config_error: Option<Arc<ConfigError>>,
266 source: Option<Arc<dyn StdError + Send + Sync + 'static>>,
267 retry_report: Option<Arc<crate::api::retry::RetryReport>>,
268 #[cfg(feature = "http-client")]
269 http_response_head: Option<Arc<crate::api::http::HttpResponseHead>>,
270}
271
272impl NetError {
273 #[cfg(feature = "quality-doctor")]
292 pub fn quality_ref(&self) -> Option<crate::quality::QualityReportRef> {
293 self.quality_ref
294 }
295
296 #[cfg(feature = "quality-doctor")]
297 pub(crate) fn with_quality_ref(mut self, reference: crate::quality::QualityReportRef) -> Self {
298 self.quality_ref = Some(reference);
299 self
300 }
301
302 pub fn from_http_status(status: http::StatusCode) -> Self {
304 let context = ErrorContext {
305 http_status: Some(status),
306 ..ErrorContext::default()
307 };
308 Self::new(ErrorKind::HttpStatus).with_context(context)
309 }
310 pub(crate) fn new(kind: ErrorKind) -> Self {
311 Self {
312 #[cfg(feature = "quality-doctor")]
313 quality_ref: None,
314 kind,
315 context: Default::default(),
316 config_error: None,
317 source: None,
318 retry_report: None,
319 #[cfg(feature = "http-client")]
320 http_response_head: None,
321 }
322 }
323
324 pub(crate) fn with_source(kind: ErrorKind, source: impl Into<BoxError>) -> Self {
325 let source: BoxError = source.into();
326 Self {
327 source: Some(Arc::from(source)),
328 ..Self::new(kind)
329 }
330 }
331
332 pub(crate) fn with_context(mut self, context: ErrorContext) -> Self {
333 #[cfg(feature = "ws-client")]
334 {
335 *self.context = context;
337 }
338 #[cfg(not(feature = "ws-client"))]
339 {
340 self.context = context;
341 }
342 self
343 }
344
345 pub(crate) fn with_stage(mut self, stage: ErrorStage) -> Self {
346 self.context.stage = Some(stage);
347 self
348 }
349
350 #[cfg(feature = "http-client")]
351 pub(crate) fn with_http_request_id(
352 mut self,
353 request_id: crate::api::http::HttpRequestId,
354 ) -> Self {
355 self.context.http_request_id = Some(request_id);
356 self
357 }
358
359 pub(crate) fn config(field: impl Into<String>, reason: impl Into<String>) -> Self {
360 ConfigError::new(field, reason).into()
361 }
362
363 #[cfg(feature = "http-client")]
364 pub(crate) fn with_http_attempt(mut self, attempt: u32) -> Self {
365 self.context.http_attempt = Some(attempt);
366 self
367 }
368
369 #[cfg(feature = "http-client")]
370 pub(crate) fn with_timeout_phase(mut self, phase: crate::api::http::TimeoutPhase) -> Self {
371 self.context.http_timeout_phase = Some(phase);
372 self
373 }
374
375 #[cfg(feature = "ws-client")]
376 pub(crate) fn with_ws_timeout_phase(mut self, phase: crate::ws::WsTimeoutPhase) -> Self {
377 self.context.ws_timeout_phase = Some(phase);
378 self
379 }
380
381 pub(crate) fn input(field: impl Into<String>, reason: impl Into<String>) -> Self {
382 Self {
383 config_error: Some(Arc::new(ConfigError::new(field, reason))),
384 ..Self::new(ErrorKind::InvalidInput).with_stage(ErrorStage::RequestBuild)
385 }
386 }
387
388 pub(crate) fn from_poison<T>(_: std::sync::PoisonError<T>) -> Self {
389 Self::new(ErrorKind::Internal)
392 }
393
394 pub fn kind(&self) -> ErrorKind {
396 self.kind
397 }
398
399 pub fn context(&self) -> &ErrorContext {
401 &self.context
402 }
403
404 pub fn retry_report(&self) -> Option<&crate::api::retry::RetryReport> {
409 self.retry_report.as_deref()
410 }
411
412 pub(crate) fn with_retry_report(mut self, report: crate::api::retry::RetryReport) -> Self {
413 self.retry_report = Some(Arc::new(report));
414 self
415 }
416
417 #[cfg(feature = "http-client")]
423 pub fn timeout_phase(&self) -> Option<crate::api::http::TimeoutPhase> {
424 self.context.http_timeout_phase
425 }
426
427 #[cfg(feature = "ws-client")]
432 pub fn ws_timeout_phase(&self) -> Option<crate::ws::WsTimeoutPhase> {
433 self.context.ws_timeout_phase
434 }
435
436 pub fn http_status(&self) -> Option<http::StatusCode> {
438 self.context.http_status
439 }
440
441 #[cfg(feature = "http-client")]
448 pub fn http_response_head(&self) -> Option<&crate::api::http::HttpResponseHead> {
449 self.http_response_head.as_deref()
450 }
451
452 #[cfg(feature = "http-client")]
453 pub(crate) fn with_http_response_head(
454 mut self,
455 head: crate::api::http::HttpResponseHead,
456 ) -> Self {
457 self.context.http_status = Some(head.status);
458 self.http_response_head = Some(Arc::new(head));
459 self
460 }
461
462 pub fn config_error(&self) -> Option<&ConfigError> {
464 self.config_error.as_deref()
465 }
466
467 pub fn io_kind(&self) -> Option<std::io::ErrorKind> {
469 let mut source = self.source();
470 for _ in 0..64 {
473 let error = source?;
474 if let Some(io) = error.downcast_ref::<std::io::Error>() {
475 return Some(io.kind());
476 }
477 source = error.source();
478 }
479 None
480 }
481
482 pub fn protocol(source: impl Into<BoxError>) -> Self {
484 Self::with_source(ErrorKind::Protocol, source)
485 }
486
487 pub fn provider(source: impl Into<BoxError>) -> Self {
489 Self::with_source(ErrorKind::ProviderFailed, source).with_stage(ErrorStage::Provider)
490 }
491}
492
493impl fmt::Debug for NetError {
494 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
495 formatter
496 .debug_struct("NetError")
497 .field("kind", &self.kind)
498 .field("context", &self.context)
499 .field("config_error", &self.config_error)
500 .field("has_source", &self.source.is_some())
501 .field("retry_report", &self.retry_report)
502 .finish()
503 }
504}
505
506impl fmt::Display for NetError {
507 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
508 write!(formatter, "{:?}", self.kind)?;
509 if let Some(stage) = self.context.stage {
510 write!(formatter, " at {stage:?}")?;
511 }
512 if let Some(status) = self.context.http_status {
513 write!(formatter, " (HTTP {})", status.as_u16())?;
514 }
515 Ok(())
516 }
517}
518
519impl StdError for NetError {
520 fn source(&self) -> Option<&(dyn StdError + 'static)> {
521 self.source
522 .as_deref()
523 .map(|source| source as &(dyn StdError + 'static))
524 }
525}
526
527impl From<ErrorKind> for NetError {
528 fn from(kind: ErrorKind) -> Self {
529 Self::new(kind)
530 }
531}
532
533impl From<std::io::Error> for NetError {
534 fn from(source: std::io::Error) -> Self {
535 Self::with_source(ErrorKind::Io, source)
536 }
537}
538
539#[derive(Clone)]
540pub struct ConfigError {
542 field: String,
543 reason: String,
544}
545
546impl ConfigError {
547 fn new(field: impl Into<String>, reason: impl Into<String>) -> Self {
548 Self {
549 field: field.into(),
550 reason: reason.into(),
551 }
552 }
553
554 pub fn field(&self) -> &str {
556 &self.field
557 }
558
559 pub fn reason(&self) -> &str {
561 &self.reason
562 }
563}
564
565impl fmt::Debug for ConfigError {
566 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
567 formatter
568 .debug_struct("ConfigError")
569 .field("field_bytes", &self.field.len())
570 .field("reason_bytes", &self.reason.len())
571 .finish()
572 }
573}
574
575impl fmt::Display for ConfigError {
576 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
577 formatter.write_str("invalid configuration")
578 }
579}
580
581impl StdError for ConfigError {}
582
583impl From<ConfigError> for NetError {
584 fn from(value: ConfigError) -> Self {
585 let detail = Arc::new(value);
586 Self {
587 config_error: Some(Arc::clone(&detail)),
588 source: Some(detail),
589 ..Self::new(ErrorKind::InvalidConfig).with_stage(ErrorStage::Configuration)
590 }
591 }
592}
593
594impl From<crate::api::retry::RetryConfigError> for NetError {
595 fn from(source: crate::api::retry::RetryConfigError) -> Self {
596 let detail = ConfigError::new(source.field(), source.reason());
597 Self {
598 config_error: Some(Arc::new(detail)),
599 ..Self::with_source(ErrorKind::InvalidConfig, source)
600 .with_stage(ErrorStage::Configuration)
601 }
602 }
603}
604
605pub struct EnqueueError<T> {
607 value: T,
608 error: NetError,
609}
610
611impl<T> EnqueueError<T> {
612 pub(crate) fn new(value: T, error: NetError) -> Self {
613 Self { value, error }
614 }
615
616 pub fn error(&self) -> &NetError {
618 &self.error
619 }
620
621 pub fn value(&self) -> &T {
623 &self.value
624 }
625
626 pub fn into_parts(self) -> (T, NetError) {
628 (self.value, self.error)
629 }
630
631 pub fn into_inner(self) -> T {
633 self.value
634 }
635
636 pub fn into_error(self) -> NetError {
638 self.error
639 }
640}
641
642impl<T> fmt::Debug for EnqueueError<T> {
643 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
644 formatter
645 .debug_struct("EnqueueError")
646 .field("error", &self.error)
647 .finish_non_exhaustive()
648 }
649}
650
651impl<T> fmt::Display for EnqueueError<T> {
652 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
653 write!(formatter, "enqueue failed: {}", self.error)
654 }
655}
656
657impl<T: Send + Sync + 'static> StdError for EnqueueError<T> {
658 fn source(&self) -> Option<&(dyn StdError + 'static)> {
659 Some(&self.error)
660 }
661}
662
663impl<T> From<EnqueueError<T>> for NetError {
664 fn from(value: EnqueueError<T>) -> Self {
665 value.into_error()
666 }
667}
668
669#[non_exhaustive]
670#[derive(Clone, Debug)]
671pub enum ReceiveError {
673 Lagged {
675 skipped: u64,
677 },
678 Failed(NetError),
680}
681
682impl fmt::Display for ReceiveError {
683 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
684 match self {
685 Self::Lagged { skipped } => {
686 write!(formatter, "receiver lagged; skipped {skipped} observations")
687 }
688 Self::Failed(error) => write!(formatter, "receive failed: {error}"),
689 }
690 }
691}
692
693impl StdError for ReceiveError {
694 fn source(&self) -> Option<&(dyn StdError + 'static)> {
695 match self {
696 Self::Lagged { .. } => None,
697 Self::Failed(error) => Some(error),
698 }
699 }
700}
701
702impl From<ReceiveError> for NetError {
703 fn from(value: ReceiveError) -> Self {
704 match value {
705 value @ ReceiveError::Lagged { .. } => {
706 Self::with_source(ErrorKind::ObservationLagged, value)
707 .with_stage(ErrorStage::Receive)
708 }
709 ReceiveError::Failed(error) => error,
710 }
711 }
712}
713
714#[non_exhaustive]
715#[derive(Clone, Debug)]
716pub enum TryReceiveError {
718 Empty,
720 Closed,
722 Lagged {
724 skipped: u64,
726 },
727 Failed(NetError),
729}
730
731impl fmt::Display for TryReceiveError {
732 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
733 match self {
734 Self::Empty => formatter.write_str("receiver is empty"),
735 Self::Closed => formatter.write_str("receiver is closed"),
736 Self::Lagged { skipped } => {
737 write!(formatter, "receiver lagged; skipped {skipped} observations")
738 }
739 Self::Failed(error) => write!(formatter, "receive failed: {error}"),
740 }
741 }
742}
743
744impl StdError for TryReceiveError {
745 fn source(&self) -> Option<&(dyn StdError + 'static)> {
746 match self {
747 Self::Failed(error) => Some(error),
748 Self::Empty | Self::Closed | Self::Lagged { .. } => None,
749 }
750 }
751}
752
753impl fmt::Display for crate::common::CommonError {
754 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
755 formatter.write_str(match self {
756 Self::None => "unknown engine failure",
757 Self::RuntimeError => "engine runtime unavailable",
758 Self::PostError => "engine queue closed",
759 })
760 }
761}
762
763impl StdError for crate::common::CommonError {}
764
765impl From<crate::common::CommonError> for NetError {
766 fn from(value: crate::common::CommonError) -> Self {
767 let kind = match value {
768 crate::common::CommonError::None => ErrorKind::Internal,
769 crate::common::CommonError::RuntimeError => ErrorKind::RuntimeUnavailable,
770 crate::common::CommonError::PostError => ErrorKind::QueueClosed,
771 };
772 Self::with_source(kind, value).with_stage(ErrorStage::Runtime)
773 }
774}
775
776#[cfg(feature = "ws-client")]
777impl From<tokio_tungstenite::tungstenite::Error> for NetError {
778 fn from(value: tokio_tungstenite::tungstenite::Error) -> Self {
779 use tokio_tungstenite::tungstenite::error::{CapacityError, UrlError};
780 use tokio_tungstenite::tungstenite::Error;
781
782 let mut context = ErrorContext::default();
783 let kind = match &value {
784 Error::ConnectionClosed | Error::AlreadyClosed => ErrorKind::Closed,
785 Error::Io(error) => {
786 context.stage = crate::module::transport::tls_error_stage(error);
787 if context.stage.is_some() {
788 ErrorKind::Tls
789 } else {
790 ErrorKind::Io
791 }
792 }
793 Error::Tls(_) => {
794 context.stage = Some(ErrorStage::Tls);
795 ErrorKind::Tls
796 }
797 Error::Capacity(CapacityError::MessageTooLong { .. }) => ErrorKind::ItemTooLarge,
798 Error::Capacity(CapacityError::TooManyHeaders) => ErrorKind::ResourceExhausted,
799 Error::Protocol(_) | Error::Utf8(_) | Error::AttackAttempt => ErrorKind::Protocol,
800 Error::HttpFormat(_) => ErrorKind::Protocol,
803 Error::Url(UrlError::UnableToConnect(_)) => {
804 context.stage = Some(ErrorStage::Tcp);
805 ErrorKind::Io
806 }
807 Error::Url(UrlError::TlsFeatureNotEnabled) => {
808 context.stage = Some(ErrorStage::Configuration);
809 ErrorKind::InvalidConfig
810 }
811 Error::Url(
812 UrlError::NoHostName
813 | UrlError::UnsupportedUrlScheme
814 | UrlError::EmptyHostName
815 | UrlError::NoPathOrQuery,
816 ) => {
817 context.stage = Some(ErrorStage::RequestBuild);
818 ErrorKind::InvalidInput
819 }
820 Error::Http(response) => {
821 context.stage = Some(ErrorStage::Upgrade);
822 context.http_status = Some(response.status());
823 ErrorKind::HandshakeRejected
824 }
825 Error::WriteBufferFull(_) => {
826 return Self::new(ErrorKind::DeliveryUnknown).with_stage(ErrorStage::Write);
831 }
832 };
833 Self::with_source(kind, value).with_context(context)
834 }
835}
836
837#[cfg(test)]
838mod tests {
839 use super::*;
840 use std::sync::atomic::{AtomicUsize, Ordering};
841
842 type TestResult<T = ()> = std::result::Result<T, BoxError>;
843
844 fn check(condition: bool, message: &str) -> TestResult {
845 if condition {
846 Ok(())
847 } else {
848 Err(std::io::Error::other(message).into())
849 }
850 }
851
852 #[cfg(feature = "ws-client")]
853 #[test]
854 fn websocket_error_stays_below_the_large_result_error_threshold() -> TestResult {
855 check(
856 std::mem::size_of::<NetError>() < 128,
857 "WebSocket context must not inflate every result past the Clippy threshold",
858 )
859 }
860
861 #[test]
862 fn cloned_error_context_updates_do_not_change_other_copies() -> TestResult {
863 let original = NetError::from(std::io::Error::new(
864 std::io::ErrorKind::BrokenPipe,
865 "private-source",
866 ))
867 .with_stage(ErrorStage::Write);
868 let replaced = original.clone().with_context(ErrorContext {
869 stage: Some(ErrorStage::Receive),
870 http_status: Some(http::StatusCode::BAD_GATEWAY),
871 ..Default::default()
872 });
873 let annotated = replaced.clone().with_stage(ErrorStage::Dispatch);
874 check(
875 original.context().stage == Some(ErrorStage::Write)
876 && original.http_status().is_none()
877 && replaced.context().stage == Some(ErrorStage::Receive)
878 && replaced.http_status() == Some(http::StatusCode::BAD_GATEWAY)
879 && annotated.context().stage == Some(ErrorStage::Dispatch)
880 && annotated.http_status() == Some(http::StatusCode::BAD_GATEWAY),
881 "context replacement and annotation must only affect the selected copy",
882 )?;
883 let source = original.source().ok_or("original source missing")?;
884 for error in [&replaced, &annotated] {
885 check(
886 error.kind() == original.kind()
887 && std::ptr::eq(source, error.source().ok_or("cloned source missing")?),
888 "updating a cloned context must preserve classification and shared source",
889 )?;
890 }
891 Ok(())
892 }
893
894 struct InputWithoutDebug {
895 payload: String,
896 drops: Arc<AtomicUsize>,
897 }
898
899 impl Drop for InputWithoutDebug {
900 fn drop(&mut self) {
901 self.drops.fetch_add(1, Ordering::SeqCst);
902 }
903 }
904
905 fn rejected(drops: &Arc<AtomicUsize>) -> EnqueueError<InputWithoutDebug> {
906 EnqueueError::new(
907 InputWithoutDebug {
908 payload: "unaccepted-payload-secret".into(),
909 drops: Arc::clone(drops),
910 },
911 NetError::new(ErrorKind::QueueFull),
912 )
913 }
914
915 #[test]
916 fn enqueue_recovery_preserves_ownership_without_requiring_debug() -> TestResult {
917 let drops = Arc::new(AtomicUsize::new(0));
918 let failure = rejected(&drops);
919 check(
920 failure.error().kind() == ErrorKind::QueueFull,
921 "enqueue classification",
922 )?;
923 check(
924 failure.value().payload == "unaccepted-payload-secret",
925 "borrow original input",
926 )?;
927 check(
928 !format!("{failure} {failure:?}").contains("payload-secret"),
929 "input must not enter default formatting",
930 )?;
931 check(
932 failure.source().is_some(),
933 "enqueue source must be its admission error",
934 )?;
935 let (input, error) = failure.into_parts();
936 check(
937 input.payload == "unaccepted-payload-secret" && error.kind() == ErrorKind::QueueFull,
938 "recover input with cause",
939 )?;
940 check(
941 drops.load(Ordering::SeqCst) == 0,
942 "recovery must not drop the input",
943 )?;
944 drop(input);
945 check(
946 drops.load(Ordering::SeqCst) == 1,
947 "recovered input must drop once",
948 )?;
949 let input = rejected(&drops).into_inner();
950 check(
951 input.payload == "unaccepted-payload-secret",
952 "recover input alone",
953 )?;
954 drop(input);
955 let error = rejected(&drops).into_error();
956 check(
957 error.kind() == ErrorKind::QueueFull && drops.load(Ordering::SeqCst) == 3,
958 "error-only conversion must drop unaccepted input",
959 )?;
960 Ok(())
961 }
962
963 #[test]
964 fn enqueue_question_mark_discards_input_and_preserves_the_error() -> TestResult {
965 fn propagate(drops: &Arc<AtomicUsize>) -> Result<()> {
966 Err(rejected(drops))?;
967 Ok(())
968 }
969 let drops = Arc::new(AtomicUsize::new(0));
970 let error = propagate(&drops)
971 .err()
972 .ok_or_else(|| std::io::Error::other("admission error missing"))?;
973 check(
974 error.kind() == ErrorKind::QueueFull,
975 "question-mark classification",
976 )?;
977 check(
978 drops.load(Ordering::SeqCst) == 1,
979 "question mark deliberately discards unaccepted input",
980 )
981 }
982
983 #[test]
984 fn configuration_details_are_explicitly_readable_but_never_default_formatted() -> TestResult {
985 let error = NetError::config("private-field-secret", "private-value-secret");
986 let detail = error
987 .config_error()
988 .ok_or_else(|| std::io::Error::other("config detail missing"))?;
989 check(
990 detail.field() == "private-field-secret" && detail.reason() == "private-value-secret",
991 "explicit config getters",
992 )?;
993 check(
994 error.kind() == ErrorKind::InvalidConfig
995 && error.context().stage == Some(ErrorStage::Configuration),
996 "configuration origin",
997 )?;
998 check(
999 error
1000 .source()
1001 .and_then(|source| source.downcast_ref::<ConfigError>())
1002 .is_some(),
1003 "config source must remain structured",
1004 )?;
1005 check(
1006 !format!("{error} {error:?} {detail} {detail:?}").contains("secret"),
1007 "configuration strings must be redacted",
1008 )?;
1009 fn propagate() -> Result<()> {
1010 Err(ConfigError::new("queue.capacity", "must be nonzero"))?;
1011 Ok(())
1012 }
1013 let propagated = propagate()
1014 .err()
1015 .ok_or_else(|| std::io::Error::other("config error did not propagate"))?;
1016 check(
1017 propagated.config_error().map(ConfigError::field) == Some("queue.capacity"),
1018 "question-mark config details",
1019 )
1020 }
1021
1022 #[test]
1023 fn common_errors_retain_the_original_engine_source() -> TestResult {
1024 for (source, kind) in [
1025 (crate::common::CommonError::None, ErrorKind::Internal),
1026 (
1027 crate::common::CommonError::RuntimeError,
1028 ErrorKind::RuntimeUnavailable,
1029 ),
1030 (
1031 crate::common::CommonError::PostError,
1032 ErrorKind::QueueClosed,
1033 ),
1034 ] {
1035 let error = NetError::from(source);
1036 check(
1037 error.kind() == kind && error.context().stage == Some(ErrorStage::Runtime),
1038 "common error category and stage",
1039 )?;
1040 check(
1041 error
1042 .source()
1043 .and_then(|source| source.downcast_ref::<crate::common::CommonError>())
1044 .copied()
1045 == Some(source),
1046 "original common source",
1047 )?;
1048 }
1049 Ok(())
1050 }
1051
1052 #[test]
1053 fn retry_report_preserves_error_identity_context_and_source() -> TestResult {
1054 use crate::api::retry::{RetryReport, RetryStopReason};
1055
1056 let report = RetryReport {
1057 attempts: 3,
1058 retry_count: 2,
1059 transport_sends: 4,
1060 elapsed: std::time::Duration::from_millis(30),
1061 stop_reason: Some(RetryStopReason::AttemptsExhausted),
1062 };
1063 let error = NetError::with_source(
1064 ErrorKind::Io,
1065 std::io::Error::new(std::io::ErrorKind::ConnectionReset, "private-source"),
1066 )
1067 .with_context(ErrorContext {
1068 stage: Some(ErrorStage::Receive),
1069 http_status: Some(http::StatusCode::OK),
1070 ..Default::default()
1071 })
1072 .with_retry_report(report);
1073 let cloned = error.clone();
1074 check(
1075 cloned.kind() == ErrorKind::Io
1076 && cloned.context().stage == Some(ErrorStage::Receive)
1077 && cloned.context().http_status == Some(http::StatusCode::OK)
1078 && cloned.io_kind() == Some(std::io::ErrorKind::ConnectionReset),
1079 "attaching a report must preserve the failure and received status",
1080 )?;
1081 let attached = cloned
1082 .retry_report()
1083 .ok_or_else(|| std::io::Error::other("retry report missing after clone"))?;
1084 check(
1085 attached.attempts == 3
1086 && attached.retry_count == 2
1087 && attached.transport_sends == 4
1088 && attached.stop_reason == Some(RetryStopReason::AttemptsExhausted),
1089 "cloning an error must retain retry statistics",
1090 )?;
1091 check(
1092 !format!("{error:?} {error}").contains("private-source"),
1093 "retry reports must not expose source text in default formatting",
1094 )
1095 }
1096
1097 #[test]
1098 fn retry_configuration_errors_support_question_mark_without_losing_details() -> TestResult {
1099 fn configure() -> Result<()> {
1100 crate::api::retry::RetrySchedule::builder()
1101 .max_attempts(0)
1102 .build()?;
1103 Ok(())
1104 }
1105 let error = match configure() {
1106 Err(error) => error,
1107 Ok(()) => return Err(std::io::Error::other("invalid configuration accepted").into()),
1108 };
1109 check(
1110 error.kind() == ErrorKind::InvalidConfig
1111 && error.context().stage == Some(ErrorStage::Configuration)
1112 && error.config_error().map(ConfigError::field) == Some("max_attempts"),
1113 "retry config conversion must retain field and origin",
1114 )?;
1115 check(
1116 error
1117 .source()
1118 .and_then(|source| source.downcast_ref::<crate::api::retry::RetryConfigError>())
1119 .is_some(),
1120 "retry config conversion must retain the original structured source",
1121 )
1122 }
1123
1124 #[cfg(feature = "ws-client")]
1125 #[test]
1126 fn websocket_timeout_phase_survives_delivery_wrapping_clone_and_retry_report() -> TestResult {
1127 use crate::ws::WsTimeoutPhase;
1128 for phase in [
1129 WsTimeoutPhase::Admission,
1130 WsTimeoutPhase::Write,
1131 WsTimeoutPhase::Response,
1132 WsTimeoutPhase::Attempt,
1133 WsTimeoutPhase::Total,
1134 ] {
1135 let source = NetError::from(ErrorKind::TimedOut)
1136 .with_stage(ErrorStage::Write)
1137 .with_ws_timeout_phase(phase);
1138 let context = source.context().clone();
1139 let error = NetError::with_source(ErrorKind::DeliveryUnknown, source)
1140 .with_context(context)
1141 .with_retry_report(crate::api::retry::RetryReport::new())
1142 .clone();
1143 check(
1144 error.ws_timeout_phase() == Some(phase),
1145 "delivery wrapper lost the WebSocket budget phase",
1146 )?;
1147 check(
1148 error
1149 .source()
1150 .and_then(|source| source.downcast_ref::<NetError>())
1151 .is_some_and(|source| {
1152 source.kind() == ErrorKind::TimedOut
1153 && source.ws_timeout_phase() == Some(phase)
1154 }),
1155 "original timeout cause lost its phase",
1156 )?;
1157 check(
1158 error.retry_report().is_some(),
1159 "timeout report lost during clone",
1160 )?;
1161 }
1162 Ok(())
1163 }
1164
1165 #[test]
1166 fn cyclic_application_sources_cannot_make_io_kind_loop_forever() -> TestResult {
1167 #[derive(Debug)]
1168 struct Cyclic;
1169 impl fmt::Display for Cyclic {
1170 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
1171 formatter.write_str("cyclic")
1172 }
1173 }
1174 impl StdError for Cyclic {
1175 fn source(&self) -> Option<&(dyn StdError + 'static)> {
1176 Some(self)
1177 }
1178 }
1179 check(
1180 NetError::provider(Cyclic).io_kind().is_none(),
1181 "cyclic source has no I/O category",
1182 )
1183 }
1184
1185 #[cfg(feature = "ws-client")]
1186 #[test]
1187 fn websocket_context_retains_details_but_redacts_peer_reason() -> TestResult {
1188 use crate::ws::{HandshakeDiagnostic, HandshakeDiagnosticKind, IoEndKind, PeerClose};
1189 use tokio_tungstenite::tungstenite::protocol::{frame::coding::CloseCode, CloseFrame};
1190
1191 let frame = CloseFrame {
1192 code: CloseCode::Normal,
1193 reason: "peer-credential-secret".into(),
1194 };
1195 let context = ErrorContext {
1196 stage: Some(ErrorStage::Receive),
1197 http_status: Some(http::StatusCode::UNAUTHORIZED),
1198 diagnostic: Some(HandshakeDiagnostic::new(
1199 HandshakeDiagnosticKind::HttpRejected,
1200 )),
1201 peer_close: Some(PeerClose::from_frame(Some(&frame))?),
1202 io_end: Some(IoEndKind::PeerClose),
1203 ..Default::default()
1204 };
1205 let error = NetError::with_source(
1206 ErrorKind::Protocol,
1207 std::io::Error::other("source-credential-secret"),
1208 )
1209 .with_context(context)
1210 .with_stage(ErrorStage::Close);
1211 let cloned = error.clone();
1212 check(
1213 cloned.context().stage == Some(ErrorStage::Close)
1214 && cloned.context().http_status == Some(http::StatusCode::UNAUTHORIZED)
1215 && cloned.context().io_end == Some(IoEndKind::PeerClose),
1216 "stage changes must preserve other contextual facts",
1217 )?;
1218 check(
1219 cloned
1220 .context()
1221 .peer_close
1222 .as_ref()
1223 .map(|value| value.reason.as_str())
1224 == Some("peer-credential-secret"),
1225 "explicit peer close access must preserve the received reason",
1226 )?;
1227 check(
1228 cloned
1229 .context()
1230 .diagnostic
1231 .as_ref()
1232 .map(|value| value.kind())
1233 == Some(HandshakeDiagnosticKind::HttpRejected),
1234 "diagnostic must survive error cloning",
1235 )?;
1236 check(
1237 !format!("{error} {error:?} {:?}", error.context()).contains("credential-secret"),
1238 "context formatting must omit peer and source strings",
1239 )
1240 }
1241}
1242
1243#[cfg(all(test, feature = "ws-client"))]
1244#[path = "identity_context_tests.rs"]
1245mod identity_context_tests;