use {
super::*,
backon::{ExponentialBuilder, Retryable},
tokio::sync::Mutex,
};
async fn fetch_for<T, P>(client: Client, base: Url, path: String, parse: P) -> (Url, Result<T>)
where
P: FnOnce(&str) -> Result<T> + Send + 'static,
{
let result = async {
let url = base.join(&path)?;
let body = fetch(&client, url).await?;
parse(&body)
}
.await;
(base, result)
}
async fn fetch(client: &Client, url: Url) -> Result<String> {
let started = Instant::now();
let backoff = ExponentialBuilder::default()
.with_min_delay(Duration::from_millis(300))
.with_max_delay(Duration::from_secs(3))
.with_jitter()
.with_max_times(MAX_ATTEMPTS)
.with_total_delay(Some(BUDGET));
let fetch = || async {
let now = Instant::now();
let elapsed = now.saturating_duration_since(started);
if elapsed >= BUDGET {
return Err(anyhow!("deadline exceeded"));
}
let remaining = BUDGET - elapsed;
let this_try = remaining.min(TIMEOUT);
let body = tokio::time::timeout(this_try, async {
let response = client.get(url.clone()).send().await?;
if let Err(status_err) = response.error_for_status_ref() {
let text = response.text().await.unwrap_or_default();
return Err(anyhow!("{status_err}: {text}").context(status_err));
}
let text = response.text().await?;
Ok::<String, Error>(text)
})
.await
.map_err(|_| anyhow::anyhow!("try timeout"))??;
Ok::<String, Error>(body)
};
let body = fetch
.retry(backoff)
.sleep(tokio::time::sleep)
.when(|err: &Error| {
if let Some(err) = err.downcast_ref::<reqwest::Error>() {
if let Some(status) = err.status() {
return status == StatusCode::TOO_MANY_REQUESTS || status.is_server_error();
}
return true;
}
!err.to_string().contains("deadline exceeded")
})
.notify(|err: &Error, duration: Duration| {
tracing::debug!(?err, ?duration, "retrying after backoff");
})
.await?;
Ok(body)
}
#[derive(Debug)]
struct Cached<T> {
value: Option<T>,
last_updated: Option<Instant>,
}
impl<T: Clone> Cached<T> {
fn init() -> Self {
Self {
value: None,
last_updated: None,
}
}
fn new(value: Option<T>) -> Self {
Self {
value,
last_updated: Some(Instant::now()),
}
}
fn is_fresh(&self, ttl: Duration) -> bool {
self.last_updated
.is_some_and(|last_updated| last_updated.elapsed() < ttl)
}
fn value(&self) -> Option<T> {
self.value.clone()
}
}
#[derive(Debug)]
pub(super) struct Cache {
client: Client,
config: Arc<ServerConfig>,
database: Option<Database>,
pool_status: Mutex<Cached<ckpool::Status>>,
user_statuses: DashMap<String, Arc<Mutex<Cached<ckpool::User>>>>,
users: Mutex<Cached<Vec<String>>>,
bestevers: DashMap<String, (i32, f64)>,
}
impl Cache {
pub(super) fn new(
client: Client,
config: Arc<ServerConfig>,
database: Option<Database>,
) -> Self {
Self {
client,
config: config.clone(),
database,
pool_status: Mutex::new(Cached::init()),
user_statuses: DashMap::new(),
users: Mutex::new(Cached::init()),
bestevers: DashMap::new(),
}
}
pub(super) async fn pool_status(&self) -> Result<Option<ckpool::Status>> {
let mut cached = self.pool_status.lock().await;
if cached.is_fresh(self.config.ttl()) {
return Ok(cached.value());
}
let fetches: FuturesUnordered<_> = self
.config
.nodes()
.into_iter()
.map(|base| {
fetch_for(
self.client.clone(),
base,
"/pool/pool.status".into(),
ckpool::Status::from_str,
)
})
.collect();
let mut aggregated = fetches
.fold(None, |acc, (base, res)| async move {
match res {
Ok(status) => Some(match acc {
Some(a) => a + status,
None => status,
}),
Err(err) => {
let host = base.host_str().unwrap_or("unknown");
warn!("Failed to fetch pool status from {host} with: {err}");
acc
}
}
})
.await;
if aggregated.is_none() {
error!("Failed to aggregate pool statistics");
}
if let (Some(status), Some(database)) = (aggregated.as_mut(), self.database.as_ref()) {
match database.get_current_round_bestshare().await {
Ok(Some(best)) => status.shares.bestshare = best as u64,
Ok(None) => status.shares.bestshare = 0,
Err(err) => warn!("Failed to load round bestshare from database: {err}"),
}
}
*cached = Cached::new(aggregated);
Ok(aggregated)
}
pub(super) async fn user_status(&self, address: String) -> Result<Option<ckpool::User>> {
let cell = self
.user_statuses
.entry(address.clone())
.or_insert_with(|| Arc::new(Mutex::new(Cached::init())))
.clone();
let mut cached = cell.lock().await;
if cached.is_fresh(self.config.ttl()) {
return Ok(cached.value());
}
let fetches: FuturesUnordered<_> = self
.config
.nodes()
.into_iter()
.map(|base| {
fetch_for(
self.client.clone(),
base,
format!("/users/{address}"),
|user| serde_json::from_str::<ckpool::User>(user).map_err(Into::into),
)
})
.collect();
let now = SystemTime::now()
.duration_since(UNIX_EPOCH)
.expect("system clock before unix epoch")
.as_secs();
let mut aggregated = fetches
.fold(None, |acc, (_, res)| async move {
match res {
Ok(status) => {
let status = status.zero_stale_hashrates(now, STALE_THRESHOLD);
Some(match acc {
Some(a) => a + status,
None => status,
})
}
Err(_) => acc,
}
})
.await;
if aggregated.is_none() {
error!("Failed to find user {address} on any node");
}
if let (Some(user), Some(database)) = (aggregated.as_mut(), self.database.as_ref()) {
match database.get_current_round_bestshare_by_user(&address).await {
Ok(best) => user.bestshare = best.unwrap_or(0.0),
Err(err) => {
warn!("Failed to load round bestshare for {address} from database: {err}")
}
}
let (after, history_best) = self
.bestevers
.get(&address)
.map(|entry| *entry)
.unwrap_or((0, 0.0));
match database.get_bestever_delta_by_user(&address, after).await {
Ok(delta) => {
let history_best = history_best.max(delta.history_best.unwrap_or(0.0));
if let Some(latest_round) = delta.latest_round {
self.bestevers
.insert(address.clone(), (after.max(latest_round), history_best));
}
let best = history_best.max(delta.current_best.unwrap_or(0.0));
user.bestever = user.bestever.max(best as u64);
}
Err(err) => {
warn!("Failed to load bestever for {address} from database: {err}")
}
}
}
*cached = Cached::new(aggregated.clone());
Ok(aggregated)
}
pub(super) async fn users(&self) -> Result<Option<Vec<String>>> {
let mut cached = self.users.lock().await;
if cached.is_fresh(self.config.ttl()) {
return Ok(cached.value());
}
let fetches: FuturesUnordered<_> = self
.config
.nodes()
.into_iter()
.map(|base| {
fetch_for(self.client.clone(), base, "/users".to_string(), |s| {
serde_json::from_str::<Vec<String>>(s).map_err(Into::into)
})
})
.collect();
let set = fetches
.fold(
HashSet::<String>::new(),
|mut acc, (base, res)| async move {
match res {
Ok(list) => acc.extend(list),
Err(err) => {
let host = base.host_str().unwrap_or("unknown");
warn!("Failed to fetch users from {host} with: {err}");
}
}
acc
},
)
.await;
let aggregated = if set.is_empty() {
error!("Failed aggregate users");
None
} else {
Some(set.into_iter().collect::<Vec<String>>())
};
*cached = Cached::new(aggregated.clone());
Ok(aggregated)
}
}