cache: add optional runtime cache contracts
This commit is contained in:
@@ -0,0 +1,180 @@
|
||||
use std::{env, num::ParseIntError};
|
||||
|
||||
use crank_core::CacheBackend;
|
||||
use thiserror::Error;
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct RuntimeCacheConfig {
|
||||
pub backend: CacheBackend,
|
||||
pub url: Option<String>,
|
||||
pub default_ttl_ms: Option<u64>,
|
||||
}
|
||||
|
||||
impl Default for RuntimeCacheConfig {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
backend: CacheBackend::Memory,
|
||||
url: None,
|
||||
default_ttl_ms: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl RuntimeCacheConfig {
|
||||
pub fn from_env() -> Result<Self, RuntimeCacheConfigError> {
|
||||
let backend = parse_backend()?;
|
||||
let url = parse_optional_string("CRANK_CACHE_URL")?;
|
||||
let default_ttl_ms = parse_optional_u64("CRANK_CACHE_DEFAULT_TTL_MS")?;
|
||||
|
||||
if backend.is_external() && url.is_none() {
|
||||
return Err(RuntimeCacheConfigError::MissingUrl { backend });
|
||||
}
|
||||
|
||||
Ok(Self {
|
||||
backend,
|
||||
url,
|
||||
default_ttl_ms,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
fn parse_backend() -> Result<CacheBackend, RuntimeCacheConfigError> {
|
||||
match env::var("CRANK_CACHE_BACKEND") {
|
||||
Ok(raw) => raw
|
||||
.parse::<CacheBackend>()
|
||||
.map_err(|source| RuntimeCacheConfigError::InvalidBackend { value: raw, source }),
|
||||
Err(env::VarError::NotPresent) => Ok(CacheBackend::Memory),
|
||||
Err(env::VarError::NotUnicode(_)) => Err(RuntimeCacheConfigError::InvalidUnicode {
|
||||
name: "CRANK_CACHE_BACKEND",
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
fn parse_optional_string(name: &'static str) -> Result<Option<String>, RuntimeCacheConfigError> {
|
||||
match env::var(name) {
|
||||
Ok(raw) => {
|
||||
let trimmed = raw.trim();
|
||||
if trimmed.is_empty() {
|
||||
Ok(None)
|
||||
} else {
|
||||
Ok(Some(trimmed.to_owned()))
|
||||
}
|
||||
}
|
||||
Err(env::VarError::NotPresent) => Ok(None),
|
||||
Err(env::VarError::NotUnicode(_)) => Err(RuntimeCacheConfigError::InvalidUnicode { name }),
|
||||
}
|
||||
}
|
||||
|
||||
fn parse_optional_u64(name: &'static str) -> Result<Option<u64>, RuntimeCacheConfigError> {
|
||||
match env::var(name) {
|
||||
Ok(raw) => {
|
||||
let value = raw
|
||||
.parse::<u64>()
|
||||
.map_err(|source| RuntimeCacheConfigError::InvalidTtl { value: raw, source })?;
|
||||
if value == 0 {
|
||||
return Err(RuntimeCacheConfigError::ZeroTtl { name });
|
||||
}
|
||||
Ok(Some(value))
|
||||
}
|
||||
Err(env::VarError::NotPresent) => Ok(None),
|
||||
Err(env::VarError::NotUnicode(_)) => Err(RuntimeCacheConfigError::InvalidUnicode { name }),
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Error)]
|
||||
pub enum RuntimeCacheConfigError {
|
||||
#[error("{name} must contain valid UTF-8")]
|
||||
InvalidUnicode { name: &'static str },
|
||||
#[error("CRANK_CACHE_BACKEND must be one of memory, valkey, redis, got {value}")]
|
||||
InvalidBackend {
|
||||
value: String,
|
||||
source: crank_core::ParseCacheBackendError,
|
||||
},
|
||||
#[error("CRANK_CACHE_DEFAULT_TTL_MS must be a positive integer, got {value}")]
|
||||
InvalidTtl {
|
||||
value: String,
|
||||
source: ParseIntError,
|
||||
},
|
||||
#[error("{name} must be greater than zero")]
|
||||
ZeroTtl { name: &'static str },
|
||||
#[error("{backend} backend requires CRANK_CACHE_URL")]
|
||||
MissingUrl { backend: CacheBackend },
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use crank_core::CacheBackend;
|
||||
|
||||
use super::{RuntimeCacheConfig, RuntimeCacheConfigError};
|
||||
|
||||
#[test]
|
||||
fn defaults_to_in_memory_cache_without_url() {
|
||||
let config = RuntimeCacheConfig::default();
|
||||
|
||||
assert_eq!(config.backend, CacheBackend::Memory);
|
||||
assert_eq!(config.url, None);
|
||||
assert_eq!(config.default_ttl_ms, None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn loads_valkey_config_from_env() {
|
||||
unsafe {
|
||||
std::env::set_var("CRANK_CACHE_BACKEND", "valkey");
|
||||
std::env::set_var("CRANK_CACHE_URL", "redis://cache:6379/0");
|
||||
std::env::set_var("CRANK_CACHE_DEFAULT_TTL_MS", "15000");
|
||||
}
|
||||
|
||||
let config = RuntimeCacheConfig::from_env().unwrap();
|
||||
|
||||
assert_eq!(config.backend, CacheBackend::Valkey);
|
||||
assert_eq!(config.url.as_deref(), Some("redis://cache:6379/0"));
|
||||
assert_eq!(config.default_ttl_ms, Some(15_000));
|
||||
|
||||
unsafe {
|
||||
std::env::remove_var("CRANK_CACHE_BACKEND");
|
||||
std::env::remove_var("CRANK_CACHE_URL");
|
||||
std::env::remove_var("CRANK_CACHE_DEFAULT_TTL_MS");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_external_backend_without_url() {
|
||||
unsafe {
|
||||
std::env::set_var("CRANK_CACHE_BACKEND", "redis");
|
||||
std::env::remove_var("CRANK_CACHE_URL");
|
||||
}
|
||||
|
||||
let error = RuntimeCacheConfig::from_env().unwrap_err();
|
||||
|
||||
assert!(matches!(
|
||||
error,
|
||||
RuntimeCacheConfigError::MissingUrl {
|
||||
backend: CacheBackend::Redis
|
||||
}
|
||||
));
|
||||
|
||||
unsafe {
|
||||
std::env::remove_var("CRANK_CACHE_BACKEND");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_zero_ttl() {
|
||||
unsafe {
|
||||
std::env::set_var("CRANK_CACHE_DEFAULT_TTL_MS", "0");
|
||||
}
|
||||
|
||||
let error = RuntimeCacheConfig::from_env().unwrap_err();
|
||||
|
||||
assert!(matches!(
|
||||
error,
|
||||
RuntimeCacheConfigError::ZeroTtl {
|
||||
name: "CRANK_CACHE_DEFAULT_TTL_MS"
|
||||
}
|
||||
));
|
||||
|
||||
unsafe {
|
||||
std::env::remove_var("CRANK_CACHE_DEFAULT_TTL_MS");
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user