1use std::collections::HashMap;
4use std::future::Future;
5use std::sync::{Arc, Mutex, MutexGuard};
6use std::time::{Duration, Instant};
7
8use redup_bootstrap_grpc::{
9 CHAIN_LEVEL_HEADER, CORRELATION_HEADER, CallContext, CompressionMode, INSTANCE_HEADER,
10 TRACEPARENT_HEADER, TraceIds,
11};
12use redup_primitives::Address;
13use tonic::metadata::KeyAndValueRef;
14use tonic::transport::{Channel, Endpoint};
15use tonic::{Request, Response, Status};
16use tracing::Instrument;
17
18use crate::clients::{ControlClient, HealthClient, InfoClient, MetricsClient};
19use crate::config::ClientConfig;
20use crate::connector::RetryingConnector;
21use crate::error::{ClientError, code_name};
22use crate::load::CallLoad;
23use crate::log::ClientLog;
24use crate::stream::GuardedStream;
25
26#[derive(Debug, Clone, PartialEq, Eq)]
28pub struct Settings {
29 pub channel: ClientConfig,
31 pub unary_timeout: Duration,
33 pub stream_timeout: Duration,
35 pub compression: CompressionMode,
37 pub compression_threshold: u64,
39 pub instance_id: String,
41}
42
43impl Default for Settings {
44 fn default() -> Self {
45 Self {
46 channel: ClientConfig::default(),
47 unary_timeout: Duration::from_secs(15),
48 stream_timeout: Duration::from_secs(15 * 60),
49 compression: CompressionMode::default(),
50 compression_threshold: 1024,
51 instance_id: String::new(),
52 }
53 }
54}
55
56#[derive(Clone)]
58pub(crate) struct Calls {
59 pub(crate) settings: Arc<Settings>,
60 pub(crate) load: Arc<dyn CallLoad>,
61 pub(crate) log: Arc<ClientLog>,
62}
63
64#[derive(Clone)]
69pub struct ClientFactory {
70 pub(crate) calls: Calls,
71 inner: Arc<Inner>,
72}
73
74struct Inner {
75 channels: Mutex<HashMap<Address, Channel>>,
76}
77
78impl ClientFactory {
79 pub fn new(settings: Settings, load: Arc<dyn CallLoad>) -> Self {
81 Self {
82 calls: Calls {
83 settings: Arc::new(settings),
84 load,
85 log: Arc::new(ClientLog::new()),
86 },
87 inner: Arc::new(Inner {
88 channels: Mutex::new(HashMap::new()),
89 }),
90 }
91 }
92
93 pub fn settings(&self) -> &Settings {
95 &self.calls.settings
96 }
97
98 pub fn channel(&self, address: &Address) -> Result<Channel, ClientError> {
105 if address.is_tls() {
106 return Err(ClientError::from(Status::failed_precondition(
107 "TLS connections are not supported by this platform build",
108 )));
109 }
110 if let Some(channel) = lock(&self.inner.channels).get(address) {
111 return Ok(channel.clone());
112 }
113 let endpoint = self.endpoint(address)?;
114 let connector = RetryingConnector::new(self.calls.settings.channel.connect_timeout());
115 let channel = endpoint.connect_with_connector_lazy(connector);
116 lock(&self.inner.channels).insert(address.clone(), channel.clone());
117 Ok(channel)
118 }
119
120 pub fn detached(&self) -> Self {
125 Self {
126 calls: self.calls.clone(),
127 inner: Arc::new(Inner {
128 channels: Mutex::new(HashMap::new()),
129 }),
130 }
131 }
132
133 pub fn health(&self, address: &Address) -> Result<HealthClient, ClientError> {
135 Ok(HealthClient::new(
136 self.calls.clone(),
137 self.channel(address)?,
138 ))
139 }
140
141 pub fn info(&self, address: &Address) -> Result<InfoClient, ClientError> {
143 Ok(InfoClient::new(self.calls.clone(), self.channel(address)?))
144 }
145
146 pub fn metrics(&self, address: &Address) -> Result<MetricsClient, ClientError> {
148 Ok(MetricsClient::new(
149 self.calls.clone(),
150 self.channel(address)?,
151 ))
152 }
153
154 pub fn control(&self, address: &Address) -> Result<ControlClient, ClientError> {
156 Ok(ControlClient::new(
157 self.calls.clone(),
158 self.channel(address)?,
159 ))
160 }
161
162 fn endpoint(&self, address: &Address) -> Result<Endpoint, ClientError> {
164 let config = &self.calls.settings.channel;
165 let mut endpoint = Endpoint::from_shared(address.uri())
166 .map_err(|error| ClientError::from(Status::invalid_argument(error.to_string())))?;
167 if let Some(window) = config.stream_window_size() {
168 endpoint = endpoint.initial_stream_window_size(window.min(u64::from(u32::MAX)) as u32);
170 }
171 if let Some(keep_alive) = config.keep_alive() {
172 endpoint = endpoint
173 .http2_keep_alive_interval(keep_alive.ping_delay())
174 .keep_alive_timeout(keep_alive.ping_timeout())
175 .keep_alive_while_idle(
176 keep_alive.policy() == crate::config::KeepAlivePolicy::WhileIdle,
177 );
178 }
179 Ok(endpoint)
180 }
181}
182
183impl Calls {
184 pub(crate) fn prepare<T>(
187 &self,
188 mut request: Request<T>,
189 context: &CallContext,
190 streaming: bool,
191 ) -> (Request<T>, Duration, TraceIds) {
192 let default = if streaming {
193 self.settings.stream_timeout
194 } else {
195 self.settings.unary_timeout
196 };
197 let timeout = context
198 .remaining()
199 .map_or(default, |left| left.min(default));
200 let trace = TraceIds::child(context.trace().trace, context.trace().sampled);
201 request.set_timeout(timeout);
202 let metadata = request.metadata_mut();
203 metadata.insert(
204 tonic::metadata::MetadataKey::from_static(CORRELATION_HEADER),
205 context
206 .correlation_id()
207 .parse()
208 .unwrap_or_else(|_| tonic::metadata::MetadataValue::from_static("invalid")),
209 );
210 if let Ok(level) = context.outgoing_chain_level().to_string().parse() {
211 metadata.insert(
212 tonic::metadata::MetadataKey::from_static(CHAIN_LEVEL_HEADER),
213 level,
214 );
215 }
216 if !self.settings.instance_id.is_empty()
217 && let Ok(value) = self.settings.instance_id.parse()
218 {
219 metadata.insert(
220 tonic::metadata::MetadataKey::from_static(INSTANCE_HEADER),
221 value,
222 );
223 }
224 if let Ok(value) = trace.traceparent().parse() {
225 metadata.insert(
226 tonic::metadata::MetadataKey::from_static(TRACEPARENT_HEADER),
227 value,
228 );
229 }
230 for entry in context.transit().iter() {
231 match entry {
232 KeyAndValueRef::Ascii(key, value) => {
233 if !metadata.contains_key(key) {
234 metadata.insert(key.clone(), value.clone());
235 }
236 }
237 KeyAndValueRef::Binary(key, value) => {
238 if !metadata.contains_key(key) {
239 metadata.insert_bin(key.clone(), value.clone());
240 }
241 }
242 }
243 }
244 (request, timeout, trace)
245 }
246
247 pub(crate) async fn unary<T, F>(
249 &self,
250 method: &'static str,
251 context: &CallContext,
252 timeout: Duration,
253 trace: TraceIds,
254 future: F,
255 ) -> Result<Response<T>, ClientError>
256 where
257 F: Future<Output = Result<Response<T>, Status>>,
258 {
259 let started = Instant::now();
260 let _guard = self.load.begin();
261 let span = client_span(method, context, trace);
262 let token = context.token();
263 let outcome = async {
264 tokio::select! {
265 _ = token.cancelled() => Err(ClientError::from(Status::cancelled(
266 format!("the call to {method} is cancelled"),
267 ))),
268 result = tokio::time::timeout(timeout, future) => match result {
269 Ok(Ok(response)) => Ok(response),
270 Ok(Err(status)) => Err(ClientError::from(status)),
271 Err(_) => Err(ClientError::from(Status::deadline_exceeded(
272 format!("the call to {method} did not finish in {timeout:?}"),
273 ))),
274 },
275 }
276 }
277 .instrument(span.clone())
278 .await;
279 self.settle(method, &span, started, &outcome);
280 outcome
281 }
282
283 pub(crate) async fn streaming<S, F>(
285 &self,
286 method: &'static str,
287 context: &CallContext,
288 timeout: Duration,
289 trace: TraceIds,
290 future: F,
291 ) -> Result<GuardedStream<tonic::Streaming<S>>, ClientError>
292 where
293 F: Future<Output = Result<Response<tonic::Streaming<S>>, Status>>,
294 {
295 let started = Instant::now();
296 let guard = self.load.begin();
297 let span = client_span(method, context, trace);
298 let deadline = Instant::now().checked_add(timeout);
299 let token = context.token();
300 let outcome = async {
301 tokio::select! {
302 _ = token.cancelled() => Err(ClientError::from(Status::cancelled(
303 format!("the call to {method} is cancelled"),
304 ))),
305 result = tokio::time::timeout(timeout, future) => match result {
306 Ok(Ok(response)) => Ok(response),
307 Ok(Err(status)) => Err(ClientError::from(status)),
308 Err(_) => Err(ClientError::from(Status::deadline_exceeded(
309 format!("the call to {method} did not start in {timeout:?}"),
310 ))),
311 },
312 }
313 }
314 .instrument(span.clone())
315 .await;
316 self.settle(method, &span, started, &outcome);
317 let response = outcome?;
318 Ok(GuardedStream::new(
319 response.into_inner(),
320 guard,
321 span,
322 deadline,
323 context.token(),
324 ))
325 }
326
327 fn settle<T>(
329 &self,
330 method: &'static str,
331 span: &tracing::Span,
332 started: Instant,
333 outcome: &Result<Response<T>, ClientError>,
334 ) {
335 let elapsed = started.elapsed();
336 let elapsed_ms = u64::try_from(elapsed.as_millis()).unwrap_or(u64::MAX);
337 match outcome {
338 Ok(_) => {
339 span.record("grpc.code", "OK");
340 }
341 Err(error) => {
342 span.record("grpc.code", code_name(error.code()));
343 span.in_scope(|| self.log.failed(method, error));
344 }
345 }
346 span.record("elapsed_ms", elapsed_ms);
347 }
348}
349
350fn client_span(method: &'static str, context: &CallContext, trace: TraceIds) -> tracing::Span {
352 tracing::info_span!(
353 "grpc.client",
354 rpc.method = method,
355 grpc.code = tracing::field::Empty,
356 elapsed_ms = tracing::field::Empty,
357 correlation_id = context.correlation_id(),
358 trace_id = hex(&trace.trace).as_str(),
359 span_id = hex8(&trace.span).as_str(),
360 )
361}
362
363fn hex(bytes: &[u8; 16]) -> String {
364 let mut text = String::with_capacity(32);
365 for byte in bytes {
366 text.push_str(&format!("{byte:02x}"));
367 }
368 text
369}
370
371fn hex8(bytes: &[u8; 8]) -> String {
372 let mut text = String::with_capacity(16);
373 for byte in bytes {
374 text.push_str(&format!("{byte:02x}"));
375 }
376 text
377}
378
379fn lock<T>(mutex: &Mutex<T>) -> MutexGuard<'_, T> {
380 mutex
381 .lock()
382 .unwrap_or_else(|poisoned| poisoned.into_inner())
383}
384
385#[cfg(test)]
386mod tests {
387 use std::sync::Arc;
388
389 use redup_primitives::Address;
390
391 use super::{ClientFactory, Settings};
392 use crate::load::NoLoad;
393
394 #[test]
395 fn the_factory_rejects_tls_addresses() {
396 let factory = ClientFactory::new(Settings::default(), Arc::new(NoLoad));
397 let error = factory
398 .channel(&Address::parse("grpcs://example.com").expect("the address"))
399 .expect_err("TLS is not supported");
400 assert_eq!(error.code(), tonic::Code::FailedPrecondition);
401 }
402
403 #[tokio::test]
404 async fn the_same_address_shares_one_channel() {
405 let factory = ClientFactory::new(Settings::default(), Arc::new(NoLoad));
406 let address = Address::parse("127.0.0.1:4200").expect("the address");
407 factory.channel(&address).expect("the channel");
408 factory.channel(&address).expect("the cached channel");
409 }
410}