1use std::time::{Duration, SystemTime, UNIX_EPOCH};
15
16use serde::Serialize;
17
18use crate::control::Phase;
19
20pub const REPORT_SCHEMA_VERSION: &str = "1.1.0";
22
23#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
25pub struct Tool {
26 pub name: &'static str,
28 pub version: &'static str,
30 pub target: String,
32}
33
34#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
36pub struct Threads {
37 pub count: usize,
39 pub started: Option<usize>,
42 pub source: &'static str,
46}
47
48#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
50pub struct Platform {
51 pub os: &'static str,
53 pub arch: &'static str,
55 pub logical_cpus: usize,
57}
58
59impl Platform {
60 #[must_use]
62 pub fn current() -> Self {
63 Self {
64 os: std::env::consts::OS,
65 arch: std::env::consts::ARCH,
66 logical_cpus: std::thread::available_parallelism()
67 .map_or(1, std::num::NonZeroUsize::get),
68 }
69 }
70}
71
72#[derive(Clone, Debug, PartialEq, Serialize)]
74pub struct Resources {
75 pub wall_seconds: f64,
77 pub cpu_user_seconds: Option<f64>,
80 pub cpu_system_seconds: Option<f64>,
82 pub peak_rss_bytes: Option<u64>,
84 pub waited_for_input_seconds: Option<f64>,
87}
88
89#[derive(Clone, Debug, PartialEq, Serialize)]
91pub struct PhaseTime {
92 pub name: &'static str,
94 pub wall_seconds: f64,
96}
97
98impl PhaseTime {
99 #[must_use]
101 pub fn new(phase: Phase, time: Duration) -> Self {
102 Self {
103 name: phase.as_str(),
104 wall_seconds: time.as_secs_f64(),
105 }
106 }
107}
108
109#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
111pub struct Work {
112 pub records: u64,
114 pub positions: Option<u64>,
116}
117
118#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
120pub struct FileRecord {
121 pub role: &'static str,
124 pub name: String,
126 pub size_bytes: u64,
128 pub sha256: String,
130}
131
132#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]
134#[serde(rename_all = "snake_case")]
135pub enum Status {
136 Completed,
138 Failed,
140 Cancelled,
142}
143
144#[derive(Clone, Debug, PartialEq, Serialize)]
146pub struct RunReport {
147 pub schema_version: &'static str,
149 pub tool: Tool,
151 pub command: Vec<String>,
153 pub status: Status,
155 pub exit_code: u8,
157 pub error: Option<String>,
159 pub start_time: String,
161 pub end_time: String,
163 pub threads: Option<Threads>,
165 pub platform: Platform,
167 pub resources: Resources,
169 pub phases: Vec<PhaseTime>,
171 pub work: Work,
173 pub inputs: Vec<FileRecord>,
175 pub outputs: Vec<FileRecord>,
177}
178
179#[must_use]
181pub fn rfc3339(t: SystemTime) -> String {
182 let d = t.duration_since(UNIX_EPOCH).unwrap_or(Duration::ZERO);
183 let secs = d.as_secs();
184 let (days, rem) = (secs / 86_400, secs % 86_400);
185 let (y, m, day) = civil_from_days(i64::try_from(days).unwrap_or(0));
186 format!(
187 "{y:04}-{m:02}-{day:02}T{:02}:{:02}:{:02}.{:03}+00:00",
188 rem / 3600,
189 (rem / 60) % 60,
190 rem % 60,
191 d.subsec_millis()
192 )
193}
194
195fn civil_from_days(z: i64) -> (i64, u32, u32) {
197 let z = z + 719_468;
198 let era = z.div_euclid(146_097);
199 let doe = z.rem_euclid(146_097);
200 let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365;
201 let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
202 let mp = (5 * doy + 2) / 153;
203 let d = doy - (153 * mp + 2) / 5 + 1;
204 let m = if mp < 10 { mp + 3 } else { mp - 9 };
205 let y = yoe + era * 400 + i64::from(m <= 2);
206 #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
207 (y, m as u32, d as u32)
208}
209
210#[must_use]
213pub fn file_name(p: &std::path::Path) -> String {
214 if p.as_os_str() == "-" || crate::input::is_descriptor_alias(p) {
215 return "-".to_owned();
216 }
217 p.file_name()
218 .map_or_else(|| "-".to_owned(), |n| n.to_string_lossy().into_owned())
219}
220
221#[must_use]
225pub fn error_text(error: &crate::DimaError, known: &[&std::path::Path]) -> String {
226 let message = error.to_string();
227 let mut text = message.lines().next().unwrap_or_default().to_owned();
228 let mut cause = std::error::Error::source(error);
229 while let Some(c) = cause {
230 text.push_str("\ncaused by: ");
231 text.push_str(&c.to_string());
232 cause = c.source();
233 }
234 if let Some(h) = error.hint() {
235 text.push_str("\nhint: ");
236 text.push_str(h);
237 }
238 redact_paths(&text, known)
239}
240
241#[must_use]
245pub fn redact_paths(message: &str, known: &[&std::path::Path]) -> String {
246 let mut known: Vec<String> = known
247 .iter()
248 .map(|p| p.display().to_string())
249 .filter(|p| !p.is_empty() && p != "-")
250 .collect();
251 known.sort_by_key(|p| std::cmp::Reverse(p.len()));
252 let mut out = message.to_owned();
253 for p in &known {
254 out = out.replace(p.as_str(), last_component(p));
255 }
256 redact_bare(&redact_quoted(&out))
257}
258
259const SEPARATORS: [char; 2] = ['/', '\\'];
260
261fn last_component(p: &str) -> &str {
263 p.rsplit(SEPARATORS).find(|c| !c.is_empty()).unwrap_or(p)
264}
265
266fn redact_quoted(s: &str) -> String {
268 let mut result = String::with_capacity(s.len());
269 let mut rest = s;
270 while let Some(i) = rest.find(['\'', '"']) {
271 let quote = &rest[i..=i];
272 result.push_str(&rest[..=i]);
273 let after = &rest[i + 1..];
274 let Some(end) = after.find(quote) else {
275 rest = after;
276 continue;
277 };
278 let content = &after[..end];
279 result.push_str(if content.contains(SEPARATORS) {
280 last_component(content)
281 } else {
282 content
283 });
284 result.push_str(quote);
285 rest = &after[end + 1..];
286 }
287 result.push_str(rest);
288 result
289}
290
291fn is_absolute(t: &str) -> bool {
293 let b = t.as_bytes();
294 t.starts_with(SEPARATORS)
295 || t.starts_with("~/")
296 || (b.len() > 2
297 && b[0].is_ascii_alphabetic()
298 && b[1] == b':'
299 && (b[2] == b'/' || b[2] == b'\\'))
300}
301
302fn redact_bare(s: &str) -> String {
304 let mut result = String::with_capacity(s.len());
305 for (i, token) in s.split(' ').enumerate() {
306 if i > 0 {
307 result.push(' ');
308 }
309 let core = token.trim_start_matches(['(', '\'', '"']);
310 let core = core.trim_end_matches([',', ';', ':', ')', '.', '\'', '"']);
311 if core.len() > 1 && is_absolute(core) {
312 let start = token.len() - token.trim_start_matches(['(', '\'', '"']).len();
313 result.push_str(&token[..start]);
314 result.push_str(last_component(core));
315 result.push_str(&token[start + core.len()..]);
316 } else {
317 result.push_str(token);
318 }
319 }
320 result
321}
322
323#[cfg(test)]
324mod tests {
325 use super::*;
326
327 #[test]
328 fn error_text_keeps_no_input_data() {
329 let e = crate::DimaError::input_data(
330 Some(crate::error::Location::new("/data/run1/in.fasta")),
331 "2 headers do not have the 3 fields\n record 4 (line 7): 2 fields: patient-17|ward B",
332 )
333 .with_hint("fix the headers");
334 let text = error_text(&e, &[std::path::Path::new("/data/run1/in.fasta")]);
335 assert_eq!(
336 text,
337 "in.fasta: 2 headers do not have the 3 fields\nhint: fix the headers"
338 );
339 }
340
341 #[test]
342 fn dates() {
343 assert_eq!(rfc3339(UNIX_EPOCH), "1970-01-01T00:00:00.000+00:00");
344 let t = UNIX_EPOCH + Duration::from_millis(1_791_000_000_123);
345 assert_eq!(rfc3339(t), "2026-10-03T04:00:00.123+00:00");
346 let t = UNIX_EPOCH + Duration::from_secs(951_782_400);
348 assert_eq!(rfc3339(t), "2000-02-29T00:00:00.000+00:00");
349 assert_eq!(file_name(std::path::Path::new("/a/b/c.fa")), "c.fa");
350 assert_eq!(file_name(std::path::Path::new("-")), "-");
351 }
352
353 #[test]
354 fn paths_are_redacted() {
355 let known = [std::path::Path::new("data dir/in.fasta")];
356 assert_eq!(
357 redact_paths(
358 "cannot open 'data dir/in.fasta'\ncaused by: No such file",
359 &known
360 ),
361 "cannot open 'in.fasta'\ncaused by: No such file"
362 );
363 assert_eq!(
364 redact_paths("failed at path \"/home/me/out/.tmpA1\" (x)", &[]),
365 "failed at path \".tmpA1\" (x)"
366 );
367 assert_eq!(
368 redact_paths("see /home/me/x.json, then C:\\Users\\me\\y.tsv.", &[]),
369 "see x.json, then y.tsv."
370 );
371 let m = "entropy ~ 1/n; format 'A|B' can't match";
373 assert_eq!(redact_paths(m, &[]), m);
374 }
375}