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
14const 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#[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
73pub struct Room {
84 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 source_policy_turn: AsyncMutex<()>,
98 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 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 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}