Skip to main content Link Menu Expand (external link) Document Search Copy Copied

RPC implementation

Now that you have specified the data types needed for the Echo RPC, you will be implementing its actual functionality.

To give you an idea of how RPC implementations look, an implementation for the Example RPC has been provided to you in src/server.rs.

pub struct KvStore {}

#[tonic::async_trait]
impl kv_store_server::KvStore for KvStore {
  async fn example(
      &self,
      req: Request<ExampleRequest>,
  ) -> Result<Response<ExampleReply>, Status> {
      log::info!("Received example request.");
      Ok(Response::new(ExampleReply {
          output: req.into_inner().input + 1,
      }))
  }
}

As a brief rundown of what the code is doing, we first define a struct KvStore that will store the state of our server. The trait kv_store_server::KvStore is defined in src/rpc/kv_store.rs, which is autogenerated from proto/kv_store.proto, and essentially enforces that our KvStore server implements the API we specified with our protocol buffers.

Finally, the actual implementation of the Example RPC is kept within the example function. The function takes in a Request<ExampleRequest> and returns a Result<Response<ExampleReply>, Status>. It first retrieves and takes ownership of the ExampleRequest struct by calling req.into_inner(), then retrieves the input integer. It then creates an ExampleReply with output set to input + 1 and wraps the struct with a tonic::Response and an Ok result.

You should not modify src/rpc/kv_store.rs, since it is autogenerated every time you run cargo build. You can look at the code in that file if you are curious, but don’t spend too much time reading it. It is full of serialization and deserialization code, has little documentation, and is not important to understand.

Once you’ve added the Echo RPC to the .proto file, running cargo build should give you an error, telling you that you have not implemented the Echo RPC you just defined.

Now implement the Echo RPC so that it echoes the received message string back to the client. You will first need to recover the message string from your RPC request in a similar manner as the Example RPC, then pass the message string back into the reply. Before moving on, make sure that your code is now compiling with cargo check.