Tonic client wrapping

Hi, Im new to Rust. Im currently implementing grpc stuffs. For this Im using tonic. I read that the implementation require &mut self to refer to the Channel structure inside.

Is it correct/proper/best practice to wrap the grpc client inside Arc<Mutex<T>> here?, For Mutex I use futures::lock::Mutex to allow it run asynchronously. I put this inside a Struct to allow it to be shared across code.

pub struct MyClient {
    client: Arc<Mutex<GrpcClient<Channel>>>
}

impl MyClient {
    pub async fn send(request) {
        ...
        self.client.lock().await.grpc_method(request).await;
        ...
    }
}

Others told that to just clone the grpc client object like this:

pub struct MyClient {
    client: Arc<Mutex<GrpcClient<Channel>>>
}

impl MyClient {
    pub async fn send(request) {
        ...
        let mut client = self.client.clone();
        client.grpc_method(request).await;
        ...
    }
}

Both ways actually compiled. I just want to know which is the proper way(best practice).

Please advise, thanks!

I don't understand this sentence, please reformulate it. In general I don't understand based on your post what the problem is. Does your code not compile? Does it not work? Does it have performance issues?

The traits generated by tonic take &self to make it possible to handle multiple requests in parallel. By using a mutex, you get &mut self access, but it will no longer handle them in parallel.

1 Like

Hi, I've edited the question.

Hi, I've edited the question to be more detail.

So you think second way is better?, I read about the way tonic handle sending request through channel is by sending them one-by-one. This is one of the way to avoid back pressure thing. I'm thinking the channel is some kind of globally shared thing that must be locked for each request.

Well, if you want to clone it, then you don't need the Arc/Mutex. Whether cloning is a good solution depends on the contents of the struct. If you make changes to the cloned struct, then those changes are not visible in the original struct.

1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.