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