fhirconnect 0.2.3

The FHIRconnect mapping language for Rust: the mapping file model and its validation, context resolution into an immutable program, and the bidirectional interpreter between openEHR compositions and FHIR resources
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
// SPDX-FileCopyrightText: Cadasto B.V.
// SPDX-License-Identifier: BUSL-1.1

//! The composition defaults and the build of the values a run produced.

use std::collections::BTreeSet;

use openehr_base::v1_3::base_types::identification::terminology_id::TerminologyId;
use openehr_mapping_core::composition::CanonicalComposition;
use openehr_mapping_core::composition::NodeValue;
use openehr_mapping_core::composition::RmPosition;
use openehr_mapping_core::index::ResolvedNode;
use openehr_mapping_core::index::paths::AqlPath;
use openehr_mapping_core::party::PartyClass;
use openehr_mapping_core::template::PathError;
use openehr_rm::v1_2::common::generic::party_identified::PartyIdentifiedData;
use openehr_rm::v1_2::data_types::text::code_phrase::CodePhrase;
use openehr_rm::v1_2::data_types::text::dv_coded_text::DvCodedText;
use openehr_rm::v1_2::support::terminology::openehr_terminology_group_identifiers::OpenehrTerminologyGroupIdentifiersData;

use crate::engine::family;
use crate::engine::outcome::Location;
use crate::engine::outcome::Loss;
use crate::engine::outcome::Warning;
use crate::engine::rm;
use crate::engine::rm::RmError;
use crate::engine::rm::RmValue;

use crate::tree::element::Table;

use crate::engine::traverse::Held;
use crate::engine::traverse::Routed;
use crate::engine::traverse::Run;
use crate::engine::traverse::defaults::Defaults;
use crate::engine::traverse::error::EngineError;
use crate::resolve::compile::openehr::occurrences;

/// The archetype path of `COMPOSITION.composer`.
pub(super) const COMPOSER: &str = "/composer";

/// The archetype path of `COMPOSITION.context`.
const CONTEXT: &str = "/context";

/// The path a defaulted health care facility is recorded under.
const HEALTH_CARE_FACILITY_PATH: &str = "/context/health_care_facility";

/// The RM type of an `INSTRUCTION` entry (RM EHR IM §INSTRUCTION).
const INSTRUCTION: &str = "INSTRUCTION";

impl<'a, T: Table + ?Sized> Run<'a, T> {
    /// Fills the composition fields no mapping wrote.
    ///
    /// Returns the openEHR path of every field it filled, in the order it
    /// filled them, which is the order of the
    /// [`Loss::Defaulted`] warnings it
    /// recorded. Which fields take a default is FHIRconnect's
    /// (`engine/defaults-for-fields.adoc`); every default travels as the `ctx/`
    /// key the FLAT builder resolves (Simplified Formats, master06 §Composer,
    /// §time, §setting, §Language and Territory). `ctx/setting` carries the
    /// code and the builder takes the rubric from the openEHR terminology's
    /// [`OpenehrTerminologyGroupIdentifiersData::GROUP_ID_SETTING`] group, so
    /// the project's value is checked against the built composition.
    ///
    /// # Errors
    ///
    /// Returns [`EngineError::Template`] when the template cannot answer for a
    /// defaulted field.
    pub(super) fn apply_defaults(
        &mut self,
        defaults: &Defaults,
    ) -> Result<Vec<String>, EngineError> {
        let mut filled = Vec::new();
        self.release_void_composer()?;
        let identified = self
            .unwritten(COMPOSER)?
            .filter(|_| !defaults.composer_identifiers.is_empty());
        if let Some(node) = identified {
            self.families.push(family::composer(
                node,
                &defaults.composer,
                defaults.composer_id.as_ref(),
                &defaults.composer_identifiers,
            ));
            self.defaulted(&mut filled, COMPOSER);
        } else {
            if self.unwritten(COMPOSER)?.is_some()
                && let Some(id) = defaults.composer_id.as_ref()
            {
                for (field, value) in [
                    ("composer_id", &id.id),
                    ("id_namespace", &id.namespace),
                    ("id_scheme", &id.scheme),
                ] {
                    self.context_keys.push(NodeValue::context(
                        field,
                        serde_json::Value::String(value.clone()),
                    ));
                }
            }
            self.default_context(&mut filled, COMPOSER, "composer_name", &defaults.composer)?;
        }
        self.default_context(
            &mut filled,
            "/context/start_time",
            "time",
            &defaults.start_time,
        )?;
        if let Some(node) = self.unwritten("/context/setting")? {
            let setting = defaults.setting.clone();
            self.context_keys.push(NodeValue::context(
                "setting",
                serde_json::Value::String(setting.code.clone()),
            ));
            self.expected.push((
                node.flat_id().clone(),
                RmValue::CodedText(Box::new(DvCodedText {
                    value: setting.value,
                    hyperlink: None,
                    formatting: None,
                    mappings: None,
                    language: None,
                    encoding: None,
                    defining_code: CodePhrase {
                        terminology_id: TerminologyId {
                            value: String::from(
                                OpenehrTerminologyGroupIdentifiersData::TERMINOLOGY_ID_OPENEHR,
                            ),
                        },
                        code_string: setting.code,
                        preferred_term: None,
                    },
                })),
            ));
            self.defaulted(&mut filled, "/context/setting");
        }
        if let Some(ref code) = defaults.language {
            self.default_context(&mut filled, "/language", "language", code)?;
        }
        if let Some(ref code) = defaults.territory {
            self.default_context(&mut filled, "/territory", "territory", code)?;
        }
        self.declare_narratives(&mut filled)?;
        Ok(filled)
    }

    /// Writes the default facility as the `_health_care_facility` family of the
    /// `context` node when the template has one and no mapping wrote the
    /// family, and answers whether the composition has no `EVENT_CONTEXT` to
    /// hold it.
    ///
    /// # Errors
    ///
    /// Returns [`EngineError::Template`] when the template cannot answer for
    /// the context node.
    pub(super) fn place_facility(
        &mut self,
        defaults: &Defaults,
        filled: &mut Vec<String>,
    ) -> Result<bool, EngineError> {
        let Some(facility) = defaults.facility.as_ref() else {
            return Ok(false);
        };
        let Some(context) = self.node_at(CONTEXT)? else {
            return Ok(true);
        };
        if !self.facility_written {
            self.families
                .extend(family::health_care_facility(context, facility));
            self.defaulted(filled, HEALTH_CARE_FACILITY_PATH);
        }
        Ok(false)
    }

    /// Declares every `INSTRUCTION.narrative` the run leaves to the FLAT
    /// builder, one per instruction instance the run writes into.
    ///
    /// `narrative` is a mandatory `DV_TEXT` of `INSTRUCTION` (RM EHR IM
    /// §INSTRUCTION), and the builder fills one no key carries with a
    /// placeholder text, so the value reaches the composition without a
    /// mapping writing it. `engine/defaults-for-fields.adoc` does not list
    /// it; declaring the fill as a default is our own design, so the stored
    /// composition names it in `FEEDER_AUDIT` and the run warns.
    ///
    /// # Errors
    ///
    /// Returns [`EngineError::Template`] when the template cannot answer for
    /// a narrative node or its occurrence axes.
    fn declare_narratives(&mut self, filled: &mut Vec<String>) -> Result<(), EngineError> {
        let instructions: Vec<&'a ResolvedNode> = self
            .index
            .nodes()
            .filter(|node| node.rm_type() == INSTRUCTION)
            .collect();
        for instruction in instructions {
            let path = format!("{}/narrative", instruction.aql_path().as_str());
            let narrative = self.node_at(&path)?.map(|node| node.flat_id().clone());
            let refuse = |source: PathError| EngineError::Template {
                mapping: String::from(self.program.context().as_str()),
                node: path.clone(),
                source: Box::new(source),
            };
            let depth = occurrences(self.index, instruction).map_err(refuse)?.len();
            let within = format!("{}/", instruction.flat_id().as_str());
            let instances: BTreeSet<&[RmPosition]> = self
                .written
                .iter()
                .filter(|written| written.flat_id.as_str().starts_with(&within))
                .filter_map(|written| written.positions.get(..depth))
                .collect();
            let unwritten = instances
                .into_iter()
                .filter(|instance| {
                    !self.written.iter().any(|written| {
                        narrative.as_ref() == Some(&written.flat_id)
                            && written.positions.get(..depth) == Some(*instance)
                    })
                })
                .count();
            for _ in 0..unwritten {
                self.defaulted(filled, &path);
            }
        }
        Ok(())
    }

    /// Writes one default as the `ctx/` key `field`, when the template holds
    /// a node at `path` and nothing wrote it already.
    ///
    /// # Errors
    ///
    /// Returns [`EngineError::Template`] when the template cannot answer for
    /// the path for any reason other than holding no node at it.
    fn default_context(
        &mut self,
        filled: &mut Vec<String>,
        path: &str,
        field: &str,
        value: &str,
    ) -> Result<(), EngineError> {
        if self.unwritten(path)?.is_some() {
            self.context_keys.push(NodeValue::context(
                field,
                serde_json::Value::String(String::from(value)),
            ));
            self.defaulted(filled, path);
        }
        Ok(())
    }

    /// Records that the engine filled the field at `path`.
    fn defaulted(&mut self, filled: &mut Vec<String>, path: &str) {
        self.warnings.push(Warning::new(
            Loss::Defaulted {
                field: String::from(path),
            },
            Location::default().with_openehr(path),
        ));
        filled.push(String::from(path));
    }

    /// Returns the node at `path` when the template holds one and no mapping
    /// wrote it.
    ///
    /// # Errors
    ///
    /// Returns [`EngineError::Template`] when the template cannot answer for
    /// the path for any reason other than holding no node at it.
    fn unwritten(&self, path: &str) -> Result<Option<&'a ResolvedNode>, EngineError> {
        let Some(node) = self.node_at(path)? else {
            return Ok(None);
        };
        let written = self
            .written
            .iter()
            .any(|written| written.flat_id == *node.flat_id());
        Ok((!written).then_some(node))
    }

    /// Forgets a composer the run wrote as a `PARTY_IDENTIFIED` holding no
    /// name, identifier or external reference, so the default composer
    /// applies.
    ///
    /// A FHIR `Reference` carrying only `reference` puts nothing in the
    /// party, since the demographics lookup the `PARTY_IDENTIFIED` cell of
    /// FHIRconnect names is the caller's, and the RM refuses such a party.
    ///
    /// # Errors
    ///
    /// Returns [`EngineError::Template`] when the template cannot answer for
    /// the composer for any reason other than holding no node at it.
    fn release_void_composer(&mut self) -> Result<(), EngineError> {
        let Some(node) = self.node_at(COMPOSER)? else {
            return Ok(());
        };
        self.written.retain(|written| {
            written.flat_id != *node.flat_id()
                || !matches!(written.value, Held::Value(RmValue::Party(ref party)) if void(party))
        });
        Ok(())
    }

    /// Returns the node at `path`, `None` when the template holds none.
    ///
    /// # Errors
    ///
    /// Returns [`EngineError::Template`] when the template cannot answer for
    /// the path for any reason other than holding no node at it.
    fn node_at(&self, path: &str) -> Result<Option<&'a ResolvedNode>, EngineError> {
        match self.index.node(&AqlPath::new(path)) {
            Ok(node) => Ok(Some(node)),
            // NOTE: engine/defaults-for-fields.adoc, the context "is usually
            // populated", so a template with no node at the path takes no default.
            Err(PathError::UnknownPath { .. }) => Ok(None),
            Err(source) => Err(EngineError::Template {
                mapping: String::from(self.program.context().as_str()),
                node: String::from(path),
                source: Box::new(source),
            }),
        }
    }

    /// Returns the values the run produced, as the composition builder wants
    /// them, with the defaults the builder takes through the `ctx/` keys.
    ///
    /// Every value travels whole as its canonical JSON under `|raw`
    /// (Simplified Formats, master04 §Raw canonical JSON), the COMPOSITION
    /// `language`, `territory` and `composer` included; each default the run
    /// expects is returned beside its node so the run can check the built
    /// composition carries it.
    pub(super) fn node_values(&self) -> Result<(Vec<NodeValue>, Vec<Routed>), EngineError> {
        let mut values = Vec::new();
        let routed = self.expected.clone();
        for written in &self.written {
            let node = self
                .index
                .node_by_flat_id(&written.flat_id)
                .map_err(|source| EngineError::Build {
                    source: Box::new(source),
                })?;
            let refuse = |source: RmError| EngineError::Rm {
                mapping: String::from(node.aql_path().as_str()),
                node: String::from(node.aql_path().as_str()),
                source: Box::new(source),
            };
            // NOTE: no specification governs a party context: our own design, an attribute of
            // the party root (`rm::PARTY_ROOTS`) travels as the root's members, which no
            // data-type cell reads whole.
            if let Held::Partial(ref object) = written.value
                && PartyClass::from_rm_type(node.rm_type()).is_some()
            {
                let mut whole = serde_json::Value::Object(object.clone());
                rm::interval::fill_flags(&mut whole, node.rm_type());
                values.push(
                    NodeValue::new(node, whole)
                        .with_occurrences(written.positions.clone())
                        .with_datum(rm::RAW),
                );
                continue;
            }
            let value = match written.value {
                Held::Canonical(ref value) => {
                    values.push(
                        NodeValue::new(node, value.clone())
                            .with_occurrences(written.positions.clone())
                            .with_datum(rm::RAW),
                    );
                    continue;
                }
                Held::Value(ref value) => value.clone(),
                Held::Partial(ref object) => {
                    let rm_type = object
                        .get("_type")
                        .and_then(serde_json::Value::as_str)
                        .unwrap_or(node.rm_type());
                    let mut whole = serde_json::Value::Object(object.clone());
                    rm::interval::fill_flags(&mut whole, rm_type);
                    RmValue::from_canonical(rm_type, node.aql_path().as_str(), &whole)
                        .map_err(refuse)?
                }
            };
            values.push(
                NodeValue::new(node, value.to_canonical().map_err(refuse)?)
                    .with_occurrences(written.positions.clone())
                    .with_datum(rm::RAW),
            );
        }
        values.extend(self.families.iter().cloned());
        values.extend(self.context_keys.iter().cloned());
        Ok((values, routed))
    }

    /// Refuses a composition whose context-set attributes do not carry the
    /// value the run wrote there whole.
    ///
    /// # Errors
    ///
    /// Returns [`EngineError::ContextAttribute`] when the built value differs
    /// from the written one, and [`EngineError::Build`] or
    /// [`EngineError::Rm`] when the built value cannot be read back.
    pub(super) fn carried_whole(
        &self,
        built: &CanonicalComposition,
        routed: &[Routed],
    ) -> Result<(), EngineError> {
        let refuse_build = |source: PathError| EngineError::Build {
            source: Box::new(source),
        };
        for (flat_id, written) in routed {
            let node = self.index.node_by_flat_id(flat_id).map_err(refuse_build)?;
            let path = node.aql_path().as_str();
            let back = self
                .index
                .read(built, node, &[])
                .map_err(refuse_build)?
                .map(|value| RmValue::from_canonical(node.rm_type(), path, &value))
                .transpose()
                .map_err(|source| EngineError::Rm {
                    mapping: String::from(self.program.context().as_str()),
                    node: String::from(path),
                    source: Box::new(source),
                })?;
            if back.as_ref() != Some(written) {
                return Err(EngineError::ContextAttribute {
                    mapping: String::from(self.program.context().as_str()),
                    node: String::from(path),
                });
            }
        }
        Ok(())
    }
}

/// Returns whether `party` holds none of `name`, `identifiers` and
/// `external_ref`.
///
/// The openEHR RM `PARTY_IDENTIFIED` requires "at least one of name,
/// identifier or `external_ref`", so such a party is no value.
fn void(party: &PartyIdentifiedData) -> bool {
    party.name.is_none() && party.identifiers.is_none() && party.external_ref.is_none()
}

#[cfg(test)]
mod tests {
    use openehr_base::v1_3::base_types::identification::generic_id::GenericId;
    use openehr_base::v1_3::base_types::identification::object_id::ObjectId;
    use openehr_base::v1_3::base_types::identification::party_ref::PartyRef;
    use openehr_rm::v1_2::common::generic::party_identified::PartyIdentifiedData;

    use super::void;

    fn party(name: Option<&str>, external_ref: Option<PartyRef>) -> PartyIdentifiedData {
        PartyIdentifiedData {
            external_ref,
            name: name.map(String::from),
            identifiers: None,
        }
    }

    fn external_ref() -> PartyRef {
        PartyRef {
            namespace: String::from("demographics"),
            r#type: String::from("PERSON"),
            id: ObjectId::GenericId(GenericId {
                value: String::from("synthetic-practitioner-0001"),
                scheme: String::from("local"),
            }),
        }
    }

    #[test]
    fn a_composer_with_a_name_or_a_reference_is_no_void() {
        assert!(!void(&party(Some("Synthetic Recorder"), None)));
        assert!(!void(&party(None, Some(external_ref()))));
    }

    #[test]
    fn an_empty_composer_is_void() {
        assert!(void(&party(None, None)));
    }
}