Skip to main content

oicp_kit/transport/
error.rs

1//! `OicpError` — the four different ways an OICP call fails, kept apart.
2
3use crate::types::{Acknowledgement, Code, StatusCode, Violations};
4
5/// Why an OICP call did not produce a usable answer.
6///
7/// # Four failures, not one
8///
9/// OICP layers its failures, and collapsing them loses the information the caller needs to decide
10/// what to do:
11///
12/// | Variant | What happened | Retry? |
13/// |---|---|---|
14/// | [`Transport`](Self::Transport) | the request never got an answer | yes, with backoff |
15/// | [`Http`](Self::Http) | the answer was a non-2xx status | on 5xx |
16/// | [`Rejected`](Self::Rejected) | `HTTP 200`, `Result: false` | ask the [`Code`] |
17/// | [`Decode`](Self::Decode) | the answer was not the message it should be | no |
18///
19/// The third is the one that catches people out: Hubject answers a refused push with `HTTP 200`
20/// and a body saying it did not happen. A client that only checks the status code believes the
21/// push landed.
22#[derive(Debug, thiserror::Error)]
23#[non_exhaustive]
24pub enum OicpError {
25    /// The request never reached Hubject, or its answer never came back.
26    #[error("the request to Hubject failed: {message}")]
27    Transport {
28        /// What went wrong.
29        message: String,
30        /// The underlying error.
31        #[source]
32        source: Option<Box<dyn std::error::Error + Send + Sync>>,
33    },
34
35    /// Hubject answered with a status outside 2xx.
36    ///
37    /// The URL is part of the error because the commonest cause of a `404` is a base URL without
38    /// its `/api/oicp` path, and "Hubject answered 404" does not say that. An error a human reads
39    /// should carry what they need to fix it.
40    #[error("{url} answered {status}{}{}", body_excerpt(.body), path_hint(*.status, .url))]
41    Http {
42        /// The HTTP status.
43        status: u16,
44        /// The URL that was called.
45        url: String,
46        /// As much of the body as was read, for the log.
47        body: String,
48    },
49
50    /// Hubject answered `HTTP 200` and said the operation did not happen.
51    ///
52    /// The most important variant: this is a **failure** that looks like a success at the HTTP
53    /// layer. [`status_code`](Self::Rejected::status_code) says why.
54    #[error("Hubject rejected the operation: {status_code}")]
55    Rejected {
56        /// Why it was rejected.
57        status_code: StatusCode,
58        /// The whole acknowledgement, so nothing is lost.
59        acknowledgement: Box<Acknowledgement>,
60    },
61
62    /// The answer was not the message it was supposed to be.
63    #[error("could not decode Hubject's answer{}: {message}", pointer_suffix(.pointer.as_deref()))]
64    Decode {
65        /// What went wrong.
66        message: String,
67        /// Where in the JSON, when `serde_path_to_error` could say.
68        pointer: Option<String>,
69    },
70
71    /// A request this crate was asked to send is not conformant.
72    ///
73    /// Raised before anything goes on the wire — the "construct strictly" rule, enforced at the
74    /// last possible moment for callers who built their request by hand.
75    #[error("the request is not conformant: {0}")]
76    Invalid(#[from] Violations),
77
78    /// The request could not be addressed.
79    #[error(transparent)]
80    Endpoint(#[from] super::endpoint::EndpointError),
81}
82
83fn body_excerpt(body: &str) -> String {
84    if body.is_empty() {
85        String::new()
86    } else {
87        let trimmed: String = body.chars().take(200).collect();
88        format!(": {trimmed}")
89    }
90}
91
92fn pointer_suffix(pointer: Option<&str>) -> String {
93    pointer.map_or_else(String::new, |p| format!(" at {p}"))
94}
95
96/// The one 404 worth guessing at: OICP's endpoints all hang off `…/api/oicp`, and a base URL
97/// given without it produces a 404 on every call with nothing to say why.
98fn path_hint(status: u16, url: &str) -> &'static str {
99    if status == 404 && !url.contains("/api/oicp") {
100        ". Every OICP endpoint hangs off `…/api/oicp`; a base URL without that path 404s on every call"
101    } else {
102        ""
103    }
104}
105
106impl OicpError {
107    /// Builds a [`Transport`](Self::Transport) error.
108    pub fn transport(message: impl Into<String>) -> Self {
109        Self::Transport { message: message.into(), source: None }
110    }
111
112    /// Builds a [`Transport`](Self::Transport) error with a cause.
113    pub fn transport_from(
114        message: impl Into<String>,
115        source: impl std::error::Error + Send + Sync + 'static,
116    ) -> Self {
117        Self::Transport { message: message.into(), source: Some(Box::new(source)) }
118    }
119
120    /// Builds a [`Rejected`](Self::Rejected) error from an acknowledgement that failed.
121    #[must_use]
122    pub fn rejected(acknowledgement: Acknowledgement) -> Self {
123        Self::Rejected {
124            status_code: acknowledgement.status_code.clone(),
125            acknowledgement: Box::new(acknowledgement),
126        }
127    }
128
129    /// The OICP status code, when the failure carried one.
130    #[must_use]
131    pub fn code(&self) -> Option<&Code> {
132        match self {
133            Self::Rejected { status_code, .. } => Some(&status_code.code),
134            _ => None,
135        }
136    }
137
138    /// Whether re-sending the identical request could plausibly succeed.
139    ///
140    /// * Transport failures: yes — the request may never have arrived.
141    /// * HTTP 5xx and 429: yes. Other HTTP statuses: no.
142    /// * A rejection: only for the transient codes — [`Code::is_retryable`].
143    /// * Decode failures and invalid requests: no. The next attempt fails identically.
144    ///
145    /// [`RetryPolicy`](crate::client::RetryPolicy) is built on this.
146    #[must_use]
147    pub fn is_retryable(&self) -> bool {
148        match self {
149            Self::Transport { .. } => true,
150            Self::Http { status, .. } => *status >= 500 || *status == 429,
151            Self::Rejected { status_code, .. } => status_code.code.is_retryable(),
152            Self::Decode { .. } | Self::Invalid(_) | Self::Endpoint(_) => false,
153        }
154    }
155
156    /// Whether this failure means the driver may not charge, as opposed to something breaking.
157    #[must_use]
158    pub fn is_authorization_failure(&self) -> bool {
159        self.code().is_some_and(Code::is_authorization_failure)
160    }
161}
162
163/// The result of an OICP call.
164pub type Result<T> = core::result::Result<T, OicpError>;
165
166#[cfg(test)]
167mod tests {
168    use super::*;
169
170    #[test]
171    fn a_two_hundred_with_result_false_is_an_error() {
172        let ack = Acknowledgement::failure(Code::UnknownEvseId);
173        let err = OicpError::rejected(ack);
174        assert_eq!(err.code(), Some(&Code::UnknownEvseId));
175        assert!(!err.is_retryable());
176        assert!(err.to_string().contains("603"));
177    }
178
179    #[test]
180    fn retryability_follows_the_layer_the_failure_came_from() {
181        assert!(OicpError::transport("connection reset").is_retryable());
182        let http = |status| OicpError::Http { status, url: "https://x/api/oicp".into(), body: String::new() };
183        assert!(http(503).is_retryable());
184        assert!(http(429).is_retryable());
185        assert!(!http(400).is_retryable());
186        assert!(!OicpError::Decode { message: "bad".into(), pointer: None }.is_retryable());
187
188        // Transient rejections are worth another go; decisions are not.
189        assert!(OicpError::rejected(Acknowledgement::failure(Code::ServiceNotAvailable)).is_retryable());
190        assert!(!OicpError::rejected(Acknowledgement::failure(Code::NoValidContract)).is_retryable());
191    }
192
193    #[test]
194    fn an_authorization_failure_is_distinguishable_from_a_breakage() {
195        let refused = OicpError::rejected(Acknowledgement::failure(Code::EvcoIdLocked));
196        assert!(refused.is_authorization_failure());
197        let broken = OicpError::rejected(Acknowledgement::failure(Code::HubjectSystemError));
198        assert!(!broken.is_authorization_failure());
199    }
200
201    #[test]
202    fn a_long_error_body_is_truncated_in_the_message() {
203        let err = OicpError::Http { status: 500, url: "https://x/api/oicp".into(), body: "x".repeat(1000) };
204        assert!(err.to_string().len() < 320, "{err}");
205    }
206
207    #[test]
208    fn a_404_on_a_base_url_without_its_path_says_so() {
209        // The commonest way to get a 404 out of Hubject is a base URL missing `/api/oicp`, and
210        // "answered 404" is exactly as much help as no message at all.
211        let missing = OicpError::Http {
212            status: 404,
213            url: "http://127.0.0.1:8080/evsepull/v23/providers/DE-DCB/data-records".into(),
214            body: String::new(),
215        };
216        assert!(missing.to_string().contains("/api/oicp"), "{missing}");
217
218        let genuine = OicpError::Http {
219            status: 404,
220            url: "https://service.hubject.com/api/oicp/evsepull/v23/x".into(),
221            body: String::new(),
222        };
223        assert!(!genuine.to_string().contains("hangs off"), "{genuine}");
224
225        // The hint is for 404 only; a 500 on the same URL is not a path problem.
226        let server = OicpError::Http { status: 500, url: "http://x/y".into(), body: String::new() };
227        assert!(!server.to_string().contains("hangs off"), "{server}");
228    }
229}