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