-
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.
feat(transport): add user-agent header to client requests. (#457)
* Add a default user-agent header to outgoing requests. * The user agent can be configured through the `Channel` builder. fixes #453
- Loading branch information
Showing
6 changed files
with
165 additions
and
2 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,55 @@ | ||
use futures_util::FutureExt; | ||
use integration_tests::pb::{test_client, test_server, Input, Output}; | ||
use std::time::Duration; | ||
use tokio::sync::oneshot; | ||
use tonic::{ | ||
transport::{Endpoint, Server}, | ||
Request, Response, Status, | ||
}; | ||
|
||
#[tokio::test] | ||
async fn writes_user_agent_header() { | ||
struct Svc; | ||
|
||
#[tonic::async_trait] | ||
impl test_server::Test for Svc { | ||
async fn unary_call(&self, req: Request<Input>) -> Result<Response<Output>, Status> { | ||
match req.metadata().get("user-agent") { | ||
Some(_) => Ok(Response::new(Output {})), | ||
None => Err(Status::internal("user-agent header is missing")), | ||
} | ||
} | ||
} | ||
|
||
let svc = 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:1322".parse().unwrap(), rx.map(drop)) | ||
.await | ||
.unwrap(); | ||
}); | ||
|
||
tokio::time::delay_for(Duration::from_millis(100)).await; | ||
|
||
let channel = Endpoint::from_static("http://127.0.0.1:1322") | ||
.user_agent("my-client") | ||
.expect("valid user agent") | ||
.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(); | ||
} |
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
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,70 @@ | ||
use http::{header::USER_AGENT, HeaderValue, Request}; | ||
use std::task::{Context, Poll}; | ||
use tower_service::Service; | ||
|
||
const TONIC_USER_AGENT: &str = concat!("tonic/", env!("CARGO_PKG_VERSION")); | ||
|
||
#[derive(Debug)] | ||
pub(crate) struct UserAgent<T> { | ||
inner: T, | ||
user_agent: HeaderValue, | ||
} | ||
|
||
impl<T> UserAgent<T> { | ||
pub(crate) fn new(inner: T, user_agent: Option<HeaderValue>) -> Self { | ||
let user_agent = user_agent | ||
.map(|value| { | ||
let mut buf = Vec::new(); | ||
buf.extend(value.as_bytes()); | ||
buf.push(b' '); | ||
buf.extend(TONIC_USER_AGENT.as_bytes()); | ||
HeaderValue::from_bytes(&buf).expect("user-agent should be valid") | ||
}) | ||
.unwrap_or(HeaderValue::from_static(TONIC_USER_AGENT)); | ||
|
||
Self { inner, user_agent } | ||
} | ||
} | ||
|
||
impl<T, ReqBody> Service<Request<ReqBody>> for UserAgent<T> | ||
where | ||
T: Service<Request<ReqBody>>, | ||
{ | ||
type Response = T::Response; | ||
type Error = T::Error; | ||
type Future = T::Future; | ||
|
||
fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> { | ||
self.inner.poll_ready(cx) | ||
} | ||
|
||
fn call(&mut self, mut req: Request<ReqBody>) -> Self::Future { | ||
req.headers_mut() | ||
.insert(USER_AGENT, self.user_agent.clone()); | ||
|
||
self.inner.call(req) | ||
} | ||
} | ||
|
||
#[cfg(test)] | ||
mod tests { | ||
use super::*; | ||
|
||
struct Svc; | ||
|
||
#[test] | ||
fn sets_default_if_no_custom_user_agent() { | ||
assert_eq!( | ||
UserAgent::new(Svc, None).user_agent, | ||
HeaderValue::from_static(TONIC_USER_AGENT) | ||
) | ||
} | ||
|
||
#[test] | ||
fn prepends_custom_user_agent_to_default() { | ||
assert_eq!( | ||
UserAgent::new(Svc, Some(HeaderValue::from_static("Greeter 1.1"))).user_agent, | ||
HeaderValue::from_str(&format!("Greeter 1.1 {}", TONIC_USER_AGENT)).unwrap() | ||
) | ||
} | ||
} |