pub struct Broadcaster<K, T>{ /* private fields */ }Expand description
Keyed broadcast channel registry for fan-out SSE delivery.
Each key maps to an independent broadcast channel. All subscribers of a key receive every message sent to that key. Register one broadcaster per domain concept (e.g., chat messages, notifications, metrics).
§Construction
use modo::sse::{Broadcaster, SseConfig};
let chat: Broadcaster<String, ChatMessage> =
Broadcaster::new(128, SseConfig::default());
registry.add(chat);§Channel lifecycle
- Channels are created lazily on first
subscribe() - Channels are auto-cleaned when the last subscriber’s stream is dropped
remove()forces immediate cleanup
Implementations§
Source§impl<K, T> Broadcaster<K, T>
impl<K, T> Broadcaster<K, T>
Sourcepub fn new(buffer: usize, config: SseConfig) -> Self
pub fn new(buffer: usize, config: SseConfig) -> Self
Create a new broadcaster.
buffer— per-channel buffer size. When a subscriber falls behind by this many messages, it lags. Typical values: 64–256 for chat, 16–64 for dashboards.config— SSE configuration (keep-alive interval).
Sourcepub fn subscribe(&self, key: &K) -> BroadcastStream<T>
pub fn subscribe(&self, key: &K) -> BroadcastStream<T>
Subscribe to a keyed channel.
Creates the channel lazily on first subscription. Returns a stream
of raw T values. The stream carries a cleanup closure that removes
the channel entry when the last subscriber drops.
Sourcepub fn send(&self, key: &K, event: T) -> usize
pub fn send(&self, key: &K, event: T) -> usize
Send an event to all subscribers of a key.
Returns the number of receivers that got the message. Returns 0 if no subscribers exist for the key — does NOT create a channel.
Sourcepub fn subscriber_count(&self, key: &K) -> usize
pub fn subscriber_count(&self, key: &K) -> usize
Number of active subscribers for a key. Returns 0 if no channel exists.
Sourcepub fn remove(&self, key: &K)
pub fn remove(&self, key: &K)
Manually remove a channel and disconnect all its subscribers.
Typically not needed — channels auto-clean on last subscriber drop. Use for explicit teardown (e.g., deleting a chat room).
Sourcepub fn channel<F, Fut>(&self, f: F) -> Response
pub fn channel<F, Fut>(&self, f: F) -> Response
Create an SSE response with an imperative sender.
Spawns the closure as a tokio task. The closure receives a super::Sender
for pushing events. The task runs until:
- The closure returns
Ok(())— stream ends cleanly - The closure returns
Err(e)— error is logged, stream ends - A
tx.send()call fails — client disconnected
Panics in the closure are caught and logged.