Skip to main content

o_sfu_core/
sfu.rs

1//! [`SfuCore::admit_user`] returns one [`MediaSession`] per admitted room connection.
2//!
3//! The session sequences offer/answer, publication, subscription, recording and
4//! cleanup without exposing room or transport internals.
5//!
6//! ```text
7//! SfuCore::admit_user -> MediaSession
8//!
9//! establish             -> offer -> answer
10//! publish               -> [offer -> answer]?
11//! deactivate_publication -> cancel pending or suppress committed source
12//! subscribe             -> persist intent and reconcile eligible routes
13//! close                 -> remove only the current connection
14//! ```
15//!
16//! `&mut MediaSession` serializes negotiation. [`MediaSession::publish`] queues
17//! the first intent for each stream while the initial offer awaits its answer.
18//! Media published or consumed while a later offer is out waits in the
19//! transport for the next one. A successful [`MediaSession::answer`] may return
20//! that follow-up offer.
21use std::{collections::BTreeMap, mem::replace, sync::Arc};
22
23use o_sfu_model::{
24    AvailableFeatures, JsonPayload, PeerSnapshot, RecordingOptions, RecordingState, UserId,
25    UserInfo,
26};
27pub use o_sfu_transport::{
28    SessionUploadEncoding as UploadEncoding, SessionUploadSlot as UploadSlot,
29};
30use o_sfu_transport::{
31    TransportAdapterError, TransportMediaId, TransportSessionHealth, TransportSessionKey,
32};
33
34use crate::{
35    ConnectionId,
36    engine::{
37        room::{
38            BroadcastPayloadError, DeactivateIntentOutcome, JoinUserRequest, PublishIntentOutcome,
39            RemoteTrackSnapshot, Room, RoomManager, RoomManagerJoinError,
40        },
41        source_model::{
42            SourceDeactivateIntent, SourcePublishIntent, SourceSubscriptionIntent, UserStreamId,
43        },
44    },
45};
46
47/// One remote track as the client binds it: a room track with the MID of its
48/// consumer media.
49#[derive(Debug, Clone, PartialEq, Eq)]
50pub struct RemoteTrackProjection {
51    pub consumer_mid: String,
52    pub user_id: UserId,
53    pub stream_id: UserStreamId,
54    pub producer_active: bool,
55}
56
57/// Server-authored SDP offer for the client.
58#[derive(Debug, Clone, PartialEq, Eq)]
59pub struct NegotiationOffer {
60    /// send it to the client unchanged
61    pub sdp: String,
62    /// media sections the client may publish after applying the offer
63    pub upload_slots: Vec<UploadSlot>,
64    /// Tracks naming the consumer MIDs this offer adds. Send them before the
65    /// offer so the client knows each new media section when it applies it.
66    pub remote_tracks: Option<Vec<RemoteTrackProjection>>,
67}
68
69/// media-session negotiation phase
70///
71/// queued publishes live beside the offer state so a publish that arrives
72/// while the initial answer is pending waits for it
73#[derive(Debug, Default)]
74enum SessionPhase {
75    /// no initial offer has been created yet
76    #[default]
77    BeforeInitialOffer,
78    /// no offer is awaiting an answer
79    Stable,
80    /// one offer has been sent and must be answered before the next offer
81    WaitingForAnswer(InFlightOffer),
82}
83
84/// in-flight offer state plus mutations deferred until its answer is accepted
85#[derive(Debug)]
86struct InFlightOffer {
87    purpose: SessionOfferPurpose,
88    queued_publishes: BTreeMap<UserStreamId, SourcePublishIntent>,
89    follow_up_renegotiation: bool,
90}
91
92impl SessionPhase {
93    /// Only the initial offer defers a publish. The room accepts one once the
94    /// initial answer gives it the client capabilities, and until then the
95    /// transport declares media without negotiation. Behind a later offer the
96    /// transport queues the media for the next one.
97    fn can_stage_publish(&self) -> bool {
98        !matches!(
99            self,
100            Self::WaitingForAnswer(InFlightOffer {
101                purpose: SessionOfferPurpose::EstablishSession,
102                ..
103            })
104        )
105    }
106
107    fn has_queued_publish(&self, stream_id: &UserStreamId) -> bool {
108        matches!(
109            self,
110            Self::WaitingForAnswer(pending)
111                if pending.queued_publishes.contains_key(stream_id)
112        )
113    }
114
115    fn queue_publish(&mut self, intent: SourcePublishIntent) {
116        if let Self::WaitingForAnswer(pending) = self {
117            let stream_id = intent.stream_id().clone();
118            pending.queued_publishes.insert(stream_id, intent);
119        }
120    }
121
122    fn remove_queued_publish(&mut self, stream_id: &UserStreamId) -> bool {
123        let Self::WaitingForAnswer(pending) = self else {
124            return false;
125        };
126        pending.queued_publishes.remove(stream_id).is_some()
127    }
128
129    fn clear_queued_publishes(&mut self) {
130        if let Self::WaitingForAnswer(pending) = self {
131            pending.queued_publishes.clear();
132        }
133    }
134
135    fn request_renegotiation(&mut self) -> bool {
136        match self {
137            Self::BeforeInitialOffer => false,
138            Self::Stable => true,
139            Self::WaitingForAnswer(pending) => {
140                pending.follow_up_renegotiation = true;
141                false
142            }
143        }
144    }
145
146    fn mark_follow_up_renegotiation(&mut self) {
147        if let Self::WaitingForAnswer(pending) = self {
148            pending.follow_up_renegotiation = true;
149        }
150    }
151
152    fn wait_for_answer(&mut self, purpose: SessionOfferPurpose) {
153        *self = Self::WaitingForAnswer(InFlightOffer {
154            purpose,
155            queued_publishes: BTreeMap::new(),
156            follow_up_renegotiation: false,
157        });
158    }
159
160    #[expect(
161        clippy::unreachable,
162        reason = "answer validates the phase before awaiting with exclusive session access"
163    )]
164    fn complete_answer(&mut self) -> InFlightOffer {
165        match replace(self, Self::Stable) {
166            Self::WaitingForAnswer(pending) => pending,
167            _ => unreachable!("answer completion requires an in-flight offer"),
168        }
169    }
170}
171
172/// reason an offer is waiting for an answer
173#[derive(Debug)]
174enum SessionOfferPurpose {
175    EstablishSession,
176    RefreshSession,
177}
178
179/// error returned by [`MediaSession`] operations
180#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
181pub enum SessionError {
182    /// [`MediaSession::answer`] was called without an in-flight offer
183    #[error("no pending media request")]
184    NoPendingRequest,
185    /// lower core operation failed or rejected the request
186    #[error(transparent)]
187    Core(#[from] SfuCoreError),
188}
189
190impl SessionError {
191    /// whether the runtime should report the error as a client or protocol fault
192    ///
193    /// transport failures that indicate malformed client input are client
194    /// errors, while infrastructure failures are internal errors
195    #[must_use]
196    pub const fn is_client_error(self) -> bool {
197        match self {
198            Self::NoPendingRequest => true,
199            Self::Core(error) => error.is_client_error(),
200        }
201    }
202}
203
204#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
205pub enum SfuCoreError {
206    /// media transport command failed
207    #[error("transport operation failed")]
208    Transport(#[source] TransportAdapterError),
209    /// accepted answer did not yield client capabilities needed by room state
210    #[error("capability projection failed")]
211    CapabilityProjection(#[source] TransportAdapterError),
212    /// initial answer was valid transport input but stale for room state
213    #[error("session negotiation rejected")]
214    SessionNegotiationRejected,
215    /// refresh answer was valid transport input but stale for room state
216    #[error("session refresh rejected")]
217    SessionRefreshRejected,
218    /// subscription intent targeted a stale or invalid room connection
219    #[error("subscription update rejected")]
220    SubscriptionUpdateRejected,
221}
222
223impl SfuCoreError {
224    /// whether this error should close the client as a protocol fault
225    #[must_use]
226    pub const fn is_client_error(self) -> bool {
227        matches!(
228            self,
229            // Dependency rejection is still a protocol fault even though it now
230            // closes the RTC session before returning to the signaling layer.
231            Self::Transport(
232                TransportAdapterError::InvalidInput
233                    | TransportAdapterError::AnswerApplicationFailed
234            ) | Self::CapabilityProjection(_)
235                | Self::SessionNegotiationRejected
236                | Self::SessionRefreshRejected
237                | Self::SubscriptionUpdateRejected
238        )
239    }
240}
241
242/// A cloneable core handle that admits users into room-bound [`MediaSession`]s.
243///
244/// Sessions reach the transport through their room, so one session cannot
245/// negotiate on a transport other than the one applying its room effects.
246#[derive(Debug, Clone)]
247pub struct SfuCore {
248    rooms: Arc<RoomManager>,
249}
250
251/// One admitted user connection in one room.
252///
253/// Room mutations revalidate the connection before committing room state.
254/// [`close`](Self::close) cannot remove a replacement connection and drains
255/// connection-scoped staged media when this session is current.
256///
257/// Futures returned by [`establish`](Self::establish), [`answer`](Self::answer),
258/// [`publish`](Self::publish),
259/// [`deactivate_publication`](Self::deactivate_publication),
260/// [`renegotiate`](Self::renegotiate), [`subscribe`](Self::subscribe),
261/// [`update_info`](Self::update_info) and [`close`](Self::close) are not
262/// cancellation safe. Once polled, await them to completion. Negotiation can
263/// otherwise leave room and transport state out of step with the local phase.
264/// Other mutations can leave committed room state without its transport or
265/// output effects.
266///
267/// Call [`close`](Self::close) before dropping the session. `Drop` performs no
268/// room or transport cleanup.
269#[derive(Debug)]
270pub struct MediaSession {
271    core: SfuCore,
272    room: Arc<Room>,
273    transport_user_key: TransportSessionKey,
274    phase: SessionPhase,
275    /// Newest tracks the room gave this connection.
276    tracks: RemoteTrackSnapshot,
277    /// MIDs of this connection's consumer media. Each offer replaces the map,
278    /// so a consumer queued since the last offer has none until the next one.
279    consumer_mids: BTreeMap<TransportMediaId, String>,
280    /// Tracks last handed to the caller, each with the consumer it names.
281    delivered_tracks: Vec<(TransportMediaId, RemoteTrackProjection)>,
282    /// Whether the client accepts a consumer MID that later names another
283    /// consumer.
284    mid_reuse: bool,
285    closed: bool,
286}
287
288impl SfuCore {
289    #[must_use]
290    pub const fn new(rooms: Arc<RoomManager>) -> Self {
291        Self { rooms }
292    }
293
294    /// Admits one room user and returns its connection-owning media session.
295    ///
296    /// An existing `request.user_id` replaces its current connection.
297    /// Replacement room and transport effects finish before return.
298    /// This future is not cancellation safe. Once polled, await it to completion.
299    /// Dropping it after membership commits can leave room or replacement
300    /// transport effects unfinished.
301    ///
302    /// # Errors
303    ///
304    /// Returns [`RoomManagerJoinError::MissingRoom`] when `room_id` is not
305    /// current. Returns [`RoomManagerJoinError::RoomFull`] when a new user
306    /// exceeds room capacity. Returns [`RoomManagerJoinError::NoUsableWorker`]
307    /// when no configured worker is usable. Returns [`RoomManagerJoinError::RouterState`]
308    /// when router placement cannot commit.
309    ///
310    /// # Panics
311    ///
312    /// Panics when existing relay state refers to an uncommitted source
313    /// placement.
314    pub async fn admit_user(
315        &self,
316        room_id: &str,
317        request: JoinUserRequest,
318    ) -> Result<MediaSession, RoomManagerJoinError> {
319        let mid_reuse = request.mid_reuse;
320        let admission = self.rooms.join_user(room_id, request).await?;
321        Ok(MediaSession {
322            core: self.clone(),
323            room: admission.room,
324            transport_user_key: admission.transport_session_key,
325            phase: SessionPhase::default(),
326            tracks: RemoteTrackSnapshot::default(),
327            consumer_mids: BTreeMap::new(),
328            delivered_tracks: Vec::new(),
329            mid_reuse,
330            closed: false,
331        })
332    }
333}
334
335impl MediaSession {
336    /// creates the first browser offer for this connection
337    ///
338    /// returns `Ok(None)` after the initial offer has already been requested
339    /// this lets reconnect or duplicate-start paths retry safely without
340    /// creating a second initial offer
341    ///
342    /// # Errors
343    ///
344    /// returns [`SessionError::Core`] when the transport cannot create the
345    /// initial offer
346    pub async fn establish(&mut self) -> Result<Option<NegotiationOffer>, SessionError> {
347        if !matches!(self.phase, SessionPhase::BeforeInitialOffer) {
348            return Ok(None);
349        }
350        let offer = self
351            .room
352            .media_transport
353            .create_initial_session_offer(
354                self.room.uuid(),
355                &self.transport_user_key,
356                self.mid_reuse,
357            )
358            .await
359            .map_err(SfuCoreError::Transport)?;
360        self.phase
361            .wait_for_answer(SessionOfferPurpose::EstablishSession);
362        // The initial offer precedes every consumer, so it names no track.
363        Ok(Some(NegotiationOffer {
364            sdp: offer.sdp,
365            upload_slots: offer.upload_slots,
366            remote_tracks: None,
367        }))
368    }
369
370    /// accepts the answer for the pending offer and commits any ready room work
371    ///
372    /// a rejection before the worker consumes its pending offer leaves the
373    /// application round in place so a direct caller may retry it
374    /// a str0m rejection after consuming the offer closes the session because
375    /// its transport state cannot be rolled back
376    /// when queued publish intent needs another SDP round the returned offer
377    /// must be sent to the client before the next answer
378    ///
379    /// # Errors
380    ///
381    /// returns [`SessionError::NoPendingRequest`] when no offer is pending
382    /// returns [`SessionError::Core`] when answer application fails, capability
383    /// projection fails or room state rejects the accepted answer as stale
384    pub async fn answer(&mut self, sdp: &str) -> Result<Option<NegotiationOffer>, SessionError> {
385        if !matches!(self.phase, SessionPhase::WaitingForAnswer(_)) {
386            return Err(SessionError::NoPendingRequest);
387        }
388        let applied_answer = match self
389            .room
390            .media_transport
391            .apply_session_answer(&self.transport_user_key, sdp)
392            .await
393        {
394            Ok(answer) => answer,
395            Err(error) => {
396                if error == TransportAdapterError::AnswerApplicationFailed {
397                    self.close().await;
398                }
399                return Err(SfuCoreError::Transport(error).into());
400            }
401        };
402        let InFlightOffer {
403            purpose,
404            queued_publishes,
405            follow_up_renegotiation,
406        } = self.phase.complete_answer();
407        match purpose {
408            SessionOfferPurpose::EstablishSession => {
409                let client_capabilities = applied_answer.client_capabilities().cloned().ok_or(
410                    SfuCoreError::CapabilityProjection(TransportAdapterError::InvalidInput),
411                )?;
412                self.room
413                    .apply_session_negotiated(
414                        self.user_id(),
415                        self.connection_id(),
416                        client_capabilities,
417                        applied_answer.declined_consumers(),
418                    )
419                    .await
420                    .ok_or(SfuCoreError::SessionNegotiationRejected)?;
421            }
422            SessionOfferPurpose::RefreshSession => {
423                self.room
424                    .apply_session_refreshed(
425                        self.user_id(),
426                        self.connection_id(),
427                        applied_answer.declined_consumers(),
428                    )
429                    .await
430                    .ok_or(SfuCoreError::SessionRefreshRejected)?;
431            }
432        }
433        self.room
434            .commit_staged_publishes(self.user_id(), self.connection_id(), &applied_answer)
435            .await;
436        let staged = self.stage_queued_publishes(queued_publishes).await?;
437        if staged || follow_up_renegotiation {
438            return self.renegotiate().await;
439        }
440        Ok(None)
441    }
442
443    /// applies publish intent for one user stream
444    ///
445    /// returns no offer when the intent is already queued, already active or
446    /// must wait for an in-flight answer, whose completion returns the offer
447    /// returns an offer when the browser must answer a new offer before the
448    /// publication can commit
449    ///
450    /// # Errors
451    ///
452    /// returns [`SessionError::Core`] when the media backend cannot stage a
453    /// publish that needs negotiation
454    pub async fn publish(
455        &mut self,
456        intent: SourcePublishIntent,
457    ) -> Result<Option<NegotiationOffer>, SessionError> {
458        if self.phase.has_queued_publish(intent.stream_id()) {
459            return Ok(None);
460        }
461        match self
462            .start_publish(&intent, self.phase.can_stage_publish())
463            .await?
464        {
465            PublishIntentOutcome::Noop | PublishIntentOutcome::Activated => Ok(None),
466            PublishIntentOutcome::Queue => {
467                self.phase.queue_publish(intent);
468                Ok(None)
469            }
470            PublishIntentOutcome::Staged => self.renegotiate().await,
471        }
472    }
473
474    /// deactivates one publication without changing negotiated media
475    ///
476    /// a queued first publication is cancelled
477    /// a staged first publication is rolled back and its pending answer creates
478    /// the cleanup offer
479    /// a committed publication keeps its source identity, routes and negotiated
480    /// MID until session teardown
481    pub async fn deactivate_publication(&mut self, intent: SourceDeactivateIntent) {
482        if self.phase.remove_queued_publish(intent.stream_id()) {
483            return;
484        }
485        match self
486            .room
487            .deactivate_publication(self.user_id(), self.connection_id(), &intent)
488            .await
489        {
490            DeactivateIntentOutcome::RolledBack => {
491                self.phase.mark_follow_up_renegotiation();
492            }
493            DeactivateIntentOutcome::Deactivated | DeactivateIntentOutcome::Noop => {}
494        }
495    }
496
497    /// closes this media session and removes its room connection if still current
498    ///
499    /// the call is idempotent
500    /// it returns `true` only when the room manager removed the current
501    /// connection
502    /// current-session cleanup drains connection-scoped staged media through
503    /// room state
504    /// stale sessions do not remove a replacement connection for the same user
505    pub async fn close(&mut self) -> bool {
506        if self.closed {
507            return false;
508        }
509        self.phase.clear_queued_publishes();
510        let did_close = self
511            .core
512            .rooms
513            .close_session(self.room_id(), self.user_id(), self.connection_id())
514            .await;
515        self.closed = true;
516        did_close
517    }
518
519    /// creates a refresh offer when the stable session needs renegotiation
520    ///
521    /// returns `Ok(None)` before the initial offer, while an answer is pending
522    /// or when the transport reports that the requested refresh is unsupported
523    /// a call made while an answer is pending records that another offer should
524    /// be created after the answer commits
525    ///
526    /// # Errors
527    ///
528    /// returns [`SessionError::Core`] when the transport rejects
529    /// renegotiation
530    pub async fn renegotiate(&mut self) -> Result<Option<NegotiationOffer>, SessionError> {
531        if !self.phase.request_renegotiation() {
532            return Ok(None);
533        }
534        let (offer, tracks) = match self
535            .room
536            .create_renegotiation_offer(&self.transport_user_key)
537            .await
538        {
539            Ok(offer) => offer,
540            Err(TransportAdapterError::UnsupportedFeature) => return Ok(None),
541            Err(error) => return Err(SfuCoreError::Transport(error).into()),
542        };
543        self.phase
544            .wait_for_answer(SessionOfferPurpose::RefreshSession);
545        // The offer adds only consumers of `tracks`, so the tracks named from
546        // both cover every MID it adds.
547        self.tracks = tracks;
548        self.consumer_mids = offer.consumer_mids.into_iter().collect();
549        Ok(Some(NegotiationOffer {
550            sdp: offer.sdp,
551            upload_slots: offer.upload_slots,
552            remote_tracks: self.named_tracks(),
553        }))
554    }
555
556    /// Adopts a track snapshot the room queued and returns the tracks to give
557    /// the client, or `None` when it already has them.
558    ///
559    /// The tracks read for an offer skip the room queue, so a snapshot built
560    /// before that read can still be queued. It is dropped because the offer's
561    /// tracks are newer.
562    pub fn fresh_remote_tracks(
563        &mut self,
564        snapshot: RemoteTrackSnapshot,
565    ) -> Option<Vec<RemoteTrackProjection>> {
566        if snapshot.revision <= self.tracks.revision {
567            return None;
568        }
569        self.tracks = snapshot;
570        self.named_tracks()
571    }
572
573    /// Returns the room tracks whose consumer media has a MID, or `None` when
574    /// the caller already has them.
575    ///
576    /// The room knows the tracks and each offer brings the MIDs, so a track is
577    /// named only here. One without a MID waits for the offer that adds its
578    /// consumer media.
579    ///
580    /// A MID outlives its consumer, so a reconnected user's track can equal
581    /// the one delivered for its previous connection. The client dropped that
582    /// binding when the user left. Tracks are therefore compared with the
583    /// consumer they name.
584    fn named_tracks(&mut self) -> Option<Vec<RemoteTrackProjection>> {
585        let named = self
586            .tracks
587            .tracks
588            .iter()
589            .filter_map(|track| {
590                let projection = RemoteTrackProjection {
591                    consumer_mid: self.consumer_mids.get(&track.consumer_media)?.clone(),
592                    user_id: track.user_id.clone(),
593                    stream_id: track.stream_id.clone(),
594                    producer_active: track.producer_active,
595                };
596                Some((track.consumer_media, projection))
597            })
598            .collect::<Vec<_>>();
599        if named == self.delivered_tracks {
600            return None;
601        }
602        let tracks = named.iter().map(|(_, track)| track.clone()).collect();
603        self.delivered_tracks = named;
604        Some(tracks)
605    }
606
607    /// applies receiver intent for sources published by another user
608    ///
609    /// subscription intent is remembered even when no producer is currently
610    /// routable
611    /// once negotiation makes the receiver consumable, room effects create the
612    /// missing consumer routes
613    ///
614    /// # Errors
615    ///
616    /// returns [`SessionError::Core`] when room state rejects this connection
617    /// as stale
618    pub async fn subscribe(
619        &self,
620        target_user_id: &UserId,
621        intents: &BTreeMap<UserStreamId, SourceSubscriptionIntent>,
622    ) -> Result<(), SessionError> {
623        self.room
624            .apply_receiver_intent(
625                self.user_id(),
626                self.connection_id(),
627                target_user_id,
628                intents,
629            )
630            .await
631            .ok_or(SfuCoreError::SubscriptionUpdateRejected)?;
632        Ok(())
633    }
634
635    /// returns `None` when the transport has no endpoint for this session key
636    #[must_use]
637    pub fn endpoint_health(&self) -> Option<TransportSessionHealth> {
638        self.room
639            .media_transport
640            .session_transport_health(&self.transport_user_key)
641    }
642
643    #[must_use]
644    pub fn user_id(&self) -> &UserId {
645        self.transport_user_key.user_id()
646    }
647
648    #[must_use]
649    pub const fn connection_id(&self) -> ConnectionId {
650        self.transport_user_key.connection_id()
651    }
652
653    #[must_use]
654    pub fn room_id(&self) -> &str {
655        self.room.uuid()
656    }
657
658    pub async fn is_current_connection(&self) -> bool {
659        self.room
660            .has_connection(self.user_id(), self.connection_id())
661            .await
662    }
663
664    #[must_use]
665    pub fn available_features(&self) -> AvailableFeatures {
666        self.room.available_features()
667    }
668
669    pub async fn recording_state(&self) -> RecordingState {
670        self.room.recording_state().await
671    }
672
673    /// Returns snapshots for current room users other than this session's user.
674    pub async fn peer_snapshots(&self) -> Vec<PeerSnapshot> {
675        self.room.user_snapshots_except(self.user_id()).await
676    }
677
678    async fn start_publish(
679        &self,
680        intent: &SourcePublishIntent,
681        can_stage: bool,
682    ) -> Result<PublishIntentOutcome, SfuCoreError> {
683        self.room
684            .start_publish(self.user_id(), self.connection_id(), intent, can_stage)
685            .await
686            .map_err(SfuCoreError::Transport)
687    }
688
689    /// Updates user information for this room connection.
690    ///
691    /// Missing or stale connections are ignored. `is_camera_on` and
692    /// `is_screen_sharing_on` are derived from publication state and discarded
693    /// from `info`.
694    pub async fn update_info(&self, info: UserInfo) {
695        self.room
696            .update_user_info(self.user_id(), self.connection_id(), info)
697            .await;
698    }
699
700    /// Broadcasts `message` to every other current room user.
701    ///
702    /// Missing or stale sender connections return `Ok(())` without delivery.
703    ///
704    /// # Errors
705    ///
706    /// Returns [`BroadcastPayloadError::TooLarge`] when the serialized payload
707    /// exceeds the room broadcast limit. Returns
708    /// [`BroadcastPayloadError::JsonSerialization`] when JSON serialization
709    /// fails.
710    pub async fn broadcast(&self, message: JsonPayload) -> Result<(), BroadcastPayloadError> {
711        self.room
712            .broadcast(self.user_id(), self.connection_id(), message)
713            .await
714    }
715
716    /// Rejects recording start because no persistent recording backend is enabled.
717    ///
718    /// `options` has no effect. The request records a rejection and returns
719    /// `false`.
720    #[must_use]
721    #[expect(
722        clippy::unused_async,
723        reason = "keeps the public MediaSession recording facade async while disabled recording is synchronous"
724    )]
725    pub async fn start_recording(&self, options: RecordingOptions) -> bool {
726        self.room
727            .apply_recording_start(self.user_id(), self.connection_id(), options)
728    }
729
730    /// Rejects recording stop because no persistent recording backend is enabled.
731    ///
732    /// The request records a rejection and returns `false`.
733    #[must_use]
734    #[expect(
735        clippy::unused_async,
736        reason = "keeps the public MediaSession recording facade async while disabled recording is synchronous"
737    )]
738    pub async fn stop_recording(&self) -> bool {
739        self.room
740            .apply_recording_stop(self.user_id(), self.connection_id())
741    }
742
743    async fn stage_queued_publishes(
744        &self,
745        queued: BTreeMap<UserStreamId, SourcePublishIntent>,
746    ) -> Result<bool, SessionError> {
747        let mut staged = false;
748        for intent in queued.into_values() {
749            if self.start_publish(&intent, true).await? == PublishIntentOutcome::Staged {
750                staged = true;
751            }
752        }
753        Ok(staged)
754    }
755}