#[cfg(feature = "host")]
use super::HostCacheError;
#[cfg(feature = "host")]
use std::path::Path;
#[cfg(feature = "subnet-catalog-host")]
use std::path::PathBuf;
#[derive(Clone, Debug, Eq, PartialEq)]
#[cfg(feature = "subnet-catalog-host")]
pub enum CacheRefreshReason {
Missing(PathBuf),
#[cfg(feature = "host")]
Stale,
Invalid(PathBuf),
}
#[cfg(feature = "host")]
pub fn load_or_refresh_missing_cache<T, Error>(
mut load: impl FnMut() -> Result<T, Error>,
missing_path: impl FnOnce(Error) -> Result<PathBuf, Error>,
refresh: impl FnOnce(&Path) -> Result<(), Error>,
) -> Result<T, Error> {
match load() {
Ok(cached) => Ok(cached),
Err(err) => {
let path = missing_path(err)?;
refresh(&path)?;
load()
}
}
}
#[cfg(feature = "subnet-catalog-host")]
pub fn load_or_refresh_cache_with_error_policy<T, Error>(
mut load: impl FnMut() -> Result<T, Error>,
refresh_reason: impl FnOnce(Error) -> Result<CacheRefreshReason, Error>,
refresh: impl FnOnce(CacheRefreshReason) -> Result<(), Error>,
) -> Result<T, Error> {
match load() {
Ok(cached) => Ok(cached),
Err(error) => {
refresh(refresh_reason(error)?)?;
load()
}
}
}
#[cfg(feature = "host")]
pub fn load_or_refresh_stale_cache_with_error_policy<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> {
match load() {
Ok(cached) if !stale(&cached) => Ok(cached),
Ok(_) => {
refresh(CacheRefreshReason::Stale)?;
load()
}
Err(err) => {
refresh(refresh_reason(err)?)?;
load()
}
}
}
#[cfg(feature = "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, .. } => {
Ok(CacheRefreshReason::Invalid(path))
}
HostCacheError::UnsupportedCacheSchemaVersion { .. }
| HostCacheError::NetworkMismatch { .. } => {
Ok(CacheRefreshReason::Invalid(expected_path.to_path_buf()))
}
error => Err(error),
}
}