Skip to content
This repository has been archived by the owner on Feb 4, 2022. It is now read-only.

Remove Sync bounds #2

Open
malobre opened this issue Jul 10, 2021 · 2 comments
Open

Remove Sync bounds #2

malobre opened this issue Jul 10, 2021 · 2 comments

Comments

@malobre
Copy link

malobre commented Jul 10, 2021

Currently all route handlers needs to be Send, Sync and 'static, the default hyper Executor only requires Send and 'static bounds (see this line).

The Sync bound is currently needed because RouterService holds an Arc<Router> which only implements Send if the underlying type is both Send AND Sync.

A workaround would be to wrap the router in a Mutex: Arc<Mutex<Router>>. Since Mutex implements Send and Sync for all types that are Send this should removes the need for all Sync bounds.

However this would prevent the user from wrapping a Router in an Arc themself:

// `router` won't be `Send` because of `Arc` `Sync` requirements
let router = Arc::new(Router::default());

let make_svc = make_service_fn(move |_| {
     let router = router.clone();
     async move {
         Ok::<_, Infallible>(service_fn(move |req: Request<Body>| {
             let router = router.clone();
             async move { router.serve(req).await }
         }))
     }
 });

 let server = Server::bind(&([127, 0, 0, 1], 3000).into())
     .serve(make_svc)
     .await;

An alternative would be to wrap all the inner fields of Router in a struct, wrapped in a Mutex:

struct Router {
    inner: Mutex<RouterInner>
}

struct RouterInner {
    /* -- snip --*/
}

There may be other solutions, but I'm not aware of them ATM.

@ibraheemdev
Copy link
Owner

Wrapping the router in a mutex would mean requiring mutual exclusion during the creation of a response future, which is not something I want to do. Is there a reason the Sync bound is a problem?

@malobre
Copy link
Author

malobre commented Jul 11, 2021

In my experience, future are often !Sync.
I use futures::future::BoxFuture quite a lot and it isn't Sync, the same goes for https://github.com/dtolnay/async-trait which expands to !Sync futures.

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants