use std::future::Future;
use std::pin::Pin;
use std::sync::Arc;
use crate::error::ModuleError;
use crate::init_policy::InitPolicy;
type Run =
Arc<dyn Fn() -> Pin<Box<dyn Future<Output = Result<(), ModuleError>> + Send>> + Send + Sync>;
pub struct Init {
run: Run,
policy: InitPolicy,
}
impl Init {
pub fn once<F, Fut>(run: F) -> Self
where
F: Fn() -> Fut + Send + Sync + 'static,
Fut: Future<Output = Result<(), ModuleError>> + Send + 'static,
{
Self::with_policy(run, InitPolicy::Once)
}
pub fn each_reconnect<F, Fut>(run: F) -> Self
where
F: Fn() -> Fut + Send + Sync + 'static,
Fut: Future<Output = Result<(), ModuleError>> + Send + 'static,
{
Self::with_policy(run, InitPolicy::OnEachReconnect)
}
pub(crate) fn policy(&self) -> InitPolicy {
self.policy
}
pub(crate) async fn execute(&self) -> Result<(), ModuleError> {
(self.run)().await
}
fn with_policy<F, Fut>(run: F, policy: InitPolicy) -> Self
where
F: Fn() -> Fut + Send + Sync + 'static,
Fut: Future<Output = Result<(), ModuleError>> + Send + 'static,
{
Self {
run: Arc::new(move || Box::pin(run())),
policy,
}
}
}
impl std::fmt::Debug for Init {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Init")
.field("policy", &self.policy)
.finish()
}
}