ferrobridge-term 0.1.129

The FerroBRIDGE FHIR terminology client for $lookup, $translate and $validate-code
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
// SPDX-FileCopyrightText: Cadasto B.V.
// SPDX-License-Identifier: BUSL-1.1

//! What can go wrong on the wire, as types that carry the upstream answer.
//!
//! A refusal a terminology operation expresses in its own `out` parameters is
//! an outcome of that call (`crate::outcome`), never an error. Everything here
//! is the other half, and every one of these carries the upstream status and
//! body rather than an empty value.

use crate::config::TokenFailure;
use crate::config::WireVersion;
use http::StatusCode;
use url::Url;

/// The `tx-issue-type` code system of the FHIR tools implementation guide
/// (<https://build.fhir.org/ig/FHIR/fhir-tools-ig/CodeSystem-tx-issue-type.html>).
pub const TX_ISSUE_TYPE: &str = "http://hl7.org/fhir/tools/CodeSystem/tx-issue-type";

/// The terminology-specific classification of one issue.
///
/// A terminology server states why a call failed in machine-readable form as a
/// `details.coding` from [`TX_ISSUE_TYPE`], beside the `issue.code` that every
/// `OperationOutcome` carries.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct TxIssue {
    /// The code, for example `not-found` or `invalid-code`.
    pub code: String,
    /// The display the server sent with the code, when it sent one.
    pub display: Option<String>,
}

/// One issue of an `OperationOutcome`
/// (<https://hl7.org/fhir/R4/operationoutcome.html>).
///
/// `severity` and `code` stay as the server spelled them: the raw body is kept
/// beside this value in [`UpstreamError`], and a code outside the FHIR value
/// set would otherwise cost the whole diagnostic.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Issue {
    /// `issue.severity`, one of `fatal`, `error`, `warning`, `information`.
    pub severity: String,
    /// `issue.code`, a code of the FHIR `IssueType` value set.
    pub code: String,
    /// `issue.details.text`, when the server sent one.
    pub details: Option<String>,
    /// `issue.diagnostics`, when the server sent one.
    pub diagnostics: Option<String>,
    /// The [`TX_ISSUE_TYPE`] coding of `issue.details.coding`, when one is
    /// present.
    pub tx_issue_type: Option<TxIssue>,
}

/// A decoded `OperationOutcome`.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Outcome {
    /// The issues, in the order the server sent them.
    pub issues: Vec<Issue>,
}

impl Outcome {
    /// Returns every [`TX_ISSUE_TYPE`] coding the outcome carries.
    pub fn tx_issues(&self) -> impl Iterator<Item = &TxIssue> {
        self.issues
            .iter()
            .filter_map(|issue| issue.tx_issue_type.as_ref())
    }

    /// Returns whether any issue carries the [`TX_ISSUE_TYPE`] code `code`.
    #[must_use]
    pub fn has_tx_issue(&self, code: &str) -> bool {
        self.tx_issues().any(|issue| issue.code == code)
    }
}

/// A non-success answer from the terminology server, with what it said.
#[derive(Debug, Clone)]
pub struct UpstreamError {
    /// The HTTP status the server answered with.
    status: StatusCode,
    /// The response body, as received.
    body: String,
    /// The decoded `OperationOutcome`, when the body was one.
    outcome: Option<Outcome>,
}

impl UpstreamError {
    /// Returns the upstream answer `status` and `body` describe, read in
    /// `version`.
    ///
    /// A failed operation answers "an `OperationOutcome` resource with error
    /// details" (<https://hl7.org/fhir/R4/operations.html>), so the body is
    /// decoded as one; a body that is not one is a legal answer from a server
    /// that failed before the operation ran, and the raw body stays either
    /// way.
    #[must_use]
    pub fn new(version: WireVersion, status: StatusCode, body: String) -> Self {
        let outcome = crate::wire::outcome(version, &body).ok();
        Self {
            status,
            body,
            outcome,
        }
    }

    /// Returns the HTTP status the server answered with.
    #[must_use]
    pub fn status(&self) -> StatusCode {
        self.status
    }

    /// Returns the response body, as received.
    #[must_use]
    pub fn body(&self) -> &str {
        &self.body
    }

    /// Returns the decoded `OperationOutcome`, when the body was one.
    #[must_use]
    pub fn outcome(&self) -> Option<&Outcome> {
        self.outcome.as_ref()
    }

    /// Returns every [`TX_ISSUE_TYPE`] coding the answer carries.
    pub fn tx_issues(&self) -> impl Iterator<Item = &TxIssue> {
        self.outcome.iter().flat_map(Outcome::tx_issues)
    }

    /// Returns whether any issue carries the [`TX_ISSUE_TYPE`] code `code`.
    #[must_use]
    pub fn has_tx_issue(&self, code: &str) -> bool {
        self.tx_issues().any(|issue| issue.code == code)
    }
}

impl std::fmt::Display for UpstreamError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self
            .outcome
            .as_ref()
            .and_then(|outcome| outcome.issues.first())
        {
            Some(issue) => write!(f, "{} ({})", self.status, issue.code),
            None => write!(f, "{}", self.status),
        }
    }
}

/// A response body that is not the resource the operation answers with.
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum BodyError {
    /// The body is not the FHIR JSON resource the route declares.
    #[error(transparent)]
    Json(#[from] serde_json::Error),
    /// The `Parameters` resource does not fit the operation's declared
    /// parameter set.
    #[error(transparent)]
    Parameters(#[from] fhir_types::operation::ParametersError),
    /// A decoded value has no FHIR JSON form, so it could not be read back.
    #[error(transparent)]
    Encode(#[from] fhir_types::codec::EncodeError),
    /// A parameter the operation declares as mandatory states no value.
    #[error("the answer states no value for the mandatory parameter `{parameter}`")]
    MissingValue {
        /// The parameter, dotted for a part.
        parameter: &'static str,
    },
    /// The answer to a `batch` is not a `batch-response` `Bundle`.
    #[error("a batch answered a `{found}` Bundle, not a `batch-response`")]
    BatchType {
        /// The `Bundle.type` the answer declared.
        found: String,
    },
    /// A `Bundle` entry carries no `response.status`, or one that is not an
    /// HTTP status line.
    #[error("a batch response entry carries no usable response.status")]
    EntryStatus,
    /// A `Bundle` entry carries no resource, so the answer to its request is
    /// absent rather than negative.
    #[error("a batch response entry carries no resource")]
    EntryResource,
}

/// A call into the terminology server that did not reach an answer.
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum Error {
    /// The request could not be built into a URL under the configured base.
    #[error("{base} cannot be a base URL for a FHIR service")]
    BaseUrl {
        /// The configured base URL.
        base: Url,
    },
    /// The HTTP client could not be built from the configuration.
    #[error("the HTTP client could not be built")]
    ClientBuild {
        /// What the HTTP stack reported.
        #[source]
        source: reqwest::Error,
    },
    /// A request body could not be written as FHIR JSON.
    #[error("the {operation} request could not be written as FHIR JSON")]
    RequestBody {
        /// The operation, as `Resource/$code`.
        operation: &'static str,
        /// What the encoder reported.
        #[source]
        source: serde_json::Error,
    },
    /// The request carries a parameter the configured release's
    /// `OperationDefinition` does not declare and has no equivalent for, so
    /// nothing was sent.
    ///
    /// STU3 `ConceptMap/$translate` has no `url`, and STU3
    /// `ValueSet/$validate-code` has no `valueSetVersion`
    /// (<https://hl7.org/fhir/STU3/terminology-service.html>). Sending the
    /// request without the parameter would ask the server a different
    /// question than the caller asked.
    #[error(
        "the {operation} request carries `{parameter}`, which FHIR {} declares no parameter for; nothing was sent",
        .wire_version.as_str()
    )]
    UnsupportedParameter {
        /// The operation, as `Resource/$code`.
        operation: &'static str,
        /// The parameter, as the R4 `OperationDefinition` names it.
        parameter: &'static str,
        /// The release the client is configured for.
        wire_version: WireVersion,
    },
    /// The request never reached the server.
    #[error("the request to {url} could not be sent")]
    Transport {
        /// The URL that was called.
        url: Url,
        /// What the HTTP stack reported.
        #[source]
        source: reqwest::Error,
    },
    /// The server did not answer inside the configured timeout.
    #[error("the request to {url} timed out")]
    Timeout {
        /// The URL that was called.
        url: Url,
        /// What the HTTP stack reported.
        #[source]
        source: reqwest::Error,
    },
    /// The server answered `5xx`.
    #[error("the terminology server answered {upstream} for {url}")]
    ServerFailure {
        /// The URL that was called.
        url: Url,
        /// The upstream status and body.
        upstream: Box<UpstreamError>,
    },
    /// The server refused the credentials.
    #[error("the terminology server refused the credentials for {url}")]
    Unauthorized {
        /// The URL that was called.
        url: Url,
        /// The `WWW-Authenticate` challenge, when the server sent one.
        challenge: Option<String>,
        /// The upstream status and body.
        upstream: Box<UpstreamError>,
    },
    /// The token provider obtained no token, so nothing was sent.
    #[error("no token could be obtained for the request to {url}")]
    Token {
        /// The URL the request was for.
        url: Url,
        /// The provider's failure.
        #[source]
        source: TokenFailure,
    },
    /// The server refused the token (`401`) and no new one could be
    /// obtained, so the request was not sent again.
    #[error("the terminology server refused the token for {url} and no new one could be obtained")]
    Renewal {
        /// The URL that was called.
        url: Url,
        /// The upstream status and body of the refusal.
        upstream: Box<UpstreamError>,
        /// The provider's failure.
        #[source]
        source: TokenFailure,
    },
    /// The server refused the operation.
    #[error("the terminology server refused {operation} with {upstream}")]
    Refused {
        /// The operation, as `Resource/$code`.
        operation: &'static str,
        /// The URL that was called.
        url: Url,
        /// The upstream status and body, with any `tx-issue-type` coding.
        upstream: Box<UpstreamError>,
    },
    /// The response body could not be decoded.
    #[error("the body of the {operation} answer from {url} could not be decoded")]
    Body {
        /// The operation, as `Resource/$code`.
        operation: &'static str,
        /// The URL that was called.
        url: Url,
        /// What the decoder reported.
        #[source]
        source: Box<BodyError>,
    },
    /// The batch answered a different number of entries than were sent.
    #[error("the batch answered {answered} entries for {sent} requests")]
    BatchArity {
        /// How many requests were sent.
        sent: usize,
        /// How many entries came back.
        answered: usize,
    },
}

impl Error {
    /// Returns the variant's name as a short kebab-case label, for a log line
    /// that must name the failure class and never the URL or a body.
    #[must_use]
    pub fn kind(&self) -> &'static str {
        match self {
            Self::BaseUrl { .. } => "base-url",
            Self::ClientBuild { .. } => "client-build",
            Self::RequestBody { .. } => "request-body",
            Self::UnsupportedParameter { .. } => "unsupported-parameter",
            Self::Transport { .. } => "transport",
            Self::Timeout { .. } => "timeout",
            Self::ServerFailure { .. } => "server-failure",
            Self::Unauthorized { .. } => "unauthorized",
            Self::Token { .. } => "token",
            Self::Renewal { .. } => "token-renewal",
            Self::Refused { .. } => "refused",
            Self::Body { .. } => "body",
            Self::BatchArity { .. } => "batch-arity",
        }
    }

    /// Returns the status the terminology server answered with, when the
    /// failure is an answer: a `5xx`, a refused credential or a refused
    /// operation. A call that never reached an answer has none.
    #[must_use]
    pub fn upstream_status(&self) -> Option<StatusCode> {
        match self {
            Self::ServerFailure { upstream, .. }
            | Self::Unauthorized { upstream, .. }
            | Self::Renewal { upstream, .. }
            | Self::Refused { upstream, .. } => Some(upstream.status()),
            _ => None,
        }
    }

    /// Returns whether a retry of the same request could succeed.
    ///
    /// Only a failure that did not reach the server, or one the server
    /// reported as its own (`5xx`), is transient. The three operations declare
    /// `affectsState: false`
    /// (`OperationDefinition-CodeSystem-lookup`,
    /// `OperationDefinition-ConceptMap-translate` and
    /// `OperationDefinition-ValueSet-validate-code`, R4B), so a repeat is the
    /// same read and the `POST` form is retried like the `GET` form
    /// (<https://hl7.org/fhir/R4/operations.html>). The STU3 definitions of
    /// the same operations declare no such flag; retrying them on the same
    /// ground is our own design.
    #[must_use]
    pub fn is_retryable(&self) -> bool {
        matches!(
            self,
            Self::Transport { .. } | Self::Timeout { .. } | Self::ServerFailure { .. }
        )
    }
}

#[cfg(test)]
mod tests {
    use super::{Error, TX_ISSUE_TYPE, TxIssue, UpstreamError};
    use crate::config::WireVersion;
    use http::StatusCode;

    fn outcome_body(tx_code: &str) -> String {
        serde_json::json!({
            "resourceType": "OperationOutcome",
            "issue": [{
                "severity": "error",
                "code": "code-invalid",
                "details": {
                    "coding": [{"system": TX_ISSUE_TYPE, "code": tx_code, "display": "Invalid code"}],
                    "text": "the code is not in the code system",
                },
                "diagnostics": "Unknown_Code_in_Version",
            }],
        })
        .to_string()
    }

    #[test]
    fn a_tx_issue_type_coding_is_surfaced() {
        let upstream = UpstreamError::new(
            WireVersion::R4,
            StatusCode::BAD_REQUEST,
            outcome_body("invalid-code"),
        );
        let outcome = upstream.outcome().expect("the body is an OperationOutcome");
        assert_eq!(1, outcome.issues.len());
        assert!(outcome.has_tx_issue("invalid-code"));
        assert_eq!(
            vec![&TxIssue {
                code: "invalid-code".to_owned(),
                display: Some("Invalid code".to_owned()),
            }],
            upstream.tx_issues().collect::<Vec<_>>()
        );
    }

    #[test]
    fn an_r4b_outcome_decodes_the_same_way() {
        let upstream = UpstreamError::new(
            WireVersion::R4B,
            StatusCode::NOT_FOUND,
            outcome_body("not-found"),
        );
        assert!(
            upstream
                .outcome()
                .is_some_and(|outcome| outcome.has_tx_issue("not-found"))
        );
    }

    #[test]
    fn a_body_that_is_not_an_outcome_stays_raw() {
        let upstream =
            UpstreamError::new(WireVersion::R4, StatusCode::BAD_GATEWAY, "no".to_owned());
        assert!(upstream.outcome().is_none());
        assert_eq!("no", upstream.body());
        assert_eq!("502 Bad Gateway", upstream.to_string());
    }

    #[test]
    fn only_transport_timeout_and_server_errors_are_retried() {
        let url: url::Url = "http://tx.invalid/r4".parse().expect("a valid URL");
        let server = Error::ServerFailure {
            url: url.clone(),
            upstream: Box::new(UpstreamError::new(
                WireVersion::R4,
                StatusCode::SERVICE_UNAVAILABLE,
                String::new(),
            )),
        };
        assert!(server.is_retryable());
        let refused = Error::Refused {
            operation: "CodeSystem/$lookup",
            url,
            upstream: Box::new(UpstreamError::new(
                WireVersion::R4,
                StatusCode::BAD_REQUEST,
                String::new(),
            )),
        };
        assert!(!refused.is_retryable());
        assert_eq!("refused", refused.kind());
        assert!(
            !Error::BatchArity {
                sent: 2,
                answered: 1
            }
            .is_retryable()
        );
    }
}