Closed8
Rust (tonic) で gRPC サーバーを立ててみる
を参考に
できたもの
新規の Rust プロジェクトを作成
$ cargo new javasparrow-tonic-grpc-server
$ cd javasparrow-tonic-grpc-server
protocol buffers の定義ファイルを作成(後で BFF からも参照できるように submodule として切り出しておく)
$ mkdir javasparrow-proto
$ touch javasparrow-proto/javasparrow-api.proto
中身
javasparrow-api.proto
syntax = "proto3";
package javasparrow;
service JavasparrowApi {
rpc Piyo (PiyoRequest) returns (PiyoResponse);
}
message PiyoRequest {
string name = 1;
}
message PiyoResponse {
string message = 1;
}
ここまで出来たら GitHub へ push しておく
Cargo.toml に依存関係を記載
Cargo.toml
[package]
name = "javasparrow-tonic-grpc-server"
version = "0.1.0"
edition = "2018"
[dependencies]
tonic = "0.4"
prost = "0.7"
tokio = { version = "1.0", features = ["macros", "rt-multi-thread"] }
[build-dependencies]
tonic-build = "0.4"
レポジトリのルートに proto ファイルからサーバー用コードを自動生成する build.rs
を追加する
build.rs
fn main() -> Result<(), Box<dyn std::error::Error>> {
tonic_build::compile_protos("proto/javasparrow-api.proto")?;
Ok(())
}
tonic では純正の protoc コマンドではなく tonic-build というツールを使ってコード生成を行っている。(更に中身は prost という crate を介しているみたい)
自動生成されたコード( cargo build すると target
配下に Rust のコードが自動生成される)
javasparrow.rs
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct PiyoRequest {
#[prost(string, tag = "1")]
pub name: ::prost::alloc::string::String,
}
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct PiyoResponse {
#[prost(string, tag = "1")]
pub message: ::prost::alloc::string::String,
}
#[doc = r" Generated client implementations."]
pub mod javasparrow_api_client {
#![allow(unused_variables, dead_code, missing_docs)]
use tonic::codegen::*;
pub struct JavasparrowApiClient<T> {
inner: tonic::client::Grpc<T>,
}
impl JavasparrowApiClient<tonic::transport::Channel> {
#[doc = r" Attempt to create a new client by connecting to a given endpoint."]
pub async fn connect<D>(dst: D) -> Result<Self, tonic::transport::Error>
where
D: std::convert::TryInto<tonic::transport::Endpoint>,
D::Error: Into<StdError>,
{
let conn = tonic::transport::Endpoint::new(dst)?.connect().await?;
Ok(Self::new(conn))
}
}
impl<T> JavasparrowApiClient<T>
where
T: tonic::client::GrpcService<tonic::body::BoxBody>,
T::ResponseBody: Body + HttpBody + Send + 'static,
T::Error: Into<StdError>,
<T::ResponseBody as HttpBody>::Error: Into<StdError> + Send,
{
pub fn new(inner: T) -> Self {
let inner = tonic::client::Grpc::new(inner);
Self { inner }
}
pub fn with_interceptor(inner: T, interceptor: impl Into<tonic::Interceptor>) -> Self {
let inner = tonic::client::Grpc::with_interceptor(inner, interceptor);
Self { inner }
}
pub async fn piyo(
&mut self,
request: impl tonic::IntoRequest<super::PiyoRequest>,
) -> Result<tonic::Response<super::PiyoResponse>, tonic::Status> {
self.inner.ready().await.map_err(|e| {
tonic::Status::new(
tonic::Code::Unknown,
format!("Service was not ready: {}", e.into()),
)
})?;
let codec = tonic::codec::ProstCodec::default();
let path = http::uri::PathAndQuery::from_static("/javasparrow.JavasparrowApi/Piyo");
self.inner.unary(request.into_request(), path, codec).await
}
}
impl<T: Clone> Clone for JavasparrowApiClient<T> {
fn clone(&self) -> Self {
Self {
inner: self.inner.clone(),
}
}
}
impl<T> std::fmt::Debug for JavasparrowApiClient<T> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "JavasparrowApiClient {{ ... }}")
}
}
}
#[doc = r" Generated server implementations."]
pub mod javasparrow_api_server {
#![allow(unused_variables, dead_code, missing_docs)]
use tonic::codegen::*;
#[doc = "Generated trait containing gRPC methods that should be implemented for use with JavasparrowApiServer."]
#[async_trait]
pub trait JavasparrowApi: Send + Sync + 'static {
async fn piyo(
&self,
request: tonic::Request<super::PiyoRequest>,
) -> Result<tonic::Response<super::PiyoResponse>, tonic::Status>;
}
#[derive(Debug)]
pub struct JavasparrowApiServer<T: JavasparrowApi> {
inner: _Inner<T>,
}
struct _Inner<T>(Arc<T>, Option<tonic::Interceptor>);
impl<T: JavasparrowApi> JavasparrowApiServer<T> {
pub fn new(inner: T) -> Self {
let inner = Arc::new(inner);
let inner = _Inner(inner, None);
Self { inner }
}
pub fn with_interceptor(inner: T, interceptor: impl Into<tonic::Interceptor>) -> Self {
let inner = Arc::new(inner);
let inner = _Inner(inner, Some(interceptor.into()));
Self { inner }
}
}
impl<T, B> Service<http::Request<B>> for JavasparrowApiServer<T>
where
T: JavasparrowApi,
B: HttpBody + Send + Sync + 'static,
B::Error: Into<StdError> + Send + 'static,
{
type Response = http::Response<tonic::body::BoxBody>;
type Error = Never;
type Future = BoxFuture<Self::Response, Self::Error>;
fn poll_ready(&mut self, _cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
Poll::Ready(Ok(()))
}
fn call(&mut self, req: http::Request<B>) -> Self::Future {
let inner = self.inner.clone();
match req.uri().path() {
"/javasparrow.JavasparrowApi/Piyo" => {
#[allow(non_camel_case_types)]
struct PiyoSvc<T: JavasparrowApi>(pub Arc<T>);
impl<T: JavasparrowApi> tonic::server::UnaryService<super::PiyoRequest> for PiyoSvc<T> {
type Response = super::PiyoResponse;
type Future = BoxFuture<tonic::Response<Self::Response>, tonic::Status>;
fn call(
&mut self,
request: tonic::Request<super::PiyoRequest>,
) -> Self::Future {
let inner = self.0.clone();
let fut = async move { (*inner).piyo(request).await };
Box::pin(fut)
}
}
let inner = self.inner.clone();
let fut = async move {
let interceptor = inner.1.clone();
let inner = inner.0;
let method = PiyoSvc(inner);
let codec = tonic::codec::ProstCodec::default();
let mut grpc = if let Some(interceptor) = interceptor {
tonic::server::Grpc::with_interceptor(codec, interceptor)
} else {
tonic::server::Grpc::new(codec)
};
let res = grpc.unary(method, req).await;
Ok(res)
};
Box::pin(fut)
}
_ => Box::pin(async move {
Ok(http::Response::builder()
.status(200)
.header("grpc-status", "12")
.header("content-type", "application/grpc")
.body(tonic::body::BoxBody::empty())
.unwrap())
}),
}
}
}
impl<T: JavasparrowApi> Clone for JavasparrowApiServer<T> {
fn clone(&self) -> Self {
let inner = self.inner.clone();
Self { inner }
}
}
impl<T: JavasparrowApi> Clone for _Inner<T> {
fn clone(&self) -> Self {
Self(self.0.clone(), self.1.clone())
}
}
impl<T: std::fmt::Debug> std::fmt::Debug for _Inner<T> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{:?}", self.0)
}
}
impl<T: JavasparrowApi> tonic::transport::NamedService for JavasparrowApiServer<T> {
const NAME: &'static str = "javasparrow.JavasparrowApi";
}
}
サーバーの実装
src/main.rs
use tonic::{transport::Server, Request, Response, Status};
use javasparrow::javasparrow_api_server::{JavasparrowApi, JavasparrowApiServer};
use javasparrow::{PiyoRequest, PiyoResponse};
pub mod javasparrow {
// proto で定義した package 名を指定すると、自動生成した
// server, client のコードをインポートしてくれる
tonic::include_proto!("javasparrow");
}
#[derive(Debug, Default)]
pub struct MyJavasparrowApi {}
#[tonic::async_trait]
impl JavasparrowApi for MyJavasparrowApi {
async fn piyo(&self, request: Request<PiyoRequest>) -> Result<Response<PiyoResponse>, Status> {
println!("Got a request: {:?}", request);
let response = javasparrow::PiyoResponse {
message: format!("PiyoPiyo {}!", request.into_inner().name).into(),
};
Ok(Response::new(response))
}
}
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let addr = "[::1]:50051".parse()?;
let javasparrow = MyJavasparrowApi::default();
Server::builder()
.add_service(JavasparrowApiServer::new(javasparrow))
.serve(addr)
.await?;
Ok(())
}
このスクラップは2021/06/11にクローズされました