Skip to main content

open_net/api/ws/
identity.rs

1use crate::error::{ErrorKind, NetError};
2use crate::Result;
3use std::fmt;
4use std::sync::atomic::{AtomicU64, Ordering};
5
6macro_rules! opaque_id {
7    ($($(#[$doc:meta])* $name:ident),+ $(,)?) => {
8        $(
9            $(#[$doc])*
10            #[derive(Clone, Copy, Debug, Eq, PartialEq, Ord, PartialOrd, Hash)]
11            pub struct $name(
12                /// Numeric identity allocated by the owning internal scope.
13                u64,
14            );
15
16            impl $name {
17                /// Returns the numeric identity value.
18                pub fn as_u64(self) -> u64 { self.0 }
19
20                /// Wrap an identity already assigned by the owning internal scope.
21                /// The caller must preserve that scope's checked allocation and lifetime.
22                pub(crate) fn from_allocated(value: u64) -> Self { Self(value) }
23
24                /// The owning scope supplies its last allocated value; zero starts at one.
25                /// Allocation only establishes uniqueness, not visibility of business state.
26                pub(crate) fn allocate(counter: &AtomicU64) -> Result<Self> {
27                    next_value(counter).map(Self::from_allocated)
28                }
29            }
30
31            impl fmt::Display for $name {
32                fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
33                    self.0.fmt(formatter)
34                }
35            }
36        )+
37    };
38}
39
40opaque_id!(
41    /// WebSocket client identity used to correlate sessions, messages, and events.
42    ClientId,
43    /// Logical session identity; one session can span reconnect attempts.
44    SessionId,
45    /// Physical connection identity distinguishing messages across reconnects.
46    ConnectionId,
47    /// One connection-attempt identity for handshake, failure, and retry events.
48    AttemptId,
49    /// Connection-cycle identity grouping attempts and backoff events.
50    CycleId,
51    /// Message or request operation identity used by snapshots and terminal events.
52    OperationId
53);
54
55fn next_value(counter: &AtomicU64) -> Result<u64> {
56    counter
57        .fetch_update(Ordering::Relaxed, Ordering::Relaxed, |last| {
58            last.checked_add(1)
59        })
60        .map(|last| last + 1)
61        .map_err(|_| NetError::from(ErrorKind::ResourceExhausted))
62}
63
64#[cfg(test)]
65#[path = "identity_tests.rs"]
66mod tests;