Skip to main content

o_sfu_core/engine/room/
factory.rs

1//! Room construction for rooms that are new to the runtime directory.
2//!
3//! `RoomManager` owns idempotent lookup, directory publication and creation
4//! diagnostics. This module contains the cold-path allocation step used
5//! after lookup misses, before the new room is visible to other runtime
6//! entrypoints.
7//!
8//! A factory-created room receives fresh process-local placement, the immutable
9//! runtime policy selected at boot, the shared runtime metrics catalog and the
10//! process media transport. It does not register the room or emit creation
11//! events.
12//!
13//! Same-room worker placement is not decided here. The factory
14//! gives a room its stable instance id and primary router id, while
15//! `RoomManager::join_user` assigns workers from packet-loop heartbeat delays
16//! when sessions arrive.
17
18use std::sync::{Arc, Mutex};
19
20use o_sfu_router::{RouterId, rtp::MediaCapabilities};
21use o_sfu_telemetry::metrics::RuntimeMetrics;
22use o_sfu_transport::MediaTransport;
23use secrecy::SecretSlice;
24
25use super::{Room, RoomRuntimeContext};
26use crate::{
27    RoomInstanceId, RoomMediaLimits, RoomWorkerPolicy, RuntimeFeatureFlags, VideoAdaptationTuning,
28    engine::sync::lock_unpoisoned,
29};
30
31/// admission limits that stay fixed for one room lifetime
32///
33/// this is kept separate from the wider runtime policy because admission is a
34/// narrow concern with its own tests and state checks
35///
36/// the policy is passed into `RoomState` at construction time and then treated
37/// as immutable room configuration
38#[derive(Debug, Clone, Copy, PartialEq, Eq)]
39pub struct RoomAdmissionPolicy {
40    /// maximum number of live users the room accepts at once
41    ///
42    /// replaced connections still consume this budget until the room transition
43    /// finishes and the old live user has been removed
44    ///
45    /// Also bounds absent publisher targets retained per receiver. Present
46    /// members do not consume this pending-intent allowance.
47    pub max_sessions: usize,
48}
49
50impl RoomAdmissionPolicy {
51    #[must_use]
52    pub const fn new(max_sessions: usize) -> Self {
53        Self { max_sessions }
54    }
55}
56
57/// stable runtime policy bundle shared by the room and its state model
58///
59/// this groups the room rules that are fixed for the room lifetime and read by
60/// more than one boundary during join, negotiation and observability work
61#[derive(Debug, Clone, PartialEq, Eq)]
62pub struct RoomRuntimePolicy {
63    /// room-level admission limits enforced by room state
64    pub admission_policy: RoomAdmissionPolicy,
65    /// feature surface the room advertises to clients
66    pub feature_flags: RuntimeFeatureFlags,
67    /// router-native capability baseline used for negotiation and bootstrap
68    pub router_rtp_capabilities: MediaCapabilities,
69    /// same-room local worker-placement policy selected at runtime boot
70    pub room_worker_policy: RoomWorkerPolicy,
71    /// room media activation caps applied by source policy
72    pub media_limits: RoomMediaLimits,
73    /// receiver video adaptation knobs applied by source policy
74    pub video_adaptation_tuning: VideoAdaptationTuning,
75}
76
77impl RoomRuntimePolicy {
78    #[must_use]
79    pub fn new(
80        admission_policy: RoomAdmissionPolicy,
81        feature_flags: RuntimeFeatureFlags,
82        router_rtp_capabilities: MediaCapabilities,
83    ) -> Self {
84        Self {
85            admission_policy,
86            feature_flags,
87            router_rtp_capabilities,
88            room_worker_policy: RoomWorkerPolicy::strict_single_router(),
89            media_limits: RoomMediaLimits::default(),
90            video_adaptation_tuning: VideoAdaptationTuning::default(),
91        }
92    }
93
94    /// return a room policy that uses the provided same-room worker policy
95    #[must_use]
96    pub fn with_room_worker_policy(mut self, room_worker_policy: RoomWorkerPolicy) -> Self {
97        self.room_worker_policy = room_worker_policy;
98        self
99    }
100
101    /// return a room policy that uses the provided media activation limits
102    #[must_use]
103    pub fn with_media_limits(mut self, media_limits: RoomMediaLimits) -> Self {
104        self.media_limits = media_limits;
105        self
106    }
107
108    #[must_use]
109    pub fn with_video_adaptation_tuning(
110        mut self,
111        video_adaptation_tuning: VideoAdaptationTuning,
112    ) -> Self {
113        self.video_adaptation_tuning = video_adaptation_tuning;
114        self
115    }
116}
117
118/// external room config passed in from the http or runtime edge
119///
120/// this type keeps room identity separate from operator-facing knobs and
121/// compatibility toggles that may be chosen per room at creation time
122#[derive(Debug, Clone, PartialEq, Eq)]
123pub struct RoomConfig {
124    /// whether this room should expose WebRTC to clients at all
125    pub web_rtc_enabled: bool,
126    /// compatibility recording address from `/v1/channel`
127    pub recording_address: Option<String>,
128}
129
130impl Default for RoomConfig {
131    fn default() -> Self {
132        Self {
133            web_rtc_enabled: true,
134            recording_address: None,
135        }
136    }
137}
138
139/// Monotonic placement counters assigned by the current process.
140///
141/// Room instance ids and router ids are allocated under one lock so every
142/// new room receives one coherent runtime placement. The counters are not a
143/// distributed identity source and must not leak into the Odoo-facing room
144/// contract.
145#[derive(Debug)]
146struct RoomRuntimeAllocator {
147    next_room_instance_id: u64,
148    /// Next router id to allocate for room-local topology.
149    ///
150    /// Room creation consumes one primary router id. Dynamic spillover
151    /// placement consumes additional router ids when sessions join.
152    next_router_id: u64,
153}
154
155/// Cold-path constructor for rooms that are new to the directory.
156///
157/// `RoomFactory` keeps runtime-wide creation dependencies behind the manager
158/// so `RoomManager::serve_room` can focus on idempotent lookup and
159/// publication. Each call to [`Self::create`] returns an unpublished
160/// [`Room`] with fresh process-local placement. The caller must insert it in
161/// the directory before exposing it to other runtime entrypoints.
162#[derive(Debug)]
163pub(crate) struct RoomFactory {
164    /// Validated boot-time room rules that each new room copies.
165    runtime_policy: RoomRuntimePolicy,
166    /// Process metric catalog cloned into each room.
167    metrics: Arc<RuntimeMetrics>,
168    /// Process media transport cloned into each room.
169    media_transport: MediaTransport,
170    /// Serialized allocator for process-local placement ids.
171    ///
172    /// This keeps concurrent create requests from receiving the same runtime
173    /// placement.
174    allocator: Mutex<RoomRuntimeAllocator>,
175}
176
177impl RoomFactory {
178    /// Builds the factory for one [`RoomManager`](super::RoomManager) lifetime.
179    #[must_use]
180    pub(crate) fn new(
181        runtime_policy: RoomRuntimePolicy,
182        metrics: Arc<RuntimeMetrics>,
183        media_transport: MediaTransport,
184    ) -> Self {
185        Self {
186            runtime_policy,
187            metrics,
188            media_transport,
189            allocator: Mutex::new(RoomRuntimeAllocator {
190                next_room_instance_id: 0,
191                next_router_id: 0,
192            }),
193        }
194    }
195
196    /// Creates an unpublished room from one manager lookup miss
197    ///
198    /// The room emits no creation diagnostics. `RoomManager` publishes it
199    /// before emitting its creation event
200    #[must_use]
201    pub(crate) fn create(
202        &self,
203        issuer: &str,
204        key: SecretSlice<u8>,
205        config: &RoomConfig,
206    ) -> Arc<Room> {
207        Arc::new(Room::new(
208            &self.allocate_runtime_context(),
209            &self.runtime_policy,
210            issuer.to_owned(),
211            key,
212            config.clone(),
213            Arc::clone(&self.metrics),
214            self.media_transport.clone(),
215        ))
216    }
217
218    /// Reserves runtime-local placement for one new room.
219    ///
220    /// The primary router id is allocated here, but worker placement remains
221    /// unset until the first session join assigns the room from live load data.
222    ///
223    /// The mutex is poisoned-tolerant because placement allocation has no
224    /// partial side effect beyond the counters themselves. Recovering the inner
225    /// value keeps later room creation possible after an unrelated panic.
226    fn allocate_runtime_context(&self) -> RoomRuntimeContext {
227        let (room_instance_id, primary_router_id) = {
228            let mut allocator = lock_unpoisoned(&self.allocator);
229            let room_instance_id = RoomInstanceId::allocate(&mut allocator.next_room_instance_id);
230            let primary_router_id = RouterId(allocator.next_router_id);
231            allocator.next_router_id = allocator.next_router_id.saturating_add(1);
232            drop(allocator);
233            (room_instance_id, primary_router_id)
234        };
235        RoomRuntimeContext::new(room_instance_id, primary_router_id)
236    }
237
238    /// reserve a new process-unique identifier for a spillover router
239    ///
240    /// this provides the room engine with a thread-safe way to allocate new router
241    /// identities on the fly when media load exceeds the primary worker capacity.
242    /// the allocator lock is held only long enough to increment the counter, keeping
243    /// the cold-path creation from blocking active request loops
244    pub(super) fn allocate_spillover_router(&self) -> RouterId {
245        let mut allocator = lock_unpoisoned(&self.allocator);
246        let router_id = RouterId(allocator.next_router_id);
247        allocator.next_router_id = allocator.next_router_id.saturating_add(1);
248        router_id
249    }
250}