use std::collections::HashMap;
use std::future::{Future, IntoFuture};
use std::marker::PhantomData;
use std::pin::Pin;
use std::sync::{Mutex, OnceLock};
use std::task::{Context, Poll};
use std::time::{Duration, Instant};
use futures_core::Stream;
use tonic::client::Grpc;
use tonic::codegen::http::uri::PathAndQuery;
use tonic::metadata::{MetadataKey, MetadataValue};
use tonic::transport::{Channel, Endpoint};
use tonic_prost::ProstCodec;
use tower_layer::Layer;
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>>;
struct Call<'c> {
service: &'c services::Client,
client: &'c Settings,
settings: Settings,
path: &'static str,
}
struct Prepared<T> {
grpc: Grpc<Propagate<Channel>>,
request: tonic::Request<T>,
deadline: Option<Instant>,
}
impl Call<'_> {
fn prepare<T>(&self, message: T) -> Result<Prepared<T>, CallError> {
let settings = self.settings.under(self.client);
let grpc = grpc(base_url_of(self.service, &settings)?)?;
let mut request = tonic::Request::new(message);
for (name, value) in &settings.headers {
let key = MetadataKey::from_bytes(name.to_ascii_lowercase().as_bytes())
.map_err(|e| invalid_header(name, e))?;
let value =
MetadataValue::try_from(value.as_str()).map_err(|e| invalid_header(name, e))?;
request.metadata_mut().insert(key, value);
}
let deadline = deadline(&mut request, settings.limit());
Ok(Prepared {
grpc,
request,
deadline,
})
}
fn path(&self) -> PathAndQuery {
PathAndQuery::from_static(self.path)
}
}
fn grpc(base: &str) -> Result<Grpc<Propagate<Channel>>, CallError> {
static CHANNELS: OnceLock<Mutex<HashMap<String, Channel>>> = OnceLock::new();
let origin: http::Uri = base.parse().map_err(|e| {
CallError::failed(
ErrCode::InvalidArgument,
format!("invalid base URL {base:?}: {e}"),
)
})?;
let mut channels = CHANNELS
.get_or_init(Default::default)
.lock()
.unwrap_or_else(|e| e.into_inner());
let channel = match channels.get(base) {
Some(channel) => channel.clone(),
None => {
let endpoint = Endpoint::from_shared(base.to_string()).map_err(|e| {
CallError::failed(
ErrCode::InvalidArgument,
format!("invalid base URL {base:?}: {e}"),
)
})?;
let _runtime = crate::runtime::core().tokio_handle().enter();
let channel = endpoint.connect_lazy();
channels.insert(base.to_string(), channel.clone());
channel
}
};
Ok(Grpc::with_origin(PropagateLayer.layer(channel), origin))
}
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)
}
fn status_error(status: tonic::Status, deadline: Option<Instant>) -> CallError {
let past_deadline = deadline.is_some_and(|d| Instant::now() >= d);
let answered = std::error::Error::source(&status).is_none()
&& !(past_deadline && status.code() == tonic::Code::Cancelled);
let code = match status.code() {
tonic::Code::Ok | tonic::Code::Unknown => ErrCode::Unknown,
tonic::Code::Cancelled if past_deadline => ErrCode::DeadlineExceeded,
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,
};
let message = status.message().to_string();
let err = if answered {
CallError::new(code, message)
} else {
CallError::failed(code, message)
};
err.caused_by(status)
}
async fn ready(grpc: &mut Grpc<Propagate<Channel>>) -> Result<(), CallError> {
grpc.ready().await.map_err(|err| {
CallError::failed(ErrCode::Unavailable, format!("connecting: {err}")).caused_by(err)
})
}
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,
} = self.call.prepare(self.message)?;
ready(&mut grpc).await?;
let codec = ProstCodec::<Req, Resp>::default();
grpc.unary(request, self.call.path(), codec)
.await
.map(tonic::Response::into_inner)
.map_err(|s| status_error(s, deadline))
}))
}
}
#[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,
} = self.call.prepare(self.message)?;
ready(&mut grpc).await?;
let codec = ProstCodec::<Req, Resp>::default();
let inner = grpc
.server_streaming(request, self.call.path(), codec)
.await
.map_err(|s| status_error(s, deadline))?
.into_inner();
Ok(Streaming { inner, deadline })
}))
}
}
#[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,
} = self.call.prepare(self.messages)?;
ready(&mut grpc).await?;
let codec = ProstCodec::<S::Item, Resp>::default();
grpc.client_streaming(request, self.call.path(), codec)
.await
.map(tonic::Response::into_inner)
.map_err(|s| status_error(s, deadline))
}))
}
}
#[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,
} = self.call.prepare(self.messages)?;
ready(&mut grpc).await?;
let codec = ProstCodec::<S::Item, Resp>::default();
let inner = grpc
.streaming(request, self.call.path(), codec)
.await
.map_err(|s| status_error(s, deadline))?
.into_inner();
Ok(Streaming { inner, deadline })
}))
}
}
pub struct Streaming<T> {
inner: tonic::Streaming<T>,
deadline: Option<Instant>,
}
impl<T> Streaming<T> {
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 deadline = self.deadline;
Pin::new(&mut self.inner)
.poll_next(cx)
.map(|item| item.map(|r| r.map_err(|s| status_error(s, deadline))))
}
}
#[cfg(test)]
mod tests {
use super::*;
#[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));
assert_eq!(
status_error(tonic::Status::cancelled("Timeout expired"), past).code,
ErrCode::DeadlineExceeded
);
assert_eq!(
status_error(tonic::Status::cancelled("Timeout expired"), future).code,
ErrCode::Canceled
);
assert_eq!(
status_error(tonic::Status::cancelled("Timeout expired"), None).code,
ErrCode::Canceled
);
let err = status_error(tonic::Status::not_found("no such product"), None);
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);
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).status, 0);
let sent = status_error(tonic::Status::unavailable("draining"), None);
assert_eq!((sent.code, sent.status), (ErrCode::Unavailable, 503));
}
}