提交 932b2d04 authored 作者: Nazar Mokrynskyi's avatar Nazar Mokrynskyi

Receive channel responses from worker as a function call instead of though file…

Receive channel responses from worker as a function call instead of though file descriptor in Rust (step 1, old fd-based read code is still there)
上级 500e6134
use crate::messages::Request; use crate::messages::Request;
use crate::worker::common::{EventHandlers, SubscriptionTarget, WeakEventHandlers}; use crate::worker::common::{EventHandlers, SubscriptionTarget, WeakEventHandlers};
use crate::worker::utils;
use crate::worker::utils::PreparedChannelWrite;
use crate::worker::{RequestError, SubscriptionHandler}; use crate::worker::{RequestError, SubscriptionHandler};
use async_executor::Executor; use async_executor::Executor;
use async_fs::File; use async_fs::File;
...@@ -133,7 +135,11 @@ pub(crate) struct Channel { ...@@ -133,7 +135,11 @@ pub(crate) struct Channel {
} }
impl Channel { impl Channel {
pub(super) fn new(executor: &Executor<'static>, reader: File, mut writer: File) -> Self { pub(super) fn new(
executor: &Executor<'static>,
reader: File,
mut writer: File,
) -> (Self, PreparedChannelWrite) {
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 =
...@@ -141,12 +147,17 @@ impl Channel { ...@@ -141,12 +147,17 @@ impl Channel {
let event_handlers = EventHandlers::new(); let event_handlers = EventHandlers::new();
let event_handlers_weak = event_handlers.downgrade(); let event_handlers_weak = event_handlers.downgrade();
let internal_message_receiver = { let (internal_message_receiver, prepared_channel_write) = {
let buffered_notifications_for = buffered_notifications_for.clone(); let (sender, receiver) = async_channel::unbounded();
let (sender, receiver) = async_channel::bounded(1);
executor executor
.spawn(async move { .spawn({
let requests_container = Arc::clone(&requests_container);
let buffered_notifications_for = Arc::clone(&buffered_notifications_for);
let event_handlers = event_handlers.clone();
let sender = sender.clone();
async move {
let mut len_bytes = [0u8; 4]; let mut len_bytes = [0u8; 4];
let mut read_buffer = vec![0u8; PAYLOAD_MAX_LEN]; let mut read_buffer = vec![0u8; PAYLOAD_MAX_LEN];
let mut reader = BufReader::new(reader); let mut reader = BufReader::new(reader);
...@@ -200,11 +211,12 @@ impl Channel { ...@@ -200,11 +211,12 @@ impl Channel {
} }
} }
ChannelReceiveMessage::Notification(notification) => { ChannelReceiveMessage::Notification(notification) => {
let target_id = notification.get("targetId").and_then(|value| { let target_id =
notification.get("targetId").and_then(|value| {
let str = value.as_str()?; let str = value.as_str()?;
str.parse().ok().map(SubscriptionTarget::Uuid).or_else(|| { str.parse().ok().map(SubscriptionTarget::Uuid).or_else(
str.parse().ok().map(SubscriptionTarget::Number) || str.parse().ok().map(SubscriptionTarget::Number),
}) )
}); });
if let Some(target_id) = target_id { if let Some(target_id) = target_id {
...@@ -243,10 +255,90 @@ impl Channel { ...@@ -243,10 +255,90 @@ impl Channel {
} }
io::Result::Ok(()) io::Result::Ok(())
}
}) })
.detach(); .detach();
receiver let buffered_notifications_for = Arc::clone(&buffered_notifications_for);
// This this contain cache of targets that are known to not have buffering, so
// that we can avoid Mutex locking overhead for them
let mut non_buffered_notifications = LruCache::<SubscriptionTarget, ()>::new(1000);
let prepared_channel_write = utils::prepare_channel_write_fn(move |message| {
trace!("received raw message: {}", String::from_utf8_lossy(message));
match deserialize_message(message) {
ChannelReceiveMessage::ResponseSuccess {
id,
accepted: _,
data,
} => {
let sender = requests_container.lock().handlers.remove(&id);
if let Some(mut sender) = sender {
let _ = sender.send(Ok(data));
} else {
warn!(
"received success response does not match any sent request [id:{}]",
id,
);
}
}
ChannelReceiveMessage::ResponseError {
id,
error: _,
reason,
} => {
let sender = requests_container.lock().handlers.remove(&id);
if let Some(mut sender) = sender {
let _ = sender.send(Err(ResponseError { reason }));
} else {
warn!(
"received error response does not match any sent request [id:{}]",
id,
);
}
}
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_value(&target_id, notification);
} else {
let unexpected_message =
InternalMessage::Unexpected(Vec::from(message));
if sender.try_send(unexpected_message).is_err() {
return;
}
}
}
ChannelReceiveMessage::Event(event_message) => {
if sender.try_send(event_message).is_err() {
return;
}
}
}
});
(receiver, prepared_channel_write)
}; };
let sender = { let sender = {
...@@ -276,7 +368,7 @@ impl Channel { ...@@ -276,7 +368,7 @@ impl Channel {
event_handlers_weak, event_handlers_weak,
}); });
Self { inner } (Self { inner }, prepared_channel_write)
} }
pub(super) fn get_internal_message_receiver(&self) -> async_channel::Receiver<InternalMessage> { pub(super) fn get_internal_message_receiver(&self) -> async_channel::Receiver<InternalMessage> {
......
mod channel_write_fn;
// Contents of this module is inspired by https://github.com/Srinivasa314/alcro/tree/master/src/chrome // Contents of this module is inspired by https://github.com/Srinivasa314/alcro/tree/master/src/chrome
use crate::worker::channel::BufferMessagesGuard; use crate::worker::channel::BufferMessagesGuard;
use crate::worker::{Channel, PayloadChannel, WorkerId}; use crate::worker::{Channel, PayloadChannel, WorkerId};
use async_executor::Executor; use async_executor::Executor;
use async_fs::File; use async_fs::File;
use async_oneshot::Receiver; use async_oneshot::Receiver;
pub(super) use channel_write_fn::{prepare_channel_write_fn, PreparedChannelWrite};
use std::ffi::CString; use std::ffi::CString;
use std::mem; use std::mem;
use std::os::raw::{c_char, c_int}; use std::os::raw::{c_char, c_int};
...@@ -67,7 +70,7 @@ pub(super) fn run_worker_with_channels( ...@@ -67,7 +70,7 @@ pub(super) fn run_worker_with_channels(
let producer_payload_file = unsafe { File::from_raw_fd(producer_payload_fd_write) }; let producer_payload_file = unsafe { File::from_raw_fd(producer_payload_fd_write) };
let consumer_payload_file = unsafe { File::from_raw_fd(consumer_payload_fd_read) }; let consumer_payload_file = unsafe { File::from_raw_fd(consumer_payload_fd_read) };
let channel = Channel::new(&executor, consumer_file, producer_file); let (channel, prepared_channel_write) = Channel::new(&executor, consumer_file, producer_file);
let payload_channel = let payload_channel =
PayloadChannel::new(&executor, consumer_payload_file, producer_payload_file); PayloadChannel::new(&executor, consumer_payload_file, producer_payload_file);
let buffer_worker_messages_guard = channel.buffer_messages_for(std::process::id().into()); let buffer_worker_messages_guard = channel.buffer_messages_for(std::process::id().into());
...@@ -88,7 +91,11 @@ pub(super) fn run_worker_with_channels( ...@@ -88,7 +91,11 @@ pub(super) fn run_worker_with_channels(
.map(|arg| arg.as_ptr().cast::<c_char>()) .map(|arg| arg.as_ptr().cast::<c_char>())
.collect::<Vec<_>>(); .collect::<Vec<_>>();
let version = CString::new(env!("CARGO_PKG_VERSION")).unwrap(); let version = CString::new(env!("CARGO_PKG_VERSION")).unwrap();
let status_code = unsafe { let status_code = unsafe {
let (channel_write_fn, channel_write_ctx, _read_callback) =
prepared_channel_write.deconstruct();
mediasoup_sys::run_worker( mediasoup_sys::run_worker(
argc, argc,
argv.as_ptr(), argv.as_ptr(),
...@@ -97,6 +104,8 @@ pub(super) fn run_worker_with_channels( ...@@ -97,6 +104,8 @@ pub(super) fn run_worker_with_channels(
consumer_fd_write, consumer_fd_write,
producer_payload_fd_read, producer_payload_fd_read,
consumer_payload_fd_write, consumer_payload_fd_write,
channel_write_fn,
channel_write_ctx,
) )
}; };
......
pub(super) use mediasoup_sys::{ChannelWriteCtx, ChannelWriteFn};
use std::os::raw::c_void;
use std::slice;
pub(super) struct ReadCallback(Box<dyn FnMut(&[u8]) + Send + 'static>);
pub(crate) struct PreparedChannelWrite {
channel_write_fn: ChannelWriteFn,
channel_write_ctx: ChannelWriteCtx,
read_callback: ReadCallback,
}
unsafe impl Send for PreparedChannelWrite {}
impl PreparedChannelWrite {
/// SAFETY:
/// 1) `ReadCallback` returned must be dropped AFTER last usage of returned function and context
/// pointers
/// 2) `ChannelWriteCtx` should not be called from multiple threads concurrently
pub(super) unsafe fn deconstruct(self) -> (ChannelWriteFn, ChannelWriteCtx, ReadCallback) {
let Self {
channel_write_fn,
channel_write_ctx,
read_callback,
} = self;
(channel_write_fn, channel_write_ctx, read_callback)
}
}
/// Given callback function, prepares a pair of channel write function and context, which can be
/// provided to of C++ worker and worker will effectively call the callback whenever it needs to
/// send something to Rust (so it is writing from C++ point of view and reading from Rust).
pub(crate) fn prepare_channel_write_fn<F>(read_callback: F) -> PreparedChannelWrite
where
F: FnMut(&[u8]) + Send + 'static,
{
unsafe extern "C" fn wrapper<F>(message: *const u8, message_len: u32, ctx: *const c_void)
where
F: FnMut(&[u8]) + Send + 'static,
{
let message = slice::from_raw_parts(message, message_len as usize);
(*(ctx as *mut F))(message);
}
// Move to heap to make sure it doesn't change address later on
let read_callback = Box::new(read_callback);
PreparedChannelWrite {
channel_write_fn: wrapper::<F>,
channel_write_ctx: read_callback.as_ref() as *const F as *const c_void,
read_callback: ReadCallback(read_callback),
}
}
...@@ -64,16 +64,18 @@ namespace Channel ...@@ -64,16 +64,18 @@ namespace Channel
public: public:
explicit ChannelSocket(int consumerFd, int producerFd); explicit ChannelSocket(int consumerFd, int producerFd);
explicit ChannelSocket(
int consumerFd, int producerFd, ChannelWriteFn channelWriteFn, ChannelWriteCtx channelWriteCtx);
virtual ~ChannelSocket(); virtual ~ChannelSocket();
public: public:
void Close(); void Close();
void SetListener(Listener* listener); void SetListener(Listener* listener);
void Send(json& jsonMessage); void Send(json& jsonMessage);
void SendLog(char* message, uint32_t messageLen); void SendLog(const char* message, uint32_t messageLen);
private: private:
void SendImpl(const void* payload, uint32_t payloadLen); void SendImpl(const uint8_t* payload, uint32_t payloadLen);
/* Pure virtual methods inherited from ConsumerSocket::Listener. */ /* Pure virtual methods inherited from ConsumerSocket::Listener. */
public: public:
...@@ -87,6 +89,8 @@ namespace Channel ...@@ -87,6 +89,8 @@ namespace Channel
bool closed{ false }; bool closed{ false };
ConsumerSocket consumerSocket; ConsumerSocket consumerSocket;
ProducerSocket producerSocket; ProducerSocket producerSocket;
ChannelWriteFn channelWriteFn{ nullptr };
ChannelWriteCtx channelWriteCtx{ nullptr };
uint8_t* writeBuffer; uint8_t* writeBuffer;
}; };
} // namespace Channel } // namespace Channel
......
...@@ -26,4 +26,8 @@ typedef SSIZE_T ssize_t; ...@@ -26,4 +26,8 @@ typedef SSIZE_T ssize_t;
#include <sys/socket.h> // struct sockaddr, struct sockaddr_storage, AF_INET, AF_INET6 #include <sys/socket.h> // struct sockaddr, struct sockaddr_storage, AF_INET, AF_INET6
#endif #endif
using ChannelWriteCtx = void*;
using ChannelWriteFn =
void (*)(const uint8_t* /* message */, uint32_t /* messageLen */, ChannelWriteCtx /* ctx */);
#endif #endif
#include "common.hpp"
extern "C" int run_worker( extern "C" int run_worker(
int argc, int argc,
char* argv[], char* argv[],
...@@ -5,4 +7,6 @@ extern "C" int run_worker( ...@@ -5,4 +7,6 @@ extern "C" int run_worker(
int consumerChannelFd, int consumerChannelFd,
int producerChannelFd, int producerChannelFd,
int payloadConsumeChannelFd, int payloadConsumeChannelFd,
int payloadProduceChannelFd); int payloadProduceChannelFd,
ChannelWriteFn channelWriteFn,
ChannelWriteCtx channelWriteCtx);
...@@ -25,6 +25,16 @@ namespace Channel ...@@ -25,6 +25,16 @@ namespace Channel
this->writeBuffer = static_cast<uint8_t*>(std::malloc(MessageMaxLen)); this->writeBuffer = static_cast<uint8_t*>(std::malloc(MessageMaxLen));
} }
ChannelSocket::ChannelSocket(
int consumerFd, int producerFd, ChannelWriteFn channelWriteFn, ChannelWriteCtx channelWriteCtx)
: consumerSocket(consumerFd, MessageMaxLen, this), producerSocket(producerFd, MessageMaxLen),
channelWriteFn(channelWriteFn), channelWriteCtx(channelWriteCtx)
{
MS_TRACE_STD();
this->writeBuffer = static_cast<uint8_t*>(std::malloc(MessageMaxLen));
}
ChannelSocket::~ChannelSocket() ChannelSocket::~ChannelSocket()
{ {
MS_TRACE_STD(); MS_TRACE_STD();
...@@ -71,10 +81,11 @@ namespace Channel ...@@ -71,10 +81,11 @@ namespace Channel
return; return;
} }
SendImpl(message.c_str(), static_cast<uint32_t>(message.length())); SendImpl(
reinterpret_cast<const uint8_t*>(message.c_str()), static_cast<uint32_t>(message.length()));
} }
void ChannelSocket::SendLog(char* message, uint32_t messageLen) void ChannelSocket::SendLog(const char* message, uint32_t messageLen)
{ {
MS_TRACE_STD(); MS_TRACE_STD();
...@@ -88,13 +99,20 @@ namespace Channel ...@@ -88,13 +99,20 @@ namespace Channel
return; return;
} }
SendImpl(message, messageLen); SendImpl(reinterpret_cast<const uint8_t*>(message), messageLen);
} }
inline void ChannelSocket::SendImpl(const void* payload, uint32_t payloadLen) inline void ChannelSocket::SendImpl(const uint8_t* payload, uint32_t payloadLen)
{ {
MS_TRACE_STD(); MS_TRACE_STD();
// Write using function call if provided.
if (this->channelWriteFn)
{
this->channelWriteFn(payload, payloadLen, this->channelWriteCtx);
}
else
{
std::memcpy(this->writeBuffer, &payloadLen, sizeof(uint32_t)); std::memcpy(this->writeBuffer, &payloadLen, sizeof(uint32_t));
if (payloadLen != 0) if (payloadLen != 0)
...@@ -106,6 +124,7 @@ namespace Channel ...@@ -106,6 +124,7 @@ namespace Channel
this->producerSocket.Write(this->writeBuffer, len); this->producerSocket.Write(this->writeBuffer, len);
} }
}
void ChannelSocket::OnConsumerSocketMessage(ConsumerSocket* /*consumerSocket*/, char* msg, size_t msgLen) void ChannelSocket::OnConsumerSocketMessage(ConsumerSocket* /*consumerSocket*/, char* msg, size_t msgLen)
{ {
......
...@@ -35,7 +35,9 @@ extern "C" int run_worker( ...@@ -35,7 +35,9 @@ extern "C" int run_worker(
int consumerChannelFd, int consumerChannelFd,
int producerChannelFd, int producerChannelFd,
int payloadConsumeChannelFd, int payloadConsumeChannelFd,
int payloadProduceChannelFd) int payloadProduceChannelFd,
ChannelWriteFn channelWriteFn,
ChannelWriteCtx channelWriteCtx)
{ {
// Initialize libuv stuff (we need it for the Channel). // Initialize libuv stuff (we need it for the Channel).
DepLibUV::ClassInit(); DepLibUV::ClassInit();
...@@ -52,7 +54,8 @@ extern "C" int run_worker( ...@@ -52,7 +54,8 @@ extern "C" int run_worker(
try try
{ {
channel.reset(new Channel::ChannelSocket(consumerChannelFd, producerChannelFd)); channel.reset(new Channel::ChannelSocket(
consumerChannelFd, producerChannelFd, channelWriteFn, channelWriteCtx));
} }
catch (const MediaSoupError& error) catch (const MediaSoupError& error)
{ {
......
use std::os::raw::{c_char, c_int}; use std::os::raw::{c_char, c_int, c_void};
pub type ChannelWriteCtx = *const c_void;
pub type ChannelWriteFn = unsafe extern "C" fn(
/* message: */ *const u8,
/* message_len: */ u32,
/* ctx: */ ChannelWriteCtx,
);
#[link(name = "mediasoup-worker", kind = "static")] #[link(name = "mediasoup-worker", kind = "static")]
extern "C" { extern "C" {
...@@ -10,5 +17,7 @@ extern "C" { ...@@ -10,5 +17,7 @@ extern "C" {
producer_channel_fd: c_int, producer_channel_fd: c_int,
payload_consumer_channel_fd: c_int, payload_consumer_channel_fd: c_int,
payload_producer_channel_fd: c_int, payload_producer_channel_fd: c_int,
channel_write_fn: ChannelWriteFn,
channel_write_ctx: ChannelWriteCtx,
) -> c_int; ) -> c_int;
} }
...@@ -30,7 +30,9 @@ int main(int argc, char* argv[]) ...@@ -30,7 +30,9 @@ int main(int argc, char* argv[])
ConsumerChannelFd, ConsumerChannelFd,
ProducerChannelFd, ProducerChannelFd,
PayloadConsumerChannelFd, PayloadConsumerChannelFd,
PayloadProducerChannelFd); PayloadProducerChannelFd,
nullptr,
nullptr);
switch (statusCode) switch (statusCode)
{ {
......
Markdown 格式
0% 或
您添加了 0 人 到此讨论。请谨慎行事。
请先完成此评论的编辑!
请 注册 或者 后发表评论