redup-bootstrap-client 0.2.0

Фабрика клиентов gRPC и клиенты инфраструктурных контрактов.
Documentation
//! Фабрика клиентов: настройки каналов, кэш каналов и общие части вызова.

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::error::{ClientError, code_name};
use crate::load::CallLoad;
use crate::log::ClientLog;
use crate::stream::GuardedStream;

/// Настройки клиентов инстанса: канал, таймауты, сжатие и имя инстанса.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Settings {
    /// Настройки каналов `grpc.client`.
    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 {
    /// Фабрика с настройками `settings` и учётом исходящей нагрузки `load`.
    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
    }

    /// Канал к адресу `address`; новый канал кэшируется.
    ///
    /// # Ошибки
    ///
    /// TLS (`https`, `grpcs`) пока не поддержан: соединение шифруется транспортом, настроек
    /// которого у платформы нет.
    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 channel = endpoint.connect_lazy();
        lock(&self.inner.channels).insert(address.clone(), channel.clone());
        Ok(channel)
    }

    /// Клиент проверки состояния к адресу `address`.
    pub fn health(&self, address: &Address) -> Result<HealthClient, ClientError> {
        Ok(HealthClient::new(
            self.calls.clone(),
            self.channel(address)?,
        ))
    }

    /// Клиент сведений к адресу `address`.
    pub fn info(&self, address: &Address) -> Result<InfoClient, ClientError> {
        Ok(InfoClient::new(self.calls.clone(), self.channel(address)?))
    }

    /// Клиент метрик к адресу `address`.
    pub fn metrics(&self, address: &Address) -> Result<MetricsClient, ClientError> {
        Ok(MetricsClient::new(
            self.calls.clone(),
            self.channel(address)?,
        ))
    }

    /// Клиент управления к адресу `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())))?;
        // HTTP/2 сам группирует сообщения в кадры; задержка Нейгла только добавляет задержку
        // малым запросам и ответам (до 40 мс на паре «запрос — подтверждение»).
        endpoint = endpoint.tcp_nodelay(true);
        if let Some(timeout) = config.connect_timeout() {
            endpoint = endpoint.connect_timeout(timeout);
        }
        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);
    }
}

/// Отрезок исходящего вызова: идентификаторы те же, что уходят в `traceparent`.
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");
    }
}