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

Send payload channel requests to worker with a function call instead of though…

Send payload channel requests to worker with a function call instead of though file descriptor in Rust (step 4, old fd-based read code is removed)
上级 f4c0bf1a
差异被折叠。
......@@ -356,12 +356,7 @@ impl Inner {
payload_channel,
status_receiver,
buffer_worker_messages_guard,
} = utils::run_worker_with_channels(
id,
thread_initializer,
Arc::clone(&executor),
spawn_args,
);
} = utils::run_worker_with_channels(id, thread_initializer, spawn_args);
let handlers = Handlers::default();
......
......@@ -4,18 +4,17 @@ 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_read_fn::{prepare_channel_read_fn, PreparedChannelRead};
pub(super) use channel_read_fn::{
prepare_channel_read_fn, prepare_payload_channel_read_fn, PreparedChannelRead,
PreparedPayloadChannelRead,
};
pub(super) use channel_write_fn::{
prepare_channel_write_fn, prepare_payload_channel_write_fn, PreparedChannelWrite,
PreparedPayloadChannelWrite,
};
use std::ffi::CString;
use std::mem;
use std::os::raw::{c_char, c_int};
use std::os::unix::io::FromRawFd;
use std::sync::Arc;
use thiserror::Error;
......@@ -39,18 +38,6 @@ pub enum ExitError {
Unexpected,
}
fn pipe() -> [c_int; 2] {
unsafe {
let mut fds = mem::MaybeUninit::<[c_int; 2]>::uninit();
if libc::pipe(fds.as_mut_ptr().cast::<c_int>()) != 0 {
panic!("libc::pipe() failed: {:?}", std::io::Error::last_os_error());
}
fds.assume_init()
}
}
pub(super) struct WorkerRunResult {
pub(super) channel: Channel,
pub(super) payload_channel: PayloadChannel,
......@@ -61,19 +48,13 @@ pub(super) struct WorkerRunResult {
pub(super) fn run_worker_with_channels(
id: WorkerId,
thread_initializer: Option<Arc<dyn Fn() + Send + Sync>>,
executor: Arc<Executor<'static>>,
args: Vec<String>,
) -> WorkerRunResult {
let [producer_payload_fd_read, producer_payload_fd_write] = pipe();
let [consumer_payload_fd_read, consumer_payload_fd_write] = pipe();
let (mut status_sender, status_receiver) = async_oneshot::oneshot();
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, prepared_channel_read, prepared_channel_write) = Channel::new();
let (payload_channel, prepared_payload_channel_write) =
PayloadChannel::new(&executor, consumer_payload_file, producer_payload_file);
let (payload_channel, prepared_payload_channel_read, prepared_payload_channel_write) =
PayloadChannel::new();
let buffer_worker_messages_guard = channel.buffer_messages_for(std::process::id().into());
std::thread::Builder::new()
......@@ -98,6 +79,11 @@ pub(super) fn run_worker_with_channels(
prepared_channel_read.deconstruct();
let (channel_write_fn, channel_write_ctx, _channel_read_callback) =
prepared_channel_write.deconstruct();
let (
payload_channel_read_fn,
payload_channel_read_ctx,
_payload_channel_write_callback,
) = prepared_payload_channel_read.deconstruct();
let (
payload_channel_write_fn,
payload_channel_write_ctx,
......@@ -110,19 +96,19 @@ pub(super) fn run_worker_with_channels(
version.as_ptr(),
0,
0,
producer_payload_fd_read,
consumer_payload_fd_write,
0,
0,
channel_read_fn,
channel_read_ctx,
channel_write_fn,
channel_write_ctx,
payload_channel_read_fn,
payload_channel_read_ctx,
payload_channel_write_fn,
payload_channel_write_ctx,
)
};
println!("Status sent {}", status_code);
let _ = status_sender.send(match status_code {
0 => Ok(()),
1 => Err(ExitError::Generic),
......
pub(super) use mediasoup_sys::{ChannelReadCtx, ChannelReadFn};
use mediasoup_sys::{ChannelReadFreeFn, UvAsyncT};
pub(super) use mediasoup_sys::{
ChannelReadCtx, ChannelReadFn, PayloadChannelReadCtx, PayloadChannelReadFn,
};
use mediasoup_sys::{ChannelReadFreeFn, PayloadChannelReadFreeFn, UvAsyncT};
use std::mem;
use std::os::raw::c_void;
unsafe extern "C" fn free_vec(message: *mut u8, message_len: u32, message_capacity: usize) {
Vec::from_raw_parts(message, message_len as usize, message_capacity);
}
pub(super) struct ChannelReadCallback(
Box<dyn (FnMut(UvAsyncT) -> Option<Vec<u8>>) + Send + 'static>,
);
......@@ -30,10 +36,6 @@ impl PreparedChannelRead {
}
}
unsafe extern "C" fn free_vec(message: *mut u8, message_len: u32, message_capacity: usize) {
Vec::from_raw_parts(message, message_len as usize, message_capacity);
}
/// Given callback function, prepares a pair of channel read function and context, which can be
/// provided to of C++ worker and worker will effectively call the callback whenever it wants to
/// read something from Rust (so it is reading from C++ point of view and writing from Rust).
......@@ -75,3 +77,91 @@ where
write_callback: ChannelReadCallback(read_callback),
}
}
pub(super) struct PayloadChannelReadCallback(
Box<dyn (FnMut(UvAsyncT) -> Option<(Vec<u8>, Vec<u8>)>) + Send + 'static>,
);
pub(crate) struct PreparedPayloadChannelRead {
payload_channel_read_fn: PayloadChannelReadFn,
payload_channel_read_ctx: PayloadChannelReadCtx,
write_callback: PayloadChannelReadCallback,
}
unsafe impl Send for PreparedPayloadChannelRead {}
impl PreparedPayloadChannelRead {
/// SAFETY:
/// 1) `PayloadChannelReadCallback` returned must be dropped AFTER last usage of returned
/// function and context pointers
/// 2) `PayloadChannelReadCtx` should not be called from multiple threads concurrently
pub(super) unsafe fn deconstruct(
self,
) -> (
PayloadChannelReadFn,
PayloadChannelReadCtx,
PayloadChannelReadCallback,
) {
let Self {
payload_channel_read_fn,
payload_channel_read_ctx,
write_callback,
} = self;
(
payload_channel_read_fn,
payload_channel_read_ctx,
write_callback,
)
}
}
/// Given callback function, prepares a pair of channel read function and context, which can be
/// provided to of C++ worker and worker will effectively call the callback whenever it wants to
/// read something from Rust (so it is reading from C++ point of view and writing from Rust).
pub(crate) fn prepare_payload_channel_read_fn<F>(read_callback: F) -> PreparedPayloadChannelRead
where
F: (FnMut(UvAsyncT) -> Option<(Vec<u8>, Vec<u8>)>) + Send + 'static,
{
unsafe extern "C" fn wrapper<F>(
message: *mut *mut u8,
message_len: *mut u32,
message_capacity: *mut usize,
payload: *mut *mut u8,
payload_len: *mut u32,
payload_capacity: *mut usize,
handle: UvAsyncT,
PayloadChannelReadCtx(ctx): PayloadChannelReadCtx,
) -> PayloadChannelReadFreeFn
where
F: (FnMut(UvAsyncT) -> Option<(Vec<u8>, Vec<u8>)>) + Send + 'static,
{
// Call Rust and try to get a new message (if there is any)
let (mut new_message, mut new_payload) = (*(ctx as *mut F))(handle)?;
// Set pointers, give out control over memory to C++
*message = new_message.as_mut_ptr();
*message_len = new_message.len() as u32;
*message_capacity = new_message.capacity();
*payload = new_payload.as_mut_ptr();
*payload_len = new_payload.len() as u32;
*payload_capacity = new_payload.capacity();
// Forget about vectors in Rust
mem::forget(new_message);
mem::forget(new_payload);
// Function pointer that C++ can use to free vectors later
Some(free_vec)
}
// Move to heap to make sure it doesn't change address later on
let read_callback = Box::new(read_callback);
PreparedPayloadChannelRead {
payload_channel_read_fn: wrapper::<F>,
payload_channel_read_ctx: PayloadChannelReadCtx(
read_callback.as_ref() as *const F as *const c_void
),
write_callback: PayloadChannelReadCallback(read_callback),
}
}
......@@ -74,9 +74,9 @@ namespace Channel
public:
void Close();
void SetListener(Listener* listener);
bool CallbackRead();
void Send(json& jsonMessage);
void SendLog(const char* message, uint32_t messageLen);
bool CallbackRead();
private:
void SendImpl(const uint8_t* payload, uint32_t payloadLen);
......
......@@ -72,8 +72,8 @@ namespace PayloadChannel
public:
explicit PayloadChannelSocket(int consumerFd, int producerFd);
explicit PayloadChannelSocket(
int consumerFd,
int producerFd,
PayloadChannelReadFn payloadChannelReadFn,
PayloadChannelReadCtx payloadChannelReadCtx,
PayloadChannelWriteFn payloadChannelWriteFn,
PayloadChannelWriteCtx payloadChannelWriteCtx);
virtual ~PayloadChannelSocket();
......@@ -81,6 +81,7 @@ namespace PayloadChannel
public:
void Close();
void SetListener(Listener* listener);
bool CallbackRead();
void Send(json& jsonMessage, const uint8_t* payload, size_t payloadLen);
void Send(json& jsonMessage);
......@@ -99,13 +100,16 @@ namespace PayloadChannel
Listener* listener{ nullptr };
// Others.
bool closed{ false };
ConsumerSocket consumerSocket;
ProducerSocket producerSocket;
ConsumerSocket* consumerSocket{ nullptr };
ProducerSocket* producerSocket{ nullptr };
PayloadChannelReadFn payloadChannelReadFn{ nullptr };
PayloadChannelReadCtx payloadChannelReadCtx{ nullptr };
PayloadChannelWriteFn payloadChannelWriteFn{ nullptr };
PayloadChannelWriteCtx payloadChannelWriteCtx{ nullptr };
PayloadChannel::Notification* ongoingNotification{ nullptr };
PayloadChannel::PayloadChannelRequest* ongoingRequest{ nullptr };
uint8_t* writeBuffer;
uv_async_t* uvReadHandle{ nullptr };
uint8_t* writeBuffer{ nullptr };
};
} // namespace PayloadChannel
......
......@@ -42,6 +42,21 @@ using ChannelWriteCtx = void*;
using ChannelWriteFn =
void (*)(const uint8_t* /* message */, uint32_t /* messageLen */, ChannelWriteCtx /* ctx */);
using PayloadChannelReadCtx = void*;
using PayloadChannelReadFreeFn = void (*)(uint8_t*, uint32_t, size_t);
// Returns `PayloadChannelReadFree` on successful read that must be used to free `message` and `payload`
using PayloadChannelReadFn = PayloadChannelReadFreeFn (*)(
uint8_t** /* message */,
uint32_t* /* messageLen */,
size_t* /* messageCapacity */,
uint8_t** /* payload */,
uint32_t* /* payloadLen */,
size_t* /* payloadCapacity */,
// This is `uv_async_t` handle that can be called later with `uv_async_send()` when there is more
// data to read
const void* /* handle */,
PayloadChannelReadCtx /* ctx */);
using PayloadChannelWriteCtx = void*;
using PayloadChannelWriteFn = void (*)(
const uint8_t* /* message */,
......
......@@ -12,5 +12,7 @@ extern "C" int run_worker(
ChannelReadCtx channelReadCtx,
ChannelWriteFn channelWriteFn,
ChannelWriteCtx channelWriteCtx,
PayloadChannelReadFn payloadChannelReadFn,
PayloadChannelReadCtx payloadChannelReadCtx,
PayloadChannelWriteFn payloadChannelWriteFn,
PayloadChannelWriteCtx payloadChannelWriteCtx);
......@@ -2,6 +2,7 @@
// #define MS_LOG_DEV_LEVEL 3
#include "PayloadChannel/PayloadChannelSocket.hpp"
#include "DepLibUV.hpp"
#include "Logger.hpp"
#include "MediaSoupErrors.hpp"
#include "PayloadChannel/PayloadChannelRequest.hpp"
......@@ -12,6 +13,18 @@
namespace PayloadChannel
{
/* Static. */
inline static void onAsync(uv_handle_t* handle)
{
while (static_cast<PayloadChannelSocket*>(handle->data)->CallbackRead())
{
// Read while there are new messages
}
}
inline static void onClose(uv_handle_t* handle)
{
delete handle;
}
// Binary length for a 4194304 bytes payload.
static constexpr size_t MessageMaxLen{ 4194308 };
......@@ -19,24 +32,48 @@ namespace PayloadChannel
/* Instance methods. */
PayloadChannelSocket::PayloadChannelSocket(int consumerFd, int producerFd)
: consumerSocket(consumerFd, MessageMaxLen, this), producerSocket(producerFd, MessageMaxLen)
: consumerSocket(new ConsumerSocket(consumerFd, MessageMaxLen, this)),
producerSocket(new ProducerSocket(producerFd, MessageMaxLen)),
writeBuffer(static_cast<uint8_t*>(std::malloc(MessageMaxLen)))
{
MS_TRACE();
this->writeBuffer = static_cast<uint8_t*>(std::malloc(MessageMaxLen));
}
PayloadChannelSocket::PayloadChannelSocket(
int consumerFd,
int producerFd,
PayloadChannelReadFn payloadChannelReadFn,
PayloadChannelReadCtx payloadChannelReadCtx,
PayloadChannelWriteFn payloadChannelWriteFn,
PayloadChannelWriteCtx payloadChannelWriteCtx)
: consumerSocket(consumerFd, MessageMaxLen, this), producerSocket(producerFd, MessageMaxLen),
: payloadChannelReadFn(payloadChannelReadFn), payloadChannelReadCtx(payloadChannelReadCtx),
payloadChannelWriteFn(payloadChannelWriteFn), payloadChannelWriteCtx(payloadChannelWriteCtx)
{
MS_TRACE();
this->writeBuffer = static_cast<uint8_t*>(std::malloc(MessageMaxLen));
int err;
this->uvReadHandle = new uv_async_t;
this->uvReadHandle->data = static_cast<void*>(this);
err =
uv_async_init(DepLibUV::GetLoop(), this->uvReadHandle, reinterpret_cast<uv_async_cb>(onAsync));
if (err != 0)
{
delete this->uvReadHandle;
this->uvReadHandle = nullptr;
MS_THROW_ERROR("uv_async_init() failed: %s", uv_strerror(err));
}
err = uv_async_send(this->uvReadHandle);
if (err != 0)
{
delete this->uvReadHandle;
this->uvReadHandle = nullptr;
MS_THROW_ERROR("uv_async_send() failed: %s", uv_strerror(err));
}
}
PayloadChannelSocket::~PayloadChannelSocket()
......@@ -48,6 +85,9 @@ namespace PayloadChannel
if (!this->closed)
Close();
delete this->consumerSocket;
delete this->producerSocket;
}
void PayloadChannelSocket::Close()
......@@ -59,8 +99,20 @@ namespace PayloadChannel
this->closed = true;
this->consumerSocket.Close();
this->producerSocket.Close();
if (this->uvReadHandle)
{
uv_close(reinterpret_cast<uv_handle_t*>(this->uvReadHandle), static_cast<uv_close_cb>(onClose));
}
if (this->consumerSocket)
{
this->consumerSocket->Close();
}
if (this->producerSocket)
{
this->producerSocket->Close();
}
}
void PayloadChannelSocket::SetListener(Listener* listener)
......@@ -119,6 +171,122 @@ namespace PayloadChannel
reinterpret_cast<const uint8_t*>(message.c_str()), static_cast<uint32_t>(message.length()));
}
bool PayloadChannelSocket::CallbackRead()
{
MS_TRACE();
if (this->closed)
return false;
uint8_t* message{ nullptr };
uint32_t messageLen;
size_t messageCapacity;
uint8_t* payload{ nullptr };
uint32_t payloadLen;
size_t payloadCapacity;
auto free = this->payloadChannelReadFn(
&message,
&messageLen,
&messageCapacity,
&payload,
&payloadLen,
&payloadCapacity,
this->uvReadHandle,
this->payloadChannelReadCtx);
if (free)
{
try
{
json jsonData = json::parse(message, message + static_cast<size_t>(messageLen));
if (PayloadChannelRequest::IsRequest(jsonData))
{
try
{
auto* request = new PayloadChannel::PayloadChannelRequest(this, jsonData);
request->SetPayload(payload, payloadLen);
// Notify the listener.
try
{
this->listener->OnPayloadChannelRequest(this, request);
}
catch (const MediaSoupTypeError& error)
{
request->TypeError(error.what());
}
catch (const MediaSoupError& error)
{
request->Error(error.what());
}
// Delete the Request.
delete request;
}
catch (const json::parse_error& error)
{
MS_ERROR_STD("JSON parsing error: %s", error.what());
}
catch (const MediaSoupError& error)
{
MS_ERROR("discarding wrong Payload Channel notification");
}
}
else if (Notification::IsNotification(jsonData))
{
try
{
auto* notification = new PayloadChannel::Notification(jsonData);
notification->SetPayload(payload, payloadLen);
// Notify the listener.
try
{
this->listener->OnPayloadChannelNotification(this, notification);
}
catch (const MediaSoupError& error)
{
MS_ERROR("notification failed: %s", error.what());
}
// Delete the Notification.
delete notification;
}
catch (const json::parse_error& error)
{
MS_ERROR_STD("JSON parsing error: %s", error.what());
}
catch (const MediaSoupError& error)
{
MS_ERROR("discarding wrong Payload Channel notification");
}
}
else
{
MS_ERROR("discarding wrong Payload Channel data");
}
}
catch (const json::parse_error& error)
{
MS_ERROR("JSON parsing error: %s", error.what());
}
catch (const MediaSoupError& error)
{
MS_ERROR("discarding wrong Channel request");
}
free(message, messageLen, messageCapacity);
free(payload, payloadLen, payloadCapacity);
}
return free != nullptr;
}
inline void PayloadChannelSocket::SendImpl(const uint8_t* message, uint32_t messageLen)
{
MS_TRACE();
......@@ -139,7 +307,7 @@ namespace PayloadChannel
size_t len = sizeof(uint32_t) + messageLen;
this->producerSocket.Write(this->writeBuffer, len);
this->producerSocket->Write(this->writeBuffer, len);
}
}
......
......@@ -40,6 +40,8 @@ extern "C" int run_worker(
ChannelReadCtx channelReadCtx,
ChannelWriteFn channelWriteFn,
ChannelWriteCtx channelWriteCtx,
PayloadChannelReadFn payloadChannelReadFn,
PayloadChannelReadCtx payloadChannelReadCtx,
PayloadChannelWriteFn payloadChannelWriteFn,
PayloadChannelWriteCtx payloadChannelWriteCtx)
{
......@@ -80,8 +82,16 @@ extern "C" int run_worker(
try
{
payloadChannel.reset(new PayloadChannel::PayloadChannelSocket(
payloadConsumeChannelFd, payloadProduceChannelFd, payloadChannelWriteFn, payloadChannelWriteCtx));
if (payloadChannelReadFn)
{
payloadChannel.reset(new PayloadChannel::PayloadChannelSocket(
payloadChannelReadFn, payloadChannelReadCtx, payloadChannelWriteFn, payloadChannelWriteCtx));
}
else
{
payloadChannel.reset(
new PayloadChannel::PayloadChannelSocket(payloadConsumeChannelFd, payloadProduceChannelFd));
}
}
catch (const MediaSoupError& error)
{
......
......@@ -34,6 +34,29 @@ pub type ChannelWriteFn = unsafe extern "C" fn(
/* ctx: */ ChannelWriteCtx,
);
#[repr(transparent)]
pub struct PayloadChannelReadCtx(pub *const c_void);
pub type PayloadChannelReadFreeFn = Option<
unsafe extern "C" fn(
/* message: */ *mut u8,
/* message_len: */ u32,
/* message_capacity: */ usize,
),
>;
pub type PayloadChannelReadFn = unsafe extern "C" fn(
/* message: */ *mut *mut u8,
/* message_len: */ *mut u32,
/* message_capacity: */ *mut usize,
/* payload: */ *mut *mut u8,
/* payload_len: */ *mut u32,
/* payload_capacity: */ *mut usize,
// This is `uv_async_t` handle that can be called later with `uv_async_send()` when there is
// more data to read
/* handle */
UvAsyncT,
/* ctx: */ PayloadChannelReadCtx,
) -> PayloadChannelReadFreeFn;
#[repr(transparent)]
pub struct PayloadChannelWriteCtx(pub *const c_void);
pub type PayloadChannelWriteFn = unsafe extern "C" fn(
......@@ -61,6 +84,8 @@ extern "C" {
channel_read_ctx: ChannelReadCtx,
channel_write_fn: ChannelWriteFn,
channel_write_ctx: ChannelWriteCtx,
payload_channel_read_fn: PayloadChannelReadFn,
payload_channel_read_ctx: PayloadChannelReadCtx,
payload_channel_write_fn: PayloadChannelWriteFn,
payload_channel_write_ctx: PayloadChannelWriteCtx,
) -> c_int;
......
......@@ -36,6 +36,8 @@ int main(int argc, char* argv[])
nullptr,
nullptr,
nullptr,
nullptr,
nullptr,
nullptr);
switch (statusCode)
......
Markdown 格式
0% 或
您添加了 0 人 到此讨论。请谨慎行事。
请先完成此评论的编辑!
请 注册 或者 后发表评论