use core::fmt;
use std::path::Path;
use std::path::PathBuf;
use std::sync::LazyLock;
use openehr_mapping_core::diagnostic::Diagnostic;
use openehr_mapping_core::header::metadata::MappingType;
use openehr_mapping_core::loader::MappingDocument;
use openehr_mapping_core::schema;
use openehr_mapping_core::schema::SchemaError;
use openehr_mapping_core::value::PositionedValue;
use crate::model::error::ModelCode;
use crate::model::error::SchemaKind;
pub struct Schemas {
model: jsonschema::Validator,
context: jsonschema::Validator,
}
impl fmt::Debug for Schemas {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Schemas").finish_non_exhaustive()
}
}
impl Schemas {
pub fn compile(model: &str, context: &str) -> Result<Self, SchemaError> {
Ok(Self {
model: schema::compile(model, SchemaKind::Model.file_name())?,
context: schema::compile(context, SchemaKind::Context.file_name())?,
})
}
#[must_use]
pub const fn validator(&self, kind: SchemaKind) -> &jsonschema::Validator {
match kind {
SchemaKind::Model => &self.model,
SchemaKind::Context => &self.context,
}
}
#[must_use]
pub fn validate_document(&self, document: &MappingDocument) -> Vec<Diagnostic> {
let kind = match document.header().mapping_type().map(|t| *t.value()) {
Some(MappingType::Context) => SchemaKind::Context,
Some(MappingType::Model | MappingType::Extension) | None => SchemaKind::Model,
};
self.validate(document.file(), kind, document.document())
}
#[must_use]
pub fn validate(
&self,
file: &Path,
kind: SchemaKind,
document: &PositionedValue,
) -> Vec<Diagnostic> {
schema::validate(
self.validator(kind),
file,
document,
&ModelCode::SchemaViolation.into(),
kind.file_name(),
)
}
}
pub mod strict {
use std::sync::LazyLock;
use crate::model::schema::Schemas;
use openehr_mapping_core::schema::SchemaError;
pub const MODEL_SCHEMA: &str = include_str!("../../schemas/model-mapping.schema.json");
pub const CONTEXT_SCHEMA: &str = include_str!("../../schemas/contextual-mapping.schema.json");
static COMPILED: LazyLock<Result<Schemas, SchemaError>> =
LazyLock::new(|| Schemas::compile(MODEL_SCHEMA, CONTEXT_SCHEMA));
pub fn schemas() -> Result<&'static Schemas, &'static SchemaError> {
COMPILED.as_ref()
}
}
static STRICT_SOURCES: LazyLock<[(SchemaKind, &str); 2]> = LazyLock::new(|| {
[
(SchemaKind::Model, strict::MODEL_SCHEMA),
(SchemaKind::Context, strict::CONTEXT_SCHEMA),
]
});
#[must_use]
pub fn strict_source(kind: SchemaKind) -> &'static str {
STRICT_SOURCES
.iter()
.find(|(candidate, _)| *candidate == kind)
.map_or(strict::MODEL_SCHEMA, |(_, source)| *source)
}
#[must_use]
pub fn vendored_published_path(kind: SchemaKind) -> PathBuf {
PathBuf::from("docs/specs/fhirconnect/modules/ROOT/attachments").join(kind.file_name())
}
#[cfg(test)]
mod tests {
use openehr_mapping_core::loader::load_str;
use openehr_mapping_core::position::Position;
use super::strict;
use crate::model::error::ModelCode;
use crate::model::error::SchemaKind;
use openehr_mapping_core::schema::locate;
const MODEL: &str = "grammar: FHIRConnect/v1.0.0\ntype: model\nmetadata:\n name: \
EVALUATION.test.v1\n version: 1.0.0\nspec:\n system: FHIR\n version: \
R4\n openEhrConfig:\n archetype: \
openEHR-EHR-EVALUATION.test.v1\nmappings:\n - name: \"a\"\n with:\n \
\x20 fhir: \"$resource.code\"\n openehr: \"$archetype\"\n";
#[test]
fn the_strict_schemas_compile() {
assert!(strict::schemas().is_ok(), "a committed schema must compile");
}
#[test]
fn a_well_formed_model_file_validates() {
let document = load_str("model.yml", MODEL).expect("a well-formed header");
let schemas = strict::schemas().expect("the strict schemas compile");
let diagnostics = schemas.validate_document(&document);
assert!(diagnostics.is_empty(), "{diagnostics:?}");
}
#[test]
fn a_mapping_key_the_grammar_does_not_define_is_refused() {
let source = format!("{MODEL} hardcodedValue: \"x\"\n");
let document = load_str("model.yml", &source).expect("a well-formed header");
let schemas = strict::schemas().expect("the strict schemas compile");
let diagnostics = schemas.validate_document(&document);
assert_eq!(diagnostics.len(), 1, "{diagnostics:?}");
let diagnostic = diagnostics.first().expect("one diagnostic");
assert_eq!(diagnostic.code(), &ModelCode::SchemaViolation.into());
assert_eq!(diagnostic.model_path().to_string(), "mappings[0]");
}
#[test]
fn the_four_omitted_concept_keys_validate() {
let source = "grammar: FHIRConnect/v1.0.0\ntype: model\nmetadata:\n name: \
EVALUATION.test.v1\n version: 1.0.0\nspec:\n system: FHIR\n version: \
R4\nmappings:\n - name: \"programmed\"\n mappingCode: \"toDaily\"\n - \
name: \"linked\"\n link:\n meaning: \"the case\"\n type: \
\"case\"\n - name: \"participation\"\n participationsFunction: \
\"asserter\"\n - name: \"translated\"\n conceptmap: \
\"http://example.invalid/ConceptMap/a\"\n";
let document = load_str("model.yml", source).expect("a well-formed header");
let schemas = strict::schemas().expect("the strict schemas compile");
let diagnostics = schemas.validate_document(&document);
assert!(diagnostics.is_empty(), "{diagnostics:?}");
}
#[test]
fn a_null_mappings_is_refused_by_the_strict_schema() {
let source = "grammar: FHIRConnect/v1.0.0\ntype: model\nmetadata:\n name: \
EVALUATION.test.v1\n version: 1.0.0\nspec:\n system: FHIR\n version: \
R4\nmappings:\n";
let document = load_str("model.yml", source).expect("a well-formed header");
let schemas = strict::schemas().expect("the strict schemas compile");
let diagnostics = schemas.validate_document(&document);
assert_eq!(diagnostics.len(), 1, "{diagnostics:?}");
}
#[test]
fn a_root_unidirectional_is_refused_by_the_strict_schema() {
let source = "grammar: FHIRConnect/v1.0.0\ntype: model\nunidirectional: \
\"openehr->fhir\"\nmetadata:\n name: EVALUATION.test.v1\n version: \
1.0.0\nspec:\n system: FHIR\n version: R4\n";
let document = load_str("model.yml", source).expect("a well-formed header");
let schemas = strict::schemas().expect("the strict schemas compile");
let diagnostics = schemas.validate_document(&document);
assert_eq!(diagnostics.len(), 1, "{diagnostics:?}");
}
#[test]
fn both_documented_direction_spellings_and_the_library_casing_validate() {
for value in [
"openehr->fhir",
"fhir->openehr",
"openEHR->fhir",
"fhir->openEHR",
] {
let source = format!("{MODEL} unidirectional: \"{value}\"\n");
let document = load_str("model.yml", &source).expect("a well-formed header");
let schemas = strict::schemas().expect("the strict schemas compile");
let diagnostics = schemas.validate_document(&document);
assert!(diagnostics.is_empty(), "{value}: {diagnostics:?}");
}
}
#[test]
fn a_direction_outside_the_set_is_refused_by_the_strict_schema() {
let source = format!("{MODEL} unidirectional: \"openehr<->fhir\"\n");
let document = load_str("model.yml", &source).expect("a well-formed header");
let schemas = strict::schemas().expect("the strict schemas compile");
let diagnostics = schemas.validate_document(&document);
assert_eq!(diagnostics.len(), 1, "{diagnostics:?}");
}
#[test]
fn an_openehr_condition_naming_no_attribute_is_refused_by_the_strict_schema() {
let source = format!(
"{MODEL} openehrCondition:\n targetRoot: \"$archetype\"\n operator: \"not empty\"\n"
);
let document = load_str("model.yml", &source).expect("a well-formed header");
let schemas = strict::schemas().expect("the strict schemas compile");
let diagnostics = schemas.validate_document(&document);
assert_eq!(diagnostics.len(), 1, "{diagnostics:?}");
let diagnostic = diagnostics.first().expect("one diagnostic");
assert_eq!(diagnostic.code(), &ModelCode::SchemaViolation.into());
}
#[test]
fn either_openehr_condition_attribute_spelling_validates() {
for attribute in [
" targetAttribute: \"items[at0071]\"\n",
" targetAttributes:\n - \"items[at0071]\"\n",
] {
let source = format!(
"{MODEL} openehrCondition:\n targetRoot: \"$archetype\"\n operator: \"not empty\"\n{attribute}"
);
let document = load_str("model.yml", &source).expect("a well-formed header");
let schemas = strict::schemas().expect("the strict schemas compile");
let diagnostics = schemas.validate_document(&document);
assert!(diagnostics.is_empty(), "{attribute}: {diagnostics:?}");
}
}
#[test]
fn a_fhir_condition_naming_no_attribute_validates() {
let source = format!(
"{MODEL} fhirCondition:\n targetRoot: \"$resource.code\"\n operator: \"not empty\"\n"
);
let document = load_str("model.yml", &source).expect("a well-formed header");
let schemas = strict::schemas().expect("the strict schemas compile");
let diagnostics = schemas.validate_document(&document);
assert!(diagnostics.is_empty(), "{diagnostics:?}");
}
#[test]
fn a_pointer_resolves_to_the_position_of_its_node() {
let document =
openehr_mapping_core::loader::parse_str("model.yml", MODEL).expect("well-formed YAML");
let (path, position) = locate(&document, "/mappings/0/with/openehr");
assert_eq!(path.to_string(), "mappings[0].with.openehr");
assert_eq!(position, Position::new(15, 7));
}
#[test]
fn the_vendored_published_path_names_the_published_file() {
let path = super::vendored_published_path(SchemaKind::Context);
assert!(
path.ends_with("contextual-mapping.schema.json"),
"{}",
path.display()
);
assert_eq!(
super::strict_source(SchemaKind::Context),
strict::CONTEXT_SCHEMA
);
}
}