提交 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 {
// the response, destroying the ordered delivery. So we must wait a bit
// here.
// 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.
else {
......
......@@ -215,7 +215,7 @@ class PayloadChannel extends EnhancedEventEmitter_1.EnhancedEventEmitter {
else if (msg.targetId && msg.event) {
this._ongoingNotification =
{
targetId: msg.targetId,
targetId: String(msg.targetId),
event: msg.event,
data: msg.data
};
......
......@@ -305,7 +305,7 @@ impl ActiveSpeakerObserver {
let handlers = Arc::clone(&handlers);
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 {
Notification::DominantSpeaker(dominant_speaker) => {
let DominantSpeakerNotification { producer_id } = dominant_speaker;
......
......@@ -319,7 +319,7 @@ impl AudioLevelObserver {
let handlers = Arc::clone(&handlers);
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 {
Notification::Volumes(volumes) => {
let volumes = volumes
......
......@@ -493,7 +493,7 @@ impl Consumer {
let inner_weak = Arc::clone(&inner_weak);
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 {
Notification::ProducerClose => {
if !closed.load(Ordering::SeqCst) {
......
......@@ -369,7 +369,7 @@ impl DataConsumer {
let inner_weak = Arc::clone(&inner_weak);
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 {
Notification::DataProducerClose => {
if !closed.load(Ordering::SeqCst) {
......
......@@ -462,7 +462,7 @@ impl DirectTransport {
let handlers = Arc::clone(&handlers);
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 {
Notification::Trace(trace_event_data) => {
handlers.trace.call(|callback| {
......
......@@ -490,7 +490,7 @@ impl PipeTransport {
let data = Arc::clone(&data);
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 {
Notification::SctpStateChange { sctp_state } => {
data.sctp_state.lock().replace(sctp_state);
......
......@@ -520,7 +520,7 @@ impl PlainTransport {
let data = Arc::clone(&data);
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 {
Notification::Tuple { tuple } => {
*data.tuple.lock() = tuple;
......
......@@ -461,7 +461,7 @@ impl Producer {
let score = Arc::clone(&score);
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 {
Notification::Score(scores) => {
*score.lock() = scores.clone();
......
......@@ -575,7 +575,7 @@ impl WebRtcTransport {
let data = Arc::clone(&data);
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 {
Notification::IceStateChange { ice_state } => {
*data.ice_state.lock() = ice_state;
......
......@@ -430,7 +430,7 @@ impl Inner {
let _handler = self.channel.subscribe_to_notifications(
std::process::id().into(),
move |notification| {
let result = match serde_json::from_value(notification.clone()) {
let result = match serde_json::from_slice(notification) {
Ok(Notification::Running) => {
debug!("worker thread running [id:{}]", id);
Ok(())
......
......@@ -39,8 +39,8 @@ pub(super) enum InternalMessage {
pub(crate) struct BufferMessagesGuard {
target_id: SubscriptionTarget,
buffered_notifications_for: Arc<Mutex<HashMap<SubscriptionTarget, Vec<Value>>>>,
event_handlers_weak: WeakEventHandlers<Arc<dyn Fn(Value) + Send + Sync + 'static>>,
buffered_notifications_for: Arc<Mutex<HashMap<SubscriptionTarget, Vec<Vec<u8>>>>>,
event_handlers_weak: WeakEventHandlers<Arc<dyn Fn(&[u8]) + 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_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 {
#[derive(Debug, Deserialize)]
#[serde(untagged)]
enum ChannelReceiveMessage {
#[serde(rename_all = "camelCase")]
Notification {
target_id: SubscriptionTarget,
},
ResponseSuccess {
id: u32,
accepted: bool,
......@@ -69,7 +73,6 @@ enum ChannelReceiveMessage {
error: Value,
reason: String,
},
Notification(Value),
Event(InternalMessage),
}
......@@ -119,8 +122,8 @@ struct Inner {
outgoing_message_buffer: Arc<Mutex<OutgoingMessageBuffer>>,
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<Arc<dyn Fn(Value) + Send + Sync + 'static>>,
buffered_notifications_for: Arc<Mutex<HashMap<SubscriptionTarget, Vec<Vec<u8>>>>>,
event_handlers_weak: WeakEventHandlers<Arc<dyn Fn(&[u8]) + Send + Sync + 'static>>,
}
impl Drop for Inner {
......@@ -143,7 +146,7 @@ impl Channel {
let requests_container = Arc::<Mutex<RequestsContainer>>::default();
let requests_container_weak = Arc::downgrade(&requests_container);
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_weak = event_handlers.downgrade();
......@@ -172,6 +175,21 @@ impl Channel {
trace!("received raw message: {}", String::from_utf8_lossy(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 {
id,
accepted: _,
......@@ -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) => {
let _ = internal_message_sender.try_send(event_message);
}
......@@ -390,7 +377,7 @@ impl Channel {
callback: F,
) -> Option<SubscriptionHandler>
where
F: Fn(Value) + Send + Sync + 'static,
F: Fn(&[u8]) + Send + Sync + 'static,
{
self.inner
.event_handlers_weak
......
......@@ -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(
&self,
target_id: &SubscriptionTarget,
value: V,
value: &V,
) {
let handlers = self.handlers.lock();
if let Some(list) = handlers.get(target_id) {
......@@ -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(handlers);
for callback in callbacks {
callback(value.clone());
callback(value);
}
}
}
......@@ -149,11 +149,17 @@ impl<F> WeakEventHandlers<F> {
#[serde(untagged)]
pub(crate) enum SubscriptionTarget {
Uuid(Uuid),
Number(u32),
Number(u64),
}
impl From<u32> for SubscriptionTarget {
fn from(number: u32) -> Self {
Self::Number(u64::from(number))
}
}
impl From<u64> for SubscriptionTarget {
fn from(number: u64) -> Self {
Self::Number(number)
}
}
......
......@@ -342,7 +342,7 @@ export class Channel extends EnhancedEventEmitter
// the response, destroying the ordered delivery. So we must wait a bit
// here.
// 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.
else
......
......@@ -366,7 +366,7 @@ export class PayloadChannel extends EnhancedEventEmitter
{
this._ongoingNotification =
{
targetId : msg.targetId,
targetId : String(msg.targetId),
event : msg.event,
data : msg.data
};
......
......@@ -12,6 +12,7 @@ namespace Channel
{
public:
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, json& data);
......
......@@ -132,7 +132,7 @@ public:
static void ClassInit(Channel::ChannelSocket* channel);
public:
static const int64_t pid;
static const uint64_t pid;
thread_local static Channel::ChannelSocket* channel;
static const size_t bufferSize {50000};
thread_local static char buffer[];
......
......@@ -19,6 +19,20 @@ namespace 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)
{
MS_TRACE();
......
......@@ -6,7 +6,7 @@
/* 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 char Logger::buffer[Logger::bufferSize];
......
......@@ -37,7 +37,7 @@ Worker::Worker(::Channel::ChannelSocket* channel, PayloadChannel::PayloadChannel
DepUsrSCTP::CreateChecker();
// 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");
DepLibUV::RunLoop();
......
Markdown 格式
0% 或
您添加了 0 人 到此讨论。请谨慎行事。
请先完成此评论的编辑!
请 注册 或者 后发表评论