zenmanage 1.0.0

Official Zenmanage feature flags SDK for Rust
Documentation
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_";

/// Supported cache backend choices.
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum CacheBackendType {
    /// In process memory. The default.
    Memory,
    /// In files under the configured cache directory.
    FileSystem,
    /// No caching between loads.
    Null,
}

/// Runtime SDK configuration. Build one with [`ConfigBuilder`].
#[derive(Clone)]
#[non_exhaustive]
pub struct Config {
    /// The server key (`srv_...`) of the environment.
    pub environment_token: String,
    /// How long loaded rules are used before they are reloaded.
    pub cache_ttl_seconds: u64,
    /// Which built-in cache to use.
    pub cache_backend: CacheBackendType,
    /// Where the filesystem cache writes.
    pub cache_directory: Option<PathBuf>,
    /// Whether evaluations are reported to Zenmanage.
    pub enable_usage_reporting: bool,
    /// The base URL of the API.
    pub api_endpoint: String,
    /// The version sent in the client agent.
    pub sdk_version: String,
    /// The SDK name sent in the client agent.
    pub client_agent: String,
    /// A cache that replaces the built-in ones.
    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()
    }
}

/// Fluent config builder.
#[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 {
    /// A builder with the default settings.
    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,
        }
    }

    /// A builder filled from the `ZENMANAGE_*` environment variables. Unset
    /// and unreadable values keep their defaults.
    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
    }

    /// Sets the server key (`srv_...`). Required.
    pub fn with_environment_token(mut self, token: impl Into<String>) -> Self {
        self.environment_token = Some(token.into());
        self
    }

    /// Sets how many seconds loaded rules are used before they are reloaded. Defaults to 3600.
    pub fn with_cache_ttl(mut self, seconds: u64) -> Self {
        self.cache_ttl_seconds = seconds;
        self
    }

    /// Chooses a built-in cache. Defaults to memory.
    pub fn with_cache_backend(mut self, backend: CacheBackendType) -> Self {
        self.cache_backend = backend;
        self
    }

    /// Sets the directory for the filesystem cache.
    pub fn with_cache_directory(mut self, directory: impl Into<PathBuf>) -> Self {
        self.cache_directory = Some(directory.into());
        self
    }

    /// Turns usage reporting on or off. It is on by default.
    pub fn with_usage_reporting(mut self, enabled: bool) -> Self {
        self.enable_usage_reporting = enabled;
        self
    }

    /// Points the SDK at another API base URL.
    pub fn with_api_endpoint(mut self, endpoint: impl Into<String>) -> Self {
        self.api_endpoint = endpoint.into();
        self
    }

    /// Overrides the version sent in the client agent.
    pub fn with_sdk_version(mut self, sdk_version: impl Into<String>) -> Self {
        self.sdk_version = sdk_version.into();
        self
    }

    /// Overrides the SDK name sent in the client agent. The API only accepts names it knows.
    pub fn with_client_agent(mut self, client_agent: impl Into<String>) -> Self {
        self.client_agent = client_agent.into();
        self
    }

    /// Uses a custom cache instead of the built-in ones.
    pub fn with_cache(mut self, cache: Arc<dyn CacheBackend>) -> Self {
        self.custom_cache = Some(cache);
        self
    }

    /// Validates the settings and returns the [`Config`].
    ///
    /// # Errors
    ///
    /// Fails without a server key, or for a filesystem cache without a directory.
    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);
    }
}