提交 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::worker::common::{EventHandlers, SubscriptionTarget, WeakEventHandlers};
use crate::worker::utils;
use crate::worker::utils::PreparedChannelWrite;
use crate::worker::{RequestError, SubscriptionHandler};
use async_executor::Executor;
use async_fs::File;
......@@ -133,7 +135,11 @@ pub(crate) struct 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_weak = Arc::downgrade(&requests_container);
let buffered_notifications_for =
......@@ -141,12 +147,17 @@ impl Channel {
let event_handlers = EventHandlers::new();
let event_handlers_weak = event_handlers.downgrade();
let internal_message_receiver = {
let buffered_notifications_for = buffered_notifications_for.clone();
let (sender, receiver) = async_channel::bounded(1);
let (internal_message_receiver, prepared_channel_write) = {
let (sender, receiver) = async_channel::unbounded();
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 read_buffer = vec![0u8; PAYLOAD_MAX_LEN];
let mut reader = BufReader::new(reader);
......@@ -200,11 +211,12 @@ impl Channel {
}
}
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()?;
str.parse().ok().map(SubscriptionTarget::Uuid).or_else(|| {
str.parse().ok().map(SubscriptionTarget::Number)
})
str.parse().ok().map(SubscriptionTarget::Uuid).or_else(
|| str.parse().ok().map(SubscriptionTarget::Number),
)
});
if let Some(target_id) = target_id {
......@@ -243,10 +255,90 @@ impl Channel {
}
io::Result::Ok(())
}
})
.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 = {
......@@ -276,7 +368,7 @@ impl Channel {
event_handlers_weak,
});
Self { inner }
(Self { inner }, prepared_channel_write)
}
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
use crate::worker::channel::BufferMessagesGuard;
use crate::worker::{Channel, PayloadChannel, WorkerId};
use async_executor::Executor;
use async_fs::File;
use async_oneshot::Receiver;
pub(super) use channel_write_fn::{prepare_channel_write_fn, PreparedChannelWrite};
use std::ffi::CString;
use std::mem;
use std::os::raw::{c_char, c_int};
......@@ -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 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 =
PayloadChannel::new(&executor, consumer_payload_file, producer_payload_file);
let buffer_worker_messages_guard = channel.buffer_messages_for(std::process::id().into());
......@@ -88,7 +91,11 @@ pub(super) fn run_worker_with_channels(
.map(|arg| arg.as_ptr().cast::<c_char>())
.collect::<Vec<_>>();
let version = CString::new(env!("CARGO_PKG_VERSION")).unwrap();
let status_code = unsafe {
let (channel_write_fn, channel_write_ctx, _read_callback) =
prepared_channel_write.deconstruct();
mediasoup_sys::run_worker(
argc,
argv.as_ptr(),
......@@ -97,6 +104,8 @@ pub(super) fn run_worker_with_channels(
consumer_fd_write,
producer_payload_fd_read,
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
public:
explicit ChannelSocket(int consumerFd, int producerFd);
explicit ChannelSocket(
int consumerFd, int producerFd, ChannelWriteFn channelWriteFn, ChannelWriteCtx channelWriteCtx);
virtual ~ChannelSocket();
public:
void Close();
void SetListener(Listener* listener);
void Send(json& jsonMessage);
void SendLog(char* message, uint32_t messageLen);
void SendLog(const char* message, uint32_t messageLen);
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. */
public:
......@@ -87,6 +89,8 @@ namespace Channel
bool closed{ false };
ConsumerSocket consumerSocket;
ProducerSocket producerSocket;
ChannelWriteFn channelWriteFn{ nullptr };
ChannelWriteCtx channelWriteCtx{ nullptr };
uint8_t* writeBuffer;
};
} // namespace Channel
......
......@@ -26,4 +26,8 @@ typedef SSIZE_T ssize_t;
#include <sys/socket.h> // struct sockaddr, struct sockaddr_storage, AF_INET, AF_INET6
#endif
using ChannelWriteCtx = void*;
using ChannelWriteFn =
void (*)(const uint8_t* /* message */, uint32_t /* messageLen */, ChannelWriteCtx /* ctx */);
#endif
#include "common.hpp"
extern "C" int run_worker(
int argc,
char* argv[],
......@@ -5,4 +7,6 @@ extern "C" int run_worker(
int consumerChannelFd,
int producerChannelFd,
int payloadConsumeChannelFd,
int payloadProduceChannelFd);
int payloadProduceChannelFd,
ChannelWriteFn channelWriteFn,
ChannelWriteCtx channelWriteCtx);
......@@ -25,6 +25,16 @@ namespace Channel
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()
{
MS_TRACE_STD();
......@@ -71,10 +81,11 @@ namespace Channel
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();
......@@ -88,13 +99,20 @@ namespace Channel
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();
// Write using function call if provided.
if (this->channelWriteFn)
{
this->channelWriteFn(payload, payloadLen, this->channelWriteCtx);
}
else
{
std::memcpy(this->writeBuffer, &payloadLen, sizeof(uint32_t));
if (payloadLen != 0)
......@@ -106,6 +124,7 @@ namespace Channel
this->producerSocket.Write(this->writeBuffer, len);
}
}
void ChannelSocket::OnConsumerSocketMessage(ConsumerSocket* /*consumerSocket*/, char* msg, size_t msgLen)
{
......
......@@ -35,7 +35,9 @@ extern "C" int run_worker(
int consumerChannelFd,
int producerChannelFd,
int payloadConsumeChannelFd,
int payloadProduceChannelFd)
int payloadProduceChannelFd,
ChannelWriteFn channelWriteFn,
ChannelWriteCtx channelWriteCtx)
{
// Initialize libuv stuff (we need it for the Channel).
DepLibUV::ClassInit();
......@@ -52,7 +54,8 @@ extern "C" int run_worker(
try
{
channel.reset(new Channel::ChannelSocket(consumerChannelFd, producerChannelFd));
channel.reset(new Channel::ChannelSocket(
consumerChannelFd, producerChannelFd, channelWriteFn, channelWriteCtx));
}
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")]
extern "C" {
......@@ -10,5 +17,7 @@ extern "C" {
producer_channel_fd: c_int,
payload_consumer_channel_fd: c_int,
payload_producer_channel_fd: c_int,
channel_write_fn: ChannelWriteFn,
channel_write_ctx: ChannelWriteCtx,
) -> c_int;
}
......@@ -30,7 +30,9 @@ int main(int argc, char* argv[])
ConsumerChannelFd,
ProducerChannelFd,
PayloadConsumerChannelFd,
PayloadProducerChannelFd);
PayloadProducerChannelFd,
nullptr,
nullptr);
switch (statusCode)
{
......
Markdown 格式
0% 或
您添加了 0 人 到此讨论。请谨慎行事。
请先完成此评论的编辑!
请 注册 或者 后发表评论