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 or validating certificates.
121    Tls,
122    /// Performing the HTTP-to-WebSocket upgrade.
123    Upgrade,
124    /// Admitting work into a bounded subsystem.
125    Admission,
126    /// Waiting on or operating a work queue.
127    Queue,
128    /// Writing bytes or frames to the transport.
129    Write,
130    /// Classifying or completing a response.
131    Response,
132    /// Receiving data or delivering an observation.
133    Receive,
134    /// Sending or awaiting heartbeat control frames.
135    Heartbeat,
136    /// Performing connection or session shutdown.
137    Close,
138    /// Dispatching callbacks or events.
139    Dispatch,
140    /// Updating network availability state.
141    NetworkMonitor,
142    /// Interacting with the asynchronous runtime.
143    Runtime,
144}
145
146/// Optional identifiers and protocol details retained alongside a [`NetError`].
147#[non_exhaustive]
148#[derive(Clone, Default)]
149pub struct ErrorContext {
150    /// Processing stage at which the error was classified.
151    pub stage: Option<ErrorStage>,
152    #[cfg(feature = "ws-client")]
153    /// WebSocket client identifier associated with the failure, when available.
154    pub client_id: Option<crate::ws::ClientId>,
155    #[cfg(feature = "ws-client")]
156    /// Logical WebSocket session identifier associated with the failure, when available.
157    pub session_id: Option<crate::ws::SessionId>,
158    #[cfg(feature = "ws-client")]
159    /// Physical connection identifier associated with the failure, when available.
160    pub connection_id: Option<crate::ws::ConnectionId>,
161    #[cfg(feature = "ws-client")]
162    /// Handshake attempt identifier associated with the failure, when available.
163    pub attempt_id: Option<crate::ws::AttemptId>,
164    #[cfg(feature = "ws-client")]
165    /// Request identifier associated with the failure, when available.
166    pub request_id: Option<crate::ws::RequestId>,
167    /// HTTP status received from the peer, including protocol or body-read failures.
168    pub http_status: Option<http::StatusCode>,
169    #[cfg(feature = "http-client")]
170    /// HTTP request identifier associated with the failure, when available.
171    pub http_request_id: Option<crate::api::http::HttpRequestId>,
172    #[cfg(feature = "http-client")]
173    /// Expired HTTP budget, when the SDK classified a timeout.
174    pub http_timeout_phase: Option<crate::api::http::TimeoutPhase>,
175    #[cfg(feature = "http-client")]
176    /// HTTP attempt number starting at one; zero means no attempt has started.
177    pub http_attempt: Option<u32>,
178    #[cfg(feature = "ws-client")]
179    /// Handshake diagnostic captured for the failure, when available.
180    pub diagnostic: Option<crate::ws::HandshakeDiagnostic>,
181    #[cfg(feature = "ws-client")]
182    /// Peer close details associated with the failure, when available.
183    pub peer_close: Option<crate::ws::PeerClose>,
184    #[cfg(feature = "ws-client")]
185    /// I/O termination classification associated with the failure, when available.
186    pub io_end: Option<crate::ws::IoEndKind>,
187}
188
189impl fmt::Debug for ErrorContext {
190    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
191        let mut output = formatter.debug_struct("ErrorContext");
192        output
193            .field("stage", &self.stage)
194            .field("http_status", &self.http_status);
195        #[cfg(feature = "http-client")]
196        output
197            .field("http_request_id", &self.http_request_id)
198            .field("http_timeout_phase", &self.http_timeout_phase)
199            .field("http_attempt", &self.http_attempt);
200        #[cfg(feature = "ws-client")]
201        output
202            .field("client_id", &self.client_id)
203            .field("session_id", &self.session_id)
204            .field("connection_id", &self.connection_id)
205            .field("attempt_id", &self.attempt_id)
206            .field(
207                "request_id_len",
208                &self.request_id.as_ref().map(|id| id.as_str().len()),
209            )
210            .field(
211                "diagnostic_kind",
212                &self.diagnostic.as_ref().map(|value| value.kind()),
213            )
214            .field(
215                "peer_close_code",
216                &self.peer_close.as_ref().map(|value| value.code),
217            )
218            .field("io_end", &self.io_end);
219        output.finish()
220    }
221}
222
223/// An error classification, safe context, and an optional shared original cause.
224/// Formatting never includes arbitrary source text. Inspect `source()` explicitly
225/// when the original third-party or application details are required.
226#[derive(Clone)]
227pub struct NetError {
228    kind: ErrorKind,
229    context: ErrorContext,
230    config_error: Option<Arc<ConfigError>>,
231    source: Option<Arc<dyn StdError + Send + Sync + 'static>>,
232    #[cfg(feature = "http-client")]
233    http_response_head: Option<Arc<crate::api::http::HttpResponseHead>>,
234}
235
236impl NetError {
237    /// Creates an error classified from an HTTP status returned by a protocol or upgrade operation.
238    pub fn from_http_status(status: http::StatusCode) -> Self {
239        let mut context = ErrorContext::default();
240        context.http_status = Some(status);
241        Self::new(ErrorKind::HttpStatus).with_context(context)
242    }
243    pub(crate) fn new(kind: ErrorKind) -> Self {
244        Self {
245            kind,
246            context: ErrorContext::default(),
247            config_error: None,
248            source: None,
249            #[cfg(feature = "http-client")]
250            http_response_head: None,
251        }
252    }
253
254    pub(crate) fn with_source(kind: ErrorKind, source: impl Into<BoxError>) -> Self {
255        let source: BoxError = source.into();
256        Self {
257            source: Some(Arc::from(source)),
258            ..Self::new(kind)
259        }
260    }
261
262    pub(crate) fn with_context(mut self, context: ErrorContext) -> Self {
263        self.context = context;
264        self
265    }
266
267    pub(crate) fn with_stage(mut self, stage: ErrorStage) -> Self {
268        self.context.stage = Some(stage);
269        self
270    }
271
272    #[cfg(feature = "http-client")]
273    pub(crate) fn with_http_request_id(
274        mut self,
275        request_id: crate::api::http::HttpRequestId,
276    ) -> Self {
277        self.context.http_request_id = Some(request_id);
278        self
279    }
280
281    pub(crate) fn config(field: impl Into<String>, reason: impl Into<String>) -> Self {
282        ConfigError::new(field, reason).into()
283    }
284
285    #[cfg(feature = "http-client")]
286    pub(crate) fn with_http_attempt(mut self, attempt: u32) -> Self {
287        self.context.http_attempt = Some(attempt);
288        self
289    }
290
291    #[cfg(feature = "http-client")]
292    pub(crate) fn with_timeout_phase(mut self, phase: crate::api::http::TimeoutPhase) -> Self {
293        self.context.http_timeout_phase = Some(phase);
294        self
295    }
296
297    pub(crate) fn input(field: impl Into<String>, reason: impl Into<String>) -> Self {
298        Self {
299            config_error: Some(Arc::new(ConfigError::new(field, reason))),
300            ..Self::new(ErrorKind::InvalidInput).with_stage(ErrorStage::RequestBuild)
301        }
302    }
303
304    pub(crate) fn from_poison<T>(_: std::sync::PoisonError<T>) -> Self {
305        // A poisoned guard may borrow protected data. Do not capture that data
306        // or require it to satisfy the owned error source's lifetime bounds.
307        Self::new(ErrorKind::Internal)
308    }
309
310    /// Returns the broad failure classification.
311    pub fn kind(&self) -> ErrorKind {
312        self.kind
313    }
314
315    /// Returns structured context captured while processing the failure.
316    pub fn context(&self) -> &ErrorContext {
317        &self.context
318    }
319
320    /// Returns the expired HTTP budget, or `None` for other failures.
321    #[cfg(feature = "http-client")]
322    pub fn timeout_phase(&self) -> Option<crate::api::http::TimeoutPhase> {
323        self.context.http_timeout_phase
324    }
325
326    /// Returns the HTTP status associated with the failure, if one was recorded.
327    pub fn http_status(&self) -> Option<http::StatusCode> {
328        self.context.http_status
329    }
330
331    /// Returns the received status and headers when a buffered HTTP response
332    /// body failed to complete. The error kind, source and timeout phase remain
333    /// authoritative; metadata must not be interpreted as a successful response.
334    ///
335    /// Failures before a response is received and explicit cancellation do not
336    /// carry a response head. Retried attempts never reuse an earlier head.
337    #[cfg(feature = "http-client")]
338    pub fn http_response_head(&self) -> Option<&crate::api::http::HttpResponseHead> {
339        self.http_response_head.as_deref()
340    }
341
342    #[cfg(feature = "http-client")]
343    pub(crate) fn with_http_response_head(
344        mut self,
345        head: crate::api::http::HttpResponseHead,
346    ) -> Self {
347        self.context.http_status = Some(head.status);
348        self.http_response_head = Some(Arc::new(head));
349        self
350    }
351
352    /// Returns structured configuration details, if the failure came from invalid input.
353    pub fn config_error(&self) -> Option<&ConfigError> {
354        self.config_error.as_deref()
355    }
356
357    /// The first retained I/O category in the source chain, if available.
358    pub fn io_kind(&self) -> Option<std::io::ErrorKind> {
359        let mut source = self.source();
360        // Application error sources can form cycles. Bound introspection so
361        // such a source cannot cause this convenience query to loop forever.
362        for _ in 0..64 {
363            let error = source?;
364            if let Some(io) = error.downcast_ref::<std::io::Error>() {
365                return Some(io.kind());
366            }
367            source = error.source();
368        }
369        None
370    }
371
372    /// Wraps a source error as a protocol failure.
373    pub fn protocol(source: impl Into<BoxError>) -> Self {
374        Self::with_source(ErrorKind::Protocol, source)
375    }
376
377    /// Wraps a source error produced by a user or transport provider.
378    pub fn provider(source: impl Into<BoxError>) -> Self {
379        Self::with_source(ErrorKind::ProviderFailed, source).with_stage(ErrorStage::Provider)
380    }
381}
382
383impl fmt::Debug for NetError {
384    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
385        formatter
386            .debug_struct("NetError")
387            .field("kind", &self.kind)
388            .field("context", &self.context)
389            .field("config_error", &self.config_error)
390            .field("has_source", &self.source.is_some())
391            .finish()
392    }
393}
394
395impl fmt::Display for NetError {
396    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
397        write!(formatter, "{:?}", self.kind)?;
398        if let Some(stage) = self.context.stage {
399            write!(formatter, " at {stage:?}")?;
400        }
401        if let Some(status) = self.context.http_status {
402            write!(formatter, " (HTTP {})", status.as_u16())?;
403        }
404        Ok(())
405    }
406}
407
408impl StdError for NetError {
409    fn source(&self) -> Option<&(dyn StdError + 'static)> {
410        self.source
411            .as_deref()
412            .map(|source| source as &(dyn StdError + 'static))
413    }
414}
415
416impl From<ErrorKind> for NetError {
417    fn from(kind: ErrorKind) -> Self {
418        Self::new(kind)
419    }
420}
421
422impl From<std::io::Error> for NetError {
423    fn from(source: std::io::Error) -> Self {
424        Self::with_source(ErrorKind::Io, source)
425    }
426}
427
428#[derive(Clone)]
429/// Details describing one invalid configuration field and the reason it was rejected.
430pub struct ConfigError {
431    field: String,
432    reason: String,
433}
434
435impl ConfigError {
436    fn new(field: impl Into<String>, reason: impl Into<String>) -> Self {
437        Self {
438            field: field.into(),
439            reason: reason.into(),
440        }
441    }
442
443    /// Returns the name of the rejected configuration field.
444    pub fn field(&self) -> &str {
445        &self.field
446    }
447
448    /// Returns a stable, human-readable explanation of the validation failure.
449    pub fn reason(&self) -> &str {
450        &self.reason
451    }
452}
453
454impl fmt::Debug for ConfigError {
455    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
456        formatter
457            .debug_struct("ConfigError")
458            .field("field_bytes", &self.field.len())
459            .field("reason_bytes", &self.reason.len())
460            .finish()
461    }
462}
463
464impl fmt::Display for ConfigError {
465    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
466        formatter.write_str("invalid configuration")
467    }
468}
469
470impl StdError for ConfigError {}
471
472impl From<ConfigError> for NetError {
473    fn from(value: ConfigError) -> Self {
474        let detail = Arc::new(value);
475        Self {
476            config_error: Some(Arc::clone(&detail)),
477            source: Some(detail),
478            ..Self::new(ErrorKind::InvalidConfig).with_stage(ErrorStage::Configuration)
479        }
480    }
481}
482
483/// A failed admission that still owns the value that was not queued.
484pub struct EnqueueError<T> {
485    value: T,
486    error: NetError,
487}
488
489impl<T> EnqueueError<T> {
490    pub(crate) fn new(value: T, error: NetError) -> Self {
491        Self { value, error }
492    }
493
494    /// Returns the admission error without consuming this value.
495    pub fn error(&self) -> &NetError {
496        &self.error
497    }
498
499    /// Borrows the value that was rejected by admission.
500    pub fn value(&self) -> &T {
501        &self.value
502    }
503
504    /// Consumes the error and returns both the rejected value and its cause.
505    pub fn into_parts(self) -> (T, NetError) {
506        (self.value, self.error)
507    }
508
509    /// Consumes the error and returns only the rejected value.
510    pub fn into_inner(self) -> T {
511        self.value
512    }
513
514    /// Consumes the error and returns only its admission cause.
515    pub fn into_error(self) -> NetError {
516        self.error
517    }
518}
519
520impl<T> fmt::Debug for EnqueueError<T> {
521    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
522        formatter
523            .debug_struct("EnqueueError")
524            .field("error", &self.error)
525            .finish_non_exhaustive()
526    }
527}
528
529impl<T> fmt::Display for EnqueueError<T> {
530    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
531        write!(formatter, "enqueue failed: {}", self.error)
532    }
533}
534
535impl<T: Send + Sync + 'static> StdError for EnqueueError<T> {
536    fn source(&self) -> Option<&(dyn StdError + 'static)> {
537        Some(&self.error)
538    }
539}
540
541impl<T> From<EnqueueError<T>> for NetError {
542    fn from(value: EnqueueError<T>) -> Self {
543        value.into_error()
544    }
545}
546
547#[non_exhaustive]
548#[derive(Clone, Debug)]
549/// Error returned while waiting for the next subscribed observation.
550pub enum ReceiveError {
551    /// Receiver fell behind and skipped this many observations.
552    Lagged {
553        /// Number of observations skipped before the next available item.
554        skipped: u64,
555    },
556    /// Underlying subscription or engine failure.
557    Failed(NetError),
558}
559
560impl fmt::Display for ReceiveError {
561    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
562        match self {
563            Self::Lagged { skipped } => {
564                write!(formatter, "receiver lagged; skipped {skipped} observations")
565            }
566            Self::Failed(error) => write!(formatter, "receive failed: {error}"),
567        }
568    }
569}
570
571impl StdError for ReceiveError {
572    fn source(&self) -> Option<&(dyn StdError + 'static)> {
573        match self {
574            Self::Lagged { .. } => None,
575            Self::Failed(error) => Some(error),
576        }
577    }
578}
579
580impl From<ReceiveError> for NetError {
581    fn from(value: ReceiveError) -> Self {
582        match value {
583            value @ ReceiveError::Lagged { .. } => {
584                Self::with_source(ErrorKind::ObservationLagged, value)
585                    .with_stage(ErrorStage::Receive)
586            }
587            ReceiveError::Failed(error) => error,
588        }
589    }
590}
591
592#[non_exhaustive]
593#[derive(Clone, Debug)]
594/// Non-blocking receive result describing empty, closed, lagged, or failed subscriptions.
595pub enum TryReceiveError {
596    /// No item is currently available.
597    Empty,
598    /// The sender side or receiving endpoint has been closed.
599    Closed,
600    /// Receiver fell behind and skipped this many observations.
601    Lagged {
602        /// Number of observations skipped before the next available item.
603        skipped: u64,
604    },
605    /// Underlying subscription or engine failure.
606    Failed(NetError),
607}
608
609impl fmt::Display for TryReceiveError {
610    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
611        match self {
612            Self::Empty => formatter.write_str("receiver is empty"),
613            Self::Closed => formatter.write_str("receiver is closed"),
614            Self::Lagged { skipped } => {
615                write!(formatter, "receiver lagged; skipped {skipped} observations")
616            }
617            Self::Failed(error) => write!(formatter, "receive failed: {error}"),
618        }
619    }
620}
621
622impl StdError for TryReceiveError {
623    fn source(&self) -> Option<&(dyn StdError + 'static)> {
624        match self {
625            Self::Failed(error) => Some(error),
626            Self::Empty | Self::Closed | Self::Lagged { .. } => None,
627        }
628    }
629}
630
631impl fmt::Display for crate::common::CommonError {
632    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
633        formatter.write_str(match self {
634            Self::None => "unknown engine failure",
635            Self::RuntimeError => "engine runtime unavailable",
636            Self::PostError => "engine queue closed",
637        })
638    }
639}
640
641impl StdError for crate::common::CommonError {}
642
643impl From<crate::common::CommonError> for NetError {
644    fn from(value: crate::common::CommonError) -> Self {
645        let kind = match value {
646            crate::common::CommonError::None => ErrorKind::Internal,
647            crate::common::CommonError::RuntimeError => ErrorKind::RuntimeUnavailable,
648            crate::common::CommonError::PostError => ErrorKind::QueueClosed,
649        };
650        Self::with_source(kind, value).with_stage(ErrorStage::Runtime)
651    }
652}
653
654#[cfg(feature = "ws-client")]
655impl From<tokio_tungstenite::tungstenite::Error> for NetError {
656    fn from(value: tokio_tungstenite::tungstenite::Error) -> Self {
657        use tokio_tungstenite::tungstenite::error::{CapacityError, UrlError};
658        use tokio_tungstenite::tungstenite::Error;
659
660        let mut context = ErrorContext::default();
661        let kind = match &value {
662            Error::ConnectionClosed | Error::AlreadyClosed => ErrorKind::Closed,
663            Error::Io(_) => ErrorKind::Io,
664            Error::Tls(_) => {
665                context.stage = Some(ErrorStage::Tls);
666                ErrorKind::Tls
667            }
668            Error::Capacity(CapacityError::MessageTooLong { .. }) => ErrorKind::ItemTooLarge,
669            Error::Capacity(CapacityError::TooManyHeaders) => ErrorKind::ResourceExhausted,
670            Error::Protocol(_) | Error::Utf8(_) | Error::AttackAttempt => ErrorKind::Protocol,
671            // Both local builders and peer response parsing use this variant.
672            // Only the boundary handling it can identify the actual stage.
673            Error::HttpFormat(_) => ErrorKind::Protocol,
674            Error::Url(UrlError::UnableToConnect(_)) => {
675                context.stage = Some(ErrorStage::Tcp);
676                ErrorKind::Io
677            }
678            Error::Url(UrlError::TlsFeatureNotEnabled) => {
679                context.stage = Some(ErrorStage::Configuration);
680                ErrorKind::InvalidConfig
681            }
682            Error::Url(
683                UrlError::NoHostName
684                | UrlError::UnsupportedUrlScheme
685                | UrlError::EmptyHostName
686                | UrlError::NoPathOrQuery,
687            ) => {
688                context.stage = Some(ErrorStage::RequestBuild);
689                ErrorKind::InvalidInput
690            }
691            Error::Http(response) => {
692                context.stage = Some(ErrorStage::Upgrade);
693                context.http_status = Some(response.status());
694                ErrorKind::HandshakeRejected
695            }
696            Error::WriteBufferFull(_) => {
697                // This variant owns the unsent business message, not just an
698                // error cause. Retaining it as source would keep that payload
699                // alive through completed handles and error clones. Release
700                // it here and expose only classification and origin instead.
701                return Self::new(ErrorKind::DeliveryUnknown).with_stage(ErrorStage::Write);
702            }
703        };
704        Self::with_source(kind, value).with_context(context)
705    }
706}
707
708#[cfg(test)]
709mod tests {
710    use super::*;
711    use std::sync::atomic::{AtomicUsize, Ordering};
712
713    type TestResult<T = ()> = std::result::Result<T, BoxError>;
714
715    fn check(condition: bool, message: &str) -> TestResult {
716        if condition {
717            Ok(())
718        } else {
719            Err(std::io::Error::other(message).into())
720        }
721    }
722
723    struct InputWithoutDebug {
724        payload: String,
725        drops: Arc<AtomicUsize>,
726    }
727
728    impl Drop for InputWithoutDebug {
729        fn drop(&mut self) {
730            self.drops.fetch_add(1, Ordering::SeqCst);
731        }
732    }
733
734    fn rejected(drops: &Arc<AtomicUsize>) -> EnqueueError<InputWithoutDebug> {
735        EnqueueError::new(
736            InputWithoutDebug {
737                payload: "unaccepted-payload-secret".into(),
738                drops: Arc::clone(drops),
739            },
740            NetError::new(ErrorKind::QueueFull),
741        )
742    }
743
744    #[test]
745    fn enqueue_recovery_preserves_ownership_without_requiring_debug() -> TestResult {
746        let drops = Arc::new(AtomicUsize::new(0));
747        let failure = rejected(&drops);
748        check(
749            failure.error().kind() == ErrorKind::QueueFull,
750            "enqueue classification",
751        )?;
752        check(
753            failure.value().payload == "unaccepted-payload-secret",
754            "borrow original input",
755        )?;
756        check(
757            !format!("{failure} {failure:?}").contains("payload-secret"),
758            "input must not enter default formatting",
759        )?;
760        check(
761            failure.source().is_some(),
762            "enqueue source must be its admission error",
763        )?;
764        let (input, error) = failure.into_parts();
765        check(
766            input.payload == "unaccepted-payload-secret" && error.kind() == ErrorKind::QueueFull,
767            "recover input with cause",
768        )?;
769        check(
770            drops.load(Ordering::SeqCst) == 0,
771            "recovery must not drop the input",
772        )?;
773        drop(input);
774        check(
775            drops.load(Ordering::SeqCst) == 1,
776            "recovered input must drop once",
777        )?;
778        let input = rejected(&drops).into_inner();
779        check(
780            input.payload == "unaccepted-payload-secret",
781            "recover input alone",
782        )?;
783        drop(input);
784        let error = rejected(&drops).into_error();
785        check(
786            error.kind() == ErrorKind::QueueFull && drops.load(Ordering::SeqCst) == 3,
787            "error-only conversion must drop unaccepted input",
788        )?;
789        Ok(())
790    }
791
792    #[test]
793    fn enqueue_question_mark_discards_input_and_preserves_the_error() -> TestResult {
794        fn propagate(drops: &Arc<AtomicUsize>) -> Result<()> {
795            Err(rejected(drops))?;
796            Ok(())
797        }
798        let drops = Arc::new(AtomicUsize::new(0));
799        let error = propagate(&drops)
800            .err()
801            .ok_or_else(|| std::io::Error::other("admission error missing"))?;
802        check(
803            error.kind() == ErrorKind::QueueFull,
804            "question-mark classification",
805        )?;
806        check(
807            drops.load(Ordering::SeqCst) == 1,
808            "question mark deliberately discards unaccepted input",
809        )
810    }
811
812    #[test]
813    fn configuration_details_are_explicitly_readable_but_never_default_formatted() -> TestResult {
814        let error = NetError::config("private-field-secret", "private-value-secret");
815        let detail = error
816            .config_error()
817            .ok_or_else(|| std::io::Error::other("config detail missing"))?;
818        check(
819            detail.field() == "private-field-secret" && detail.reason() == "private-value-secret",
820            "explicit config getters",
821        )?;
822        check(
823            error.kind() == ErrorKind::InvalidConfig
824                && error.context().stage == Some(ErrorStage::Configuration),
825            "configuration origin",
826        )?;
827        check(
828            error
829                .source()
830                .and_then(|source| source.downcast_ref::<ConfigError>())
831                .is_some(),
832            "config source must remain structured",
833        )?;
834        check(
835            !format!("{error} {error:?} {detail} {detail:?}").contains("secret"),
836            "configuration strings must be redacted",
837        )?;
838        fn propagate() -> Result<()> {
839            Err(ConfigError::new("queue.capacity", "must be nonzero"))?;
840            Ok(())
841        }
842        let propagated = propagate()
843            .err()
844            .ok_or_else(|| std::io::Error::other("config error did not propagate"))?;
845        check(
846            propagated.config_error().map(ConfigError::field) == Some("queue.capacity"),
847            "question-mark config details",
848        )
849    }
850
851    #[test]
852    fn common_errors_retain_the_original_engine_source() -> TestResult {
853        for (source, kind) in [
854            (crate::common::CommonError::None, ErrorKind::Internal),
855            (
856                crate::common::CommonError::RuntimeError,
857                ErrorKind::RuntimeUnavailable,
858            ),
859            (
860                crate::common::CommonError::PostError,
861                ErrorKind::QueueClosed,
862            ),
863        ] {
864            let error = NetError::from(source);
865            check(
866                error.kind() == kind && error.context().stage == Some(ErrorStage::Runtime),
867                "common error category and stage",
868            )?;
869            check(
870                error
871                    .source()
872                    .and_then(|source| source.downcast_ref::<crate::common::CommonError>())
873                    .copied()
874                    == Some(source),
875                "original common source",
876            )?;
877        }
878        Ok(())
879    }
880
881    #[test]
882    fn cyclic_application_sources_cannot_make_io_kind_loop_forever() -> TestResult {
883        #[derive(Debug)]
884        struct Cyclic;
885        impl fmt::Display for Cyclic {
886            fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
887                formatter.write_str("cyclic")
888            }
889        }
890        impl StdError for Cyclic {
891            fn source(&self) -> Option<&(dyn StdError + 'static)> {
892                Some(self)
893            }
894        }
895        check(
896            NetError::provider(Cyclic).io_kind().is_none(),
897            "cyclic source has no I/O category",
898        )
899    }
900
901    #[cfg(feature = "ws-client")]
902    #[test]
903    fn websocket_context_retains_details_but_redacts_peer_reason() -> TestResult {
904        use crate::ws::{HandshakeDiagnostic, HandshakeDiagnosticKind, IoEndKind, PeerClose};
905        use tokio_tungstenite::tungstenite::protocol::{frame::coding::CloseCode, CloseFrame};
906
907        let frame = CloseFrame {
908            code: CloseCode::Normal,
909            reason: "peer-credential-secret".into(),
910        };
911        let context = ErrorContext {
912            stage: Some(ErrorStage::Receive),
913            http_status: Some(http::StatusCode::UNAUTHORIZED),
914            diagnostic: Some(HandshakeDiagnostic::new(
915                HandshakeDiagnosticKind::HttpRejected,
916            )),
917            peer_close: Some(PeerClose::from_frame(Some(&frame))?),
918            io_end: Some(IoEndKind::PeerClose),
919            ..Default::default()
920        };
921        let error = NetError::with_source(
922            ErrorKind::Protocol,
923            std::io::Error::other("source-credential-secret"),
924        )
925        .with_context(context)
926        .with_stage(ErrorStage::Close);
927        let cloned = error.clone();
928        check(
929            cloned.context().stage == Some(ErrorStage::Close)
930                && cloned.context().http_status == Some(http::StatusCode::UNAUTHORIZED)
931                && cloned.context().io_end == Some(IoEndKind::PeerClose),
932            "stage changes must preserve other contextual facts",
933        )?;
934        check(
935            cloned
936                .context()
937                .peer_close
938                .as_ref()
939                .map(|value| value.reason.as_str())
940                == Some("peer-credential-secret"),
941            "explicit peer close access must preserve the received reason",
942        )?;
943        check(
944            cloned
945                .context()
946                .diagnostic
947                .as_ref()
948                .map(|value| value.kind())
949                == Some(HandshakeDiagnosticKind::HttpRejected),
950            "diagnostic must survive error cloning",
951        )?;
952        check(
953            !format!("{error} {error:?} {:?}", error.context()).contains("credential-secret"),
954            "context formatting must omit peer and source strings",
955        )
956    }
957}
958
959#[cfg(all(test, feature = "ws-client"))]
960#[path = "identity_context_tests.rs"]
961mod identity_context_tests;