-
Notifications
You must be signed in to change notification settings - Fork 1k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Adds `tonic::Extensions` which is a newtype around `http::Extensions`. Extensions can be set by interceptors with `Request::extensions_mut` and retrieved from RPCs with `Request::extensions`. Extensions can also be set in tower middleware and will be carried through to the RPC. Fixes #255
- Loading branch information
1 parent
f33316d
commit b937f78
Showing
6 changed files
with
296 additions
and
6 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,150 @@ | ||
use futures_util::FutureExt; | ||
use hyper::{Body, Request as HyperRequest, Response as HyperResponse}; | ||
use integration_tests::pb::{test_client, test_server, Input, Output}; | ||
use std::{ | ||
task::{Context, Poll}, | ||
time::Duration, | ||
}; | ||
use tokio::sync::oneshot; | ||
use tonic::{ | ||
body::BoxBody, | ||
transport::{Endpoint, NamedService, Server}, | ||
Request, Response, Status, | ||
}; | ||
use tower_service::Service; | ||
|
||
struct ExtensionValue(i32); | ||
|
||
#[tokio::test] | ||
async fn setting_extension_from_interceptor() { | ||
struct Svc; | ||
|
||
#[tonic::async_trait] | ||
impl test_server::Test for Svc { | ||
async fn unary_call(&self, req: Request<Input>) -> Result<Response<Output>, Status> { | ||
let value = req.extensions().get::<ExtensionValue>().unwrap(); | ||
assert_eq!(value.0, 42); | ||
|
||
Ok(Response::new(Output {})) | ||
} | ||
} | ||
|
||
let svc = test_server::TestServer::with_interceptor(Svc, |mut req: Request<()>| { | ||
req.extensions_mut().insert(ExtensionValue(42)); | ||
Ok(req) | ||
}); | ||
|
||
let (tx, rx) = oneshot::channel::<()>(); | ||
|
||
let jh = tokio::spawn(async move { | ||
Server::builder() | ||
.add_service(svc) | ||
.serve_with_shutdown("127.0.0.1:1323".parse().unwrap(), rx.map(drop)) | ||
.await | ||
.unwrap(); | ||
}); | ||
|
||
tokio::time::sleep(Duration::from_millis(100)).await; | ||
|
||
let channel = Endpoint::from_static("http://127.0.0.1:1323") | ||
.connect() | ||
.await | ||
.unwrap(); | ||
|
||
let mut client = test_client::TestClient::new(channel); | ||
|
||
match client.unary_call(Input {}).await { | ||
Ok(_) => {} | ||
Err(status) => panic!("{}", status.message()), | ||
} | ||
|
||
tx.send(()).unwrap(); | ||
|
||
jh.await.unwrap(); | ||
} | ||
|
||
#[tokio::test] | ||
async fn setting_extension_from_tower() { | ||
struct Svc; | ||
|
||
#[tonic::async_trait] | ||
impl test_server::Test for Svc { | ||
async fn unary_call(&self, req: Request<Input>) -> Result<Response<Output>, Status> { | ||
let value = req.extensions().get::<ExtensionValue>().unwrap(); | ||
assert_eq!(value.0, 42); | ||
|
||
Ok(Response::new(Output {})) | ||
} | ||
} | ||
|
||
let svc = InterceptedService { | ||
inner: test_server::TestServer::new(Svc), | ||
}; | ||
|
||
let (tx, rx) = oneshot::channel::<()>(); | ||
|
||
let jh = tokio::spawn(async move { | ||
Server::builder() | ||
.add_service(svc) | ||
.serve_with_shutdown("127.0.0.1:1324".parse().unwrap(), rx.map(drop)) | ||
.await | ||
.unwrap(); | ||
}); | ||
|
||
tokio::time::sleep(Duration::from_millis(100)).await; | ||
|
||
let channel = Endpoint::from_static("http://127.0.0.1:1324") | ||
.connect() | ||
.await | ||
.unwrap(); | ||
|
||
let mut client = test_client::TestClient::new(channel); | ||
|
||
match client.unary_call(Input {}).await { | ||
Ok(_) => {} | ||
Err(status) => panic!("{}", status.message()), | ||
} | ||
|
||
tx.send(()).unwrap(); | ||
|
||
jh.await.unwrap(); | ||
} | ||
|
||
#[derive(Debug, Clone)] | ||
struct InterceptedService<S> { | ||
inner: S, | ||
} | ||
|
||
impl<S> Service<HyperRequest<Body>> for InterceptedService<S> | ||
where | ||
S: Service<HyperRequest<Body>, Response = HyperResponse<BoxBody>> | ||
+ NamedService | ||
+ Clone | ||
+ Send | ||
+ 'static, | ||
S::Future: Send + 'static, | ||
{ | ||
type Response = S::Response; | ||
type Error = S::Error; | ||
type Future = futures::future::BoxFuture<'static, Result<Self::Response, Self::Error>>; | ||
|
||
fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> { | ||
self.inner.poll_ready(cx) | ||
} | ||
|
||
fn call(&mut self, mut req: HyperRequest<Body>) -> Self::Future { | ||
let clone = self.inner.clone(); | ||
let mut inner = std::mem::replace(&mut self.inner, clone); | ||
|
||
req.extensions_mut().insert(ExtensionValue(42)); | ||
|
||
Box::pin(async move { | ||
let response = inner.call(req).await?; | ||
Ok(response) | ||
}) | ||
} | ||
} | ||
|
||
impl<S: NamedService> NamedService for InterceptedService<S> { | ||
const NAME: &'static str = S::NAME; | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,67 @@ | ||
use std::fmt; | ||
|
||
/// A type map of protocol extensions. | ||
/// | ||
/// `Extensions` can be used by [`Interceptor`] and [`Request`] to store extra data derived from | ||
/// the underlying protocol. | ||
/// | ||
/// [`Interceptor`]: crate::Interceptor | ||
/// [`Request`]: crate::Request | ||
pub struct Extensions(http::Extensions); | ||
|
||
impl Extensions { | ||
pub(crate) fn new() -> Self { | ||
Self(http::Extensions::new()) | ||
} | ||
|
||
/// Insert a type into this `Extensions`. | ||
/// | ||
/// If a extension of this type already existed, it will | ||
/// be returned. | ||
#[inline] | ||
pub fn insert<T: Send + Sync + 'static>(&mut self, val: T) -> Option<T> { | ||
self.0.insert(val) | ||
} | ||
|
||
/// Get a reference to a type previously inserted on this `Extensions`. | ||
#[inline] | ||
pub fn get<T: Send + Sync + 'static>(&self) -> Option<&T> { | ||
self.0.get() | ||
} | ||
|
||
/// Get a mutable reference to a type previously inserted on this `Extensions`. | ||
#[inline] | ||
pub fn get_mut<T: Send + Sync + 'static>(&mut self) -> Option<&mut T> { | ||
self.0.get_mut() | ||
} | ||
|
||
/// Remove a type from this `Extensions`. | ||
/// | ||
/// If a extension of this type existed, it will be returned. | ||
#[inline] | ||
pub fn remove<T: Send + Sync + 'static>(&mut self) -> Option<T> { | ||
self.0.remove() | ||
} | ||
|
||
/// Clear the `Extensions` of all inserted extensions. | ||
#[inline] | ||
pub fn clear(&mut self) { | ||
self.0.clear() | ||
} | ||
|
||
#[inline] | ||
pub(crate) fn from_http(http: http::Extensions) -> Self { | ||
Self(http) | ||
} | ||
|
||
#[inline] | ||
pub(crate) fn into_http(self) -> http::Extensions { | ||
self.0 | ||
} | ||
} | ||
|
||
impl fmt::Debug for Extensions { | ||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { | ||
f.debug_struct("Extensions").finish() | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters