Skip to main content

o_sfu_core/engine/room/
instance.rs

1use std::{fmt, sync::Arc};
2
3use o_sfu_model::{AvailableFeatures, PeerSnapshot, RecordingState, UserId};
4use o_sfu_telemetry::metrics::RuntimeMetrics;
5use o_sfu_transport::MediaTransport;
6use secrecy::{ExposeSecret, SecretSlice};
7use subtle::ConstantTimeEq;
8use tokio::sync::{Mutex as AsyncMutex, MutexGuard, RwLock};
9use uuid::Uuid;
10
11use super::{RoomConfig, RoomRuntimeContext, RoomRuntimePolicy, state::RoomState};
12use crate::{MediaWorkerId, RoomInstanceId, RoomWorkerPolicy, RuntimeFeatureFlags};
13
14/// Central gate for exposing recording as a production room capability.
15///
16/// This must become true only when accepted recording controls can produce the
17/// promised persistent artifact or handoff.
18const fn persistent_recording_backend_available() -> bool {
19    false
20}
21
22#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
23pub enum RoomJoinError {
24    #[error("room is full")]
25    RoomFull,
26    #[error("no usable media worker")]
27    NoUsableWorker,
28    #[error("router state error")]
29    RouterState,
30}
31
32#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
33pub enum RoomManagerJoinError {
34    #[error("room not found")]
35    MissingRoom,
36    #[error("room is full")]
37    RoomFull,
38    #[error("no usable media worker")]
39    NoUsableWorker,
40    #[error("router state error")]
41    RouterState,
42}
43
44#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
45pub enum RoomManagerServeError {
46    #[error("conflicting room reservation")]
47    ConflictingReservation,
48}
49
50#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
51pub struct RoomMediaCounts {
52    pub publications: usize,
53    pub subscriptions: usize,
54}
55
56/// Holds publication and source-policy ordering for one room.
57///
58/// Guarded effects derive their room from this guard so another room's lock
59/// cannot authorize them. Keep the guard across each state commit and its
60/// effects, including every publication resolved by one answer.
61#[must_use = "dropping this guard releases source-policy ordering"]
62pub(in crate::engine) struct SourcePolicyGuard<'a> {
63    room: &'a Room,
64    _lock: MutexGuard<'a, ()>,
65}
66
67impl SourcePolicyGuard<'_> {
68    pub const fn room(&self) -> &Room {
69        self.room
70    }
71}
72
73/// One room lifetime, known by two identities fixed at construction:
74///
75/// ```text
76/// Odoo-facing identity        Runtime-local placement
77/// issuer, uuid, key           instance, router, media worker
78/// ```
79///
80/// The first identity is visible at the HTTP and websocket edge. The second
81/// is process-local and drives transport ownership, diagnostics and room
82/// topology. Committed membership and routing live in `state`.
83pub struct Room {
84    /// Recreating a room for the same issuer allocates a fresh instance id so
85    /// stale transport work cannot be confused with the new room lifetime.
86    instance_id: RoomInstanceId,
87    uuid: String,
88    issuer: String,
89    key: SecretSlice<u8>,
90    pub(super) config: RoomConfig,
91    feature_flags: RuntimeFeatureFlags,
92    worker_policy: RoomWorkerPolicy,
93    pub(in crate::engine) metrics: Arc<RuntimeMetrics>,
94    pub(crate) media_transport: MediaTransport,
95    /// Serializes publication commits and activity changes with source-policy
96    /// turns so their transport effects cannot overtake each other.
97    source_policy_turn: AsyncMutex<()>,
98    /// Code outside `engine` reads through `Room` methods that drop the read
99    /// guard before returning.
100    pub(in crate::engine) state: RwLock<RoomState>,
101}
102
103impl Room {
104    pub(super) fn new(
105        runtime_context: &RoomRuntimeContext,
106        runtime_policy: &RoomRuntimePolicy,
107        issuer: String,
108        key: SecretSlice<u8>,
109        config: RoomConfig,
110        metrics: Arc<RuntimeMetrics>,
111        media_transport: MediaTransport,
112    ) -> Self {
113        Self {
114            instance_id: runtime_context.instance(),
115            uuid: Uuid::new_v4().to_string(),
116            issuer,
117            key,
118            config,
119            feature_flags: runtime_policy.feature_flags,
120            worker_policy: runtime_policy.room_worker_policy,
121            metrics,
122            media_transport,
123            source_policy_turn: AsyncMutex::new(()),
124            state: RwLock::new(RoomState::new(
125                runtime_context,
126                runtime_policy.admission_policy,
127                runtime_policy.media_limits,
128                runtime_policy.video_adaptation_tuning,
129                runtime_policy.router_rtp_capabilities.clone(),
130            )),
131        }
132    }
133
134    /// Serializes publication commits and effects with source-policy turns.
135    ///
136    /// Call guarded operations while this guard is held. Acquiring another
137    /// source-policy guard for this room before releasing it would deadlock.
138    pub(in crate::engine) async fn lock_source_policy(&self) -> SourcePolicyGuard<'_> {
139        SourcePolicyGuard {
140            room: self,
141            _lock: self.source_policy_turn.lock().await,
142        }
143    }
144
145    #[must_use]
146    pub fn uuid(&self) -> &str {
147        &self.uuid
148    }
149
150    #[must_use]
151    pub fn issuer(&self) -> &str {
152        &self.issuer
153    }
154
155    #[must_use]
156    pub fn key(&self) -> &SecretSlice<u8> {
157        &self.key
158    }
159
160    #[must_use]
161    pub(super) fn matches_reservation(&self, key: &SecretSlice<u8>, config: &RoomConfig) -> bool {
162        // Reservation comparison must not stop at the first differing secret byte.
163        bool::from(self.key.expose_secret().ct_eq(key.expose_secret())) && self.config == *config
164    }
165
166    #[must_use]
167    pub(crate) fn available_features(&self) -> AvailableFeatures {
168        let recording_available =
169            self.config.recording_address.is_some() && persistent_recording_backend_available();
170        AvailableFeatures {
171            rtc: self.config.web_rtc_enabled,
172            transcription: recording_available && self.feature_flags.transcription,
173            audio_recording: recording_available && self.feature_flags.audio_recording,
174            video_recording: recording_available && self.feature_flags.video_recording,
175        }
176    }
177
178    pub async fn recording_state(&self) -> RecordingState {
179        self.state.read().await.recording_state()
180    }
181
182    pub(crate) async fn user_snapshots_except(
183        &self,
184        excluded_user_id: &UserId,
185    ) -> Vec<PeerSnapshot> {
186        self.state
187            .read()
188            .await
189            .user_snapshots_except(excluded_user_id)
190    }
191
192    #[must_use]
193    pub const fn web_rtc_enabled(&self) -> bool {
194        self.config.web_rtc_enabled
195    }
196
197    pub fn worker_policy(&self) -> RoomWorkerPolicy {
198        self.worker_policy
199    }
200
201    #[must_use]
202    pub(crate) const fn instance_id(&self) -> RoomInstanceId {
203        self.instance_id
204    }
205}
206
207impl fmt::Debug for Room {
208    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
209        let media_worker_id = self
210            .state
211            .try_read()
212            .ok()
213            .and_then(|state| state.topology.router().primary_worker())
214            .map(MediaWorkerId::as_usize);
215        formatter
216            .debug_struct("Room")
217            .field("instance_id", &self.instance_id)
218            .field("media_worker_id", &media_worker_id)
219            .field("uuid", &self.uuid)
220            .field("issuer", &self.issuer)
221            .field("web_rtc_enabled", &self.config.web_rtc_enabled)
222            .finish_non_exhaustive()
223    }
224}