Skip to main content

o_sfu_core/engine/room/media_graph/
route_graph.rs

1//! Logical subscriptions and their transport realization.
2//!
3//! Explicit receiver intent survives while no publication is attached. A
4//! current publication realizes as `Absent -> Pending -> Committed`. Current
5//! setup failures and receiver replacement return realization to `Absent`.
6//! Reservation IDs reject async completion after source detach or replacement.
7//!
8//! ```text
9//! logical subscription realization:
10//!      publication attached
11//!              |
12//!              v
13//!   +--------------------+  reserve setup
14//!   | ConsumerRealization| ------------------> +-------------------------------+
15//!   |      Absent        |                     | ConsumerRealization::Pending  |
16//!   +--------------------+ <------------------ | (RouteReservationId)          |
17//!              ^       setup fails/rejected    +-------------------------------+
18//!              |                                                  |
19//!              |              decline/replace                     v setup accepted
20//!              +---------------------------------- +---------------------------------+
21//!                                                  | ConsumerRealization::Committed  |
22//!                                                  +---------------------------------+
23//! ```
24//!
25//! Intent without a current publication keeps `Subscription.current` at `None`.
26//! Accepted setup requires a current identity and a successful transport
27//! declaration. Source detach returns to `None` while retaining intent.
28//! `remove_receiver` deletes the record and its intent.
29//!
30//! Each receiver retains at most the room session limit of absent publisher
31//! targets. Sparse updates keep the target's original age. A new target evicts
32//! every stream preference of the oldest absent target. Present members do not
33//! consume this allowance, including members with no publications. Joining
34//! promotes existing intent and departure enters the allowance as a new target.
35
36use std::{
37    collections::{BTreeMap, BTreeSet, VecDeque},
38    mem,
39};
40
41use o_sfu_model::UserId;
42use o_sfu_transport::{
43    ConsumerActivity, TransportConsumerRoute, TransportMediaId, TransportSessionKey,
44};
45
46use super::{SubscriptionKey, remove_from_index_set};
47use crate::{
48    ConnectionId,
49    engine::{
50        director::{PendingUpgrade, RouteAllocation},
51        source_model::{PublishedSourceId, SourceSubscriptionIntent},
52    },
53};
54
55#[derive(Debug)]
56pub(in crate::engine) struct RouteGraph {
57    entries: BTreeMap<SubscriptionKey, Subscription>,
58    by_receiver: BTreeMap<UserId, BTreeSet<SubscriptionKey>>,
59    by_source: BTreeMap<PublishedSourceId, BTreeSet<SubscriptionKey>>,
60    next_reservation: RouteReservationId,
61    pending_targets: BTreeMap<UserId, VecDeque<UserId>>,
62    pending_target_limit: usize,
63}
64
65#[derive(Debug, Default)]
66struct Subscription {
67    intent: SourceSubscriptionIntent,
68    current: Option<CurrentPublication>,
69}
70
71#[derive(Debug)]
72pub(super) struct CurrentPublication {
73    pub source_id: PublishedSourceId,
74    pub allocation: RouteAllocation,
75    realization: ConsumerRealization,
76}
77
78#[derive(Debug, Default)]
79enum ConsumerRealization {
80    #[default]
81    Absent,
82    Pending(RouteReservationId),
83    Committed(CommittedConsumerRoute),
84}
85
86/// Transport realization and adaptation hold share the exact route lifetime.
87#[derive(Debug)]
88pub(super) struct CommittedConsumerRoute {
89    pub route: TransportConsumerRoute,
90    pub pending_upgrade: Option<PendingUpgrade>,
91}
92
93#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
94struct RouteReservationId(u64);
95
96/// A subscription with its receiver intent and the publication it follows.
97pub(super) type Attached<'graph> = (
98    &'graph SubscriptionKey,
99    SourceSubscriptionIntent,
100    &'graph CurrentPublication,
101);
102
103#[derive(Debug)]
104pub struct ConsumerRouteReservation {
105    key: SubscriptionKey,
106    source_id: PublishedSourceId,
107    declared_activity: ConsumerActivity,
108    id: RouteReservationId,
109}
110
111impl RouteGraph {
112    pub(super) fn new(pending_target_limit: usize) -> Self {
113        Self {
114            entries: BTreeMap::new(),
115            by_receiver: BTreeMap::new(),
116            by_source: BTreeMap::new(),
117            next_reservation: RouteReservationId::default(),
118            pending_targets: BTreeMap::new(),
119            pending_target_limit,
120        }
121    }
122
123    /// Membership promotion preserves every stream preference and frees its
124    /// absent-target allowance without duplicating the logical subscriptions.
125    pub(super) fn publisher_joined(&mut self, publisher: &UserId) {
126        self.pending_targets.retain(|_, pending| {
127            pending.retain(|target| target != publisher);
128            !pending.is_empty()
129        });
130    }
131
132    /// Call after detaching every source and removing this user's receiver state.
133    /// A departed member becomes the newest absent target for each receiver
134    /// retaining explicit intent, even when it never published media.
135    pub(super) fn publisher_left(&mut self, publisher: &UserId) -> usize {
136        let receivers: Vec<_> = self
137            .by_receiver
138            .iter()
139            .filter(|(_, keys)| keys.iter().any(|key| &key.publisher == publisher))
140            .map(|(receiver, _)| receiver.clone())
141            .collect();
142        receivers
143            .iter()
144            .map(|receiver| self.retain_pending_target(receiver, publisher))
145            .sum()
146    }
147
148    fn retain_pending_target(&mut self, receiver: &UserId, publisher: &UserId) -> usize {
149        let pending = self.pending_targets.entry(receiver.clone()).or_default();
150        if pending.contains(publisher) {
151            return 0;
152        }
153        pending.push_back(publisher.clone());
154        if pending.len() <= self.pending_target_limit {
155            return 0;
156        }
157        let Some(evicted) = pending.pop_front() else {
158            return 0;
159        };
160        if pending.is_empty() {
161            self.pending_targets.remove(receiver);
162        }
163        // Only absent publishers enter this index. Their detached records have
164        // no transport ownership, so eviction removes intent alone.
165        if let Some(keys) = self.by_receiver.get_mut(receiver) {
166            keys.retain(|key| {
167                if key.publisher != evicted {
168                    return true;
169                }
170                let removed = self.entries.remove(key);
171                debug_assert!(removed.is_none_or(|entry| entry.current.is_none()));
172                false
173            });
174            if keys.is_empty() {
175                self.by_receiver.remove(receiver);
176            }
177        }
178        1
179    }
180
181    pub(super) fn subscription_count(&self) -> usize {
182        self.entries
183            .values()
184            .filter(|entry| entry.has_consumer_setup_or_route())
185            .count()
186    }
187
188    /// Counts committed consumers, including inactive subscriptions.
189    pub(in crate::engine) fn consumer_count(&self) -> usize {
190        self.attached()
191            .filter(|(_, _, current)| current.committed().is_some())
192            .count()
193    }
194
195    pub(super) fn merge_intent(
196        &mut self,
197        key: &SubscriptionKey,
198        update: SourceSubscriptionIntent,
199        publisher_present: bool,
200    ) -> usize {
201        if update.is_empty() {
202            return 0;
203        }
204        let entry = self.entry(key.clone());
205        entry.intent.merge(update);
206        // A hold needs continuous eligibility, which an inactive subscription ends.
207        if update.active() == Some(false)
208            && let Some(current) = entry.current.as_mut()
209        {
210            current.clear_upgrade();
211        }
212        if publisher_present {
213            0
214        } else {
215            self.retain_pending_target(&key.receiver, &key.publisher)
216        }
217    }
218
219    /// Returns merged receiver intent or the default for a missing subscription.
220    pub(in crate::engine) fn intent(&self, key: &SubscriptionKey) -> SourceSubscriptionIntent {
221        self.entries
222            .get(key)
223            .map_or_else(SourceSubscriptionIntent::default, |entry| entry.intent)
224    }
225
226    pub(super) fn attach_for_setup(
227        &mut self,
228        key: SubscriptionKey,
229        source_id: PublishedSourceId,
230    ) -> bool {
231        let entry = self.entry(key.clone());
232        if let Some(current) = &entry.current {
233            return current.source_id == source_id
234                && matches!(current.realization, ConsumerRealization::Absent);
235        }
236        entry.current = Some(CurrentPublication {
237            source_id,
238            allocation: RouteAllocation::default(),
239            realization: ConsumerRealization::Absent,
240        });
241        self.by_source.entry(source_id).or_default().insert(key);
242        true
243    }
244
245    /// Returns `None` unless the attachment matches `source_id` and any
246    /// committed route serves `connection_id`.
247    pub(super) fn attached_allocation_mut(
248        &mut self,
249        key: &SubscriptionKey,
250        source_id: PublishedSourceId,
251        connection_id: ConnectionId,
252    ) -> Option<&mut RouteAllocation> {
253        let current = self.current_mut(key, source_id)?;
254        if let ConsumerRealization::Committed(committed) = &current.realization
255            && committed.route.consumer_session_key().connection_id() != connection_id
256        {
257            return None;
258        }
259        Some(&mut current.allocation)
260    }
261
262    pub(super) fn reserve_consumer_setup(
263        &mut self,
264        key: SubscriptionKey,
265        source_id: PublishedSourceId,
266        allocation: RouteAllocation,
267    ) -> Option<ConsumerRouteReservation> {
268        let entry = self.entries.get_mut(&key)?;
269        let intent = entry.intent;
270        let current = entry.current.as_mut()?;
271        if current.source_id != source_id
272            || !matches!(current.realization, ConsumerRealization::Absent)
273        {
274            return None;
275        }
276        self.next_reservation.0 += 1;
277        let id = self.next_reservation;
278        current.allocation = allocation;
279        current.realization = ConsumerRealization::Pending(id);
280        Some(ConsumerRouteReservation {
281            key,
282            source_id,
283            declared_activity: ConsumerActivity::from_active(allocation.delivers(intent)),
284            id,
285        })
286    }
287
288    pub(super) fn release_consumer_setup(&mut self, reservation: &ConsumerRouteReservation) {
289        if let Some(current) = self.reserved_mut(reservation) {
290            current.realization = ConsumerRealization::Absent;
291        }
292    }
293
294    /// Returns whether the route committed.
295    #[must_use]
296    #[expect(
297        clippy::needless_pass_by_value,
298        reason = "commit consumes the reservation on both success and failure"
299    )]
300    pub(super) fn commit(
301        &mut self,
302        reservation: ConsumerRouteReservation,
303        route: TransportConsumerRoute,
304        allocation: RouteAllocation,
305    ) -> bool {
306        let Some(current) = self.reserved_mut(&reservation) else {
307            return false;
308        };
309        current.allocation = allocation;
310        current.realization = ConsumerRealization::Committed(CommittedConsumerRoute {
311            route,
312            pending_upgrade: None,
313        });
314        true
315    }
316
317    pub(super) fn update_allocation(
318        &mut self,
319        key: &SubscriptionKey,
320        source_id: PublishedSourceId,
321        route: &TransportConsumerRoute,
322        update: impl FnOnce(&mut RouteAllocation),
323    ) -> bool {
324        let Some(current) = self.current_mut(key, source_id) else {
325            return false;
326        };
327        let ConsumerRealization::Committed(committed) = &current.realization else {
328            return false;
329        };
330        if &committed.route != route {
331            return false;
332        }
333        update(&mut current.allocation);
334        true
335    }
336
337    pub(super) fn update_upgrade(
338        &mut self,
339        key: &SubscriptionKey,
340        source_id: PublishedSourceId,
341        route: &TransportConsumerRoute,
342        pending_upgrade: Option<PendingUpgrade>,
343    ) -> bool {
344        let Some(entry) = self.entries.get_mut(key) else {
345            return false;
346        };
347        let Some(current) = entry
348            .current
349            .as_mut()
350            .filter(|current| current.source_id == source_id && entry.intent.is_active())
351        else {
352            return false;
353        };
354        let ConsumerRealization::Committed(committed) = &mut current.realization else {
355            return false;
356        };
357        if &committed.route != route {
358            return false;
359        }
360        committed.pending_upgrade = pending_upgrade;
361        true
362    }
363
364    pub(super) fn clear_source_upgrades(&mut self, source_id: PublishedSourceId) {
365        let (entries, by_source) = (&mut self.entries, &self.by_source);
366        for key in by_source.get(&source_id).into_iter().flatten() {
367            if let Some(current) = entries
368                .get_mut(key)
369                .and_then(|entry| entry.current.as_mut())
370            {
371                current.clear_upgrade();
372            }
373        }
374    }
375
376    /// Returns `None` when the attached source differs from `source_id`.
377    pub(super) fn allocation(
378        &self,
379        key: &SubscriptionKey,
380        source_id: PublishedSourceId,
381    ) -> Option<RouteAllocation> {
382        let current = self.entries.get(key)?.current.as_ref()?;
383        (current.source_id == source_id).then_some(current.allocation)
384    }
385
386    pub(super) fn attached(&self) -> impl Iterator<Item = Attached<'_>> {
387        self.entries
388            .iter()
389            .filter_map(|(key, entry)| Some((key, entry.intent, entry.current.as_ref()?)))
390    }
391
392    pub(super) fn current(&self, key: &SubscriptionKey) -> Option<Attached<'_>> {
393        let (key, entry) = self.entries.get_key_value(key)?;
394        Some((key, entry.intent, entry.current.as_ref()?))
395    }
396
397    pub(super) fn attached_for_receiver(
398        &self,
399        receiver: &UserId,
400    ) -> impl Iterator<Item = Attached<'_>> {
401        self.by_receiver
402            .get(receiver)
403            .into_iter()
404            .flat_map(BTreeSet::iter)
405            .filter_map(|key| self.current(key))
406    }
407
408    pub(super) fn attached_for_source(
409        &self,
410        source_id: PublishedSourceId,
411    ) -> impl Iterator<Item = Attached<'_>> {
412        self.by_source
413            .get(&source_id)
414            .into_iter()
415            .flat_map(BTreeSet::iter)
416            .filter_map(|key| self.current(key))
417    }
418
419    pub(super) fn detach_source(
420        &mut self,
421        source_id: PublishedSourceId,
422    ) -> Vec<TransportConsumerRoute> {
423        let keys = self.by_source.remove(&source_id).unwrap_or_default();
424        let mut removed = Vec::new();
425        for key in keys {
426            let (realization, prune) = {
427                let Some(entry) = self.entries.get_mut(&key) else {
428                    continue;
429                };
430                let Some(current) = entry.current.take() else {
431                    continue;
432                };
433                debug_assert_eq!(current.source_id, source_id);
434                (current.realization, entry.intent.is_empty())
435            };
436            removed.extend(realization.into_committed_route());
437            if prune {
438                self.entries.remove(&key);
439                remove_from_index_set(&mut self.by_receiver, &key.receiver, &key);
440            }
441        }
442        removed
443    }
444
445    pub(super) fn reset_receiver_for_replacement(&mut self, receiver: &UserId) {
446        for key in self.by_receiver.get(receiver).into_iter().flatten() {
447            let Some(entry) = self.entries.get_mut(key) else {
448                continue;
449            };
450            let Some(current) = entry.current.as_mut() else {
451                continue;
452            };
453            current.allocation = RouteAllocation::default();
454            current.realization = ConsumerRealization::Absent;
455        }
456    }
457
458    pub(super) fn remove_receiver(&mut self, receiver: &UserId) -> Vec<TransportConsumerRoute> {
459        self.pending_targets.remove(receiver);
460        let keys = self.by_receiver.remove(receiver).unwrap_or_default();
461        let mut removed = Vec::new();
462        for key in keys {
463            let Some(entry) = self.entries.remove(&key) else {
464                continue;
465            };
466            let Some(current) = entry.current else {
467                continue;
468            };
469            remove_from_index_set(&mut self.by_source, &current.source_id, &key);
470            removed.extend(current.realization.into_committed_route());
471        }
472        removed
473    }
474
475    pub(super) fn detach_declined_consumers(
476        &mut self,
477        session: &TransportSessionKey,
478        declined: &[TransportMediaId],
479    ) -> Vec<TransportConsumerRoute> {
480        let keys = self
481            .by_receiver
482            .get(session.user_id())
483            .cloned()
484            .unwrap_or_default();
485        let mut removed = Vec::new();
486        for key in keys {
487            let realization = {
488                let Some(current) = self
489                    .entries
490                    .get_mut(&key)
491                    .and_then(|entry| entry.current.as_mut())
492                else {
493                    continue;
494                };
495                let ConsumerRealization::Committed(committed) = &current.realization else {
496                    continue;
497                };
498                if committed.route.consumer_session_key() != session
499                    || !declined.contains(&committed.route.consumer_transport_media_id())
500                {
501                    continue;
502                }
503                mem::take(&mut current.realization)
504            };
505            removed.extend(realization.into_committed_route());
506        }
507        removed
508    }
509
510    fn entry(&mut self, key: SubscriptionKey) -> &mut Subscription {
511        self.by_receiver
512            .entry(key.receiver.clone())
513            .or_default()
514            .insert(key.clone());
515        self.entries.entry(key).or_default()
516    }
517
518    fn current_mut(
519        &mut self,
520        key: &SubscriptionKey,
521        source_id: PublishedSourceId,
522    ) -> Option<&mut CurrentPublication> {
523        let current = self.entries.get_mut(key)?.current.as_mut()?;
524        (current.source_id == source_id).then_some(current)
525    }
526
527    /// Returns the attachment only while `reservation` is its pending realization.
528    fn reserved_mut(
529        &mut self,
530        reservation: &ConsumerRouteReservation,
531    ) -> Option<&mut CurrentPublication> {
532        let current = self.current_mut(&reservation.key, reservation.source_id)?;
533        let ConsumerRealization::Pending(id) = current.realization else {
534            return None;
535        };
536        (id == reservation.id).then_some(current)
537    }
538}
539
540impl ConsumerRouteReservation {
541    pub const fn declared_activity(&self) -> ConsumerActivity {
542        self.declared_activity
543    }
544}
545
546impl Subscription {
547    fn has_consumer_setup_or_route(&self) -> bool {
548        self.current
549            .as_ref()
550            .is_some_and(|current| !matches!(current.realization, ConsumerRealization::Absent))
551    }
552}
553
554impl ConsumerRealization {
555    fn into_committed_route(self) -> Option<TransportConsumerRoute> {
556        match self {
557            Self::Committed(committed) => Some(committed.route),
558            Self::Absent | Self::Pending(..) => None,
559        }
560    }
561}
562
563impl CurrentPublication {
564    fn clear_upgrade(&mut self) {
565        if let ConsumerRealization::Committed(committed) = &mut self.realization {
566            committed.pending_upgrade = None;
567        }
568    }
569
570    pub(super) const fn is_pending(&self) -> bool {
571        matches!(self.realization, ConsumerRealization::Pending(..))
572    }
573
574    pub(super) fn committed(&self) -> Option<&CommittedConsumerRoute> {
575        match &self.realization {
576            ConsumerRealization::Committed(committed) => Some(committed),
577            ConsumerRealization::Absent | ConsumerRealization::Pending(..) => None,
578        }
579    }
580}
581
582#[cfg(test)]
583#[path = "TESTS/route_graph.rs"]
584mod tests;