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
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
// SPDX-FileCopyrightText: Cadasto B.V.
// SPDX-License-Identifier: BUSL-1.1

//! The Query Client of ITI-90 and the Update Client of ITI-91 over the
//! `Organization` and `Endpoint` resources of a care services directory
//! (mCSD 4.0.0, ITI TF-2 §3.90, §3.91).
//!
//! [`McsdClient::find`] is ITI-90, Find Matching Care Services: a FHIR
//! `search-type` interaction, `GET [base]/[type]?[parameters]`, answered with
//! a `searchset` Bundle (`CapabilityStatement-IHE.mCSD.QueryClient`).
//! [`McsdClient::updates`] is ITI-91, Request Care Services Updates: a FHIR
//! `history-type` interaction, `GET [base]/[type]/_history?_since=[instant]`,
//! answered with a `history` Bundle, newest version first
//! (`CapabilityStatement-IHE.mCSD.UpdateClient`; FHIR R4 history,
//! <http://hl7.org/fhir/R4/http.html#history>). Both follow every `next` link
//! on the directory's own origin, so a caller gets the whole answer or an
//! error.

mod response;

use fhir_types::r4::endpoint::Endpoint;
use fhir_types::r4::organization::Organization;
use http::header::{ACCEPT, CONTENT_TYPE, DATE};
use std::fmt;
use std::sync::Arc;
use url::Url;

use super::budget::Budget;
use super::error::{InvalidBase, McsdError};
use crate::authorizer::{self, Authorizer};

use ihe_atna::redact::RedactedUrl;

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

/// The care service resource types a federation registry reads from a
/// directory.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[non_exhaustive]
pub enum CareService {
    /// `Organization`.
    Organization,
    /// `Endpoint`.
    Endpoint,
}

impl CareService {
    /// The FHIR resource type name.
    #[must_use]
    pub const fn resource_type(self) -> &'static str {
        match self {
            Self::Organization => "Organization",
            Self::Endpoint => "Endpoint",
        }
    }
}

/// One `Organization` or `Endpoint` a directory answered with.
///
/// `Debug` shows the type and the logical id only: an `Endpoint`'s `header`
/// list may hold a credential.
#[derive(Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum CareResource {
    /// An `Organization`.
    Organization(Box<Organization>),
    /// An `Endpoint`.
    Endpoint(Box<Endpoint>),
}

impl CareResource {
    /// The resource's type.
    #[must_use]
    pub fn kind(&self) -> CareService {
        match self {
            Self::Organization(_) => CareService::Organization,
            Self::Endpoint(_) => CareService::Endpoint,
        }
    }

    /// The resource's logical id.
    #[must_use]
    pub fn logical_id(&self) -> Option<&str> {
        match self {
            Self::Organization(resource) => resource.id.as_deref(),
            Self::Endpoint(resource) => resource.id.as_deref(),
        }
    }

    /// Whether the resource carries an identifier in `system`.
    #[must_use]
    pub fn identified_in(&self, system: &str) -> bool {
        let identifiers = match self {
            Self::Organization(resource) => &resource.identifier,
            Self::Endpoint(resource) => &resource.identifier,
        };
        identifiers.iter().any(|identifier| {
            identifier
                .system
                .as_ref()
                .and_then(|uri| uri.value.as_deref())
                == Some(system)
        })
    }
}

impl fmt::Debug for CareResource {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("CareResource")
            .field("kind", &self.kind())
            .field("logical_id", &self.logical_id())
            .finish()
    }
}

/// One resource an ITI-90 search matched, with the `fullUrl` its entry
/// carried.
#[derive(Clone, PartialEq, Eq)]
pub struct Match {
    full_url: String,
    resource: CareResource,
}

impl Match {
    /// The entry's `fullUrl`.
    #[must_use]
    pub fn full_url(&self) -> &str {
        &self.full_url
    }

    /// The resource.
    #[must_use]
    pub fn resource(&self) -> &CareResource {
        &self.resource
    }

    /// The `fullUrl` and the resource.
    #[must_use]
    pub fn into_parts(self) -> (String, CareResource) {
        (self.full_url, self.resource)
    }
}

impl fmt::Debug for Match {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("Match")
            .field("full_url", &RedactedUrl(&self.full_url))
            .field("resource", &self.resource)
            .finish()
    }
}

/// What an ITI-90 search found, over every page.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Found {
    matches: Vec<Match>,
    answered_at: Option<String>,
}

impl Found {
    /// Every match, in the order the pages listed them.
    #[must_use]
    pub fn matches(&self) -> &[Match] {
        &self.matches
    }

    /// Every match, by value.
    #[must_use]
    pub fn into_matches(self) -> Vec<Match> {
        self.matches
    }

    /// The `Date` the directory stamped its first page with (RFC 9110
    /// §6.6.1), as written, on the directory's own clock; `None` when it
    /// sent none.
    #[must_use]
    pub fn answered_at(&self) -> Option<&str> {
        self.answered_at.as_deref()
    }
}

/// What one ITI-91 history entry says of a resource.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum Version {
    /// The resource was created or updated to this version, with the
    /// `fullUrl` its entry carried.
    Current {
        /// The entry's `fullUrl`.
        full_url: String,
        /// The resource.
        resource: CareResource,
    },
    /// The resource was deleted.
    Deleted,
}

/// One entry of an ITI-91 history: a resource's logical id and what became
/// of it.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Change {
    logical_id: String,
    version: Version,
}

impl Change {
    /// The logical id of the resource the entry is about.
    #[must_use]
    pub fn logical_id(&self) -> &str {
        &self.logical_id
    }

    /// What became of it.
    #[must_use]
    pub fn version(&self) -> &Version {
        &self.version
    }

    /// The logical id and the version.
    #[must_use]
    pub fn into_parts(self) -> (String, Version) {
        (self.logical_id, self.version)
    }
}

/// What an ITI-91 history answered, over every page: newest version first
/// (FHIR R4 history, "sorted with oldest versions last").
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Updates {
    changes: Vec<Change>,
    answered_at: Option<String>,
}

impl Updates {
    /// Every change, newest first.
    #[must_use]
    pub fn changes(&self) -> &[Change] {
        &self.changes
    }

    /// Every change, by value, newest first.
    #[must_use]
    pub fn into_changes(self) -> Vec<Change> {
        self.changes
    }

    /// The `Date` the directory stamped its first page with (RFC 9110
    /// §6.6.1), as written, on the directory's own clock; `None` when it
    /// sent none.
    #[must_use]
    pub fn answered_at(&self) -> Option<&str> {
        self.answered_at.as_deref()
    }
}

/// A Query Client and Update Client bound to one care services directory.
///
/// `Debug` shows the base with its userinfo and query replaced by `***`, and
/// leaves out the HTTP client, whose default headers may hold a credential.
#[derive(Clone)]
pub struct McsdClient {
    base: Url,
    organization: Interactions,
    endpoint: Interactions,
    http: reqwest::Client,
    authorizer: Option<Arc<dyn Authorizer>>,
    #[cfg(feature = "balp")]
    audit: Option<Arc<dyn ihe_atna::balp::AuditRecorder>>,
}

/// The URLs of the two interactions on one resource type.
#[derive(Clone)]
struct Interactions {
    /// `[base]/[type]`, the `search-type` interaction.
    search: Url,
    /// `[base]/[type]/_history`, the `history-type` interaction.
    history: Url,
}

impl Interactions {
    /// The interactions on `kind` under the FHIR base `base`.
    fn of(base: &Url, kind: CareService) -> Result<Self, InvalidBase> {
        let search = ihe_atna::fhir_base::under_base(base.clone(), kind.resource_type())
            .ok_or(InvalidBase)?;
        let history = ihe_atna::fhir_base::under_base(
            base.clone(),
            &format!("{}/_history", kind.resource_type()),
        )
        .ok_or(InvalidBase)?;
        Ok(Self { search, history })
    }
}

impl McsdClient {
    /// Creates a client for the directory 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()`, so a `3xx` is an error like
    /// any other unexpected status and never takes the credentials elsewhere.
    ///
    /// # Errors
    /// [`InvalidBase`] 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, InvalidBase> {
        let base = ihe_atna::fhir_base::under_base(base, "").ok_or(InvalidBase)?;
        Ok(Self {
            organization: Interactions::of(&base, CareService::Organization)?,
            endpoint: Interactions::of(&base, CareService::Endpoint)?,
            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 ITI-90 search and
    /// ITI-91 history through `recorder` (§2:3.90.5.1, §2:3.91.5.1, feature
    /// `balp`).
    ///
    /// An audited client records each transaction before it returns,
    /// whatever its outcome; one whose record the recorder does not accept
    /// fails with [`McsdError::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 transaction of `kind` begun with `request`, when the
    /// client is audited, and returns `result` unless the record was refused.
    #[cfg(feature = "balp")]
    async fn audit<T>(
        &self,
        kind: ihe_atna::balp::EventKind,
        request: &Url,
        result: Result<T, McsdError>,
    ) -> Result<T, McsdError> {
        if let Some(recorder) = &self.audit {
            let exchange = super::audit::exchange(kind, &self.base, request, &result);
            // NOTE: mCSD §2:3.90.5.1 and §2:3.91.5.1 make the audit record part of
            // the transaction, so an answer whose record was refused is not used.
            recorder.record(exchange).await.map_err(McsdError::Audit)?;
        }
        result
    }

    /// The interactions on `kind`.
    fn interactions(&self, kind: CareService) -> &Interactions {
        match kind {
            CareService::Organization => &self.organization,
            CareService::Endpoint => &self.endpoint,
        }
    }

    /// Returns the directory's FHIR base URL, ending in `/`.
    #[must_use]
    pub fn base(&self) -> &Url {
        &self.base
    }

    /// Asks the directory for every resource of type `kind` that matches
    /// `parameters`, each a search parameter name and its value as FHIR search
    /// writes it (ITI-90, §3.90.4.1).
    ///
    /// Every page draws on `budget`: its deadline bounds the whole walk, and
    /// its pages, bytes and entries are spent as the pages are read.
    ///
    /// # Errors
    /// A [`McsdError`] for a page that is not a `searchset` Bundle of `kind`,
    /// a page link off the directory's origin, a budget that runs out, a
    /// failure to get a page at all, and, when audited, a record the
    /// recorder refused.
    pub async fn find(
        &self,
        kind: CareService,
        parameters: &[(&str, &str)],
        budget: &mut Budget,
    ) -> Result<Found, McsdError> {
        let mut url = self.interactions(kind).search.clone();
        if !parameters.is_empty() {
            url.query_pairs_mut().extend_pairs(parameters);
        }
        let result = self.find_pages(url.clone(), kind, budget).await;
        #[cfg(feature = "balp")]
        let result = self.audit(super::audit::query(), &url, result).await;
        result
    }

    /// Reads every page of the search that begins at `url`.
    async fn find_pages(
        &self,
        url: Url,
        kind: CareService,
        budget: &mut Budget,
    ) -> Result<Found, McsdError> {
        let mut matches = Vec::new();
        let mut answered_at = None;
        let mut next = Some(url);
        let mut first = true;
        while let Some(url) = next.take() {
            let page = self.page(url, budget).await?;
            if first {
                answered_at = page.date;
                first = false;
            }
            let read = response::searchset(&page.body, kind, &self.base)?;
            budget.entries(read.entries)?;
            matches.extend(read.matches);
            next = read.next;
        }
        Ok(Found {
            matches,
            answered_at,
        })
    }

    /// Asks the directory for every version of a resource of type `kind`
    /// created at or after `since`, a FHIR `instant` as written (ITI-91,
    /// §3.91.4.1; FHIR R4 history, `_since`).
    ///
    /// Every page draws on `budget`, as [`McsdClient::find`]'s do.
    ///
    /// # Errors
    /// A [`McsdError`] for a page that is not a `history` Bundle of `kind`,
    /// a page link off the directory's origin, a budget that runs out, a
    /// failure to get a page at all, and, when audited, a record the
    /// recorder refused.
    pub async fn updates(
        &self,
        kind: CareService,
        since: &str,
        budget: &mut Budget,
    ) -> Result<Updates, McsdError> {
        let mut url = self.interactions(kind).history.clone();
        url.query_pairs_mut().append_pair("_since", since);
        let result = self.history_pages(url.clone(), kind, budget).await;
        #[cfg(feature = "balp")]
        let result = self.audit(super::audit::updates(), &url, result).await;
        result
    }

    /// Reads every page of the history that begins at `url`.
    async fn history_pages(
        &self,
        url: Url,
        kind: CareService,
        budget: &mut Budget,
    ) -> Result<Updates, McsdError> {
        let mut changes = Vec::new();
        let mut answered_at = None;
        let mut next = Some(url);
        let mut first = true;
        while let Some(url) = next.take() {
            let page = self.page(url, budget).await?;
            if first {
                answered_at = page.date;
                first = false;
            }
            let read = response::history(&page.body, kind, &self.base)?;
            budget.entries(read.changes.len())?;
            changes.extend(read.changes);
            next = read.next;
        }
        Ok(Updates {
            changes,
            answered_at,
        })
    }

    /// Reads one page from `url`, within what is left of `budget`.
    async fn page(&self, url: Url, budget: &mut Budget) -> Result<response::Page, McsdError> {
        budget.page()?;
        // NOTE: no specification governs this: our own design, so a directory's
        // link cannot send this client's credentials to another origin.
        if url.origin() != self.base.origin() {
            return Err(McsdError::ForeignPage);
        }
        let request = self
            .http
            .get(url)
            .header(ACCEPT, FHIR_JSON)
            .build()
            .map_err(response::transport)?;
        let answer = authorizer::send(
            &self.http,
            self.authorizer.as_deref(),
            request,
            budget.remaining()?,
        )
        .await
        .map_err(response::unsent)?;
        let status = answer.status();
        let media = answer
            .headers()
            .get(CONTENT_TYPE)
            .and_then(|value| value.to_str().ok())
            .map(str::to_owned);
        let date = answer
            .headers()
            .get(DATE)
            .and_then(|value| value.to_str().ok())
            .map(str::to_owned);
        let body = response::body(answer, budget).await?;
        response::page(status, media.as_deref(), body, date)
    }
}

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