Skip to main content

xtask/
artifact.rs

1//! The artifact layout: object keys, per-kind provenance, and the manifest.
2//!
3//! One definition, used by the producers, by finalize and by deploy. Two places
4//! that each "know" the layout is how a producer and a consumer drift apart
5//! without anyone noticing, which is why this is a module with types rather
6//! than a string built in three scripts.
7//!
8//! Layout:
9//!
10//! ```text
11//! s3://<bucket>/<commit>/<run_id>/
12//!     <kind>-<sha256>.tar     the payload, content-addressed
13//!     <kind>.meta             pointer + provenance for that kind
14//!     nomisync-manifest.json  written by finalize, and only by finalize
15//! s3://<bucket>/latest/coverage.meta
16//!                             copy of the newest master coverage meta
17//! ```
18//!
19//! **Content-addressed** because the key contains the hash of the bytes: an
20//! object can never be overwritten with different content, since different
21//! bytes are a different key. That structurally removes the window where a
22//! manifest is valid while the bytes behind a mutable name changed underneath.
23//!
24//! **Run-scoped, not attempt-scoped.** A re-run keeps its run id and only
25//! bumps the attempt, so a failed-only rerun of release lands under the same
26//! prefix as the first attempt, and mixing across runs or commits is
27//! unreachable, because the prefix contains both.
28//!
29//! **Coverage is a report, not part of the deploy.** The deploy waits for the
30//! tests in `checks`, not for coverage, so finalize writes a manifest of the
31//! release alone. Each master coverage run also copies its meta to
32//! `latest/coverage.meta`, and the deploy overlays whichever report that names:
33//! the newest finished one, usually one commit behind the release.
34
35use std::fmt;
36use std::str::FromStr;
37
38use anyhow::{Context, Result, bail};
39
40pub const MANIFEST_NAME: &str = "nomisync-manifest.json";
41
42/// Which half of the artifact pair an object is.
43#[derive(Debug, Clone, Copy, PartialEq, Eq)]
44pub enum Kind {
45    Coverage,
46    Release,
47}
48
49impl Kind {
50    pub fn as_str(self) -> &'static str {
51        match self {
52            Kind::Coverage => "coverage",
53            Kind::Release => "release",
54        }
55    }
56}
57
58impl fmt::Display for Kind {
59    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
60        f.write_str(self.as_str())
61    }
62}
63
64impl FromStr for Kind {
65    type Err = anyhow::Error;
66
67    fn from_str(s: &str) -> Result<Self> {
68        match s {
69            "coverage" => Ok(Kind::Coverage),
70            "release" => Ok(Kind::Release),
71            other => bail!("unknown artifact kind: {other}"),
72        }
73    }
74}
75
76/// Who built an artifact, and in which run.
77///
78/// Read from the environment rather than defaulted. `ci-build` derives Job
79/// *names* from `GITHUB_RUN_NUMBER` with a `:-0` fallback, which is right for a
80/// name and catastrophic for a path — it would collapse every run onto one
81/// prefix and reopen exactly the mixing this layout prevents. A missing value
82/// is an error here, and this reads the run id rather than reusing that
83/// defaulted number.
84#[derive(Debug, Clone, PartialEq, Eq)]
85pub struct Identity {
86    pub commit: String,
87    pub run_id: String,
88    pub run_attempt: String,
89    pub builder: String,
90}
91
92impl Identity {
93    /// Reads identity from the process environment, failing closed.
94    pub fn from_env() -> Result<Self> {
95        Self::from_source(|key| std::env::var(key).ok())
96    }
97
98    /// Reads identity from an arbitrary lookup.
99    ///
100    /// Taking the source as a parameter keeps the tests off the process
101    /// environment: `set_var` is `unsafe` and racy across threads, and cargo
102    /// runs a crate's tests in one process.
103    pub fn from_source(lookup: impl Fn(&str) -> Option<String>) -> Result<Self> {
104        let required = |key: &str| -> Result<String> {
105            match lookup(key) {
106                Some(value) if !value.is_empty() => Ok(value),
107                _ => bail!("{key} is required for artifact paths and was empty or unset"),
108            }
109        };
110
111        let commit = required("SHA")?;
112        // GITHUB_RUN_ID, verified populated in a real build pod (362 while the
113        // run number was 12), and globally unique where the number is only
114        // sequential per repository. A re-run keeps its id and increments the
115        // attempt, which is exactly the prefix behaviour this layout wants.
116        let run_id = required("GITHUB_RUN_ID")?;
117        let builder = required("RUST_BUILDER_IMAGE_REF")?;
118
119        // The digest requirement lives with the producer, not in the shared
120        // ci-build orchestrator: other projects on that orchestrator pin tags
121        // and must keep working.
122        if !builder.contains("@sha256:") {
123            bail!(
124                "RUST_BUILDER_IMAGE_REF is not digest-pinned: {builder}\n\
125                 a tag can be moved, so it cannot prove two producers used one image"
126            );
127        }
128
129        Ok(Self {
130            commit,
131            run_id,
132            // Best-effort: unlike the others this is provenance detail, not a
133            // path component, so an platform that does not supply it still works.
134            run_attempt: lookup("GITHUB_RUN_ATTEMPT")
135                .filter(|value| !value.is_empty())
136                .unwrap_or_else(|| "unknown".into()),
137            builder,
138        })
139    }
140
141    /// `s3://<bucket>/<commit>/<run_id>` — no trailing slash.
142    pub fn prefix(&self, bucket: &str) -> String {
143        format!("s3://{bucket}/{}/{}", self.commit, self.run_id)
144    }
145}
146
147/// A published object: what it is, what it hashes to, and what produced it.
148#[derive(Debug, Clone, PartialEq, Eq)]
149pub struct Meta {
150    pub kind: Kind,
151    pub sha256: String,
152    pub bytes: u64,
153    pub identity: Identity,
154}
155
156impl Meta {
157    /// Content-addressed key. The hash is in the name, so republishing
158    /// different bytes cannot land on the same object.
159    pub fn object_key(&self) -> String {
160        format!("{}-{}.tar", self.kind, self.sha256)
161    }
162
163    pub fn meta_key(kind: Kind) -> String {
164        format!("{kind}.meta")
165    }
166
167    /// Bucket-relative key of the newest master meta of a kind.
168    pub fn latest_key(kind: Kind) -> String {
169        format!("latest/{}", Self::meta_key(kind))
170    }
171
172    /// Flat `key=value`, because a meta is read by the deploy container too and
173    /// a JSON parser there is a cost with no benefit at this size.
174    pub fn to_text(&self) -> String {
175        format!(
176            "kind={}\nobject={}\nsha256={}\nbytes={}\ncommit={}\nrun_id={}\nrun_attempt={}\nbuilder={}\n",
177            self.kind,
178            self.object_key(),
179            self.sha256,
180            self.bytes,
181            self.identity.commit,
182            self.identity.run_id,
183            self.identity.run_attempt,
184            self.identity.builder,
185        )
186    }
187
188    /// Parses a meta fetched from object storage.
189    ///
190    /// Parsed, never evaluated: the previous shell version had to be careful not
191    /// to `source` a file that came off the network. Here that class of mistake
192    /// is not expressible.
193    pub fn from_text(text: &str) -> Result<Self> {
194        let get = |key: &str| -> Result<String> {
195            text.lines()
196                .find_map(|line| line.strip_prefix(&format!("{key}=")))
197                .map(str::to_owned)
198                .with_context(|| format!("meta is missing {key}"))
199        };
200
201        Ok(Self {
202            kind: get("kind")?.parse()?,
203            sha256: get("sha256")?,
204            bytes: get("bytes")?
205                .parse()
206                .context("meta bytes is not a number")?,
207            identity: Identity {
208                commit: get("commit")?,
209                run_id: get("run_id")?,
210                run_attempt: get("run_attempt")?,
211                builder: get("builder")?,
212            },
213        })
214    }
215}
216
217#[cfg(test)]
218mod tests;