cargo/ops/cargo_report/
timings.rs

1//! The `cargo report timings` command.
2
3use std::collections::HashSet;
4use std::fs::File;
5use std::io::BufReader;
6use std::path::Path;
7use std::path::PathBuf;
8
9use annotate_snippets::Level;
10use anyhow::Context as _;
11use cargo_util::paths;
12use indexmap::IndexMap;
13use indexmap::map::Entry;
14use itertools::Itertools as _;
15use tempfile::TempDir;
16
17use crate::AlreadyPrintedError;
18use crate::CargoResult;
19use crate::GlobalContext;
20use crate::core::Workspace;
21use crate::core::compiler::CompileMode;
22use crate::core::compiler::timings::CompilationSection;
23use crate::core::compiler::timings::UnitData;
24use crate::core::compiler::timings::report::RenderContext;
25use crate::core::compiler::timings::report::aggregate_sections;
26use crate::core::compiler::timings::report::compute_concurrency;
27use crate::core::compiler::timings::report::round_to_centisecond;
28use crate::core::compiler::timings::report::write_html;
29use crate::ops::cargo_report::util::list_log_files;
30use crate::util::log_message::FingerprintStatus;
31use crate::util::log_message::LogMessage;
32use crate::util::log_message::Target;
33use crate::util::logger::RunId;
34use crate::util::style;
35
36pub struct ReportTimingsOptions<'gctx> {
37    /// Whether to attempt to open the browser after the report is generated
38    pub open_result: bool,
39    pub gctx: &'gctx GlobalContext,
40}
41
42/// Collects sections data for later post-processing through [`aggregate_sections`].
43struct UnitEntry {
44    target: Target,
45    data: UnitData,
46    sections: IndexMap<String, CompilationSection>,
47    rmeta_time: Option<f64>,
48}
49
50pub fn report_timings(
51    gctx: &GlobalContext,
52    ws: Option<&Workspace<'_>>,
53    opts: ReportTimingsOptions<'_>,
54) -> CargoResult<()> {
55    let Some((log, run_id)) = list_log_files(gctx, ws)?.next() else {
56        let context = if let Some(ws) = ws {
57            format!(" for workspace at `{}`", ws.root().display())
58        } else {
59            String::new()
60        };
61        let title = format!("no sessions found{context}");
62        let note = "run command with `-Z build-analysis` to generate log files";
63        let report = [Level::ERROR
64            .primary_title(title)
65            .element(Level::NOTE.message(note))];
66        gctx.shell().print_report(&report, false)?;
67        return Err(AlreadyPrintedError::new(anyhow::anyhow!("")).into());
68    };
69
70    let ctx = prepare_context(&log, &run_id)
71        .with_context(|| format!("failed to analyze log at `{}`", log.display()))?;
72
73    // If we are in a workspace,
74    // put timing reports in <target-dir>/cargo-timings/` as usual for easy access.
75    // Otherwise in a temporary directory
76    let reports_dir = if let Some(ws) = ws {
77        let target_dir = ws.target_dir();
78        let target_dir = target_dir.as_path_unlocked();
79        paths::create_dir_all_excluded_from_backups_atomic(target_dir)?;
80        let timings_dir = target_dir.join("cargo-timings");
81        paths::create_dir_all(&timings_dir)?;
82        timings_dir
83    } else if let Ok(path) = gctx.get_env("__CARGO_TEST_REPORT_TIMINGS_TEMPDIR") {
84        PathBuf::from(path.to_owned())
85    } else {
86        TempDir::with_prefix("cargo-timings-")?.keep()
87    };
88
89    let timing_path = reports_dir.join(format!("cargo-timing-{run_id}.html"));
90
91    let mut out_file = std::fs::OpenOptions::new()
92        .write(true)
93        .create(true)
94        .truncate(true)
95        .open(&timing_path)
96        .with_context(|| format!("failed to open `{}`", timing_path.display()))?;
97
98    write_html(ctx, &mut out_file)?;
99
100    let link = gctx.shell().err_file_hyperlink(&timing_path);
101    let msg = format!("report saved to {link}{}{link:#}", timing_path.display());
102    gctx.shell()
103        .status_with_color("Timing", msg, &style::NOTE)?;
104
105    if opts.open_result {
106        crate::util::open::open(&timing_path, gctx)?;
107    }
108
109    Ok(())
110}
111
112fn prepare_context(log: &Path, run_id: &RunId) -> CargoResult<RenderContext<'static>> {
113    let reader = BufReader::new(File::open(&log)?);
114
115    let mut ctx = RenderContext {
116        start_str: run_id.timestamp().to_string(),
117        root_units: Default::default(),
118        profile: Default::default(),
119        total_fresh: Default::default(),
120        total_dirty: Default::default(),
121        unit_data: Default::default(),
122        concurrency: Default::default(),
123        cpu_usage: Default::default(),
124        rustc_version: Default::default(),
125        host: Default::default(),
126        requested_targets: Default::default(),
127        jobs: 0,
128        num_cpus: None,
129        error: &None,
130    };
131    let mut units: IndexMap<_, UnitEntry> = IndexMap::new();
132
133    let mut platform_targets = HashSet::new();
134
135    let mut requested_units = HashSet::new();
136
137    for (log_index, result) in serde_json::Deserializer::from_reader(reader)
138        .into_iter::<LogMessage>()
139        .enumerate()
140    {
141        let msg = match result {
142            Ok(msg) => msg,
143            Err(e) => {
144                tracing::warn!("failed to parse log message at index {log_index}: {e}");
145                continue;
146            }
147        };
148
149        match msg {
150            LogMessage::BuildStarted {
151                cwd: _,
152                host,
153                jobs,
154                num_cpus,
155                profile,
156                rustc_version,
157                rustc_version_verbose,
158                target_dir: _,
159                workspace_root: _,
160            } => {
161                let rustc_version = rustc_version_verbose
162                    .lines()
163                    .next()
164                    .map(ToOwned::to_owned)
165                    .unwrap_or(rustc_version);
166                ctx.host = host;
167                ctx.jobs = jobs;
168                ctx.num_cpus = num_cpus;
169                ctx.profile = profile;
170                ctx.rustc_version = rustc_version;
171            }
172            LogMessage::UnitRegistered {
173                package_id,
174                target,
175                mode,
176                platform,
177                index,
178                features,
179                requested,
180                dependencies: _,
181            } => {
182                if requested {
183                    requested_units.insert(index);
184                }
185                platform_targets.insert(platform);
186
187                let version = package_id
188                    .version()
189                    .map(|v| v.to_string())
190                    .unwrap_or_else(|| "N/A".into());
191
192                // This is pretty similar to how the current `core::compiler::timings`
193                // renders `core::manifest::Target`. However, our target is
194                // a simplified type so we cannot reuse the same logic here.
195                let mut target_str = if target.kind == "lib" && mode == CompileMode::Build {
196                    // Special case for brevity, since most dependencies hit this path.
197                    "".to_string()
198                } else if target.kind == "build-script" {
199                    " build-script".to_string()
200                } else {
201                    format!(r#" {} "{}""#, target.name, target.kind)
202                };
203
204                match mode {
205                    CompileMode::Test => target_str.push_str(" (test)"),
206                    CompileMode::Build => {}
207                    CompileMode::Check { test: true } => target_str.push_str(" (check-test)"),
208                    CompileMode::Check { test: false } => target_str.push_str(" (check)"),
209                    CompileMode::Doc { .. } => target_str.push_str(" (doc)"),
210                    CompileMode::Doctest => target_str.push_str(" (doc test)"),
211                    CompileMode::Docscrape => target_str.push_str(" (doc scrape)"),
212                    CompileMode::RunCustomBuild => target_str.push_str(" (run)"),
213                }
214
215                let mode_str = if mode.is_run_custom_build() {
216                    "run-custom-build"
217                } else {
218                    "todo"
219                };
220
221                let data = UnitData {
222                    i: index,
223                    name: package_id.name().to_string(),
224                    version,
225                    mode: mode_str.to_owned(),
226                    target: target_str,
227                    features,
228                    start: 0.0,
229                    duration: 0.0,
230                    unblocked_units: Vec::new(),
231                    unblocked_rmeta_units: Vec::new(),
232                    sections: None,
233                };
234
235                units.insert(
236                    index,
237                    UnitEntry {
238                        target,
239                        data,
240                        sections: IndexMap::new(),
241                        rmeta_time: None,
242                    },
243                );
244            }
245            LogMessage::UnitFingerprint { status, .. } => match status {
246                FingerprintStatus::New => ctx.total_dirty += 1,
247                FingerprintStatus::Dirty => ctx.total_dirty += 1,
248                FingerprintStatus::Fresh => ctx.total_fresh += 1,
249            },
250            LogMessage::UnitStarted { index, elapsed } => {
251                units
252                    .entry(index)
253                    .and_modify(|unit| unit.data.start = elapsed)
254                    .or_insert_with(|| {
255                        unreachable!("unit {index} must have been registered first")
256                    });
257            }
258            LogMessage::UnitRmetaFinished {
259                index,
260                elapsed,
261                unblocked,
262            } => match units.entry(index) {
263                Entry::Occupied(mut e) => {
264                    let elapsed = f64::max(elapsed - e.get().data.start, 0.0);
265                    e.get_mut().data.unblocked_rmeta_units = unblocked;
266                    e.get_mut().data.duration = elapsed;
267                    e.get_mut().rmeta_time = Some(elapsed);
268                }
269                Entry::Vacant(_) => {
270                    tracing::warn!(
271                        "section `frontend` ended, but unit {index} has no start recorded"
272                    )
273                }
274            },
275            LogMessage::UnitSectionStarted {
276                index,
277                elapsed,
278                section,
279            } => match units.entry(index) {
280                Entry::Occupied(mut e) => {
281                    let elapsed = f64::max(elapsed - e.get().data.start, 0.0);
282                    if e.get_mut()
283                        .sections
284                        .insert(
285                            section.clone(),
286                            CompilationSection {
287                                start: elapsed,
288                                end: None,
289                            },
290                        )
291                        .is_some()
292                    {
293                        tracing::warn!(
294                            "section `{section}` for unit {index} started more than once",
295                        );
296                    }
297                }
298                Entry::Vacant(_) => {
299                    tracing::warn!(
300                        "section `{section}` started, but unit {index} has no start recorded"
301                    )
302                }
303            },
304            LogMessage::UnitSectionFinished {
305                index,
306                elapsed,
307                section,
308            } => match units.entry(index) {
309                Entry::Occupied(mut e) => {
310                    let elapsed = f64::max(elapsed - e.get().data.start, 0.0);
311                    if let Some(section) = e.get_mut().sections.get_mut(&section) {
312                        section.end = Some(elapsed);
313                    } else {
314                        tracing::warn!(
315                            "section `{section}` for unit {index} ended, but section `{section}` has no start recorded"
316                        );
317                    }
318                }
319                Entry::Vacant(_) => {
320                    tracing::warn!(
321                        "section `{section}` ended, but unit {index} has no start recorded"
322                    )
323                }
324            },
325            LogMessage::UnitFinished {
326                index,
327                elapsed,
328                unblocked,
329            } => match units.entry(index) {
330                Entry::Occupied(mut e) => {
331                    let elapsed = f64::max(elapsed - e.get().data.start, 0.0);
332                    e.get_mut().data.duration = elapsed;
333                    e.get_mut().data.unblocked_units = unblocked;
334                }
335                Entry::Vacant(_) => {
336                    tracing::warn!("unit {index} ended, but it has no start recorded");
337                }
338            },
339            _ => {} // skip non-timing logs
340        }
341    }
342
343    ctx.root_units = {
344        let mut root_map: IndexMap<_, Vec<_>> = IndexMap::new();
345        for index in requested_units {
346            let unit = &units[&index];
347            // Pretty much like `core::Target::description_named`
348            let target_desc = if unit.target.kind == "lib" {
349                "lib".to_owned()
350            } else if unit.target.kind == "build-script" {
351                "build script".to_owned()
352            } else {
353                format!(r#" {} "{}""#, unit.target.name, unit.target.kind)
354            };
355            root_map.entry(index).or_default().push(target_desc);
356        }
357        root_map
358            .into_iter()
359            .sorted_by_key(|(i, _)| *i)
360            .map(|(index, targets)| {
361                let unit = &units[&index];
362                let pkg_desc = format!("{} {}", unit.data.name, unit.data.version);
363                (pkg_desc, targets)
364            })
365            .collect()
366    };
367
368    let unit_data: Vec<_> = units
369        .into_values()
370        .map(
371            |UnitEntry {
372                 target: _,
373                 mut data,
374                 sections,
375                 rmeta_time,
376             }| {
377                // Post-processing for compilation sections we've collected so far.
378                data.sections = aggregate_sections(sections, data.duration, rmeta_time);
379                data.start = round_to_centisecond(data.start);
380                data.duration = round_to_centisecond(data.duration);
381                data
382            },
383        )
384        .sorted_unstable_by(|a, b| a.start.partial_cmp(&b.start).unwrap())
385        .collect();
386
387    if unit_data.is_empty() {
388        anyhow::bail!("no timing data found in log");
389    }
390
391    ctx.unit_data = unit_data;
392    ctx.concurrency = compute_concurrency(&ctx.unit_data);
393    ctx.requested_targets = platform_targets.into_iter().sorted_unstable().collect();
394
395    Ok(ctx)
396}