rustev-contract 0.3.0

Rustev's versioned wire contract: documents, bounded parsing, canonical form and identities.
Documentation
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
//! Evidence grades, value metadata and presence (spec 032, 3.2 to 3.4).
//!
//! A grade states evidence quality, never permission: `authoritative` means
//! "attested live by the system that owns the fact", not "authorized"
//! (spec 032, 2.1). Grade is metadata, not a value kind, and is orthogonal
//! to derivation class.

use std::collections::BTreeMap;

use serde::{Deserialize, Serialize};
use serde_json::Value;

use crate::canonical::{CanonicalError, canonical_value_bytes, tagged_digest};
use crate::definition::ProvenanceClass;
use crate::time::Timestamp;

/// The tag of a value digest (spec 032, 3.1.5).
pub const VALUE_TAG: &str = "rustev.value/1";

/// `sha256:` and 64 hex digits over `rustev.value/1 || 0x00 || canonical
/// bytes` of a decoded value (spec 032, 3.1.5).
pub fn value_digest(value: &Value) -> Result<String, CanonicalError> {
    Ok(tagged_digest(VALUE_TAG, &canonical_value_bytes(value)?))
}

/// The closed, ordered evidence grade. The derived order runs weakest to
/// strongest, so `min` and `max` are the grade order of spec 032, 3.2.1.
#[derive(
    Debug,
    Clone,
    Copy,
    PartialEq,
    Eq,
    PartialOrd,
    Ord,
    Hash,
    Serialize,
    Deserialize,
    schemars::JsonSchema,
)]
#[serde(rename_all = "snake_case")]
pub enum Grade {
    /// A label from a source declared unreliable for that field, or a
    /// constructed key not yet corroborated.
    Hint,
    /// A computed or crawled approximation that never was authoritative.
    Estimated,
    /// Was authoritative at its as-of time and has not been revalidated.
    Cached,
    /// Live, attested by the system that owns the fact.
    Authoritative,
}

impl Grade {
    /// Strongest first, the order the spec lists them in.
    pub const ALL: [Grade; 4] = [
        Grade::Authoritative,
        Grade::Cached,
        Grade::Estimated,
        Grade::Hint,
    ];

    pub fn name(self) -> &'static str {
        match self {
            Grade::Authoritative => "authoritative",
            Grade::Cached => "cached",
            Grade::Estimated => "estimated",
            Grade::Hint => "hint",
        }
    }
}

/// A value's grade, or `ungraded` when no graded value contributed.
/// `ungraded` is not a point of the grade order (spec 032, 3.2.3).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, schemars::JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum ValueGrade {
    Authoritative,
    Cached,
    Estimated,
    Hint,
    Ungraded,
}

impl ValueGrade {
    pub fn graded(self) -> Option<Grade> {
        match self {
            ValueGrade::Authoritative => Some(Grade::Authoritative),
            ValueGrade::Cached => Some(Grade::Cached),
            ValueGrade::Estimated => Some(Grade::Estimated),
            ValueGrade::Hint => Some(Grade::Hint),
            ValueGrade::Ungraded => None,
        }
    }

    /// The grade combination of spec 032, 3.2.2: the minimum over graded
    /// parts; ungraded parts do not participate.
    pub fn combine(self, other: ValueGrade) -> ValueGrade {
        match (self.graded(), other.graded()) {
            (Some(a), Some(b)) => a.min(b).into(),
            (Some(a), None) | (None, Some(a)) => a.into(),
            (None, None) => ValueGrade::Ungraded,
        }
    }

    pub fn name(self) -> &'static str {
        match self.graded() {
            Some(g) => g.name(),
            None => "ungraded",
        }
    }
}

impl From<Grade> for ValueGrade {
    fn from(g: Grade) -> Self {
        match g {
            Grade::Authoritative => ValueGrade::Authoritative,
            Grade::Cached => ValueGrade::Cached,
            Grade::Estimated => ValueGrade::Estimated,
            Grade::Hint => ValueGrade::Hint,
        }
    }
}

/// The oldest as-of among contributing graded values, or `none`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
#[serde(rename_all = "snake_case", deny_unknown_fields)]
pub enum AsOf {
    None,
    Ms(Timestamp),
}

impl AsOf {
    /// The older of two as-of times; `none` contributes nothing.
    pub fn oldest(self, other: AsOf) -> AsOf {
        match (self, other) {
            (AsOf::Ms(a), AsOf::Ms(b)) => AsOf::Ms(a.min(b)),
            (AsOf::Ms(a), AsOf::None) | (AsOf::None, AsOf::Ms(a)) => AsOf::Ms(a),
            (AsOf::None, AsOf::None) => AsOf::None,
        }
    }
}

/// Which side of a merge a field came from (spec 032, 3.6.3).
#[derive(
    Debug,
    Clone,
    Copy,
    PartialEq,
    Eq,
    PartialOrd,
    Ord,
    Hash,
    Serialize,
    Deserialize,
    schemars::JsonSchema,
)]
#[serde(rename_all = "snake_case")]
pub enum MergeSide {
    Base,
    Overlay,
}

/// How a value's metadata came about (spec 032, 3.2.2).
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
#[serde(rename_all = "snake_case", deny_unknown_fields)]
pub enum Basis {
    /// An item supplied by an acquisition source (spec 036, 3.4.6).
    Acquired {
        step: String,
    },
    /// An input.
    Declared,
    /// An exact step or the policy.
    Computed,
    Corroborated {
        step: String,
    },
    Merged {
        step: String,
        side: MergeSide,
    },
    /// An input whose disagreement a declared rule resolved.
    Resolved {
        input: String,
    },
}

/// Value metadata (spec 032, 3.2.2): carried by every input and step value
/// of a plan 3 evaluation. A record carries one per field, a list one per
/// item and a map one per entry, in the optional members.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct ValueMeta {
    pub grade: ValueGrade,
    /// Sorted, duplicate-free.
    pub provenance: Vec<ProvenanceClass>,
    /// Sorted, duplicate-free source names.
    pub sources: Vec<String>,
    pub as_of_ms: AsOf,
    pub basis: Basis,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub fields: Option<BTreeMap<String, ValueMeta>>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub items: Option<Vec<ValueMeta>>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub entries: Option<BTreeMap<String, ValueMeta>>,
}

impl ValueMeta {
    /// Metadata to which nothing graded contributed.
    pub fn ungraded(basis: Basis) -> Self {
        ValueMeta {
            grade: ValueGrade::Ungraded,
            provenance: vec![],
            sources: vec![],
            as_of_ms: AsOf::None,
            basis,
            fields: None,
            items: None,
            entries: None,
        }
    }

    /// The combination of spec 032, 3.2.2 (minimum graded grade, union of
    /// provenance and sources, oldest as-of) under `basis`, without parts.
    pub fn combination<'a>(parts: impl IntoIterator<Item = &'a ValueMeta>, basis: Basis) -> Self {
        let mut out = ValueMeta::ungraded(basis);
        for p in parts {
            out.grade = out.grade.combine(p.grade);
            out.provenance.extend(p.provenance.iter().copied());
            out.sources.extend(p.sources.iter().cloned());
            out.as_of_ms = out.as_of_ms.oldest(p.as_of_ms);
        }
        out.provenance.sort();
        out.provenance.dedup();
        out.sources.sort();
        out.sources.dedup();
        out
    }
}

/// A record presence predicate (spec 032, 3.4.2). Each list is non-empty;
/// the canonical form sorts and deduplicates every field list.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
#[serde(rename_all = "snake_case", deny_unknown_fields)]
pub enum PresentWhen {
    AnyNonNull(Vec<String>),
    AllNonNull(Vec<String>),
    All(Vec<PresentWhen>),
    Any(Vec<PresentWhen>),
}

impl PresentWhen {
    /// The declared tree with each field list sorted and deduplicated.
    pub fn canonical(&self) -> PresentWhen {
        let sorted = |v: &[String]| {
            let mut v = v.to_vec();
            v.sort();
            v.dedup();
            v
        };
        match self {
            PresentWhen::AnyNonNull(f) => PresentWhen::AnyNonNull(sorted(f)),
            PresentWhen::AllNonNull(f) => PresentWhen::AllNonNull(sorted(f)),
            PresentWhen::All(ps) => PresentWhen::All(ps.iter().map(Self::canonical).collect()),
            PresentWhen::Any(ps) => PresentWhen::Any(ps.iter().map(Self::canonical).collect()),
        }
    }

    /// Nesting depth (a leaf is 1) and the number of leaf predicates.
    pub fn shape(&self) -> (usize, usize) {
        match self {
            PresentWhen::AnyNonNull(_) | PresentWhen::AllNonNull(_) => (1, 1),
            PresentWhen::All(ps) | PresentWhen::Any(ps) => ps.iter().fold((1, 0), |(d, n), p| {
                let (pd, pn) = p.shape();
                (d.max(pd + 1), n.saturating_add(pn))
            }),
        }
    }

    /// Every field the predicate names, in reading order.
    pub fn fields(&self, out: &mut Vec<String>) {
        match self {
            PresentWhen::AnyNonNull(f) | PresentWhen::AllNonNull(f) => {
                out.extend(f.iter().cloned())
            }
            PresentWhen::All(ps) | PresentWhen::Any(ps) => ps.iter().for_each(|p| p.fields(out)),
        }
    }

    /// Evaluate over `is_null(field)`.
    pub fn holds(&self, is_null: &dyn Fn(&str) -> bool) -> bool {
        match self {
            PresentWhen::AnyNonNull(f) => f.iter().any(|x| !is_null(x)),
            PresentWhen::AllNonNull(f) => f.iter().all(|x| !is_null(x)),
            PresentWhen::All(ps) => ps.iter().all(|p| p.holds(is_null)),
            PresentWhen::Any(ps) => ps.iter().any(|p| p.holds(is_null)),
        }
    }
}

/// Why a value is absent (spec 032, 3.4.3 and 3.6.2).
#[derive(
    Debug,
    Clone,
    Copy,
    PartialEq,
    Eq,
    PartialOrd,
    Ord,
    Hash,
    Serialize,
    Deserialize,
    schemars::JsonSchema,
)]
#[serde(rename_all = "snake_case")]
pub enum AbsentReason {
    PredicateFailed,
    OverlayMissing,
    BaseMissing,
    OverlayMissingBaseBelowGrade,
    OverlayAndBaseMissing,
    AcceptanceFailed {
        cause: crate::extraction_results::AcceptanceFailure,
    },
}

impl AbsentReason {
    pub fn name(self) -> &'static str {
        match self {
            AbsentReason::AcceptanceFailed { .. } => "acceptance_failed",
            AbsentReason::PredicateFailed => "predicate_failed",
            AbsentReason::OverlayMissing => "overlay_missing",
            AbsentReason::BaseMissing => "base_missing",
            AbsentReason::OverlayMissingBaseBelowGrade => "overlay_missing_base_below_grade",
            AbsentReason::OverlayAndBaseMissing => "overlay_and_base_missing",
        }
    }
}

/// A value's presence status. Key existence alone is never presence.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
#[serde(rename_all = "snake_case", deny_unknown_fields)]
pub enum Presence {
    Present,
    Absent {
        reason: AbsentReason,
        /// The canonical predicate that failed, for `predicate_failed`.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        predicate: Option<PresentWhen>,
    },
}

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

    #[test]
    fn grade_order_and_combination() {
        assert!(Grade::Authoritative > Grade::Cached);
        assert!(Grade::Cached > Grade::Estimated);
        assert!(Grade::Estimated > Grade::Hint);
        let a = ValueGrade::Authoritative;
        assert_eq!(a.combine(ValueGrade::Hint), ValueGrade::Hint);
        assert_eq!(a.combine(ValueGrade::Ungraded), a, "ungraded never lowers");
        assert_eq!(
            ValueGrade::Ungraded.combine(ValueGrade::Ungraded),
            ValueGrade::Ungraded
        );
        assert_eq!(
            ValueGrade::Hint.combine(ValueGrade::Ungraded),
            ValueGrade::Hint,
            "ungraded never raises"
        );
    }

    #[test]
    fn present_when_shape_and_canonical_form() {
        let p = PresentWhen::All(vec![
            PresentWhen::AnyNonNull(vec!["b".into(), "a".into(), "a".into()]),
            PresentWhen::AllNonNull(vec!["c".into()]),
        ]);
        assert_eq!(p.shape(), (2, 2));
        assert_eq!(
            p.canonical(),
            PresentWhen::All(vec![
                PresentWhen::AnyNonNull(vec!["a".into(), "b".into()]),
                PresentWhen::AllNonNull(vec!["c".into()]),
            ])
        );
        // a null, b set, c null: any(a, b) holds, all(c) does not.
        let null = |f: &str| f != "b";
        assert!(!p.holds(&null));
    }

    #[test]
    fn value_digest_is_tagged() {
        let d = value_digest(&serde_json::json!({"b": 1, "a": "x"})).unwrap();
        assert!(d.starts_with("sha256:") && d.len() == 71);
        assert_eq!(
            d,
            value_digest(&serde_json::json!({"a": "x", "b": 1})).unwrap()
        );
    }
}