tower icon indicating copy to clipboard operation
tower copied to clipboard

Question about BoxService

Open mattklein123 opened this issue 4 years ago • 31 comments

Hi,

I have a quick question about BoxService. I notice that it is Send but not Sync.

Is there any particular reason that it would be a bad idea to make a version of BoxService that is Send and Sync? The real service stack that I am working with is Send and Sync and a type erased version of that that is also Send and Sync would be useful.

I'm mostly just trying to understand if that is a bad idea and I should avoid it.

Thank you!

mattklein123 avatar May 27 '22 20:05 mattklein123

Hey @mattklein123 :wave:

It's not a bad idea.

Note that Buffer erases (most of) the inner service type; so we'll sometimes use that with an inner layer that boxes the future to make an erased/cloneable service when the inner service isn't already cloneable.

But it's probably reasonable to have a BoxSyncService or something

olix0r avatar May 27 '22 21:05 olix0r

Note that Buffer erases (most of) the inner service type; so we'll sometimes use that with an inner layer that boxes the future to make an erased/cloneable service when the inner service isn't already cloneable.

Thanks yeah I saw this, though I didn't want to pay for the extra serialization/buffering when I don't really need it.

But it's probably reasonable to have a BoxSyncService or something

OK sounds good I can try to do a PR at some point.

mattklein123 avatar May 27 '22 21:05 mattklein123

I might be wrong but I assumed that it wasn't Sync because you need a &mut self to do anything with it since poll_ready and call take &mut self. So being able to have &self on multiple threads/tasks isn't useful.

davidpdrsn avatar May 27 '22 21:05 davidpdrsn

I might be wrong but I assumed that it wasn't Sync because you need a &mut self to do anything with it since poll_ready and call take &mut self. So being able to have &self on multiple threads/tasks isn't usefu

I very well might be doing something wrong, but in my case it would be useful, because I can do a cheap clone() before ready/call. My case is that I'm sharing a service across all incoming requests to make upstream/egress calls. So essentially I'm storing it in an Arc that itself is required to be Sync for other reasons. So with BoxService I would need to hold it in a mutex just so I can clone(). If we had BoxCloneSyncService or whatever that would handle this case.

mattklein123 avatar May 27 '22 21:05 mattklein123

But you cannot get a mutable reference from an Arc 🤔

davidpdrsn avatar May 27 '22 21:05 davidpdrsn

But you cannot get a mutable reference from an Arc

I don't need a mutable reference. I clone() before ready/call. My (very limited) understanding is this is an acceptable pattern as with the stack I'm using clones are designed to be cheap.

mattklein123 avatar May 27 '22 21:05 mattklein123

Are you able to share some code to illustrate what you mean? Just to make things more clear.

davidpdrsn avatar May 27 '22 21:05 davidpdrsn

async fn do_call(&self, request: Request<Body>) -> Result<Response<Body>, BoxError> {
  // The following service stack should be cheap to clone, with state shared across clones.
  self.service.clone().ready().await?.call(request).await
}

service is loosely something like:

service: ServiceBuilder::new()
        .load_shed()
        .concurrency_limit(...)
        .timeout(...)
        .service(hyper::Client::new()),

This service is Send and Sync, which makes the pattern of holding it in an Arc and using &self with a clone to make the call work fine.

However, putting the above in a BoxCloneService erases Sync which makes it not work anymore.

mattklein123 avatar May 27 '22 21:05 mattklein123

It sounds like you're attempting to use Arc<BoxSyncService<Request<Body>, Response<Body>, BoxError>> where BoxSyncService is just like BoxService except its Send + Sync. That doesn't work:

#[tokio::main]
async fn main() {
    let service = ServiceBuilder::new()
        .load_shed()
        .concurrency_limit(10)
        .timeout(Duration::from_secs(10))
        .service(Client::new());

    let service = BoxSyncService::new(service);
    // ensure the service actually is `Send + Sync`
    let service = assert_send_sync(service);
    let service = Arc::new(service);

    let _ = do_call(service, Request::new(Body::empty())).await;
}

fn assert_send_sync<T: Send + Sync>(t: T) -> T { t }

async fn do_call(
    service: Arc<BoxSyncService<Request<Body>, Response<Body>, BoxError>>,
    request: Request<Body>,
) -> Result<Response<Body>, BoxError> {
    service.clone().ready().await?.call(request).await
}

// all this is just like `BoxService` but with `Send + Sync` instead of just `Send`

pub struct BoxSyncService<T, U, E> {
    inner: Box<dyn Service<T, Response = U, Error = E, Future = BoxFuture<U, E>> + Send + Sync>,
}

type BoxFuture<T, E> = Pin<Box<dyn Future<Output = Result<T, E>> + Send>>;

impl<T, U, E> BoxSyncService<T, U, E> {
    pub fn new<S>(inner: S) -> Self
    where
        S: Service<T, Response = U, Error = E> + Send + Sync + 'static,
        S::Future: Send + 'static,
    {
        let inner = Box::new(inner.map_future(|f: S::Future| Box::pin(f) as _));
        BoxSyncService { inner }
    }
}

impl<T, U, E> Service<T> for BoxSyncService<T, U, E> {
    type Response = U;
    type Error = E;
    type Future = BoxFuture<U, E>;

    fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), E>> {
        self.inner.poll_ready(cx)
    }

    fn call(&mut self, request: T) -> BoxFuture<U, E> {
        self.inner.call(request)
    }
}

That fails with:

    Checking example v0.1.0
error[E0596]: cannot borrow data in an `Arc` as mutable
  --> src/main.rs:46:5
   |
46 |     service.clone().ready().await?.call(request).await
   |     ^^^^^^^^^^^^^^^^^^^^^^^ cannot borrow as mutable
   |
   = help: trait `DerefMut` is required to modify through a dereference, but it is not implemented
   for `Arc<BoxCloneService<Request<Body>, Response<Body>, Box<dyn StdError + Send + Sync>>>`

davidpdrsn avatar May 27 '22 21:05 davidpdrsn

Maybe BoxCloneService is what you're looking for? That is a boxed + cloneable service.

davidpdrsn avatar May 27 '22 21:05 davidpdrsn

Maybe BoxCloneService is what you're looking for? That is a boxed + cloneable service.

It's not sync. I need BoxSyncCloneService. That will work.

mattklein123 avatar May 27 '22 21:05 mattklein123

I get the feeling we're talking past each other. BoxSyncCloneService doesn't make a difference:

#[tokio::main]
async fn main() {
    let service = ServiceBuilder::new()
        .load_shed()
        .concurrency_limit(10)
        .timeout(Duration::from_secs(10))
        .service(Client::new());

    let service = BoxSyncCloneService::new(service);
    // ensure the service actually is `Send + Sync`
    let service = assert_send_sync(service);
    let service = Arc::new(service);

    let _ = do_call(service, Request::new(Body::empty())).await;
}

fn assert_send_sync<T: Send + Sync>(t: T) -> T {
    t
}

async fn do_call(
    service: Arc<BoxSyncCloneService<Request<Body>, Response<Body>, BoxError>>,
    request: Request<Body>,
) -> Result<Response<Body>, BoxError> {
    service.clone().ready().await?.call(request).await
}

pub struct BoxSyncCloneService<T, U, E>(
    Box<
        dyn CloneService<T, Response = U, Error = E, Future = BoxFuture<'static, Result<U, E>>>
            + Send
            + Sync,
    >,
);

impl<T, U, E> BoxSyncCloneService<T, U, E> {
    pub fn new<S>(inner: S) -> Self
    where
        S: Service<T, Response = U, Error = E> + Clone + Send + Sync + 'static,
        S::Future: Send + 'static,
    {
        let inner = inner.map_future(|f| Box::pin(f) as _);
        BoxSyncCloneService(Box::new(inner))
    }
}

impl<T, U, E> Service<T> for BoxSyncCloneService<T, U, E> {
    type Response = U;
    type Error = E;
    type Future = BoxFuture<'static, Result<U, E>>;

    #[inline]
    fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), E>> {
        self.0.poll_ready(cx)
    }

    #[inline]
    fn call(&mut self, request: T) -> Self::Future {
        self.0.call(request)
    }
}

impl<T, U, E> Clone for BoxSyncCloneService<T, U, E> {
    fn clone(&self) -> Self {
        Self(self.0.clone_box())
    }
}

trait CloneService<R>: Service<R> {
    fn clone_box(
        &self,
    ) -> Box<
        dyn CloneService<R, Response = Self::Response, Error = Self::Error, Future = Self::Future>
            + Send
            + Sync,
    >;
}

impl<R, T> CloneService<R> for T
where
    T: Service<R> + Send + Sync + Clone + 'static,
{
    fn clone_box(
        &self,
    ) -> Box<
        dyn CloneService<R, Response = T::Response, Error = T::Error, Future = T::Future>
            + Send
            + Sync,
    > {
        Box::new(self.clone())
    }
}

That fails with the same error:

error[E0596]: cannot borrow data in an `Arc` as mutable
  --> src/main.rs:57:5
   |
57 |     service.clone().ready().await?.call(request).await
   |     ^^^^^^^^^^^^^^^^^^^^^^^ cannot borrow as mutable
   |
   = help: trait `DerefMut` is required to modify through a dereference, but it is not implemented
   for `Arc<BoxSyncCloneService<Request<Body>, Response<Body>, Box<dyn StdError + Sync +
       std::marker::Send>>>`

Because you cannot get a &mut T from an Arc<T>.

davidpdrsn avatar May 27 '22 22:05 davidpdrsn

I'm out of my depth here, but your example is not quite what I'm doing. I'm doing something more like this:

struct ServiceHolder {
  service: ServiceStack
}

impl ServiceHolder {
  async fn do_call(&self, ...) -> ... {
    self.service.clone().ready().await?.call(request).await
  }
}

fn some_other_function() {
  let state = Arc::new(ServiceHolder{...});
  state.do_call(...).await;
}

This works just fine in my code, as I expect it would given that clone takes &self. It seems like there should be some way of making a type erased version of service also work.

mattklein123 avatar May 27 '22 22:05 mattklein123

Sorry I think I see the problem in your code, you are cloning the arc, not the service. Try service.as_ref().clone()

mattklein123 avatar May 27 '22 22:05 mattklein123

Yes thats right 😊 I got the impression thats what you were doing but you're right that Arc<BoxCloneService<Request<Body>, Response<Body>, BoxError>> is !Send because BoxCloneService is !Sync. Is that the issue you're seeing?

I would probably just go with BoxCloneService without the Arc, as that is Send. You have to clone the inner service anyway to actually be able to call it so what is the Arc for?

I also wouldn't worry about service stacks being expensive to Clone. hyper::Client is basically a shared cloneable connection pool so thats cheap, same goes for load shed, timeout, and concurrency limit. If you need to share a !Clone service you can use Buffer like Oliver mentioned.

davidpdrsn avatar May 27 '22 22:05 davidpdrsn

Is that the issue you're seeing?

No the issue is that it isn't Sync.

I would probably just go with BoxCloneService without the Arc, as that is Send. You have to clone the inner service anyway to actually be able to call it so what is the Arc for?

The issue boils down to the fact that Tonic is generating code like this:

#[async_trait]
pub trait FooService: Send + Sync + 'static {
  ...

I haven't dug into exactly why Tonic requires Sync, but I assume it's because the service instance is shared between all incoming calls. Thus, anything I store in my service instance needs to be Sync, or I have to wrap it in a Mutex, etc. to force the issue.

So, at the root of all of this is a requirement for Sync, and from that comes various usage of Arc (service wide state, per stream state that can be safely passed to a spawn, etc.).

So essentially, AFAICT, I can't use either BoxService or BoxCloneService anywhere in this tree without forcing it into a Mutex which seems very odd to me. And like I said, the fully typed service stack works fine.

Hopefully this explains why having a BoxCloneSyncService would be useful.

As I said before, I'm still learning, so I could very well be doing something wrong. Please correct me if so.

mattklein123 avatar May 28 '22 03:05 mattklein123

Ah so this is because of tonic, why didn't you say that?

I'm not sure why tonic has that requirement but I believe you can use sync-wrapper to work around it.

I think we should try removing the Sync requirement from tonic before adding anything to tower. I believe tonic applies Buffer to the server so it isn't shared 🤔

davidpdrsn avatar May 28 '22 08:05 davidpdrsn

Ah so this is because of tonic, why didn't you say that?

Because I felt it was an implementation detail of my original query, which is that I need a type erased service that is sync, and not relevant. Sorry if I didn't provide enough info!

I'm not sure why tonic has that requirement but I believe you can use sync-wrapper to work around it.

I don't think so. This requires a &mut self reference which I don't have.

I think we should try removing the Sync requirement from tonic before adding anything to tower.

That would be one solution, though that's not a yak I'm going to shave personally, as I don't think it makes much of a difference in the end. It just moves the clone from one place to another. Concretely the issue is Tonic generates code like this:

fn call(
  &mut self,
  request: tonic::Request<
      tonic::Streaming<super::FooApiRequest>,
  >,
  ) -> Self::Future {
  let inner = self.0.clone();
  let fut = async move { (*inner).mux(request).await };
  Box::pin(fut)
  }

My actual service instance is an Arc (self.0), it is cloned, and then passed as &self to my handler. This is why it has to be Sync. As I said above, you could potentially make the service implement Clone, but I think that's just moving the same issue from one place to another.

I believe tonic applies Buffer to the server so it isn't shared thinking

I haven't inspected all of the code, but I would be very surprised if it worked this way, as it would introduce needless serialization into the request flow. Also, in my case, I'm calling my gRPC handler via an axum any_service handler, so I'm pretty certain there is no buffering layer in place.

Anyhow, I will go ahead and close this issue as I think I have a pretty good understanding of all of this at this point and I can just make my own private version of BoxCloneSyncService. Thanks for the discussion!

mattklein123 avatar May 29 '22 02:05 mattklein123

I ran into the same problem.

It is sometimes useful to hold boxed service in a struct so it can abstract the actual type. Let's see if we can use BoxCloneService.

struct S {
  svc: BoxCloneService<...>
}
impl S {
  async fn run(&self, ...);

This code isn't compiled because BoxCloneService is !Sync.

I might be wrong but I assumed that it wasn't Sync because you need a &mut self to do anything with it since poll_ready and call take &mut self. So being able to have &self on multiple threads/tasks isn't useful.

Are you saying the run function should take self to take a &mut to the member svc?

I think ideally, run should take &self and then the svc is cloned to take a &mut to call the Services functions.

akiradeveloper avatar Aug 11 '22 12:08 akiradeveloper

You do this instead:

impl S {
    fn run(&self) -> impl Future {
        let mut svc = self.svc.clone();
        async move {
            svc.call(()).await;
        }
    }
}

This only moves the owned BoxCloneService into the future and not &self.

davidpdrsn avatar Aug 11 '22 12:08 davidpdrsn