Skip to main content

nextest_runner/reuse_build/
unarchiver.rs

1// Copyright (c) The nextest Contributors
2// SPDX-License-Identifier: MIT OR Apache-2.0
3
4use super::{
5    ArchiveEvent, ArchiveFormat, BINARIES_METADATA_FILE_NAME, CARGO_METADATA_FILE_NAME,
6    LIBDIRS_BASE_DIR, LibdirMapper, PlatformLibdirMapper,
7};
8use crate::{
9    errors::{ArchiveExtractError, ArchiveReadError},
10    helpers::convert_rel_path_to_main_sep,
11    list::BinaryList,
12};
13use camino::{Utf8Component, Utf8Path, Utf8PathBuf};
14use camino_tempfile::Utf8TempDir;
15use guppy::{CargoMetadata, graph::PackageGraph};
16use nextest_metadata::BinaryListSummary;
17use std::{
18    fs,
19    io::{self, Seek},
20    time::Instant,
21};
22
23#[derive(Debug)]
24pub(crate) struct Unarchiver<'a> {
25    file: &'a mut fs::File,
26    format: ArchiveFormat,
27}
28
29impl<'a> Unarchiver<'a> {
30    pub(crate) fn new(file: &'a mut fs::File, format: ArchiveFormat) -> Self {
31        Self { file, format }
32    }
33
34    pub(crate) fn extract<F>(
35        &mut self,
36        dest: ExtractDestination,
37        mut callback: F,
38    ) -> Result<ExtractInfo, ArchiveExtractError>
39    where
40        F: for<'e> FnMut(ArchiveEvent<'e>) -> io::Result<()>,
41    {
42        let (dest_dir, temp_dir) = match dest {
43            ExtractDestination::TempDir { persist } => {
44                // Create a new temporary directory and extract contents to it.
45                let temp_dir = camino_tempfile::Builder::new()
46                    .prefix("nextest-archive-")
47                    .tempdir()
48                    .map_err(ArchiveExtractError::TempDirCreate)?;
49
50                let dest_dir: Utf8PathBuf = temp_dir.path().to_path_buf();
51                let dest_dir = temp_dir.path().canonicalize_utf8().map_err(|error| {
52                    ArchiveExtractError::DestDirCanonicalization {
53                        dir: dest_dir,
54                        error,
55                    }
56                })?;
57
58                let temp_dir = if persist {
59                    // Persist the temporary directory.
60                    let _ = temp_dir.keep();
61                    None
62                } else {
63                    Some(temp_dir)
64                };
65
66                (dest_dir, temp_dir)
67            }
68            ExtractDestination::Destination { dir, overwrite } => {
69                // Extract contents to the destination directory.
70                let dest_dir = dir
71                    .canonicalize_utf8()
72                    .map_err(|error| ArchiveExtractError::DestDirCanonicalization { dir, error })?;
73
74                let dest_target = dest_dir.join("target");
75                if dest_target.exists() && !overwrite {
76                    return Err(ArchiveExtractError::DestinationExists(dest_target));
77                }
78
79                (dest_dir, None)
80            }
81        };
82
83        let start_time = Instant::now();
84
85        // Extract the archive.
86        self.file
87            .rewind()
88            .map_err(|error| ArchiveExtractError::Read(ArchiveReadError::Io(error)))?;
89        let mut archive_reader =
90            ArchiveReader::new(self.file, self.format).map_err(ArchiveExtractError::Read)?;
91
92        // Will be filled out by the for loop below.
93        let mut binary_list = None;
94        let mut graph_data = None;
95        let mut host_libdir = PlatformLibdirMapper::Unavailable;
96        let mut target_libdir = PlatformLibdirMapper::Unavailable;
97        let binaries_metadata_path = Utf8Path::new(BINARIES_METADATA_FILE_NAME);
98        let cargo_metadata_path = Utf8Path::new(CARGO_METADATA_FILE_NAME);
99
100        let mut file_count = 0;
101
102        for entry in archive_reader
103            .entries()
104            .map_err(ArchiveExtractError::Read)?
105        {
106            file_count += 1;
107            let (mut entry, path) = entry.map_err(ArchiveExtractError::Read)?;
108
109            entry
110                .unpack_in(&dest_dir)
111                .map_err(|error| ArchiveExtractError::WriteFile {
112                    path: path.clone(),
113                    error,
114                })?;
115
116            // For archives created by nextest, binaries_metadata_path should be towards the beginning
117            // so this should report the ExtractStarted event instantly.
118            if path == binaries_metadata_path {
119                // Try reading the binary list from the file on disk.
120                let mut file = fs::File::open(dest_dir.join(binaries_metadata_path))
121                    .map_err(|error| ArchiveExtractError::WriteFile { path, error })?;
122
123                let summary: BinaryListSummary =
124                    serde_json::from_reader(&mut file).map_err(|error| {
125                        ArchiveExtractError::Read(ArchiveReadError::MetadataDeserializeError {
126                            path: binaries_metadata_path,
127                            error,
128                        })
129                    })?;
130
131                let this_binary_list = BinaryList::from_summary(summary)?;
132                let test_binary_count = this_binary_list.rust_binaries.len();
133                let non_test_binary_count = this_binary_list
134                    .rust_build_meta
135                    .non_test_binaries
136                    .binary_count();
137                let build_script_out_dir_count =
138                    this_binary_list.rust_build_meta.build_script_out_dirs.len();
139                let linked_path_count = this_binary_list.rust_build_meta.linked_paths.len();
140
141                // TODO: also store a manifest of extra paths, and report them here.
142
143                // Report begin extraction.
144                callback(ArchiveEvent::ExtractStarted {
145                    test_binary_count,
146                    non_test_binary_count,
147                    build_script_out_dir_count,
148                    linked_path_count,
149                    dest_dir: &dest_dir,
150                })
151                .map_err(ArchiveExtractError::ReporterIo)?;
152
153                binary_list = Some(this_binary_list);
154            } else if path == cargo_metadata_path {
155                // Parse the input Cargo metadata as a `PackageGraph`.
156                let json = fs::read_to_string(dest_dir.join(cargo_metadata_path))
157                    .map_err(|error| ArchiveExtractError::WriteFile { path, error })?;
158
159                // Doing this in multiple steps results in better error messages.
160                let cargo_metadata: CargoMetadata =
161                    serde_json::from_str(&json).map_err(|error| {
162                        ArchiveExtractError::Read(ArchiveReadError::MetadataDeserializeError {
163                            path: binaries_metadata_path,
164                            error,
165                        })
166                    })?;
167
168                let package_graph = cargo_metadata.build_graph().map_err(|error| {
169                    ArchiveExtractError::Read(ArchiveReadError::PackageGraphConstructError {
170                        path: cargo_metadata_path,
171                        error: Box::new(error),
172                    })
173                })?;
174                graph_data = Some((json, package_graph));
175                continue;
176            } else if let Ok(suffix) = path.strip_prefix(LIBDIRS_BASE_DIR) {
177                if suffix.starts_with("host") {
178                    host_libdir = PlatformLibdirMapper::Path(dest_dir.join(
179                        convert_rel_path_to_main_sep(&Utf8Path::new(LIBDIRS_BASE_DIR).join("host")),
180                    ));
181                } else if suffix.starts_with("target/0") {
182                    // Currently we only support one target, so just check explicitly for target/0.
183                    target_libdir =
184                        PlatformLibdirMapper::Path(dest_dir.join(convert_rel_path_to_main_sep(
185                            &Utf8Path::new(LIBDIRS_BASE_DIR).join("target/0"),
186                        )));
187                }
188            }
189        }
190
191        let binary_list = binary_list.ok_or_else(|| {
192            ArchiveExtractError::Read(ArchiveReadError::MetadataFileNotFound(
193                binaries_metadata_path,
194            ))
195        })?;
196
197        let (cargo_metadata_json, graph) = graph_data.ok_or_else(|| {
198            ArchiveExtractError::Read(ArchiveReadError::MetadataFileNotFound(cargo_metadata_path))
199        })?;
200
201        let elapsed = start_time.elapsed();
202        // Report end extraction.
203        callback(ArchiveEvent::Extracted {
204            file_count,
205            dest_dir: &dest_dir,
206            elapsed,
207        })
208        .map_err(ArchiveExtractError::ReporterIo)?;
209
210        Ok(ExtractInfo {
211            dest_dir,
212            temp_dir,
213            binary_list,
214            cargo_metadata_json,
215            graph,
216            libdir_mapper: LibdirMapper {
217                host: host_libdir,
218                target: target_libdir,
219            },
220        })
221    }
222}
223
224#[derive(Debug)]
225pub(crate) struct ExtractInfo {
226    /// The destination directory.
227    pub dest_dir: Utf8PathBuf,
228
229    /// An optional [`Utf8TempDir`], used for cleanup.
230    pub temp_dir: Option<Utf8TempDir>,
231
232    /// The [`BinaryList`] read from the archive.
233    pub binary_list: BinaryList,
234
235    /// The Cargo metadata JSON.
236    pub cargo_metadata_json: String,
237
238    /// The [`PackageGraph`] read from the archive.
239    pub graph: PackageGraph,
240
241    /// A remapper for the Rust libdir.
242    pub libdir_mapper: LibdirMapper,
243}
244
245struct ArchiveReader<'a> {
246    archive: tar::Archive<zstd::Decoder<'static, io::BufReader<&'a mut fs::File>>>,
247}
248
249impl<'a> ArchiveReader<'a> {
250    fn new(file: &'a mut fs::File, format: ArchiveFormat) -> Result<Self, ArchiveReadError> {
251        let archive = match format {
252            ArchiveFormat::TarZst => {
253                let decoder = zstd::Decoder::new(file).map_err(ArchiveReadError::Io)?;
254                tar::Archive::new(decoder)
255            }
256        };
257        Ok(Self { archive })
258    }
259
260    fn entries<'r>(
261        &'r mut self,
262    ) -> Result<
263        impl Iterator<Item = Result<(ArchiveEntry<'r, 'a>, Utf8PathBuf), ArchiveReadError>>,
264        ArchiveReadError,
265    > {
266        let entries = self.archive.entries().map_err(ArchiveReadError::Io)?;
267        Ok(entries.map(|entry| {
268            let entry = entry.map_err(ArchiveReadError::Io)?;
269
270            // Validation: entry paths must be valid UTF-8.
271            let path = entry_path(&entry)?;
272
273            // Validation: paths start with "target".
274            if !path.starts_with("target") {
275                return Err(ArchiveReadError::NoTargetPrefix(path));
276            }
277
278            // Validation: paths only contain normal components.
279            for component in path.components() {
280                match component {
281                    Utf8Component::Normal(_) => {}
282                    other => {
283                        return Err(ArchiveReadError::InvalidComponent {
284                            path: path.clone(),
285                            component: other.as_str().to_owned(),
286                        });
287                    }
288                }
289            }
290
291            // Validation: checksum matches.
292            let mut header = entry.header().clone();
293            let actual_cksum = header
294                .cksum()
295                .map_err(|error| ArchiveReadError::ChecksumRead {
296                    path: path.clone(),
297                    error,
298                })?;
299
300            header.set_cksum();
301            let expected_cksum = header
302                .cksum()
303                .expect("checksum that was just set can't be invalid");
304
305            if expected_cksum != actual_cksum {
306                return Err(ArchiveReadError::InvalidChecksum {
307                    path,
308                    expected: expected_cksum,
309                    actual: actual_cksum,
310                });
311            }
312
313            Ok((entry, path))
314        }))
315    }
316}
317
318/// Given an entry, returns its path as a `Utf8Path`.
319fn entry_path(entry: &ArchiveEntry<'_, '_>) -> Result<Utf8PathBuf, ArchiveReadError> {
320    let path_bytes = entry.path_bytes();
321    let path_str = std::str::from_utf8(&path_bytes)
322        .map_err(|_| ArchiveReadError::NonUtf8Path(path_bytes.to_vec()))?;
323    let utf8_path = Utf8Path::new(path_str);
324    Ok(utf8_path.to_owned())
325}
326
327/// Where to extract a nextest archive to.
328#[derive(Clone, Debug)]
329pub enum ExtractDestination {
330    /// Extract the archive to a new temporary directory.
331    TempDir {
332        /// Whether to persist the temporary directory at the end of execution.
333        persist: bool,
334    },
335    /// Extract the archive to a custom destination.
336    Destination {
337        /// The directory to extract to.
338        dir: Utf8PathBuf,
339        /// Whether to overwrite existing contents.
340        overwrite: bool,
341    },
342}
343
344type ArchiveEntry<'r, 'a> = tar::Entry<'r, zstd::Decoder<'static, io::BufReader<&'a mut fs::File>>>;