Skip to main content

wellfare_core/
shapes.rs

1use crate::rdf::generate_rdf_prefixes;
2/// SHACL-equivalent validation constraints expressed as SPARQL ASK queries.
3/// Each shape returns true = violation found (use RDFS/SHACL semantics,
4/// NOT OWL class membership — people are described by constraints, not ontological types).
5use crate::store::HealthStore;
6
7pub struct ShapeViolation {
8    pub shape_id: &'static str,
9    pub message: &'static str,
10}
11
12const SHAPES: &[(&str, &str, &str)] = &[
13    (
14        "sleep:efficiency-range",
15        "Sleep efficiency must be between 0 and 100 percent",
16        "ASK { ?obs <https://health.example.org/ns#sleepEfficiency> ?e \
17               FILTER(?e < 0 || ?e > 100) }",
18    ),
19    (
20        "sleep:duration-positive",
21        "Sleep duration must be greater than zero",
22        "ASK { ?obs a <http://hl7.org/fhir/Observation> ; \
23                    <http://hl7.org/fhir/Observation.valueQuantity> ?d \
24               FILTER(?d <= 0) }",
25    ),
26    (
27        "heart-rate:physiological-range",
28        "Resting heart rate must be between 20 and 300 BPM",
29        "ASK { ?obs <http://hl7.org/fhir/Observation.valueQuantity> ?hr ; \
30                    <https://health.example.org/ns#snomedConcept> \
31                    <http://snomed.info/id/364075005> \
32               FILTER(?hr < 20 || ?hr > 300) }",
33    ),
34    (
35        "weight:positive",
36        "Body weight must be a positive value",
37        "ASK { ?obs a <http://hl7.org/fhir/Observation> ; \
38                    <http://hl7.org/fhir/Observation.valueQuantity> ?w ; \
39                    <https://health.example.org/ns#snomedConcept> \
40                    <http://snomed.info/id/27113001> \
41               FILTER(?w <= 0) }",
42    ),
43    (
44        "weight:body-fat-range",
45        "Body fat percentage must be between 0 and 100",
46        "ASK { ?obs <https://health.example.org/ns#bodyFatPercentage> ?f \
47               FILTER(?f < 0 || ?f > 100) }",
48    ),
49    (
50        "steps:non-negative",
51        "Step count must be zero or greater",
52        "ASK { ?obs <http://hl7.org/fhir/Observation.valueQuantity> ?s ; \
53                    <https://health.example.org/ns#snomedConcept> \
54                    <http://snomed.info/id/256235009> \
55               FILTER(?s < 0) }",
56    ),
57];
58
59pub struct ValidationReport {
60    pub violations: Vec<ShapeViolation>,
61    pub checked: usize,
62}
63
64impl ValidationReport {
65    ///  when valid.
66    pub fn is_valid(&self) -> bool {
67        self.violations.is_empty()
68    }
69
70    /// Converts to json.
71    pub fn to_json(&self) -> String {
72        let v: Vec<String> = self
73            .violations
74            .iter()
75            .map(|v| {
76                format!(
77                    "{{\"shape\":\"{}\",\"message\":\"{}\"}}",
78                    v.shape_id, v.message
79                )
80            })
81            .collect();
82        format!(
83            "{{\"valid\":{},\"checked\":{},\"violations\":[{}]}}",
84            self.is_valid(),
85            self.checked,
86            v.join(",")
87        )
88    }
89}
90
91/// Validate a Turtle document against all registered shapes.
92/// Individual shape errors are non-fatal (store is rebuilt per check).
93pub fn validate_turtle(turtle_data: &str) -> ValidationReport {
94    let prefixes = generate_rdf_prefixes();
95    let mut violations = Vec::new();
96
97    for (shape_id, message, ask_query) in SHAPES {
98        let mut store = match HealthStore::new() {
99            Ok(s) => s,
100            Err(_) => continue,
101        };
102        match store.check_shape(&prefixes, turtle_data, ask_query) {
103            Ok(true) => violations.push(ShapeViolation { shape_id, message }),
104            Ok(false) | Err(_) => {}
105        }
106    }
107
108    ValidationReport {
109        violations,
110        checked: SHAPES.len(),
111    }
112}
113
114#[cfg(test)]
115mod tests {
116    use super::*;
117
118    #[test]
119    fn test_valid_sleep_passes() {
120        let ttl = "<urn:health:sleep:ok> a <http://hl7.org/fhir/Observation> ; \
121                   <https://health.example.org/ns#sleepEfficiency> 78 .";
122        let report = validate_turtle(ttl);
123        assert!(
124            !report
125                .violations
126                .iter()
127                .any(|v| v.shape_id == "sleep:efficiency-range")
128        );
129    }
130
131    #[test]
132    fn test_invalid_efficiency_caught() {
133        let ttl = "<urn:health:sleep:bad> a <http://hl7.org/fhir/Observation> ; \
134                   <https://health.example.org/ns#sleepEfficiency> 150 .";
135        let report = validate_turtle(ttl);
136        assert!(
137            report
138                .violations
139                .iter()
140                .any(|v| v.shape_id == "sleep:efficiency-range")
141        );
142    }
143}