use core::error::Error;
use core::fmt;
use fhir_types::codec::Value;
use crate::engine::bundle::Entry;
use crate::engine::bundle::resolve;
use crate::engine::demographics::Demographics;
use crate::engine::demographics::NoDemographics;
use crate::engine::linked::LinkedCompositions;
use crate::engine::terminology::NoTerminology;
use crate::engine::terminology::Terminology;
use crate::engine::traverse::functions::MappingFunctions;
use crate::engine::traverse::functions::NoMappingFunctions;
use crate::resolve::program::binding::ResourceType;
pub mod identity;
use identity::{DerivedIdentity, IdentitySink, ResourceIdentity};
pub trait ReferenceSource: fmt::Debug + Send + Sync {
fn fetch(
&self,
reference: &str,
expected: &ResourceType,
) -> Result<Option<Value>, ReferenceError>;
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct NoReferences;
impl ReferenceSource for NoReferences {
fn fetch(
&self,
_reference: &str,
_expected: &ResourceType,
) -> Result<Option<Value>, ReferenceError> {
Ok(None)
}
}
#[derive(Debug)]
pub struct BundleReferences<'source> {
entries: Vec<Entry>,
referrer: Option<String>,
further: &'source dyn ReferenceSource,
}
impl<'source> BundleReferences<'source> {
#[must_use]
pub fn new(
entries: Vec<(Option<String>, Value)>,
further: &'source dyn ReferenceSource,
) -> Self {
Self {
entries,
referrer: None,
further,
}
}
#[must_use]
pub fn with_referrer(mut self, full_url: impl Into<String>) -> Self {
self.referrer = Some(full_url.into());
self
}
}
impl ReferenceSource for BundleReferences<'_> {
fn fetch(
&self,
reference: &str,
expected: &ResourceType,
) -> Result<Option<Value>, ReferenceError> {
let found = resolve(&self.entries, self.referrer.as_deref(), reference);
match *found.as_slice() {
[] => self.further.fetch(reference, expected),
[only] => Ok(self.entries.get(only).map(|(_, resource)| resource.clone())),
ref several => Err(ReferenceError::Ambiguous {
reference: String::from(reference),
count: several.len(),
}),
}
}
}
#[derive(Debug, thiserror::Error)]
pub enum ReferenceError {
#[error("the resource {reference} could not be fetched")]
Fetch {
reference: String,
#[source]
source: Box<dyn Error + Send + Sync>,
},
#[error("{reference} resolves to a {found}, and the mapping reads a {expected}")]
WrongType {
reference: String,
expected: String,
found: String,
},
#[error("{reference} names {count} entries of the bundle")]
Ambiguous {
reference: String,
count: usize,
},
#[error("the composition of {reference} could not be linked")]
Link {
reference: String,
#[source]
source: Box<dyn Error + Send + Sync>,
},
#[error("no id could be assigned to the {resource_type} the run creates")]
Identity {
resource_type: String,
#[source]
source: Box<dyn Error + Send + Sync>,
},
}
#[derive(Debug, Clone, Copy)]
pub struct Seams<'seam> {
functions: &'seam dyn MappingFunctions,
references: &'seam dyn ReferenceSource,
identities: &'seam dyn IdentitySink,
terminology: &'seam dyn Terminology,
demographics: &'seam dyn Demographics,
resources: Option<&'seam dyn ResourceIdentity>,
linked: Option<&'seam dyn LinkedCompositions>,
}
const _: fn() = || {
const fn send<T: Send + Sync>() {}
send::<Seams<'static>>();
};
impl Default for Seams<'_> {
fn default() -> Self {
Self {
functions: &NoMappingFunctions,
references: &NoReferences,
identities: &DerivedIdentity,
terminology: &NoTerminology,
demographics: &NoDemographics,
resources: None,
linked: None,
}
}
}
impl<'seam> Seams<'seam> {
#[must_use]
pub fn with_functions(mut self, functions: &'seam dyn MappingFunctions) -> Self {
self.functions = functions;
self
}
#[must_use]
pub fn with_references(mut self, references: &'seam dyn ReferenceSource) -> Self {
self.references = references;
self
}
#[must_use]
pub fn with_identities(mut self, identities: &'seam dyn IdentitySink) -> Self {
self.identities = identities;
self
}
#[must_use]
pub fn functions(&self) -> &'seam dyn MappingFunctions {
self.functions
}
#[must_use]
pub fn references(&self) -> &'seam dyn ReferenceSource {
self.references
}
#[must_use]
pub fn with_terminology(mut self, terminology: &'seam dyn Terminology) -> Self {
self.terminology = terminology;
self
}
#[must_use]
pub fn identities(&self) -> &'seam dyn IdentitySink {
self.identities
}
#[must_use]
pub fn terminology(&self) -> &'seam dyn Terminology {
self.terminology
}
#[must_use]
pub fn with_demographics(mut self, demographics: &'seam dyn Demographics) -> Self {
self.demographics = demographics;
self
}
#[must_use]
pub fn demographics(&self) -> &'seam dyn Demographics {
self.demographics
}
#[must_use]
pub fn with_resource_identity(mut self, resources: &'seam dyn ResourceIdentity) -> Self {
self.resources = Some(resources);
self
}
#[must_use]
pub fn resource_identity(&self) -> Option<&'seam dyn ResourceIdentity> {
self.resources
}
#[must_use]
pub fn with_linked(mut self, linked: &'seam dyn LinkedCompositions) -> Self {
self.linked = Some(linked);
self
}
#[must_use]
pub fn linked(&self) -> Option<&'seam dyn LinkedCompositions> {
self.linked
}
}
#[cfg(test)]
mod tests {
use super::BundleReferences;
use super::NoReferences;
use super::ReferenceError;
use super::ReferenceSource;
use super::identity::DerivedIdentity;
use super::identity::IdentityRequest;
use super::identity::IdentitySink;
use crate::resolve::program::binding::ResourceType;
use fhir_types::codec::Value;
#[test]
fn a_derived_id_is_stable_and_inside_the_id_grammar() {
let request = IdentityRequest::new("Condition", "Condition", "context")
.with_occurrence(vec![2])
.with_unique(vec![String::from("left")]);
let first = DerivedIdentity
.identify(&request)
.expect("a digest is total");
let second = DerivedIdentity
.identify(&request)
.expect("a digest is total");
assert_eq!(first, second, "the same request derives the same id");
assert_eq!(first.len(), 64);
assert!(first.chars().all(|character| character.is_ascii_hexdigit()));
}
#[test]
fn two_occurrences_derive_two_ids() {
let at = |position: u32| {
DerivedIdentity
.identify(
&IdentityRequest::new("Condition", "Condition", "context")
.with_occurrence(vec![position]),
)
.expect("a digest is total")
};
assert_ne!(at(1), at(2));
}
#[test]
fn a_bundle_entry_answers_by_full_url_and_by_type_and_id() {
let specimen = Value::from_serde_json(serde_json::json!({
"resourceType": "Specimen",
"id": "synthetic-specimen-1"
}));
let source = BundleReferences::new(
vec![(Some(String::from("urn:uuid:5e3c")), specimen.clone())],
&NoReferences,
);
let expected = ResourceType::new("Specimen");
assert_eq!(
source
.fetch("urn:uuid:5e3c", &expected)
.expect("no failure"),
Some(specimen.clone())
);
assert_eq!(
source
.fetch("Specimen/synthetic-specimen-1", &expected)
.expect("no failure"),
Some(specimen)
);
assert_eq!(
source
.fetch("Specimen/another", &expected)
.expect("no failure"),
None
);
}
fn specimen(id: &str, version: Option<&str>) -> Value {
let mut resource = serde_json::json!({ "resourceType": "Specimen", "id": id });
if let (Some(version), Some(object)) = (version, resource.as_object_mut()) {
object.insert(
String::from("meta"),
serde_json::json!({ "versionId": version }),
);
}
Value::from_serde_json(resource)
}
#[test]
fn a_relative_reference_is_read_against_the_server_base_of_the_referrer() {
let near = specimen("synthetic-specimen-1", None);
let far = specimen("synthetic-specimen-1", None);
let source = BundleReferences::new(
vec![
(
Some(String::from(
"http://example.net/fhir/Specimen/synthetic-specimen-1",
)),
far,
),
(
Some(String::from(
"http://example.org/fhir/Specimen/synthetic-specimen-1",
)),
near.clone(),
),
],
&NoReferences,
)
.with_referrer("http://example.org/fhir/Observation/synthetic-9");
let expected = ResourceType::new("Specimen");
assert_eq!(
source
.fetch("Specimen/synthetic-specimen-1", &expected)
.expect("no failure"),
Some(near)
);
}
#[test]
fn a_versioned_reference_answers_the_entry_at_that_version() {
let url = "http://example.org/fhir/Specimen/synthetic-specimen-1";
let second = specimen("synthetic-specimen-1", Some("2"));
let source = BundleReferences::new(
vec![
(
Some(String::from(url)),
specimen("synthetic-specimen-1", Some("1")),
),
(Some(String::from(url)), second.clone()),
],
&NoReferences,
)
.with_referrer("http://example.org/fhir/Observation/synthetic-9");
let expected = ResourceType::new("Specimen");
assert_eq!(
source
.fetch("Specimen/synthetic-specimen-1/_history/2", &expected)
.expect("no failure"),
Some(second)
);
let refused = source
.fetch(url, &expected)
.expect_err("two versions answer an unversioned reference");
assert!(
matches!(refused, ReferenceError::Ambiguous { count: 2, .. }),
"the refusal counts the entries: {refused}"
);
}
}