1
//! The nomisync CI pipeline, as a program.
2
//!
3
//! Invoked from `.forgejo/workflows/ci.yml` as `cargo run -p xtask -- <command>`.
4
//! Deliberately dependency-light: this is the first thing a CI job builds, and
5
//! it starts the database the rest of the workspace compiles against, so it
6
//! must not itself need one.
7
//!
8
//! What stays outside: `.forgejo/scripts/deploy.sh` runs in a kaniko init
9
//! container that has no Rust toolchain, and `ci/builder/build.sh` builds the
10
//! container image this program runs inside.
11

            
12
mod artifact;
13
mod clean;
14
mod coverage;
15
mod deploy_render;
16
mod heartbeat;
17
mod postgres;
18
mod publish;
19
mod release;
20
mod snapshot;
21
mod watchdog;
22

            
23
#[cfg(test)]
24
mod test_support;
25

            
26
use anyhow::{Context, Result};
27
use clap::{Parser, Subcommand};
28

            
29
use artifact::Kind;
30
use heartbeat::Heartbeat;
31

            
32
#[derive(Parser)]
33
#[command(about = "nomisync CI tasks")]
34
struct Cli {
35
    #[command(subcommand)]
36
    command: Command,
37
}
38

            
39
#[derive(Subcommand)]
40
enum Command {
41
    /// Run a command against a throwaway, migrated Postgres.
42
    Postgres {
43
        /// The command and its arguments.
44
        #[arg(required = true, trailing_var_arg = true)]
45
        argv: Vec<String>,
46
    },
47
    /// Instrumented test run, grcov, and the coverage payload.
48
    Coverage,
49
    /// Docs and the static musl binaries, and the release payload.
50
    Release,
51
    /// Restore a prod snapshot into fresh local databases and open every
52
    /// transaction and template in the forms; the databases are dropped after.
53
    CheckForms {
54
        /// Directory with `nomisync.dump` and one `<tenant database>.dump` each.
55
        dumps: std::path::PathBuf,
56
        /// Local Postgres server URL without a database name.
57
        #[arg(long, default_value = "postgres://localhost")]
58
        server: String,
59
    },
60
    /// Restore a prod snapshot as `check-forms` does and list the templates and
61
    /// sources that name accounts or commodities ambiguously or by bare name.
62
    CheckReferences {
63
        /// Directory with `nomisync.dump` and one `<tenant database>.dump` each.
64
        dumps: std::path::PathBuf,
65
        /// Local Postgres server URL without a database name.
66
        #[arg(long, default_value = "postgres://localhost")]
67
        server: String,
68
        /// Directory of shipped source files to scan.
69
        #[arg(long)]
70
        sources: Option<std::path::PathBuf>,
71
    },
72
    /// Verify the published release, then write the manifest.
73
    Finalize,
74
}
75

            
76
5
fn main() -> Result<()> {
77
5
    if let Some(failure) = coverage::wrapper::intercept() {
78
        return Err(failure);
79
5
    }
80
5
    match Cli::parse().command {
81
4
        Command::Postgres { argv } => with_postgres(&argv),
82
        Command::Coverage => produce(Kind::Coverage),
83
1
        Command::Release => produce(Kind::Release),
84
        Command::CheckForms { dumps, server } => snapshot::check_forms(&dumps, &server),
85
        Command::CheckReferences {
86
            dumps,
87
            server,
88
            sources,
89
        } => snapshot::check_references(&dumps, &server, sources.as_deref()),
90
        Command::Finalize => finalize(),
91
    }
92
5
}
93

            
94
/// The single writer of the manifest.
95
///
96
/// Runs after checks and release, holds the write credential, and is
97
/// master-only — a PR run never publishes, so there is nothing to finalize.
98
/// Being the only writer is what removes the concurrent-writer case, and with
99
/// it any need for a conditional put the object store may not support.
100
/// Coverage is not waited for; deploy takes the newest report on its own.
101
fn finalize() -> Result<()> {
102
    let identity = artifact::Identity::from_env()?;
103
    let store = publish::Store::from_env()?;
104
    let work =
105
        tempfile::TempDir::with_prefix("nomisync-finalize").context("cannot make a temp dir")?;
106

            
107
    let release = store.fetch_meta(Kind::Release, &identity, work.path())?;
108
    let local = store.verify_object(&release, &identity, work.path())?;
109
    println!(
110
        ">> verified {} ({} bytes)",
111
        local.file_name().unwrap_or_default().to_string_lossy(),
112
        release.bytes
113
    );
114

            
115
    store.write_manifest(&[release], &identity, work.path())?;
116
    println!(
117
        ">> manifest written for {} run {}",
118
        identity.commit, identity.run_id
119
    );
120
    Ok(())
121
}
122

            
123
/// True only where the workflow decided this run may hold the artifacts key —
124
/// master. A PR run builds and verifies everything with no credential mounted.
125
fn with_artifacts() -> bool {
126
    std::env::var("WITH_ARTIFACTS").as_deref() == Ok("1")
127
}
128

            
129
1
fn produce(kind: Kind) -> Result<()> {
130
    // The heartbeat starts before the database, so the pulse also covers initdb
131
    // and the migrations. Nesting it inside meant a hung startup could still go
132
    // quiet for longer than Forgejo tolerates.
133
1
    let heartbeat = Heartbeat::start();
134
1
    heartbeat.phase("starting postgres");
135

            
136
    // Both kinds need it: the coverage run executes the suite, and `cargo doc`
137
    // recompiles the sqlx macros.
138
1
    let (_termination, database) = watched_cluster()?;
139
1
    let url = database.database_url();
140

            
141
1
    match kind {
142
        Kind::Coverage => coverage::run_coverage(&heartbeat, &url)?,
143
1
        Kind::Release => release::build(&heartbeat, &url)?,
144
    }
145
    release::package(kind, &heartbeat, with_artifacts())
146
1
}
147

            
148
/// Watches for termination signals, then starts the cluster, so a signal that
149
/// arrives at any point afterwards unwinds and drops it instead of leaking it.
150
5
fn watched_cluster() -> Result<(watchdog::Termination, postgres::Postgres)> {
151
5
    let termination = watchdog::Termination::watch()?;
152
5
    let runtime = tokio::runtime::Builder::new_current_thread()
153
5
        .enable_all()
154
5
        .build()
155
5
        .context("cannot build a tokio runtime")?;
156
5
    let database = runtime.block_on(postgres::start())?;
157
5
    Ok((termination, database))
158
5
}
159

            
160
/// Starts Postgres, exports DATABASE_URL, and runs the given command.
161
///
162
/// The cluster stops when `Postgres` drops, including on the error paths.
163
4
fn with_postgres(argv: &[String]) -> Result<()> {
164
4
    let (termination, database) = watched_cluster()?;
165

            
166
4
    let (program, args) = argv.split_first().context("no command given")?;
167
4
    watchdog::run_supervised(
168
4
        program,
169
4
        args,
170
4
        &[("DATABASE_URL", &database.database_url())],
171
4
        &termination,
172
4
    )
173
4
}