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
|
//! The build pipeline (§8).
//!
//! Ten steps, each idempotent and checkpointed in `build_step`. A worker can die
//! at any instant and the pipeline resumes at the next incomplete step with no
//! duplicate side effects (I5). Only the last step is externally visible, and it
//! is serialized per repo (I4).
pub mod publish;
pub mod dispatch;
mod steps;
use std::path::PathBuf;
use crate::config::Config;
use crate::db::{self, builds, Db, Pkgbase};
use crate::db::model::*;
use crate::error::{Error, Result};
/// The approved source identity a build must reproduce.
///
/// For a new version it comes from the candidate; for a manual rebuild it comes
/// from the accepted release, which is what makes I6 true: a rebuild reuses the
/// approved source identity and never needs a new approval.
#[derive(Debug, Clone)]
pub struct SourceIdentity {
pub aur_commit: String,
pub recipe_hash: String,
pub upstream_pins_json: String,
pub source_digests_json: String,
pub epoch: String,
pub pkgver: String,
pub pkgrel: String,
pub identity_hash: String,
}
impl SourceIdentity {
pub fn from_candidate(c: &CandidateRow) -> Self {
Self {
aur_commit: String::new(),
recipe_hash: String::new(),
upstream_pins_json: c.upstream_pins_json.clone(),
source_digests_json: c.source_digests_json.clone(),
epoch: c.epoch.clone(),
pkgver: c.pkgver.clone(),
pkgrel: c.pkgrel.clone(),
identity_hash: c.identity_hash.clone(),
}
}
pub fn from_release(r: &ReleaseRow) -> Self {
Self {
aur_commit: r.aur_commit.clone(),
recipe_hash: r.recipe_hash.clone(),
upstream_pins_json: r.upstream_pins_json.clone(),
source_digests_json: r.source_digests_json.clone(),
epoch: r.epoch.clone(),
pkgver: r.pkgver.clone(),
pkgrel: r.pkgrel.clone(),
identity_hash: String::new(),
}
}
pub fn version(&self) -> String {
crate::pkgver::full_version(&self.epoch, &self.pkgver, &self.pkgrel)
}
}
/// One package produced by the build, as recorded by `collect` and `ingest`.
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct CollectedPkg {
pub name: String,
pub version: String,
pub arch: String,
/// Where the artifact lives: staging until `ingest`, the store afterwards.
pub path: String,
pub digest: String,
pub size: u64,
pub signature_path: Option<String>,
pub depends: Vec<String>,
pub makedepends: Vec<String>,
pub provides: Vec<String>,
pub conflicts: Vec<String>,
/// The full installed set from `.BUILDINFO`, unfiltered (§10.1).
pub installed: Vec<(String, String)>,
}
#[derive(Debug, Clone, Default, serde::Serialize, serde::Deserialize)]
pub struct Collect {
pub packages: Vec<CollectedPkg>,
}
impl Collect {
pub fn load(path: &std::path::Path) -> Result<Self> {
if !path.exists() {
return Ok(Self::default());
}
Ok(serde_json::from_str(&std::fs::read_to_string(path)?)?)
}
pub fn save(&self, path: &std::path::Path) -> Result<()> {
std::fs::write(path, serde_json::to_string_pretty(self)?)?;
Ok(())
}
}
/// Everything a step needs. Built once per build run, cheap to clone handles.
pub struct Ctx {
pub cfg: Config,
pub db: Db,
pub build: builds::BuildRow,
pub pb: Pkgbase,
pub src: SourceIdentity,
pub staging: PathBuf,
pub srcdir: PathBuf,
pub collect_path: PathBuf,
pub log: PathBuf,
pub profile: String,
pub attempt: i64,
}
impl Ctx {
pub fn new(cfg: &Config, db: &Db, build_id: &str) -> Result<Self> {
let build = builds::get(db, build_id)?
.ok_or_else(|| Error::not_found(format!("build {build_id}")))?;
let pb = db::get_pkgbase_by_id(db, build.pkgbase_id)?
.ok_or_else(|| Error::not_found("pkgbase for build"))?;
let src = match build.candidate_id {
Some(cid) => {
let c = crate::review::candidates::candidate_by_id(db, cid)?
.ok_or_else(|| Error::not_found("candidate for build"))?;
let mut si = SourceIdentity::from_candidate(&c);
if let Some(s) = db::snapshot_by_id(db, c.snapshot_id)? {
si.aur_commit = s.aur_commit;
si.recipe_hash = s.recipe_hash;
}
si
}
None => {
let rid = build
.release_id
.ok_or_else(|| Error::invalid("build has neither candidate nor release"))?;
let r = db::release_by_id(db, rid)?
.ok_or_else(|| Error::not_found("release for rebuild"))?;
SourceIdentity::from_release(&r)
}
};
let attempt = build.attempt;
let profile = build.build_profile.clone();
let staging = cfg.staging_build_dir(build_id);
let srcdir = staging.join("src");
let collect_path = staging.join("collect.json");
Ok(Self {
cfg: cfg.clone(),
db: db.clone(),
build,
pb,
src,
staging,
srcdir,
collect_path,
log: cfg.build_log_path(build_id),
profile,
attempt,
})
}
/// Append to the build log; the SSE tail reads this file (§12).
pub fn log_line(&self, line: &str) {
use std::io::Write;
if let Some(parent) = self.log.parent() {
let _ = std::fs::create_dir_all(parent);
}
if let Ok(mut f) = std::fs::OpenOptions::new().create(true).append(true).open(&self.log) {
let _ = writeln!(f, "{line}");
}
}
}
/// What a full run produced.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Outcome {
Succeeded { release_id: i64 },
Failed { step: String, error: String, transient: bool },
Blocked { on: Vec<String> },
Cancelled,
}
/// Run a build to completion, resuming at the first incomplete step (I5).
pub fn run(cfg: &Config, db: &Db, build_id: &str) -> Result<Outcome> {
let ctx = Ctx::new(cfg, db, build_id)?;
db::audit_system(
&db.writer,
"build.start",
"build",
build_id,
serde_json::json!({"pkgbase": ctx.pb.name, "version": ctx.src.version(), "attempt": ctx.attempt}),
)?;
run_with(&ctx)
}
pub fn run_with(ctx: &Ctx) -> Result<Outcome> {
std::fs::create_dir_all(&ctx.staging)?;
for step in crate::db::model::BUILD_STEPS {
if crate::db::builds::cancel_requested(&ctx.db, &ctx.build.id)? {
builds::set_state(&ctx.db, &ctx.build.id, build_state::CANCELLED, Some("cancelled"))?;
return Ok(Outcome::Cancelled);
}
let status = builds::step_status(&ctx.db, &ctx.build.id, step)?;
if status.as_deref() == Some(step_state::SUCCEEDED) || status.as_deref() == Some(step_state::SKIPPED) {
continue; // checkpoint says we already did this
}
builds::begin_step(&ctx.db, &ctx.build.id, step, ctx.attempt)?;
builds::set_state(&ctx.db, &ctx.build.id, build_state::RUNNING, None)?;
ctx.log_line(&format!("==> step {step} (attempt {})", ctx.attempt));
match steps::run_step(ctx, step) {
Ok(StepResult::Done(digest)) => {
builds::finish_step(&ctx.db, &ctx.build.id, step, step_state::SUCCEEDED, digest.as_deref(), None)?;
builds::extend_lease(&ctx.db, &ctx.build.id, 90)?;
}
Ok(StepResult::Skipped(why)) => {
ctx.log_line(&format!(" skipped: {why}"));
builds::finish_step(&ctx.db, &ctx.build.id, step, step_state::SKIPPED, None, None)?;
}
Ok(StepResult::Blocked(on)) => {
builds::finish_step(&ctx.db, &ctx.build.id, step, step_state::PENDING, None, Some("blocked"))?;
builds::block_on(&ctx.db, &ctx.build.id, &on)?;
ctx.log_line(&format!(" blocked on: {}", on.join(", ")));
return Ok(Outcome::Blocked { on });
}
Err(e) => {
let transient = e.is_transient();
builds::finish_step(&ctx.db, &ctx.build.id, step, step_state::FAILED, None, Some(&e.to_string()))?;
builds::set_state(
&ctx.db,
&ctx.build.id,
build_state::FAILED,
Some(&format!("{step}: {e}")),
)?;
ctx.log_line(&format!("!! {step} failed: {e}"));
// A failed build must not leave the old version looking healthy:
// the release stays approved_but_unbuilt and the UI says so.
if let Some(cid) = ctx.build.candidate_id {
if ctx.build.release_id.is_none() {
mark_approved_but_unbuilt(&ctx.db, cid)?;
}
}
return Ok(Outcome::Failed { step: step.to_string(), error: e.to_string(), transient });
}
}
}
let release_id = ctx
.release_id()
.ok_or_else(|| Error::other("publish produced no release"))?;
builds::set_state(&ctx.db, &ctx.build.id, build_state::SUCCEEDED, None)?;
db::audit_system(
&ctx.db.writer,
"build.succeeded",
"build",
&ctx.build.id,
serde_json::json!({"release": release_id}),
)?;
Ok(Outcome::Succeeded { release_id })
}
impl Ctx {
fn release_id(&self) -> Option<i64> {
builds::get(&self.db, &self.build.id).ok().flatten().and_then(|b| b.release_id)
}
}
/// A failed build must not make the old version look healthy (§8.4). The
/// candidate stays `approved`; what the UI renders is the *absence* of a
/// published release behind it: "v2 approved, build failed, index still
/// serving v1". Nothing here mutates the accepted pointer.
fn mark_approved_but_unbuilt(_db: &Db, _candidate_id: i64) -> Result<()> {
Ok(())
}
/// Enqueue the build an approval implies. Deterministic id, so calling this
/// twice is a no-op (§8.2).
pub fn enqueue_for_candidate(cfg: &Config, db: &Db, c: &CandidateRow) -> Result<String> {
let pb = db::get_pkgbase_by_id(db, c.pkgbase_id)?
.ok_or_else(|| Error::not_found("pkgbase"))?;
let world = publish::index_world(db)?;
let world_hash = crate::hash::canonical_json(&world)?;
let id = builds::build_id(&pb.name, &c.identity_hash, &world_hash, &cfg.build_profile);
let world_id = db::put_world_snapshot(&db.writer, &world)?;
builds::enqueue(db, &id, pb.id, Some(c.id), "new_version", Some(world_id), &cfg.build_profile, 0)?;
Ok(id)
}
/// Manual rebuild of the current accepted version (I6): same source identity,
/// no new approval, same version.
pub fn enqueue_manual_rebuild(cfg: &Config, db: &Db, pkgbase: &str) -> Result<String> {
let pb = db::get_pkgbase(db, pkgbase)?
.ok_or_else(|| Error::not_found(format!("pkgbase {pkgbase}")))?;
let rel = db::accepted_release(db, pkgbase)?
.ok_or_else(|| Error::invalid(format!("{pkgbase} has no accepted release")))?;
let identity = crate::hash::hex_str(&format!(
"{}|{}|manual",
rel.aur_commit, rel.recipe_hash
));
let world = publish::index_world(db)?;
let world_hash = crate::hash::canonical_json(&world)?;
let id = builds::build_id(pkgbase, &identity, &world_hash, &cfg.build_profile);
let world_id = db::put_world_snapshot(&db.writer, &world)?;
builds::enqueue(db, &id, pb.id, None, "manual_rebuild", Some(world_id), &cfg.build_profile, 1)?;
let id_for_tx = id.clone();
let rid = rel.id;
db.writer.tx(move |tx| builds::set_release_in(tx, &id_for_tx, rid))?;
Ok(id)
}
/// What one step produced.
pub enum StepResult {
Done(Option<String>),
Skipped(String),
/// A dependency we publish is not in the index yet (§10.4).
Blocked(Vec<String>),
}
|