nornir 0.4.54

Companion to cargo: dependency tracking, release gating, deploy, benchmarks, and documentation assembly. Project-agnostic.
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
//! `nornir release stage` — the brave-but-safe tier: rehearse the whole release
//! cascade against the embedded holger `/sparring` registry before crates.io.
//!
//! This module owns the **plan** (pure, testable): given the cross-repo graph, the
//! topo publish order and, for each repo, the direct dependents to build-verify
//! from `/sparring` once it's published. Execution (cut a release branch →
//! `cargo publish --registry sparring` in order → `cargo build` each dependent
//! against `/sparring` → `seal`) drives this plan; `--dry-run` just prints it.
//!
//! Promote (`release promote`) replays the same order against crates.io once the
//! sparring run is green.

use serde::Serialize;

use crate::release::doctor::{publish_order, RepoGraph};

#[derive(Debug, Clone, Serialize)]
pub struct StageStep {
    /// Repo to package + publish into `/sparring` at this position.
    pub repo: String,
    /// Direct dependents to `cargo build` against `/sparring` after publishing
    /// `repo` — proves the just-published crates actually resolve from a registry.
    pub verify: Vec<String>,
}

#[derive(Debug, Clone, Serialize)]
pub struct StagePlan {
    /// Sparse registry the cascade publishes into, e.g.
    /// `sparse+http://127.0.0.1:18464/sparring/index/`.
    pub registry: String,
    /// Ephemeral release branch the version bumps + cascade live on.
    pub branch: String,
    /// Publish steps in dependency order (dependencies first).
    pub order: Vec<StageStep>,
    /// Repos left unordered by a dependency cycle (must be empty to execute).
    pub cycle: Vec<String>,
}

impl StagePlan {
    /// A plan is executable only when the graph is a clean DAG.
    pub fn is_executable(&self) -> bool {
        self.cycle.is_empty() && !self.order.is_empty()
    }
}

/// Repos that directly depend on `repo` (one hop): X depends on `repo` when X
/// declares a dependency on a crate `repo` produces.
fn direct_dependents(graphs: &[RepoGraph], repo: &str) -> Vec<String> {
    let Some(target) = graphs.iter().find(|g| g.repo == repo) else {
        return vec![];
    };
    let mut out: Vec<String> = graphs
        .iter()
        .filter(|g| g.repo != repo && g.deps.iter().any(|d| target.produces.contains(d)))
        .map(|g| g.repo.clone())
        .collect();
    out.sort();
    out
}

/// Build the stage plan: topo publish order + per-repo verify (direct dependents).
pub fn plan_stage(graphs: &[RepoGraph], registry: &str, branch: &str) -> StagePlan {
    let topo = publish_order(graphs);
    let order = topo
        .order
        .iter()
        .map(|repo| StageStep { repo: repo.clone(), verify: direct_dependents(graphs, repo) })
        .collect();
    StagePlan { registry: registry.to_string(), branch: branch.to_string(), order, cycle: topo.cycle }
}

/// Human-readable plan (the dry-run output).
pub fn format_plan(p: &StagePlan) -> String {
    let mut s = String::new();
    s.push_str("nornir release stage — plan (dry-run)\n\n");
    s.push_str(&format!("  registry: {}\n", p.registry));
    s.push_str(&format!("  branch:   {}\n\n", p.branch));
    if !p.cycle.is_empty() {
        s.push_str(&format!(
            "  ⚠ dependency cycle — NOT executable until resolved: {}\n\n",
            p.cycle.join(", ")
        ));
    }
    s.push_str("  Publish order (dependencies first):\n");
    for (i, step) in p.order.iter().enumerate() {
        s.push_str(&format!("    {}. cargo publish {} → /sparring\n", i + 1, step.repo));
        if !step.verify.is_empty() {
            s.push_str(&format!("       verify (build from /sparring): {}\n", step.verify.join(", ")));
        }
    }
    if p.is_executable() {
        s.push_str("\n  → green plan; run with --execute to publish into /sparring, then promote.\n");
    }
    s
}

// ─────────────────────── execution (steps 1–3) ───────────────────────

use std::collections::BTreeMap;
use std::path::{Path, PathBuf};
use std::process::Command;
#[cfg(not(feature = "embed-holger"))]
use std::process::{Child, Stdio};

use anyhow::{Context, Result};

/// Cargo config the cascade runs under: defines the `sparring` registry to publish
/// INTO, and source-replaces crates.io with it so a dependent's build resolves the
/// just-published workspace crates from `/sparring` (everything else falls through
/// `/sparring`'s crates.io upstream).
pub fn cargo_config_toml(http_addr: &str) -> String {
    format!(
        r#"[registries.sparring]
index = "sparse+http://{http_addr}/sparring/index/"

[source.crates-io]
replace-with = "sparring-mirror"

[source.sparring-mirror]
registry = "sparse+http://{http_addr}/sparring/index/"

[net]
retry = 2
"#
    )
}

/// The embedded holger subprocess — killed on drop. Only the lean
/// `--no-default-features` build uses this; the default build embeds holger
/// in-process (`crate::holger_embed`), so it's compiled out when `embed-holger`
/// is on.
#[cfg(not(feature = "embed-holger"))]
struct HolgerProc(Child);
#[cfg(not(feature = "embed-holger"))]
impl Drop for HolgerProc {
    fn drop(&mut self) {
        let _ = self.0.kill();
        let _ = self.0.wait();
    }
}

#[cfg(not(feature = "embed-holger"))]
fn spawn_holger(holger_bin: &Path, data_dir: &Path, grpc: &str, http: &str) -> Result<HolgerProc> {
    let child = Command::new(holger_bin)
        .arg("dev-pair")
        .arg("--data")
        .arg(data_dir)
        .args(["--grpc", grpc, "--http", http])
        .stdout(Stdio::null())
        .stderr(Stdio::null())
        .spawn()
        .with_context(|| format!("spawn holger dev-pair via {}", holger_bin.display()))?;
    Ok(HolgerProc(child))
}

/// Poll the HTTP gateway until it serves (or give up after ~15s).
#[cfg(not(feature = "embed-holger"))]
fn wait_ready(http_addr: &str) -> Result<()> {
    let url = format!("http://{http_addr}/cache/index/config.json");
    for _ in 0..60 {
        if ureq::get(&url)
            .timeout(std::time::Duration::from_millis(500))
            .call()
            .is_ok()
        {
            return Ok(());
        }
        std::thread::sleep(std::time::Duration::from_millis(250));
    }
    anyhow::bail!("holger dev-pair never became ready at {url}")
}

#[derive(Debug, Default)]
pub struct StageOutcome {
    /// Repos whose crates published into /sparring.
    pub published: Vec<String>,
    /// Repos already present in /sparring at this version — a benign skip (the crate
    /// is staged and still build-verifies). NOT an error: re-running a rehearsal
    /// without a version bump lands here, exactly as crates.io would reject a re-publish.
    pub already_staged: Vec<String>,
    /// Verify targets that built against /sparring.
    pub verified: Vec<String>,
    /// Non-fatal per-step failures (repo: reason).
    pub errors: Vec<String>,
}

/// RAII cleanup for the ephemeral release branches the rehearsal cuts. Records each
/// repo's branch BEFORE `checkout -B <release>`, and on Drop — success, `?`-early-return,
/// OR panic — switches back to the original branch and deletes the staging branch, so a
/// rehearsal leaves NO trace.
///
/// CRITICAL: it must NEVER blanket-discard the working tree (`git checkout -- .`) — that
/// would eat the user's *uncommitted* edits (it once ate this very file's). The staging
/// branch is cut from the original with no commits, so switching back carries any
/// uncommitted changes cleanly; we then restore only the generated `Cargo.lock` (the one
/// file `cargo publish` churns), leaving every other change untouched.
pub(crate) struct BranchGuard {
    /// `(repo_path, original_branch)` captured pre-cut, restored newest-first on Drop.
    restores: Vec<(PathBuf, String)>,
    /// The ephemeral branch to delete after restoring (e.g. `release/staging`).
    branch: String,
}

impl BranchGuard {
    pub(crate) fn new(branch: &str) -> Self {
        BranchGuard { restores: Vec::new(), branch: branch.to_string() }
    }

    /// Capture `path`'s current branch so it can be restored later. Skips capture when
    /// the repo is already on the staging branch or HEAD can't be read (best-effort).
    pub(crate) fn capture(&mut self, path: &Path) {
        if let Ok(o) = Command::new("git")
            .arg("-C")
            .arg(path)
            .args(["rev-parse", "--abbrev-ref", "HEAD"])
            .output()
        {
            let prev = String::from_utf8_lossy(&o.stdout).trim().to_string();
            if !prev.is_empty() && prev != self.branch {
                self.restores.push((path.to_path_buf(), prev));
            }
        }
    }
}

impl Drop for BranchGuard {
    fn drop(&mut self) {
        for (path, prev) in self.restores.iter().rev() {
            // Switch back — uncommitted changes (the user's work + the publish's
            // Cargo.lock churn) carry across cleanly since the staging branch was cut
            // from here with no commits. Then drop the ephemeral branch and restore ONLY
            // Cargo.lock (the publish artifact). Never `checkout -- .`.
            let _ = Command::new("git").arg("-C").arg(path).args(["checkout", prev]).status();
            let _ = Command::new("git")
                .arg("-C")
                .arg(path)
                .args(["branch", "-D", &self.branch])
                .status();
            // `.output()` swallows the harmless "pathspec 'Cargo.lock' did not match"
            // stderr when the repo tracks no lockfile (e.g. a library workspace).
            let _ = Command::new("git")
                .arg("-C")
                .arg(path)
                .args(["checkout", "--", "Cargo.lock"])
                .output();
            eprintln!("stage: restored {}{prev} (release branch cleaned)", path.display());
        }
    }
}

/// Steps 1–3: spawn the embedded holger, cut the release branch per repo, then in
/// plan order `cargo publish --workspace` each repo into `/sparring`, then
/// `cargo build` each verify target against `/sparring`. Stops before seal/promote.
/// holger is torn down on return. Per-repo failures are collected, not fatal, so
/// the outcome shows how far the rehearsal got.
pub fn execute(
    plan: &StagePlan,
    repo_paths: &BTreeMap<String, PathBuf>,
    _holger_bin: &Path,
    data_dir: &Path,
    grpc: &str,
    http: &str,
) -> Result<StageOutcome> {
    if !plan.is_executable() {
        anyhow::bail!("stage plan not executable (dependency cycle: {})", plan.cycle.join(", "));
    }
    std::fs::create_dir_all(data_dir)?;
    let cfg_path = data_dir.join("cargo-config.toml");
    std::fs::write(&cfg_path, cargo_config_toml(http))?;

    // Bring up the /cache + /sparring dev pair. Default build: in-process (the
    // nornir⇆holger marriage). Lean `--no-default-features` build: subprocess.
    // `_holger` stays alive until this fn returns, then the rehearsal registry is
    // torn down (runtime dropped / child killed).
    #[cfg(feature = "embed-holger")]
    let _holger = {
        let h = crate::holger_embed::EmbeddedHolger::start(&data_dir.join("registry"), grpc, http)
            .context("start embedded holger")?;
        h.wait_ready(std::time::Duration::from_secs(15))
            .context("embedded holger did not become ready")?;
        h
    };
    #[cfg(not(feature = "embed-holger"))]
    let _holger = {
        let p = spawn_holger(_holger_bin, &data_dir.join("registry"), grpc, http)?;
        wait_ready(http)?;
        p
    };
    eprintln!("stage: holger /cache + /sparring ready on http://{http}");

    let mut out = StageOutcome::default();
    // Auto-restore the working trees when the rehearsal ends (Drop runs on every exit
    // path, so no repo is left stranded on `release/staging`).
    let mut guard = BranchGuard::new(&plan.branch);

    // 1 + 2 — cut branch, publish each repo's crates into /sparring in plan order.
    for step in &plan.order {
        let Some(path) = repo_paths.get(&step.repo) else { continue };
        guard.capture(path);
        let _ = Command::new("git")
            .arg("-C")
            .arg(path)
            .args(["checkout", "-B", &plan.branch])
            .status(); // best-effort branch isolation
        let res = Command::new("cargo")
            .current_dir(path)
            .args(["publish", "--workspace", "--no-verify", "--allow-dirty", "--registry", "sparring"])
            .arg("--config")
            .arg(&cfg_path)
            .env("CARGO_REGISTRIES_SPARRING_TOKEN", "stage-rehearsal")
            .output()
            .with_context(|| format!("cargo publish {}", step.repo))?;
        if res.status.success() {
            out.published.push(step.repo.clone());
            eprintln!("stage: published {} → /sparring", step.repo);
        } else {
            let err = String::from_utf8_lossy(&res.stderr);
            // crates.io / sparring both reject re-publishing an existing version. For a
            // rehearsal that's a benign "already staged" — surface it, then let the
            // verify step still prove it builds. A real publish failure (compile, auth,
            // missing metadata) is a genuine error.
            if err.contains("already exists") || err.contains("already uploaded") {
                out.already_staged.push(step.repo.clone());
                eprintln!("stage: {} already staged in /sparring (skip; bump to re-stage)", step.repo);
            } else {
                eprint!("{err}");
                out.errors.push(format!("{}: cargo publish failed ({})", step.repo, res.status));
            }
        }
    }

    // 3 — verify each dependent builds against /sparring (unique targets).
    let mut seen = std::collections::BTreeSet::new();
    for step in &plan.order {
        for dep in &step.verify {
            if !seen.insert(dep.clone()) {
                continue;
            }
            let Some(path) = repo_paths.get(dep) else { continue };
            let status = Command::new("cargo")
                .current_dir(path)
                .args(["build", "--quiet"])
                .arg("--config")
                .arg(&cfg_path)
                .status()
                .with_context(|| format!("cargo build {dep}"))?;
            if status.success() {
                out.verified.push(dep.clone());
                eprintln!("stage: verified {} builds from /sparring", dep);
            } else {
                out.errors.push(format!("{dep}: verify build failed ({status})"));
            }
        }
    }

    Ok(out)
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::collections::BTreeSet;

    fn graph(repo: &str, produces: &[&str], deps: &[&str]) -> RepoGraph {
        RepoGraph {
            repo: repo.to_string(),
            produces: produces.iter().map(|s| s.to_string()).collect::<BTreeSet<_>>(),
            deps: deps.iter().map(|s| s.to_string()).collect::<BTreeSet<_>>(),
        }
    }

    /// The plan publishes in dependency order, and each base repo lists the
    /// dependents to verify: znippy & skade before nornir; both list nornir.
    #[test]
    fn plan_orders_topologically_with_verify_targets() {
        let graphs = [
            graph("znippy", &["znippy-common"], &["serde"]),
            graph("skade", &["skade-katalog"], &["arrow"]),
            graph("nornir", &["nornir"], &["znippy-common", "skade-katalog"]),
        ];
        let plan = plan_stage(&graphs, "sparse+http://h/sparring/index/", "release/arrow-58");
        assert!(plan.is_executable(), "clean DAG must be executable");
        assert_eq!(plan.branch, "release/arrow-58");

        let order: Vec<&str> = plan.order.iter().map(|s| s.repo.as_str()).collect();
        let pos = |r: &str| order.iter().position(|x| *x == r).unwrap();
        assert!(pos("znippy") < pos("nornir") && pos("skade") < pos("nornir"));

        let znippy = plan.order.iter().find(|s| s.repo == "znippy").unwrap();
        assert_eq!(znippy.verify, vec!["nornir"], "publishing znippy must verify nornir");
        let nornir = plan.order.iter().find(|s| s.repo == "nornir").unwrap();
        assert!(nornir.verify.is_empty(), "nothing depends on nornir here");
    }

    #[test]
    fn cargo_config_targets_sparring_and_replaces_crates_io() {
        let c = cargo_config_toml("127.0.0.1:18464");
        assert!(c.contains("[registries.sparring]"), "defines the publish registry");
        assert!(c.contains("sparse+http://127.0.0.1:18464/sparring/index/"));
        assert!(c.contains(r#"replace-with = "sparring-mirror""#), "resolves deps via /sparring");
    }

    #[test]
    fn plan_with_cycle_is_not_executable() {
        let graphs = [
            graph("a", &["a-crate"], &["b-crate"]),
            graph("b", &["b-crate"], &["a-crate"]),
        ];
        let plan = plan_stage(&graphs, "reg", "rel");
        assert!(!plan.is_executable(), "a cycle must block execution");
        assert_eq!(plan.cycle.len(), 2);
    }
}