Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

chore: fix gRPC multiplex example #2825

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 6 additions & 5 deletions examples/rest-grpc-multiplex/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -5,16 +5,17 @@ edition = "2021"
publish = false

[dependencies]
axum = { path = "../../axum" }
# needs to match tonic
axum = { version = "0.7.5" }
Comment on lines +8 to +9
Copy link
Member

@jplatte jplatte Sep 28, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I wouldn't want examples within this repo to pull in a crates.io release of axum. I'm considering moving examples to a separate repo anyways though, see #2942 for discussion.

futures = "0.3"
hyper = { version = "1.0.0", features = ["full"] }
prost = "0.11"
prost = "0.13.1"
tokio = { version = "1", features = ["full"] }
tonic = { version = "0.9" }
tonic-reflection = "0.9"
tonic = "0.12"
tonic-reflection = "0.12"
tower = { version = "0.4", features = ["full"] }
tracing = "0.1"
tracing-subscriber = { version = "0.3", features = ["env-filter"] }

[build-dependencies]
tonic-build = { version = "0.9", features = ["prost"] }
tonic-build = { version = "0.12", features = ["prost"] }
140 changes: 73 additions & 67 deletions examples/rest-grpc-multiplex/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,84 +4,90 @@
//! cargo run -p example-rest-grpc-multiplex
//! ```

// TODO
fn main() {
eprint!("this example has not yet been updated to hyper 1.0");
}
use axum::{extract::Request, http::header::CONTENT_TYPE, routing::get, Router};
use proto::{
greeter_server::{Greeter, GreeterServer},
HelloReply, HelloRequest,
};
use std::net::SocketAddr;
use tonic::{Request as TonicRequest, Response as TonicResponse, Status};
use tower::{steer::Steer, make::Shared};
use tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt};

// use self::multiplex_service::MultiplexService;
// use axum::{routing::get, Router};
// use proto::{
// greeter_server::{Greeter, GreeterServer},
// HelloReply, HelloRequest,
// };
// use std::net::SocketAddr;
// use tonic::{Response as TonicResponse, Status};
// use tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt};
mod proto {
tonic::include_proto!("helloworld");

// mod multiplex_service;
pub(crate) const FILE_DESCRIPTOR_SET: &[u8] =
tonic::include_file_descriptor_set!("helloworld_descriptor");
}

// mod proto {
// tonic::include_proto!("helloworld");
#[derive(Default)]
struct GrpcServiceImpl {}

// pub(crate) const FILE_DESCRIPTOR_SET: &[u8] =
// tonic::include_file_descriptor_set!("helloworld_descriptor");
// }
#[tonic::async_trait]
impl Greeter for GrpcServiceImpl {
async fn say_hello(
&self,
request: TonicRequest<HelloRequest>,
) -> Result<TonicResponse<HelloReply>, Status> {
tracing::info!("Got a gRPC request from {:?}", request.remote_addr());

// #[derive(Default)]
// struct GrpcServiceImpl {}
let reply = HelloReply {
message: format!("Hello {}!", request.into_inner().name),
};

// #[tonic::async_trait]
// impl Greeter for GrpcServiceImpl {
// async fn say_hello(
// &self,
// request: tonic::Request<HelloRequest>,
// ) -> Result<TonicResponse<HelloReply>, Status> {
// tracing::info!("Got a request from {:?}", request.remote_addr());
Ok(TonicResponse::new(reply))
}
}

// let reply = HelloReply {
// message: format!("Hello {}!", request.into_inner().name),
// };
async fn web_root() -> &'static str {
tracing::info!("Got a REST request");

// Ok(TonicResponse::new(reply))
// }
// }
"Hello, World!"
}

// async fn web_root() -> &'static str {
// "Hello, World!"
// }
#[tokio::main]
async fn main() {
// initialize tracing
tracing_subscriber::registry()
.with(
tracing_subscriber::EnvFilter::try_from_default_env()
.unwrap_or_else(|_| "example_rest_grpc_multiplex=debug".into()),
)
.with(tracing_subscriber::fmt::layer())
.init();

// #[tokio::main]
// async fn main() {
// // initialize tracing
// tracing_subscriber::registry()
// .with(
// tracing_subscriber::EnvFilter::try_from_default_env()
// .unwrap_or_else(|_| "example_rest_grpc_multiplex=debug".into()),
// )
// .with(tracing_subscriber::fmt::layer())
// .init();
// build the rest service
let rest = Router::new().route("/", get(web_root));

// // build the rest service
// let rest = Router::new().route("/", get(web_root));
// build the grpc service
let reflection_service = tonic_reflection::server::Builder::configure()
.register_encoded_file_descriptor_set(proto::FILE_DESCRIPTOR_SET)
.build()
.unwrap();

// // build the grpc service
// let reflection_service = tonic_reflection::server::Builder::configure()
// .register_encoded_file_descriptor_set(proto::FILE_DESCRIPTOR_SET)
// .build()
// .unwrap();
// let grpc = tonic::transport::Server::builder()
// .add_service(reflection_service)
// .add_service(GreeterServer::new(GrpcServiceImpl::default()))
// .into_service();
let grpc = tonic::transport::Server::builder()
.add_service(reflection_service)
.add_service(GreeterServer::new(GrpcServiceImpl::default()))
.into_router();
Comment on lines +69 to +72
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If I'm reading the docs correctly, I think you want something like:

Suggested change
let grpc = tonic::transport::Server::builder()
.add_service(reflection_service)
.add_service(GreeterServer::new(GrpcServiceImpl::default()))
.into_router();
let grpc = Routes::default()
.add_service(reflection_service)
.add_service(GreeterServer::new(GrpcServiceImpl::default()))
.into_axum_router();

which would avoid the deprecated into_router function. It was deprecated in 0.12.2 so it's pretty recent!

Thank you for this pr! I found it very helpful ❤️


// // combine them into one service
// let service = MultiplexService::new(rest, grpc);
// combine them into one service
let service = Steer::new(vec![rest, grpc], |req: &Request, _services: &[_]| {
if req
.headers()
.get(CONTENT_TYPE)
.map(|content_type| content_type.as_bytes())
.filter(|content_type| content_type.starts_with(b"application/grpc"))
.is_some()
Comment on lines +79 to +81
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit, you could do just .and_then(|content_type| content_type.as_bytes().starts_with(b"...").then_some(1)).unwrap_or(0) without an explicit condition instead.

(Although now I see you have just copied this from the deleted file)

{
1
} else {
0
}
});

// let addr = SocketAddr::from(([127, 0, 0, 1], 3000));
// tracing::debug!("listening on {}", addr);
// hyper::Server::bind(&addr)
// .serve(tower::make::Shared::new(service))
// .await
// .unwrap();
// }
let addr = SocketAddr::from(([127, 0, 0, 1], 3000));
let listener = tokio::net::TcpListener::bind(&addr).await.unwrap();
tracing::debug!("listening on {}", addr);
axum::serve(listener, Shared::new(service)).await.unwrap();
}
118 changes: 0 additions & 118 deletions examples/rest-grpc-multiplex/src/multiplex_service.rs

This file was deleted.