redup_bootstrap/dependency/
custom_probe.rs1use std::future::Future;
4use std::pin::Pin;
5use std::sync::Arc;
6
7use redup_abstractions::{Attempt, Observation, Probe, ProbeSettings};
8use tokio::sync::watch;
9use tokio_util::sync::CancellationToken;
10
11use crate::error::ModuleError;
12
13type Check = Arc<
16 dyn Fn(Attempt) -> Pin<Box<dyn Future<Output = Result<bool, ModuleError>> + Send>>
17 + Send
18 + Sync,
19>;
20
21pub struct CustomProbe {
28 check: Check,
29}
30
31impl CustomProbe {
32 pub fn new<F, Fut>(check: F) -> Self
34 where
35 F: Fn(Attempt) -> Fut + Send + Sync + 'static,
36 Fut: Future<Output = Result<bool, ModuleError>> + Send + 'static,
37 {
38 Self {
39 check: Arc::new(move |attempt| Box::pin(check(attempt))),
40 }
41 }
42
43 async fn attempt(&self, settings: &ProbeSettings, token: &CancellationToken) -> Observation {
45 let attempt_token = token.child_token();
46 let check = (self.check)(Attempt::new(settings.timeout(), attempt_token));
47 match tokio::time::timeout(settings.timeout(), check).await {
48 Ok(Ok(true)) => Observation::up(),
49 Ok(Ok(false)) => Observation::down("neighbor replied that it is not ready"),
50 Ok(Err(error)) => Observation::down(error.to_string()),
51 Err(_elapsed) => Observation::down("check did not finish within the timeout"),
52 }
53 }
54}
55
56#[async_trait::async_trait]
57impl Probe for CustomProbe {
58 async fn run(
59 &self,
60 settings: &ProbeSettings,
61 states: watch::Sender<Observation>,
62 token: CancellationToken,
63 ) {
64 loop {
66 if token.is_cancelled() {
67 return;
68 }
69 let observation = self.attempt(settings, &token).await;
70 if let Some(text) = observation.error() {
71 tracing::debug!(error = text, "neighbor check attempt failed");
72 }
73 states.send_if_modified(|current| {
74 if *current == observation {
75 false
76 } else {
77 *current = observation.clone();
78 true
79 }
80 });
81 if token.is_cancelled() {
82 return;
83 }
84 tokio::select! {
85 _ = token.cancelled() => return,
86 _ = tokio::time::sleep(settings.pull_delay()) => {}
87 }
88 }
89 }
90}
91
92impl std::fmt::Debug for CustomProbe {
93 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
94 f.debug_struct("CustomProbe").finish_non_exhaustive()
95 }
96}