use std::time::Duration;
use crate::request_context::RequestContext;
pub const DEFAULT_TIMEOUT: Duration = Duration::from_secs(30);
#[derive(Debug, Clone, Default)]
pub struct TlsConfig {
pub domain_name: Option<String>,
pub ca_certificate_pem: Option<Vec<u8>>,
pub client_identity_pem: Option<(Vec<u8>, Vec<u8>)>,
}
impl TlsConfig {
#[must_use]
pub fn new() -> Self {
Self::default()
}
#[must_use]
pub fn with_domain_name(mut self, name: impl Into<String>) -> Self {
self.domain_name = Some(name.into());
self
}
#[must_use]
pub fn with_ca_certificate_pem(mut self, pem: impl Into<Vec<u8>>) -> Self {
self.ca_certificate_pem = Some(pem.into());
self
}
#[must_use]
pub fn with_client_identity_pem(
mut self,
certificate: impl Into<Vec<u8>>,
key: impl Into<Vec<u8>>,
) -> Self {
self.client_identity_pem = Some((certificate.into(), key.into()));
self
}
}
#[derive(Debug, Clone)]
pub struct ClientConfig {
pub endpoint: String,
pub default_timeout: Duration,
pub connect_timeout: Option<Duration>,
pub max_decoding_message_size: Option<usize>,
pub max_encoding_message_size: Option<usize>,
pub default_context: RequestContext,
pub tls: Option<TlsConfig>,
pub metadata: Vec<(String, String)>,
}
impl ClientConfig {
#[must_use]
pub fn new(endpoint: impl Into<String>) -> Self {
Self {
endpoint: endpoint.into(),
default_timeout: DEFAULT_TIMEOUT,
connect_timeout: Some(Duration::from_secs(10)),
max_decoding_message_size: Some(16 * 1024 * 1024),
max_encoding_message_size: Some(16 * 1024 * 1024),
default_context: RequestContext::new(),
tls: None,
metadata: Vec::new(),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn defaults_are_sane() {
let config = ClientConfig::new("http://127.0.0.1:50051");
assert_eq!(config.endpoint, "http://127.0.0.1:50051");
assert_eq!(config.default_timeout, DEFAULT_TIMEOUT);
assert!(config.tls.is_none());
assert!(config.default_context.is_empty());
assert!(config.max_decoding_message_size.is_some());
assert!(config.metadata.is_empty());
}
#[test]
fn tls_config_builders_set_fields() {
let tls = TlsConfig::new()
.with_domain_name("example.com")
.with_ca_certificate_pem(b"ca-pem".to_vec())
.with_client_identity_pem(b"cert".to_vec(), b"key".to_vec());
assert_eq!(tls.domain_name.as_deref(), Some("example.com"));
assert_eq!(tls.ca_certificate_pem.as_deref(), Some(&b"ca-pem"[..]));
let (cert, key) = tls.client_identity_pem.expect("identity set");
assert_eq!(cert, b"cert");
assert_eq!(key, b"key");
}
}