redup-bootstrap-client 0.3.3

Фабрика клиентов gRPC и клиенты инфраструктурных контрактов.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
//! Фабрика клиентов: настройки каналов, кэш каналов и общие части вызова.

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 {
    /// Настройки каналов `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 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()),
            }),
        }
    }

    /// Клиент проверки состояния к адресу `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())))?;
        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");
    }
}