use std::future::Future;
use std::pin::Pin;
use std::sync::Arc;
use std::time::Duration;
use rustls::pki_types::CertificateDer;
use rustls::pki_types::pem::PemObject;
use crate::error::Error;
pub type TokenResult = Result<String, String>;
#[derive(Clone)]
pub struct TokenProvider(
Arc<dyn Fn() -> Pin<Box<dyn Future<Output = TokenResult> + Send>> + Send + Sync>,
);
impl TokenProvider {
pub fn fetch(&self) -> Pin<Box<dyn Future<Output = TokenResult> + Send>> {
(self.0)()
}
}
impl std::fmt::Debug for TokenProvider {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str("TokenProvider")
}
}
impl PartialEq for TokenProvider {
fn eq(&self, other: &Self) -> bool {
Arc::ptr_eq(&self.0, &other.0)
}
}
impl Eq for TokenProvider {}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Credentials {
Password {
username: String,
password: String,
},
Token(String),
Provider(TokenProvider),
}
impl Credentials {
pub fn password(username: impl Into<String>, password: impl Into<String>) -> Self {
Credentials::Password {
username: username.into(),
password: password.into(),
}
}
pub fn provider<F, Fut, E>(fetch: F) -> Self
where
F: Fn() -> Fut + Send + Sync + 'static,
Fut: Future<Output = Result<String, E>> + Send + 'static,
E: std::fmt::Display,
{
Credentials::Provider(TokenProvider(Arc::new(move || {
let fetched = fetch();
Box::pin(async move { fetched.await.map_err(|e| e.to_string()) })
})))
}
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub enum AckMode {
#[default]
Auto,
Manual,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ReconnectPolicy {
pub initial: Duration,
pub max: Duration,
pub max_attempts: Option<u32>,
}
impl Default for ReconnectPolicy {
fn default() -> Self {
Self {
initial: Duration::from_millis(250),
max: Duration::from_secs(30),
max_attempts: None,
}
}
}
impl ReconnectPolicy {
pub fn ceiling(&self, attempt: u32) -> Duration {
let factor = 2u32.saturating_pow(attempt.min(30));
self.initial.saturating_mul(factor).min(self.max)
}
}
#[derive(Debug, Clone)]
pub struct ClientConfig {
pub url: String,
pub credentials: Credentials,
pub session_id: Option<String>,
pub clean_start: bool,
pub ack_mode: AckMode,
pub reconnect: ReconnectPolicy,
pub request_timeout: Duration,
pub subscription_buffer: usize,
pub(crate) extra_roots: Vec<CertificateDer<'static>>,
}
impl ClientConfig {
pub fn new(url: impl Into<String>, credentials: Credentials) -> Self {
Self {
url: url.into(),
credentials,
session_id: None,
clean_start: false,
ack_mode: AckMode::Auto,
reconnect: ReconnectPolicy::default(),
request_timeout: Duration::from_secs(30),
subscription_buffer: 1024,
extra_roots: Vec::new(),
}
}
pub fn add_root_certificates_pem(mut self, pem: &[u8]) -> Result<Self, Error> {
let certificates = CertificateDer::pem_slice_iter(pem)
.collect::<Result<Vec<_>, _>>()
.map_err(|e| Error::Config(format!("the certificate isn't valid PEM: {e}")))?;
if certificates.is_empty() {
return Err(Error::Config("no certificate found".to_string()));
}
self.extra_roots.extend(certificates);
Ok(self)
}
pub fn session(mut self, session_id: impl Into<String>) -> Self {
self.session_id = Some(session_id.into());
self
}
pub fn ack_mode(mut self, ack_mode: AckMode) -> Self {
self.ack_mode = ack_mode;
self
}
pub fn reconnect(mut self, reconnect: ReconnectPolicy) -> Self {
self.reconnect = reconnect;
self
}
pub fn request_timeout(mut self, timeout: Duration) -> Self {
self.request_timeout = timeout;
self
}
}