提交 c6783a45 authored 作者: Nazar Mokrynskyi's avatar Nazar Mokrynskyi

Optimize notifications handling

上级 336c398e
......@@ -2,6 +2,7 @@ use criterion::async_executor::FuturesExecutor;
use criterion::{criterion_group, criterion_main, Criterion};
use futures_lite::StreamExt;
use mediasoup::prelude::*;
use std::borrow::Cow;
async fn create_data_producer_consumer_pair(
) -> Result<(DataProducer, DataConsumer), Box<dyn std::error::Error>> {
......@@ -47,7 +48,7 @@ pub fn criterion_benchmark(c: &mut Criterion) {
group.bench_with_input("send", &data, |b, data| {
b.to_async(FuturesExecutor).iter(|| async {
let _ = direct_data_producer
.send(WebRtcMessage::Binary(data.clone()))
.send(WebRtcMessage::Binary(Cow::from(data)))
.await;
})
});
......@@ -72,7 +73,7 @@ pub fn criterion_benchmark(c: &mut Criterion) {
});
let _ = direct_data_producer
.send(WebRtcMessage::Binary(data.clone()))
.send(WebRtcMessage::Binary(Cow::from(data)))
.await;
let _ = receiver.next().await;
......
......@@ -769,18 +769,18 @@ pub enum TraceEventDirection {
/// Container used for sending/receiving messages using `DirectTransport` data producers and data
/// consumers.
#[derive(Debug, Clone)]
pub enum WebRtcMessage {
pub enum WebRtcMessage<'a> {
/// String
String(String),
/// Binary
Binary(Vec<u8>),
Binary(Cow<'a, [u8]>),
/// EmptyString
EmptyString,
/// EmptyBinary
EmptyBinary,
}
impl WebRtcMessage {
impl<'a> WebRtcMessage<'a> {
// +------------------------------------+-----------+
// | Value | SCTP PPID |
// +------------------------------------+-----------+
......@@ -792,7 +792,7 @@ impl WebRtcMessage {
// | WebRTC Binary Empty | 57 |
// +------------------------------------+-----------+
pub(crate) fn new(ppid: u32, payload: Vec<u8>) -> Result<Self, u32> {
pub(crate) fn new(ppid: u32, payload: Cow<'a, [u8]>) -> Result<Self, u32> {
match ppid {
51 => Ok(WebRtcMessage::String(
String::from_utf8(payload.to_vec()).unwrap(),
......@@ -804,12 +804,12 @@ impl WebRtcMessage {
}
}
pub(crate) fn into_ppid_and_payload(self) -> (u32, Vec<u8>) {
pub(crate) fn into_ppid_and_payload(self) -> (u32, Cow<'a, [u8]>) {
match self {
WebRtcMessage::String(string) => (51_u32, string.into_bytes()),
WebRtcMessage::String(string) => (51_u32, Cow::from(string.into_bytes())),
WebRtcMessage::Binary(binary) => (53_u32, binary),
WebRtcMessage::EmptyString => (56_u32, Vec::from(b" ".as_ref())),
WebRtcMessage::EmptyBinary => (57_u32, vec![0_u8]),
WebRtcMessage::EmptyString => (56_u32, Cow::from(b" ".as_ref())),
WebRtcMessage::EmptyBinary => (57_u32, Cow::from(vec![0_u8])),
}
}
}
......
......@@ -13,9 +13,7 @@ use crate::rtp_parameters::{MediaKind, MimeType, RtpCapabilities, RtpParameters}
use crate::scalability_modes::ScalabilityMode;
use crate::transport::Transport;
use crate::uuid_based_wrapper_type;
use crate::worker::{
Channel, NotificationMessage, PayloadChannel, RequestError, SubscriptionHandler,
};
use crate::worker::{Channel, PayloadChannel, RequestError, SubscriptionHandler};
use async_executor::Executor;
use event_listener_primitives::{Bag, BagOnce, HandlerId};
use log::{debug, error};
......@@ -346,7 +344,7 @@ enum PayloadNotification {
#[derive(Default)]
struct Handlers {
rtp: Bag<Box<dyn Fn(&Vec<u8>) + Send + Sync>>,
rtp: Bag<Box<dyn Fn(&[u8]) + Send + Sync>>,
pause: Bag<Box<dyn Fn() + Send + Sync>>,
resume: Bag<Box<dyn Fn() + Send + Sync>>,
producer_pause: Bag<Box<dyn Fn() + Send + Sync>>,
......@@ -558,13 +556,12 @@ impl Consumer {
let payload_subscription_handler = {
let handlers = Arc::clone(&handlers);
payload_channel.subscribe_to_notifications(id.into(), move |notification| {
let NotificationMessage { message, payload } = notification;
payload_channel.subscribe_to_notifications(id.into(), move |message, payload| {
match serde_json::from_value::<PayloadNotification>(message) {
Ok(notification) => match notification {
PayloadNotification::Rtp => {
handlers.rtp.call(|callback| {
callback(&payload);
callback(payload);
});
}
},
......@@ -867,7 +864,7 @@ impl Consumer {
/// # Notes on usage
/// Just available in direct transports, this is, those created via
/// [`Router::create_direct_transport`](crate::router::Router::create_direct_transport).
pub fn on_rtp<F: Fn(&Vec<u8>) + Send + Sync + 'static>(&self, callback: F) -> HandlerId {
pub fn on_rtp<F: Fn(&[u8]) + Send + Sync + 'static>(&self, callback: F) -> HandlerId {
self.inner.handlers.rtp.add(Box::new(callback))
}
......
......@@ -12,14 +12,13 @@ use crate::messages::{
use crate::sctp_parameters::SctpStreamParameters;
use crate::transport::Transport;
use crate::uuid_based_wrapper_type;
use crate::worker::{
Channel, NotificationMessage, PayloadChannel, RequestError, SubscriptionHandler,
};
use crate::worker::{Channel, PayloadChannel, RequestError, SubscriptionHandler};
use async_executor::Executor;
use event_listener_primitives::{Bag, BagOnce, HandlerId};
use log::{debug, error};
use parking_lot::Mutex;
use serde::{Deserialize, Serialize};
use std::borrow::Cow;
use std::fmt;
use std::fmt::Debug;
use std::sync::atomic::{AtomicBool, Ordering};
......@@ -184,7 +183,7 @@ enum PayloadNotification {
#[derive(Default)]
struct Handlers {
message: Bag<Box<dyn Fn(&WebRtcMessage) + Send + Sync>>,
message: Bag<Box<dyn Fn(&WebRtcMessage<'_>) + Send + Sync>>,
sctp_send_buffer_full: Bag<Box<dyn Fn() + Send + Sync>>,
buffered_amount_low: Bag<Box<dyn Fn(u32) + Send + Sync>>,
data_producer_close: BagOnce<Box<dyn FnOnce() + Send>>,
......@@ -401,12 +400,11 @@ impl DataConsumer {
let payload_subscription_handler = {
let handlers = Arc::clone(&handlers);
payload_channel.subscribe_to_notifications(id.into(), move |notification| {
let NotificationMessage { message, payload } = notification;
payload_channel.subscribe_to_notifications(id.into(), move |message, payload| {
match serde_json::from_value::<PayloadNotification>(message) {
Ok(notification) => match notification {
PayloadNotification::Message { ppid } => {
match WebRtcMessage::new(ppid, payload) {
match WebRtcMessage::new(ppid, Cow::from(payload)) {
Ok(message) => {
handlers.message.call(|callback| {
callback(&message);
......@@ -586,7 +584,7 @@ impl DataConsumer {
/// # Notes on usage
/// Just available in direct transports, this is, those created via
/// [`Router::create_direct_transport`](crate::router::Router::create_direct_transport).
pub fn on_message<F: Fn(&WebRtcMessage) + Send + Sync + 'static>(
pub fn on_message<F: Fn(&WebRtcMessage<'_>) + Send + Sync + 'static>(
&self,
callback: F,
) -> HandlerId {
......@@ -675,7 +673,7 @@ impl DataConsumer {
impl DirectDataConsumer {
/// Sends direct messages from the Rust process.
pub async fn send(&self, message: WebRtcMessage) -> Result<(), RequestError> {
pub async fn send<'a>(&self, message: WebRtcMessage<'a>) -> Result<(), RequestError> {
let (ppid, payload) = message.into_ppid_and_payload();
self.inner
......@@ -690,7 +688,7 @@ impl DirectDataConsumer {
},
data: DataConsumerSendRequestData { ppid },
},
payload,
payload.into_owned(),
)
.await
}
......
......@@ -441,7 +441,7 @@ impl DataProducer {
impl DirectDataProducer {
/// Sends direct messages from the Rust process.
pub async fn send(&self, message: WebRtcMessage) -> Result<(), NotificationError> {
pub async fn send<'a>(&self, message: WebRtcMessage<'a>) -> Result<(), NotificationError> {
let (ppid, payload) = message.into_ppid_and_payload();
self.inner
......@@ -455,7 +455,7 @@ impl DirectDataProducer {
},
data: DataProducerSendData { ppid },
},
payload,
payload.into_owned(),
)
.await
}
......
......@@ -16,8 +16,7 @@ use crate::transport::{
TransportTraceEventType,
};
use crate::worker::{
Channel, NotificationError, NotificationMessage, PayloadChannel, RequestError,
SubscriptionHandler,
Channel, NotificationError, PayloadChannel, RequestError, SubscriptionHandler,
};
use async_executor::Executor;
use async_trait::async_trait;
......@@ -112,7 +111,7 @@ pub struct DirectTransportStat {
#[derive(Default)]
struct Handlers {
rtcp: Bag<Box<dyn Fn(&Vec<u8>) + Send + Sync>>,
rtcp: Bag<Box<dyn Fn(&[u8]) + Send + Sync>>,
new_producer: Bag<Box<dyn Fn(&Producer) + Send + Sync>>,
new_consumer: Bag<Box<dyn Fn(&Consumer) + Send + Sync>>,
new_data_producer: Bag<Box<dyn Fn(&DataProducer) + Send + Sync>>,
......@@ -481,13 +480,12 @@ impl DirectTransport {
let payload_subscription_handler = {
let handlers = Arc::clone(&handlers);
payload_channel.subscribe_to_notifications(id.into(), move |notification| {
let NotificationMessage { message, payload } = notification;
payload_channel.subscribe_to_notifications(id.into(), move |message, payload| {
match serde_json::from_value::<PayloadNotification>(message) {
Ok(notification) => match notification {
PayloadNotification::Rtcp => {
handlers.rtcp.call(|callback| {
callback(&payload);
callback(payload);
});
}
},
......@@ -549,7 +547,7 @@ impl DirectTransport {
}
/// Callback is called when the direct transport receives a RTCP packet from its router.
pub fn on_rtcp<F: Fn(&Vec<u8>) + Send + Sync + 'static>(&self, callback: F) -> HandlerId {
pub fn on_rtcp<F: Fn(&[u8]) + Send + Sync + 'static>(&self, callback: F) -> HandlerId {
self.inner.handlers.rtcp.add(Box::new(callback))
}
......
......@@ -24,7 +24,7 @@ use event_listener_primitives::{Bag, BagOnce, HandlerId};
use futures_lite::FutureExt;
use log::{debug, error, warn};
use parking_lot::Mutex;
pub(crate) use payload_channel::{NotificationError, NotificationMessage, PayloadChannel};
pub(crate) use payload_channel::{NotificationError, PayloadChannel};
use serde::{Deserialize, Serialize};
use std::ops::RangeInclusive;
use std::path::PathBuf;
......
......@@ -40,7 +40,7 @@ pub(super) enum InternalMessage {
pub(crate) struct BufferMessagesGuard {
target_id: SubscriptionTarget,
buffered_notifications_for: Arc<Mutex<HashMap<SubscriptionTarget, Vec<Value>>>>,
event_handlers_weak: WeakEventHandlers<Value>,
event_handlers_weak: WeakEventHandlers<Arc<dyn Fn(Value) + Send + Sync + 'static>>,
}
impl Drop for BufferMessagesGuard {
......@@ -49,7 +49,7 @@ impl Drop for BufferMessagesGuard {
if let Some(notifications) = buffered_notifications_for.remove(&self.target_id) {
if let Some(event_handlers) = self.event_handlers_weak.upgrade() {
for notification in notifications {
event_handlers.call_callbacks_with_value(&self.target_id, notification);
event_handlers.call_callbacks_with_single_value(&self.target_id, notification);
}
}
}
......@@ -120,7 +120,7 @@ struct Inner {
internal_message_receiver: async_channel::Receiver<InternalMessage>,
requests_container_weak: Weak<Mutex<RequestsContainer>>,
buffered_notifications_for: Arc<Mutex<HashMap<SubscriptionTarget, Vec<Value>>>>,
event_handlers_weak: WeakEventHandlers<Value>,
event_handlers_weak: WeakEventHandlers<Arc<dyn Fn(Value) + Send + Sync + 'static>>,
}
impl Drop for Inner {
......@@ -225,7 +225,8 @@ impl Channel {
// Remember we don't need to buffer these
non_buffered_notifications.put(target_id, ());
}
event_handlers.call_callbacks_with_value(&target_id, notification);
event_handlers
.call_callbacks_with_single_value(&target_id, notification);
} else {
let unexpected_message =
InternalMessage::Unexpected(Vec::from(message));
......@@ -401,6 +402,6 @@ impl Channel {
self.inner
.event_handlers_weak
.upgrade()
.map(|event_handlers| event_handlers.add(target_id, Box::new(callback)))
.map(|event_handlers| event_handlers.add(target_id, Arc::new(callback)))
}
}
......@@ -3,13 +3,13 @@ use std::collections::HashMap;
use std::sync::{Arc, Weak};
use uuid::Uuid;
struct EventHandlersList<V: Clone + 'static> {
struct EventHandlersList<F> {
index: usize,
#[allow(clippy::type_complexity)]
callbacks: HashMap<usize, Arc<dyn Fn(V) + Send + Sync>>,
callbacks: HashMap<usize, F>,
}
impl<V: Clone + 'static> Default for EventHandlersList<V> {
impl<F> Default for EventHandlersList<F> {
fn default() -> Self {
Self {
index: 0,
......@@ -19,21 +19,17 @@ impl<V: Clone + 'static> Default for EventHandlersList<V> {
}
#[derive(Clone)]
pub(super) struct EventHandlers<V: Clone + 'static> {
handlers: Arc<Mutex<HashMap<SubscriptionTarget, EventHandlersList<V>>>>,
pub(super) struct EventHandlers<F> {
handlers: Arc<Mutex<HashMap<SubscriptionTarget, EventHandlersList<F>>>>,
}
impl<V: Clone + 'static> EventHandlers<V> {
impl<F: Sized + Send + Sync + 'static> EventHandlers<F> {
pub(super) fn new() -> Self {
let handlers = Arc::<Mutex<HashMap<SubscriptionTarget, EventHandlersList<V>>>>::default();
let handlers = Arc::<Mutex<HashMap<SubscriptionTarget, EventHandlersList<F>>>>::default();
Self { handlers }
}
pub(super) fn add(
&self,
target_id: SubscriptionTarget,
callback: Box<dyn Fn(V) + Send + Sync + 'static>,
) -> SubscriptionHandler {
pub(super) fn add(&self, target_id: SubscriptionTarget, callback: F) -> SubscriptionHandler {
let index;
{
let mut event_handlers = self.handlers.lock();
......@@ -42,7 +38,7 @@ impl<V: Clone + 'static> EventHandlers<V> {
.or_insert_with(EventHandlersList::default);
index = list.index;
list.index += 1;
list.callbacks.insert(index, Arc::new(Box::new(callback)));
list.callbacks.insert(index, callback);
drop(event_handlers);
}
......@@ -75,7 +71,19 @@ impl<V: Clone + 'static> EventHandlers<V> {
})
}
pub(super) fn call_callbacks_with_value(&self, target_id: &SubscriptionTarget, value: V) {
pub(super) fn downgrade(&self) -> WeakEventHandlers<F> {
WeakEventHandlers {
handlers: Arc::downgrade(&self.handlers),
}
}
}
impl<V: Clone> EventHandlers<Arc<dyn Fn(V) + Send + Sync + 'static>> {
pub(super) fn call_callbacks_with_single_value(
&self,
target_id: &SubscriptionTarget,
value: V,
) {
let handlers = self.handlers.lock();
if let Some(list) = handlers.get(target_id) {
// Tiny optimization that avoids cloning `value` unless necessary
......@@ -94,21 +102,42 @@ impl<V: Clone + 'static> EventHandlers<V> {
}
}
}
}
pub(super) fn downgrade(&self) -> WeakEventHandlers<V> {
WeakEventHandlers {
handlers: Arc::downgrade(&self.handlers),
impl<V1: Clone, V2: ?Sized> EventHandlers<Arc<dyn Fn(V1, &V2) + Send + Sync + 'static>> {
pub(super) fn call_callbacks_with_two_values(
&self,
target_id: &SubscriptionTarget,
value1: V1,
value2: &V2,
) {
let handlers = self.handlers.lock();
if let Some(list) = handlers.get(target_id) {
// Tiny optimization that avoids cloning `value` unless necessary
if list.callbacks.len() == 1 {
let callback = list.callbacks.values().next().cloned().unwrap();
// Drop mutex guard before running callbacks to avoid deadlocks
drop(handlers);
callback(value1, value2);
} else {
let callbacks = list.callbacks.values().cloned().collect::<Vec<_>>();
// Drop mutex guard before running callbacks to avoid deadlocks
drop(handlers);
for callback in callbacks {
callback(value1.clone(), value2);
}
}
}
}
}
#[derive(Clone)]
pub(super) struct WeakEventHandlers<V: Clone + 'static> {
handlers: Weak<Mutex<HashMap<SubscriptionTarget, EventHandlersList<V>>>>,
pub(super) struct WeakEventHandlers<F> {
handlers: Weak<Mutex<HashMap<SubscriptionTarget, EventHandlersList<F>>>>,
}
impl<V: Clone + 'static> WeakEventHandlers<V> {
pub(super) fn upgrade(&self) -> Option<EventHandlers<V>> {
impl<F> WeakEventHandlers<F> {
pub(super) fn upgrade(&self) -> Option<EventHandlers<F>> {
self.handlers
.upgrade()
.map(|handlers| EventHandlers { handlers })
......
......@@ -22,12 +22,6 @@ pub(super) enum InternalMessage {
UnexpectedData(Vec<u8>),
}
#[derive(Clone)]
pub(crate) struct NotificationMessage {
pub(crate) message: Value,
pub(crate) payload: Vec<u8>,
}
#[derive(Debug, Deserialize)]
#[serde(untagged)]
enum PayloadChannelReceiveMessage {
......@@ -89,7 +83,7 @@ struct Inner {
outgoing_message_buffer: Arc<Mutex<OutgoingMessageBuffer>>,
internal_message_receiver: async_channel::Receiver<InternalMessage>,
requests_container_weak: Weak<Mutex<RequestsContainer>>,
event_handlers_weak: WeakEventHandlers<NotificationMessage>,
event_handlers_weak: WeakEventHandlers<Arc<dyn Fn(Value, &[u8]) + Send + Sync + 'static>>,
}
impl Drop for Inner {
......@@ -179,15 +173,11 @@ impl PayloadChannel {
trace!("received notification payload of {} bytes", payload.len());
let payload = Vec::from(payload);
if let Some(target_id) = target_id {
event_handlers.call_callbacks_with_value(
event_handlers.call_callbacks_with_two_values(
&target_id,
NotificationMessage {
message: notification,
payload,
},
notification,
payload,
);
} else {
let unexpected_message =
......@@ -394,11 +384,11 @@ impl PayloadChannel {
callback: F,
) -> Option<SubscriptionHandler>
where
F: Fn(NotificationMessage) + Send + Sync + 'static,
F: Fn(Value, &[u8]) + Send + Sync + 'static,
{
self.inner
.event_handlers_weak
.upgrade()
.map(|event_handlers| event_handlers.add(target_id, Box::new(callback)))
.map(|event_handlers| event_handlers.add(target_id, Arc::new(callback)))
}
}
......@@ -8,6 +8,7 @@ use mediasoup::router::{Router, RouterOptions};
use mediasoup::worker::{Worker, WorkerSettings};
use mediasoup::worker_manager::WorkerManager;
use parking_lot::Mutex;
use std::borrow::Cow;
use std::collections::HashSet;
use std::env;
use std::sync::atomic::{AtomicUsize, Ordering};
......@@ -241,7 +242,7 @@ fn send_succeeds() {
} else {
let content = id.to_string().into_bytes();
sent_message_bytes += content.len();
WebRtcMessage::Binary(content)
WebRtcMessage::Binary(Cow::from(content))
};
direct_data_producer
......
Markdown 格式
0% 或
您添加了 0 人 到此讨论。请谨慎行事。
请先完成此评论的编辑!
请 注册 或者 后发表评论