Skip to main content

ProtocolCore

Struct ProtocolCore 

Source
pub struct ProtocolCore {
    phase: ProtocolPhase,
    track_bindings: BTreeMap<String, TrackBinding>,
    sticky_replay: StickyReplayState,
    connect_context: Option<ConnectContext>,
    recovery_delay_ms: u32,
    outbound_batch: OutboundBatcher,
    request_tracker: RequestTracker,
}
Expand description

The stored state falls into three groups:

  • session state needed to interpret later protocol messages
  • remembered client intent that should survive reconnects
  • in-flight host work that must be cancelled or resolved during cleanup

Fields§

§phase: ProtocolPhase

Lifecycle and server-driven negotiation state.

§track_bindings: BTreeMap<String, TrackBinding>

Current server-maintained mapping from SDP mid to stream binding metadata.

The map is replaced by track snapshots and trimmed when peers leave. It is runtime state only and is cleared on disconnect or socket loss.

§sticky_replay: StickyReplayState

Latest client intent that must be replayed after a recovered socket is authenticated.

Publication, subscription and local user-info updates are kept here because they describe what the user still wants. One-off broadcasts and request-response operations are not sticky because replaying them later would change their meaning.

§connect_context: Option<ConnectContext>

Saved admission context for the active connection attempt.

Recovery reuses this URL, JWT and optional room to open the next socket. Explicit disconnects, terminal close codes and fresh connects clear or replace it so old credentials cannot revive a stopped session.

§recovery_delay_ms: u32

Delay that will be used for the next recovery retry.

The value is reset after a successful welcome or intentional lifecycle reset. Transient websocket loss consumes the current value when scheduling recovery, then increases it for the following retry.

§outbound_batch: OutboundBatcher

Buffered outbound envelopes waiting for an immediate flush, size limit or batch timer.

The batcher owns only serializable protocol envelopes and the knowledge that a flush timer is pending. The host still owns the actual timer and websocket write side effects emitted as commands.

§request_tracker: RequestTracker

Tracks request-response operations that must resolve exactly once.

Each live request is paired with one timeout timer. Responses and timer callbacks both flow through this tracker so stale, mismatched or racing events cannot resolve the wrong host promise.

Implementations§

Source§

impl ProtocolCore

Source

pub fn new() -> Self

Builds a fresh protocol state machine with no remembered user intent.

Reconnect replay is opt-in through the mutating APIs below, so a new core starts from a fully fresh state instead of assuming any previous room, publication, or subscription state.

Source

pub const fn state(&self) -> ConnectionState

Source

pub fn connect( &mut self, url: impl Into<String>, jwt: impl Into<String>, room: Option<String>, ) -> Vec<Command>

Starts a fresh connection attempt when the current state permits one.

Accepts ConnectionState::Disconnected, ConnectionState::Closed and ConnectionState::Recovering. Calls from ConnectionState::Connecting, ConnectionState::Authenticated and ConnectionState::Connected return no commands without replacing the saved admission context.

This is stricter than a reconnect path: it clears sticky replay and runtime state so a caller switching rooms or credentials cannot accidentally leak the previous user intent into the new connection.

Source

pub fn on_ws_open(&mut self) -> Vec<Command>

Authenticates a newly opened socket with the stored connect context.

Recovery reuses the same JWT and optional room that ProtocolCore::connect captured, which keeps every socket attempt tied to one explicit admission context.

Source

pub fn on_ws_message(&mut self, frame: &str) -> Vec<Command>

handle ws message

Malformed batches or envelopes are treated as protocol violations. The whole batch is decoded before any envelope is applied so partially applied server state cannot survive after a later decode error.

Source

fn accept_welcome(&mut self, payload: WelcomePayload) -> Vec<Command>

Source

pub fn on_transport_ready(&mut self) -> Vec<Command>

Marks the local transport layer as ready after the initial negotiation.

The host should call this only once the peer connection is usable for media, because it is what upgrades the core from authenticated signaling state to a fully connected user.

Source

pub fn publish(&mut self, stream_type: StreamType, active: bool) -> Vec<Command>

Stores the desired publication state and sends it when the media transport is ready.

Publish intent is sticky across reconnects, which lets UI toggles be issued before authentication completes without losing the latest desired state.

Source

pub fn subscribe( &mut self, user_id: UserId, states: DownloadStates, ) -> Vec<Command>

Remembers the latest per-peer subscription intent for reconnect replay.

Repeated updates merge at the sticky layer, so callers can send partial audio/camera/screen adjustments without rebuilding the full preference set on every change or after recovery.

Source

pub fn update_info(&mut self, info: UserInfo) -> Vec<Command>

Persists the latest local user metadata patch for the current room.

User info is replayed after reconnect so transient transport failures do not silently reset presence indicators such as mute, hand raise or camera state back to server defaults.

Source

pub fn broadcast(&mut self, message: JsonPayload) -> Vec<Command>

Sends a best-effort broadcast to the current room.

Broadcast payloads are not sticky: if the client is not yet authenticated, the message is dropped instead of being replayed later out of its original conversational context.

Source

pub fn start_recording(&mut self, options: RecordingOptions) -> Vec<Command>

Source

pub fn stop_recording(&mut self) -> Vec<Command>

Source

pub fn submit_negotiation_answer( &mut self, request_id: &RequestId, kind: NegotiationKind, sdp: impl Into<String>, ) -> Vec<Command>

Replies to the currently pending negotiation request.

The host must echo the exact request_id and kind from Command::ApplyNegotiation; mismatches are ignored so a stale or reordered SDP answer cannot accidentally resolve the wrong negotiation.

Source

pub fn disconnect(&mut self) -> Vec<Command>

Source

pub fn on_ws_close(&mut self, code: u16) -> Vec<Command>

Source

pub fn on_timer(&mut self, timer_id: u32) -> Vec<Command>

Dispatches all timer callbacks through one entry point.

Timer ids are part of the protocol-core contract: recovery, outbound batch flushing, and request timeouts each reserve their own namespace and must be routed back here by the host in the order they fire.

Source

fn enqueue_envelope( &mut self, envelope: Envelope, mode: FlushMode, ) -> Vec<Command>

Source

fn enqueue_client_message( &mut self, message: ClientMessage, mode: FlushMode, ) -> Vec<Command>

Source

fn flush_pending_batch(&mut self, cancel_timer: bool) -> Vec<Command>

Source

fn clear_runtime_state(&mut self)

Source

fn teardown_runtime_state(&mut self) -> Vec<Command>

Tears down runtime state while emitting the cleanup commands the host still owes.

This is used on disconnect and terminal close paths where queued batches, timeout timers, and pending requests must be cancelled explicitly instead of being forgotten inside the pure state machine.

Source

fn clear_sticky_state(&mut self)

Source

fn replay_session_state(&mut self) -> Vec<Command>

Flushes room-level intent immediately after the server snapshot is known.

Source

fn replay_publication_state(&mut self) -> Vec<Command>

Flushes publish intent after the recovered media transport is ready.

Source

fn can_send_client_messages(&self) -> bool

Trait Implementations§

Source§

impl Clone for ProtocolCore

Source§

fn clone(&self) -> ProtocolCore

Returns a duplicate of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for ProtocolCore

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Default for ProtocolCore

Source§

fn default() -> Self

Returns the “default value” for a type. Read more
Source§

impl PartialEq for ProtocolCore

Source§

fn eq(&self, other: &ProtocolCore) -> bool

Tests for self and other values to be equal, and is used by ==.
1.0.0 · Source§

fn ne(&self, other: &Rhs) -> bool

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
Source§

impl Eq for ProtocolCore

Source§

impl StructuralPartialEq for ProtocolCore

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.