use std::{path::PathBuf, sync::Arc};
use crate::{
cache::{CacheBackend, SharedCache},
errors::{Result, ZenmanageError},
};
const SERVER_KEY_PREFIX: &str = "srv_";
const CLIENT_KEY_PREFIX: &str = "cli_";
const MOBILE_KEY_PREFIX: &str = "mob_";
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum CacheBackendType {
Memory,
FileSystem,
Null,
}
#[derive(Clone)]
#[non_exhaustive]
pub struct Config {
pub environment_token: String,
pub cache_ttl_seconds: u64,
pub cache_backend: CacheBackendType,
pub cache_directory: Option<PathBuf>,
pub enable_usage_reporting: bool,
pub api_endpoint: String,
pub sdk_version: String,
pub client_agent: String,
pub custom_cache: Option<SharedCache>,
}
impl std::fmt::Debug for Config {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Config")
.field("environment_token", &"***")
.field("cache_ttl_seconds", &self.cache_ttl_seconds)
.field("cache_backend", &self.cache_backend)
.field("cache_directory", &self.cache_directory)
.field("enable_usage_reporting", &self.enable_usage_reporting)
.field("api_endpoint", &self.api_endpoint)
.field("sdk_version", &self.sdk_version)
.field("client_agent", &self.client_agent)
.finish()
}
}
#[derive(Clone)]
pub struct ConfigBuilder {
environment_token: Option<String>,
cache_ttl_seconds: u64,
cache_backend: CacheBackendType,
cache_directory: Option<PathBuf>,
enable_usage_reporting: bool,
api_endpoint: String,
sdk_version: String,
client_agent: String,
custom_cache: Option<Arc<dyn CacheBackend>>,
}
impl ConfigBuilder {
pub fn create() -> Self {
Self {
environment_token: None,
cache_ttl_seconds: 3600,
cache_backend: CacheBackendType::Memory,
cache_directory: None,
enable_usage_reporting: true,
api_endpoint: "https://api.zenmanage.com".to_owned(),
sdk_version: env!("CARGO_PKG_VERSION").to_owned(),
client_agent: "zenmanage-rust".to_owned(),
custom_cache: None,
}
}
pub fn from_environment() -> Self {
Self::from_variables(|name| std::env::var(name).ok())
}
fn from_variables(variable: impl Fn(&str) -> Option<String>) -> Self {
let read = |name: &str| {
variable(name)
.map(|value| value.trim().to_owned())
.filter(|value| !value.is_empty())
};
let mut builder = Self::create();
if let Some(token) = read("ZENMANAGE_ENVIRONMENT_TOKEN") {
builder = builder.with_environment_token(token);
}
if let Some(ttl) = read("ZENMANAGE_CACHE_TTL")
&& let Ok(parsed) = ttl.parse::<u64>()
{
builder = builder.with_cache_ttl(parsed);
}
if let Some(backend) = read("ZENMANAGE_CACHE_BACKEND") {
builder = match backend.to_ascii_lowercase().as_str() {
"memory" => builder.with_cache_backend(CacheBackendType::Memory),
"filesystem" => builder.with_cache_backend(CacheBackendType::FileSystem),
"null" => builder.with_cache_backend(CacheBackendType::Null),
_ => builder,
};
}
if let Some(cache_dir) = read("ZENMANAGE_CACHE_DIR") {
builder = builder.with_cache_directory(cache_dir);
}
if let Some(reporting) = read("ZENMANAGE_ENABLE_USAGE_REPORTING") {
builder = match reporting.to_ascii_lowercase().as_str() {
"1" | "true" | "yes" | "on" => builder.with_usage_reporting(true),
"0" | "false" | "no" | "off" => builder.with_usage_reporting(false),
_ => builder,
};
}
if let Some(endpoint) = read("ZENMANAGE_API_ENDPOINT") {
builder = builder.with_api_endpoint(endpoint);
}
builder
}
pub fn with_environment_token(mut self, token: impl Into<String>) -> Self {
self.environment_token = Some(token.into());
self
}
pub fn with_cache_ttl(mut self, seconds: u64) -> Self {
self.cache_ttl_seconds = seconds;
self
}
pub fn with_cache_backend(mut self, backend: CacheBackendType) -> Self {
self.cache_backend = backend;
self
}
pub fn with_cache_directory(mut self, directory: impl Into<PathBuf>) -> Self {
self.cache_directory = Some(directory.into());
self
}
pub fn with_usage_reporting(mut self, enabled: bool) -> Self {
self.enable_usage_reporting = enabled;
self
}
pub fn with_api_endpoint(mut self, endpoint: impl Into<String>) -> Self {
self.api_endpoint = endpoint.into();
self
}
pub fn with_sdk_version(mut self, sdk_version: impl Into<String>) -> Self {
self.sdk_version = sdk_version.into();
self
}
pub fn with_client_agent(mut self, client_agent: impl Into<String>) -> Self {
self.client_agent = client_agent.into();
self
}
pub fn with_cache(mut self, cache: Arc<dyn CacheBackend>) -> Self {
self.custom_cache = Some(cache);
self
}
pub fn build(self) -> Result<Config> {
let token = self
.environment_token
.map(|token| token.trim().to_owned())
.filter(|token| !token.is_empty())
.ok_or_else(|| {
ZenmanageError::Configuration("environment token is required".to_owned())
})?;
Self::validate_environment_token(&token)?;
if self.cache_backend == CacheBackendType::FileSystem
&& self.cache_directory.is_none()
&& self.custom_cache.is_none()
{
return Err(ZenmanageError::Configuration(
"cache directory is required for filesystem cache".to_owned(),
));
}
Ok(Config {
environment_token: token,
cache_ttl_seconds: self.cache_ttl_seconds,
cache_backend: self.cache_backend,
cache_directory: self.cache_directory,
enable_usage_reporting: self.enable_usage_reporting,
api_endpoint: self.api_endpoint,
sdk_version: self.sdk_version,
client_agent: self.client_agent,
custom_cache: self.custom_cache,
})
}
fn validate_environment_token(token: &str) -> Result<()> {
if token.starts_with(SERVER_KEY_PREFIX) {
return Ok(());
}
if token.starts_with(CLIENT_KEY_PREFIX) {
return Err(ZenmanageError::Configuration(
"client key provided. Rust SDK requires a server key (srv_...)".to_owned(),
));
}
if token.starts_with(MOBILE_KEY_PREFIX) {
return Err(ZenmanageError::Configuration(
"mobile key provided. Rust SDK requires a server key (srv_...)".to_owned(),
));
}
Err(ZenmanageError::Configuration(
"invalid environment token format".to_owned(),
))
}
}
#[cfg(test)]
mod tests {
use std::collections::HashMap;
use super::*;
fn from_map(variables: &[(&str, &str)]) -> ConfigBuilder {
let variables: HashMap<&str, &str> = variables.iter().copied().collect();
ConfigBuilder::from_variables(|name| variables.get(name).map(|value| value.to_string()))
}
#[test]
fn uses_the_documented_defaults() {
let config = ConfigBuilder::create()
.with_environment_token("srv_123")
.build()
.unwrap();
assert_eq!(config.cache_ttl_seconds, 3600);
assert_eq!(config.cache_backend, CacheBackendType::Memory);
assert!(config.enable_usage_reporting);
assert_eq!(config.api_endpoint, "https://api.zenmanage.com");
assert_eq!(config.client_agent, "zenmanage-rust");
assert_eq!(config.sdk_version, env!("CARGO_PKG_VERSION"));
}
#[test]
fn accepts_only_server_keys() {
for token in ["cli_123", "mob_123", "nonsense", "", " "] {
let result = ConfigBuilder::create()
.with_environment_token(token)
.build();
assert!(result.is_err(), "{token:?} should be rejected");
}
assert!(ConfigBuilder::create().build().is_err());
}
#[test]
fn trims_the_token() {
let config = ConfigBuilder::create()
.with_environment_token(" srv_123\n")
.build()
.unwrap();
assert_eq!(config.environment_token, "srv_123");
}
#[test]
fn debug_output_hides_the_token() {
let config = ConfigBuilder::create()
.with_environment_token("srv_secret")
.build()
.unwrap();
assert!(!format!("{config:?}").contains("srv_secret"));
}
#[test]
fn requires_cache_directory_for_filesystem_backend() {
let result = ConfigBuilder::create()
.with_environment_token("srv_123")
.with_cache_backend(CacheBackendType::FileSystem)
.build();
assert!(result.is_err());
}
#[test]
fn reads_every_environment_variable() {
let config = from_map(&[
("ZENMANAGE_ENVIRONMENT_TOKEN", "srv_env"),
("ZENMANAGE_CACHE_TTL", "60"),
("ZENMANAGE_CACHE_BACKEND", "FileSystem"),
("ZENMANAGE_CACHE_DIR", "/tmp/zenmanage"),
("ZENMANAGE_ENABLE_USAGE_REPORTING", "off"),
("ZENMANAGE_API_ENDPOINT", "https://example.test"),
])
.build()
.unwrap();
assert_eq!(config.environment_token, "srv_env");
assert_eq!(config.cache_ttl_seconds, 60);
assert_eq!(config.cache_backend, CacheBackendType::FileSystem);
assert_eq!(config.cache_directory, Some("/tmp/zenmanage".into()));
assert!(!config.enable_usage_reporting);
assert_eq!(config.api_endpoint, "https://example.test");
}
#[test]
fn usage_reporting_accepts_the_common_boolean_spellings() {
for (value, expected) in [
("1", true),
("TRUE", true),
("yes", true),
("on", true),
("0", false),
("False", false),
("no", false),
("off", false),
("maybe", true),
] {
let config = from_map(&[
("ZENMANAGE_ENVIRONMENT_TOKEN", "srv_env"),
("ZENMANAGE_ENABLE_USAGE_REPORTING", value),
])
.build()
.unwrap();
assert_eq!(config.enable_usage_reporting, expected, "{value}");
}
}
#[test]
fn unreadable_environment_values_keep_the_defaults() {
let config = from_map(&[
("ZENMANAGE_ENVIRONMENT_TOKEN", "srv_env"),
("ZENMANAGE_CACHE_TTL", "soon"),
("ZENMANAGE_CACHE_BACKEND", "redis"),
])
.build()
.unwrap();
assert_eq!(config.cache_ttl_seconds, 3600);
assert_eq!(config.cache_backend, CacheBackendType::Memory);
}
}