Skip to main content

o_sfu_core/engine/room/
membership.rs

1//! Membership commit and effect boundary.
2//!
3//! [`JoinCommit`], [`ConnectionCloseCommit`] and
4//! [`DisconnectCommit`](crate::engine::room::state::DisconnectCommit) capture
5//! authoritative membership changes and the work consumed by [`RoomEffects`].
6//! Effects execute after the room-state write guard is released.
7
8use o_sfu_model::{UserId, UserInfo, UserPermissions};
9use o_sfu_telemetry::schema::event as telemetry_event;
10use o_sfu_transport::TransportSessionKey;
11use tracing::{info, warn};
12
13use super::{
14    BroadcastPayloadError, Room, UserOutboundSender, effects::batch::RoomEffects,
15    state::ConnectionCloseCommit,
16};
17use crate::{ConnectionId, MediaWorkerId, engine::room::state::JoinCommit};
18
19#[derive(Debug, Clone, Copy, PartialEq, Eq)]
20pub enum UserCloseReason {
21    Replaced,
22    RemovedByRuntime,
23}
24
25/// Existing users replace their current connection without consuming another admission slot.
26pub struct JoinUserRequest {
27    pub user_id: UserId,
28    /// Ignored by room admission.
29    pub label: Option<String>,
30    /// Ignored by room admission.
31    pub permissions: UserPermissions,
32    pub sender: UserOutboundSender,
33    /// Whether the client accepts a consumer MID that later names another
34    /// consumer. Ignored by room admission.
35    pub mid_reuse: bool,
36}
37
38impl Room {
39    /// Executes the join's [`RoomEffects`] before returning the committed transport key
40    pub(super) async fn finalize_admission(&self, commit: JoinCommit) -> TransportSessionKey {
41        let transport_session_key = commit.transport_session_key.clone();
42        RoomEffects::from(commit).execute(self).await;
43        let session = &transport_session_key;
44        info!(
45            event = telemetry_event::USER_JOINED,
46            room_id = self.uuid(),
47            user_id = %session.user_id().path_segment(),
48            connection_id = session.connection_id().as_u64(),
49            media_worker_id = session.media_worker_id().as_usize(),
50            "user joined room"
51        );
52        transport_session_key
53    }
54
55    /// Returns `true` only when `connection_id` was current. A stale committed
56    /// placement may still be retired before returning `false`.
57    pub(super) async fn remove_user(&self, user_id: &UserId, connection_id: ConnectionId) -> bool {
58        let Some(commit) = self
59            .state
60            .write()
61            .await
62            .close_connection(user_id, connection_id)
63        else {
64            return false;
65        };
66        if let ConnectionCloseCommit::Current { evictions, .. } = &commit {
67            self.metrics
68                .record_subscription_intent_evictions(*evictions);
69        }
70        let (removed_current_user, media_worker_id) = match &commit {
71            ConnectionCloseCommit::Current {
72                session_teardown, ..
73            } => (
74                true,
75                session_teardown
76                    .as_ref()
77                    .map(|teardown| teardown.session_key().media_worker_id()),
78            ),
79            ConnectionCloseCommit::StalePlacement { .. } => (false, None),
80        };
81        RoomEffects::from(commit).execute(self).await;
82        if removed_current_user {
83            info!(
84                event = telemetry_event::USER_CLOSED,
85                room_id = self.uuid(),
86                user_id = %user_id.path_segment(),
87                connection_id = connection_id.as_u64(),
88                media_worker_id = media_worker_id.map(MediaWorkerId::as_usize),
89                "user closed"
90            );
91        }
92        removed_current_user
93    }
94
95    /// Captures recipients in the state snapshot that validates `connection_id`
96    /// as current for `sender_id`. Missing or stale senders are ignored.
97    ///
98    /// # Errors
99    ///
100    /// Returns [`BroadcastPayloadError`] when the payload exceeds the room
101    /// broadcast byte limit or cannot be measured as serialized JSON.
102    pub(crate) async fn broadcast(
103        &self,
104        sender_id: &UserId,
105        connection_id: ConnectionId,
106        message: serde_json::Value,
107    ) -> Result<(), BroadcastPayloadError> {
108        let fanout = {
109            let state = self.state.read().await;
110            state.broadcast_fanout(sender_id, connection_id, message)
111        }?;
112        if let Some(fanout) = fanout {
113            fanout.emit();
114        }
115        Ok(())
116    }
117
118    pub(crate) async fn has_connection(
119        &self,
120        user_id: &UserId,
121        connection_id: ConnectionId,
122    ) -> bool {
123        self.state.read().await.user_connection_id(user_id) == Some(connection_id)
124    }
125
126    /// Ignores missing or stale connections. Publication transitions remain
127    /// authoritative for camera and screen-sharing presence.
128    pub(crate) async fn update_user_info(
129        &self,
130        user_id: &UserId,
131        connection_id: ConnectionId,
132        mut info: UserInfo,
133    ) {
134        info.is_camera_on = None;
135        info.is_screen_sharing_on = None;
136        let commit = {
137            let mut state = self.state.write().await;
138            state.apply_presence_update(user_id, connection_id, &info)
139        };
140        if let Some(commit) = commit {
141            RoomEffects::from(commit).execute(self).await;
142        } else {
143            warn!(
144                ?user_id,
145                connection_id = ?connection_id,
146                ?info,
147                "user info update was rejected by room state"
148            );
149        }
150    }
151
152    /// Removes current sessions in one state commit and ignores missing users.
153    ///
154    /// Returns the number of sessions actually torn down.
155    ///
156    /// # Panics
157    ///
158    /// Panics if a current room user has no committed router placement.
159    pub(super) async fn disconnect_users(&self, user_ids: &[UserId]) -> usize {
160        let commit = self.state.write().await.apply_disconnect_users(user_ids);
161        self.metrics
162            .record_subscription_intent_evictions(commit.evictions);
163        let sessions = commit
164            .session_teardowns
165            .iter()
166            .map(|teardown| teardown.session_key().clone())
167            .collect::<Vec<_>>();
168        RoomEffects::from(commit).execute(self).await;
169        for session in &sessions {
170            info!(
171                event = telemetry_event::USER_DISCONNECTED,
172                room_id = self.uuid(),
173                user_id = %session.user_id().path_segment(),
174                connection_id = session.connection_id().as_u64(),
175                media_worker_id = session.media_worker_id().as_usize(),
176                "user disconnected"
177            );
178        }
179        sessions.len()
180    }
181}