use std::collections::HashMap;
use std::fmt;
use std::future::{Future, IntoFuture};
use std::marker::PhantomData;
use std::pin::Pin;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Mutex};
use std::task::{Context, Poll};
use std::time::{Duration, Instant};
use futures_core::Stream;
use http_body::Body as _;
use tonic::body::Body;
use tonic::client::Grpc;
use tonic::codegen::http::uri::PathAndQuery;
use tonic::metadata::MetadataMap;
use tonic::transport::{Channel, ClientTlsConfig, Endpoint};
use tonic_prost::ProstCodec;
use tower_layer::Layer;
use tower_service::Service;
use crate::opentelemetry::trace::FutureExt as _;
use super::{base_url_of, invalid_header, CallError, Settings};
use crate::services::{self, Propagate, PropagateLayer};
use crate::ErrCode;
type Sending<'c, T> = Pin<Box<dyn Future<Output = Result<T, CallError>> + Send + 'c>>;
type BoxError = Box<dyn std::error::Error + Send + Sync>;
pub const CONNECT_TIMEOUT: Duration = Duration::from_secs(10);
const MAX_CHANNELS: usize = 64;
const IDLE_CHANNEL: Duration = Duration::from_secs(5 * 60);
const MAX_ERROR_BODY: usize = 4096;
struct Call<'c> {
service: &'c services::Client,
client: &'c Settings,
settings: Settings,
path: &'static str,
}
struct Prepared<T> {
grpc: Grpc<Watched>,
request: tonic::Request<T>,
deadline: Option<Instant>,
heard: Arc<Heard>,
}
impl Call<'_> {
fn prepare<T>(&self, message: T) -> Result<Prepared<T>, CallError> {
let settings = self.settings.under(self.client);
let heard = Arc::new(Heard::default());
let grpc = grpc(base_url_of(self.service, &settings)?, &heard)?;
let mut request = tonic::Request::from_parts(
metadata(&settings.headers)?,
tonic::Extensions::default(),
message,
);
let deadline = deadline(&mut request, settings.limit());
Ok(Prepared {
grpc,
request,
deadline,
heard,
})
}
fn path(&self) -> PathAndQuery {
PathAndQuery::from_static(self.path)
}
}
fn metadata(headers: &[(String, String)]) -> Result<MetadataMap, CallError> {
let mut map = http::HeaderMap::new();
for (name, value) in headers {
let key = http::HeaderName::from_bytes(name.to_ascii_lowercase().as_bytes())
.map_err(|e| invalid_header(name, e))?;
let value = http::HeaderValue::from_str(value).map_err(|e| invalid_header(name, e))?;
map.insert(key, value);
}
let metadata = MetadataMap::from_headers(map);
for (name, _) in headers {
let name = name.to_ascii_lowercase();
if !name.ends_with("-bin") {
continue;
}
if let Some(Err(err)) = metadata.get_bin(name.as_str()).map(|v| v.to_bytes()) {
return Err(invalid_header(
&name,
format_args!("binary metadata is sent base64-encoded: {err}"),
));
}
}
Ok(metadata)
}
fn grpc(base: &str, heard: &Arc<Heard>) -> Result<Grpc<Watched>, CallError> {
static CHANNELS: Mutex<Channels<Channel>> = Mutex::new(Channels::new());
let origin: http::Uri = base.parse().map_err(|e| invalid_base(base, e))?;
let channel =
CHANNELS
.lock()
.unwrap_or_else(|e| e.into_inner())
.get(base, Instant::now(), || connect(base, &origin))?;
Ok(Grpc::with_origin(
Watched {
inner: PropagateLayer.layer(channel),
heard: heard.clone(),
},
origin,
))
}
fn invalid_base(base: &str, err: impl fmt::Display) -> CallError {
CallError::failed(
ErrCode::InvalidArgument,
format!("invalid base URL {base:?}: {err}"),
)
}
struct Channels<C> {
kept: Option<HashMap<String, (C, Instant)>>,
}
impl<C: Clone> Channels<C> {
const fn new() -> Self {
Channels { kept: None }
}
fn get(
&mut self,
base: &str,
now: Instant,
connect: impl FnOnce() -> Result<C, CallError>,
) -> Result<C, CallError> {
let kept = self.kept.get_or_insert_with(HashMap::new);
kept.retain(|_, (_, used)| now.saturating_duration_since(*used) < IDLE_CHANNEL);
if let Some((channel, used)) = kept.get_mut(base) {
*used = now;
return Ok(channel.clone());
}
let channel = connect()?;
if kept.len() >= MAX_CHANNELS {
let oldest = kept
.iter()
.min_by_key(|(_, (_, used))| *used)
.map(|(base, _)| base.clone());
if let Some(oldest) = oldest {
kept.remove(&oldest);
}
}
kept.insert(base.to_string(), (channel.clone(), now));
Ok(channel)
}
}
fn connect(base: &str, origin: &http::Uri) -> Result<Channel, CallError> {
let mut endpoint = Endpoint::from_shared(base.to_string())
.map_err(|e| invalid_base(base, e))?
.connect_timeout(CONNECT_TIMEOUT);
match origin.scheme_str() {
Some("http") => {}
Some("https") => {
let tls = ClientTlsConfig::new()
.with_native_roots()
.timeout(CONNECT_TIMEOUT);
endpoint = endpoint.tls_config(tls).map_err(|err| {
CallError::failed(
ErrCode::Unavailable,
format!("configuring TLS for {base}: {err}"),
)
.caused_by(err)
})?;
}
_ => return Err(invalid_base(base, "gRPC is called at http:// or https://")),
}
let _runtime = crate::runtime::core().tokio_handle().enter();
Ok(endpoint.connect_lazy())
}
#[derive(Debug, Default)]
struct Heard {
answered: AtomicBool,
status: AtomicBool,
}
#[derive(Clone)]
struct Watched {
inner: Propagate<Channel>,
heard: Arc<Heard>,
}
impl Service<http::Request<Body>> for Watched {
type Response = http::Response<Body>;
type Error = BoxError;
type Future = Pin<Box<dyn Future<Output = Result<Self::Response, BoxError>> + Send>>;
fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), BoxError>> {
self.inner.poll_ready(cx).map_err(Into::into)
}
fn call(&mut self, request: http::Request<Body>) -> Self::Future {
let heard = self.heard.clone();
let response = self.inner.call(request);
Box::pin(async move {
let response = response.await?;
heard.answered.store(true, Ordering::Release);
if response.headers().contains_key("grpc-status") {
heard.status.store(true, Ordering::Release);
} else if let Some(not_grpc) = NotGrpc::of(&response) {
return Err(Box::new(not_grpc.read(response.into_body()).await) as BoxError);
}
Ok(response.map(|body| Body::new(Trailers { body, heard })))
})
}
}
struct Trailers {
body: Body,
heard: Arc<Heard>,
}
impl http_body::Body for Trailers {
type Data = bytes::Bytes;
type Error = tonic::Status;
fn poll_frame(
mut self: Pin<&mut Self>,
cx: &mut Context<'_>,
) -> Poll<Option<Result<http_body::Frame<bytes::Bytes>, tonic::Status>>> {
let frame = Pin::new(&mut self.body).poll_frame(cx);
if let Poll::Ready(Some(Ok(frame))) = &frame {
if frame
.trailers_ref()
.is_some_and(|t| t.contains_key("grpc-status"))
{
self.heard.status.store(true, Ordering::Release);
}
}
frame
}
fn is_end_stream(&self) -> bool {
self.body.is_end_stream()
}
fn size_hint(&self) -> http_body::SizeHint {
self.body.size_hint()
}
}
#[derive(Debug)]
struct NotGrpc {
status: http::StatusCode,
content_type: String,
code: ErrCode,
message: String,
}
impl NotGrpc {
fn of<B>(response: &http::Response<B>) -> Option<NotGrpc> {
let status = response.status();
let content_type = response
.headers()
.get(http::header::CONTENT_TYPE)
.and_then(|v| v.to_str().ok())
.unwrap_or_default()
.to_ascii_lowercase();
let grpc = content_type
.strip_prefix("application/grpc")
.is_some_and(|rest| rest.is_empty() || rest.starts_with(['+', ';']));
if status == http::StatusCode::OK && grpc {
return None;
}
let code = match status.as_u16() {
400 => ErrCode::Internal,
401 => ErrCode::Unauthenticated,
403 => ErrCode::PermissionDenied,
404 => ErrCode::Unimplemented,
429 | 502 | 503 | 504 => ErrCode::Unavailable,
_ => ErrCode::Unknown,
};
Some(NotGrpc {
status,
content_type,
code,
message: String::new(),
})
}
async fn read(mut self, mut body: Body) -> NotGrpc {
let mut text = Vec::new();
while text.len() < MAX_ERROR_BODY {
match std::future::poll_fn(|cx| Pin::new(&mut body).poll_frame(cx)).await {
Some(Ok(frame)) => {
if let Ok(data) = frame.into_data() {
text.extend_from_slice(&data);
}
}
_ => break,
}
}
text.truncate(MAX_ERROR_BODY);
self.message = self.message_for(&String::from_utf8_lossy(&text));
self
}
fn message_for(&self, text: &str) -> String {
if self.content_type.starts_with("text/") && !text.trim().is_empty() {
return text.trim().to_string();
}
let content_type = match self.content_type.as_str() {
"" => "no content type",
ct => ct,
};
format!(
"the service answered {} with {content_type}, not gRPC",
self.status
)
}
fn error(&self) -> CallError {
let err = CallError::new(self.code, self.message.clone());
if self.status.is_client_error() || self.status.is_server_error() {
err.with_status(self.status.as_u16())
} else {
err
}
}
}
impl fmt::Display for NotGrpc {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(&self.message)
}
}
impl std::error::Error for NotGrpc {}
const MAX_TIMEOUT: Duration = Duration::from_secs(99_999_999 * 3600);
fn deadline<T>(request: &mut tonic::Request<T>, timeout: Option<Duration>) -> Option<Instant> {
let timeout = timeout.filter(|t| *t <= MAX_TIMEOUT)?;
let deadline = Instant::now().checked_add(timeout)?;
request.set_timeout(timeout);
Some(deadline)
}
async fn within<T>(
deadline: Option<Instant>,
call: impl Future<Output = Result<T, CallError>>,
) -> Result<T, CallError> {
let Some(deadline) = deadline else {
return call.await;
};
tokio::time::timeout_at(deadline.into(), call)
.await
.unwrap_or_else(|_| Err(timed_out()))
}
fn timed_out() -> CallError {
CallError::failed(
ErrCode::DeadlineExceeded,
"the call took longer than its timeout",
)
}
#[derive(Clone, PartialEq, prost::Message)]
struct RpcStatus {
#[prost(int32, tag = "1")]
code: i32,
#[prost(string, tag = "2")]
message: String,
#[prost(message, repeated, tag = "3")]
details: Vec<prost_types::Any>,
}
fn status_error(status: tonic::Status, deadline: Option<Instant>, heard: &Heard) -> CallError {
if let Some(not_grpc) = find::<NotGrpc>(&status) {
return not_grpc.error().caused_by(status);
}
let past_deadline = deadline.is_some_and(|d| Instant::now() >= d);
let sent = heard.status.load(Ordering::Acquire) && std::error::Error::source(&status).is_none();
let code = if past_deadline
&& matches!(
status.code(),
tonic::Code::Cancelled | tonic::Code::DeadlineExceeded
) {
ErrCode::DeadlineExceeded
} else if sent {
code_of(status.code())
} else if lost(&status, heard.answered.load(Ordering::Acquire)) {
ErrCode::Unavailable
} else {
code_of(status.code())
};
let message = status.message().to_string();
let err = if sent {
let mut err = CallError::new(code, message);
if let Ok(details) = <RpcStatus as prost::Message>::decode(status.details()) {
err.grpc_details = details.details;
}
err
} else {
CallError::failed(code, message)
};
err.caused_by(status)
}
fn lost(status: &tonic::Status, answered: bool) -> bool {
match find::<h2::Error>(status) {
Some(err) if err.is_reset() && err.is_remote() => false,
Some(err) if err.is_io() || err.is_go_away() => true,
_ => !answered,
}
}
fn find<E: std::error::Error + 'static>(status: &tonic::Status) -> Option<&E> {
let mut source = std::error::Error::source(status);
while let Some(err) = source {
if let Some(found) = err.downcast_ref::<E>() {
return Some(found);
}
source = err.source();
}
None
}
fn code_of(code: tonic::Code) -> ErrCode {
match code {
tonic::Code::Ok | tonic::Code::Unknown => ErrCode::Unknown,
tonic::Code::Cancelled => ErrCode::Canceled,
tonic::Code::InvalidArgument => ErrCode::InvalidArgument,
tonic::Code::DeadlineExceeded => ErrCode::DeadlineExceeded,
tonic::Code::NotFound => ErrCode::NotFound,
tonic::Code::AlreadyExists => ErrCode::AlreadyExists,
tonic::Code::PermissionDenied => ErrCode::PermissionDenied,
tonic::Code::ResourceExhausted => ErrCode::ResourceExhausted,
tonic::Code::FailedPrecondition => ErrCode::FailedPrecondition,
tonic::Code::Aborted => ErrCode::Aborted,
tonic::Code::OutOfRange => ErrCode::OutOfRange,
tonic::Code::Unimplemented => ErrCode::Unimplemented,
tonic::Code::Internal => ErrCode::Internal,
tonic::Code::Unavailable => ErrCode::Unavailable,
tonic::Code::DataLoss => ErrCode::DataLoss,
tonic::Code::Unauthenticated => ErrCode::Unauthenticated,
}
}
async fn ready(grpc: &mut Grpc<Watched>) -> Result<(), CallError> {
grpc.ready().await.map_err(|err| {
let status = tonic::Status::from_error(err);
CallError::failed(ErrCode::Unavailable, format!("connecting: {status}")).caused_by(status)
})
}
macro_rules! settings {
() => {
pub fn timeout(mut self, timeout: Duration) -> Self {
self.call.settings = self.call.settings.timeout(timeout);
self
}
pub fn no_timeout(mut self) -> Self {
self.call.settings = self.call.settings.no_timeout();
self
}
pub fn header(mut self, name: impl Into<String>, value: impl Into<String>) -> Self {
self.call.settings = self.call.settings.header(name, value);
self
}
};
}
#[must_use = "a call is sent only when awaited"]
pub struct Unary<'c, Req, Resp> {
call: Call<'c>,
message: Req,
answer: PhantomData<fn() -> Resp>,
}
impl<'c, Req, Resp> Unary<'c, Req, Resp> {
#[doc(hidden)]
pub fn new(
service: &'c services::Client,
client: &'c Settings,
path: &'static str,
message: Req,
) -> Self {
Unary {
call: Call {
service,
client,
settings: Settings::new(),
path,
},
message,
answer: PhantomData,
}
}
settings!();
}
impl<'c, Req, Resp> IntoFuture for Unary<'c, Req, Resp>
where
Req: prost::Message + Send + Sync + 'static,
Resp: prost::Message + Default + Send + Sync + 'static,
{
type Output = Result<Resp, CallError>;
type IntoFuture = Sending<'c, Resp>;
fn into_future(self) -> Self::IntoFuture {
Box::pin(super::sent(async move {
let Prepared {
mut grpc,
request,
deadline,
heard,
} = self.call.prepare(self.message)?;
let path = self.call.path();
within(deadline, async move {
ready(&mut grpc).await?;
let codec = ProstCodec::<Req, Resp>::default();
grpc.unary(request, path, codec)
.await
.map(tonic::Response::into_inner)
.map_err(|s| status_error(s, deadline, &heard))
})
.await
}))
}
}
#[must_use = "a call is sent only when awaited"]
pub struct ServerStreaming<'c, Req, Resp> {
call: Call<'c>,
message: Req,
answer: PhantomData<fn() -> Resp>,
}
impl<'c, Req, Resp> ServerStreaming<'c, Req, Resp> {
#[doc(hidden)]
pub fn new(
service: &'c services::Client,
client: &'c Settings,
path: &'static str,
message: Req,
) -> Self {
ServerStreaming {
call: Call {
service,
client,
settings: Settings::new(),
path,
},
message,
answer: PhantomData,
}
}
settings!();
}
impl<'c, Req, Resp> IntoFuture for ServerStreaming<'c, Req, Resp>
where
Req: prost::Message + Send + Sync + 'static,
Resp: prost::Message + Default + Send + Sync + 'static,
{
type Output = Result<Streaming<Resp>, CallError>;
type IntoFuture = Sending<'c, Streaming<Resp>>;
fn into_future(self) -> Self::IntoFuture {
Box::pin(super::sent(async move {
let Prepared {
mut grpc,
request,
deadline,
heard,
} = self.call.prepare(self.message)?;
let path = self.call.path();
let inner = within(deadline, async {
ready(&mut grpc).await?;
let codec = ProstCodec::<Req, Resp>::default();
grpc.server_streaming(request, path, codec)
.await
.map_err(|s| status_error(s, deadline, &heard))
})
.await?
.into_inner();
Ok(Streaming::new(
State::Open(Box::new(inner)),
deadline,
heard,
))
}))
}
}
#[must_use = "a call is sent only when awaited"]
pub struct ClientStreaming<'c, S, Resp> {
call: Call<'c>,
messages: S,
answer: PhantomData<fn() -> Resp>,
}
impl<'c, S, Resp> ClientStreaming<'c, S, Resp> {
#[doc(hidden)]
pub fn new(
service: &'c services::Client,
client: &'c Settings,
path: &'static str,
messages: S,
) -> Self {
ClientStreaming {
call: Call {
service,
client,
settings: Settings::new(),
path,
},
messages,
answer: PhantomData,
}
}
settings!();
}
impl<'c, S, Resp> IntoFuture for ClientStreaming<'c, S, Resp>
where
S: Stream + Send + 'static,
S::Item: prost::Message + Send + Sync + 'static,
Resp: prost::Message + Default + Send + Sync + 'static,
{
type Output = Result<Resp, CallError>;
type IntoFuture = Sending<'c, Resp>;
fn into_future(self) -> Self::IntoFuture {
Box::pin(super::sent(async move {
let Prepared {
mut grpc,
request,
deadline,
heard,
} = self.call.prepare(self.messages)?;
let path = self.call.path();
within(deadline, async move {
ready(&mut grpc).await?;
let codec = ProstCodec::<S::Item, Resp>::default();
grpc.client_streaming(request, path, codec)
.await
.map(tonic::Response::into_inner)
.map_err(|s| status_error(s, deadline, &heard))
})
.await
}))
}
}
#[must_use = "a call is sent only when awaited"]
pub struct BidiStreaming<'c, S, Resp> {
call: Call<'c>,
messages: S,
answer: PhantomData<fn() -> Resp>,
}
impl<'c, S, Resp> BidiStreaming<'c, S, Resp> {
#[doc(hidden)]
pub fn new(
service: &'c services::Client,
client: &'c Settings,
path: &'static str,
messages: S,
) -> Self {
BidiStreaming {
call: Call {
service,
client,
settings: Settings::new(),
path,
},
messages,
answer: PhantomData,
}
}
settings!();
}
impl<'c, S, Resp> IntoFuture for BidiStreaming<'c, S, Resp>
where
S: Stream + Send + 'static,
S::Item: prost::Message + Send + Sync + 'static,
Resp: prost::Message + Default + Send + Sync + 'static,
{
type Output = Result<Streaming<Resp>, CallError>;
type IntoFuture = Sending<'c, Streaming<Resp>>;
fn into_future(self) -> Self::IntoFuture {
Box::pin(super::sent(async move {
let Prepared {
mut grpc,
request,
deadline,
heard,
} = self.call.prepare(self.messages)?;
let path = self.call.path();
let answering = heard.clone();
let mut call: Answering<Resp> = Box::pin(
async move {
ready(&mut grpc).await?;
let codec = ProstCodec::<S::Item, Resp>::default();
grpc.streaming(request, path, codec)
.await
.map(tonic::Response::into_inner)
.map_err(|s| status_error(s, deadline, &answering))
}
.with_context(crate::opentelemetry::Context::current()),
);
let state = std::future::poll_fn(|cx| match call.as_mut().poll(cx) {
Poll::Ready(Ok(messages)) => Poll::Ready(Ok(Some(messages))),
Poll::Ready(Err(err)) => Poll::Ready(Err(err)),
Poll::Pending => Poll::Ready(Ok(None)),
})
.await?;
let state = match state {
Some(messages) => State::Open(Box::new(messages)),
None => State::Answering(call),
};
Ok(Streaming::new(state, deadline, heard))
}))
}
}
pub struct Streaming<T> {
state: State<T>,
deadline: Option<Instant>,
timer: Option<Pin<Box<tokio::time::Sleep>>>,
heard: Arc<Heard>,
}
type Answering<T> = Pin<Box<dyn Future<Output = Result<tonic::Streaming<T>, CallError>> + Send>>;
enum State<T> {
Answering(Answering<T>),
Open(Box<tonic::Streaming<T>>),
Ended,
}
impl<T> Streaming<T> {
fn new(state: State<T>, deadline: Option<Instant>, heard: Arc<Heard>) -> Self {
Streaming {
state,
deadline,
timer: deadline.map(|d| Box::pin(tokio::time::sleep_until(d.into()))),
heard,
}
}
pub async fn message(&mut self) -> Result<Option<T>, CallError> {
std::future::poll_fn(|cx| Pin::new(&mut *self).poll_next(cx))
.await
.transpose()
}
}
impl<T> std::fmt::Debug for Streaming<T> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Streaming").finish_non_exhaustive()
}
}
impl<T> Stream for Streaming<T> {
type Item = Result<T, CallError>;
fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
let this = &mut *self;
if matches!(this.state, State::Ended) {
return Poll::Ready(None);
}
let past_deadline = this
.timer
.as_mut()
.is_some_and(|timer| timer.as_mut().poll(cx).is_ready());
let item = loop {
if past_deadline {
break Some(Err(timed_out()));
}
match &mut this.state {
State::Answering(call) => match call.as_mut().poll(cx) {
Poll::Ready(Ok(messages)) => this.state = State::Open(Box::new(messages)),
Poll::Ready(Err(err)) => break Some(Err(err)),
Poll::Pending => return Poll::Pending,
},
State::Open(messages) => match Pin::new(messages).poll_next(cx) {
Poll::Ready(Some(Ok(message))) => return Poll::Ready(Some(Ok(message))),
Poll::Ready(Some(Err(status))) => {
break Some(Err(status_error(status, this.deadline, &this.heard)))
}
Poll::Ready(None) => break None,
Poll::Pending => return Poll::Pending,
},
State::Ended => break None,
}
};
this.state = State::Ended;
this.timer = None;
Poll::Ready(item)
}
}
#[cfg(test)]
mod tests {
use super::*;
fn answered() -> Heard {
Heard {
answered: AtomicBool::new(true),
status: AtomicBool::new(true),
}
}
fn headers_only() -> Heard {
Heard {
answered: AtomicBool::new(true),
status: AtomicBool::new(false),
}
}
#[test]
fn a_cancel_past_the_deadline_is_deadline_exceeded() {
let past = Some(Instant::now() - Duration::from_millis(1));
let future = Some(Instant::now() + Duration::from_secs(60));
let none = Heard::default();
assert_eq!(
status_error(tonic::Status::cancelled("Timeout expired"), past, &none).code,
ErrCode::DeadlineExceeded
);
assert_eq!(
status_error(
tonic::Status::cancelled("Timeout expired"),
future,
&answered()
)
.code,
ErrCode::Canceled
);
assert_eq!(
status_error(
tonic::Status::cancelled("Timeout expired"),
None,
&answered()
)
.code,
ErrCode::Canceled
);
let err = status_error(
tonic::Status::not_found("no such product"),
None,
&answered(),
);
assert_eq!((err.code, err.status), (ErrCode::NotFound, 404));
assert_eq!(err.message, "no such product");
}
#[test]
fn a_timeout_too_long_to_send_is_none() {
let mut request = tonic::Request::new(());
assert_eq!(deadline(&mut request, Some(Duration::MAX)), None);
assert!(request.metadata().get("grpc-timeout").is_none());
assert!(deadline(&mut request, Some(Duration::from_secs(1))).is_some());
assert!(request.metadata().get("grpc-timeout").is_some());
}
#[test]
fn only_a_status_the_service_sent_has_an_http_status() {
let past = Some(Instant::now() - Duration::from_millis(1));
let timed_out = status_error(
tonic::Status::cancelled("Timeout expired"),
past,
&Heard::default(),
);
assert_eq!(timed_out.status, 0);
let refused = tonic::Status::from_error(Box::new(std::io::Error::from(
std::io::ErrorKind::ConnectionRefused,
)));
assert_eq!(status_error(refused, None, &Heard::default()).status, 0);
let sent = status_error(tonic::Status::unavailable("draining"), None, &answered());
assert_eq!((sent.code, sent.status), (ErrCode::Unavailable, 503));
let undecodable = status_error(tonic::Status::internal("bad frame"), None, &headers_only());
assert_eq!(
(undecodable.code, undecodable.status),
(ErrCode::Internal, 0)
);
}
#[test]
fn no_answer_is_unavailable() {
for status in [
tonic::Status::from_error(Box::new(std::io::Error::from(
std::io::ErrorKind::ConnectionReset,
))),
tonic::Status::from_error(Box::new(h2::Error::from(h2::Reason::PROTOCOL_ERROR))),
] {
let err = status_error(status, None, &Heard::default());
assert_eq!((err.code, err.status), (ErrCode::Unavailable, 0), "{err}");
}
}
#[test]
fn a_status_keeps_its_details() {
let detail = prost_types::Any {
type_url: "type.googleapis.com/conformance.v1.Detail".into(),
value: vec![0x0a, 0x03, b'w', b'h', b'y'],
};
let details = prost::Message::encode_to_vec(&RpcStatus {
code: 5,
message: "nope".into(),
details: vec![detail.clone()],
});
let status = tonic::Status::with_details(tonic::Code::NotFound, "nope", details.into());
let err = status_error(status, None, &answered());
assert_eq!(
(err.code, err.message.as_str()),
(ErrCode::NotFound, "nope")
);
assert_eq!(err.grpc_details, [detail]);
let err = status_error(tonic::Status::not_found("nope"), None, &answered());
assert!(err.grpc_details.is_empty());
}
#[test]
fn an_answer_that_is_not_grpc_is_its_http_status() {
let response = |status: u16, content_type: &str| {
http::Response::builder()
.status(status)
.header("content-type", content_type)
.body(())
.unwrap()
};
assert!(NotGrpc::of(&response(200, "application/grpc")).is_none());
assert!(NotGrpc::of(&response(200, "application/grpc+proto")).is_none());
let mut bad_gateway = NotGrpc::of(&response(502, "text/plain")).unwrap();
bad_gateway.message = bad_gateway.message_for("service down\n");
let err = bad_gateway.error();
assert_eq!(
(err.code, err.status, err.message.as_str()),
(ErrCode::Unavailable, 502, "service down")
);
let status = tonic::Status::from_error(Box::new(bad_gateway));
let err = status_error(status, None, &Heard::default());
assert_eq!((err.code, err.status), (ErrCode::Unavailable, 502));
for (status, code) in [
(400, ErrCode::Internal),
(401, ErrCode::Unauthenticated),
(403, ErrCode::PermissionDenied),
(404, ErrCode::Unimplemented),
(429, ErrCode::Unavailable),
(503, ErrCode::Unavailable),
(504, ErrCode::Unavailable),
(500, ErrCode::Unknown),
] {
let answer = NotGrpc::of(&response(status, "application/json")).unwrap();
assert_eq!(answer.code, code, "{status}");
assert_eq!(answer.error().status, status);
}
let html = NotGrpc::of(&response(200, "text/html")).unwrap();
assert_eq!(html.code, ErrCode::Unknown);
assert_eq!(html.error().status, 500);
assert_eq!(
html.message_for(""),
"the service answered 200 OK with text/html, not gRPC"
);
}
#[test]
fn binary_metadata_is_base64() {
let headers = |pairs: &[(&str, &str)]| -> Vec<(String, String)> {
pairs
.iter()
.map(|(k, v)| (k.to_string(), v.to_string()))
.collect()
};
let metadata = metadata(&headers(&[("X-Id-Bin", "AP8Q"), ("x-plain", "a")])).unwrap();
assert_eq!(
metadata.get_bin("x-id-bin").unwrap().to_bytes().unwrap(),
&[0x00, 0xff, 0x10][..]
);
assert_eq!(metadata.get("x-plain").unwrap(), "a");
let err = super::metadata(&headers(&[("x-id-bin", "not base64!")])).unwrap_err();
assert_eq!(err.code, ErrCode::InvalidArgument);
assert!(err.message.contains("base64"), "{err}");
let err = super::metadata(&headers(&[("x y", "a")])).unwrap_err();
assert_eq!(err.code, ErrCode::InvalidArgument);
}
#[test]
fn channels_are_dropped_when_idle_or_too_many() {
let mut channels = Channels::<usize>::new();
let start = Instant::now();
let mut made = 0;
let mut get = |channels: &mut Channels<usize>, base: &str, at: Duration| {
channels
.get(base, start + at, || {
made += 1;
Ok(made)
})
.unwrap()
};
assert_eq!(get(&mut channels, "http://a", Duration::ZERO), 1);
assert_eq!(get(&mut channels, "http://a", Duration::from_secs(1)), 1);
let later = Duration::from_secs(1) + IDLE_CHANNEL;
assert_eq!(get(&mut channels, "http://a", later), 2);
for i in 0..MAX_CHANNELS * 2 {
let at = later + Duration::from_millis(i as u64);
get(&mut channels, &format!("http://{i}"), at);
}
let kept = channels.kept.as_ref().unwrap();
assert_eq!(kept.len(), MAX_CHANNELS);
assert!(kept.contains_key(&format!("http://{}", MAX_CHANNELS * 2 - 1)));
assert!(!kept.contains_key("http://0"));
}
}