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