pub struct BroadcastHub<T>{ /* private fields */ }Expand description
A typed broadcast hub for WebSocket messages.
T must be Clone (required by tokio::sync::broadcast) and
Serialize so that it can be encoded via crate::codec::Codec.
The hub is cheap to clone — all clones share the same underlying channel and connection counter.
§Example
use ws_kit::hub::BroadcastHub;
use serde::{Serialize, Deserialize};
#[derive(Clone, Serialize, Deserialize, Debug, PartialEq)]
struct Msg { text: String }
let hub = BroadcastHub::<Msg>::new(16);
let mut rx = hub.subscribe();
hub.broadcast(Msg { text: "hello".into() }).unwrap();
assert_eq!(rx.recv().await.unwrap().text, "hello");Implementations§
Source§impl<T> BroadcastHub<T>
impl<T> BroadcastHub<T>
Sourcepub fn from_config(config: &WsConfig) -> Self
pub fn from_config(config: &WsConfig) -> Self
Create a hub from crate::config::WsConfig.
Sourcepub fn broadcast(&self, msg: T) -> Result<usize, WsError>
pub fn broadcast(&self, msg: T) -> Result<usize, WsError>
Broadcast a message to all subscribers.
Returns the number of receivers that received the message.
§Errors
Returns WsError::BroadcastFull if there are no active receivers.
tokio::sync::broadcast does not have a full error — the buffer is a
ring — but to preserve the WsError::BroadcastFull contract we surface
it when send fails due to lack of receivers or lag.
Sourcepub fn try_broadcast(&self, msg: T) -> usize
pub fn try_broadcast(&self, msg: T) -> usize
Try to broadcast, returning Ok(0) when there are no receivers instead
of an error. Useful for fire-and-forget.
Sourcepub fn connection_count(&self) -> u64
pub fn connection_count(&self) -> u64
Current number of tracked connections.
Sourcepub fn increment_connections(&self, max: Option<usize>) -> Result<u64, WsError>
pub fn increment_connections(&self, max: Option<usize>) -> Result<u64, WsError>
Atomically increment the connection counter.
Returns the new count. If max is Some, returns
WsError::TooManyConnections when the limit would be exceeded and
does not increment.
Sourcepub fn decrement_connections(&self) -> u64
pub fn decrement_connections(&self) -> u64
Atomically decrement the connection counter (saturating).
Sourcepub fn receiver_count(&self) -> usize
pub fn receiver_count(&self) -> usize
Number of active receivers.
Source§impl<T> BroadcastHub<T>
impl<T> BroadcastHub<T>
Sourcepub fn with_capacity(capacity: usize) -> Self
pub fn with_capacity(capacity: usize) -> Self
Create hub with explicit capacity tracking (internal).