optimizely 0.5.0

An unofficial Rust SDK for Optimizely Feature Experimentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
use super::match_type::MatchType;
use super::operator::{NumericOperator, SemVerOperator, StringOperator};
use crate::{AttributeValue, UserAttributeMap};
use semver::Version;
use serde::de::{Error, MapAccess, SeqAccess, Visitor};
use serde::{Deserialize, Deserializer};
use std::fmt;

#[derive(Deserialize, Debug)]
#[serde(rename_all = "camelCase")]
// A simplified version of a condition to simplify parsing
enum Field {
    #[serde(rename = "match")]
    MatchType,
    #[serde(rename = "name")]
    AttributeName,
    Value,
    Type,
}

type AttributeName = String;

#[derive(Debug, PartialEq)]
pub(crate) enum Condition {
    AndSequence(Vec<Condition>),
    OrSequence(Vec<Condition>),
    Negation(Box<Condition>),
    IntegerComparison {
        attribute_name: AttributeName,
        operator: NumericOperator,
        desired_value: u64,
    },
    DecimalComparison {
        attribute_name: AttributeName,
        operator: NumericOperator,
        desired_value: f64,
    },
    StringComparison {
        attribute_name: AttributeName,
        operator: StringOperator,
        desired_value: String,
    },
    BooleanComparison {
        attribute_name: AttributeName,
        desired_value: bool,
    },
    Exists {
        attribute_name: AttributeName,
    },
}

impl Condition {
    /// Whether the user attributes match the condition or not
    pub fn does_match(&self, user_attributes: &UserAttributeMap) -> bool {
        match self {
            Condition::AndSequence(sequence) => {
                // Combine sequence with AND
                sequence
                    .iter()
                    .all(|condition| condition.does_match(user_attributes))
            }
            Condition::OrSequence(sequence) => {
                // Combine sequence with OR
                sequence
                    .iter()
                    .any(|condition| condition.does_match(user_attributes))
            }
            Condition::Negation(condition) => {
                // Negate the result of condition within
                !condition.does_match(user_attributes)
            }
            Condition::Exists { attribute_name } => {
                // Verify that attribute does exist
                user_attributes.get(attribute_name).is_some()
            }
            Condition::BooleanComparison {
                attribute_name,
                desired_value,
            } => {
                // Retrieve value
                user_attributes
                    .get(attribute_name)
                    .map(|user_attribute| {
                        // Instead of parsing a string to bool, we'll just match cases
                        match user_attribute.value() {
                            // User has attribute set to true, so the condition is true if the desired value is true
                            AttributeValue::Boolean(true) => *desired_value,
                            // User has attribute set to false, so the condition is true if the desired value is false
                            AttributeValue::Boolean(false) => !desired_value,
                            // Not a valid bool, so does not match
                            _ => false,
                        }
                    })
                    .unwrap_or(false)
            }
            Condition::StringComparison {
                attribute_name,
                operator,
                desired_value,
            } => {
                // Retrieve value
                user_attributes
                    .get(attribute_name)
                    .map(|user_attribute| {
                        let user_attribute_value = match user_attribute.value() {
                            AttributeValue::String(value) => value,
                            _ => {
                                // Cannot perform StringComparison on a non String value
                                return false;
                            }
                        };

                        // Apply string operator
                        match operator {
                            StringOperator::Equal => desired_value == user_attribute_value,
                            StringOperator::Contains => user_attribute_value.contains(desired_value),
                            StringOperator::SemVer(sem_ver_operator) => {
                                let user_attribute_value = match Version::parse(user_attribute_value) {
                                    Ok(version) => version,
                                    Err(_) => {
                                        // Unable to parse String as version number
                                        return false;
                                    }
                                };
                                let desired_value = match Version::parse(desired_value) {
                                    Ok(version) => version,
                                    Err(_) => {
                                        // Unable to parse String as version number
                                        return false;
                                    }
                                };
                                // Apply semantic version operator
                                match sem_ver_operator {
                                    SemVerOperator::Equal => user_attribute_value == desired_value,
                                    SemVerOperator::LessThan => user_attribute_value < desired_value,
                                    SemVerOperator::LessThanOrEqual => user_attribute_value <= desired_value,
                                    SemVerOperator::GreaterThan => user_attribute_value > desired_value,
                                    SemVerOperator::GreaterThanOrEqual => user_attribute_value >= desired_value,
                                }
                            }
                        }
                    })
                    .unwrap_or(false)
            }
            Condition::IntegerComparison {
                attribute_name,
                operator,
                desired_value,
            } => {
                // Retrieve value
                user_attributes
                    .get(attribute_name)
                    .map(|user_attribute| {
                        let user_attribute_value = match user_attribute.value() {
                            AttributeValue::Integer(value) => value,
                            _ => {
                                // Cannot perform IntegerComparison on a non Integer value
                                return false;
                            }
                        };
                        // Apply operator
                        match operator {
                            NumericOperator::Equal => user_attribute_value == desired_value,
                            NumericOperator::LessThan => user_attribute_value < desired_value,
                            NumericOperator::LessThanOrEqual => user_attribute_value <= desired_value,
                            NumericOperator::GreaterThan => user_attribute_value > desired_value,
                            NumericOperator::GreaterThanOrEqual => user_attribute_value >= desired_value,
                        }
                    })
                    .unwrap_or(false)
            }
            Condition::DecimalComparison {
                attribute_name,
                operator,
                desired_value,
            } => {
                // Retrieve value
                user_attributes
                    .get(attribute_name)
                    .map(|user_attribute| {
                        let user_attribute_value = match user_attribute.value() {
                            AttributeValue::Decimal(value) => value,
                            _ => {
                                // Cannot perform DecimalComparison on a non Decimal value
                                return false;
                            }
                        };
                        // Apply operator
                        match operator {
                            NumericOperator::Equal => user_attribute_value == desired_value,
                            NumericOperator::LessThan => user_attribute_value < desired_value,
                            NumericOperator::LessThanOrEqual => user_attribute_value <= desired_value,
                            NumericOperator::GreaterThan => user_attribute_value > desired_value,
                            NumericOperator::GreaterThanOrEqual => user_attribute_value >= desired_value,
                        }
                    })
                    .unwrap_or(false)
            }
        }
    }
}

// Advanced serde Deserialize
struct ConditionVisitor;
impl<'de> Visitor<'de> for ConditionVisitor {
    type Value = Condition;

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

    fn visit_seq<A>(self, mut seq: A) -> Result<Self::Value, A::Error>
    where
        A: SeqAccess<'de>,
    {
        let operator = seq
            .next_element::<String>()?
            .ok_or_else(|| Error::custom("expected at least one element"))?;

        let mut conditions = Vec::new();

        while let Some(condition) = seq.next_element::<Condition>()? {
            conditions.push(condition);
        }

        let condition = match operator.as_str() {
            "and" => Condition::AndSequence(conditions),
            "or" => Condition::OrSequence(conditions),
            "not" => {
                if conditions.len() > 1 {
                    return Err(Error::custom("too many conditions found within not statement"));
                }
                let condition = match conditions.pop() {
                    Some(condition) => condition,
                    None => {
                        return Err(Error::custom("no condition found within not statement"));
                    }
                };
                Condition::Negation(Box::new(condition))
            }
            _ => {
                return Err(Error::custom(r#"expected either "and" or "or""#));
            }
        };

        Ok(condition)
    }

    fn visit_map<V>(self, mut map: V) -> Result<Self::Value, V::Error>
    where
        V: MapAccess<'de>,
    {
        // Start with all variables set to none
        let mut match_type = Option::None;
        let mut attribute_name = Option::None;
        let mut value = Option::None;

        // Iterate over all keys
        while let Some(key) = map.next_key::<Field>()? {
            match key {
                Field::MatchType => {
                    if match_type.is_some() {
                        return Err(Error::duplicate_field("match"));
                    }
                    match_type = Some(map.next_value::<MatchType>()?);
                }
                Field::AttributeName => {
                    if attribute_name.is_some() {
                        return Err(Error::duplicate_field("name"));
                    }
                    attribute_name = Some(map.next_value::<AttributeName>()?);
                }
                Field::Value => {
                    if value.is_some() {
                        return Err(Error::duplicate_field("value"));
                    }
                    value = Some(map.next_value::<AttributeValue>()?);
                }
                Field::Type => {
                    // Skip type field as it is always "custom_attribute"
                    let _type = map.next_value::<String>()?;
                    assert_eq!(_type, "custom_attribute");
                }
            }
        }

        // Verify that match type and attribute name have been set
        let match_type = match_type.ok_or_else(|| Error::missing_field("match"))?;
        let attribute_name = attribute_name.ok_or_else(|| Error::missing_field("name"))?;

        // Value is optional. It is not needed for exists
        let value = value.unwrap_or(AttributeValue::Null);

        // Only accept valid combinations of match type and value type
        let condition = match value {
            // Checking whether an attribute exists
            AttributeValue::Null => {
                // Only one valid operator
                if match_type != MatchType::Exists {
                    return Err(Error::custom("invalid operator for empty type"));
                }

                Condition::Exists { attribute_name }
            }
            // Comparing an attribute to a boolean value
            AttributeValue::Boolean(desired_value) => {
                // Only one valid operator
                if match_type != MatchType::Exact {
                    return Err(Error::custom("invalid operator for boolean"));
                }

                Condition::BooleanComparison {
                    attribute_name,
                    desired_value,
                }
            }
            // Comparing an attribute to a numeric value
            AttributeValue::Integer(desired_value) => {
                let operator = match match_type {
                    MatchType::Exact => NumericOperator::Equal,
                    MatchType::LessThan => NumericOperator::LessThan,
                    MatchType::LessThanOrEqual => NumericOperator::LessThanOrEqual,
                    MatchType::GreaterThan => NumericOperator::GreaterThan,
                    MatchType::GreaterThanOrEqual => NumericOperator::GreaterThanOrEqual,
                    _ => return Err(Error::custom("invalid operator for number")),
                };

                Condition::IntegerComparison {
                    operator,
                    attribute_name,
                    desired_value,
                }
            }
            // Comparing an attribute to a numeric value
            AttributeValue::Decimal(desired_value) => {
                let operator = match match_type {
                    MatchType::Exact => NumericOperator::Equal,
                    MatchType::LessThan => NumericOperator::LessThan,
                    MatchType::LessThanOrEqual => NumericOperator::LessThanOrEqual,
                    MatchType::GreaterThan => NumericOperator::GreaterThan,
                    MatchType::GreaterThanOrEqual => NumericOperator::GreaterThanOrEqual,
                    _ => return Err(Error::custom("invalid operator for number")),
                };

                Condition::DecimalComparison {
                    operator,
                    attribute_name,
                    desired_value,
                }
            }
            // Comparing an attribute to a string value
            AttributeValue::String(desired_value) => {
                let operator = match match_type {
                    MatchType::Exact => StringOperator::Equal,
                    MatchType::Substring => StringOperator::Contains,
                    MatchType::SemVerEqual => StringOperator::SemVer(SemVerOperator::Equal),
                    MatchType::SemVerLessThan => StringOperator::SemVer(SemVerOperator::LessThan),
                    MatchType::SemVerLessThanOrEqual => StringOperator::SemVer(SemVerOperator::LessThanOrEqual),
                    MatchType::SemVerGreaterThan => StringOperator::SemVer(SemVerOperator::GreaterThan),
                    MatchType::SemVerGreaterThanOrEqual => StringOperator::SemVer(SemVerOperator::GreaterThanOrEqual),
                    _ => {
                        return Err(Error::custom("invalid operator for string"));
                    }
                };

                Condition::StringComparison {
                    operator,
                    attribute_name,
                    desired_value,
                }
            }
        };

        Ok(condition)
    }
}

impl<'de> Deserialize<'de> for Condition {
    fn deserialize<D>(deserializer: D) -> Result<Condition, D::Error>
    where
        D: Deserializer<'de>,
    {
        deserializer.deserialize_any(ConditionVisitor)
    }
}

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

    #[test]
    fn single_match() -> Result<(), Box<dyn Error>> {
        // JSON encoded condition
        let json = r#"{"match":"semver_ge","name":"app_version","type":"custom_attribute","value":"0.4.0"}"#;

        // Native condition
        let condition = Condition::StringComparison {
            attribute_name: String::from("app_version"),
            operator: StringOperator::SemVer(SemVerOperator::GreaterThanOrEqual),
            desired_value: String::from("0.4.0"),
        };

        // Parse successfully
        assert_eq!(serde_json::from_str::<Condition>(json)?, condition);

        // TODO: check against user attribute value

        Ok(())
    }

    #[test]
    fn structured_sequence() -> Result<(), Box<dyn Error>> {
        let json = r#"["and",["or",["or",{"match":"substring","name":"currentPath","type":"custom_attribute","value":"/checkout"}]]]"#;

        // First layer, AND-sequence
        let expected = Condition::AndSequence(Vec::from([
            // Second layer, OR-sequence
            Condition::OrSequence(Vec::from([
                // Third layer, OR-sequence
                Condition::OrSequence(Vec::from([
                    // Fourth layer, match
                    Condition::StringComparison {
                        attribute_name: String::from("currentPath"),
                        operator: StringOperator::Contains,
                        desired_value: String::from("/checkout"),
                    },
                ])),
            ])),
        ]));

        assert_eq!(serde_json::from_str::<Condition>(json)?, expected);

        Ok(())
    }
}