1use std::error::Error as StdError;
4use std::fmt;
5use std::sync::Arc;
6
7pub type BoxError = Box<dyn StdError + Send + Sync + 'static>;
9pub type Result<T> = std::result::Result<T, NetError>;
11
12#[non_exhaustive]
13#[derive(Clone, Copy, Debug, Eq, PartialEq)]
14pub enum ErrorKind {
19 InvalidInput,
21 InvalidConfig,
23 Io,
25 Dns,
27 Tls,
29 Protocol,
31 HandshakeRejected,
33 ProviderFailed,
35 CallbackPanicked,
37 RuntimeUnavailable,
39 ResourceExhausted,
41 QueueFull,
43 QueueClosed,
45 ItemTooLarge,
47 PendingLimitReached,
49 SubscriptionLimitReached,
51 CallbackOverflow,
53 ControlOverflow,
55 ObservationLagged,
57 NotConnected,
59 SessionAlreadyExists,
61 ConnectionClosing,
63 Closed,
65 EngineDropped,
67 Cancelled,
69 TimedOut,
71 DeadlineExceeded,
73 DeliveryUnknown,
75 RetryExhausted,
77 InvalidPolicy,
79 BodyNotReplayable,
81 DuplicateRequestId,
83 RoutingDisabled,
85 RoutingModeMismatch,
87 ClientAlreadyExists,
89 ClientNotFound,
91 Internal,
93 HttpStatus,
95}
96
97#[non_exhaustive]
98#[derive(Clone, Copy, Debug, Eq, PartialEq)]
99pub enum ErrorStage {
104 Configuration,
106 Provider,
108 RequestBuild,
110 Dns,
112 Tcp,
114 Proxy,
116 Tls,
118 Upgrade,
120 Admission,
122 Queue,
124 Write,
126 Response,
128 Receive,
130 Heartbeat,
132 Close,
134 Dispatch,
136 NetworkMonitor,
138 Runtime,
140}
141
142#[non_exhaustive]
144#[derive(Clone, Default)]
145pub struct ErrorContext {
146 pub stage: Option<ErrorStage>,
148 #[cfg(feature = "ws-client")]
149 pub client_id: Option<crate::ws::ClientId>,
151 #[cfg(feature = "ws-client")]
152 pub session_id: Option<crate::ws::SessionId>,
154 #[cfg(feature = "ws-client")]
155 pub connection_id: Option<crate::ws::ConnectionId>,
157 #[cfg(feature = "ws-client")]
158 pub attempt_id: Option<crate::ws::AttemptId>,
160 #[cfg(feature = "ws-client")]
161 pub request_id: Option<crate::ws::RequestId>,
163 pub http_status: Option<http::StatusCode>,
165 #[cfg(feature = "http-client")]
166 pub http_request_id: Option<crate::api::http::HttpRequestId>,
168 #[cfg(feature = "http-client")]
169 pub http_timeout_phase: Option<crate::api::http::TimeoutPhase>,
171 #[cfg(feature = "http-client")]
172 pub http_attempt: Option<u32>,
174 #[cfg(feature = "ws-client")]
175 pub diagnostic: Option<crate::ws::HandshakeDiagnostic>,
177 #[cfg(feature = "ws-client")]
178 pub peer_close: Option<crate::ws::PeerClose>,
180 #[cfg(feature = "ws-client")]
181 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#[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 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 Self::new(ErrorKind::Internal)
300 }
301
302 pub fn kind(&self) -> ErrorKind {
304 self.kind
305 }
306
307 pub fn context(&self) -> &ErrorContext {
309 &self.context
310 }
311
312 #[cfg(feature = "http-client")]
314 pub fn timeout_phase(&self) -> Option<crate::api::http::TimeoutPhase> {
315 self.context.http_timeout_phase
316 }
317
318 pub fn http_status(&self) -> Option<http::StatusCode> {
320 self.context.http_status
321 }
322
323 pub fn config_error(&self) -> Option<&ConfigError> {
325 self.config_error.as_deref()
326 }
327
328 pub fn io_kind(&self) -> Option<std::io::ErrorKind> {
330 let mut source = self.source();
331 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 pub fn protocol(source: impl Into<BoxError>) -> Self {
345 Self::with_source(ErrorKind::Protocol, source)
346 }
347
348 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)]
400pub 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 pub fn field(&self) -> &str {
416 &self.field
417 }
418
419 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
454pub 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 pub fn error(&self) -> &NetError {
467 &self.error
468 }
469
470 pub fn value(&self) -> &T {
472 &self.value
473 }
474
475 pub fn into_parts(self) -> (T, NetError) {
477 (self.value, self.error)
478 }
479
480 pub fn into_inner(self) -> T {
482 self.value
483 }
484
485 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)]
520pub enum ReceiveError {
522 Lagged {
524 skipped: u64,
526 },
527 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)]
565pub enum TryReceiveError {
567 Empty,
569 Closed,
571 Lagged {
573 skipped: u64,
575 },
576 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 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 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;