fhir 1.0.0

Fast Healthcare Interoperability Resources (FHIR) API is a standardized, RESTful interface for exchanging electronic health records.
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
//! Lightweight FHIR R5 validation.
//!
//! Provides a [`Validate`] trait and format checks for the FHIR primitive
//! datatypes (the regular-expression constraints from the specification,
//! implemented without an external regex dependency).
//!
//! Recursive validation of complex types and resources (walking every field)
//! is intended to be added via a `#[derive(Validate)]` procedural macro; until
//! then, callers validate primitive values directly.
//!
//! # Examples
//!
//! ```
//! use fhir::r5::types::Id;
//! use fhir::r5::validate::Validate;
//!
//! assert!(Id("patient-1".to_string()).validate().is_empty());
//! assert!(!Id("bad id!".to_string()).validate().is_empty());
//! ```

use crate::r5::types;

/// A single validation problem, with the location and a human-readable message.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ValidationIssue {
    /// A path or label identifying what failed (e.g. the datatype name).
    pub path: String,
    /// A human-readable description of the problem.
    pub message: String,
}

impl From<ValidationIssue> for crate::r5::resources::operation_outcome::OperationOutcomeIssue {
    fn from(issue: ValidationIssue) -> Self {
        use crate::r5::coded::Coded;
        use crate::r5::codes::{IssueSeverity, IssueType};
        Self {
            severity: Coded::Known(IssueSeverity::Error),
            code: Coded::Known(IssueType::Invalid),
            diagnostics: Some(types::String(issue.message)),
            expression: vec![types::String(issue.path)],
            ..Default::default()
        }
    }
}

/// Bridge validation results into a FHIR `OperationOutcome` — each
/// [`ValidationIssue`] becomes an `issue` entry with `error` severity and an
/// `invalid` code, its message in `diagnostics` and its path in `expression`.
///
/// ```
/// use fhir::r5::resources::Patient;
/// use fhir::r5::resources::operation_outcome::OperationOutcome;
/// use fhir::r5::types::Uri;
/// use fhir::r5::validate::Validate;
///
/// let mut patient = Patient::default();
/// patient.implicit_rules = Some(Uri(" bad ".to_string()));
///
/// let outcome: OperationOutcome = patient.validate().into();
/// assert_eq!(outcome.issue.len(), 1);
/// assert_eq!(outcome.issue[0].expression[0].0, "implicit_rules.uri");
/// ```
impl From<Vec<ValidationIssue>> for crate::r5::resources::operation_outcome::OperationOutcome {
    fn from(issues: Vec<ValidationIssue>) -> Self {
        use crate::r5::coded::Coded;
        use crate::r5::codes::{IssueSeverity, IssueType};
        use crate::r5::resources::operation_outcome::{OperationOutcome, OperationOutcomeIssue};

        let mut items: Vec<OperationOutcomeIssue> = issues.into_iter().map(Into::into).collect();
        if items.is_empty() {
            // `OperationOutcome.issue` is 1..*; represent "no problems" as an
            // information-severity issue.
            items.push(OperationOutcomeIssue {
                severity: Coded::Known(IssueSeverity::Information),
                code: Coded::Known(IssueType::Informational),
                diagnostics: Some(types::String("No issues detected.".to_string())),
                ..Default::default()
            });
        }
        OperationOutcome {
            issue: ::vec1::Vec1::try_from_vec(items).expect("non-empty"),
            id: None,
            meta: None,
            implicit_rules: None,
            implicit_rules_ext: None,
            language: None,
            language_ext: None,
            text: None,
            contained: Vec::new(),
            extension: Vec::new(),
            modifier_extension: Vec::new(),
        }
    }
}

impl ValidationIssue {
    pub(crate) fn new(path: &str, message: impl Into<String>) -> Self {
        Self {
            path: path.to_string(),
            message: message.into(),
        }
    }
}

/// Types that can validate themselves against FHIR constraints.
pub trait Validate {
    /// Return all validation issues; an empty vector means the value is valid.
    fn validate(&self) -> Vec<ValidationIssue>;

    /// Convenience: `true` when [`Validate::validate`] finds no issues.
    fn is_valid(&self) -> bool {
        self.validate().is_empty()
    }
}

impl<T: Validate> Validate for Option<T> {
    fn validate(&self) -> Vec<ValidationIssue> {
        self.as_ref().map(Validate::validate).unwrap_or_default()
    }
}

impl<T: Validate> Validate for Vec<T> {
    fn validate(&self) -> Vec<ValidationIssue> {
        self.iter().flat_map(Validate::validate).collect()
    }
}

/// A non-empty `Vec1` (used for FHIR `1..*` elements) validates each element.
impl<T: Validate> Validate for ::vec1::Vec1<T> {
    fn validate(&self) -> Vec<ValidationIssue> {
        self.iter().flat_map(Validate::validate).collect()
    }
}

/// FHIR `code`: non-empty, no leading/trailing whitespace, single internal
/// spaces (regex `[^\s]+(\s[^\s]+)*`).
fn is_valid_code(s: &str) -> bool {
    !s.is_empty()
        && s == s.trim()
        && !s.split(' ').any(str::is_empty)
        && !s.chars().any(|c| c != ' ' && c.is_whitespace())
}

/// FHIR `id`: 1..=64 chars from `[A-Za-z0-9-.]`.
fn is_valid_id(s: &str) -> bool {
    (1..=64).contains(&s.len())
        && s.chars()
            .all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '.')
}

impl Validate for types::Code {
    fn validate(&self) -> Vec<ValidationIssue> {
        if is_valid_code(&self.0) {
            vec![]
        } else {
            vec![ValidationIssue::new("code", format!("invalid FHIR code: {:?}", self.0))]
        }
    }
}

impl Validate for types::Id {
    fn validate(&self) -> Vec<ValidationIssue> {
        if is_valid_id(&self.0) {
            vec![]
        } else {
            vec![ValidationIssue::new("id", format!("invalid FHIR id: {:?}", self.0))]
        }
    }
}

impl Validate for types::Oid {
    fn validate(&self) -> Vec<ValidationIssue> {
        if self.0.starts_with("urn:oid:") {
            vec![]
        } else {
            vec![ValidationIssue::new("oid", "FHIR oid must start with `urn:oid:`")]
        }
    }
}

impl Validate for types::Uuid {
    fn validate(&self) -> Vec<ValidationIssue> {
        if self.0.starts_with("urn:uuid:") {
            vec![]
        } else {
            vec![ValidationIssue::new("uuid", "FHIR uuid must start with `urn:uuid:`")]
        }
    }
}

impl Validate for types::Uri {
    fn validate(&self) -> Vec<ValidationIssue> {
        if self.0.trim() == self.0 && !self.0.is_empty() {
            vec![]
        } else {
            vec![ValidationIssue::new("uri", "FHIR uri must be non-empty and not surrounded by whitespace")]
        }
    }
}

impl<T: Validate> Validate for Box<T> {
    fn validate(&self) -> Vec<ValidationIssue> {
        (**self).validate()
    }
}

/// A zero-sized type marker (e.g. the phantom on `Reference<T>`) has nothing to
/// validate.
impl<T: ?Sized> Validate for ::std::marker::PhantomData<T> {
    fn validate(&self) -> Vec<ValidationIssue> {
        Vec::new()
    }
}

/// Arbitrary embedded JSON (e.g. a `contained` resource) is not structurally
/// validated here.
impl Validate for ::serde_json::Value {
    fn validate(&self) -> Vec<ValidationIssue> {
        Vec::new()
    }
}

/// A bare `String` (used by a few fields) carries no FHIR-level constraint here.
impl Validate for ::std::string::String {
    fn validate(&self) -> Vec<ValidationIssue> {
        Vec::new()
    }
}

impl Validate for types::Canonical {
    fn validate(&self) -> Vec<ValidationIssue> {
        if !self.0.is_empty() && self.0.trim() == self.0 {
            vec![]
        } else {
            vec![ValidationIssue::new("canonical", "must be non-empty and not surrounded by whitespace")]
        }
    }
}

impl Validate for types::Url {
    fn validate(&self) -> Vec<ValidationIssue> {
        if !self.0.is_empty() && self.0.trim() == self.0 {
            vec![]
        } else {
            vec![ValidationIssue::new("url", "must be non-empty and not surrounded by whitespace")]
        }
    }
}

/// Primitives whose Rust representation already guarantees validity, so there
/// is no further structural constraint to check here.
macro_rules! always_valid {
    ($($t:ty),* $(,)?) => {
        $(impl Validate for $t {
            fn validate(&self) -> Vec<ValidationIssue> { Vec::new() }
        })*
    };
}

always_valid!(
    types::Base64Binary,
    types::Boolean,
    types::Date,
    types::DateTime,
    types::Decimal,
    types::Instant,
    types::Integer,
    types::Integer64,
    types::Markdown,
    types::PositiveInt,
    types::String,
    types::Time,
    types::UnsignedInt,
    types::Xhtml,
);

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn code_ok() {
        assert!(types::Code("final".to_string()).is_valid());
        assert!(types::Code("entered in error".to_string()).is_valid());
    }

    #[test]
    fn code_bad() {
        assert!(!types::Code(" leading".to_string()).is_valid());
        assert!(!types::Code("double  space".to_string()).is_valid());
        assert!(!types::Code(String::new()).is_valid());
    }

    #[test]
    fn id_ok_and_bad() {
        assert!(types::Id("abc-123.4".to_string()).is_valid());
        assert!(!types::Id("bad id!".to_string()).is_valid());
        assert!(!types::Id("x".repeat(65)).is_valid());
    }

    #[test]
    fn option_and_vec() {
        let good: Option<types::Code> = Some(types::Code("ok".to_string()));
        assert!(good.validate().is_empty());
        let bad = vec![types::Id("ok".to_string()), types::Id("no!".to_string())];
        assert_eq!(bad.validate().len(), 1);
    }

    // T13: a required binding rejects a code outside the value set.
    #[test]
    fn required_binding_flags_unknown_code() {
        use crate::r5::codes::AdministrativeGender;
        use crate::r5::coded::Coded;
        use crate::r5::resources::Patient;

        let mut patient = Patient {
            gender: Some(Coded::Known(AdministrativeGender::Male)),
            ..Default::default()
        };
        assert!(patient.validate().is_empty());

        patient.gender = Some(Coded::Unknown("robot".to_string()));
        let issues = patient.validate();
        assert_eq!(issues.len(), 1);
        assert_eq!(issues[0].path, "gender.code");
    }

    // T14: ext-1 — an Extension must have a value XOR nested extensions.
    #[test]
    fn invariant_ext_1() {
        use crate::r5::choice::Primitive;
        use crate::r5::types::extension::{Extension, ExtensionValue};
        use crate::r5::types::{Boolean, String as FhirString};

        let url = || FhirString("http://example.org/x".to_string());

        // Neither value nor extension -> violates ext-1.
        let neither = Extension { url: url(), ..Default::default() };
        assert!(neither.validate().iter().any(|i| i.message.contains("ext-1")));

        // Exactly a value -> ok.
        let value_only = Extension {
            url: url(),
            value: Some(ExtensionValue::Boolean(Primitive::new(Boolean(true)))),
            ..Default::default()
        };
        assert!(!value_only.validate().iter().any(|i| i.message.contains("ext-1")));

        // Both value and a nested extension -> violates ext-1.
        let both = Extension {
            url: url(),
            value: Some(ExtensionValue::Boolean(Primitive::new(Boolean(true)))),
            extension: vec![value_only.clone()],
            ..Default::default()
        };
        assert!(both.validate().iter().any(|i| i.message.contains("ext-1")));
    }

    // T14: dom-2 — a contained resource must not itself contain resources.
    #[test]
    fn invariant_dom_2() {
        use crate::r5::resources::Patient;

        let patient = Patient {
            contained: vec![serde_json::json!({
                "resourceType": "Observation",
                "id": "o1",
                "contained": [{ "resourceType": "Patient", "id": "nested" }]
            })],
            ..Default::default()
        };
        assert!(patient.validate().iter().any(|i| i.message.contains("dom-2")));
    }

    // T13: 1..* cardinality is now enforced at the type level — a `1..*` field is
    // a non-empty `Vec1<T>`, so an empty required list is unrepresentable.
    #[test]
    fn one_or_more_is_a_non_empty_vec1() {
        use crate::r5::resources::appointment::AppointmentParticipant;
        let empty: Vec<AppointmentParticipant> = Vec::new();
        assert!(::vec1::Vec1::try_from_vec(empty).is_err());
        assert!(::vec1::Vec1::try_from_vec(vec![AppointmentParticipant::default()]).is_ok());
    }

    #[test]
    fn derived_validate_recurses_with_dotted_path() {
        // The `#[derive(Validate)]` on Coding recurses into its `code` field,
        // whose primitive validator flags the double space.
        let coding = types::Coding {
            code: Some(types::Code("bad  code".to_string())),
            ..Default::default()
        };
        let issues = coding.validate();
        assert_eq!(issues.len(), 1, "{issues:?}");
        assert_eq!(issues[0].path, "code.code");

        // A well-formed Coding validates clean.
        let ok = types::Coding {
            code: Some(types::Code("final".to_string())),
            ..Default::default()
        };
        assert!(ok.validate().is_empty());
    }
}