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