summaryrefslogtreecommitdiffstats
path: root/src
diff options
context:
space:
mode:
authoraur-build <aur-build@localhost>2026-11-19 17:09:59 +0000
committeraur-build <aur-build@localhost>2026-11-19 17:09:59 +0000
commite757979f1a2afdbe7146066345bb9acd19d3b151 (patch)
tree30d5f5fbccd25ea7bf01c5202684af463b74e7d3 /src
parent94c318f13264bb3c00a9f3057ba2e1aafb57c9e4 (diff)
downloadaur-build-e757979f1a2afdbe7146066345bb9acd19d3b151.tar.gz
aur-build-e757979f1a2afdbe7146066345bb9acd19d3b151.zip
comments: say why, not what
Every module-level `//!` header is gone, and the comments that remained either re-explained the line below them or had grown into paragraphs. Density went from one comment line per 6.7 lines of code to one per 10. 827 insertions against 2194 deletions across 86 files. What survived: the invariants (I1-I12), the design cross-references into DESIGN.md, and the notes recording a bug that was found and fixed — those are the comments that carry weight, because they answer a question the code cannot answer about itself. What did not: restating a function signature in prose, and narration of the statement underneath.
Diffstat (limited to 'src')
-rw-r--r--src/bin/gpg.rs2
-rw-r--r--src/bin/makechrootpkg.rs2
-rw-r--r--src/bin/makepkg.rs2
-rw-r--r--src/bin/mkarchroot.rs2
-rw-r--r--src/bin/pacman.rs2
-rw-r--r--src/bin/repo-add.rs2
-rw-r--r--src/bin/sandbox-agent.rs6
-rw-r--r--src/config.rs231
-rw-r--r--src/db/approvals.rs8
-rw-r--r--src/db/builds.rs40
-rw-r--r--src/db/candidates.rs24
-rw-r--r--src/db/migrations.rs23
-rw-r--r--src/db/mod.rs73
-rw-r--r--src/db/model.rs152
-rw-r--r--src/db/queries.rs95
-rw-r--r--src/error.rs39
-rw-r--r--src/fetch.rs6
-rw-r--r--src/git.rs24
-rw-r--r--src/hash.rs30
-rw-r--r--src/http/auth.rs45
-rw-r--r--src/http/forms.rs5
-rw-r--r--src/http/mod.rs44
-rw-r--r--src/http/render.rs14
-rw-r--r--src/http/routes/mod.rs6
-rw-r--r--src/http/routes/mutations.rs3
-rw-r--r--src/http/routes/pages.rs9
-rw-r--r--src/http/sse.rs12
-rw-r--r--src/lib.rs17
-rw-r--r--src/main.rs22
-rw-r--r--src/ops.rs85
-rw-r--r--src/pipeline/dispatch.rs39
-rw-r--r--src/pipeline/mod.rs49
-rw-r--r--src/pipeline/publish.rs138
-rw-r--r--src/pipeline/steps.rs93
-rw-r--r--src/pkginfo.rs18
-rw-r--r--src/pkgver/mod.rs27
-rw-r--r--src/recipe.rs20
-rw-r--r--src/review/approve.rs62
-rw-r--r--src/review/candidates.rs21
-rw-r--r--src/review/diff.rs7
-rw-r--r--src/review/mod.rs3
-rw-r--r--src/review/risk.rs12
-rw-r--r--src/sandbox/agent.rs15
-rw-r--r--src/sandbox/kata.rs34
-rw-r--r--src/sandbox/loopback.rs13
-rw-r--r--src/sandbox/mod.rs99
-rw-r--r--src/sandbox/remote.rs21
-rw-r--r--src/sandbox/wire.rs36
-rw-r--r--src/shims/mod.rs117
-rw-r--r--src/time.rs28
-rw-r--r--src/urlutil.rs11
-rw-r--r--src/watch/detect.rs82
-rw-r--r--src/watch/digests.rs26
-rw-r--r--src/watch/mirror.rs14
-rw-r--r--src/watch/mod.rs3
-rw-r--r--src/watch/scheduler.rs5
-rw-r--r--src/watch/staleness.rs19
-rw-r--r--src/watch/upstream.rs28
58 files changed, 531 insertions, 1534 deletions
diff --git a/src/bin/gpg.rs b/src/bin/gpg.rs
index e9df5e3..da8c3db 100644
--- a/src/bin/gpg.rs
+++ b/src/bin/gpg.rs
@@ -1,5 +1,3 @@
-//! Toolchain shim: `gpg` (§16a). See `aur_build::shims`.
-
fn main() {
std::process::exit(aur_build::shims::run("gpg"));
}
diff --git a/src/bin/makechrootpkg.rs b/src/bin/makechrootpkg.rs
index 00569fb..c190e8b 100644
--- a/src/bin/makechrootpkg.rs
+++ b/src/bin/makechrootpkg.rs
@@ -1,5 +1,3 @@
-//! Toolchain shim: `makechrootpkg` (§16a). See `aur_build::shims`.
-
fn main() {
std::process::exit(aur_build::shims::run("makechrootpkg"));
}
diff --git a/src/bin/makepkg.rs b/src/bin/makepkg.rs
index 1c5cd7f..3398f5d 100644
--- a/src/bin/makepkg.rs
+++ b/src/bin/makepkg.rs
@@ -1,5 +1,3 @@
-//! Toolchain shim: `makepkg` (§16a). See `aur_build::shims`.
-
fn main() {
std::process::exit(aur_build::shims::run("makepkg"));
}
diff --git a/src/bin/mkarchroot.rs b/src/bin/mkarchroot.rs
index a4be6eb..33f2577 100644
--- a/src/bin/mkarchroot.rs
+++ b/src/bin/mkarchroot.rs
@@ -1,5 +1,3 @@
-//! Toolchain shim: `mkarchroot` (§16a). See `aur_build::shims`.
-
fn main() {
std::process::exit(aur_build::shims::run("mkarchroot"));
}
diff --git a/src/bin/pacman.rs b/src/bin/pacman.rs
index 5f7a357..e42b50b 100644
--- a/src/bin/pacman.rs
+++ b/src/bin/pacman.rs
@@ -1,5 +1,3 @@
-//! Toolchain shim: `pacman` (§16a). See `aur_build::shims`.
-
fn main() {
std::process::exit(aur_build::shims::run("pacman"));
}
diff --git a/src/bin/repo-add.rs b/src/bin/repo-add.rs
index 6714de6..ce74b24 100644
--- a/src/bin/repo-add.rs
+++ b/src/bin/repo-add.rs
@@ -1,5 +1,3 @@
-//! Toolchain shim: `repo-add` (§16a). See `aur_build::shims`.
-
fn main() {
std::process::exit(aur_build::shims::run("repo-add"));
}
diff --git a/src/bin/sandbox-agent.rs b/src/bin/sandbox-agent.rs
index 4e959a9..ce34d50 100644
--- a/src/bin/sandbox-agent.rs
+++ b/src/bin/sandbox-agent.rs
@@ -1,9 +1,3 @@
-//! The ephemeral sandbox agent — see `aur_build::sandbox::agent`.
-//!
-//! This is the piece that runs *inside* the disposable sandbox (a Kata
-//! container, a throwaway VM, a test's temp process). It dials the hub,
-//! serves exactly one lease, and dies with it.
-
use std::time::Duration;
fn main() {
diff --git a/src/config.rs b/src/config.rs
index d583b05..f8fe51a 100644
--- a/src/config.rs
+++ b/src/config.rs
@@ -1,72 +1,43 @@
-//! Filesystem layout and runtime configuration.
-//!
-//! Everything the server owns lives under one root directory so a test can point
-//! the whole application at a `tempdir` and get an isolated instance. The heavy
-//! bytes (packages, logs, mirrors) live on the filesystem and are referenced by
-//! path from the DB (DESIGN.md §11a).
-
use std::path::{Path, PathBuf};
use serde::{Deserialize, Serialize};
-/// The tag a provisioned sandbox image gets when the configuration names a
-/// provisioning kind but the caller has no image of its own (tests, mostly).
+/// Fallback tag for a provisioning backend when the caller has no image of its own.
pub const DEFAULT_SANDBOX_IMAGE: &str = "aur-build-sandbox:latest";
/// Where build code runs (§8, the sandbox seam).
///
-/// Three kinds, and only three. This is an enum with required fields rather
-/// than a string plus a `validate()` that has to be remembered, because the
-/// failure mode of the string was silent: `sandbox_backend = "kata"` fell
-/// through to loopback and a build that was supposed to run inside a VM ran
-/// as the hub's own user. Here an unknown kind is a parse error naming the
-/// valid set, and a kind is missing a field it needs is a parse error naming
-/// the field.
-///
-/// Secrets are redacted in `Debug` on purpose: a config that ends up in a log
-/// line or a panic message must not carry the rendezvous token.
+/// An enum with required fields rather than a string plus a `validate()`: the
+/// string version silently fell through to loopback.
#[derive(Clone, Serialize, Deserialize)]
#[serde(tag = "kind", rename_all = "kebab-case", deny_unknown_fields)]
pub enum Sandbox {
- /// Subprocesses of this process — tests, and the single-machine deployment
- /// where §14's sudo rules are the boundary. The default, and the only kind
- /// that needs no configuration, which is what keeps an existing
- /// `config.json` valid without edits.
- ///
- /// Isolation is *none*: the sandbox is the hub's own user.
+ /// Subprocesses of this process; isolation is *none* (§14's sudo rules are
+ /// the boundary). The default, and the only kind needing no configuration.
Loopback,
- /// Sandboxes that dial in over the agent protocol (§8a). The hub never
- /// provisions them; it waits for an agent carrying the token to connect.
+ /// Sandboxes that dial in over the agent protocol (§8a); the hub never
+ /// provisions them.
Remote {
- /// Address the hub listens on for agent dial-ins. Port 0 is allowed
- /// and resolves at bind.
+ /// Agent dial-in listener; port 0 resolves at bind.
listen: String,
- /// Shared secret an agent presents at rendezvous. A sandbox is
- /// untrusted the moment it boots; this is the only thing saying "you
- /// belong to me". Deploy it like a credential.
+ /// Rendezvous secret. Deploy it like a credential.
token: String,
- /// Asserts that hub and sandbox see the same filesystem. The workspace
- /// is not yet shipped to a remote sandbox (§8a), so a remote build only
- /// works where the srcdir is shared; saying so explicitly is what
- /// turns a silent misconfiguration into a refusal. See `Config`'s
- /// startup guard.
+ /// Asserts hub and sandbox see the same filesystem — required, because
+ /// the workspace is not shipped to a remote sandbox (§8a). See
+ /// `Config`'s startup guard.
#[serde(default)]
shared_workspace: bool,
},
- /// agent-sandbox: disposable Kata VMs provisioned by a Kubernetes CRD, so
- /// the orchestrator enforces the TTL even if the hub dies (§8a).
+ /// Disposable Kata VMs provisioned by a Kubernetes CRD, so the orchestrator
+ /// enforces the TTL even if the hub dies (§8a).
AgentSandbox {
- /// Kubernetes API server serving the agent-sandbox CRD.
api: String,
- /// Namespace the sandboxes are created in.
namespace: String,
- /// Bearer token for the API. A credential; never logged.
+ /// Never logged.
bearer: String,
- /// Image a provisioned sandbox boots — the `sandbox-agent` entrypoint.
+ /// The `sandbox-agent` entrypoint.
image: String,
- /// Address the hub listens on for agent dial-ins.
listen: String,
- /// Shared secret an agent presents at rendezvous.
token: String,
/// As [`Sandbox::Remote`].
#[serde(default)]
@@ -75,16 +46,14 @@ pub enum Sandbox {
}
impl Default for Sandbox {
- /// The fully local option, so a config that says nothing still builds.
fn default() -> Self {
Sandbox::Loopback
}
}
impl std::fmt::Debug for Sandbox {
- /// Hand-written so the secrets cannot ride along: a config that ends up in
- /// a log line, a panic message, or an audit payload must not carry the
- /// rendezvous token or the cluster bearer.
+ // Hand-written so the rendezvous token and cluster bearer cannot ride into
+ // a log line, a panic message, or an audit payload.
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Sandbox::Loopback => f.write_str("Sandbox::Loopback"),
@@ -109,7 +78,6 @@ impl std::fmt::Debug for Sandbox {
}
impl Sandbox {
- /// The kind name, for error messages and the UI.
pub fn kind(&self) -> &'static str {
match self {
Sandbox::Loopback => "loopback",
@@ -118,7 +86,6 @@ impl Sandbox {
}
}
- /// The rendezvous listener address, for the kinds that have one.
pub fn listen(&self) -> Option<&str> {
match self {
Sandbox::Remote { listen, .. } => Some(listen),
@@ -127,7 +94,7 @@ impl Sandbox {
}
}
- /// The rendezvous token, for the kinds that have one. Never log this.
+ /// Never log this.
pub fn token(&self) -> Option<&str> {
match self {
Sandbox::Remote { token, .. } => Some(token),
@@ -136,9 +103,7 @@ impl Sandbox {
}
}
- /// The image a provisioning backend boots. `None` for kinds that
- /// provision nothing — there is no honest default for loopback, and a
- /// field that is never consulted is a field that lies.
+ /// `None` for kinds that provision nothing.
pub fn image(&self) -> Option<&str> {
match self {
Sandbox::AgentSandbox { image, .. } => Some(image),
@@ -146,8 +111,6 @@ impl Sandbox {
}
}
- /// Whether the operator has asserted that hub and sandbox share a
- /// filesystem. Loopback shares it by construction.
pub fn shared_workspace(&self) -> bool {
match self {
Sandbox::Loopback => true,
@@ -156,7 +119,6 @@ impl Sandbox {
}
}
- /// The valid kind names, for the error that names them.
pub const KINDS: [&'static str; 3] = ["loopback", "remote", "agent-sandbox"];
}
@@ -164,101 +126,63 @@ impl Sandbox {
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct Config {
- /// Root directory holding db, mirrors, caches, store, repo and logs.
+ /// Holds db, mirrors, caches, store, repo and logs.
pub root: PathBuf,
- /// Name of the single pacman repo we publish (DESIGN.md §9, decision 4).
pub repo_name: String,
- /// Architecture, fixed to x86_64 by decision 17.
pub arch: String,
- /// GPG key id used to sign packages *and* the database (decision 22).
+ /// Signs packages *and* the database (decision 22).
pub signing_key_id: String,
- /// Address the HTTP UI binds to. Default is loopback only (§14).
+ /// Loopback only by default (§14).
pub bind: String,
- /// Shared credential for the UI. Single user, one credential, no user table.
+ /// One credential, no user table.
pub password: String,
- /// Public base URL used in consumer-facing snippets.
pub base_url: String,
- /// devtools build profile (§8.3).
pub build_profile: String,
- /// Path to the git executable.
pub git_bin: String,
- /// Path to the makepkg executable.
pub makepkg_bin: String,
- /// Path to pacman. The provisioning step installs the pinned lease set
- /// with `pacman -U` inside the sandbox (§8); nothing resolves against a
- /// live mirror at build time.
+ /// The lease set is installed with `pacman -U` inside the sandbox (§8).
pub pacman_bin: String,
- /// Path to repo-add.
pub repo_add_bin: String,
- /// Path to gpg.
pub gpg_bin: String,
- /// Unprivileged user that runs PKGBUILD code (§14). Empty = current user.
+ /// Unprivileged user running PKGBUILD code (§14). Empty = current user.
pub build_user: String,
- /// Where build code runs (§8). A tagged enum rather than a free-form string
- /// plus a validation pass: the configurations that cannot work are not
- /// representable, so there is no input that silently becomes "loopback".
- /// See [`Sandbox`].
pub sandbox: Sandbox,
- /// Test-only hooks (§16a). Not part of the production configuration at all
- /// unless the crate is built with `test-support` — see [`TestHooks`].
+ /// Absent unless built with `test-support` (§16a).
#[cfg(feature = "test-support")]
#[serde(default, skip_serializing_if = "TestHooks::is_empty")]
pub hooks: TestHooks,
- /// How many builds may run at once (§8.2 backpressure). Default 1, which
- /// also means the chroot pool only needs one warm root.
+ /// Default 1, so the chroot pool needs only one warm root.
pub max_concurrent_builds: usize,
- /// Seconds of lease a worker takes when it claims a build (§8.2).
pub lease_secs: i64,
- /// A build is not admitted unless at least this much free space remains
- /// on the filesystem holding `root` (§8.2 disk headroom).
pub min_free_disk_mb: u64,
- /// Transient step failures are retried up to this many attempts; a
- /// deterministic build failure is never retried (§8.4).
+ /// Transient step failures only (§8.4).
pub max_transient_attempts: i64,
- /// Seconds between dispatcher passes.
pub dispatch_tick_secs: u64,
}
-/// The test harness's handles on a real pipeline (§16a), grouped into one
-/// submodule so the production configuration says what it is.
-///
-/// Each of these exists because a *fake* pipeline would test something else:
-/// I4 (atomic publish) needs a process that really dies between the tmp write
-/// and the rename; I5 needs a step that really dies mid-child; I9 needs a
-/// PKGBUILD that really reaches outside its staging dir. The alternative was a
-/// mock that asserts the mock's own behaviour.
+/// The test harness's handles on a real pipeline (§16a).
///
-/// They are compiled out entirely unless the crate is built with the
-/// `test-support` feature (the same feature that gates the shims, §6 M-4), so a
-/// production binary has no fault-injection branch in its publish path and no
-/// shim protocol in its child environment. The test suite enables the feature
-/// through a dev-dependency on this crate, and nothing else does.
+/// Each exists because a *fake* pipeline would test something else: I4 needs a
+/// process that really dies between the tmp write and the rename, I5 needs a step
+/// that really dies mid-child, I9 needs a PKGBUILD that really reaches outside its
+/// staging dir.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(default)]
pub struct TestHooks {
- /// Directory prepended to PATH for child processes: the toolchain shims.
pub path_prepend: Option<PathBuf>,
- /// Fixture manifest the shims should obey, exported as `AUR_SHIM_MANIFEST`.
pub shim_manifest: Option<PathBuf>,
- /// Where shims record their invocations, exported as `AUR_SHIM_DIR`.
pub shim_dir: Option<PathBuf>,
- /// Abort publish at a named point so I4 (atomic publish) can be exercised
- /// for real: `before-rename` or `after-rename`.
+ /// `before-rename` or `after-rename`, for I4.
pub publish_fault: Option<String>,
/// The named shim must fail, e.g. `makepkg`.
pub shim_fail: Option<String>,
- /// The named shim SIGKILLs its parent — the process running the pipeline —
- /// mid-step. This is how a real crash is reproduced for I5: not a caught
- /// error, an uncatchable death.
+ /// The named shim SIGKILLs the pipeline process mid-step (I5).
pub shim_kill_parent: Option<String>,
- /// Make the build shim plant a symlink to this path in its srcdir, so a test
- /// can act out the I9 attack: an untrusted PKGBUILD smuggling bytes in from
- /// outside its own staging dir.
+ /// The build shim plants a symlink to this path in its srcdir (I9).
pub shim_plant_link: Option<String>,
}
impl TestHooks {
- /// True when nothing is hooked — the state every real process runs in.
pub fn is_empty(&self) -> bool {
self.path_prepend.is_none()
&& self.shim_manifest.is_none()
@@ -300,10 +224,6 @@ impl Default for Config {
}
impl Config {
- /// The image a provisioning sandbox boots, when this configuration
- /// provisions anything. Falls back to the conventional tag so a test that
- /// builds a `KataBackend` over a default config still gets a name to hand
- /// an agent.
pub fn sandbox_image(&self) -> String {
self.sandbox
.image()
@@ -313,12 +233,8 @@ impl Config {
/// Refuse a configuration that cannot work, before anything builds with it.
///
- /// The enum already makes the impossible unrepresentable; this catches what
- /// a type cannot see — a field that is present but empty, and the one
- /// assertion the type deliberately leaves defaulted so the refusal can
- /// explain itself instead of arriving as a parse error. Called at startup
- /// (so the operator hears about it now, not at the first build) and again
- /// where a backend is constructed (so a hand-built `Config` cannot skip it).
+ /// The enum makes the impossible unrepresentable; this catches what a type cannot
+ /// see — empty-but-present fields, and the assertion the type leaves defaulted.
pub fn validate(&self) -> crate::error::Result<()> {
let require = |field: &str, value: &str| -> crate::error::Result<()> {
if value.trim().is_empty() {
@@ -351,10 +267,7 @@ impl Config {
if self.sandbox.shared_workspace() {
return Ok(());
}
- // The one gap a remote configuration cannot be trusted to notice by
- // itself: the workspace is not shipped to the sandbox, so a remote
- // build only works where hub and sandbox see the same path. Refusing
- // here is what stops "remote" from silently meaning "on the hub".
+ // A remote build only works where hub and sandbox see the same path.
Err(crate::error::Error::invalid(format!(
concat!(
"sandbox kind \"{}\" was not told that hub and sandbox share a filesystem: ",
@@ -370,20 +283,10 @@ impl Config {
/// Read `<root>/config.json`.
///
- /// The crate's own error type, like everything else that can fail (m-15):
- /// `anyhow::Result` here meant two error vocabularies in one crate, and the
- /// one thing a caller can actually branch on — "there is no config yet, run
- /// init" — arrived as an opaque string.
- ///
- /// **The root is the directory the config file was found in.** The `root`
- /// field inside the file is written for whoever is looking at the tree, not
- /// as a second source of truth: `load` is only ever handed the directory it
- /// then reads the config from, so a field that disagreed with its own
- /// location could only ever contradict it. Honouring a relative field by
- /// re-joining it onto the config's directory is what turned `--root runtime`
- /// (which `init` used to save verbatim) into `runtime/runtime/…` — every
- /// command after `init` ran against a second tree with its own database,
- /// while `init` had created and migrated the first one.
+ /// **The root is the directory the config file was found in.** The `root` field
+ /// inside the file is documentation, not a second source of truth; honouring a
+ /// relative field by re-joining it onto the config's directory is what turned
+ /// `--root runtime` into `runtime/runtime/…`.
pub fn load(root: &Path) -> crate::error::Result<Self> {
let dir = absolute(root)?;
let p = dir.join("config.json");
@@ -404,9 +307,8 @@ impl Config {
pub fn save(&self) -> crate::error::Result<()> {
std::fs::create_dir_all(&self.root)?;
let mut out = self.clone();
- // Absolutize on the way out, so a config written by a process that was
- // handed a relative `--root` can never be misread — by the next command,
- // or by a person editing it by hand.
+ // Absolutize on the way out, so a config written from a relative
+ // `--root` can never be misread.
out.root = absolute(&self.root)?;
std::fs::write(
self.root.join("config.json"),
@@ -415,17 +317,12 @@ impl Config {
Ok(())
}
- /// Environment for a child process: PATH with the shims in front, plus the
- /// shim protocol variables (§16a). The pairs form is what the remote
- /// backend puts on the wire, so a remote child sees exactly what a local
- /// one would.
+ /// Child environment as pairs — the form the remote backend puts on the
+ /// wire, so a remote child sees what a local one would.
#[cfg_attr(not(feature = "test-support"), allow(unused_variables))]
pub fn child_env_pairs(&self) -> Vec<(String, String)> {
#[cfg_attr(not(feature = "test-support"), allow(unused_mut))]
let mut pairs = Vec::new();
- // Without `test-support` there is no shim protocol to export and no
- // PATH to rewrite: the child inherits the real environment, which is
- // what a real build needs (§16a).
#[cfg(feature = "test-support")]
{
let h = &self.hooks;
@@ -452,9 +349,6 @@ impl Config {
pairs
}
- /// Environment for a child process: PATH with the shims in front, plus the
- /// shim protocol variables (§16a).
- #[cfg_attr(not(feature = "test-support"), allow(unused_variables))]
pub fn child_env(&self, cmd: &mut std::process::Command) {
for (k, v) in self.child_env_pairs() {
cmd.env(k, v);
@@ -482,15 +376,12 @@ impl Config {
pub fn db_path(&self) -> PathBuf {
self.root.join("aur-build.db")
}
- /// Local AUR git mirrors, one clone per pkgbase (§5.1). Load-bearing, not a
- /// cache: it is what makes historical releases rebuildable (§5.1a).
pub fn mirrors_dir(&self) -> PathBuf {
self.root.join("mirrors")
}
pub fn mirror_path(&self, pkgbase: &str) -> PathBuf {
self.mirrors_dir().join(format!("{pkgbase}.git"))
}
- /// Persistent upstream VCS clones (§5.2 cost control).
pub fn vcs_cache_dir(&self) -> PathBuf {
self.root.join("vcs_cache")
}
@@ -498,21 +389,18 @@ impl Config {
let h = crate::hash::short(url.as_bytes(), 16);
self.vcs_cache_dir().join(format!("{}-{}.git", slug(url), h))
}
- /// Content-addressed download cache reused by the build (§5.3).
pub fn source_cache_dir(&self) -> PathBuf {
self.root.join("source_cache")
}
pub fn source_cache_path(&self, digest: &str) -> PathBuf {
self.source_cache_dir().join(&digest[..2.min(digest.len())]).join(digest)
}
- /// Disposable per-build workspace (§8.2).
pub fn staging_dir(&self) -> PathBuf {
self.root.join("staging")
}
pub fn staging_build_dir(&self, build_id: &str) -> PathBuf {
self.staging_dir().join(build_id)
}
- /// Content-addressed artifact store.
pub fn store_dir(&self) -> PathBuf {
self.root.join("store")
}
@@ -525,7 +413,6 @@ impl Config {
pub fn build_log_path(&self, build_id: &str) -> PathBuf {
self.log_dir().join(format!("{build_id}.log"))
}
- /// The served repo tree: `<repo>/<name>/os/<arch>/` (§9).
pub fn repo_dir(&self) -> PathBuf {
self.root.join("repo")
}
@@ -540,11 +427,9 @@ impl Config {
}
}
-/// Whether a retired key holds exactly the value `init` used to write for a
-/// local deployment. Such a value states nothing the default does not already
-/// state, so it is noise from an old file rather than an intent that could be
-/// lost — which is what lets a working local config keep loading across the
-/// change. Anything else is refused.
+/// A retired key holding exactly what `init` used to write for a local
+/// deployment states nothing the default does not already state, so it is noise
+/// from an old file rather than lost intent. Anything else is refused.
fn retired_key_is_inert(key: &str, value: &str) -> bool {
match key {
"sandbox_backend" => value == "loopback",
@@ -554,14 +439,9 @@ fn retired_key_is_inert(key: &str, value: &str) -> bool {
}
/// The sandbox configuration moved from four flat keys to one tagged object
-/// ([`Sandbox`]). A retired key is refused rather than quietly ignored — but
-/// only when it would have changed behaviour.
-///
-/// `init` used to write `sandbox_backend: "loopback"` alongside three empty
-/// strings, and a config carrying exactly that says nothing the default does
-/// not already say, so it keeps loading untouched. Anything else is an error:
-/// silently turning a retired `sandbox_backend: "remote"` into loopback is
-/// precisely the failure the enum exists to make impossible.
+/// ([`Sandbox`]). A retired key is refused only when it would have changed
+/// behaviour: `init` used to write `sandbox_backend: "loopback"` alongside three
+/// empty strings, and a config carrying exactly that keeps loading untouched.
fn check_retired_sandbox_keys(v: &serde_json::Value) -> crate::error::Result<()> {
const RETIRED: [&str; 4] = ["sandbox_backend", "agent_listen", "agent_token", "sandbox_image"];
let named: Vec<String> = RETIRED
@@ -591,14 +471,13 @@ fn check_retired_sandbox_keys(v: &serde_json::Value) -> crate::error::Result<()>
)))
}
-/// Absolutize a path without resolving symlinks and without requiring it to
+/// Absolutize without resolving symlinks and without requiring the path to
/// exist, both of which `canonicalize` insists on — and `init` saves its config
/// before the tree under it is complete.
fn absolute(p: &Path) -> crate::error::Result<PathBuf> {
Ok(std::path::absolute(p)?)
}
-/// Filesystem-safe slug for a URL, used in cache filenames.
pub fn slug(url: &str) -> String {
url.chars()
.map(|c| {
diff --git a/src/db/approvals.rs b/src/db/approvals.rs
index f04d641..b5a9b59 100644
--- a/src/db/approvals.rs
+++ b/src/db/approvals.rs
@@ -1,11 +1,3 @@
-//! The approval table: the record of a human decision, and the only thing that
-//! makes a candidate publishable (§7.1a, I1).
-//!
-//! An approval row is what an index entry must trace back to. The rules about
-//! *when* one may be written — same identity, same diff, same base — are domain
-//! logic in `review::approve`; what lives here is the SQL, so the schema has one
-//! owner (§6 M-1).
-
use rusqlite::{params, OptionalExtension, Transaction};
use crate::db::Db;
diff --git a/src/db/builds.rs b/src/db/builds.rs
index 072836b..8598dd3 100644
--- a/src/db/builds.rs
+++ b/src/db/builds.rs
@@ -1,5 +1,3 @@
-//! Build queue rows: deterministic ids, leases, step checkpoints (§8.1, §8.2).
-
use rusqlite::{params, Connection, OptionalExtension};
use crate::db::{BuildState, Db, StepState};
@@ -160,12 +158,10 @@ pub fn extend_lease(db: &Db, id: &str, lease_secs: i64) -> Result<()> {
})
}
-/// Reaper pass (§8.2): expired leases go back to the queue and their in-flight
-/// step is marked interrupted, so the checkpoint decides where it resumes.
+/// Reaper pass (§8.2): expired leases go back to the queue and their in-flight step
+/// is marked interrupted, so the checkpoint decides where it resumes.
///
-/// Both `leased` and `running` are reaped: a worker sets `running` as soon as it
-/// starts a step, so a process that dies mid-step leaves a `running` row, not a
-/// `leased` one. Reaping only `leased` would strand every real crash.
+/// Both `leased` and `running` are reaped: a mid-step death leaves a `running` row.
pub fn reap_expired(db: &Db) -> Result<usize> {
let now = time::now();
db.writer.tx(move |tx| {
@@ -195,10 +191,8 @@ pub fn reap_expired(db: &Db) -> Result<usize> {
/// The one way a build changes state, usable inside a transaction.
///
-/// The write is a compare-and-swap: only a row currently in one of `to`'s legal
-/// predecessor states is updated, so two workers cannot both land a terminal
-/// state, and a zombie worker whose lease was reaped gets an error instead of
-/// silently rewriting a build that has since been handed to somebody else.
+/// The write is a compare-and-swap: only a row in one of `to`'s legal predecessor
+/// states is updated, so a zombie worker whose lease was reaped gets an error.
fn transition_in_tx(
tx: &mut rusqlite::Transaction<'_>,
id: &str,
@@ -248,13 +242,10 @@ pub fn block_on(db: &Db, id: &str, blocked_on: &[String]) -> Result<()> {
})
}
-/// Re-check blocked builds whenever a publish lands (§10.4).
/// Requeue blocked builds whose blocking packages have since arrived (§10.4).
///
-/// Not "requeue everything that is blocked": the dispatcher calls this every
-/// pass, and requeueing a build that will immediately block again is a busy loop
-/// that burns a claim and a plan step each tick. A build only goes back on the
-/// queue when every name it is waiting for is actually in the index now.
+/// Not "requeue everything that is blocked": the dispatcher calls this every pass,
+/// and requeueing a build that will immediately block again burns a claim each tick.
pub fn requeue_blocked(db: &Db) -> Result<usize> {
let now = time::now();
db.writer.tx(move |tx| {
@@ -265,9 +256,8 @@ pub fn requeue_blocked(db: &Db) -> Result<usize> {
.collect::<rusqlite::Result<Vec<(String, String)>>>()?;
out
};
- // The index membership check is one query for the whole pass, not one
- // per dependency of every blocked build (m-17): the old shape was an N+1
- // whose N grew with the backlog, and it ran on the dispatcher's hot loop.
+ // The index membership check is one query for the whole pass, not one per
+ // dependency of every blocked build (m-17), on the dispatcher's hot loop.
let in_index: std::collections::HashSet<String> = {
let mut stmt = tx.prepare("SELECT name FROM package WHERE state='in_index'")?;
let names = stmt
@@ -544,8 +534,7 @@ pub fn current_state(c: &Connection, id: &str) -> Result<Option<BuildState>> {
/// Claim up to `limit` queued builds in one `BEGIN IMMEDIATE` transaction and
/// hand them to workers (§8.2). SQLite has no `SKIP LOCKED`, but with exactly one
-/// writer the claim cannot race: the SELECT and the UPDATE are the same
-/// transaction, so no other claimer can see a row in between.
+/// writer the claim cannot race: the SELECT and the UPDATE are one transaction.
pub fn claim_batch(db: &Db, owner: &str, limit: usize, lease_secs: i64) -> Result<Vec<String>> {
if limit == 0 {
return Ok(Vec::new());
@@ -597,9 +586,9 @@ pub fn requeue_transient(db: &Db, id: &str) -> Result<()> {
.tx(move |tx| transition_in_tx(tx, &id, BuildState::Queued, None))
}
-/// Explicitly retry a failed build (§8.4). This is a human decision, not a
-/// policy: the failed step is put back to pending so it runs again, everything
-/// that succeeded stays checkpointed, and the attempt counter keeps counting.
+/// Explicitly retry a failed build (§8.4): the failed step goes back to pending,
+/// everything that succeeded stays checkpointed, and the attempt counter keeps
+/// counting.
pub fn retry(db: &Db, id: &str) -> Result<()> {
let id = id.to_string();
db.writer.tx(move |tx| {
@@ -609,8 +598,7 @@ pub fn retry(db: &Db, id: &str) -> Result<()> {
params![id],
)?;
// The move itself goes through the machine, so requeueing a build that
- // already published is refused with a reason instead of silently
- // re-queueing a row whose every step is checkpointed as done.
+ // already published is refused with a reason.
transition_in_tx(tx, &id, BuildState::Queued, None)?;
tx.execute("UPDATE build SET cancel_requested=0 WHERE id=?1", params![id])?;
Ok(())
diff --git a/src/db/candidates.rs b/src/db/candidates.rs
index 63c089f..631bf42 100644
--- a/src/db/candidates.rs
+++ b/src/db/candidates.rs
@@ -1,22 +1,10 @@
-//! The candidate table: its row shape, its column list, and every statement
-//! that touches it (§7.1).
-//!
-//! The *rules* about candidates — collapse into the open review, supersede once
-//! a human has looked, never re-raise a rejection — are domain logic and live
-//! in `review::candidates`. What lives here is SQL, so that the schema has one
-//! owner (§6 M-1). The `_in` functions take a transaction handle so a caller
-//! can compose several of them into one atomic decision; the decision itself
-//! stays with the caller.
-
use rusqlite::{params, OptionalExtension, Row, Transaction};
use crate::db::{CandidateRow, CandidateState, Db};
use crate::error::{Error, Result};
use crate::time;
-/// The columns `row_to_candidate` reads, spelled once. Every other table in
-/// this module already works this way; the candidate select was simply copied
-/// four times for long enough to be noticed (§6 m-3).
+/// The columns `row_to_candidate` reads, spelled once (§6 m-3).
const CANDIDATE_COLS: &str = "c.id, c.pkgbase_id, c.base_release_id, c.kind, c.snapshot_id, c.epoch, c.pkgver, \
c.pkgrel, c.upstream_pins_json, c.source_digests_json, c.identity_hash, c.diff_digest, \
c.revision, c.viewed_at, c.risk_level, c.risk_signals_json, c.missing_deps_json, c.state, \
@@ -130,10 +118,8 @@ pub fn review_subject_in(tx: &Transaction<'_>, candidate_id: i64) -> Result<Opti
/// Take a candidate out of the open state: approved, rejected or superseded.
///
-/// The write is a compare-and-swap on [`CandidateState`]: a decided review is
-/// never re-decided, so an approval racing a rejection — or a stale worker
-/// resolving a review that has since been superseded — fails instead of
-/// silently overwriting what a human did.
+/// The write is a compare-and-swap on [`CandidateState`]: a decided review is never
+/// re-decided, so an approval racing a rejection fails instead of overwriting.
pub fn resolve_in(tx: &Transaction<'_>, id: i64, to: CandidateState, at: &str) -> Result<()> {
let froms = CandidateState::predecessors(to);
let placeholders = froms.iter().map(|_| "?").collect::<Vec<_>>().join(",");
@@ -233,7 +219,7 @@ pub fn supersede_in(tx: &Transaction<'_>, id: i64) -> Result<()> {
}
/// Has this exact identity been rejected before? If so the watcher stays quiet
-/// until a human re-opens it (§7.1: "do not nag").
+/// until a human re-opens it (§7.1).
pub fn rejected_before_in(tx: &Transaction<'_>, pkgbase_id: i64, identity_hash: &str) -> Result<bool> {
Ok(tx
.query_row(
@@ -362,7 +348,7 @@ pub fn mark_viewed(db: &Db, id: i64) -> Result<()> {
})
}
-/// §7.1: a rejection can be re-opened. We retire the rejected row so it stops
+/// §7.1: a rejection can be re-opened. The rejected row is retired so it stops
/// suppressing the identity, and the next detection opens a fresh review.
pub fn reopen_rejected(db: &Db, id: i64) -> Result<()> {
let at = time::now();
diff --git a/src/db/migrations.rs b/src/db/migrations.rs
index 9e60132..b1954ab 100644
--- a/src/db/migrations.rs
+++ b/src/db/migrations.rs
@@ -1,9 +1,3 @@
-//! Hand-rolled `user_version` migration stepper (DESIGN.md §4, "Migrations").
-//!
-//! Each entry is applied inside its own transaction and bumps
-//! `PRAGMA user_version`. Migrations must never be edited after they ship; add
-//! a new one instead.
-
/// One migration: version number + SQL body.
pub struct Migration {
pub version: u32,
@@ -300,9 +294,8 @@ END;
"#;
/// Stage B results, keyed on `(pkgbase, recipe_hash, upstream_tip)` (§5.2).
-/// Re-resolving means cloning an upstream repo and running makepkg, so the
-/// answer is worth keeping; the same key also implements the per-pkgbase
-/// cooldown, because a fresh tip inside the window reuses the old answer.
+/// Re-resolving means cloning an upstream repo and running makepkg, so the answer
+/// is worth keeping; the same key also implements the per-pkgbase cooldown.
const M_0007_STAGE_B_CACHE: &str = r#"
CREATE TABLE stage_b_cache (
pkgbase_id INTEGER NOT NULL REFERENCES pkgbase(id),
@@ -319,14 +312,10 @@ CREATE TABLE stage_b_cache (
CREATE INDEX stage_b_cache_by_pkgbase ON stage_b_cache (pkgbase_id, resolved_at);
"#;
-/// Retention (§15, open question 21). The rows are never compacted — the whole
-/// point of the schema is that "which bytes produced this installed package"
-/// stays answerable — but the bytes on disk cannot be kept forever. So eviction
-/// is recorded rather than implied: the artifact row keeps its digest, size and
-/// provenance and gains a `purged_at`, which says "these bytes existed, and were
-/// dropped from the store at T" instead of silently pretending they are still
-/// there. A `cp` of the store and a database that disagrees about what is on disk
-/// is the failure mode this avoids.
+/// Retention (§15). The rows are never compacted — the schema exists so "which
+/// bytes produced this installed package" stays answerable — but the bytes on disk
+/// cannot be kept forever. So eviction is recorded rather than implied: the
+/// artifact row keeps its digest, size and provenance and gains a `purged_at`.
const M_0008_RETENTION: &str = r#"
ALTER TABLE artifact ADD COLUMN purged_at TEXT;
diff --git a/src/db/mod.rs b/src/db/mod.rs
index 403ced2..c271fe7 100644
--- a/src/db/mod.rs
+++ b/src/db/mod.rs
@@ -1,13 +1,3 @@
-//! SQLite access (DESIGN.md §11a).
-//!
-//! The app is multi-threaded and SQLite has one writer at a time, so there is
-//! exactly **one writer thread** owning the write connection. Everything that
-//! mutates is sent to it over a channel as a closure and answered with a
-//! `Result`. That makes "who can write" a compile-time fact (only [`Writer`]
-//! hands out `&mut`-equivalent access) and removes `SQLITE_BUSY` from the
-//! design entirely. Readers are thread-local, read-only connections; WAL lets
-//! them proceed concurrently with the writer.
-
pub mod approvals;
pub mod builds;
pub mod candidates;
@@ -18,11 +8,8 @@ pub mod queries;
pub use migrations::MIGRATIONS;
pub use model::*;
-/// Parse a state column into one of the state enums.
-///
-/// A value the code does not recognise fails the row instead of becoming a
-/// default: a build in a state we cannot name must not be listed, claimed, or
-/// rendered as if it were in one we could.
+/// Parse a state column into one of the state enums. A value the code does not
+/// recognise fails the row instead of becoming a default.
pub(crate) fn state_col<T: StateEnum>(col: usize, text: &str) -> rusqlite::Result<T> {
T::parse(text).ok_or_else(|| {
rusqlite::Error::FromSqlConversionFailure(
@@ -158,17 +145,13 @@ impl Writer {
self.alive.load(Ordering::SeqCst)
}
- /// Run `f` on the write connection and wait for its result.
- ///
- /// No transaction may span a build step: `f` should be short.
- /// Use [`Writer::tx`] for atomic multi-statement mutations.
+ /// Run `f` on the write connection and wait for its result. No transaction
+ /// may span a build step: `f` should be short.
///
- /// `pub(crate)`, not `pub`: the schema is the system's most protected asset
- /// and it has one owner, this module (§6 M-1). Code outside `db/` asks for a
- /// typed query instead of writing SQL. `pub(crate)` is what keeps the
- /// *crate's* users (the integration tests, the shim binaries) out; inside
- /// the crate the convention is enforced by `tests/schema_ownership.rs`,
- /// which fails the build if a SQL statement appears outside `src/db/`.
+ /// `pub(crate)`, not `pub`: the schema has one owner, this module (§6 M-1).
+ /// Inside the crate the convention is enforced by
+ /// `tests/schema_ownership.rs`, which fails the build if a SQL statement
+ /// appears outside `src/db/`.
pub(crate) fn call<T>(&self, f: impl FnOnce(&mut Connection) -> Result<T> + Send + 'static) -> Result<T>
where
T: Send + 'static,
@@ -182,8 +165,7 @@ impl Writer {
.map_err(|_| Error::db("writer actor gone"))?
}
- /// Run `f` inside a single `BEGIN IMMEDIATE` transaction on the write
- /// connection. This is how every multi-statement mutation is expressed.
+ /// Run `f` inside a single `BEGIN IMMEDIATE` transaction.
pub(crate) fn tx<T>(
&self,
f: impl FnOnce(&mut rusqlite::Transaction<'_>) -> Result<T> + Send + 'static,
@@ -216,17 +198,12 @@ impl Writer {
}
}
-/// The raw-SQL door, open only for the test harness (§6 M-9).
-///
-/// A fixture sometimes has to put the database in a state the typed API only
-/// reaches through several steps — a release published without a build, a
-/// pointer moved out from under a review. That is a reason to have a door, not
-/// a reason to leave it unlocked in the binary an operator runs, so it exists
-/// only under the `test-support` feature, which nothing but this crate's own
-/// dev-dependency enables.
+/// The raw-SQL door, open only for the test harness (§6 M-9). A fixture
+/// sometimes has to reach a state the typed API only reaches through several
+/// steps, but that is not a reason to leave the door unlocked in the binary an
+/// operator runs.
#[cfg(feature = "test-support")]
impl Writer {
- /// Run `f` in a transaction. Test fixtures only.
pub fn tx_for_tests<T>(
&self,
f: impl FnOnce(&mut rusqlite::Transaction<'_>) -> Result<T> + Send + 'static,
@@ -237,7 +214,6 @@ impl Writer {
self.tx(f)
}
- /// Run `f` on the write connection. Test fixtures only.
pub fn call_for_tests<T>(&self, f: impl FnOnce(&mut Connection) -> Result<T> + Send + 'static) -> Result<T>
where
T: Send + 'static,
@@ -246,10 +222,9 @@ impl Writer {
}
}
-/// Thread-local read-only connection pool.
-///
-/// One connection per thread per database file, opened read-only. HTTP handlers
-/// and watchers use this; they never touch the write connection.
+/// Thread-local read-only connection pool: one connection per thread per
+/// database file. HTTP handlers and watchers use this; they never touch the
+/// write connection.
pub struct Readers {
path: PathBuf,
}
@@ -275,9 +250,8 @@ impl Readers {
.iter()
.position(|(p, _)| p == &path)
.ok_or_else(|| Error::db("reader pool lost entry"))?;
- // Safety of the borrow: we only ever use one connection at a time
- // per thread and `f` cannot re-enter this function for the same pool
- // (it receives &Connection, not &Readers).
+ // We only ever use one connection at a time per thread, and `f`
+ // receives &Connection rather than &Readers, so it cannot re-enter.
let conn = &pool[idx].1;
f(conn)
})
@@ -321,13 +295,11 @@ pub fn backup_to(writer: &Writer, dest: &Path) -> Result<()> {
})
}
-/// The schema version a database file reports. A backup that does not open and
-/// answer with a migrated schema is a file, not a backup, and the only way to
-/// find that out is to ask it.
+/// The schema version a database file reports. A backup that does not answer
+/// with a migrated schema is a file, not a backup.
///
-/// Opened read-write and untouched by the connection pragmas: the point is to
-/// read one number from a file we are not going to modify, and a WAL database
-/// cannot even be opened read-only (it needs its sidecar).
+/// Opened read-write and untouched by the connection pragmas: a WAL database
+/// cannot even be opened read-only.
pub fn schema_version(path: &Path) -> Result<i64> {
let conn = rusqlite::Connection::open(path)
.map_err(|e| Error::db(format!("{} does not open: {e}", path.display())))?;
@@ -335,7 +307,6 @@ pub fn schema_version(path: &Path) -> Result<i64> {
.map_err(|e| Error::db(format!("{} has no schema version: {e}", path.display())))
}
-/// WAL size + checkpoint lag, surfaced on the Ops page and in metrics.
pub fn wal_stats(db: &Db) -> (u64, u64) {
let db_file = std::fs::metadata(db.writer.path()).map(|m| m.len()).unwrap_or(0);
let mut wal = db.writer.path().as_os_str().to_os_string();
diff --git a/src/db/model.rs b/src/db/model.rs
index 3fa2840..84701d1 100644
--- a/src/db/model.rs
+++ b/src/db/model.rs
@@ -1,35 +1,25 @@
-//! Row types and small value objects that appear in JSON columns.
-
use serde::{Deserialize, Serialize};
use crate::hash;
-/// One resolved upstream VCS source (DESIGN.md §3, "Three things to pin").
-///
-/// The commit SHA alone is sufficient: a git commit transitively commits to its
-/// tree, and a gitlink in that tree commits to any submodule's commit.
+/// One resolved upstream VCS source (DESIGN.md §3). The commit SHA alone is
+/// sufficient: a git commit transitively commits to its tree, and a gitlink in
+/// that tree commits to any submodule's commit.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct UpstreamPin {
- /// Index into the PKGBUILD `source=()` array.
pub index: usize,
pub url: String,
/// The ref we asked for: `HEAD`, a tag, or an explicit commit.
pub ref_: String,
- /// Branch the ref resolved to, when known.
pub branch: Option<String>,
- /// Resolved commit SHA. This is the pin.
+ /// The pin.
pub commit: String,
}
-/// A row of the Stage B cache (§5.2): the version that resolution produced,
-/// with the pins it was computed from.
-///
-/// This lives with the schema because the table lives here — the persistence
-/// layer must not name a type from the module that owns VCS probing, which is
-/// the dependency pointing the wrong way (§6 M-6). `watch::upstream::StageB`
-/// is this plus `cached`, and that extra field is the reason the two are not
-/// the same type: "was this answer a cache hit?" is a fact about the resolution
-/// that just happened, not a column.
+/// A row of the Stage B cache (§5.2): the version resolution produced, with the
+/// pins it was computed from. This lives with the schema because the table does —
+/// the persistence layer must not name a type from the module that owns VCS
+/// probing (§6 M-6).
#[derive(Debug, Clone)]
pub struct StageBCacheRow {
pub epoch: String,
@@ -55,20 +45,16 @@ pub struct SourceDigest {
/// sha256, or the resolved VCS commit for vcs sources.
pub digest: String,
pub size: u64,
- /// True when the PKGBUILD gave us no checksum to trust for this source —
- /// `SKIP`, a malformed digest, or nothing at all.
- ///
- /// It means that and nothing else (m-19). It used to be hardcoded `true` for
- /// VCS entries, where it reads as a warning the recipe never earned: a
- /// `-git` source has no checksum by design because the *pin* is the
- /// integrity. Ask [`SourceDigest::is_vcs`] when you need to know which of
- /// the two mechanisms protects an entry.
+ /// True when the PKGBUILD gave us no checksum to trust — `SKIP`, a malformed
+ /// digest, or nothing at all. It means that and nothing else (m-19): a `-git`
+ /// source has no checksum by design because the *pin* is the integrity. Ask
+ /// [`SourceDigest::is_vcs`] which mechanism protects an entry.
pub skip_declared: bool,
}
impl SourceDigest {
- /// True when this entry's integrity comes from a resolved commit rather than
- /// a content hash.
+ /// True when this entry's integrity comes from a resolved commit rather than a
+ /// content hash.
pub fn is_vcs(&self) -> bool {
matches!(self.kind.as_str(), "vcs" | "git" | "svn" | "hg" | "bzr")
}
@@ -93,35 +79,28 @@ pub struct Identity {
}
impl Identity {
- /// The hash that makes I3 a fact: two byte-identical inputs never produce
- /// two candidates, and any change to what becomes a byte in the artifact
- /// produces a new one.
- ///
- /// A digest of the canonical JSON of the identity tuple. This is the value
- /// an approval must echo: two candidates share an `identity_hash` only if
- /// every pin, digest and version in them is identical. A value that cannot
- /// be serialized is an error rather than a digest — a shared fallback digest
- /// would be the one way two identities could collide by accident.
+ /// The hash that makes I3 a fact: two byte-identical inputs never produce two
+ /// candidates, and any change to what becomes a byte in the artifact produces a
+ /// new one. This is the value an approval must echo; a value that cannot be
+ /// serialized is an error rather than a digest, because a shared fallback
+ /// digest would be the one way two identities could collide by accident.
pub fn hash(&self) -> crate::error::Result<String> {
Ok(format!("sha256:{}", hash::hex(hash::canonical_json(self)?.as_bytes())))
}
}
-/// The review state machine (§7.1).
-///
-/// A candidate is what a human decides on, and the decision is the one thing in
-/// this system that must never be overwritten by accident: an approval that
-/// silently replaced a rejection, or a superseded review resurrected, would
-/// break I2 and I3 without any symptom. So the states are an enum, and
+/// The review state machine (§7.1). A decision must never be overwritten by
+/// accident — an approval that silently replaced a rejection would break I2 and
+/// I3 without any symptom — so the states are an enum and
/// [`crate::db::candidates::resolve_in`] refuses a move the machine forbids.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum CandidateState {
- /// Open: nobody has decided yet. The only state a reviewer can act on.
+ /// The only state a reviewer can act on.
PendingReview,
Approved,
Rejected,
- /// Frozen: a newer review of the same pkgbase took its place (§7.1).
+ /// A newer review of the same pkgbase took its place (§7.1).
Superseded,
/// Not approved because something it needs is missing (§10.4).
Blocked,
@@ -150,13 +129,11 @@ impl CandidateState {
CandidateState::ALL.iter().copied().find(|c| c.as_str() == s)
}
- /// The state a reviewer can still act on.
pub fn is_open(&self) -> bool {
*self == CandidateState::PendingReview
}
- /// May a candidate in this state be written to `to`? Re-writing the state it
- /// already has is a no-op, not a move.
+ /// Re-writing the state a row already has is a no-op, not a move.
pub fn can_transition(&self, to: CandidateState) -> bool {
use CandidateState::*;
if *self == to {
@@ -195,7 +172,6 @@ pub mod candidate_kind {
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ReleaseState {
- /// In the served index.
Published,
/// Taken out of the index (§9 withdrawal); the row stays (§15).
Withdrawn,
@@ -222,8 +198,7 @@ impl ReleaseState {
ReleaseState::ALL.iter().copied().find(|r| r.as_str() == s)
}
- /// Withdrawal is the only move a release makes on its own; a failed-unbuilt
- /// release is a record of an attempt, and a published one is live.
+ /// Withdrawal is the only move a release makes on its own.
pub fn can_transition(&self, to: ReleaseState) -> bool {
use ReleaseState::*;
if *self == to {
@@ -243,8 +218,8 @@ impl std::fmt::Display for ReleaseState {
}
/// What the state enums below have in common: a closed set of column values,
-/// parsed where a row is read. `db::state_col` uses this to fail a row whose
-/// state the code does not know instead of defaulting it.
+/// parsed where a row is read, so `db::state_col` can fail an unknown state
+/// instead of defaulting it.
pub trait StateEnum: Copy + Sized {
/// The name of the machine, for the error message.
const KIND: &'static str;
@@ -272,17 +247,11 @@ impl_state_enum!(StepState, "build step");
impl_state_enum!(ReleaseState, "release");
impl_state_enum!(SubscriptionState, "subscription");
-/// The build state machine (§7.1, §8.2).
-///
-/// This used to be seven `&str` constants and a `set_state(&str)` that wrote any
-/// string a caller invented, so the machine existed only as `WHERE state IN
-/// (...)` clauses scattered across six modules — nothing could tell you that
-/// `succeeded → running` is nonsense. The enum is the machine: a state is one
-/// of these seven, it is parsed where a row is read, and `can_transition` is
-/// the only way a write happens.
+/// The build state machine (§7.1, §8.2). A state is one of these seven, it is
+/// parsed where a row is read, and `can_transition` is the only way a write
+/// happens.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub enum BuildState {
- /// Approved and waiting for a worker.
Queued,
/// Claimed by a worker with a lease (§8.2).
Leased,
@@ -306,8 +275,8 @@ impl BuildState {
BuildState::Cancelled,
];
- /// The text in the `state` column. The spelling is part of the schema: the
- /// reaper, the dispatcher and the UI all speak it.
+ /// The text in the `state` column — a spelling the reaper, dispatcher and UI
+ /// all speak.
pub fn as_str(&self) -> &'static str {
match self {
BuildState::Queued => "queued",
@@ -320,17 +289,14 @@ impl BuildState {
}
}
- /// The only way in from the database text. An unrecognised state is `None`,
- /// and the row boundary turns that into an error rather than a silent
- /// fallback: a state we cannot name is a state we must not act on.
+ /// An unrecognised state is `None`, and the row boundary turns that into an
+ /// error: a state we cannot name is one we must not act on.
pub fn parse(s: &str) -> Option<BuildState> {
BuildState::ALL.iter().copied().find(|b| b.as_str() == s)
}
- /// Nothing happens to a finished build by itself. `Succeeded` is final —
- /// the release is published and the row is history (§15). `Failed` and
- /// `Cancelled` end a worker's involvement, and only an explicit human
- /// requeue or resume moves them again ([`BuildState::can_transition`]).
+ /// Nothing happens to a finished build by itself; only an explicit human
+ /// requeue or resume moves it again.
pub fn is_terminal(&self) -> bool {
matches!(
self,
@@ -338,17 +304,11 @@ impl BuildState {
)
}
- /// May a row in this state be written to `to`?
- ///
- /// Writing the state a row already has is always allowed: it is a no-op, not
- /// a move. The step loop re-asserts `Running` at every step boundary (§8.3),
- /// and re-running a finished build must stay harmless rather than turn into
- /// an error.
- ///
- /// Everything else is refused by [`crate::db::builds::set_state`], and the
- /// refusals are the point: nothing revives a `Succeeded` build, and a build
- /// reaped back to `Queued` cannot be completed by the zombie worker that
- /// lost its lease — that refusal is the alarm.
+ /// Writing the state a row already has is always allowed: the step loop
+ /// re-asserts `Running` at every step boundary (§8.3). Everything else is
+ /// refused by [`crate::db::builds::set_state`], and the refusals are the point:
+ /// nothing revives a `Succeeded` build, and a build reaped back to `Queued`
+ /// cannot be completed by the zombie worker that lost its lease.
pub fn can_transition(&self, to: BuildState) -> bool {
use BuildState::*;
if *self == to {
@@ -356,16 +316,13 @@ impl BuildState {
}
match self {
// The dispatcher claims queued builds; `aur-build run <id>` runs one
- // in the foreground without a lease, so `Running` is legal from here
- // too. A dependency can be discovered before a worker ever starts.
+ // in the foreground without a lease.
Queued => matches!(to, Leased | Running | BlockedMissingDep | Cancelled),
Leased => matches!(to, Running | Queued | BlockedMissingDep | Succeeded | Failed | Cancelled),
Running => matches!(to, Queued | BlockedMissingDep | Succeeded | Failed | Cancelled),
BlockedMissingDep => matches!(to, Queued | Cancelled),
- // A failed build is resumed on the same row — that is I5 (the step
- // checkpoints say where to continue) and §8.4's human requeue.
+ // A failed build is resumed on the same row — that is I5 (§8.4).
Failed => matches!(to, Queued | Running),
- // §8.4: requeue is a human decision, not a policy.
Cancelled => to == Queued,
Succeeded => false,
}
@@ -381,7 +338,6 @@ impl BuildState {
.collect()
}
- /// The states the queue considers "in flight" for metrics and the index.
pub fn active() -> &'static [BuildState] {
&[
BuildState::Queued,
@@ -398,11 +354,9 @@ impl std::fmt::Display for BuildState {
}
}
-/// The step checkpoint state machine (§8.3, I5).
-///
-/// The checkpoint row is what a resumed build reads to decide what not to redo,
-/// so the rule that matters is that a completed checkpoint is frozen: a step
-/// recorded `succeeded` or `skipped` is never re-run and never rewritten.
+/// The step checkpoint state machine (§8.3, I5). The checkpoint row is what a
+/// resumed build reads to decide what not to redo, so a completed checkpoint is
+/// frozen.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum StepState {
@@ -441,7 +395,7 @@ impl StepState {
}
/// I5: the resume skips a step in one of these two states, so nothing may
- /// move it again — a checkpoint that can be rewritten is not a checkpoint.
+ /// move it again.
pub fn is_done(&self) -> bool {
matches!(self, StepState::Succeeded | StepState::Skipped)
}
@@ -565,13 +519,10 @@ pub struct SourceEntry {
pub url: String,
/// Explicit filename (`::name` / `::` prefix handling).
pub filename: Option<String>,
- /// `#commit=` fragment.
pub commit: Option<String>,
- /// `#tag=` fragment.
pub tag: Option<String>,
- /// `#branch=` fragment.
pub branch: Option<String>,
- /// VCS kind if the url is prefixed `git+`, `svn+`, `hg+`, `bzr+`.
+ /// Set when the url is prefixed `git+`, `svn+`, `hg+`, `bzr+`.
pub vcs: Option<String>,
/// True for files shipped inside the AUR repo (no scheme).
pub local: bool,
@@ -610,21 +561,18 @@ pub struct Recipe {
pub install: Option<String>,
/// Names of the binary packages this pkgbase emits (split pkgbases have N).
pub pkgnames: Vec<String>,
- /// Per-package depends, for split pkgbases.
pub pkg_depends: Vec<(String, Vec<String>)>,
/// Raw PKGBUILD text, for display and diffing.
pub pkgbuild: String,
- /// Raw .SRCINFO text when it was present.
pub srcinfo: Option<String>,
/// True if `--skippgpcheck` appears in the PKGBUILD.
pub skipgpcheck: bool,
- /// Parsed `source=()` entries. Derived from `source`, so not serialized.
+ /// Derived from `source`, so not serialized.
#[serde(skip, default)]
pub source_entries: Vec<SourceEntry>,
}
impl Recipe {
- /// `epoch:pkgver-pkgrel` as displayed to consumers.
pub fn full_version(&self) -> String {
crate::pkgver::full_version(&self.epoch, &self.pkgver, &self.pkgrel)
}
diff --git a/src/db/queries.rs b/src/db/queries.rs
index fe0518f..924051d 100644
--- a/src/db/queries.rs
+++ b/src/db/queries.rs
@@ -1,6 +1,3 @@
-//! Typed query helpers. Everything that mutates goes through the writer actor;
-//! everything that reads takes a `&Connection` from the reader pool.
-
use rusqlite::{params, params_from_iter, OptionalExtension, Row};
use crate::db::*;
@@ -12,9 +9,7 @@ use crate::time;
/// Every setting, for the settings page.
///
/// Row-error policy, applied everywhere in `db` (m-9): a row that cannot be read
-/// fails the query. `filter_map(|r| r.ok())` used to drop such rows silently,
-/// which is fine for a page that merely looks incomplete and fatal for the
-/// callers that decide what to reap, what to claim, and what is stale.
+/// fails the query rather than being dropped silently.
pub fn all_settings(db: &Db) -> Result<Vec<(String, String)>> {
db.read(|c| {
let mut st = c.prepare("SELECT key, value FROM settings ORDER BY key")?;
@@ -34,12 +29,10 @@ pub fn setting(db: &Db, key: &str) -> Result<Option<String>> {
/// An integer setting, or `default`.
///
/// The policy, stated once (m-9): a *missing* setting is normal — the default is
-/// the answer, and every knob in `settings` has one. A setting that is present
-/// but unparseable, or a read that failed outright, is not normal, and silently
-/// returning the default would hide an operator's typo behind a config that
-/// looks applied. Both still fall back — these are tuning knobs, and refusing to
-/// start over `stage_b_cooldown = 86400x` is worse than using the default — but
-/// they fall back out loud.
+/// the answer. A setting present but unparseable, or a read that failed, is not,
+/// and silently returning the default would hide an operator's typo. Both still
+/// fall back, because refusing to start over a tuning knob is worse — but they
+/// fall back out loud.
pub fn setting_i64(db: &Db, key: &str, default: i64) -> i64 {
match setting(db, key) {
Ok(None) => default,
@@ -101,14 +94,9 @@ pub fn audit(
})
}
-/// An audit row to append inside someone else's transaction.
-///
-/// Build one with [`AuditEntry::human`] or [`AuditEntry::system`] rather than
-/// by writing the literal: `actor_kind` is a closed set and the timestamp is
-/// not the caller's to improvise (§6 m-4). Three review sites had each
-/// hand-built this struct, and their `detail` shapes drifted until the log
-/// could not answer, for two of the three, which candidate bytes the decision
-/// was about.
+/// An audit row to append inside someone else's transaction. Build one with
+/// [`AuditEntry::human`] or [`AuditEntry::system`]: `actor_kind` is a closed set
+/// and the timestamp is not the caller's to improvise (§6 m-4).
#[derive(Debug)]
pub struct AuditEntry<'a> {
pub at: &'a str,
@@ -145,10 +133,8 @@ impl<'a> AuditEntry<'a> {
}
}
-/// Append an audit row inside a caller's transaction (I10). This is the variant
-/// every multi-statement mutation uses: the record of a decision commits with
-/// the decision or not at all, so there is no window where an audit row
-/// describes a change that was rolled back.
+/// Append an audit row inside a caller's transaction (I10), so the record of a
+/// decision commits with the decision or not at all.
pub fn audit_in(tx: &rusqlite::Transaction<'_>, e: &AuditEntry<'_>) -> Result<()> {
tx.execute(
"INSERT INTO audit (at, actor_kind, actor, action, entity, entity_id, detail_json)
@@ -523,16 +509,12 @@ const RELEASE_COLS_R: &str = "r.id, r.pkgbase_id, r.candidate_id, r.approval_id,
r.recipe_hash, r.upstream_pins_json, r.source_digests_json, r.epoch, r.pkgver, r.pkgrel, \
r.world_snapshot_id, r.state, r.published_at";
-/// Withdraw a published release and remove the packages it served (§9
-/// `repo-remove`, decision 23). Runs in the caller's transaction so the removal
-/// and the audit row that explains it are one fact.
-/// Take a release out of the served index (§9, decision 23).
+/// Take a release out of the served index (§9, decision 23), in the caller's
+/// transaction so the removal and the audit row explaining it are one fact.
///
/// Refuses a release that is not currently published (m-10): re-withdrawing used
-/// to report success and rewrite nothing, so an operator who clicked twice — or
-/// withdrew a release that had never been live — got a green result and no
-/// explanation. The write is a compare-and-swap on `state='published'`, and the
-/// refusal names the state that was actually there.
+/// to report success and rewrite nothing. The write is a compare-and-swap on
+/// `state='published'`, and the refusal names the state that was actually there.
pub fn withdraw_release_in(tx: &rusqlite::Transaction<'_>, release_id: i64) -> Result<()> {
let n = tx.execute(
"UPDATE release SET state='withdrawn' WHERE id=?1 AND state='published'",
@@ -679,10 +661,9 @@ pub fn index_version(db: &Db, name: &str) -> Result<Option<String>> {
})
}
-/// The exact artifact we serve for a package name: `(version, digest)` of the
-/// in-index row's artifact. This is what a build's lease manifest pins — the
-/// dependency arrives as these bytes or the build fails closed (§8,
-/// provisioning); nothing about it is re-resolved at build time.
+/// The exact artifact we serve for a package name: `(version, digest)`. This is
+/// what a build's lease manifest pins — the dependency arrives as these bytes or
+/// the build fails closed (§8).
pub fn index_artifact(db: &Db, name: &str) -> Result<Option<(String, String)>> {
db.read(|c| {
c.query_row(
@@ -766,9 +747,7 @@ pub fn builds_for_pkgbase(db: &Db, pkgbase_id: i64, limit: i64) -> Result<Vec<cr
// ------------------------------------------------------------ publish writes --
//
// Publishing is the one externally visible step, so every statement it needs is
-// here and the *decision* stays in `pipeline::publish`: the caller opens the
-// transaction, calls these in order, and bails if the compare-and-swap says the
-// world moved (I4).
+// here and the *decision* stays in `pipeline::publish` (I4).
/// The on-disk path of an artifact, by id.
pub fn artifact_path(db: &Db, id: i64) -> Result<Option<String>> {
@@ -899,9 +878,8 @@ pub fn insert_package_in(
// ------------------------------------------------------------ staleness reads --
//
-// Staleness is derived on read (§10.2), and these are the reads it is derived
-// from. They return plain tuples: the *meaning* ("this dependency moved") is
-// `watch::staleness`'s business, the SQL is this module's.
+// Staleness is derived on read (§10.2). These return plain tuples: the *meaning*
+// is `watch::staleness`'s business, the SQL is this module's.
/// `(pkgbase, world members JSON)` for every published release, taken from the
/// world snapshot its build recorded (§10.1).
@@ -944,13 +922,12 @@ pub fn served_vs_offered_pkgvers(db: &Db) -> Result<Vec<(String, String, String)
})
}
-/// The `srcinfo_json` of the recipe the index's copy of a package was built
-/// from — what its dependency list actually said.
-/// Every in-index package's recipe JSON, as (name, srcinfo_json).
+/// Every in-index package's recipe JSON, as (name, srcinfo_json) — what each
+/// dependency list actually said.
///
-/// One query, not one per package (m-17). `watch::staleness::dependents_of`
-/// wants the whole table: asking for each package by name was an N+1 whose N is
-/// the size of the index, on a code path that runs after every publish.
+/// One query, not one per package (m-17): `watch::staleness::dependents_of`
+/// wants the whole table, and asking per name was an N+1 on a path that runs
+/// after every publish.
pub fn index_recipes(db: &Db) -> Result<Vec<(String, String)>> {
db.read(|c| {
let mut stmt = c.prepare(
@@ -1314,10 +1291,7 @@ pub fn list_audit(db: &Db, limit: i64) -> Result<Vec<AuditRow>> {
// -------------------------------------------------------------- metrics reads --
//
-// The metrics surface is derived from live state, never stored (§10.3: a
-// counter that is written is a counter that can drift out of truth). These are
-// the reads that derivation is made of, and they live here because the schema
-// they read lives here.
+// The metrics surface is derived from live state, never stored (§10.3).
/// The `count(*)` idiom in one place, so a metric cannot accidentally become a
/// `count(*)` of a join.
@@ -1412,9 +1386,8 @@ pub fn last_gc_age_secs(db: &Db, now: &str) -> Result<Option<i64>> {
Ok(at.and_then(|t| time::delta_secs(now, &t)))
}
-/// Seconds since the last successful poll of any source, if there has been one.
-/// This is the metric that catches a watcher that stopped, which no log line
-/// will tell you about.
+/// Seconds since the last successful poll of any source. This is the metric that
+/// catches a watcher that stopped.
pub fn last_poll_age_secs(db: &Db, now: &str) -> Result<Option<i64>> {
let at = db.read(|c| {
c.query_row("SELECT max(last_checked_at) FROM subscription", [], |r| r.get::<_, Option<String>>(0))
@@ -1575,10 +1548,9 @@ pub fn index_pkgbase_drift(db: &Db) -> Result<(Vec<String>, Vec<String>)> {
})
}
-/// An approved change whose build failed and which therefore never reached the
-/// index (§8.4). This is the state that must never look healthy: a human said
-/// yes, the build died, and the index is quietly still serving the previous
-/// version. Surfacing it is the whole point of `approved_but_unbuilt`.
+/// An approved change whose build failed and never reached the index (§8.4). A
+/// human said yes, the build died, and the index is quietly still serving the
+/// previous version; surfacing that is the whole point.
#[derive(Debug, Clone)]
pub struct Unbuilt {
pub pkgbase: String,
@@ -1593,9 +1565,8 @@ pub struct Unbuilt {
pub fn approved_but_unbuilt(db: &Db) -> Result<Vec<Unbuilt>> {
db.read(|c| {
// The version strings are assembled in Rust by `pkgver::full_version`,
- // not by a CASE expression here (m-18): the epoch-omitted form is a rule
- // of ours, and a second copy of it in SQL is a second rule that can
- // disagree with the first.
+ // not by a CASE expression here (m-18): a second copy of the
+ // epoch-omission rule in SQL is a second rule that can disagree.
let mut stmt = c.prepare(
"SELECT p.name,
cnd.epoch, cnd.pkgver, cnd.pkgrel,
diff --git a/src/error.rs b/src/error.rs
index 342c628..f849f83 100644
--- a/src/error.rs
+++ b/src/error.rs
@@ -1,5 +1,3 @@
-//! Error type shared across the application.
-
use std::fmt;
#[derive(Debug, thiserror::Error)]
@@ -30,20 +28,17 @@ pub enum Error {
Invalid(String),
#[error("blocked: {0}")]
Blocked(String),
- /// The sandbox pool could not fit a lease right now. Not a failure and not
- /// a retry: the build waits, the same way it waits for a dependency it
- /// publishes (§10.4). A quota is a fact about capacity, not a bug.
+ /// The sandbox pool could not fit a lease right now. Not a failure and not a
+ /// retry: the build waits, as it waits for a dependency it publishes
+ /// (§10.4). A quota is a fact about capacity, not a bug.
#[error("sandbox pool exhausted: {0}")]
PoolExhausted(String),
- /// The world inside the sandbox is not the world the plan approved:
- /// a pinned dependency did not land, or the closure was incomplete.
- /// Fail-closed with its own class so a test (and an operator) can tell
- /// "the sandbox lied" apart from "the sandbox broke".
+ /// The world inside the sandbox is not the world the plan approved: a pinned
+ /// dependency did not land, or the closure was incomplete. Its own class so
+ /// a test can tell "the sandbox lied" from "the sandbox broke".
#[error("world mismatch: {0}")]
WorldMismatch(String),
- /// A failure the outside world caused and a retry may clear: an unreachable
- /// upstream, a half-written mirror. Distinct from a deterministic failure,
- /// which must never be retried into a different answer (§8.4).
+ /// A failure the outside world caused and a retry may clear (§8.4).
#[error("transient: {0}")]
Transient(String),
#[error("{0}")]
@@ -86,25 +81,19 @@ impl Error {
}
/// True when the sandbox pool, not the build, is the problem: the build
- /// should block and wait, not fail and not be retried into a different
- /// answer.
+ /// blocks and waits rather than failing.
pub fn is_pool_exhausted(&self) -> bool {
matches!(self, Error::PoolExhausted(_))
}
- /// True when a retry could plausibly help (§8.4): an unreachable upstream, a
- /// mirror that 5xx'd, a connection that reset.
+ /// True when a retry could plausibly help (§8.4).
///
- /// `Error::Io` is *not* automatically transient (m-14). `ENOSPC` and
- /// `EACCES` are `Io`, and treating them as retryable meant a full disk or a
- /// misconfigured root turned into three identical failures, a shrug, and a
- /// build that never got the operator's attention. Only the kinds that mean
- /// "the same call might work in a moment" are retried.
+ /// `Error::Io` is *not* automatically transient (m-14): `ENOSPC` and `EACCES`
+ /// are `Io`, and retrying them burns attempts while a full disk goes unnoticed.
pub fn is_transient(&self) -> bool {
match self {
Error::Http(_) | Error::Transient(_) => true,
- // A quota is capacity, not a hiccup: retrying a build that has no
- // sandbox just burns attempts. It blocks instead.
+ // A quota is capacity, not a hiccup; the build blocks instead.
Error::PoolExhausted(_) | Error::WorldMismatch(_) => false,
Error::Io(e) => matches!(
e.kind(),
@@ -129,9 +118,6 @@ mod tests {
#[test]
fn a_full_disk_is_not_a_retryable_failure() {
- // m-14: `Error::Io` used to mean "retry", so ENOSPC and EACCES — both
- // plain `Io` — turned into three identical failures and a build that
- // never announced itself as broken.
let enospc = Error::Io(std::io::Error::from_raw_os_error(28));
let eacces = Error::Io(std::io::Error::from_raw_os_error(13));
assert!(!enospc.is_transient(), "a full disk does not clear itself between retries");
@@ -146,7 +132,6 @@ mod tests {
assert!(Error::Http("connection reset".into()).is_transient());
assert!(!Error::invalid("recipe has no pkgbase").is_transient());
assert!(!Error::fail_closed("identity hash moved").is_transient());
- // A full pool waits; it does not retry. A lying world fails closed.
assert!(!Error::pool_exhausted("at quota").is_transient());
assert!(!Error::world_mismatch("missing pinned dep").is_transient());
assert!(Error::pool_exhausted("at quota").is_pool_exhausted());
diff --git a/src/fetch.rs b/src/fetch.rs
index c1c4575..c802339 100644
--- a/src/fetch.rs
+++ b/src/fetch.rs
@@ -1,9 +1,3 @@
-//! Outbound HTTP. `ureq` is blocking, which is the whole point of this stack
-//! (DESIGN.md §4: "`reqwest` pulls in tokio even in blocking mode — avoid").
-//!
-//! `file://` is supported as a first-class scheme so the test corpus can serve
-//! sources from disk with no network (§16a).
-
use std::io::{Read, Write};
use std::path::PathBuf;
diff --git a/src/git.rs b/src/git.rs
index 6c1f442..4520548 100644
--- a/src/git.rs
+++ b/src/git.rs
@@ -1,9 +1,3 @@
-//! Shelling out to `git` (DESIGN.md §4: "shell out to git ... avoids libgit2
-//! build pain").
-//!
-//! Every git operation the system performs goes through here so the subprocess
-//! surface is auditable in one place.
-
use std::path::Path;
use std::process::{Command, Output};
@@ -40,8 +34,8 @@ pub fn git_ok(cwd: Option<&Path>, args: &[&str]) -> bool {
git(cwd, args).is_ok()
}
-/// `git ls-remote <url> HEAD` — the cheap poll (§5.1). Returns the remote HEAD
-/// SHA, or `None` when the remote is gone (deletion / orphan handling).
+/// `git ls-remote <url> HEAD` — the cheap poll (§5.1). `None` when the remote is
+/// gone.
pub fn ls_remote_head(url: &str) -> Result<Option<String>> {
match git(None, &["ls-remote", url, "HEAD"]) {
Ok(out) => {
@@ -91,10 +85,9 @@ fn is_missing_remote(e: &Error) -> bool {
|| s.contains("404")
}
-/// Clone an AUR mirror. `--mirror` so that `git fetch` actually moves our refs
-/// (a plain clone would leave HEAD on the original commit), and **never**
-/// `--filter=blob:none`: a partial clone can lazily drop blobs and we must be
-/// able to materialize any historical commit forever (§5.1).
+/// Clone an AUR mirror. `--mirror` so that `git fetch` actually moves our refs,
+/// and **never** `--filter=blob:none`: a partial clone can lazily drop blobs and
+/// we must be able to materialize any historical commit forever (§5.1).
pub fn clone(url: &str, dest: &Path) -> Result<()> {
if dest.exists() {
return Ok(());
@@ -132,8 +125,8 @@ pub fn head(mirror: &Path) -> Result<String> {
Ok(git(Some(mirror), &["rev-parse", "HEAD"])?.trim().to_string())
}
-/// True if `commit` exists in the local mirror. Guards against a force-pushed
-/// AUR history making a pin vanish (§16 mirror divergence).
+/// True if `commit` exists in the local mirror. Guards against a force-pushed AUR
+/// history making a pin vanish (§16 mirror divergence).
pub fn has_commit(mirror: &Path, commit: &str) -> bool {
git_ok(Some(mirror), &["cat-file", "-e", &format!("{commit}^{{commit}}")])
}
@@ -192,8 +185,7 @@ pub fn materialize(mirror: &Path, commit: &str, dest: &Path) -> Result<()> {
Ok(())
}
-/// `git log --oneline range` — review context (§5.1) and the upstream delta
-/// panel (§6).
+/// `git log --oneline range` — review context (§5.1) and the upstream delta panel.
pub fn log_oneline(mirror: &Path, range: &str) -> Result<Vec<String>> {
let out = git(Some(mirror), &["log", "--oneline", range])?;
Ok(out.lines().map(|l| l.to_string()).collect())
diff --git a/src/hash.rs b/src/hash.rs
index 0321437..70c3791 100644
--- a/src/hash.rs
+++ b/src/hash.rs
@@ -1,6 +1,3 @@
-//! Hashing helpers. `sha256` hex strings are the currency of identity and
-//! provenance throughout the system (DESIGN.md §3, §5.3).
-
use sha2::{Digest, Sha256};
use std::io::{self, Read, Write};
@@ -22,10 +19,9 @@ pub fn short(bytes: &[u8], n: usize) -> String {
h[..n.min(h.len())].to_string()
}
-/// Stream-hash a reader, optionally teeing every byte into `sink`.
-///
-/// Used to hash a download while writing it into the source cache, so the
-/// bandwidth is paid for once (§5.3 "stream-hash, don't buffer").
+/// Stream-hash a reader, optionally teeing every byte into `sink` — so a
+/// download can be hashed into the source cache without paying for the
+/// bandwidth twice (§5.3).
pub fn digest_reader<R: Read>(mut r: R, mut sink: Option<&mut dyn Write>) -> io::Result<(String, u64)> {
let mut h = Sha256::new();
let mut buf = vec![0u8; 64 * 1024];
@@ -50,11 +46,8 @@ pub fn digest_file(path: &std::path::Path) -> io::Result<(String, u64)> {
digest_reader(&mut br, None)
}
-/// Hash of a canonical, sorted list of `(path, blob_hash)` pairs.
-///
/// This is `recipe_hash` (DESIGN.md §3): a digest over *every* file in the AUR
-/// snapshot tree — PKGBUILD, .SRCINFO, *.install and any shipped patches or
-/// assets — because a patch file shipped in the AUR repo is part of the recipe
+/// snapshot tree, because a patch shipped in the AUR repo is part of the recipe
/// and is a classic silent-change vector.
pub fn recipe_hash(entries: &[(String, String)]) -> String {
let mut sorted: Vec<&(String, String)> = entries.iter().collect();
@@ -69,17 +62,12 @@ pub fn recipe_hash(entries: &[(String, String)]) -> String {
hex::encode(h.finalize())
}
-/// Serialize a value to canonical JSON: compact, with every object's keys in
-/// sorted order, so equal values always produce equal bytes.
-///
-/// The ordering is not free in `serde_json` — a struct serializes in field
-/// declaration order and a map in whatever order it happens to hold — so the
-/// value is routed through `serde_json::Value`, whose map is a `BTreeMap`.
-/// That makes the name true rather than aspirational.
+/// Serialize to canonical JSON: compact, object keys sorted, so equal values always
+/// produce equal bytes. The value is routed through `serde_json::Value` because a
+/// struct otherwise serializes in field declaration order.
///
-/// A serialization failure is an error. It used to be `"{}"`, which meant every
-/// value that failed to serialize hashed to the same digest — and this is the
-/// function behind `Identity::hash`, the value an approval echoes (§6 M-2).
+/// A serialization failure is an error, not `"{}"`: this is the function behind
+/// `Identity::hash` (M-2).
pub fn canonical_json<T: serde::Serialize>(v: &T) -> Result<String, serde_json::Error> {
serde_json::to_string(&serde_json::to_value(v)?)
}
diff --git a/src/http/auth.rs b/src/http/auth.rs
index 8c56c1f..9689fd8 100644
--- a/src/http/auth.rs
+++ b/src/http/auth.rs
@@ -1,26 +1,11 @@
-//! Session and CSRF (§12: "form posts are plain `<form method=post>` with a
-//! CSRF token").
-//!
-//! One operator, one shared credential, no user table (§14). A session is an
-//! opaque random id held in memory; the CSRF token is derived from it, so a
-//! cross-site form cannot produce one it has not seen, and there is no token
-//! table to keep in step with the sessions.
-//!
-//! **The sid is the credential.** A sid is minted for anonymous visitors too,
-//! because the CSRF token has to be derivable before anyone has typed a
-//! password; what the password buys is the `authenticated` flag on one sid.
-//! Nothing else in the request proves who you are, which is why there is no
-//! separate "logged in" cookie to forge.
-
use std::collections::HashMap;
use std::sync::Mutex;
use std::sync::OnceLock;
use crate::hash;
-/// Live sids and whether each has passed the password gate. One map, so the
-/// two facts cannot drift apart: dropping a session removes its authentication
-/// with it.
+/// Live sids and whether each has passed the password gate. One map, so
+/// dropping a session removes its authentication with it.
static SESSIONS: OnceLock<Mutex<HashMap<String, bool>>> = OnceLock::new();
fn sessions() -> &'static Mutex<HashMap<String, bool>> {
@@ -28,19 +13,14 @@ fn sessions() -> &'static Mutex<HashMap<String, bool>> {
}
/// Random hex token from the system RNG, or `None` when there is no usable one.
-///
-/// The old version read `/dev/urandom` into a zeroed buffer, ignored every
-/// error, and hashed the result anyway (§6 m-13): a failed read produced a
-/// session id derived from a buffer of zeros plus the clock and a counter,
-/// which is guessable by anyone who can guess roughly when the process started
-/// — and nothing anywhere said the RNG had failed. A session id is the whole
-/// credential now (C-1), so "no RNG" is a refusal, not a weaker token.
+/// A session id is the whole credential (C-1), so "no RNG" is a refusal rather
+/// than a weaker, guessable token.
fn random_hex() -> Option<String> {
use std::io::Read;
let mut buf = [0u8; 32];
let mut f = std::fs::File::open("/dev/urandom").ok()?;
f.read_exact(&mut buf).ok()?;
- // Mixed in regardless, so two calls in the same instant still differ.
+ // Mixed in so two calls in the same instant still differ.
let nanos = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map(|d| d.as_nanos())
@@ -68,8 +48,7 @@ pub fn is_valid_session(sid: &str) -> bool {
sessions().lock().map(|s| s.contains_key(sid)).unwrap_or(false)
}
-/// Mark a session as having passed the password gate. Only ever called with a
-/// sid this process minted, and it cannot mint one: an unknown sid stays
+/// Mark a session as having passed the password gate. An unknown sid stays
/// unknown rather than being inserted as a side effect of a login attempt.
pub fn authenticate(sid: &str) {
if let Ok(mut s) = sessions().lock() {
@@ -79,8 +58,8 @@ pub fn authenticate(sid: &str) {
}
}
-/// The gate's whole question: is this sid one we issued *and* did someone type
-/// the password into a form on this session?
+/// The gate's whole question: is this sid one we issued, and did someone type
+/// the password into a form on it?
pub fn is_authenticated(sid: &str) -> bool {
sessions().lock().map(|s| s.get(sid).copied().unwrap_or(false)).unwrap_or(false)
}
@@ -91,8 +70,8 @@ pub fn drop_session(sid: &str) {
}
}
-/// The CSRF token for a session. Derived rather than stored: it cannot drift
-/// out of sync with the session, and it is cheap to recompute per request.
+/// The CSRF token for a session. Derived rather than stored, so it cannot drift
+/// out of sync with the session.
pub fn csrf_token(sid: &str) -> String {
hash::hex(format!("csrf|{sid}").as_bytes())[..32].to_string()
}
@@ -125,8 +104,8 @@ pub fn parse_cookies(header: &str) -> Vec<(String, String)> {
.collect()
}
-/// Check the shared password. Empty password means the UI is open, which is the
-// default on loopback; the CSRF gate still applies.
+/// An empty password means the UI is open, which is the default on loopback;
+/// the CSRF gate still applies.
pub fn password_ok(cfg: &crate::config::Config, given: &str) -> bool {
cfg.password.is_empty() || constant_time_eq(&cfg.password, given)
}
diff --git a/src/http/forms.rs b/src/http/forms.rs
index 6e36e38..03da7b8 100644
--- a/src/http/forms.rs
+++ b/src/http/forms.rs
@@ -1,8 +1,3 @@
-//! `application/x-www-form-urlencoded` parsing and HTML escaping.
-//!
-//! Deliberately tiny: the only forms in this application are ours, so we need
-//! decoding for names, versions and hashes — not a general MIME parser.
-
/// Percent-decode one token (`+` means space in a form body).
pub fn decode(s: &str) -> String {
let bytes = s.as_bytes();
diff --git a/src/http/mod.rs b/src/http/mod.rs
index 81c526c..11ea107 100644
--- a/src/http/mod.rs
+++ b/src/http/mod.rs
@@ -1,16 +1,3 @@
-//! The web surface (§12).
-//!
-//! `tiny_http`, thread-per-connection, blocking. Handlers **read** through the
-//! thread-local read-only connections and never touch the write connection;
-//! mutations are handed to the writer actor as a transaction request. That is
-//! what keeps a slow browser from ever holding the database lock.
-//!
-//! Two guards on every POST: a session id, and a CSRF token that must match
-//! it. The session id is the only credential the browser holds, and it counts
-//! as authentication only if someone typed the password into a form on that
-//! exact session (§12). Forms are plain `<form method=post>`, so the whole
-//! approval flow works with JavaScript switched off.
-
mod auth;
mod forms;
mod render;
@@ -36,10 +23,8 @@ pub struct Req {
pub body: String,
pub cookies: Vec<(String, String)>,
pub query_pairs: Vec<(String, String)>,
- /// The body's form pairs, parsed once when the request is decoded (n-3).
- /// `form_get` used to re-parse the whole body on every call, and a single
- /// handler — approve, with its two hashes, its note and its CSRF token —
- /// asks five times.
+ /// The body's form pairs, parsed once when the request is decoded (n-3) — a
+ /// single handler asks for five of them.
pub form_pairs: Vec<(String, String)>,
/// Whether the client said it can take gzip. Used to decide whether to hand
/// out the precompressed static asset.
@@ -67,9 +52,9 @@ pub struct Res {
pub content_type: String,
pub body: Vec<u8>,
pub headers: Vec<(String, String)>,
- /// When set, the response body is produced by reading this to EOF instead of
- /// `body`. Used for the log tail (§13), which must stream bytes as a build
- /// appends them rather than buffering a response that never finishes.
+ /// When set, the body is produced by reading this to EOF instead of `body`.
+ /// Used for the log tail (§13), which must stream bytes as a build appends
+ /// them rather than buffering a response that never finishes.
pub stream: Option<Box<dyn std::io::Read + Send>>,
/// Length of `stream` when it is known up front, so the response can carry a
/// Content-Length instead of chunked transfer encoding.
@@ -84,8 +69,8 @@ impl Res {
Self { status, content_type: "text/plain; charset=utf-8".into(), body: body.into_bytes(), headers: Vec::new(), stream: None, stream_len: None }
}
/// A streamed response. `known_len` lets a static file be sent with a
- /// Content-Length instead of chunked, which is what a browser wants for a
- /// file it already knows the size of.
+ /// Content-Length, which is what a browser wants for a file whose size it
+ /// already knows.
pub fn stream(content_type: &str, reader: impl std::io::Read + Send + 'static, known_len: Option<usize>) -> Self {
Self {
status: 200,
@@ -221,8 +206,8 @@ fn serve(state: Arc<State>, mut request: tiny_http::Request) -> std::io::Result<
request.respond(builder)
}
-/// Route table (§12). Everything is one flat match: there is no middleware
-/// stack, just the session gate and then a path.
+/// Route table (§12). One flat match: no middleware stack, just the session gate
+/// and then a path.
fn dispatch(state: &State, req: &Req) -> Res {
let seg: Vec<&str> = req.path.trim_matches('/').split('/').filter(|s| !s.is_empty()).collect();
let is_get = req.method == "GET";
@@ -233,17 +218,16 @@ fn dispatch(state: &State, req: &Req) -> Res {
("GET", ["login"]) => return routes::login_form(state, req),
("POST", ["login"]) => return routes::login(state, req),
("GET", ["healthz"]) => return Res::text(200, "ok\n".into()),
- // Metrics are counts only — no package names, no versions, no audit
- // detail — and a Prometheus scraper has no session to present. Serving
- // them unauthenticated is what makes them scrapeable at all; the bind
- // address is loopback by default, which is where that is safe.
+ // Metrics are counts only — no package names, versions, or audit detail
+ // — and a Prometheus scraper has no session to present. The bind address
+ // is loopback by default, which is where this is safe.
("GET", ["metrics"]) => return routes::metrics(state),
_ => {}
}
// Session gate: mint a session for anonymous visitors so the CSRF token
- // exists even before anyone logs in. It is not a login — `gate` only lets
- // through a sid that a successful login marked authenticated.
+ // exists before anyone logs in. It is not a login — `gate` only lets through
+ // a sid that a successful login marked authenticated.
let (sid, new_session) = match req.cookie("sid") {
Some(s) if auth::is_valid_session(&s) => (s, false),
_ => match auth::new_session() {
diff --git a/src/http/render.rs b/src/http/render.rs
index ca3ba51..f049a25 100644
--- a/src/http/render.rs
+++ b/src/http/render.rs
@@ -1,9 +1,3 @@
-//! Template contexts (§12, §13).
-//!
-//! Askama compiles every template into Rust at build time, so a missing field
-//! is a compile error rather than a blank page at 2am. Contexts are built from
-//! live DB state; nothing here writes.
-
use askama::Template;
/// Everything the shared chrome needs. Embedded in each page context because
@@ -293,8 +287,7 @@ pub struct Builds {
pub recent: Vec<BuildRow>,
}
-/// The same table on its own, for the htmx fragment refresh. Same fields, so
-/// the include in builds.html and this standalone render cannot drift apart.
+/// The same table on its own, for the htmx fragment refresh.
#[derive(Template)]
#[template(path = "builds_table.html")]
pub struct BuildsTable {
@@ -386,13 +379,10 @@ pub struct SettingRow {
pub value: String,
}
-/// Vendored static assets. htmx arrives in P3; until then this serves the
-/// favicon and refuses everything else rather than walking the filesystem.
/// Static assets. Two files, both vendored, both served from `include_bytes!`
/// so the binary is self-contained and there is no install step and no bundler
/// (§13). htmx is the only JavaScript this app ships; it is served precompressed
-/// because the raw file is 48 KB and the gzip is 15 KB, and the budget that
-/// matters is what a browser actually downloads.
+/// because the budget that matters is what a browser actually downloads.
pub fn static_asset(name: &str, accept_gzip: bool) -> crate::http::Res {
use crate::http::Res;
match name {
diff --git a/src/http/routes/mod.rs b/src/http/routes/mod.rs
index e78cc74..0dfed52 100644
--- a/src/http/routes/mod.rs
+++ b/src/http/routes/mod.rs
@@ -1,9 +1,3 @@
-//! Route handlers (§12).
-//!
-//! Every handler reads through `db.read` — the thread-local read-only
-//! connection — and hands mutations to the writer actor. A slow client can
-//! therefore never hold the write lock, which is the whole point of the split.
-
use crate::db::{self, builds, model::*};
use crate::review::candidates;
use crate::time;
diff --git a/src/http/routes/mutations.rs b/src/http/routes/mutations.rs
index 133d491..79089b2 100644
--- a/src/http/routes/mutations.rs
+++ b/src/http/routes/mutations.rs
@@ -1,6 +1,3 @@
-//! The write side of the UI: every handler that changes something, and the flash
-//! it answers with.
-
use crate::db::{self, builds};
use crate::review::{approve as ap, candidates};
use crate::pipeline;
diff --git a/src/http/routes/pages.rs b/src/http/routes/pages.rs
index dea7de0..f1f3ef8 100644
--- a/src/http/routes/pages.rs
+++ b/src/http/routes/pages.rs
@@ -1,5 +1,3 @@
-//! The read side of the UI: pages that only ever go through `db.read`.
-
use crate::db::{self, builds, Db};
use crate::review::{candidates, diff, risk};
use crate::ops;
@@ -554,10 +552,9 @@ pub(crate) fn audit(state: &State, req: &Req) -> Res {
/// `GET /metrics` in Prometheus text exposition format (§12, §15).
///
-/// Everything here is computed from live state on every scrape. There are no
-/// counters incremented at event sites, because a counter that has to be
-/// maintained by every code path is a counter that quietly drifts the first time
-/// a path is added; a query cannot drift.
+/// Everything here is computed from live state on every scrape. There are no counters
+/// incremented at event sites: a counter every code path has to maintain quietly
+/// drifts the first time a path is added; a query cannot drift.
pub fn metrics(state: &State) -> Res {
match ops::metrics(&state.cfg, &state.db) {
Ok(m) => {
diff --git a/src/http/sse.rs b/src/http/sse.rs
index 5bfb75b..561de33 100644
--- a/src/http/sse.rs
+++ b/src/http/sse.rs
@@ -1,15 +1,3 @@
-//! The live log tail (§13): `GET /builds/:id/log.stream` as server-sent events.
-//!
-//! This is a blocking `std::io::Read` polled by the connection's thread, which is
-//! exactly the shape §14 asks for — no async runtime, no timer wheel. The
-//! pipeline appends to a plain file, so "streaming the log" means noticing that
-//! the file grew and forwarding the new bytes. Nothing in the build path knows
-//! this reader exists, which is what makes it safe to have at all: a client that
-//! disconnects, hangs or never connects cannot slow a build by a microsecond.
-//!
-//! The stream ends when the build reaches a terminal state and the file has no
-//! more bytes, so a browser tab does not hold a connection open forever.
-
use std::io::{self, Read};
use std::path::{Path, PathBuf};
use std::time::{Duration, Instant};
diff --git a/src/lib.rs b/src/lib.rs
index d4e69de..a284bf3 100644
--- a/src/lib.rs
+++ b/src/lib.rs
@@ -1,10 +1,3 @@
-//! AUR Build Server — see DESIGN.md.
-//!
-//! One process, many threads, no async. The write path is: watcher detects a
-//! change → candidate → human approval → build pipeline → atomic publish into a
-//! signed pacman repo. Nothing reaches a consumer without an approval row
-//! behind it (I1).
-
pub mod config;
pub mod db;
pub mod error;
@@ -20,13 +13,9 @@ pub mod recipe;
pub mod review;
pub mod sandbox;
/// The §16a fake toolchain: stand-ins for `makepkg`, `mkarchroot`, `gpg`,
-/// `repo-add` and `pacman` so the whole step machine runs without root, network
-/// or an Arch chroot.
-///
-/// Test-only, and compiled out of a production build (§6 M-4): the module exists
-/// only under the `test-support` feature, which nothing but this crate's own
-/// dev-dependency enables, and the shim binaries declare the same feature. A
-/// binary an operator runs cannot fake a build tool it cannot see.
+/// `repo-add` and `pacman`, so the whole step machine runs without root, network
+/// or an Arch chroot. Compiled out of a production build (§6 M-4): a binary an
+/// operator runs cannot fake a build tool it cannot see.
#[cfg(feature = "test-support")]
pub mod shims;
pub mod time;
diff --git a/src/main.rs b/src/main.rs
index ccd20a2..edfcd44 100644
--- a/src/main.rs
+++ b/src/main.rs
@@ -1,11 +1,3 @@
-//! `aur-build` — the operator's command line (§7.2, §12).
-//!
-//! P0 ships the approval path as a CLI subcommand: the same code the web UI
-//! will call in P2, so the invariant "we build exactly what was displayed, or
-//! nothing" is enforced here too. `approve` renders the review, prints it, and
-//! then approves with the hashes it just displayed — it cannot approve a diff it
-//! did not show you.
-
use std::path::PathBuf;
use clap::{Parser, Subcommand};
@@ -119,10 +111,9 @@ enum Cmd {
fn main() -> anyhow::Result<()> {
let cli = Cli::parse();
// `init` is the only command that runs before a config exists. For everything
- // else a missing config is the error it sounds like, not a reason to invent
- // one: the old unconditional fallback turned a typo'd `--root` into a fresh
- // empty server at the wrong path, whose commands then "succeeded" against a
- // database with no subscriptions and no releases in it.
+ // else a missing config is an error, not a reason to invent one: the old
+ // unconditional fallback turned a typo'd `--root` into a fresh empty server
+ // at the wrong path.
let root = cli.root.clone().unwrap_or_else(|| Config::default().root);
let cfg = if matches!(cli.cmd, Cmd::Init { .. }) {
Config::load(&root).unwrap_or_else(|_| Config {
@@ -156,9 +147,8 @@ fn main() -> anyhow::Result<()> {
let stop = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
aur_build::watch::scheduler::spawn_scheduler(std::sync::Arc::new(cfg.clone()), db.clone(), stop.clone());
let _server = aur_build::http::spawn(cfg.clone(), db.clone())?;
- // The dispatcher reaps expired leases before its first claim, so a
- // restart recovers whatever a crash left leased without any special
- // startup routine (§8.2).
+ // The dispatcher reaps expired leases before its first claim, so a restart
+ // recovers whatever a crash left leased (§8.2).
let _pool = aur_build::pipeline::dispatch::Pool::spawn(std::sync::Arc::new(cfg.clone()), db.clone());
println!("serving on http://{} — ctrl-c to stop", cfg.bind);
// Single process, thread per connection: the main thread has nothing to
@@ -259,7 +249,7 @@ fn main() -> anyhow::Result<()> {
}
Cmd::Approve { candidate, yes, note, identity, diff: diff_arg } => {
let c = need_candidate(&ctx.db, candidate)?;
- // Render first, always. The hashes we send are the hashes of what we
+ // Render first, always: the hashes we send are the hashes of what we
// just rendered, unless the operator explicitly names older ones.
let (text, digest) = diff::render_current(&ctx.db, &cfg, &c)?;
candidates::set_diff_digest(&ctx.db, c.id, &digest)?;
diff --git a/src/ops.rs b/src/ops.rs
index fd644c3..612db78 100644
--- a/src/ops.rs
+++ b/src/ops.rs
@@ -1,20 +1,3 @@
-//! Retention, metrics and backups (§15).
-//!
-//! Three separate jobs that share one premise: the database is the thing that
-//! must survive, and the bytes on disk are the thing that cannot be kept forever.
-//!
-//! *Retention* evicts files for releases beyond the last N of a pkgbase. It never
-//! deletes a row. The artifact keeps its digest, size and provenance and gains a
-//! `purged_at`, so the record says "these bytes existed and were dropped at T"
-//! rather than continuing to claim a file that is no longer there.
-//!
-//! *Metrics* are computed on read, like staleness. A counter that has to be
-//! incremented on every state change is a counter that drifts.
-//!
-//! *Backups* use `VACUUM INTO`. Copying a live WAL database with `cp` produces a
-//! main file plus a WAL that may or may not belong to it, which is to say a backup
-//! that is only sometimes restorable.
-
use std::path::{Path, PathBuf};
use crate::config::Config;
@@ -37,7 +20,7 @@ pub struct RetentionReport {
/// Everything a metrics scrape reports, computed in one pass over the database.
///
/// Kept as a struct rather than a string builder so the HTTP handler, the CLI and
-/// the tests all read the same numbers from the same source.
+/// the tests read the same numbers from the same source.
#[derive(Debug, Default, Clone)]
pub struct Metrics {
pub builds: Vec<(String, i64)>,
@@ -67,8 +50,8 @@ pub struct Metrics {
impl Metrics {
/// Share of recorded builds that published. Reported as 1.0 when nothing has
- /// run yet: a fresh install is not a failing install, and an alert rule that
- /// reads 0% success on an empty system pages someone for no reason.
+ /// run yet: an alert rule reading 0% success on an empty system pages someone
+ /// for no reason.
pub fn build_success_rate(&self) -> f64 {
match self.succeeded + self.failed {
0 => 1.0,
@@ -76,10 +59,9 @@ impl Metrics {
}
}
- /// Render in Prometheus text exposition format.
- ///
- /// Every family is declared with `# HELP` and `# TYPE` because a scrape that
- /// fails validation silently drops the whole payload, not just the bad line.
+ /// Render in Prometheus text exposition format. Every family is declared with
+ /// `# HELP` and `# TYPE`, because a scrape that fails validation drops the
+ /// whole payload.
pub fn to_prometheus(&self) -> String {
let mut o = String::new();
@@ -97,8 +79,7 @@ impl Metrics {
o.push_str(&header("aurbuild_pending_review_candidates", "Reviews waiting on a human — the review debt."));
o.push_str(&format!("aurbuild_pending_review_candidates {}\n", self.pending_review));
- // The debt number nobody asks for until it is weeks old: not how many
- // reviews are pending, but how stale the pending ones are.
+ // Not how many reviews are pending, but how stale the pending ones are.
o.push_str("# HELP aurbuild_pending_review_age_seconds Histogram of how long pending reviews have waited.\n# TYPE aurbuild_pending_review_age_seconds histogram\n");
for le in [3600i64, 21600, 86400, 259200, 604800] {
let n = self.review_ages.iter().filter(|a| **a <= le).count();
@@ -214,8 +195,7 @@ pub fn metrics(cfg: &Config, db: &Db) -> Result<Metrics> {
Ok(m)
}
-/// A Prometheus family header. Kept as a function rather than a closure over the
-/// output buffer so the borrow checker does not object to interleaving.
+/// A Prometheus family header.
fn header(name: &str, help: &str) -> String {
format!("# HELP {name} {help}\n# TYPE {name} gauge\n")
}
@@ -254,12 +234,7 @@ fn dir_bytes(path: &Path) -> u64 {
/// Which releases of a pkgbase keep their files, and which lose them.
///
-/// The rule is "newest N, plus anything that would be a lie to evict": the
-/// currently accepted release and any release still backing an `in_index`
-/// package are kept regardless of how far down the list they sit. Evicting those
-/// would delete the bytes the index is actively pointing at, which is the one
-/// thing retention must never do — a rollback target is worth disk, a served
-/// package is not optional.
+/// The rule is "newest N, plus anything that would be a lie to evict".
pub fn plan_retention(db: &Db, keep: usize) -> Result<(Vec<i64>, Vec<EvictPlan>)> {
let keep = keep.max(1);
let pkgbases = db::pkgbase_release_pointers(db)?;
@@ -268,8 +243,7 @@ pub fn plan_retention(db: &Db, keep: usize) -> Result<(Vec<i64>, Vec<EvictPlan>)
let mut evict = Vec::new();
for (pb_id, accepted) in pkgbases {
let releases = db::published_release_ids(db, pb_id)?;
- // Still in the index? Then it is being served and is not a candidate for
- // eviction no matter how old it is.
+ // Still in the index? Then it is being served, whatever its age.
let serving = db::serving_release_ids(db, pb_id)?;
let mut keep_set: std::collections::BTreeSet<i64> = serving.iter().cloned().collect();
@@ -298,10 +272,8 @@ pub struct EvictPlan {
/// Run retention: evict files for releases beyond the keep window, then sweep
/// abandoned staging directories.
///
-/// Files are only removed when no *retained* release still references them. The
-/// store is content-addressed, so two releases built from the same source share
-/// one cached archive; deleting it because one release aged out would corrupt a
-/// release that is still current.
+/// Files are only removed when no *retained* release still references them: the store
+/// is content-addressed.
pub fn retention(cfg: &Config, db: &Db, keep: Option<usize>) -> Result<RetentionReport> {
let keep = keep.unwrap_or_else(|| db::setting_i64(db, "retention_versions", DEFAULT_KEEP as i64) as usize);
let (kept, evict) = plan_retention(db, keep)?;
@@ -366,13 +338,11 @@ pub fn retention(cfg: &Config, db: &Db, keep: Option<usize>) -> Result<Retention
/// belong to a build that is still running right now.
pub const STAGING_GRACE_SECS: i64 = 3600;
-/// The files a release holds on disk: package, signature, build log, and the
-/// cached sources it was built from.
+/// The files a release holds on disk: package, signature, build log, and the cached
+/// sources it was built from.
///
-/// These are returned as a unit because that is how they must be treated. A
-/// package without its build log is a byte nobody can explain, and a package
-/// without its sources cannot be rebuilt — keeping one and dropping the others
-/// is how a store ends up full of orphans and empty of answers.
+/// Returned as a unit because that is how they must be treated: keeping one and
+/// dropping the others is how a store ends up full of orphans.
pub fn release_files(cfg: &Config, db: &Db, release_id: i64) -> Result<Vec<PathBuf>> {
let mut out = Vec::new();
for (path, sig, log) in db::release_artifact_paths(db, release_id)? {
@@ -380,8 +350,8 @@ pub fn release_files(cfg: &Config, db: &Db, release_id: i64) -> Result<Vec<PathB
out.push(PathBuf::from(p));
}
}
- // Cached sources, by content digest (§5.1a: the mirror and the source cache
- // are what make an old release rebuildable).
+ // Cached sources, by content digest (§5.1a: these are what make an old
+ // release rebuildable).
let digests = db::release_by_id(db, release_id)?
.map(|r| r.source_digests_json)
.unwrap_or_else(|| "[]".into());
@@ -395,13 +365,10 @@ pub fn release_files(cfg: &Config, db: &Db, release_id: i64) -> Result<Vec<PathB
Ok(out)
}
-/// Remove staging directories whose build is finished or unknown (§8.2: staging
-/// is disposable, and a GC pass sweeps what was abandoned).
+/// Remove staging directories whose build is finished or unknown (§8.2).
///
-/// "Abandoned" is derived, not guessed: a dir is swept when its build row is in a
-/// terminal state, or when no build row exists at all, and the dir is older than
-/// the grace period. A dir belonging to a live build is left alone no matter how
-/// old it looks, because a long build is not an abandoned one.
+/// "Abandoned" is derived, not guessed: a dir is swept when its build row is terminal
+/// or absent and the dir is older than the grace period.
pub fn sweep_staging(cfg: &Config, db: &Db, grace_secs: i64) -> Result<(usize, u64)> {
let root = cfg.staging_dir();
let Ok(entries) = std::fs::read_dir(&root) else { return Ok((0, 0)) };
@@ -419,7 +386,7 @@ pub fn sweep_staging(cfg: &Config, db: &Db, grace_secs: i64) -> Result<(usize, u
let state = db::builds::get(db, &build_id)?.map(|b| b.state);
let abandonable = match &state {
// No build row: staging left over from a crash before the row was
- // written, or from a build id that no longer exists.
+ // written.
None => true,
Some(s) => matches!(s.as_str(), "succeeded" | "failed" | "cancelled"),
};
@@ -461,11 +428,9 @@ fn record_run(db: &Db, r: &RetentionReport) -> Result<()> {
/// A consistent snapshot of the database, written to `dest`.
///
-/// `VACUUM INTO` runs on the writer connection so the snapshot cannot interleave
-/// with a write, and it produces a compacted single file with no WAL — which is
-/// what you want to be holding at 3am when the main file is gone. A `cp` of a
-/// live WAL database gives you a main file and a sidecar log that may or may not
-/// belong to it, and you find out which during the restore.
+/// `VACUUM INTO` runs on the writer connection so the snapshot cannot interleave with
+/// a write, and produces a compacted single file with no WAL. A `cp` of a live WAL
+/// database gives a main file and a sidecar log that may not belong to it.
pub fn backup(db: &Db, dest: &Path) -> Result<PathBuf> {
let dest = dest.to_path_buf();
if dest.exists() {
diff --git a/src/pipeline/dispatch.rs b/src/pipeline/dispatch.rs
index 62052fd..d9891c2 100644
--- a/src/pipeline/dispatch.rs
+++ b/src/pipeline/dispatch.rs
@@ -1,21 +1,3 @@
-//! The dispatcher actor, the worker pool and the reaper (§8.2).
-//!
-//! Shape: one dispatcher thread, N worker threads, one crossbeam channel
-//! between them. The dispatcher's loop is
-//!
-//! ```text
-//! reaper: expired leases -> queued, in-flight step -> interrupted
-//! cancel: superseded in-flight builds -> cancel_requested
-//! claim: BEGIN IMMEDIATE { SELECT queued LIMIT admissible; UPDATE leased }
-//! send: build_tx.send(id) for each
-//! ```
-//!
-//! Nothing lives only in a worker's memory. If the process is killed, the lease
-//! expires and the next dispatcher pass puts the build back; the step
-//! checkpoint decides where it resumes (I5). That is the whole crash-recovery
-//! story, and it is why there is no separate "recover on startup" routine — the
-//! reaper pass *is* the recovery, and it runs first in every loop.
-
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc;
use std::thread::JoinHandle;
@@ -83,9 +65,8 @@ impl Pool {
}
fn dispatcher(cfg: Arc<Config>, db: Db, stop: Arc<AtomicBool>, tx: Sender<String>) {
- // The reaper pass runs first on every loop, including the very first one, so
- // "recover from a crash" and "notice an expired lease" are the same code
- // path. There is no special startup recovery to get wrong.
+ // The reaper runs first on every loop, including the first, so "recover from
+ // a crash" and "notice an expired lease" are the same code path.
while !stop.load(Ordering::SeqCst) {
dispatch_once(&cfg, &db, &tx);
let mut slept = 0u64;
@@ -112,7 +93,6 @@ pub fn dispatch_once(cfg: &Config, db: &Db, tx: &Sender<String>) -> Vec<String>
}
// Blocked builds become eligible again when the blocking package arrives.
let _ = builds::requeue_blocked(db);
- // A newer approval makes an in-flight build pointless (§8.2).
let _ = builds::cancel_superseded(db);
let room = admissible(cfg, db);
@@ -131,10 +111,9 @@ pub fn dispatch_once(cfg: &Config, db: &Db, tx: &Sender<String>) -> Vec<String>
ids
}
-/// How many builds may be admitted right now (§8.2 backpressure):
-/// `min(max_concurrent - in_flight, disk headroom)`. A build that cannot fit on
-/// disk is not admitted — it stays queued rather than filling the filesystem
-/// halfway through a compile.
+/// How many builds may be admitted right now (§8.2 backpressure). A build that
+/// cannot fit on disk stays queued rather than filling the filesystem halfway
+/// through a compile.
pub fn admissible(cfg: &Config, db: &Db) -> usize {
let in_flight = builds::in_flight(db).unwrap_or(0) as usize;
let slots = cfg.max_concurrent_builds.saturating_sub(in_flight);
@@ -176,11 +155,9 @@ fn worker(cfg: Arc<Config>, db: Db, rx: crossbeam_channel::Receiver<String>, sto
let attempt = builds::get(&db, &id).ok().flatten().map(|b| b.attempt).unwrap_or(1);
match pipeline::run(&cfg, &db, &id) {
Ok(Outcome::Failed { transient, .. }) => {
- // §8.4: transient failures (network, mirror 5xx) retry with a
- // bounded number of attempts. A deterministic build failure
- // does NOT retry — the release stays approved_but_unbuilt and
- // the UI says "index still serving v1". Retrying that would burn
- // a chroot to produce the same failure.
+ // §8.4: transient failures retry with a bounded number of
+ // attempts; a deterministic failure does not, because it would
+ // produce the same answer.
if transient && attempt < cfg.max_transient_attempts {
let _ = builds::requeue_transient(&db, &id);
db::audit_system(
diff --git a/src/pipeline/mod.rs b/src/pipeline/mod.rs
index 6729605..308f2a8 100644
--- a/src/pipeline/mod.rs
+++ b/src/pipeline/mod.rs
@@ -1,10 +1,3 @@
-//! 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;
@@ -37,15 +30,10 @@ pub struct SourceIdentity {
}
impl SourceIdentity {
- /// The identity of a build's source, complete on construction (n-1).
- ///
- /// This used to return a value with `aur_commit` and `recipe_hash` left
- /// empty, which `Ctx::new` filled in afterwards if it happened to find the
- /// snapshot row — so a `SourceIdentity` was a type whose empty strings could
- /// mean either "not filled in yet" or "genuinely unknown", and a new call
- /// site that forgot the second half produced a build that silently recorded
- /// an empty provenance. The snapshot is an argument now: you cannot build one
- /// without it.
+ /// The identity of a build's source, complete on construction (n-1). The
+ /// snapshot is an argument because an `aur_commit` that could mean either
+ /// "not filled in yet" or "genuinely unknown" records empty provenance
+ /// silently.
pub fn from_candidate(c: &CandidateRow, snapshot: &SnapshotRow) -> Self {
Self {
aur_commit: snapshot.aur_commit.clone(),
@@ -175,12 +163,9 @@ impl Ctx {
})
}
- /// Lease a sandbox for this build's profile. Today every step acquires and
- /// releases around itself; a remote backend will hold one sandbox across
- /// the sandbox-bearing steps of a build, and steps stay idempotent either
- /// way (I5). The TTL is the lease window: a sandbox that outlives it is
- /// assumed dead, which is exactly what the reaper already concludes about
- /// an expired build lease.
+ /// Lease a sandbox for this build's profile. The TTL is the lease window: a
+ /// sandbox that outlives it is assumed dead, which is what the reaper already
+ /// concludes about an expired build lease.
pub fn sandbox(&self) -> Result<Arc<dyn Sandbox>> {
let spec = crate::sandbox::SandboxSpec {
profile: self.profile.clone(),
@@ -265,10 +250,9 @@ pub fn run_with(ctx: &Ctx) -> Result<Outcome> {
)?;
ctx.log_line(&format!("!! {step} failed: {e}"));
// A failed build must not leave the old version looking healthy.
- // Nothing has to *do* that: the accepted pointer was never moved,
- // so "approved, build failed, index still serving the old
- // version" is what the derived query reads back (§8.4). There is
- // deliberately no state to set here — see `approved_but_unbuilt`.
+ // Nothing has to do that: the accepted pointer was never moved,
+ // so the derived query reads it back (§8.4). There is
+ // deliberately no state to set here.
return Ok(Outcome::Failed { step: step.to_string(), error: e.to_string(), transient });
}
}
@@ -314,15 +298,10 @@ pub fn enqueue_manual_rebuild(cfg: &Config, db: &Db, pkgbase: &str) -> Result<St
let rel = db::accepted_release(db, pkgbase)?
.ok_or_else(|| Error::invalid(format!("{pkgbase} has no accepted release")))?;
// A manual rebuild is the accepted release asked for again, so its identity
- // is derived from what that release actually is — commit, recipe, pins,
- // digests — through the same canonical-JSON hash every other identity uses
- // (n-5). The old version was an ad-hoc `commit|hash|manual` string: a
- // different format for the same concept, with a delimiter that could appear
- // inside the values, and no pins or digests at all, so two releases with the
- // same recipe but different upstream commits... were distinguished only by
- // luck. `requested` is what keeps a rebuild a *distinct* build from the one
- // that produced the release, while staying deterministic (§8.2): clicking
- // rebuild twice is one build, not two.
+ // is derived from what that release actually is, through the same
+ // canonical-JSON hash every other identity uses (n-5). `requested` is what
+ // keeps a rebuild a *distinct* build while staying deterministic (§8.2):
+ // clicking rebuild twice is one build, not two.
let identity = format!(
"sha256:{}",
crate::hash::hex(crate::hash::canonical_json(&serde_json::json!({
diff --git a/src/pipeline/publish.rs b/src/pipeline/publish.rs
index f8efeff..7340e53 100644
--- a/src/pipeline/publish.rs
+++ b/src/pipeline/publish.rs
@@ -1,11 +1,3 @@
-//! Publishing and serving the index (§9).
-//!
-//! Publishing is the only externally visible step, and it is atomic and
-//! serialized per repo (I4). The served database is a materialized view of the
-//! DB: we render it in scratch space beside the live file, fsync, commit the DB,
-//! then `rename` over the real one. A crash anywhere in there leaves the *old*
-//! index intact, and [`reconcile`] re-materializes from the DB on startup.
-
use std::collections::BTreeSet;
use std::path::{Path, PathBuf};
use std::process::Command;
@@ -17,27 +9,15 @@ use crate::error::{Error, Result};
use crate::pipeline::{Collect, Ctx};
use crate::time;
-/// One writer to the served repo at a time.
-///
-/// This is *the* serialization guarantee for the index (§8.2, §9, I4): a publish
-/// renders a new pacman database in scratch space, commits the DB, then renames
-/// over the live one, and a second writer interleaving anywhere in that sequence
-/// would produce an index that matches neither DB state. It is held by
-/// [`publish`] for the whole of it — staging, render, DB commit, rename, sign —
-/// and by [`withdraw_package`] for the same reason. With
-/// `max_concurrent_builds > 1` it is what stops two workers racing on one file.
-///
-/// It is a process-local mutex, which is exactly the guarantee the design asks
-/// for: one `aur-build` process owns one repo directory. Two processes sharing
-/// a directory is not a configuration this system supports.
+/// One writer to the served repo at a time — *the* serialization guarantee for
+/// the index (§8.2, §9, I4). A publish renders a new database in scratch space,
+/// commits the DB, then renames over the live one; a second writer interleaving
+/// anywhere in that sequence produces an index matching neither DB state. Held by
+/// [`publish`] and [`withdraw_package`] for the whole sequence; [`reconcile`] skips
+/// it because it runs before the dispatcher exists.
///
-/// [`reconcile`] rewrites the index without it because it runs at startup,
-/// before the dispatcher exists, when there is nothing to race with.
-///
-/// A panic while holding it is recovered from rather than propagated: atomic
-/// publish means a poisoned lock cannot have left a half-written database — the
-/// live file is whatever was last renamed into place — so clearing the poison
-/// continues instead of wedging the queue forever.
+/// A panic while holding it is recovered rather than propagated: atomic publish
+/// means a poisoned lock cannot have left a half-written database.
static REPO_LOCK: Mutex<()> = Mutex::new(());
fn lock_repo() -> std::sync::MutexGuard<'static, ()> {
@@ -61,7 +41,7 @@ pub fn index_world(db: &Db) -> Result<Vec<WorldMember>> {
}
/// Package files that belong in the served index right now, plus the extra ones
-/// being published (which are not in the DB yet when the new index is rendered).
+/// being published (not in the DB yet when the new index is rendered).
fn index_artifacts(db: &Db, extra: &[PathBuf]) -> Result<Vec<PathBuf>> {
let mut out: Vec<PathBuf> = Vec::new();
for p in db::index_packages(db)? {
@@ -77,8 +57,7 @@ fn index_artifacts(db: &Db, extra: &[PathBuf]) -> Result<Vec<PathBuf>> {
/// Publish the collected artifacts of a build. Returns the new release id.
///
-/// Serialized against every other writer of the index by [`REPO_LOCK`], which
-/// is held for the whole function.
+/// Serialized against every other writer of the index by [`REPO_LOCK`].
pub fn publish(ctx: &Ctx) -> Result<i64> {
let _guard = lock_repo();
let collect = Collect::load(&ctx.collect_path)?;
@@ -91,13 +70,11 @@ pub fn publish(ctx: &Ctx) -> Result<i64> {
// Artifacts are copied into the served tree under their real filenames.
let mut staged: Vec<(PathBuf, PathBuf)> = Vec::new();
- // Set once the render starts, so the failure path below can sweep the scratch
- // directory even when the publish died after repo-add returned.
+ // Set once the render starts, so the failure path can sweep the scratch
+ // directory even if the publish died after repo-add returned.
let mut scratch_dir: Option<PathBuf> = None;
- // Files this publish created that were not there before. If the publish does
- // not land, they are orphans: no index names them and no consumer will ever
- // ask for them (§6 m-16). A file that already existed belongs to the release
- // that is still live, so it is never on this list.
+ // Files this publish created that were not there before: if the publish does
+ // not land they are orphans no index names (§6 m-16).
let mut fresh: Vec<PathBuf> = Vec::new();
for p in &collect.packages {
let from = PathBuf::from(&p.path);
@@ -122,25 +99,21 @@ pub fn publish(ctx: &Ctx) -> Result<i64> {
}
let outcome = (|| -> Result<i64> {
- // 1. render the new database and fsync it. The live one is untouched
- // until step 3's rename.
+ // 1. render the new database; the live one is untouched until step 3.
let db_name = ctx.cfg.repo_db_name();
let final_db = arch_dir.join(format!("{db_name}.tar.gz"));
let mut pkgs = index_artifacts(&ctx.db, &staged.iter().map(|(d, _)| d.clone()).collect::<Vec<_>>())?;
- // Deduplicate: the same package name must appear once, newest wins.
pkgs = dedupe_by_name(pkgs);
let rendered = render_db(&ctx.cfg, &arch_dir, "publish", &pkgs, &mut scratch_dir)?;
- // Fault injection so I4 can be tested for real: die between the render
- // and the rename, and the old index must still be what consumers get.
- // Compiled out of a production build (§6 M-9).
+ // Fault injection so I4 can be tested for real (§6 M-9).
#[cfg(feature = "test-support")]
if ctx.cfg.hooks.publish_fault.as_deref() == Some("before-rename") {
return Err(Error::other("injected fault: before-rename"));
}
- // 2. commit the DB: release + package rows + the accepted pointer, in one
- // transaction, with the pointer moved by compare-and-swap.
+ // 2. commit the DB: release + package rows + the accepted pointer, in
+ // one transaction, with the pointer moved by compare-and-swap.
let release_id = commit_release(ctx, &collect)?;
// 3. atomic swap: rename over the real database, then sign the new bytes.
@@ -168,9 +141,8 @@ pub fn publish(ctx: &Ctx) -> Result<i64> {
})();
if outcome.is_err() {
- // The publish did not land, so nothing in the served tree may look like it
- // did: the bytes this call copied in are removed again (m-16). Files that
- // were already there belong to the release still being served and stay.
+ // Nothing in the served tree may look like a publish that did not land
+ // (m-16); files already there belong to the release still served.
for p in &fresh {
let _ = std::fs::remove_file(p);
}
@@ -222,9 +194,7 @@ fn commit_release(ctx: &Ctx, collect: &Collect) -> Result<i64> {
.and_then(|b| b.world_snapshot_id);
let repo_id = db::repo_id(&ctx.db)?;
// The compare-and-swap baseline is the release the *approval* was taken
- // against, not whatever the pointer happens to say now. If they differ,
- // someone accepted a newer version while we were building, and publishing
- // this one would roll it back.
+ // against, not whatever the pointer says now.
let expected_base: Option<i64> = match ctx.build.kind.as_str() {
"manual_rebuild" => ctx.build.release_id,
_ => ctx
@@ -235,16 +205,15 @@ fn commit_release(ctx: &Ctx, collect: &Collect) -> Result<i64> {
};
ctx.db.writer.tx(move |tx| {
- // Compare-and-swap on the accepted pointer, inside the write
- // transaction: two publishes cannot both land (I4).
+ // Compare-and-swap inside the write transaction (I4).
let actual_base = db::accepted_pointer_in(tx, pkgbase_id)?;
if actual_base != expected_base {
return Err(Error::conflict(
"accepted pointer moved while this build was running; refusing to publish",
));
}
- // Retire whatever the index held for these names *before* inserting the
- // new rows: the index holds exactly the accepted pointer, nothing else.
+ // The index holds exactly the accepted pointer, so what it held for these
+ // names goes before the new rows go in.
db::remove_index_packages_in(tx, &names)?;
let release_id = db::insert_release_in(
tx,
@@ -280,10 +249,8 @@ fn commit_release(ctx: &Ctx, collect: &Collect) -> Result<i64> {
})
}
-/// Remove scratch directories a crash left behind. [`render_db`] cleans up after
-/// itself on every path it controls; these are the ones it did not get to, and
-/// they are unambiguous — the leading dot means nothing a consumer asks for, and
-/// only a render creates one.
+/// Remove scratch directories a crash left behind: the leading dot means nothing
+/// a consumer asks for, and only a render creates one.
pub fn sweep_render_dirs(arch_dir: &Path) {
let Ok(entries) = std::fs::read_dir(arch_dir) else {
return;
@@ -303,9 +270,8 @@ struct Rendered {
}
impl Rendered {
- /// The publish point: rename the rendered database over the live one, fsync
- /// the directory entry, then drop the scratch directory. Before the rename a
- /// consumer still gets the old index; after it, the new one.
+ /// The publish point: rename over the live database, fsync the directory
+ /// entry, then drop the scratch directory.
fn swap_into(self, final_db: &Path) -> Result<()> {
std::fs::rename(&self.db, final_db)?;
fsync_dir(&self.arch_dir)?;
@@ -317,18 +283,12 @@ impl Rendered {
/// Render a fresh database with repo-add, ready to be renamed into place.
///
/// repo-add refuses any database argument that is not a name pacman itself would
-/// accept (`<repo>.db.tar.gz` and friends) — a `.tmp` suffix is a usage error to
-/// it, not a convention. So the render cannot happen at `<db>.tar.gz.tmp` beside
-/// the live file, which is what this code used to do: every publish of a real
-/// package failed the moment it met a real repo-add, while 200+ tests stayed
-/// green because the shim accepted any filename. It renders instead into a
-/// scratch directory *under* the served directory, under the exact name a
-/// consumer will download. Same filesystem, so the caller's `rename` is still the
-/// atomic swap I4 requires, and the live database is never the file repo-add is
-/// writing into.
+/// accept, so the render happens in a scratch directory *under* the served
+/// directory, under the exact name a consumer will download. Same filesystem, so
+/// the caller's `rename` is still the atomic swap I4 requires.
///
-/// `scratch` is filled in as soon as the directory exists, so the caller can
-/// sweep it even if this function is never reached again.
+/// `scratch` is filled in as soon as the directory exists, so the caller can sweep
+/// it even if this function is never reached again.
fn render_db(
cfg: &Config,
arch_dir: &Path,
@@ -343,8 +303,6 @@ fn render_db(
*scratch = Some(dir.clone());
let db = dir.join(format!("{}.tar.gz", cfg.repo_db_name()));
let rendered = Rendered { db, dir, arch_dir: arch_dir.to_path_buf() };
- // Anything that can still fail lives here, so the scratch directory does not
- // outlive the attempt on the error path.
let attempt = (|| -> Result<()> {
run_repo_add(cfg, &rendered.db, pkgs)?;
fsync_file(&rendered.db)?;
@@ -358,12 +316,8 @@ fn render_db(
Ok(rendered)
}
-/// `repo-add -R <db> <pkgs...>`.
-///
-/// Deliberately *not* `-s`: repo-add would sign the database into whatever
-/// directory it was rendered in, which is scratch space that gets deleted, and
-/// the hub signs the live file itself in [`sign`] — one key, one code path, and
-/// the signature is always over the bytes that were renamed into place (§9).
+/// `repo-add -R <db> <pkgs...>`, deliberately *not* `-s`: repo-add would sign into
+/// scratch space that gets deleted. The hub signs the live file itself in [`sign`].
fn run_repo_add(cfg: &Config, db_path: &Path, pkgs: &[PathBuf]) -> Result<()> {
let mut cmd = Command::new(&cfg.repo_add_bin);
cmd.arg("-R");
@@ -390,10 +344,8 @@ fn sign(cfg: &Config, path: &Path) -> Result<()> {
sign_to(cfg, path, Path::new(&sig))
}
-/// `gpg --detach-sign` over `path`, written to `sig_out` atomically. Shared by
-/// publish (the database) and ingest (the packages): one key, one code path,
-/// and the key never leaves the hub — a build sandbox signs nothing (§8,
-/// remote-builder design).
+/// `gpg --detach-sign` over `path`, written to `sig_out` atomically. The key never
+/// leaves the hub — a build sandbox signs nothing (§8).
pub(crate) fn sign_to(cfg: &Config, path: &Path, sig_out: &Path) -> Result<()> {
if cfg.signing_key_id.is_empty() {
return Ok(());
@@ -416,11 +368,8 @@ pub(crate) fn sign_to(cfg: &Config, path: &Path, sig_out: &Path) -> Result<()> {
Ok(())
}
-/// fsync, and *say so* when it fails (m-7). The whole point of writing to a
-/// scratch file, fsyncing, and renaming is the promise that a consumer never
-/// sees a half-written database; swallowing the error made that a comment rather
-/// than a guarantee — on a filesystem that refuses `fsync` (full, read-only, a
-/// network mount that dropped), the rename still "succeeded".
+/// fsync, and *say so* when it fails (m-7). Swallowing the error would make the
+/// write-scratch-fsync-rename promise a comment rather than a guarantee.
fn fsync_file(p: &Path) -> Result<()> {
let f = std::fs::File::open(p)
.map_err(|e| Error::other(format!("open {} for fsync: {e}", p.display())))?;
@@ -439,8 +388,7 @@ fn fsync_dir(p: &Path) -> Result<()> {
/// Keep one entry per package name; the newest file wins. The name comes from
-/// `.PKGINFO` inside the tarball, not from the filename, because package names
-/// contain dashes.
+/// `.PKGINFO`, not the filename, because package names contain dashes.
fn dedupe_by_name(paths: Vec<PathBuf>) -> Vec<PathBuf> {
let mut seen: BTreeSet<String> = BTreeSet::new();
let mut out: Vec<PathBuf> = Vec::new();
@@ -460,10 +408,8 @@ fn dedupe_by_name(paths: Vec<PathBuf>) -> Vec<PathBuf> {
/// The package name a built artifact declares, read from its own `.PKGINFO`.
///
-/// This is the real parser in `crate::pkginfo`, not the shim harness's: the
-/// name that goes into the index must come from the same read of the bytes that
-/// the pipeline signs, and a second parser in the test scaffolding is one
-/// refactor away from disagreeing about what a package calls itself (§6 M-4).
+/// The name that goes into the index must come from the same read of the bytes the
+/// pipeline signs, so this uses the real parser (§6 M-4).
fn package_name(path: &Path) -> Option<String> {
let bytes = std::fs::read(path).ok()?;
let info = crate::pkginfo::pkginfo_text(&bytes).ok()?;
diff --git a/src/pipeline/steps.rs b/src/pipeline/steps.rs
index 59c9a64..c19ac6b 100644
--- a/src/pipeline/steps.rs
+++ b/src/pipeline/steps.rs
@@ -1,8 +1,3 @@
-//! The ten pipeline steps (§8.1).
-//!
-//! Every step is idempotent and records its result in one short transaction;
-//! the long-running child process happens outside any transaction (§11a).
-
use std::path::Path;
use crate::db::{self, builds, model::*};
@@ -115,16 +110,14 @@ fn plan(ctx: &Ctx) -> Result<StepResult> {
/// Step 2 — provision the sandbox with the pinned lease set.
///
-/// The devtools chroot is gone: the sandbox boots from a base that already
-/// carries the official packages, and everything *we* publish that this build
-/// needs arrives as content-addressed blobs installed with `pacman -U`. The
-/// step id stays `chroot` in the checkpoint table — the DB does not care what
-/// the string means, and renaming would strand every existing checkpoint row.
+/// The devtools chroot is gone: the sandbox boots from a base that already carries
+/// the official packages, and everything *we* publish arrives as blobs installed
+/// with `pacman -U`. The step id stays `chroot` so existing checkpoint rows are
+/// not stranded.
///
-/// Nothing is resolved at build time: the lease manifest is the plan, every
-/// blob is re-hashed before it is staged, and the sandbox's own `pacman -Q`
-/// must confirm the pinned world actually landed. A byte that hashes to
-/// something else, or a world that drifted, fails the build closed.
+/// Nothing is resolved at build time: the lease manifest is the plan, every blob
+/// is re-hashed before it is staged, and the sandbox's own `pacman -Q` must confirm
+/// the pinned world landed.
fn provision(ctx: &Ctx) -> Result<StepResult> {
let lease = lease_manifest(ctx)?;
if lease.is_empty() {
@@ -152,18 +145,15 @@ fn provision(ctx: &Ctx) -> Result<StepResult> {
argv.extend(lease.iter().map(|e| format!("blob:{}", e.digest)));
let out = sbx.run(&Cmd::new(argv), &mut |_| {})?;
if !out.success() {
- // A refused `-U` is almost always an incomplete closure: the lease set
- // cannot satisfy itself. Its own error class, because "the sandbox
- // lied about its world" must not look like "the sandbox broke".
+ // A refused `-U` is almost always an incomplete closure — "the sandbox lied
+ // about its world", not "the sandbox broke".
return Err(Error::world_mismatch(format!(
"{} -U refused the lease set: {}",
ctx.cfg.pacman_bin,
tail(&out.stderr)
)));
}
- // Fail-closed world check: every pinned entry must be present in the
- // sandbox at exactly the pinned version. The world we approved is the
- // world we build in, or nothing.
+ // Fail-closed world check: the world we approved is the world we build in.
let q = sbx.run(&Cmd::new(vec![ctx.cfg.pacman_bin.clone(), "-Q".into()]), &mut |_| {})?;
if !q.success() {
return Err(Error::fail_closed(format!(
@@ -197,9 +187,8 @@ fn provision(ctx: &Ctx) -> Result<StepResult> {
Ok(StepResult::Done(Some(crate::hash::canonical_json(&world)?)))
}
-/// Lease a sandbox for a step, or report that the pool cannot fit one right
-/// now. A full pool is not a broken build: the build blocks and waits, the
-/// same way it waits for a dependency it publishes (§10.4).
+/// Lease a sandbox for a step, or report that the pool cannot fit one. A full
+/// pool blocks the build rather than failing it (§10.4).
fn sandbox_or_wait(
ctx: &Ctx,
) -> Result<Option<std::sync::Arc<dyn crate::sandbox::Sandbox>>> {
@@ -223,9 +212,8 @@ struct LeasePkg {
/// The lease manifest: every dependency this build needs that we publish,
/// pinned to the exact version and digest of the artifact we serve. Official
-/// packages are the base image's business — they arrive with the sandbox, and
-/// pinning them is the hub's official-repo cache, not this step. Anything
-/// unresolvable here would have been `plan()`'s problem (blocked, not built).
+/// packages arrive with the sandbox; anything unresolvable here would have been
+/// `plan()`'s problem.
fn lease_manifest(ctx: &Ctx) -> Result<Vec<LeasePkg>> {
let recipe = recipe_at(&ctx.srcdir)?;
let mut wanted: Vec<String> = Vec::new();
@@ -248,8 +236,7 @@ fn lease_manifest(ctx: &Ctx) -> Result<Vec<LeasePkg>> {
/// Step 3 — make sure every source we reviewed is on disk and hashes to what the
/// candidate recorded. For a `SKIP` source this is the only verification that
-/// exists, and it closes the window between "we hashed it at review time" and
-/// "makepkg downloaded something else just now" (§8.1).
+/// exists (§8.1).
fn sources(ctx: &Ctx) -> Result<StepResult> {
let digests: Vec<SourceDigest> = serde_json::from_str(&ctx.src.source_digests_json).unwrap_or_default();
let mut verified = 0;
@@ -281,9 +268,8 @@ fn sources(ctx: &Ctx) -> Result<StepResult> {
))))
}
-/// Step 4 — the belt-and-braces assertion that what we build is what was
-/// approved. If upstream moved between approval and build, fail with both
-/// versions instead of silently shipping the new one (§8.1).
+/// Step 4 — the belt-and-braces assertion that what we build is what was approved.
+/// If upstream moved between approval and build, fail with both versions (§8.1).
fn pkgver(ctx: &Ctx) -> Result<StepResult> {
let recipe = recipe_at(&ctx.srcdir)?;
let has_vcs = recipe.source_entries.iter().any(|s| s.is_vcs());
@@ -323,19 +309,17 @@ fn pkgver(ctx: &Ctx) -> Result<StepResult> {
}
/// Step 5 — `makepkg -c -f` in the provisioned sandbox, with the log going to
-/// the file the SSE tail reads. No `-s`: the lease set is already installed,
-/// and a build that resolves dependencies at build time is exactly what the
-/// pinning model forbids. No `-si`: the sandbox never holds the signing key;
-/// ingest signs hub-side.
+/// the file the SSE tail reads. No `-s`: the lease set is already installed, and
+/// resolving dependencies at build time is what the pinning model forbids. No
+/// `-si`: the sandbox never holds the signing key.
fn build(ctx: &Ctx) -> Result<StepResult> {
let argv = vec![ctx.cfg.makepkg_bin.clone(), "-c".into(), "-f".into()];
let sbx = match sandbox_or_wait(ctx)? {
Some(s) => s,
None => return Ok(StepResult::Blocked(vec!["sandbox-pool".into()])),
};
- // Capture the child's output into the build log regardless of outcome —
- // the sandbox streams it here as it arrives, and the SSE tail reads the
- // same file.
+ // The sandbox streams the child's output here as it arrives; the SSE tail
+ // reads the same file.
if let Some(parent) = ctx.log.parent() {
let _ = std::fs::create_dir_all(parent);
}
@@ -376,16 +360,12 @@ fn collect(ctx: &Ctx) -> Result<StepResult> {
.filter(|p| p.to_string_lossy().ends_with(".pkg.tar.zst"))
.collect();
entries.sort();
- // I9: the build is untrusted. In production it runs in a chroot, but the
- // control plane must not *depend* on that for its own safety. Everything
- // below takes a path that a PKGBUILD could have arranged to exist in the
- // srcdir, and the next step copies whatever that path points at into the
- // content-addressed store — from where it is served from our repo and signed
- // with our key. A symlink to the signing keyring, the database, or anyone's
- // home directory would otherwise become a signed artifact we publish. So:
- // no symlinks, and the resolved target must live inside this build's own
- // staging directory. Anything else fails the build closed.
- let staging_root = ctx.staging.canonicalize()?;
+ // I9: the build is untrusted, and the control plane must not *depend* on the
+ // sandbox for its own safety. Everything below takes a path a PKGBUILD could
+ // have arranged to exist in the srcdir, and the next step copies whatever it
+ // points at into the store, from where we serve and sign it. So: no symlinks,
+ // and the resolved target must live inside this build's staging directory.
+ let staging_root = ctx.staging.canonicalize()?;;
for path in entries {
if std::fs::symlink_metadata(&path).map(|m| m.file_type().is_symlink()).unwrap_or(true) {
return Err(Error::fail_closed(format!(
@@ -409,8 +389,7 @@ fn collect(ctx: &Ctx) -> Result<StepResult> {
.map_err(|e| Error::invalid(format!("{}: {e}", path.display())))?;
let meta = crate::pkginfo::parse_pkginfo(&pkginfo);
// `.BUILDINFO` is what the world snapshot is built from. Absent is not
- // fatal — the snapshot is then simply empty for this package — but a
- // present-but-unparseable one would be a lie we should not swallow.
+ // fatal; present-but-unparseable would be a lie we should not swallow.
let buildinfo = crate::pkginfo::buildinfo_text(&bytes).unwrap_or_default();
let sig = path.with_extension("pkg.tar.zst.sig");
pkgs.push(CollectedPkg {
@@ -436,14 +415,12 @@ fn collect(ctx: &Ctx) -> Result<StepResult> {
}
let collect = Collect { packages: pkgs.clone() };
collect.save(&ctx.collect_path)?;
- // A split pkgbase is one approval and N index entries (§3).
ctx.log_line(&format!(" collected {}", pkgs.iter().map(|p| format!("{}-{}", p.name, p.version)).collect::<Vec<_>>().join(", ")));
Ok(StepResult::Done(Some(crate::hash::hex_str(&serde_json::to_string(&pkgs)?))))
}
/// Step 7 — dependencies satisfiable, no downgrade. Signature checking is not
-/// here: the build no longer signs (the sandbox never sees the key), so the
-/// signature is made at ingest, after these checks pass.
+/// here: the sandbox never sees the key, so the signature is made at ingest.
fn verify(ctx: &Ctx) -> Result<StepResult> {
let collect = Collect::load(&ctx.collect_path)?;
let ours = db::our_package_names(&ctx.db)?;
@@ -486,10 +463,8 @@ fn ingest(ctx: &Ctx) -> Result<StepResult> {
std::fs::copy(from, &dest)?;
}
p.path = dest.display().to_string();
- // Hub-side signing: the build environment never holds the key, so the
- // signature is made here, over the exact bytes that just entered the
- // store, by the same key that signs the database. A gpg failure fails
- // the build closed — an unsigned artifact never reaches the repo.
+ // Hub-side signing: over the exact bytes that just entered the store. A
+ // gpg failure fails the build closed.
if !ctx.cfg.signing_key_id.is_empty() {
let sigdest = ctx.cfg.store_path(&format!("{}-sig", p.digest));
if !sigdest.exists() {
@@ -524,8 +499,8 @@ fn ingest(ctx: &Ctx) -> Result<StepResult> {
})?;
// §10.1: the world snapshot is the build's installed set INTERSECTED with our
- // own packages, filtered at ingest time, not at query time. Left unfiltered,
- // every package would be permanently stale because Arch never stops moving.
+ // own packages, filtered at ingest time. Left unfiltered, every package would
+ // be permanently stale because Arch never stops moving.
let ours = db::our_package_names(&ctx.db)?;
let mut members: Vec<WorldMember> = Vec::new();
for p in &collect.packages {
diff --git a/src/pkginfo.rs b/src/pkginfo.rs
index 7ec8b83..be0aeb6 100644
--- a/src/pkginfo.rs
+++ b/src/pkginfo.rs
@@ -1,17 +1,3 @@
-//! Reading `.PKGINFO` and `.BUILDINFO` out of a package archive (§10.1).
-//!
-//! A `.pkg.tar.zst` is a zstd-compressed tar with two plain-text metadata files
-//! inside it. pacman reads these through libalpm; we do not link libalpm (no
-//! FFI, no C toolchain dependency, §14), so this module parses the tar and the
-//! text directly. That is not a shortcut — the format is a `key = value` file
-//! with repeated keys, and a `.BUILDINFO` `installed =` block of
-//! `name version arch signature` lines. Both are stable and documented, and
-//! parsing them here is roughly eighty lines.
-//!
-//! This is production code, not harness code: the ingest step decides what the
-//! index claims about a package, and what the world snapshot records, by reading
-//! these two files.
-
use std::io::Read;
/// A package's own metadata, as `.PKGINFO` states it.
@@ -97,9 +83,7 @@ pub fn parse_pkginfo(text: &str) -> PkgInfo {
/// Parse the `.BUILDINFO` `installed` block.
///
/// The first entry shares the line with the key — `installed = glibc 2.39-1
-/// x86_64 -` — and the rest are indented under it, so the header line has to be
-/// parsed as well as skipped. Dropping it would silently lose one dependency from
-/// every snapshot, which is exactly the kind of gap that makes staleness lie.
+/// x86_64 -` — so the header line has to be parsed as well as skipped.
pub fn parse_installed(text: &str) -> Vec<Installed> {
let mut out = Vec::new();
let mut in_block = false;
diff --git a/src/pkgver/mod.rs b/src/pkgver/mod.rs
index e968256..bd77a01 100644
--- a/src/pkgver/mod.rs
+++ b/src/pkgver/mod.rs
@@ -1,12 +1,3 @@
-//! Version comparison and dependency-string parsing.
-//!
-//! Hand-written rather than bound to libalpm (DESIGN.md §4). The algorithm is
-//! the ALPM one and is fully specified: compare epoch numerically, then compare
-//! `pkgver` chunk-wise, then `pkgrel` chunk-wise. A chunk is a maximal run of
-//! digits or a maximal run of non-digits; non-alphanumeric characters are
-//! ignored. A numeric chunk always sorts before an alphabetic chunk, so `1.5`
-//! < `1.5a` and `1.1` < `1.a`.
-
use std::cmp::Ordering;
use std::fmt;
@@ -127,25 +118,19 @@ fn preceded_by_separator(s: &[u8], k: usize) -> bool {
k > 0 && !is_alnum(s[k - 1])
}
-/// ALPM's `vercmp`, character-wise.
-///
-/// Three rules do all the work, and each one is surprising the first time:
+/// ALPM's `vercmp`, character-wise. Three rules do all the work:
///
/// 1. A numeric chunk is newer than an alphabetic chunk at the same position, so
/// `1.0.1` > `1.0.a`.
/// 2. When one string runs out, the other side decides by its *next raw
/// character*: a letter there makes the exhausted string newer (`1.0` >
-/// `1.0a`, the `1.0rc1 < 1.0` rule), anything else makes it older
-/// (`1.0` < `1.0.1`).
-/// 3. Separators are not merely skipped. An alphabetic chunk that follows a
-/// separator is newer than one glued to the previous chunk, whatever the
-/// letters are: `1.0.a` > `1.0z`. Two versions that differ only in where the
-/// dot sits are *not* equal, which is the part a chunk-splitting
-/// implementation gets wrong.
+/// `1.0a`), anything else makes it older (`1.0` < `1.0.1`).
+/// 3. An alphabetic chunk following a separator is newer than one glued to the
+/// previous chunk, whatever the letters are: `1.0.a` > `1.0z`. Versions
+/// differing only in where the dot sits are *not* equal.
///
/// The cross-product test in `tests/versions.rs` checks this against pacman's own
-/// `vercmp` over ~1100 pairs, which is the only reason anyone can be confident
-/// about rule 3.
+/// `vercmp` over ~1100 pairs.
pub fn vercmp_string(a: &str, b: &str) -> Ordering {
let (a, b) = (a.as_bytes(), b.as_bytes());
let (mut i, mut j) = (0usize, 0usize);
diff --git a/src/recipe.rs b/src/recipe.rs
index 4ba6a6f..cfdb4c6 100644
--- a/src/recipe.rs
+++ b/src/recipe.rs
@@ -1,9 +1,3 @@
-//! Recipe parsing: `.SRCINFO` (authoritative, present in every AUR repo) with a
-//! `PKGBUILD` fallback, plus `source=()` parsing.
-//!
-//! The recipe is what a human reviews, so parsing failures are loud: a recipe we
-//! cannot read must never silently produce a candidate with an empty source list.
-
use std::collections::BTreeMap;
use crate::db::model::{Recipe, SourceEntry};
@@ -92,8 +86,8 @@ fn push_field(r: &mut Recipe, in_pkg: bool, pkg: Option<&str>, k: &str, v: &str)
/// Minimal `PKGBUILD` variable reader: top-level `var=value` and `var=(...)`
/// assignments, including arrays spanning several lines and quoted elements.
///
-/// This is a fallback for recipes without `.SRCINFO`; it deliberately does not
-/// try to evaluate bash. Anything it cannot read is reported, not guessed.
+/// A fallback for recipes without `.SRCINFO`; it deliberately does not evaluate
+/// bash. Anything it cannot read is reported, not guessed.
pub fn parse_pkgbuild(text: &str) -> Result<Recipe> {
let vars = pkgbuild_vars(text);
let mut r = Recipe::default();
@@ -357,13 +351,9 @@ pub fn is_diffable(path: &str) -> bool {
/// The executable part of a `PKGBUILD`: everything from the first function
/// definition onward.
///
-/// The variable assignments above the functions are metadata — a new version
-/// string, another dependency. The functions are code that runs on this machine
-/// and, through the package, on every machine that installs it. Reviewers and
-/// the risk scorer both need that line drawn in the same place, so it is drawn
-/// once here (§6 m-2): two copies had drifted, and the diff panel's version
-/// compared only the function *header* lines, so a rewritten `build()` body
-/// with the same function names showed the reviewer nothing.
+/// The assignments above the functions are metadata; the functions are code that runs
+/// here and, through the package, everywhere it installs.
+/// scorer need that line drawn in the same place (§6 m-2).
pub fn pkgbuild_bodies(text: &str) -> String {
let mut out = String::new();
let mut inside = false;
diff --git a/src/review/approve.rs b/src/review/approve.rs
index e5f446f..c8cd99d 100644
--- a/src/review/approve.rs
+++ b/src/review/approve.rs
@@ -1,10 +1,3 @@
-//! Approval semantics (§7.1, §7.1a, §7.2, §7.4).
-//!
-//! Rule of the system: **we build exactly what was displayed, or nothing.**
-//! The approve POST carries the `identity_hash` and `diff_digest` that were
-//! rendered; if either has moved under the reviewer, the approval is refused
-//! with a conflict (HTTP 409) and a re-render, never silently retargeted.
-
use crate::db::{self, approvals, candidates, CandidateState, *};
use crate::error::{Error, Result};
use crate::time;
@@ -36,20 +29,16 @@ pub struct Approval {
/// Why a decision did not happen (§7.1a, §6 M-3).
///
-/// Two families, and the difference is the whole point. `Stale` means the
-/// reviewer's screen no longer matches the database: the answer is to look
-/// again, and the UI says so with a 409 and a fresh diff. `System` means the
-/// database itself refused: looking again changes nothing, and the operator has
-/// a broken thing to fix. They used to be the same variant — every failure,
-/// SQLite included, arrived as "review is no longer pending (state: sqlite:
-/// …)", which told a reviewer their eyes were wrong when the truth was that
-/// the write failed.
+/// Two families, and the difference is the whole point: `Stale` means the
+/// reviewer's screen no longer matches the database, so the answer is to look
+/// again; `System` means the database itself refused, and looking again changes
+/// nothing.
#[derive(Debug, thiserror::Error)]
pub enum ApproveError {
/// What is stored is not what was displayed.
#[error(transparent)]
Stale(#[from] Stale),
- /// The write itself failed. Nothing about the review is at fault.
+ /// The write itself failed; nothing about the review is at fault.
#[error("the decision could not be recorded: {0}")]
System(#[from] Error),
}
@@ -77,19 +66,16 @@ pub fn approve(
let base = subject.base_release_id;
let current_base = subject.current_base_release_id;
- // 1. still open
if !subject.state.is_open() {
return Ok(Err(ApproveError::Stale(Stale::NotPending { state: subject.state.to_string() })));
}
- // 2. same candidate bytes
if subject.identity_hash != ih {
return Ok(Err(ApproveError::Stale(Stale::Identity { expected: ih.clone(), actual: subject.identity_hash })));
}
- // 3. same rendered diff
if subject.diff_digest != dd {
return Ok(Err(ApproveError::Stale(Stale::Diff { expected: dd.clone(), actual: subject.diff_digest })));
}
- // 4. base is still the accepted release (I2, end to end)
+ // Base is still the accepted release (I2, end to end).
if base != current_base {
return Ok(Err(ApproveError::Stale(Stale::Base { expected: base, actual: current_base })));
}
@@ -128,7 +114,7 @@ pub fn approve(
identity_hash: ih,
}))
})
- // A failure of the transaction is a system failure, never a stale review.
+ // A failed transaction is a system failure, never a stale review.
.map_err(ApproveError::System)?
}
@@ -156,9 +142,6 @@ pub fn reject(db: &Db, actor: &str, candidate_id: i64, note: &str) -> Result<()>
"reject",
"candidate",
&candidate_id.to_string(),
- // The identity hash, not only the note: "why was this rejected"
- // is unanswerable if the row does not say which bytes were on
- // screen (§11).
serde_json::json!({"identity": identity, "note": note}),
),
)?;
@@ -169,15 +152,13 @@ pub fn reject(db: &Db, actor: &str, candidate_id: i64, note: &str) -> Result<()>
/// One item of a bulk decision, and what happened to it (§7.4).
#[derive(Debug)]
pub struct BulkItem {
- /// The review this outcome is about; `None` when the id matched nothing —
- /// which is exactly the case a caller must be able to report, so the row
- /// cannot be the key.
+ /// `None` when the id matched nothing — which a caller must be able to
+ /// report, so the row cannot be the key.
pub candidate: Option<CandidateRow>,
pub outcome: BulkOutcome,
}
impl BulkItem {
- /// The pkgbase to name in a summary line.
pub fn pkgbase(&self) -> &str {
self.candidate.as_ref().map(|c| c.pkgbase.as_str()).unwrap_or("(gone)")
}
@@ -188,21 +169,14 @@ impl BulkItem {
pub enum BulkOutcome {
/// Approved; the approval row is here so the caller can queue the build.
Approved(Approval),
- /// Rejected. A rejection records no approval, so there is no row to hand
- /// back — the old code fabricated `Approval { id: 0 }`, which a caller
- /// could not tell from a real one (§6 M-3).
+ /// A rejection records no approval, so there is no row to hand back.
Rejected,
/// Not decided, and why.
Refused(BulkRefusal),
}
-/// Why a bulk decision skipped one of its items (§7.4).
-///
-/// Each reason is its own variant because they are different answers to give a
-/// human: one wants a confirmation click, one is a form bug, one means the
-/// review moved while the page was open, one means the database is broken. They
-/// used to all be `Stale::NotPending`, which made the flash message the only
-/// place the truth survived.
+/// Why a bulk decision skipped one of its items (§7.4). Each reason is its own
+/// variant because they are different answers to give a human.
#[derive(Debug, thiserror::Error)]
pub enum BulkRefusal {
/// High-risk items need their own confirmation, per item (§7.4).
@@ -222,11 +196,11 @@ pub enum BulkRefusal {
System(Error),
}
-/// §7.4 bulk decision. High-risk items are refused unless confirmed individually,
-/// and one refused item never rolls back the ones that were decided.
-///
-/// `items` carries the identity and diff each review was displayed with, so the
-/// approval-echo rule applies to bulk exactly as it does to a single approval.
+/// §7.4 bulk decision. High-risk items are refused unless confirmed
+/// individually, and one refused item never rolls back the ones that were
+/// decided. `items` carries the identity and diff each review was displayed
+/// with, so the approval-echo rule applies to bulk exactly as to a single
+/// approval.
pub fn bulk(
db: &Db,
actor: &str,
@@ -262,7 +236,6 @@ pub fn bulk(
Ok(out)
}
-/// The approval behind a candidate, if any.
pub fn approval_for(db: &Db, candidate_id: i64) -> Result<Option<(i64, String)>> {
approvals::for_candidate(db, candidate_id)
}
@@ -290,7 +263,6 @@ pub fn withdraw(db: &Db, actor: &str, release_id: i64, reason: &str) -> Result<(
})
}
-/// The pkgbase's accepted release pointer, exposed for callers that need it.
pub fn current_accepted(db: &Db, pkgbase: &str) -> Result<Option<ReleaseRow>> {
db::accepted_release(db, pkgbase)
}
diff --git a/src/review/candidates.rs b/src/review/candidates.rs
index 7cedf4b..d4c49e8 100644
--- a/src/review/candidates.rs
+++ b/src/review/candidates.rs
@@ -1,15 +1,3 @@
-//! Candidate creation and the collapse-in-place rule (§7.1).
-//!
-//! One review object per pkgbase at a time. A newer detection **collapses into**
-//! the open review rather than queueing beside it, and the review's `base` is
-//! fixed at creation to the pkgbase's `current_accepted_release` — that is what
-//! makes "diff against the last accepted version, never the last seen one" (I2)
-//! true no matter how many detections arrive while nobody is looking.
-//!
-//! This module is the *rule*, not the SQL: every statement it needs lives in
-//! `db::candidates` and is called through the transaction handle, so the whole
-//! decision is atomic and the schema still has one owner.
-
use crate::db::{self, candidates as sql, Db, Pkgbase, ReleaseRow};
use crate::error::Result;
@@ -49,22 +37,20 @@ pub fn upsert_candidate(db: &Db, pb: &Pkgbase, accepted: Option<&ReleaseRow>, nc
return Ok(Upsert::Unchanged);
}
if !open.viewed() {
- // Collapse in place: same base, no new row, revision bumped.
let revision = sql::collapse_in(tx, &open, &nc)?;
return Ok(Upsert::Collapsed { id: open.id, revision });
}
- // A human saw the old diff: freeze it for the audit trail and open a
- // fresh review against the same base.
+ // A human saw the old diff: freeze it for the audit trail and open
+ // a fresh review against the same base.
sql::supersede_in(tx, open.id)?;
let new_id = sql::insert_in(tx, pkgbase_id, base, kind, &nc)?;
return Ok(Upsert::Superseded { old: open.id, new: new_id });
}
- // No open review. A previously rejected identity must not be re-raised.
+ // A previously rejected identity must not be re-raised.
if sql::rejected_before_in(tx, pkgbase_id, &nc.identity_hash)? {
return Ok(Upsert::PreviouslyRejected);
}
- // Same identity already approved/recorded: nothing to do.
if sql::recorded_before_in(tx, pkgbase_id, &nc.identity_hash)? {
return Ok(Upsert::Unchanged);
}
@@ -73,7 +59,6 @@ pub fn upsert_candidate(db: &Db, pb: &Pkgbase, accepted: Option<&ReleaseRow>, nc
})
}
-/// Convenience used by the watcher: the accepted release of a pkgbase row.
pub fn accepted_for(db: &Db, pb: &Pkgbase) -> Result<Option<ReleaseRow>> {
match pb.current_accepted_release_id {
Some(id) => db::release_by_id(db, id),
diff --git a/src/review/diff.rs b/src/review/diff.rs
index 3eecc4e..519d9ae 100644
--- a/src/review/diff.rs
+++ b/src/review/diff.rs
@@ -1,10 +1,3 @@
-//! Diff rendering (§6).
-//!
-//! A review is not one diff, it is a panel set, and **every** panel compares what
-//! the accepted release recorded against what the candidate records now — never
-//! "last seen". The rendered text is hashed into `diff_digest`, which is what
-//! makes "we build exactly what was displayed, or nothing" (§7.1a) provable.
-
use crate::config::Config;
use crate::db::{self, *};
use crate::error::Result;
diff --git a/src/review/mod.rs b/src/review/mod.rs
index c8b2f50..eb78b3a 100644
--- a/src/review/mod.rs
+++ b/src/review/mod.rs
@@ -1,6 +1,3 @@
-//! Review lifecycle: candidate creation and collapse-in-place (§7.1), the
-//! approval record (§7.2), diffing (§6) and risk scoring (§6).
-
pub mod approve;
pub mod candidates;
pub mod diff;
diff --git a/src/review/risk.rs b/src/review/risk.rs
index cf7069d..3b483cf 100644
--- a/src/review/risk.rs
+++ b/src/review/risk.rs
@@ -1,15 +1,3 @@
-//! Advisory risk scoring (§6).
-//!
-//! The reviewer's attention is the scarcest resource in this system, so every
-//! candidate gets a computed level that orders and colours the inbox. It is
-//! **advisory only**: there is no auto-approval in v1 (§7.3), so nothing is
-//! gated on a score and no heuristic can let something through. A wrong score
-//! costs attention, never safety.
-//!
-//! Every signal is computed from what the accepted release recorded against
-//! what the candidate records now — the same "never last seen" rule that makes
-//! I2 true for the diff panels.
-
use crate::db::{self, model::*, Db};
use crate::error::Result;
use crate::pkgver;
diff --git a/src/sandbox/agent.rs b/src/sandbox/agent.rs
index 09a6f93..d7b841c 100644
--- a/src/sandbox/agent.rs
+++ b/src/sandbox/agent.rs
@@ -1,18 +1,3 @@
-//! The ephemeral sandbox agent: what runs *inside* the sandbox.
-//!
-//! One connection, one lease, one life: the agent dials the hub (outbound
-//! rendezvous — the hub never needs a route into an untrusted box), accepts
-//! `Run`/`Put`/`Get` frames for as long as the hub keeps the connection alive,
-//! and dies — taking its child processes with it — when the connection drops
-//! or its TTL expires. There is no state between leases by design: the sandbox
-//! is disposable, the TTL is the guarantee, and a leaked sandbox is a bug in
-//! the TTL watchdog, not a lifecycle question.
-//!
-//! The TTL watchdog is the backstop under every failure mode: hub crashes,
-//! network partition, a hub bug that forgets `Destroy`. The hub keeps it fed
-//! with `Ping` frames while a run is in flight; silence longer than the TTL
-//! means nobody is coming, so the agent kills its child and exits.
-
use std::io::BufReader;
use std::net::TcpStream;
use std::path::{Path, PathBuf};
diff --git a/src/sandbox/kata.rs b/src/sandbox/kata.rs
index c7d717f..9169f9f 100644
--- a/src/sandbox/kata.rs
+++ b/src/sandbox/kata.rs
@@ -1,25 +1,3 @@
-//! The kata backend: ad-hoc, TTL-bounded sandboxes provisioned by an
-//! orchestrator, leased over the same agent protocol as everything else.
-//!
-//! This is composition, not a new protocol: a kata sandbox is a small VM that
-//! boots the `sandbox-agent` image pointed at this hub, and `acquire` is
-//! "ask the provisioner for a box, then wait for *that specific box* to dial
-//! in". The nonce each lease generates is handed to the provisioner and comes
-//! back as the agent's `agent_id`, so a stray sandbox can never be leased to
-//! the wrong build, and a sandbox that never dials in is a TTL expiry — the
-//! same vocabulary every other failure in this system speaks (I5).
-//!
-//! The payload is an agent-sandbox-style Kubernetes CR (`runtimeClass: kata`,
-//! `activeDeadlineSeconds` as the TTL the orchestrator enforces). It is a pure
-//! function, unit-tested; the network call that sends it is exercised only by
-//! the gated live tier, which skips — with a printed note, never a silent
-//! pass — wherever a cluster is absent.
-//!
-//! The `LocalAgentProvisioner` is the shape this tier is tested with: a real
-//! `sandbox-agent` process, real rendezvous, no VM. It is to kata what the
-//! loopback backend is to a clean machine — the honest stand-in that keeps
-//! the interface itself under test.
-
use std::collections::HashMap;
use std::io::BufReader;
use std::net::{TcpListener, TcpStream};
@@ -218,16 +196,12 @@ impl KataBackend {
///
/// A Kata backend cannot share only its listener the way the plain remote
/// backend does: it routes every dial-in by the nonce in its `Hello` into a
- /// map that belongs to it, so two backends on one address would each see
- /// half the dial-ins and neither could complete a rendezvous. So the whole
- /// backend is shared, not just the socket — which is also what makes
- /// "one listener per process" true here, since binding happens exactly once
- /// per distinct configuration.
+ /// map that belongs to it, so two backends on one address would each see half
+ /// the dial-ins. The whole backend is therefore shared, and binding happens
+ /// exactly once per distinct configuration.
///
/// The key is a digest of everything that distinguishes one backend from
- /// another, so the rendezvous token and the cluster bearer are not sitting
- /// around in a second place, and two configurations that differ only in
- /// unrelated hub settings still get their own backend.
+ /// another, so the tokens are not sitting around in a second place.
pub fn shared_for(cfg: &Config) -> Result<Arc<KataBackend>> {
let crate::config::Sandbox::AgentSandbox { api, namespace, bearer, image, listen, token, .. } =
&cfg.sandbox
diff --git a/src/sandbox/loopback.rs b/src/sandbox/loopback.rs
index 8e9f52d..8a3c229 100644
--- a/src/sandbox/loopback.rs
+++ b/src/sandbox/loopback.rs
@@ -1,16 +1,3 @@
-//! The loopback backend: run sandbox commands as local subprocesses.
-//!
-//! This is today's behavior wearing the new interface — same `Config::child_env`
-//! shim protocol (§16a), same captured output, same process as the hub. It is
-//! what `cargo test` exercises and what a single machine with devtools runs;
-//! the shim suite passing unchanged through this file is what makes the seam a
-//! pure refactor rather than a re-architecture.
-//!
-//! Isolation here is *none*: the "sandbox" is the hub's own user. That is
-//! honest — the loopback backend is for development, tests, and the local
-//! chroot deployment where §14's sudo rules are the boundary — and the Kata
-//! backend is where the machine boundary lives.
-
use std::fs;
use std::io::Read;
use std::path::PathBuf;
diff --git a/src/sandbox/mod.rs b/src/sandbox/mod.rs
index 13cf282..ea3e126 100644
--- a/src/sandbox/mod.rs
+++ b/src/sandbox/mod.rs
@@ -1,29 +1,3 @@
-//! The sandbox seam: where build code actually runs (§8, remote-builder design).
-//!
-//! The pipeline executes untrusted recipe code, and the security boundary around
-//! it has so far been "a chroot on this machine, with sudo rules" (§14). That
-//! boundary is a *deployment* fact, not a pipeline fact: the step machine should
-//! not know whether it is talking to a local process, a Kata container on a
-//! cluster, or a loopback harness. So every subprocess the pipeline runs goes
-//! through this interface instead of spawning one itself.
-//!
-//! Two implementations exist:
-//!
-//! * [`loopback::LoopbackBackend`] — today's behavior: commands run as local
-//! subprocesses of the hub process, with the §16a shim protocol applied
-//! through [`Config::child_env`]. This is what `cargo test` and a single
-//! machine with devtools use.
-//! * (planned) a Kata/agent-sandbox backend that leases disposable, TTL-bounded
-//! sandboxes and speaks the wire protocol; the pipeline cannot tell the
-//! difference, which is the entire point of the seam.
-//!
-//! The unit of isolation is a *sandbox lease*: [`SandboxBackend::acquire`]
-//! hands out a handle, steps run commands on it, and the handle is destroyable
-//! at any time. Nothing may assume a sandbox outlives its TTL, and nothing may
-//! assume two tasks share one. Blob transfer is content-addressed by design:
-//! there is no "path on the sandbox" concept in the interface at all, which
-//! removes a class of hostile-write bugs that a path-based API would invite.
-
use std::collections::HashMap;
use std::io::Read;
use std::net::{TcpListener, TcpStream};
@@ -42,15 +16,14 @@ pub mod loopback;
pub mod remote;
pub mod wire;
-/// A command to run inside a sandbox. Deliberately argv-shaped, not
-/// `Command`-shaped: a remote sandbox must never be handed a shell string, and
-/// the environment is the backend's business (see `Config::child_env`), not the
-/// caller's.
+/// A command to run inside a sandbox. Deliberately argv-shaped, never
+/// shell-shaped: a remote sandbox must not be handed a shell string. The
+/// environment is the backend's business (see `Config::child_env`).
///
-/// An argv element of the form `blob:<digest>` names a content-addressed blob
-/// staged with [`Sandbox::put`]: the backend expands it to wherever that blob
-/// materializes inside the sandbox. Callers never name sandbox-local paths —
-/// that is what keeps a loopback step byte-identical to a remote one.
+/// An argv element of the form `blob:<digest>` names a blob staged with
+/// [`Sandbox::put`]; the backend expands it to wherever the blob materializes
+/// inside the sandbox. Callers never name sandbox-local paths, which is what
+/// keeps a loopback step byte-identical to a remote one.
#[derive(Debug, Clone)]
pub struct Cmd {
pub argv: Vec<String>,
@@ -69,15 +42,12 @@ impl Cmd {
self.cwd = Some(dir.into());
self
}
- /// The program name, for error messages.
pub fn name(&self) -> &str {
self.argv.first().map(String::as_str).unwrap_or("")
}
}
-/// A finished command: exit status plus captured output. `code` is `None` when
-/// the child died by signal — `success()` is false either way, matching what
-/// `ExitStatus::success` would have said before the seam existed.
+/// A finished command. `code` is `None` when the child died by signal.
#[derive(Debug)]
pub struct Exit {
pub code: Option<i32>,
@@ -92,11 +62,9 @@ impl Exit {
}
/// What a caller asks the pool for. `profile` is the only affinity key warm
-/// pools need today (one warm root per build profile, §8.3); `task` is for
-/// attribution and rendezvous, `ttl` is the guarantee that the sandbox is dead
-/// no matter what this process then does, and `disk_mb` is the admission hint
-/// that replaces the hub's local disk-headroom check (§8.2) once builds leave
-/// the hub's filesystem.
+/// pools need today (§8.3); `ttl` is the guarantee that the sandbox is dead no
+/// matter what this process then does; `disk_mb` replaces the hub's local
+/// disk-headroom check (§8.2) once builds leave the hub's filesystem.
#[derive(Debug, Clone)]
pub struct SandboxSpec {
pub profile: String,
@@ -111,7 +79,7 @@ impl SandboxSpec {
}
}
-/// Pool state for the UI and notices: who is warm, who is busy, what profile.
+/// Pool state for the UI and notices.
#[derive(Debug, Clone)]
pub struct SandboxInfo {
pub id: String,
@@ -121,37 +89,30 @@ pub struct SandboxInfo {
/// A leased sandbox. `run` streams output through `on_log` as it arrives and
/// also returns it captured, so a step can parse stdout while the build log
-/// stays complete. `put`/`get` move content-addressed blobs in and out — the
-/// hub pulls artifacts by digest and never accepts a destination path from a
-/// sandbox, which is the same I9 posture the local staging-containment checks
-/// already enforce.
+/// stays complete. `put`/`get` move content-addressed blobs and never accept a
+/// destination path from a sandbox — the same I9 posture the local staging
+/// containment checks enforce.
pub trait Sandbox: Send + Sync {
fn id(&self) -> &str;
fn run(&self, cmd: &Cmd, on_log: &mut dyn FnMut(&[u8])) -> Result<Exit>;
fn put(&self, digest: &str, r: &mut dyn Read) -> Result<()>;
fn get(&self, digest: &str) -> Result<Box<dyn Read>>;
- /// Idempotent, and also happens by itself when the TTL bites. Destroying a
- /// sandbox must never be the only thing standing between untrusted code and
- /// the world.
+ /// Idempotent, and also happens by itself when the TTL bites.
fn destroy(&self) -> Result<()>;
}
/// The pool. `acquire` may return a pre-warmed sandbox, cold-start one, or fail
-/// when at quota; callers treat a failed acquire like a blocked build, not a
-/// broken one.
+/// when at quota; a failed acquire is a blocked build, not a broken one.
pub trait SandboxBackend: Send + Sync {
fn acquire(&self, spec: &SandboxSpec) -> Result<Arc<dyn Sandbox>>;
fn status(&self) -> Result<Vec<SandboxInfo>>;
}
-/// Turn a configuration into the backend it names — the only place that does,
-/// so "which backend" has exactly one answer.
+/// Turn a configuration into the backend it names — the only place that does.
///
/// `Config::validate` runs here as well as at startup: a guard that only exists
-/// in the CLI is a guard a test, a tool, or a future daemon can walk past.
-/// And an unknown or unwired kind is an error, never a fallthrough — a build
-/// configured for a Kata VM that quietly ran as the hub's own user is the
-/// failure this function used to have.
+/// in the CLI is a guard a test or a future daemon can walk past. An unknown or
+/// unwired kind is an error, never a fallthrough.
pub fn backend_for(cfg: &Config) -> Result<Arc<dyn SandboxBackend>> {
cfg.validate()?;
match &cfg.sandbox {
@@ -175,23 +136,17 @@ pub(crate) struct Bound {
/// One bound listener per `(address, token)` per process.
///
-/// The listener is a property of the *process*, not of a build. Binding it per
-/// build — which is what happened while `Ctx::new` constructed a backend for
-/// every build — meant a second concurrent build hit `EADDRINUSE` on a fixed
-/// `listen` and failed for a reason that had nothing to do with its package.
-/// Sharing the queue is also exactly the semantics the agent protocol has: an
-/// agent dials in when it is booted, and whichever build is waiting takes it.
-///
-/// The token is part of the key on purpose. Two different tokens cannot share a
-/// listener, and reusing the first one's listener for a second, different token
-/// would be a fail-open surprise; forcing a real bind makes the mistake loud.
+/// The listener belongs to the process, not to a build: binding it per build
+/// meant a second concurrent build hit `EADDRINUSE` for a reason unrelated to
+/// its package. The token is part of the key because two different tokens
+/// cannot share a listener, and silently reusing the first one's listener would
+/// be a fail-open surprise.
pub(crate) fn bound_listener(addr: &str, token: &str) -> Result<Bound> {
static REGISTRY: OnceLock<Mutex<HashMap<(String, String), Bound>>> = OnceLock::new();
let registry = REGISTRY.get_or_init(|| Mutex::new(HashMap::new()));
let key = (addr.to_string(), token.to_string());
- // A poisoned registry means a panic in some other thread's bind; the map
- // itself is still sound, so recover rather than wedge every later build —
- // the same posture as the publish lock.
+ // A poisoned registry means a panic in another thread's bind; the map is
+ // still sound, so recover rather than wedge every later build.
let mut reg = registry.lock().unwrap_or_else(|p| p.into_inner());
if let Some(b) = reg.get(&key) {
return Ok(b.clone());
diff --git a/src/sandbox/remote.rs b/src/sandbox/remote.rs
index d02335c..1f9514f 100644
--- a/src/sandbox/remote.rs
+++ b/src/sandbox/remote.rs
@@ -1,24 +1,3 @@
-//! The hub side of the agent protocol: a [`SandboxBackend`] that leases
-//! sandboxes which dial in from outside.
-//!
-//! The rendezvous is outbound-only: `acquire` waits for an agent to connect
-//! and present the shared token, and every command since then is a frame on
-//! the connection *the agent initiated*. A sandbox that vanishes mid-run is
-//! not an error this code invents — a closed connection reads as a failed
-//! step, which reads as an expired lease, which the reaper already turns into
-//! a requeue (I5). The remote backend adds no new failure vocabulary.
-//!
-//! One connection is one lease: after `destroy` (or a drop of the hub side),
-//! the agent dies and the next `acquire` waits for a fresh one. That matches
-//! the disposable-sandbox model — warm pooling across steps of one build is
-//! a backend optimization, not an interface requirement.
-//!
-//! Workspace note: `Run` frames carry a hub-side `cwd`, which is honest for
-//! loopback-shaped deployments and the test tier where hub and sandbox share
-//! a filesystem. A remote-over-the-network deployment needs the workspace
-//! manifest/tar sync from the design sketch; that is deliberately not here
-//! yet, and nothing should pretend otherwise.
-
use std::io::BufReader;
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::{Arc, Mutex};
diff --git a/src/sandbox/wire.rs b/src/sandbox/wire.rs
index 4ea1c74..8f03063 100644
--- a/src/sandbox/wire.rs
+++ b/src/sandbox/wire.rs
@@ -1,19 +1,3 @@
-//! The hub↔sandbox wire protocol: length-prefixed JSON frames over a plain
-//! socket, payloads hex-encoded.
-//!
-//! Deliberately boring, and deliberately dependency-free: one frame is a 4-byte
-//! big-endian length followed by one JSON object. Binary payloads ride inside
-//! the JSON as hex — twice the bytes of base64, but `hex` is already a
-//! dependency and blobs (recipes, pinned packages) are small. A frame is
-//! self-delimiting, so a reader that times out mid-frame cannot silently
-//! desynchronize: the connection is dead, and a dead sandbox is a lease
-//! expiry, which the reaper already knows how to handle (I5).
-//!
-//! The direction of connection matters: the *agent dials the hub*, never the
-//! reverse. A sandbox is untrusted the moment it boots; the hub must never need
-//! a route into it. Everything the hub wants — runs, blobs, teardown — is a
-//! frame on the connection the agent initiated (outbound rendezvous).
-
use std::io::{self, BufRead, Write};
use serde::{Deserialize, Serialize};
@@ -33,18 +17,16 @@ pub enum Frame {
/// hub → agent: rendezvous accepted; `ttl_secs` arms the agent's watchdog.
HelloAck { ttl_secs: u64 },
/// hub → agent: run argv. `blob:<digest>` argv elements name blobs the
- /// agent must have received via `Put`. `env` is the hub's child
- /// environment (the §16a shim protocol rides on it in tests).
+ /// agent must already have via `Put`; `env` is the hub's child environment.
Run { req: u64, argv: Vec<String>, cwd: Option<String>, env: Vec<(String, String)> },
/// agent → hub: a chunk of the running child's output, hex-encoded.
Log { req: u64, stream: String, data: String },
/// agent → hub: the child finished. `code` is None when it died by signal.
Exit { req: u64, code: Option<i32> },
- /// hub → agent: stage this content-addressed blob. The agent verifies
- /// `data` hashes to `digest` before writing — the same posture the local
- /// pacman fake enforces.
+ /// hub → agent: stage this blob. The agent verifies `data` hashes to
+ /// `digest` before writing.
Put { req: u64, digest: String, data: String },
- /// hub → agent: pull this blob back out (artifacts come home by digest).
+ /// hub → agent: pull this blob back out.
Get { req: u64, digest: String },
/// agent → hub: reply to `Get`.
Blob { req: u64, data: String },
@@ -54,8 +36,7 @@ pub enum Frame {
Err { req: u64, msg: String },
/// hub → agent: keepalive; resets the agent's TTL watchdog.
Ping {},
- /// hub → agent: tear down now. The agent would also die on its own when
- /// the connection drops — destroy is courtesy, TTL is the guarantee.
+ /// hub → agent: tear down now. TTL is the guarantee, this is courtesy.
Destroy {},
}
@@ -70,9 +51,8 @@ pub fn write_frame(w: &mut impl Write, f: &Frame) -> io::Result<()> {
w.flush()
}
-/// Read one frame. `Ok(None)` means the peer closed the connection cleanly —
-/// which, for a sandbox, is indistinguishable from "the sandbox is gone" and
-/// therefore means the same thing to the hub: lease expired, requeue.
+/// Read one frame. `Ok(None)` means a clean close, which for a sandbox means
+/// the lease expired and the build should requeue.
pub fn read_frame(r: &mut impl BufRead) -> io::Result<Option<Frame>> {
let mut len = [0u8; 4];
match r.read_exact(&mut len) {
@@ -130,8 +110,6 @@ mod tests {
#[test]
fn a_truncated_frame_is_an_error_not_a_silent_none() {
- // Half a frame on the wire must read as a dead connection through an
- // error path, never as a parsed frame.
let mut buf = Vec::new();
write_frame(&mut buf, &Frame::Ping {}).unwrap();
buf.truncate(3);
diff --git a/src/shims/mod.rs b/src/shims/mod.rs
index 7118283..818d28d 100644
--- a/src/shims/mod.rs
+++ b/src/shims/mod.rs
@@ -1,26 +1,3 @@
-//! Toolchain shims (§16a).
-//!
-//! The pipeline shells out to `makepkg`, `pacman`, `repo-add` and `gpg` inside
-//! a sandbox, and `git` outside it. In test mode the harness prepends a
-//! directory of fakes to `PATH`; each fake records its invocation, obeys a
-//! scripted outcome from the fixture manifest, and emits plausible
-//! `.PKGINFO`/`.BUILDINFO`/`.sig` output. The `mkarchroot` and `makechrootpkg`
-//! fakes remain as stand-ins for the real devtools — the pipeline stopped
-//! calling them when builds moved to the provisioning model — so the shim
-//! protocol itself stays exercised end to end.
-//!
-//! That is what makes the full step machine, checkpointing, lease/reaper
-//! recovery, publishing and index regeneration runnable in milliseconds on any
-//! machine — no Arch host, no root, no network.
-//!
-//! Protocol, all via environment so the pipeline needs no test-only code paths:
-//!
-//! | var | meaning |
-//! |---|---|
-//! | `AUR_SHIM_DIR` | where invocations are recorded (`invocations.jsonl`) |
-//! | `AUR_SHIM_MANIFEST` | fixture manifest describing the scripted outcome |
-//! | `AUR_SHIM_FAIL` | optional step name that must fail, e.g. `build` |
-
use std::path::{Path, PathBuf};
use serde::{Deserialize, Serialize};
@@ -150,15 +127,11 @@ pub fn record(tool: &str, args: &[String]) {
}
}
-/// Test hook: kill the process that invoked us, mid-step, with a signal it
-/// cannot catch. This is how the crash-resume invariant (I5) is tested for real:
-/// the pipeline process dies while a step is running, with no chance to clean
-/// up, and the next process must pick up from the checkpoints.
+/// Test hook: kill the process that invoked us, mid-step, with a signal it cannot
+/// catch. This is how the crash-resume invariant (I5) is tested for real.
fn kill_parent_if_asked(tool: &str) {
let want = std::env::var("AUR_SHIM_KILL_PARENT").unwrap_or_default();
if want == tool {
- // Flush the invocation log first (record() already closed the file),
- // then murder the parent. No cleanup, no unwinding, no atexit.
unsafe {
libc::kill(libc::getppid(), libc::SIGKILL);
}
@@ -250,20 +223,17 @@ pub fn mkarchroot(args: &[String]) -> Result<i32, String> {
Ok(0)
}
-/// `makechrootpkg -c -r <chroot> -- ...`: the real tool's contract, kept as a
-/// stand-in for direct shim tests. The pipeline no longer calls it — the build
-/// step runs `makepkg` in the provisioned sandbox — so the package-emitting
-/// logic lives in [`emit_packages`], shared with the `makepkg` shim.
+/// `makechrootpkg -c -r <chroot> -- ...`: kept as a stand-in for direct shim
+/// tests. The pipeline no longer calls it; the package-emitting logic lives in
+/// [`emit_packages`], shared with the `makepkg` shim.
pub fn makechrootpkg(args: &[String], m: &Manifest) -> Result<i32, String> {
// The real tool reads a chroot root; asserting it keeps the fake honest
// about the real tool's contract.
if !args.iter().any(|a| a == "-r") {
return Err("makechrootpkg: expected -r <chroot>".into());
}
- // Sign only when the caller asked for it, like the real tool: signing is
- // `-si<key>`/`-i`, and the pipeline stopped passing it when signing moved
- // hub-side to ingest. A shim that signed anyway would hide that move from
- // every test in the suite.
+ // Sign only when the caller asked, like the real tool. A shim that signed
+ // anyway would hide the move of signing hub-side from every test.
let wants_sig = args.iter().any(|a| a.starts_with("-si") || a == "-i" || a == "--sign");
emit_packages(m, "makechrootpkg", wants_sig)
}
@@ -283,8 +253,8 @@ pub fn emit_packages(m: &Manifest, tool: &str, wants_sig: bool) -> Result<i32, S
return Ok(1);
}
let startdir = std::env::current_dir().map_err(|e| e.to_string())?;
- // The real tool reads the PKGBUILD it was handed; we assert it is there so
- // a broken materialize step cannot pass silently.
+ // Assert the PKGBUILD is there so a broken materialize step cannot pass
+ // silently.
if !startdir.join("PKGBUILD").exists() {
let found = std::fs::read_dir(&startdir)
.map(|rd| rd.filter_map(|e| e.ok()).map(|e| e.file_name().to_string_lossy().into_owned()).collect::<Vec<_>>())
@@ -309,9 +279,9 @@ pub fn emit_packages(m: &Manifest, tool: &str, wants_sig: bool) -> Result<i32, S
Ok(0)
}
-/// I9 test hook: drop a symlink into the srcdir pointing wherever the test names,
-/// standing in for a PKGBUILD that tries to smuggle outside bytes into the
-/// artifact store. The pipeline must refuse it; see `collect` in steps.rs.
+/// I9 test hook: drop a symlink into the srcdir standing in for a PKGBUILD that
+/// tries to smuggle outside bytes into the artifact store. The pipeline must
+/// refuse it; see `collect` in steps.rs.
fn plant_link_if_asked(startdir: &Path) {
let target = match std::env::var("AUR_SHIM_PLANT_LINK") {
Ok(t) if !t.is_empty() => t,
@@ -498,23 +468,19 @@ pub fn makepkg(args: &[String], m: &Manifest) -> Result<i32, String> {
}
}
} else {
- // `makepkg -c -f` style: the pipeline's build step, running in the
- // provisioned sandbox. No `-s` and no `-si` reach this shim, and the
- // emulation does not care: dependencies and signatures are the hub's
- // business now.
+ // `makepkg -c -f`: the pipeline's build step in the provisioned sandbox.
+ // No `-s` and no `-si` reach this shim.
emit_packages(m, "makepkg", false)
}
}
-/// `pacman -U <blobs...>` / `pacman -Q`: a fake installed database living in
-/// the shim dir, so the provisioning step's world check runs against something
-/// that behaves.
+/// `pacman -U <blobs...>` / `pacman -Q`: a fake installed database living in the
+/// shim dir, so the provisioning step's world check runs against something that
+/// behaves.
///
-/// `-U` refuses any file that does not hash to the digest its filename claims
-/// — the same trust posture as the real signature check — and records each
-/// package from its `.PKGINFO`. `-Q` then reports exactly what was installed,
-/// which is what makes the pipeline's fail-closed world assertion a real test
-/// rather than a no-op.
+/// `-U` refuses any file that does not hash to the digest its filename claims and
+/// records each package from its `.PKGINFO`; `-Q` reports exactly what was
+/// installed, which makes the pipeline's fail-closed world assertion a real test.
pub fn pacman(args: &[String]) -> Result<i32, String> {
if args.iter().any(|a| a == "-U") {
for path in args.iter().filter(|a| !a.starts_with('-')) {
@@ -556,24 +522,18 @@ fn installed_db() -> Option<std::path::PathBuf> {
std::env::var("AUR_SHIM_DIR").ok().map(|d| std::path::Path::new(&d).join("installed.txt"))
}
-/// `repo-add [-s -p key -R] <db.tar.{gz,zst}> <pkg...>`: rebuild the database
-/// from the packages handed to it.
-///
-/// The real tool appends; `-R` replaces an existing entry. We rebuild the whole
-/// db from the packages given, which is what our publish step does anyway (it
-/// passes exactly the packages that belong in the index).
-/// The database filenames pacman's repo-add accepts — and therefore the ones
-/// this shim must accept, and no others.
-///
-/// A shim that is more permissive than the tool it stands in for is worse than no
-/// shim: the pipeline used to render its database to `<db>.tar.gz.tmp` and rename
-/// it into place, real repo-add rejects that filename as a usage error, and every
-/// publish test in the suite passed because the shim would write anywhere. That
-/// is how the first real package anyone tried to publish died at the last step.
-/// This list is the accepted set as measured against `repo-add (pacman) 7.1.0`:
-/// the `.db.tar` forms with or without a compression suffix, and nothing else —
-/// not `aur.db`, not `aur.db.gz`, and not the `.files.*` forms, which belong to
-/// `repo-files`.
+// `repo-add [-s -p key -R] <db.tar.{gz,zst}> <pkg...>`: rebuild the database
+// from the packages handed to it. The real tool appends and `-R` replaces an
+// existing entry; we rebuild the whole db, which is what our publish step does
+// anyway.
+
+/// The database filenames pacman's repo-add accepts — and therefore the ones this
+/// shim must accept, and no others. A shim more permissive than the tool it
+/// stands in for is worse than no shim: the pipeline used to render its database
+/// to `<db>.tar.gz.tmp`, real repo-add rejects that as a usage error, and every
+/// publish test passed because the shim would write anywhere. Measured against
+/// `repo-add (pacman) 7.1.0`: the `.db.tar` forms with or without a compression
+/// suffix, and nothing else.
pub const DB_SUFFIXES: [&str; 5] = [
".db.tar",
".db.tar.gz",
@@ -669,14 +629,11 @@ pub fn repo_add(args: &[String], _m: &Manifest) -> Result<i32, String> {
Ok(0)
}
-/// Pull `.PKGINFO` out of a `.pkg.tar.zst` and render the `DESC` fields a
-/// pacman database carries beyond the fixed ones.
-///
-/// Both halves come from `crate::pkginfo`, the parser the production pipeline
-/// uses (§6 M-4). The shim used to carry its own copy of the field parser, and
-/// two parsers that can drift is a supply-chain-shaped foot-gun in a system
-/// whose whole job is provenance: a test that passed because the shim read a
-/// package one way would not have meant the pipeline read it that way.
+/// Pull `.PKGINFO` out of a `.pkg.tar.zst` and render the `DESC` fields a pacman
+/// database carries beyond the fixed ones. Both halves come from
+/// `crate::pkginfo`, the parser the production pipeline uses — two parsers that
+/// can drift is a supply-chain-shaped foot-gun in a system whose whole job is
+/// provenance (§6 M-4).
fn pkginfo_fields(pkg_bytes: &[u8]) -> Result<(String, String, String, String), String> {
let text = crate::pkginfo::pkginfo_text(pkg_bytes)?;
let info = crate::pkginfo::parse_pkginfo(&text);
diff --git a/src/time.rs b/src/time.rs
index 88a27c7..b5f077e 100644
--- a/src/time.rs
+++ b/src/time.rs
@@ -1,29 +1,17 @@
-//! Clock helpers.
-//!
-//! DESIGN.md §16: "use DB time (`strftime` at write) for all ordering and audit
-//! stamps". We store timestamps as UTC ISO-8601 with second resolution so that
-//! lexicographic ordering equals chronological ordering, and every write path
-//! funnels through [`now`] so a test can pin the clock.
-
use chrono::{DateTime, SecondsFormat, TimeZone, Utc};
/// Current time as a canonical DB timestamp: `2026-11-17T20:43:24Z`.
pub fn now() -> String {
- // A test may pin the clock (see `pin`); production reads the real clock.
match pinned() {
Some(pinned) => pinned,
None => fmt(Utc::now()),
}
}
-/// The instant relative arithmetic should use.
-///
-/// This is what makes `secs_ago` and `secs_ahead` honest under a pinned clock
-/// (§6 m-1): a test that pins the clock and then asks for a 90-second lease
-/// means a lease expiring 90 seconds after *the pinned instant*, not after the
-/// real one. Reading the wall clock here instead would hand a pinned test a
-/// lease that had already expired — or would not expire for a century — and the
-/// test would pass while proving nothing about expiry at all.
+/// The instant relative arithmetic should use, which is what makes `secs_ago`
+/// and `secs_ahead` honest under a pinned clock (§6 m-1): a pinned test asking
+/// for a 90-second lease means 90 seconds after *the pinned instant*, not after
+/// the real one.
fn base() -> DateTime<Utc> {
match pinned().and_then(|p| parse(&p)) {
Some(t) => t,
@@ -51,12 +39,10 @@ pub fn pin(ts: &str) -> Option<String> {
})
}
-/// Unpin the clock for the current thread.
pub fn unpin() {
CLOCK.with(|c| *c.borrow_mut() = None);
}
-/// Parse a DB timestamp back into a `DateTime<Utc>`.
pub fn parse(ts: &str) -> Option<DateTime<Utc>> {
DateTime::parse_from_rfc3339(ts)
.ok()
@@ -68,19 +54,15 @@ pub fn parse(ts: &str) -> Option<DateTime<Utc>> {
})
}
-/// Whole seconds between two timestamps (`b - a`), or `None` if unparseable.
pub fn delta_secs(a: &str, b: &str) -> Option<i64> {
Some(parse(b)?.signed_duration_since(parse(a)?).num_seconds())
}
-/// A timestamp `secs` seconds in the past, canonical format. Honors the pinned
-/// clock — see [`base`].
+/// A timestamp `secs` from [`base`], canonical format.
pub fn secs_ago(secs: i64) -> String {
fmt(base() - chrono::Duration::seconds(secs))
}
-/// A timestamp `secs` seconds in the future, canonical format. Honors the
-/// pinned clock — see [`base`].
pub fn secs_ahead(secs: i64) -> String {
fmt(base() + chrono::Duration::seconds(secs))
}
diff --git a/src/urlutil.rs b/src/urlutil.rs
index 75b52b9..51def16 100644
--- a/src/urlutil.rs
+++ b/src/urlutil.rs
@@ -1,17 +1,10 @@
-//! Source-URL questions that more than one module asks (§6 m-2).
-//!
-//! `review::diff` and `review::risk` each carried a verbatim copy of `hosts`,
-//! which is the kind of duplication that stays harmless until one copy is fixed
-//! and the other is not: the diff panel would tell a reviewer a host appeared
-//! while the risk scorer stayed quiet about the same host.
-
use std::collections::BTreeSet;
/// The host of one `source=()` entry, or `None` when it names no host — a local
/// file, a relative path, or a `file://` URL.
///
-/// Handles the two prefixes a PKGBUILD puts in front of a URL: a `custom::`
-/// filename prefix, and the `git+`/`svn+`/`npm+` VCS scheme prefix.
+/// Handles the `custom::` and `git+`/`svn+`/`npm+` prefixes a PKGBUILD puts before a
+/// URL.
pub fn host_of(source: &str) -> Option<String> {
let s = source.rsplit("::").next().unwrap_or(source);
let s = s.rsplit('+').next().unwrap_or(s);
diff --git a/src/watch/detect.rs b/src/watch/detect.rs
index 6271dae..de1285e 100644
--- a/src/watch/detect.rs
+++ b/src/watch/detect.rs
@@ -1,11 +1,3 @@
-//! Detection: the recipe watcher pass for one pkgbase (§5.1, §5.2, §5.3).
-//!
-//! The decision that matters is *what counts as a change*. A candidate exists
-//! only if something **publishable** changed — if the version string is
-//! unchanged, `pacman` cannot offer an upgrade, so there is nothing to approve.
-//! Those events become `notice` rows instead, and are never silently dropped
-//! (I11).
-
use crate::config::Config;
use crate::db::{self, *};
use crate::error::Result;
@@ -18,19 +10,10 @@ use crate::watch::mirror::{read_tree, sync_mirror, Sync};
/// What one check of one pkgbase resulted in.
///
-/// Four variants mirror [`Upsert`], and that is deliberate rather than lazy
-/// duplication (n-2). `Upsert` answers a storage question — what did the
-/// candidate write do — and belongs to `review::candidates`; `Outcome` answers
-/// the watcher's question — what should happen next, including the cases that
-/// never reach the candidate table at all (paused, gone, blocked, a
-/// non-publishable notice). Folding them into one enum would put
-/// `Paused`/`Blocked` next to `Collapsed` in the review module, where they mean
-/// nothing, and would make every caller in the scheduler match on storage
-/// vocabulary. `outcome_of` is the total, compiler-checked translation between
-/// the two, and it is the only place that knows both.
+/// Four variants mirror [`Upsert`] deliberately (n-2): `Upsert` answers the storage
+/// question, `Outcome` the watcher's. `outcome_of` is the only place that knows both.
#[derive(Debug, Clone)]
pub enum Outcome {
- /// Nothing moved at all.
NoChange,
/// The subscription is paused: we look at nothing and change nothing.
Paused,
@@ -61,11 +44,9 @@ pub struct CheckReport {
pub fn check_pkgbase(cfg: &Config, db: &Db, name: &str) -> Result<CheckReport> {
let pb = get_pkgbase(db, name)?
.ok_or_else(|| crate::error::Error::not_found(format!("pkgbase {name}")))?;
- // A paused subscription is not observed at all. Pausing because a package is
- // broken must not keep opening reviews nobody is going to act on, and it
- // must not keep polling AUR either. The pause lives on the subscription, so
- // that is what we consult.
- let sub = db::get_subscription(db, name)?;
+ // A paused subscription is not observed at all: pausing must not keep opening
+ // reviews nobody will act on, nor keep polling AUR.
+ let sub = db::get_subscription(db, name)?;;
let paused = sub.as_ref().map(|s| s.state == SubscriptionState::Paused).unwrap_or(false);
if paused {
return Ok(CheckReport { pkgbase: name.into(), head: String::new(), outcome: Outcome::Paused });
@@ -83,9 +64,8 @@ pub fn check_pkgbase(cfg: &Config, db: &Db, name: &str) -> Result<CheckReport> {
db::set_subscription_state(&db.writer, name, SubscriptionState::Orphaned)?;
return Ok(CheckReport { pkgbase: name.into(), head: String::new(), outcome: Outcome::Gone });
}
- // The cheap poll saved us a fetch, but we still have to look: a source
- // can change its bytes without the recipe moving at all, and that is the
- // digest-drift case §5.3 calls the single most valuable detection.
+ // The cheap poll saved a fetch, but we still have to look: a source can
+ // change its bytes without the recipe moving (§5.3).
Sync::Unchanged { head } => head.clone(),
Sync::Fetched { head, .. } | Sync::Cloned { head } => head.clone(),
};
@@ -95,18 +75,13 @@ pub fn check_pkgbase(cfg: &Config, db: &Db, name: &str) -> Result<CheckReport> {
}
/// When to look at this pkgbase again: its own interval if the subscription
-/// carries one, otherwise the global default.
-///
-/// The interval arrives as an argument because the caller read the subscription
-/// row a moment ago to decide whether this pkgbase is paused (m-11); going back
-/// to the database for a number the caller was holding was both a second query
-/// and a second, possibly different, answer.
+/// carries one, otherwise the global default. The interval is an argument because
+/// the caller already read the subscription row (m-11).
fn schedule_next(db: &Db, name: &str, poll_interval: Option<i64>) {
let interval = poll_interval.unwrap_or_else(|| crate::db::setting_i64(db, "poll_interval", 86400));
let next = time::secs_ahead(interval);
- // Best-effort: a missed "next check" stamp means the scheduler looks again
- // a tick early, not that a change goes unnoticed — the tick re-selects by
- // `next_check_at` and a NULL is due immediately.
+ // Best-effort: a missed stamp means the scheduler looks again a tick early,
+ // not that a change goes unnoticed.
let _ = db::note_check(&db.writer, name, &next, None);
}
@@ -139,12 +114,11 @@ fn analyse(cfg: &Config, db: &Db, pb: &Pkgbase, head: &str) -> Result<CheckRepor
let recipe_hash = tree.recipe_hash();
// §5.2, the two-stage funnel. Stage A is one `ls-remote` per VCS source and
- // costs no clone; if the tip set is what the accepted release was built
- // from, nothing can have changed and Stage B never runs.
+ // costs no clone; if the tip set is what the accepted release was built from,
+ // nothing can have changed and Stage B never runs.
let has_vcs = recipe.source_entries.iter().any(|e| e.is_vcs());
let accepted_pins: Vec<UpstreamPin> = accepted.as_ref().map(|a| a.pins()).unwrap_or_default();
- // A recipe with no VCS sources states its own version; there is nothing to
- // probe and nothing to resolve.
+ // A recipe with no VCS sources states its own version.
let stage_a = if has_vcs {
Some(crate::watch::upstream::probe(&recipe, &accepted_pins)?)
} else {
@@ -155,8 +129,8 @@ fn analyse(cfg: &Config, db: &Db, pb: &Pkgbase, head: &str) -> Result<CheckRepor
} else if stage_a.as_ref().unwrap().needs_stage_b() {
crate::watch::upstream::resolve(cfg, db, pb, &recipe, &recipe_hash, stage_a.as_ref().unwrap())?
} else {
- // Upstream has not moved. The version we serve is still the answer, and
- // reusing its pins is what makes the next pass cheap too.
+ // Upstream has not moved; reusing the accepted pins keeps the next pass
+ // cheap too.
accepted.as_ref().map(|a| crate::watch::upstream::StageB {
epoch: a.epoch.clone(),
pkgver: a.pkgver.clone(),
@@ -166,7 +140,7 @@ fn analyse(cfg: &Config, db: &Db, pb: &Pkgbase, head: &str) -> Result<CheckRepor
})
};
// For a VCS package the literal `pkgver=` is frozen; the resolved one is the
- // only version a consumer could actually install.
+ // only version a consumer could install.
let (epoch, pkgver, pkgrel, pins) = match &resolved {
Some(r) => (r.epoch.clone(), r.pkgver.clone(), r.pkgrel.clone(), r.pins.clone()),
None => (recipe.epoch.clone(), recipe.pkgver.clone(), recipe.pkgrel.clone(), Vec::new()),
@@ -266,9 +240,7 @@ fn score(
let _ = crate::review::candidates::set_risk(db, id, &a.level, &a.signals);
}
// Record now what would block the build later, using the same rule the plan
- // step uses. A reviewer approving a package whose dependencies we have not
- // published yet should see that before they approve it, not as a blocked
- // build afterwards (§10.4).
+ // step uses, so a reviewer sees it before approving (§10.4).
let missing = missing_deps(db, pb, recipe);
let _ = crate::review::candidates::set_missing_deps(db, id, &missing);
}
@@ -306,9 +278,8 @@ fn outcome_of(up: Upsert) -> Outcome {
}
}
-/// The version string did not move, so there is no review to open — but the
-/// change is recorded, because a silently drifting tarball is exactly the kind
-/// of thing that must not be invisible (§5.3).
+/// The version string did not move, so there is no review to open — but the change
+/// is recorded, because a silently drifting tarball must not be invisible (§5.3).
fn non_publishable(
db: &Db,
pb: &Pkgbase,
@@ -319,12 +290,8 @@ fn non_publishable(
let old_digests: Vec<SourceDigest> = base.digests();
let new_digests: Vec<SourceDigest> = serde_json::from_str(&nc.source_digests_json).unwrap_or_default();
// A local source is part of the recipe: when its bytes move, that *is* the
- // recipe drift, not an integrity event. The integrity alert is specifically
- // "the bytes upstream serves no longer match what we built" (§5.3).
- // A VCS source's digest *is* its pin, so upstream moving shows up there too
- // — but that is ordinary drift, handled by the pin check below, not an
- // integrity event. Integrity means "the bytes we built are gone and the
- // version says nothing moved", which only applies to fixed downloads.
+ // recipe drift. A VCS source's digest is its pin, so upstream moving shows up
+ // there too, but that is ordinary drift (§5.3).
let vcs_indices: std::collections::BTreeSet<usize> = recipe
.source_entries
.iter()
@@ -346,9 +313,8 @@ fn non_publishable(
if digest_changed {
// The single most valuable detection in the system: the artifact in the
- // index was built from bytes upstream no longer serves, and the version
- // string is unchanged. An approval would be useless (approving it would
- // not let us publish anything), so this is an alert, not a review.
+ // index was built from bytes upstream no longer serves, and the version is
+ // unchanged. An approval would be useless, so this is an alert.
let changed: Vec<serde_json::Value> = changed_remote
.iter()
.map(|n| {
diff --git a/src/watch/digests.rs b/src/watch/digests.rs
index 8136850..d3119eb 100644
--- a/src/watch/digests.rs
+++ b/src/watch/digests.rs
@@ -1,15 +1,3 @@
-//! Source digest resolution (§5.3).
-//!
-//! `sha256sums=('SKIP')` is the hole in the integrity story. We resolve and
-//! record the digest of *every* source ourselves, at detection time, regardless
-//! of what the PKGBUILD declares — which turns a silent artifact swap into a
-//! reviewable (or at least alertable) event.
-//!
-//! Cost control: only `SKIP`-declared static sources cost bandwidth. Declared
-//! checksums are trusted-as-declared for identity because makepkg enforces them
-//! at build time; VCS digests come free from the pin we already resolved; local
-//! files are already in the mirror.
-
use crate::config::Config;
use crate::db::{self, *};
use crate::error::Result;
@@ -49,10 +37,9 @@ pub fn resolve_sources(
digest,
size: 0,
// Computed from the recipe like every other entry (m-19), not
- // hardcoded: the field answers "did the recipe give us a
- // checksum?", and for a VCS source the answer is usually yes-by-
- // absence — which is why renderers must ask `is_vcs` before
- // calling it a missing checksum.
+ // hardcoded: for a VCS source the answer is usually
+ // yes-by-absence, so renderers must ask `is_vcs` before calling
+ // it a missing checksum.
skip_declared: match declared_sums(recipe, entry.index) {
Some(d) => d == SKIP || !is_hex_digest(&d),
None => true,
@@ -120,11 +107,8 @@ pub fn resolve_sources(
/// Download `url`, hashing as we go, and record it in `source_cache`.
///
-/// This always goes to the network. That is deliberate: the whole point of §5.3
-/// is to notice that the bytes behind a `SKIP` source changed while the version
-/// did not, and answering from our own cache would make that impossible. The
-/// cache exists so the *build* can reuse the bytes it was reviewed against
-/// ([`cached_path`]), not so detection can skip looking.
+/// This always goes to the network: the point of .5.3 is to notice that the bytes
+/// behind a `SKIP` source changed while the version did not.
pub fn download_and_cache(cfg: &Config, db: &Db, url: &str) -> Result<(String, u64)> {
let tmp = cfg.source_cache_dir().join(format!("tmp-{}", crate::hash::short(url.as_bytes(), 16)));
let (digest, size) = crate::fetch::fetch_to(url, &tmp)?;
diff --git a/src/watch/mirror.rs b/src/watch/mirror.rs
index 989b968..b6f9c47 100644
--- a/src/watch/mirror.rs
+++ b/src/watch/mirror.rs
@@ -1,10 +1,3 @@
-//! The local AUR git mirror (§5.1).
-//!
-//! Clone, don't scrape. The mirror is load-bearing rather than a cache: every
-//! build materializes its recipe from it at the pinned commit and never asks
-//! the network for a recipe (§5.1a), so losing it would mean losing the ability
-//! to reproduce any historical release.
-
use std::collections::BTreeMap;
use std::path::Path;
@@ -64,11 +57,10 @@ fn record(db: &Db, name: &str, head: &str, mirror: &Path) -> Result<()> {
#[derive(Debug, Clone)]
pub struct Tree {
/// `(path, git blob id)` for every file in the tree — the input to
- /// `recipe_hash`. Covers PKGBUILD, .SRCINFO, *.install and shipped patches
- /// (§3): a patch file is part of the recipe.
+ /// `recipe_hash`, which covers shipped patches too (§3).
pub blobs: Vec<(String, String)>,
- /// Text bodies, keyed by path. Binary files are omitted from this map but
- /// still counted in `blobs`.
+ /// Text bodies, keyed by path. Binary files are omitted here but still
+ /// counted in `blobs`.
pub files: BTreeMap<String, String>,
}
diff --git a/src/watch/mod.rs b/src/watch/mod.rs
index 87df3f3..8c7604f 100644
--- a/src/watch/mod.rs
+++ b/src/watch/mod.rs
@@ -1,6 +1,3 @@
-//! Watchers: AUR recipe mirror (§5.1), upstream VCS probe (§5.2), source digest
-//! resolution (§5.3), and the scheduler tick.
-
pub mod detect;
pub mod digests;
pub mod mirror;
diff --git a/src/watch/scheduler.rs b/src/watch/scheduler.rs
index ca42e32..837a51a 100644
--- a/src/watch/scheduler.rs
+++ b/src/watch/scheduler.rs
@@ -1,8 +1,3 @@
-//! The scheduler tick (§4: "one tick thread + sweep over `next_check_at`").
-//!
-//! Blocking is the right shape here: the tick sleeps between sweeps and each
-//! sweep is a sequence of blocking git and HTTP calls.
-
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc;
use std::thread::JoinHandle;
diff --git a/src/watch/staleness.rs b/src/watch/staleness.rs
index e052b26..2631769 100644
--- a/src/watch/staleness.rs
+++ b/src/watch/staleness.rs
@@ -1,14 +1,3 @@
-//! Staleness (§10.2): "would rebuilding this change what a consumer gets?"
-//!
-//! Computed **on read**, never stored. A stored staleness flag goes wrong the
-//! moment anything else is published, and there is always something else being
-//! published; deriving it from the world snapshots and the current index means
-//! it can never lie.
-//!
-//! The pair comes from §10.1: each build recorded the versions of *our*
-//! packages it was built against. If any of those differ from what the index
-//! holds now, the artifact was built against a world that no longer exists.
-
use crate::db::{self, Db};
use crate::error::Result;
@@ -73,12 +62,10 @@ pub fn stale_for(db: &Db, pkgbase: &str) -> Result<Vec<Stale>> {
Ok(stale_rows(db)?.into_iter().filter(|s| s.pkgbase == pkgbase).collect())
}
-/// AUR now offers a **lower** version than we serve (§10.2). This is not a
-/// build request; it is an announcement that the mirror and the upstream have
-/// disagreed, and someone has to decide which one consumers follow.
+/// AUR now offers a **lower** version than we serve (§10.2). This is not a build
+/// request; it is an announcement that the mirror and upstream have disagreed.
///
-/// Derived on read from the newest candidate per pkgbase against the accepted
-/// release, so it disappears the moment either side moves.
+/// Derived on read, so it disappears the moment either side moves.
pub fn downgrades(db: &Db) -> Result<Vec<Stale>> {
let rows = db::served_vs_offered_pkgvers(db)?;
let mut out = Vec::new();
diff --git a/src/watch/upstream.rs b/src/watch/upstream.rs
index c2772a2..507d734 100644
--- a/src/watch/upstream.rs
+++ b/src/watch/upstream.rs
@@ -1,20 +1,3 @@
-//! The two-stage VCS watcher (§5.2) — the expensive path, made cheap.
-//!
-//! For a `-git` package the `pkgver=` field is frozen and the real version is
-//! computed by `pkgver()` at build time, so detection cannot read it off the
-//! recipe. Running the real thing every poll would be absurd, so:
-//!
-//! **Stage A** asks each upstream where its tip is now (`git ls-remote`, which
-//! costs one network round trip and no clone). If the set of tips is identical
-//! to the set recorded on the accepted release, *nothing can have changed* and
-//! we stop. This is the common case: most days, nothing moves.
-//!
-//! **Stage B** runs only when Stage A saw movement: clone/fetch into the
-//! persistent cache, run `makepkg --vercheck` against the recipe, and read back
-//! the computed `epoch:pkgver-pkgrel` — the only correct answer, because
-//! `pkgver()` can do arbitrary things. The clone is already there, so this is
-//! also where the pins are captured.
-
use std::collections::BTreeSet;
use std::path::PathBuf;
use std::process::Command;
@@ -148,9 +131,8 @@ impl StageB {
}
}
-/// A process-wide cap on concurrent Stage B resolutions (§5.2 "a global
-/// concurrency cap"). Each one clones repositories and runs a chroot-less
-/// makepkg; letting twenty run at once would be silly.
+/// A process-wide cap on concurrent Stage B resolutions (§5.2). Each one clones
+/// repositories and runs a chroot-less makepkg.
static RUNNING: AtomicUsize = AtomicUsize::new(0);
static SLOT_FREE: Condvar = Condvar::new();
static SLOT_LOCK: Mutex<()> = Mutex::new(());
@@ -205,9 +187,9 @@ pub fn resolve(
return Ok(Some(StageB::from_cache(hit)));
}
- // Per-pkgbase cooldown: even if the tips moved again, we do not re-resolve
- // the same pkgbase more than once per cooldown window. The previous answer
- // is reused, so a chatty upstream cannot turn detection into a build loop.
+ // Per-pkgbase cooldown: even if the tips moved again, we do not re-resolve the
+ // same pkgbase more than once per window, so a chatty upstream cannot turn
+ // detection into a build loop.
let cooldown = db::setting_i64(db, "stage_b_cooldown", 86400);
if let Some(recent) = db::stage_b_recent(db, pb.id, cooldown)? {
return Ok(Some(StageB::from_cache(recent)));