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

            
35
use std::fmt;
36
use std::str::FromStr;
37

            
38
use anyhow::{Context, Result, bail};
39

            
40
pub 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)]
44
pub enum Kind {
45
    Coverage,
46
    Release,
47
}
48

            
49
impl Kind {
50
5
    pub fn as_str(self) -> &'static str {
51
5
        match self {
52
3
            Kind::Coverage => "coverage",
53
2
            Kind::Release => "release",
54
        }
55
5
    }
56
}
57

            
58
impl fmt::Display for Kind {
59
5
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
60
5
        f.write_str(self.as_str())
61
5
    }
62
}
63

            
64
impl FromStr for Kind {
65
    type Err = anyhow::Error;
66

            
67
3
    fn from_str(s: &str) -> Result<Self> {
68
3
        match s {
69
2
            "coverage" => Ok(Kind::Coverage),
70
1
            "release" => Ok(Kind::Release),
71
            other => bail!("unknown artifact kind: {other}"),
72
        }
73
3
    }
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)]
85
pub struct Identity {
86
    pub commit: String,
87
    pub run_id: String,
88
    pub run_attempt: String,
89
    pub builder: String,
90
}
91

            
92
impl 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
5
    pub fn from_source(lookup: impl Fn(&str) -> Option<String>) -> Result<Self> {
104
13
        let required = |key: &str| -> Result<String> {
105
13
            match lookup(key) {
106
12
                Some(value) if !value.is_empty() => Ok(value),
107
2
                _ => bail!("{key} is required for artifact paths and was empty or unset"),
108
            }
109
13
        };
110

            
111
5
        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
5
        let run_id = required("GITHUB_RUN_ID")?;
117
3
        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
3
        if !builder.contains("@sha256:") {
123
1
            bail!(
124
1
                "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
2
        }
128

            
129
        Ok(Self {
130
2
            commit,
131
2
            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
2
            run_attempt: lookup("GITHUB_RUN_ATTEMPT")
135
1
                .filter(|value| !value.is_empty())
136
1
                .unwrap_or_else(|| "unknown".into()),
137
2
            builder,
138
        })
139
5
    }
140

            
141
    /// `s3://<bucket>/<commit>/<run_id>` — no trailing slash.
142
1
    pub fn prefix(&self, bucket: &str) -> String {
143
1
        format!("s3://{bucket}/{}/{}", self.commit, self.run_id)
144
1
    }
145
}
146

            
147
/// A published object: what it is, what it hashes to, and what produced it.
148
#[derive(Debug, Clone, PartialEq, Eq)]
149
pub struct Meta {
150
    pub kind: Kind,
151
    pub sha256: String,
152
    pub bytes: u64,
153
    pub identity: Identity,
154
}
155

            
156
impl Meta {
157
    /// Content-addressed key. The hash is in the name, so republishing
158
    /// different bytes cannot land on the same object.
159
3
    pub fn object_key(&self) -> String {
160
3
        format!("{}-{}.tar", self.kind, self.sha256)
161
3
    }
162

            
163
1
    pub fn meta_key(kind: Kind) -> String {
164
1
        format!("{kind}.meta")
165
1
    }
166

            
167
    /// Bucket-relative key of the newest master meta of a kind.
168
1
    pub fn latest_key(kind: Kind) -> String {
169
1
        format!("latest/{}", Self::meta_key(kind))
170
1
    }
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
1
    pub fn to_text(&self) -> String {
175
1
        format!(
176
            "kind={}\nobject={}\nsha256={}\nbytes={}\ncommit={}\nrun_id={}\nrun_attempt={}\nbuilder={}\n",
177
1
            self.kind,
178
1
            self.object_key(),
179
1
            self.sha256,
180
1
            self.bytes,
181
1
            self.identity.commit,
182
1
            self.identity.run_id,
183
1
            self.identity.run_attempt,
184
1
            self.identity.builder,
185
        )
186
1
    }
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
3
    pub fn from_text(text: &str) -> Result<Self> {
194
18
        let get = |key: &str| -> Result<String> {
195
18
            text.lines()
196
77
                .find_map(|line| line.strip_prefix(&format!("{key}=")))
197
18
                .map(str::to_owned)
198
1
                .with_context(|| format!("meta is missing {key}"))
199
18
        };
200

            
201
        Ok(Self {
202
3
            kind: get("kind")?.parse()?,
203
3
            sha256: get("sha256")?,
204
3
            bytes: get("bytes")?
205
                .parse()
206
3
                .context("meta bytes is not a number")?,
207
            identity: Identity {
208
3
                commit: get("commit")?,
209
2
                run_id: get("run_id")?,
210
2
                run_attempt: get("run_attempt")?,
211
2
                builder: get("builder")?,
212
            },
213
        })
214
3
    }
215
}
216

            
217
#[cfg(test)]
218
mod tests;