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
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
|
mod common;
use std::path::{Path, PathBuf};
use aur_build::ops;
use aur_build::pipeline;
use aur_build::review::{candidates, diff};
use common::*;
fn approve_and_build(env: &Env, name: &str) {
aur_build::watch::detect::check_pkgbase(&env.cfg, &env.db, name).unwrap();
let c = candidates::pending_candidates(&env.db).unwrap().remove(0);
let dd = diff::render_and_store(&env.db, &env.cfg, &c).unwrap();
let c = candidates::candidate_by_id(&env.db, c.id).unwrap().unwrap();
aur_build::review::approve::approve(&env.db, "t", c.id, &c.identity_hash, &dd, None).unwrap();
let c = candidates::candidate_by_id(&env.db, c.id).unwrap().unwrap();
let id = pipeline::enqueue_for_candidate(&env.cfg, &env.db, &c).unwrap();
pipeline::run(&env.cfg, &env.db, &id).unwrap();
}
fn publish_versions(env: &Env, fx: &Fixture, name: &str, n: usize) {
approve_and_build(env, name);
for i in 1..n {
fx.bump(&[("pkgver", &format!("1.{i}"))]);
approve_and_build(env, name);
}
}
fn artifact_paths(env: &Env) -> Vec<PathBuf> {
env.db
.read(|c| {
let mut st = c.prepare("SELECT path FROM artifact ORDER BY id")?;
let rows = st.query_map([], |r| r.get::<_, String>(0))?;
let mut out = Vec::new();
for r in rows {
out.push(PathBuf::from(r?));
}
Ok::<_, aur_build::Error>(out)
})
.unwrap()
}
#[test]
fn retention_keeps_the_newest_n_versions_and_never_deletes_a_row() {
let (env, fx) = env_with_fixture("plain-make");
publish_versions(&env, &fx, "plain-make", 5);
let before = artifact_paths(&env);
assert_eq!(before.len(), 5, "five published versions");
for p in &before {
assert!(p.exists(), "every published artifact should be on disk: {}", p.display());
}
let report = ops::retention(&env.cfg, &env.db, Some(2)).unwrap();
assert_eq!(report.releases_evicted, 3, "5 versions, keep 2: {report:?}");
assert!(report.files_removed >= 3, "each evicted release removes its package: {report:?}");
let kept: Vec<PathBuf> = env
.db
.read(|c| {
let mut st = c.prepare("SELECT path FROM artifact WHERE purged_at IS NULL ORDER BY id")?;
let rows = st.query_map([], |r| r.get::<_, String>(0))?;
let mut out = Vec::new();
for r in rows {
out.push(PathBuf::from(r?));
}
Ok::<_, aur_build::Error>(out)
})
.unwrap();
assert_eq!(kept.len(), 2, "exactly the keep window survives: {kept:?}");
for p in &kept {
assert!(p.exists(), "a retained artifact must still be on disk: {}", p.display());
}
for p in before.iter().rev().skip(2) {
assert!(!p.exists(), "an evicted artifact should be gone: {}", p.display());
}
assert_eq!(env.query_i64("SELECT count(*) FROM release", &[]), Some(5));
assert_eq!(env.query_i64("SELECT count(*) FROM artifact", &[]), Some(5));
assert_eq!(
env.query_i64("SELECT count(*) FROM artifact WHERE purged_at IS NOT NULL", &[]),
Some(3)
);
assert_eq!(
env.query_i64("SELECT count(*) FROM release WHERE purged_at IS NOT NULL", &[]),
Some(3)
);
assert_eq!(env.query_i64("SELECT count(*) FROM gc_run", &[]), Some(1));
assert!(env.query_i64("SELECT count(*) FROM audit WHERE action='retention'", &[]) == Some(1));
}
#[test]
fn retention_keeps_a_package_with_its_log_and_sources_as_one_unit() {
let (env, fx) = env_with_fixture("plain-make");
publish_versions(&env, &fx, "plain-make", 4);
let oldest = env
.db
.read(|c| {
Ok(c.query_row(
"SELECT id FROM release WHERE state='published' ORDER BY id LIMIT 1",
[],
|r| r.get::<_, i64>(0),
)?)
})
.unwrap();
let files = ops::release_files(&env.cfg, &env.db, oldest).unwrap();
let held: Vec<(Option<String>, Option<String>, Option<String>)> = env
.db
.read(|c| {
let mut st = c.prepare(
"SELECT a.path, a.signature_path, a.build_log_path FROM artifact a
JOIN package p ON p.artifact_id = a.id WHERE p.release_id = ?1",
)?;
let rows = st.query_map(rusqlite::params![oldest], |r| {
Ok((r.get::<_, Option<String>>(0)?, r.get::<_, Option<String>>(1)?, r.get::<_, Option<String>>(2)?))
})?;
let mut out = Vec::new();
for r in rows {
out.push(r?);
}
Ok::<_, aur_build::Error>(out)
})
.unwrap();
assert_eq!(held.len(), 1, "one artifact for this release: {held:?}");
let (pkg, sig, log) = &held[0];
for (what, p) in [("package", pkg), ("signature", sig), ("build log", log)] {
let p = p.as_ref().unwrap_or_else(|| panic!("the release should hold a {what}"));
assert!(
files.iter().any(|f| f == Path::new(p)),
"release_files must include the {what} ({p}): {files:?}"
);
assert!(Path::new(p).exists(), "the {what} should exist before eviction");
}
ops::retention(&env.cfg, &env.db, Some(1)).unwrap();
let still_there: Vec<&PathBuf> = files.iter().filter(|f| f.exists()).collect();
assert!(
still_there.is_empty(),
"evicting a release must take its log and signature with it: {still_there:?}"
);
}
#[test]
fn retention_never_evicts_the_version_the_index_is_serving() {
let (env, fx) = env_with_fixture("plain-make");
publish_versions(&env, &fx, "plain-make", 2);
let served = env
.db
.read(|c| {
Ok(c.query_row(
"SELECT a.path FROM artifact a JOIN package p ON p.artifact_id=a.id WHERE p.state='in_index'",
[],
|r| r.get::<_, String>(0),
)?)
})
.unwrap();
let served_release = env
.db
.read(|c| {
Ok(c.query_row(
"SELECT p.release_id FROM package p WHERE p.state='in_index' LIMIT 1",
[],
|r| r.get::<_, i64>(0),
)?)
})
.unwrap();
env.exec("UPDATE package SET state='removed' WHERE state='in_index'", &[]);
env.exec(
"UPDATE package SET state='in_index' WHERE release_id=?1",
&[P::I(served_release)],
);
let report = ops::retention(&env.cfg, &env.db, Some(1)).unwrap();
assert!(report.releases_evicted >= 1, "something should have been evicted: {report:?}");
assert!(
Path::new(&served).exists(),
"retention deleted the artifact the index is serving: {served}"
);
}
#[test]
fn staging_dirs_are_swept_only_when_their_build_is_finished() {
let (env, fx) = env_with_fixture("plain-make");
approve_and_build(&env, "plain-make");
let done = env.cfg.staging_dir().join("finished-build");
let orphan = env.cfg.staging_dir().join("no-such-build");
let live = env.cfg.staging_dir().join("live-build");
for d in [&done, &orphan, &live] {
std::fs::create_dir_all(d).unwrap();
std::fs::write(d.join("pkg.tar.zst"), vec![b'x'; 4096]).unwrap();
backdate(d, 7200);
}
env.exec(
"INSERT INTO build (id, pkgbase_id, candidate_id, kind, build_profile, state, attempt, created_at, updated_at)
VALUES ('live-build', 1, 1, 'new_version', 'default', 'running', 1, '2020-01-01T00:00:00Z', '2020-01-01T00:00:00Z')",
&[],
);
let _ = fx;
let (swept, freed) = ops::sweep_staging(&env.cfg, &env.db, ops::STAGING_GRACE_SECS).unwrap();
assert_eq!(swept, 2, "the finished and the orphaned dir go; the running one stays");
assert_eq!(freed, 8192, "two dirs of 4 KiB each");
assert!(!done.exists(), "a finished build's staging is disposable");
assert!(!orphan.exists(), "a staging dir with no build row is abandoned");
assert!(live.exists(), "a long-running build is not an abandoned one");
}
#[test]
fn metrics_reports_the_operating_numbers_in_prometheus_format() {
let (env, fx) = env_with_fixture("plain-make");
approve_and_build(&env, "plain-make");
fx.bump(&[("pkgver", "9.9")]);
aur_build::watch::detect::check_pkgbase(&env.cfg, &env.db, "plain-make").unwrap();
let c = candidates::pending_candidates(&env.db).unwrap().remove(0);
let _ = pipeline::enqueue_for_candidate(&env.cfg, &env.db, &c);
let m = ops::metrics(&env.cfg, &env.db).unwrap();
let text = m.to_prometheus();
for family in [
"aurbuild_queue_depth",
"aurbuild_pending_review_candidates",
"aurbuild_pending_review_age_seconds_bucket",
"aurbuild_build_success_rate",
"aurbuild_sqlite_wal_size_bytes",
"aurbuild_builds_total",
"aurbuild_index_packages",
"aurbuild_stale_releases",
] {
assert!(text.contains(family), "missing metric {family}: {text}");
}
for line in text.lines().filter(|l| !l.starts_with('#')) {
let tail = line.rsplit(' ').next().unwrap_or("");
assert!(
tail.parse::<f64>().is_ok(),
"not a prometheus sample: {line:?}"
);
}
for line in text.lines().filter(|l| l.starts_with("# TYPE")) {
let name = line.split_whitespace().nth(2).unwrap();
assert!(
text.contains(&format!("{name} ")) || text.contains(&format!("{name}{{")),
"family {name} declared but never sampled"
);
}
assert_eq!(m.queue_depth, 1, "one queued build");
assert_eq!(m.pending_review, 1, "one review waiting");
assert_eq!(m.review_ages.len(), 1);
assert_eq!(m.succeeded, 1);
assert_eq!(m.failed, 0);
assert!((m.build_success_rate() - 1.0).abs() < 1e-9);
assert!(m.db_bytes > 0, "the database file has a size");
assert!(
text.contains("aurbuild_pending_review_age_seconds_bucket{le=\"+Inf\"} 1"),
"histograms need a +Inf bucket: {text}"
);
assert!(text.contains("aurbuild_pending_review_age_seconds_count 1"));
assert!(text.contains("aurbuild_pending_review_age_seconds_sum"));
}
#[test]
fn a_fresh_install_reports_a_clean_sheet_not_a_division_by_zero() {
let env = Env::new();
let m = ops::metrics(&env.cfg, &env.db).unwrap();
assert_eq!(m.succeeded + m.failed, 0);
assert!((m.build_success_rate() - 1.0).abs() < 1e-9, "no builds yet should read as healthy");
assert!(m.to_prometheus().contains("aurbuild_up 1"));
}
#[test]
fn the_http_metrics_endpoint_serves_scrapeable_text() {
let web = Web::new("plain-make");
let page = web.get("/metrics");
assert_eq!(page.status, 200);
assert!(page.body.contains("# TYPE aurbuild_queue_depth gauge"));
assert!(page.body.contains("aurbuild_sqlite_wal_size_bytes"));
let (headers, body) = web.raw_get("/metrics");
assert!(body.contains("aurbuild_up 1"), "metrics should be reachable unauthenticated");
let ct = headers
.iter()
.find(|(k, _)| k.eq_ignore_ascii_case("content-type"))
.map(|(_, v)| v.clone())
.unwrap_or_default();
assert!(ct.starts_with("text/plain"), "a scraper wants text/plain, got {ct}");
}
#[test]
fn backup_is_a_consistent_single_file_that_reopens_and_matches() {
let (env, _fx) = env_with_fixture("plain-make");
approve_and_build(&env, "plain-make");
let dest = env.root().join("backup/aur-build.db");
let out = ops::backup(&env.db, &dest).unwrap();
assert_eq!(out, dest);
assert!(dest.exists());
assert!(!Path::new(&format!("{}-wal", dest.display())).exists(), "a backup must not need a sidecar");
assert!(!Path::new(&format!("{}-shm", dest.display())).exists());
let probe = rusqlite::Connection::open(&dest).unwrap();
let version: i64 = probe.query_row("PRAGMA user_version", [], |r| r.get(0)).unwrap();
assert!(version >= 8, "the snapshot carries the migrated schema, got {version}");
let approvals: i64 = probe.query_row("SELECT count(*) FROM approval", [], |r| r.get(0)).unwrap();
assert_eq!(approvals, 1, "the approval history is the reason backups exist");
let releases: i64 = probe.query_row("SELECT count(*) FROM release", [], |r| r.get(0)).unwrap();
assert_eq!(releases, 1);
drop(probe);
let mode: String = env
.db
.read(|c| Ok(c.query_row("PRAGMA journal_mode", [], |r| r.get::<_, String>(0))?))
.unwrap();
assert_eq!(mode.to_lowercase(), "wal", "the live db should still be WAL");
assert!(env.query_i64("SELECT count(*) FROM approval", &[]) == Some(1));
}
#[test]
fn backup_refuses_to_overwrite_an_existing_snapshot() {
let (env, _fx) = env_with_fixture("plain-make");
approve_and_build(&env, "plain-make");
let dest = env.root().join("snap.db");
ops::backup(&env.db, &dest).unwrap();
let second = ops::backup(&env.db, &dest);
assert!(second.is_err(), "overwriting an existing backup must be refused");
assert!(dest.exists(), "the refusal must not have truncated the existing file");
assert!(std::fs::metadata(&dest).unwrap().len() > 0);
}
fn backdate(path: &Path, secs: u64) {
let old = std::time::SystemTime::now() - std::time::Duration::from_secs(secs);
for f in std::fs::read_dir(path).into_iter().flatten().flatten() {
let _ = std::fs::File::open(f.path()).and_then(|f| f.set_modified(old));
}
let _ = std::fs::File::open(path).and_then(|f| f.set_modified(old));
}
|