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
7mod network_monitor;
8pub use network_monitor::{NetworkMonitorDiagnostic, NetworkMonitorPhase};
9mod windows_reachability;
10pub use windows_reachability::{WindowsReachabilityDiagnostic, WindowsReachabilityOperation};
11
12/// An owned, thread-safe error source retained by [`NetError`].
13pub type BoxError = Box<dyn StdError + Send + Sync + 'static>;
14/// The crate's standard result type.
15pub type Result<T> = std::result::Result<T, NetError>;
16
17#[non_exhaustive]
18#[derive(Clone, Copy, Debug, Eq, PartialEq)]
19/// Broad classification of failures exposed by the networking API.
20///
21/// This enum is non-exhaustive so callers must handle values added in future
22/// releases.
23pub enum ErrorKind {
24    /// The caller supplied a value that cannot be used for the requested operation.
25    InvalidInput,
26    /// A configuration value violates a documented validation rule.
27    InvalidConfig,
28    /// An operating-system or transport I/O operation failed.
29    Io,
30    /// Resolving the remote host name failed.
31    Dns,
32    /// TLS negotiation or certificate validation failed.
33    Tls,
34    /// The peer or an application callback violated the expected protocol.
35    Protocol,
36    /// The peer rejected the WebSocket upgrade handshake.
37    HandshakeRejected,
38    /// A user-supplied provider returned an error.
39    ProviderFailed,
40    /// A user callback or callback future unwound with a panic.
41    CallbackPanicked,
42    /// The runtime could not start or accept required work.
43    RuntimeUnavailable,
44    /// A bounded resource or concurrency budget could not admit more work.
45    ResourceExhausted,
46    /// A bounded queue reached its configured item or byte limit.
47    QueueFull,
48    /// The receiving side of a work queue has been closed.
49    QueueClosed,
50    /// A message or frame exceeds the configured size limit.
51    ItemTooLarge,
52    /// The maximum number of in-flight requests has been reached.
53    PendingLimitReached,
54    /// The maximum number of subscriptions has been reached.
55    SubscriptionLimitReached,
56    /// Callback delivery exceeded its bounded backlog.
57    CallbackOverflow,
58    /// Control-plane work exceeded its bounded backlog.
59    ControlOverflow,
60    /// A subscription receiver fell behind and skipped observations.
61    ObservationLagged,
62    /// The requested operation requires an established connection.
63    NotConnected,
64    /// The operation requires an actively running network monitor view.
65    NotRunning,
66    /// The operation is not implemented on this platform.
67    Unsupported,
68    /// A session with the requested identity is already active.
69    SessionAlreadyExists,
70    /// The connection is already performing its closing sequence.
71    ConnectionClosing,
72    /// The relevant sender or receiver endpoint has been closed.
73    Closed,
74    /// The owning networking engine was dropped before completion.
75    EngineDropped,
76    /// The operation was cancelled by its caller or cancellation group.
77    Cancelled,
78    /// The operation exceeded its configured deadline.
79    TimedOut,
80    /// The operation exceeded its total retry deadline.
81    DeadlineExceeded,
82    /// The message may have been written partially or its final delivery state is unknown.
83    DeliveryUnknown,
84    /// All configured connection or request retry attempts were consumed.
85    RetryExhausted,
86    /// A retry policy or deadline configuration cannot be used.
87    InvalidPolicy,
88    /// The request body cannot be materialized again for another attempt.
89    BodyNotReplayable,
90    /// A request identifier is already registered in the session.
91    DuplicateRequestId,
92    /// Response routing is disabled for the session.
93    RoutingDisabled,
94    /// The operation requires a different response-routing mode.
95    RoutingModeMismatch,
96    /// A client with the requested name is already registered.
97    ClientAlreadyExists,
98    /// No client with the requested name is registered.
99    ClientNotFound,
100    /// An invariant or internal subsystem operation failed.
101    Internal,
102    /// An HTTP status represents the failed operation.
103    HttpStatus,
104}
105
106#[non_exhaustive]
107#[derive(Clone, Copy, Debug, Eq, PartialEq)]
108/// Processing stage at which a failure was observed.
109///
110/// This enum is non-exhaustive so callers must handle values added in future
111/// releases.
112pub enum ErrorStage {
113    /// Validating or materializing configuration.
114    Configuration,
115    /// Invoking a user-supplied provider.
116    Provider,
117    /// Building or validating a request.
118    RequestBuild,
119    /// Resolving the remote host name.
120    Dns,
121    /// Opening or configuring the TCP transport.
122    Tcp,
123    /// Connecting through or authenticating with a proxy.
124    Proxy,
125    /// Negotiating TLS with the proxy or a later alert from that TLS layer.
126    ProxyTls,
127    /// Negotiating TLS or validating certificates.
128    Tls,
129    /// Performing the HTTP-to-WebSocket upgrade.
130    Upgrade,
131    /// Admitting work into a bounded subsystem.
132    Admission,
133    /// Waiting on or operating a work queue.
134    Queue,
135    /// Writing bytes or frames to the transport.
136    Write,
137    /// Classifying or completing a response.
138    Response,
139    /// Receiving data or delivering an observation.
140    Receive,
141    /// Sending or awaiting heartbeat control frames.
142    Heartbeat,
143    /// Performing connection or session shutdown.
144    Close,
145    /// Dispatching callbacks or events.
146    Dispatch,
147    /// Updating network availability state.
148    NetworkMonitor,
149    /// Interacting with the asynchronous runtime.
150    Runtime,
151}
152
153/// Optional identifiers and protocol details retained alongside a [`NetError`].
154#[non_exhaustive]
155#[derive(Clone, Default)]
156pub struct ErrorContext {
157    /// Processing stage at which the error was classified, when known.
158    /// HTTP execution failures can leave this unset when the transport does
159    /// not establish the send/receive phase. A stage is not delivery evidence.
160    pub stage: Option<ErrorStage>,
161    /// The monitor step associated with a failure, with optional timing evidence.
162    ///
163    /// Available on all platforms. For a timeout, the phase is the last observed
164    /// progress, not proof that a native call returned an error. Shared ownership
165    /// keeps unrelated errors small; clones retain the same immutable evidence.
166    pub network_monitor: Option<Arc<NetworkMonitorDiagnostic>>,
167    /// Native failure details from Windows Internet-reachability sampling.
168    ///
169    /// This field is available on every platform. The SDK leaves it `None`
170    /// for other failures, including network-name queries and non-Windows
171    /// sampling. It does not indicate that the network is offline.
172    pub windows_reachability: Option<WindowsReachabilityDiagnostic>,
173    #[cfg(feature = "ws-client")]
174    /// WebSocket client identifier associated with the failure, when available.
175    pub client_id: Option<crate::ws::ClientId>,
176    #[cfg(feature = "ws-client")]
177    /// Logical WebSocket session identifier associated with the failure, when available.
178    pub session_id: Option<crate::ws::SessionId>,
179    #[cfg(feature = "ws-client")]
180    /// Physical connection identifier associated with the failure, when available.
181    pub connection_id: Option<crate::ws::ConnectionId>,
182    #[cfg(feature = "ws-client")]
183    /// Handshake attempt identifier associated with the failure, when available.
184    pub attempt_id: Option<crate::ws::AttemptId>,
185    #[cfg(feature = "ws-client")]
186    /// Request identifier associated with the failure, when available.
187    pub request_id: Option<crate::ws::RequestId>,
188    #[cfg(feature = "ws-client")]
189    /// Expired WebSocket operation budget, when classified by the SDK.
190    pub ws_timeout_phase: Option<crate::ws::WsTimeoutPhase>,
191    /// HTTP status received from the peer, including protocol or body-read failures.
192    pub http_status: Option<http::StatusCode>,
193    #[cfg(feature = "http-client")]
194    /// HTTP request identifier associated with the failure, when available.
195    pub http_request_id: Option<crate::api::http::HttpRequestId>,
196    #[cfg(feature = "http-client")]
197    /// Expired SDK-owned HTTP budget, when identified.
198    /// A transport timeout such as HTTP/2 keepalive expiry can be `TimedOut`
199    /// while this remains `None`; the field does not describe send progress.
200    pub http_timeout_phase: Option<crate::api::http::TimeoutPhase>,
201    #[cfg(feature = "http-client")]
202    /// HTTP attempt number starting at one; zero means no attempt has started.
203    pub http_attempt: Option<u32>,
204    #[cfg(feature = "ws-client")]
205    /// Handshake diagnostic captured for the failure, when available.
206    pub diagnostic: Option<crate::ws::HandshakeDiagnostic>,
207    #[cfg(feature = "ws-client")]
208    /// Peer close details associated with the failure, when available.
209    pub peer_close: Option<crate::ws::PeerClose>,
210    #[cfg(feature = "ws-client")]
211    /// I/O termination classification associated with the failure, when available.
212    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/// An error classification, safe context, and an optional shared original cause.
253/// Formatting never includes arbitrary source text. Inspect `source()` explicitly
254/// when the original third-party or application details are required.
255#[derive(Clone)]
256pub struct NetError {
257    #[cfg(feature = "quality-doctor")]
258    quality_ref: Option<crate::quality::QualityReportRef>,
259    kind: ErrorKind,
260    // WebSocket diagnostics make the context large; keep smaller feature sets inline.
261    #[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    /// Returns the passive report reference attached by an observed failure path.
274    ///
275    /// HTTP and WebSocket adapters attach the reference of the operation they
276    /// observed; its operation kind distinguishes a request, stream, message, or
277    /// logical retry operation. A logical operation can select its own reference
278    /// when returning an underlying attempt's error. The error classification and
279    /// context remain the authority for the operation's actual failure.
280    ///
281    /// `None` means this error has no associated reference. Common causes include
282    /// errors created before observation begins, Off/dormant diagnostics, excluded
283    /// protocols, exhausted diagnostic capacity, or errors constructed directly by
284    /// application code. This accessor neither activates collection nor creates a
285    /// report. A reference may outlive retained evidence and does not guarantee
286    /// that the collector accepted every event.
287    ///
288    /// Use the originating owner's `QualityDoctor::lookup` to resolve it; another
289    /// owner's collector reports a scope mismatch. The reference retains no
290    /// request, owner, response payload, or network resource.
291    #[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    /// Creates an error classified from an HTTP status returned by a protocol or upgrade operation.
303    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            // Reuse the allocation made when this error was constructed.
336            *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        // A poisoned guard may borrow protected data. Do not capture that data
390        // or require it to satisfy the owned error source's lifetime bounds.
391        Self::new(ErrorKind::Internal)
392    }
393
394    /// Returns the broad failure classification.
395    pub fn kind(&self) -> ErrorKind {
396        self.kind
397    }
398
399    /// Returns structured context captured while processing the failure.
400    pub fn context(&self) -> &ErrorContext {
401        &self.context
402    }
403
404    /// Returns retry statistics for the logical operation that produced this error.
405    ///
406    /// Errors constructed outside a submitted operation have no report. Attaching
407    /// a report preserves the original classification, source and protocol context.
408    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    /// Returns the expired SDK-owned HTTP budget, when identified.
418    ///
419    /// `None` does not rule out `ErrorKind::TimedOut`: transport timeouts such
420    /// as HTTP/2 keepalive expiry are not an SDK phase budget. This value does
421    /// not establish whether request bytes reached the peer.
422    #[cfg(feature = "http-client")]
423    pub fn timeout_phase(&self) -> Option<crate::api::http::TimeoutPhase> {
424        self.context.http_timeout_phase
425    }
426
427    /// Returns the expired WebSocket operation budget, or `None` for other failures.
428    ///
429    /// `Attempt` is independent of the write and response timers; admission and
430    /// total timeouts always terminate the logical operation.
431    #[cfg(feature = "ws-client")]
432    pub fn ws_timeout_phase(&self) -> Option<crate::ws::WsTimeoutPhase> {
433        self.context.ws_timeout_phase
434    }
435
436    /// Returns the HTTP status associated with the failure, if one was recorded.
437    pub fn http_status(&self) -> Option<http::StatusCode> {
438        self.context.http_status
439    }
440
441    /// Returns the received status and headers when a buffered HTTP response
442    /// body failed to complete. The error kind, source and timeout phase remain
443    /// authoritative; metadata must not be interpreted as a successful response.
444    ///
445    /// Failures before a response is received and explicit cancellation do not
446    /// carry a response head. Retried attempts never reuse an earlier head.
447    #[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    /// Returns structured configuration details, if the failure came from invalid input.
463    pub fn config_error(&self) -> Option<&ConfigError> {
464        self.config_error.as_deref()
465    }
466
467    /// The first retained I/O category in the source chain, if available.
468    pub fn io_kind(&self) -> Option<std::io::ErrorKind> {
469        let mut source = self.source();
470        // Application error sources can form cycles. Bound introspection so
471        // such a source cannot cause this convenience query to loop forever.
472        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    /// Wraps a source error as a protocol failure.
483    pub fn protocol(source: impl Into<BoxError>) -> Self {
484        Self::with_source(ErrorKind::Protocol, source)
485    }
486
487    /// Wraps a source error produced by a user or transport provider.
488    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)]
540/// Details describing one invalid configuration field and the reason it was rejected.
541pub 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    /// Returns the name of the rejected configuration field.
555    pub fn field(&self) -> &str {
556        &self.field
557    }
558
559    /// Returns a stable, human-readable explanation of the validation failure.
560    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
605/// A failed admission that still owns the value that was not queued.
606pub 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    /// Returns the admission error without consuming this value.
617    pub fn error(&self) -> &NetError {
618        &self.error
619    }
620
621    /// Borrows the value that was rejected by admission.
622    pub fn value(&self) -> &T {
623        &self.value
624    }
625
626    /// Consumes the error and returns both the rejected value and its cause.
627    pub fn into_parts(self) -> (T, NetError) {
628        (self.value, self.error)
629    }
630
631    /// Consumes the error and returns only the rejected value.
632    pub fn into_inner(self) -> T {
633        self.value
634    }
635
636    /// Consumes the error and returns only its admission cause.
637    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)]
671/// Error returned while waiting for the next subscribed observation.
672pub enum ReceiveError {
673    /// Receiver fell behind and skipped this many observations.
674    Lagged {
675        /// Number of observations skipped before the next available item.
676        skipped: u64,
677    },
678    /// Underlying subscription or engine failure.
679    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)]
716/// Non-blocking receive result describing empty, closed, lagged, or failed subscriptions.
717pub enum TryReceiveError {
718    /// No item is currently available.
719    Empty,
720    /// The sender side or receiving endpoint has been closed.
721    Closed,
722    /// Receiver fell behind and skipped this many observations.
723    Lagged {
724        /// Number of observations skipped before the next available item.
725        skipped: u64,
726    },
727    /// Underlying subscription or engine failure.
728    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            // Both local builders and peer response parsing use this variant.
801            // Only the boundary handling it can identify the actual stage.
802            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                // This variant owns the unsent business message, not just an
827                // error cause. Retaining it as source would keep that payload
828                // alive through completed handles and error clones. Release
829                // it here and expose only classification and origin instead.
830                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;