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    #[cfg(feature = "quality-doctor")]
239    quality_ref: Option<crate::quality::QualityReportRef>,
240    kind: ErrorKind,
241    context: ErrorContext,
242    config_error: Option<Arc<ConfigError>>,
243    source: Option<Arc<dyn StdError + Send + Sync + 'static>>,
244    retry_report: Option<Arc<crate::api::retry::RetryReport>>,
245    #[cfg(feature = "http-client")]
246    http_response_head: Option<Arc<crate::api::http::HttpResponseHead>>,
247}
248
249impl NetError {
250    /// Returns the passive report reference attached by an observed failure path.
251    ///
252    /// HTTP and WebSocket adapters attach the reference of the operation they
253    /// observed; its operation kind distinguishes a request, stream, message, or
254    /// logical retry operation. A logical operation can select its own reference
255    /// when returning an underlying attempt's error. The error classification and
256    /// context remain the authority for the operation's actual failure.
257    ///
258    /// `None` means this error has no associated reference. Common causes include
259    /// errors created before observation begins, Off/dormant diagnostics, excluded
260    /// protocols, exhausted diagnostic capacity, or errors constructed directly by
261    /// application code. This accessor neither activates collection nor creates a
262    /// report. A reference may outlive retained evidence and does not guarantee
263    /// that the collector accepted every event.
264    ///
265    /// Use the originating owner's `QualityDoctor::lookup` to resolve it; another
266    /// owner's collector reports a scope mismatch. The reference retains no
267    /// request, owner, response payload, or network resource.
268    #[cfg(feature = "quality-doctor")]
269    pub fn quality_ref(&self) -> Option<crate::quality::QualityReportRef> {
270        self.quality_ref.clone()
271    }
272
273    #[cfg(feature = "quality-doctor")]
274    pub(crate) fn with_quality_ref(mut self, reference: crate::quality::QualityReportRef) -> Self {
275        self.quality_ref = Some(reference);
276        self
277    }
278
279    /// Creates an error classified from an HTTP status returned by a protocol or upgrade operation.
280    pub fn from_http_status(status: http::StatusCode) -> Self {
281        let mut context = ErrorContext::default();
282        context.http_status = Some(status);
283        Self::new(ErrorKind::HttpStatus).with_context(context)
284    }
285    pub(crate) fn new(kind: ErrorKind) -> Self {
286        Self {
287            #[cfg(feature = "quality-doctor")]
288            quality_ref: None,
289            kind,
290            context: ErrorContext::default(),
291            config_error: None,
292            source: None,
293            retry_report: None,
294            #[cfg(feature = "http-client")]
295            http_response_head: None,
296        }
297    }
298
299    pub(crate) fn with_source(kind: ErrorKind, source: impl Into<BoxError>) -> Self {
300        let source: BoxError = source.into();
301        Self {
302            source: Some(Arc::from(source)),
303            ..Self::new(kind)
304        }
305    }
306
307    pub(crate) fn with_context(mut self, context: ErrorContext) -> Self {
308        self.context = context;
309        self
310    }
311
312    pub(crate) fn with_stage(mut self, stage: ErrorStage) -> Self {
313        self.context.stage = Some(stage);
314        self
315    }
316
317    #[cfg(feature = "http-client")]
318    pub(crate) fn with_http_request_id(
319        mut self,
320        request_id: crate::api::http::HttpRequestId,
321    ) -> Self {
322        self.context.http_request_id = Some(request_id);
323        self
324    }
325
326    pub(crate) fn config(field: impl Into<String>, reason: impl Into<String>) -> Self {
327        ConfigError::new(field, reason).into()
328    }
329
330    #[cfg(feature = "http-client")]
331    pub(crate) fn with_http_attempt(mut self, attempt: u32) -> Self {
332        self.context.http_attempt = Some(attempt);
333        self
334    }
335
336    #[cfg(feature = "http-client")]
337    pub(crate) fn with_timeout_phase(mut self, phase: crate::api::http::TimeoutPhase) -> Self {
338        self.context.http_timeout_phase = Some(phase);
339        self
340    }
341
342    #[cfg(feature = "ws-client")]
343    pub(crate) fn with_ws_timeout_phase(mut self, phase: crate::ws::WsTimeoutPhase) -> Self {
344        self.context.ws_timeout_phase = Some(phase);
345        self
346    }
347
348    pub(crate) fn input(field: impl Into<String>, reason: impl Into<String>) -> Self {
349        Self {
350            config_error: Some(Arc::new(ConfigError::new(field, reason))),
351            ..Self::new(ErrorKind::InvalidInput).with_stage(ErrorStage::RequestBuild)
352        }
353    }
354
355    pub(crate) fn from_poison<T>(_: std::sync::PoisonError<T>) -> Self {
356        // A poisoned guard may borrow protected data. Do not capture that data
357        // or require it to satisfy the owned error source's lifetime bounds.
358        Self::new(ErrorKind::Internal)
359    }
360
361    /// Returns the broad failure classification.
362    pub fn kind(&self) -> ErrorKind {
363        self.kind
364    }
365
366    /// Returns structured context captured while processing the failure.
367    pub fn context(&self) -> &ErrorContext {
368        &self.context
369    }
370
371    /// Returns retry statistics for the logical operation that produced this error.
372    ///
373    /// Errors constructed outside a submitted operation have no report. Attaching
374    /// a report preserves the original classification, source and protocol context.
375    pub fn retry_report(&self) -> Option<&crate::api::retry::RetryReport> {
376        self.retry_report.as_deref()
377    }
378
379    pub(crate) fn with_retry_report(mut self, report: crate::api::retry::RetryReport) -> Self {
380        self.retry_report = Some(Arc::new(report));
381        self
382    }
383
384    /// Returns the expired SDK-owned HTTP budget, when identified.
385    ///
386    /// `None` does not rule out `ErrorKind::TimedOut`: transport timeouts such
387    /// as HTTP/2 keepalive expiry are not an SDK phase budget. This value does
388    /// not establish whether request bytes reached the peer.
389    #[cfg(feature = "http-client")]
390    pub fn timeout_phase(&self) -> Option<crate::api::http::TimeoutPhase> {
391        self.context.http_timeout_phase
392    }
393
394    /// Returns the expired WebSocket operation budget, or `None` for other failures.
395    ///
396    /// `Attempt` is independent of the write and response timers; admission and
397    /// total timeouts always terminate the logical operation.
398    #[cfg(feature = "ws-client")]
399    pub fn ws_timeout_phase(&self) -> Option<crate::ws::WsTimeoutPhase> {
400        self.context.ws_timeout_phase
401    }
402
403    /// Returns the HTTP status associated with the failure, if one was recorded.
404    pub fn http_status(&self) -> Option<http::StatusCode> {
405        self.context.http_status
406    }
407
408    /// Returns the received status and headers when a buffered HTTP response
409    /// body failed to complete. The error kind, source and timeout phase remain
410    /// authoritative; metadata must not be interpreted as a successful response.
411    ///
412    /// Failures before a response is received and explicit cancellation do not
413    /// carry a response head. Retried attempts never reuse an earlier head.
414    #[cfg(feature = "http-client")]
415    pub fn http_response_head(&self) -> Option<&crate::api::http::HttpResponseHead> {
416        self.http_response_head.as_deref()
417    }
418
419    #[cfg(feature = "http-client")]
420    pub(crate) fn with_http_response_head(
421        mut self,
422        head: crate::api::http::HttpResponseHead,
423    ) -> Self {
424        self.context.http_status = Some(head.status);
425        self.http_response_head = Some(Arc::new(head));
426        self
427    }
428
429    /// Returns structured configuration details, if the failure came from invalid input.
430    pub fn config_error(&self) -> Option<&ConfigError> {
431        self.config_error.as_deref()
432    }
433
434    /// The first retained I/O category in the source chain, if available.
435    pub fn io_kind(&self) -> Option<std::io::ErrorKind> {
436        let mut source = self.source();
437        // Application error sources can form cycles. Bound introspection so
438        // such a source cannot cause this convenience query to loop forever.
439        for _ in 0..64 {
440            let error = source?;
441            if let Some(io) = error.downcast_ref::<std::io::Error>() {
442                return Some(io.kind());
443            }
444            source = error.source();
445        }
446        None
447    }
448
449    /// Wraps a source error as a protocol failure.
450    pub fn protocol(source: impl Into<BoxError>) -> Self {
451        Self::with_source(ErrorKind::Protocol, source)
452    }
453
454    /// Wraps a source error produced by a user or transport provider.
455    pub fn provider(source: impl Into<BoxError>) -> Self {
456        Self::with_source(ErrorKind::ProviderFailed, source).with_stage(ErrorStage::Provider)
457    }
458}
459
460impl fmt::Debug for NetError {
461    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
462        formatter
463            .debug_struct("NetError")
464            .field("kind", &self.kind)
465            .field("context", &self.context)
466            .field("config_error", &self.config_error)
467            .field("has_source", &self.source.is_some())
468            .field("retry_report", &self.retry_report)
469            .finish()
470    }
471}
472
473impl fmt::Display for NetError {
474    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
475        write!(formatter, "{:?}", self.kind)?;
476        if let Some(stage) = self.context.stage {
477            write!(formatter, " at {stage:?}")?;
478        }
479        if let Some(status) = self.context.http_status {
480            write!(formatter, " (HTTP {})", status.as_u16())?;
481        }
482        Ok(())
483    }
484}
485
486impl StdError for NetError {
487    fn source(&self) -> Option<&(dyn StdError + 'static)> {
488        self.source
489            .as_deref()
490            .map(|source| source as &(dyn StdError + 'static))
491    }
492}
493
494impl From<ErrorKind> for NetError {
495    fn from(kind: ErrorKind) -> Self {
496        Self::new(kind)
497    }
498}
499
500impl From<std::io::Error> for NetError {
501    fn from(source: std::io::Error) -> Self {
502        Self::with_source(ErrorKind::Io, source)
503    }
504}
505
506#[derive(Clone)]
507/// Details describing one invalid configuration field and the reason it was rejected.
508pub struct ConfigError {
509    field: String,
510    reason: String,
511}
512
513impl ConfigError {
514    fn new(field: impl Into<String>, reason: impl Into<String>) -> Self {
515        Self {
516            field: field.into(),
517            reason: reason.into(),
518        }
519    }
520
521    /// Returns the name of the rejected configuration field.
522    pub fn field(&self) -> &str {
523        &self.field
524    }
525
526    /// Returns a stable, human-readable explanation of the validation failure.
527    pub fn reason(&self) -> &str {
528        &self.reason
529    }
530}
531
532impl fmt::Debug for ConfigError {
533    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
534        formatter
535            .debug_struct("ConfigError")
536            .field("field_bytes", &self.field.len())
537            .field("reason_bytes", &self.reason.len())
538            .finish()
539    }
540}
541
542impl fmt::Display for ConfigError {
543    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
544        formatter.write_str("invalid configuration")
545    }
546}
547
548impl StdError for ConfigError {}
549
550impl From<ConfigError> for NetError {
551    fn from(value: ConfigError) -> Self {
552        let detail = Arc::new(value);
553        Self {
554            config_error: Some(Arc::clone(&detail)),
555            source: Some(detail),
556            ..Self::new(ErrorKind::InvalidConfig).with_stage(ErrorStage::Configuration)
557        }
558    }
559}
560
561impl From<crate::api::retry::RetryConfigError> for NetError {
562    fn from(source: crate::api::retry::RetryConfigError) -> Self {
563        let detail = ConfigError::new(source.field(), source.reason());
564        Self {
565            config_error: Some(Arc::new(detail)),
566            ..Self::with_source(ErrorKind::InvalidConfig, source)
567                .with_stage(ErrorStage::Configuration)
568        }
569    }
570}
571
572/// A failed admission that still owns the value that was not queued.
573pub struct EnqueueError<T> {
574    value: T,
575    error: NetError,
576}
577
578impl<T> EnqueueError<T> {
579    pub(crate) fn new(value: T, error: NetError) -> Self {
580        Self { value, error }
581    }
582
583    /// Returns the admission error without consuming this value.
584    pub fn error(&self) -> &NetError {
585        &self.error
586    }
587
588    /// Borrows the value that was rejected by admission.
589    pub fn value(&self) -> &T {
590        &self.value
591    }
592
593    /// Consumes the error and returns both the rejected value and its cause.
594    pub fn into_parts(self) -> (T, NetError) {
595        (self.value, self.error)
596    }
597
598    /// Consumes the error and returns only the rejected value.
599    pub fn into_inner(self) -> T {
600        self.value
601    }
602
603    /// Consumes the error and returns only its admission cause.
604    pub fn into_error(self) -> NetError {
605        self.error
606    }
607}
608
609impl<T> fmt::Debug for EnqueueError<T> {
610    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
611        formatter
612            .debug_struct("EnqueueError")
613            .field("error", &self.error)
614            .finish_non_exhaustive()
615    }
616}
617
618impl<T> fmt::Display for EnqueueError<T> {
619    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
620        write!(formatter, "enqueue failed: {}", self.error)
621    }
622}
623
624impl<T: Send + Sync + 'static> StdError for EnqueueError<T> {
625    fn source(&self) -> Option<&(dyn StdError + 'static)> {
626        Some(&self.error)
627    }
628}
629
630impl<T> From<EnqueueError<T>> for NetError {
631    fn from(value: EnqueueError<T>) -> Self {
632        value.into_error()
633    }
634}
635
636#[non_exhaustive]
637#[derive(Clone, Debug)]
638/// Error returned while waiting for the next subscribed observation.
639pub enum ReceiveError {
640    /// Receiver fell behind and skipped this many observations.
641    Lagged {
642        /// Number of observations skipped before the next available item.
643        skipped: u64,
644    },
645    /// Underlying subscription or engine failure.
646    Failed(NetError),
647}
648
649impl fmt::Display for ReceiveError {
650    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
651        match self {
652            Self::Lagged { skipped } => {
653                write!(formatter, "receiver lagged; skipped {skipped} observations")
654            }
655            Self::Failed(error) => write!(formatter, "receive failed: {error}"),
656        }
657    }
658}
659
660impl StdError for ReceiveError {
661    fn source(&self) -> Option<&(dyn StdError + 'static)> {
662        match self {
663            Self::Lagged { .. } => None,
664            Self::Failed(error) => Some(error),
665        }
666    }
667}
668
669impl From<ReceiveError> for NetError {
670    fn from(value: ReceiveError) -> Self {
671        match value {
672            value @ ReceiveError::Lagged { .. } => {
673                Self::with_source(ErrorKind::ObservationLagged, value)
674                    .with_stage(ErrorStage::Receive)
675            }
676            ReceiveError::Failed(error) => error,
677        }
678    }
679}
680
681#[non_exhaustive]
682#[derive(Clone, Debug)]
683/// Non-blocking receive result describing empty, closed, lagged, or failed subscriptions.
684pub enum TryReceiveError {
685    /// No item is currently available.
686    Empty,
687    /// The sender side or receiving endpoint has been closed.
688    Closed,
689    /// Receiver fell behind and skipped this many observations.
690    Lagged {
691        /// Number of observations skipped before the next available item.
692        skipped: u64,
693    },
694    /// Underlying subscription or engine failure.
695    Failed(NetError),
696}
697
698impl fmt::Display for TryReceiveError {
699    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
700        match self {
701            Self::Empty => formatter.write_str("receiver is empty"),
702            Self::Closed => formatter.write_str("receiver is closed"),
703            Self::Lagged { skipped } => {
704                write!(formatter, "receiver lagged; skipped {skipped} observations")
705            }
706            Self::Failed(error) => write!(formatter, "receive failed: {error}"),
707        }
708    }
709}
710
711impl StdError for TryReceiveError {
712    fn source(&self) -> Option<&(dyn StdError + 'static)> {
713        match self {
714            Self::Failed(error) => Some(error),
715            Self::Empty | Self::Closed | Self::Lagged { .. } => None,
716        }
717    }
718}
719
720impl fmt::Display for crate::common::CommonError {
721    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
722        formatter.write_str(match self {
723            Self::None => "unknown engine failure",
724            Self::RuntimeError => "engine runtime unavailable",
725            Self::PostError => "engine queue closed",
726        })
727    }
728}
729
730impl StdError for crate::common::CommonError {}
731
732impl From<crate::common::CommonError> for NetError {
733    fn from(value: crate::common::CommonError) -> Self {
734        let kind = match value {
735            crate::common::CommonError::None => ErrorKind::Internal,
736            crate::common::CommonError::RuntimeError => ErrorKind::RuntimeUnavailable,
737            crate::common::CommonError::PostError => ErrorKind::QueueClosed,
738        };
739        Self::with_source(kind, value).with_stage(ErrorStage::Runtime)
740    }
741}
742
743#[cfg(feature = "ws-client")]
744impl From<tokio_tungstenite::tungstenite::Error> for NetError {
745    fn from(value: tokio_tungstenite::tungstenite::Error) -> Self {
746        use tokio_tungstenite::tungstenite::error::{CapacityError, UrlError};
747        use tokio_tungstenite::tungstenite::Error;
748
749        let mut context = ErrorContext::default();
750        let kind = match &value {
751            Error::ConnectionClosed | Error::AlreadyClosed => ErrorKind::Closed,
752            Error::Io(error) => {
753                context.stage = crate::module::transport::tls_error_stage(error);
754                if context.stage.is_some() {
755                    ErrorKind::Tls
756                } else {
757                    ErrorKind::Io
758                }
759            }
760            Error::Tls(_) => {
761                context.stage = Some(ErrorStage::Tls);
762                ErrorKind::Tls
763            }
764            Error::Capacity(CapacityError::MessageTooLong { .. }) => ErrorKind::ItemTooLarge,
765            Error::Capacity(CapacityError::TooManyHeaders) => ErrorKind::ResourceExhausted,
766            Error::Protocol(_) | Error::Utf8(_) | Error::AttackAttempt => ErrorKind::Protocol,
767            // Both local builders and peer response parsing use this variant.
768            // Only the boundary handling it can identify the actual stage.
769            Error::HttpFormat(_) => ErrorKind::Protocol,
770            Error::Url(UrlError::UnableToConnect(_)) => {
771                context.stage = Some(ErrorStage::Tcp);
772                ErrorKind::Io
773            }
774            Error::Url(UrlError::TlsFeatureNotEnabled) => {
775                context.stage = Some(ErrorStage::Configuration);
776                ErrorKind::InvalidConfig
777            }
778            Error::Url(
779                UrlError::NoHostName
780                | UrlError::UnsupportedUrlScheme
781                | UrlError::EmptyHostName
782                | UrlError::NoPathOrQuery,
783            ) => {
784                context.stage = Some(ErrorStage::RequestBuild);
785                ErrorKind::InvalidInput
786            }
787            Error::Http(response) => {
788                context.stage = Some(ErrorStage::Upgrade);
789                context.http_status = Some(response.status());
790                ErrorKind::HandshakeRejected
791            }
792            Error::WriteBufferFull(_) => {
793                // This variant owns the unsent business message, not just an
794                // error cause. Retaining it as source would keep that payload
795                // alive through completed handles and error clones. Release
796                // it here and expose only classification and origin instead.
797                return Self::new(ErrorKind::DeliveryUnknown).with_stage(ErrorStage::Write);
798            }
799        };
800        Self::with_source(kind, value).with_context(context)
801    }
802}
803
804#[cfg(test)]
805mod tests {
806    use super::*;
807    use std::sync::atomic::{AtomicUsize, Ordering};
808
809    type TestResult<T = ()> = std::result::Result<T, BoxError>;
810
811    fn check(condition: bool, message: &str) -> TestResult {
812        if condition {
813            Ok(())
814        } else {
815            Err(std::io::Error::other(message).into())
816        }
817    }
818
819    struct InputWithoutDebug {
820        payload: String,
821        drops: Arc<AtomicUsize>,
822    }
823
824    impl Drop for InputWithoutDebug {
825        fn drop(&mut self) {
826            self.drops.fetch_add(1, Ordering::SeqCst);
827        }
828    }
829
830    fn rejected(drops: &Arc<AtomicUsize>) -> EnqueueError<InputWithoutDebug> {
831        EnqueueError::new(
832            InputWithoutDebug {
833                payload: "unaccepted-payload-secret".into(),
834                drops: Arc::clone(drops),
835            },
836            NetError::new(ErrorKind::QueueFull),
837        )
838    }
839
840    #[test]
841    fn enqueue_recovery_preserves_ownership_without_requiring_debug() -> TestResult {
842        let drops = Arc::new(AtomicUsize::new(0));
843        let failure = rejected(&drops);
844        check(
845            failure.error().kind() == ErrorKind::QueueFull,
846            "enqueue classification",
847        )?;
848        check(
849            failure.value().payload == "unaccepted-payload-secret",
850            "borrow original input",
851        )?;
852        check(
853            !format!("{failure} {failure:?}").contains("payload-secret"),
854            "input must not enter default formatting",
855        )?;
856        check(
857            failure.source().is_some(),
858            "enqueue source must be its admission error",
859        )?;
860        let (input, error) = failure.into_parts();
861        check(
862            input.payload == "unaccepted-payload-secret" && error.kind() == ErrorKind::QueueFull,
863            "recover input with cause",
864        )?;
865        check(
866            drops.load(Ordering::SeqCst) == 0,
867            "recovery must not drop the input",
868        )?;
869        drop(input);
870        check(
871            drops.load(Ordering::SeqCst) == 1,
872            "recovered input must drop once",
873        )?;
874        let input = rejected(&drops).into_inner();
875        check(
876            input.payload == "unaccepted-payload-secret",
877            "recover input alone",
878        )?;
879        drop(input);
880        let error = rejected(&drops).into_error();
881        check(
882            error.kind() == ErrorKind::QueueFull && drops.load(Ordering::SeqCst) == 3,
883            "error-only conversion must drop unaccepted input",
884        )?;
885        Ok(())
886    }
887
888    #[test]
889    fn enqueue_question_mark_discards_input_and_preserves_the_error() -> TestResult {
890        fn propagate(drops: &Arc<AtomicUsize>) -> Result<()> {
891            Err(rejected(drops))?;
892            Ok(())
893        }
894        let drops = Arc::new(AtomicUsize::new(0));
895        let error = propagate(&drops)
896            .err()
897            .ok_or_else(|| std::io::Error::other("admission error missing"))?;
898        check(
899            error.kind() == ErrorKind::QueueFull,
900            "question-mark classification",
901        )?;
902        check(
903            drops.load(Ordering::SeqCst) == 1,
904            "question mark deliberately discards unaccepted input",
905        )
906    }
907
908    #[test]
909    fn configuration_details_are_explicitly_readable_but_never_default_formatted() -> TestResult {
910        let error = NetError::config("private-field-secret", "private-value-secret");
911        let detail = error
912            .config_error()
913            .ok_or_else(|| std::io::Error::other("config detail missing"))?;
914        check(
915            detail.field() == "private-field-secret" && detail.reason() == "private-value-secret",
916            "explicit config getters",
917        )?;
918        check(
919            error.kind() == ErrorKind::InvalidConfig
920                && error.context().stage == Some(ErrorStage::Configuration),
921            "configuration origin",
922        )?;
923        check(
924            error
925                .source()
926                .and_then(|source| source.downcast_ref::<ConfigError>())
927                .is_some(),
928            "config source must remain structured",
929        )?;
930        check(
931            !format!("{error} {error:?} {detail} {detail:?}").contains("secret"),
932            "configuration strings must be redacted",
933        )?;
934        fn propagate() -> Result<()> {
935            Err(ConfigError::new("queue.capacity", "must be nonzero"))?;
936            Ok(())
937        }
938        let propagated = propagate()
939            .err()
940            .ok_or_else(|| std::io::Error::other("config error did not propagate"))?;
941        check(
942            propagated.config_error().map(ConfigError::field) == Some("queue.capacity"),
943            "question-mark config details",
944        )
945    }
946
947    #[test]
948    fn common_errors_retain_the_original_engine_source() -> TestResult {
949        for (source, kind) in [
950            (crate::common::CommonError::None, ErrorKind::Internal),
951            (
952                crate::common::CommonError::RuntimeError,
953                ErrorKind::RuntimeUnavailable,
954            ),
955            (
956                crate::common::CommonError::PostError,
957                ErrorKind::QueueClosed,
958            ),
959        ] {
960            let error = NetError::from(source);
961            check(
962                error.kind() == kind && error.context().stage == Some(ErrorStage::Runtime),
963                "common error category and stage",
964            )?;
965            check(
966                error
967                    .source()
968                    .and_then(|source| source.downcast_ref::<crate::common::CommonError>())
969                    .copied()
970                    == Some(source),
971                "original common source",
972            )?;
973        }
974        Ok(())
975    }
976
977    #[test]
978    fn retry_report_preserves_error_identity_context_and_source() -> TestResult {
979        use crate::api::retry::{RetryReport, RetryStopReason};
980
981        let report = RetryReport {
982            attempts: 3,
983            retry_count: 2,
984            transport_sends: 4,
985            elapsed: std::time::Duration::from_millis(30),
986            stop_reason: Some(RetryStopReason::AttemptsExhausted),
987        };
988        let error = NetError::with_source(
989            ErrorKind::Io,
990            std::io::Error::new(std::io::ErrorKind::ConnectionReset, "private-source"),
991        )
992        .with_context(ErrorContext {
993            stage: Some(ErrorStage::Receive),
994            http_status: Some(http::StatusCode::OK),
995            ..Default::default()
996        })
997        .with_retry_report(report);
998        let cloned = error.clone();
999        check(
1000            cloned.kind() == ErrorKind::Io
1001                && cloned.context().stage == Some(ErrorStage::Receive)
1002                && cloned.context().http_status == Some(http::StatusCode::OK)
1003                && cloned.io_kind() == Some(std::io::ErrorKind::ConnectionReset),
1004            "attaching a report must preserve the failure and received status",
1005        )?;
1006        let attached = cloned
1007            .retry_report()
1008            .ok_or_else(|| std::io::Error::other("retry report missing after clone"))?;
1009        check(
1010            attached.attempts == 3
1011                && attached.retry_count == 2
1012                && attached.transport_sends == 4
1013                && attached.stop_reason == Some(RetryStopReason::AttemptsExhausted),
1014            "cloning an error must retain retry statistics",
1015        )?;
1016        check(
1017            !format!("{error:?} {error}").contains("private-source"),
1018            "retry reports must not expose source text in default formatting",
1019        )
1020    }
1021
1022    #[test]
1023    fn retry_configuration_errors_support_question_mark_without_losing_details() -> TestResult {
1024        fn configure() -> Result<()> {
1025            crate::api::retry::RetrySchedule::builder()
1026                .max_attempts(0)
1027                .build()?;
1028            Ok(())
1029        }
1030        let error = match configure() {
1031            Err(error) => error,
1032            Ok(()) => return Err(std::io::Error::other("invalid configuration accepted").into()),
1033        };
1034        check(
1035            error.kind() == ErrorKind::InvalidConfig
1036                && error.context().stage == Some(ErrorStage::Configuration)
1037                && error.config_error().map(ConfigError::field) == Some("max_attempts"),
1038            "retry config conversion must retain field and origin",
1039        )?;
1040        check(
1041            error
1042                .source()
1043                .and_then(|source| source.downcast_ref::<crate::api::retry::RetryConfigError>())
1044                .is_some(),
1045            "retry config conversion must retain the original structured source",
1046        )
1047    }
1048
1049    #[cfg(feature = "ws-client")]
1050    #[test]
1051    fn websocket_timeout_phase_survives_delivery_wrapping_clone_and_retry_report() -> TestResult {
1052        use crate::ws::WsTimeoutPhase;
1053        for phase in [
1054            WsTimeoutPhase::Admission,
1055            WsTimeoutPhase::Write,
1056            WsTimeoutPhase::Response,
1057            WsTimeoutPhase::Attempt,
1058            WsTimeoutPhase::Total,
1059        ] {
1060            let source = NetError::from(ErrorKind::TimedOut)
1061                .with_stage(ErrorStage::Write)
1062                .with_ws_timeout_phase(phase);
1063            let context = source.context().clone();
1064            let error = NetError::with_source(ErrorKind::DeliveryUnknown, source)
1065                .with_context(context)
1066                .with_retry_report(crate::api::retry::RetryReport::new())
1067                .clone();
1068            check(
1069                error.ws_timeout_phase() == Some(phase),
1070                "delivery wrapper lost the WebSocket budget phase",
1071            )?;
1072            check(
1073                error
1074                    .source()
1075                    .and_then(|source| source.downcast_ref::<NetError>())
1076                    .is_some_and(|source| {
1077                        source.kind() == ErrorKind::TimedOut
1078                            && source.ws_timeout_phase() == Some(phase)
1079                    }),
1080                "original timeout cause lost its phase",
1081            )?;
1082            check(
1083                error.retry_report().is_some(),
1084                "timeout report lost during clone",
1085            )?;
1086        }
1087        Ok(())
1088    }
1089
1090    #[test]
1091    fn cyclic_application_sources_cannot_make_io_kind_loop_forever() -> TestResult {
1092        #[derive(Debug)]
1093        struct Cyclic;
1094        impl fmt::Display for Cyclic {
1095            fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
1096                formatter.write_str("cyclic")
1097            }
1098        }
1099        impl StdError for Cyclic {
1100            fn source(&self) -> Option<&(dyn StdError + 'static)> {
1101                Some(self)
1102            }
1103        }
1104        check(
1105            NetError::provider(Cyclic).io_kind().is_none(),
1106            "cyclic source has no I/O category",
1107        )
1108    }
1109
1110    #[cfg(feature = "ws-client")]
1111    #[test]
1112    fn websocket_context_retains_details_but_redacts_peer_reason() -> TestResult {
1113        use crate::ws::{HandshakeDiagnostic, HandshakeDiagnosticKind, IoEndKind, PeerClose};
1114        use tokio_tungstenite::tungstenite::protocol::{frame::coding::CloseCode, CloseFrame};
1115
1116        let frame = CloseFrame {
1117            code: CloseCode::Normal,
1118            reason: "peer-credential-secret".into(),
1119        };
1120        let context = ErrorContext {
1121            stage: Some(ErrorStage::Receive),
1122            http_status: Some(http::StatusCode::UNAUTHORIZED),
1123            diagnostic: Some(HandshakeDiagnostic::new(
1124                HandshakeDiagnosticKind::HttpRejected,
1125            )),
1126            peer_close: Some(PeerClose::from_frame(Some(&frame))?),
1127            io_end: Some(IoEndKind::PeerClose),
1128            ..Default::default()
1129        };
1130        let error = NetError::with_source(
1131            ErrorKind::Protocol,
1132            std::io::Error::other("source-credential-secret"),
1133        )
1134        .with_context(context)
1135        .with_stage(ErrorStage::Close);
1136        let cloned = error.clone();
1137        check(
1138            cloned.context().stage == Some(ErrorStage::Close)
1139                && cloned.context().http_status == Some(http::StatusCode::UNAUTHORIZED)
1140                && cloned.context().io_end == Some(IoEndKind::PeerClose),
1141            "stage changes must preserve other contextual facts",
1142        )?;
1143        check(
1144            cloned
1145                .context()
1146                .peer_close
1147                .as_ref()
1148                .map(|value| value.reason.as_str())
1149                == Some("peer-credential-secret"),
1150            "explicit peer close access must preserve the received reason",
1151        )?;
1152        check(
1153            cloned
1154                .context()
1155                .diagnostic
1156                .as_ref()
1157                .map(|value| value.kind())
1158                == Some(HandshakeDiagnosticKind::HttpRejected),
1159            "diagnostic must survive error cloning",
1160        )?;
1161        check(
1162            !format!("{error} {error:?} {:?}", error.context()).contains("credential-secret"),
1163            "context formatting must omit peer and source strings",
1164        )
1165    }
1166}
1167
1168#[cfg(all(test, feature = "ws-client"))]
1169#[path = "identity_context_tests.rs"]
1170mod identity_context_tests;