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

Apply similar optimizations to channel communication

上级 4d4b97be
...@@ -211,7 +211,7 @@ class Channel extends EnhancedEventEmitter_1.EnhancedEventEmitter { ...@@ -211,7 +211,7 @@ class Channel extends EnhancedEventEmitter_1.EnhancedEventEmitter {
// the response, destroying the ordered delivery. So we must wait a bit // the response, destroying the ordered delivery. So we must wait a bit
// here. // here.
// See https://github.com/versatica/mediasoup/issues/510 // See https://github.com/versatica/mediasoup/issues/510
setImmediate(() => this.emit(msg.targetId, msg.event, msg.data)); setImmediate(() => this.emit(String(msg.targetId), msg.event, msg.data));
} }
// Otherwise unexpected message. // Otherwise unexpected message.
else { else {
......
...@@ -215,7 +215,7 @@ class PayloadChannel extends EnhancedEventEmitter_1.EnhancedEventEmitter { ...@@ -215,7 +215,7 @@ class PayloadChannel extends EnhancedEventEmitter_1.EnhancedEventEmitter {
else if (msg.targetId && msg.event) { else if (msg.targetId && msg.event) {
this._ongoingNotification = this._ongoingNotification =
{ {
targetId: msg.targetId, targetId: String(msg.targetId),
event: msg.event, event: msg.event,
data: msg.data data: msg.data
}; };
......
...@@ -305,7 +305,7 @@ impl ActiveSpeakerObserver { ...@@ -305,7 +305,7 @@ impl ActiveSpeakerObserver {
let handlers = Arc::clone(&handlers); let handlers = Arc::clone(&handlers);
channel.subscribe_to_notifications(id.into(), move |notification| { channel.subscribe_to_notifications(id.into(), move |notification| {
match serde_json::from_value::<Notification>(notification) { match serde_json::from_slice::<Notification>(notification) {
Ok(notification) => match notification { Ok(notification) => match notification {
Notification::DominantSpeaker(dominant_speaker) => { Notification::DominantSpeaker(dominant_speaker) => {
let DominantSpeakerNotification { producer_id } = dominant_speaker; let DominantSpeakerNotification { producer_id } = dominant_speaker;
......
...@@ -319,7 +319,7 @@ impl AudioLevelObserver { ...@@ -319,7 +319,7 @@ impl AudioLevelObserver {
let handlers = Arc::clone(&handlers); let handlers = Arc::clone(&handlers);
channel.subscribe_to_notifications(id.into(), move |notification| { channel.subscribe_to_notifications(id.into(), move |notification| {
match serde_json::from_value::<Notification>(notification) { match serde_json::from_slice::<Notification>(notification) {
Ok(notification) => match notification { Ok(notification) => match notification {
Notification::Volumes(volumes) => { Notification::Volumes(volumes) => {
let volumes = volumes let volumes = volumes
......
...@@ -493,7 +493,7 @@ impl Consumer { ...@@ -493,7 +493,7 @@ impl Consumer {
let inner_weak = Arc::clone(&inner_weak); let inner_weak = Arc::clone(&inner_weak);
channel.subscribe_to_notifications(id.into(), move |notification| { channel.subscribe_to_notifications(id.into(), move |notification| {
match serde_json::from_value::<Notification>(notification) { match serde_json::from_slice::<Notification>(notification) {
Ok(notification) => match notification { Ok(notification) => match notification {
Notification::ProducerClose => { Notification::ProducerClose => {
if !closed.load(Ordering::SeqCst) { if !closed.load(Ordering::SeqCst) {
......
...@@ -369,7 +369,7 @@ impl DataConsumer { ...@@ -369,7 +369,7 @@ impl DataConsumer {
let inner_weak = Arc::clone(&inner_weak); let inner_weak = Arc::clone(&inner_weak);
channel.subscribe_to_notifications(id.into(), move |notification| { channel.subscribe_to_notifications(id.into(), move |notification| {
match serde_json::from_value::<Notification>(notification) { match serde_json::from_slice::<Notification>(notification) {
Ok(notification) => match notification { Ok(notification) => match notification {
Notification::DataProducerClose => { Notification::DataProducerClose => {
if !closed.load(Ordering::SeqCst) { if !closed.load(Ordering::SeqCst) {
......
...@@ -462,7 +462,7 @@ impl DirectTransport { ...@@ -462,7 +462,7 @@ impl DirectTransport {
let handlers = Arc::clone(&handlers); let handlers = Arc::clone(&handlers);
channel.subscribe_to_notifications(id.into(), move |notification| { channel.subscribe_to_notifications(id.into(), move |notification| {
match serde_json::from_value::<Notification>(notification) { match serde_json::from_slice::<Notification>(notification) {
Ok(notification) => match notification { Ok(notification) => match notification {
Notification::Trace(trace_event_data) => { Notification::Trace(trace_event_data) => {
handlers.trace.call(|callback| { handlers.trace.call(|callback| {
......
...@@ -490,7 +490,7 @@ impl PipeTransport { ...@@ -490,7 +490,7 @@ impl PipeTransport {
let data = Arc::clone(&data); let data = Arc::clone(&data);
channel.subscribe_to_notifications(id.into(), move |notification| { channel.subscribe_to_notifications(id.into(), move |notification| {
match serde_json::from_value::<Notification>(notification) { match serde_json::from_slice::<Notification>(notification) {
Ok(notification) => match notification { Ok(notification) => match notification {
Notification::SctpStateChange { sctp_state } => { Notification::SctpStateChange { sctp_state } => {
data.sctp_state.lock().replace(sctp_state); data.sctp_state.lock().replace(sctp_state);
......
...@@ -520,7 +520,7 @@ impl PlainTransport { ...@@ -520,7 +520,7 @@ impl PlainTransport {
let data = Arc::clone(&data); let data = Arc::clone(&data);
channel.subscribe_to_notifications(id.into(), move |notification| { channel.subscribe_to_notifications(id.into(), move |notification| {
match serde_json::from_value::<Notification>(notification) { match serde_json::from_slice::<Notification>(notification) {
Ok(notification) => match notification { Ok(notification) => match notification {
Notification::Tuple { tuple } => { Notification::Tuple { tuple } => {
*data.tuple.lock() = tuple; *data.tuple.lock() = tuple;
......
...@@ -461,7 +461,7 @@ impl Producer { ...@@ -461,7 +461,7 @@ impl Producer {
let score = Arc::clone(&score); let score = Arc::clone(&score);
channel.subscribe_to_notifications(id.into(), move |notification| { channel.subscribe_to_notifications(id.into(), move |notification| {
match serde_json::from_value::<Notification>(notification) { match serde_json::from_slice::<Notification>(notification) {
Ok(notification) => match notification { Ok(notification) => match notification {
Notification::Score(scores) => { Notification::Score(scores) => {
*score.lock() = scores.clone(); *score.lock() = scores.clone();
......
...@@ -575,7 +575,7 @@ impl WebRtcTransport { ...@@ -575,7 +575,7 @@ impl WebRtcTransport {
let data = Arc::clone(&data); let data = Arc::clone(&data);
channel.subscribe_to_notifications(id.into(), move |notification| { channel.subscribe_to_notifications(id.into(), move |notification| {
match serde_json::from_value::<Notification>(notification) { match serde_json::from_slice::<Notification>(notification) {
Ok(notification) => match notification { Ok(notification) => match notification {
Notification::IceStateChange { ice_state } => { Notification::IceStateChange { ice_state } => {
*data.ice_state.lock() = ice_state; *data.ice_state.lock() = ice_state;
......
...@@ -430,7 +430,7 @@ impl Inner { ...@@ -430,7 +430,7 @@ impl Inner {
let _handler = self.channel.subscribe_to_notifications( let _handler = self.channel.subscribe_to_notifications(
std::process::id().into(), std::process::id().into(),
move |notification| { move |notification| {
let result = match serde_json::from_value(notification.clone()) { let result = match serde_json::from_slice(notification) {
Ok(Notification::Running) => { Ok(Notification::Running) => {
debug!("worker thread running [id:{}]", id); debug!("worker thread running [id:{}]", id);
Ok(()) Ok(())
......
...@@ -39,8 +39,8 @@ pub(super) enum InternalMessage { ...@@ -39,8 +39,8 @@ pub(super) enum InternalMessage {
pub(crate) struct BufferMessagesGuard { pub(crate) struct BufferMessagesGuard {
target_id: SubscriptionTarget, target_id: SubscriptionTarget,
buffered_notifications_for: Arc<Mutex<HashMap<SubscriptionTarget, Vec<Value>>>>, buffered_notifications_for: Arc<Mutex<HashMap<SubscriptionTarget, Vec<Vec<u8>>>>>,
event_handlers_weak: WeakEventHandlers<Arc<dyn Fn(Value) + Send + Sync + 'static>>, event_handlers_weak: WeakEventHandlers<Arc<dyn Fn(&[u8]) + Send + Sync + 'static>>,
} }
impl Drop for BufferMessagesGuard { impl Drop for BufferMessagesGuard {
...@@ -49,7 +49,7 @@ 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(notifications) = buffered_notifications_for.remove(&self.target_id) {
if let Some(event_handlers) = self.event_handlers_weak.upgrade() { if let Some(event_handlers) = self.event_handlers_weak.upgrade() {
for notification in notifications { for notification in notifications {
event_handlers.call_callbacks_with_single_value(&self.target_id, notification); event_handlers.call_callbacks_with_single_value(&self.target_id, &notification);
} }
} }
} }
...@@ -59,6 +59,10 @@ impl Drop for BufferMessagesGuard { ...@@ -59,6 +59,10 @@ impl Drop for BufferMessagesGuard {
#[derive(Debug, Deserialize)] #[derive(Debug, Deserialize)]
#[serde(untagged)] #[serde(untagged)]
enum ChannelReceiveMessage { enum ChannelReceiveMessage {
#[serde(rename_all = "camelCase")]
Notification {
target_id: SubscriptionTarget,
},
ResponseSuccess { ResponseSuccess {
id: u32, id: u32,
accepted: bool, accepted: bool,
...@@ -69,7 +73,6 @@ enum ChannelReceiveMessage { ...@@ -69,7 +73,6 @@ enum ChannelReceiveMessage {
error: Value, error: Value,
reason: String, reason: String,
}, },
Notification(Value),
Event(InternalMessage), Event(InternalMessage),
} }
...@@ -119,8 +122,8 @@ struct Inner { ...@@ -119,8 +122,8 @@ struct Inner {
outgoing_message_buffer: Arc<Mutex<OutgoingMessageBuffer>>, outgoing_message_buffer: Arc<Mutex<OutgoingMessageBuffer>>,
internal_message_receiver: async_channel::Receiver<InternalMessage>, internal_message_receiver: async_channel::Receiver<InternalMessage>,
requests_container_weak: Weak<Mutex<RequestsContainer>>, requests_container_weak: Weak<Mutex<RequestsContainer>>,
buffered_notifications_for: Arc<Mutex<HashMap<SubscriptionTarget, Vec<Value>>>>, buffered_notifications_for: Arc<Mutex<HashMap<SubscriptionTarget, Vec<Vec<u8>>>>>,
event_handlers_weak: WeakEventHandlers<Arc<dyn Fn(Value) + Send + Sync + 'static>>, event_handlers_weak: WeakEventHandlers<Arc<dyn Fn(&[u8]) + Send + Sync + 'static>>,
} }
impl Drop for Inner { impl Drop for Inner {
...@@ -143,7 +146,7 @@ impl Channel { ...@@ -143,7 +146,7 @@ impl Channel {
let requests_container = Arc::<Mutex<RequestsContainer>>::default(); let requests_container = Arc::<Mutex<RequestsContainer>>::default();
let requests_container_weak = Arc::downgrade(&requests_container); let requests_container_weak = Arc::downgrade(&requests_container);
let buffered_notifications_for = let buffered_notifications_for =
Arc::<Mutex<HashMap<SubscriptionTarget, Vec<Value>>>>::default(); Arc::<Mutex<HashMap<SubscriptionTarget, Vec<Vec<u8>>>>>::default();
let event_handlers = EventHandlers::new(); let event_handlers = EventHandlers::new();
let event_handlers_weak = event_handlers.downgrade(); let event_handlers_weak = event_handlers.downgrade();
...@@ -172,6 +175,21 @@ impl Channel { ...@@ -172,6 +175,21 @@ impl Channel {
trace!("received raw message: {}", String::from_utf8_lossy(message)); trace!("received raw message: {}", String::from_utf8_lossy(message));
match deserialize_message(message) { match deserialize_message(message) {
ChannelReceiveMessage::Notification { target_id } => {
if !non_buffered_notifications.contains(&target_id) {
let mut buffer_notifications_for = buffered_notifications_for.lock();
// Check if we need to buffer notifications for this
// target_id
if let Some(list) = buffer_notifications_for.get_mut(&target_id) {
list.push(Vec::from(message));
return;
}
// Remember we don't need to buffer these
non_buffered_notifications.put(target_id, ());
}
event_handlers.call_callbacks_with_single_value(&target_id, message);
}
ChannelReceiveMessage::ResponseSuccess { ChannelReceiveMessage::ResponseSuccess {
id, id,
accepted: _, accepted: _,
...@@ -202,37 +220,6 @@ impl Channel { ...@@ -202,37 +220,6 @@ impl Channel {
); );
} }
} }
ChannelReceiveMessage::Notification(notification) => {
let target_id = notification.get("targetId").and_then(|value| {
let str = value.as_str()?;
str.parse()
.ok()
.map(SubscriptionTarget::Uuid)
.or_else(|| str.parse().ok().map(SubscriptionTarget::Number))
});
if let Some(target_id) = target_id {
if !non_buffered_notifications.contains(&target_id) {
let mut buffer_notifications_for =
buffered_notifications_for.lock();
// Check if we need to buffer notifications for this
// target_id
if let Some(list) = buffer_notifications_for.get_mut(&target_id) {
list.push(notification);
return;
}
// Remember we don't need to buffer these
non_buffered_notifications.put(target_id, ());
}
event_handlers
.call_callbacks_with_single_value(&target_id, notification);
} else {
let unexpected_message =
InternalMessage::Unexpected(Vec::from(message));
let _ = internal_message_sender.try_send(unexpected_message);
}
}
ChannelReceiveMessage::Event(event_message) => { ChannelReceiveMessage::Event(event_message) => {
let _ = internal_message_sender.try_send(event_message); let _ = internal_message_sender.try_send(event_message);
} }
...@@ -390,7 +377,7 @@ impl Channel { ...@@ -390,7 +377,7 @@ impl Channel {
callback: F, callback: F,
) -> Option<SubscriptionHandler> ) -> Option<SubscriptionHandler>
where where
F: Fn(Value) + Send + Sync + 'static, F: Fn(&[u8]) + Send + Sync + 'static,
{ {
self.inner self.inner
.event_handlers_weak .event_handlers_weak
......
...@@ -79,11 +79,11 @@ impl<F: Sized + Send + Sync + 'static> EventHandlers<F> { ...@@ -79,11 +79,11 @@ impl<F: Sized + Send + Sync + 'static> EventHandlers<F> {
} }
} }
impl<V: Clone> EventHandlers<Arc<dyn Fn(V) + Send + Sync + 'static>> { impl<V: ?Sized> EventHandlers<Arc<dyn Fn(&V) + Send + Sync + 'static>> {
pub(super) fn call_callbacks_with_single_value( pub(super) fn call_callbacks_with_single_value(
&self, &self,
target_id: &SubscriptionTarget, target_id: &SubscriptionTarget,
value: V, value: &V,
) { ) {
let handlers = self.handlers.lock(); let handlers = self.handlers.lock();
if let Some(list) = handlers.get(target_id) { if let Some(list) = handlers.get(target_id) {
...@@ -98,7 +98,7 @@ impl<V: Clone> EventHandlers<Arc<dyn Fn(V) + Send + Sync + 'static>> { ...@@ -98,7 +98,7 @@ impl<V: Clone> EventHandlers<Arc<dyn Fn(V) + Send + Sync + 'static>> {
// Drop mutex guard before running callbacks to avoid deadlocks // Drop mutex guard before running callbacks to avoid deadlocks
drop(handlers); drop(handlers);
for callback in callbacks { for callback in callbacks {
callback(value.clone()); callback(value);
} }
} }
} }
...@@ -149,11 +149,17 @@ impl<F> WeakEventHandlers<F> { ...@@ -149,11 +149,17 @@ impl<F> WeakEventHandlers<F> {
#[serde(untagged)] #[serde(untagged)]
pub(crate) enum SubscriptionTarget { pub(crate) enum SubscriptionTarget {
Uuid(Uuid), Uuid(Uuid),
Number(u32), Number(u64),
} }
impl From<u32> for SubscriptionTarget { impl From<u32> for SubscriptionTarget {
fn from(number: u32) -> Self { fn from(number: u32) -> Self {
Self::Number(u64::from(number))
}
}
impl From<u64> for SubscriptionTarget {
fn from(number: u64) -> Self {
Self::Number(number) Self::Number(number)
} }
} }
......
...@@ -342,7 +342,7 @@ export class Channel extends EnhancedEventEmitter ...@@ -342,7 +342,7 @@ export class Channel extends EnhancedEventEmitter
// the response, destroying the ordered delivery. So we must wait a bit // the response, destroying the ordered delivery. So we must wait a bit
// here. // here.
// See https://github.com/versatica/mediasoup/issues/510 // See https://github.com/versatica/mediasoup/issues/510
setImmediate(() => this.emit(msg.targetId, msg.event, msg.data)); setImmediate(() => this.emit(String(msg.targetId), msg.event, msg.data));
} }
// Otherwise unexpected message. // Otherwise unexpected message.
else else
......
...@@ -366,7 +366,7 @@ export class PayloadChannel extends EnhancedEventEmitter ...@@ -366,7 +366,7 @@ export class PayloadChannel extends EnhancedEventEmitter
{ {
this._ongoingNotification = this._ongoingNotification =
{ {
targetId : msg.targetId, targetId : String(msg.targetId),
event : msg.event, event : msg.event,
data : msg.data data : msg.data
}; };
......
...@@ -12,6 +12,7 @@ namespace Channel ...@@ -12,6 +12,7 @@ namespace Channel
{ {
public: public:
static void ClassInit(Channel::ChannelSocket* channel); static void ClassInit(Channel::ChannelSocket* channel);
static void Emit(uint64_t targetId, const char* event);
static void Emit(const std::string& targetId, const char* event); static void Emit(const std::string& targetId, const char* event);
static void Emit(const std::string& targetId, const char* event, json& data); static void Emit(const std::string& targetId, const char* event, json& data);
......
...@@ -132,7 +132,7 @@ public: ...@@ -132,7 +132,7 @@ public:
static void ClassInit(Channel::ChannelSocket* channel); static void ClassInit(Channel::ChannelSocket* channel);
public: public:
static const int64_t pid; static const uint64_t pid;
thread_local static Channel::ChannelSocket* channel; thread_local static Channel::ChannelSocket* channel;
static const size_t bufferSize {50000}; static const size_t bufferSize {50000};
thread_local static char buffer[]; thread_local static char buffer[];
......
...@@ -19,6 +19,20 @@ namespace Channel ...@@ -19,6 +19,20 @@ namespace Channel
ChannelNotifier::channel = channel; ChannelNotifier::channel = channel;
} }
void ChannelNotifier::Emit(uint64_t targetId, const char* event)
{
MS_TRACE();
MS_ASSERT(ChannelNotifier::channel, "channel unset");
json jsonNotification = json::object();
jsonNotification["targetId"] = targetId;
jsonNotification["event"] = event;
ChannelNotifier::channel->Send(jsonNotification);
}
void ChannelNotifier::Emit(const std::string& targetId, const char* event) void ChannelNotifier::Emit(const std::string& targetId, const char* event)
{ {
MS_TRACE(); MS_TRACE();
......
...@@ -6,7 +6,7 @@ ...@@ -6,7 +6,7 @@
/* Class variables. */ /* Class variables. */
const int64_t Logger::pid{ static_cast<int64_t>(uv_os_getpid()) }; const uint64_t Logger::pid{ static_cast<uint64_t>(uv_os_getpid()) };
thread_local Channel::ChannelSocket* Logger::channel{ nullptr }; thread_local Channel::ChannelSocket* Logger::channel{ nullptr };
thread_local char Logger::buffer[Logger::bufferSize]; thread_local char Logger::buffer[Logger::bufferSize];
......
...@@ -37,7 +37,7 @@ Worker::Worker(::Channel::ChannelSocket* channel, PayloadChannel::PayloadChannel ...@@ -37,7 +37,7 @@ Worker::Worker(::Channel::ChannelSocket* channel, PayloadChannel::PayloadChannel
DepUsrSCTP::CreateChecker(); DepUsrSCTP::CreateChecker();
// Tell the Node process that we are running. // Tell the Node process that we are running.
Channel::ChannelNotifier::Emit(std::to_string(Logger::pid), "running"); Channel::ChannelNotifier::Emit(Logger::pid, "running");
MS_DEBUG_DEV("starting libuv loop"); MS_DEBUG_DEV("starting libuv loop");
DepLibUV::RunLoop(); DepLibUV::RunLoop();
......
Markdown 格式
0% 或
您添加了 0 人 到此讨论。请谨慎行事。
请先完成此评论的编辑!
请 注册 或者 后发表评论