Skip to main content

ocpp_kit/
decode.rs

1//! Payload decoding with spec-exact failure classification.
2//!
3//! OCPP does not have one "bad payload" error. It has five, and answering with the wrong one
4//! is a conformance failure that most implementations make because they collapse every
5//! `serde` error into a single code. This module keeps them apart:
6//!
7//! | What went wrong | [`DecodeErrorKind`] |
8//! |---|---|
9//! | The payload is not a JSON object, or the JSON is malformed | [`Format`](DecodeErrorKind::Format) |
10//! | A required member is missing, or an array is too short/long | [`Occurrence`](DecodeErrorKind::Occurrence) |
11//! | A member has the wrong JSON type | [`Type`](DecodeErrorKind::Type) |
12//! | A value is too long, out of range, or an undefined enum value | [`Property`](DecodeErrorKind::Property) |
13//! | A member the schema does not define was present (strict mode) | [`UnknownField`](DecodeErrorKind::UnknownField) |
14//! | Cross-field rules broken | [`Protocol`](DecodeErrorKind::Protocol) |
15//!
16//! [`DecodeOptions`] additionally carries the leniency knobs that make it possible to talk to
17//! the substantial share of field devices that do not follow the schemas. Leniency is
18//! implemented as a bounded *repair loop*: the strict parse runs first, and only when it
19//! fails is the offending member — identified by path — rewritten and the parse retried. A
20//! conforming payload therefore costs exactly one strict parse.
21
22use alloc::borrow::ToOwned;
23use alloc::format;
24use alloc::string::{String, ToString};
25use alloc::vec::Vec;
26use core::fmt;
27
28use serde::de::DeserializeOwned;
29use serde_json::value::RawValue;
30
31use crate::validate::{Validate, ViolationKind};
32
33/// How to treat enumeration values the schema does not define.
34#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
35pub enum UnknownEnumValues {
36    /// Fail with [`DecodeErrorKind::Property`].
37    #[default]
38    Reject,
39    /// Keep them in the enum's open `UnknownValue` variant.
40    Preserve,
41}
42
43/// How to treat members the schema does not define.
44///
45/// The 2.x schemas say `additionalProperties: false`, but rejecting is not the safe default
46/// in the field: stations routinely add vendor members outside `customData`.
47#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
48pub enum UnknownFields {
49    /// Fail with [`DecodeErrorKind::UnknownField`].
50    Reject,
51    /// Drop them.
52    #[default]
53    Ignore,
54}
55
56/// How much to forgive in `dateTime` members.
57#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
58pub enum DateTimeLeniency {
59    /// RFC 3339 with a mandatory offset, as the schemas require.
60    #[default]
61    Strict,
62    /// Also accept a missing offset, interpreted as UTC.
63    AllowNaive,
64    /// Also accept a space instead of `T`, and a missing offset.
65    AllowSpace,
66}
67
68/// How to treat numbers sent as JSON strings (`"42"`).
69#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
70pub enum NumericStrings {
71    /// Fail with [`DecodeErrorKind::Type`].
72    #[default]
73    Reject,
74    /// Convert them, when the string is a valid number.
75    Coerce,
76}
77
78/// Decoding policy. The strict default is exactly what the specification requires.
79#[derive(Clone, Debug, PartialEq, Eq)]
80#[non_exhaustive]
81pub struct DecodeOptions {
82    /// Enumeration values the schema does not define.
83    pub unknown_enum_values: UnknownEnumValues,
84    /// Members the schema does not define.
85    pub unknown_fields: UnknownFields,
86    /// `dateTime` spellings.
87    pub datetime: DateTimeLeniency,
88    /// Numbers sent as strings.
89    pub numeric_strings: NumericStrings,
90    /// Upper bound on one *payload*, in bytes — the fourth element of a `CALL`, not the
91    /// whole frame.
92    ///
93    /// The frame is bounded earlier and elsewhere, at the socket, by
94    /// [`Csms::max_message_size_bytes`](crate::transport::CsmsBuilder::max_message_size_bytes);
95    /// this is the second line, and it is what a handler that decodes a payload of its own
96    /// gets for free. OCPP sets no limit of its own, and `NotifyReport` and
97    /// `GetCompositeSchedule` payloads can be large, so the default is generous.
98    pub max_payload_size: usize,
99    /// Upper bound on the number of leniency repairs applied to one payload.
100    pub max_repairs: usize,
101}
102
103impl Default for DecodeOptions {
104    fn default() -> Self {
105        Self::strict()
106    }
107}
108
109impl DecodeOptions {
110    /// Exactly what the specification requires. The default.
111    #[must_use]
112    pub const fn strict() -> Self {
113        Self {
114            unknown_enum_values: UnknownEnumValues::Reject,
115            unknown_fields: UnknownFields::Ignore,
116            datetime: DateTimeLeniency::Strict,
117            numeric_strings: NumericStrings::Reject,
118            max_payload_size: 1024 * 1024,
119            max_repairs: 32,
120        }
121    }
122
123    /// Everything the schemas require, plus rejection of undefined members.
124    ///
125    /// Useful in tests and for a CSMS that wants to hold its fleet to the letter of
126    /// `additionalProperties: false`.
127    #[must_use]
128    pub const fn pedantic() -> Self {
129        Self {
130            unknown_fields: UnknownFields::Reject,
131            ..Self::strict()
132        }
133    }
134
135    /// The knobs field devices actually need: undefined enum values and members are kept,
136    /// offset-less and space-separated timestamps are accepted, and numeric strings are
137    /// coerced.
138    #[must_use]
139    pub const fn lenient() -> Self {
140        Self {
141            unknown_enum_values: UnknownEnumValues::Preserve,
142            unknown_fields: UnknownFields::Ignore,
143            datetime: DateTimeLeniency::AllowSpace,
144            numeric_strings: NumericStrings::Coerce,
145            max_payload_size: 1024 * 1024,
146            max_repairs: 32,
147        }
148    }
149
150    /// Sets the maximum accepted payload size.
151    #[must_use]
152    pub const fn with_max_payload_size(mut self, bytes: usize) -> Self {
153        self.max_payload_size = bytes;
154        self
155    }
156
157    fn repairs_enabled(&self) -> bool {
158        self.datetime != DateTimeLeniency::Strict || self.numeric_strings == NumericStrings::Coerce
159    }
160}
161
162/// The category of a decoding failure, which decides the OCPP error code.
163#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
164#[non_exhaustive]
165pub enum DecodeErrorKind {
166    /// Malformed JSON, or a payload that is not a JSON object.
167    Format,
168    /// A required member is absent, or an array's cardinality is wrong.
169    Occurrence,
170    /// A member has the wrong JSON type.
171    Type,
172    /// A value violates a `maxLength`, range, or enumeration constraint.
173    Property,
174    /// A member the schema does not define was present.
175    UnknownField,
176    /// Individually valid members that break a cross-field rule.
177    Protocol,
178    /// The action is not defined for this direction or version.
179    UnsupportedAction,
180}
181
182/// A decoding failure, carrying enough detail to fill an OCPP `CALLERROR`.
183#[derive(Clone, Debug, PartialEq, Eq)]
184pub struct DecodeError {
185    /// Which OCPP error code this maps to.
186    pub kind: DecodeErrorKind,
187    /// RFC 6901 pointer to the offending member, empty for whole-payload failures.
188    pub path: String,
189    /// Human-readable reason, suitable for `errorDescription`.
190    pub reason: String,
191}
192
193impl DecodeError {
194    /// Builds a decoding failure.
195    #[must_use]
196    pub fn new(kind: DecodeErrorKind, path: impl Into<String>, reason: impl Into<String>) -> Self {
197        Self {
198            kind,
199            path: path.into(),
200            reason: reason.into(),
201        }
202    }
203
204    /// The action is not valid for this direction or version.
205    #[must_use]
206    pub fn unsupported_action(action: &str) -> Self {
207        Self::new(
208            DecodeErrorKind::UnsupportedAction,
209            "",
210            format!("action {action:?} is not valid in this direction"),
211        )
212    }
213
214    #[must_use]
215    fn from_violation(violation: &crate::validate::Violation) -> Self {
216        let kind = match violation.kind {
217            ViolationKind::Occurrence => DecodeErrorKind::Occurrence,
218            ViolationKind::Type => DecodeErrorKind::Type,
219            ViolationKind::Property | ViolationKind::UnknownEnumValue => DecodeErrorKind::Property,
220            ViolationKind::UnknownField => DecodeErrorKind::UnknownField,
221            ViolationKind::Protocol => DecodeErrorKind::Protocol,
222        };
223        Self::new(kind, violation.path.clone(), violation.reason.clone())
224    }
225}
226
227impl fmt::Display for DecodeError {
228    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
229        if self.path.is_empty() {
230            write!(f, "{}", self.reason)
231        } else {
232            write!(f, "{}: {}", self.path, self.reason)
233        }
234    }
235}
236
237#[cfg(feature = "std")]
238impl std::error::Error for DecodeError {}
239
240/// Decodes and validates one payload according to `options`.
241///
242/// Used by the generated `CsRequest::decode` / `CsmsRequest::decode` dispatchers, and usable
243/// directly when the action is known statically.
244pub fn decode_payload<T: DeserializeOwned + serde::Serialize + Validate>(
245    payload: &RawValue,
246    options: &DecodeOptions,
247) -> Result<T, DecodeError> {
248    let text = payload.get();
249    if text.len() > options.max_payload_size {
250        return Err(DecodeError::new(
251            DecodeErrorKind::Format,
252            "",
253            format!(
254                "payload is {} bytes, limit is {}",
255                text.len(),
256                options.max_payload_size
257            ),
258        ));
259    }
260    // Part 4 §4.2.1: the payload of a CALL / CALLRESULT is a JSON object.
261    if !text.trim_start().starts_with('{') {
262        return Err(DecodeError::new(
263            DecodeErrorKind::Format,
264            "",
265            "payload is not a JSON object",
266        ));
267    }
268
269    let value: T = match parse(text) {
270        Ok(value) => value,
271        Err(error) if options.repairs_enabled() => repair_and_parse(text, options, &error)?,
272        Err(error) => return Err(error),
273    };
274
275    if options.unknown_fields == UnknownFields::Reject {
276        if let Some(path) = first_unknown_field(text, &value)? {
277            return Err(DecodeError::new(
278                DecodeErrorKind::UnknownField,
279                path,
280                "member is not defined by the schema",
281            ));
282        }
283    }
284
285    let mut violations = match value.validate() {
286        Ok(()) => return Ok(value),
287        Err(violations) => violations,
288    };
289    if options.unknown_enum_values == UnknownEnumValues::Preserve {
290        violations.retain_kinds(|kind| kind != ViolationKind::UnknownEnumValue);
291    }
292    match violations.first() {
293        Some(violation) => Err(DecodeError::from_violation(violation)),
294        None => Ok(value),
295    }
296}
297
298/// Decodes a payload and serializes the typed value straight back.
299///
300/// Used by [`v2_1::transcode_request`](crate::v2_1::transcode_request) and friends: what comes
301/// out is what the Rust types actually model, so comparing it with the input reveals any
302/// member the types drop.
303pub fn transcode<T: DeserializeOwned + serde::Serialize + Validate>(
304    payload: &RawValue,
305    options: &DecodeOptions,
306) -> Result<alloc::boxed::Box<RawValue>, DecodeError> {
307    let value = decode_payload::<T>(payload, options)?;
308    serde_json::value::to_raw_value(&value)
309        .map_err(|error| DecodeError::new(DecodeErrorKind::Format, "", error.to_string()))
310}
311
312fn parse<T: DeserializeOwned>(text: &str) -> Result<T, DecodeError> {
313    let mut deserializer = serde_json::Deserializer::from_str(text);
314    match serde_path_to_error::deserialize(&mut deserializer) {
315        Ok(value) => Ok(value),
316        Err(error) => Err(classify(&error)),
317    }
318}
319
320/// Maps a `serde` failure onto the OCPP error taxonomy.
321///
322/// `serde`'s messages are the only structured signal available for derived impls, so the
323/// mapping is pinned by tests (see the module's unit tests) — a `serde` change that altered
324/// the wording would fail CI rather than silently downgrade every error to `FormatViolation`.
325fn classify(error: &serde_path_to_error::Error<serde_json::Error>) -> DecodeError {
326    let path = pointer_from(&error.path().to_string());
327    let inner = error.inner();
328    let message = inner.to_string();
329    let kind = match inner.classify() {
330        serde_json::error::Category::Syntax | serde_json::error::Category::Eof => {
331            DecodeErrorKind::Format
332        }
333        serde_json::error::Category::Io => DecodeErrorKind::Format,
334        serde_json::error::Category::Data => {
335            // A missing member and a wrong array length are both occurrence constraints.
336            if message.starts_with("missing field") || message.starts_with("invalid length") {
337                DecodeErrorKind::Occurrence
338            } else if message.starts_with("invalid type") {
339                DecodeErrorKind::Type
340            } else if message.starts_with("unknown field") {
341                DecodeErrorKind::UnknownField
342            } else if message.starts_with("duplicate field") {
343                DecodeErrorKind::Format
344            } else {
345                // `invalid value: …` and every custom error our own impls raise
346                // (undefined enum value, bad RFC 3339 timestamp).
347                DecodeErrorKind::Property
348            }
349        }
350    };
351    // The trailing " at line L column C" is noise once a path is available.
352    let reason = match message.rfind(" at line ") {
353        Some(cut) => message[..cut].to_owned(),
354        None => message,
355    };
356    DecodeError::new(kind, path, reason)
357}
358
359/// `serde_path_to_error` renders paths as `a.b.0.c`; OCPP error details use JSON pointers.
360fn pointer_from(path: &str) -> String {
361    if path.is_empty() || path == "." {
362        return String::new();
363    }
364    let mut out = String::with_capacity(path.len() + 1);
365    for segment in path.split('.') {
366        out.push('/');
367        out.push_str(&segment.replace('~', "~0").replace('/', "~1"));
368    }
369    out
370}
371
372// ---------------------------------------------------------------------------
373// Leniency repairs
374// ---------------------------------------------------------------------------
375
376/// Re-parses `text` after rewriting the member the strict parse tripped over, repeating for
377/// as long as progress is made and `options.max_repairs` allows.
378fn repair_and_parse<T: DeserializeOwned>(
379    text: &str,
380    options: &DecodeOptions,
381    first: &DecodeError,
382) -> Result<T, DecodeError> {
383    let mut json: serde_json::Value = serde_json::from_str(text)
384        .map_err(|error| DecodeError::new(DecodeErrorKind::Format, "", error.to_string()))?;
385
386    let mut error = first.clone();
387    for _ in 0..options.max_repairs {
388        if !apply_repair(&mut json, &error, options) {
389            return Err(error);
390        }
391        match serde_path_to_error::deserialize::<_, T>(&json) {
392            Ok(value) => return Ok(value),
393            Err(next) => {
394                let next = classify(&next);
395                if next == error {
396                    return Err(next);
397                }
398                error = next;
399            }
400        }
401    }
402    Err(error)
403}
404
405/// Rewrites the single member `error` points at. Returns `false` when no repair applies.
406fn apply_repair(
407    json: &mut serde_json::Value,
408    error: &DecodeError,
409    options: &DecodeOptions,
410) -> bool {
411    let Some(slot) = pointer_mut(json, &error.path) else {
412        return false;
413    };
414    let Some(text) = slot.as_str().map(ToOwned::to_owned) else {
415        return false;
416    };
417
418    // A number that arrived as a string.
419    if options.numeric_strings == NumericStrings::Coerce && error.kind == DecodeErrorKind::Type {
420        if let Ok(number) = text.parse::<serde_json::Number>() {
421            *slot = serde_json::Value::Number(number);
422            return true;
423        }
424    }
425
426    // A timestamp without an offset, or with a space instead of `T`.
427    if options.datetime != DateTimeLeniency::Strict && error.kind == DecodeErrorKind::Property {
428        let allow_space = options.datetime == DateTimeLeniency::AllowSpace;
429        if !allow_space && text.contains(' ') {
430            return false;
431        }
432        let normalized = crate::types::normalize_datetime(&text);
433        if normalized != text && crate::types::DateTime::parse(&normalized).is_ok() {
434            *slot = serde_json::Value::String(normalized);
435            return true;
436        }
437    }
438    false
439}
440
441/// Resolves an RFC 6901 pointer to a mutable slot.
442fn pointer_mut<'a>(
443    value: &'a mut serde_json::Value,
444    pointer: &str,
445) -> Option<&'a mut serde_json::Value> {
446    if pointer.is_empty() {
447        return Some(value);
448    }
449    let mut current = value;
450    for raw in pointer.trim_start_matches('/').split('/') {
451        let key = raw.replace("~1", "/").replace("~0", "~");
452        current = match current {
453            serde_json::Value::Object(map) => map.get_mut(&key)?,
454            serde_json::Value::Array(items) => items.get_mut(key.parse::<usize>().ok()?)?,
455            _ => return None,
456        };
457    }
458    Some(current)
459}
460
461// ---------------------------------------------------------------------------
462// Strict unknown-field detection
463// ---------------------------------------------------------------------------
464
465/// Finds the first member present on the wire but absent from the decoded value.
466///
467/// Implemented by re-serializing the decoded payload and diffing, which needs no schema
468/// descriptors and cannot drift from the types. It runs only when
469/// [`UnknownFields::Reject`] is configured.
470fn first_unknown_field<T: serde::Serialize>(
471    text: &str,
472    value: &T,
473) -> Result<Option<String>, DecodeError> {
474    let wire: serde_json::Value = serde_json::from_str(text)
475        .map_err(|error| DecodeError::new(DecodeErrorKind::Format, "", error.to_string()))?;
476    let ours = serde_json::to_value(value)
477        .map_err(|error| DecodeError::new(DecodeErrorKind::Format, "", error.to_string()))?;
478    let mut path = Vec::new();
479    Ok(diff(&wire, &ours, &mut path))
480}
481
482fn diff(
483    wire: &serde_json::Value,
484    ours: &serde_json::Value,
485    path: &mut Vec<String>,
486) -> Option<String> {
487    match (wire, ours) {
488        (serde_json::Value::Object(w), serde_json::Value::Object(o)) => {
489            for (key, value) in w {
490                if value.is_null() {
491                    continue; // an explicit null is indistinguishable from an absent member
492                }
493                path.push(key.replace('~', "~0").replace('/', "~1"));
494                let found = match o.get(key) {
495                    None => Some(render(path)),
496                    Some(mine) => diff(value, mine, path),
497                };
498                path.pop();
499                if found.is_some() {
500                    return found;
501                }
502            }
503            None
504        }
505        (serde_json::Value::Array(w), serde_json::Value::Array(o)) => {
506            for (index, (value, mine)) in w.iter().zip(o).enumerate() {
507                path.push(index.to_string());
508                let found = diff(value, mine, path);
509                path.pop();
510                if found.is_some() {
511                    return found;
512                }
513            }
514            None
515        }
516        _ => None,
517    }
518}
519
520fn render(path: &[String]) -> String {
521    let mut out = String::new();
522    for segment in path {
523        out.push('/');
524        out.push_str(segment);
525    }
526    out
527}