Skip to content

Commit

Permalink
fix: try with everthing rollbacked
Browse files Browse the repository at this point in the history
  • Loading branch information
evdokimovs committed Dec 9, 2024
1 parent 0d40bae commit a2398f5
Show file tree
Hide file tree
Showing 11 changed files with 72 additions and 112 deletions.
2 changes: 0 additions & 2 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,6 @@ readme = "README.md"
keywords = ["medea", "jason", "webrtc", "client", "browser"]
categories = ["multimedia", "api-bindings", "web-programming", "wasm"]
include = ["/src/", "/build.rs", "/CHANGELOG.md", "/LICENSE.md"]
# TODO: Remove when https://github.com/rustwasm/wasm-pack/issues/1441 will be resolved.
wasm-opt = false

[workspace]
members = [
Expand Down
1 change: 0 additions & 1 deletion crates/medea-macro/src/dart_bridge.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,6 @@ use syn::{parse_quote, punctuated::Punctuated, spanned::Spanned as _, token};
use crate::dart_codegen::{DartCodegen, FnRegistrationBuilder};

/// Expands `#[dart_bridge]` attribute placed on a Rust module declaration.
// TODO: Refactor to get rid of `static mut` in this macro.
pub(crate) fn expand(
args: TokenStream,
input: TokenStream,
Expand Down
9 changes: 3 additions & 6 deletions src/api/dart/api/local_media_track.rs
Original file line number Diff line number Diff line change
Expand Up @@ -40,12 +40,9 @@ impl LocalMediaTrack {
#[frb(sync)]
#[must_use]
pub fn get_track(&self) -> DartOpaque {
DartOpaque::new(
self.0.get_track().handle() as _,
DART_HANDLER_PORT
.get()
.expect("`DART_HANDLER_PORT` must be initialized"),
)
DartOpaque::new(self.0.get_track().handle() as _, unsafe {
DART_HANDLER_PORT.unwrap()
})
}

/// Returns a [`MediaKind::Audio`] if the provided [`LocalMediaTrack`]
Expand Down
17 changes: 10 additions & 7 deletions src/api/dart/api/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,9 @@ pub mod remote_media_track;
pub mod room;
pub mod room_close_reason;

use std::{cell::Cell, ptr};
use std::ptr;

use flutter_rust_bridge::{frb, DartOpaque};

use crate::{
media::{
Expand All @@ -51,7 +53,6 @@ use crate::{
},
platform::{self},
};
use flutter_rust_bridge::{frb, DartOpaque};

pub use dart_sys::Dart_Handle;

Expand All @@ -62,10 +63,8 @@ pub use self::{
room::RoomHandle, room_close_reason::RoomCloseReason,
};

thread_local! {
/// Used to create [`DartOpaque`]s on the Rust side.
pub static DART_HANDLER_PORT: Cell<Option<i64>> = Cell::default();
}
/// Used to create [`DartOpaque`]s on the Rust side.
pub static mut DART_HANDLER_PORT: Option<i64> = None;

/// Rust structure having wrapper class in Dart.
///
Expand Down Expand Up @@ -382,5 +381,9 @@ pub fn on_panic(cb: DartOpaque) {
#[frb(sync)]
#[must_use]
pub fn set_dart_opaque_message_port(dart_handler_port: i64) {
DART_HANDLER_PORT.set(Some(dart_handler_port));
// TODO: Refactor to get rid of `static mut`.
#[expect(static_mut_refs, reason = "needs refactoring")]
unsafe {
DART_HANDLER_PORT.replace(dart_handler_port);
}
}
9 changes: 3 additions & 6 deletions src/api/dart/api/remote_media_track.rs
Original file line number Diff line number Diff line change
Expand Up @@ -34,12 +34,9 @@ impl RemoteMediaTrack {
#[frb(sync)]
#[must_use]
pub fn get_track(&self) -> DartOpaque {
DartOpaque::new(
self.0.get_track().handle() as _,
DART_HANDLER_PORT
.get()
.expect("`DART_HANDLER_PORT` must be initialized"),
)
DartOpaque::new(self.0.get_track().handle() as _, unsafe {
DART_HANDLER_PORT.unwrap()
})
}

/// Sets callback to invoke once this [`RemoteMediaTrack`] is muted.
Expand Down
10 changes: 3 additions & 7 deletions src/api/dart/err.rs
Original file line number Diff line number Diff line change
Expand Up @@ -135,16 +135,12 @@ impl DartError {
}
}

#[expect(clippy::fallible_impl_from, reason = "FFI error is unexpected")]
impl From<DartError> for DartOpaque {
fn from(val: DartError) -> Self {
let boxed = unsafe { Box::from_raw(val.0.as_ptr()) };
#[expect(clippy::expect_used, reason = "expected behavior")]
Self::new(
(*boxed).cast(),
DART_HANDLER_PORT
.get()
.expect("`DART_HANDLER_PORT` must be initialized"),
)
#[expect(clippy::unwrap_used, reason = "FFI error is unexpected")]
Self::new((*boxed).cast(), unsafe { DART_HANDLER_PORT.unwrap() })
}
}

Expand Down
23 changes: 11 additions & 12 deletions src/platform/dart/executor/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
mod task;

use std::{cell::Cell, future::Future, ptr, rc::Rc};
use std::{future::Future, ptr, rc::Rc};

use dart_sys::{
Dart_CObject, Dart_CObject_Type_Dart_CObject_kInt64, Dart_Port,
Expand All @@ -18,14 +18,12 @@ pub fn spawn(fut: impl Future<Output = ()> + 'static) {
Task::spawn(Box::pin(fut));
}

thread_local! {
/// A [`Dart_Port`] used to send [`Task`]'s poll commands so Dart will poll
/// Rust [`Future`]s.
///
/// Must be initialized with the [`rust_executor_init()`] function during
/// FFI initialization.
static WAKE_PORT: Cell<Option<Dart_Port>> = Cell::default();
}
/// A [`Dart_Port`] used to send [`Task`]'s poll commands so Dart will poll Rust
/// [`Future`]s.
///
/// Must be initialized with the [`rust_executor_init()`] function during FFI
/// initialization.
static mut WAKE_PORT: Option<Dart_Port> = None;

/// Initializes Dart-driven async [`Task`] executor.
///
Expand All @@ -37,7 +35,9 @@ thread_local! {
/// Must ONLY be called by Dart during FFI initialization.
#[no_mangle]
pub unsafe extern "C" fn rust_executor_init(wake_port: Dart_Port) {
WAKE_PORT.set(Some(wake_port));
unsafe {
WAKE_PORT = Some(wake_port);
}
}

/// Polls the provided [`Task`].
Expand All @@ -58,8 +58,7 @@ pub unsafe extern "C" fn rust_executor_poll_task(task: ptr::NonNull<Task>) {
/// [`WAKE_PORT`]. When received, Dart must poll it by calling the
/// [`rust_executor_poll_task()`] function.
fn task_wake(task: Rc<Task>) {
#[expect(clippy::expect_used, reason = "expected behavior")]
let wake_port = WAKE_PORT.get().expect("`WAKE_PORT` should be initialized");
let wake_port = unsafe { WAKE_PORT }.unwrap();
let task = Rc::into_raw(task);

let mut task_addr = Dart_CObject {
Expand Down
50 changes: 20 additions & 30 deletions src/platform/dart/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -30,10 +30,7 @@ pub mod transceiver;
pub mod transport;
pub mod utils;

use std::{
cell::{Cell, RefCell},
panic,
};
use std::panic;

use libc::c_void;

Expand Down Expand Up @@ -69,42 +66,36 @@ pub unsafe extern "C" fn init_jason_dart_api_dl(data: *mut c_void) -> isize {
/// Dart's functions.
pub fn set_panic_hook() {
panic::set_hook(Box::new(|bt| {
// PANIC_FN.with_borrow(|f| {
// if let Some(f) = f {
// f.call1(format!("{bt}"));
// }
// });
// TODO: Refactor to get rid of `static mut`.
#[expect(static_mut_refs, reason = "needs refactoring")]
if let Some(f) = unsafe { PANIC_FN.as_ref() } {
f.call1(format!("{bt}"));
}
}));
}

thread_local! {
/// [`Function`] being called whenever Rust code [`panic`]s.
static PANIC_FN: RefCell<Option<Function<String>>> = RefCell::default();
}
/// [`Function`] being called whenever Rust code [`panic`]s.
static mut PANIC_FN: Option<Function<String>> = None;

/// Sets the provided [`Function`] as a callback to be called whenever Rust code
/// [`panic`]s.
///
/// [`panic`]: panic!
pub fn set_panic_callback(cb: Function<String>) {
PANIC_FN.set(Some(cb));
}

thread_local! {
/// Flag which indicates that Android logger is initialized.
static IS_LOGGER_INITIALIZED: Cell<bool> = Cell::default();
unsafe {
PANIC_FN = Some(cb);
}
}

#[cfg(target_os = "android")]
/// Initializes [`android_logger`] as the default application logger with filter
/// level set to [`log::LevelFilter::Debug`].
pub fn init_logger() {
if !IS_LOGGER_INITIALIZED.replace(true) {
android_logger::init_once(
android_logger::Config::default()
.with_max_level(log::LevelFilter::Debug),
);
}
// TODO: `android_logger::init_once()` should be called only once.
android_logger::init_once(
android_logger::Config::default()
.with_max_level(log::LevelFilter::Debug),
);
}

#[cfg(any(
Expand All @@ -116,9 +107,8 @@ pub fn init_logger() {
/// Initializes [`simple_logger`] as the default application logger with filter
/// level set to [`log::LevelFilter::Debug`].
pub fn init_logger() {
if !IS_LOGGER_INITIALIZED.replace(true) {
_ = simple_logger::SimpleLogger::new()
.with_level(log::LevelFilter::Debug)
.init();
}
// TODO: Should be called only once.
_ = simple_logger::SimpleLogger::new()
.with_level(log::LevelFilter::Debug)
.init();
}
21 changes: 7 additions & 14 deletions src/platform/dart/utils/callback.rs
Original file line number Diff line number Diff line change
Expand Up @@ -220,8 +220,6 @@ extern "C" fn callback_finalizer(_: *mut c_void, cb: *mut c_void) {
pub mod tests {
#![expect(clippy::missing_safety_doc, reason = "only for testing")]

use std::cell::RefCell;

use dart_sys::Dart_Handle;

use crate::api::DartValueArg;
Expand Down Expand Up @@ -274,29 +272,24 @@ pub mod tests {

type TestCallbackHandleFunction = extern "C" fn(Dart_Handle);

thread_local! {
static TEST_CALLBACK_HANDLE_FUNCTION: RefCell<Option<
TestCallbackHandleFunction,
>> = RefCell::default();
}
static mut TEST_CALLBACK_HANDLE_FUNCTION: Option<
TestCallbackHandleFunction,
> = None;

#[no_mangle]
pub unsafe extern "C" fn register__test__test_callback_handle_function(
f: TestCallbackHandleFunction,
) {
TEST_CALLBACK_HANDLE_FUNCTION.set(Some(f));
unsafe {
TEST_CALLBACK_HANDLE_FUNCTION = Some(f);
}
}

#[expect(clippy::expect_used, reason = "intended behavior")]
#[no_mangle]
pub unsafe extern "C" fn test_callback_listener_dart_handle() -> Dart_Handle
{
Callback::from_once(move |val: Dart_Handle| {
TEST_CALLBACK_HANDLE_FUNCTION.with_borrow(|f| {
(f.expect("TEST_CALLBACK_HANDLE_FUNCTION must be initialized"))(
val,
);
});
(unsafe { TEST_CALLBACK_HANDLE_FUNCTION.unwrap() })(val);
})
.into_dart()
}
Expand Down
22 changes: 7 additions & 15 deletions src/platform/dart/utils/dart_future.rs
Original file line number Diff line number Diff line change
Expand Up @@ -160,7 +160,7 @@ impl<O> DartFuture<O> {
/// transferred to Dart side via `flutter_rust_bridge` bindings.
#[must_use]
pub fn into_dart_opaque(self) -> DartOpaque {
DartOpaque::new(self.0.cast(), DART_HANDLER_PORT.get().unwrap())
DartOpaque::new(self.0.cast(), unsafe { DART_HANDLER_PORT.unwrap() })
}
}

Expand Down Expand Up @@ -208,8 +208,6 @@ where
pub mod tests {
#![expect(clippy::missing_safety_doc, reason = "for testing only")]

use std::cell::RefCell;

use dart_sys::Dart_Handle;

use crate::{
Expand Down Expand Up @@ -252,20 +250,18 @@ pub mod tests {

type TestFutureHandleFunction = extern "C" fn(Dart_Handle);

thread_local! {
static TEST_FUTURE_HANDLE_FUNCTION: RefCell<
Option<TestFutureHandleFunction>
> = RefCell::default();
}
static mut TEST_FUTURE_HANDLE_FUNCTION: Option<TestFutureHandleFunction> =
None;

#[no_mangle]
pub unsafe extern "C" fn register__test__future_from_dart_handle_fn(
f: TestFutureHandleFunction,
) {
TEST_FUTURE_HANDLE_FUNCTION.set(Some(f));
unsafe {
TEST_FUTURE_HANDLE_FUNCTION = Some(f);
}
}

#[expect(clippy::expect_used, reason = "intended behavior")]
#[no_mangle]
pub unsafe extern "C" fn test__future_from_dart__handle(
future: Dart_Handle,
Expand All @@ -276,11 +272,7 @@ pub mod tests {
unsafe { FutureFromDart::execute::<DartHandle>(future.get()) }
.await
.unwrap();
TEST_FUTURE_HANDLE_FUNCTION.with_borrow(|f| {
(f.expect("TEST_FUTURE_HANDLE_FUNCTION must be initialized"))(
val.get(),
);
});
(unsafe { TEST_FUTURE_HANDLE_FUNCTION.unwrap() })(val.get());
Ok(())
}
.into_dart_future()
Expand Down
20 changes: 8 additions & 12 deletions src/platform/dart/utils/string.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
//! Helper functionality for passing [`String`]s through FFI boundaries.
use std::{
cell::RefCell,
ffi::{CStr, CString},
os::raw::c_char,
ptr,
Expand All @@ -12,15 +11,10 @@ use crate::api::propagate_panic;
/// Pointer to an extern function that frees the provided Dart native string.
type FreeDartNativeStringFunction = extern "C" fn(ptr::NonNull<c_char>);

thread_local! {
/// Stores a pointer to the [`FreeDartNativeStringFunction`] extern
/// function.
///
/// Must be initialized by Dart during FFI initialization phase.
static FREE_DART_NATIVE_STRING: RefCell<
Option<FreeDartNativeStringFunction>
> = RefCell::default();
}
/// Stores a pointer to the [`FreeDartNativeStringFunction`] extern function.
///
/// Must be initialized by Dart during FFI initialization phase.
static mut FREE_DART_NATIVE_STRING: Option<FreeDartNativeStringFunction> = None;

/// Constructs a Rust [`String`] from the provided raw C string.
///
Expand Down Expand Up @@ -94,7 +88,9 @@ pub unsafe extern "C" fn String_free(s: ptr::NonNull<c_char>) {
pub unsafe extern "C" fn register_free_dart_native_string(
f: FreeDartNativeStringFunction,
) {
FREE_DART_NATIVE_STRING.set(Some(f));
unsafe {
FREE_DART_NATIVE_STRING = Some(f);
}
}

/// Calls Dart to release memory allocated for the provided native string.
Expand All @@ -107,5 +103,5 @@ pub unsafe extern "C" fn register_free_dart_native_string(
/// `FREE_DART_NATIVE_STRING` function must be registered and the provided
/// pointer must be a valid native string.
pub unsafe fn free_dart_native_string(s: ptr::NonNull<c_char>) {
FREE_DART_NATIVE_STRING.with_borrow(|f| (f.unwrap())(s));
(unsafe { FREE_DART_NATIVE_STRING.unwrap() })(s);
}

0 comments on commit a2398f5

Please sign in to comment.