selmeci / dgraph-tonic

Async/Sync gRPC client for Dgraph DB
MIT License
83 stars 8 forks source link

Help Wanted: Concurrent use of Client #26

Closed MateusAmin closed 3 years ago

MateusAmin commented 4 years ago

Is there a recommended way to concurrently and/or in-parallel use the client? I am using it from within a tonic server implementation in some of the receiving methods.

I saw the recommendation to clone it here: https://github.com/hyperium/tonic/issues/285, But the dgraph-tonic client does not have clone. I suppose I could wrap it in a an arc. With the clone I thought the best way to do it would be roughly something like this:

pub async fn connect_client() -> (mpsc::Sender<DbCom>, JoinHandle<()>) {
    let client = arc::new(Client::new(vec!["http://localhost:9080"]).expect("Dgraph  client"));
    let (mut tx, mut rx) = mpsc::channel(32);

    let loop_handle = tokio::spawn(async move {
        while let Some(cmd) = rx.recv().await {
            match cmd {
                Command::asd {tx} => {
                    let client = client.clone();
                    tokio::spawn(async move {
                        tx.send(asd(client).await);
                    });
                }
            }
        }
    });

    (tx , loop_handle)
}

pub struct GrpcServer {
    pub db_tx: mpsc::Sender<db::DbCom>,
}

#[tonic::async_trait]
impl Service for GrpcServer {

    async fn asd(
        &self,
        request: Request<asd>,
    ) -> Result<Response<asd>, Status> {
        let (tx, rx) = mpsc::channel(100);
        db_tx.send(Command::asd{tx: tx});

        Ok(Response::new(asd {uid: rx.recv(uid).await}))
    }
 }

main {
    let (db_rx, db_f_loop) = db::connect_client();
    let tonic_signal_server = Server::builder()
        .add_service(ServiceServer::new(GrpcServer {
            db_rx: db_rx
        }))
        .serve(addr);

    tokio::join!(
        tonic_signal_server,
        db_f_loop)
} 
MateusAmin commented 4 years ago

Well, since it is sync/send and methods are immutable references unlike the underlying tonic client I suppose I should be fine using it directly.