From e757979f1a2afdbe7146066345bb9acd19d3b151 Mon Sep 17 00:00:00 2001 From: aur-build Date: Thu, 19 Nov 2026 17:09:59 +0000 Subject: comments: say why, not what MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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. --- src/config.rs | 231 ++++++++++++++-------------------------------------------- 1 file changed, 55 insertions(+), 176 deletions(-) (limited to 'src/config.rs') 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, - /// Fixture manifest the shims should obey, exported as `AUR_SHIM_MANIFEST`. pub shim_manifest: Option, - /// Where shims record their invocations, exported as `AUR_SHIM_DIR`. pub shim_dir: Option, - /// 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, /// The named shim must fail, e.g. `makepkg`. pub shim_fail: Option, - /// 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, - /// 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, } 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 `/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 { 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: `//os//` (§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 = 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 { 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| { -- cgit v1.2.3