use std::future::Future;
use std::pin::Pin;
use std::sync::Arc;
use redup_abstractions::{Attempt, Observation, Probe, ProbeSettings};
use tokio::sync::watch;
use tokio_util::sync::CancellationToken;
use crate::error::ModuleError;
type Check = Arc<
dyn Fn(Attempt) -> Pin<Box<dyn Future<Output = Result<bool, ModuleError>> + Send>>
+ Send
+ Sync,
>;
pub struct CustomProbe {
check: Check,
}
impl CustomProbe {
pub fn new<F, Fut>(check: F) -> Self
where
F: Fn(Attempt) -> Fut + Send + Sync + 'static,
Fut: Future<Output = Result<bool, ModuleError>> + Send + 'static,
{
Self {
check: Arc::new(move |attempt| Box::pin(check(attempt))),
}
}
async fn attempt(&self, settings: &ProbeSettings, token: &CancellationToken) -> Observation {
let attempt_token = token.child_token();
let check = (self.check)(Attempt::new(settings.timeout(), attempt_token));
match tokio::time::timeout(settings.timeout(), check).await {
Ok(Ok(true)) => Observation::up(),
Ok(Ok(false)) => Observation::down("neighbor replied that it is not ready"),
Ok(Err(error)) => Observation::down(error.to_string()),
Err(_elapsed) => Observation::down("check did not finish within the timeout"),
}
}
}
#[async_trait::async_trait]
impl Probe for CustomProbe {
async fn run(
&self,
settings: &ProbeSettings,
states: watch::Sender<Observation>,
token: CancellationToken,
) {
loop {
if token.is_cancelled() {
return;
}
let observation = self.attempt(settings, &token).await;
if let Some(text) = observation.error() {
tracing::debug!(error = text, "neighbor check attempt failed");
}
states.send_if_modified(|current| {
if *current == observation {
false
} else {
*current = observation.clone();
true
}
});
if token.is_cancelled() {
return;
}
tokio::select! {
_ = token.cancelled() => return,
_ = tokio::time::sleep(settings.pull_delay()) => {}
}
}
}
}
impl std::fmt::Debug for CustomProbe {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("CustomProbe").finish_non_exhaustive()
}
}