Skip to main content

open_net/api/ws/
connection.rs

1use super::{
2    AttemptId, ClientId, ConnectionId, CycleId, HandshakeAttempt, IoEndKind, PeerClose, QueueLimit,
3    SessionId,
4};
5use crate::error::{ErrorKind, ErrorStage};
6use crate::{NetError, Result};
7use std::fmt;
8use std::time::{Duration, Instant, SystemTime};
9
10pub(crate) const MAX_CONNECTION_EVENT_BYTES: usize = 32 * 1024;
11
12/// Capacity limits for the connection lifecycle journal, constraining both the
13/// number of retained events and their measured byte total.
14#[derive(Clone, Debug)]
15pub struct JournalOptions {
16    /// Maximum number of events that may be retained; the minimum is 4 and the
17    /// default is 32.
18    pub max_events: usize,
19    /// Maximum measured bytes that may be retained for events; the minimum is
20    /// 131,072 bytes and the default is 1 MiB.
21    pub max_bytes: usize,
22}
23impl Default for JournalOptions {
24    fn default() -> Self {
25        Self {
26            max_events: 32,
27            max_bytes: 1024 * 1024,
28        }
29    }
30}
31impl JournalOptions {
32    /// Minimum lifecycle events required to retain the session boundary facts.
33    pub const MIN_EVENTS: usize = 4;
34    /// Validates event-count and measured-byte retention limits.
35    pub fn validate(&self) -> Result<()> {
36        if self.max_events < Self::MIN_EVENTS {
37            return Err(NetError::config(
38                "journal.max_events",
39                "must reserve at least four lifecycle facts",
40            ));
41        }
42        if self.max_bytes < Self::MIN_EVENTS * MAX_CONNECTION_EVENT_BYTES {
43            return Err(NetError::config(
44                "journal.max_bytes",
45                "must reserve at least 131072 bytes for four lifecycle facts",
46            ));
47        }
48        QueueLimit {
49            max_items: self.max_events,
50            max_bytes: self.max_bytes,
51        }
52        .validate_fields("journal.max_events", "journal.max_bytes")
53    }
54}
55
56/// Latest state snapshot for a connection session; observers may receive a
57/// snapshot after intermediate updates have been coalesced.
58#[derive(Clone, Debug)]
59pub struct ConnectionSnapshot {
60    /// Monotonically increasing snapshot revision within the session; starts at 0.
61    pub revision: u64,
62    /// Identifier of the logical connection session represented by this snapshot.
63    pub session_id: SessionId,
64    /// Current lifecycle state of the session.
65    pub state: ConnectionState,
66    /// Most recently recorded error, if any. Later state changes do not clear an
67    /// existing error automatically.
68    pub last_error: Option<NetError>,
69}
70
71/// Current status of a connection session, including initial connection,
72/// reconnection, network waiting, and shutdown.
73/// This enum is non-exhaustive; callers must handle future states.
74#[non_exhaustive]
75#[derive(Clone, Debug)]
76pub enum ConnectionState {
77    /// Preparing for or performing the first connection attempt.
78    Connecting,
79    /// A usable WebSocket connection was successfully established.
80    Connected(
81        /// The identity, establishment time, and credential version of the currently established connection.
82        ConnectionInfo,
83    ),
84    /// Network conditions currently prevent a connection, so the session is
85    /// waiting for reachability to recover.
86    WaitingForNetwork,
87    /// Waiting for or performing a new connection attempt.
88    Reconnecting {
89        /// The identifier of the current reconnection period.
90        cycle_id: CycleId,
91        /// The scheduled next attempt time; `None` means that no backoff deadline is currently reserved.
92        next_attempt_at: Option<Instant>,
93    },
94    /// The session is closing and completing its shutdown work.
95    Closing,
96    /// The session has ended and no more connection attempts are initiated.
97    Closed(
98        /// Final session-end details, or the error that caused termination.
99        Result<SessionEnd>,
100    ),
101}
102
103/// Identity and timing information for one established WebSocket connection.
104/// A reconnecting logical session receives a new physical connection ID.
105/// `Debug` reports only the byte length of the credential version and never its content.
106#[derive(Clone)]
107pub struct ConnectionInfo {
108    /// The client instance ID that established this connection.
109    pub client_id: ClientId,
110    /// Logical session identifier; it remains stable across reconnects.
111    pub session_id: SessionId,
112    /// Identifier of this physical connection.
113    pub connection_id: ConnectionId,
114    /// Identifier of the connect or reconnect cycle that generated this connection.
115    pub cycle_id: CycleId,
116    /// Identifier of the handshake attempt that established this connection.
117    pub attempt_id: AttemptId,
118    /// The system time when the connection was successfully established.
119    pub connected_at: SystemTime,
120    /// Optional credential version used for this handshake, returned by the dynamic handshake provider.
121    pub credential_version: Option<String>,
122}
123
124impl fmt::Debug for ConnectionInfo {
125    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
126        formatter
127            .debug_struct("ConnectionInfo")
128            .field("client_id", &self.client_id)
129            .field("session_id", &self.session_id)
130            .field("connection_id", &self.connection_id)
131            .field("cycle_id", &self.cycle_id)
132            .field("attempt_id", &self.attempt_id)
133            .field("connected_at", &self.connected_at)
134            .field(
135                "credential_version_bytes",
136                &self.credential_version.as_ref().map(String::len),
137            )
138            .finish()
139    }
140}
141
142/// Lifecycle event generated by a connection session, with a session-local
143/// sequence number and event-specific payload.
144#[derive(Clone, Debug)]
145pub struct ConnectionEvent {
146    /// A monotonically increasing event sequence number within the session, with the first event starting from 1.
147    pub sequence: u64,
148    /// The ID of the client instance that generated the event.
149    pub client_id: ClientId,
150    /// Logical session identifier that generated the event.
151    pub session_id: SessionId,
152    /// The system time recorded when the event occurred.
153    pub occurred_at: SystemTime,
154    /// Lifecycle fact and associated data recorded by this event.
155    pub kind: ConnectionEventKind,
156}
157
158/// Specific lifecycle event kinds and their associated information.
159#[non_exhaustive]
160#[derive(Clone)]
161pub enum ConnectionEventKind {
162    /// A new handshake attempt has been started.
163    AttemptStarted {
164        /// Client, session, cycle ID and metadata for this attempt.
165        attempt: HandshakeAttempt,
166    },
167    /// The handshake is successful and the connection is established.
168    Established {
169        /// The identity and establishment time of the newly established connection.
170        connection: ConnectionInfo,
171    },
172    /// A handshake attempt failed and it has been determined whether to continue retrying.
173    AttemptFailed {
174        /// Identity and metadata of the failed attempt.
175        attempt: HandshakeAttempt,
176        /// Credential version obtained for the attempt; `None` if the provider
177        /// did not return one.
178        credential_version: Option<String>,
179        /// The error and context that caused this attempt to fail.
180        error: NetError,
181        /// The decision to stop or delay retry after this failure.
182        retry: RetryDecision,
183    },
184    /// The physical connection ended; the session's reconnect policy determines
185    /// whether another connection attempt is made.
186    Disconnected {
187        /// The connection information ended this time.
188        connection: ConnectionInfo,
189        /// Termination reason and any available error, peer-close, and I/O details.
190        end: ConnectionEnd,
191    },
192    /// The entire connection session has ended.
193    Closed {
194        /// Final session-end details, or the error that caused termination.
195        result: Result<SessionEnd>,
196    },
197}
198
199impl fmt::Debug for ConnectionEventKind {
200    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
201        match self {
202            Self::AttemptStarted { attempt } => formatter
203                .debug_struct("AttemptStarted")
204                .field("attempt", attempt)
205                .finish(),
206            Self::Established { connection } => formatter
207                .debug_struct("Established")
208                .field("connection", connection)
209                .finish(),
210            Self::AttemptFailed {
211                attempt,
212                credential_version,
213                error,
214                retry,
215            } => formatter
216                .debug_struct("AttemptFailed")
217                .field("attempt", attempt)
218                .field(
219                    "credential_version_bytes",
220                    &credential_version.as_ref().map(String::len),
221                )
222                .field("error", error)
223                .field("retry", retry)
224                .finish(),
225            Self::Disconnected { connection, end } => formatter
226                .debug_struct("Disconnected")
227                .field("connection", connection)
228                .field("end", end)
229                .finish(),
230            Self::Closed { result } => formatter
231                .debug_struct("Closed")
232                .field("result", result)
233                .finish(),
234        }
235    }
236}
237
238/// The retry decision taken after a failed connection attempt.
239#[derive(Clone, Debug)]
240pub enum RetryDecision {
241    /// Stop trying to connect.
242    Stop,
243    /// The next connection attempt has been scheduled.
244    Scheduled {
245        /// The planned amount of time to wait before the next attempt.
246        after: Duration,
247    },
248}
249
250/// Termination details for one established connection, including the reason,
251/// peer close information, and low-level I/O outcome.
252#[derive(Clone, Debug)]
253pub struct ConnectionEnd {
254    /// The main reason why this connection ended.
255    pub reason: TerminationReason,
256    /// Error associated with termination, if one was recorded.
257    pub error: Option<NetError>,
258    /// Peer close frame received during termination, if any.
259    pub peer_close: Option<PeerClose>,
260    /// Low-level I/O termination classification, if one was recorded.
261    pub io_end: Option<IoEndKind>,
262}
263
264/// Terminal result for the logical connection session, optionally including
265/// details for its last established physical connection.
266#[derive(Clone, Debug)]
267pub struct SessionEnd {
268    /// Main reason the session stopped and will not reconnect.
269    pub reason: TerminationReason,
270    /// End information for the last established connection; `None` if there is no connection end record to retain.
271    pub last_connection: Option<ConnectionEnd>,
272}
273
274/// Main reason for connection or session termination, distinguishing local
275/// closure, cancellation, peer actions, and failure classes.
276/// This enum is non-exhaustive; callers must handle future reasons.
277#[non_exhaustive]
278#[derive(Clone, Copy, Debug, Eq, PartialEq)]
279pub enum TerminationReason {
280    /// The operation or session was canceled.
281    Cancelled,
282    /// The local caller explicitly closed the connection session.
283    LocalClose,
284    /// The owning client was shut down.
285    ClientShutdown,
286    /// The underlying network engine has been destroyed.
287    EngineDropped,
288    /// The peer initiated shutdown.
289    PeerClose,
290    /// A connection attempt failed and the session will not try again.
291    ConnectFailed,
292    /// The retry policy exhausted its allowed attempts.
293    RetryExhausted,
294    /// The underlying read/write or transmission failed.
295    IoFailure,
296    /// Network unavailability ended the connection or session.
297    NetworkUnavailable,
298}
299
300impl ConnectionEvent {
301    /// Charge the fixed record and retained UTF-8/byte fields of this record.
302    /// Shared metadata/config detail is charged to each retaining record, so
303    /// accounting is deterministic and never depends on another observer's lifetime.
304    /// Arbitrary application error sources and allocator overhead are not traversed.
305    pub(crate) fn measured_size(&self) -> Result<usize> {
306        let mut bytes = EventSize(std::mem::size_of::<Self>());
307        match &self.kind {
308            ConnectionEventKind::AttemptStarted { attempt } => bytes.attempt(attempt)?,
309            ConnectionEventKind::Established { connection } => bytes.connection(connection)?,
310            ConnectionEventKind::AttemptFailed {
311                attempt,
312                credential_version,
313                error,
314                ..
315            } => {
316                bytes.attempt(attempt)?;
317                bytes.string(credential_version.as_deref())?;
318                bytes.error(error)?;
319            }
320            ConnectionEventKind::Disconnected { connection, end } => {
321                bytes.connection(connection)?;
322                bytes.end(end)?;
323            }
324            ConnectionEventKind::Closed { result: Ok(end) } => {
325                if let Some(last) = &end.last_connection {
326                    bytes.end(last)?;
327                }
328            }
329            ConnectionEventKind::Closed { result: Err(error) } => bytes.error(error)?,
330        }
331        bytes.add(0)?;
332        Ok(bytes.0)
333    }
334}
335
336/// Accumulates the measured size of one connection event and fails on overflow
337/// or when the per-event limit is exceeded.
338struct EventSize(
339    /// Bytes counted so far, including fixed structure overhead and retained
340    /// string or byte content.
341    usize,
342);
343impl EventSize {
344    fn add(&mut self, count: usize) -> Result<()> {
345        let total = self.0.checked_add(count).ok_or_else(|| {
346            NetError::from(ErrorKind::ResourceExhausted).with_stage(ErrorStage::Dispatch)
347        })?;
348        if total > MAX_CONNECTION_EVENT_BYTES {
349            return Err(NetError::from(ErrorKind::ItemTooLarge).with_stage(ErrorStage::Dispatch));
350        }
351        self.0 = total;
352        Ok(())
353    }
354    fn string(&mut self, value: Option<&str>) -> Result<()> {
355        if let Some(value) = value {
356            self.add(value.len())?;
357        }
358        Ok(())
359    }
360    fn attempt(&mut self, attempt: &HandshakeAttempt) -> Result<()> {
361        for (key, value) in attempt.metadata.iter() {
362            self.add(key.len())?;
363            self.add(value.len())?;
364        }
365        Ok(())
366    }
367    fn connection(&mut self, connection: &ConnectionInfo) -> Result<()> {
368        self.string(connection.credential_version.as_deref())
369    }
370    fn end(&mut self, end: &ConnectionEnd) -> Result<()> {
371        if let Some(peer) = &end.peer_close {
372            self.add(peer.reason.len())?;
373        }
374        if let Some(error) = &end.error {
375            self.error(error)?;
376        }
377        Ok(())
378    }
379    fn error(&mut self, error: &NetError) -> Result<()> {
380        let context = error.context();
381        if let Some(peer) = &context.peer_close {
382            self.add(peer.reason.len())?;
383        }
384        if let Some(id) = &context.request_id {
385            self.add(id.as_str().len())?;
386        }
387        if let Some(diagnostic) = &context.diagnostic {
388            for (name, value) in diagnostic.headers() {
389                self.add(name.as_str().len())?;
390                self.add(value.as_bytes().len())?;
391            }
392            self.string(diagnostic.body_summary())?;
393        }
394        if let Some(detail) = error.config_error() {
395            self.add(detail.field().len())?;
396            self.add(detail.reason().len())?;
397        }
398        Ok(())
399    }
400}
401
402#[cfg(test)]
403#[path = "connection_tests.rs"]
404mod tests;