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