zenmanage 1.0.0

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

/// Primitive flag value as represented by the API.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Default)]
pub struct PrimitiveValue {
    /// Set for a boolean value.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub boolean: Option<bool>,
    /// Set for a string value.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub string: Option<String>,
    /// Set for a number value.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub number: Option<f64>,
    /// Set for a JSON value.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub json: Option<serde_json::Value>,
}

/// A value wrapper used in targets and rule values.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct RuleValue {
    /// Identifier of this value.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub version: Option<String>,
    /// The value itself.
    pub value: PrimitiveValue,
}

/// Target payload for a flag.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct FlagTarget {
    /// Identifier of this target.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub version: Option<String>,
    /// When the target expired.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub expired_at: Option<String>,
    /// When the target was published.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub published_at: Option<String>,
    /// When the target is scheduled to be published.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub scheduled_at: Option<String>,
    /// The value the target serves.
    pub value: RuleValue,
}

/// Supported flag types.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
#[non_exhaustive]
pub enum FlagType {
    /// `true` or `false`.
    Boolean,
    /// Text.
    String,
    /// A number.
    Number,
    /// A JSON object or array.
    Json,
    /// Any flag type this SDK release doesn't know about yet (for example a
    /// future type served before this SDK release understands it). Kept
    /// instead of failing deserialization so one unrecognized flag in a
    /// rules payload doesn't take the rest of the payload down with it;
    /// evaluation treats a flag with this type like a missing flag and
    /// falls back to the caller-provided default.
    #[serde(other)]
    Unknown,
}

/// Context or segment rule target object.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct RuleContextTarget {
    /// The identifier of the targeted context.
    pub identifier: String,
    /// The type of the targeted context; `None` applies to any type.
    #[serde(default)]
    pub r#type: Option<String>,
}

/// Rule condition payload.
#[derive(Clone, Debug, PartialEq, Serialize)]
pub struct RuleCondition {
    /// The attribute name, or `context` or `segment`.
    pub attribute: String,
    /// The comparison to apply.
    pub operator: String,
    /// The values to compare against.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub value: Option<serde_json::Value>,
}

impl<'de> serde::Deserialize<'de> for RuleCondition {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        use serde::de::{self, MapAccess, Visitor};
        use std::fmt;

        struct RuleConditionVisitor;

        impl<'de> Visitor<'de> for RuleConditionVisitor {
            type Value = RuleCondition;

            fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
                formatter.write_str("a RuleCondition object")
            }

            fn visit_map<M>(self, mut map: M) -> Result<Self::Value, M::Error>
            where
                M: MapAccess<'de>,
            {
                let mut attribute: Option<String> = None;
                let mut operator: Option<String> = None;
                let mut value: Option<serde_json::Value> = None;
                let mut selector: Option<String> = None;
                let mut selector_subtype: Option<String> = None;
                let mut comparer: Option<String> = None;
                let mut values: Option<serde_json::Value> = None;

                while let Some(key) = map.next_key::<String>()? {
                    match key.as_str() {
                        "attribute" => attribute = Some(map.next_value()?),
                        "operator" => operator = Some(map.next_value()?),
                        "value" => value = Some(map.next_value()?),
                        "selector" => selector = Some(map.next_value()?),
                        "selector_subtype" => {
                            selector_subtype = map.next_value::<Option<String>>()?
                        }
                        "comparer" => comparer = Some(map.next_value()?),
                        "values" => values = Some(map.next_value()?),
                        _ => {
                            let _ = map.next_value::<serde_json::Value>()?;
                        }
                    }
                }

                // CDN format: selector/selector_subtype/comparer/values
                if let (Some(sel), Some(cmp)) = (selector, comparer) {
                    let attr = if sel == "attribute" {
                        selector_subtype.unwrap_or_else(|| sel.clone())
                    } else {
                        sel
                    };
                    return Ok(RuleCondition {
                        attribute: attr,
                        operator: cmp,
                        value: values,
                    });
                }

                // Legacy format: attribute/operator/value
                let attribute = attribute.ok_or_else(|| de::Error::missing_field("attribute"))?;
                let operator = operator.ok_or_else(|| de::Error::missing_field("operator"))?;
                Ok(RuleCondition {
                    attribute,
                    operator,
                    value,
                })
            }
        }

        deserializer.deserialize_map(RuleConditionVisitor)
    }
}

/// Rule entry on a flag.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Rule {
    /// Identifier of this rule.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub version: Option<String>,
    /// The description entered in Zenmanage.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,
    /// The rule's condition.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub criteria: Option<RuleCondition>,
    /// Conditions that must all match; used instead of `criteria` when present.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub clauses: Option<Vec<RuleCondition>>,
    /// Rules are tried from the lowest position up.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub position: Option<i32>,
    /// The value served when the rule matches.
    pub value: RuleValue,
}

/// Rollout payload for active percentage rollouts.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct RolloutData {
    /// The target served inside the rollout.
    pub target: FlagTarget,
    /// The rules applied inside the rollout.
    #[serde(default)]
    pub rules: Vec<Rule>,
    /// How many of every 100 identifiers are included.
    pub percentage: u8,
    /// Mixed into the hash so each rollout picks its own identifiers.
    pub salt: String,
    /// The rollout state reported by the API.
    pub status: String,
}

/// Flag payload from the rules API.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct FlagData {
    /// Identifier of this flag.
    pub version: String,
    /// The flag's type.
    #[serde(rename = "type")]
    pub flag_type: FlagType,
    /// The key used to look the flag up.
    pub key: String,
    /// The display name.
    pub name: String,
    /// The target served outside any rollout.
    pub target: FlagTarget,
    /// The rules applied outside any rollout.
    #[serde(default)]
    pub rules: Vec<Rule>,
    /// The active percentage rollout, if there is one.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub rollout: Option<RolloutData>,
}

/// Full rules response payload.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct RulesResponse {
    /// Payload format version.
    pub version: String,
    /// The flags. One that can't be read is left out.
    #[serde(deserialize_with = "deserialize_flags")]
    pub flags: Vec<FlagData>,
}

/// Parses flags one at a time so that a single flag this release can't read
/// (for example one with no published value, which the API sends as `[]`) is
/// skipped instead of failing the whole payload.
fn deserialize_flags<'de, D>(deserializer: D) -> Result<Vec<FlagData>, D::Error>
where
    D: serde::Deserializer<'de>,
{
    let raw = Vec::<serde_json::Value>::deserialize(deserializer)?;

    Ok(raw
        .into_iter()
        .filter_map(|value| match FlagData::deserialize(&value) {
            Ok(flag) => Some(flag),
            Err(error) => {
                let key = value
                    .get("key")
                    .and_then(|key| key.as_str())
                    .unwrap_or("<unknown>");
                log::warn!(
                    "zenmanage: flag \"{key}\" couldn't be read; skipping it and falling back \
                     to the caller-provided default: {error}"
                );
                None
            }
        })
        .collect())
}

/// Metadata API response used to discover the CDN path.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct MetadataResponse {
    /// The location of the rules.
    pub data: MetadataData,
}

/// Where the rules are served from.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct MetadataData {
    /// Base URL of the CDN.
    pub cdn: String,
    /// Path of the environment's rules on the CDN.
    pub path: String,
}

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

    #[test]
    fn known_flag_types_deserialize_to_their_variant() {
        assert_eq!(
            serde_json::from_str::<FlagType>("\"boolean\"").unwrap(),
            FlagType::Boolean
        );
        assert_eq!(
            serde_json::from_str::<FlagType>("\"string\"").unwrap(),
            FlagType::String
        );
        assert_eq!(
            serde_json::from_str::<FlagType>("\"number\"").unwrap(),
            FlagType::Number
        );
        assert_eq!(
            serde_json::from_str::<FlagType>("\"json\"").unwrap(),
            FlagType::Json
        );
    }

    #[test]
    fn unrecognized_flag_type_deserializes_to_unknown_instead_of_erroring() {
        // Represents any future type this SDK release predates.
        assert_eq!(
            serde_json::from_str::<FlagType>("\"some-future-type\"").unwrap(),
            FlagType::Unknown
        );
    }

    #[test]
    fn a_flag_that_cannot_be_read_does_not_fail_the_payload() {
        let payload = r#"{
            "version": "2026-02-24",
            "flags": [
                {"version": "1", "type": "boolean", "key": "unpublished", "name": "n", "target": [], "rules": []},
                {"version": "1", "type": "boolean", "key": "no-value", "name": "n", "target": {"value": []}},
                {"key": "mangled"},
                "not an object",
                {"version": "1", "type": "boolean", "key": "ok", "name": "n",
                 "target": {"value": {"value": {"boolean": true}}}}
            ]
        }"#;

        let response: RulesResponse = serde_json::from_str(payload).unwrap();

        let keys: Vec<&str> = response
            .flags
            .iter()
            .map(|flag| flag.key.as_str())
            .collect();
        assert_eq!(keys, ["ok"]);
    }

    #[test]
    fn rule_conditions_read_the_delivered_selector_format() {
        let attribute: RuleCondition = serde_json::from_str(
            r#"{"selector": "attribute", "selector_subtype": "country", "comparer": "equal", "values": ["US"]}"#,
        )
        .unwrap();
        assert_eq!(attribute.attribute, "country");
        assert_eq!(attribute.operator, "equal");
        assert_eq!(attribute.value, Some(serde_json::json!(["US"])));

        let segment: RuleCondition = serde_json::from_str(
            r#"{"selector": "segment", "selector_subtype": null, "comparer": "in", "values": []}"#,
        )
        .unwrap();
        assert_eq!(segment.attribute, "segment");

        // The round trip through the cache uses the attribute/operator/value shape.
        let cached = serde_json::to_string(&attribute).unwrap();
        assert_eq!(
            serde_json::from_str::<RuleCondition>(&cached).unwrap(),
            attribute
        );
    }

    #[test]
    fn primitive_value_with_json_field_round_trips() {
        let value: PrimitiveValue =
            serde_json::from_str(r#"{"json": {"limit": 5, "flags": [1, 2]}}"#).unwrap();
        assert_eq!(
            value.json,
            Some(serde_json::json!({"limit": 5, "flags": [1, 2]}))
        );
        assert_eq!(value.boolean, None);
        assert_eq!(value.string, None);
        assert_eq!(value.number, None);
    }
}