Skip to main content

cfd_craft/
input.rs

1//! Shared strict JSON parsing and complete case preflight for all interfaces.
2use crate::{
3    case::{Case, CheckReport, Diagnostic},
4    grid::{GeometryEvidence, Grid},
5};
6use std::fs;
7fn diagnostic(code: &str, path: &str, message: impl Into<String>) -> Diagnostic {
8    Diagnostic {
9        code: code.into(),
10        severity: "error".into(),
11        path: path.into(),
12        message: message.into(),
13    }
14}
15
16/// Splits "CFD-E040: message" into its code and message.
17fn coded(e: &str, default: &str) -> (String, String) {
18    match e.split_once(": ") {
19        Some((code, rest)) if code.starts_with("CFD-") => (code.into(), rest.into()),
20        _ => (default.into(), e.into()),
21    }
22}
23
24fn invalid_report(diagnostics: Vec<Diagnostic>) -> CheckReport {
25    CheckReport {
26        schema_version: "cfd-craft.check/0.1".into(),
27        valid: false,
28        cells: 0,
29        estimated_peak_mib: 0.0,
30        estimated_output_mib: 0.0,
31        diagnostics,
32    }
33}
34
35/// Reads a case. A parse failure becomes a CFD-E000 diagnostic with the JSON path
36/// of the offending element.
37///
38/// Unknown fields, unknown variants, duplicate fields and trailing data are
39/// all rejected. Only the types are checked here; run [`full_check`] (or
40/// [`Case::check`](crate::case::Case::check)) for the semantic checks.
41///
42/// ```
43/// use cfd_craft::input;
44///
45/// let report = input::parse_case(br#"{"schema_version": "cfd-craft.case/0.1",
46///     "name": "typo", "domain": {"size_m": [1.0, 1.0, 1.0], "origin_m": [0, 0, 0]}}"#)
47///     .unwrap_err();
48/// assert!(!report.valid);
49/// assert_eq!(report.diagnostics[0].code, "CFD-E000");
50/// assert_eq!(report.diagnostics[0].path, "domain.origin_m");
51/// ```
52pub fn parse_case(bytes: &[u8]) -> std::result::Result<Case, CheckReport> {
53    let mut de = serde_json::Deserializer::from_slice(bytes);
54    match serde_path_to_error::deserialize::<_, Case>(&mut de) {
55        Ok(c) => match de.end() {
56            Ok(()) => Ok(c),
57            Err(e) => Err(invalid_report(vec![diagnostic(
58                "CFD-E000",
59                "",
60                e.to_string(),
61            )])),
62        },
63        Err(e) => {
64            let path = e.path().to_string();
65            Err(invalid_report(vec![diagnostic(
66                "CFD-E000",
67                if path == "." { "" } else { &path },
68                e.into_inner().to_string(),
69            )]))
70        }
71    }
72}
73
74/// Available host memory in MiB, where the platform reports it.
75pub fn available_mib() -> Option<f64> {
76    let info = fs::read_to_string("/proc/meminfo").ok()?;
77    info.lines().find_map(|line| {
78        line.strip_prefix("MemAvailable:")
79            .and_then(|s| s.split_whitespace().next())
80            .and_then(|s| s.parse::<f64>().ok())
81            .map(|kib| kib / 1024.0)
82    })
83}
84
85/// Case checks plus the grid, source and receptor checks that need the built grid.
86/// Every source and receptor is checked, so all problems are reported at once. When the
87/// estimated peak does not fit this host (CFD-W070), the grid is not built and its checks
88/// are skipped, so a check never allocates what the host cannot hold.
89pub fn full_check(c: &Case) -> (CheckReport, Option<GeometryEvidence>) {
90    let mut report = c.check();
91    if let Some(mib) = available_mib()
92        && report.estimated_peak_mib > 0.8 * mib
93    {
94        report.diagnostics.push(Diagnostic {
95            code: "CFD-W070".into(),
96            severity: "warning".into(),
97            path: "run.memory_limit_mib".into(),
98            message: format!(
99                "The estimated peak of {:.0} MiB exceeds 80 % of the {mib:.0} MiB this host has available; run refuses it here. The grid, source and receptor checks were skipped.",
100                report.estimated_peak_mib
101            ),
102        });
103        return (report, None);
104    }
105    if !report.valid {
106        return (report, None);
107    }
108    let g = match Grid::build(c) {
109        Ok(g) => g,
110        Err(e) => {
111            let (code, message) = coded(&e, "CFD-E030");
112            // Shape errors start with the element path, for example "geometry[3] (box b) ...".
113            let path = message
114                .split_once(' ')
115                .map(|(p, _)| p)
116                .filter(|p| p.starts_with("geometry["))
117                .unwrap_or("geometry")
118                .to_string();
119            report.valid = false;
120            report.diagnostics.push(diagnostic(&code, &path, message));
121            return (report, None);
122        }
123    };
124    for (i, s) in c.sources.iter().enumerate() {
125        let mut one = c.clone();
126        one.sources = vec![s.clone()];
127        if let Err(e) = crate::transport::source_fields(&one, &g) {
128            let (code, message) = coded(&e, "CFD-E040");
129            report.valid = false;
130            report
131                .diagnostics
132                .push(diagnostic(&code, &format!("sources[{i}]"), message));
133        }
134    }
135    for (i, r) in c.receptors.iter().enumerate() {
136        if let Err(e) = crate::transport::receptor_weights(&g, r) {
137            let (code, message) = coded(&e, "CFD-E042");
138            report.valid = false;
139            report
140                .diagnostics
141                .push(diagnostic(&code, &format!("receptors[{i}]"), message));
142        }
143    }
144    (report, Some(g.evidence()))
145}
146
147/// `run` refuses what `check` only warns about: a peak that does not fit this host.
148pub fn refuse_host_memory(report: &mut CheckReport) {
149    if let Some(w) = report.diagnostics.iter_mut().find(|d| d.code == "CFD-W070") {
150        w.code = "CFD-E070".into();
151        w.severity = "error".into();
152        report.valid = false;
153    }
154}