ihe-iti 0.0.44

The IHE IT Infrastructure (ITI) identity profiles: PIXm (ITI-83), PDQm (ITI-78, ITI-119), mCSD (ITI-90, ITI-91), PMIR (ITI-93, ITI-94) and XCPD (ITI-55), one feature per profile, with their audit records behind `balp` and `atna`
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
// SPDX-FileCopyrightText: Cadasto B.V.
// SPDX-License-Identifier: BUSL-1.1

//! PDQm, Patient Demographics Query for Mobile (feature `pdqm`).
//!
//! The Patient Demographics Consumer side of ITI-78, Mobile Patient
//! Demographics Query (PDQm 3.2.0, ITI TF-2 §2:3.78): a search on the Patient
//! Demographics Supplier's `Patient` type with demographic criteria, answered
//! with a `searchset` Bundle of the matching Patients.
//!
//! [`PdqmClient::search`] sends the [`query::PatientQuery`] and reads the
//! answer into a [`matches::SearchResult`] or an [`error::PdqmError`];
//! [`PdqmClient::next_page`] follows the result set's paging
//! (§2:3.78.4.2.2.4). No match is a result with a `total` of `0`
//! (§2:3.78.4.1.3, Case 3); every failure, including a `404` that is not the
//! profile's unrecognised-domain answer (Case 4), is an error, so an outage or
//! a misrouted request never reads as no match.
//!
//! The same client is the Consumer side of ITI-119, Patient Demographics Match
//! (ITI TF-2 §2:3.119): [`PdqmClient::match_patient`] posts the
//! [`input::MatchInput`] to `[base]/Patient/$match` and reads the answer into a
//! [`matches::MatchResult`], every matched Patient with its score and
//! `match-grade` (§2:3.119.4.2.2.4). No match is a result with no Patient
//! (§2:3.119.4.1.3, Cases 4, 5 and 7).
//!
//! The criteria are directly identifying. They travel only to the Supplier,
//! which is the transaction's purpose, and in the body of a `POST` search
//! rather than in a URL, which the profile admits ("the Patient Demographics
//! Supplier SHALL support both GET and POST based searches", §2:3.78.4.1.2).
//! The query, every matched Patient and every page link redact their content
//! in `Debug`, none of them has `Display`, and no error this module returns
//! carries a value, a URL or the Supplier's free text.
//!
//! # Examples
//!
//! ```no_run
//! use std::time::Duration;
//!
//! use ihe_iti::pdqm::PdqmClient;
//! use ihe_iti::pdqm::query::{DatePrefix, PatientQuery, StringMatch};
//! use ihe_atna::user::OnBehalfOf;
//! use secrecy::{ExposeSecret, SecretString};
//! use url::Url;
//!
//! # async fn run() -> Result<(), Box<dyn std::error::Error>> {
//! let http = reqwest::Client::builder()
//!     .redirect(reqwest::redirect::Policy::none())
//!     .build()?;
//! let client = PdqmClient::new(Url::parse("https://pdq.example.org/fhir/")?, http)?;
//! let query = PatientQuery::new()
//!     .family(&SecretString::from("Schmidt"), StringMatch::Exact)?
//!     .birthdate(DatePrefix::Eq, &SecretString::from("1923-07-25"))?;
//! let on_behalf = OnBehalfOf::System;
//! let mut page = client.search(&query, &on_behalf, Duration::from_secs(2)).await?;
//! loop {
//!     for matched in page.patients() {
//!         let _location = matched.full_url().expose_secret();
//!         let _deprecated = matched.patient().active.as_ref();
//!     }
//!     let Some(next) = page.next() else { break };
//!     page = client
//!         .next_page(next, &on_behalf, Duration::from_secs(2))
//!         .await?;
//! }
//! # Ok(())
//! # }
//! # fn main() {
//! #     let _pending = run();
//! # }
//! ```

#[cfg(feature = "balp")]
pub mod audit;
pub mod error;
pub mod input;
pub mod matches;
pub mod query;
mod request;
mod response;

use std::fmt;
use std::sync::Arc;
use std::time::Duration;

use http::header::{ACCEPT, CONTENT_TYPE};
use url::Url;

use crate::authorizer::{self, Authorizer};
use error::{InvalidInput, PdqmError};
use ihe_atna::redact::RedactedUrl;
use ihe_atna::user::OnBehalfOf;
use input::MatchInput;
use matches::{MatchResult, Page, SearchResult};
use query::PatientQuery;

/// The media type ITI-78 asks for and reads (ITI TF-2 Appendix Z.6).
const FHIR_JSON: &str = "application/fhir+json";

/// A Patient Demographics Consumer bound to one Patient Demographics Supplier.
///
/// `Debug` shows the base and the endpoint with their userinfo replaced by
/// `***`, and leaves out the HTTP client, whose default headers may hold a
/// credential.
#[derive(Clone)]
pub struct PdqmClient {
    base: Url,
    endpoint: Url,
    match_endpoint: Url,
    http: reqwest::Client,
    authorizer: Option<Arc<dyn Authorizer>>,
    #[cfg(feature = "balp")]
    audit: Option<Arc<dyn ihe_atna::balp::AuditRecorder>>,
}

impl PdqmClient {
    /// Creates a client for the Supplier whose FHIR base URL is `base`.
    ///
    /// `http` carries the transport the caller chose: TLS, client
    /// certificates, default authorization headers (ITI TF-2 Appendix Z.8).
    /// Build it with `redirect::Policy::none()`: a client that follows a `307`
    /// sends the criteria wherever the Supplier points it, and a `3xx` is then
    /// an error like any other unexpected status.
    ///
    /// # Errors
    /// [`InvalidInput::Base`] when `base` is not an `http` or `https` URL
    /// without a query or a fragment.
    pub fn new(base: Url, http: reqwest::Client) -> Result<Self, InvalidInput> {
        let base = request::base(base)?;
        Ok(Self {
            endpoint: request::endpoint(base.clone())?,
            match_endpoint: request::match_endpoint(base.clone())?,
            base,
            http,
            authorizer: None,
            #[cfg(feature = "balp")]
            audit: None,
        })
    }

    /// This client, asking `authorizer` for the headers of every request and
    /// handing it every answer, as for an access token it incorporates (IUA
    /// ITI-72 §3.72.4.2).
    ///
    /// Build the HTTP client without a default `Authorization` header then:
    /// the authorizer's headers are added to it, never in its place.
    #[must_use]
    pub fn with_authorizer(mut self, authorizer: Arc<dyn Authorizer>) -> Self {
        self.authorizer = Some(authorizer);
        self
    }

    /// This client, recording the audit record of every search, every page
    /// and every match through `recorder` (§2:3.78.5.1, §2:3.119.5.1.1,
    /// feature `balp`).
    ///
    /// An audited client records each request before it returns, whatever
    /// its outcome; one whose record the recorder does not accept fails with
    /// [`PdqmError::Audit`], and its answer is not used.
    #[cfg(feature = "balp")]
    #[must_use]
    pub fn audited(mut self, recorder: Arc<dyn ihe_atna::balp::AuditRecorder>) -> Self {
        self.audit = Some(recorder);
        self
    }

    /// Records the request `request`, when the client is audited, and
    /// returns `result` unless the record was refused, or was not accepted
    /// by `deadline` for an answer that would be used
    /// ([`ihe_atna::balp::recording`]).
    #[cfg(feature = "balp")]
    async fn audit(
        &self,
        request: impl FnOnce() -> secrecy::SecretString,
        on_behalf: &OnBehalfOf,
        result: Result<SearchResult, PdqmError>,
        deadline: Option<tokio::time::Instant>,
    ) -> Result<SearchResult, PdqmError> {
        use ihe_atna::balp::recording::{Late, Recorded, within};
        if let Some(recorder) = &self.audit {
            let exchange = audit::exchange(&self.base, request(), on_behalf, &result);
            // NOTE: PDQm §2:3.78.5.1 makes the audit record part of the query, so
            // an answer whose record was refused is not used.
            match within(deadline, recorder.record(exchange)).await {
                Recorded::Refused(error) => return Err(PdqmError::Audit(error)),
                Recorded::Late if result.is_ok() => {
                    return Err(PdqmError::Audit(ihe_atna::balp::AuditError(Box::new(
                        Late::new(),
                    ))));
                }
                Recorded::Accepted | Recorded::Late => {}
            }
        }
        result
    }

    /// Returns the `[base]/Patient/_search` URL the client posts to
    /// (§2:3.78.4.1.2).
    #[must_use]
    pub fn endpoint(&self) -> &Url {
        &self.endpoint
    }

    /// Returns the `[base]/Patient/$match` URL the client posts a match to
    /// (§2:3.119.4.1.2).
    #[must_use]
    pub fn match_endpoint(&self) -> &Url {
        &self.match_endpoint
    }

    /// Asks the Supplier for the Patients that match `input` (ITI-119), on
    /// behalf of `on_behalf`, whom an audited client's record names.
    ///
    /// `timeout` bounds the whole exchange, from connecting until the answer is
    /// read, and an audited client's record of it.
    ///
    /// # Errors
    /// [`PdqmError::Unwritable`] before anything is sent when the input
    /// cannot be written as JSON, and a [`PdqmError`] for every answer that is
    /// not a Match Output Bundle and for a failure to get an answer at all.
    pub async fn match_patient(
        &self,
        input: &MatchInput,
        #[cfg_attr(
            not(feature = "balp"),
            expect(
                unused_variables,
                reason = "only an audited client names whom it acted for"
            )
        )]
        on_behalf: &OnBehalfOf,
        timeout: Duration,
    ) -> Result<MatchResult, PdqmError> {
        #[cfg(feature = "balp")]
        let deadline = ihe_atna::balp::recording::deadline(timeout);
        let body = secrecy::SecretString::from(
            serde_json::to_string(&input.parameters()).map_err(PdqmError::Unwritable)?,
        );
        let result = self.post_match(&body, timeout).await;
        #[cfg(feature = "balp")]
        let result = self
            .audit_match((input, &body), on_behalf, result, deadline)
            .await;
        result
    }

    /// Records the match of `input`, sent as `body`, when the client is
    /// audited, and returns `result` unless the record was refused, or was
    /// not accepted by `deadline` for an answer that would be used
    /// ([`ihe_atna::balp::recording`]).
    #[cfg(feature = "balp")]
    async fn audit_match(
        &self,
        (input, body): (&MatchInput, &secrecy::SecretString),
        on_behalf: &OnBehalfOf,
        result: Result<MatchResult, PdqmError>,
        deadline: Option<tokio::time::Instant>,
    ) -> Result<MatchResult, PdqmError> {
        use ihe_atna::balp::recording::{Late, Recorded, within};
        use secrecy::ExposeSecret as _;
        if let Some(recorder) = &self.audit {
            // NOTE: BALP Query records the raw request; a POST operation is its
            // request line, media type and body, as for the ITI-78 POST search.
            let request = secrecy::SecretString::from(format!(
                "POST {}\nContent-Type: {FHIR_JSON}\n\n{}",
                ihe_atna::balp::request_text(&self.match_endpoint).expose_secret(),
                body.expose_secret()
            ));
            let exchange = audit::match_exchange(
                &self.base,
                (request, input.sole_identifier()),
                on_behalf,
                &result,
            );
            // NOTE: PDQm §2:3.119.5.1.1 makes the audit record part of the match, so
            // an answer whose record was refused is not used.
            match within(deadline, recorder.record(exchange)).await {
                Recorded::Refused(error) => return Err(PdqmError::Audit(error)),
                Recorded::Late if result.is_ok() => {
                    return Err(PdqmError::Audit(ihe_atna::balp::AuditError(Box::new(
                        Late::new(),
                    ))));
                }
                Recorded::Accepted | Recorded::Late => {}
            }
        }
        result
    }

    async fn post_match(
        &self,
        body: &secrecy::SecretString,
        timeout: Duration,
    ) -> Result<MatchResult, PdqmError> {
        use secrecy::ExposeSecret as _;
        let body = body.expose_secret().as_bytes().to_vec();
        let built = self
            .http
            .post(self.match_endpoint.clone())
            .header(ACCEPT, FHIR_JSON)
            .header(CONTENT_TYPE, FHIR_JSON)
            .body(body)
            .build()
            .map_err(error::transport)?;
        let response = self.send(built, timeout).await?;
        let status = response.status();
        let media = response
            .headers()
            .get(CONTENT_TYPE)
            .and_then(|value| value.to_str().ok())
            .map(str::to_owned);
        let body = response::body(response).await?;
        response::read_match(status, media.as_deref(), &body)
    }

    /// Asks the Supplier for the first page of Patients that match `query`,
    /// on behalf of `on_behalf`, whom an audited client's record names.
    ///
    /// `timeout` bounds the whole exchange, from connecting until the answer is
    /// read, and an audited client's record of it.
    ///
    /// # Errors
    /// A [`PdqmError`] for every answer that is not a `searchset` Bundle, and
    /// for a failure to get an answer at all.
    pub async fn search(
        &self,
        query: &PatientQuery,
        #[cfg_attr(
            not(feature = "balp"),
            expect(
                unused_variables,
                reason = "only an audited client names whom it acted for"
            )
        )]
        on_behalf: &OnBehalfOf,
        timeout: Duration,
    ) -> Result<SearchResult, PdqmError> {
        #[cfg(feature = "balp")]
        let deadline = ihe_atna::balp::recording::deadline(timeout);
        let result = self.post(query, timeout).await;
        #[cfg(feature = "balp")]
        let result = self
            .audit(
                || {
                    // NOTE: BALP Query records the raw request; a POST search is its
                    // request line, media type and form body, as BALP's own example writes.
                    secrecy::SecretString::from(format!(
                        "POST {}\nContent-Type: {}\n\n{}",
                        secrecy::ExposeSecret::expose_secret(&ihe_atna::balp::request_text(
                            &self.endpoint
                        )),
                        request::FORM,
                        query.form()
                    ))
                },
                on_behalf,
                result,
                deadline,
            )
            .await;
        result
    }

    async fn post(
        &self,
        query: &PatientQuery,
        timeout: Duration,
    ) -> Result<SearchResult, PdqmError> {
        let built = self
            .http
            .post(self.endpoint.clone())
            .header(ACCEPT, FHIR_JSON)
            .header(CONTENT_TYPE, request::FORM)
            .body(query.form())
            .build()
            .map_err(error::transport)?;
        let response = self.send(built, timeout).await?;
        self.answer(response, query.names_domain()).await
    }

    /// Asks the Supplier for the page `page` links to, the `next` link of an
    /// earlier page (FHIR R4 paging, <http://hl7.org/fhir/R4/http.html#paging>),
    /// on behalf of `on_behalf`, whom an audited client's record names.
    ///
    /// # Errors
    /// [`PdqmError::ForeignPage`] when `page` is not on the Supplier's origin,
    /// which the client does not follow; otherwise as [`PdqmClient::search`].
    pub async fn next_page(
        &self,
        page: &Page,
        #[cfg_attr(
            not(feature = "balp"),
            expect(
                unused_variables,
                reason = "only an audited client names whom it acted for"
            )
        )]
        on_behalf: &OnBehalfOf,
        timeout: Duration,
    ) -> Result<SearchResult, PdqmError> {
        // NOTE: no specification governs this: our own design, so a Supplier's
        // link cannot send this client's credentials to another origin.
        if page.url().origin() != self.endpoint.origin() {
            return Err(PdqmError::ForeignPage);
        }
        #[cfg(feature = "balp")]
        let deadline = ihe_atna::balp::recording::deadline(timeout);
        let result = self.get(page, timeout).await;
        #[cfg(feature = "balp")]
        let result = self
            .audit(
                || ihe_atna::balp::request_text(page.url()),
                on_behalf,
                result,
                deadline,
            )
            .await;
        result
    }

    async fn get(&self, page: &Page, timeout: Duration) -> Result<SearchResult, PdqmError> {
        let built = self
            .http
            .get(page.url().clone())
            .header(ACCEPT, FHIR_JSON)
            .build()
            .map_err(error::transport)?;
        let response = self.send(built, timeout).await?;
        self.answer(response, false).await
    }

    /// Sends `request` within `timeout`, authenticated by the authorizer when
    /// there is one.
    async fn send(
        &self,
        request: reqwest::Request,
        timeout: Duration,
    ) -> Result<reqwest::Response, PdqmError> {
        authorizer::send(&self.http, self.authorizer.as_deref(), request, timeout)
            .await
            .map_err(error::unsent)
    }

    async fn answer(
        &self,
        response: reqwest::Response,
        names_domain: bool,
    ) -> Result<SearchResult, PdqmError> {
        let status = response.status();
        let media = response
            .headers()
            .get(CONTENT_TYPE)
            .and_then(|value| value.to_str().ok())
            .map(str::to_owned);
        let body = response::body(response).await?;
        response::read(status, media.as_deref(), &body, &self.base, names_domain)
    }
}

impl fmt::Debug for PdqmClient {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("PdqmClient")
            .field("base", &RedactedUrl(self.base.as_str()))
            .field("endpoint", &RedactedUrl(self.endpoint.as_str()))
            .field("authorizer", &self.authorizer.is_some())
            .finish_non_exhaustive()
    }
}