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 NotRunning,
61 Unsupported,
63 SessionAlreadyExists,
65 ConnectionClosing,
67 Closed,
69 EngineDropped,
71 Cancelled,
73 TimedOut,
75 DeadlineExceeded,
77 DeliveryUnknown,
79 RetryExhausted,
81 InvalidPolicy,
83 BodyNotReplayable,
85 DuplicateRequestId,
87 RoutingDisabled,
89 RoutingModeMismatch,
91 ClientAlreadyExists,
93 ClientNotFound,
95 Internal,
97 HttpStatus,
99}
100
101#[non_exhaustive]
102#[derive(Clone, Copy, Debug, Eq, PartialEq)]
103pub enum ErrorStage {
108 Configuration,
110 Provider,
112 RequestBuild,
114 Dns,
116 Tcp,
118 Proxy,
120 Tls,
122 Upgrade,
124 Admission,
126 Queue,
128 Write,
130 Response,
132 Receive,
134 Heartbeat,
136 Close,
138 Dispatch,
140 NetworkMonitor,
142 Runtime,
144}
145
146#[non_exhaustive]
148#[derive(Clone, Default)]
149pub struct ErrorContext {
150 pub stage: Option<ErrorStage>,
152 #[cfg(feature = "ws-client")]
153 pub client_id: Option<crate::ws::ClientId>,
155 #[cfg(feature = "ws-client")]
156 pub session_id: Option<crate::ws::SessionId>,
158 #[cfg(feature = "ws-client")]
159 pub connection_id: Option<crate::ws::ConnectionId>,
161 #[cfg(feature = "ws-client")]
162 pub attempt_id: Option<crate::ws::AttemptId>,
164 #[cfg(feature = "ws-client")]
165 pub request_id: Option<crate::ws::RequestId>,
167 pub http_status: Option<http::StatusCode>,
169 #[cfg(feature = "http-client")]
170 pub http_request_id: Option<crate::api::http::HttpRequestId>,
172 #[cfg(feature = "http-client")]
173 pub http_timeout_phase: Option<crate::api::http::TimeoutPhase>,
175 #[cfg(feature = "http-client")]
176 pub http_attempt: Option<u32>,
178 #[cfg(feature = "ws-client")]
179 pub diagnostic: Option<crate::ws::HandshakeDiagnostic>,
181 #[cfg(feature = "ws-client")]
182 pub peer_close: Option<crate::ws::PeerClose>,
184 #[cfg(feature = "ws-client")]
185 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#[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 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 Self::new(ErrorKind::Internal)
308 }
309
310 pub fn kind(&self) -> ErrorKind {
312 self.kind
313 }
314
315 pub fn context(&self) -> &ErrorContext {
317 &self.context
318 }
319
320 #[cfg(feature = "http-client")]
322 pub fn timeout_phase(&self) -> Option<crate::api::http::TimeoutPhase> {
323 self.context.http_timeout_phase
324 }
325
326 pub fn http_status(&self) -> Option<http::StatusCode> {
328 self.context.http_status
329 }
330
331 #[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 pub fn config_error(&self) -> Option<&ConfigError> {
354 self.config_error.as_deref()
355 }
356
357 pub fn io_kind(&self) -> Option<std::io::ErrorKind> {
359 let mut source = self.source();
360 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 pub fn protocol(source: impl Into<BoxError>) -> Self {
374 Self::with_source(ErrorKind::Protocol, source)
375 }
376
377 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)]
429pub 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 pub fn field(&self) -> &str {
445 &self.field
446 }
447
448 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
483pub 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 pub fn error(&self) -> &NetError {
496 &self.error
497 }
498
499 pub fn value(&self) -> &T {
501 &self.value
502 }
503
504 pub fn into_parts(self) -> (T, NetError) {
506 (self.value, self.error)
507 }
508
509 pub fn into_inner(self) -> T {
511 self.value
512 }
513
514 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)]
549pub enum ReceiveError {
551 Lagged {
553 skipped: u64,
555 },
556 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)]
594pub enum TryReceiveError {
596 Empty,
598 Closed,
600 Lagged {
602 skipped: u64,
604 },
605 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 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 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;