nimbus_fml/defaults/
hasher.rs

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
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */

use crate::schema::TypeQuery;
use crate::{
    intermediate_representation::{FeatureDef, ObjectDef, PropDef, TypeRef},
    schema::Sha256Hasher,
};
use serde_json::Value;
use std::{
    collections::{BTreeMap, BTreeSet, HashSet},
    hash::{Hash, Hasher},
};

pub(crate) struct DefaultsHasher<'a> {
    object_defs: &'a BTreeMap<String, ObjectDef>,
}

impl<'a> DefaultsHasher<'a> {
    pub(crate) fn new(objs: &'a BTreeMap<String, ObjectDef>) -> Self {
        Self { object_defs: objs }
    }

    pub(crate) fn hash(&self, feature_def: &FeatureDef) -> u64 {
        let mut hasher = Sha256Hasher::default();
        feature_def.defaults_hash(&mut hasher);

        let types = self.all_types(feature_def);

        // We iterate through the object_defs because they are both
        // ordered, and we want to maintain a stable ordering.
        // By contrast, `types`, a HashSet, definitely does not have a stable ordering.
        for (name, obj_def) in self.object_defs {
            if types.contains(&TypeRef::Object(name.clone())) {
                obj_def.defaults_hash(&mut hasher);
            }
        }

        hasher.finish()
    }

    fn all_types(&self, feature_def: &FeatureDef) -> HashSet<TypeRef> {
        TypeQuery::new(self.object_defs).all_types(feature_def)
    }
}

trait DefaultsHash {
    fn defaults_hash<H: Hasher>(&self, state: &mut H);
}

impl DefaultsHash for FeatureDef {
    fn defaults_hash<H: Hasher>(&self, state: &mut H) {
        self.props.defaults_hash(state);
    }
}

impl DefaultsHash for Vec<PropDef> {
    fn defaults_hash<H: Hasher>(&self, state: &mut H) {
        let mut vec = self.iter().collect::<Vec<_>>();
        vec.sort_by_key(|item| &item.name);

        for item in vec {
            item.defaults_hash(state);
        }
    }
}

impl DefaultsHash for PropDef {
    fn defaults_hash<H: Hasher>(&self, state: &mut H) {
        self.name.hash(state);
        self.default.defaults_hash(state);
    }
}

impl DefaultsHash for ObjectDef {
    fn defaults_hash<H: Hasher>(&self, state: &mut H) {
        self.props.defaults_hash(state);
    }
}

impl DefaultsHash for Value {
    fn defaults_hash<H: Hasher>(&self, state: &mut H) {
        match self {
            Self::Null => 0_u8.hash(state),
            Self::Number(v) => v.hash(state),
            Self::Bool(v) => v.hash(state),
            Self::String(v) => v.hash(state),
            Self::Array(array) => {
                for v in array {
                    v.defaults_hash(state);
                }
            }
            Self::Object(map) => {
                let keys = map.keys().collect::<BTreeSet<_>>();
                for k in keys {
                    let v = map.get(k).unwrap();
                    v.defaults_hash(state);
                }
            }
        }
    }
}

#[cfg(test)]
mod unit_tests {
    use super::*;
    use crate::error::Result;

    use serde_json::json;

    #[test]
    fn test_simple_feature_stable_over_time() -> Result<()> {
        let objs = Default::default();

        let feature_def = {
            let p1 = PropDef::new("my-int", &TypeRef::Int, &json!(1));
            let p2 = PropDef::new("my-bool", &TypeRef::Boolean, &json!(true));
            let p3 = PropDef::new("my-string", &TypeRef::String, &json!("string"));
            FeatureDef::new("test_feature", "", vec![p1, p2, p3], false)
        };

        let mut prev: Option<u64> = None;
        for _ in 0..100 {
            let hasher = DefaultsHasher::new(&objs);
            let hash = hasher.hash(&feature_def);
            if let Some(prev) = prev {
                assert_eq!(prev, hash);
            }
            prev = Some(hash);
        }

        Ok(())
    }

    #[test]
    fn test_simple_feature_is_stable_with_props_in_any_order() -> Result<()> {
        let objs = Default::default();

        let p1 = PropDef::new("my-int", &TypeRef::Int, &json!(1));
        let p2 = PropDef::new("my-bool", &TypeRef::Boolean, &json!(true));
        let p3 = PropDef::new("my-string", &TypeRef::String, &json!("string"));

        let f1 = FeatureDef::new(
            "test_feature",
            "",
            vec![p1.clone(), p2.clone(), p3.clone()],
            false,
        );
        let f2 = FeatureDef::new("test_feature", "", vec![p3, p2, p1], false);

        let hasher = DefaultsHasher::new(&objs);
        assert_eq!(hasher.hash(&f1), hasher.hash(&f2));
        Ok(())
    }

    #[test]
    fn test_simple_feature_is_stable_changing_types() -> Result<()> {
        let objs = Default::default();

        // unsure how you'd do this.
        let f1 = {
            let prop1 = PropDef::new("p1", &TypeRef::Int, &json!(42));
            let prop2 = PropDef::new("p2", &TypeRef::String, &json!("Yes"));
            FeatureDef::new("test_feature", "documentation", vec![prop1, prop2], false)
        };

        let f2 = {
            let prop1 = PropDef::new("p1", &TypeRef::String, &json!(42));
            let prop2 = PropDef::new("p2", &TypeRef::Int, &json!("Yes"));
            FeatureDef::new("test_feature", "documentation", vec![prop1, prop2], false)
        };

        let hasher = DefaultsHasher::new(&objs);
        assert_eq!(hasher.hash(&f1), hasher.hash(&f2));

        Ok(())
    }

    #[test]
    fn test_simple_feature_is_sensitive_to_change() -> Result<()> {
        let objs = Default::default();

        let f1 = {
            let prop1 = PropDef::new("p1", &TypeRef::String, &json!("Yes"));
            let prop2 = PropDef::new("p2", &TypeRef::Int, &json!(1));
            FeatureDef::new("test_feature", "documentation", vec![prop1, prop2], false)
        };

        let hasher = DefaultsHasher::new(&objs);

        // Sensitive to change in type of properties
        let ne = {
            let prop1 = PropDef::new("p1", &TypeRef::String, &json!("Nope"));
            let prop2 = PropDef::new("p2", &TypeRef::Boolean, &json!(1));
            FeatureDef::new("test_feature", "documentation", vec![prop1, prop2], false)
        };
        assert_ne!(hasher.hash(&f1), hasher.hash(&ne));

        // Sensitive to change in name of properties
        let ne = {
            let prop1 = PropDef::new("p1_", &TypeRef::String, &json!("Yes"));
            let prop2 = PropDef::new("p2", &TypeRef::Int, &json!(1));
            FeatureDef::new("test_feature", "documentation", vec![prop1, prop2], false)
        };
        assert_ne!(hasher.hash(&f1), hasher.hash(&ne));

        // Not Sensitive to change in changes in coenrollment status
        let eq = {
            let prop1 = PropDef::new("p1", &TypeRef::String, &json!("Yes"));
            let prop2 = PropDef::new("p2", &TypeRef::Int, &json!(1));
            FeatureDef::new("test_feature", "documentation", vec![prop1, prop2], true)
        };
        assert_eq!(hasher.hash(&f1), hasher.hash(&eq));

        Ok(())
    }

    #[test]
    fn test_feature_is_sensitive_to_object_change() -> Result<()> {
        let obj_nm = "MyObject";
        let obj_t = TypeRef::Object(obj_nm.to_string());

        let f1 = {
            let prop1 = PropDef::new("p1", &obj_t, &json!({}));
            FeatureDef::new("test_feature", "documentation", vec![prop1], false)
        };

        let objs = {
            let obj_def = ObjectDef::new(
                obj_nm,
                &[PropDef::new("obj-p1", &TypeRef::Boolean, &json!(true))],
            );

            ObjectDef::into_map(&[obj_def])
        };

        let hasher = DefaultsHasher::new(&objs);
        // Get an original hash here.
        let h1 = hasher.hash(&f1);

        // Then change the object later on.
        let objs = {
            let obj_def = ObjectDef::new(
                obj_nm,
                &[PropDef::new("obj-p1", &TypeRef::Boolean, &json!(false))],
            );

            ObjectDef::into_map(&[obj_def])
        };

        let hasher = DefaultsHasher::new(&objs);
        let ne = hasher.hash(&f1);

        assert_ne!(h1, ne);

        Ok(())
    }

    #[test]
    fn test_hash_is_sensitive_to_nested_change() -> Result<()> {
        let obj1_nm = "MyObject";
        let obj1_t = TypeRef::Object(obj1_nm.to_string());

        let obj2_nm = "MyNestedObject";
        let obj2_t = TypeRef::Object(obj2_nm.to_string());

        let obj1_def = ObjectDef::new(obj1_nm, &[PropDef::new("p1-obj2", &obj2_t, &json!({}))]);

        let f1 = {
            let prop1 = PropDef::new("p1", &obj1_t.clone(), &json!({}));
            FeatureDef::new("test_feature", "documentation", vec![prop1], false)
        };

        let objs = {
            let obj2_def = ObjectDef::new(
                obj2_nm,
                &[PropDef::new("p1-string", &TypeRef::String, &json!("one"))],
            );
            ObjectDef::into_map(&[obj1_def.clone(), obj2_def])
        };

        let hasher = DefaultsHasher::new(&objs);
        // Get an original hash here.
        let h1 = hasher.hash(&f1);

        // Now change just the deeply nested object.
        let objs = {
            let obj2_def = ObjectDef::new(
                obj2_nm,
                &[PropDef::new("p1-string", &TypeRef::String, &json!("two"))],
            );
            ObjectDef::into_map(&[obj1_def.clone(), obj2_def])
        };
        let hasher = DefaultsHasher::new(&objs);
        let ne = hasher.hash(&f1);

        assert_ne!(h1, ne);
        Ok(())
    }
}