use std::collections::HashMap;
use std::future::Future;
use std::sync::{Arc, Mutex, MutexGuard};
use std::time::{Duration, Instant};
use redup_bootstrap_grpc::{
CHAIN_LEVEL_HEADER, CORRELATION_HEADER, CallContext, CompressionMode, INSTANCE_HEADER,
TRACEPARENT_HEADER, TraceIds,
};
use redup_primitives::Address;
use tonic::metadata::KeyAndValueRef;
use tonic::transport::{Channel, Endpoint};
use tonic::{Request, Response, Status};
use tracing::Instrument;
use crate::clients::{ControlClient, HealthClient, InfoClient, MetricsClient};
use crate::config::ClientConfig;
use crate::connector::RetryingConnector;
use crate::error::{ClientError, code_name};
use crate::load::CallLoad;
use crate::log::ClientLog;
use crate::stream::GuardedStream;
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Settings {
pub channel: ClientConfig,
pub unary_timeout: Duration,
pub stream_timeout: Duration,
pub compression: CompressionMode,
pub compression_threshold: u64,
pub instance_id: String,
}
impl Default for Settings {
fn default() -> Self {
Self {
channel: ClientConfig::default(),
unary_timeout: Duration::from_secs(15),
stream_timeout: Duration::from_secs(15 * 60),
compression: CompressionMode::default(),
compression_threshold: 1024,
instance_id: String::new(),
}
}
}
#[derive(Clone)]
pub(crate) struct Calls {
pub(crate) settings: Arc<Settings>,
pub(crate) load: Arc<dyn CallLoad>,
pub(crate) log: Arc<ClientLog>,
}
#[derive(Clone)]
pub struct ClientFactory {
pub(crate) calls: Calls,
inner: Arc<Inner>,
}
struct Inner {
channels: Mutex<HashMap<Address, Channel>>,
}
impl ClientFactory {
pub fn new(settings: Settings, load: Arc<dyn CallLoad>) -> Self {
Self {
calls: Calls {
settings: Arc::new(settings),
load,
log: Arc::new(ClientLog::new()),
},
inner: Arc::new(Inner {
channels: Mutex::new(HashMap::new()),
}),
}
}
pub fn settings(&self) -> &Settings {
&self.calls.settings
}
pub fn channel(&self, address: &Address) -> Result<Channel, ClientError> {
if address.is_tls() {
return Err(ClientError::from(Status::failed_precondition(
"TLS connections are not supported by this platform build",
)));
}
if let Some(channel) = lock(&self.inner.channels).get(address) {
return Ok(channel.clone());
}
let endpoint = self.endpoint(address)?;
let connector = RetryingConnector::new(self.calls.settings.channel.connect_timeout());
let channel = endpoint.connect_with_connector_lazy(connector);
lock(&self.inner.channels).insert(address.clone(), channel.clone());
Ok(channel)
}
pub fn detached(&self) -> Self {
Self {
calls: self.calls.clone(),
inner: Arc::new(Inner {
channels: Mutex::new(HashMap::new()),
}),
}
}
pub fn health(&self, address: &Address) -> Result<HealthClient, ClientError> {
Ok(HealthClient::new(
self.calls.clone(),
self.channel(address)?,
))
}
pub fn info(&self, address: &Address) -> Result<InfoClient, ClientError> {
Ok(InfoClient::new(self.calls.clone(), self.channel(address)?))
}
pub fn metrics(&self, address: &Address) -> Result<MetricsClient, ClientError> {
Ok(MetricsClient::new(
self.calls.clone(),
self.channel(address)?,
))
}
pub fn control(&self, address: &Address) -> Result<ControlClient, ClientError> {
Ok(ControlClient::new(
self.calls.clone(),
self.channel(address)?,
))
}
fn endpoint(&self, address: &Address) -> Result<Endpoint, ClientError> {
let config = &self.calls.settings.channel;
let mut endpoint = Endpoint::from_shared(address.uri())
.map_err(|error| ClientError::from(Status::invalid_argument(error.to_string())))?;
if let Some(window) = config.stream_window_size() {
endpoint = endpoint.initial_stream_window_size(window.min(u64::from(u32::MAX)) as u32);
}
if let Some(keep_alive) = config.keep_alive() {
endpoint = endpoint
.http2_keep_alive_interval(keep_alive.ping_delay())
.keep_alive_timeout(keep_alive.ping_timeout())
.keep_alive_while_idle(
keep_alive.policy() == crate::config::KeepAlivePolicy::WhileIdle,
);
}
Ok(endpoint)
}
}
impl Calls {
pub(crate) fn prepare<T>(
&self,
mut request: Request<T>,
context: &CallContext,
streaming: bool,
) -> (Request<T>, Duration, TraceIds) {
let default = if streaming {
self.settings.stream_timeout
} else {
self.settings.unary_timeout
};
let timeout = context
.remaining()
.map_or(default, |left| left.min(default));
let trace = TraceIds::child(context.trace().trace, context.trace().sampled);
request.set_timeout(timeout);
let metadata = request.metadata_mut();
metadata.insert(
tonic::metadata::MetadataKey::from_static(CORRELATION_HEADER),
context
.correlation_id()
.parse()
.unwrap_or_else(|_| tonic::metadata::MetadataValue::from_static("invalid")),
);
if let Ok(level) = context.outgoing_chain_level().to_string().parse() {
metadata.insert(
tonic::metadata::MetadataKey::from_static(CHAIN_LEVEL_HEADER),
level,
);
}
if !self.settings.instance_id.is_empty()
&& let Ok(value) = self.settings.instance_id.parse()
{
metadata.insert(
tonic::metadata::MetadataKey::from_static(INSTANCE_HEADER),
value,
);
}
if let Ok(value) = trace.traceparent().parse() {
metadata.insert(
tonic::metadata::MetadataKey::from_static(TRACEPARENT_HEADER),
value,
);
}
for entry in context.transit().iter() {
match entry {
KeyAndValueRef::Ascii(key, value) => {
if !metadata.contains_key(key) {
metadata.insert(key.clone(), value.clone());
}
}
KeyAndValueRef::Binary(key, value) => {
if !metadata.contains_key(key) {
metadata.insert_bin(key.clone(), value.clone());
}
}
}
}
(request, timeout, trace)
}
pub(crate) async fn unary<T, F>(
&self,
method: &'static str,
context: &CallContext,
timeout: Duration,
trace: TraceIds,
future: F,
) -> Result<Response<T>, ClientError>
where
F: Future<Output = Result<Response<T>, Status>>,
{
let started = Instant::now();
let _guard = self.load.begin();
let span = client_span(method, context, trace);
let token = context.token();
let outcome = async {
tokio::select! {
_ = token.cancelled() => Err(ClientError::from(Status::cancelled(
format!("the call to {method} is cancelled"),
))),
result = tokio::time::timeout(timeout, future) => match result {
Ok(Ok(response)) => Ok(response),
Ok(Err(status)) => Err(ClientError::from(status)),
Err(_) => Err(ClientError::from(Status::deadline_exceeded(
format!("the call to {method} did not finish in {timeout:?}"),
))),
},
}
}
.instrument(span.clone())
.await;
self.settle(method, &span, started, &outcome);
outcome
}
pub(crate) async fn streaming<S, F>(
&self,
method: &'static str,
context: &CallContext,
timeout: Duration,
trace: TraceIds,
future: F,
) -> Result<GuardedStream<tonic::Streaming<S>>, ClientError>
where
F: Future<Output = Result<Response<tonic::Streaming<S>>, Status>>,
{
let started = Instant::now();
let guard = self.load.begin();
let span = client_span(method, context, trace);
let deadline = Instant::now().checked_add(timeout);
let token = context.token();
let outcome = async {
tokio::select! {
_ = token.cancelled() => Err(ClientError::from(Status::cancelled(
format!("the call to {method} is cancelled"),
))),
result = tokio::time::timeout(timeout, future) => match result {
Ok(Ok(response)) => Ok(response),
Ok(Err(status)) => Err(ClientError::from(status)),
Err(_) => Err(ClientError::from(Status::deadline_exceeded(
format!("the call to {method} did not start in {timeout:?}"),
))),
},
}
}
.instrument(span.clone())
.await;
self.settle(method, &span, started, &outcome);
let response = outcome?;
Ok(GuardedStream::new(
response.into_inner(),
guard,
span,
deadline,
context.token(),
))
}
fn settle<T>(
&self,
method: &'static str,
span: &tracing::Span,
started: Instant,
outcome: &Result<Response<T>, ClientError>,
) {
let elapsed = started.elapsed();
let elapsed_ms = u64::try_from(elapsed.as_millis()).unwrap_or(u64::MAX);
match outcome {
Ok(_) => {
span.record("grpc.code", "OK");
}
Err(error) => {
span.record("grpc.code", code_name(error.code()));
span.in_scope(|| self.log.failed(method, error));
}
}
span.record("elapsed_ms", elapsed_ms);
}
}
fn client_span(method: &'static str, context: &CallContext, trace: TraceIds) -> tracing::Span {
tracing::info_span!(
"grpc.client",
rpc.method = method,
grpc.code = tracing::field::Empty,
elapsed_ms = tracing::field::Empty,
correlation_id = context.correlation_id(),
trace_id = hex(&trace.trace).as_str(),
span_id = hex8(&trace.span).as_str(),
)
}
fn hex(bytes: &[u8; 16]) -> String {
let mut text = String::with_capacity(32);
for byte in bytes {
text.push_str(&format!("{byte:02x}"));
}
text
}
fn hex8(bytes: &[u8; 8]) -> String {
let mut text = String::with_capacity(16);
for byte in bytes {
text.push_str(&format!("{byte:02x}"));
}
text
}
fn lock<T>(mutex: &Mutex<T>) -> MutexGuard<'_, T> {
mutex
.lock()
.unwrap_or_else(|poisoned| poisoned.into_inner())
}
#[cfg(test)]
mod tests {
use std::sync::Arc;
use redup_primitives::Address;
use super::{ClientFactory, Settings};
use crate::load::NoLoad;
#[test]
fn the_factory_rejects_tls_addresses() {
let factory = ClientFactory::new(Settings::default(), Arc::new(NoLoad));
let error = factory
.channel(&Address::parse("grpcs://example.com").expect("the address"))
.expect_err("TLS is not supported");
assert_eq!(error.code(), tonic::Code::FailedPrecondition);
}
#[tokio::test]
async fn the_same_address_shares_one_channel() {
let factory = ClientFactory::new(Settings::default(), Arc::new(NoLoad));
let address = Address::parse("127.0.0.1:4200").expect("the address");
factory.channel(&address).expect("the channel");
factory.channel(&address).expect("the cached channel");
}
}