Skip to main content

ocpp_kit/
validate.rs

1//! Constraint validation, kept deliberately separate from `serde`.
2//!
3//! OCPP's JSON schemas carry constraints that Rust's type system cannot express
4//! (`maxLength`, `minItems`, numeric ranges, closed enumerations). Running them inside
5//! `Deserialize` would make every failure a `serde` error with no structure, and would tax
6//! the hot path. Instead, deserialization is pure shape-checking and validation is a second,
7//! explicit pass whose output is a list of [`Violation`]s carrying a JSON pointer and a
8//! category — which is exactly what the OCPP error codes are keyed on
9//! (see [`crate::rpc::ErrorCode`]).
10
11use alloc::format;
12use alloc::string::{String, ToString};
13use alloc::vec::Vec;
14use core::fmt;
15
16use crate::decimal::Decimal;
17
18/// One step of a JSON pointer into a payload.
19#[derive(Clone, Copy, Debug, PartialEq, Eq)]
20pub enum PathSegment {
21    /// An object member, always a schema-defined name.
22    Key(&'static str),
23    /// An array index.
24    Index(usize),
25}
26
27/// A cursor into the payload being validated.
28///
29/// The path is only rendered into a [`String`] when a violation is actually recorded, so
30/// validating a valid payload allocates nothing beyond the (reusable) segment stack.
31#[derive(Clone, Debug, Default)]
32pub struct ValidationPath {
33    segments: Vec<PathSegment>,
34}
35
36impl ValidationPath {
37    /// An empty path, pointing at the payload root.
38    #[must_use]
39    pub fn new() -> Self {
40        Self::default()
41    }
42
43    /// Descends into an object member.
44    pub fn push_key(&mut self, key: &'static str) {
45        self.segments.push(PathSegment::Key(key));
46    }
47
48    /// Descends into an array element.
49    pub fn push_index(&mut self, index: usize) {
50        self.segments.push(PathSegment::Index(index));
51    }
52
53    /// Returns to the parent.
54    pub fn pop(&mut self) {
55        self.segments.pop();
56    }
57
58    /// Renders the current position as an RFC 6901 JSON pointer, e.g. `/evse/0/connectorId`.
59    #[must_use]
60    pub fn to_pointer(&self) -> String {
61        if self.segments.is_empty() {
62            return String::new();
63        }
64        let mut out = String::new();
65        for segment in &self.segments {
66            out.push('/');
67            match segment {
68                PathSegment::Key(k) => {
69                    // RFC 6901 escaping; OCPP member names never contain these, but be exact.
70                    out.push_str(&k.replace('~', "~0").replace('/', "~1"));
71                }
72                PathSegment::Index(i) => {
73                    out.push_str(&i.to_string());
74                }
75            }
76        }
77        out
78    }
79}
80
81/// Why a payload is invalid. Maps 1:1 onto the OCPP error codes.
82#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
83#[non_exhaustive]
84pub enum ViolationKind {
85    /// A required member is absent, or an array has too few/too many elements.
86    ///
87    /// → `OccurrenceConstraintViolation`.
88    Occurrence,
89    /// A member has the wrong JSON type.
90    ///
91    /// → `TypeConstraintViolation`.
92    Type,
93    /// A value is out of range, too long, or otherwise outside its constraint.
94    ///
95    /// → `PropertyConstraintViolation`.
96    Property,
97    /// A string was accepted into an enumeration's open `UnknownValue` variant.
98    ///
99    /// → `PropertyConstraintViolation`, unless
100    /// [`DecodeOptions::unknown_enum_values`](crate::decode::DecodeOptions::unknown_enum_values)
101    /// says to preserve it.
102    UnknownEnumValue,
103    /// A member that the schema does not define was present.
104    ///
105    /// → `PropertyConstraintViolation`, unless
106    /// [`DecodeOptions::unknown_fields`](crate::decode::DecodeOptions::unknown_fields)
107    /// says to ignore it.
108    UnknownField,
109    /// The payload is individually well-formed but breaks a cross-field rule.
110    ///
111    /// → `ProtocolError`.
112    Protocol,
113}
114
115impl fmt::Display for ViolationKind {
116    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
117        f.write_str(match self {
118            ViolationKind::Occurrence => "occurrence",
119            ViolationKind::Type => "type",
120            ViolationKind::Property => "property",
121            ViolationKind::UnknownEnumValue => "unknown enum value",
122            ViolationKind::UnknownField => "unknown field",
123            ViolationKind::Protocol => "protocol",
124        })
125    }
126}
127
128/// A single constraint failure.
129#[derive(Clone, Debug, PartialEq, Eq)]
130pub struct Violation {
131    /// RFC 6901 pointer to the offending member, e.g. `/chargingStation/model`.
132    pub path: String,
133    /// Category, which decides the OCPP error code.
134    pub kind: ViolationKind,
135    /// Human-readable reason, e.g. `maxLength 20 exceeded (got 27)`.
136    pub reason: String,
137}
138
139impl fmt::Display for Violation {
140    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
141        if self.path.is_empty() {
142            write!(f, "{}", self.reason)
143        } else {
144            write!(f, "{}: {}", self.path, self.reason)
145        }
146    }
147}
148
149/// The complete result of validating one payload.
150#[derive(Clone, Debug, Default, PartialEq, Eq)]
151pub struct Violations {
152    items: Vec<Violation>,
153}
154
155impl Violations {
156    /// An empty violation list.
157    #[must_use]
158    pub fn new() -> Self {
159        Self::default()
160    }
161
162    #[must_use]
163    /// Whether the payload is free of violations.
164    pub fn is_empty(&self) -> bool {
165        self.items.is_empty()
166    }
167
168    #[must_use]
169    /// How many violations were recorded.
170    pub fn len(&self) -> usize {
171        self.items.len()
172    }
173
174    #[must_use]
175    /// All recorded violations.
176    pub fn as_slice(&self) -> &[Violation] {
177        &self.items
178    }
179
180    /// The first violation, which is the one reported back to the peer.
181    #[must_use]
182    pub fn first(&self) -> Option<&Violation> {
183        self.items.first()
184    }
185
186    /// Records one violation at the current position.
187    pub fn push(&mut self, path: &ValidationPath, kind: ViolationKind, reason: impl Into<String>) {
188        self.items.push(Violation {
189            path: path.to_pointer(),
190            kind,
191            reason: reason.into(),
192        });
193    }
194
195    /// Drops violations of kinds the caller has opted to tolerate.
196    pub fn retain_kinds(&mut self, mut keep: impl FnMut(ViolationKind) -> bool) {
197        self.items.retain(|v| keep(v.kind));
198    }
199
200    #[must_use]
201    /// Unwraps the recorded violations.
202    pub fn into_vec(self) -> Vec<Violation> {
203        self.items
204    }
205}
206
207impl IntoIterator for Violations {
208    type Item = Violation;
209    type IntoIter = alloc::vec::IntoIter<Violation>;
210
211    fn into_iter(self) -> Self::IntoIter {
212        self.items.into_iter()
213    }
214}
215
216impl fmt::Display for Violations {
217    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
218        for (i, v) in self.items.iter().enumerate() {
219            if i > 0 {
220                f.write_str("; ")?;
221            }
222            write!(f, "{v}")?;
223        }
224        Ok(())
225    }
226}
227
228#[cfg(feature = "std")]
229impl std::error::Error for Violations {}
230
231/// Checks the constraints the JSON schema places on a value.
232///
233/// Implemented by every generated payload and data type.
234pub trait Validate {
235    /// Appends this value's violations to `out`, relative to `path`.
236    fn validate_at(&self, path: &mut ValidationPath, out: &mut Violations);
237
238    /// Validates this value from the payload root.
239    fn validate(&self) -> Result<(), Violations> {
240        let mut path = ValidationPath::new();
241        let mut out = Violations::new();
242        self.validate_at(&mut path, &mut out);
243        if out.is_empty() { Ok(()) } else { Err(out) }
244    }
245}
246
247impl<T: Validate> Validate for Option<T> {
248    fn validate_at(&self, path: &mut ValidationPath, out: &mut Violations) {
249        if let Some(v) = self {
250            v.validate_at(path, out);
251        }
252    }
253}
254
255impl<T: Validate> Validate for Vec<T> {
256    fn validate_at(&self, path: &mut ValidationPath, out: &mut Violations) {
257        for (index, item) in self.iter().enumerate() {
258            path.push_index(index);
259            item.validate_at(path, out);
260            path.pop();
261        }
262    }
263}
264
265// ---------------------------------------------------------------------------
266// Helpers used by generated code.
267// ---------------------------------------------------------------------------
268
269/// `minLength` / `maxLength`, counted in characters as the schemas intend.
270pub fn string(
271    value: &str,
272    min: Option<u32>,
273    max: Option<u32>,
274    path: &ValidationPath,
275    out: &mut Violations,
276) {
277    let len = value.chars().count();
278    if let Some(max) = max {
279        if len > max as usize {
280            out.push(
281                path,
282                ViolationKind::Property,
283                format!("maxLength {max} exceeded (got {len} characters)"),
284            );
285        }
286    }
287    if let Some(min) = min {
288        if len < min as usize {
289            out.push(
290                path,
291                ViolationKind::Property,
292                format!("minLength {min} not reached (got {len} characters)"),
293            );
294        }
295    }
296}
297
298/// `minimum` / `maximum` for integers.
299pub fn int_range(
300    value: i64,
301    min: Option<i64>,
302    max: Option<i64>,
303    path: &ValidationPath,
304    out: &mut Violations,
305) {
306    if let Some(min) = min {
307        if value < min {
308            out.push(
309                path,
310                ViolationKind::Property,
311                format!("minimum {min} violated (got {value})"),
312            );
313        }
314    }
315    if let Some(max) = max {
316        if value > max {
317            out.push(
318                path,
319                ViolationKind::Property,
320                format!("maximum {max} violated (got {value})"),
321            );
322        }
323    }
324}
325
326/// `minimum` / `maximum` for numbers.
327///
328/// The bounds are [`Decimal`]s, not `f64`s, so the comparison is the exact one the schema
329/// wrote: a `maximum` of `100` rejects `100.000000000000001` rather than the value it happens
330/// to round to.
331pub fn range(
332    value: Decimal,
333    min: Option<Decimal>,
334    max: Option<Decimal>,
335    path: &ValidationPath,
336    out: &mut Violations,
337) {
338    if let Some(min) = min {
339        if value < min {
340            out.push(
341                path,
342                ViolationKind::Property,
343                format!("minimum {min} violated (got {value})"),
344            );
345        }
346    }
347    if let Some(max) = max {
348        if value > max {
349            out.push(
350                path,
351                ViolationKind::Property,
352                format!("maximum {max} violated (got {value})"),
353            );
354        }
355    }
356}
357
358/// `minItems` / `maxItems`.
359pub fn list_len(
360    len: usize,
361    min: Option<u32>,
362    max: Option<u32>,
363    path: &ValidationPath,
364    out: &mut Violations,
365) {
366    if let Some(min) = min {
367        if len < min as usize {
368            out.push(
369                path,
370                ViolationKind::Occurrence,
371                format!("minItems {min} not reached (got {len})"),
372            );
373        }
374    }
375    if let Some(max) = max {
376        if len > max as usize {
377            out.push(
378                path,
379                ViolationKind::Occurrence,
380                format!("maxItems {max} exceeded (got {len})"),
381            );
382        }
383    }
384}
385
386/// Records a value that was accepted into an enumeration's open `UnknownValue` variant.
387pub fn unknown_enum_value(
388    value: &str,
389    type_name: &'static str,
390    path: &ValidationPath,
391    out: &mut Violations,
392) {
393    out.push(
394        path,
395        ViolationKind::UnknownEnumValue,
396        format!("{value:?} is not a defined value of {type_name}"),
397    );
398}