Skip to main content

ocpp_kit/rpc/
error.rs

1//! OCPP-J error codes and `CALLERROR` payloads.
2
3use alloc::borrow::{Cow, ToOwned};
4use alloc::format;
5use alloc::string::{String, ToString};
6use core::fmt;
7
8use crate::decode::{DecodeError, DecodeErrorKind};
9use crate::version::Version;
10
11/// An OCPP-J RPC framework error code (2.1 Part 4 Table 9; 1.6J Table 7).
12///
13/// The wire spelling is version-dependent and the differences are not cosmetic:
14///
15/// | Variant | 1.6J | 2.0.1 / 2.1 |
16/// |---|---|---|
17/// | [`FormatViolation`](Self::FormatViolation) | `FormationViolation` | `FormatViolation` |
18/// | [`OccurrenceConstraintViolation`](Self::OccurrenceConstraintViolation) | `OccurenceConstraintViolation` (one `r`, as printed in the specification) | `OccurrenceConstraintViolation` |
19/// | [`RpcFrameworkError`](Self::RpcFrameworkError) | not defined — sent as `GenericError` | `RpcFrameworkError` |
20/// | [`MessageTypeNotSupported`](Self::MessageTypeNotSupported) | not defined — sent as `GenericError` | `MessageTypeNotSupported` |
21///
22/// Parsing accepts every spelling on every version, because peers mix them up constantly.
23#[derive(Clone, Debug, PartialEq, Eq, Hash)]
24#[non_exhaustive]
25pub enum ErrorCode {
26    /// The payload is syntactically incorrect.
27    FormatViolation,
28    /// Any error not covered by a more specific code.
29    GenericError,
30    /// The receiver failed internally while processing the action.
31    InternalError,
32    /// A message type number the receiver does not support (2.x only).
33    MessageTypeNotSupported,
34    /// The requested action is not known to the receiver.
35    NotImplemented,
36    /// The action is known but not supported by the receiver.
37    NotSupported,
38    /// A field violates an occurrence constraint.
39    OccurrenceConstraintViolation,
40    /// A field contains an invalid value.
41    PropertyConstraintViolation,
42    /// The payload does not conform to the action's PDU structure.
43    ProtocolError,
44    /// The message is not a valid RPC request — for example the `MessageId` could not be
45    /// read (2.x only).
46    RpcFrameworkError,
47    /// A security issue prevented the receiver from completing the action.
48    SecurityError,
49    /// A field violates a data-type constraint.
50    TypeConstraintViolation,
51    /// A code this crate does not define, kept verbatim.
52    Other(String),
53}
54
55impl ErrorCode {
56    /// The spelling this code uses on the wire for `version`.
57    ///
58    /// Codes that a version does not define are downgraded to `GenericError`, which is the
59    /// only code 1.6J offers for "something else went wrong".
60    #[must_use]
61    pub fn as_wire(&self, version: Version) -> &str {
62        let legacy = version == Version::V1_6;
63        match self {
64            ErrorCode::FormatViolation => {
65                if legacy {
66                    "FormationViolation"
67                } else {
68                    "FormatViolation"
69                }
70            }
71            ErrorCode::GenericError => "GenericError",
72            ErrorCode::InternalError => "InternalError",
73            ErrorCode::MessageTypeNotSupported => {
74                if legacy {
75                    "GenericError"
76                } else {
77                    "MessageTypeNotSupported"
78                }
79            }
80            ErrorCode::NotImplemented => "NotImplemented",
81            ErrorCode::NotSupported => "NotSupported",
82            ErrorCode::OccurrenceConstraintViolation => {
83                if legacy {
84                    // The 1.6J specification prints it with a single `r`.
85                    "OccurenceConstraintViolation"
86                } else {
87                    "OccurrenceConstraintViolation"
88                }
89            }
90            ErrorCode::PropertyConstraintViolation => "PropertyConstraintViolation",
91            ErrorCode::ProtocolError => "ProtocolError",
92            ErrorCode::RpcFrameworkError => {
93                if legacy {
94                    "GenericError"
95                } else {
96                    "RpcFrameworkError"
97                }
98            }
99            ErrorCode::SecurityError => "SecurityError",
100            ErrorCode::TypeConstraintViolation => "TypeConstraintViolation",
101            ErrorCode::Other(code) => code.as_str(),
102        }
103    }
104
105    /// Parses a wire code, accepting every version's spelling.
106    #[must_use]
107    pub fn parse(code: &str) -> Self {
108        match code {
109            "FormatViolation" | "FormationViolation" => ErrorCode::FormatViolation,
110            "GenericError" => ErrorCode::GenericError,
111            "InternalError" => ErrorCode::InternalError,
112            "MessageTypeNotSupported" => ErrorCode::MessageTypeNotSupported,
113            "NotImplemented" => ErrorCode::NotImplemented,
114            "NotSupported" => ErrorCode::NotSupported,
115            "OccurrenceConstraintViolation" | "OccurenceConstraintViolation" => {
116                ErrorCode::OccurrenceConstraintViolation
117            }
118            "PropertyConstraintViolation" => ErrorCode::PropertyConstraintViolation,
119            "ProtocolError" => ErrorCode::ProtocolError,
120            "RpcFrameworkError" => ErrorCode::RpcFrameworkError,
121            "SecurityError" => ErrorCode::SecurityError,
122            "TypeConstraintViolation" => ErrorCode::TypeConstraintViolation,
123            other => ErrorCode::Other(other.to_owned()),
124        }
125    }
126
127    /// Whether `version` defines this code at all.
128    #[must_use]
129    pub fn is_defined_in(&self, version: Version) -> bool {
130        match self {
131            ErrorCode::RpcFrameworkError | ErrorCode::MessageTypeNotSupported => {
132                version != Version::V1_6
133            }
134            ErrorCode::Other(_) => false,
135            _ => true,
136        }
137    }
138}
139
140impl fmt::Display for ErrorCode {
141    /// Uses the 2.x spelling; call [`as_wire`](Self::as_wire) when the version matters.
142    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
143        f.write_str(self.as_wire(Version::V2_1))
144    }
145}
146
147/// The longest `errorDescription` the specification allows (Part 4, Table 7).
148pub const ERROR_DESCRIPTION_MAX_LEN: usize = 255;
149
150/// Truncates a description to the length the wire format allows.
151///
152/// Descriptions are built from decoding failures, which quote paths and values and can run
153/// long. Emitting an over-long one would be a violation in the very message that reports a
154/// violation.
155fn cap_description(text: &str) -> String {
156    match text.char_indices().nth(ERROR_DESCRIPTION_MAX_LEN) {
157        Some((cut, _)) => text[..cut].to_owned(),
158        None => text.to_owned(),
159    }
160}
161
162/// The body of a `CALLERROR` (or, in 2.1, a `CALLRESULTERROR`).
163#[derive(Clone, Debug, PartialEq)]
164pub struct CallError {
165    /// The RPC framework error code.
166    pub code: ErrorCode,
167    /// Short human-readable description. Empty is allowed; the spec suggests `""`.
168    pub description: String,
169    /// Free-form details object. Never `null` on the wire — an empty object is used.
170    pub details: serde_json::Value,
171}
172
173impl CallError {
174    /// Builds a `CALLERROR` body with an empty details object.
175    #[must_use]
176    pub fn new(code: ErrorCode, description: impl Into<String>) -> Self {
177        Self {
178            code,
179            description: cap_description(&description.into()),
180            details: serde_json::Value::Object(serde_json::Map::new()),
181        }
182    }
183
184    /// Attaches a details object.
185    #[must_use]
186    pub fn with_details(mut self, details: serde_json::Value) -> Self {
187        self.details = details;
188        self
189    }
190
191    /// The action is not known to this implementation.
192    #[must_use]
193    pub fn not_implemented(action: &str) -> Self {
194        Self::new(
195            ErrorCode::NotImplemented,
196            format!("unknown action {action:?}"),
197        )
198    }
199
200    /// The action is known but this peer does not handle it.
201    #[must_use]
202    pub fn not_supported(action: &str) -> Self {
203        Self::new(
204            ErrorCode::NotSupported,
205            format!("action {action:?} is not supported"),
206        )
207    }
208
209    /// The handler failed.
210    #[must_use]
211    pub fn internal(description: impl Into<String>) -> Self {
212        Self::new(ErrorCode::InternalError, description)
213    }
214
215    /// A security check failed while processing the action.
216    #[must_use]
217    pub fn security(description: impl Into<String>) -> Self {
218        Self::new(ErrorCode::SecurityError, description)
219    }
220}
221
222impl From<DecodeError> for CallError {
223    /// Maps a decoding failure onto the error code the specification prescribes, and puts
224    /// the offending JSON pointer into `errorDetails` so the peer can find it.
225    fn from(error: DecodeError) -> Self {
226        let code = match error.kind {
227            DecodeErrorKind::Format => ErrorCode::FormatViolation,
228            DecodeErrorKind::Occurrence => ErrorCode::OccurrenceConstraintViolation,
229            DecodeErrorKind::Type => ErrorCode::TypeConstraintViolation,
230            DecodeErrorKind::Property => ErrorCode::PropertyConstraintViolation,
231            // "Payload for Action is not conform the PDU structure" — an undefined member is
232            // exactly that, since the 2.x schemas set `additionalProperties: false`.
233            DecodeErrorKind::UnknownField | DecodeErrorKind::Protocol => ErrorCode::ProtocolError,
234            DecodeErrorKind::UnsupportedAction => ErrorCode::NotSupported,
235        };
236        let mut details = serde_json::Map::new();
237        if !error.path.is_empty() {
238            details.insert(
239                "path".to_string(),
240                serde_json::Value::String(error.path.clone()),
241            );
242        }
243        details.insert(
244            "reason".to_string(),
245            serde_json::Value::String(error.reason.clone()),
246        );
247        Self {
248            code,
249            description: cap_description(&error.to_string()),
250            details: serde_json::Value::Object(details),
251        }
252    }
253}
254
255impl fmt::Display for CallError {
256    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
257        if self.description.is_empty() {
258            write!(f, "{}", self.code)
259        } else {
260            write!(f, "{}: {}", self.code, self.description)
261        }
262    }
263}
264
265#[cfg(feature = "std")]
266impl std::error::Error for CallError {}
267
268/// Borrowed form of [`CallError`], as produced by frame parsing.
269///
270/// The details object stays unparsed so a Local Controller can relay it untouched.
271#[derive(Clone, Debug)]
272pub struct CallErrorRef<'a> {
273    /// The RPC framework error code.
274    pub code: ErrorCode,
275    /// Short human-readable description.
276    pub description: Cow<'a, str>,
277    /// Free-form details object, still unparsed.
278    pub details: Cow<'a, serde_json::value::RawValue>,
279}
280
281impl CallErrorRef<'_> {
282    /// Copies the borrowed error into an owned [`CallError`].
283    #[must_use]
284    pub fn to_call_error(&self) -> CallError {
285        CallError {
286            code: self.code.clone(),
287            description: self.description.clone().into_owned(),
288            details: serde_json::from_str(self.details.get())
289                .unwrap_or_else(|_| serde_json::Value::Object(serde_json::Map::new())),
290        }
291    }
292
293    /// Detaches the error from the buffer it was parsed from.
294    #[must_use]
295    pub fn into_owned(self) -> CallErrorRef<'static> {
296        CallErrorRef {
297            code: self.code,
298            description: Cow::Owned(self.description.into_owned()),
299            details: Cow::Owned(self.details.into_owned()),
300        }
301    }
302}
303
304impl PartialEq for CallErrorRef<'_> {
305    /// Compares the details object by its raw JSON text.
306    fn eq(&self, other: &Self) -> bool {
307        self.code == other.code
308            && self.description == other.description
309            && self.details.get() == other.details.get()
310    }
311}
312
313impl From<CallError> for CallErrorRef<'static> {
314    fn from(error: CallError) -> Self {
315        CallErrorRef {
316            code: error.code,
317            description: Cow::Owned(cap_description(&error.description)),
318            details: Cow::Owned(
319                serde_json::value::to_raw_value(&error.details).unwrap_or_else(|_| {
320                    serde_json::value::RawValue::from_string("{}".to_string()).expect("valid")
321                }),
322            ),
323        }
324    }
325}
326
327impl From<&CallError> for CallErrorRef<'static> {
328    fn from(error: &CallError) -> Self {
329        CallErrorRef {
330            code: error.code.clone(),
331            description: Cow::Owned(cap_description(&error.description)),
332            details: Cow::Owned(
333                serde_json::value::to_raw_value(&error.details).unwrap_or_else(|_| {
334                    serde_json::value::RawValue::from_string("{}".to_string()).expect("valid")
335                }),
336            ),
337        }
338    }
339}