Skip to main content

o_sfu_core/engine/room/transition/
publication.rs

1//! publication transitions keep unnegotiated media out of the room graph
2//!
3//! ```text
4//! publish intent
5//!   |
6//!   +-- existing producer -------> activity commit --> effects after lock
7//!   |
8//!   +-- initial offer in flight -> queued intent ----> answer --> stage
9//!   |
10//!   +-- new producer ------------> StagedPublish ----> answer-proven RTP
11//!                                    |                   |
12//!                                    |                   v
13//!                                    |                 room graph commit
14//!                                    |                   |
15//!                                    v                   v
16//!                               rollback teardown    effects after lock
17//! ```
18//!
19//! A publish staged while a later offer is in flight waits in the transport
20//! for the next offer and stays staged across the answer in between.
21//!
22//! only answer-proven RTP enters the room graph
23//! teardown, worker route updates and fanout run after state mutation releases
24//! the room lock
25
26use o_sfu_model::UserId;
27use o_sfu_router::rtp::MediaStream as RouterRtpParameters;
28use o_sfu_transport::{AppliedSessionAnswer, TransportAdapterError};
29use tracing::warn;
30
31use super::super::{
32    Room, SourcePolicyGuard,
33    effects::batch::PublicationEffects,
34    media_graph::{ProducerActivityCommit, PublishIntentPlan, ValidatedPublish},
35};
36use crate::{
37    ConnectionId,
38    engine::source_model::{SourceDeactivateIntent, SourcePublishIntent, UserStreamId},
39};
40
41mod staging;
42#[cfg(any(test, feature = "testing-transport"))]
43#[path = "publication/TESTS/test_support.rs"]
44mod test_support;
45
46pub use staging::{StagedPublish, StagedPublishes};
47
48#[derive(Debug, Clone, Copy, PartialEq, Eq)]
49pub enum PublishIntentOutcome {
50    Noop,
51    Queue,
52    Activated,
53    Staged,
54}
55
56#[derive(Debug, Clone, Copy, PartialEq, Eq)]
57pub enum DeactivateIntentOutcome {
58    Noop,
59    RolledBack,
60    Deactivated,
61}
62
63#[derive(Debug, Clone, Copy, PartialEq, Eq)]
64pub enum PublishStageOutcome {
65    Staged,
66    Duplicate,
67    DuplicateAfterReservation,
68}
69
70impl Room {
71    async fn stage_validated_publish(
72        &self,
73        validated_descriptor: ValidatedPublish,
74    ) -> Result<PublishStageOutcome, TransportAdapterError> {
75        let session_key = &validated_descriptor.session_key;
76        let is_duplicate = {
77            let state = self.state.read().await;
78            state.staged_publishes.contains(
79                session_key.user_id(),
80                session_key.connection_id(),
81                validated_descriptor.intent.stream_id(),
82            )
83        };
84        if is_duplicate {
85            return Ok(PublishStageOutcome::Duplicate);
86        }
87        let rtp_parameters = RouterRtpParameters::default();
88        let media = match self
89            .media_transport
90            .publish_media(
91                &validated_descriptor.session_key,
92                validated_descriptor.intent.media_kind(),
93                &rtp_parameters,
94            )
95            .await
96        {
97            Ok(media) => media,
98            Err(error) => {
99                warn!(
100                    user_id = ?session_key.user_id(),
101                    connection_id = ?session_key.connection_id(),
102                    stream_id = %validated_descriptor.intent.stream_id(),
103                    media_kind = ?validated_descriptor.intent.media_kind(),
104                    "failed to stage negotiated publish stream"
105                );
106                return Err(error);
107            }
108        };
109        let reserved_publish = StagedPublish::new(validated_descriptor, media);
110        let duplicate = {
111            let mut state = self.state.write().await;
112            // `publish_media` ran without the room lock. Revalidate connection
113            // identity and stream uniqueness before room state accepts it.
114            if state
115                .validate_publish_commit(reserved_publish.descriptor(), reserved_publish.media())
116                .is_some()
117            {
118                state.staged_publishes.stage(reserved_publish)
119            } else {
120                Some(reserved_publish)
121            }
122        };
123        if let Some(duplicate) = duplicate {
124            duplicate.release_reserved_media(self).await;
125            return Ok(PublishStageOutcome::DuplicateAfterReservation);
126        }
127        Ok(PublishStageOutcome::Staged)
128    }
129
130    pub(crate) async fn start_publish(
131        &self,
132        user_id: &UserId,
133        connection_id: ConnectionId,
134        intent: &SourcePublishIntent,
135        can_stage: bool,
136    ) -> Result<PublishIntentOutcome, TransportAdapterError> {
137        let has_staged_publish = {
138            let state = self.state.read().await;
139            state
140                .staged_publishes
141                .contains(user_id, connection_id, intent.stream_id())
142        };
143        if has_staged_publish {
144            return Ok(PublishIntentOutcome::Noop);
145        }
146        let source_policy_guard = self.lock_source_policy().await;
147        let plan = {
148            let mut state = source_policy_guard.room().state.write().await;
149            state.apply_publish_intent(user_id, connection_id, intent, can_stage)
150        };
151        match plan {
152            PublishIntentPlan::Activate(commit) => {
153                // Prevent another source-policy turn from interleaving with this
154                // activity commit and its ordered policy and transport effects.
155                execute_publication_activity(&source_policy_guard, commit).await;
156                drop(source_policy_guard);
157                Ok(PublishIntentOutcome::Activated)
158            }
159            PublishIntentPlan::Noop => {
160                drop(source_policy_guard);
161                Ok(PublishIntentOutcome::Noop)
162            }
163            PublishIntentPlan::Queue => {
164                drop(source_policy_guard);
165                Ok(PublishIntentOutcome::Queue)
166            }
167            PublishIntentPlan::Stage(validated) => {
168                drop(source_policy_guard);
169                if self.stage_validated_publish(validated).await? == PublishStageOutcome::Staged {
170                    Ok(PublishIntentOutcome::Staged)
171                } else {
172                    Ok(PublishIntentOutcome::Noop)
173                }
174            }
175        }
176    }
177
178    pub(crate) async fn rollback_staged_publish(
179        &self,
180        user_id: &UserId,
181        connection_id: ConnectionId,
182        stream_id: &UserStreamId,
183    ) -> bool {
184        let Some(staged) = ({
185            let mut state = self.state.write().await;
186            state
187                .staged_publishes
188                .take(user_id, connection_id, stream_id)
189        }) else {
190            return false;
191        };
192        staged.release_reserved_media(self).await;
193        true
194    }
195
196    pub(crate) async fn deactivate_publication(
197        &self,
198        user_id: &UserId,
199        connection_id: ConnectionId,
200        intent: &SourceDeactivateIntent,
201    ) -> DeactivateIntentOutcome {
202        if self
203            .rollback_staged_publish(user_id, connection_id, intent.stream_id())
204            .await
205        {
206            return DeactivateIntentOutcome::RolledBack;
207        }
208        // Keep publication activity and its policy effects in one serialized
209        // turn so policy cannot observe the state change without its transport work.
210        let source_policy_guard = self.lock_source_policy().await;
211        let commit = {
212            let mut state = source_policy_guard.room().state.write().await;
213            state.apply_publication_activity(
214                user_id,
215                connection_id,
216                intent.stream_id(),
217                false,
218                intent.presence(),
219            )
220        };
221        let Ok(commit) = commit else {
222            return DeactivateIntentOutcome::Noop;
223        };
224        execute_publication_activity(&source_policy_guard, commit).await;
225        drop(source_policy_guard);
226        DeactivateIntentOutcome::Deactivated
227    }
228
229    /// Resolves this connection's staged publishes against an accepted answer.
230    pub(crate) async fn commit_staged_publishes(
231        &self,
232        user_id: &UserId,
233        connection_id: ConnectionId,
234        applied_answer: &AppliedSessionAnswer,
235    ) {
236        // Hold one source-policy turn across the answer batch. Policy must not
237        // observe a committed prefix while later answer-proven publishes remain
238        // outside the room graph.
239        let source_policy_guard = self.lock_source_policy().await;
240        let staged = {
241            let mut state = source_policy_guard.room().state.write().await;
242            state
243                .staged_publishes
244                .take_answered(user_id, connection_id, applied_answer)
245        };
246        for publish in staged {
247            publish
248                .commit_answer_guarded(&source_policy_guard, applied_answer)
249                .await;
250        }
251        drop(source_policy_guard);
252    }
253}
254
255async fn execute_publication_activity(
256    guard: &SourcePolicyGuard<'_>,
257    commit: ProducerActivityCommit,
258) {
259    PublicationEffects::from(commit).execute(guard).await;
260}
261
262#[cfg(test)]
263#[path = "TESTS/publication.rs"]
264mod tests;