socketio_next/state.rs
1use std::fmt;
2use std::time::Duration;
3
4use tokio::time::Instant;
5
6use crate::Error;
7use crate::engineio::TransportKind;
8
9/// Why a connection ended. The first six are socket.io-client's `disconnect` reasons.
10#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
11#[non_exhaustive]
12pub enum DisconnectReason {
13 /// The server disconnected the socket (`socket.disconnect()` on the server). No reconnect
14 /// unless `reconnect_on_disconnect` is on.
15 IoServerDisconnect,
16 /// [`Client::disconnect`](crate::Client::disconnect) was called.
17 IoClientDisconnect,
18 /// No ping from the server within pingInterval + pingTimeout.
19 PingTimeout,
20 /// The connection was closed (the server went away, the network dropped it).
21 TransportClose,
22 /// The transport failed (HTTP error, websocket error, a write that failed).
23 TransportError,
24 /// The server sent a packet that does not decode.
25 ParseError,
26 /// The server refused the namespace (CONNECT_ERROR). Final.
27 ConnectRejected,
28 /// The reconnect attempts ran out (`reconnection_attempts`). Final.
29 ReconnectFailed,
30 /// Every [`Client`](crate::Client) handle was dropped. Final.
31 Dropped,
32}
33
34impl DisconnectReason {
35 /// The socket.io-client string (`"io server disconnect"`, `"ping timeout"`, ...).
36 pub fn as_str(self) -> &'static str {
37 match self {
38 DisconnectReason::IoServerDisconnect => "io server disconnect",
39 DisconnectReason::IoClientDisconnect => "io client disconnect",
40 DisconnectReason::PingTimeout => "ping timeout",
41 DisconnectReason::TransportClose => "transport close",
42 DisconnectReason::TransportError => "transport error",
43 DisconnectReason::ParseError => "parse error",
44 DisconnectReason::ConnectRejected => "connect rejected",
45 DisconnectReason::ReconnectFailed => "reconnect failed",
46 DisconnectReason::Dropped => "client dropped",
47 }
48 }
49}
50
51impl fmt::Display for DisconnectReason {
52 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
53 f.write_str(self.as_str())
54 }
55}
56
57/// The connection lifecycle, published on every transition.
58///
59/// A network loss goes `Connected` -> `Disconnected` -> `Reconnecting` -> `Connecting` ->
60/// (`Reconnecting` -> `Connecting` per failed attempt) -> `Connected`. `Closed` is final.
61#[derive(Debug, Clone)]
62#[non_exhaustive]
63pub enum ConnectionState {
64 /// A connect attempt is running (`attempt` 0 is the initial connect).
65 #[non_exhaustive]
66 Connecting {
67 /// 0 for the initial connect, then 1, 2, ... per reconnect attempt.
68 attempt: u32,
69 },
70 /// The namespace is joined.
71 #[non_exhaustive]
72 Connected {
73 /// The socket id the server assigned (`socket.id`).
74 sid: String,
75 /// Connection state recovery restored the session (`socket.recovered`).
76 recovered: bool,
77 },
78 /// The connection was lost; a reconnect follows.
79 #[non_exhaustive]
80 Disconnected {
81 /// Why.
82 reason: DisconnectReason,
83 /// The error behind it (`WebsocketClosed { code, reason }`, `PingTimeout`, ...).
84 error: Option<Error>,
85 },
86 /// Waiting `delay` before reconnect attempt `attempt`.
87 #[non_exhaustive]
88 Reconnecting {
89 /// 1, 2, ... (socket.io-client `reconnect_attempt`).
90 attempt: u32,
91 /// The backoff delay before this attempt.
92 delay: Duration,
93 /// Why the previous attempt failed (`None` before the first attempt).
94 error: Option<Error>,
95 },
96 /// Final: no more connects or events.
97 #[non_exhaustive]
98 Closed {
99 /// Why.
100 reason: DisconnectReason,
101 /// The error behind it (rejection, last failed attempt).
102 error: Option<Error>,
103 },
104}
105
106impl ConnectionState {
107 /// The namespace is joined.
108 pub fn is_connected(&self) -> bool {
109 matches!(self, ConnectionState::Connected { .. })
110 }
111
112 /// Final state.
113 pub fn is_closed(&self) -> bool {
114 matches!(self, ConnectionState::Closed { .. })
115 }
116}
117
118/// A snapshot of the link for health checks and debugging.
119#[derive(Debug, Clone, Default)]
120#[non_exhaustive]
121pub struct LinkInfo {
122 /// The socket id (`socket.id`) while connected.
123 pub sid: Option<String>,
124 /// The engine.io session id while connected.
125 pub engine_sid: Option<String>,
126 /// The transport in use while connected.
127 pub transport: Option<TransportKind>,
128 /// pingInterval from the last handshake.
129 pub ping_interval: Option<Duration>,
130 /// pingTimeout from the last handshake.
131 pub ping_timeout: Option<Duration>,
132 /// maxPayload from the last handshake.
133 pub max_payload: Option<u64>,
134 /// When the current connection was established.
135 pub connected_at: Option<Instant>,
136 /// When the last engine.io packet of any kind arrived.
137 pub last_packet_at: Option<Instant>,
138 /// When the last ping arrived.
139 pub last_ping_at: Option<Instant>,
140 /// When the last connect attempt started.
141 pub last_attempt_at: Option<Instant>,
142 /// Reconnect attempts since the last successful connect.
143 pub reconnect_attempts: u32,
144 /// Acks waiting for the server.
145 pub pending_acks: usize,
146 /// Emits queued while disconnected (`buffer_while_disconnected`).
147 pub buffered_emits: usize,
148 /// Engine.io message packets sent (socket.io packets and their binary attachments).
149 pub packets_out: u64,
150 /// Engine.io message packets received.
151 pub packets_in: u64,
152 /// Bytes of those packets sent (encoded socket.io text plus raw attachments).
153 pub bytes_out: u64,
154 /// Bytes of those packets received.
155 pub bytes_in: u64,
156 /// Successful connects (the first one and every reconnect) of this client.
157 pub sessions: u32,
158}