pub struct BroadcastChannel<T> { /* private fields */ }Expand description
Broadcast channel for multi-consumer scenarios.
Uses a shared ring buffer with per-subscriber cursors for memory efficiency. Slowest consumer determines retention. Supports dynamic subscribe/unsubscribe.
§Lock-Free Hot Path
The hot path methods (broadcast, read, slowest_cursor) are completely
lock-free, using only atomic operations on the pre-allocated cursor slots.
This achieves consistent sub-100ns latency without the 5-50μs spikes that
RwLock can cause.
§Type Parameters
T- The event type. Must beClonefor subscribers (typicallyArc<RecordBatch>where clone is an O(1) atomic increment).
§Performance Targets
| Operation | Target |
|---|---|
broadcast() (2 subs) | < 100ns |
broadcast() (4 subs) | < 150ns |
read() | < 50ns |
§Example
use laminar_core::streaming::broadcast::{BroadcastChannel, BroadcastConfig};
let channel = BroadcastChannel::<i32>::new(BroadcastConfig::default());
// Subscribe
let sub1 = channel.subscribe("mv1").unwrap();
let sub2 = channel.subscribe("mv2").unwrap();
// Broadcast
channel.broadcast(42).unwrap();
// Each subscriber receives the value
assert_eq!(channel.read(sub1), Some(42));
assert_eq!(channel.read(sub2), Some(42));Implementations§
Source§impl<T> BroadcastChannel<T>
impl<T> BroadcastChannel<T>
Sourcepub fn new(config: BroadcastConfig) -> Self
pub fn new(config: BroadcastConfig) -> Self
Sourcepub fn slowest_cursor(&self) -> u64
pub fn slowest_cursor(&self) -> u64
Returns the slowest cursor position among active subscribers.
Lock-free: Only uses atomic loads, no locks.
Returns u64::MAX if there are no active subscribers.
Sourcepub fn subscriber_lag(&self, subscriber_id: usize) -> u64
pub fn subscriber_lag(&self, subscriber_id: usize) -> u64
Returns the lag (unread messages) for a subscriber.
Lock-free: Only uses atomic loads, no locks.
Returns 0 if the subscriber ID is out of bounds or inactive.
Sourcepub fn subscriber_count(&self) -> usize
pub fn subscriber_count(&self) -> usize
Returns the number of active subscribers.
Lock-free: Returns the atomically-maintained count.
Sourcepub fn is_lagging(&self, subscriber_id: usize) -> bool
pub fn is_lagging(&self, subscriber_id: usize) -> bool
Returns true if the subscriber is lagging beyond the warning threshold.
Lock-free: Only uses atomic loads.
Sourcepub fn write_position(&self) -> u64
pub fn write_position(&self) -> u64
Returns the current write position.
Sourcepub fn config(&self) -> &BroadcastConfig
pub fn config(&self) -> &BroadcastConfig
Returns the configuration.
Sourcepub fn close(&self)
pub fn close(&self)
Closes the channel.
After closing, broadcast() returns Err(Closed) and subscribers
can only read remaining buffered data.
Sourcepub fn subscriber_info(&self, subscriber_id: usize) -> Option<SubscriberInfo>
pub fn subscriber_info(&self, subscriber_id: usize) -> Option<SubscriberInfo>
Sourcepub fn list_subscribers(&self) -> Vec<SubscriberInfo>
pub fn list_subscribers(&self) -> Vec<SubscriberInfo>
Sourcepub fn unsubscribe(&self, subscriber_id: usize)
pub fn unsubscribe(&self, subscriber_id: usize)
Unsubscribes a subscriber.
Lock-free: Only uses atomic store on the slot.
The subscriber’s cursor is deactivated but the slot remains allocated
(can be reused by future subscribers). Subsequent reads with this ID
will return None.
Source§impl<T: Clone> BroadcastChannel<T>
impl<T: Clone> BroadcastChannel<T>
Sourcepub fn broadcast(&self, value: T) -> Result<(), BroadcastError>
pub fn broadcast(&self, value: T) -> Result<(), BroadcastError>
Broadcasts a value to all subscribers.
Lock-free: Only uses atomic operations, no locks on hot path.
Writes the value into the next available slot. All active subscribers
will be able to read this value via read().
§Errors
BroadcastError::NoSubscribersif there are no active subscribersBroadcastError::SlowSubscriberTimeoutif Block policy times outBroadcastError::Closedif the channel is closed
§Safety Contract
Must be called from a single writer thread only. The DAG executor enforces this by assigning exactly one producer per broadcast channel.
Sourcepub fn subscribe(
&self,
name: impl Into<String>,
) -> Result<usize, BroadcastError>
pub fn subscribe( &self, name: impl Into<String>, ) -> Result<usize, BroadcastError>
Registers a new subscriber.
Returns the subscriber ID which can be used with read().
The subscriber ID is the slot index for O(1) direct access on the hot path.
New subscribers start reading from the current write position (they don’t see historical data).
§Errors
Returns BroadcastError::MaxSubscribersReached if all slots are occupied.
§Performance
Uses CAS to claim a slot, then takes write lock for name storage. Should only be called during setup, not on hot path.
§Panics
Panics if the internal lock is poisoned (should not happen in normal use).
Sourcepub fn read(&self, subscriber_id: usize) -> Option<T>
pub fn read(&self, subscriber_id: usize) -> Option<T>
Reads the next value for a subscriber.
Lock-free: Uses direct O(1) array indexing, no locks.
Returns Some(value) if data is available, or None if the subscriber
is caught up with the producer, has been unsubscribed, or the ID is invalid.
§Arguments
subscriber_id- The subscriber’s ID fromsubscribe()
Sourcepub fn try_read(
&self,
subscriber_id: usize,
) -> Result<Option<T>, BroadcastError>
pub fn try_read( &self, subscriber_id: usize, ) -> Result<Option<T>, BroadcastError>
Tries to read without blocking.
Lock-free: Inlined logic, no double-locking.
Returns Ok(Some(value)) if data is available, Ok(None) if caught up,
or Err if the subscriber is invalid or unsubscribed.
§Errors
Returns BroadcastError::SubscriberNotFound if the subscriber ID is invalid
or the subscriber has been unsubscribed.
Trait Implementations§
Source§impl<T> Debug for BroadcastChannel<T>
impl<T> Debug for BroadcastChannel<T>
impl<T: Send> Send for BroadcastChannel<T>
impl<T: Send> Sync for BroadcastChannel<T>
Auto Trait Implementations§
impl<T> !Freeze for BroadcastChannel<T>
impl<T> !RefUnwindSafe for BroadcastChannel<T>
impl<T> Unpin for BroadcastChannel<T>
impl<T> UnwindSafe for BroadcastChannel<T>where
T: UnwindSafe,
Blanket Implementations§
Source§impl<T> ArchivePointee for T
impl<T> ArchivePointee for T
Source§type ArchivedMetadata = ()
type ArchivedMetadata = ()
Source§fn pointer_metadata(
_: &<T as ArchivePointee>::ArchivedMetadata,
) -> <T as Pointee>::Metadata
fn pointer_metadata( _: &<T as ArchivePointee>::ArchivedMetadata, ) -> <T as Pointee>::Metadata
Source§impl<T> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
Source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
Source§impl<T> Instrument for T
impl<T> Instrument for T
Source§fn instrument(self, span: Span) -> Instrumented<Self>
fn instrument(self, span: Span) -> Instrumented<Self>
Source§fn in_current_span(self) -> Instrumented<Self>
fn in_current_span(self) -> Instrumented<Self>
Source§impl<T> LayoutRaw for T
impl<T> LayoutRaw for T
Source§fn layout_raw(_: <T as Pointee>::Metadata) -> Result<Layout, LayoutError>
fn layout_raw(_: <T as Pointee>::Metadata) -> Result<Layout, LayoutError>
Source§impl<T, N1, N2> Niching<NichedOption<T, N1>> for N2
impl<T, N1, N2> Niching<NichedOption<T, N1>> for N2
Source§unsafe fn is_niched(niched: *const NichedOption<T, N1>) -> bool
unsafe fn is_niched(niched: *const NichedOption<T, N1>) -> bool
Source§fn resolve_niched(out: Place<NichedOption<T, N1>>)
fn resolve_niched(out: Place<NichedOption<T, N1>>)
out indicating that a T is niched.