hyperlane-plugin-websocket 23.3.0

A WebSocket plugin for the Hyperlane framework, providing robust WebSocket communication capabilities and integrating with hyperlane-broadcast for efficient message dissemination.
Documentation
use super::*;

/// Stack-backed `fmt::Write` cursor for zero-allocation broadcast key formatting.
pub(crate) struct StackKeyWriter<'a> {
    /// Destination stack byte buffer.
    pub(crate) buf: &'a mut [u8],
    /// Current number of written UTF-8 bytes.
    pub(crate) len: usize,
}

/// Zero-allocation multiplicative 64-bit hasher for sparse WebSocket room shards.
#[derive(Clone, Copy, Default)]
pub(crate) struct WsKeyHasher {
    /// Running 64-bit hash state.
    pub(crate) state: u64,
}

/// One pre-framed RFC 6455 server message awaiting delivery to active room subscribers.
pub(crate) struct WsRoomEntry {
    /// Strictly monotonic per-room delivery sequence number.
    pub(crate) seq: u64,
    /// Pre-encoded RFC 6455 server wire bytes shared zero-copy across all room subscribers.
    pub(crate) frame: Arc<[u8]>,
    /// Exact number of live subscribers with cursor `<= seq` that have not consumed this frame.
    pub(crate) unread: usize,
}

/// Lazily allocated, auto-reclaiming bounded delivery ring for one sparse WebSocket room.
pub(crate) struct WsRoomRing {
    /// Unread pre-framed messages (`VecDeque::new()` — zero heap bytes when idle or drained).
    pub(crate) entries: VecDeque<WsRoomEntry>,
    /// Sequence number of `entries.front()`, or `next_seq` when empty.
    pub(crate) head_seq: u64,
    /// Next sequence number assigned on broadcast.
    pub(crate) next_seq: u64,
    /// Active subscriber count synchronized with `unread` entry counters.
    pub(crate) subscribers: usize,
    /// Maximum unread messages retained before evicting oldest frames.
    pub(crate) capacity: usize,
    /// Whether this room was explicitly closed.
    pub(crate) closed: bool,
}

/// Per-room zero-idle-ring WebSocket broadcast state.
pub(crate) struct WsRoom {
    /// Lock-free active subscriber count avoiding lock probes when empty.
    pub(crate) subscribers: AtomicUsize,
    /// Zero-allocation intrusive waiter list waking idle subscribers on broadcast.
    pub(crate) notify: Notify,
    /// Lazily allocated, auto-reclaiming bounded frame delivery ring.
    pub(crate) ring: Mutex<WsRoomRing>,
}

/// Cache-line-aligned WebSocket room shard preventing cross-thread false sharing.
#[repr(align(64))]
pub(crate) struct WsShard {
    /// Per-shard read-write lock guarding active room handles.
    pub(crate) map: RwLock<WsShardMap>,
}

/// Shared 64-way sharded storage backing [`SparseWsHub`].
pub(crate) struct SparseWsHubInner {
    /// 64-way lock-striped room registry indexed by [`WsKeyHasher`].
    pub(crate) shards: Box<[WsShard; WS_SHARD_COUNT]>,
}

/// Lazily initialized sparse-connection WebSocket room hub holding zero ring bytes for idle rooms.
#[derive(Default)]
pub(crate) struct SparseWsHub {
    /// Lazily initialized sharded hub storage (zero allocation until the first `WebSocket::run` call).
    pub(crate) inner: OnceLock<Arc<SparseWsHubInner>>,
}

/// Active sparse-hub room subscription owned by one [`WebSocket::run`] task.
pub(crate) struct SparseWsSubscription {
    /// Shared room key for automatic empty-room cleanup on drop.
    pub(crate) key: Arc<str>,
    /// Cached room state avoiding shard lookups on receive and drop.
    pub(crate) room: Arc<WsRoom>,
    /// Owning sparse hub for automatic empty-room eviction on drop.
    pub(crate) hub: Arc<SparseWsHubInner>,
    /// Next per-room delivery sequence number expected by this connection.
    pub(crate) cursor: u64,
}

/// RAII guard returning a worker-local WebSocket coalesce scratch buffer on drop.
pub(crate) struct WsScratchBuf {
    /// Borrowed scratch byte buffer.
    pub(crate) buf: Vec<u8>,
}

/// Represents a WebSocket instance.
///
/// This struct manages broadcast capabilities and holds the internal broadcast map
/// responsible for handling message distribution to various WebSocket connections.
#[derive(Data, Default)]
pub struct WebSocket {
    /// The internal broadcast map.
    ///
    /// This map is used for managing WebSocket message distribution.
    pub(crate) broadcast_map: BroadcastMap<Vec<u8>>,
    /// Zero-idle-ring sparse room hub serving `WebSocket::run` connections at high scale.
    #[get(skip)]
    #[get_mut(skip)]
    #[set(skip)]
    pub(crate) sparse_hub: SparseWsHub,
}

/// Process-wide [`WebSocketPlugin`] singleton holding a shared [`WebSocket`] room hub.
#[derive(Clone, Debug, Default)]
pub struct WebSocketPlugin {
    /// Shared WebSocket broadcast hub.
    pub(crate) websocket: WebSocket,
}

/// Configuration for a WebSocket connection.
///
/// This struct encapsulates all necessary parameters for setting up and managing
/// a WebSocket connection, including context, buffer sizes, capacity, broadcast type,
/// and hook handlers for different lifecycle events.
///
/// # Type Parameters
///
/// - `B`: The type used for broadcast keys, which must implement `BroadcastTypeTrait`.
#[derive(Data)]
pub struct WebSocketConfig<'a, B: BroadcastTypeTrait> {
    /// The underlying stream for this WebSocket connection.
    #[set(skip)]
    pub(crate) stream: &'a mut Stream,
    /// The Hyperlane context.
    ///
    /// This context is associated with this WebSocket connection.
    #[set(skip)]
    pub(crate) context: &'a mut Context,
    /// The capacity.
    ///
    /// This is the capacity of the broadcast sender channel.
    #[get(type(copy))]
    #[set(skip)]
    pub(crate) capacity: usize,
    /// The broadcast type.
    ///
    /// This defines the type of broadcast this WebSocket connection will participate in
    /// (point-to-point or point-to-group).
    #[set(skip)]
    pub(crate) broadcast_type: BroadcastType<B>,
    /// The connected hook handler.
    ///
    /// This hook is executed when the WebSocket connection is established.
    #[set(skip)]
    pub(crate) connected_hook: ServerHookHandler,
    /// The request hook handler.
    ///
    /// This hook is executed when a new request is received on the WebSocket.
    #[set(skip)]
    pub(crate) request_hook: ServerHookHandler,
    /// The sended hook handler.
    ///
    /// This hook is executed after a message has been successfully sent over the WebSocket.
    #[set(skip)]
    pub(crate) sended_hook: ServerHookHandler,
    /// The closed hook handler.
    ///
    /// This hook is executed when the WebSocket connection is closed.
    #[set(skip)]
    pub(crate) closed_hook: ServerHookHandler,
}