Skip to main content

o_sfu_core/engine/room/
outbound.rs

1//! Bounded per-user room output.
2//!
3//! [`UserOutboundSender::send`] enqueues without waiting and signals
4//! [`UserOutboundEvent::Overflow`] when message-count or byte capacity is
5//! exhausted. [`UserOutboundReceiver::recv_event`] prioritizes that signal over
6//! queued output. User-session loops must stop normal draining after overflow.
7
8use std::{
9    collections::BTreeMap,
10    future::pending,
11    io,
12    sync::{
13        Arc, Mutex,
14        atomic::{AtomicUsize, Ordering},
15    },
16};
17
18use o_sfu_model::{JsonPayload, RecordingStateUpdate, UserId, UserInfo};
19use o_sfu_telemetry::metrics::RuntimeMetrics;
20use o_sfu_transport::TransportMediaId;
21use tokio::sync::{
22    mpsc::{self, error::TrySendError},
23    watch,
24};
25
26use super::UserCloseReason;
27use crate::engine::{source_model::UserStreamId, sync::lock_unpoisoned};
28
29pub const MAX_BROADCAST_PAYLOAD_BYTES: usize = 16 * 1024;
30
31const ROOM_EVENT_QUEUE_BYTES: usize = 1024;
32const BROADCAST_QUEUE_OVERHEAD_BYTES: usize = 256;
33const TRACK_PROJECTION_QUEUE_OVERHEAD_BYTES: usize = 256;
34
35#[derive(Debug, Clone, PartialEq, Eq)]
36pub struct BroadcastPayload {
37    message: Arc<JsonPayload>,
38    byte_len: usize,
39}
40
41impl BroadcastPayload {
42    /// Creates a broadcast payload and records its serialized byte length.
43    ///
44    /// # Errors
45    ///
46    /// Returns [`BroadcastPayloadError::TooLarge`] when the serialized JSON
47    /// exceeds the limit that the error carries. Returns
48    /// [`BroadcastPayloadError::JsonSerialization`] when JSON serialization
49    /// fails.
50    pub fn try_new(message: JsonPayload) -> Result<Self, BroadcastPayloadError> {
51        let byte_len = serialized_json_len(&message)?;
52        if byte_len > MAX_BROADCAST_PAYLOAD_BYTES {
53            return Err(BroadcastPayloadError::TooLarge {
54                actual: byte_len,
55                limit: MAX_BROADCAST_PAYLOAD_BYTES,
56            });
57        }
58        Ok(Self {
59            message: Arc::new(message),
60            byte_len,
61        })
62    }
63
64    #[must_use]
65    pub const fn byte_len(&self) -> usize {
66        self.byte_len
67    }
68
69    #[must_use]
70    pub fn to_json(&self) -> JsonPayload {
71        self.message.as_ref().clone()
72    }
73}
74
75#[derive(Debug, Clone, Copy, PartialEq, Eq)]
76pub enum BroadcastPayloadError {
77    TooLarge { actual: usize, limit: usize },
78    JsonSerialization,
79}
80
81#[derive(Debug, Clone, PartialEq, Eq)]
82pub enum RoomEventMessage {
83    Broadcast {
84        sender_id: UserId,
85        message: BroadcastPayload,
86    },
87    UserJoined {
88        user_id: UserId,
89        info: UserInfo,
90    },
91    UserDeparted {
92        user_id: UserId,
93    },
94    UserInfoChanged(BTreeMap<UserId, UserInfo>),
95    RecordingStateChanged(RecordingStateUpdate),
96}
97
98impl RoomEventMessage {
99    #[must_use]
100    pub(super) fn queued_bytes(&self) -> usize {
101        match self {
102            Self::Broadcast { message, .. } => message
103                .byte_len()
104                .saturating_add(BROADCAST_QUEUE_OVERHEAD_BYTES),
105            Self::UserInfoChanged(snapshot) => {
106                ROOM_EVENT_QUEUE_BYTES.saturating_mul(snapshot.len())
107            }
108            Self::UserJoined { .. }
109            | Self::UserDeparted { .. }
110            | Self::RecordingStateChanged(_) => ROOM_EVENT_QUEUE_BYTES,
111        }
112    }
113}
114
115#[derive(Debug, Default)]
116struct JsonByteCounter {
117    len: usize,
118}
119
120impl io::Write for JsonByteCounter {
121    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
122        self.len = self.len.saturating_add(buf.len());
123        Ok(buf.len())
124    }
125
126    fn flush(&mut self) -> io::Result<()> {
127        Ok(())
128    }
129}
130
131fn serialized_json_len(value: &JsonPayload) -> Result<usize, BroadcastPayloadError> {
132    let mut counter = JsonByteCounter::default();
133    serde_json::to_writer(&mut counter, value)
134        .map_err(|_error| BroadcastPayloadError::JsonSerialization)?;
135    Ok(counter.len)
136}
137
138pub const DEFAULT_USER_OUTBOUND_QUEUE_CAPACITY: usize = 128;
139pub const DEFAULT_USER_OUTBOUND_QUEUE_BYTE_CAPACITY: usize =
140    DEFAULT_USER_OUTBOUND_QUEUE_CAPACITY * MAX_BROADCAST_PAYLOAD_BYTES;
141
142pub(super) type OutboundSender = UserOutboundSender;
143
144/// One track a connection consumes. The room knows no MID: the session adds
145/// it once an offer has bound `consumer_media`.
146#[derive(Debug, Clone, PartialEq, Eq)]
147pub struct RemoteTrack {
148    pub consumer_media: TransportMediaId,
149    pub user_id: UserId,
150    pub stream_id: UserStreamId,
151    pub producer_active: bool,
152}
153
154#[derive(Debug, Clone, Default, PartialEq, Eq)]
155pub struct RemoteTrackSnapshot {
156    pub tracks: Vec<RemoteTrack>,
157    pub requires_negotiation: bool,
158    /// Order in which the room built its snapshots. A higher one supersedes.
159    pub(crate) revision: u64,
160}
161
162impl RemoteTrackSnapshot {
163    fn queued_bytes(&self) -> usize {
164        self.tracks
165            .iter()
166            .fold(ROOM_EVENT_QUEUE_BYTES, |bytes, track| {
167                let user_id_bytes = match &track.user_id {
168                    UserId::Integer(_) => 0,
169                    UserId::String(value) => value.len(),
170                };
171                bytes
172                    .saturating_add(TRACK_PROJECTION_QUEUE_OVERHEAD_BYTES)
173                    .saturating_add(user_id_bytes)
174                    .saturating_add(track.stream_id.as_str().len())
175            })
176    }
177}
178
179/// room output that belongs to one connected user
180#[derive(Debug, Clone)]
181pub enum UserOutbound {
182    Message(RoomEventMessage),
183    RemoteTracks(RemoteTrackSnapshot),
184    Close(UserCloseReason),
185}
186
187impl UserOutbound {
188    #[must_use]
189    pub(super) fn queued_bytes(&self) -> usize {
190        match self {
191            Self::Message(message) => message.queued_bytes(),
192            Self::RemoteTracks(snapshot) => snapshot.queued_bytes(),
193            Self::Close(_) => ROOM_EVENT_QUEUE_BYTES,
194        }
195    }
196}
197
198/// queue overflow details captured when a user cannot accept more outbound work
199#[derive(Debug, Clone, Copy, PartialEq, Eq)]
200pub struct UserOutboundOverflow {
201    kind: UserOutboundOverflowKind,
202    message_capacity: usize,
203    byte_capacity: usize,
204    queued_bytes: usize,
205    message_bytes: usize,
206}
207
208/// outbound queue limit that rejected a message
209#[derive(Debug, Clone, Copy, PartialEq, Eq)]
210pub enum UserOutboundOverflowKind {
211    MessageCount,
212    QueuedBytes,
213}
214
215impl UserOutboundOverflow {
216    const fn new(
217        kind: UserOutboundOverflowKind,
218        message_capacity: usize,
219        byte_capacity: usize,
220        queued_bytes: usize,
221        message_bytes: usize,
222    ) -> Self {
223        Self {
224            kind,
225            message_capacity,
226            byte_capacity,
227            queued_bytes,
228            message_bytes,
229        }
230    }
231
232    #[must_use]
233    pub const fn capacity(self) -> usize {
234        self.message_capacity
235    }
236
237    #[must_use]
238    pub const fn kind(self) -> UserOutboundOverflowKind {
239        self.kind
240    }
241
242    #[must_use]
243    pub const fn byte_capacity(self) -> usize {
244        self.byte_capacity
245    }
246
247    #[must_use]
248    pub const fn queued_bytes(self) -> usize {
249        self.queued_bytes
250    }
251
252    #[must_use]
253    pub const fn message_bytes(self) -> usize {
254        self.message_bytes
255    }
256}
257
258/// non-blocking outbound send failure
259#[derive(Debug, Clone, Copy, PartialEq, Eq)]
260pub enum UserOutboundSendError {
261    Full(UserOutboundOverflow),
262    Closed,
263}
264
265/// receiver-side queue event for user-session loops
266#[derive(Debug)]
267pub enum UserOutboundEvent {
268    Message(UserOutbound),
269    Overflow(UserOutboundOverflow),
270    Closed,
271}
272
273/// message and byte capacity for one user outbound queue
274#[derive(Debug, Clone, Copy, PartialEq, Eq)]
275pub struct UserOutboundQueueLimits {
276    message_capacity: usize,
277    byte_capacity: usize,
278}
279
280impl UserOutboundQueueLimits {
281    #[must_use]
282    pub fn new(message_capacity: usize, byte_capacity: usize) -> Self {
283        Self {
284            message_capacity: message_capacity.max(1),
285            byte_capacity: byte_capacity.max(1),
286        }
287    }
288
289    #[must_use]
290    pub const fn message_capacity(self) -> usize {
291        self.message_capacity
292    }
293
294    #[must_use]
295    pub const fn byte_capacity(self) -> usize {
296        self.byte_capacity
297    }
298}
299
300impl Default for UserOutboundQueueLimits {
301    fn default() -> Self {
302        Self::new(
303            DEFAULT_USER_OUTBOUND_QUEUE_CAPACITY,
304            DEFAULT_USER_OUTBOUND_QUEUE_BYTE_CAPACITY,
305        )
306    }
307}
308
309#[derive(Debug)]
310struct QueuedUserOutbound {
311    outbound: UserOutbound,
312    bytes: usize,
313}
314
315#[derive(Debug, Clone)]
316pub struct UserOutboundSender {
317    messages: mpsc::Sender<QueuedUserOutbound>,
318    overflow: watch::Sender<Option<UserOutboundOverflow>>,
319    metrics: Arc<RuntimeMetrics>,
320    limits: UserOutboundQueueLimits,
321    queued_bytes: Arc<AtomicUsize>,
322    latest_track_snapshot: Arc<Mutex<Option<RemoteTrackSnapshot>>>,
323}
324
325#[derive(Debug)]
326pub struct UserOutboundReceiver {
327    messages: mpsc::Receiver<QueuedUserOutbound>,
328    overflow: watch::Receiver<Option<UserOutboundOverflow>>,
329    metrics: Arc<RuntimeMetrics>,
330    queued_bytes: Arc<AtomicUsize>,
331}
332
333impl UserOutboundSender {
334    #[must_use]
335    pub fn channel(capacity: usize, metrics: Arc<RuntimeMetrics>) -> (Self, UserOutboundReceiver) {
336        Self::channel_with_limits(
337            UserOutboundQueueLimits::new(capacity, DEFAULT_USER_OUTBOUND_QUEUE_BYTE_CAPACITY),
338            metrics,
339        )
340    }
341
342    #[must_use]
343    pub fn channel_with_limits(
344        limits: UserOutboundQueueLimits,
345        metrics: Arc<RuntimeMetrics>,
346    ) -> (Self, UserOutboundReceiver) {
347        let (messages_tx, messages_rx) = mpsc::channel(limits.message_capacity());
348        let (overflow_tx, overflow_rx) = watch::channel(None);
349        let queued_bytes = Arc::new(AtomicUsize::new(0));
350        (
351            Self {
352                messages: messages_tx,
353                overflow: overflow_tx,
354                metrics: Arc::clone(&metrics),
355                limits,
356                queued_bytes: Arc::clone(&queued_bytes),
357                latest_track_snapshot: Arc::new(Mutex::new(None)),
358            },
359            UserOutboundReceiver {
360                messages: messages_rx,
361                overflow: overflow_rx,
362                metrics,
363                queued_bytes,
364            },
365        )
366    }
367
368    /// Enqueues `outbound` without waiting for capacity.
369    ///
370    /// [`UserOutboundSendError::Full`] also signals an overflow event for
371    /// [`UserOutboundReceiver::recv_event`].
372    ///
373    /// # Errors
374    ///
375    /// Returns [`UserOutboundSendError::Full`] when message-count or byte
376    /// capacity is exhausted. Returns [`UserOutboundSendError::Closed`] when the
377    /// receiver has been dropped.
378    pub fn send(&self, outbound: UserOutbound) -> Result<(), UserOutboundSendError> {
379        self.enqueue(outbound)
380    }
381
382    /// Suppresses older track state while carrying every late negotiation edge
383    /// forward on the latest snapshot.
384    pub(in crate::engine::room) fn send_remote_tracks(
385        &self,
386        snapshot: RemoteTrackSnapshot,
387    ) -> Result<(), UserOutboundSendError> {
388        let revision = snapshot.revision;
389        {
390            let mut latest = lock_unpoisoned(&self.latest_track_snapshot);
391            if self.messages.is_closed() {
392                return Err(UserOutboundSendError::Closed);
393            }
394            if latest
395                .as_ref()
396                .is_none_or(|current| revision > current.revision)
397            {
398                self.enqueue(UserOutbound::RemoteTracks(snapshot.clone()))?;
399                *latest = Some(snapshot);
400                return Ok(());
401            }
402            if let Some(current) = latest.as_mut()
403                && revision < current.revision
404                && snapshot.requires_negotiation
405            {
406                current.requires_negotiation = true;
407                self.enqueue(UserOutbound::RemoteTracks(current.clone()))?;
408            }
409        }
410        Ok(())
411    }
412
413    fn enqueue(&self, outbound: UserOutbound) -> Result<(), UserOutboundSendError> {
414        let bytes = outbound.queued_bytes();
415        self.reserve_bytes(bytes)?;
416        match self
417            .messages
418            .try_send(QueuedUserOutbound { outbound, bytes })
419        {
420            Ok(()) => {
421                self.metrics.add_ws_outbound_queued_messages(1);
422                Ok(())
423            }
424            Err(TrySendError::Full(_outbound)) => {
425                self.release_bytes(bytes);
426                let overflow = self.mark_overflow(
427                    UserOutboundOverflowKind::MessageCount,
428                    self.queued_bytes.load(Ordering::Acquire),
429                    bytes,
430                );
431                Err(UserOutboundSendError::Full(overflow))
432            }
433            Err(TrySendError::Closed(_outbound)) => {
434                self.release_bytes(bytes);
435                Err(UserOutboundSendError::Closed)
436            }
437        }
438    }
439
440    fn reserve_bytes(&self, bytes: usize) -> Result<(), UserOutboundSendError> {
441        let byte_capacity = self.limits.byte_capacity();
442        let mut queued = self.queued_bytes.load(Ordering::Acquire);
443        loop {
444            let Some(next) = queued
445                .checked_add(bytes)
446                .filter(|next| *next <= byte_capacity)
447            else {
448                let overflow =
449                    self.mark_overflow(UserOutboundOverflowKind::QueuedBytes, queued, bytes);
450                return Err(UserOutboundSendError::Full(overflow));
451            };
452            match self.queued_bytes.compare_exchange_weak(
453                queued,
454                next,
455                Ordering::AcqRel,
456                Ordering::Acquire,
457            ) {
458                Ok(_previous) => return Ok(()),
459                Err(current) => queued = current,
460            }
461        }
462    }
463
464    fn release_bytes(&self, bytes: usize) {
465        self.queued_bytes.fetch_sub(bytes, Ordering::AcqRel);
466    }
467
468    fn mark_overflow(
469        &self,
470        kind: UserOutboundOverflowKind,
471        queued_bytes: usize,
472        message_bytes: usize,
473    ) -> UserOutboundOverflow {
474        let overflow = UserOutboundOverflow::new(
475            kind,
476            self.limits.message_capacity(),
477            self.limits.byte_capacity(),
478            queued_bytes,
479            message_bytes,
480        );
481        self.metrics.record_ws_outbound_queue_overflow();
482        let _ = self.overflow.send(Some(overflow));
483        overflow
484    }
485}
486
487impl UserOutboundReceiver {
488    #[must_use]
489    pub fn has_overflowed(&self) -> bool {
490        self.overflow.borrow().is_some()
491    }
492
493    /// Receives queued output without observing overflow.
494    ///
495    /// User-session loops should use [`Self::recv_event`].
496    pub async fn recv(&mut self) -> Option<UserOutbound> {
497        self.messages
498            .recv()
499            .await
500            .map(|message| self.record_received(message))
501    }
502
503    /// Attempts to receive queued output without observing overflow.
504    ///
505    /// User-session loops should use [`Self::recv_event`].
506    ///
507    /// # Errors
508    ///
509    /// Returns [`mpsc::error::TryRecvError::Empty`] when no output is queued and
510    /// [`mpsc::error::TryRecvError::Disconnected`] when every sender is dropped.
511    pub fn try_recv(&mut self) -> Result<UserOutbound, mpsc::error::TryRecvError> {
512        self.messages
513            .try_recv()
514            .map(|message| self.record_received(message))
515    }
516
517    /// Receives the next queue event with overflow prioritized over queued output.
518    pub async fn recv_event(&mut self) -> UserOutboundEvent {
519        if let Some(overflow) = *self.overflow.borrow_and_update() {
520            return UserOutboundEvent::Overflow(overflow);
521        }
522        tokio::select! {
523            biased;
524            overflow = wait_for_overflow(&mut self.overflow) => {
525                UserOutboundEvent::Overflow(overflow)
526            }
527            message = self.messages.recv() => {
528                message.map_or(UserOutboundEvent::Closed, |message| {
529                    UserOutboundEvent::Message(self.record_received(message))
530                })
531            }
532        }
533    }
534
535    fn record_received(&self, message: QueuedUserOutbound) -> UserOutbound {
536        self.queued_bytes.fetch_sub(message.bytes, Ordering::AcqRel);
537        self.metrics.add_ws_outbound_queued_messages(-1);
538        message.outbound
539    }
540}
541
542impl Drop for UserOutboundReceiver {
543    fn drop(&mut self) {
544        let mut pending = 0_i64;
545        let mut bytes = 0_usize;
546        while let Ok(message) = self.messages.try_recv() {
547            pending = pending.saturating_add(1);
548            bytes = bytes.saturating_add(message.bytes);
549        }
550        if pending > 0 {
551            self.metrics.add_ws_outbound_queued_messages(-pending);
552        }
553        if bytes > 0 {
554            self.queued_bytes.fetch_sub(bytes, Ordering::AcqRel);
555        }
556    }
557}
558
559async fn wait_for_overflow(
560    overflow: &mut watch::Receiver<Option<UserOutboundOverflow>>,
561) -> UserOutboundOverflow {
562    loop {
563        if let Some(overflow) = *overflow.borrow_and_update() {
564            return overflow;
565        }
566        if overflow.changed().await.is_err() {
567            // A dropped overflow sender parks this arm forever, avoiding a busy
568            // loop and letting the message arm of the select resolve.
569            pending::<()>().await;
570        }
571    }
572}
573
574#[derive(Debug, Clone)]
575pub(in crate::engine) struct MessageFanout {
576    recipients: Vec<OutboundSender>,
577    message: RoomEventMessage,
578}
579
580impl MessageFanout {
581    pub(in crate::engine) fn emit(self) {
582        for recipient in self.recipients {
583            let _ = recipient.send(UserOutbound::Message(self.message.clone()));
584        }
585    }
586}
587
588pub(super) fn fanout_all(
589    recipients: impl IntoIterator<Item = OutboundSender>,
590    message: RoomEventMessage,
591) -> MessageFanout {
592    MessageFanout {
593        recipients: recipients.into_iter().collect(),
594        message,
595    }
596}