Skip to main content

hyperlane_plugin_websocket/
struct.rs

1use super::*;
2
3/// Stack-backed `fmt::Write` cursor for zero-allocation broadcast key formatting.
4pub(crate) struct StackKeyWriter<'a> {
5    /// Destination stack byte buffer.
6    pub(crate) buf: &'a mut [u8],
7    /// Current number of written UTF-8 bytes.
8    pub(crate) len: usize,
9}
10
11/// Zero-allocation multiplicative 64-bit hasher for sparse WebSocket room shards.
12#[derive(Clone, Copy, Default)]
13pub(crate) struct WsKeyHasher {
14    /// Running 64-bit hash state.
15    pub(crate) state: u64,
16}
17
18/// One pre-framed RFC 6455 server message awaiting delivery to active room subscribers.
19pub(crate) struct WsRoomEntry {
20    /// Strictly monotonic per-room delivery sequence number.
21    pub(crate) seq: u64,
22    /// Pre-encoded RFC 6455 server wire bytes shared zero-copy across all room subscribers.
23    pub(crate) frame: Arc<[u8]>,
24    /// Exact number of live subscribers with cursor `<= seq` that have not consumed this frame.
25    pub(crate) unread: usize,
26}
27
28/// Lazily allocated, auto-reclaiming bounded delivery ring for one sparse WebSocket room.
29pub(crate) struct WsRoomRing {
30    /// Unread pre-framed messages (`VecDeque::new()` — zero heap bytes when idle or drained).
31    pub(crate) entries: VecDeque<WsRoomEntry>,
32    /// Sequence number of `entries.front()`, or `next_seq` when empty.
33    pub(crate) head_seq: u64,
34    /// Next sequence number assigned on broadcast.
35    pub(crate) next_seq: u64,
36    /// Active subscriber count synchronized with `unread` entry counters.
37    pub(crate) subscribers: usize,
38    /// Maximum unread messages retained before evicting oldest frames.
39    pub(crate) capacity: usize,
40    /// Whether this room was explicitly closed.
41    pub(crate) closed: bool,
42}
43
44/// Per-room zero-idle-ring WebSocket broadcast state.
45pub(crate) struct WsRoom {
46    /// Lock-free active subscriber count avoiding lock probes when empty.
47    pub(crate) subscribers: AtomicUsize,
48    /// Zero-allocation intrusive waiter list waking idle subscribers on broadcast.
49    pub(crate) notify: Notify,
50    /// Lazily allocated, auto-reclaiming bounded frame delivery ring.
51    pub(crate) ring: Mutex<WsRoomRing>,
52}
53
54/// Cache-line-aligned WebSocket room shard preventing cross-thread false sharing.
55#[repr(align(64))]
56pub(crate) struct WsShard {
57    /// Per-shard read-write lock guarding active room handles.
58    pub(crate) map: RwLock<WsShardMap>,
59}
60
61/// Shared 64-way sharded storage backing [`SparseWsHub`].
62pub(crate) struct SparseWsHubInner {
63    /// 64-way lock-striped room registry indexed by [`WsKeyHasher`].
64    pub(crate) shards: Box<[WsShard; WS_SHARD_COUNT]>,
65}
66
67/// Lazily initialized sparse-connection WebSocket room hub holding zero ring bytes for idle rooms.
68#[derive(Default)]
69pub(crate) struct SparseWsHub {
70    /// Lazily initialized sharded hub storage (zero allocation until the first `WebSocket::run` call).
71    pub(crate) inner: OnceLock<Arc<SparseWsHubInner>>,
72}
73
74/// Active sparse-hub room subscription owned by one [`WebSocket::run`] task.
75pub(crate) struct SparseWsSubscription {
76    /// Shared room key for automatic empty-room cleanup on drop.
77    pub(crate) key: Arc<str>,
78    /// Cached room state avoiding shard lookups on receive and drop.
79    pub(crate) room: Arc<WsRoom>,
80    /// Owning sparse hub for automatic empty-room eviction on drop.
81    pub(crate) hub: Arc<SparseWsHubInner>,
82    /// Next per-room delivery sequence number expected by this connection.
83    pub(crate) cursor: u64,
84}
85
86/// RAII guard returning a worker-local WebSocket coalesce scratch buffer on drop.
87pub(crate) struct WsScratchBuf {
88    /// Borrowed scratch byte buffer.
89    pub(crate) buf: Vec<u8>,
90}
91
92/// Represents a WebSocket instance.
93///
94/// This struct manages broadcast capabilities and holds the internal broadcast map
95/// responsible for handling message distribution to various WebSocket connections.
96#[derive(Data, Default)]
97pub struct WebSocket {
98    /// The internal broadcast map.
99    ///
100    /// This map is used for managing WebSocket message distribution.
101    pub(crate) broadcast_map: BroadcastMap<Vec<u8>>,
102    /// Zero-idle-ring sparse room hub serving `WebSocket::run` connections at high scale.
103    #[get(skip)]
104    #[get_mut(skip)]
105    #[set(skip)]
106    pub(crate) sparse_hub: SparseWsHub,
107}
108
109/// Process-wide [`WebSocketPlugin`] singleton holding a shared [`WebSocket`] room hub.
110#[derive(Clone, Debug, Default)]
111pub struct WebSocketPlugin {
112    /// Shared WebSocket broadcast hub.
113    pub(crate) websocket: WebSocket,
114}
115
116/// Configuration for a WebSocket connection.
117///
118/// This struct encapsulates all necessary parameters for setting up and managing
119/// a WebSocket connection, including context, buffer sizes, capacity, broadcast type,
120/// and hook handlers for different lifecycle events.
121///
122/// # Type Parameters
123///
124/// - `B`: The type used for broadcast keys, which must implement `BroadcastTypeTrait`.
125#[derive(Data)]
126pub struct WebSocketConfig<'a, B: BroadcastTypeTrait> {
127    /// The underlying stream for this WebSocket connection.
128    #[set(skip)]
129    pub(crate) stream: &'a mut Stream,
130    /// The Hyperlane context.
131    ///
132    /// This context is associated with this WebSocket connection.
133    #[set(skip)]
134    pub(crate) context: &'a mut Context,
135    /// The capacity.
136    ///
137    /// This is the capacity of the broadcast sender channel.
138    #[get(type(copy))]
139    #[set(skip)]
140    pub(crate) capacity: usize,
141    /// The broadcast type.
142    ///
143    /// This defines the type of broadcast this WebSocket connection will participate in
144    /// (point-to-point or point-to-group).
145    #[set(skip)]
146    pub(crate) broadcast_type: BroadcastType<B>,
147    /// The connected hook handler.
148    ///
149    /// This hook is executed when the WebSocket connection is established.
150    #[set(skip)]
151    pub(crate) connected_hook: ServerHookHandler,
152    /// The request hook handler.
153    ///
154    /// This hook is executed when a new request is received on the WebSocket.
155    #[set(skip)]
156    pub(crate) request_hook: ServerHookHandler,
157    /// The sended hook handler.
158    ///
159    /// This hook is executed after a message has been successfully sent over the WebSocket.
160    #[set(skip)]
161    pub(crate) sended_hook: ServerHookHandler,
162    /// The closed hook handler.
163    ///
164    /// This hook is executed when the WebSocket connection is closed.
165    #[set(skip)]
166    pub(crate) closed_hook: ServerHookHandler,
167}