ifc_lite_diff/
fingerprint_checked.rs

1// This Source Code Form is subject to the terms of the Mozilla Public
2// License, v. 2.0. If a copy of the MPL was not distributed with this
3// file, You can obtain one at https://mozilla.org/MPL/2.0/.
4//! Fingerprint builders, with the engine string-length checks of #8114.
5//!
6//! The TypeScript oracle projects the input, then only computes: sorts with
7//! stableSerialize tiebreaks and JSON.stringify per hash. Past projection its
8//! only other outcome is the engine's RangeError for a string over the engine
9//! maximum. A hole costs one `null` (or one separator) of text but no memory,
10//! so the `_checked` builders give the caller each hole-bearing string's exact
11//! UTF-16 length, in the oracle's order and before any O(holes) hashing. A
12//! rejected length returns the caller's error. Hole-free strings are never
13//! offered: they cost the input their own size. Both dense and sparse values
14//! stream canonical UTF-16 into the hasher. The unchecked builders accept every length.
15use std::collections::BTreeMap;
16use std::convert::Infallible;
17use crate::JsString;
18use crate::input::{DataFingerprintInput, PropertyEntryInput, PropertySetInput, QuantitySetInput, TypeAssignmentInput};
19use crate::js_json::{stable_hash_json, utf16_length, JsonValue};
20use crate::projections::sorted_string_list;
21use crate::sparse_collection::SparseCollection;
22use super::{core_attributes, set_to_json, sorted_entries, sorted_property_sets, sorted_quantity_sets,
23    sorted_type_assignments, string_array, with_holes};
24
25fn accept_all<T>(result: Result<T, Infallible>) -> T {
26    match result { Ok(value) => value, Err(never) => match never {} }
27}
28pub(super) fn has_holes(input: &DataFingerprintInput) -> bool {
29    input.property_sets.holes() > 0 || input.quantity_sets.holes() > 0 || input.type_assignments.holes() > 0
30        || input.property_sets.present().any(|set| set.properties.holes() > 0)
31        || input.quantity_sets.present().any(|set| set.quantities.holes() > 0)
32}
33
34/// Strings the oracle builds for one set collection: the stableSerialize
35/// tiebreak of every set sharing its name with another (a sort compares each
36/// adjacent pair of equal names), then, for components, each member array's
37/// JSON.stringify. Only hole-bearing strings are checked: one call with the
38/// longest tiebreak, then one with the longest member text.
39fn check_sets<S, E>(sets: &SparseCollection<S>, part: impl Fn(&S) -> (&JsString, &SparseCollection<PropertyEntryInput>),
40    key: &str, components: bool, check: &mut impl FnMut(u64) -> Result<(), E>) -> Result<(), E> {
41    if !sets.present().any(|set| part(set).1.holes() > 0) { return Ok(()); }
42    let mut names: Vec<&JsString> = sets.present().map(|set| part(set).0).collect();
43    names.sort();
44    let shared = |name: &JsString| names.partition_point(|other| *other < name) + 1 < names.partition_point(|other| *other <= name);
45    let (mut tiebreak, mut members) = (None::<u64>, None::<u64>);
46    for (name, entries) in sets.present().map(&part).filter(|(_, entries)| entries.holes() > 0) {
47        let entries = sorted_entries(entries);
48        if shared(name) {
49            tiebreak = tiebreak.max(Some(utf16_length(&set_to_json(name, key, &entries), true)));
50        }
51        if components {
52            members = members.max(Some(utf16_length(&JsonValue::Array(entries), false)));
53        }
54    }
55    tiebreak.map_or(Ok(()), &mut *check)?;
56    members.map_or(Ok(()), check)
57}
58/// Check the strings the oracle builds while sorting property sets and, for
59/// components, while hashing each set's members (#8114). Call it once the
60/// whole collection is projected, before any later input is read.
61pub fn check_property_sets<E>(sets: &SparseCollection<PropertySetInput>, components: bool,
62    check: &mut impl FnMut(u64) -> Result<(), E>) -> Result<(), E> {
63    check_sets(sets, |set| (&set.name, &set.properties), "properties", components, check)
64}
65/// [`check_property_sets`] for quantity sets.
66pub fn check_quantity_sets<E>(sets: &SparseCollection<QuantitySetInput>, components: bool,
67    check: &mut impl FnMut(u64) -> Result<(), E>) -> Result<(), E> {
68    check_sets(sets, |set| (&set.name, &set.quantities), "quantities", components, check)
69}
70/// The component `type-assignment` text, the only hole-bearing string a type
71/// assignment projection builds before the oracle reads materials (#8114).
72pub fn check_type_assignments<E>(types: &SparseCollection<TypeAssignmentInput>, components: bool,
73    check: &mut impl FnMut(u64) -> Result<(), E>) -> Result<(), E> {
74    if !components || types.holes() == 0 { return Ok(()); }
75    check(utf16_length(&JsonValue::Array(sorted_type_assignments(types)), false))
76}
77
78/// Build the canonical data fingerprint for one entity.
79///
80/// Key order in the hashed object is part of the format: `Type`, `Name`,
81/// `Description`, `ObjectType`, `PredefinedType`, `Tag`, `TypeAssignments`,
82/// `PropertySets`, `QuantitySets`, then `Materials` and `Classifications`
83/// **only when non-empty**.
84pub fn build_data_fingerprint(input: &DataFingerprintInput) -> String {
85    accept_all(build_data_fingerprint_checked(input, |_| Ok(())))
86}
87
88/// [`build_data_fingerprint`], offering `check` each hole-bearing string length
89/// the oracle builds, in its order, before hashing (see the module docs).
90pub fn build_data_fingerprint_checked<E>(input: &DataFingerprintInput,
91    mut check: impl FnMut(u64) -> Result<(), E>) -> Result<String, E> {
92    check_property_sets(&input.property_sets, false, &mut check)?;
93    check_quantity_sets(&input.quantity_sets, false, &mut check)?;
94    let (value, _) = project_data(input);
95    if has_holes(input) { check(utf16_length(&value, false))?; }
96    Ok(stable_hash_json(&value))
97}
98
99pub(super) fn project_data(input: &DataFingerprintInput) -> (JsonValue, usize) {
100    let mut object = core_attributes(input);
101    let core_len = object.len();
102
103    object.push((
104        "TypeAssignments".into(),
105        JsonValue::Array(sorted_type_assignments(&input.type_assignments)),
106    ));
107    object.push((
108        "PropertySets".into(),
109        JsonValue::Array(with_holes(sorted_property_sets(input).into_iter().map(|(_, v)| v).collect(), input.property_sets.holes())),
110    ));
111    object.push((
112        "QuantitySets".into(),
113        JsonValue::Array(with_holes(sorted_quantity_sets(input).into_iter().map(|(_, v)| v).collect(), input.quantity_sets.holes())),
114    ));
115
116    let materials = sorted_string_list(&input.materials);
117    if !materials.is_empty() {
118        object.push(("Materials".into(), string_array(&materials)));
119    }
120    let classifications = sorted_string_list(&input.classifications);
121    if !classifications.is_empty() {
122        object.push(("Classifications".into(), string_array(&classifications)));
123    }
124
125    (JsonValue::Object(object), core_len)
126
127}
128
129/// Per-component sub-hashes, making the conflict unit `(entity, componentKey)`.
130///
131/// Keys match the layer op vocabulary so diff keys and op keys share one
132/// spelling: `attr:core`, `pset:<Name>`, `qset:<Name>`, `type-assignment`,
133/// `material`, `classification`.
134///
135/// Only components the entity actually carries get a key, so adding or
136/// removing one is visible as key presence rather than as an "empty" hash.
137///
138/// Every sub-hash is computed over the same projection
139/// [`build_data_fingerprint`] hashes, the `GlobalId`-free type assignment
140/// included. That is a requirement: the content pass uses these as a collision
141/// guard, retiring an added/deleted pair only once they agree, on the grounds
142/// that a component hashes a slice of what the whole hash covers. Projecting
143/// differently here would turn that guard into a re-export filter, vetoing the
144/// very matches the engine exists to find.
145pub fn build_component_fingerprints(input: &DataFingerprintInput) -> BTreeMap<JsString, String> {
146    build_component_fingerprint_entries(input).into_iter().collect()
147}
148
149/// JavaScript Map insertion order, including first-position/last-value updates
150/// for duplicate component keys. The WASM object boundary consumes this form.
151///
152/// Panics for outer property/quantity-set holes: component iteration requires
153/// a set name. The public JS facade raises its original host TypeError before
154/// crossing this boundary, while native callers must supply named outer sets.
155pub fn build_component_fingerprint_entries(input: &DataFingerprintInput) -> Vec<(JsString, String)> {
156    accept_all(build_component_fingerprint_entries_checked(input, |_| Ok(())))
157}
158
159/// [`build_component_fingerprint_entries`] with [`build_data_fingerprint_checked`]'s
160/// length checks. Like the oracle, a set collection's checks precede the panic
161/// for its outer holes, and each collection's precede the next collection.
162pub fn build_component_fingerprint_entries_checked<E>(input: &DataFingerprintInput,
163    mut check: impl FnMut(u64) -> Result<(), E>) -> Result<Vec<(JsString, String)>, E> {
164    let mut components = OrderedComponents(Vec::new());
165
166    components.insert(
167        "attr:core".into(),
168        stable_hash_json(&JsonValue::Object(core_attributes(input))),
169    );
170
171    check_property_sets(&input.property_sets, true, &mut check)?;
172    assert_eq!(input.property_sets.holes(), 0, "component property sets require present records");
173    let mut ordinals = SetOrdinals::default();
174    for (name, set) in sorted_property_sets(input) {
175        let members = member_array(set, "properties");
176        components.insert(ordinals.key("pset", &name), stable_hash_json(&members));
177    }
178    check_quantity_sets(&input.quantity_sets, true, &mut check)?;
179    assert_eq!(input.quantity_sets.holes(), 0, "component quantity sets require present records");
180    let mut ordinals = SetOrdinals::default();
181    for (name, set) in sorted_quantity_sets(input) {
182        let members = member_array(set, "quantities");
183        components.insert(ordinals.key("qset", &name), stable_hash_json(&members));
184    }
185
186    check_type_assignments(&input.type_assignments, true, &mut check)?;
187    let type_assignments = sorted_type_assignments(&input.type_assignments);
188    if !type_assignments.is_empty() {
189        let value = JsonValue::Array(type_assignments);
190        components.insert("type-assignment".into(), stable_hash_json(&value));
191    }
192
193    let materials = sorted_string_list(&input.materials);
194    if !materials.is_empty() {
195        components.insert(
196            "material".into(),
197            stable_hash_json(&string_array(&materials)),
198        );
199    }
200    let classifications = sorted_string_list(&input.classifications);
201    if !classifications.is_empty() {
202        components.insert(
203            "classification".into(),
204            stable_hash_json(&string_array(&classifications)),
205        );
206    }
207
208    Ok(components.0)
209}
210
211/// Component keys for one sorted set collection (#8136). The first set of a
212/// name keeps `pset:<Name>`; later same-named sets get `pset#<n>:<Name>`
213/// instead of overwriting it, so `dataHash` and the components still cover the
214/// same content. The ordinal sits in the prefix because a name may contain
215/// `#` or `:`; everything after the first `:` is the name. Sets arrive sorted
216/// by name then content, so ordinals follow content order.
217#[derive(Default)]
218pub(super) struct SetOrdinals { last: Option<JsString>, ordinal: u32 }
219impl SetOrdinals {
220    pub(super) fn key(&mut self, kind: &str, name: &JsString) -> JsString {
221        if self.last.as_ref() == Some(name) { self.ordinal += 1; }
222        else { self.last = Some(name.clone()); self.ordinal = 1; }
223        if self.ordinal == 1 { JsString::surround(&format!("{kind}:"), name, "") }
224        else { JsString::surround(&format!("{kind}#{}:", self.ordinal), name, "") }
225    }
226}
227
228pub(super) struct OrderedComponents(pub(super) Vec<(JsString, String)>);
229impl OrderedComponents {
230    pub(super) fn insert(&mut self, key: JsString, value: String) {
231        if let Some((_, old)) = self.0.iter_mut().find(|(name, _)| *name == key) { *old = value; }
232        else { self.0.push((key, value)); }
233    }
234}
235
236/// Pull a set's member array back out of its canonical object form.
237///
238/// The component hash covers only the members, not the wrapping `name`, which
239/// is already carried by the component key itself.
240fn member_array(set: JsonValue, members_key: &str) -> JsonValue {
241    if let JsonValue::Object(entries) = set {
242        for (key, value) in entries {
243            if key == members_key {
244                return value;
245            }
246        }
247    }
248    JsonValue::Array(Vec::new())
249}