archive.rs
| 1 | //! Streaming archive builders (zip / tar / tar.gz / tar.zst). |
| 2 | //! |
| 3 | //! Everything writes directly into an `impl std::io::Write` sink — no temp |
| 4 | //! files, no full in-memory buffering. The sink is typically a channel that |
| 5 | //! feeds the HTTP response body, so bytes reach the client while the tree is |
| 6 | //! still being walked. |
| 7 | |
| 8 | use std::io::{self, Write}; |
| 9 | use std::path::{Path, PathBuf}; |
| 10 | use std::time::UNIX_EPOCH; |
| 11 | |
| 12 | /// The archive formats offered for folder downloads. |
| 13 | #[derive(Clone, Copy, PartialEq, Eq, Debug)] |
| 14 | pub enum ArchiveFormat { |
| 15 | Zip, |
| 16 | Tar, |
| 17 | TarGz, |
| 18 | TarZst, |
| 19 | } |
| 20 | |
| 21 | impl ArchiveFormat { |
| 22 | /// Parse the `format` query parameter. Unknown values are rejected. |
| 23 | pub fn parse(s: &str) -> Option<Self> { |
| 24 | match s { |
| 25 | "zip" => Some(Self::Zip), |
| 26 | "tar" => Some(Self::Tar), |
| 27 | "tar.gz" | "tgz" => Some(Self::TarGz), |
| 28 | "tar.zst" | "tzst" => Some(Self::TarZst), |
| 29 | _ => None, |
| 30 | } |
| 31 | } |
| 32 | |
| 33 | /// The file-name suffix for the produced archive. |
| 34 | pub fn extension(self) -> &'static str { |
| 35 | match self { |
| 36 | Self::Zip => "zip", |
| 37 | Self::Tar => "tar", |
| 38 | Self::TarGz => "tar.gz", |
| 39 | Self::TarZst => "tar.zst", |
| 40 | } |
| 41 | } |
| 42 | |
| 43 | /// MIME type for the produced archive. |
| 44 | pub fn mime(self) -> &'static str { |
| 45 | match self { |
| 46 | Self::Zip => "application/zip", |
| 47 | Self::Tar => "application/x-tar", |
| 48 | Self::TarGz => "application/gzip", |
| 49 | Self::TarZst => "application/zstd", |
| 50 | } |
| 51 | } |
| 52 | } |
| 53 | |
| 54 | /// Build `dir` (top-level entry named `top_name`) as `format`, streaming into |
| 55 | /// `sink`. Blocking — call from `spawn_blocking`. |
| 56 | pub fn build( |
| 57 | format: ArchiveFormat, |
| 58 | dir: &Path, |
| 59 | top_name: &str, |
| 60 | sink: impl Write, |
| 61 | ) -> io::Result<()> { |
| 62 | match format { |
| 63 | ArchiveFormat::Tar => build_tar(dir, top_name, sink), |
| 64 | ArchiveFormat::TarGz => build_tar_gz(dir, top_name, sink), |
| 65 | ArchiveFormat::TarZst => build_tar_zst(dir, top_name, sink), |
| 66 | ArchiveFormat::Zip => build_zip(dir, top_name, sink), |
| 67 | } |
| 68 | } |
| 69 | |
| 70 | fn mtime_secs(p: &Path) -> u64 { |
| 71 | std::fs::metadata(p) |
| 72 | .and_then(|m| m.modified()) |
| 73 | .ok() |
| 74 | .and_then(|t| t.duration_since(UNIX_EPOCH).ok()) |
| 75 | .map(|d| d.as_secs()) |
| 76 | .unwrap_or(0) |
| 77 | } |
| 78 | |
| 79 | /// Depth-first walk. Invokes `f(entry_name, abs_path, is_dir)` for the |
| 80 | /// directory itself and every descendant. Directory entry names carry no |
| 81 | /// trailing slash; each format appends it as needed. Deterministic order |
| 82 | /// (case-insensitive name) so archives are reproducible. |
| 83 | fn walk<F: FnMut(&str, &Path, bool) -> io::Result<()>>( |
| 84 | abs_dir: &Path, |
| 85 | entry_prefix: &str, |
| 86 | f: &mut F, |
| 87 | ) -> io::Result<()> { |
| 88 | f(entry_prefix, abs_dir, true)?; |
| 89 | let rd = std::fs::read_dir(abs_dir)?; |
| 90 | let mut children: Vec<(String, PathBuf, bool)> = Vec::new(); |
| 91 | for e in rd.flatten() { |
| 92 | let name = e.file_name().to_string_lossy().into_owned(); |
| 93 | let p = e.path(); |
| 94 | // Follows symlinks (a broken link shows up as an empty file). |
| 95 | let is_dir = p.is_dir(); |
| 96 | children.push((name, p, is_dir)); |
| 97 | } |
| 98 | children.sort_by(|a, b| a.0.to_lowercase().cmp(&b.0.to_lowercase())); |
| 99 | for (name, p, is_dir) in children { |
| 100 | let child = format!("{entry_prefix}/{name}"); |
| 101 | if is_dir { |
| 102 | walk(&p, &child, f)?; |
| 103 | } else { |
| 104 | f(&child, &p, false)?; |
| 105 | } |
| 106 | } |
| 107 | Ok(()) |
| 108 | } |
| 109 | |
| 110 | // --------------------------------------------------------------------------- |
| 111 | // tar |
| 112 | // --------------------------------------------------------------------------- |
| 113 | |
| 114 | fn tar_add<W: Write>( |
| 115 | tar: &mut tar::Builder<W>, |
| 116 | entry: &str, |
| 117 | abs: &Path, |
| 118 | is_dir: bool, |
| 119 | ) -> io::Result<()> { |
| 120 | let mut header = tar::Header::new_gnu(); |
| 121 | let meta = std::fs::metadata(abs)?; |
| 122 | header.set_mode(if is_dir { 0o755 } else { 0o644 }); |
| 123 | header.set_mtime(mtime_secs(abs)); |
| 124 | let name = if is_dir { |
| 125 | format!("{entry}/") |
| 126 | } else { |
| 127 | entry.to_string() |
| 128 | }; |
| 129 | if is_dir { |
| 130 | header.set_entry_type(tar::EntryType::Directory); |
| 131 | header.set_size(0); |
| 132 | tar.append_data(&mut header, name, io::empty())?; |
| 133 | } else { |
| 134 | header.set_entry_type(tar::EntryType::Regular); |
| 135 | header.set_size(meta.len()); |
| 136 | let f = std::fs::File::open(abs)?; |
| 137 | tar.append_data(&mut header, name, f)?; |
| 138 | } |
| 139 | Ok(()) |
| 140 | } |
| 141 | |
| 142 | fn build_tar<W: Write>(dir: &Path, top: &str, sink: W) -> io::Result<()> { |
| 143 | let mut tar = tar::Builder::new(sink); |
| 144 | let mut add = |entry: &str, abs: &Path, is_dir: bool| -> io::Result<()> { |
| 145 | tar_add(&mut tar, entry, abs, is_dir) |
| 146 | }; |
| 147 | walk(dir, top, &mut add)?; |
| 148 | tar.finish()?; |
| 149 | Ok(()) |
| 150 | } |
| 151 | |
| 152 | fn build_tar_gz<W: Write>(dir: &Path, top: &str, sink: W) -> io::Result<()> { |
| 153 | let enc = flate2::write::GzEncoder::new(sink, flate2::Compression::default()); |
| 154 | let mut tar = tar::Builder::new(enc); |
| 155 | let mut add = |entry: &str, abs: &Path, is_dir: bool| -> io::Result<()> { |
| 156 | tar_add(&mut tar, entry, abs, is_dir) |
| 157 | }; |
| 158 | walk(dir, top, &mut add)?; |
| 159 | let enc = tar.into_inner()?; |
| 160 | enc.finish()?; |
| 161 | Ok(()) |
| 162 | } |
| 163 | |
| 164 | fn build_tar_zst<W: Write>(dir: &Path, top: &str, sink: W) -> io::Result<()> { |
| 165 | let enc = zstd::stream::write::Encoder::new(sink, 3)?; |
| 166 | let mut tar = tar::Builder::new(enc); |
| 167 | let mut add = |entry: &str, abs: &Path, is_dir: bool| -> io::Result<()> { |
| 168 | tar_add(&mut tar, entry, abs, is_dir) |
| 169 | }; |
| 170 | walk(dir, top, &mut add)?; |
| 171 | let enc = tar.into_inner()?; |
| 172 | enc.finish()?; |
| 173 | Ok(()) |
| 174 | } |
| 175 | |
| 176 | // --------------------------------------------------------------------------- |
| 177 | // zip |
| 178 | // --------------------------------------------------------------------------- |
| 179 | |
| 180 | fn build_zip<W: Write>(dir: &Path, top: &str, sink: W) -> io::Result<()> { |
| 181 | // Streaming mode: no `Seek` needed, entries use data descriptors. |
| 182 | let mut zip = zip::write::ZipWriter::new_stream(sink); |
| 183 | let mut add = |entry: &str, abs: &Path, is_dir: bool| -> io::Result<()> { |
| 184 | let opts = zip::write::SimpleFileOptions::default(); |
| 185 | let name = if is_dir { |
| 186 | format!("{entry}/") |
| 187 | } else { |
| 188 | entry.to_string() |
| 189 | }; |
| 190 | if is_dir { |
| 191 | zip.add_directory(&name, opts)?; |
| 192 | } else { |
| 193 | zip.start_file(&name, opts)?; |
| 194 | let mut f = std::fs::File::open(abs)?; |
| 195 | io::copy(&mut f, &mut zip)?; |
| 196 | } |
| 197 | Ok(()) |
| 198 | }; |
| 199 | walk(dir, top, &mut add)?; |
| 200 | zip.finish()?; |
| 201 | Ok(()) |
| 202 | } |
| 203 |