webrtc icon indicating copy to clipboard operation
webrtc copied to clipboard

[All] change callback fn from Box<dyn ...> to Arc<dyn ..>

Open rainliu opened this issue 4 years ago • 5 comments

example:

pub type FnTimeGen = Arc<dyn (Fn() -> Pin<Box<dyn Future<Output = SystemTime> + Send + 'static>>) + Send + Sync>;

The purpose is to avoid potential deadlock by allowing callback fn cloneable and using tokio::spawn to call it without locking

rainliu avatar Oct 21 '21 05:10 rainliu

It would be nicer for the external interfaces if the signature of functions that specify callbacks didn't require specifying the smart pointer type e.g.

instead of

pub type FnTimeGen = Arc<dyn (Fn() -> Pin<Box<dyn Future<Output = SystemTime> + Send + 'static>>) + Send + Sync>;

fn set_callback(&self, fn: FnTimeGen) 

use

fn set_callback<F>(&self, fn: F)
where F: (Fn() -> Pin<Box<dyn Future<Output = SystemTime> + Send + 'static>>) + Send + Sync

This way it's simpler for the caller and a change like this doesn't change the public interface.

k0nserv avatar Nov 01 '21 15:11 k0nserv

I think one further step from what @k0nserv suggests would be to have an interface like so:

trait TimeGen {
type Future: Future<Output = SystemTime> + Unpin; // other bounds may be necessary

fn call() -> Self::Future;

I think that such a trait is object safe, and can be stored in the same way it is done now.

There are 3 major advantages to this:

  • No need to box the future
  • Easier to pass along state, in tidier ways (boxed closure returning a boxed future is rather unergonomic)
  • We can still implement the trait for Fn, so changes to existing codebases would be minor.

MarinPostma avatar Nov 27 '21 17:11 MarinPostma

I would also appreciate a more ergonomic API.

Pascualex avatar Dec 16 '21 22:12 Pascualex

Yes, I'm having some major trouble calling async functions from inside the Boxed closure... I either get 'static lifetime issues, or cycle detected issues.

jeremy-prater avatar Apr 26 '22 03:04 jeremy-prater

@llacqie is working on an attempt to improve this in several PRs:

  • #293
  • https://github.com/webrtc-rs/webrtc/pull/296

See this branch for the full code so far

k0nserv avatar Sep 20 '22 08:09 k0nserv