use crate::errors::HandlerResult;
use crate::serde::{Deserialize, Serialize};
use std::future::Future;
use std::time::Duration;
pub trait RunClosure {
type Output: Deserialize + Serialize + 'static;
type Fut: Future<Output = HandlerResult<Self::Output>>;
fn run(self) -> Self::Fut;
}
impl<F, O, Fut> RunClosure for F
where
F: FnOnce() -> Fut,
Fut: Future<Output = HandlerResult<O>>,
O: Deserialize + Serialize + 'static,
{
type Output = O;
type Fut = Fut;
fn run(self) -> Self::Fut {
self()
}
}
pub trait RunFuture<O>: Future<Output = O> {
fn retry_policy(self, retry_policy: RunRetryPolicy) -> Self;
fn name(self, name: impl Into<String>) -> Self;
}
#[derive(Debug, Clone)]
pub struct RunRetryPolicy {
pub(crate) initial_delay: Duration,
pub(crate) factor: f32,
pub(crate) max_delay: Option<Duration>,
pub(crate) max_attempts: Option<u32>,
pub(crate) max_duration: Option<Duration>,
}
impl Default for RunRetryPolicy {
fn default() -> Self {
Self {
initial_delay: Duration::from_millis(100),
factor: 2.0,
max_delay: Some(Duration::from_secs(2)),
max_attempts: None,
max_duration: Some(Duration::from_secs(50)),
}
}
}
impl RunRetryPolicy {
pub fn new() -> Self {
Self {
initial_delay: Duration::from_millis(100),
factor: 1.0,
max_delay: None,
max_attempts: None,
max_duration: None,
}
}
pub fn initial_delay(mut self, initial_interval: Duration) -> Self {
self.initial_delay = initial_interval;
self
}
pub fn exponentiation_factor(mut self, factor: f32) -> Self {
self.factor = factor;
self
}
pub fn max_delay(mut self, max_interval: Duration) -> Self {
self.max_delay = Some(max_interval);
self
}
pub fn max_attempts(mut self, max_attempts: u32) -> Self {
self.max_attempts = Some(max_attempts);
self
}
pub fn max_duration(mut self, max_duration: Duration) -> Self {
self.max_duration = Some(max_duration);
self
}
}