Skip to main content

o_sfu_core/engine/room/manager/
mod.rs

1//! Current-room registry and lifecycle coordinator.
2//!
3//! [`RoomManager`] publishes one current room per requester address and
4//! issuer, admits WebSocket sessions and runs background room work. Lease
5//! admission holds the directory read guard to prove currentness and releases
6//! it before room work begins. Empty-room removal waits for every accepted
7//! lease to finish.
8
9use std::{
10    cmp::Reverse,
11    collections::{BTreeMap, BTreeSet},
12    future::Future,
13    net::IpAddr,
14    sync::Arc,
15    time::Duration,
16};
17
18use futures_util::{
19    FutureExt, StreamExt,
20    future::try_join_all,
21    stream::{self, BoxStream, FuturesUnordered},
22};
23use o_sfu_model::UserId;
24use o_sfu_telemetry::{
25    metrics::{RoomGaugeValues, RuntimeMetrics},
26    schema::event as telemetry_event,
27};
28use o_sfu_transport::{
29    ActiveSpeakerSource, MediaTransport, TransportAdapterError, TransportSessionKey,
30};
31use secrecy::SecretSlice;
32use tokio::sync::{RwLock, Semaphore};
33use tracing::{info, warn};
34
35use super::{
36    Room, RoomConfig, RoomJoinError, RoomManagerJoinError, RoomRuntimePolicy,
37    RoomUserStatsSnapshot,
38    directory::{RoomDirectory, RoomDirectoryEntry, RoomLifecycleLease},
39    factory::RoomFactory,
40    membership::JoinUserRequest,
41};
42use crate::{
43    ConnectionId, RoomInstanceId,
44    engine::{
45        director,
46        director::SourcePolicyTurn,
47        room::{
48            directory::{ExpiryReason, RoomRemovalPolicy},
49            instance::RoomManagerServeError,
50        },
51    },
52};
53
54#[cfg(any(test, feature = "testing-transport"))]
55#[path = "TESTS/test_support.rs"]
56mod test_support;
57
58const SOURCE_POLICY_CONCURRENCY: usize = 8;
59
60/// operator-facing room stats assembled from directory and transport snapshots
61#[derive(Debug, Clone, PartialEq, Eq)]
62pub struct RuntimeRoomStatsSnapshot {
63    /// room publication timestamp in RFC 3339 UTC format
64    pub create_date: String,
65    /// room uuid returned by `/v1/channel`
66    pub uuid: String,
67    /// address of the requester that reserved the room
68    pub remote_address: IpAddr,
69    /// live user, stream and bitrate stats read after the directory snapshot
70    pub users_stats: RoomUserStatsSnapshot,
71    /// room creation flag exposed by `/v1/stats`
72    pub web_rtc_enabled: bool,
73}
74
75/// committed admission result returned after join-side effects run
76#[derive(Debug, Clone)]
77pub struct RoomUserAdmission {
78    /// current room that accepted the session
79    pub room: Arc<Room>,
80    /// room-local connection id assigned to the admitted user
81    pub connection_id: ConnectionId,
82    /// transport key used by [`crate::prelude::SfuCore`] to build
83    /// [`crate::prelude::MediaSession`]
84    pub transport_session_key: TransportSessionKey,
85}
86
87/// current room directory row used by diagnostics views
88#[derive(Debug, Clone)]
89pub struct RuntimeRoomDirectorySnapshot {
90    /// current room for this directory row
91    pub room: Arc<Room>,
92    /// room publication timestamp in RFC 3339 UTC format
93    pub create_date: String,
94    /// address of the requester that reserved the room
95    pub remote_address: IpAddr,
96}
97
98fn retrieve_room_reservation(
99    directory: &RoomDirectory,
100    issuer: &str,
101    key: &SecretSlice<u8>,
102    config: &RoomConfig,
103    remote_address: IpAddr,
104) -> Result<Option<Arc<Room>>, RoomManagerServeError> {
105    let Some(entry) = directory.entry_by_reservation(remote_address, issuer) else {
106        return Ok(None);
107    };
108    if !entry.room.matches_reservation(key, config) {
109        warn!(
110            event = telemetry_event::ROOM_RESERVATION_CONFLICT,
111            room_id = entry.room.uuid(),
112            issuer,
113            config = ?config,
114            "conflicting reservation request"
115        );
116        return Err(RoomManagerServeError::ConflictingReservation);
117    }
118    entry.lifecycle.renew_reservation();
119    Ok(Some(Arc::clone(&entry.room)))
120}
121
122/// Coordinates current room admission and lifecycle.
123#[derive(Debug)]
124pub struct RoomManager {
125    directory: RwLock<RoomDirectory>,
126    factory: RoomFactory,
127    media_transport: MediaTransport,
128    reservation_ttl: Duration,
129    departure_grace: Duration,
130    policy_permits: Semaphore,
131}
132
133fn room_active_speaker_sources(
134    snapshots: &[Arc<Vec<ActiveSpeakerSource>>],
135    source_ids: &[u64],
136) -> Vec<ActiveSpeakerSource> {
137    let mut by_media = BTreeMap::<u64, ActiveSpeakerSource>::new();
138    for &media_id in source_ids {
139        for snapshot in snapshots {
140            let candidate = snapshot
141                .binary_search_by_key(&media_id, |source| source.transport_media_id().as_u64())
142                .ok()
143                .and_then(|index| snapshot.get(index))
144                .copied();
145            if let Some(candidate) = candidate {
146                let candidate_rank = (
147                    candidate.observed_at(),
148                    candidate.last_audio_level_dbov().unwrap_or(i8::MIN),
149                );
150                let entry = by_media.entry(media_id).or_insert(candidate);
151                let current_rank = (
152                    entry.observed_at(),
153                    entry.last_audio_level_dbov().unwrap_or(i8::MIN),
154                );
155                if candidate_rank > current_rank {
156                    *entry = candidate;
157                }
158            }
159        }
160    }
161    let mut sources = by_media.into_values().collect::<Vec<_>>();
162    sources.sort_unstable_by_key(|source| {
163        (
164            Reverse(source.observed_at()),
165            source.transport_media_id().as_u64(),
166        )
167    });
168    sources
169}
170
171impl RoomManager {
172    /// builds a room manager with an empty directory
173    ///
174    #[must_use]
175    pub fn new(
176        runtime_policy: RoomRuntimePolicy,
177        metrics: Arc<RuntimeMetrics>,
178        media_transport: MediaTransport,
179        reservation_ttl: Duration,
180        departure_grace: Duration,
181    ) -> Self {
182        let factory = RoomFactory::new(runtime_policy, metrics, media_transport.clone());
183        Self {
184            directory: RwLock::new(RoomDirectory::default()),
185            factory,
186            media_transport,
187            reservation_ttl,
188            departure_grace,
189            policy_permits: Semaphore::new(SOURCE_POLICY_CONCURRENCY),
190        }
191    }
192
193    /// Returns the current room that `remote_address` reserved for `issuer` or
194    /// publishes a new reservation.
195    ///
196    /// Each requester address has its own issuer namespace, and an
197    /// IPv4-mapped IPv6 address shares the namespace of its IPv4 form. The
198    /// first reservation fixes decoded key bytes and config. The admitting
199    /// runtime validates key encoding and strength before this call.
200    /// Matching requests return the same room and renew an outstanding
201    /// reservation without rearming one retired by a successful join.
202    ///
203    /// # Errors
204    ///
205    /// Returns [`RoomManagerServeError::ConflictingReservation`] when the
206    /// current room has a different `key` or `config`.
207    pub async fn serve_room(
208        &self,
209        issuer: &str,
210        key: SecretSlice<u8>,
211        config: &RoomConfig,
212        remote_address: IpAddr,
213    ) -> Result<Arc<Room>, RoomManagerServeError> {
214        let remote_address = remote_address.to_canonical();
215        {
216            let directory = self.directory.read().await;
217            if let Some(room) =
218                retrieve_room_reservation(&directory, issuer, &key, config, remote_address)?
219            {
220                return Ok(room);
221            }
222        }
223        let mut directory = self.directory.write().await;
224        if let Some(room) =
225            retrieve_room_reservation(&directory, issuer, &key, config, remote_address)?
226        {
227            return Ok(room);
228        }
229        let room = self.factory.create(issuer, key, config);
230        directory.insert(
231            Arc::clone(&room),
232            remote_address,
233            self.reservation_ttl,
234            self.departure_grace,
235        );
236        drop(directory);
237        info!(
238            event = telemetry_event::ROOM_CREATED,
239            room_id = room.uuid(),
240            remote_address = %remote_address,
241            web_rtc_enabled = config.web_rtc_enabled,
242            "room created"
243        );
244        Ok(room)
245    }
246
247    /// returns the current room for a public room uuid
248    pub async fn get_by_uuid(&self, uuid: &str) -> Option<Arc<Room>> {
249        let directory = self.directory.read().await;
250        directory.get_by_uuid(uuid)
251    }
252
253    /// builds `/v1/stats` rows from one directory snapshot
254    ///
255    /// the directory lock is released before transport stats are read, so the
256    /// returned rows are best-effort runtime observations rather than a global
257    /// transaction across room and media state
258    pub async fn stats_snapshots(&self) -> Vec<RuntimeRoomStatsSnapshot> {
259        let entries = self.directory_entries().await;
260        let mut snapshots = Vec::with_capacity(entries.len());
261        for entry in entries {
262            snapshots.push(entry_stats_snapshot(entry).await);
263        }
264        snapshots
265    }
266
267    /// returns current directory rows for room diagnostics
268    pub async fn directory_snapshots(&self) -> Vec<RuntimeRoomDirectorySnapshot> {
269        self.directory_entries()
270            .await
271            .into_iter()
272            .map(|entry| RuntimeRoomDirectorySnapshot {
273                room: entry.room,
274                create_date: entry.create_date,
275                remote_address: entry.remote_address,
276            })
277            .collect()
278    }
279
280    /// Returns counts from rooms in one directory snapshot.
281    ///
282    /// Room states are read sequentially after the directory lock is released.
283    /// Removed rooms may contribute once. New rooms appear on the next call.
284    pub async fn room_gauges(&self) -> RoomGaugeValues {
285        let rooms = self.directory.read().await.rooms();
286        let mut gauges = RoomGaugeValues {
287            rooms: rooms.len(),
288            ..RoomGaugeValues::default()
289        };
290        for room in rooms {
291            let state = room.state.read().await;
292            let media = state.topology.media_counts();
293            gauges.users = gauges.users.saturating_add(state.users.len());
294            gauges.publications = gauges.publications.saturating_add(media.publications);
295            gauges.subscriptions = gauges.subscriptions.saturating_add(media.subscriptions);
296            gauges.recording_rooms = gauges
297                .recording_rooms
298                .saturating_add(usize::from(state.recording_state().recording == Some(true)));
299        }
300        gauges
301    }
302
303    /// returns one current directory row for room diagnostics
304    pub async fn directory_snapshot(&self, room_id: &str) -> Option<RuntimeRoomDirectorySnapshot> {
305        let entry = self.entry(room_id).await?;
306        Some(RuntimeRoomDirectorySnapshot {
307            room: entry.room,
308            create_date: entry.create_date,
309            remote_address: entry.remote_address,
310        })
311    }
312
313    /// Recalculates packet selection for the requested current rooms.
314    pub async fn sync_source_packet_selection_policies_for_runtime_ids(
315        &self,
316        room_instance_ids: &BTreeSet<RoomInstanceId>,
317    ) {
318        self.source_policy_turns(room_instance_ids)
319            .await
320            .for_each(|_| async {})
321            .await;
322    }
323
324    /// Yields each requested room after its ordered policy turn completes.
325    ///
326    /// Worker reads are shared within the batch. Missing rooms also complete.
327    /// Failed observations schedule a retry before completing their room.
328    /// Dropping the stream cancels pending turns, including accepted effects.
329    pub async fn source_policy_turns(
330        &self,
331        room_instance_ids: &BTreeSet<RoomInstanceId>,
332    ) -> BoxStream<'_, RoomInstanceId> {
333        let media_transport = &self.media_transport;
334        let rooms = self
335            .directory_entries_for_instance_ids(room_instance_ids)
336            .await;
337        let mut absent = room_instance_ids.clone();
338        let mut jobs = Vec::with_capacity(rooms.len());
339        let mut needed_workers = BTreeSet::new();
340        for room in rooms {
341            absent.remove(&room.instance_id());
342            let worker_indices = director::policy_worker_indices(&room).await;
343            needed_workers.extend(worker_indices.iter().copied());
344            jobs.push((room, worker_indices));
345        }
346        // Shared futures send one read per worker while each room waits only for
347        // the workers that own its published sources.
348        let observations = needed_workers
349            .into_iter()
350            .map(|worker_index| {
351                let future = async move {
352                    let mut sources = media_transport
353                        .active_speaker_source_snapshot_for_worker(worker_index)
354                        .await?;
355                    sources.sort_unstable_by_key(|source| {
356                        (
357                            source.transport_media_id().as_u64(),
358                            Reverse(source.observed_at()),
359                            Reverse(source.last_audio_level_dbov().unwrap_or(i8::MIN)),
360                        )
361                    });
362                    sources.dedup_by_key(|source| source.transport_media_id());
363                    Ok::<_, TransportAdapterError>(Arc::new(sources))
364                }
365                .boxed()
366                .shared();
367                (worker_index, future)
368            })
369            .collect::<BTreeMap<_, _>>();
370        let turns = jobs
371            .into_iter()
372            .map(|(room, worker_indices)| {
373                let worker_reads = worker_indices
374                    .iter()
375                    .map(|worker_index| observations.get(worker_index).cloned())
376                    .collect::<Option<Vec<_>>>();
377                async move {
378                    let room_id = room.instance_id();
379                    let Some(worker_reads) = worker_reads else {
380                        media_transport.schedule_source_policy_retry(room_id);
381                        return room_id;
382                    };
383                    let Ok(snapshots) = try_join_all(worker_reads).await else {
384                        media_transport.schedule_source_policy_retry(room_id);
385                        return room_id;
386                    };
387                    let guard = room.lock_source_policy().await;
388                    let Ok(_permit) = self.policy_permits.acquire().await else {
389                        return room_id;
390                    };
391                    if director::policy_worker_indices(&room).await != worker_indices {
392                        media_transport.schedule_source_policy_retry(room_id);
393                        return room_id;
394                    }
395                    let source_ids = {
396                        let state = room.state.read().await;
397                        state
398                            .topology
399                            .sources()
400                            .iter()
401                            .map(|source| source.transport.transport_media_id().as_u64())
402                            .collect::<Vec<_>>()
403                    };
404                    let sources = room_active_speaker_sources(&snapshots, &source_ids);
405                    SourcePolicyTurn::packet_selection()
406                        .execute_guarded(&guard, Some(&sources))
407                        .await;
408                    room_id
409                }
410            })
411            .collect::<FuturesUnordered<_>>();
412        stream::iter(absent).chain(turns).boxed()
413    }
414
415    /// Admits one WebSocket connection into a current room.
416    ///
417    /// Returns after join-side room effects complete.
418    ///
419    /// # Errors
420    ///
421    /// Returns [`RoomManagerJoinError::MissingRoom`] when `room_id` is not
422    /// current. Returns [`RoomManagerJoinError::RoomFull`] when a new user
423    /// exceeds room capacity. Returns [`RoomManagerJoinError::NoUsableWorker`]
424    /// when no worker can accept placement and [`RoomManagerJoinError::RouterState`]
425    /// when router placement cannot commit.
426    pub async fn join_user(
427        &self,
428        room_id: &str,
429        request: JoinUserRequest,
430    ) -> Result<RoomUserAdmission, RoomManagerJoinError> {
431        let mutation = self
432            .begin_current_room_mutation(room_id)
433            .await
434            .ok_or(RoomManagerJoinError::MissingRoom)?;
435        let room = Arc::clone(&mutation.room);
436
437        let join_commit = match room
438            .commit_join(request, || self.factory.allocate_spillover_router())
439            .await
440        {
441            Ok(commit) => commit,
442            Err(err) => {
443                self.finish_session_mutation(room_id, mutation, None).await;
444                return Err(match err {
445                    RoomJoinError::RoomFull => RoomManagerJoinError::RoomFull,
446                    RoomJoinError::RouterState => RoomManagerJoinError::RouterState,
447                    RoomJoinError::NoUsableWorker => RoomManagerJoinError::NoUsableWorker,
448                });
449            }
450        };
451        // Retire the reservation only after membership commits. Failed admission
452        // must leave its deadline intact for the reaper.
453        mutation.lease.clear_expiration();
454        let transport_session_key = room.finalize_admission(join_commit).await;
455
456        self.finish_session_mutation(room_id, mutation, None).await;
457        Ok(RoomUserAdmission {
458            room,
459            connection_id: transport_session_key.connection_id(),
460            transport_session_key,
461        })
462    }
463
464    /// closes one room connection and then re-checks empty-room removal
465    ///
466    /// returns `false` when the room is missing or the connection was not
467    /// removed by this call. the empty current room can still be removed after
468    /// stale or already-completed teardown
469    pub async fn close_session(
470        &self,
471        room_id: &str,
472        user_id: &UserId,
473        connection_id: ConnectionId,
474    ) -> bool {
475        let Some(did_remove_active_session) = self
476            .run_current_room_mutation(
477                room_id,
478                |room| async move { room.remove_user(user_id, connection_id).await },
479                Some(RoomRemovalPolicy::AfterGrace),
480            )
481            .await
482        else {
483            return false;
484        };
485        did_remove_active_session
486    }
487
488    /// disconnects selected users from a current room and removes it if empty
489    ///
490    /// missing rooms are ignored because the caller's disconnect intent is
491    /// already satisfied
492    pub async fn disconnect_users(&self, room_id: &str, user_ids: &[UserId]) {
493        let result = self
494            .run_current_room_mutation(
495                room_id,
496                |room| async move { room.disconnect_users(user_ids).await },
497                Some(RoomRemovalPolicy::Immediately),
498            )
499            .await;
500        let (disconnected_session_count, outcome) =
501            result.map_or((0, "room_missing"), |count| (count, "success"));
502        info!(
503            event = telemetry_event::USERS_BULK_DISCONNECTED,
504            disconnected_session_count,
505            outcome,
506            requested_user_count = user_ids.len(),
507            room_id,
508            "bulk disconnect handled"
509        );
510    }
511
512    /// Claims and removes expired reservations with no active room mutations.
513    pub async fn check_expired_room_reservations(&self) {
514        let mut directory = self.directory.write().await;
515        for entry in directory.entries() {
516            if let Some(expiry_reason) = entry.lifecycle.claim_expired_room()
517                && directory.remove_if_current(entry.room.uuid(), &entry.room)
518            {
519                match expiry_reason {
520                    ExpiryReason::ReservationLapsed => {
521                        info!(
522                            event = telemetry_event::ROOM_RESERVATION_EXPIRED,
523                            room_id = entry.room.uuid(),
524                            "room reservation expired"
525                        );
526                    }
527                    ExpiryReason::GraceElapsed => {
528                        info!(
529                            event = telemetry_event::ROOM_DESTROYED,
530                            room_id = entry.room.uuid(),
531                            "room destroyed"
532                        );
533                    }
534                }
535            }
536        }
537        drop(directory);
538    }
539
540    async fn run_current_room_mutation<T, F, Fut>(
541        &self,
542        room_id: &str,
543        action: F,
544        on_empty: Option<RoomRemovalPolicy>,
545    ) -> Option<T>
546    where
547        F: FnOnce(Arc<Room>) -> Fut,
548        Fut: Future<Output = T>,
549    {
550        let mutation = self.begin_current_room_mutation(room_id).await?;
551        let output = action(Arc::clone(&mutation.room)).await;
552        self.finish_session_mutation(room_id, mutation, on_empty)
553            .await;
554        Some(output)
555    }
556
557    async fn finish_session_mutation(
558        &self,
559        room_id: &str,
560        mutation: CurrentRoomMutation,
561        on_empty: Option<RoomRemovalPolicy>,
562    ) {
563        let CurrentRoomMutation { room, lease } = mutation;
564        // Read emptiness after this mutation. A later accepted mutation can
565        // supply the final removal proof. Dropping the final lease supplies no
566        // proof and cancels the pending claim.
567        let empty = room.state.read().await.users.is_empty();
568        if lease.finish(on_empty, empty)
569            && self
570                .directory
571                .write()
572                .await
573                .remove_if_current(room_id, &room)
574        {
575            info!(
576                event = telemetry_event::ROOM_DESTROYED,
577                room_id, "room destroyed"
578            );
579        }
580    }
581
582    /// Accepts work while the directory read guard proves the row is current.
583    ///
584    /// The returned lease protects subsequent room work without retaining the
585    /// directory guard.
586    async fn begin_current_room_mutation(&self, room_id: &str) -> Option<CurrentRoomMutation> {
587        let directory = self.directory.read().await;
588        let entry = directory.entry(room_id)?;
589        let lease = entry.lifecycle.begin()?;
590        let room = Arc::clone(&entry.room);
591        drop(directory);
592        Some(CurrentRoomMutation { room, lease })
593    }
594
595    async fn entry(&self, room_id: &str) -> Option<RoomDirectoryEntry> {
596        let directory = self.directory.read().await;
597        directory.entry(room_id).cloned()
598    }
599
600    async fn directory_entries(&self) -> Vec<RoomDirectoryEntry> {
601        let directory = self.directory.read().await;
602        directory.entries()
603    }
604
605    async fn directory_entries_for_instance_ids(
606        &self,
607        room_instance_ids: &BTreeSet<RoomInstanceId>,
608    ) -> Vec<Arc<Room>> {
609        let directory = self.directory.read().await;
610        room_instance_ids
611            .iter()
612            .filter_map(|room_instance_id| directory.get_by_instance_id(*room_instance_id))
613            .collect()
614    }
615}
616
617async fn entry_stats_snapshot(entry: RoomDirectoryEntry) -> RuntimeRoomStatsSnapshot {
618    let room = entry.room;
619    let users_stats = room.session_stats_snapshot().await;
620    RuntimeRoomStatsSnapshot {
621        create_date: entry.create_date,
622        uuid: room.uuid().to_owned(),
623        remote_address: entry.remote_address,
624        users_stats,
625        web_rtc_enabled: room.web_rtc_enabled(),
626    }
627}
628
629/// lease plus room pointer accepted from the current directory row
630///
631/// dropping the lease without [`RoomManager::finish_session_mutation`] releases
632/// admission but never removes the room
633#[derive(Debug)]
634struct CurrentRoomMutation {
635    room: Arc<Room>,
636    lease: RoomLifecycleLease,
637}