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 // Some IDs are assigned by their owning scope in production; identity
27 // tests exercise this shared allocator for every generated ID type.
28 #[cfg_attr(not(test), allow(dead_code))]
29 pub(crate) fn allocate(counter: &AtomicU64) -> Result<Self> {
30 next_value(counter).map(Self::from_allocated)
31 }
32 }
33
34 impl fmt::Display for $name {
35 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
36 self.0.fmt(formatter)
37 }
38 }
39 )+
40 };
41}
42
43opaque_id!(
44 /// WebSocket client identity used to correlate sessions, messages, and events.
45 ClientId,
46 /// Logical session identity; one session can span reconnect attempts.
47 SessionId,
48 /// Physical connection identity distinguishing messages across reconnects.
49 ConnectionId,
50 /// One connection-attempt identity for handshake, failure, and retry events.
51 AttemptId,
52 /// Connection-cycle identity grouping attempts and backoff events.
53 CycleId,
54 /// Message or request operation identity used by snapshots and terminal events.
55 OperationId
56);
57
58fn next_value(counter: &AtomicU64) -> Result<u64> {
59 counter
60 .fetch_update(Ordering::Relaxed, Ordering::Relaxed, |last| {
61 last.checked_add(1)
62 })
63 .map(|last| last + 1)
64 .map_err(|_| NetError::from(ErrorKind::ResourceExhausted))
65}
66
67#[cfg(test)]
68#[path = "identity_tests.rs"]
69mod tests;