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

feat(transport): Make tower internal dependency #1947

Merged
merged 3 commits into from
Nov 7, 2024
Merged
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
5 changes: 1 addition & 4 deletions examples/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -51,12 +51,10 @@ path = "src/load_balance/server.rs"
[[bin]]
name = "dynamic-load-balance-client"
path = "src/dynamic_load_balance/client.rs"
required-features = ["dynamic-load-balance"]

[[bin]]
name = "dynamic-load-balance-server"
path = "src/dynamic_load_balance/server.rs"
required-features = ["dynamic-load-balance"]

[[bin]]
name = "tls-client"
Expand Down Expand Up @@ -267,13 +265,12 @@ json-codec = ["dep:serde", "dep:serde_json", "dep:bytes"]
compression = ["tonic/gzip"]
tls = ["tonic/tls"]
tls-rustls = ["dep:http", "dep:hyper", "dep:hyper-util", "dep:hyper-rustls", "dep:tower", "tower-http/util", "tower-http/add-extension", "dep:rustls-pki-types", "dep:tokio-rustls", "dep:pin-project", "dep:http-body-util"]
dynamic-load-balance = ["dep:tower"]
tls-client-auth = ["tonic/tls"]
types = ["dep:tonic-types"]
h2c = ["dep:hyper", "dep:tower", "dep:http", "dep:hyper-util"]
cancellation = ["dep:tokio-util"]

full = ["gcp", "routeguide", "reflection", "autoreload", "health", "grpc-web", "tracing", "uds", "streaming", "mock", "tower", "json-codec", "compression", "tls", "tls-rustls", "dynamic-load-balance", "tls-client-auth", "types", "cancellation", "h2c"]
full = ["gcp", "routeguide", "reflection", "autoreload", "health", "grpc-web", "tracing", "uds", "streaming", "mock", "tower", "json-codec", "compression", "tls", "tls-rustls", "tls-client-auth", "types", "cancellation", "h2c"]
default = ["full"]

[dependencies]
Expand Down
3 changes: 1 addition & 2 deletions examples/src/dynamic_load_balance/client.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,15 +3,14 @@ pub mod pb {
}

use pb::{echo_client::EchoClient, EchoRequest};
use tonic::transport::channel::Change;
use tonic::transport::Channel;

use tonic::transport::Endpoint;

use std::sync::Arc;

use std::sync::atomic::{AtomicBool, Ordering::SeqCst};
use tokio::time::timeout;
use tower::discover::Change;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
Expand Down
1 change: 0 additions & 1 deletion tonic-web/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,6 @@ allowed_external_types = [
# not major released
"futures_core::stream::Stream",
"http_body_util::combinators::box_body::UnsyncBoxBody",
"tower_http::cors::Cors",
"tower_layer::Layer",
"tower_service::Service",
]
42 changes: 34 additions & 8 deletions tonic-web/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -108,7 +108,14 @@ mod layer;
mod service;

use http::header::HeaderName;
use std::time::Duration;
use pin_project::pin_project;
use std::{
fmt,
future::Future,
pin::Pin,
task::{Context, Poll},
time::Duration,
};
use tonic::{body::BoxBody, server::NamedService, Status};
use tower_http::cors::{AllowOrigin, CorsLayer};
use tower_layer::Layer;
Expand Down Expand Up @@ -159,18 +166,37 @@ where
{
type Response = S::Response;
type Error = S::Error;
type Future =
<tower_http::cors::Cors<GrpcWebService<S>> as Service<http::Request<BoxBody>>>::Future;
type Future = CorsGrpcWebResponseFuture<S::Future>;

fn poll_ready(
&mut self,
cx: &mut std::task::Context<'_>,
) -> std::task::Poll<Result<(), Self::Error>> {
fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
self.0.poll_ready(cx)
}

fn call(&mut self, req: http::Request<BoxBody>) -> Self::Future {
self.0.call(req)
CorsGrpcWebResponseFuture(self.0.call(req))
}
}

/// Response Future for the [`CorsGrpcWeb`].
#[pin_project]
pub struct CorsGrpcWebResponseFuture<F>(
#[pin] tower_http::cors::ResponseFuture<service::ResponseFuture<F>>,
);

impl<F, E> Future for CorsGrpcWebResponseFuture<F>
where
F: Future<Output = Result<http::Response<BoxBody>, E>>,
{
type Output = Result<http::Response<BoxBody>, E>;

fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
self.project().0.poll(cx)
}
}

impl<F> fmt::Debug for CorsGrpcWebResponseFuture<F> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_tuple("CorsGrpcWebResponseFuture").finish()
}
}

Expand Down
1 change: 0 additions & 1 deletion tonic/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -137,7 +137,6 @@ allowed_external_types = [
"futures_core::stream::Stream",
"h2::error::Error",
"http_body_util::combinators::box_body::UnsyncBoxBody",
"tower::discover::Change",
"tower_service::Service",
"tower_layer::Layer",
"tower_layer::stack::Stack",
Expand Down
3 changes: 2 additions & 1 deletion tonic/src/transport/channel/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ pub(crate) mod service;
#[cfg(feature = "_tls-any")]
mod tls;

pub use self::service::Change;
pub use endpoint::Endpoint;
#[cfg(feature = "_tls-any")]
pub use tls::ClientTlsConfig;
Expand All @@ -29,7 +30,7 @@ use hyper::rt;
use tower::balance::p2c::Balance;
use tower::{
buffer::{future::ResponseFuture as BufferResponseFuture, Buffer},
discover::{Change, Discover},
discover::Discover,
util::BoxService,
Service,
};
Expand Down
20 changes: 13 additions & 7 deletions tonic/src/transport/channel/service/discover.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,11 +7,17 @@ use std::{
task::{Context, Poll},
};
use tokio::sync::mpsc::Receiver;

use tokio_stream::Stream;
use tower::discover::Change;

type DiscoverResult<K, S, E> = Result<Change<K, S>, E>;
use tower::discover::Change as TowerChange;

/// A change in the service set.
#[derive(Debug, Clone)]
pub enum Change<K, V> {
/// A new service identified by key `K` was identified.
Insert(K, V),
/// The service identified by key `K` disappeared.
Remove(K),
}

pub(crate) struct DynamicServiceStream<K: Hash + Eq + Clone> {
changes: Receiver<Change<K, Endpoint>>,
Expand All @@ -24,7 +30,7 @@ impl<K: Hash + Eq + Clone> DynamicServiceStream<K> {
}

impl<K: Hash + Eq + Clone> Stream for DynamicServiceStream<K> {
type Item = DiscoverResult<K, Connection, crate::BoxError>;
type Item = Result<TowerChange<K, Connection>, crate::BoxError>;

fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
let c = &mut self.changes;
Expand All @@ -39,10 +45,10 @@ impl<K: Hash + Eq + Clone> Stream for DynamicServiceStream<K> {
http.enforce_http(false);

let connection = Connection::lazy(endpoint.connector(http), endpoint);
let change = Ok(Change::Insert(k, connection));
let change = Ok(TowerChange::Insert(k, connection));
Poll::Ready(Some(change))
}
Change::Remove(k) => Poll::Ready(Some(Ok(Change::Remove(k)))),
Change::Remove(k) => Poll::Ready(Some(Ok(TowerChange::Remove(k)))),
},
}
}
Expand Down
1 change: 1 addition & 0 deletions tonic/src/transport/channel/service/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ mod connection;
pub(super) use self::connection::Connection;

mod discover;
pub use self::discover::Change;
pub(super) use self::discover::DynamicServiceStream;

mod io;
Expand Down
6 changes: 1 addition & 5 deletions tonic/src/transport/server/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ use tower::{
layer::util::{Identity, Stack},
layer::Layer,
limit::concurrency::ConcurrencyLimitLayer,
util::{BoxCloneService, Either},
util::BoxCloneService,
Service, ServiceBuilder, ServiceExt,
};

Expand Down Expand Up @@ -138,10 +138,6 @@ pub struct Router<L = Identity> {
routes: Routes,
}

impl<S: NamedService, T> NamedService for Either<S, T> {
const NAME: &'static str = S::NAME;
}

impl Server {
/// Create a new server builder that can configure a [`Server`].
pub fn builder() -> Self {
Expand Down