nimbus_fml/schema/
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
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
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
/* 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 sha2::{Digest, Sha256};

use crate::intermediate_representation::{
    EnumDef, FeatureDef, ObjectDef, PropDef, TypeRef, VariantDef,
};
use std::{
    collections::{BTreeMap, HashSet},
    hash::{Hash, Hasher},
};

use super::TypeQuery;

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

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

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

        let types = self.all_types(feature_def);

        // We iterate through the object_defs, then the enum_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 (obj_nm, obj_def) in self.object_defs {
            if types.contains(&TypeRef::Object(obj_nm.clone())) {
                obj_def.schema_hash(&mut hasher);
            }
        }

        for (enum_nm, enum_def) in self.enum_defs {
            if types.contains(&TypeRef::Enum(enum_nm.clone())) {
                enum_def.schema_hash(&mut hasher);
            }
        }

        hasher.finish()
    }

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

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

impl SchemaHash for FeatureDef {
    fn schema_hash<H: Hasher>(&self, state: &mut H) {
        self.props.schema_hash(state);
        self.allow_coenrollment.hash(state);
    }
}

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

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

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

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

impl SchemaHash for PropDef {
    fn schema_hash<H: Hasher>(&self, state: &mut H) {
        self.name.hash(state);
        self.typ.hash(state);
        self.string_alias.hash(state);
    }
}

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

impl SchemaHash for EnumDef {
    fn schema_hash<H: Hasher>(&self, state: &mut H) {
        self.variants.schema_hash(state);
    }
}

impl SchemaHash for VariantDef {
    fn schema_hash<H: Hasher>(&self, state: &mut H) {
        self.name.hash(state);
    }
}

#[derive(Default)]
pub(crate) struct Sha256Hasher {
    hasher: Sha256,
}

impl std::hash::Hasher for Sha256Hasher {
    fn finish(&self) -> u64 {
        let v = self.hasher.clone().finalize();
        u64::from_le_bytes(v[0..8].try_into().unwrap())
    }

    fn write(&mut self, bytes: &[u8]) {
        self.hasher.update(bytes);
    }
}

#[cfg(test)]
mod unit_tests {

    use crate::error::Result;
    use serde_json::json;

    use super::*;

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

        let prop1 = PropDef::new("p1", &TypeRef::String, &json!("No"));
        let prop2 = PropDef::new("p2", &TypeRef::Int, &json!(42));

        let feature_def =
            FeatureDef::new("test_feature", "documentation", vec![prop1, prop2], false);
        let mut prev: Option<u64> = None;
        for _ in 0..100 {
            let hasher = SchemaHasher::new(&enums, &objs);
            let hash = hasher.hash(&feature_def);
            if let Some(prev) = prev {
                assert_eq!(prev, hash);
            }
            prev = Some(hash);
        }

        Ok(())
    }

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

        let prop1 = PropDef::new("p1", &TypeRef::String, &json!("No"));
        let prop2 = PropDef::new("p2", &TypeRef::Int, &json!(42));

        let f1 = {
            FeatureDef::new(
                "test_feature",
                "documentation",
                vec![prop1.clone(), prop2.clone()],
                false,
            )
        };

        let f2 = { FeatureDef::new("test_feature", "documentation", vec![prop2, prop1], false) };

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

        Ok(())
    }

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

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

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

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

        Ok(())
    }

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

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

        let hasher = SchemaHasher::new(&enums, &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!("Nope"));
            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));

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

        Ok(())
    }

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

        let enum_nm = "MyEnum";
        let enum_t = TypeRef::Enum(enum_nm.to_string());

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

        let enums = {
            let enum1 = EnumDef::new(enum_nm, &["one", "two"]);
            EnumDef::into_map(&[enum1])
        };

        let hasher = SchemaHasher::new(&enums, &objs);
        let h1 = hasher.hash(&f1);

        let enums = {
            let enum1 = EnumDef::new(enum_nm, &["one", "two", "newly-added"]);
            EnumDef::into_map(&[enum1])
        };
        let hasher = SchemaHasher::new(&enums, &objs);
        let ne = hasher.hash(&f1);

        assert_ne!(h1, ne);

        Ok(())
    }

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

        let enum_nm = "MyEnum";
        let enum_t = TypeRef::Enum(enum_nm.to_string());

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

        let enums = {
            let enum1 = EnumDef::new(enum_nm, &["one", "two"]);
            let enums1 = &[enum1];
            EnumDef::into_map(enums1)
        };

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

        let enums = {
            let enum1 = EnumDef::new(enum_nm, &["one", "two"]);
            // Add an extra enum here.
            let enum2 = EnumDef::new("AnotherEnum", &["one", "two"]);
            let enums1 = &[enum1, enum2];
            EnumDef::into_map(enums1)
        };
        let hasher = SchemaHasher::new(&enums, &objs);
        let h2 = hasher.hash(&f1);

        assert_eq!(h1, h2);

        Ok(())
    }

    #[test]
    fn test_schema_is_sensitive_to_object_change() -> Result<()> {
        let enums = Default::default();
        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 = SchemaHasher::new(&enums, &objs);
        // Get an original hash here.
        let h1 = hasher.hash(&f1);

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

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

        let hasher = SchemaHasher::new(&enums, &objs);
        let ne = hasher.hash(&f1);

        assert_ne!(h1, ne);

        Ok(())
    }

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

        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 objects = {
            let obj1 = ObjectDef::new(
                obj_nm,
                &[PropDef::new("obj-p1", &TypeRef::Boolean, &json!(true))],
            );
            ObjectDef::into_map(&[obj1])
        };

        let hasher = SchemaHasher::new(&enums, &objects);
        // Get an original hash here.
        let h1 = hasher.hash(&f1);

        // Now add more objects, that aren't related to this feature.
        let objects = {
            let obj1 = ObjectDef::new(
                obj_nm,
                &[PropDef::new("obj-p1", &TypeRef::Boolean, &json!(true))],
            );
            let obj2 = ObjectDef::new(
                "AnotherObject",
                &[PropDef::new("obj-p1", &TypeRef::Boolean, &json!(true))],
            );
            ObjectDef::into_map(&[obj1, obj2])
        };

        let hasher = SchemaHasher::new(&enums, &objects);
        let h2 = hasher.hash(&f1);

        assert_eq!(h1, h2);

        Ok(())
    }

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

        let enum_nm = "MyEnum";
        let enum_t = TypeRef::Enum(enum_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", &enum_t, &json!("one"))]);

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

        let enums = {
            let enum1 = EnumDef::new(enum_nm, &["one", "two"]);
            EnumDef::into_map(&[enum1])
        };

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

        // Now change a deeply nested enum variant.
        let enums = {
            let enum1 = EnumDef::new(enum_nm, &["one", "two", "newly-added"]);
            EnumDef::into_map(&[enum1])
        };
        let hasher = SchemaHasher::new(&enums, &objs);
        let ne = hasher.hash(&f1);

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