提交 1f07ea1b authored 作者: Nazar Mokrynskyi's avatar Nazar Mokrynskyi

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

Receive payload channel responses from worker as a function call instead of though file descriptor in Rust (step 2, old fd-based read code is still there)
上级 932b2d04
use crate::messages::{MetaNotification, MetaRequest, Notification, Request}; use crate::messages::{MetaNotification, MetaRequest, Notification, Request};
use crate::worker::common::{EventHandlers, SubscriptionTarget, WeakEventHandlers}; use crate::worker::common::{EventHandlers, SubscriptionTarget, WeakEventHandlers};
use crate::worker::{RequestError, SubscriptionHandler}; use crate::worker::utils::PreparedPayloadChannelWrite;
use crate::worker::{utils, RequestError, SubscriptionHandler};
use async_executor::Executor; use async_executor::Executor;
use async_fs::File; use async_fs::File;
use bytes::Bytes; use bytes::Bytes;
...@@ -115,17 +116,26 @@ pub(crate) struct PayloadChannel { ...@@ -115,17 +116,26 @@ pub(crate) struct PayloadChannel {
} }
impl PayloadChannel { impl PayloadChannel {
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, PreparedPayloadChannelWrite) {
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 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_payload_channel_write) = {
let (sender, receiver) = async_channel::bounded(1); let (sender, receiver) = async_channel::bounded(1);
executor executor
.spawn(async move { .spawn({
let requests_container = Arc::clone(&requests_container);
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);
...@@ -175,11 +185,12 @@ impl PayloadChannel { ...@@ -175,11 +185,12 @@ impl PayloadChannel {
} }
} }
PayloadChannelReceiveMessage::Notification(notification) => { PayloadChannelReceiveMessage::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),
}) )
}); });
reader.read_exact(&mut len_bytes).await?; reader.read_exact(&mut len_bytes).await?;
...@@ -217,10 +228,85 @@ impl PayloadChannel { ...@@ -217,10 +228,85 @@ impl PayloadChannel {
} }
io::Result::Ok(()) io::Result::Ok(())
}
}) })
.detach(); .detach();
receiver let prepared_payload_channel_write =
utils::prepare_payload_channel_write_fn(move |message, payload| {
trace!("received raw message: {}", String::from_utf8_lossy(message));
match deserialize_message(message) {
PayloadChannelReceiveMessage::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,
);
}
}
PayloadChannelReceiveMessage::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,
);
}
}
PayloadChannelReceiveMessage::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))
});
trace!("received notification payload of {} bytes", payload.len());
let payload = Bytes::copy_from_slice(payload);
if let Some(target_id) = target_id {
event_handlers.call_callbacks_with_value(
&target_id,
NotificationMessage {
message: notification,
payload,
},
);
} else {
let unexpected_message =
InternalMessage::UnexpectedData(Vec::from(message));
if sender.try_send(unexpected_message).is_err() {
return;
}
}
}
PayloadChannelReceiveMessage::Internal(internal_message) => {
if sender.try_send(internal_message).is_err() {
return;
}
}
}
});
(receiver, prepared_payload_channel_write)
}; };
let sender = { let sender = {
...@@ -319,7 +405,7 @@ impl PayloadChannel { ...@@ -319,7 +405,7 @@ impl PayloadChannel {
event_handlers_weak, event_handlers_weak,
}); });
Self { inner } (Self { inner }, prepared_payload_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> {
......
...@@ -6,7 +6,10 @@ use crate::worker::{Channel, PayloadChannel, WorkerId}; ...@@ -6,7 +6,10 @@ 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}; pub(super) use channel_write_fn::{
prepare_channel_write_fn, prepare_payload_channel_write_fn, PreparedChannelWrite,
PreparedPayloadChannelWrite,
};
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};
...@@ -71,7 +74,7 @@ pub(super) fn run_worker_with_channels( ...@@ -71,7 +74,7 @@ pub(super) fn run_worker_with_channels(
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, prepared_channel_write) = 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, prepared_payload_channel_write) =
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());
...@@ -93,8 +96,13 @@ pub(super) fn run_worker_with_channels( ...@@ -93,8 +96,13 @@ pub(super) fn run_worker_with_channels(
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) = let (channel_write_fn, channel_write_ctx, _channel_read_callback) =
prepared_channel_write.deconstruct(); prepared_channel_write.deconstruct();
let (
payload_channel_write_fn,
payload_channel_write_ctx,
_payload_channel_read_callback,
) = prepared_payload_channel_write.deconstruct();
mediasoup_sys::run_worker( mediasoup_sys::run_worker(
argc, argc,
...@@ -106,6 +114,8 @@ pub(super) fn run_worker_with_channels( ...@@ -106,6 +114,8 @@ pub(super) fn run_worker_with_channels(
consumer_payload_fd_write, consumer_payload_fd_write,
channel_write_fn, channel_write_fn,
channel_write_ctx, channel_write_ctx,
payload_channel_write_fn,
payload_channel_write_ctx,
) )
}; };
......
pub(super) use mediasoup_sys::{ChannelWriteCtx, ChannelWriteFn}; pub(super) use mediasoup_sys::{
ChannelWriteCtx, ChannelWriteFn, PayloadChannelWriteCtx, PayloadChannelWriteFn,
};
use std::os::raw::c_void; use std::os::raw::c_void;
use std::slice; use std::slice;
pub(super) struct ReadCallback(Box<dyn FnMut(&[u8]) + Send + 'static>); pub(super) struct ChannelReadCallback(Box<dyn FnMut(&[u8]) + Send + 'static>);
pub(crate) struct PreparedChannelWrite { pub(crate) struct PreparedChannelWrite {
channel_write_fn: ChannelWriteFn, channel_write_fn: ChannelWriteFn,
channel_write_ctx: ChannelWriteCtx, channel_write_ctx: ChannelWriteCtx,
read_callback: ReadCallback, read_callback: ChannelReadCallback,
} }
unsafe impl Send for PreparedChannelWrite {} unsafe impl Send for PreparedChannelWrite {}
...@@ -17,7 +19,9 @@ impl PreparedChannelWrite { ...@@ -17,7 +19,9 @@ impl PreparedChannelWrite {
/// 1) `ReadCallback` returned must be dropped AFTER last usage of returned function and context /// 1) `ReadCallback` returned must be dropped AFTER last usage of returned function and context
/// pointers /// pointers
/// 2) `ChannelWriteCtx` should not be called from multiple threads concurrently /// 2) `ChannelWriteCtx` should not be called from multiple threads concurrently
pub(super) unsafe fn deconstruct(self) -> (ChannelWriteFn, ChannelWriteCtx, ReadCallback) { pub(super) unsafe fn deconstruct(
self,
) -> (ChannelWriteFn, ChannelWriteCtx, ChannelReadCallback) {
let Self { let Self {
channel_write_fn, channel_write_fn,
channel_write_ctx, channel_write_ctx,
...@@ -48,6 +52,72 @@ where ...@@ -48,6 +52,72 @@ where
PreparedChannelWrite { PreparedChannelWrite {
channel_write_fn: wrapper::<F>, channel_write_fn: wrapper::<F>,
channel_write_ctx: read_callback.as_ref() as *const F as *const c_void, channel_write_ctx: read_callback.as_ref() as *const F as *const c_void,
read_callback: ReadCallback(read_callback), read_callback: ChannelReadCallback(read_callback),
}
}
pub(super) struct PayloadChannelReadCallback(Box<dyn FnMut(&[u8], &[u8]) + Send + 'static>);
pub(crate) struct PreparedPayloadChannelWrite {
channel_write_fn: PayloadChannelWriteFn,
channel_write_ctx: PayloadChannelWriteCtx,
read_callback: PayloadChannelReadCallback,
}
unsafe impl Send for PreparedPayloadChannelWrite {}
impl PreparedPayloadChannelWrite {
/// SAFETY:
/// 1) `ReadCallback` returned must be dropped AFTER last usage of returned function and context
/// pointers
/// 2) `PayloadChannelWriteCtx` should not be called from multiple threads concurrently
pub(super) unsafe fn deconstruct(
self,
) -> (
PayloadChannelWriteFn,
PayloadChannelWriteCtx,
PayloadChannelReadCallback,
) {
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_payload_channel_write_fn<F>(read_callback: F) -> PreparedPayloadChannelWrite
where
F: FnMut(&[u8], &[u8]) + Send + 'static,
{
unsafe extern "C" fn wrapper<F>(
message: *const u8,
message_len: u32,
payload: *const u8,
payload_len: u32,
ctx: *const c_void,
) where
F: FnMut(&[u8], &[u8]) + Send + 'static,
{
let message = slice::from_raw_parts(message, message_len as usize);
let payload = if payload_len == 0 {
&[]
} else {
slice::from_raw_parts(payload, payload_len as usize)
};
(*(ctx as *mut F))(message, payload);
}
// Move to heap to make sure it doesn't change address later on
let read_callback = Box::new(read_callback);
PreparedPayloadChannelWrite {
channel_write_fn: wrapper::<F>,
channel_write_ctx: read_callback.as_ref() as *const F as *const c_void,
read_callback: PayloadChannelReadCallback(read_callback),
} }
} }
...@@ -71,6 +71,11 @@ namespace PayloadChannel ...@@ -71,6 +71,11 @@ namespace PayloadChannel
public: public:
explicit PayloadChannelSocket(int consumerFd, int producerFd); explicit PayloadChannelSocket(int consumerFd, int producerFd);
explicit PayloadChannelSocket(
int consumerFd,
int producerFd,
PayloadChannelWriteFn payloadChannelWriteFn,
PayloadChannelWriteCtx payloadChannelWriteCtx);
virtual ~PayloadChannelSocket(); virtual ~PayloadChannelSocket();
public: public:
...@@ -80,7 +85,9 @@ namespace PayloadChannel ...@@ -80,7 +85,9 @@ namespace PayloadChannel
void Send(json& jsonMessage); void Send(json& jsonMessage);
private: private:
void SendImpl(const void* payload, uint32_t payloadLen); void SendImpl(const uint8_t* message, uint32_t messageLen);
void SendImpl(
const uint8_t* message, uint32_t messageLen, const uint8_t* payload, uint32_t payloadLen);
/* Pure virtual methods inherited from ConsumerSocket::Listener. */ /* Pure virtual methods inherited from ConsumerSocket::Listener. */
public: public:
...@@ -94,6 +101,8 @@ namespace PayloadChannel ...@@ -94,6 +101,8 @@ namespace PayloadChannel
bool closed{ false }; bool closed{ false };
ConsumerSocket consumerSocket; ConsumerSocket consumerSocket;
ProducerSocket producerSocket; ProducerSocket producerSocket;
PayloadChannelWriteFn payloadChannelWriteFn{ nullptr };
PayloadChannelWriteCtx payloadChannelWriteCtx{ nullptr };
PayloadChannel::Notification* ongoingNotification{ nullptr }; PayloadChannel::Notification* ongoingNotification{ nullptr };
PayloadChannel::PayloadChannelRequest* ongoingRequest{ nullptr }; PayloadChannel::PayloadChannelRequest* ongoingRequest{ nullptr };
uint8_t* writeBuffer; uint8_t* writeBuffer;
......
...@@ -29,5 +29,12 @@ typedef SSIZE_T ssize_t; ...@@ -29,5 +29,12 @@ typedef SSIZE_T ssize_t;
using ChannelWriteCtx = void*; using ChannelWriteCtx = void*;
using ChannelWriteFn = using ChannelWriteFn =
void (*)(const uint8_t* /* message */, uint32_t /* messageLen */, ChannelWriteCtx /* ctx */); void (*)(const uint8_t* /* message */, uint32_t /* messageLen */, ChannelWriteCtx /* ctx */);
using PayloadChannelWriteCtx = void*;
using PayloadChannelWriteFn = void (*)(
const uint8_t* /* message */,
uint32_t /* messageLen */,
const uint8_t* /* payload */,
uint32_t /* payloadLen */,
ChannelWriteCtx /* ctx */);
#endif #endif
...@@ -9,4 +9,6 @@ extern "C" int run_worker( ...@@ -9,4 +9,6 @@ extern "C" int run_worker(
int payloadConsumeChannelFd, int payloadConsumeChannelFd,
int payloadProduceChannelFd, int payloadProduceChannelFd,
ChannelWriteFn channelWriteFn, ChannelWriteFn channelWriteFn,
ChannelWriteCtx channelWriteCtx); ChannelWriteCtx channelWriteCtx,
PayloadChannelWriteFn payloadChannelWriteFn,
PayloadChannelWriteCtx payloadChannelWriteCtx);
...@@ -23,7 +23,20 @@ namespace PayloadChannel ...@@ -23,7 +23,20 @@ namespace PayloadChannel
{ {
MS_TRACE(); MS_TRACE();
this->writeBuffer = (uint8_t*)std::malloc(MessageMaxLen); this->writeBuffer = static_cast<uint8_t*>(std::malloc(MessageMaxLen));
}
PayloadChannelSocket::PayloadChannelSocket(
int consumerFd,
int producerFd,
PayloadChannelWriteFn payloadChannelWriteFn,
PayloadChannelWriteCtx payloadChannelWriteCtx)
: consumerSocket(consumerFd, MessageMaxLen, this), producerSocket(producerFd, MessageMaxLen),
payloadChannelWriteFn(payloadChannelWriteFn), payloadChannelWriteCtx(payloadChannelWriteCtx)
{
MS_TRACE();
this->writeBuffer = static_cast<uint8_t*>(std::malloc(MessageMaxLen));
} }
PayloadChannelSocket::~PayloadChannelSocket() PayloadChannelSocket::~PayloadChannelSocket()
...@@ -79,8 +92,11 @@ namespace PayloadChannel ...@@ -79,8 +92,11 @@ namespace PayloadChannel
return; return;
} }
SendImpl(message.c_str(), static_cast<uint32_t>(message.length())); SendImpl(
SendImpl(payload, static_cast<uint32_t>(payloadLen)); reinterpret_cast<const uint8_t*>(message.c_str()),
static_cast<uint32_t>(message.length()),
payload,
static_cast<uint32_t>(payloadLen));
} }
void PayloadChannelSocket::Send(json& jsonMessage) void PayloadChannelSocket::Send(json& jsonMessage)
...@@ -99,24 +115,51 @@ namespace PayloadChannel ...@@ -99,24 +115,51 @@ namespace PayloadChannel
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()));
} }
inline void PayloadChannelSocket::SendImpl(const void* payload, uint32_t payloadLen) inline void PayloadChannelSocket::SendImpl(const uint8_t* message, uint32_t messageLen)
{ {
MS_TRACE(); MS_TRACE();
std::memcpy(this->writeBuffer, &payloadLen, sizeof(uint32_t)); // Write using function call if provided.
if (this->payloadChannelWriteFn)
{
this->payloadChannelWriteFn(message, messageLen, nullptr, 0, this->payloadChannelWriteCtx);
}
else
{
std::memcpy(this->writeBuffer, &messageLen, sizeof(uint32_t));
if (payloadLen != 0) if (messageLen != 0)
{ {
std::memcpy(this->writeBuffer + sizeof(uint32_t), payload, payloadLen); std::memcpy(this->writeBuffer + sizeof(uint32_t), message, messageLen);
} }
size_t len = sizeof(uint32_t) + payloadLen; size_t len = sizeof(uint32_t) + messageLen;
this->producerSocket.Write(this->writeBuffer, len); this->producerSocket.Write(this->writeBuffer, len);
} }
}
inline void PayloadChannelSocket::SendImpl(
const uint8_t* message, uint32_t messageLen, const uint8_t* payload, uint32_t payloadLen)
{
MS_TRACE();
// Write using function call if provided.
if (this->payloadChannelWriteFn)
{
this->payloadChannelWriteFn(
message, messageLen, payload, payloadLen, this->payloadChannelWriteCtx);
}
else
{
SendImpl(message, messageLen);
SendImpl(payload, payloadLen);
}
}
void PayloadChannelSocket::OnConsumerSocketMessage( void PayloadChannelSocket::OnConsumerSocketMessage(
ConsumerSocket* /*consumerSocket*/, char* msg, size_t msgLen) ConsumerSocket* /*consumerSocket*/, char* msg, size_t msgLen)
......
...@@ -37,7 +37,9 @@ extern "C" int run_worker( ...@@ -37,7 +37,9 @@ extern "C" int run_worker(
int payloadConsumeChannelFd, int payloadConsumeChannelFd,
int payloadProduceChannelFd, int payloadProduceChannelFd,
ChannelWriteFn channelWriteFn, ChannelWriteFn channelWriteFn,
ChannelWriteCtx channelWriteCtx) ChannelWriteCtx channelWriteCtx,
PayloadChannelWriteFn payloadChannelWriteFn,
PayloadChannelWriteCtx payloadChannelWriteCtx)
{ {
// Initialize libuv stuff (we need it for the Channel). // Initialize libuv stuff (we need it for the Channel).
DepLibUV::ClassInit(); DepLibUV::ClassInit();
...@@ -69,8 +71,8 @@ extern "C" int run_worker( ...@@ -69,8 +71,8 @@ extern "C" int run_worker(
try try
{ {
payloadChannel.reset( payloadChannel.reset(new PayloadChannel::PayloadChannelSocket(
new PayloadChannel::PayloadChannelSocket(payloadConsumeChannelFd, payloadProduceChannelFd)); payloadConsumeChannelFd, payloadProduceChannelFd, payloadChannelWriteFn, payloadChannelWriteCtx));
} }
catch (const MediaSoupError& error) catch (const MediaSoupError& error)
{ {
......
...@@ -7,6 +7,15 @@ pub type ChannelWriteFn = unsafe extern "C" fn( ...@@ -7,6 +7,15 @@ pub type ChannelWriteFn = unsafe extern "C" fn(
/* ctx: */ ChannelWriteCtx, /* ctx: */ ChannelWriteCtx,
); );
pub type PayloadChannelWriteCtx = *const c_void;
pub type PayloadChannelWriteFn = unsafe extern "C" fn(
/* message: */ *const u8,
/* message_len: */ u32,
/* payload: */ *const u8,
/* payload_len: */ u32,
/* ctx: */ ChannelWriteCtx,
);
#[link(name = "mediasoup-worker", kind = "static")] #[link(name = "mediasoup-worker", kind = "static")]
extern "C" { extern "C" {
pub fn run_worker( pub fn run_worker(
...@@ -19,5 +28,7 @@ extern "C" { ...@@ -19,5 +28,7 @@ extern "C" {
payload_producer_channel_fd: c_int, payload_producer_channel_fd: c_int,
channel_write_fn: ChannelWriteFn, channel_write_fn: ChannelWriteFn,
channel_write_ctx: ChannelWriteCtx, channel_write_ctx: ChannelWriteCtx,
payload_channel_write_fn: PayloadChannelWriteFn,
payload_channel_write_ctx: PayloadChannelWriteCtx,
) -> c_int; ) -> c_int;
} }
...@@ -32,6 +32,8 @@ int main(int argc, char* argv[]) ...@@ -32,6 +32,8 @@ int main(int argc, char* argv[])
PayloadConsumerChannelFd, PayloadConsumerChannelFd,
PayloadProducerChannelFd, PayloadProducerChannelFd,
nullptr, nullptr,
nullptr,
nullptr,
nullptr); nullptr);
switch (statusCode) switch (statusCode)
......
Markdown 格式
0% 或
您添加了 0 人 到此讨论。请谨慎行事。
请先完成此评论的编辑!
请 注册 或者 后发表评论