redup_bootstrap/dependency/
init.rs1use std::future::Future;
4use std::pin::Pin;
5use std::sync::Arc;
6
7use crate::error::ModuleError;
8use crate::init_policy::InitPolicy;
9
10type Run =
12 Arc<dyn Fn() -> Pin<Box<dyn Future<Output = Result<(), ModuleError>> + Send>> + Send + Sync>;
13
14pub struct Init {
20 run: Run,
21 policy: InitPolicy,
22}
23
24impl Init {
25 pub fn once<F, Fut>(run: F) -> Self
27 where
28 F: Fn() -> Fut + Send + Sync + 'static,
29 Fut: Future<Output = Result<(), ModuleError>> + Send + 'static,
30 {
31 Self::with_policy(run, InitPolicy::Once)
32 }
33
34 pub fn each_reconnect<F, Fut>(run: F) -> Self
36 where
37 F: Fn() -> Fut + Send + Sync + 'static,
38 Fut: Future<Output = Result<(), ModuleError>> + Send + 'static,
39 {
40 Self::with_policy(run, InitPolicy::OnEachReconnect)
41 }
42
43 pub(crate) fn policy(&self) -> InitPolicy {
45 self.policy
46 }
47
48 pub(crate) async fn execute(&self) -> Result<(), ModuleError> {
50 (self.run)().await
51 }
52
53 fn with_policy<F, Fut>(run: F, policy: InitPolicy) -> Self
55 where
56 F: Fn() -> Fut + Send + Sync + 'static,
57 Fut: Future<Output = Result<(), ModuleError>> + Send + 'static,
58 {
59 Self {
60 run: Arc::new(move || Box::pin(run())),
61 policy,
62 }
63 }
64}
65
66impl std::fmt::Debug for Init {
67 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
68 f.debug_struct("Init")
69 .field("policy", &self.policy)
70 .finish()
71 }
72}