Skip to main content

oicp_kit/types/
validate.rs

1//! Explicit validation: parse permissively, validate deliberately, construct strictly.
2//!
3//! # Why validation is a separate pass
4//!
5//! A single `PullEvseData` page carries up to a few thousand EVSE records drawn from dozens of
6//! operators. One operator's `HotlinePhoneNumber` that is missing its leading `+` must not make
7//! the other records on that page undecodable — a roaming platform that drops a page because one
8//! CPO is sloppy is worse than one that accepts the page and reports the problem.
9//!
10//! `oicp-kit` therefore follows one rule throughout:
11//!
12//! > **Parse permissively, validate explicitly, construct strictly.**
13//!
14//! * `Deserialize` accepts what the peer sent, as long as it is well-typed JSON.
15//! * [`Validate::validate`] reports *every* violation, each with a JSON Pointer
16//!   ([RFC 6901](https://datatracker.ietf.org/doc/html/rfc6901)) into the object, so a conformance
17//!   report can point at the exact field.
18//! * The constructors ([`EvseId::new`](crate::types::EvseId::new),
19//!   [`Text::new`](crate::types::Text::new), …) refuse to build a value that is already out of
20//!   spec, so data *this* crate emits is conformant by construction.
21//!
22//! The pointers are pointers into the JSON the peer actually sent — they use OICP's wire field
23//! names (`/EvseID`, `/Address/PostalCode`), not the snake-case Rust field names.
24
25use core::fmt;
26
27/// A single spec violation found by [`Validate::validate`].
28#[derive(Clone, Debug, PartialEq, Eq)]
29pub struct Violation {
30    /// JSON Pointer (RFC 6901) to the offending value, relative to the validated object.
31    ///
32    /// The empty string refers to the validated object itself.
33    pub pointer: String,
34    /// Machine-readable classification of the violation.
35    pub code: ViolationCode,
36    /// Human-readable explanation, including the spec rule that was broken.
37    pub message: String,
38}
39
40impl fmt::Display for Violation {
41    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
42        let at = if self.pointer.is_empty() { "/" } else { &self.pointer };
43        write!(f, "{at}: {}", self.message)
44    }
45}
46
47/// Classification of a [`Violation`].
48#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
49#[non_exhaustive]
50pub enum ViolationCode {
51    /// A string exceeded the maximum length given in the spec's property table.
52    TooLong,
53    /// A string was shorter than the spec's minimum.
54    TooShort,
55    /// A string did not match the regular expression the spec gives for its type.
56    PatternMismatch,
57    /// A list that the spec requires to be non-empty was empty.
58    EmptyRequiredList,
59    /// A list exceeded the maximum number of items the spec allows.
60    TooManyItems,
61    /// A value was outside the range the spec allows.
62    OutOfRange,
63    /// A field was syntactically fine but violates a cross-field rule of the spec.
64    Inconsistent,
65    /// A conditionally required field was missing.
66    MissingConditional,
67    /// Exactly one of a group of mutually exclusive fields must be set, and that was not the case.
68    ExclusiveChoice,
69    /// The value cannot survive a JSON round-trip without loss of precision.
70    Imprecise,
71}
72
73impl ViolationCode {
74    /// A short, stable, machine-readable slug for this code.
75    #[must_use]
76    pub const fn as_str(self) -> &'static str {
77        match self {
78            Self::TooLong => "too_long",
79            Self::TooShort => "too_short",
80            Self::PatternMismatch => "pattern_mismatch",
81            Self::EmptyRequiredList => "empty_required_list",
82            Self::TooManyItems => "too_many_items",
83            Self::OutOfRange => "out_of_range",
84            Self::Inconsistent => "inconsistent",
85            Self::MissingConditional => "missing_conditional",
86            Self::ExclusiveChoice => "exclusive_choice",
87            Self::Imprecise => "imprecise",
88        }
89    }
90}
91
92impl fmt::Display for ViolationCode {
93    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
94        f.write_str(self.as_str())
95    }
96}
97
98/// Every [`Violation`] found in one object, in document order.
99#[derive(Clone, Debug, PartialEq, Eq, Default)]
100pub struct Violations(Vec<Violation>);
101
102impl Violations {
103    /// The violations, in document order.
104    #[must_use]
105    pub fn as_slice(&self) -> &[Violation] {
106        &self.0
107    }
108
109    /// Whether no violation was found.
110    #[must_use]
111    pub fn is_empty(&self) -> bool {
112        self.0.is_empty()
113    }
114
115    /// How many violations were found.
116    #[must_use]
117    pub fn len(&self) -> usize {
118        self.0.len()
119    }
120
121    /// Consumes this set and yields the violations.
122    #[must_use]
123    pub fn into_vec(self) -> Vec<Violation> {
124        self.0
125    }
126
127    /// The violations, in document order.
128    pub fn iter(&self) -> core::slice::Iter<'_, Violation> {
129        self.0.iter()
130    }
131}
132
133impl IntoIterator for Violations {
134    type Item = Violation;
135    type IntoIter = std::vec::IntoIter<Violation>;
136    fn into_iter(self) -> Self::IntoIter {
137        self.0.into_iter()
138    }
139}
140
141impl<'a> IntoIterator for &'a Violations {
142    type Item = &'a Violation;
143    type IntoIter = core::slice::Iter<'a, Violation>;
144    fn into_iter(self) -> Self::IntoIter {
145        self.iter()
146    }
147}
148
149impl fmt::Display for Violations {
150    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
151        for (i, v) in self.0.iter().enumerate() {
152            if i > 0 {
153                f.write_str("; ")?;
154            }
155            write!(f, "{v}")?;
156        }
157        Ok(())
158    }
159}
160
161impl std::error::Error for Violations {}
162
163/// Accumulates violations while walking an object graph, tracking the current JSON Pointer.
164#[derive(Debug, Default)]
165pub struct Validator {
166    path: String,
167    found: Vec<Violation>,
168}
169
170impl Validator {
171    /// A validator positioned at the root of an object.
172    #[must_use]
173    pub fn new() -> Self {
174        Self::default()
175    }
176
177    /// Records a violation at the current position.
178    pub fn report(&mut self, code: ViolationCode, message: impl Into<String>) {
179        self.found.push(Violation { pointer: self.path.clone(), code, message: message.into() });
180    }
181
182    /// Records a violation at `field` below the current position.
183    pub fn report_at(&mut self, field: &str, code: ViolationCode, message: impl Into<String>) {
184        self.enter(field);
185        self.report(code, message);
186        self.leave();
187    }
188
189    /// Descends into a named field or array index, escaping it per RFC 6901.
190    pub fn enter(&mut self, segment: &str) {
191        self.path.push('/');
192        for ch in segment.chars() {
193            match ch {
194                '~' => self.path.push_str("~0"),
195                '/' => self.path.push_str("~1"),
196                c => self.path.push(c),
197            }
198        }
199    }
200
201    /// Returns to the parent of the current position.
202    ///
203    /// # Panics
204    ///
205    /// Panics if called more often than [`Validator::enter`].
206    pub fn leave(&mut self) {
207        let cut = self.path.rfind('/').expect("leave() without a matching enter()");
208        self.path.truncate(cut);
209    }
210
211    /// Validates `value` at `segment` below the current position.
212    pub fn field(&mut self, segment: &str, value: &impl Validate) {
213        self.enter(segment);
214        value.validate_in(self);
215        self.leave();
216    }
217
218    /// The JSON Pointer of the current position.
219    #[must_use]
220    pub fn pointer(&self) -> &str {
221        &self.path
222    }
223
224    /// Consumes the validator and yields everything it found.
225    #[must_use]
226    pub fn finish(self) -> Violations {
227        Violations(self.found)
228    }
229}
230
231/// Checks an OICP value against the constraints in the specification's property tables.
232///
233/// See [the validation rule](crate::types#parse-permissively-validate-explicitly-construct-strictly)
234/// for why this is not part of `Deserialize`.
235pub trait Validate {
236    /// Appends this value's violations to `v`, relative to `v`'s current position.
237    fn validate_in(&self, v: &mut Validator);
238
239    /// Validates this value as the root of an object graph.
240    ///
241    /// # Errors
242    ///
243    /// Returns every violation found, in document order.
244    fn validate(&self) -> Result<(), Violations> {
245        let mut v = Validator::new();
246        self.validate_in(&mut v);
247        let found = v.finish();
248        if found.is_empty() { Ok(()) } else { Err(found) }
249    }
250}
251
252impl<T: Validate> Validate for Option<T> {
253    fn validate_in(&self, v: &mut Validator) {
254        if let Some(inner) = self {
255            inner.validate_in(v);
256        }
257    }
258}
259
260impl<T: Validate> Validate for Vec<T> {
261    fn validate_in(&self, v: &mut Validator) {
262        for (i, item) in self.iter().enumerate() {
263            v.enter(&i.to_string());
264            item.validate_in(v);
265            v.leave();
266        }
267    }
268}
269
270impl<T: Validate> Validate for Box<T> {
271    fn validate_in(&self, v: &mut Validator) {
272        T::validate_in(self, v);
273    }
274}
275
276/// Implements [`Validate`] as a no-op for types that carry no spec constraints.
277macro_rules! impl_validate_noop {
278    ($($t:ty),* $(,)?) => {
279        $(impl Validate for $t {
280            fn validate_in(&self, _v: &mut Validator) {}
281        })*
282    };
283}
284
285impl_validate_noop!(bool, i8, i16, i32, i64, u8, u16, u32, u64, usize, String, serde_json::Value);
286
287/// Validates each named field of `$self` in turn.
288///
289/// Expands to a [`Validator::field`] call per field, using the **OICP wire name** as the JSON
290/// Pointer segment, so the pointers a violation reports are pointers into the JSON the peer
291/// actually sent. OICP field names are `PascalCase` with irregular casing (`EvseID`, `lastUpdate`,
292/// `deltaType`), so the wire name is given explicitly rather than derived.
293macro_rules! validate_fields {
294    ($self:ident, $v:ident, $($field:ident as $wire:literal),* $(,)?) => {
295        $( $v.field($wire, &$self.$field); )*
296    };
297}
298
299pub(crate) use validate_fields;
300
301#[cfg(test)]
302mod tests {
303    use super::*;
304
305    struct Leaf(bool);
306    impl Validate for Leaf {
307        fn validate_in(&self, v: &mut Validator) {
308            if !self.0 {
309                v.report(ViolationCode::OutOfRange, "leaf is false");
310            }
311        }
312    }
313
314    #[test]
315    fn pointer_tracks_nesting_and_escapes_rfc6901() {
316        let mut v = Validator::new();
317        v.enter("a/b");
318        v.enter("c~d");
319        v.report(ViolationCode::TooLong, "boom");
320        v.leave();
321        v.leave();
322        let found = v.finish();
323        assert_eq!(found.as_slice()[0].pointer, "/a~1b/c~0d");
324    }
325
326    #[test]
327    fn vec_and_option_are_walked_with_indices() {
328        let value = vec![Leaf(true), Leaf(false), Leaf(false)];
329        let err = value.validate().unwrap_err();
330        assert_eq!(err.len(), 2);
331        assert_eq!(err.as_slice()[0].pointer, "/1");
332        assert_eq!(err.as_slice()[1].pointer, "/2");
333        assert!(Some(Leaf(true)).validate().is_ok());
334        assert!(Option::<Leaf>::None.validate().is_ok());
335    }
336}