1use serde_json::Value;
10
11use critpath_core::Millis;
12
13use crate::error::ParseError;
14
15#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
22#[non_exhaustive]
23pub enum TimingTarget {
24 Library,
26 BuildScriptCompile,
28 BuildScriptRun,
30 Named {
32 name: String,
34 kind: String,
36 },
37 Other(String),
39}
40
41impl TimingTarget {
42 #[must_use]
44 pub fn label(&self) -> &str {
45 match self {
46 Self::Library => "lib",
47 Self::BuildScriptCompile => "build-script",
48 Self::BuildScriptRun => "build-script (run)",
49 Self::Named { name, .. } => name,
50 Self::Other(text) => text,
51 }
52 }
53}
54
55#[derive(Clone, Debug, PartialEq, Eq)]
57#[non_exhaustive]
58pub struct TimingUnit {
59 pub index: usize,
63 pub position: usize,
65 pub package: String,
67 pub version: String,
69 pub target: TimingTarget,
71 pub features: Vec<String>,
74 pub start: Millis,
76 pub duration: Millis,
78 pub metadata_at: Option<Millis>,
81 pub unblocked: Vec<usize>,
85 pub unblocked_rmeta: Vec<usize>,
87}
88
89#[derive(Clone, Debug, PartialEq, Eq)]
91#[non_exhaustive]
92pub struct TimingReport {
93 pub units: Vec<TimingUnit>,
95 pub fresh_units: usize,
97 pub dirty_units: usize,
99 pub total_units: usize,
101 pub jobs: Option<u32>,
103 pub cpus: Option<u32>,
105 pub max_concurrency: Option<u32>,
108 pub profile: Option<String>,
110 pub rustc_version: Option<String>,
112 pub host: Option<String>,
114 pub target: Option<String>,
116 pub reported_total: Option<Millis>,
118 pub targets: Option<String>,
120 pub build_start: Option<String>,
122}
123
124impl TimingReport {
125 #[must_use]
131 pub fn compilation_span(&self) -> Millis {
132 let first = self.units.iter().map(|u| u.start).min();
133 let last = self
134 .units
135 .iter()
136 .map(|u| u.start.saturating_add(u.duration))
137 .max();
138 match (first, last) {
139 (Some(first), Some(last)) => last.saturating_sub(first),
140 _ => Millis::ZERO,
141 }
142 }
143
144 #[must_use]
150 pub fn excluded_prefix(&self) -> Millis {
151 match self.reported_total {
152 Some(total) => total.saturating_sub(self.compilation_span()),
153 None => Millis::ZERO,
154 }
155 }
156}
157
158pub fn parse(text: &str) -> Result<TimingReport, ParseError> {
166 crate::error::reject_wide_text(text, "timing report")?;
167 let raw = array_literal(text, "UNIT_DATA")?.ok_or(ParseError::NoUnitData)?;
170
171 let summary = summary_table(text)?;
172 let fresh_units = summary.number("Fresh units")?;
173 let dirty_units = summary.number("Dirty units")?;
174 let total_units = summary
175 .number("Total units")
176 .unwrap_or_else(|_| fresh_units.saturating_add(dirty_units));
177 if fresh_units > 0 {
178 return Err(ParseError::FreshUnits {
179 fresh: fresh_units,
180 total: total_units,
181 });
182 }
183
184 let value: Value = serde_json::from_str(&raw).map_err(|e| ParseError::MalformedArray {
185 name: "UNIT_DATA".to_owned(),
186 detail: e.to_string(),
187 })?;
188 let entries = value.as_array().ok_or_else(|| ParseError::MalformedArray {
189 name: "UNIT_DATA".to_owned(),
190 detail: "the literal is not an array".to_owned(),
191 })?;
192
193 let mut units = Vec::with_capacity(entries.len());
194 for (position, entry) in entries.iter().enumerate() {
195 units.push(unit(entry, position)?);
196 }
197
198 let (max_concurrency, jobs, cpus) = concurrency_row(&summary);
199 let (rustc_version, host, target) = compiler_row(&summary);
200
201 Ok(TimingReport {
202 units,
203 fresh_units,
204 dirty_units,
205 total_units,
206 jobs,
207 cpus,
208 max_concurrency,
209 profile: summary.text("Profile"),
210 rustc_version,
211 host,
212 target,
213 reported_total: summary.text("Total time").and_then(|v| seconds_prefix(&v)),
214 targets: summary.text("Targets"),
215 build_start: summary.text("Build start"),
216 })
217}
218
219fn unit(entry: &Value, position: usize) -> Result<TimingUnit, ParseError> {
220 let bad = |field: &'static str, expected: &'static str| ParseError::BadUnitField {
221 entry: position,
222 field,
223 expected,
224 };
225
226 let index = entry
227 .get("i")
228 .and_then(Value::as_u64)
229 .ok_or_else(|| bad("i", "a unit index"))? as usize;
230 let package = entry
231 .get("name")
232 .and_then(Value::as_str)
233 .ok_or_else(|| bad("name", "a package name"))?
234 .to_owned();
235 let version = entry
236 .get("version")
237 .and_then(Value::as_str)
238 .unwrap_or_default()
239 .to_owned();
240 let display = entry
241 .get("target")
242 .and_then(Value::as_str)
243 .ok_or_else(|| bad("target", "a target display string"))?;
244 let start_seconds = entry
245 .get("start")
246 .and_then(Value::as_f64)
247 .ok_or_else(|| bad("start", "a number of seconds"))?;
248 let duration_seconds = entry
249 .get("duration")
250 .and_then(Value::as_f64)
251 .ok_or_else(|| bad("duration", "a number of seconds"))?;
252
253 let start = millis_from_seconds(start_seconds, position)?;
254 let duration = millis_from_seconds(duration_seconds, position)?;
255
256 let mut features: Vec<String> = entry
257 .get("features")
258 .and_then(Value::as_array)
259 .map(|items| {
260 items
261 .iter()
262 .filter_map(Value::as_str)
263 .map(str::to_owned)
264 .collect()
265 })
266 .unwrap_or_default();
267 features.sort();
268 features.dedup();
269
270 let frontend_end = entry
273 .get("sections")
274 .and_then(Value::as_array)
275 .and_then(|sections| {
276 sections.iter().find_map(|section| {
277 let pair = section.as_array()?;
278 if pair.first().and_then(Value::as_str)? != "frontend" {
279 return None;
280 }
281 pair.get(1)?.get("end")?.as_f64()
282 })
283 });
284 let metadata_at = match frontend_end {
285 Some(seconds) => Some(millis_from_seconds(seconds, position)?.max(Millis::ZERO)),
286 None => None,
287 };
288 let metadata_at = metadata_at.map(|at| if at > duration { duration } else { at });
292
293 Ok(TimingUnit {
294 index,
295 position,
296 package,
297 version,
298 target: target_of(display),
299 features,
300 start,
301 duration,
302 metadata_at,
303 unblocked: indices(entry.get("unblocked_units")),
304 unblocked_rmeta: indices(entry.get("unblocked_rmeta_units")),
305 })
306}
307
308fn indices(value: Option<&Value>) -> Vec<usize> {
309 value
310 .and_then(Value::as_array)
311 .map(|items| {
312 items
313 .iter()
314 .filter_map(Value::as_u64)
315 .map(|i| i as usize)
316 .collect()
317 })
318 .unwrap_or_default()
319}
320
321fn millis_from_seconds(seconds: f64, entry: usize) -> Result<Millis, ParseError> {
328 const LIMIT: f64 = 1e15;
329 if !seconds.is_finite() || !(0.0..=LIMIT).contains(&seconds) {
330 return Err(ParseError::DurationOutOfRange { entry, seconds });
331 }
332 Ok(Millis::new((seconds * 1000.0).round() as u64))
333}
334
335fn target_of(display: &str) -> TimingTarget {
336 match display {
338 "" => return TimingTarget::Library,
339 " build-script" => return TimingTarget::BuildScriptCompile,
340 " build-script (run)" => return TimingTarget::BuildScriptRun,
341 _ => {}
342 }
343 let trimmed = display.trim();
345 if let Some((name, rest)) = trimmed.split_once(' ') {
346 let kind = rest.trim().trim_matches('"');
347 if !name.is_empty() && !kind.is_empty() && !kind.contains(char::is_whitespace) {
348 return TimingTarget::Named {
349 name: name.to_owned(),
350 kind: kind.to_owned(),
351 };
352 }
353 }
354 TimingTarget::Other(trimmed.to_owned())
355}
356
357fn concurrency_row(summary: &Summary) -> (Option<u32>, Option<u32>, Option<u32>) {
359 let Some(value) = summary.text("Max concurrency") else {
360 return (None, None, None);
361 };
362 let peak = value.split_whitespace().next().and_then(|n| n.parse().ok());
363 let field = |name: &str| {
364 value
365 .split(|c: char| c.is_whitespace() || c == '(' || c == ')')
366 .find_map(|part| part.strip_prefix(name)?.parse().ok())
367 };
368 (peak, field("jobs="), field("ncpu="))
369}
370
371fn compiler_row(summary: &Summary) -> (Option<String>, Option<String>, Option<String>) {
373 let Some(raw) = summary.raw("rustc") else {
374 return (None, None, None);
375 };
376 let mut version = None;
377 let mut host = None;
378 let mut target = None;
379 for part in raw.split("<br>") {
380 let text = strip_tags(part);
381 if let Some(rest) = text.strip_prefix("Host:") {
382 host = Some(rest.trim().to_owned());
383 } else if let Some(rest) = text.strip_prefix("Target:") {
384 target = Some(rest.trim().to_owned());
385 } else if !text.is_empty() && version.is_none() {
386 version = Some(text);
387 }
388 }
389 (version, host, target)
390}
391
392fn seconds_prefix(value: &str) -> Option<Millis> {
394 let digits: String = value
395 .chars()
396 .take_while(|c| c.is_ascii_digit() || *c == '.')
397 .collect();
398 let seconds: f64 = digits.parse().ok()?;
399 millis_from_seconds(seconds, 0).ok()
400}
401
402struct Summary {
404 rows: Vec<(String, String)>,
405}
406
407impl Summary {
408 fn raw(&self, label: &str) -> Option<&str> {
409 self.rows
410 .iter()
411 .find(|(name, _)| name == label)
412 .map(|(_, value)| value.as_str())
413 }
414
415 fn text(&self, label: &str) -> Option<String> {
416 self.raw(label).map(strip_tags)
417 }
418
419 fn number(&self, label: &'static str) -> Result<usize, ParseError> {
420 let value = self
421 .text(label)
422 .ok_or(ParseError::MissingSummaryRow { row: label })?;
423 value.trim().parse().map_err(|_| ParseError::BadSummaryRow {
424 row: label,
425 value,
426 expected: "a count",
427 })
428 }
429}
430
431fn summary_table(text: &str) -> Result<Summary, ParseError> {
432 let start = text.find("<table").ok_or(ParseError::NoSummaryTable)?;
433 let rest = text.get(start..).ok_or(ParseError::NoSummaryTable)?;
434 let end = rest.find("</table>").ok_or(ParseError::NoSummaryTable)?;
435 let table = rest.get(..end).ok_or(ParseError::NoSummaryTable)?;
436
437 let mut cells = Vec::new();
441 let mut remaining = table;
442 while let Some(open) = remaining.find("<td>") {
443 let after = match remaining.get(open.saturating_add(4)..) {
444 Some(after) => after,
445 None => break,
446 };
447 let Some(close) = after.find("</td>") else {
448 break;
449 };
450 if let Some(cell) = after.get(..close) {
451 cells.push(cell);
452 }
453 remaining = match after.get(close.saturating_add(5)..) {
454 Some(rest) => rest,
455 None => break,
456 };
457 }
458
459 let mut rows = Vec::new();
460 let mut pairs = cells.chunks_exact(2);
461 for pair in &mut pairs {
462 let (Some(label), Some(value)) = (pair.first(), pair.get(1)) else {
463 continue;
464 };
465 let label = strip_tags(label);
466 let label = label.trim().trim_end_matches(':').to_owned();
467 rows.push((label, (*value).to_owned()));
468 }
469 if rows.is_empty() {
470 return Err(ParseError::NoSummaryTable);
471 }
472 Ok(Summary { rows })
473}
474
475fn strip_tags(html: &str) -> String {
477 let mut out = String::with_capacity(html.len());
478 let mut depth = 0usize;
479 for c in html.chars() {
480 match c {
481 '<' => depth = depth.saturating_add(1),
482 '>' => depth = depth.saturating_sub(1),
483 _ if depth == 0 => out.push(c),
484 _ => {}
485 }
486 }
487 decode_entities(out.trim())
488}
489
490fn decode_entities(text: &str) -> String {
491 if !text.contains('&') {
492 return text.to_owned();
493 }
494 let mut out = String::with_capacity(text.len());
495 let mut rest = text;
496 while let Some(at) = rest.find('&') {
497 if let Some(head) = rest.get(..at) {
498 out.push_str(head);
499 }
500 let tail = rest.get(at..).unwrap_or("");
501 let replacement = [
502 ("&", "&"),
503 ("<", "<"),
504 (">", ">"),
505 (""", "\""),
506 ("'", "'"),
507 ]
508 .into_iter()
509 .find(|(entity, _)| tail.starts_with(entity));
510 match replacement {
511 Some((entity, decoded)) => {
512 out.push_str(decoded);
513 rest = tail.get(entity.len()..).unwrap_or("");
514 }
515 None => {
516 out.push('&');
517 rest = tail.get(1..).unwrap_or("");
518 }
519 }
520 }
521 out.push_str(rest);
522 out
523}
524
525fn array_literal(text: &str, name: &str) -> Result<Option<String>, ParseError> {
528 let needle = format!("const {name} = ");
529 let Some(at) = text.find(&needle) else {
530 return Ok(None);
531 };
532 let rest = text
533 .get(at.saturating_add(needle.len())..)
534 .unwrap_or_default();
535 let mut depth = 0usize;
536 let mut in_string = false;
537 let mut escaped = false;
538 for (offset, c) in rest.char_indices() {
539 if in_string {
540 if escaped {
541 escaped = false;
542 } else if c == '\\' {
543 escaped = true;
544 } else if c == '"' {
545 in_string = false;
546 }
547 continue;
548 }
549 match c {
550 '"' => in_string = true,
551 '[' | '{' => depth = depth.saturating_add(1),
552 ']' | '}' => {
553 depth = depth.saturating_sub(1);
554 if depth == 0 {
555 let end = offset.saturating_add(c.len_utf8());
556 return Ok(rest.get(..end).map(str::to_owned));
557 }
558 }
559 _ => {}
560 }
561 }
562 Err(ParseError::TruncatedArray {
563 name: name.to_owned(),
564 })
565}