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 SessionAlreadyExists,
61 ConnectionClosing,
63 Closed,
65 EngineDropped,
67 Cancelled,
69 TimedOut,
71 DeadlineExceeded,
73 DeliveryUnknown,
75 RetryExhausted,
77 InvalidPolicy,
79 BodyNotReplayable,
81 DuplicateRequestId,
83 RoutingDisabled,
85 RoutingModeMismatch,
87 ClientAlreadyExists,
89 ClientNotFound,
91 Internal,
93 HttpStatus,
95}
96
97#[non_exhaustive]
98#[derive(Clone, Copy, Debug, Eq, PartialEq)]
99pub enum ErrorStage {
104 Configuration,
106 Provider,
108 RequestBuild,
110 Dns,
112 Tcp,
114 Proxy,
116 Tls,
118 Upgrade,
120 Admission,
122 Queue,
124 Write,
126 Response,
128 Receive,
130 Heartbeat,
132 Close,
134 Dispatch,
136 NetworkMonitor,
138 Runtime,
140}
141
142#[non_exhaustive]
144#[derive(Clone, Default)]
145pub struct ErrorContext {
146 pub stage: Option<ErrorStage>,
148 #[cfg(feature = "ws-client")]
149 pub client_id: Option<crate::ws::ClientId>,
151 #[cfg(feature = "ws-client")]
152 pub session_id: Option<crate::ws::SessionId>,
154 #[cfg(feature = "ws-client")]
155 pub connection_id: Option<crate::ws::ConnectionId>,
157 #[cfg(feature = "ws-client")]
158 pub attempt_id: Option<crate::ws::AttemptId>,
160 #[cfg(feature = "ws-client")]
161 pub request_id: Option<crate::ws::RequestId>,
163 pub http_status: Option<http::StatusCode>,
165 #[cfg(feature = "ws-client")]
166 pub diagnostic: Option<crate::ws::HandshakeDiagnostic>,
168 #[cfg(feature = "ws-client")]
169 pub peer_close: Option<crate::ws::PeerClose>,
171 #[cfg(feature = "ws-client")]
172 pub io_end: Option<crate::ws::IoEndKind>,
174}
175
176impl fmt::Debug for ErrorContext {
177 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
178 let mut output = formatter.debug_struct("ErrorContext");
179 output
180 .field("stage", &self.stage)
181 .field("http_status", &self.http_status);
182 #[cfg(feature = "ws-client")]
183 output
184 .field("client_id", &self.client_id)
185 .field("session_id", &self.session_id)
186 .field("connection_id", &self.connection_id)
187 .field("attempt_id", &self.attempt_id)
188 .field(
189 "request_id_len",
190 &self.request_id.as_ref().map(|id| id.as_str().len()),
191 )
192 .field(
193 "diagnostic_kind",
194 &self.diagnostic.as_ref().map(|value| value.kind()),
195 )
196 .field(
197 "peer_close_code",
198 &self.peer_close.as_ref().map(|value| value.code),
199 )
200 .field("io_end", &self.io_end);
201 output.finish()
202 }
203}
204
205#[derive(Clone)]
209pub struct NetError {
210 kind: ErrorKind,
211 context: ErrorContext,
212 config_error: Option<Arc<ConfigError>>,
213 source: Option<Arc<dyn StdError + Send + Sync + 'static>>,
214}
215
216impl NetError {
217 pub fn from_http_status(status: http::StatusCode) -> Self {
219 let mut context = ErrorContext::default();
220 context.http_status = Some(status);
221 Self::new(ErrorKind::HttpStatus).with_context(context)
222 }
223 pub(crate) fn new(kind: ErrorKind) -> Self {
224 Self {
225 kind,
226 context: ErrorContext::default(),
227 config_error: None,
228 source: None,
229 }
230 }
231
232 pub(crate) fn with_source(kind: ErrorKind, source: impl Into<BoxError>) -> Self {
233 let source: BoxError = source.into();
234 Self {
235 source: Some(Arc::from(source)),
236 ..Self::new(kind)
237 }
238 }
239
240 pub(crate) fn with_context(mut self, context: ErrorContext) -> Self {
241 self.context = context;
242 self
243 }
244
245 pub(crate) fn with_stage(mut self, stage: ErrorStage) -> Self {
246 self.context.stage = Some(stage);
247 self
248 }
249
250 pub(crate) fn config(field: impl Into<String>, reason: impl Into<String>) -> Self {
251 ConfigError::new(field, reason).into()
252 }
253
254 pub(crate) fn input(field: impl Into<String>, reason: impl Into<String>) -> Self {
255 Self {
256 config_error: Some(Arc::new(ConfigError::new(field, reason))),
257 ..Self::new(ErrorKind::InvalidInput).with_stage(ErrorStage::RequestBuild)
258 }
259 }
260
261 pub(crate) fn from_poison<T>(_: std::sync::PoisonError<T>) -> Self {
262 Self::new(ErrorKind::Internal)
265 }
266
267 pub fn kind(&self) -> ErrorKind {
269 self.kind
270 }
271
272 pub fn context(&self) -> &ErrorContext {
274 &self.context
275 }
276
277 pub fn http_status(&self) -> Option<http::StatusCode> {
279 self.context.http_status
280 }
281
282 pub fn config_error(&self) -> Option<&ConfigError> {
284 self.config_error.as_deref()
285 }
286
287 pub fn io_kind(&self) -> Option<std::io::ErrorKind> {
289 let mut source = self.source();
290 for _ in 0..64 {
293 let error = source?;
294 if let Some(io) = error.downcast_ref::<std::io::Error>() {
295 return Some(io.kind());
296 }
297 source = error.source();
298 }
299 None
300 }
301
302 pub fn protocol(source: impl Into<BoxError>) -> Self {
304 Self::with_source(ErrorKind::Protocol, source)
305 }
306
307 pub fn provider(source: impl Into<BoxError>) -> Self {
309 Self::with_source(ErrorKind::ProviderFailed, source).with_stage(ErrorStage::Provider)
310 }
311}
312
313impl fmt::Debug for NetError {
314 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
315 formatter
316 .debug_struct("NetError")
317 .field("kind", &self.kind)
318 .field("context", &self.context)
319 .field("config_error", &self.config_error)
320 .field("has_source", &self.source.is_some())
321 .finish()
322 }
323}
324
325impl fmt::Display for NetError {
326 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
327 write!(formatter, "{:?}", self.kind)?;
328 if let Some(stage) = self.context.stage {
329 write!(formatter, " at {stage:?}")?;
330 }
331 if let Some(status) = self.context.http_status {
332 write!(formatter, " (HTTP {})", status.as_u16())?;
333 }
334 Ok(())
335 }
336}
337
338impl StdError for NetError {
339 fn source(&self) -> Option<&(dyn StdError + 'static)> {
340 self.source
341 .as_deref()
342 .map(|source| source as &(dyn StdError + 'static))
343 }
344}
345
346impl From<ErrorKind> for NetError {
347 fn from(kind: ErrorKind) -> Self {
348 Self::new(kind)
349 }
350}
351
352impl From<std::io::Error> for NetError {
353 fn from(source: std::io::Error) -> Self {
354 Self::with_source(ErrorKind::Io, source)
355 }
356}
357
358#[derive(Clone)]
359pub struct ConfigError {
361 field: String,
362 reason: String,
363}
364
365impl ConfigError {
366 fn new(field: impl Into<String>, reason: impl Into<String>) -> Self {
367 Self {
368 field: field.into(),
369 reason: reason.into(),
370 }
371 }
372
373 pub fn field(&self) -> &str {
375 &self.field
376 }
377
378 pub fn reason(&self) -> &str {
380 &self.reason
381 }
382}
383
384impl fmt::Debug for ConfigError {
385 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
386 formatter
387 .debug_struct("ConfigError")
388 .field("field_bytes", &self.field.len())
389 .field("reason_bytes", &self.reason.len())
390 .finish()
391 }
392}
393
394impl fmt::Display for ConfigError {
395 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
396 formatter.write_str("invalid configuration")
397 }
398}
399
400impl StdError for ConfigError {}
401
402impl From<ConfigError> for NetError {
403 fn from(value: ConfigError) -> Self {
404 let detail = Arc::new(value);
405 Self {
406 config_error: Some(Arc::clone(&detail)),
407 source: Some(detail),
408 ..Self::new(ErrorKind::InvalidConfig).with_stage(ErrorStage::Configuration)
409 }
410 }
411}
412
413pub struct EnqueueError<T> {
415 value: T,
416 error: NetError,
417}
418
419impl<T> EnqueueError<T> {
420 pub(crate) fn new(value: T, error: NetError) -> Self {
421 Self { value, error }
422 }
423
424 pub fn error(&self) -> &NetError {
426 &self.error
427 }
428
429 pub fn value(&self) -> &T {
431 &self.value
432 }
433
434 pub fn into_parts(self) -> (T, NetError) {
436 (self.value, self.error)
437 }
438
439 pub fn into_inner(self) -> T {
441 self.value
442 }
443
444 pub fn into_error(self) -> NetError {
446 self.error
447 }
448}
449
450impl<T> fmt::Debug for EnqueueError<T> {
451 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
452 formatter
453 .debug_struct("EnqueueError")
454 .field("error", &self.error)
455 .finish_non_exhaustive()
456 }
457}
458
459impl<T> fmt::Display for EnqueueError<T> {
460 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
461 write!(formatter, "enqueue failed: {}", self.error)
462 }
463}
464
465impl<T: Send + Sync + 'static> StdError for EnqueueError<T> {
466 fn source(&self) -> Option<&(dyn StdError + 'static)> {
467 Some(&self.error)
468 }
469}
470
471impl<T> From<EnqueueError<T>> for NetError {
472 fn from(value: EnqueueError<T>) -> Self {
473 value.into_error()
474 }
475}
476
477#[non_exhaustive]
478#[derive(Clone, Debug)]
479pub enum ReceiveError {
481 Lagged {
483 skipped: u64,
485 },
486 Failed(NetError),
488}
489
490impl fmt::Display for ReceiveError {
491 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
492 match self {
493 Self::Lagged { skipped } => {
494 write!(formatter, "receiver lagged; skipped {skipped} observations")
495 }
496 Self::Failed(error) => write!(formatter, "receive failed: {error}"),
497 }
498 }
499}
500
501impl StdError for ReceiveError {
502 fn source(&self) -> Option<&(dyn StdError + 'static)> {
503 match self {
504 Self::Lagged { .. } => None,
505 Self::Failed(error) => Some(error),
506 }
507 }
508}
509
510impl From<ReceiveError> for NetError {
511 fn from(value: ReceiveError) -> Self {
512 match value {
513 value @ ReceiveError::Lagged { .. } => {
514 Self::with_source(ErrorKind::ObservationLagged, value)
515 .with_stage(ErrorStage::Receive)
516 }
517 ReceiveError::Failed(error) => error,
518 }
519 }
520}
521
522#[non_exhaustive]
523#[derive(Clone, Debug)]
524pub enum TryReceiveError {
526 Empty,
528 Closed,
530 Lagged {
532 skipped: u64,
534 },
535 Failed(NetError),
537}
538
539impl fmt::Display for TryReceiveError {
540 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
541 match self {
542 Self::Empty => formatter.write_str("receiver is empty"),
543 Self::Closed => formatter.write_str("receiver is closed"),
544 Self::Lagged { skipped } => {
545 write!(formatter, "receiver lagged; skipped {skipped} observations")
546 }
547 Self::Failed(error) => write!(formatter, "receive failed: {error}"),
548 }
549 }
550}
551
552impl StdError for TryReceiveError {
553 fn source(&self) -> Option<&(dyn StdError + 'static)> {
554 match self {
555 Self::Failed(error) => Some(error),
556 Self::Empty | Self::Closed | Self::Lagged { .. } => None,
557 }
558 }
559}
560
561impl fmt::Display for crate::common::CommonError {
562 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
563 formatter.write_str(match self {
564 Self::None => "unknown engine failure",
565 Self::RuntimeError => "engine runtime unavailable",
566 Self::PostError => "engine queue closed",
567 })
568 }
569}
570
571impl StdError for crate::common::CommonError {}
572
573impl From<crate::common::CommonError> for NetError {
574 fn from(value: crate::common::CommonError) -> Self {
575 let kind = match value {
576 crate::common::CommonError::None => ErrorKind::Internal,
577 crate::common::CommonError::RuntimeError => ErrorKind::RuntimeUnavailable,
578 crate::common::CommonError::PostError => ErrorKind::QueueClosed,
579 };
580 Self::with_source(kind, value).with_stage(ErrorStage::Runtime)
581 }
582}
583
584#[cfg(feature = "ws-client")]
585impl From<tokio_tungstenite::tungstenite::Error> for NetError {
586 fn from(value: tokio_tungstenite::tungstenite::Error) -> Self {
587 use tokio_tungstenite::tungstenite::error::{CapacityError, UrlError};
588 use tokio_tungstenite::tungstenite::Error;
589
590 let mut context = ErrorContext::default();
591 let kind = match &value {
592 Error::ConnectionClosed | Error::AlreadyClosed => ErrorKind::Closed,
593 Error::Io(_) => ErrorKind::Io,
594 Error::Tls(_) => {
595 context.stage = Some(ErrorStage::Tls);
596 ErrorKind::Tls
597 }
598 Error::Capacity(CapacityError::MessageTooLong { .. }) => ErrorKind::ItemTooLarge,
599 Error::Capacity(CapacityError::TooManyHeaders) => ErrorKind::ResourceExhausted,
600 Error::Protocol(_) | Error::Utf8(_) | Error::AttackAttempt => ErrorKind::Protocol,
601 Error::HttpFormat(_) => ErrorKind::Protocol,
604 Error::Url(UrlError::UnableToConnect(_)) => {
605 context.stage = Some(ErrorStage::Tcp);
606 ErrorKind::Io
607 }
608 Error::Url(UrlError::TlsFeatureNotEnabled) => {
609 context.stage = Some(ErrorStage::Configuration);
610 ErrorKind::InvalidConfig
611 }
612 Error::Url(
613 UrlError::NoHostName
614 | UrlError::UnsupportedUrlScheme
615 | UrlError::EmptyHostName
616 | UrlError::NoPathOrQuery,
617 ) => {
618 context.stage = Some(ErrorStage::RequestBuild);
619 ErrorKind::InvalidInput
620 }
621 Error::Http(response) => {
622 context.stage = Some(ErrorStage::Upgrade);
623 context.http_status = Some(response.status());
624 ErrorKind::HandshakeRejected
625 }
626 Error::WriteBufferFull(_) => {
627 return Self::new(ErrorKind::DeliveryUnknown).with_stage(ErrorStage::Write);
632 }
633 };
634 Self::with_source(kind, value).with_context(context)
635 }
636}
637
638#[cfg(test)]
639mod tests {
640 use super::*;
641 use std::sync::atomic::{AtomicUsize, Ordering};
642
643 type TestResult<T = ()> = std::result::Result<T, BoxError>;
644
645 fn check(condition: bool, message: &str) -> TestResult {
646 if condition {
647 Ok(())
648 } else {
649 Err(std::io::Error::other(message).into())
650 }
651 }
652
653 struct InputWithoutDebug {
654 payload: String,
655 drops: Arc<AtomicUsize>,
656 }
657
658 impl Drop for InputWithoutDebug {
659 fn drop(&mut self) {
660 self.drops.fetch_add(1, Ordering::SeqCst);
661 }
662 }
663
664 fn rejected(drops: &Arc<AtomicUsize>) -> EnqueueError<InputWithoutDebug> {
665 EnqueueError::new(
666 InputWithoutDebug {
667 payload: "unaccepted-payload-secret".into(),
668 drops: Arc::clone(drops),
669 },
670 NetError::new(ErrorKind::QueueFull),
671 )
672 }
673
674 #[test]
675 fn enqueue_recovery_preserves_ownership_without_requiring_debug() -> TestResult {
676 let drops = Arc::new(AtomicUsize::new(0));
677 let failure = rejected(&drops);
678 check(
679 failure.error().kind() == ErrorKind::QueueFull,
680 "enqueue classification",
681 )?;
682 check(
683 failure.value().payload == "unaccepted-payload-secret",
684 "borrow original input",
685 )?;
686 check(
687 !format!("{failure} {failure:?}").contains("payload-secret"),
688 "input must not enter default formatting",
689 )?;
690 check(
691 failure.source().is_some(),
692 "enqueue source must be its admission error",
693 )?;
694 let (input, error) = failure.into_parts();
695 check(
696 input.payload == "unaccepted-payload-secret" && error.kind() == ErrorKind::QueueFull,
697 "recover input with cause",
698 )?;
699 check(
700 drops.load(Ordering::SeqCst) == 0,
701 "recovery must not drop the input",
702 )?;
703 drop(input);
704 check(
705 drops.load(Ordering::SeqCst) == 1,
706 "recovered input must drop once",
707 )?;
708 let input = rejected(&drops).into_inner();
709 check(
710 input.payload == "unaccepted-payload-secret",
711 "recover input alone",
712 )?;
713 drop(input);
714 let error = rejected(&drops).into_error();
715 check(
716 error.kind() == ErrorKind::QueueFull && drops.load(Ordering::SeqCst) == 3,
717 "error-only conversion must drop unaccepted input",
718 )?;
719 Ok(())
720 }
721
722 #[test]
723 fn enqueue_question_mark_discards_input_and_preserves_the_error() -> TestResult {
724 fn propagate(drops: &Arc<AtomicUsize>) -> Result<()> {
725 Err(rejected(drops))?;
726 Ok(())
727 }
728 let drops = Arc::new(AtomicUsize::new(0));
729 let error = propagate(&drops)
730 .err()
731 .ok_or_else(|| std::io::Error::other("admission error missing"))?;
732 check(
733 error.kind() == ErrorKind::QueueFull,
734 "question-mark classification",
735 )?;
736 check(
737 drops.load(Ordering::SeqCst) == 1,
738 "question mark deliberately discards unaccepted input",
739 )
740 }
741
742 #[test]
743 fn configuration_details_are_explicitly_readable_but_never_default_formatted() -> TestResult {
744 let error = NetError::config("private-field-secret", "private-value-secret");
745 let detail = error
746 .config_error()
747 .ok_or_else(|| std::io::Error::other("config detail missing"))?;
748 check(
749 detail.field() == "private-field-secret" && detail.reason() == "private-value-secret",
750 "explicit config getters",
751 )?;
752 check(
753 error.kind() == ErrorKind::InvalidConfig
754 && error.context().stage == Some(ErrorStage::Configuration),
755 "configuration origin",
756 )?;
757 check(
758 error
759 .source()
760 .and_then(|source| source.downcast_ref::<ConfigError>())
761 .is_some(),
762 "config source must remain structured",
763 )?;
764 check(
765 !format!("{error} {error:?} {detail} {detail:?}").contains("secret"),
766 "configuration strings must be redacted",
767 )?;
768 fn propagate() -> Result<()> {
769 Err(ConfigError::new("queue.capacity", "must be nonzero"))?;
770 Ok(())
771 }
772 let propagated = propagate()
773 .err()
774 .ok_or_else(|| std::io::Error::other("config error did not propagate"))?;
775 check(
776 propagated.config_error().map(ConfigError::field) == Some("queue.capacity"),
777 "question-mark config details",
778 )
779 }
780
781 #[test]
782 fn common_errors_retain_the_original_engine_source() -> TestResult {
783 for (source, kind) in [
784 (crate::common::CommonError::None, ErrorKind::Internal),
785 (
786 crate::common::CommonError::RuntimeError,
787 ErrorKind::RuntimeUnavailable,
788 ),
789 (
790 crate::common::CommonError::PostError,
791 ErrorKind::QueueClosed,
792 ),
793 ] {
794 let error = NetError::from(source);
795 check(
796 error.kind() == kind && error.context().stage == Some(ErrorStage::Runtime),
797 "common error category and stage",
798 )?;
799 check(
800 error
801 .source()
802 .and_then(|source| source.downcast_ref::<crate::common::CommonError>())
803 .copied()
804 == Some(source),
805 "original common source",
806 )?;
807 }
808 Ok(())
809 }
810
811 #[test]
812 fn cyclic_application_sources_cannot_make_io_kind_loop_forever() -> TestResult {
813 #[derive(Debug)]
814 struct Cyclic;
815 impl fmt::Display for Cyclic {
816 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
817 formatter.write_str("cyclic")
818 }
819 }
820 impl StdError for Cyclic {
821 fn source(&self) -> Option<&(dyn StdError + 'static)> {
822 Some(self)
823 }
824 }
825 check(
826 NetError::provider(Cyclic).io_kind().is_none(),
827 "cyclic source has no I/O category",
828 )
829 }
830
831 #[cfg(feature = "ws-client")]
832 #[test]
833 fn websocket_context_retains_details_but_redacts_peer_reason() -> TestResult {
834 use crate::ws::{HandshakeDiagnostic, HandshakeDiagnosticKind, IoEndKind, PeerClose};
835 use tokio_tungstenite::tungstenite::protocol::{frame::coding::CloseCode, CloseFrame};
836
837 let frame = CloseFrame {
838 code: CloseCode::Normal,
839 reason: "peer-credential-secret".into(),
840 };
841 let context = ErrorContext {
842 stage: Some(ErrorStage::Receive),
843 http_status: Some(http::StatusCode::UNAUTHORIZED),
844 diagnostic: Some(HandshakeDiagnostic::new(
845 HandshakeDiagnosticKind::HttpRejected,
846 )),
847 peer_close: Some(PeerClose::from_frame(Some(&frame))?),
848 io_end: Some(IoEndKind::PeerClose),
849 ..Default::default()
850 };
851 let error = NetError::with_source(
852 ErrorKind::Protocol,
853 std::io::Error::other("source-credential-secret"),
854 )
855 .with_context(context)
856 .with_stage(ErrorStage::Close);
857 let cloned = error.clone();
858 check(
859 cloned.context().stage == Some(ErrorStage::Close)
860 && cloned.context().http_status == Some(http::StatusCode::UNAUTHORIZED)
861 && cloned.context().io_end == Some(IoEndKind::PeerClose),
862 "stage changes must preserve other contextual facts",
863 )?;
864 check(
865 cloned
866 .context()
867 .peer_close
868 .as_ref()
869 .map(|value| value.reason.as_str())
870 == Some("peer-credential-secret"),
871 "explicit peer close access must preserve the received reason",
872 )?;
873 check(
874 cloned
875 .context()
876 .diagnostic
877 .as_ref()
878 .map(|value| value.kind())
879 == Some(HandshakeDiagnosticKind::HttpRejected),
880 "diagnostic must survive error cloning",
881 )?;
882 check(
883 !format!("{error} {error:?} {:?}", error.context()).contains("credential-secret"),
884 "context formatting must omit peer and source strings",
885 )
886 }
887}
888
889#[cfg(all(test, feature = "ws-client"))]
890#[path = "identity_context_tests.rs"]
891mod identity_context_tests;