diff options
| -rw-r--r-- | .pi/.goals-pool-snapshot.json | 2 | ||||
| -rw-r--r-- | .pi/goals/.goal-ledger-checkpoint.json | 2 | ||||
| -rw-r--r-- | .pi/goals/active_goal_2026111720432444_mwl5tehk-xhe7fk.md | 22 | ||||
| -rw-r--r-- | .pi/goals/goal_events.jsonl | 2 | ||||
| -rw-r--r-- | Cargo.toml | 5 | ||||
| -rw-r--r-- | src/config.rs | 201 | ||||
| -rw-r--r-- | src/db/migrations.rs | 293 | ||||
| -rw-r--r-- | src/db/mod.rs | 272 | ||||
| -rw-r--r-- | src/db/model.rs | 286 | ||||
| -rw-r--r-- | src/db/queries.rs | 808 | ||||
| -rw-r--r-- | src/error.rs | 70 | ||||
| -rw-r--r-- | src/hash.rs | 78 | ||||
| -rw-r--r-- | src/lib.rs | 14 | ||||
| -rw-r--r-- | src/pkgver/mod.rs | 273 | ||||
| -rw-r--r-- | src/time.rs | 69 | ||||
| -rw-r--r-- | tests/common/mod.rs | 177 | ||||
| -rw-r--r-- | tests/db.rs | 239 |
17 files changed, 2801 insertions, 12 deletions
diff --git a/.pi/.goals-pool-snapshot.json b/.pi/.goals-pool-snapshot.json index bfcdd3b..11f0b89 100644 --- a/.pi/.goals-pool-snapshot.json +++ b/.pi/.goals-pool-snapshot.json @@ -1 +1 @@ -{"version":1,"dirMtimeMs":1794948419101.1257,"goals":[{"id":"mwl5tehk-xhe7fk","objective":"Implement the AUR Build Server described in DESIGN.md as a single-process Rust binary in /workspace/aur-build, delivering phases P0–P4 (walking skeleton + test harness, VCS/pkgver detection, review web UI, durable build pipeline, staleness tracking), with every §2 invariant expressed as an executable test and the work committed incrementally to git.\n\nSUCCESS CRITERIA (observable):\n1. `cargo test` passes on the host with no `#[ignore]`-tier tests required; the §16a fake-package corpus and toolchain PATH shims drive the full step machine, publishing and crash-resume tests without root, network, or a real chroot.\n2. Invariants I1–I12 of §2 each have a named test that passes (I1 no-artifact-without-approval is a post-test query; I2 diff-base-is-last-accepted; I4 atomic publish survives kill-mid-publish; I5 step checkpoint/resume; I7 one open review enforced by the partial unique index; I12 world snapshots recorded).\n3. End-to-end against shims: subscribe pkgbase → detect → review → approve → build → publish a signed repo where both packages and the .db are signed, and the served index equals the set of current_accepted_release pointers (I8).\n4. Web UI serves the five §13 surfaces (Inbox, Builds, Attention, Index, Subscriptions) plus Ops/audit as server-rendered HTML; approve carries identity_hash + diff_digest and returns HTTP 409 on a stale approval (§7.1a).\n5. `cargo clippy` reports no errors; `git log` shows a sequence of small, meaningful commits from the initial scaffold to the final state; README documents build, run, and test commands.\n\nBOUNDARIES — IN SCOPE: P0, P1, P2, P3, P4 of §17, the §11 schema, §16 edge cases, §16a test harness, and one gated real-chroot integration attempt (devtools installed) if time permits.\nOUT OF SCOPE: everything in §20 (auto-approval policies, automatic dependency rebuilds, recipe-mutating hardening transforms, build-time upstream-pin honouring, network controls, cost-weighted admission, notifications), P5 polish, multi-tenancy/RBAC, non-x86_64 arches, and any change to DESIGN.md's decided decisions in §18.\n\nCONSTRAINTS (hard):\n- Rust edition 2021, no `async`/`await`, no tokio/axum/actix/reqwest/sqlx/libgit2; threads + crossbeam channels only; blocking HTTP via tiny_http; outbound HTTP via ureq; git by shelling out.\n- SQLite via rusqlite in WAL mode with exactly one writer actor thread (channel-based `Tx` enum) and thread-local read-only readers; no transaction may span a build step.\n- UI is server-rendered (askama or minijinja) with at most vendored htmx (~14 KB) plus ~30 lines of glue; no JS written by us beyond that glue, no bundler.\n- Fail closed on every pin assertion (recipe_hash, pkgver match against approved identity); non-publishable changes become `notice` rows, never candidates, never dropped (I11).\n- Provisioning: `sudo pacman -S --needed rustup devtools` (fall back to `pacman -S rust` only if rustup is unusable); no other system mutations; never commit secrets, the signing key, or build artifacts.\n- Commit incrementally: one commit per coherent step with a descriptive message; never a single monolithic commit; DESIGN.md stays untouched.\n- If a §19 open question blocks a design choice, pick the least-entangling option, record it in a `docs/DECISIONS.md` entry, and keep moving; stop and ask only if the choice is genuinely irreversible.\n\nIF BLOCKED: stop and ask the user (e.g. no network for crates, toolchain uninstallable, an invariant that cannot be made testable).","status":"active","autoContinue":true,"usage":{"tokensUsed":85148,"activeSeconds":210},"sisyphus":false,"createdAt":"2026-11-17T20:43:24.440Z","updatedAt":"2026-11-17T20:46:59.095Z","activePath":".pi/goals/active_goal_2026111720432444_mwl5tehk-xhe7fk.md","revision":16,"scheduler":{"version":1,"owner":"01a1eb32-2e3f-757c-a79a-21ac993facc5","generation":"c7162450-1294-427e-aa34-597ba566e462","used":1,"phase":"running","repairUsed":false,"decision":{"kind":"ready","purpose":"ready"},"dispatch":{"id":"b07063cc-4112-4b45-b62f-b597761e0d52","kind":"ready","claimedAt":1794948204539}},"taskList":{"tasks":[{"id":"task-setup","title":"Provision toolchain (pacman rustup + devtools) and initialize git","status":"pending","verificationContract":"`rustup show` and `cargo --version` work; `git -C /workspace/aur-build log` contains an initial commit with DESIGN.md, .gitignore, and a scaffolded Cargo.toml that `cargo build` compiles."},{"id":"task-p0","title":"P0 — walking skeleton + test harness (§17 P0, §16a)","status":"pending","subtasks":[{"id":"task-p0-schema","title":"SQLite schema, migrations, and single writer actor (§11, §11a)","status":"pending","verificationContract":"Migrations apply from empty DB; partial unique index rejects a second pending_review per pkgbase; audit table rejects UPDATE/DELETE by trigger; concurrent readers do not block the writer in a test."},{"id":"task-p0-shims","title":"Toolchain PATH shims + fake-package corpus (§16a)","status":"pending","verificationContract":"Fakes for mkarchroot/makechrootpkg/makepkg/repo-add/gpg/pacman record invocations and emit plausible .PKGINFO/.BUILDINFO/.sig per fixture manifest; at least plain-make, with-patch, skip-checksum, split-pkgbase, build-fails, missing-dep, epoch-bump, pkgrel-reset and downgrade fixtures exist and are driven by a test."},{"id":"task-p0-detect","title":"AUR mirror watcher: aur_commit pin, recipe_hash, source digests, candidate creation (§5.1, §5.1a, §5.3)","status":"pending","verificationContract":"Against a local file:// 'AUR' repo fixture: clone + ls-remote poll + fetch only on SHA move; snapshot records aur_commit and recipe_hash covering PKGBUILD/.SRCINFO/*.install/patches; SKIP sources are stream-hashed into source_cache; candidate.base is current_accepted_release; a brand-new pkgbase yields kind=first_introduction."},{"id":"task-p0-approve","title":"Approval semantics + CLI approval path (§7.1, §7.1a, §7.2)","status":"pending","verificationContract":"CLI approve writes an immutable approval row with diff_digest and identity_hash; approving with a stale identity_hash or diff_digest is refused; collapse-in-place bumps revision without a new row while unviewed and freezes as superseded once viewed; a rejected identity is not re-detected."},{"id":"task-p0-build","title":"Build pipeline steps 0–9 and atomic signed publish (§8.1, §9)","status":"pending","verificationContract":"Shim-driven run of materialize→plan→chroot→sources→pkgver→build→collect→verify→ingest→publish; step 0 materializes from the local mirror and fails closed on recipe_hash mismatch; step 4 fails closed on pkgver mismatch; publish writes .tmp, fsyncs, renames, signs package and db, and updates current_accepted_release_id by compare-and-swap."},{"id":"task-p0-invariants","title":"Executable invariant tests I1/I2/I4/I5/I8","status":"pending","verificationContract":"cargo test includes: post-run query proving no index entry lacks an approval (I1); multi-detection fixture proving the diff base is the last accepted version (I2); kill-mid-publish leaving the old index intact (I4); restart-resumes-at-next-incomplete-step with no duplicate side effects (I5); index set equals accepted-release pointers (I8)."}]},{"id":"task-p1","title":"P1 — VCS / computed pkgver detection (§5.2, §3)","status":"pending","subtasks":[{"id":"task-p1-stageA","title":"Stage A upstream probes over all VCS sources + persistent vcs_cache","status":"pending","verificationContract":"Parses source=() for git+/svn+/hg+ with #tag/#commit refs; probes via git ls-remote against local file:// repos; an unchanged HEAD set short-circuits before Stage B; multiple VCS sources each get their own pin entry."},{"id":"task-p1-stageB","title":"Stage B pkgver() resolution with pin capture + identity tuple","status":"pending","verificationContract":"Resolved epoch:pkgver-pkgrel plus upstream_pins become part of identity_hash; cooldown and global concurrency cap enforced; cache keyed on (pkgbase, recipe_hash, upstream_tip); a git-sourced fixture produces a candidate whose pins match the fixture repo HEAD."},{"id":"task-p1-notices","title":"Non-publishable change handling: pin_drift, recipe drift, digest drift → notice / integrity_alert (§5.2, §5.3, I11)","status":"pending","verificationContract":"pin-drift fixture yields a notice and no candidate; digest-drift fixture yields a high-severity integrity_alert and no candidate; SKIP-on-non-VCS is flagged as a risk signal; nothing publishable is silently dropped."}]},{"id":"task-p2","title":"P2 — review surface (§12, §13, §6)","status":"pending","subtasks":[{"id":"task-p2-http","title":"tiny_http server, templating, thread-local readers, CSRF + session gate","status":"pending","verificationContract":"Thread-per-connection server renders all §12 routes; every POST requires a CSRF token; handlers never use the write connection; pages render with JS disabled."},{"id":"task-p2-inbox","title":"Inbox + diff panels + advisory risk scoring (§6, §7.1b)","status":"pending","verificationContract":"Review detail renders recipe / version / source-digest / upstream / source / dependency / build-env / install-hook panels, all based on accepted→candidate; risk signals computed and shown inline; base and aur_commit displayed with an AUR cgit link; first_introduction renders the full recipe with the subtle accent and no diff pane."},{"id":"task-p2-approve409","title":"Optimistic-concurrency approve/reject + bulk operations (§7.1a, §7.4)","status":"pending","verificationContract":"Approve POST with a stale identity_hash/diff_digest returns 409 and re-renders the current diff with an explanation; bulk approve refuses high-risk items without per-item confirmation; reject requires a note and is re-openable."},{"id":"task-p2-surfaces","title":"Subscriptions, Index, Builds, Attention, Ops/audit pages","status":"pending","verificationContract":"Each §13 surface renders from live DB state; Attention shows outdated-dependency, downgrade and blocked-build rows; the package page shows timeline, deps in/out, staleness and aur_commit history; manual rebuild reuses the approved source identity without a new approval (I6)."}]},{"id":"task-p3","title":"P3 — durability (§8.2, §8.3, §8.4)","status":"pending","subtasks":[{"id":"task-p3-dispatch","title":"Dispatcher actor, worker pool, leases, and reaper","status":"pending","verificationContract":"Dispatcher claims with BEGIN IMMEDIATE + lease expiry, requeues expired leases on startup, marks in-flight steps interrupted; the deterministic build id makes re-enqueue an INSERT OR IGNORE no-op; backpressure respects max_concurrent_builds and disk headroom."},{"id":"task-p3-crash","title":"Cancellation, retry policy, and crash-resume tests against shims (I5)","status":"pending","verificationContract":"A test kills the process mid-step and asserts resume at the next incomplete step with no duplicate side effects; cancel_requested stops a worker at a step boundary; deterministic build failures do not auto-retry and the release stays approved_but_unbuilt with the UI showing 'index still serving v1'."},{"id":"task-p3-sse","title":"SSE log tail + htmx live builds table","status":"pending","verificationContract":"GET /builds/:id/log.stream streams appended log bytes from a blocking thread; the builds table refreshes via htmx every 3s; vendored htmx is the only JS shipped and total vendored JS stays under 20 KB."}]},{"id":"task-p4","title":"P4 — staleness, retention, metrics (§10, §15)","status":"pending","subtasks":[{"id":"task-p4-world","title":".PKGINFO/.BUILDINFO parsing and world_snapshot filtered to our own repo","status":"pending","verificationContract":"Ingest parses tar+text without libalpm; world_snapshot members are intersected with our index at ingest time (not query time); split pkgbases produce N package rows from one approval."},{"id":"task-p4-stale","title":"Staleness query, downgrades, blocked_missing_dep, and dependents view","status":"pending","verificationContract":"stale_outdated and stale_missing are derived purely on read; a build with an unresolvable dep enters blocked_missing_dep, appears on Attention with the blocking pkgbase named, and the review page warns about missing deps before approval; the dep_edge view answers 'approving this marks N packages stale'."},{"id":"task-p4-ops","title":"Retention/GC, metrics endpoint, and backup helper","status":"pending","verificationContract":"Retention keeps N versions with logs and sources as a unit and sweeps abandoned staging dirs; GET /metrics emits prometheus text including queue depth, pending-review age histogram, build success rate and WAL size; backup uses VACUUM INTO (never cp of a live WAL db)."},{"id":"task-p4-deps","title":"vercmp + dependency-string parser and version-delta flagging (§4, §6)","status":"pending","verificationContract":"Hand-written vercmp and dep-string parser pass a table-driven test suite (epoch, pkgrel reset, alpha/numeric boundaries, provides/conflicts syntax); downgrade and epoch-bump detection use them and are covered by tests."}]},{"id":"task-verify","title":"Final verification pass, real-chroot attempt, and documentation","status":"pending","verificationContract":"Full `cargo test` and `cargo clippy` run clean; every §2 invariant maps to a named passing test (list produced); README + docs/DECISIONS.md written; git history reviewed for incremental commits; the gated real-chroot integration attempt against devtools is run or explicitly recorded as skipped with the reason."}],"blockCompletion":true,"proposedAt":"2026-11-17T20:39:23.165Z"},"currentTaskId":"task-setup"}]}
\ No newline at end of file +{"version":1,"dirMtimeMs":1794949184563.521,"goals":[{"id":"mwl5tehk-xhe7fk","objective":"Implement the AUR Build Server described in DESIGN.md as a single-process Rust binary in /workspace/aur-build, delivering phases P0–P4 (walking skeleton + test harness, VCS/pkgver detection, review web UI, durable build pipeline, staleness tracking), with every §2 invariant expressed as an executable test and the work committed incrementally to git.\n\nSUCCESS CRITERIA (observable):\n1. `cargo test` passes on the host with no `#[ignore]`-tier tests required; the §16a fake-package corpus and toolchain PATH shims drive the full step machine, publishing and crash-resume tests without root, network, or a real chroot.\n2. Invariants I1–I12 of §2 each have a named test that passes (I1 no-artifact-without-approval is a post-test query; I2 diff-base-is-last-accepted; I4 atomic publish survives kill-mid-publish; I5 step checkpoint/resume; I7 one open review enforced by the partial unique index; I12 world snapshots recorded).\n3. End-to-end against shims: subscribe pkgbase → detect → review → approve → build → publish a signed repo where both packages and the .db are signed, and the served index equals the set of current_accepted_release pointers (I8).\n4. Web UI serves the five §13 surfaces (Inbox, Builds, Attention, Index, Subscriptions) plus Ops/audit as server-rendered HTML; approve carries identity_hash + diff_digest and returns HTTP 409 on a stale approval (§7.1a).\n5. `cargo clippy` reports no errors; `git log` shows a sequence of small, meaningful commits from the initial scaffold to the final state; README documents build, run, and test commands.\n\nBOUNDARIES — IN SCOPE: P0, P1, P2, P3, P4 of §17, the §11 schema, §16 edge cases, §16a test harness, and one gated real-chroot integration attempt (devtools installed) if time permits.\nOUT OF SCOPE: everything in §20 (auto-approval policies, automatic dependency rebuilds, recipe-mutating hardening transforms, build-time upstream-pin honouring, network controls, cost-weighted admission, notifications), P5 polish, multi-tenancy/RBAC, non-x86_64 arches, and any change to DESIGN.md's decided decisions in §18.\n\nCONSTRAINTS (hard):\n- Rust edition 2021, no `async`/`await`, no tokio/axum/actix/reqwest/sqlx/libgit2; threads + crossbeam channels only; blocking HTTP via tiny_http; outbound HTTP via ureq; git by shelling out.\n- SQLite via rusqlite in WAL mode with exactly one writer actor thread (channel-based `Tx` enum) and thread-local read-only readers; no transaction may span a build step.\n- UI is server-rendered (askama or minijinja) with at most vendored htmx (~14 KB) plus ~30 lines of glue; no JS written by us beyond that glue, no bundler.\n- Fail closed on every pin assertion (recipe_hash, pkgver match against approved identity); non-publishable changes become `notice` rows, never candidates, never dropped (I11).\n- Provisioning: `sudo pacman -S --needed rustup devtools` (fall back to `pacman -S rust` only if rustup is unusable); no other system mutations; never commit secrets, the signing key, or build artifacts.\n- Commit incrementally: one commit per coherent step with a descriptive message; never a single monolithic commit; DESIGN.md stays untouched.\n- If a §19 open question blocks a design choice, pick the least-entangling option, record it in a `docs/DECISIONS.md` entry, and keep moving; stop and ask only if the choice is genuinely irreversible.\n\nIF BLOCKED: stop and ask the user (e.g. no network for crates, toolchain uninstallable, an invariant that cannot be made testable).","status":"active","autoContinue":true,"usage":{"tokensUsed":342691,"activeSeconds":955},"sisyphus":false,"createdAt":"2026-11-17T20:43:24.440Z","updatedAt":"2026-11-17T20:59:44.561Z","activePath":".pi/goals/active_goal_2026111720432444_mwl5tehk-xhe7fk.md","revision":57,"scheduler":{"version":1,"owner":"01a1eb32-2e3f-757c-a79a-21ac993facc5","generation":"c7162450-1294-427e-aa34-597ba566e462","used":1,"phase":"running","repairUsed":false,"decision":{"kind":"ready","purpose":"ready"},"dispatch":{"id":"b07063cc-4112-4b45-b62f-b597761e0d52","kind":"ready","claimedAt":1794948204539}},"taskList":{"tasks":[{"id":"task-setup","title":"Provision toolchain (pacman rustup + devtools) and initialize git","status":"complete","verificationContract":"`rustup show` and `cargo --version` work; `git -C /workspace/aur-build log` contains an initial commit with DESIGN.md, .gitignore, and a scaffolded Cargo.toml that `cargo build` compiles.","completedAt":"2026-11-17T20:48:20.900Z","evidence":"rustup 1.29.3 (pacman) + stable 1.100.0, devtools installed (mkarchroot/makechrootpkg present); git repo initialized on main with commit 3762c7c containing DESIGN.md, .gitignore, Cargo.toml; `cargo bu"},{"id":"task-p0","title":"P0 — walking skeleton + test harness (§17 P0, §16a)","status":"pending","subtasks":[{"id":"task-p0-schema","title":"SQLite schema, migrations, and single writer actor (§11, §11a)","status":"pending","verificationContract":"Migrations apply from empty DB; partial unique index rejects a second pending_review per pkgbase; audit table rejects UPDATE/DELETE by trigger; concurrent readers do not block the writer in a test."},{"id":"task-p0-shims","title":"Toolchain PATH shims + fake-package corpus (§16a)","status":"pending","verificationContract":"Fakes for mkarchroot/makechrootpkg/makepkg/repo-add/gpg/pacman record invocations and emit plausible .PKGINFO/.BUILDINFO/.sig per fixture manifest; at least plain-make, with-patch, skip-checksum, split-pkgbase, build-fails, missing-dep, epoch-bump, pkgrel-reset and downgrade fixtures exist and are driven by a test."},{"id":"task-p0-detect","title":"AUR mirror watcher: aur_commit pin, recipe_hash, source digests, candidate creation (§5.1, §5.1a, §5.3)","status":"pending","verificationContract":"Against a local file:// 'AUR' repo fixture: clone + ls-remote poll + fetch only on SHA move; snapshot records aur_commit and recipe_hash covering PKGBUILD/.SRCINFO/*.install/patches; SKIP sources are stream-hashed into source_cache; candidate.base is current_accepted_release; a brand-new pkgbase yields kind=first_introduction."},{"id":"task-p0-approve","title":"Approval semantics + CLI approval path (§7.1, §7.1a, §7.2)","status":"pending","verificationContract":"CLI approve writes an immutable approval row with diff_digest and identity_hash; approving with a stale identity_hash or diff_digest is refused; collapse-in-place bumps revision without a new row while unviewed and freezes as superseded once viewed; a rejected identity is not re-detected."},{"id":"task-p0-build","title":"Build pipeline steps 0–9 and atomic signed publish (§8.1, §9)","status":"pending","verificationContract":"Shim-driven run of materialize→plan→chroot→sources→pkgver→build→collect→verify→ingest→publish; step 0 materializes from the local mirror and fails closed on recipe_hash mismatch; step 4 fails closed on pkgver mismatch; publish writes .tmp, fsyncs, renames, signs package and db, and updates current_accepted_release_id by compare-and-swap."},{"id":"task-p0-invariants","title":"Executable invariant tests I1/I2/I4/I5/I8","status":"pending","verificationContract":"cargo test includes: post-run query proving no index entry lacks an approval (I1); multi-detection fixture proving the diff base is the last accepted version (I2); kill-mid-publish leaving the old index intact (I4); restart-resumes-at-next-incomplete-step with no duplicate side effects (I5); index set equals accepted-release pointers (I8)."}]},{"id":"task-p1","title":"P1 — VCS / computed pkgver detection (§5.2, §3)","status":"pending","subtasks":[{"id":"task-p1-stageA","title":"Stage A upstream probes over all VCS sources + persistent vcs_cache","status":"pending","verificationContract":"Parses source=() for git+/svn+/hg+ with #tag/#commit refs; probes via git ls-remote against local file:// repos; an unchanged HEAD set short-circuits before Stage B; multiple VCS sources each get their own pin entry."},{"id":"task-p1-stageB","title":"Stage B pkgver() resolution with pin capture + identity tuple","status":"pending","verificationContract":"Resolved epoch:pkgver-pkgrel plus upstream_pins become part of identity_hash; cooldown and global concurrency cap enforced; cache keyed on (pkgbase, recipe_hash, upstream_tip); a git-sourced fixture produces a candidate whose pins match the fixture repo HEAD."},{"id":"task-p1-notices","title":"Non-publishable change handling: pin_drift, recipe drift, digest drift → notice / integrity_alert (§5.2, §5.3, I11)","status":"pending","verificationContract":"pin-drift fixture yields a notice and no candidate; digest-drift fixture yields a high-severity integrity_alert and no candidate; SKIP-on-non-VCS is flagged as a risk signal; nothing publishable is silently dropped."}]},{"id":"task-p2","title":"P2 — review surface (§12, §13, §6)","status":"pending","subtasks":[{"id":"task-p2-http","title":"tiny_http server, templating, thread-local readers, CSRF + session gate","status":"pending","verificationContract":"Thread-per-connection server renders all §12 routes; every POST requires a CSRF token; handlers never use the write connection; pages render with JS disabled."},{"id":"task-p2-inbox","title":"Inbox + diff panels + advisory risk scoring (§6, §7.1b)","status":"pending","verificationContract":"Review detail renders recipe / version / source-digest / upstream / source / dependency / build-env / install-hook panels, all based on accepted→candidate; risk signals computed and shown inline; base and aur_commit displayed with an AUR cgit link; first_introduction renders the full recipe with the subtle accent and no diff pane."},{"id":"task-p2-approve409","title":"Optimistic-concurrency approve/reject + bulk operations (§7.1a, §7.4)","status":"pending","verificationContract":"Approve POST with a stale identity_hash/diff_digest returns 409 and re-renders the current diff with an explanation; bulk approve refuses high-risk items without per-item confirmation; reject requires a note and is re-openable."},{"id":"task-p2-surfaces","title":"Subscriptions, Index, Builds, Attention, Ops/audit pages","status":"pending","verificationContract":"Each §13 surface renders from live DB state; Attention shows outdated-dependency, downgrade and blocked-build rows; the package page shows timeline, deps in/out, staleness and aur_commit history; manual rebuild reuses the approved source identity without a new approval (I6)."}]},{"id":"task-p3","title":"P3 — durability (§8.2, §8.3, §8.4)","status":"pending","subtasks":[{"id":"task-p3-dispatch","title":"Dispatcher actor, worker pool, leases, and reaper","status":"pending","verificationContract":"Dispatcher claims with BEGIN IMMEDIATE + lease expiry, requeues expired leases on startup, marks in-flight steps interrupted; the deterministic build id makes re-enqueue an INSERT OR IGNORE no-op; backpressure respects max_concurrent_builds and disk headroom."},{"id":"task-p3-crash","title":"Cancellation, retry policy, and crash-resume tests against shims (I5)","status":"pending","verificationContract":"A test kills the process mid-step and asserts resume at the next incomplete step with no duplicate side effects; cancel_requested stops a worker at a step boundary; deterministic build failures do not auto-retry and the release stays approved_but_unbuilt with the UI showing 'index still serving v1'."},{"id":"task-p3-sse","title":"SSE log tail + htmx live builds table","status":"pending","verificationContract":"GET /builds/:id/log.stream streams appended log bytes from a blocking thread; the builds table refreshes via htmx every 3s; vendored htmx is the only JS shipped and total vendored JS stays under 20 KB."}]},{"id":"task-p4","title":"P4 — staleness, retention, metrics (§10, §15)","status":"pending","subtasks":[{"id":"task-p4-world","title":".PKGINFO/.BUILDINFO parsing and world_snapshot filtered to our own repo","status":"pending","verificationContract":"Ingest parses tar+text without libalpm; world_snapshot members are intersected with our index at ingest time (not query time); split pkgbases produce N package rows from one approval."},{"id":"task-p4-stale","title":"Staleness query, downgrades, blocked_missing_dep, and dependents view","status":"pending","verificationContract":"stale_outdated and stale_missing are derived purely on read; a build with an unresolvable dep enters blocked_missing_dep, appears on Attention with the blocking pkgbase named, and the review page warns about missing deps before approval; the dep_edge view answers 'approving this marks N packages stale'."},{"id":"task-p4-ops","title":"Retention/GC, metrics endpoint, and backup helper","status":"pending","verificationContract":"Retention keeps N versions with logs and sources as a unit and sweeps abandoned staging dirs; GET /metrics emits prometheus text including queue depth, pending-review age histogram, build success rate and WAL size; backup uses VACUUM INTO (never cp of a live WAL db)."},{"id":"task-p4-deps","title":"vercmp + dependency-string parser and version-delta flagging (§4, §6)","status":"pending","verificationContract":"Hand-written vercmp and dep-string parser pass a table-driven test suite (epoch, pkgrel reset, alpha/numeric boundaries, provides/conflicts syntax); downgrade and epoch-bump detection use them and are covered by tests."}]},{"id":"task-verify","title":"Final verification pass, real-chroot attempt, and documentation","status":"pending","verificationContract":"Full `cargo test` and `cargo clippy` run clean; every §2 invariant maps to a named passing test (list produced); README + docs/DECISIONS.md written; git history reviewed for incremental commits; the gated real-chroot integration attempt against devtools is run or explicitly recorded as skipped with the reason."}],"blockCompletion":true,"proposedAt":"2026-11-17T20:39:23.165Z"},"currentTaskId":"task-p0-schema"}]}
\ No newline at end of file diff --git a/.pi/goals/.goal-ledger-checkpoint.json b/.pi/goals/.goal-ledger-checkpoint.json index 5e37be3..1de8283 100644 --- a/.pi/goals/.goal-ledger-checkpoint.json +++ b/.pi/goals/.goal-ledger-checkpoint.json @@ -1 +1 @@ -{"version":4,"format":"goal-ledger-checkpoint","createdAt":"2026-11-17T20:43:42.925Z","coveredBytes":3883,"coveredEvents":3,"acc":{"goals":[{"goalId":"mwl5tehk-xhe7fk","latestStatus":"active","latestFocus":false,"createdAt":"2026-11-17T20:43:24.440Z"}],"terminalGoals":[],"focusedGoalId":null,"focusGeneration":0,"focusGenByGoal":[]},"recentEventsByGoal":[["mwl5tehk-xhe7fk",[{"type":"goal_created","goalId":"mwl5tehk-xhe7fk","objective":"Implement the AUR Build Server described in DESIGN.md as a single-process Rust binary in /workspace/aur-build, delivering phases P0–P4 (walking skeleton + test harness, VCS/pkgver detection, review web UI, durable build pipeline, staleness tracking), with every §2 invariant expressed as an executable test and the work committed incrementally to git.\n\nSUCCESS CRITERIA (observable):\n1. `cargo test` passes on the host with no `#[ignore]`-tier tests required; the §16a fake-package corpus and toolchain PATH shims drive the full step machine, publishing and crash-resume tests without root, network, or a real chroot.\n2. Invariants I1–I12 of §2 each have a named test that passes (I1 no-artifact-without-approval is a post-test query; I2 diff-base-is-last-accepted; I4 atomic publish survives kill-mid-publish; I5 step checkpoint/resume; I7 one open review enforced by the partial unique index; I12 world snapshots recorded).\n3. End-to-end against shims: subscribe pkgbase → detect → review → approve → build → publish a signed repo where both packages and the .db are signed, and the served index equals the set of current_accepted_release pointers (I8).\n4. Web UI serves the five §13 surfaces (Inbox, Builds, Attention, Index, Subscriptions) plus Ops/audit as server-rendered HTML; approve carries identity_hash + diff_digest and returns HTTP 409 on a stale approval (§7.1a).\n5. `cargo clippy` reports no errors; `git log` shows a sequence of small, meaningful commits from the initial scaffold to the final state; README documents build, run, and test commands.\n\nBOUNDARIES — IN SCOPE: P0, P1, P2, P3, P4 of §17, the §11 schema, §16 edge cases, §16a test harness, and one gated real-chroot integration attempt (devtools installed) if time permits.\nOUT OF SCOPE: everything in §20 (auto-approval policies, automatic dependency rebuilds, recipe-mutating hardening transforms, build-time upstream-pin honouring, network controls, cost-weighted admission, notifications), P5 polish, multi-tenancy/RBAC, non-x86_64 arches, and any change to DESIGN.md's decided decisions in §18.\n\nCONSTRAINTS (hard):\n- Rust edition 2021, no `async`/`await`, no tokio/axum/actix/reqwest/sqlx/libgit2; threads + crossbeam channels only; blocking HTTP via tiny_http; outbound HTTP via ureq; git by shelling out.\n- SQLite via rusqlite in WAL mode with exactly one writer actor thread (channel-based `Tx` enum) and thread-local read-only readers; no transaction may span a build step.\n- UI is server-rendered (askama or minijinja) with at most vendored htmx (~14 KB) plus ~30 lines of glue; no JS written by us beyond that glue, no bundler.\n- Fail closed on every pin assertion (recipe_hash, pkgver match against approved identity); non-publishable changes become `notice` rows, never candidates, never dropped (I11).\n- Provisioning: `sudo pacman -S --needed rustup devtools` (fall back to `pacman -S rust` only if rustup is unusable); no other system mutations; never commit secrets, the signing key, or build artifacts.\n- Commit incrementally: one commit per coherent step with a descriptive message; never a single monolithic commit; DESIGN.md stays untouched.\n- If a §19 open question blocks a design choice, pick the least-entangling option, record it in a `docs/DECISIONS.md` entry, and keep moving; stop and ask only if the choice is genuinely irreversible.\n\nIF BLOCKED: stop and ask the user (e.g. no network for crates, toolchain uninstallable, an invariant that cannot be made testable).","sisyphus":false,"autoContinue":true,"at":"2026-11-17T20:43:24.440Z"},{"type":"task_list_set","goalId":"mwl5tehk-xhe7fk","taskCount":7,"blockCompletion":true,"at":"2026-11-17T20:43:24.440Z"},{"type":"task_started","goalId":"mwl5tehk-xhe7fk","taskId":"task-setup","at":"2026-11-17T20:43:42.908Z"}]]],"runtimeIndex":[["mwl5tehk-xhe7fk",{"recent":[{"type":"goal_created","goalId":"mwl5tehk-xhe7fk","objective":"Implement the AUR Build Server described in DESIGN.md as a single-process Rust binary in /workspace/aur-build, delivering phases P0–P4 (walking skeleton + test harness, VCS/pkgver detection, review web UI, durable build pipeline, staleness tracking), with every §2 invariant expressed as an executable test and the work committed incrementally to git.\n\nSUCCESS CRITERIA (observable):\n1. `cargo test` passes on the host with no `#[ignore]`-tier tests required; the §16a fake-package corpus and toolchain PATH shims drive the full step machine, publishing and crash-resume tests without root, network, or a real chroot.\n2. Invariants I1–I12 of §2 each have a named test that passes (I1 no-artifact-without-approval is a post-test query; I2 diff-base-is-last-accepted; I4 atomic publish survives kill-mid-publish; I5 step checkpoint/resume; I7 one open review enforced by the partial unique index; I12 world snapshots recorded).\n3. End-to-end against shims: subscribe pkgbase → detect → review → approve → build → publish a signed repo where both packages and the .db are signed, and the served index equals the set of current_accepted_release pointers (I8).\n4. Web UI serves the five §13 surfaces (Inbox, Builds, Attention, Index, Subscriptions) plus Ops/audit as server-rendered HTML; approve carries identity_hash + diff_digest and returns HTTP 409 on a stale approval (§7.1a).\n5. `cargo clippy` reports no errors; `git log` shows a sequence of small, meaningful commits from the initial scaffold to the final state; README documents build, run, and test commands.\n\nBOUNDARIES — IN SCOPE: P0, P1, P2, P3, P4 of §17, the §11 schema, §16 edge cases, §16a test harness, and one gated real-chroot integration attempt (devtools installed) if time permits.\nOUT OF SCOPE: everything in §20 (auto-approval policies, automatic dependency rebuilds, recipe-mutating hardening transforms, build-time upstream-pin honouring, network controls, cost-weighted admission, notifications), P5 polish, multi-tenancy/RBAC, non-x86_64 arches, and any change to DESIGN.md's decided decisions in §18.\n\nCONSTRAINTS (hard):\n- Rust edition 2021, no `async`/`await`, no tokio/axum/actix/reqwest/sqlx/libgit2; threads + crossbeam channels only; blocking HTTP via tiny_http; outbound HTTP via ureq; git by shelling out.\n- SQLite via rusqlite in WAL mode with exactly one writer actor thread (channel-based `Tx` enum) and thread-local read-only readers; no transaction may span a build step.\n- UI is server-rendered (askama or minijinja) with at most vendored htmx (~14 KB) plus ~30 lines of glue; no JS written by us beyond that glue, no bundler.\n- Fail closed on every pin assertion (recipe_hash, pkgver match against approved identity); non-publishable changes become `notice` rows, never candidates, never dropped (I11).\n- Provisioning: `sudo pacman -S --needed rustup devtools` (fall back to `pacman -S rust` only if rustup is unusable); no other system mutations; never commit secrets, the signing key, or build artifacts.\n- Commit incrementally: one commit per coherent step with a descriptive message; never a single monolithic commit; DESIGN.md stays untouched.\n- If a §19 open question blocks a design choice, pick the least-entangling option, record it in a `docs/DECISIONS.md` entry, and keep moving; stop and ask only if the choice is genuinely irreversible.\n\nIF BLOCKED: stop and ask the user (e.g. no network for crates, toolchain uninstallable, an invariant that cannot be made testable).","sisyphus":false,"autoContinue":true,"at":"2026-11-17T20:43:24.440Z"},{"type":"task_list_set","goalId":"mwl5tehk-xhe7fk","taskCount":7,"blockCompletion":true,"at":"2026-11-17T20:43:24.440Z"},{"type":"task_started","goalId":"mwl5tehk-xhe7fk","taskId":"task-setup","at":"2026-11-17T20:43:42.908Z"}],"activity":[{"type":"goal_created","goalId":"mwl5tehk-xhe7fk","objective":"Implement the AUR Build Server described in DESIGN.md as a single-process Rust binary in /workspace/aur-build, delivering phases P0–P4 (walking skeleton + test harness, VCS/pkgver detection, review web UI, durable build pipeline, staleness tracking), with every §2 invariant expressed as an executable test and the work committed incrementally to git.\n\nSUCCESS CRITERIA (observable):\n1. `cargo test` passes on the host with no `#[ignore]`-tier tests required; the §16a fake-package corpus and toolchain PATH shims drive the full step machine, publishing and crash-resume tests without root, network, or a real chroot.\n2. Invariants I1–I12 of §2 each have a named test that passes (I1 no-artifact-without-approval is a post-test query; I2 diff-base-is-last-accepted; I4 atomic publish survives kill-mid-publish; I5 step checkpoint/resume; I7 one open review enforced by the partial unique index; I12 world snapshots recorded).\n3. End-to-end against shims: subscribe pkgbase → detect → review → approve → build → publish a signed repo where both packages and the .db are signed, and the served index equals the set of current_accepted_release pointers (I8).\n4. Web UI serves the five §13 surfaces (Inbox, Builds, Attention, Index, Subscriptions) plus Ops/audit as server-rendered HTML; approve carries identity_hash + diff_digest and returns HTTP 409 on a stale approval (§7.1a).\n5. `cargo clippy` reports no errors; `git log` shows a sequence of small, meaningful commits from the initial scaffold to the final state; README documents build, run, and test commands.\n\nBOUNDARIES — IN SCOPE: P0, P1, P2, P3, P4 of §17, the §11 schema, §16 edge cases, §16a test harness, and one gated real-chroot integration attempt (devtools installed) if time permits.\nOUT OF SCOPE: everything in §20 (auto-approval policies, automatic dependency rebuilds, recipe-mutating hardening transforms, build-time upstream-pin honouring, network controls, cost-weighted admission, notifications), P5 polish, multi-tenancy/RBAC, non-x86_64 arches, and any change to DESIGN.md's decided decisions in §18.\n\nCONSTRAINTS (hard):\n- Rust edition 2021, no `async`/`await`, no tokio/axum/actix/reqwest/sqlx/libgit2; threads + crossbeam channels only; blocking HTTP via tiny_http; outbound HTTP via ureq; git by shelling out.\n- SQLite via rusqlite in WAL mode with exactly one writer actor thread (channel-based `Tx` enum) and thread-local read-only readers; no transaction may span a build step.\n- UI is server-rendered (askama or minijinja) with at most vendored htmx (~14 KB) plus ~30 lines of glue; no JS written by us beyond that glue, no bundler.\n- Fail closed on every pin assertion (recipe_hash, pkgver match against approved identity); non-publishable changes become `notice` rows, never candidates, never dropped (I11).\n- Provisioning: `sudo pacman -S --needed rustup devtools` (fall back to `pacman -S rust` only if rustup is unusable); no other system mutations; never commit secrets, the signing key, or build artifacts.\n- Commit incrementally: one commit per coherent step with a descriptive message; never a single monolithic commit; DESIGN.md stays untouched.\n- If a §19 open question blocks a design choice, pick the least-entangling option, record it in a `docs/DECISIONS.md` entry, and keep moving; stop and ask only if the choice is genuinely irreversible.\n\nIF BLOCKED: stop and ask the user (e.g. no network for crates, toolchain uninstallable, an invariant that cannot be made testable).","sisyphus":false,"autoContinue":true,"at":"2026-11-17T20:43:24.440Z"},{"type":"task_started","goalId":"mwl5tehk-xhe7fk","taskId":"task-setup","at":"2026-11-17T20:43:42.908Z"}],"oracle":[],"lifecycle":{"type":"goal_created","goalId":"mwl5tehk-xhe7fk","objective":"Implement the AUR Build Server described in DESIGN.md as a single-process Rust binary in /workspace/aur-build, delivering phases P0–P4 (walking skeleton + test harness, VCS/pkgver detection, review web UI, durable build pipeline, staleness tracking), with every §2 invariant expressed as an executable test and the work committed incrementally to git.\n\nSUCCESS CRITERIA (observable):\n1. `cargo test` passes on the host with no `#[ignore]`-tier tests required; the §16a fake-package corpus and toolchain PATH shims drive the full step machine, publishing and crash-resume tests without root, network, or a real chroot.\n2. Invariants I1–I12 of §2 each have a named test that passes (I1 no-artifact-without-approval is a post-test query; I2 diff-base-is-last-accepted; I4 atomic publish survives kill-mid-publish; I5 step checkpoint/resume; I7 one open review enforced by the partial unique index; I12 world snapshots recorded).\n3. End-to-end against shims: subscribe pkgbase → detect → review → approve → build → publish a signed repo where both packages and the .db are signed, and the served index equals the set of current_accepted_release pointers (I8).\n4. Web UI serves the five §13 surfaces (Inbox, Builds, Attention, Index, Subscriptions) plus Ops/audit as server-rendered HTML; approve carries identity_hash + diff_digest and returns HTTP 409 on a stale approval (§7.1a).\n5. `cargo clippy` reports no errors; `git log` shows a sequence of small, meaningful commits from the initial scaffold to the final state; README documents build, run, and test commands.\n\nBOUNDARIES — IN SCOPE: P0, P1, P2, P3, P4 of §17, the §11 schema, §16 edge cases, §16a test harness, and one gated real-chroot integration attempt (devtools installed) if time permits.\nOUT OF SCOPE: everything in §20 (auto-approval policies, automatic dependency rebuilds, recipe-mutating hardening transforms, build-time upstream-pin honouring, network controls, cost-weighted admission, notifications), P5 polish, multi-tenancy/RBAC, non-x86_64 arches, and any change to DESIGN.md's decided decisions in §18.\n\nCONSTRAINTS (hard):\n- Rust edition 2021, no `async`/`await`, no tokio/axum/actix/reqwest/sqlx/libgit2; threads + crossbeam channels only; blocking HTTP via tiny_http; outbound HTTP via ureq; git by shelling out.\n- SQLite via rusqlite in WAL mode with exactly one writer actor thread (channel-based `Tx` enum) and thread-local read-only readers; no transaction may span a build step.\n- UI is server-rendered (askama or minijinja) with at most vendored htmx (~14 KB) plus ~30 lines of glue; no JS written by us beyond that glue, no bundler.\n- Fail closed on every pin assertion (recipe_hash, pkgver match against approved identity); non-publishable changes become `notice` rows, never candidates, never dropped (I11).\n- Provisioning: `sudo pacman -S --needed rustup devtools` (fall back to `pacman -S rust` only if rustup is unusable); no other system mutations; never commit secrets, the signing key, or build artifacts.\n- Commit incrementally: one commit per coherent step with a descriptive message; never a single monolithic commit; DESIGN.md stays untouched.\n- If a §19 open question blocks a design choice, pick the least-entangling option, record it in a `docs/DECISIONS.md` entry, and keep moving; stop and ask only if the choice is genuinely irreversible.\n\nIF BLOCKED: stop and ask the user (e.g. no network for crates, toolchain uninstallable, an invariant that cannot be made testable).","sisyphus":false,"autoContinue":true,"at":"2026-11-17T20:43:24.440Z"},"lastActivityEvent":{"type":"task_started","goalId":"mwl5tehk-xhe7fk","taskId":"task-setup","at":"2026-11-17T20:43:42.908Z"}}]]}
\ No newline at end of file +{"version":4,"format":"goal-ledger-checkpoint","createdAt":"2026-11-17T20:48:42.928Z","coveredBytes":4312,"coveredEvents":5,"acc":{"goals":[{"goalId":"mwl5tehk-xhe7fk","latestStatus":"active","latestFocus":false,"createdAt":"2026-11-17T20:43:24.440Z"}],"terminalGoals":[],"focusedGoalId":null,"focusGeneration":0,"focusGenByGoal":[]},"recentEventsByGoal":[["mwl5tehk-xhe7fk",[{"type":"goal_created","goalId":"mwl5tehk-xhe7fk","objective":"Implement the AUR Build Server described in DESIGN.md as a single-process Rust binary in /workspace/aur-build, delivering phases P0–P4 (walking skeleton + test harness, VCS/pkgver detection, review web UI, durable build pipeline, staleness tracking), with every §2 invariant expressed as an executable test and the work committed incrementally to git.\n\nSUCCESS CRITERIA (observable):\n1. `cargo test` passes on the host with no `#[ignore]`-tier tests required; the §16a fake-package corpus and toolchain PATH shims drive the full step machine, publishing and crash-resume tests without root, network, or a real chroot.\n2. Invariants I1–I12 of §2 each have a named test that passes (I1 no-artifact-without-approval is a post-test query; I2 diff-base-is-last-accepted; I4 atomic publish survives kill-mid-publish; I5 step checkpoint/resume; I7 one open review enforced by the partial unique index; I12 world snapshots recorded).\n3. End-to-end against shims: subscribe pkgbase → detect → review → approve → build → publish a signed repo where both packages and the .db are signed, and the served index equals the set of current_accepted_release pointers (I8).\n4. Web UI serves the five §13 surfaces (Inbox, Builds, Attention, Index, Subscriptions) plus Ops/audit as server-rendered HTML; approve carries identity_hash + diff_digest and returns HTTP 409 on a stale approval (§7.1a).\n5. `cargo clippy` reports no errors; `git log` shows a sequence of small, meaningful commits from the initial scaffold to the final state; README documents build, run, and test commands.\n\nBOUNDARIES — IN SCOPE: P0, P1, P2, P3, P4 of §17, the §11 schema, §16 edge cases, §16a test harness, and one gated real-chroot integration attempt (devtools installed) if time permits.\nOUT OF SCOPE: everything in §20 (auto-approval policies, automatic dependency rebuilds, recipe-mutating hardening transforms, build-time upstream-pin honouring, network controls, cost-weighted admission, notifications), P5 polish, multi-tenancy/RBAC, non-x86_64 arches, and any change to DESIGN.md's decided decisions in §18.\n\nCONSTRAINTS (hard):\n- Rust edition 2021, no `async`/`await`, no tokio/axum/actix/reqwest/sqlx/libgit2; threads + crossbeam channels only; blocking HTTP via tiny_http; outbound HTTP via ureq; git by shelling out.\n- SQLite via rusqlite in WAL mode with exactly one writer actor thread (channel-based `Tx` enum) and thread-local read-only readers; no transaction may span a build step.\n- UI is server-rendered (askama or minijinja) with at most vendored htmx (~14 KB) plus ~30 lines of glue; no JS written by us beyond that glue, no bundler.\n- Fail closed on every pin assertion (recipe_hash, pkgver match against approved identity); non-publishable changes become `notice` rows, never candidates, never dropped (I11).\n- Provisioning: `sudo pacman -S --needed rustup devtools` (fall back to `pacman -S rust` only if rustup is unusable); no other system mutations; never commit secrets, the signing key, or build artifacts.\n- Commit incrementally: one commit per coherent step with a descriptive message; never a single monolithic commit; DESIGN.md stays untouched.\n- If a §19 open question blocks a design choice, pick the least-entangling option, record it in a `docs/DECISIONS.md` entry, and keep moving; stop and ask only if the choice is genuinely irreversible.\n\nIF BLOCKED: stop and ask the user (e.g. no network for crates, toolchain uninstallable, an invariant that cannot be made testable).","sisyphus":false,"autoContinue":true,"at":"2026-11-17T20:43:24.440Z"},{"type":"task_list_set","goalId":"mwl5tehk-xhe7fk","taskCount":7,"blockCompletion":true,"at":"2026-11-17T20:43:24.440Z"},{"type":"task_started","goalId":"mwl5tehk-xhe7fk","taskId":"task-setup","at":"2026-11-17T20:43:42.908Z"},{"type":"task_complete","goalId":"mwl5tehk-xhe7fk","taskId":"task-setup","evidence":"rustup 1.29.3 (pacman) + stable 1.100.0, devtools installed (mkarchroot/makechrootpkg present); git repo initialized on main with commit 3762c7c containing DESIGN.md, .gitignore, Cargo.toml; `cargo bu","at":"2026-11-17T20:48:20.900Z"},{"type":"task_started","goalId":"mwl5tehk-xhe7fk","taskId":"task-p0-schema","at":"2026-11-17T20:48:42.903Z"}]]],"runtimeIndex":[["mwl5tehk-xhe7fk",{"recent":[{"type":"goal_created","goalId":"mwl5tehk-xhe7fk","objective":"Implement the AUR Build Server described in DESIGN.md as a single-process Rust binary in /workspace/aur-build, delivering phases P0–P4 (walking skeleton + test harness, VCS/pkgver detection, review web UI, durable build pipeline, staleness tracking), with every §2 invariant expressed as an executable test and the work committed incrementally to git.\n\nSUCCESS CRITERIA (observable):\n1. `cargo test` passes on the host with no `#[ignore]`-tier tests required; the §16a fake-package corpus and toolchain PATH shims drive the full step machine, publishing and crash-resume tests without root, network, or a real chroot.\n2. Invariants I1–I12 of §2 each have a named test that passes (I1 no-artifact-without-approval is a post-test query; I2 diff-base-is-last-accepted; I4 atomic publish survives kill-mid-publish; I5 step checkpoint/resume; I7 one open review enforced by the partial unique index; I12 world snapshots recorded).\n3. End-to-end against shims: subscribe pkgbase → detect → review → approve → build → publish a signed repo where both packages and the .db are signed, and the served index equals the set of current_accepted_release pointers (I8).\n4. Web UI serves the five §13 surfaces (Inbox, Builds, Attention, Index, Subscriptions) plus Ops/audit as server-rendered HTML; approve carries identity_hash + diff_digest and returns HTTP 409 on a stale approval (§7.1a).\n5. `cargo clippy` reports no errors; `git log` shows a sequence of small, meaningful commits from the initial scaffold to the final state; README documents build, run, and test commands.\n\nBOUNDARIES — IN SCOPE: P0, P1, P2, P3, P4 of §17, the §11 schema, §16 edge cases, §16a test harness, and one gated real-chroot integration attempt (devtools installed) if time permits.\nOUT OF SCOPE: everything in §20 (auto-approval policies, automatic dependency rebuilds, recipe-mutating hardening transforms, build-time upstream-pin honouring, network controls, cost-weighted admission, notifications), P5 polish, multi-tenancy/RBAC, non-x86_64 arches, and any change to DESIGN.md's decided decisions in §18.\n\nCONSTRAINTS (hard):\n- Rust edition 2021, no `async`/`await`, no tokio/axum/actix/reqwest/sqlx/libgit2; threads + crossbeam channels only; blocking HTTP via tiny_http; outbound HTTP via ureq; git by shelling out.\n- SQLite via rusqlite in WAL mode with exactly one writer actor thread (channel-based `Tx` enum) and thread-local read-only readers; no transaction may span a build step.\n- UI is server-rendered (askama or minijinja) with at most vendored htmx (~14 KB) plus ~30 lines of glue; no JS written by us beyond that glue, no bundler.\n- Fail closed on every pin assertion (recipe_hash, pkgver match against approved identity); non-publishable changes become `notice` rows, never candidates, never dropped (I11).\n- Provisioning: `sudo pacman -S --needed rustup devtools` (fall back to `pacman -S rust` only if rustup is unusable); no other system mutations; never commit secrets, the signing key, or build artifacts.\n- Commit incrementally: one commit per coherent step with a descriptive message; never a single monolithic commit; DESIGN.md stays untouched.\n- If a §19 open question blocks a design choice, pick the least-entangling option, record it in a `docs/DECISIONS.md` entry, and keep moving; stop and ask only if the choice is genuinely irreversible.\n\nIF BLOCKED: stop and ask the user (e.g. no network for crates, toolchain uninstallable, an invariant that cannot be made testable).","sisyphus":false,"autoContinue":true,"at":"2026-11-17T20:43:24.440Z"},{"type":"task_list_set","goalId":"mwl5tehk-xhe7fk","taskCount":7,"blockCompletion":true,"at":"2026-11-17T20:43:24.440Z"},{"type":"task_started","goalId":"mwl5tehk-xhe7fk","taskId":"task-setup","at":"2026-11-17T20:43:42.908Z"},{"type":"task_complete","goalId":"mwl5tehk-xhe7fk","taskId":"task-setup","evidence":"rustup 1.29.3 (pacman) + stable 1.100.0, devtools installed (mkarchroot/makechrootpkg present); git repo initialized on main with commit 3762c7c containing DESIGN.md, .gitignore, Cargo.toml; `cargo bu","at":"2026-11-17T20:48:20.900Z"},{"type":"task_started","goalId":"mwl5tehk-xhe7fk","taskId":"task-p0-schema","at":"2026-11-17T20:48:42.903Z"}],"activity":[{"type":"goal_created","goalId":"mwl5tehk-xhe7fk","objective":"Implement the AUR Build Server described in DESIGN.md as a single-process Rust binary in /workspace/aur-build, delivering phases P0–P4 (walking skeleton + test harness, VCS/pkgver detection, review web UI, durable build pipeline, staleness tracking), with every §2 invariant expressed as an executable test and the work committed incrementally to git.\n\nSUCCESS CRITERIA (observable):\n1. `cargo test` passes on the host with no `#[ignore]`-tier tests required; the §16a fake-package corpus and toolchain PATH shims drive the full step machine, publishing and crash-resume tests without root, network, or a real chroot.\n2. Invariants I1–I12 of §2 each have a named test that passes (I1 no-artifact-without-approval is a post-test query; I2 diff-base-is-last-accepted; I4 atomic publish survives kill-mid-publish; I5 step checkpoint/resume; I7 one open review enforced by the partial unique index; I12 world snapshots recorded).\n3. End-to-end against shims: subscribe pkgbase → detect → review → approve → build → publish a signed repo where both packages and the .db are signed, and the served index equals the set of current_accepted_release pointers (I8).\n4. Web UI serves the five §13 surfaces (Inbox, Builds, Attention, Index, Subscriptions) plus Ops/audit as server-rendered HTML; approve carries identity_hash + diff_digest and returns HTTP 409 on a stale approval (§7.1a).\n5. `cargo clippy` reports no errors; `git log` shows a sequence of small, meaningful commits from the initial scaffold to the final state; README documents build, run, and test commands.\n\nBOUNDARIES — IN SCOPE: P0, P1, P2, P3, P4 of §17, the §11 schema, §16 edge cases, §16a test harness, and one gated real-chroot integration attempt (devtools installed) if time permits.\nOUT OF SCOPE: everything in §20 (auto-approval policies, automatic dependency rebuilds, recipe-mutating hardening transforms, build-time upstream-pin honouring, network controls, cost-weighted admission, notifications), P5 polish, multi-tenancy/RBAC, non-x86_64 arches, and any change to DESIGN.md's decided decisions in §18.\n\nCONSTRAINTS (hard):\n- Rust edition 2021, no `async`/`await`, no tokio/axum/actix/reqwest/sqlx/libgit2; threads + crossbeam channels only; blocking HTTP via tiny_http; outbound HTTP via ureq; git by shelling out.\n- SQLite via rusqlite in WAL mode with exactly one writer actor thread (channel-based `Tx` enum) and thread-local read-only readers; no transaction may span a build step.\n- UI is server-rendered (askama or minijinja) with at most vendored htmx (~14 KB) plus ~30 lines of glue; no JS written by us beyond that glue, no bundler.\n- Fail closed on every pin assertion (recipe_hash, pkgver match against approved identity); non-publishable changes become `notice` rows, never candidates, never dropped (I11).\n- Provisioning: `sudo pacman -S --needed rustup devtools` (fall back to `pacman -S rust` only if rustup is unusable); no other system mutations; never commit secrets, the signing key, or build artifacts.\n- Commit incrementally: one commit per coherent step with a descriptive message; never a single monolithic commit; DESIGN.md stays untouched.\n- If a §19 open question blocks a design choice, pick the least-entangling option, record it in a `docs/DECISIONS.md` entry, and keep moving; stop and ask only if the choice is genuinely irreversible.\n\nIF BLOCKED: stop and ask the user (e.g. no network for crates, toolchain uninstallable, an invariant that cannot be made testable).","sisyphus":false,"autoContinue":true,"at":"2026-11-17T20:43:24.440Z"},{"type":"task_started","goalId":"mwl5tehk-xhe7fk","taskId":"task-setup","at":"2026-11-17T20:43:42.908Z"},{"type":"task_complete","goalId":"mwl5tehk-xhe7fk","taskId":"task-setup","evidence":"rustup 1.29.3 (pacman) + stable 1.100.0, devtools installed (mkarchroot/makechrootpkg present); git repo initialized on main with commit 3762c7c containing DESIGN.md, .gitignore, Cargo.toml; `cargo bu","at":"2026-11-17T20:48:20.900Z"},{"type":"task_started","goalId":"mwl5tehk-xhe7fk","taskId":"task-p0-schema","at":"2026-11-17T20:48:42.903Z"}],"oracle":[],"lifecycle":{"type":"goal_created","goalId":"mwl5tehk-xhe7fk","objective":"Implement the AUR Build Server described in DESIGN.md as a single-process Rust binary in /workspace/aur-build, delivering phases P0–P4 (walking skeleton + test harness, VCS/pkgver detection, review web UI, durable build pipeline, staleness tracking), with every §2 invariant expressed as an executable test and the work committed incrementally to git.\n\nSUCCESS CRITERIA (observable):\n1. `cargo test` passes on the host with no `#[ignore]`-tier tests required; the §16a fake-package corpus and toolchain PATH shims drive the full step machine, publishing and crash-resume tests without root, network, or a real chroot.\n2. Invariants I1–I12 of §2 each have a named test that passes (I1 no-artifact-without-approval is a post-test query; I2 diff-base-is-last-accepted; I4 atomic publish survives kill-mid-publish; I5 step checkpoint/resume; I7 one open review enforced by the partial unique index; I12 world snapshots recorded).\n3. End-to-end against shims: subscribe pkgbase → detect → review → approve → build → publish a signed repo where both packages and the .db are signed, and the served index equals the set of current_accepted_release pointers (I8).\n4. Web UI serves the five §13 surfaces (Inbox, Builds, Attention, Index, Subscriptions) plus Ops/audit as server-rendered HTML; approve carries identity_hash + diff_digest and returns HTTP 409 on a stale approval (§7.1a).\n5. `cargo clippy` reports no errors; `git log` shows a sequence of small, meaningful commits from the initial scaffold to the final state; README documents build, run, and test commands.\n\nBOUNDARIES — IN SCOPE: P0, P1, P2, P3, P4 of §17, the §11 schema, §16 edge cases, §16a test harness, and one gated real-chroot integration attempt (devtools installed) if time permits.\nOUT OF SCOPE: everything in §20 (auto-approval policies, automatic dependency rebuilds, recipe-mutating hardening transforms, build-time upstream-pin honouring, network controls, cost-weighted admission, notifications), P5 polish, multi-tenancy/RBAC, non-x86_64 arches, and any change to DESIGN.md's decided decisions in §18.\n\nCONSTRAINTS (hard):\n- Rust edition 2021, no `async`/`await`, no tokio/axum/actix/reqwest/sqlx/libgit2; threads + crossbeam channels only; blocking HTTP via tiny_http; outbound HTTP via ureq; git by shelling out.\n- SQLite via rusqlite in WAL mode with exactly one writer actor thread (channel-based `Tx` enum) and thread-local read-only readers; no transaction may span a build step.\n- UI is server-rendered (askama or minijinja) with at most vendored htmx (~14 KB) plus ~30 lines of glue; no JS written by us beyond that glue, no bundler.\n- Fail closed on every pin assertion (recipe_hash, pkgver match against approved identity); non-publishable changes become `notice` rows, never candidates, never dropped (I11).\n- Provisioning: `sudo pacman -S --needed rustup devtools` (fall back to `pacman -S rust` only if rustup is unusable); no other system mutations; never commit secrets, the signing key, or build artifacts.\n- Commit incrementally: one commit per coherent step with a descriptive message; never a single monolithic commit; DESIGN.md stays untouched.\n- If a §19 open question blocks a design choice, pick the least-entangling option, record it in a `docs/DECISIONS.md` entry, and keep moving; stop and ask only if the choice is genuinely irreversible.\n\nIF BLOCKED: stop and ask the user (e.g. no network for crates, toolchain uninstallable, an invariant that cannot be made testable).","sisyphus":false,"autoContinue":true,"at":"2026-11-17T20:43:24.440Z"},"lastActivityEvent":{"type":"task_started","goalId":"mwl5tehk-xhe7fk","taskId":"task-p0-schema","at":"2026-11-17T20:48:42.903Z"}}]]}
\ No newline at end of file diff --git a/.pi/goals/active_goal_2026111720432444_mwl5tehk-xhe7fk.md b/.pi/goals/active_goal_2026111720432444_mwl5tehk-xhe7fk.md index 6041cfd..a54de59 100644 --- a/.pi/goals/active_goal_2026111720432444_mwl5tehk-xhe7fk.md +++ b/.pi/goals/active_goal_2026111720432444_mwl5tehk-xhe7fk.md @@ -5,14 +5,14 @@ "status": "active", "autoContinue": true, "usage": { - "tokensUsed": 85148, - "activeSeconds": 210 + "tokensUsed": 342691, + "activeSeconds": 955 }, "sisyphus": false, "createdAt": "2026-11-17T20:43:24.440Z", - "updatedAt": "2026-11-17T20:46:59.095Z", + "updatedAt": "2026-11-17T20:59:44.561Z", "activePath": ".pi/goals/active_goal_2026111720432444_mwl5tehk-xhe7fk.md", - "revision": 16, + "revision": 57, "scheduler": { "version": 1, "owner": "01a1eb32-2e3f-757c-a79a-21ac993facc5", @@ -35,8 +35,10 @@ { "id": "task-setup", "title": "Provision toolchain (pacman rustup + devtools) and initialize git", - "status": "pending", - "verificationContract": "`rustup show` and `cargo --version` work; `git -C /workspace/aur-build log` contains an initial commit with DESIGN.md, .gitignore, and a scaffolded Cargo.toml that `cargo build` compiles." + "status": "complete", + "verificationContract": "`rustup show` and `cargo --version` work; `git -C /workspace/aur-build log` contains an initial commit with DESIGN.md, .gitignore, and a scaffolded Cargo.toml that `cargo build` compiles.", + "completedAt": "2026-11-17T20:48:20.900Z", + "evidence": "rustup 1.29.3 (pacman) + stable 1.100.0, devtools installed (mkarchroot/makechrootpkg present); git repo initialized on main with commit 3762c7c containing DESIGN.md, .gitignore, Cargo.toml; `cargo bu" }, { "id": "task-p0", @@ -203,7 +205,7 @@ "blockCompletion": true, "proposedAt": "2026-11-17T20:39:23.165Z" }, - "currentTaskId": "task-setup" + "currentTaskId": "task-p0-schema" } # Goal Prompt @@ -236,12 +238,12 @@ IF BLOCKED: stop and ask the user (e.g. no network for crates, toolchain uninsta - Status: running - Auto-continue: on - Sisyphus mode: no -- Time spent: 3m30s -- Tokens used: 85K (85,148) tokens +- Time spent: 15m55s +- Tokens used: 343K (342,691) tokens ## Tasks <!-- blockCompletion: true --> -- [ ] task-setup: Provision toolchain (pacman rustup + devtools) and initialize git — contract: `rustup show` and `cargo --version` work; `git -C /workspace/aur-build log` contains an initial commit with DESIGN.md, .gitignore, and a scaffolded Cargo.toml that `cargo build` compiles. +- [x] task-setup: Provision toolchain (pacman rustup + devtools) and initialize git — evidence: rustup 1.29.3 (pacman) + stable 1.100.0, devtools installed (mkarchroot/makechrootpkg present); git repo initialized on main with commit 3762c7c containing DESIGN.md, .gitignore, Cargo.toml; `cargo bu - [ ] task-p0: P0 — walking skeleton + test harness (§17 P0, §16a) - [ ] task-p1: P1 — VCS / computed pkgver detection (§5.2, §3) - [ ] task-p2: P2 — review surface (§12, §13, §6) diff --git a/.pi/goals/goal_events.jsonl b/.pi/goals/goal_events.jsonl index 5a879c6..271fe31 100644 --- a/.pi/goals/goal_events.jsonl +++ b/.pi/goals/goal_events.jsonl @@ -1,3 +1,5 @@ {"type":"goal_created","goalId":"mwl5tehk-xhe7fk","objective":"Implement the AUR Build Server described in DESIGN.md as a single-process Rust binary in /workspace/aur-build, delivering phases P0–P4 (walking skeleton + test harness, VCS/pkgver detection, review web UI, durable build pipeline, staleness tracking), with every §2 invariant expressed as an executable test and the work committed incrementally to git.\n\nSUCCESS CRITERIA (observable):\n1. `cargo test` passes on the host with no `#[ignore]`-tier tests required; the §16a fake-package corpus and toolchain PATH shims drive the full step machine, publishing and crash-resume tests without root, network, or a real chroot.\n2. Invariants I1–I12 of §2 each have a named test that passes (I1 no-artifact-without-approval is a post-test query; I2 diff-base-is-last-accepted; I4 atomic publish survives kill-mid-publish; I5 step checkpoint/resume; I7 one open review enforced by the partial unique index; I12 world snapshots recorded).\n3. End-to-end against shims: subscribe pkgbase → detect → review → approve → build → publish a signed repo where both packages and the .db are signed, and the served index equals the set of current_accepted_release pointers (I8).\n4. Web UI serves the five §13 surfaces (Inbox, Builds, Attention, Index, Subscriptions) plus Ops/audit as server-rendered HTML; approve carries identity_hash + diff_digest and returns HTTP 409 on a stale approval (§7.1a).\n5. `cargo clippy` reports no errors; `git log` shows a sequence of small, meaningful commits from the initial scaffold to the final state; README documents build, run, and test commands.\n\nBOUNDARIES — IN SCOPE: P0, P1, P2, P3, P4 of §17, the §11 schema, §16 edge cases, §16a test harness, and one gated real-chroot integration attempt (devtools installed) if time permits.\nOUT OF SCOPE: everything in §20 (auto-approval policies, automatic dependency rebuilds, recipe-mutating hardening transforms, build-time upstream-pin honouring, network controls, cost-weighted admission, notifications), P5 polish, multi-tenancy/RBAC, non-x86_64 arches, and any change to DESIGN.md's decided decisions in §18.\n\nCONSTRAINTS (hard):\n- Rust edition 2021, no `async`/`await`, no tokio/axum/actix/reqwest/sqlx/libgit2; threads + crossbeam channels only; blocking HTTP via tiny_http; outbound HTTP via ureq; git by shelling out.\n- SQLite via rusqlite in WAL mode with exactly one writer actor thread (channel-based `Tx` enum) and thread-local read-only readers; no transaction may span a build step.\n- UI is server-rendered (askama or minijinja) with at most vendored htmx (~14 KB) plus ~30 lines of glue; no JS written by us beyond that glue, no bundler.\n- Fail closed on every pin assertion (recipe_hash, pkgver match against approved identity); non-publishable changes become `notice` rows, never candidates, never dropped (I11).\n- Provisioning: `sudo pacman -S --needed rustup devtools` (fall back to `pacman -S rust` only if rustup is unusable); no other system mutations; never commit secrets, the signing key, or build artifacts.\n- Commit incrementally: one commit per coherent step with a descriptive message; never a single monolithic commit; DESIGN.md stays untouched.\n- If a §19 open question blocks a design choice, pick the least-entangling option, record it in a `docs/DECISIONS.md` entry, and keep moving; stop and ask only if the choice is genuinely irreversible.\n\nIF BLOCKED: stop and ask the user (e.g. no network for crates, toolchain uninstallable, an invariant that cannot be made testable).","sisyphus":false,"autoContinue":true,"at":"2026-11-17T20:43:24.440Z"} {"type":"task_list_set","goalId":"mwl5tehk-xhe7fk","taskCount":7,"blockCompletion":true,"at":"2026-11-17T20:43:24.440Z"} {"type":"task_started","goalId":"mwl5tehk-xhe7fk","taskId":"task-setup","at":"2026-11-17T20:43:42.908Z"} +{"type":"task_complete","goalId":"mwl5tehk-xhe7fk","taskId":"task-setup","evidence":"rustup 1.29.3 (pacman) + stable 1.100.0, devtools installed (mkarchroot/makechrootpkg present); git repo initialized on main with commit 3762c7c containing DESIGN.md, .gitignore, Cargo.toml; `cargo bu","at":"2026-11-17T20:48:20.900Z"} +{"type":"task_started","goalId":"mwl5tehk-xhe7fk","taskId":"task-p0-schema","at":"2026-11-17T20:48:42.903Z"} @@ -57,5 +57,10 @@ tar = "0.4" zstd = "0.13" flate2 = "1" +[lints.cargo] +# Cargo warns about dependencies that are not yet referenced from every target; +# they are all used by targets further down the roadmap. +unused_dependencies = "allow" + [dev-dependencies] tempfile = "3" diff --git a/src/config.rs b/src/config.rs new file mode 100644 index 0000000..44b110c --- /dev/null +++ b/src/config.rs @@ -0,0 +1,201 @@ +//! 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}; + +/// Runtime configuration. Persisted as `<root>/config.json`. +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(default)] +pub struct Config { + /// Root directory holding 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). + pub signing_key_id: String, + /// Address the HTTP UI binds to. Default is loopback only (§14). + pub bind: String, + /// Shared credential for the UI. Single user, 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 makechrootpkg. + pub makechrootpkg_bin: String, + /// Path to mkarchroot. + pub mkarchroot_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. + pub build_user: String, + /// Directory prepended to PATH for child processes. The test harness puts + /// the toolchain shims here (§16a). + pub path_prepend: Option<PathBuf>, +} + +impl Default for Config { + fn default() -> Self { + Self { + root: PathBuf::from("/var/lib/aur-build"), + repo_name: "aur-build".into(), + arch: "x86_64".into(), + signing_key_id: String::new(), + bind: "127.0.0.1:8484".into(), + password: String::new(), + base_url: "http://127.0.0.1:8484".into(), + build_profile: "extra-x86_64".into(), + git_bin: "git".into(), + makepkg_bin: "makepkg".into(), + makechrootpkg_bin: "makechrootpkg".into(), + mkarchroot_bin: "mkarchroot".into(), + repo_add_bin: "repo-add".into(), + gpg_bin: "gpg".into(), + build_user: String::new(), + path_prepend: None, + } + } +} + +impl Config { + pub fn load(root: &Path) -> anyhow::Result<Self> { + let p = root.join("config.json"); + if !p.exists() { + anyhow::bail!("no config at {}; run `aur-build init`", p.display()); + } + let s = std::fs::read_to_string(&p)?; + let mut cfg: Config = serde_json::from_str(&s)?; + // root inside the config file is relative to the config's directory + // unless it is absolute; that keeps a moved tree usable. + if !cfg.root.is_absolute() { + cfg.root = root.join(&cfg.root); + } + Ok(cfg) + } + + pub fn save(&self) -> anyhow::Result<()> { + std::fs::create_dir_all(&self.root)?; + std::fs::write( + self.root.join("config.json"), + serde_json::to_string_pretty(self)? + "\n", + )?; + Ok(()) + } + + /// Create the directory tree the server needs. Idempotent. + pub fn ensure_dirs(&self) -> anyhow::Result<()> { + for d in [ + self.root.clone(), + self.mirrors_dir(), + self.vcs_cache_dir(), + self.source_cache_dir(), + self.staging_dir(), + self.store_dir(), + self.log_dir(), + self.repo_dir(), + self.chroot_dir(), + ] { + std::fs::create_dir_all(d)?; + } + std::fs::create_dir_all(self.repo_arch_dir())?; + Ok(()) + } + + 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") + } + pub fn vcs_cache_path(&self, url: &str) -> PathBuf { + 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") + } + pub fn store_path(&self, digest: &str) -> PathBuf { + self.store_dir().join(&digest[..2.min(digest.len())]).join(digest) + } + pub fn log_dir(&self) -> PathBuf { + self.root.join("logs") + } + 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") + } + pub fn repo_arch_dir(&self) -> PathBuf { + self.repo_dir() + .join(&self.repo_name) + .join("os") + .join(&self.arch) + } + pub fn repo_db_name(&self) -> String { + format!("{}.db", self.repo_name) + } + /// Warm chroot seeds, one per profile (§8.3). + pub fn chroot_dir(&self) -> PathBuf { + self.root.join("chroot") + } + pub fn chroot_seed(&self, profile: &str) -> PathBuf { + self.chroot_dir().join(profile) + } +} + +/// Filesystem-safe slug for a URL, used in cache filenames. +pub fn slug(url: &str) -> String { + url.chars() + .map(|c| { + if c.is_ascii_alphanumeric() { + c.to_ascii_lowercase() + } else { + '-' + } + }) + .collect::<String>() + .trim_matches('-') + .chars() + .take(32) + .collect() +} diff --git a/src/db/migrations.rs b/src/db/migrations.rs new file mode 100644 index 0000000..e0c1cb3 --- /dev/null +++ b/src/db/migrations.rs @@ -0,0 +1,293 @@ +//! 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, + pub name: &'static str, + pub sql: &'static str, +} + +const M_0001_CORE: &str = r#" +-- The single repo we publish. Exactly one row (DESIGN.md §9, decision 4). +CREATE TABLE repo ( + id INTEGER PRIMARY KEY, + name TEXT NOT NULL UNIQUE, + signing_key_id TEXT NOT NULL DEFAULT '', + path TEXT NOT NULL, + arch TEXT NOT NULL DEFAULT 'x86_64', + state TEXT NOT NULL DEFAULT 'active' +); + +CREATE TABLE settings ( + key TEXT PRIMARY KEY, + value TEXT NOT NULL +); + +-- Append-only audit log (I10). Enforced by trigger below. +CREATE TABLE audit ( + id INTEGER PRIMARY KEY, + at TEXT NOT NULL, + actor_kind TEXT NOT NULL, -- human | policy | system + actor TEXT NOT NULL DEFAULT '', + action TEXT NOT NULL, + entity TEXT NOT NULL, + entity_id TEXT NOT NULL DEFAULT '', + detail_json TEXT NOT NULL DEFAULT '{}' +); + +-- The unit of subscription, detection, diffing and approval. +CREATE TABLE pkgbase ( + id INTEGER PRIMARY KEY, + name TEXT NOT NULL UNIQUE, + aur_url TEXT NOT NULL, + mirror_path TEXT, + aur_head TEXT, -- live mirror tip + current_accepted_release_id INTEGER, -- the single pointer everything reads + state TEXT NOT NULL DEFAULT 'tracked', + unpinable INTEGER NOT NULL DEFAULT 0, -- §16 pkgver() that ignores pins + created_at TEXT NOT NULL +); + +CREATE TABLE subscription ( + id INTEGER PRIMARY KEY, + repo_id INTEGER NOT NULL REFERENCES repo(id), + pkgbase TEXT NOT NULL, + aur_url TEXT NOT NULL, + maintainer TEXT, + state TEXT NOT NULL DEFAULT 'active', -- active|paused|orphaned|removed + next_check_at TEXT, + last_checked_at TEXT, + last_error TEXT, + poll_interval_secs INTEGER, -- per-source override (§19) + created_at TEXT NOT NULL, + UNIQUE (repo_id, pkgbase) +); +CREATE INDEX subscription_due ON subscription (state, next_check_at); + +-- An immutable pin of the AUR git repo for a pkgbase (§5.1a). +CREATE TABLE snapshot ( + id INTEGER PRIMARY KEY, + pkgbase_id INTEGER NOT NULL REFERENCES pkgbase(id), + aur_commit TEXT NOT NULL, -- THE PIN + recipe_hash TEXT NOT NULL, + srcinfo_json TEXT NOT NULL, + files_json TEXT NOT NULL, + fetched_at TEXT NOT NULL, + UNIQUE (pkgbase_id, aur_commit) +); + +-- Fingerprint of the accepted dep set a build ran against (§10.1). +CREATE TABLE world_snapshot ( + id INTEGER PRIMARY KEY, + hash TEXT NOT NULL UNIQUE, + members_json TEXT NOT NULL, + created_at TEXT NOT NULL +); + +CREATE TABLE artifact ( + id INTEGER PRIMARY KEY, + digest TEXT NOT NULL UNIQUE, + size INTEGER NOT NULL, + path TEXT NOT NULL, + signature_path TEXT, + build_log_path TEXT, + source_archive_path TEXT, + created_at TEXT NOT NULL +); + +-- A detected, reviewable change. +CREATE TABLE candidate ( + id INTEGER PRIMARY KEY, + pkgbase_id INTEGER NOT NULL REFERENCES pkgbase(id), + base_release_id INTEGER REFERENCES release(id), -- last ACCEPTED, never last seen + kind TEXT NOT NULL, -- new_version | first_introduction + snapshot_id INTEGER NOT NULL REFERENCES snapshot(id), + epoch TEXT NOT NULL DEFAULT '0', + pkgver TEXT NOT NULL, + pkgrel TEXT NOT NULL, + upstream_pins_json TEXT NOT NULL DEFAULT '[]', + source_digests_json TEXT NOT NULL DEFAULT '[]', + identity_hash TEXT NOT NULL, + diff_digest TEXT NOT NULL DEFAULT '', + revision INTEGER NOT NULL DEFAULT 0, + viewed_at TEXT, + risk_level TEXT NOT NULL DEFAULT 'none', + risk_signals_json TEXT NOT NULL DEFAULT '[]', + missing_deps_json TEXT NOT NULL DEFAULT '[]', + state TEXT NOT NULL, -- pending_review|approved|rejected|superseded|blocked + detected_at TEXT NOT NULL, + resolved_at TEXT, + UNIQUE (pkgbase_id, identity_hash) +); +CREATE INDEX candidate_by_pkgbase ON candidate (pkgbase_id, state); +CREATE INDEX candidate_pending_age ON candidate (state, detected_at); + +-- I7: at most one open review per pkgbase, as a database guarantee. +CREATE UNIQUE INDEX one_open_review_per_pkgbase + ON candidate (pkgbase_id) WHERE state = 'pending_review'; + +-- The immutable decision record (§7.2). +CREATE TABLE approval ( + id INTEGER PRIMARY KEY, + candidate_id INTEGER NOT NULL UNIQUE REFERENCES candidate(id), + base_release_id INTEGER REFERENCES release(id), + decided_at TEXT NOT NULL, + decision TEXT NOT NULL, -- approved | rejected + risk_level TEXT NOT NULL, + diff_digest TEXT NOT NULL, + identity_hash TEXT NOT NULL, + note TEXT +); + +-- An approved candidate that has been built & published. +CREATE TABLE release ( + id INTEGER PRIMARY KEY, + pkgbase_id INTEGER NOT NULL REFERENCES pkgbase(id), + candidate_id INTEGER REFERENCES candidate(id), + approval_id INTEGER REFERENCES approval(id), + aur_commit TEXT NOT NULL, -- copied: provenance survives compaction + recipe_hash TEXT NOT NULL, + upstream_pins_json TEXT NOT NULL DEFAULT '[]', + source_digests_json TEXT NOT NULL DEFAULT '[]', + epoch TEXT NOT NULL DEFAULT '0', + pkgver TEXT NOT NULL, + pkgrel TEXT NOT NULL, + world_snapshot_id INTEGER REFERENCES world_snapshot(id), + state TEXT NOT NULL, -- published|withdrawn|failed_unbuilt + build_id TEXT, + published_at TEXT, + created_at TEXT NOT NULL +); +CREATE INDEX release_by_pkgbase ON release (pkgbase_id, state); + +-- `package` is the unit of the index and dependency resolution (§3). +CREATE TABLE package ( + id INTEGER PRIMARY KEY, + repo_id INTEGER NOT NULL REFERENCES repo(id), + release_id INTEGER NOT NULL REFERENCES release(id), + name TEXT NOT NULL, + arch TEXT NOT NULL, + version TEXT NOT NULL, + artifact_id INTEGER REFERENCES artifact(id), + state TEXT NOT NULL DEFAULT 'in_index' -- in_index | removed +); +CREATE INDEX package_by_name ON package (repo_id, name, state); +"#; + +const M_0002_BUILD: &str = r#" +CREATE TABLE build ( + id TEXT PRIMARY KEY, -- deterministic intent hash (§8.2) + pkgbase_id INTEGER NOT NULL REFERENCES pkgbase(id), + candidate_id INTEGER REFERENCES candidate(id), + release_id INTEGER REFERENCES release(id), + kind TEXT NOT NULL, -- new_version | manual_rebuild + world_snapshot_id INTEGER REFERENCES world_snapshot(id), + build_profile TEXT NOT NULL, + state TEXT NOT NULL, -- queued|leased|running|blocked_missing_dep| + -- succeeded|failed|cancelled + blocked_on_json TEXT NOT NULL DEFAULT '[]', + current_step TEXT, + lease_owner TEXT, + lease_expires_at TEXT, + attempt INTEGER NOT NULL DEFAULT 0, + priority INTEGER NOT NULL DEFAULT 0, + cancel_requested INTEGER NOT NULL DEFAULT 0, + error TEXT, + created_at TEXT NOT NULL, + updated_at TEXT NOT NULL +); +CREATE INDEX build_queued ON build (state, priority DESC, created_at); +CREATE INDEX build_lease ON build (state, lease_expires_at); + +-- Step-level checkpoints: the mechanism behind I5. +CREATE TABLE build_step ( + build_id TEXT NOT NULL REFERENCES build(id), + step TEXT NOT NULL, + status TEXT NOT NULL, -- pending|running|succeeded|failed|interrupted|skipped + attempt INTEGER NOT NULL DEFAULT 0, + output_digest TEXT, + error TEXT, + started_at TEXT, + finished_at TEXT, + PRIMARY KEY (build_id, step) +); +"#; + +const M_0003_NOTICES: &str = r#" +-- "something changed but nothing is publishable" (§5.2, I11). +CREATE TABLE notice ( + id INTEGER PRIMARY KEY, + pkgbase_id INTEGER NOT NULL REFERENCES pkgbase(id), + kind TEXT NOT NULL, -- pin_drift|recipe_drift|digest_drift|integrity_alert| + -- unpinable_pkgver|orphaned|deleted|renamed|downgrade + severity TEXT NOT NULL, -- info|warning|high + detail_json TEXT NOT NULL DEFAULT '{}', + created_at TEXT NOT NULL, + acknowledged_at TEXT +); +CREATE INDEX notice_open ON notice (acknowledged_at, severity, created_at); + +CREATE TABLE source_cache ( + url TEXT NOT NULL, + digest TEXT NOT NULL, + size INTEGER NOT NULL, + fetched_at TEXT NOT NULL, + path TEXT NOT NULL, + PRIMARY KEY (url, digest) +); + +CREATE TABLE vcs_cache ( + url TEXT PRIMARY KEY, + head TEXT NOT NULL, + path TEXT NOT NULL, + fetched_at TEXT NOT NULL +); + +-- Derived, read-only: "approving this marks N packages stale" (§10.5). +-- Nothing consumes it automatically; it is a read-time aid only. +CREATE TABLE dep_edge ( + from_pkgbase TEXT NOT NULL, + to_pkgbase TEXT NOT NULL, + kind TEXT NOT NULL, + updated_at TEXT NOT NULL, + CHECK (kind IN ('depend','makedepends')), + PRIMARY KEY (from_pkgbase, to_pkgbase, kind) +); +"#; + +const M_0004_TRIGGERS: &str = r#" +-- I10: the audit log is append-only. +CREATE TRIGGER audit_no_update +BEFORE UPDATE ON audit +BEGIN + SELECT RAISE(ABORT, 'audit log is append-only: updates are forbidden'); +END; + +CREATE TRIGGER audit_no_delete +BEFORE DELETE ON audit +BEGIN + SELECT RAISE(ABORT, 'audit log is append-only: deletes are forbidden'); +END; +"#; + +pub static MIGRATIONS: &[Migration] = &[ + Migration { version: 1, name: "core", sql: M_0001_CORE }, + Migration { version: 2, name: "build", sql: M_0002_BUILD }, + Migration { version: 3, name: "notices", sql: M_0003_NOTICES }, + Migration { version: 4, name: "audit-triggers", sql: M_0004_TRIGGERS }, +]; + +/// Default settings seeded into `settings` (DESIGN.md §11). +pub const DEFAULT_SETTINGS: &[(&str, &str)] = &[ + ("max_concurrent_builds", "1"), + ("build_timeout", "5400"), + ("poll_interval", "86400"), + ("stage_b_cooldown", "86400"), + ("retention_versions", "3"), + ("dry_run", "0"), + ("review_budget_days", "14"), +]; diff --git a/src/db/mod.rs b/src/db/mod.rs new file mode 100644 index 0000000..c11bf5a --- /dev/null +++ b/src/db/mod.rs @@ -0,0 +1,272 @@ +//! 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. + +mod migrations; +mod model; +mod queries; + +pub use migrations::MIGRATIONS; +pub use model::*; +pub use queries::*; + +use std::path::{Path, PathBuf}; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::Arc; + +use crossbeam_channel::{bounded, unbounded, Sender}; +use rusqlite::Connection; + +use crate::config::Config; +use crate::error::{Error, Result}; + +/// Open a connection with the pragmas every connection needs. +fn open(path: &Path, read_only: bool) -> Result<Connection> { + let conn = if read_only { + Connection::open_with_flags( + path, + rusqlite::OpenFlags::SQLITE_OPEN_READ_ONLY | rusqlite::OpenFlags::SQLITE_OPEN_NO_MUTEX, + ) + } else { + Connection::open(path) + } + .map_err(|e| Error::db(format!("open {}: {e}", path.display())))?; + configure(&conn, read_only)?; + Ok(conn) +} + +fn configure(conn: &Connection, read_only: bool) -> Result<()> { + conn.pragma_update(None, "journal_mode", "WAL") + .and_then(|_| conn.pragma_update(None, "busy_timeout", 5000)) + .and_then(|_| conn.pragma_update(None, "foreign_keys", "ON")) + .map_err(|e| Error::db(e.to_string()))?; + if !read_only { + // Durability of the approval trail is worth the fsync (§11a). + conn.pragma_update(None, "synchronous", "FULL") + .map_err(|e| Error::db(e.to_string()))?; + } + Ok(()) +} + +/// Apply pending migrations. Must run before the writer actor starts. +pub fn migrate(path: &Path) -> Result<u32> { + let mut conn = open(path, false)?; + let mut applied = 0u32; + let current: u32 = conn + .pragma_query_value(None, "user_version", |r| r.get(0)) + .map_err(|e| Error::db(e.to_string()))?; + for m in migrations::MIGRATIONS { + if m.version > current { + let tx = conn + .transaction() + .map_err(|e| Error::db(e.to_string()))?; + tx.execute_batch(m.sql) + .map_err(|e| Error::db(format!("migration {} ({}): {e}", m.version, m.name)))?; + tx.pragma_update(None, "user_version", m.version) + .map_err(|e| Error::db(e.to_string()))?; + tx.commit().map_err(|e| Error::db(e.to_string()))?; + applied += 1; + } + } + if applied > 0 { + let mut stmt = conn + .prepare("INSERT OR IGNORE INTO settings (key, value) VALUES (?1, ?2)") + .map_err(|e| Error::db(e.to_string()))?; + for (k, v) in migrations::DEFAULT_SETTINGS { + let _ = stmt.execute(rusqlite::params![k, *v]); + } + } + Ok(applied) +} + +type BoxedCall = Box<dyn FnOnce(&mut Connection) + Send>; + +enum Msg { + Call(BoxedCall), + Shutdown, +} + +/// Handle on the single writer thread. +/// +/// Cheap to clone; every clone talks to the same actor. +pub struct Writer { + tx: Sender<Msg>, + path: PathBuf, + alive: Arc<AtomicBool>, +} + +impl Writer { + /// Spawn the writer actor thread. + pub fn start(path: &Path) -> Result<Self> { + let conn = open(path, false)?; + let (tx, rx) = unbounded::<Msg>(); + let alive = Arc::new(AtomicBool::new(true)); + let alive_thread = alive.clone(); + let thread_path = path.to_path_buf(); + std::thread::Builder::new() + .name("db-writer".into()) + .spawn(move || { + let mut conn = conn; + alive_thread.store(true, Ordering::SeqCst); + for msg in rx.iter() { + match msg { + Msg::Call(f) => f(&mut conn), + Msg::Shutdown => break, + } + } + // Best-effort WAL checkpoint on the way out. + let _ = conn.pragma_update(None, "wal_checkpoint", "TRUNCATE"); + alive_thread.store(false, Ordering::SeqCst); + }) + .map_err(|e| Error::db(format!("spawn writer: {e}")))?; + Ok(Self { tx, path: thread_path, alive }) + } + + pub fn path(&self) -> &Path { + &self.path + } + + pub fn is_alive(&self) -> bool { + 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. + pub fn call<T>(&self, f: impl FnOnce(&mut Connection) -> Result<T> + Send + 'static) -> Result<T> + where + T: Send + 'static, + { + let (reply_tx, reply_rx) = bounded::<Result<T>>(1); + self.send(Box::new(move |conn| { + let _ = reply_tx.send(f(conn)); + }))?; + reply_rx + .recv() + .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. + pub fn tx<T>( + &self, + f: impl FnOnce(&mut rusqlite::Transaction<'_>) -> Result<T> + Send + 'static, + ) -> Result<T> + where + T: Send + 'static, + { + self.call(move |conn| { + let mut tx = conn + .transaction_with_behavior(rusqlite::TransactionBehavior::Immediate) + .map_err(|e| Error::db(e.to_string()))?; + let out = f(&mut tx)?; + tx.commit().map_err(|e| Error::db(e.to_string()))?; + Ok(out) + }) + } + + /// Fire-and-forget write (audit rows, bookkeeping where the result is unused). + pub fn send(&self, f: BoxedCall) -> Result<()> { + if !self.is_alive() { + return Err(Error::db("writer actor gone")); + } + self.tx + .send(Msg::Call(f)) + .map_err(|_| Error::db("writer actor gone")) + } + + pub fn shutdown(&self) { + let _ = self.tx.send(Msg::Shutdown); + } +} + +/// 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. +pub struct Readers { + path: PathBuf, +} + +thread_local! { + static POOL: std::cell::RefCell<Vec<(PathBuf, Connection)>> = const { std::cell::RefCell::new(Vec::new()) }; +} + +impl Readers { + pub fn new(path: &Path) -> Self { + Self { path: path.to_path_buf() } + } + + /// Run `f` against this thread's read-only connection. + pub fn with<T>(&self, f: impl FnOnce(&Connection) -> Result<T>) -> Result<T> { + let path = self.path.clone(); + POOL.with(|pool| { + let mut pool = pool.borrow_mut(); + if pool.iter().position(|(p, _)| p == &path).is_none() { + pool.push((path.clone(), open(&path, true)?)); + } + let idx = pool + .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). + let conn = &pool[idx].1; + f(conn) + }) + } +} + +/// A handle bundling the writer with a reader factory; passed around as `App`. +#[derive(Clone)] +pub struct Db { + pub writer: Arc<Writer>, + pub readers: Arc<Readers>, +} + +impl Db { + pub fn open(cfg: &Config) -> Result<Self> { + let path = cfg.db_path(); + migrate(&path)?; + Self::open_migrated(&path) + } + + pub fn open_migrated(path: &Path) -> Result<Self> { + Ok(Self { + writer: Arc::new(Writer::start(path)?), + readers: Arc::new(Readers::new(path)), + }) + } + + /// Convenience: read-only query against the shared reader pool. + pub fn read<T>(&self, f: impl FnOnce(&Connection) -> Result<T>) -> Result<T> { + self.readers.with(f) + } +} + +/// Consistent snapshot for backups: `VACUUM INTO`, never `cp` of a live WAL db. +pub fn backup_to(writer: &Writer, dest: &Path) -> Result<()> { + let dest_s = dest.display().to_string(); + writer.call(move |conn| { + conn.execute("VACUUM INTO ?1", rusqlite::params![dest_s]) + .map_err(|e| Error::db(e.to_string()))?; + Ok(()) + }) +} + +/// 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(); + wal.push("-wal"); + let wal_file = std::fs::metadata(&wal).map(|m| m.len()).unwrap_or(0); + (db_file, wal_file) +} diff --git a/src/db/model.rs b/src/db/model.rs new file mode 100644 index 0000000..599fc21 --- /dev/null +++ b/src/db/model.rs @@ -0,0 +1,286 @@ +//! 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. +#[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. + pub commit: String, +} + +/// A source entry with the digest *we* computed, regardless of what the +/// PKGBUILD declares (§5.3). +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct SourceDigest { + pub index: usize, + pub url: String, + /// `static` | `vcs` | `local` + pub kind: String, + /// sha256, or the resolved VCS commit for vcs sources. + pub digest: String, + pub size: u64, + /// True when the PKGBUILD declared `SKIP` (or nothing) for this source. + pub skip_declared: bool, +} + +/// A member of a world snapshot: one of *our* packages the build ran against. +#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)] +pub struct WorldMember { + pub pkgbase: String, + pub version: String, +} + +/// The identity tuple of a candidate (§3). Every element is part of the key. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct Identity { + pub aur_commit: String, + pub epoch: String, + pub pkgver: String, + pub pkgrel: String, + pub upstream_pins: Vec<UpstreamPin>, + pub source_digests: Vec<SourceDigest>, +} + +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. + pub fn hash(&self) -> String { + hash::canonical_json(self) + } +} + +/// Candidate/review states (§7.1). +pub mod candidate_state { + pub const PENDING: &str = "pending_review"; + pub const APPROVED: &str = "approved"; + pub const REJECTED: &str = "rejected"; + pub const SUPERSEDED: &str = "superseded"; + pub const BLOCKED: &str = "blocked"; +} + +pub mod candidate_kind { + pub const NEW_VERSION: &str = "new_version"; + pub const FIRST_INTRODUCTION: &str = "first_introduction"; +} + +pub mod release_state { + pub const PUBLISHED: &str = "published"; + pub const WITHDRAWN: &str = "withdrawn"; + pub const FAILED_UNBUILT: &str = "failed_unbuilt"; +} + +pub mod build_state { + pub const QUEUED: &str = "queued"; + pub const LEASED: &str = "leased"; + pub const RUNNING: &str = "running"; + pub const BLOCKED_MISSING_DEP: &str = "blocked_missing_dep"; + pub const SUCCEEDED: &str = "succeeded"; + pub const FAILED: &str = "failed"; + pub const CANCELLED: &str = "cancelled"; +} + +pub mod step_state { + pub const PENDING: &str = "pending"; + pub const RUNNING: &str = "running"; + pub const SUCCEEDED: &str = "succeeded"; + pub const FAILED: &str = "failed"; + pub const INTERRUPTED: &str = "interrupted"; + pub const SKIPPED: &str = "skipped"; +} + +pub mod notice_kind { + pub const PIN_DRIFT: &str = "pin_drift"; + pub const RECIPE_DRIFT: &str = "recipe_drift"; + pub const DIGEST_DRIFT: &str = "digest_drift"; + pub const INTEGRITY_ALERT: &str = "integrity_alert"; + pub const UNPINABLE_PKGVER: &str = "unpinable_pkgver"; + pub const ORPHANED: &str = "orphaned"; + pub const DELETED: &str = "deleted"; + pub const RENAMED: &str = "renamed"; + pub const DOWNGRADE: &str = "downgrade"; +} + +pub mod subscription_state { + pub const ACTIVE: &str = "active"; + pub const PAUSED: &str = "paused"; + pub const ORPHANED: &str = "orphaned"; + pub const REMOVED: &str = "removed"; +} + +/// The pipeline steps (§8.1). Order matters: a build resumes at the first step +/// in this list without a `succeeded` row. +pub const BUILD_STEPS: &[&str] = &[ + "materialize", + "plan", + "chroot", + "sources", + "pkgver", + "build", + "collect", + "verify", + "ingest", + "publish", +]; + +/// A `source=()` entry after parsing. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct SourceEntry { + pub index: usize, + /// The URL as written, minus the filename fragment. + 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+`. + pub vcs: Option<String>, + /// True for files shipped inside the AUR repo (no scheme). + pub local: bool, +} + +impl SourceEntry { + pub fn is_vcs(&self) -> bool { + self.vcs.is_some() + } +} + +/// A parsed recipe: what `.SRCINFO` / `PKGBUILD` tell us. +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct Recipe { + pub pkgbase: String, + pub pkgver: String, + pub pkgrel: String, + pub epoch: String, + pub pkgdesc: String, + pub url: String, + pub arch: Vec<String>, + pub license: Vec<String>, + pub groups: Vec<String>, + pub depends: Vec<String>, + pub makedepends: Vec<String>, + pub checkdepends: Vec<String>, + pub optdepends: Vec<String>, + pub provides: Vec<String>, + pub conflicts: Vec<String>, + pub source: Vec<String>, + pub sha256sums: Vec<String>, + pub b2sums: Vec<String>, + pub validpgpkeys: Vec<String>, + pub options: Vec<String>, + pub backup: Vec<String>, + 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, +} + +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) + } +} + +/// A source row as stored on a candidate/release. +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct ReleaseRow { + pub id: i64, + pub pkgbase_id: i64, + pub candidate_id: Option<i64>, + pub approval_id: Option<i64>, + pub aur_commit: String, + pub recipe_hash: String, + pub upstream_pins_json: String, + pub source_digests_json: String, + pub epoch: String, + pub pkgver: String, + pub pkgrel: String, + pub world_snapshot_id: Option<i64>, + pub state: String, + pub published_at: Option<String>, +} + +impl ReleaseRow { + pub fn version(&self) -> String { + crate::pkgver::full_version(&self.epoch, &self.pkgver, &self.pkgrel) + } + pub fn pins(&self) -> Vec<UpstreamPin> { + serde_json::from_str(&self.upstream_pins_json).unwrap_or_default() + } + pub fn digests(&self) -> Vec<SourceDigest> { + serde_json::from_str(&self.source_digests_json).unwrap_or_default() + } +} + +#[derive(Debug, Clone, Serialize)] +pub struct CandidateRow { + pub id: i64, + pub pkgbase_id: i64, + pub base_release_id: Option<i64>, + pub kind: String, + pub snapshot_id: i64, + pub epoch: String, + pub pkgver: String, + pub pkgrel: String, + pub upstream_pins_json: String, + pub source_digests_json: String, + pub identity_hash: String, + pub diff_digest: String, + pub revision: i64, + pub viewed_at: Option<String>, + pub risk_level: String, + pub risk_signals_json: String, + pub missing_deps_json: String, + pub state: String, + pub detected_at: String, + pub resolved_at: Option<String>, + pub pkgbase: String, +} + +impl CandidateRow { + pub fn version(&self) -> String { + crate::pkgver::full_version(&self.epoch, &self.pkgver, &self.pkgrel) + } + pub fn pins(&self) -> Vec<UpstreamPin> { + serde_json::from_str(&self.upstream_pins_json).unwrap_or_default() + } + pub fn digests(&self) -> Vec<SourceDigest> { + serde_json::from_str(&self.source_digests_json).unwrap_or_default() + } + pub fn risk_signals(&self) -> Vec<String> { + serde_json::from_str(&self.risk_signals_json).unwrap_or_default() + } + pub fn missing_deps(&self) -> Vec<String> { + serde_json::from_str(&self.missing_deps_json).unwrap_or_default() + } +} + +/// Parse a JSON column with a fallback, so one bad row never takes down a page. +pub fn json_or<T: serde::de::DeserializeOwned>(s: &str, fallback: T) -> T { + serde_json::from_str(s).unwrap_or(fallback) +} diff --git a/src/db/queries.rs b/src/db/queries.rs new file mode 100644 index 0000000..b1f7e4d --- /dev/null +++ b/src/db/queries.rs @@ -0,0 +1,808 @@ +//! Typed query helpers. Everything that mutates goes through the writer actor; +//! everything that reads takes a `&Connection` from the reader pool. + +use rusqlite::{params, OptionalExtension, Row}; + +use crate::db::*; +use crate::error::{Error, Result}; +use crate::time; + +// ---------------------------------------------------------------- settings -- + +pub fn setting(db: &Db, key: &str) -> Result<Option<String>> { + db.read(|c| { + c.query_row("SELECT value FROM settings WHERE key = ?1", params![key], |r| r.get(0)) + .optional() + .map_err(Into::into) + }) +} + +pub fn setting_i64(db: &Db, key: &str, default: i64) -> i64 { + setting(db, key) + .ok() + .flatten() + .and_then(|v| v.parse().ok()) + .unwrap_or(default) +} + +pub fn set_setting(writer: &Writer, key: &str, value: &str) -> Result<()> { + let v = value.to_string(); + let k = key.to_string(); + writer.tx(move |tx| { + tx.execute( + "INSERT INTO settings (key, value) VALUES (?1, ?2) + ON CONFLICT(key) DO UPDATE SET value = excluded.value", + params![k, v], + )?; + Ok(()) + }) +} + +// ------------------------------------------------------------------- audit -- + +/// Append an audit row (I10). Every state transition funnels through here. +pub fn audit( + writer: &Writer, + actor_kind: &str, + actor: &str, + action: &str, + entity: &str, + entity_id: &str, + detail: serde_json::Value, +) -> Result<()> { + let at = time::now(); + let actor_kind = actor_kind.to_string(); + let actor = actor.to_string(); + let action = action.to_string(); + let entity = entity.to_string(); + let entity_id = entity_id.to_string(); + let detail = detail.to_string(); + writer.tx(move |tx| { + tx.execute( + "INSERT INTO audit (at, actor_kind, actor, action, entity, entity_id, detail_json) + VALUES (?1,?2,?3,?4,?5,?6,?7)", + params![at, actor_kind, actor, action, entity, entity_id, detail], + )?; + Ok(()) + }) +} + +pub fn audit_system(writer: &Writer, action: &str, entity: &str, entity_id: &str, detail: serde_json::Value) -> Result<()> { + audit(writer, "system", "", action, entity, entity_id, detail) +} + +// -------------------------------------------------------------------- repo -- + +/// Ensure the single repo row exists (decision 4: exactly one). +pub fn ensure_repo(writer: &Writer, name: &str, path: &str, arch: &str, key: &str) -> Result<i64> { + let (n, p, a, k) = (name.to_string(), path.to_string(), arch.to_string(), key.to_string()); + writer.tx(move |tx| { + tx.execute( + "INSERT INTO repo (name, path, arch, signing_key_id) VALUES (?1,?2,?3,?4) + ON CONFLICT(name) DO UPDATE SET path=excluded.path, arch=excluded.arch, + signing_key_id=excluded.signing_key_id", + params![n, p, a, k], + )?; + let id: i64 = tx.query_row("SELECT id FROM repo WHERE name = ?1", params![n], |r| r.get(0))?; + Ok(id) + }) +} + +pub fn repo_id(db: &Db) -> Result<i64> { + db.read(|c| { + c.query_row("SELECT id FROM repo ORDER BY id LIMIT 1", [], |r| r.get(0)) + .optional()? + .ok_or_else(|| Error::not_found("no repo row; run `aur-build init`")) + }) +} + +// ------------------------------------------------------------- subscriptions -- + +#[derive(Debug, Clone)] +pub struct Subscription { + pub id: i64, + pub pkgbase: String, + pub aur_url: String, + pub maintainer: Option<String>, + pub state: String, + pub next_check_at: Option<String>, + pub last_checked_at: Option<String>, + pub last_error: Option<String>, + pub poll_interval_secs: Option<i64>, +} + +fn row_to_sub(r: &Row<'_>) -> rusqlite::Result<Subscription> { + Ok(Subscription { + id: r.get(0)?, + pkgbase: r.get(1)?, + aur_url: r.get(2)?, + maintainer: r.get(3)?, + state: r.get(4)?, + next_check_at: r.get(5)?, + last_checked_at: r.get(6)?, + last_error: r.get(7)?, + poll_interval_secs: r.get(8)?, + }) +} + +const SUB_COLS: &str = "id, pkgbase, aur_url, maintainer, state, next_check_at, last_checked_at, \ + last_error, poll_interval_secs"; + +pub fn list_subscriptions(db: &Db) -> Result<Vec<Subscription>> { + db.read(|c| { + let mut stmt = c.prepare(&format!("SELECT {SUB_COLS} FROM subscription ORDER BY pkgbase"))?; + let rows = stmt.query_map([], row_to_sub)?; + let mut out = Vec::new(); + for r in rows { + out.push(r?); + } + Ok(out) + }) +} + +pub fn get_subscription(db: &Db, pkgbase: &str) -> Result<Option<Subscription>> { + db.read(|c| { + c.query_row( + &format!("SELECT {SUB_COLS} FROM subscription WHERE pkgbase = ?1"), + params![pkgbase], + row_to_sub, + ) + .optional() + .map_err(Into::into) + }) +} + +/// Subscribe: creates the pkgbase row and an active subscription. Idempotent. +pub fn subscribe(writer: &Writer, repo_id: i64, pkgbase: &str, aur_url: &str) -> Result<i64> { + let (p, u) = (pkgbase.to_string(), aur_url.to_string()); + let at = time::now(); + writer.tx(move |tx| { + tx.execute( + "INSERT INTO pkgbase (name, aur_url, created_at) VALUES (?1,?2,?3) + ON CONFLICT(name) DO UPDATE SET aur_url = excluded.aur_url", + params![p, u, at], + )?; + tx.execute( + "INSERT INTO subscription (repo_id, pkgbase, aur_url, state, next_check_at, created_at) + VALUES (?1,?2,?3,'active',?4,?5) + ON CONFLICT(repo_id, pkgbase) DO UPDATE SET state='active', aur_url=excluded.aur_url", + params![repo_id, p, u, at.clone(), at], + )?; + Ok(1) + }) +} + +pub fn set_subscription_state(writer: &Writer, pkgbase: &str, state: &str) -> Result<()> { + let (p, s) = (pkgbase.to_string(), state.to_string()); + writer.tx(move |tx| { + tx.execute( + "UPDATE subscription SET state=?1 WHERE pkgbase=?2", + params![s, p], + )?; + Ok(()) + }) +} + +pub fn note_check(writer: &Writer, pkgbase: &str, next_check_at: &str, err: Option<&str>) -> Result<()> { + let (p, n) = (pkgbase.to_string(), next_check_at.to_string()); + let e = err.map(|s| s.to_string()); + let at = time::now(); + writer.tx(move |tx| { + tx.execute( + "UPDATE subscription SET last_checked_at=?1, next_check_at=?2, last_error=?3 + WHERE pkgbase=?4", + params![at, n, e, p], + )?; + Ok(()) + }) +} + +/// Subscriptions whose next check is due. +pub fn due_subscriptions(db: &Db, now: &str) -> Result<Vec<Subscription>> { + db.read(|c| { + let mut stmt = c.prepare(&format!( + "SELECT {SUB_COLS} FROM subscription + WHERE state IN ('active','orphaned') AND (next_check_at IS NULL OR next_check_at <= ?1) + ORDER BY next_check_at IS NULL DESC, next_check_at LIMIT 200" + ))?; + let rows = stmt.query_map(params![now], row_to_sub)?; + let mut out = Vec::new(); + for r in rows { + out.push(r?); + } + Ok(out) + }) +} + +// ---------------------------------------------------------------- pkgbase -- + +#[derive(Debug, Clone)] +pub struct Pkgbase { + pub id: i64, + pub name: String, + pub aur_url: String, + pub mirror_path: Option<String>, + pub aur_head: Option<String>, + pub current_accepted_release_id: Option<i64>, + pub state: String, + pub unpinable: bool, +} + +fn row_to_pkgbase(r: &Row<'_>) -> rusqlite::Result<Pkgbase> { + Ok(Pkgbase { + id: r.get(0)?, + name: r.get(1)?, + aur_url: r.get(2)?, + mirror_path: r.get(3)?, + aur_head: r.get(4)?, + current_accepted_release_id: r.get(5)?, + state: r.get(6)?, + unpinable: r.get::<_, i64>(7)? != 0, + }) +} + +const PKGBASE_COLS: &str = "id, name, aur_url, mirror_path, aur_head, \ + current_accepted_release_id, state, unpinable"; + +pub fn get_pkgbase(db: &Db, name: &str) -> Result<Option<Pkgbase>> { + db.read(|c| { + c.query_row( + &format!("SELECT {PKGBASE_COLS} FROM pkgbase WHERE name = ?1"), + params![name], + row_to_pkgbase, + ) + .optional() + .map_err(Into::into) + }) +} + +pub fn get_pkgbase_by_id(db: &Db, id: i64) -> Result<Option<Pkgbase>> { + db.read(|c| { + c.query_row( + &format!("SELECT {PKGBASE_COLS} FROM pkgbase WHERE id = ?1"), + params![id], + row_to_pkgbase, + ) + .optional() + .map_err(Into::into) + }) +} + +pub fn list_pkgbases(db: &Db) -> Result<Vec<Pkgbase>> { + db.read(|c| { + let mut stmt = c.prepare(&format!("SELECT {PKGBASE_COLS} FROM pkgbase ORDER BY name"))?; + let rows = stmt.query_map([], row_to_pkgbase)?; + let mut out = Vec::new(); + for r in rows { + out.push(r?); + } + Ok(out) + }) +} + +pub fn set_aur_head(writer: &Writer, pkgbase_id: i64, head: &str, mirror: &str) -> Result<()> { + let (h, m) = (head.to_string(), mirror.to_string()); + writer.tx(move |tx| { + tx.execute( + "UPDATE pkgbase SET aur_head=?1, mirror_path=?2 WHERE id=?3", + params![h, m, pkgbase_id], + )?; + Ok(()) + }) +} + +pub fn set_unpinable(writer: &Writer, pkgbase_id: i64, unpinable: bool) -> Result<()> { + writer.tx(move |tx| { + tx.execute( + "UPDATE pkgbase SET unpinable=?1 WHERE id=?2", + params![unpinable as i64, pkgbase_id], + )?; + Ok(()) + }) +} + +/// Compare-and-swap the accepted-release pointer (§16: concurrent approvals). +/// Returns Ok(true) when the swap happened. +pub fn cas_accepted_release( + writer: &Writer, + pkgbase_id: i64, + expected: Option<i64>, + new_id: i64, +) -> Result<bool> { + writer.tx(move |tx| { + let n = tx.execute( + "UPDATE pkgbase SET current_accepted_release_id=?1 + WHERE id=?2 AND current_accepted_release_id IS ?3", + params![new_id, pkgbase_id, expected], + )?; + Ok(n == 1) + }) +} + +// ---------------------------------------------------------------- snapshot -- + +/// Insert-or-get a snapshot for (pkgbase, aur_commit). +#[allow(clippy::too_many_arguments)] +pub fn put_snapshot( + writer: &Writer, + pkgbase_id: i64, + aur_commit: &str, + recipe_hash: &str, + srcinfo_json: &str, + files_json: &str, +) -> Result<i64> { + let (c, rh, si, fj) = ( + aur_commit.to_string(), + recipe_hash.to_string(), + srcinfo_json.to_string(), + files_json.to_string(), + ); + let at = time::now(); + writer.tx(move |tx| { + tx.execute( + "INSERT INTO snapshot (pkgbase_id, aur_commit, recipe_hash, srcinfo_json, files_json, fetched_at) + VALUES (?1,?2,?3,?4,?5,?6) + ON CONFLICT(pkgbase_id, aur_commit) DO NOTHING", + params![pkgbase_id, c, rh, si, fj, at], + )?; + tx.query_row( + "SELECT id FROM snapshot WHERE pkgbase_id=?1 AND aur_commit=?2", + params![pkgbase_id, c], + |r| r.get(0), + ) + .map_err(Into::into) + }) +} + +#[derive(Debug, Clone)] +pub struct SnapshotRow { + pub id: i64, + pub aur_commit: String, + pub recipe_hash: String, + pub srcinfo_json: String, + pub files_json: String, +} + +pub fn snapshot_by_commit(db: &Db, pkgbase_id: i64, commit: &str) -> Result<Option<SnapshotRow>> { + db.read(|c| { + c.query_row( + "SELECT id, aur_commit, recipe_hash, srcinfo_json, files_json FROM snapshot + WHERE pkgbase_id=?1 AND aur_commit=?2", + params![pkgbase_id, commit], + |r| { + Ok(SnapshotRow { + id: r.get(0)?, + aur_commit: r.get(1)?, + recipe_hash: r.get(2)?, + srcinfo_json: r.get(3)?, + files_json: r.get(4)?, + }) + }, + ) + .optional() + .map_err(Into::into) + }) +} + +pub fn snapshot_by_id(db: &Db, id: i64) -> Result<Option<SnapshotRow>> { + db.read(|c| { + c.query_row( + "SELECT id, aur_commit, recipe_hash, srcinfo_json, files_json FROM snapshot WHERE id=?1", + params![id], + |r| { + Ok(SnapshotRow { + id: r.get(0)?, + aur_commit: r.get(1)?, + recipe_hash: r.get(2)?, + srcinfo_json: r.get(3)?, + files_json: r.get(4)?, + }) + }, + ) + .optional() + .map_err(Into::into) + }) +} + +// ---------------------------------------------------------------- release -- + +fn row_to_release(r: &Row<'_>) -> rusqlite::Result<ReleaseRow> { + Ok(ReleaseRow { + id: r.get(0)?, + pkgbase_id: r.get(1)?, + candidate_id: r.get(2)?, + approval_id: r.get(3)?, + aur_commit: r.get(4)?, + recipe_hash: r.get(5)?, + upstream_pins_json: r.get(6)?, + source_digests_json: r.get(7)?, + epoch: r.get(8)?, + pkgver: r.get(9)?, + pkgrel: r.get(10)?, + world_snapshot_id: r.get(11)?, + state: r.get(12)?, + published_at: r.get(13)?, + }) +} + +const RELEASE_COLS: &str = "id, pkgbase_id, candidate_id, approval_id, aur_commit, recipe_hash, \ + upstream_pins_json, source_digests_json, epoch, pkgver, pkgrel, world_snapshot_id, state, published_at"; + +const RELEASE_COLS_R: &str = "r.id, r.pkgbase_id, r.candidate_id, r.approval_id, r.aur_commit, \ + 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"; + +pub fn release_by_id(db: &Db, id: i64) -> Result<Option<ReleaseRow>> { + db.read(|c| { + c.query_row( + &format!("SELECT {RELEASE_COLS} FROM release WHERE id = ?1"), + params![id], + row_to_release, + ) + .optional() + .map_err(Into::into) + }) +} + +/// The accepted release of a pkgbase, by name. `None` for a pkgbase that has +/// never been accepted — the case that makes `first_introduction` special (§7.1b). +pub fn accepted_release(db: &Db, pkgbase: &str) -> Result<Option<ReleaseRow>> { + db.read(|c| { + c.query_row( + &format!( + "SELECT {RELEASE_COLS_R} FROM release r + JOIN pkgbase p ON p.current_accepted_release_id = r.id + WHERE p.name = ?1 AND r.state = 'published'"), + params![pkgbase], + row_to_release, + ) + .optional() + .map_err(Into::into) + }) +} + +pub fn releases_for_pkgbase(db: &Db, pkgbase_id: i64, limit: i64) -> Result<Vec<ReleaseRow>> { + db.read(|c| { + let sql = format!( + "SELECT {RELEASE_COLS} FROM release WHERE pkgbase_id=?1 ORDER BY id DESC LIMIT ?2" + ); + let mut stmt = c.prepare(&sql)?; + let rows = stmt.query_map(params![pkgbase_id, limit], row_to_release)?; + let mut out = Vec::new(); + for r in rows { + out.push(r?); + } + Ok(out) + }) +} + +pub fn all_published_releases(db: &Db) -> Result<Vec<ReleaseRow>> { + db.read(|c| { + let sql = format!( + "SELECT {RELEASE_COLS} FROM release WHERE state='published' ORDER BY pkgbase_id, id DESC" + ); + let mut stmt = c.prepare(&sql)?; + let rows = stmt.query_map([], row_to_release)?; + let mut out = Vec::new(); + for r in rows { + out.push(r?); + } + Ok(out) + }) +} + +// ---------------------------------------------------------------- package -- + +#[derive(Debug, Clone)] +pub struct PackageRow { + pub id: i64, + pub release_id: i64, + pub name: String, + pub arch: String, + pub version: String, + pub artifact_id: Option<i64>, + pub pkgbase: String, +} + +pub fn index_packages(db: &Db) -> Result<Vec<PackageRow>> { + db.read(|c| { + let mut stmt = c.prepare( + "SELECT p.id, p.release_id, p.name, p.arch, p.version, p.artifact_id, b.name + FROM package p + JOIN release r ON r.id = p.release_id + JOIN pkgbase b ON b.id = r.pkgbase_id + WHERE p.state = 'in_index' + ORDER BY p.name", + )?; + let rows = stmt.query_map([], |r| { + Ok(PackageRow { + id: r.get(0)?, + release_id: r.get(1)?, + name: r.get(2)?, + arch: r.get(3)?, + version: r.get(4)?, + artifact_id: r.get(5)?, + pkgbase: r.get(6)?, + }) + })?; + let mut out = Vec::new(); + for r in rows { + out.push(r?); + } + Ok(out) + }) +} + +/// Version of the package with this name currently in our index, if any. +pub fn index_version(db: &Db, name: &str) -> Result<Option<String>> { + db.read(|c| { + c.query_row( + "SELECT p.version FROM package p WHERE p.name=?1 AND p.state='in_index' + ORDER BY p.id DESC LIMIT 1", + params![name], + |r| r.get(0), + ) + .optional() + .map_err(Into::into) + }) +} + +/// Is `name` one of the packages we publish? Used to filter world snapshots +/// down to our own packages (§10.1). +pub fn is_ours(db: &Db, name: &str) -> Result<bool> { + db.read(|c| { + c.query_row( + "SELECT 1 FROM package WHERE name=?1 AND state='in_index' LIMIT 1", + params![name], + |r| r.get::<_, i64>(0), + ) + .optional() + .map(|o| o.is_some()) + .map_err(Into::into) + }) +} + +/// All package names we publish (in_index), as a set. +pub fn our_package_names(db: &Db) -> Result<std::collections::BTreeSet<String>> { + db.read(|c| { + let mut stmt = c.prepare("SELECT DISTINCT name FROM package WHERE state='in_index'")?; + let rows = stmt.query_map([], |r| r.get::<_, String>(0))?; + let mut out = std::collections::BTreeSet::new(); + for r in rows { + out.insert(r?); + } + Ok(out) + }) +} + +// ----------------------------------------------------------------- notice -- + +pub fn put_notice( + writer: &Writer, + pkgbase_id: i64, + kind: &str, + severity: &str, + detail: serde_json::Value, +) -> Result<i64> { + let (k, s, d) = (kind.to_string(), severity.to_string(), detail.to_string()); + let at = time::now(); + writer.tx(move |tx| { + tx.execute( + "INSERT INTO notice (pkgbase_id, kind, severity, detail_json, created_at) + VALUES (?1,?2,?3,?4,?5)", + params![pkgbase_id, k, s, d, at], + )?; + Ok(tx.last_insert_rowid()) + }) +} + +/// Suppress a notice if an identical unacknowledged one already exists, so a +/// watcher polling daily does not spam the same alert. +pub fn put_notice_once( + writer: &Writer, + pkgbase_id: i64, + kind: &str, + severity: &str, + detail: serde_json::Value, +) -> Result<Option<i64>> { + let (k, s, d) = (kind.to_string(), severity.to_string(), detail.to_string()); + let at = time::now(); + writer.tx(move |tx| { + let exists: Option<i64> = tx + .query_row( + "SELECT id FROM notice WHERE pkgbase_id=?1 AND kind=?2 AND detail_json=?3 + AND acknowledged_at IS NULL ORDER BY id DESC LIMIT 1", + params![pkgbase_id, k, d], + |r| r.get(0), + ) + .optional()?; + if exists.is_some() { + return Ok(None); + } + tx.execute( + "INSERT INTO notice (pkgbase_id, kind, severity, detail_json, created_at) + VALUES (?1,?2,?3,?4,?5)", + params![pkgbase_id, k, s, d, at], + )?; + Ok(Some(tx.last_insert_rowid())) + }) +} + +#[derive(Debug, Clone)] +pub struct NoticeRow { + pub id: i64, + pub pkgbase: String, + pub kind: String, + pub severity: String, + pub detail_json: String, + pub created_at: String, + pub acknowledged_at: Option<String>, +} + +pub fn list_notices(db: &Db, include_acknowledged: bool) -> Result<Vec<NoticeRow>> { + db.read(|c| { + let sql = format!( + "SELECT n.id, b.name, n.kind, n.severity, n.detail_json, n.created_at, n.acknowledged_at + FROM notice n JOIN pkgbase b ON b.id = n.pkgbase_id + {} ORDER BY (n.severity='high') DESC, n.created_at DESC LIMIT 500", + if include_acknowledged { + "" + } else { + "WHERE n.acknowledged_at IS NULL" + } + ); + let mut stmt = c.prepare(&sql)?; + let rows = stmt.query_map([], |r| { + Ok(NoticeRow { + id: r.get(0)?, + pkgbase: r.get(1)?, + kind: r.get(2)?, + severity: r.get(3)?, + detail_json: r.get(4)?, + created_at: r.get(5)?, + acknowledged_at: r.get(6)?, + }) + })?; + let mut out = Vec::new(); + for r in rows { + out.push(r?); + } + Ok(out) + }) +} + +pub fn acknowledge_notice(writer: &Writer, id: i64) -> Result<()> { + let at = time::now(); + writer.tx(move |tx| { + tx.execute( + "UPDATE notice SET acknowledged_at=?1 WHERE id=?2", + params![at, id], + )?; + Ok(()) + }) +} + +// --------------------------------------------------------- world snapshots -- + +pub fn put_world_snapshot(writer: &Writer, members: &[WorldMember]) -> Result<i64> { + let mut sorted = members.to_vec(); + sorted.sort(); + sorted.dedup(); + let hash = crate::hash::canonical_json(&sorted); + let json = serde_json::to_string(&sorted)?; + let at = time::now(); + writer.tx(move |tx| { + tx.execute( + "INSERT INTO world_snapshot (hash, members_json, created_at) VALUES (?1,?2,?3) + ON CONFLICT(hash) DO NOTHING", + params![hash, json, at], + )?; + tx.query_row("SELECT id FROM world_snapshot WHERE hash=?1", params![hash], |r| r.get(0)) + .map_err(Into::into) + }) +} + +pub fn world_members(db: &Db, id: i64) -> Result<Vec<WorldMember>> { + db.read(|c| { + let s: String = c.query_row( + "SELECT members_json FROM world_snapshot WHERE id=?1", + params![id], + |r| r.get(0), + )?; + Ok(json_or(&s, Vec::new())) + }) +} + +// ------------------------------------------------------------------ audit -- + +#[derive(Debug, Clone)] +pub struct AuditRow { + pub id: i64, + pub at: String, + pub actor_kind: String, + pub actor: String, + pub action: String, + pub entity: String, + pub entity_id: String, + pub detail_json: String, +} + +pub fn list_audit(db: &Db, limit: i64) -> Result<Vec<AuditRow>> { + db.read(|c| { + let mut stmt = c.prepare( + "SELECT id, at, actor_kind, actor, action, entity, entity_id, detail_json + FROM audit ORDER BY id DESC LIMIT ?1", + )?; + let rows = stmt.query_map(params![limit], |r| { + Ok(AuditRow { + id: r.get(0)?, + at: r.get(1)?, + actor_kind: r.get(2)?, + actor: r.get(3)?, + action: r.get(4)?, + entity: r.get(5)?, + entity_id: r.get(6)?, + detail_json: r.get(7)?, + }) + })?; + let mut out = Vec::new(); + for r in rows { + out.push(r?); + } + Ok(out) + }) +} + +// ------------------------------------------------------- invariant helpers -- + +/// I1: every artifact in a served repo index traces to an approval row. +/// Returns offending package names; empty means the invariant holds. +pub fn unapproved_index_entries(db: &Db) -> Result<Vec<String>> { + db.read(|c| { + let mut stmt = c.prepare( + "SELECT p.name FROM package p + JOIN release r ON r.id = p.release_id + WHERE p.state='in_index' AND (r.approval_id IS NULL OR NOT EXISTS + (SELECT 1 FROM approval a WHERE a.id = r.approval_id AND a.decision='approved'))", + )?; + let rows = stmt.query_map([], |r| r.get::<_, String>(0))?; + let mut out = Vec::new(); + for r in rows { + out.push(r?); + } + Ok(out) + }) +} + +/// I8: the set of packages in the index is exactly the set of +/// `current_accepted_release` pointers for active subscriptions. +pub fn index_pkgbase_drift(db: &Db) -> Result<(Vec<String>, Vec<String>)> { + db.read(|c| { + let mut orphans = Vec::new(); + let mut stmt = c.prepare( + "SELECT DISTINCT b.name FROM package p + JOIN release r ON r.id = p.release_id + JOIN pkgbase b ON b.id = r.pkgbase_id + WHERE p.state='in_index' + AND r.id NOT IN (SELECT current_accepted_release_id FROM pkgbase + WHERE current_accepted_release_id IS NOT NULL)", + )?; + let rows = stmt.query_map([], |r| r.get::<_, String>(0))?; + for r in rows { + orphans.push(r?); + } + let mut missing = Vec::new(); + let mut stmt = c.prepare( + "SELECT b.name FROM pkgbase b + JOIN subscription s ON s.pkgbase = b.name AND s.state IN ('active','orphaned') + WHERE b.current_accepted_release_id IS NOT NULL + AND NOT EXISTS (SELECT 1 FROM package p WHERE p.release_id = b.current_accepted_release_id + AND p.state='in_index')", + )?; + let rows = stmt.query_map([], |r| r.get::<_, String>(0))?; + for r in rows { + missing.push(r?); + } + Ok((orphans, missing)) + }) +} diff --git a/src/error.rs b/src/error.rs new file mode 100644 index 0000000..a60843c --- /dev/null +++ b/src/error.rs @@ -0,0 +1,70 @@ +//! Error type shared across the application. + +use std::fmt; + +#[derive(Debug, thiserror::Error)] +pub enum Error { + #[error("io: {0}")] + Io(#[from] std::io::Error), + #[error("json: {0}")] + Json(#[from] serde_json::Error), + #[error("sqlite: {0}")] + Db(String), + #[error("sqlite: {0}")] + Sqlite(#[from] rusqlite::Error), + #[error("git: {0}")] + Git(String), + #[error("http fetch: {0}")] + Http(String), + #[error("child process {cmd}: {detail}")] + Subprocess { cmd: String, detail: String }, + /// A fail-closed assertion. Everything that guards "we build what we reviewed" + /// raises this: recipe_hash mismatch, pkgver mismatch, missing approval. + #[error("assertion failed: {0}")] + FailClosed(String), + #[error("not found: {0}")] + NotFound(String), + #[error("conflict: {0}")] + Conflict(String), + #[error("invalid: {0}")] + Invalid(String), + #[error("blocked: {0}")] + Blocked(String), + #[error("{0}")] + Other(String), +} + +impl Error { + pub fn db(s: impl fmt::Display) -> Self { + Error::Db(s.to_string()) + } + pub fn git(s: impl fmt::Display) -> Self { + Error::Git(s.to_string()) + } + pub fn fail_closed(s: impl fmt::Display) -> Self { + Error::FailClosed(s.to_string()) + } + pub fn not_found(s: impl fmt::Display) -> Self { + Error::NotFound(s.to_string()) + } + pub fn conflict(s: impl fmt::Display) -> Self { + Error::Conflict(s.to_string()) + } + pub fn invalid(s: impl fmt::Display) -> Self { + Error::Invalid(s.to_string()) + } + pub fn blocked(s: impl fmt::Display) -> Self { + Error::Blocked(s.to_string()) + } + pub fn other(s: impl fmt::Display) -> Self { + Error::Other(s.to_string()) + } + + /// True when a retry could plausibly help (network, mirror 5xx). Deterministic + /// build failures must not auto-retry (§8.4). + pub fn is_transient(&self) -> bool { + matches!(self, Error::Http(_) | Error::Io(_)) + } +} + +pub type Result<T> = std::result::Result<T, Error>; diff --git a/src/hash.rs b/src/hash.rs new file mode 100644 index 0000000..5243520 --- /dev/null +++ b/src/hash.rs @@ -0,0 +1,78 @@ +//! 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}; + +pub const EMPTY: &str = "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"; + +pub fn hex(bytes: &[u8]) -> String { + let mut h = Sha256::new(); + h.update(bytes); + hex::encode(h.finalize()) +} + +pub fn hex_str(s: &str) -> String { + hex(s.as_bytes()) +} + +/// First `n` hex chars — enough for display, not for identity. +pub fn short(bytes: &[u8], n: usize) -> String { + let h = hex(bytes); + 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"). +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]; + let mut total = 0u64; + loop { + let n = r.read(&mut buf)?; + if n == 0 { + break; + } + h.update(&buf[..n]); + if let Some(s) = sink.as_mut() { + s.write_all(&buf[..n])?; + } + total += n as u64; + } + Ok((hex::encode(h.finalize()), total)) +} + +pub fn digest_file(path: &std::path::Path) -> io::Result<(String, u64)> { + let f = std::fs::File::open(path)?; + let mut br = io::BufReader::new(f); + 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 +/// and is a classic silent-change vector. +pub fn recipe_hash(entries: &[(String, String)]) -> String { + let mut sorted: Vec<&(String, String)> = entries.iter().collect(); + sorted.sort_unstable_by(|a, b| a.0.cmp(&b.0)); + let mut h = Sha256::new(); + for (path, blob) in &sorted { + h.update(path.as_bytes()); + h.update([0u8]); + h.update(blob.as_bytes()); + h.update([0u8]); + } + hex::encode(h.finalize()) +} + +/// Canonical JSON used for identity digests. Key order in serde_json maps is +/// not stable across object construction, so we serialize through a +/// `BTreeMap`-preserving path: callers pass already-canonical values (arrays of +/// objects with a fixed field order) and we hash the compact rendering. +pub fn canonical_json<T: serde::Serialize>(v: &T) -> String { + serde_json::to_string(v).unwrap_or_else(|_| "{}".into()) +} @@ -1 +1,15 @@ //! 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; +pub mod hash; +pub mod pkgver; +pub mod time; + +pub use error::{Error, Result}; diff --git a/src/pkgver/mod.rs b/src/pkgver/mod.rs new file mode 100644 index 0000000..a940dc0 --- /dev/null +++ b/src/pkgver/mod.rs @@ -0,0 +1,273 @@ +//! 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; + +/// `epoch:pkgver-pkgrel` as pacman displays it, with the epoch omitted when 0. +pub fn full_version(epoch: &str, pkgver: &str, pkgrel: &str) -> String { + let e = epoch.trim(); + if e.is_empty() || e == "0" { + format!("{pkgver}-{pkgrel}") + } else { + format!("{e}:{pkgver}-{pkgrel}") + } +} + +/// Parse a full `epoch:pkgver-pkgrel` string back into its parts. +pub fn split_full_version(v: &str) -> (String, String, String) { + let (epoch, rest) = match v.split_once(':') { + Some((e, r)) => (e.to_string(), r.to_string()), + None => ("0".to_string(), v.to_string()), + }; + match rest.rsplit_once('-') { + Some((pv, pr)) => (epoch, pv.to_string(), pr.to_string()), + None => (epoch, rest, "1".to_string()), + } +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Version { + pub epoch: String, + pub pkgver: String, + pub pkgrel: String, +} + +impl fmt::Display for Version { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "{}", full_version(&self.epoch, &self.pkgver, &self.pkgrel)) + } +} + +impl Version { + pub fn parse(v: &str) -> Self { + let (epoch, pkgver, pkgrel) = split_full_version(v); + Self { epoch, pkgver, pkgrel } + } + pub fn cmp_full(&self, other: &Version) -> Ordering { + compare(self.epoch_as_i64(), &self.pkgver, &self.pkgrel, other.epoch_as_i64(), &other.pkgver, &other.pkgrel) + } + pub fn epoch_as_i64(&self) -> i64 { + self.epoch.trim().parse().unwrap_or(0) + } + pub fn display(&self) -> String { + self.to_string() + } +} + +/// Compare `epoch:pkgver-pkgrel` triples the way pacman does. +pub fn compare( + epoch_a: i64, + pkgver_a: &str, + pkgrel_a: &str, + epoch_b: i64, + pkgver_b: &str, + pkgrel_b: &str, +) -> Ordering { + match epoch_a.cmp(&epoch_b) { + Ordering::Equal => {} + o => return o, + } + match vercmp_string(pkgver_a, pkgver_b) { + Ordering::Equal => vercmp_string(pkgrel_a, pkgrel_b), + o => o, + } +} + +/// Compare two full version strings (`1.2.3-1`, `1:2-3`). +pub fn vercmp(a: &str, b: &str) -> Ordering { + let va = Version::parse(a); + let vb = Version::parse(b); + va.cmp_full(&vb) +} + +#[derive(Debug, PartialEq, Eq)] +enum Chunk<'a> { + Num(u128), + Alpha(&'a str), +} + +/// Split into maximal digit / alpha runs, ignoring everything else. +fn chunks(s: &str) -> Vec<Chunk<'_>> { + let b = s.as_bytes(); + let mut out = Vec::new(); + let mut i = 0; + while i < b.len() { + let c = b[i] as char; + if c.is_ascii_digit() { + let start = i; + while i < b.len() && (b[i] as char).is_ascii_digit() { + i += 1; + } + // Leading zeros are not significant. + let digits = s[start..i].trim_start_matches('0'); + out.push(Chunk::Num(digits.parse::<u128>().unwrap_or(0))); + } else if c.is_ascii_alphabetic() { + let start = i; + while i < b.len() && (b[i] as char).is_ascii_alphabetic() { + i += 1; + } + out.push(Chunk::Alpha(&s[start..i])); + } else { + i += 1; + } + } + out +} + +/// ALPM's `vercmp_string`: chunk-wise comparison where digits precede letters. +pub fn vercmp_string(a: &str, b: &str) -> Ordering { + let ca = chunks(a); + let cb = chunks(b); + let mut i = 0; + loop { + match (ca.get(i), cb.get(i)) { + (None, None) => return Ordering::Equal, + (None, Some(Chunk::Num(_))) => return Ordering::Less, + (None, Some(Chunk::Alpha(_))) => return Ordering::Greater, + (Some(Chunk::Num(_)), None) => return Ordering::Greater, + (Some(Chunk::Alpha(_)), None) => return Ordering::Less, + (Some(x), Some(y)) => { + let o = match (x, y) { + (Chunk::Num(x), Chunk::Num(y)) => x.cmp(y), + (Chunk::Alpha(x), Chunk::Alpha(y)) => x.cmp(y), + // A numeric chunk is always older than an alphabetic one. + (Chunk::Num(_), Chunk::Alpha(_)) => Ordering::Less, + (Chunk::Alpha(_), Chunk::Num(_)) => Ordering::Greater, + }; + if o != Ordering::Equal { + return o; + } + i += 1; + } + } + } +} + +/// True if `new` is a downgrade relative to `current` (§16: maintainer reverted). +pub fn is_downgrade(current: &str, new: &str) -> bool { + vercmp(current, new) == Ordering::Greater +} + +/// True if `new` is exactly equal to `current` in the pacman sense. +pub fn same_version(current: &str, new: &str) -> bool { + vercmp(current, new) == Ordering::Equal +} + +// ------------------------------------------------------------- dep strings -- + +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum DepOp { + /// `foo` + Any, + /// `foo=1.2` + Eq, + /// `foo>=1.2` + Ge, + /// `foo<=1.2` + Le, + /// `foo>1.2` + Gt, + /// `foo<1.2` + Lt, +} + +impl fmt::Display for DepOp { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str(match self { + DepOp::Any => "", + DepOp::Eq => "=", + DepOp::Ge => ">=", + DepOp::Le => "<=", + DepOp::Gt => ">", + DepOp::Lt => "<", + }) + } +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Dep { + pub name: String, + pub op: DepOp, + pub version: Option<String>, +} + +impl Dep { + /// Parse one dependency string, e.g. `python>=3.11`, `gcc`, `foo=1.2-3`. + /// + /// Returns `None` for an empty or malformed string rather than failing the + /// whole recipe: a weird `optdepends` line must not break detection. + pub fn parse(s: &str) -> Option<Dep> { + let s = s.trim(); + if s.is_empty() { + return None; + } + // optdepends carry a `: description` suffix. + let s = match s.split_once(':') { + Some((head, _desc)) if !head.contains(['>', '<', '=']) => head, + _ => s, + }; + for (tok, op) in [ + (">=", DepOp::Ge), + ("<=", DepOp::Le), + ("=", DepOp::Eq), + (">", DepOp::Gt), + ("<", DepOp::Lt), + ] { + if let Some((name, ver)) = s.split_once(tok) { + let name = name.trim(); + if name.is_empty() { + return None; + } + return Some(Dep { + name: name.to_string(), + op, + version: Some(ver.trim().to_string()), + }); + } + } + Some(Dep { name: s.trim().to_string(), op: DepOp::Any, version: None }) + } + + /// The bare package name, which is what we resolve against our index. + pub fn name(&self) -> &str { + &self.name + } + + /// Does a candidate version satisfy this constraint? + pub fn satisfied_by(&self, version: &str) -> bool { + match self.op { + DepOp::Any => true, + DepOp::Eq => vercmp(version, self.version.as_deref().unwrap_or("0")) == Ordering::Equal, + DepOp::Ge => vercmp(version, self.version.as_deref().unwrap_or("0")) != Ordering::Less, + DepOp::Le => vercmp(version, self.version.as_deref().unwrap_or("0")) != Ordering::Greater, + DepOp::Gt => vercmp(version, self.version.as_deref().unwrap_or("0")) == Ordering::Greater, + DepOp::Lt => vercmp(version, self.version.as_deref().unwrap_or("0")) == Ordering::Less, + } + } +} + +impl fmt::Display for Dep { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match &self.version { + Some(v) => write!(f, "{}{}{}", self.name, self.op, v), + None => write!(f, "{}", self.name), + } + } +} + +/// Parse a whole `depends=()` style list, dropping unparseable entries. +pub fn parse_deps(list: &[String]) -> Vec<Dep> { + list.iter().filter_map(|s| Dep::parse(s)).collect() +} + +/// Strip a `name=version` constraint down to the name, for index resolution. +pub fn dep_names(list: &[String]) -> Vec<String> { + parse_deps(list).into_iter().map(|d| d.name).collect() +} diff --git a/src/time.rs b/src/time.rs new file mode 100644 index 0000000..69fbc3c --- /dev/null +++ b/src/time.rs @@ -0,0 +1,69 @@ +//! 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. + if let Some(pinned) = pinned() { + return pinned; + } + fmt(Utc::now()) +} + +fn fmt(t: DateTime<Utc>) -> String { + t.to_rfc3339_opts(SecondsFormat::Secs, true) +} + +fn pinned() -> Option<String> { + CLOCK.with(|c| c.borrow().clone()) +} + +thread_local! { + static CLOCK: std::cell::RefCell<Option<String>> = const { std::cell::RefCell::new(None) }; +} + +/// Pin the clock for the current thread (tests only). Returns the previous value. +pub fn pin(ts: &str) -> Option<String> { + CLOCK.with(|c| { + let mut slot = c.borrow_mut(); + (*slot).replace(ts.to_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() + .map(|d| d.with_timezone(&Utc)) + .or_else(|| { + chrono::NaiveDateTime::parse_from_str(ts, "%Y-%m-%d %H:%M:%S") + .ok() + .map(|n| Utc.from_utc_datetime(&n)) + }) +} + +/// 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. +pub fn secs_ago(secs: i64) -> String { + fmt(Utc::now() - chrono::Duration::seconds(secs)) +} + +/// A timestamp `secs` seconds in the future, canonical format. +pub fn secs_ahead(secs: i64) -> String { + fmt(Utc::now() + chrono::Duration::seconds(secs)) +} diff --git a/tests/common/mod.rs b/tests/common/mod.rs new file mode 100644 index 0000000..4cf78ec --- /dev/null +++ b/tests/common/mod.rs @@ -0,0 +1,177 @@ +//! Shared test scaffolding: an isolated server root in a tempdir with a migrated +//! database and a running writer actor. + +#![allow(dead_code)] + +use std::path::{Path, PathBuf}; + +use aur_build::config::Config; +use aur_build::db::{self, Db}; + +pub struct Env { + pub tmp: tempfile::TempDir, + pub cfg: Config, + pub db: Db, +} + +impl Env { + pub fn new() -> Self { + let tmp = tempfile::tempdir().expect("tempdir"); + let cfg = Config { + root: tmp.path().to_path_buf(), + signing_key_id: "TESTKEY".into(), + ..Config::default() + }; + cfg.ensure_dirs().expect("ensure_dirs"); + db::migrate(&cfg.db_path()).expect("migrate"); + let db = Db::open_migrated(&cfg.db_path()).expect("open db"); + let rid = db::ensure_repo( + &db.writer, + &cfg.repo_name, + &cfg.repo_arch_dir().display().to_string(), + &cfg.arch, + &cfg.signing_key_id, + ) + .expect("repo row"); + assert!(rid > 0); + Self { tmp, cfg, db } + } + + pub fn root(&self) -> &Path { + self.tmp.path() + } + + pub fn path(&self, p: &str) -> PathBuf { + self.tmp.path().join(p) + } + + /// Insert a pkgbase + active subscription and return the pkgbase id. + pub fn subscribe(&self, name: &str) -> i64 { + let rid = db::repo_id(&self.db).unwrap(); + let url = format!("file://{}/aur/{}.git", self.root().display(), name); + db::subscribe(&self.db.writer, rid, name, &url).unwrap(); + db::get_pkgbase(&self.db, name).unwrap().unwrap().id + } + + /// Drop a row back in via raw SQL (tests need to construct states the API + /// only reaches through several steps). + pub fn exec(&self, sql: &str, params: &[P]) -> usize { + let sql = sql.to_string(); + let params: Vec<P> = params.to_vec(); + self.db + .writer + .tx(move |tx| { + let refs: Vec<&dyn rusqlite::ToSql> = params + .iter() + .map(|p| match p { + P::I(i) => i as &dyn rusqlite::ToSql, + P::S(s) => s as &dyn rusqlite::ToSql, + }) + .collect(); + Ok(tx.execute(&sql, rusqlite::params_from_iter(refs.iter()))?) + }) + .unwrap() + } + + pub fn query_i64(&self, sql: &str, params: &[P]) -> Option<i64> { + let sql = sql.to_string(); + let params: Vec<P> = params.to_vec(); + self.db + .read(move |c| { + let refs: Vec<&dyn rusqlite::ToSql> = params + .iter() + .map(|p| match p { + P::I(i) => i as &dyn rusqlite::ToSql, + P::S(s) => s as &dyn rusqlite::ToSql, + }) + .collect(); + use rusqlite::OptionalExtension; + Ok(c.query_row(&sql, rusqlite::params_from_iter(refs.iter()), |r| r.get::<_, i64>(0)) + .optional()?) + }) + .unwrap() + } +} + +/// A test parameter. Owned so it can cross the writer-actor channel. +#[derive(Debug, Clone)] +pub enum P { + I(i64), + S(String), +} + +impl From<i64> for P { + fn from(i: i64) -> Self { + P::I(i) + } +} +impl From<&str> for P { + fn from(s: &str) -> Self { + P::S(s.to_string()) + } +} +impl From<String> for P { + fn from(s: String) -> Self { + P::S(s) + } +} + +/// Shorthand for building a parameter slice. +pub fn params(v: Vec<impl Into<P>>) -> Vec<P> { + v.into_iter().map(Into::into).collect() +} + +impl Drop for Env { + fn drop(&mut self) { + self.db.writer.shutdown(); + } +} + +/// A minimal PKGBUILD for tests that need recipe bytes without a fixture dir. +pub fn pkgbuild(pkgbase: &str, pkgver: &str, pkgrel: &str, extra: &str) -> String { + format!( + "pkgbase={pkgbase}\npkgver={pkgver}\npkgrel={pkgrel}\npkgdesc=test\narch=(x86_64)\nurl=https://example.invalid\nlicense=(MIT)\n{extra}\nbuild() {{ :\n}}\npackage_{pkgbase}() {{ :\n}}\n" + ) +} + +/// Build a throwaway git repo with the given files and return its path. +pub fn make_git_repo(dir: &Path, files: &[(&str, &str)], msg: &str) -> String { + std::fs::create_dir_all(dir).unwrap(); + git(dir, &["init", "-q", "-b", "master"]); + git(dir, &["config", "user.email", "t@example.invalid"]); + git(dir, &["config", "user.name", "t"]); + for (name, body) in files { + let p = dir.join(name); + if let Some(parent) = p.parent() { + std::fs::create_dir_all(parent).unwrap(); + } + std::fs::write(p, body).unwrap(); + } + git(dir, &["add", "-A"]); + git(dir, &["commit", "-q", "-m", msg]); + git(dir, &["rev-parse", "HEAD"]) +} + +pub fn git_add_commit(dir: &Path, files: &[(&str, &str)], msg: &str) -> String { + for (name, body) in files { + std::fs::write(dir.join(name), body).unwrap(); + } + git(dir, &["add", "-A"]); + git(dir, &["commit", "-q", "-m", msg]); + git(dir, &["rev-parse", "HEAD"]) +} + +pub fn git(dir: &Path, args: &[&str]) -> String { + let out = std::process::Command::new("git") + .arg("-C") + .arg(dir) + .args(args) + .output() + .expect("git"); + assert!( + out.status.success(), + "git {args:?} failed: {}", + String::from_utf8_lossy(&out.stderr) + ); + String::from_utf8_lossy(&out.stdout).trim().to_string() +} diff --git a/tests/db.rs b/tests/db.rs new file mode 100644 index 0000000..60c9256 --- /dev/null +++ b/tests/db.rs @@ -0,0 +1,239 @@ +//! Schema and writer-actor tests (DESIGN.md §11, §11a). +//! +//! These are the parts of the §2 invariant set that are database guarantees +//! rather than code conventions. + +mod common; + +use common::{params, Env, P}; +use rusqlite::params; + +use aur_build::db; + +fn insert_snapshot(env: &Env, pkgbase_id: i64, commit: &str) -> i64 { + db::put_snapshot( + &env.db.writer, + pkgbase_id, + commit, + &format!("rh-{commit}"), + "{}", + "[]", + ) + .unwrap() +} + +fn insert_candidate(env: &Env, pkgbase_id: i64, snap_id: i64, identity: &str, state: &str) { + env.exec( + "INSERT INTO candidate (pkgbase_id, kind, snapshot_id, pkgver, pkgrel, identity_hash, state, detected_at) + VALUES (?1,'new_version',?2,'1.0','1',?3,?4,'2026-01-01T00:00:00Z')", + &[P::I(pkgbase_id), P::I(snap_id), P::S(identity.into()), P::S(state.into())], + ); +} + +#[test] +fn migrations_apply_from_empty_and_are_idempotent() { + let env = Env::new(); + let v = env + .db + .read(|c| { + Ok(c.pragma_query_value(None, "user_version", |r| r.get::<_, u32>(0))?) + }) + .unwrap(); + assert_eq!(v, 4, "all four migrations applied"); + // Re-running migration over an existing DB is a no-op, not an error. + assert_eq!(db::migrate(&env.cfg.db_path()).unwrap(), 0); + let journal: String = env + .db + .read(|c| Ok(c.pragma_query_value(None, "journal_mode", |r| r.get(0))?)) + .unwrap(); + assert_eq!(journal.to_lowercase(), "wal", "WAL mode (§11a)"); +} + +#[test] +fn default_settings_are_seeded() { + let env = Env::new(); + assert_eq!(db::setting_i64(&env.db, "max_concurrent_builds", 0), 1); + assert_eq!(db::setting_i64(&env.db, "poll_interval", 0), 86400); + assert_eq!(db::setting_i64(&env.db, "retention_versions", 0), 3); + db::set_setting(&env.db.writer, "retention_versions", "5").unwrap(); + assert_eq!(db::setting_i64(&env.db, "retention_versions", 0), 5); +} + +/// I7: a pkgbase has at most one open review, enforced by a partial unique index. +#[test] +fn i7_second_open_review_is_rejected_by_the_database() { + let env = Env::new(); + let pb = env.subscribe("foo"); + let snap = insert_snapshot(&env, pb, "aaaa"); + insert_candidate(&env, pb, snap, "id-1", "pending_review"); + let snap2 = insert_snapshot(&env, pb, "bbbb"); + let err = std::panic::catch_unwind(|| { + insert_candidate(&env, pb, snap2, "id-2", "pending_review"); + }); + assert!(err.is_err(), "second pending_review must fail"); + + // A terminal state frees the slot again. + insert_candidate(&env, pb, snap2, "id-2", "rejected"); + let n: Option<i64> = env.query_i64( + "SELECT count(*) FROM candidate WHERE pkgbase_id=?1", + ¶ms(vec![pb]), + ); + assert_eq!(n, Some(2)); +} + +/// Same identity for the same pkgbase must never create a second candidate (I3). +#[test] +fn candidate_identity_is_unique_per_pkgbase() { + let env = Env::new(); + let pb = env.subscribe("foo"); + let s1 = insert_snapshot(&env, pb, "aaaa"); + let s2 = insert_snapshot(&env, pb, "bbbb"); + insert_candidate(&env, pb, s1, "same", "rejected"); + let res = std::panic::catch_unwind(|| insert_candidate(&env, pb, s2, "same", "pending_review")); + assert!(res.is_err(), "UNIQUE(pkgbase_id, identity_hash) must hold"); +} + +/// I10: every state transition is recorded, and the log cannot be rewritten. +#[test] +fn audit_log_is_append_only() { + let env = Env::new(); + db::audit_system(&env.db.writer, "test", "pkgbase", "1", serde_json::json!({"k": 1})).unwrap(); + let id = env + .query_i64("SELECT id FROM audit ORDER BY id DESC LIMIT 1", &[]) + .unwrap(); + assert!( + std::panic::catch_unwind(|| env + .exec("UPDATE audit SET action='x' WHERE id=?1", ¶ms(vec![id]))) + .is_err(), + "audit UPDATE must be refused by trigger" + ); + assert!( + std::panic::catch_unwind(|| env.exec("DELETE FROM audit WHERE id=?1", ¶ms(vec![id]))).is_err(), + "audit DELETE must be refused by trigger" + ); + // Inserts keep working. + db::audit_system(&env.db.writer, "test2", "pkgbase", "1", serde_json::json!({})).unwrap(); +} + +/// §16: concurrent approvals on the same pkgbase are a guarded compare-and-swap. +#[test] +fn accepted_release_pointer_is_compared_and_swapped() { + let env = Env::new(); + let pb = env.subscribe("foo"); + let snap = insert_snapshot(&env, pb, "aaaa"); + insert_candidate(&env, pb, snap, "id-1", "approved"); + let rel = env + .db + .writer + .tx(move |tx| { + tx.execute( + "INSERT INTO release (pkgbase_id, aur_commit, recipe_hash, pkgver, pkgrel, state, created_at) + VALUES (?1,'aaaa','rh','1.0','1','published','2026-01-01T00:00:00Z')", + params![pb], + )?; + Ok(tx.last_insert_rowid()) + }) + .unwrap(); + // First swap from NULL wins, second loses. + assert!(db::cas_accepted_release(&env.db.writer, pb, None, rel).unwrap()); + assert!(!db::cas_accepted_release(&env.db.writer, pb, None, rel).unwrap()); + assert_eq!( + db::get_pkgbase(&env.db, "foo").unwrap().unwrap().current_accepted_release_id, + Some(rel) + ); +} + +/// §11a: WAL lets readers proceed concurrently with the writer. +#[test] +fn many_readers_do_not_block_the_writer() { + let env = std::sync::Arc::new(Env::new()); + let pb = env.subscribe("foo"); + let snap = insert_snapshot(&env, pb, "aaaa"); + insert_candidate(&env, pb, snap, "id-1", "pending_review"); + + let stop = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false)); + let mut readers = Vec::new(); + for _ in 0..8 { + let db = env.db.clone(); + let stop = stop.clone(); + readers.push( + std::thread::Builder::new() + .name("reader".into()) + .spawn(move || { + let mut n = 0u64; + while !stop.load(std::sync::atomic::Ordering::SeqCst) { + let c = db::setting_i64(&db, "max_concurrent_builds", 0); + assert_eq!(c, 1); + n += 1; + } + n + }) + .unwrap(), + ); + } + // Write while they read: none of these may fail with SQLITE_BUSY. + for i in 0..200 { + db::set_setting(&env.db.writer, &format!("k{i}"), "1").unwrap(); + } + stop.store(true, std::sync::atomic::Ordering::SeqCst); + let total: u64 = readers.into_iter().map(|h| h.join().unwrap()).sum(); + assert!(total > 0, "readers made progress during writes"); +} + +#[test] +fn world_snapshot_dedupes_by_hash() { + let env = Env::new(); + let m = |b: &str, v: &str| db::WorldMember { pkgbase: b.into(), version: v.into() }; + let a = db::put_world_snapshot(&env.db.writer, &[m("foo", "1-1"), m("bar", "2-1")]).unwrap(); + // Order-insensitive: same set, same snapshot. + let b = db::put_world_snapshot(&env.db.writer, &[m("bar", "2-1"), m("foo", "1-1")]).unwrap(); + assert_eq!(a, b); + let members = db::world_members(&env.db, a).unwrap(); + assert_eq!(members.len(), 2); + assert_eq!(members[0].pkgbase, "bar", "members are stored sorted"); +} + +#[test] +fn duplicate_open_notices_are_suppressed() { + let env = Env::new(); + let pb = env.subscribe("foo"); + let detail = serde_json::json!({"old": "a", "new": "b"}); + assert!(db::put_notice_once(&env.db.writer, pb, "pin_drift", "info", detail.clone()) + .unwrap() + .is_some()); + assert!(db::put_notice_once(&env.db.writer, pb, "pin_drift", "info", detail.clone()) + .unwrap() + .is_none()); + // Acknowledging lets a fresh one through. + let id = env + .query_i64("SELECT id FROM notice ORDER BY id DESC LIMIT 1", &[]) + .unwrap(); + db::acknowledge_notice(&env.db.writer, id).unwrap(); + assert!(db::put_notice_once(&env.db.writer, pb, "pin_drift", "info", detail) + .unwrap() + .is_some()); +} + +#[test] +fn i1_query_flags_index_entries_without_approval() { + let env = Env::new(); + let pb = env.subscribe("foo"); + // A published release with no approval row: exactly the thing I1 forbids. + let rel = env + .db + .writer + .tx(move |tx| { + tx.execute( + "INSERT INTO release (pkgbase_id, aur_commit, recipe_hash, pkgver, pkgrel, state, created_at) + VALUES (?1,'aaaa','rh','1.0','1','published','2026-01-01T00:00:00Z')", + params![pb], + )?; + Ok(tx.last_insert_rowid()) + }) + .unwrap(); + env.exec( + "INSERT INTO package (repo_id, release_id, name, arch, version, state) VALUES (1,?1,'foo','x86_64','1.0-1','in_index')", + ¶ms(vec![rel]), + ); + assert_eq!(db::unapproved_index_entries(&env.db).unwrap(), vec!["foo".to_string()]); +} |
