#[cfg(any(
feature = "dashboard-host",
feature = "icrc-host",
feature = "nns-topology-host",
feature = "sns-host"
))]
use super::HostCacheError;
#[cfg(any(
feature = "dashboard-host",
feature = "icrc-host",
feature = "nns-topology-host",
feature = "sns-host"
))]
use std::path::Path;
#[cfg(any(
feature = "dashboard-host",
feature = "icrc-host",
feature = "nns-topology-host",
feature = "sns-host"
))]
use std::path::PathBuf;
#[derive(Clone, Debug, Eq, PartialEq)]
#[cfg(any(
feature = "dashboard-host",
feature = "icrc-host",
feature = "nns-topology-host",
feature = "sns-host"
))]
pub enum CacheRefreshReason {
Missing(PathBuf),
Stale,
Invalid(PathBuf),
}
#[cfg(any(
feature = "dashboard-host",
feature = "icrc-host",
feature = "nns-topology-host",
feature = "sns-host"
))]
pub fn load_or_refresh_cache<T, Error>(
mut load: impl FnMut() -> Result<T, Error>,
stale: impl FnOnce(&T) -> bool,
refresh_reason: impl FnOnce(Error) -> Result<CacheRefreshReason, Error>,
refresh: impl FnOnce(CacheRefreshReason) -> Result<(), Error>,
) -> Result<T, Error> {
let reason = match load() {
Ok(cached) if !stale(&cached) => return Ok(cached),
Ok(_) => CacheRefreshReason::Stale,
Err(error) => refresh_reason(error)?,
};
refresh(reason)?;
load()
}
#[cfg(any(
feature = "dashboard-host",
feature = "icrc-host",
feature = "nns-topology-host",
feature = "sns-host"
))]
pub fn host_cache_refresh_reason(
error: HostCacheError,
expected_path: &Path,
) -> Result<CacheRefreshReason, HostCacheError> {
match error {
HostCacheError::MissingCache { path, .. } => Ok(CacheRefreshReason::Missing(path)),
HostCacheError::ParseCache { path, .. }
| HostCacheError::InvalidCache { path, .. }
| HostCacheError::CacheTooLarge { path, .. } => Ok(CacheRefreshReason::Invalid(path)),
HostCacheError::UnsupportedCacheSchemaVersion { .. }
| HostCacheError::NetworkMismatch { .. } => {
Ok(CacheRefreshReason::Invalid(expected_path.to_path_buf()))
}
error => Err(error),
}
}