Skip to main content

open_net/api/ws/
close.rs

1use crate::error::{ErrorKind, ErrorStage};
2use crate::{NetError, Result};
3use std::fmt;
4
5/// Validated outbound close frame with a UTF-8 reason of at most 123 bytes.
6///
7/// `Debug` reports the close code and reason byte count without exposing the reason text.
8#[derive(Clone)]
9pub struct CloseFrame {
10    /// WebSocket wire close code validated by the constructor.
11    code: u16,
12    /// Reason text sent with the close frame; may be empty.
13    reason: String,
14}
15
16impl fmt::Debug for CloseFrame {
17    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
18        formatter
19            .debug_struct("CloseFrame")
20            .field("code", &self.code)
21            .field("reason_len", &self.reason.len())
22            .finish()
23    }
24}
25
26impl CloseFrame {
27    /// Validates a wire close code and UTF-8 reason.
28    pub fn new(code: u16, reason: impl Into<String>) -> Result<Self> {
29        // RFC 6455 ยงยง5.5/7.4 and the IANA WebSocket Close Code registry.
30        if !matches!(code, 1000..=1003 | 1007..=1014 | 3000..=4999) {
31            return Err(NetError::input(
32                "close.code",
33                "must be an allowed WebSocket wire close code",
34            )
35            .with_stage(ErrorStage::Close));
36        }
37        let reason = reason.into();
38        if reason.len() > 123 {
39            return Err(
40                NetError::input("close.reason", "must be at most 123 UTF-8 bytes")
41                    .with_stage(ErrorStage::Close),
42            );
43        }
44        Ok(Self { code, reason })
45    }
46
47    /// Returns the validated close code.
48    pub fn code(&self) -> u16 {
49        self.code
50    }
51
52    /// Borrows the close reason.
53    pub fn reason(&self) -> &str {
54        &self.reason
55    }
56
57    pub(crate) fn into_wire(self) -> tokio_tungstenite::tungstenite::protocol::CloseFrame {
58        use tokio_tungstenite::tungstenite::protocol::frame::coding::CloseCode;
59        // Tungstenite 0.30 maps registered code 1014 to Bad. Preserve its valid
60        // numeric wire value using the library's explicit IANA-code variant.
61        let code = if self.code == 1014 {
62            CloseCode::Iana(self.code)
63        } else {
64            CloseCode::from(self.code)
65        };
66        tokio_tungstenite::tungstenite::protocol::CloseFrame {
67            code,
68            reason: self.reason.into(),
69        }
70    }
71}
72
73/// Peer close information observed by the receiver, including code-less closes.
74#[derive(Clone)]
75pub struct PeerClose {
76    /// Decoded close code; `None` for an empty close frame.
77    pub code: Option<u16>,
78    /// Complete decoded reason; empty for an empty close frame.
79    pub reason: String,
80}
81
82impl PeerClose {
83    /// Own the decoder's complete UTF-8 reason; an empty Close has no code.
84    /// Tungstenite may already have replaced an invalid wire code with its
85    /// protocol-error Close before this observation reaches the SDK.
86    pub(crate) fn from_frame(
87        frame: Option<&tokio_tungstenite::tungstenite::protocol::CloseFrame>,
88    ) -> Result<Self> {
89        let Some(frame) = frame else {
90            return Ok(Self {
91                code: None,
92                reason: String::new(),
93            });
94        };
95        if frame.reason.len() > 123 {
96            // Real network frames are checked by the decoder. Reject malformed
97            // internal streams as well, without truncating a UTF-8 sequence.
98            return Err(NetError::from(ErrorKind::Protocol).with_stage(ErrorStage::Close));
99        }
100        let mut reason = String::new();
101        reason
102            .try_reserve_exact(frame.reason.len())
103            .map_err(|error| {
104                NetError::with_source(ErrorKind::ResourceExhausted, error)
105                    .with_stage(ErrorStage::Close)
106            })?;
107        reason.push_str(frame.reason.as_str());
108        Ok(Self {
109            code: Some(u16::from(frame.code)),
110            reason,
111        })
112    }
113}
114
115impl fmt::Debug for PeerClose {
116    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
117        formatter
118            .debug_struct("PeerClose")
119            .field("code", &self.code)
120            .field("reason_len", &self.reason.len())
121            .finish()
122    }
123}
124
125/// I/O notification category that ended a physical connection.
126/// An observed peer close is retained even if the close reply write fails.
127#[non_exhaustive]
128#[derive(Clone, Copy, Debug, Eq, PartialEq)]
129pub enum IoEndKind {
130    /// A WebSocket close frame was received from the peer.
131    PeerClose,
132    /// The stream ended before the expected close handshake completed.
133    UnexpectedEof,
134    /// The underlying connection was reset.
135    ConnectionReset,
136    /// A WebSocket protocol error occurred during I/O.
137    ProtocolError,
138    /// Another I/O, heartbeat, timeout, or internal-channel failure occurred.
139    Other,
140}
141
142#[cfg(test)]
143#[path = "close_tests.rs"]
144mod tests;
145
146#[cfg(test)]
147#[path = "peer_close_tests.rs"]
148mod peer_tests;