1
//! The artifact-producing phases.
2
//!
3
//! Ported from `ci/scripts/release-artifact.sh`. The assertions are the part
4
//! worth keeping: each one exists because something once shipped wrong, and
5
//! several of them are the only thing standing between a green run and an image
6
//! that is missing half its content.
7

            
8
use std::path::{Path, PathBuf};
9

            
10
use anyhow::{Context, Result, bail};
11

            
12
use crate::artifact::{Identity, Kind};
13
use crate::clean::{remove_dir_if_present, remove_file_if_present};
14
use crate::heartbeat::Heartbeat;
15
use crate::publish::Store;
16
use crate::watchdog::{Termination, run_supervised};
17

            
18
pub(crate) const DOC_DIR: &str = "web/static/doc";
19

            
20
/// Runs a command, inheriting stdio so its output reaches the job log.
21
///
22
/// A termination signal stops it and fails the call, so `produce` unwinds and
23
/// drops its cluster.
24
6
pub(crate) fn run(program: &str, args: &[&str], env: &[(&str, &str)]) -> Result<()> {
25
6
    let args: Vec<String> = args.iter().map(ToString::to_string).collect();
26
6
    run_supervised(program, &args, env, &Termination::watch()?)
27
6
}
28

            
29
/// rustdoc, the org exports, and the static musl binaries.
30
///
31
/// A rustdoc warning fails the build.
32
1
pub fn build(heartbeat: &Heartbeat, database_url: &str) -> Result<()> {
33
1
    let doc_dir = PathBuf::from(DOC_DIR);
34

            
35
1
    heartbeat.phase("rustdoc");
36
1
    for stale in ["rustdoc", "scripts", "nomiscript"] {
37
3
        remove_dir_if_present(&doc_dir.join(stale))?;
38
    }
39
1
    remove_file_if_present(&doc_dir.join("disdoc.html"))?;
40
    // cargo doc recompiles the sqlx macros, so this phase needs a live schema
41
    // even though it produces no test results.
42
1
    run(
43
1
        "cargo",
44
1
        &["doc", "--workspace", "--all-features", "--no-deps"],
45
1
        &[
46
1
            ("DATABASE_URL", database_url),
47
1
            ("RUSTDOCFLAGS", "-D warnings"),
48
1
        ],
49
1
    )?;
50
    std::fs::rename("target/doc", doc_dir.join("rustdoc"))
51
        .context("cannot move the rustdoc tree into the static dir")?;
52

            
53
    heartbeat.phase("org exports");
54
    for dir in ["scripts", "nomiscript"] {
55
        std::fs::create_dir_all(doc_dir.join(dir))
56
            .with_context(|| format!("cannot make the {dir} doc dir"))?;
57
    }
58
    export_org(Path::new("doc/disdoc.org"))?;
59
    std::fs::rename("doc/disdoc.html", doc_dir.join("disdoc.html"))
60
        .context("cannot move disdoc.html")?;
61
    export_dir(Path::new("doc/scripts"), &doc_dir.join("scripts"))?;
62
    export_dir(Path::new("doc/nomiscript"), &doc_dir.join("nomiscript"))?;
63

            
64
    heartbeat.phase("musl release build");
65
    // CXX stays because -sys crates that build C++ need it, and the image has no
66
    // x86_64-linux-musl-g++ — only the gcc driver.
67
    run(
68
        "cargo",
69
        &[
70
            "build",
71
            "--release",
72
            "--target",
73
            "x86_64-unknown-linux-musl",
74
            "-p",
75
            "web",
76
            "-p",
77
            "sshd",
78
            "-p",
79
            "fleet-migrator",
80
        ],
81
        &[
82
            ("SQLX_OFFLINE", "true"),
83
            ("CC_x86_64_unknown_linux_musl", "x86_64-linux-musl-gcc"),
84
            ("CXX_x86_64_unknown_linux_musl", "x86_64-linux-musl-gcc"),
85
        ],
86
    )?;
87

            
88
    std::fs::copy(
89
        "target/x86_64-unknown-linux-musl/release/web",
90
        "release-web",
91
    )
92
    .context("cannot stage release-web")?;
93
    std::fs::copy(
94
        "target/x86_64-unknown-linux-musl/release/nomisync-sshd",
95
        "release-sshd",
96
    )
97
    .context("cannot stage release-sshd")?;
98
    std::fs::copy(
99
        "target/x86_64-unknown-linux-musl/release/nomisync-fleet-migrate",
100
        "release-fleet-migrate",
101
    )
102
    .context("cannot stage release-fleet-migrate")?;
103

            
104
    verify_binaries()?;
105
    stage_licences()?;
106
    Ok(())
107
1
}
108

            
109
/// One emacs invocation PER FILE.
110
///
111
/// `emacs --batch a.org b.org --eval (org-html-export-to-html)` runs the eval
112
/// once, against the last visited buffer, so a glob silently publishes a single
113
/// page — the retired Drone pipeline shipped 1 of 4 script pages exactly that way.
114
fn export_org(org: &Path) -> Result<()> {
115
    run(
116
        "emacs",
117
        &[
118
            "-q",
119
            "--batch",
120
            &org.to_string_lossy(),
121
            "-l",
122
            "ox-html",
123
            "--eval",
124
            "(progn (org-babel-do-load-languages (quote org-babel-load-languages) (quote ((emacs-lisp . t) (shell . t)))) (setq org-confirm-babel-evaluate nil) (setq org-html-validation-link nil) (org-html-export-to-html))",
125
            "-f",
126
            "save-buffer",
127
            "-f",
128
            "kill-emacs",
129
        ],
130
        &[],
131
    )
132
}
133

            
134
fn export_dir(src: &Path, dest: &Path) -> Result<()> {
135
    let orgs: Vec<PathBuf> = std::fs::read_dir(src)
136
        .with_context(|| format!("cannot read {}", src.display()))?
137
        .filter_map(Result::ok)
138
        .map(|entry| entry.path())
139
        .filter(|path| path.extension().is_some_and(|ext| ext == "org"))
140
        .collect();
141
    if orgs.is_empty() {
142
        bail!("no org files in {}", src.display());
143
    }
144

            
145
    for org in &orgs {
146
        export_org(org)?;
147
    }
148

            
149
    // Count what was produced, not what was attempted.
150
    let produced: Vec<PathBuf> = std::fs::read_dir(src)?
151
        .filter_map(Result::ok)
152
        .map(|entry| entry.path())
153
        .filter(|path| path.extension().is_some_and(|ext| ext == "html"))
154
        .collect();
155
    if produced.len() != orgs.len() {
156
        bail!(
157
            "{}: exported {} of {} pages",
158
            src.display(),
159
            produced.len(),
160
            orgs.len()
161
        );
162
    }
163
    for page in produced {
164
        let target = dest.join(page.file_name().context("html page has no file name")?);
165
        std::fs::rename(&page, &target)
166
            .with_context(|| format!("cannot move {}", page.display()))?;
167
    }
168
    println!(">> exported {} pages from {}", orgs.len(), src.display());
169
    Ok(())
170
}
171

            
172
/// The assertions that prove the shipped binaries are what we think they are.
173
fn verify_binaries() -> Result<()> {
174
    for binary in ["release-web", "release-sshd", "release-fleet-migrate"] {
175
        let bytes = std::fs::read(binary).with_context(|| format!("cannot read {binary}"))?;
176

            
177
        // Coverage instrumentation in a shipped binary is invisible until
178
        // production is slow and writing .profraw files.
179
        if contains(&bytes, b"__llvm_profile") {
180
            bail!(
181
                "{binary} contains coverage instrumentation — RUSTFLAGS leaked out of the coverage phase"
182
            );
183
        }
184

            
185
        // plotters prefers its `ttf` backend when both are enabled, and that
186
        // backend dlopens fontconfig — impossible in a static musl binary, so
187
        // chart rendering PANICS rather than degrading. The builder still
188
        // carries the fontconfig packages, which would let such a regression
189
        // build cleanly and only fail inside the scratch image.
190
        if binary == "release-web" && contains(&bytes, b"fontconfig") {
191
            bail!(
192
                "release-web references fontconfig — plotters' ttf backend is back; it cannot work in the scratch image"
193
            );
194
        }
195
    }
196

            
197
    // The generated trees are gitignored, so their absence here means a phase
198
    // above failed quietly. The deploy job asserts the same on the unpacked side.
199
    //
200
    // NOT coverage: that is the coverage job's output, published as its own
201
    // artifact and overlaid at deploy time. Asserting it here is what made the
202
    // first xtask release run fail — the phase had moved, the assertion had not.
203
    for required in ["rustdoc", "scripts", "nomiscript", "disdoc.html"] {
204
        let path = PathBuf::from(DOC_DIR).join(required);
205
        if !path.exists() {
206
            bail!("missing {}", path.display());
207
        }
208
    }
209
    Ok(())
210
}
211

            
212
fn contains(haystack: &[u8], needle: &[u8]) -> bool {
213
    haystack
214
        .windows(needle.len())
215
        .any(|window| window == needle)
216
}
217

            
218
/// release-web embeds DejaVuSans via include_bytes!, and that font's licence
219
/// requires its notice to travel with copies of the font software. web/static is
220
/// copied wholesale into the runtime image, so putting it here makes it ship
221
/// with both the tarball and the image, and be servable.
222
fn stage_licences() -> Result<()> {
223
    let dir = PathBuf::from("web/static/licenses");
224
    std::fs::create_dir_all(&dir).context("cannot make the licenses dir")?;
225
    let target = dir.join("DejaVuSans-LICENSE.txt");
226
    std::fs::copy("plotting/fonts/LICENSE", &target).context("cannot copy the font licence")?;
227
    if std::fs::metadata(&target)?.len() == 0 {
228
        bail!("font licence missing from artifact");
229
    }
230
    Ok(())
231
}
232

            
233
/// Tars the payload for a kind and, when this run holds the write key, publishes it.
234
pub fn package(kind: Kind, heartbeat: &Heartbeat, with_artifacts: bool) -> Result<()> {
235
    heartbeat.phase("packaging");
236

            
237
    let tarball = PathBuf::from(format!("nomisync-{kind}.tar"));
238
    let members: &[&str] = match kind {
239
        // Only the coverage tree, so the two payloads are disjoint by rule and
240
        // the assembler can reject any overlap rather than guess.
241
        Kind::Coverage => &["web/static/doc/coverage"],
242
        Kind::Release => &[
243
            "release-web",
244
            "release-sshd",
245
            "release-fleet-migrate",
246
            "web/static",
247
        ],
248
    };
249
    let mut args = vec!["-czf", &tarball.to_str().context("tarball path")?];
250
    args.extend_from_slice(members);
251
    run("tar", &args, &[])?;
252

            
253
    if !with_artifacts {
254
        println!(">> WITH_ARTIFACTS unset — built and verified, not uploading");
255
        return Ok(());
256
    }
257

            
258
    let identity = Identity::from_env()?;
259
    let store = Store::from_env()?;
260
    let meta = store.publish(kind, &tarball, &identity)?;
261
    println!(
262
        ">> published {} ({} bytes) for {} run {}",
263
        meta.object_key(),
264
        meta.bytes,
265
        identity.commit,
266
        identity.run_id
267
    );
268
    Ok(())
269
}