Skip to main content

open_net/api/error/
mod.rs

1//! Structured failures with explicit classification and retained error sources.
2
3use std::error::Error as StdError;
4use std::fmt;
5use std::sync::Arc;
6
7/// An owned, thread-safe error source retained by [`NetError`].
8pub type BoxError = Box<dyn StdError + Send + Sync + 'static>;
9/// The crate's standard result type.
10pub type Result<T> = std::result::Result<T, NetError>;
11
12#[non_exhaustive]
13#[derive(Clone, Copy, Debug, Eq, PartialEq)]
14/// Broad classification of failures exposed by the networking API.
15///
16/// This enum is non-exhaustive so callers must handle values added in future
17/// releases.
18pub enum ErrorKind {
19    /// The caller supplied a value that cannot be used for the requested operation.
20    InvalidInput,
21    /// A configuration value violates a documented validation rule.
22    InvalidConfig,
23    /// An operating-system or transport I/O operation failed.
24    Io,
25    /// Resolving the remote host name failed.
26    Dns,
27    /// TLS negotiation or certificate validation failed.
28    Tls,
29    /// The peer or an application callback violated the expected protocol.
30    Protocol,
31    /// The peer rejected the WebSocket upgrade handshake.
32    HandshakeRejected,
33    /// A user-supplied provider returned an error.
34    ProviderFailed,
35    /// A user callback or callback future unwound with a panic.
36    CallbackPanicked,
37    /// The runtime could not start or accept required work.
38    RuntimeUnavailable,
39    /// A bounded resource or concurrency budget could not admit more work.
40    ResourceExhausted,
41    /// A bounded queue reached its configured item or byte limit.
42    QueueFull,
43    /// The receiving side of a work queue has been closed.
44    QueueClosed,
45    /// A message or frame exceeds the configured size limit.
46    ItemTooLarge,
47    /// The maximum number of in-flight requests has been reached.
48    PendingLimitReached,
49    /// The maximum number of subscriptions has been reached.
50    SubscriptionLimitReached,
51    /// Callback delivery exceeded its bounded backlog.
52    CallbackOverflow,
53    /// Control-plane work exceeded its bounded backlog.
54    ControlOverflow,
55    /// A subscription receiver fell behind and skipped observations.
56    ObservationLagged,
57    /// The requested operation requires an established connection.
58    NotConnected,
59    /// The operation requires an actively running network monitor view.
60    NotRunning,
61    /// The operation is not implemented on this platform.
62    Unsupported,
63    /// A session with the requested identity is already active.
64    SessionAlreadyExists,
65    /// The connection is already performing its closing sequence.
66    ConnectionClosing,
67    /// The relevant sender or receiver endpoint has been closed.
68    Closed,
69    /// The owning networking engine was dropped before completion.
70    EngineDropped,
71    /// The operation was cancelled by its caller or cancellation group.
72    Cancelled,
73    /// The operation exceeded its configured deadline.
74    TimedOut,
75    /// The operation exceeded its total retry deadline.
76    DeadlineExceeded,
77    /// The message may have been written partially or its final delivery state is unknown.
78    DeliveryUnknown,
79    /// All configured connection or request retry attempts were consumed.
80    RetryExhausted,
81    /// A retry policy or deadline configuration cannot be used.
82    InvalidPolicy,
83    /// The request body cannot be materialized again for another attempt.
84    BodyNotReplayable,
85    /// A request identifier is already registered in the session.
86    DuplicateRequestId,
87    /// Response routing is disabled for the session.
88    RoutingDisabled,
89    /// The operation requires a different response-routing mode.
90    RoutingModeMismatch,
91    /// A client with the requested name is already registered.
92    ClientAlreadyExists,
93    /// No client with the requested name is registered.
94    ClientNotFound,
95    /// An invariant or internal subsystem operation failed.
96    Internal,
97    /// An HTTP status represents the failed operation.
98    HttpStatus,
99}
100
101#[non_exhaustive]
102#[derive(Clone, Copy, Debug, Eq, PartialEq)]
103/// Processing stage at which a failure was observed.
104///
105/// This enum is non-exhaustive so callers must handle values added in future
106/// releases.
107pub enum ErrorStage {
108    /// Validating or materializing configuration.
109    Configuration,
110    /// Invoking a user-supplied provider.
111    Provider,
112    /// Building or validating a request.
113    RequestBuild,
114    /// Resolving the remote host name.
115    Dns,
116    /// Opening or configuring the TCP transport.
117    Tcp,
118    /// Connecting through or authenticating with a proxy.
119    Proxy,
120    /// Negotiating TLS with the proxy or a later alert from that TLS layer.
121    ProxyTls,
122    /// Negotiating TLS or validating certificates.
123    Tls,
124    /// Performing the HTTP-to-WebSocket upgrade.
125    Upgrade,
126    /// Admitting work into a bounded subsystem.
127    Admission,
128    /// Waiting on or operating a work queue.
129    Queue,
130    /// Writing bytes or frames to the transport.
131    Write,
132    /// Classifying or completing a response.
133    Response,
134    /// Receiving data or delivering an observation.
135    Receive,
136    /// Sending or awaiting heartbeat control frames.
137    Heartbeat,
138    /// Performing connection or session shutdown.
139    Close,
140    /// Dispatching callbacks or events.
141    Dispatch,
142    /// Updating network availability state.
143    NetworkMonitor,
144    /// Interacting with the asynchronous runtime.
145    Runtime,
146}
147
148/// Optional identifiers and protocol details retained alongside a [`NetError`].
149#[non_exhaustive]
150#[derive(Clone, Default)]
151pub struct ErrorContext {
152    /// Processing stage at which the error was classified, when known.
153    /// HTTP execution failures can leave this unset when the transport does
154    /// not establish the send/receive phase. A stage is not delivery evidence.
155    pub stage: Option<ErrorStage>,
156    #[cfg(feature = "ws-client")]
157    /// WebSocket client identifier associated with the failure, when available.
158    pub client_id: Option<crate::ws::ClientId>,
159    #[cfg(feature = "ws-client")]
160    /// Logical WebSocket session identifier associated with the failure, when available.
161    pub session_id: Option<crate::ws::SessionId>,
162    #[cfg(feature = "ws-client")]
163    /// Physical connection identifier associated with the failure, when available.
164    pub connection_id: Option<crate::ws::ConnectionId>,
165    #[cfg(feature = "ws-client")]
166    /// Handshake attempt identifier associated with the failure, when available.
167    pub attempt_id: Option<crate::ws::AttemptId>,
168    #[cfg(feature = "ws-client")]
169    /// Request identifier associated with the failure, when available.
170    pub request_id: Option<crate::ws::RequestId>,
171    #[cfg(feature = "ws-client")]
172    /// Expired WebSocket operation budget, when classified by the SDK.
173    pub ws_timeout_phase: Option<crate::ws::WsTimeoutPhase>,
174    /// HTTP status received from the peer, including protocol or body-read failures.
175    pub http_status: Option<http::StatusCode>,
176    #[cfg(feature = "http-client")]
177    /// HTTP request identifier associated with the failure, when available.
178    pub http_request_id: Option<crate::api::http::HttpRequestId>,
179    #[cfg(feature = "http-client")]
180    /// Expired SDK-owned HTTP budget, when identified.
181    /// A transport timeout such as HTTP/2 keepalive expiry can be `TimedOut`
182    /// while this remains `None`; the field does not describe send progress.
183    pub http_timeout_phase: Option<crate::api::http::TimeoutPhase>,
184    #[cfg(feature = "http-client")]
185    /// HTTP attempt number starting at one; zero means no attempt has started.
186    pub http_attempt: Option<u32>,
187    #[cfg(feature = "ws-client")]
188    /// Handshake diagnostic captured for the failure, when available.
189    pub diagnostic: Option<crate::ws::HandshakeDiagnostic>,
190    #[cfg(feature = "ws-client")]
191    /// Peer close details associated with the failure, when available.
192    pub peer_close: Option<crate::ws::PeerClose>,
193    #[cfg(feature = "ws-client")]
194    /// I/O termination classification associated with the failure, when available.
195    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/// An error classification, safe context, and an optional shared original cause.
234/// Formatting never includes arbitrary source text. Inspect `source()` explicitly
235/// when the original third-party or application details are required.
236#[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    /// Creates an error classified from an HTTP status returned by a protocol or upgrade operation.
249    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        // A poisoned guard may borrow protected data. Do not capture that data
324        // or require it to satisfy the owned error source's lifetime bounds.
325        Self::new(ErrorKind::Internal)
326    }
327
328    /// Returns the broad failure classification.
329    pub fn kind(&self) -> ErrorKind {
330        self.kind
331    }
332
333    /// Returns structured context captured while processing the failure.
334    pub fn context(&self) -> &ErrorContext {
335        &self.context
336    }
337
338    /// Returns retry statistics for the logical operation that produced this error.
339    ///
340    /// Errors constructed outside a submitted operation have no report. Attaching
341    /// a report preserves the original classification, source and protocol context.
342    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    /// Returns the expired SDK-owned HTTP budget, when identified.
352    ///
353    /// `None` does not rule out `ErrorKind::TimedOut`: transport timeouts such
354    /// as HTTP/2 keepalive expiry are not an SDK phase budget. This value does
355    /// not establish whether request bytes reached the peer.
356    #[cfg(feature = "http-client")]
357    pub fn timeout_phase(&self) -> Option<crate::api::http::TimeoutPhase> {
358        self.context.http_timeout_phase
359    }
360
361    /// Returns the expired WebSocket operation budget, or `None` for other failures.
362    ///
363    /// `Attempt` is independent of the write and response timers; admission and
364    /// total timeouts always terminate the logical operation.
365    #[cfg(feature = "ws-client")]
366    pub fn ws_timeout_phase(&self) -> Option<crate::ws::WsTimeoutPhase> {
367        self.context.ws_timeout_phase
368    }
369
370    /// Returns the HTTP status associated with the failure, if one was recorded.
371    pub fn http_status(&self) -> Option<http::StatusCode> {
372        self.context.http_status
373    }
374
375    /// Returns the received status and headers when a buffered HTTP response
376    /// body failed to complete. The error kind, source and timeout phase remain
377    /// authoritative; metadata must not be interpreted as a successful response.
378    ///
379    /// Failures before a response is received and explicit cancellation do not
380    /// carry a response head. Retried attempts never reuse an earlier head.
381    #[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    /// Returns structured configuration details, if the failure came from invalid input.
397    pub fn config_error(&self) -> Option<&ConfigError> {
398        self.config_error.as_deref()
399    }
400
401    /// The first retained I/O category in the source chain, if available.
402    pub fn io_kind(&self) -> Option<std::io::ErrorKind> {
403        let mut source = self.source();
404        // Application error sources can form cycles. Bound introspection so
405        // such a source cannot cause this convenience query to loop forever.
406        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    /// Wraps a source error as a protocol failure.
417    pub fn protocol(source: impl Into<BoxError>) -> Self {
418        Self::with_source(ErrorKind::Protocol, source)
419    }
420
421    /// Wraps a source error produced by a user or transport provider.
422    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)]
474/// Details describing one invalid configuration field and the reason it was rejected.
475pub 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    /// Returns the name of the rejected configuration field.
489    pub fn field(&self) -> &str {
490        &self.field
491    }
492
493    /// Returns a stable, human-readable explanation of the validation failure.
494    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
539/// A failed admission that still owns the value that was not queued.
540pub 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    /// Returns the admission error without consuming this value.
551    pub fn error(&self) -> &NetError {
552        &self.error
553    }
554
555    /// Borrows the value that was rejected by admission.
556    pub fn value(&self) -> &T {
557        &self.value
558    }
559
560    /// Consumes the error and returns both the rejected value and its cause.
561    pub fn into_parts(self) -> (T, NetError) {
562        (self.value, self.error)
563    }
564
565    /// Consumes the error and returns only the rejected value.
566    pub fn into_inner(self) -> T {
567        self.value
568    }
569
570    /// Consumes the error and returns only its admission cause.
571    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)]
605/// Error returned while waiting for the next subscribed observation.
606pub enum ReceiveError {
607    /// Receiver fell behind and skipped this many observations.
608    Lagged {
609        /// Number of observations skipped before the next available item.
610        skipped: u64,
611    },
612    /// Underlying subscription or engine failure.
613    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)]
650/// Non-blocking receive result describing empty, closed, lagged, or failed subscriptions.
651pub enum TryReceiveError {
652    /// No item is currently available.
653    Empty,
654    /// The sender side or receiving endpoint has been closed.
655    Closed,
656    /// Receiver fell behind and skipped this many observations.
657    Lagged {
658        /// Number of observations skipped before the next available item.
659        skipped: u64,
660    },
661    /// Underlying subscription or engine failure.
662    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            // Both local builders and peer response parsing use this variant.
735            // Only the boundary handling it can identify the actual stage.
736            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                // This variant owns the unsent business message, not just an
761                // error cause. Retaining it as source would keep that payload
762                // alive through completed handles and error clones. Release
763                // it here and expose only classification and origin instead.
764                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;