zenmanage 1.0.0

Official Zenmanage feature flags SDK for Rust
Documentation
use serde::{Deserialize, Serialize};

/// A single attribute value in a context.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct ContextValue {
    /// The value as text.
    pub value: String,
}

impl ContextValue {
    /// A single attribute value.
    pub fn new(value: impl Into<String>) -> Self {
        Self {
            value: value.into(),
        }
    }
}

/// A context attribute with one or more values.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct Attribute {
    /// The attribute name that rules refer to.
    pub key: String,
    /// The attribute's values.
    pub values: Vec<ContextValue>,
}

impl Attribute {
    /// An attribute with the given values.
    pub fn new(key: impl Into<String>, values: Vec<impl Into<String>>) -> Self {
        Self {
            key: key.into(),
            values: values.into_iter().map(ContextValue::new).collect(),
        }
    }

    /// The values as text.
    pub fn get_values(&self) -> Vec<&str> {
        self.values.iter().map(|v| v.value.as_str()).collect()
    }

    /// Adds another value.
    pub fn add_value(mut self, value: impl Into<String>) -> Self {
        self.values.push(ContextValue::new(value));
        self
    }
}

/// Targeting context for rule evaluation and usage reporting.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct Context {
    /// The kind of thing being evaluated, such as `user` or `organization`.
    #[serde(rename = "type")]
    pub context_type: String,
    /// A display name, shown in Zenmanage.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub name: Option<String>,
    /// The stable identifier used for targeting and rollouts.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub identifier: Option<String>,
    /// Attributes that rules can target.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub attributes: Vec<Attribute>,
}

impl Context {
    /// A context of the given type, without an identifier.
    pub fn new(context_type: impl Into<String>) -> Self {
        Self {
            context_type: context_type.into(),
            name: None,
            identifier: None,
            attributes: Vec::new(),
        }
    }

    /// A context with an identifier. An empty identifier counts as none.
    pub fn single(
        context_type: impl Into<String>,
        identifier: impl Into<String>,
        name: Option<impl Into<String>>,
    ) -> Self {
        let context = Self {
            context_type: context_type.into(),
            identifier: None,
            name: name.map(Into::into),
            attributes: Vec::new(),
        };

        context.with_identifier(identifier)
    }

    /// Sets the display name.
    pub fn with_name(mut self, name: impl Into<String>) -> Self {
        self.name = Some(name.into());
        self
    }

    /// Sets the identifier. An empty identifier counts as none.
    pub fn with_identifier(mut self, identifier: impl Into<String>) -> Self {
        let identifier = identifier.into();
        self.identifier = (!identifier.is_empty()).then_some(identifier);
        self
    }

    /// Adds an attribute, replacing any attribute with the same key.
    pub fn add_attribute(mut self, attribute: Attribute) -> Self {
        match self
            .attributes
            .iter_mut()
            .find(|existing| existing.key == attribute.key)
        {
            Some(existing) => *existing = attribute,
            None => self.attributes.push(attribute),
        }
        self
    }

    /// The attribute with this key, if there is one.
    pub fn get_attribute(&self, key: &str) -> Option<&Attribute> {
        self.attributes.iter().find(|attr| attr.key == key)
    }

    /// Whether this is the empty default context, which is not sent with usage reports.
    pub fn is_anonymous(&self) -> bool {
        self.context_type == "anonymous"
            && self.name.is_none()
            && self.identifier.is_none()
            && self.attributes.is_empty()
    }
}

impl Default for Context {
    fn default() -> Self {
        Self::new("anonymous")
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn a_repeated_attribute_key_replaces_the_earlier_one() {
        let context = Context::new("user")
            .add_attribute(Attribute::new("plan", vec!["free"]))
            .add_attribute(Attribute::new("country", vec!["US"]))
            .add_attribute(Attribute::new("plan", vec!["pro"]));

        assert_eq!(context.attributes.len(), 2);
        assert_eq!(
            context.get_attribute("plan").map(Attribute::get_values),
            Some(vec!["pro"])
        );
    }

    #[test]
    fn empty_identifier_is_treated_as_missing() {
        let context = Context::single("anonymous", "", None::<String>);

        assert_eq!(context.identifier, None);
        assert!(context.is_anonymous());
        assert_eq!(
            serde_json::to_value(&context).unwrap(),
            serde_json::json!({"type": "anonymous"})
        );
    }

    #[test]
    fn context_round_trips_through_json() {
        let context = Context::single("user", "user-42", Some("Ada"))
            .add_attribute(Attribute::new("country", vec!["US"]));

        let json = serde_json::to_string(&context).unwrap();

        assert_eq!(serde_json::from_str::<Context>(&json).unwrap(), context);
    }

    #[test]
    fn context_json_shape_matches_api_contract() {
        let context = Context::single("user", "user-42", Some("Ada"))
            .add_attribute(Attribute::new("country", vec!["US", "CA"]));

        let json = serde_json::to_value(context).expect("serialize");
        assert_eq!(json["type"], "user");
        assert_eq!(json["identifier"], "user-42");
        assert_eq!(json["name"], "Ada");
        assert_eq!(json["attributes"][0]["key"], "country");
        assert_eq!(json["attributes"][0]["values"][0]["value"], "US");
    }
}