Skip to main content

oicp_kit/types/
status.rs

1//! `StatusCode` and `Code` — OICP's error table, as a type that knows what its values mean.
2
3use core::fmt;
4use core::str::FromStr;
5
6use serde::{Deserialize, Serialize};
7
8use super::builder::strict_builder;
9use super::text::Text;
10use super::validate::{Validate, Validator, ViolationCode, validate_fields};
11
12/// One of the status codes OICP 2.3 defines, or a code this crate has not seen.
13///
14/// The specification gives these as a table of three-digit strings in the `StatusCode.Code`
15/// description. They are the *only* machine-readable signal a partner gets about why an operation
16/// failed, so this crate makes them a type rather than a string: the semantics —
17/// [is this retryable?](Self::is_retryable), [is this an authorization
18/// failure?](Self::is_authorization_failure) — are encoded once, from the spec table, instead of
19/// being re-derived (and got wrong) at every call site.
20///
21/// A code Hubject adds later lands in [`Code::Custom`] and is preserved, like every other open
22/// value in this crate.
23#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
24#[non_exhaustive]
25pub enum Code {
26    /// `000` — Success. *(General)*
27    Success,
28    /// `001` — Hubject system error. *(Internal system)*
29    HubjectSystemError,
30    /// `002` — Hubject database error. *(Internal system)*
31    HubjectDatabaseError,
32    /// `009` — Data transaction error. *(Internal system)*
33    DataTransactionError,
34    /// `017` — Unauthorized Access. *(Internal system)*
35    ///
36    /// In practice this almost always means the `OperatorID`/`ProviderID` in the URL does not
37    /// match the TLS client certificate Hubject sees. See
38    /// [`ClientIdentity`](crate::client::ClientIdentity), which catches the mismatch locally.
39    UnauthorizedAccess,
40    /// `018` — Inconsistent EvseID. *(Internal system)*
41    InconsistentEvseId,
42    /// `019` — Inconsistent EvcoID. *(Internal system)*
43    InconsistentEvcoId,
44    /// `021` — System error. *(General)*
45    SystemError,
46    /// `022` — Data error. *(General)*
47    DataError,
48    /// `101` — QR Code Authentication failed – Invalid Credentials. *(Authentication)*
49    QrCodeAuthenticationFailed,
50    /// `102` — RFID Authentication failed – invalid UID. *(Authentication)*
51    RfidInvalidUid,
52    /// `103` — RFID Authentication failed – card not readable. *(Authentication)*
53    RfidCardNotReadable,
54    /// `105` — PLC Authentication failed - invalid EvcoID. *(Authentication)*
55    PlcInvalidEvcoId,
56    /// `106` — No positive authentication response. *(Authentication / Internal system)*
57    NoPositiveAuthenticationResponse,
58    /// `110` — QR Code App Authentication failed – time out error. *(Authentication)*
59    QrCodeAppTimeout,
60    /// `120` — PLC (ISO/IEC 15118) Authentication failed – invalid underlying EvcoID.
61    /// *(Authentication)*
62    PlcInvalidUnderlyingEvcoId,
63    /// `121` — PLC (ISO/IEC 15118) Authentication failed – invalid certificate. *(Authentication)*
64    PlcInvalidCertificate,
65    /// `122` — PLC (ISO/IEC 15118) Authentication failed – time out error. *(Authentication)*
66    PlcTimeout,
67    /// `200` — EvcoID locked. *(Authentication)*
68    EvcoIdLocked,
69    /// `210` — No valid contract. *(Session)*
70    NoValidContract,
71    /// `300` — Partner not found. *(Session)*
72    PartnerNotFound,
73    /// `310` — Partner did not respond. *(Session)*
74    PartnerDidNotRespond,
75    /// `320` — Service not available. *(Session)*
76    ServiceNotAvailable,
77    /// `400` — Session is invalid. *(Session)*
78    SessionIsInvalid,
79    /// `501` — Communication to EVSE failed. *(EVSE)*
80    CommunicationToEvseFailed,
81    /// `510` — No EV connected to EVSE. *(EVSE)*
82    NoEvConnectedToEvse,
83    /// `601` — EVSE already reserved. *(EVSE)*
84    EvseAlreadyReserved,
85    /// `602` — EVSE already in use / wrong token. *(EVSE)*
86    EvseAlreadyInUse,
87    /// `603` — Unknown EVSE ID. *(EVSE)*
88    UnknownEvseId,
89    /// `604` — EVSE ID is not Hubject compatible. *(EVSE)*
90    EvseIdNotHubjectCompatible,
91    /// `700` — EVSE out of service. *(EVSE)*
92    EvseOutOfService,
93    /// A code this crate does not know, preserved exactly as it arrived.
94    Custom(String),
95}
96
97/// Which area of the protocol a [`Code`] belongs to, per the spec table's third column.
98#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
99#[non_exhaustive]
100pub enum CodeArea {
101    /// General codes.
102    General,
103    /// Internal system codes.
104    InternalSystem,
105    /// Authentication codes.
106    Authentication,
107    /// Session codes.
108    Session,
109    /// EVSE codes.
110    Evse,
111    /// A code this crate does not know.
112    Unknown,
113}
114
115macro_rules! code_table {
116    ($( $variant:ident = $wire:literal, $area:ident, $text:literal );* $(;)?) => {
117        impl Code {
118            /// Every code this crate knows, in numeric order.
119            pub const ALL: &'static [Self] = &[ $( Self::$variant ),* ];
120
121            /// The three-digit code as it appears on the wire.
122            #[must_use]
123            pub fn as_str(&self) -> &str {
124                match self {
125                    $( Self::$variant => $wire, )*
126                    Self::Custom(s) => s.as_str(),
127                }
128            }
129
130            /// The specification's description of this code.
131            #[must_use]
132            pub fn description(&self) -> &str {
133                match self {
134                    $( Self::$variant => $text, )*
135                    Self::Custom(_) => "a status code this version of oicp-kit does not know",
136                }
137            }
138
139            /// Which area of the protocol this code belongs to.
140            #[must_use]
141            pub fn area(&self) -> CodeArea {
142                match self {
143                    $( Self::$variant => CodeArea::$area, )*
144                    Self::Custom(_) => CodeArea::Unknown,
145                }
146            }
147
148            /// Whether this is a code the specification documents.
149            #[must_use]
150            pub fn is_known(&self) -> bool {
151                !matches!(self, Self::Custom(_))
152            }
153        }
154
155        impl From<&str> for Code {
156            fn from(s: &str) -> Self {
157                match s {
158                    $( $wire => Self::$variant, )*
159                    other => Self::Custom(other.to_owned()),
160                }
161            }
162        }
163    };
164}
165
166code_table! {
167    Success = "000", General, "Success";
168    HubjectSystemError = "001", InternalSystem, "Hubject system error";
169    HubjectDatabaseError = "002", InternalSystem, "Hubject database error";
170    DataTransactionError = "009", InternalSystem, "Data transaction error";
171    UnauthorizedAccess = "017", InternalSystem, "Unauthorized Access";
172    InconsistentEvseId = "018", InternalSystem, "Inconsistent EvseID";
173    InconsistentEvcoId = "019", InternalSystem, "Inconsistent EvcoID";
174    SystemError = "021", General, "System error";
175    DataError = "022", General, "Data error";
176    QrCodeAuthenticationFailed = "101", Authentication, "QR Code Authentication failed - Invalid Credentials";
177    RfidInvalidUid = "102", Authentication, "RFID Authentication failed - invalid UID";
178    RfidCardNotReadable = "103", Authentication, "RFID Authentication failed - card not readable";
179    PlcInvalidEvcoId = "105", Authentication, "PLC Authentication failed - invalid EvcoID";
180    NoPositiveAuthenticationResponse = "106", Authentication, "No positive authentication response";
181    QrCodeAppTimeout = "110", Authentication, "QR Code App Authentication failed - time out error";
182    PlcInvalidUnderlyingEvcoId = "120", Authentication, "PLC (ISO/IEC 15118) Authentication failed - invalid underlying EvcoID";
183    PlcInvalidCertificate = "121", Authentication, "PLC (ISO/IEC 15118) Authentication failed - invalid certificate";
184    PlcTimeout = "122", Authentication, "PLC (ISO/IEC 15118) Authentication failed - time out error";
185    EvcoIdLocked = "200", Authentication, "EvcoID locked";
186    NoValidContract = "210", Session, "No valid contract";
187    PartnerNotFound = "300", Session, "Partner not found";
188    PartnerDidNotRespond = "310", Session, "Partner did not respond";
189    ServiceNotAvailable = "320", Session, "Service not available";
190    SessionIsInvalid = "400", Session, "Session is invalid";
191    CommunicationToEvseFailed = "501", Evse, "Communication to EVSE failed";
192    NoEvConnectedToEvse = "510", Evse, "No EV connected to EVSE";
193    EvseAlreadyReserved = "601", Evse, "EVSE already reserved";
194    EvseAlreadyInUse = "602", Evse, "EVSE already in use/ wrong token";
195    UnknownEvseId = "603", Evse, "Unknown EVSE ID";
196    EvseIdNotHubjectCompatible = "604", Evse, "EVSE ID is not Hubject compatible";
197    EvseOutOfService = "700", Evse, "EVSE out of service";
198}
199
200impl Code {
201    /// Whether this code means the operation succeeded.
202    #[must_use]
203    pub fn is_success(&self) -> bool {
204        matches!(self, Self::Success)
205    }
206
207    /// Whether re-sending the identical request could plausibly succeed.
208    ///
209    /// True for transient conditions on Hubject's side or the counterparty's — `001`, `002`,
210    /// `009`, `021`, `310`, `320`. **False** for every authorization decision, every data error
211    /// and every EVSE-state code: retrying `210 No valid contract` or `601 EVSE already reserved`
212    /// cannot help, and retrying `017 Unauthorized Access` will not fix a certificate.
213    ///
214    /// [`RetryPolicy`](crate::client::RetryPolicy) uses exactly this.
215    #[must_use]
216    pub fn is_retryable(&self) -> bool {
217        matches!(
218            self,
219            Self::HubjectSystemError
220                | Self::HubjectDatabaseError
221                | Self::DataTransactionError
222                | Self::SystemError
223                | Self::PartnerDidNotRespond
224                | Self::ServiceNotAvailable
225        )
226    }
227
228    /// Whether this code reports that the driver may not charge.
229    ///
230    /// Every `Authentication`-area code plus `210 No valid contract` — the codes that answer
231    /// "may this session start?" with "no", as opposed to "something broke".
232    #[must_use]
233    pub fn is_authorization_failure(&self) -> bool {
234        self.area() == CodeArea::Authentication || matches!(self, Self::NoValidContract)
235    }
236
237    /// Whether this code is about the state of the charging point rather than the request.
238    #[must_use]
239    pub fn is_evse_problem(&self) -> bool {
240        self.area() == CodeArea::Evse
241    }
242}
243
244impl fmt::Display for Code {
245    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
246        write!(f, "{} {}", self.as_str(), self.description())
247    }
248}
249
250impl FromStr for Code {
251    type Err = core::convert::Infallible;
252    fn from_str(s: &str) -> Result<Self, Self::Err> {
253        Ok(Self::from(s))
254    }
255}
256
257impl Serialize for Code {
258    fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
259        s.serialize_str(self.as_str())
260    }
261}
262
263impl<'de> Deserialize<'de> for Code {
264    fn deserialize<D: serde::Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
265        struct V;
266        impl serde::de::Visitor<'_> for V {
267            type Value = Code;
268            fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
269                f.write_str("an OICP status code")
270            }
271            fn visit_str<E: serde::de::Error>(self, v: &str) -> Result<Code, E> {
272                Ok(Code::from(v))
273            }
274            // Hubject writes these as strings ("000"), but a partner that hand-rolls its JSON
275            // sometimes sends the number. Accepting it costs nothing and saves an integration.
276            fn visit_u64<E: serde::de::Error>(self, v: u64) -> Result<Code, E> {
277                Ok(Code::from(format!("{v:03}").as_str()))
278            }
279            fn visit_i64<E: serde::de::Error>(self, v: i64) -> Result<Code, E> {
280                Ok(Code::from(format!("{v:03}").as_str()))
281            }
282        }
283        d.deserialize_any(V)
284    }
285}
286
287#[cfg(feature = "schema")]
288impl schemars::JsonSchema for Code {
289    fn schema_name() -> std::borrow::Cow<'static, str> {
290        "StatusCodeValue".into()
291    }
292    fn json_schema(_g: &mut schemars::SchemaGenerator) -> schemars::Schema {
293        schemars::json_schema!({ "type": "string", "pattern": "^[0-9]{3}$" })
294    }
295}
296
297/// The status of an operation: a [`Code`], and optional human-readable detail.
298///
299/// > *The structure consists of a defined code, an optional functional description of the status,
300/// > and optional additional information. It can be used e.g. to send error details or detailed
301/// > reasons for a certain process or system behavior.*
302///
303/// Spec: `StatusCode`.
304#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, bon::Builder)]
305#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
306#[builder(finish_fn = build_unchecked)]
307pub struct StatusCode {
308    /// The machine-readable code.
309    #[serde(rename = "Code")]
310    pub code: Code,
311    /// A functional description of the status.
312    #[serde(rename = "Description", default, skip_serializing_if = "Option::is_none")]
313    #[builder(into)]
314    pub description: Option<Text<200>>,
315    /// Further individual, non-standardised information.
316    #[serde(rename = "AdditionalInfo", default, skip_serializing_if = "Option::is_none")]
317    #[builder(into)]
318    pub additional_info: Option<Text<1000>>,
319}
320
321impl StatusCode {
322    /// A status carrying just `code`, with the spec's own description filled in.
323    #[must_use]
324    pub fn new(code: Code) -> Self {
325        let description = Text::new(code.description()).ok();
326        Self { code, description, additional_info: None }
327    }
328
329    /// `000 Success`.
330    #[must_use]
331    pub fn success() -> Self {
332        Self::new(Code::Success)
333    }
334
335    /// A status carrying `code` and free-text detail.
336    #[must_use]
337    pub fn with_info(code: Code, additional_info: impl Into<String>) -> Self {
338        Self { additional_info: Text::new_unchecked(additional_info).into(), ..Self::new(code) }
339    }
340
341    /// Whether this reports success.
342    #[must_use]
343    pub fn is_success(&self) -> bool {
344        self.code.is_success()
345    }
346}
347
348impl fmt::Display for StatusCode {
349    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
350        write!(f, "{}", self.code)?;
351        if let Some(info) = &self.additional_info {
352            write!(f, " ({info})")?;
353        }
354        Ok(())
355    }
356}
357
358impl Validate for StatusCode {
359    fn validate_in(&self, v: &mut Validator) {
360        if let Code::Custom(value) = &self.code {
361            v.report_at(
362                "Code",
363                ViolationCode::PatternMismatch,
364                format!("{value:?} is not one of the {} status codes OICP 2.3 defines", Code::ALL.len()),
365            );
366        }
367        validate_fields!(self, v, description as "Description", additional_info as "AdditionalInfo");
368    }
369}
370
371impl From<Code> for StatusCode {
372    fn from(code: Code) -> Self {
373        Self::new(code)
374    }
375}
376
377// Every builder's `build()` validates; `build_unchecked()` is the escape hatch.
378strict_builder!(StatusCode, StatusCodeBuilder, status_code_builder);
379
380#[cfg(test)]
381mod tests {
382    use super::*;
383
384    #[test]
385    fn every_code_in_the_spec_table_round_trips() {
386        for code in Code::ALL {
387            let json = serde_json::to_string(code).unwrap();
388            let back: Code = serde_json::from_str(&json).unwrap();
389            assert_eq!(*code, back);
390            assert_eq!(code.as_str().len(), 3);
391        }
392        assert_eq!(Code::ALL.len(), 31);
393    }
394
395    #[test]
396    fn an_unknown_code_is_preserved_not_dropped() {
397        let code: Code = serde_json::from_str(r#""999""#).unwrap();
398        assert!(!code.is_known());
399        assert_eq!(code.as_str(), "999");
400        assert_eq!(serde_json::to_string(&code).unwrap(), r#""999""#);
401    }
402
403    #[test]
404    fn a_code_sent_as_a_number_is_understood() {
405        let code: Code = serde_json::from_str("0").unwrap();
406        assert_eq!(code, Code::Success);
407        // …and goes back out as the string the spec requires.
408        assert_eq!(serde_json::to_string(&code).unwrap(), r#""000""#);
409    }
410
411    #[test]
412    fn retry_semantics_come_from_the_table_not_from_guesswork() {
413        // Transient: worth another attempt.
414        assert!(Code::HubjectSystemError.is_retryable());
415        assert!(Code::PartnerDidNotRespond.is_retryable());
416        assert!(Code::ServiceNotAvailable.is_retryable());
417        // Decisions and states: retrying is pointless, and for a start/stop, harmful.
418        assert!(!Code::NoValidContract.is_retryable());
419        assert!(!Code::EvseAlreadyReserved.is_retryable());
420        assert!(!Code::UnauthorizedAccess.is_retryable());
421        assert!(!Code::Success.is_retryable());
422    }
423
424    #[test]
425    fn authorization_failures_are_classified_as_such() {
426        assert!(Code::RfidInvalidUid.is_authorization_failure());
427        assert!(Code::EvcoIdLocked.is_authorization_failure());
428        assert!(Code::NoValidContract.is_authorization_failure());
429        assert!(!Code::EvseOutOfService.is_authorization_failure());
430        assert!(Code::EvseOutOfService.is_evse_problem());
431    }
432
433    #[test]
434    fn a_status_carries_the_specs_own_description_by_default() {
435        let status = StatusCode::new(Code::UnknownEvseId);
436        assert_eq!(status.description.as_ref().unwrap().as_str(), "Unknown EVSE ID");
437        assert!(status.validate().is_ok());
438    }
439}