Skip to main content

ocpp_kit/rpc/
frame.rs

1//! OCPP-J frame parsing and serialization (Part 4 §4.2, 1.6J §4.2).
2//!
3//! Parsing is two-stage and zero-copy: the JSON array skeleton is split into elements while
4//! the payload stays an unparsed [`RawValue`]. The payload is only deserialized once the
5//! action *and* the direction are known — which is what makes a Local Controller able to
6//! relay a signed message byte-for-byte, and what keeps the "unknown action" path from
7//! paying for a payload parse it will throw away.
8
9use alloc::borrow::Cow;
10use alloc::string::{String, ToString};
11use core::fmt;
12
13use serde_json::value::RawValue;
14
15use crate::types::MessageId;
16use crate::version::Version;
17
18use super::error::{CallErrorRef, ErrorCode};
19
20/// The OCPP-J message type numbers.
21#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
22#[repr(u8)]
23pub enum MessageTypeId {
24    /// `CALL` — a request.
25    Call = 2,
26    /// `CALLRESULT` — a successful answer.
27    CallResult = 3,
28    /// `CALLERROR` — a failed answer.
29    CallError = 4,
30    /// `CALLRESULTERROR` — the answer itself was unusable (OCPP 2.1).
31    CallResultError = 5,
32    /// `SEND` — an unconfirmed message that is never answered (OCPP 2.1).
33    Send = 6,
34}
35
36impl MessageTypeId {
37    /// Maps a message type number, if it is one of the five defined types.
38    #[must_use]
39    pub const fn from_number(number: u8) -> Option<Self> {
40        Some(match number {
41            2 => MessageTypeId::Call,
42            3 => MessageTypeId::CallResult,
43            4 => MessageTypeId::CallError,
44            5 => MessageTypeId::CallResultError,
45            6 => MessageTypeId::Send,
46            _ => return None,
47        })
48    }
49
50    /// The message type number.
51    #[must_use]
52    pub const fn number(self) -> u8 {
53        self as u8
54    }
55
56    /// Whether `version` defines this message type.
57    ///
58    /// `CALLRESULTERROR` and `SEND` are new in 2.1 (Part 4 §4.2).
59    #[must_use]
60    pub const fn is_defined_in(self, version: Version) -> bool {
61        match self {
62            MessageTypeId::CallResultError | MessageTypeId::Send => {
63                version.has_extended_message_types()
64            }
65            _ => true,
66        }
67    }
68}
69
70impl fmt::Display for MessageTypeId {
71    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
72        f.write_str(match self {
73            MessageTypeId::Call => "CALL",
74            MessageTypeId::CallResult => "CALLRESULT",
75            MessageTypeId::CallError => "CALLERROR",
76            MessageTypeId::CallResultError => "CALLRESULTERROR",
77            MessageTypeId::Send => "SEND",
78        })
79    }
80}
81
82/// One OCPP-J frame.
83///
84/// Borrows from the text it was parsed from; [`Frame::into_owned`] detaches it.
85#[derive(Clone, Debug)]
86pub enum Frame<'a> {
87    /// `[2, "<id>", "<action>", {payload}]`
88    Call {
89        /// Correlation id.
90        id: MessageId,
91        /// Action name, exactly as received.
92        action: Cow<'a, str>,
93        /// Unparsed payload object.
94        payload: Cow<'a, RawValue>,
95    },
96    /// `[3, "<id>", {payload}]`
97    CallResult {
98        /// The id of the `CALL` being answered.
99        id: MessageId,
100        /// Unparsed payload object.
101        payload: Cow<'a, RawValue>,
102    },
103    /// `[4, "<id>", "<code>", "<description>", {details}]`
104    CallError {
105        /// The id of the `CALL` being answered.
106        id: MessageId,
107        /// The error.
108        error: CallErrorRef<'a>,
109    },
110    /// `[5, "<id>", "<code>", "<description>", {details}]` — OCPP 2.1.
111    ///
112    /// Sent when a received `CALLRESULT` could not be processed, so the original sender
113    /// learns that its request did not really succeed.
114    CallResultError {
115        /// The id of the `CALLRESULT` being rejected.
116        id: MessageId,
117        /// The error.
118        error: CallErrorRef<'a>,
119    },
120    /// `[6, "<id>", "<action>", {payload}]` — OCPP 2.1.
121    ///
122    /// Unconfirmed: it is never answered, and it may be transmitted while a `CALL` is
123    /// outstanding (Part 4 §4.2.4).
124    Send {
125        /// Identifies the message; never correlated with a response.
126        id: MessageId,
127        /// Action name, exactly as received.
128        action: Cow<'a, str>,
129        /// Unparsed payload object.
130        payload: Cow<'a, RawValue>,
131    },
132}
133
134impl PartialEq for Frame<'_> {
135    /// Payloads compare by their raw JSON text, so a frame is equal to itself after a
136    /// parse/serialize round trip only when the bytes match.
137    fn eq(&self, other: &Self) -> bool {
138        match (self, other) {
139            (
140                Frame::Call {
141                    id: a,
142                    action: aa,
143                    payload: ap,
144                },
145                Frame::Call {
146                    id: b,
147                    action: ba,
148                    payload: bp,
149                },
150            )
151            | (
152                Frame::Send {
153                    id: a,
154                    action: aa,
155                    payload: ap,
156                },
157                Frame::Send {
158                    id: b,
159                    action: ba,
160                    payload: bp,
161                },
162            ) => a == b && aa == ba && ap.get() == bp.get(),
163            (
164                Frame::CallResult { id: a, payload: ap },
165                Frame::CallResult { id: b, payload: bp },
166            ) => a == b && ap.get() == bp.get(),
167            (Frame::CallError { id: a, error: ae }, Frame::CallError { id: b, error: be })
168            | (
169                Frame::CallResultError { id: a, error: ae },
170                Frame::CallResultError { id: b, error: be },
171            ) => a == b && ae == be,
172            _ => false,
173        }
174    }
175}
176
177impl<'a> Frame<'a> {
178    /// The message type of this frame.
179    #[must_use]
180    pub const fn message_type(&self) -> MessageTypeId {
181        match self {
182            Frame::Call { .. } => MessageTypeId::Call,
183            Frame::CallResult { .. } => MessageTypeId::CallResult,
184            Frame::CallError { .. } => MessageTypeId::CallError,
185            Frame::CallResultError { .. } => MessageTypeId::CallResultError,
186            Frame::Send { .. } => MessageTypeId::Send,
187        }
188    }
189
190    /// The correlation id.
191    #[must_use]
192    pub fn id(&self) -> &MessageId {
193        match self {
194            Frame::Call { id, .. }
195            | Frame::CallResult { id, .. }
196            | Frame::CallError { id, .. }
197            | Frame::CallResultError { id, .. }
198            | Frame::Send { id, .. } => id,
199        }
200    }
201
202    /// The action name, for the frame types that carry one.
203    #[must_use]
204    pub fn action(&self) -> Option<&str> {
205        match self {
206            Frame::Call { action, .. } | Frame::Send { action, .. } => Some(action),
207            _ => None,
208        }
209    }
210
211    /// The unparsed payload, for the frame types that carry one.
212    #[must_use]
213    pub fn payload(&self) -> Option<&RawValue> {
214        match self {
215            Frame::Call { payload, .. }
216            | Frame::CallResult { payload, .. }
217            | Frame::Send { payload, .. } => Some(payload),
218            _ => None,
219        }
220    }
221
222    /// Parses one OCPP-J text frame.
223    ///
224    /// `version` decides which message types are accepted; a frame whose type number is not
225    /// defined at all yields [`FrameError::UnknownMessageType`], which the caller must handle
226    /// per version (2.0.1 answers `MessageTypeNotSupported`, 1.6J and 2.1 ignore it).
227    pub fn parse(text: &'a str, version: Version) -> Result<Self, FrameError> {
228        let elements: alloc::vec::Vec<&'a RawValue> =
229            serde_json::from_str(text).map_err(|_| FrameError::NotAnArray)?;
230
231        // Read the type element as a full-width integer: `[300, …]` is a badly chosen
232        // *number*, not a frame that stopped being an array, and §4.4 answers it differently.
233        let number = elements
234            .first()
235            .and_then(|e| serde_json::from_str::<i64>(e.get()).ok())
236            .ok_or(FrameError::NotAnArray)?;
237
238        let Some(message_type) = u8::try_from(number)
239            .ok()
240            .and_then(MessageTypeId::from_number)
241        else {
242            return Err(FrameError::UnknownMessageType {
243                number: raw_number(&elements),
244            });
245        };
246        if !message_type.is_defined_in(version) {
247            return Err(FrameError::MessageTypeNotInVersion {
248                message_type,
249                version,
250            });
251        }
252
253        // Extra trailing elements are tolerated: 1.6J and 2.x both say "at least", and a
254        // peer that appends a future element must not take the connection down.
255        //
256        // The two error frames also tolerate a *short* tail. §4.2.3 requires five elements,
257        // but implementations routinely omit `errorDescription`, `errorDetails` or both, and
258        // refusing one leaves the CALL it answers outstanding until the message timeout.
259        let (arity, minimum) = match message_type {
260            MessageTypeId::Call | MessageTypeId::Send => (4, 4),
261            MessageTypeId::CallResult => (3, 3),
262            MessageTypeId::CallError | MessageTypeId::CallResultError => (5, 3),
263        };
264        if elements.len() < minimum {
265            return Err(FrameError::WrongArity {
266                message_type,
267                found: elements.len(),
268                expected: arity,
269            });
270        }
271
272        let id = string_at(&elements, 1).ok_or(FrameError::UnreadableMessageId { message_type })?;
273        if id.is_empty() {
274            return Err(FrameError::UnreadableMessageId { message_type });
275        }
276        let id = MessageId::from_wire(&id);
277
278        Ok(match message_type {
279            MessageTypeId::Call | MessageTypeId::Send => {
280                let action = string_at(&elements, 2)
281                    .ok_or(FrameError::UnreadableAction { id: id.clone() })?;
282                let payload = Cow::Borrowed(elements[3]);
283                if message_type == MessageTypeId::Call {
284                    Frame::Call {
285                        id,
286                        action: Cow::Owned(action),
287                        payload,
288                    }
289                } else {
290                    Frame::Send {
291                        id,
292                        action: Cow::Owned(action),
293                        payload,
294                    }
295                }
296            }
297            MessageTypeId::CallResult => Frame::CallResult {
298                id,
299                payload: Cow::Borrowed(elements[2]),
300            },
301            MessageTypeId::CallError | MessageTypeId::CallResultError => {
302                let code = string_at(&elements, 2)
303                    .ok_or_else(|| FrameError::UnreadableErrorCode { id: id.clone() })?;
304                let description = string_at(&elements, 3).unwrap_or_default();
305                let details = match elements.get(4) {
306                    Some(raw) => Cow::Borrowed(*raw),
307                    // §4.2.3 requires `{}` when there are no details; a peer that left the
308                    // element out meant exactly that.
309                    None => Cow::Owned(
310                        RawValue::from_string(String::from("{}")).expect("`{}` is valid JSON"),
311                    ),
312                };
313                let error = CallErrorRef {
314                    code: ErrorCode::parse(&code),
315                    description: Cow::Owned(description),
316                    details,
317                };
318                if message_type == MessageTypeId::CallError {
319                    Frame::CallError { id, error }
320                } else {
321                    Frame::CallResultError { id, error }
322                }
323            }
324        })
325    }
326
327    /// Serializes the frame using `version`'s spelling of the error codes.
328    pub fn to_json(&self, version: Version) -> Result<String, serde_json::Error> {
329        match self {
330            Frame::Call {
331                id,
332                action,
333                payload,
334            } => serde_json::to_string(&(2u8, id.as_str(), action.as_ref(), payload.as_ref())),
335            Frame::CallResult { id, payload } => {
336                serde_json::to_string(&(3u8, id.as_str(), payload.as_ref()))
337            }
338            Frame::CallError { id, error } => serde_json::to_string(&(
339                4u8,
340                id.as_str(),
341                error.code.as_wire(version),
342                error.description.as_ref(),
343                error.details.as_ref(),
344            )),
345            Frame::CallResultError { id, error } => serde_json::to_string(&(
346                5u8,
347                id.as_str(),
348                error.code.as_wire(version),
349                error.description.as_ref(),
350                error.details.as_ref(),
351            )),
352            Frame::Send {
353                id,
354                action,
355                payload,
356            } => serde_json::to_string(&(6u8, id.as_str(), action.as_ref(), payload.as_ref())),
357        }
358    }
359
360    /// Detaches the frame from the buffer it was parsed from.
361    #[must_use]
362    pub fn into_owned(self) -> Frame<'static> {
363        fn own(value: Cow<'_, RawValue>) -> Cow<'static, RawValue> {
364            Cow::Owned(value.into_owned())
365        }
366        match self {
367            Frame::Call {
368                id,
369                action,
370                payload,
371            } => Frame::Call {
372                id,
373                action: Cow::Owned(action.into_owned()),
374                payload: own(payload),
375            },
376            Frame::CallResult { id, payload } => Frame::CallResult {
377                id,
378                payload: own(payload),
379            },
380            Frame::Send {
381                id,
382                action,
383                payload,
384            } => Frame::Send {
385                id,
386                action: Cow::Owned(action.into_owned()),
387                payload: own(payload),
388            },
389            Frame::CallError { id, error } => Frame::CallError {
390                id,
391                error: error.into_owned(),
392            },
393            Frame::CallResultError { id, error } => Frame::CallResultError {
394                id,
395                error: error.into_owned(),
396            },
397        }
398    }
399}
400
401fn string_at(elements: &[&RawValue], index: usize) -> Option<String> {
402    let raw = elements.get(index)?;
403    serde_json::from_str::<String>(raw.get()).ok()
404}
405
406fn raw_number(elements: &[&RawValue]) -> String {
407    elements
408        .first()
409        .map_or_else(|| "?".to_string(), |e| e.get().to_string())
410}
411
412/// Why a text frame could not be turned into a [`Frame`].
413#[derive(Clone, Debug, PartialEq, Eq)]
414#[non_exhaustive]
415pub enum FrameError {
416    /// Not valid JSON, or not a JSON array with a numeric message type first.
417    NotAnArray,
418    /// The array has fewer elements than the message type requires.
419    WrongArity {
420        /// The message type that was read.
421        message_type: MessageTypeId,
422        /// How many elements the array had.
423        found: usize,
424        /// How many it needed.
425        expected: usize,
426    },
427    /// A message type number outside 2–6.
428    ///
429    /// Part 4 §4.4: 1.6J and 2.1 ignore the message; 2.0.1 answers `MessageTypeNotSupported`.
430    UnknownMessageType {
431        /// The raw JSON of the type element.
432        number: String,
433    },
434    /// A message type that exists in OCPP but not in the negotiated version
435    /// (`CALLRESULTERROR` and `SEND` before 2.1).
436    MessageTypeNotInVersion {
437        /// The message type that was read.
438        message_type: MessageTypeId,
439        /// The negotiated version.
440        version: Version,
441    },
442    /// The `MessageId` element is missing, empty, or not a JSON string.
443    ///
444    /// 2.x answers with id `"-1"` (Part 4 §4.1.1); the message type decides *which* answer,
445    /// so it is kept even though the id could not be read.
446    UnreadableMessageId {
447        /// The message type that was read.
448        message_type: MessageTypeId,
449    },
450    /// The action element is not a JSON string.
451    UnreadableAction {
452        /// The id to answer with.
453        id: MessageId,
454    },
455    /// The error-code element is not a JSON string.
456    UnreadableErrorCode {
457        /// The id to answer with.
458        id: MessageId,
459    },
460}
461
462/// How a frame that could not be parsed must be answered (Part 4 §4.2.3).
463///
464/// `CALLERROR` "is sent in response to a CALL", `CALLRESULTERROR` "on receipt of a CALLRESULT
465/// that contains errors" — and an unparseable error frame gets neither, or two peers end up
466/// trading error frames over a message that was already an error.
467#[derive(Clone, Copy, Debug, PartialEq, Eq)]
468pub enum FrameReply {
469    /// Say nothing. The frame was a `SEND`, or was itself an error frame, or the version
470    /// says to ignore it.
471    Ignore,
472    /// Answer with a `CALLERROR`.
473    CallError,
474    /// Answer with a `CALLRESULTERROR` (OCPP 2.1 only; before that the failure stays local).
475    CallResultError,
476}
477
478impl FrameError {
479    /// The message type of the frame that failed to parse, when it got far enough to be read.
480    #[must_use]
481    pub fn message_type(&self) -> Option<MessageTypeId> {
482        match self {
483            FrameError::WrongArity { message_type, .. }
484            | FrameError::MessageTypeNotInVersion { message_type, .. }
485            | FrameError::UnreadableMessageId { message_type } => Some(*message_type),
486            _ => None,
487        }
488    }
489
490    /// What the receiver must send back, per Part 4 §4.2.3.
491    #[must_use]
492    pub fn reply(&self, version: Version) -> FrameReply {
493        if self.is_ignorable(version) {
494            return FrameReply::Ignore;
495        }
496        // A type this version does not define is, to this version, an unknown type number,
497        // so §4.4 applies unchanged and `message_type()` must not be consulted: a type-6 frame
498        // on 2.0.1 is not "a SEND", because 2.0.1 has no SEND to recognise it as.
499        if matches!(self, FrameError::MessageTypeNotInVersion { .. }) {
500            return FrameReply::CallError;
501        }
502        match self.message_type() {
503            // "A CALLRESULTERROR is sent back on receipt of a CALLRESULT that contains
504            // errors" — and only 2.1 has one to send.
505            Some(MessageTypeId::CallResult) => {
506                if version.has_extended_message_types() {
507                    FrameReply::CallResultError
508                } else {
509                    FrameReply::Ignore
510                }
511            }
512            // A SEND is never answered (§4.2.4, FR.07), and a broken error frame has no
513            // answer defined for it.
514            Some(
515                MessageTypeId::Send | MessageTypeId::CallError | MessageTypeId::CallResultError,
516            ) => FrameReply::Ignore,
517            // A CALL, or a frame too broken to classify: §4.2.3's "-1" case.
518            Some(MessageTypeId::Call) | None => FrameReply::CallError,
519        }
520    }
521
522    /// Whether the specification says to silently ignore this frame rather than answer it.
523    ///
524    /// True only for a message type this version does not define, on 1.6J (§4.1.3) and 2.1
525    /// (§4.4). OCPP 2.0.1 §4.4 instead requires a `CALLERROR: MessageTypeNotSupported`.
526    #[must_use]
527    pub fn is_ignorable(&self, version: Version) -> bool {
528        matches!(
529            self,
530            FrameError::UnknownMessageType { .. } | FrameError::MessageTypeNotInVersion { .. }
531        ) && !matches!(version, Version::V2_0_1)
532    }
533
534    /// The `CALLERROR` code to answer with, if the frame must be answered at all.
535    #[must_use]
536    pub fn error_code(&self) -> ErrorCode {
537        match self {
538            FrameError::UnknownMessageType { .. } | FrameError::MessageTypeNotInVersion { .. } => {
539                ErrorCode::MessageTypeNotSupported
540            }
541            _ => ErrorCode::RpcFrameworkError,
542        }
543    }
544
545    /// The id to use in the answer. `"-1"` when the incoming id could not be read.
546    #[must_use]
547    pub fn reply_id(&self) -> MessageId {
548        match self {
549            FrameError::UnreadableAction { id } | FrameError::UnreadableErrorCode { id } => {
550                id.clone()
551            }
552            _ => MessageId::unreadable(),
553        }
554    }
555}
556
557impl fmt::Display for FrameError {
558    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
559        match self {
560            FrameError::NotAnArray => f.write_str("frame is not a JSON array with a message type"),
561            FrameError::WrongArity {
562                message_type,
563                found,
564                expected,
565            } => {
566                write!(f, "{message_type} needs {expected} elements, got {found}")
567            }
568            FrameError::UnknownMessageType { number } => {
569                write!(f, "unknown message type number {number}")
570            }
571            FrameError::MessageTypeNotInVersion {
572                message_type,
573                version,
574            } => {
575                write!(f, "{message_type} is not defined in OCPP {version}")
576            }
577            FrameError::UnreadableMessageId { message_type } => {
578                write!(f, "the MessageId of a {message_type} could not be read")
579            }
580            FrameError::UnreadableAction { .. } => f.write_str("action could not be read"),
581            FrameError::UnreadableErrorCode { .. } => f.write_str("error code could not be read"),
582        }
583    }
584}
585
586#[cfg(feature = "std")]
587impl std::error::Error for FrameError {}