1use 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
16fn 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
35pub 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
74pub 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
85pub 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 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
147pub 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}