Skip to main content

ferrobridge_term/
error.rs

1// SPDX-FileCopyrightText: Cadasto B.V.
2// SPDX-License-Identifier: BUSL-1.1
3
4//! What can go wrong on the wire, as types that carry the upstream answer.
5//!
6//! A refusal a terminology operation expresses in its own `out` parameters is
7//! an outcome of that call (`crate::outcome`), never an error. Everything here
8//! is the other half, and every one of these carries the upstream status and
9//! body rather than an empty value.
10
11use crate::config::TokenFailure;
12use crate::config::WireVersion;
13use http::StatusCode;
14use url::Url;
15
16/// The `tx-issue-type` code system of the FHIR tools implementation guide
17/// (<https://build.fhir.org/ig/FHIR/fhir-tools-ig/CodeSystem-tx-issue-type.html>).
18pub const TX_ISSUE_TYPE: &str = "http://hl7.org/fhir/tools/CodeSystem/tx-issue-type";
19
20/// The terminology-specific classification of one issue.
21///
22/// A terminology server states why a call failed in machine-readable form as a
23/// `details.coding` from [`TX_ISSUE_TYPE`], beside the `issue.code` that every
24/// `OperationOutcome` carries.
25#[derive(Debug, Clone, PartialEq, Eq)]
26pub struct TxIssue {
27    /// The code, for example `not-found` or `invalid-code`.
28    pub code: String,
29    /// The display the server sent with the code, when it sent one.
30    pub display: Option<String>,
31}
32
33/// One issue of an `OperationOutcome`
34/// (<https://hl7.org/fhir/R4/operationoutcome.html>).
35///
36/// `severity` and `code` stay as the server spelled them: the raw body is kept
37/// beside this value in [`UpstreamError`], and a code outside the FHIR value
38/// set would otherwise cost the whole diagnostic.
39#[derive(Debug, Clone, PartialEq, Eq)]
40pub struct Issue {
41    /// `issue.severity`, one of `fatal`, `error`, `warning`, `information`.
42    pub severity: String,
43    /// `issue.code`, a code of the FHIR `IssueType` value set.
44    pub code: String,
45    /// `issue.details.text`, when the server sent one.
46    pub details: Option<String>,
47    /// `issue.diagnostics`, when the server sent one.
48    pub diagnostics: Option<String>,
49    /// The [`TX_ISSUE_TYPE`] coding of `issue.details.coding`, when one is
50    /// present.
51    pub tx_issue_type: Option<TxIssue>,
52}
53
54/// A decoded `OperationOutcome`.
55#[derive(Debug, Clone, PartialEq, Eq)]
56pub struct Outcome {
57    /// The issues, in the order the server sent them.
58    pub issues: Vec<Issue>,
59}
60
61impl Outcome {
62    /// Returns every [`TX_ISSUE_TYPE`] coding the outcome carries.
63    pub fn tx_issues(&self) -> impl Iterator<Item = &TxIssue> {
64        self.issues
65            .iter()
66            .filter_map(|issue| issue.tx_issue_type.as_ref())
67    }
68
69    /// Returns whether any issue carries the [`TX_ISSUE_TYPE`] code `code`.
70    #[must_use]
71    pub fn has_tx_issue(&self, code: &str) -> bool {
72        self.tx_issues().any(|issue| issue.code == code)
73    }
74}
75
76/// A non-success answer from the terminology server, with what it said.
77#[derive(Debug, Clone)]
78pub struct UpstreamError {
79    /// The HTTP status the server answered with.
80    status: StatusCode,
81    /// The response body, as received.
82    body: String,
83    /// The decoded `OperationOutcome`, when the body was one.
84    outcome: Option<Outcome>,
85}
86
87impl UpstreamError {
88    /// Returns the upstream answer `status` and `body` describe, read in
89    /// `version`.
90    ///
91    /// A failed operation answers "an `OperationOutcome` resource with error
92    /// details" (<https://hl7.org/fhir/R4/operations.html>), so the body is
93    /// decoded as one; a body that is not one is a legal answer from a server
94    /// that failed before the operation ran, and the raw body stays either
95    /// way.
96    #[must_use]
97    pub fn new(version: WireVersion, status: StatusCode, body: String) -> Self {
98        let outcome = crate::wire::outcome(version, &body).ok();
99        Self {
100            status,
101            body,
102            outcome,
103        }
104    }
105
106    /// Returns the HTTP status the server answered with.
107    #[must_use]
108    pub fn status(&self) -> StatusCode {
109        self.status
110    }
111
112    /// Returns the response body, as received.
113    #[must_use]
114    pub fn body(&self) -> &str {
115        &self.body
116    }
117
118    /// Returns the decoded `OperationOutcome`, when the body was one.
119    #[must_use]
120    pub fn outcome(&self) -> Option<&Outcome> {
121        self.outcome.as_ref()
122    }
123
124    /// Returns every [`TX_ISSUE_TYPE`] coding the answer carries.
125    pub fn tx_issues(&self) -> impl Iterator<Item = &TxIssue> {
126        self.outcome.iter().flat_map(Outcome::tx_issues)
127    }
128
129    /// Returns whether any issue carries the [`TX_ISSUE_TYPE`] code `code`.
130    #[must_use]
131    pub fn has_tx_issue(&self, code: &str) -> bool {
132        self.tx_issues().any(|issue| issue.code == code)
133    }
134}
135
136impl std::fmt::Display for UpstreamError {
137    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
138        match self
139            .outcome
140            .as_ref()
141            .and_then(|outcome| outcome.issues.first())
142        {
143            Some(issue) => write!(f, "{} ({})", self.status, issue.code),
144            None => write!(f, "{}", self.status),
145        }
146    }
147}
148
149/// A response body that is not the resource the operation answers with.
150#[derive(Debug, thiserror::Error)]
151#[non_exhaustive]
152pub enum BodyError {
153    /// The body is not the FHIR JSON resource the route declares.
154    #[error(transparent)]
155    Json(#[from] serde_json::Error),
156    /// The `Parameters` resource does not fit the operation's declared
157    /// parameter set.
158    #[error(transparent)]
159    Parameters(#[from] fhir_types::operation::ParametersError),
160    /// A decoded value has no FHIR JSON form, so it could not be read back.
161    #[error(transparent)]
162    Encode(#[from] fhir_types::codec::EncodeError),
163    /// A parameter the operation declares as mandatory states no value.
164    #[error("the answer states no value for the mandatory parameter `{parameter}`")]
165    MissingValue {
166        /// The parameter, dotted for a part.
167        parameter: &'static str,
168    },
169    /// The answer to a `batch` is not a `batch-response` `Bundle`.
170    #[error("a batch answered a `{found}` Bundle, not a `batch-response`")]
171    BatchType {
172        /// The `Bundle.type` the answer declared.
173        found: String,
174    },
175    /// A `Bundle` entry carries no `response.status`, or one that is not an
176    /// HTTP status line.
177    #[error("a batch response entry carries no usable response.status")]
178    EntryStatus,
179    /// A `Bundle` entry carries no resource, so the answer to its request is
180    /// absent rather than negative.
181    #[error("a batch response entry carries no resource")]
182    EntryResource,
183}
184
185/// A call into the terminology server that did not reach an answer.
186#[derive(Debug, thiserror::Error)]
187#[non_exhaustive]
188pub enum Error {
189    /// The request could not be built into a URL under the configured base.
190    #[error("{base} cannot be a base URL for a FHIR service")]
191    BaseUrl {
192        /// The configured base URL.
193        base: Url,
194    },
195    /// The HTTP client could not be built from the configuration.
196    #[error("the HTTP client could not be built")]
197    ClientBuild {
198        /// What the HTTP stack reported.
199        #[source]
200        source: reqwest::Error,
201    },
202    /// A request body could not be written as FHIR JSON.
203    #[error("the {operation} request could not be written as FHIR JSON")]
204    RequestBody {
205        /// The operation, as `Resource/$code`.
206        operation: &'static str,
207        /// What the encoder reported.
208        #[source]
209        source: serde_json::Error,
210    },
211    /// The request carries a parameter the configured release's
212    /// `OperationDefinition` does not declare and has no equivalent for, so
213    /// nothing was sent.
214    ///
215    /// STU3 `ConceptMap/$translate` has no `url`, and STU3
216    /// `ValueSet/$validate-code` has no `valueSetVersion`
217    /// (<https://hl7.org/fhir/STU3/terminology-service.html>). Sending the
218    /// request without the parameter would ask the server a different
219    /// question than the caller asked.
220    #[error(
221        "the {operation} request carries `{parameter}`, which FHIR {} declares no parameter for; nothing was sent",
222        .wire_version.as_str()
223    )]
224    UnsupportedParameter {
225        /// The operation, as `Resource/$code`.
226        operation: &'static str,
227        /// The parameter, as the R4 `OperationDefinition` names it.
228        parameter: &'static str,
229        /// The release the client is configured for.
230        wire_version: WireVersion,
231    },
232    /// The request never reached the server.
233    #[error("the request to {url} could not be sent")]
234    Transport {
235        /// The URL that was called.
236        url: Url,
237        /// What the HTTP stack reported.
238        #[source]
239        source: reqwest::Error,
240    },
241    /// The server did not answer inside the configured timeout.
242    #[error("the request to {url} timed out")]
243    Timeout {
244        /// The URL that was called.
245        url: Url,
246        /// What the HTTP stack reported.
247        #[source]
248        source: reqwest::Error,
249    },
250    /// The server answered `5xx`.
251    #[error("the terminology server answered {upstream} for {url}")]
252    ServerFailure {
253        /// The URL that was called.
254        url: Url,
255        /// The upstream status and body.
256        upstream: Box<UpstreamError>,
257    },
258    /// The server refused the credentials.
259    #[error("the terminology server refused the credentials for {url}")]
260    Unauthorized {
261        /// The URL that was called.
262        url: Url,
263        /// The `WWW-Authenticate` challenge, when the server sent one.
264        challenge: Option<String>,
265        /// The upstream status and body.
266        upstream: Box<UpstreamError>,
267    },
268    /// The token provider obtained no token, so nothing was sent.
269    #[error("no token could be obtained for the request to {url}")]
270    Token {
271        /// The URL the request was for.
272        url: Url,
273        /// The provider's failure.
274        #[source]
275        source: TokenFailure,
276    },
277    /// The server refused the token (`401`) and no new one could be
278    /// obtained, so the request was not sent again.
279    #[error("the terminology server refused the token for {url} and no new one could be obtained")]
280    Renewal {
281        /// The URL that was called.
282        url: Url,
283        /// The upstream status and body of the refusal.
284        upstream: Box<UpstreamError>,
285        /// The provider's failure.
286        #[source]
287        source: TokenFailure,
288    },
289    /// The server refused the operation.
290    #[error("the terminology server refused {operation} with {upstream}")]
291    Refused {
292        /// The operation, as `Resource/$code`.
293        operation: &'static str,
294        /// The URL that was called.
295        url: Url,
296        /// The upstream status and body, with any `tx-issue-type` coding.
297        upstream: Box<UpstreamError>,
298    },
299    /// The response body could not be decoded.
300    #[error("the body of the {operation} answer from {url} could not be decoded")]
301    Body {
302        /// The operation, as `Resource/$code`.
303        operation: &'static str,
304        /// The URL that was called.
305        url: Url,
306        /// What the decoder reported.
307        #[source]
308        source: Box<BodyError>,
309    },
310    /// The batch answered a different number of entries than were sent.
311    #[error("the batch answered {answered} entries for {sent} requests")]
312    BatchArity {
313        /// How many requests were sent.
314        sent: usize,
315        /// How many entries came back.
316        answered: usize,
317    },
318}
319
320impl Error {
321    /// Returns the variant's name as a short kebab-case label, for a log line
322    /// that must name the failure class and never the URL or a body.
323    #[must_use]
324    pub fn kind(&self) -> &'static str {
325        match self {
326            Self::BaseUrl { .. } => "base-url",
327            Self::ClientBuild { .. } => "client-build",
328            Self::RequestBody { .. } => "request-body",
329            Self::UnsupportedParameter { .. } => "unsupported-parameter",
330            Self::Transport { .. } => "transport",
331            Self::Timeout { .. } => "timeout",
332            Self::ServerFailure { .. } => "server-failure",
333            Self::Unauthorized { .. } => "unauthorized",
334            Self::Token { .. } => "token",
335            Self::Renewal { .. } => "token-renewal",
336            Self::Refused { .. } => "refused",
337            Self::Body { .. } => "body",
338            Self::BatchArity { .. } => "batch-arity",
339        }
340    }
341
342    /// Returns the status the terminology server answered with, when the
343    /// failure is an answer: a `5xx`, a refused credential or a refused
344    /// operation. A call that never reached an answer has none.
345    #[must_use]
346    pub fn upstream_status(&self) -> Option<StatusCode> {
347        match self {
348            Self::ServerFailure { upstream, .. }
349            | Self::Unauthorized { upstream, .. }
350            | Self::Renewal { upstream, .. }
351            | Self::Refused { upstream, .. } => Some(upstream.status()),
352            _ => None,
353        }
354    }
355
356    /// Returns whether a retry of the same request could succeed.
357    ///
358    /// Only a failure that did not reach the server, or one the server
359    /// reported as its own (`5xx`), is transient. The three operations declare
360    /// `affectsState: false`
361    /// (`OperationDefinition-CodeSystem-lookup`,
362    /// `OperationDefinition-ConceptMap-translate` and
363    /// `OperationDefinition-ValueSet-validate-code`, R4B), so a repeat is the
364    /// same read and the `POST` form is retried like the `GET` form
365    /// (<https://hl7.org/fhir/R4/operations.html>). The STU3 definitions of
366    /// the same operations declare no such flag; retrying them on the same
367    /// ground is our own design.
368    #[must_use]
369    pub fn is_retryable(&self) -> bool {
370        matches!(
371            self,
372            Self::Transport { .. } | Self::Timeout { .. } | Self::ServerFailure { .. }
373        )
374    }
375}
376
377#[cfg(test)]
378mod tests {
379    use super::{Error, TX_ISSUE_TYPE, TxIssue, UpstreamError};
380    use crate::config::WireVersion;
381    use http::StatusCode;
382
383    fn outcome_body(tx_code: &str) -> String {
384        serde_json::json!({
385            "resourceType": "OperationOutcome",
386            "issue": [{
387                "severity": "error",
388                "code": "code-invalid",
389                "details": {
390                    "coding": [{"system": TX_ISSUE_TYPE, "code": tx_code, "display": "Invalid code"}],
391                    "text": "the code is not in the code system",
392                },
393                "diagnostics": "Unknown_Code_in_Version",
394            }],
395        })
396        .to_string()
397    }
398
399    #[test]
400    fn a_tx_issue_type_coding_is_surfaced() {
401        let upstream = UpstreamError::new(
402            WireVersion::R4,
403            StatusCode::BAD_REQUEST,
404            outcome_body("invalid-code"),
405        );
406        let outcome = upstream.outcome().expect("the body is an OperationOutcome");
407        assert_eq!(1, outcome.issues.len());
408        assert!(outcome.has_tx_issue("invalid-code"));
409        assert_eq!(
410            vec![&TxIssue {
411                code: "invalid-code".to_owned(),
412                display: Some("Invalid code".to_owned()),
413            }],
414            upstream.tx_issues().collect::<Vec<_>>()
415        );
416    }
417
418    #[test]
419    fn an_r4b_outcome_decodes_the_same_way() {
420        let upstream = UpstreamError::new(
421            WireVersion::R4B,
422            StatusCode::NOT_FOUND,
423            outcome_body("not-found"),
424        );
425        assert!(
426            upstream
427                .outcome()
428                .is_some_and(|outcome| outcome.has_tx_issue("not-found"))
429        );
430    }
431
432    #[test]
433    fn a_body_that_is_not_an_outcome_stays_raw() {
434        let upstream =
435            UpstreamError::new(WireVersion::R4, StatusCode::BAD_GATEWAY, "no".to_owned());
436        assert!(upstream.outcome().is_none());
437        assert_eq!("no", upstream.body());
438        assert_eq!("502 Bad Gateway", upstream.to_string());
439    }
440
441    #[test]
442    fn only_transport_timeout_and_server_errors_are_retried() {
443        let url: url::Url = "http://tx.invalid/r4".parse().expect("a valid URL");
444        let server = Error::ServerFailure {
445            url: url.clone(),
446            upstream: Box::new(UpstreamError::new(
447                WireVersion::R4,
448                StatusCode::SERVICE_UNAVAILABLE,
449                String::new(),
450            )),
451        };
452        assert!(server.is_retryable());
453        let refused = Error::Refused {
454            operation: "CodeSystem/$lookup",
455            url,
456            upstream: Box::new(UpstreamError::new(
457                WireVersion::R4,
458                StatusCode::BAD_REQUEST,
459                String::new(),
460            )),
461        };
462        assert!(!refused.is_retryable());
463        assert_eq!("refused", refused.kind());
464        assert!(
465            !Error::BatchArity {
466                sent: 2,
467                answered: 1
468            }
469            .is_retryable()
470        );
471    }
472}