mitts 0.3.28

Rust-first build and package tooling with a shared artifact cache
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
/*
 * Mitts Build — Rust-first build and package tooling with shared artifact cache
 * Copyright (c) 2026 Alexander Panasenko
 *
 * Contact: alex@prod.codes
 * Author: https://prod.codes/about/
 * Project: https://github.com/alex09x/mitts
 * SPDX-License-Identifier: MIT OR Apache-2.0
 */

use crate::core::hash::Sha256;
use anyhow::{bail, Context, Result};
use std::collections::HashMap;
use std::fs;
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::{Mutex, OnceLock};

static STAGING_SEQ: AtomicU64 = AtomicU64::new(0);

/// Marker file written as the final step in staging before atomic `rename` into the store.
pub const MITTS_OK_MARKER: &str = ".mitts-ok";

/// Thread-safe global content store for downloaded and unpacked crate sources.
/// Stored packages reside at `{root}/{crate_name}-{version}/` with zero workspace or Cargo registry pollution.
#[derive(Debug, Clone)]
pub struct SourceStore {
    root: PathBuf,
    locks_dir: PathBuf,
}

impl SourceStore {
    /// Creates or opens a SourceStore at the given root directory.
    pub fn new(root: PathBuf) -> Result<Self> {
        fs::create_dir_all(&root)
            .with_context(|| format!("Failed to create source store at {:?}", root))?;
        let locks_dir = root.join(".locks");
        fs::create_dir_all(&locks_dir)
            .with_context(|| format!("Failed to create source locks dir at {:?}", locks_dir))?;

        Ok(Self { root, locks_dir })
    }

    /// Returns the default store root path (`<cache root>/sources`, see
    /// [`crate::core::cache_root`] for the precedence) without creating directories on disk.
    pub fn default_root() -> PathBuf {
        crate::core::cache_root::default_root().join(crate::core::cache_root::SOURCES_DIR)
    }

    /// Default global store location under the default cache root.
    /// Never writes into `$CARGO_HOME/registry`.
    pub fn default_store() -> Result<Self> {
        Self::new(Self::default_root())
    }

    /// Resolves the active Cargo home directory (`$CARGO_HOME` if explicitly set, otherwise `$HOME/.cargo`).
    pub fn active_cargo_home() -> Option<PathBuf> {
        if let Some(ch) = std::env::var_os("CARGO_HOME").filter(|v| !v.is_empty()) {
            return Some(PathBuf::from(ch));
        }
        std::env::var_os("HOME")
            .filter(|v| !v.is_empty())
            .map(|h| PathBuf::from(h).join(".cargo"))
    }

    fn discover_cargo_registry_subdir(sub: &str) -> Option<PathBuf> {
        let dir = Self::active_cargo_home()?.join("registry").join(sub);
        for entry in fs::read_dir(dir).ok()?.flatten() {
            let name = entry.file_name().to_string_lossy().to_string();
            if (name.starts_with("index.crates.io-") || name.starts_with("github.com-"))
                && entry.path().is_dir()
            {
                return Some(entry.path());
            }
        }
        None
    }

    /// Read-only discovery of active standard ~/.cargo/registry/src/index.crates.io-* directory if present.
    pub fn discover_cargo_registry_src() -> Option<PathBuf> {
        Self::discover_cargo_registry_subdir("src")
    }

    /// Read-only discovery of active standard ~/.cargo/registry/cache/index.crates.io-* directory if present.
    pub fn discover_cargo_registry_cache() -> Option<PathBuf> {
        Self::discover_cargo_registry_subdir("cache")
    }

    /// Root directory of the source store.
    pub fn root(&self) -> &Path {
        &self.root
    }

    /// Locks directory used for single-flight download coordination and atomic staging.
    pub fn locks_dir(&self) -> &Path {
        &self.locks_dir
    }

    /// Returns the target unpacked directory path for a crate: `{root}/{name}-{version}`.
    pub fn package_dir(&self, name: &str, version: &str) -> PathBuf {
        self.root.join(format!("{}-{}", name, version))
    }

    /// Lockfile path used to synchronize downloading and unpacking of a specific crate.
    pub fn lock_path(&self, name: &str, version: &str) -> PathBuf {
        self.locks_dir.join(format!("{}-{}.lock", name, version))
    }

    /// Checks whether a candidate directory is atomically unpacked and ready (`.mitts-ok` + `Cargo.toml`).
    pub fn is_valid_source_dir(dir: &Path) -> bool {
        dir.join(MITTS_OK_MARKER).is_file() && dir.join("Cargo.toml").is_file()
    }

    /// Checks whether the crate source is already atomically unpacked and ready (`.mitts-ok` + `Cargo.toml`).
    pub fn has_source(&self, name: &str, version: &str) -> bool {
        Self::is_valid_source_dir(&self.package_dir(name, version))
    }

    fn next_staging_dir(&self, name: &str, version: &str, suffix: &str) -> PathBuf {
        let seq = STAGING_SEQ.fetch_add(1, Ordering::Relaxed);
        self.locks_dir.join(format!(
            "{}-{}-{}-{}.{}",
            name,
            version,
            std::process::id(),
            seq,
            suffix
        ))
    }

    /// Removes orphaned `.staging` and `.trash` directories in `.locks` whose owning PID is no
    /// longer alive (`ESRCH`) and whose `mtime` is older than 1 hour (safe across container PID namespaces).
    pub fn cleanup_dead_staging(&self) -> usize {
        let Ok(entries) = fs::read_dir(&self.locks_dir) else {
            return 0;
        };
        let mut removed = 0;
        for entry in entries.flatten() {
            let path = entry.path();
            if !path.is_dir() {
                continue;
            }
            let fname = entry.file_name().to_string_lossy().to_string();
            let Some(stem) = fname
                .strip_suffix(".staging")
                .or_else(|| fname.strip_suffix(".trash"))
            else {
                continue;
            };
            let mut parts = stem.rsplitn(3, '-');
            let _seq = parts.next();
            let Some(pid_str) = parts.next() else {
                continue;
            };
            let Ok(pid) = pid_str.parse::<u32>() else {
                continue;
            };
            if pid == std::process::id() {
                continue;
            }
            #[cfg(unix)]
            let is_dead = unsafe {
                libc::kill(pid as i32, 0) == -1
                    && std::io::Error::last_os_error().raw_os_error() == Some(libc::ESRCH)
            };
            #[cfg(not(unix))]
            let is_dead = false;
            let is_stale = entry
                .metadata()
                .and_then(|m| m.modified())
                .ok()
                .and_then(|mtime| std::time::SystemTime::now().duration_since(mtime).ok())
                .is_some_and(|age| age >= std::time::Duration::from_secs(3600));
            if is_dead && is_stale && fs::remove_dir_all(&path).is_ok() {
                removed += 1;
            }
        }
        removed
    }

    /// Atomically publishes `src_to_move` (inside `staging_root` on the same filesystem) to `{root}/{name}-{version}`.
    fn publish_staged_dir(
        &self,
        name: &str,
        version: &str,
        staging_root: &Path,
        src_to_move: &Path,
    ) -> Result<PathBuf> {
        let target_dir = self.package_dir(name, version);
        if !src_to_move.join("Cargo.toml").is_file() {
            let _ = fs::remove_dir_all(staging_root);
            bail!(
                "Extracted crate {}-{} is missing Cargo.toml in {:?}",
                name,
                version,
                target_dir
            );
        }

        if let Err(e) = fs::write(src_to_move.join(MITTS_OK_MARKER), b"ok\n") {
            let _ = fs::remove_dir_all(staging_root);
            return Err(e).with_context(|| {
                format!("Failed to write {} in {:?}", MITTS_OK_MARKER, src_to_move)
            });
        }

        if self.has_source(name, version) {
            let _ = fs::remove_dir_all(staging_root);
            return Ok(target_dir);
        }

        // If an incomplete/legacy directory exists without `.mitts-ok`, move it aside atomically before rename.
        if target_dir.exists() && !self.has_source(name, version) {
            let trash_dir = self.next_staging_dir(name, version, "trash");
            if fs::rename(&target_dir, &trash_dir).is_ok() {
                if trash_dir.join(MITTS_OK_MARKER).is_file() {
                    let _ = fs::rename(&trash_dir, &target_dir);
                } else {
                    let _ = fs::remove_dir_all(&trash_dir);
                }
            }
        }

        match fs::rename(src_to_move, &target_dir) {
            Ok(()) => {
                if src_to_move != staging_root {
                    let _ = fs::remove_dir_all(staging_root);
                }
                Ok(target_dir)
            }
            Err(e) => {
                let _ = fs::remove_dir_all(staging_root);
                if self.has_source(name, version) {
                    return Ok(target_dir);
                }
                Err(e).with_context(|| {
                    format!("Failed to atomically publish crate {name}-{version} to {target_dir:?}")
                })
            }
        }
    }

    /// Unpacks a downloaded `.crate` (tar.gz) archive into a staging directory after verifying its
    /// SHA-256 checksum, writes `.mitts-ok`, and atomically renames it into the store.
    pub fn unpack_archive(
        &self,
        name: &str,
        version: &str,
        archive_bytes: &[u8],
        expected_checksum: &str,
    ) -> Result<PathBuf> {
        if !expected_checksum.is_empty() {
            let actual_checksum = Sha256::digest(archive_bytes);
            if actual_checksum != expected_checksum {
                bail!("Checksum mismatch for crate {name}-{version}: expected {expected_checksum}, got {actual_checksum}");
            }
        }

        let target_dir = self.package_dir(name, version);
        if self.has_source(name, version) {
            return Ok(target_dir);
        }

        let staging_dir = self.next_staging_dir(name, version, "staging");
        fs::create_dir_all(&staging_dir)
            .with_context(|| format!("Failed to create staging dir {staging_dir:?}"))?;

        let gz = flate2::read::GzDecoder::new(archive_bytes);
        let mut archive = tar::Archive::new(gz);
        archive.set_preserve_mtime(false);
        archive.set_preserve_permissions(false);
        if let Err(e) = archive.unpack(&staging_dir) {
            let _ = fs::remove_dir_all(&staging_dir);
            return Err(e).with_context(|| {
                format!("Failed to unpack crate archive in-memory for {name}-{version}")
            });
        }

        let nested_dir = staging_dir.join(format!("{}-{}", name, version));
        let src_to_move = if nested_dir.join("Cargo.toml").is_file() {
            nested_dir
        } else {
            staging_dir.clone()
        };

        self.publish_staged_dir(name, version, &staging_dir, &src_to_move)
    }

    /// Stages a copy of an existing unpacked crate directory on the store's filesystem,
    /// writes `.mitts-ok`, and atomically renames it into `{root}/{name}-{version}`.
    pub fn stage_copy_dir(&self, name: &str, version: &str, src_dir: &Path) -> Result<PathBuf> {
        let target_dir = self.package_dir(name, version);
        if self.has_source(name, version) {
            return Ok(target_dir);
        }

        let staging_dir = self.next_staging_dir(name, version, "staging");
        if let Err(e) = Self::copy_dir_recursive(src_dir, &staging_dir) {
            let _ = fs::remove_dir_all(&staging_dir);
            return Err(e).with_context(|| {
                format!(
                    "Failed to stage copy from {:?} to {:?}",
                    src_dir, staging_dir
                )
            });
        }

        self.publish_staged_dir(name, version, &staging_dir, &staging_dir)
    }

    /// Recursively copies a directory to the destination.
    pub fn copy_dir_recursive(src: &Path, dst: &Path) -> Result<()> {
        fs::create_dir_all(dst)?;
        for entry in fs::read_dir(src)? {
            let entry = entry?;
            let path = entry.path();
            let dest_path = dst.join(entry.file_name());
            if path.is_dir() {
                Self::copy_dir_recursive(&path, &dest_path)?;
            } else {
                fs::copy(&path, &dest_path)?;
            }
        }
        Ok(())
    }
}

/// Pre-resolved local Cargo registry index directories (strictly read-only).
pub struct RegistryLookup {
    cache_index_dirs: Vec<PathBuf>,
    src_index_dirs: Vec<PathBuf>,
}

impl RegistryLookup {
    pub fn discover(exclude_store_root: &Path) -> Self {
        Self::discover_with_home(SourceStore::active_cargo_home(), exclude_store_root)
    }

    /// `discover` for an explicit Cargo home. The listing is taken once per process for
    /// each `(cargo_home, exclude_store_root)`: Mitts never writes into Cargo's registry,
    /// so the index directories cannot change underneath a running build, and the planner
    /// asks once per package.
    pub fn discover_with_home(cargo_home: Option<PathBuf>, exclude_store_root: &Path) -> Self {
        type Key = (Option<PathBuf>, PathBuf);
        type Dirs = (Vec<PathBuf>, Vec<PathBuf>);
        static DISCOVERED: OnceLock<Mutex<HashMap<Key, Dirs>>> = OnceLock::new();
        let cache = DISCOVERED.get_or_init(|| Mutex::new(HashMap::new()));
        let key = (cargo_home.clone(), exclude_store_root.to_path_buf());
        if let Some((cache_dirs, src_dirs)) =
            cache.lock().unwrap_or_else(|e| e.into_inner()).get(&key)
        {
            return Self {
                cache_index_dirs: cache_dirs.clone(),
                src_index_dirs: src_dirs.clone(),
            };
        }
        let found = Self::scan(cargo_home.as_deref(), exclude_store_root);
        cache.lock().unwrap_or_else(|e| e.into_inner()).insert(
            key,
            (found.cache_index_dirs.clone(), found.src_index_dirs.clone()),
        );
        found
    }

    /// Registry `src/` index directories, in discovery order.
    pub fn src_index_dirs(&self) -> &[PathBuf] {
        &self.src_index_dirs
    }

    /// Lists the registry index directories under `cargo_home` right now, uncached.
    pub fn scan(cargo_home: Option<&Path>, exclude_store_root: &Path) -> Self {
        let mut cache_index_dirs = Vec::new();
        let mut src_index_dirs = Vec::new();
        let is_crates_io_dir = |entry: &fs::DirEntry| -> bool {
            let name = entry.file_name().to_string_lossy().to_string();
            (name.starts_with("index.crates.io-") || name.starts_with("github.com-"))
                && entry.path().is_dir()
        };

        if let Some(reg_dir) = cargo_home.map(|ch| ch.join("registry")) {
            if let Ok(entries) = fs::read_dir(reg_dir.join("cache")) {
                cache_index_dirs.extend(
                    entries
                        .flatten()
                        .filter(&is_crates_io_dir)
                        .map(|e| e.path()),
                );
            }
            if let Ok(entries) = fs::read_dir(reg_dir.join("src")) {
                src_index_dirs.extend(
                    entries
                        .flatten()
                        .filter(&is_crates_io_dir)
                        .map(|e| e.path())
                        .filter(|p| p != exclude_store_root),
                );
            }
        }
        Self {
            cache_index_dirs,
            src_index_dirs,
        }
    }

    pub fn find_in_cache(&self, name: &str, version: &str) -> Option<PathBuf> {
        let file_name = format!("{}-{}.crate", name, version);
        self.cache_index_dirs
            .iter()
            .map(|dir| dir.join(&file_name))
            .find(|c| c.is_file())
    }

    pub fn find_in_src(&self, name: &str, version: &str) -> Option<PathBuf> {
        let dir_name = format!("{}-{}", name, version);
        self.src_index_dirs
            .iter()
            .map(|dir| dir.join(&dir_name))
            .find(|c| c.join("Cargo.toml").is_file() && c.join(".cargo-ok").is_file())
    }
}