use super::resolve::Reading;
use super::{Provenance, Unit};
use serde_json::{json, Map, Value};
pub const IRONMON_NS: &str = "https://nervosys.github.io/IronMonitor/ns#";
pub const QUDT_UNIT_NS: &str = "http://qudt.org/vocab/unit/";
pub fn qudt_unit(unit: Unit) -> Option<&'static str> {
Some(match unit {
Unit::Celsius => "DEG_C",
Unit::Percent => "PERCENT",
Unit::Bytes => "BYTE",
Unit::BytesPerSecond => "BYTE-PER-SEC",
Unit::Hertz => "HZ",
Unit::Megahertz => "MegaHZ",
Unit::MegatransfersPerSecond => "NUM-PER-SEC",
Unit::Watts => "W",
Unit::Milliwatts => "MilliW",
Unit::Volts => "V",
Unit::Rpm => "REV-PER-MIN",
Unit::Seconds => "SEC",
Unit::Hours => "HR",
Unit::Milliseconds => "MilliSEC",
Unit::Count => "NUM",
Unit::Dbm => "DeciB_M",
Unit::MegabitsPerSecond => "MegaBIT-PER-SEC",
Unit::TokensPerSecond => "NUM-PER-SEC",
Unit::Identifier | Unit::Text | Unit::Amount => return None,
})
}
pub fn context() -> Value {
json!({
"ironmon": IRONMON_NS,
"qudt": "http://qudt.org/schema/qudt/",
"unit": QUDT_UNIT_NS,
"xsd": "http://www.w3.org/2001/XMLSchema#",
"id": "@id",
"type": "@type",
"value": "ironmon:value",
"hasUnit": {
"@id": "qudt:hasUnit",
"@type": "@id"
},
"provenance": "ironmon:provenance",
"unavailableReason": "ironmon:unavailableReason",
"entityKind": "ironmon:entityKind",
"domain": "ironmon:domain",
"observedAt": {
"@id": "ironmon:observedAt",
"@type": "xsd:dateTime"
}
})
}
fn node(reading: &Reading, ontology: &super::Ontology) -> Value {
let mut map = Map::new();
map.insert("id".into(), json!(format!("{IRONMON_NS}{}", reading.id)));
let entity = ontology.template_for(&reading.id);
let kind = entity
.map(|e| match e.kind {
super::EntityKind::Measurement => "ironmon:Measurement",
super::EntityKind::Identity => "ironmon:Identity",
super::EntityKind::Setting => "ironmon:Setting",
super::EntityKind::Limit => "ironmon:Limit",
super::EntityKind::Diagnostic => "ironmon:Diagnostic",
})
.unwrap_or("ironmon:Reading");
map.insert("type".into(), json!(kind));
if let Some(e) = entity {
map.insert("domain".into(), json!(e.domain.as_str()));
map.insert("entityKind".into(), json!(e.kind.as_str()));
}
map.insert("provenance".into(), json!(reading.provenance.as_str()));
match (&reading.value, reading.provenance) {
(_, Provenance::Unavailable) | (None, _) => {
map.insert(
"unavailableReason".into(),
json!(reading
.note
.clone()
.unwrap_or_else(|| "no reason recorded".to_string())),
);
}
(Some(v), _) => {
map.insert("value".into(), v.clone());
if let Some(u) = reading.unit.and_then(qudt_unit) {
map.insert("hasUnit".into(), json!(format!("unit:{u}")));
} else if let Some(u) = reading.unit {
map.insert("hasUnit".into(), json!(format!("ironmon:{}", u.as_str())));
}
}
}
Value::Object(map)
}
pub fn document(readings: &[Reading], observed_at: &str) -> Value {
let ontology = super::Ontology::build();
let graph: Vec<Value> = readings.iter().map(|r| node(r, &ontology)).collect();
json!({
"@context": context(),
"id": format!("{IRONMON_NS}snapshot"),
"type": "ironmon:Snapshot",
"observedAt": observed_at,
"ironmon:readingCount": graph.len(),
"@graph": graph,
})
}
#[cfg(test)]
mod tests {
use super::*;
use crate::ontology::Unit;
fn measured(id: &str, value: Value, unit: Option<Unit>) -> Reading {
Reading {
id: id.to_string(),
value: Some(value),
provenance: Provenance::Measured,
unit,
note: None,
}
}
fn unavailable(id: &str, reason: &str) -> Reading {
Reading {
id: id.to_string(),
value: None,
provenance: Provenance::Unavailable,
unit: Some(Unit::Percent),
note: Some(reason.to_string()),
}
}
#[test]
fn the_context_defines_every_term_the_nodes_use() {
let ctx = context();
for term in [
"value",
"hasUnit",
"provenance",
"unavailableReason",
"entityKind",
"domain",
"observedAt",
] {
assert!(
ctx.get(term).is_some(),
"nodes emit {term:?} and the context does not define it, so a \
consumer following the document cannot resolve it"
);
}
}
#[test]
fn every_prefixed_name_the_graph_emits_has_a_defined_prefix() {
let doc = document(
&[
measured("cpu.total.utilization", json!(1), Some(Unit::Percent)),
measured("cpu.model", json!("x"), Some(Unit::Text)),
],
"2026-01-01T00:00:00Z",
);
let ctx = doc["@context"].as_object().expect("context is an object");
let mut checked = 0;
for n in doc["@graph"].as_array().unwrap() {
for key in ["hasUnit", "type"] {
let Some(v) = n.get(key).and_then(|v| v.as_str()) else {
continue;
};
let Some((prefix, _)) = v.split_once(':') else {
continue;
};
if v.starts_with("http") {
continue;
}
let defined = ctx.get(prefix).is_some();
assert!(
defined,
"the graph emits {v:?} and the context defines no {prefix:?} prefix, so a consumer cannot resolve it"
);
checked += 1;
}
}
assert!(
checked > 0,
"no prefixed names were examined, so this test proved nothing"
);
}
#[test]
fn an_unavailable_reading_has_no_value_and_carries_its_reason() {
let doc = document(
&[unavailable("cpu.total.utilization", "the reader failed")],
"2026-01-01T00:00:00Z",
);
let n = &doc["@graph"][0];
assert!(
n.get("value").is_none(),
"an unavailable reading must not carry a value, not even null: a \
consumer that finds one will use it"
);
assert_eq!(n["unavailableReason"], json!("the reader failed"));
assert_eq!(n["provenance"], json!("unavailable"));
}
#[test]
fn a_measured_reading_carries_its_value_and_a_qudt_unit() {
let doc = document(
&[measured(
"cpu.total.utilization",
json!(42.5),
Some(Unit::Percent),
)],
"2026-01-01T00:00:00Z",
);
let n = &doc["@graph"][0];
assert_eq!(n["value"], json!(42.5));
assert_eq!(n["hasUnit"], json!("unit:PERCENT"));
assert!(n["id"].as_str().unwrap().starts_with(IRONMON_NS));
}
#[test]
fn non_quantities_are_not_given_a_qudt_unit() {
assert_eq!(qudt_unit(Unit::Identifier), None);
assert_eq!(qudt_unit(Unit::Text), None);
let doc = document(
&[measured("cpu.model", json!("Ryzen"), Some(Unit::Text))],
"2026-01-01T00:00:00Z",
);
let unit = doc["@graph"][0]["hasUnit"].as_str().unwrap();
assert!(
unit.starts_with("ironmon:"),
"a text field must not be typed as a physical quantity — something \
downstream will do arithmetic on it. got {unit}"
);
}
#[test]
fn every_quantity_unit_has_a_qudt_term() {
for unit in [
Unit::Celsius,
Unit::Percent,
Unit::Bytes,
Unit::BytesPerSecond,
Unit::Hertz,
Unit::Megahertz,
Unit::Watts,
Unit::Milliwatts,
Unit::Volts,
Unit::Rpm,
Unit::Seconds,
Unit::Hours,
Unit::Milliseconds,
Unit::Count,
] {
assert!(
qudt_unit(unit).is_some(),
"{:?} is a quantity and has no QUDT term; a consumer cannot \
convert or compare it",
unit
);
}
}
#[test]
fn the_document_is_a_function_of_its_inputs() {
let readings = [measured(
"cpu.total.utilization",
json!(1),
Some(Unit::Percent),
)];
let a = document(&readings, "2026-01-01T00:00:00Z");
let b = document(&readings, "2026-01-01T00:00:00Z");
assert_eq!(
a, b,
"the same readings and stamp must give the same document"
);
}
#[test]
fn a_declared_entity_carries_its_domain_and_kind() {
let doc = document(
&[measured(
"cpu.total.utilization",
json!(10),
Some(Unit::Percent),
)],
"2026-01-01T00:00:00Z",
);
let n = &doc["@graph"][0];
assert_eq!(n["domain"], json!("cpu"));
assert!(n["type"].as_str().unwrap().starts_with("ironmon:"));
}
}