use std::fmt;
use std::path::PathBuf;
use typed_builder::TypedBuilder;
#[cfg(persistent_cache)]
use crate::error::{Error, Result};
#[cfg(persistent_cache)]
const PERSISTENT_BACKEND_COUNT: usize = cfg!(feature = "cache-json") as usize
+ cfg!(feature = "cache-redb") as usize
+ cfg!(feature = "cache-redis") as usize;
#[cfg(persistent_cache)]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum PersistentBackendKind {
#[cfg(feature = "cache-json")]
Json,
#[cfg(feature = "cache-redb")]
Redb,
#[cfg(feature = "cache-redis")]
Redis,
}
#[cfg(persistent_cache)]
impl PersistentBackendKind {
pub fn resolve(kind: Option<Self>) -> Result<Self> {
if let Some(k) = kind {
return Ok(k);
}
if PERSISTENT_BACKEND_COUNT > 1 {
return Err(Error::ambiguous_cache_backend(PERSISTENT_BACKEND_COUNT));
}
#[cfg(feature = "cache-json")]
let backend = Self::Json;
#[cfg(all(feature = "cache-redb", not(feature = "cache-json")))]
let backend = Self::Redb;
#[cfg(all(feature = "cache-redis", not(feature = "cache-json"), not(feature = "cache-redb")))]
let backend = Self::Redis;
Ok(backend)
}
}
#[cfg(persistent_cache)]
impl fmt::Display for PersistentBackendKind {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
#[cfg(feature = "cache-json")]
Self::Json => f.write_str("Json"),
#[cfg(feature = "cache-redb")]
Self::Redb => f.write_str("Redb"),
#[cfg(feature = "cache-redis")]
Self::Redis => f.write_str("Redis"),
}
}
}
#[derive(Debug, Clone, TypedBuilder)]
pub struct CacheConfig {
pub cache_dir: PathBuf,
#[builder(default)]
pub redis_url: Option<String>,
#[builder(default)]
pub video_ttl: Option<u64>,
#[builder(default)]
pub playlist_ttl: Option<u64>,
#[builder(default)]
pub download_ttl: Option<u64>,
#[cfg(persistent_cache)]
#[builder(default)]
pub persistent_backend: Option<PersistentBackendKind>,
}
impl fmt::Display for CacheConfig {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
f,
"CacheConfig(dir={:?}, redis={}, video_ttl={:?}, playlist_ttl={:?}, download_ttl={:?}",
self.cache_dir,
self.redis_url.as_deref().unwrap_or("none"),
self.video_ttl,
self.playlist_ttl,
self.download_ttl,
)?;
#[cfg(persistent_cache)]
write!(
f,
", backend={}",
self.persistent_backend.map_or("auto".to_string(), |k| k.to_string()),
)?;
f.write_str(")")
}
}