use crate::{GroupcacheInner, GroupcachePeer, ValueBounds};
use async_trait::async_trait;
use log::error;
use std::collections::HashSet;
use std::error::Error;
use std::sync::Weak;
use std::time::Duration;
#[async_trait]
pub trait ServiceDiscovery: Send {
async fn pull_instances(
&self,
) -> Result<HashSet<GroupcachePeer>, Box<dyn Error + Send + Sync + 'static>>;
fn interval(&self) -> Duration {
Duration::from_secs(10)
}
}
pub(crate) async fn run_service_discovery<Value: ValueBounds>(
cache: Weak<GroupcacheInner<Value>>,
service_discovery: Box<dyn ServiceDiscovery>,
) {
while let Some(cache) = cache.upgrade() {
tokio::time::sleep(service_discovery.interval()).await;
match service_discovery.pull_instances().await {
Ok(instances) => {
if let Err(error) = cache.set_peers(instances).await {
error!("Error connecting to refreshed instances: {}", error);
};
}
Err(error) => {
error!("Error during when refreshing instances: {}", error);
}
}
}
}