summaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authoraur-build <aur-build@localhost>2026-11-18 15:20:13 +0000
committeraur-build <aur-build@localhost>2026-11-18 15:20:13 +0000
commit933c637de34095f1ea1ab88b02626bbf22eec7f4 (patch)
treeee7bd3d7a2b18163c0fdbe061ef53a73b74907ab
parent7946e9ffc48748992f051ada15bec772b16a585d (diff)
downloadaur-build-933c637de34095f1ea1ab88b02626bbf22eec7f4.tar.gz
aur-build-933c637de34095f1ea1ab88b02626bbf22eec7f4.zip
db: the schema gets an owner — every statement moves into db/, and the writer stops handing out connections
Twelve modules outside `db/` contained hand-rolled SQL — 22 statements in `ops.rs`, 17 in `approve.rs`, 15 in `candidates.rs`, 11 in `publish.rs`, and a dozen more scattered through `watch`, `pipeline`, `http` — which meant the blast radius of a schema change was "any module", and `db/` was a directory rather than a boundary. The audit trail alone was defined in four places with three different detail payloads. Every statement now lives in `db/`. New modules `db::candidates` and `db::approvals` own their tables (including the 21-column candidate select, spelled once as `CANDIDATE_COLS` instead of four times); `db::queries` gains the metrics reads, the retention reads and writes, the publish writes (`insert_release_in`, `cas_accepted_release_in`, `remove_index_packages_in`), the staleness reads and the source-cache lookups; `db::builds` gains `set_release_in`. Where a mutation is a *decision* — the collapse rules, the approval gate, the publish compare-and-swap — the decision stays where it was and the statements are called through the transaction handle, so the atomicity is unchanged and only the SQL moved. `audit_in` is the in-transaction audit append, and `audit` is now a wrapper over it: a decision and its audit row commit together or not at all, which is what I10 actually claims. Enforcement is two-layered, because one layer is a lie. `Writer::call`, `tx` and `send` are `pub(crate)`, which keeps the crate's *users* out — the integration tests and the shim binaries — but `pub(crate)` is crate-wide, so on its own it would not stop `approve.rs` from writing SQL tomorrow. The layer that does is `tests/schema_ownership.rs`: it walks `src/` and fails the build if a statement literal or a rusqlite statement call appears outside `src/db/`. It was checked against a deliberate violation. The test harness still needs to construct states no typed API reaches, so the raw door exists but only under the `test-support` feature, which nothing but this crate's own dev-dependency enables; a production binary cannot see it.
-rw-r--r--ARCH_REVIEW.md438
-rw-r--r--Cargo.lock1
-rw-r--r--Cargo.toml11
-rw-r--r--src/db/approvals.rs70
-rw-r--r--src/db/builds.rs11
-rw-r--r--src/db/candidates.rs388
-rw-r--r--src/db/mod.rs63
-rw-r--r--src/db/queries.rs544
-rw-r--r--src/http/routes.rs15
-rw-r--r--src/ops.rs210
-rw-r--r--src/pipeline/mod.rs8
-rw-r--r--src/pipeline/publish.rs92
-rw-r--r--src/pipeline/steps.rs16
-rw-r--r--src/review/approve.rs177
-rw-r--r--src/review/candidates.rs273
-rw-r--r--src/review/diff.rs13
-rw-r--r--src/watch/detect.rs12
-rw-r--r--src/watch/digests.rs31
-rw-r--r--src/watch/staleness.rs67
-rw-r--r--tests/approve.rs2
-rw-r--r--tests/common/mod.rs4
-rw-r--r--tests/db.rs4
-rw-r--r--tests/invariants.rs4
-rw-r--r--tests/schema_ownership.rs88
24 files changed, 1779 insertions, 763 deletions
diff --git a/ARCH_REVIEW.md b/ARCH_REVIEW.md
new file mode 100644
index 0000000..438e45f
--- /dev/null
+++ b/ARCH_REVIEW.md
@@ -0,0 +1,438 @@
+# Architecture Review — `aur-build`
+
+**Scope.** A review of the code as it stands, judged on its own merits: module
+boundaries, encapsulation, coupling, API surfaces, state modeling, naming, and
+clarity. No conformance check against `DESIGN.md` / `INVARIANTS.md` was
+attempted; where those documents are cited it is only because the code cites
+them back at the reader.
+
+**Method.** Full read of `src/` (~12.0k lines, 40 modules), plus the module
+dependency graph, public-surface census, and inline-SQL census. Every finding
+cites `file:line`. Severity definitions at the top of §6.
+
+---
+
+## 1. Executive summary
+
+This is an unusually thoughtful codebase. The core safety story — *nothing is
+published that a human did not approve, and what is published is byte-identical
+to what was reviewed* — is expressed in mechanisms (identity hashes, diff
+digests echoed by the approve request, compare-and-swap on the accepted-release
+pointer, checkpointed build steps, lease-based crash recovery) rather than in
+prose, and the module doc comments explain *why* far more often than they
+explain *what*. The single-writer database actor, the deterministic build id,
+and the read-derived staleness/metrics design are all genuinely good
+architectural decisions, and they are implemented consistently.
+
+The review found **one critical defect**, which is also the sharpest encapsulation
+failure in the codebase: the web session is a static cookie value (`auth=1`),
+so the login gate is trivially bypassed by any client that sets the cookie
+itself (§6, C-1). Everything else is structural:
+
+- **Encapsulation is by convention, not by the compiler.** There are zero
+ `pub(crate)`/`pub(super)` items in the crate; 513 items are fully `pub`. The
+ DB writer actor hands raw `&mut Connection` closures to any module that asks,
+ and 12 modules outside `db/` contain hand-rolled SQL (22 statements in
+ `ops.rs` alone). The schema is the system's most protected asset and nothing
+ stands guard over it.
+- **The persistence layer depends on a domain layer** (`db/queries.rs` returns
+ `watch::upstream::StageB`), and `watch` ↔ `review` are mutually dependent —
+ the dependency graph has cycles at the module-group level.
+- **State machines are stringly typed.** Candidate, build, step, release, and
+ subscription states are `&str` constants; transitions are validated
+ per-call-site at runtime, and `builds::set_state` will happily write any
+ string. The compile-time guarantees the writer-actor comment promises
+ ("*who can write* is a compile-time fact") stop at the connection and never
+ reach the data.
+- **Test scaffolding is load-bearing in production surfaces.** The production
+ publish path calls into the test-shim module to read `.PKGINFO`; fault-
+ injection and clock-pinning hooks live in the production `Config` and the
+ hot path; the clock helper's `secs_ahead`/`secs_ago` silently ignore the
+ pinned clock that `now()` honors.
+- **Error-type discipline slips exactly where the stakes are highest**: the
+ approve path maps *all* internal failures (including SQLite errors) into
+ `Stale::NotPending`, and `bulk()` stuffs unrelated refusals into the same
+ variant.
+
+None of these are hard to fix, and most have obvious fixes that the existing
+style invites. §7 is a prioritized punch list.
+
+---
+
+## 2. Architecture at a glance
+
+One binary (`src/main.rs`), one library crate (`src/lib.rs`), no async runtime.
+Threads: a DB writer actor, a watcher tick, an HTTP accept loop (thread per
+connection), a dispatcher + worker pool, and a reaper folded into the
+dispatcher loop.
+
+```
+ main.rs (CLI) http/ (UI)
+ | |
+ v v
+ review/ (approve, candidates, diff, risk)
+ | |
+ watch/ (scheduler, detect, upstream, |
+ digests, staleness, mirror) <------+----> risk.rs -> watch::digests
+ | |
+ v v
+ pipeline/ (steps, dispatch, publish) ---> shims/ (prod path!)
+ |
+ v
+ db/ (writer actor, readers, queries, builds, model)
+ config.rs error.rs time.rs hash.rs git.rs fetch.rs
+ pkgver/ pkginfo.rs recipe.rs ops.rs
+```
+
+**Inline-SQL census** (statements outside `src/db/`): `ops.rs` 22,
+`review/approve.rs` 17, `review/candidates.rs` 15, `pipeline/publish.rs` 11,
+`watch/staleness.rs` 4, `watch/digests.rs` 3, one or two each in
+`watch/detect.rs`, `review/diff.rs`, `pipeline/{steps,mod,dispatch}.rs`,
+`http/routes.rs`.
+
+**Visibility census:** 513 `pub` items, **0** `pub(crate)` / `pub(super)`.
+`db/mod.rs:17-18` glob-re-exports `model::*` and `queries::*`, so the entire
+row/query surface is flattened into `db::` and reachable from everywhere.
+
+---
+
+## 3. Encapsulation assessment
+
+**The good.** The writer actor (`db/mod.rs:89-190`) is a clean idea well
+executed: one thread owns the write connection, mutations arrive as closures,
+`tx()` wraps everything in `BEGIN IMMEDIATE`, readers are thread-local
+read-only connections, and the `Readers::with` re-entrancy hazard is called out
+and reasoned about in a comment (`db/mod.rs:220-223`). The compare-and-swap on
+`current_accepted_release_id` *inside* the publish transaction
+(`pipeline/publish.rs:213, 258`) is exactly the right way to make I4
+crash-safe. `review::candidates::upsert_candidate` (`review/candidates.rs:45`)
+is the model the rest of the codebase should follow: one transaction, a rich
+return enum (`Upsert`), no leaked SQL semantics to callers.
+
+**The bad.** The actor's *distribution* is unguarded. `Writer::call` /
+`Writer::tx` / `Writer::send` (`db/mod.rs:144,159,177`) are `pub` and hand any
+caller a `&mut Connection`. There are ~50 write sites outside `db/`, and 12
+modules contain raw SQL. This is not merely stylistic:
+
+- `review/approve.rs` hand-writes its `INSERT INTO audit` rows
+ (`approve.rs:134, 187, 256`) instead of calling `db::audit`
+ (`db/queries.rs:53`), so the audit trail's shape is defined in four places
+ with three subtly different detail payloads.
+- `pipeline/publish.rs:42-52, 369-373` queries `artifact.path` directly in two
+ duplicated blocks; `pipeline/mod.rs:316-323` re-implements
+ `builds::set_release` inline.
+- `watch/detect.rs:86-104` (`schedule_next`) re-queries `poll_interval_secs`
+ with raw SQL even though `db::get_subscription` already returns that column —
+ and the scheduler already has it in hand (`watch/scheduler.rs:47-51`).
+
+When the schema changes, the blast radius is "any module," which means the
+`db/` module is not a boundary, it is a directory.
+
+**Layer inversions and cycles.**
+
+- `db/queries.rs:641, 670, 699` — the persistence layer constructs and returns
+ `crate::watch::upstream::StageB`. The cache row type belongs in `db/model.rs`
+ (or its own module) with a conversion at the `watch` boundary.
+- `watch` ↔ `review` is a cycle: `watch/detect.rs` calls
+ `review::candidates::{accepted_for, upsert_candidate, set_risk}` and
+ `review::risk::assess` (`detect.rs:14, 113, 258-266`), while
+ `review/risk.rs:74` calls `watch::digests::skip_on_non_vcs` and
+ `review/risk.rs` imports from `watch`. The cycle is survivable today only
+ because nobody mutates across it, which is exactly the kind of fact
+ encapsulation should make mechanical.
+- `pipeline/publish.rs:353` — production publish calls `crate::shims::read_pkginfo`
+ to parse a package name out of a tarball. The shims module is the fake
+ toolchain (§16a); the real parser already exists in `pkginfo.rs:61-71`. Worse,
+ `shims/mod.rs:568-576` contains a *second* `.PKGINFO` parser
+ (`shims::parse_pkginfo`) that duplicates `pkginfo::parse_pkginfo`
+ (`pkginfo.rs:73`). Two parsers that can drift is a supply-chain-shaped
+ foot-gun in a system whose whole job is provenance.
+
+**Test hooks in production surfaces.** `Config` carries `publish_fault`,
+`shim_fail`, `shim_kill_parent`, `shim_plant_link` (`config.rs:62-83`); the
+publish hot path branches on `publish_fault` twice (`publish.rs:115, 146`);
+`time::pin` (`time.rs:32`) thread-locally fakes the clock. The *existence* of
+these hooks is defensible — the test suite drives the real binary and real
+crashes, which is admirable — but they are unmarked, un-gated, and part of the
+public `Config` API a production operator reads and edits. A `cfg(test)`/feature
+gate, or a separate `TestHooks` struct that production `Config` cannot
+deserialize, would keep the power and drop the exposure.
+
+---
+
+## 4. Clarity-of-design assessment
+
+**Naming and docs are a strength.** Module headers read like design notes
+("Clone, don't scrape", "A stored staleness flag goes wrong the moment anything
+else is published"), and functions that fail closed say what they refuse and
+why. `pipeline/dispatch.rs:1-17` is the best module comment in the repo: it
+states the loop shape, the recovery story, and *why there is no startup
+recovery routine*.
+
+**Where clarity breaks down:**
+
+1. **Stringly-typed state.** `db/model.rs:70-135` defines six state modules of
+ `&str` constants. `builds::set_state(db, id, state: &str, ...)`
+ (`db/builds.rs:195`) accepts any string; legality of a transition is checked
+ (when it is checked) at individual call sites, e.g. `approve.rs` checks
+ `state != candidate_state::PENDING` itself. The build state machine —
+ queued → leased → running → {succeeded, failed, cancelled,
+ blocked_missing_dep} — is the most consequential state machine in the system
+ and exists only as a comment plus scattered `WHERE state IN (...)` clauses.
+ Rust enums (with `str` mapping at the SQL boundary) would move a whole class
+ of "impossible state" bugs to compile time.
+2. **Error types that lie.** `approve()` returns `Result<Result<Approval, Stale>>`
+ and then collapses every inner error into `Stale::NotPending { state:
+ e.to_string() }` (`approve.rs:153`), so a SQLite failure is reported to the
+ reviewer as "review is no longer pending (state: sqlite: …)". `bulk()`
+ reuses `Stale::NotPending` for "high-risk: needs individual confirmation"
+ (`approve.rs:216`) and "unknown decision" (`approve.rs:224`), and fabricates
+ an `Approval { id: 0, … }` sentinel for rejects (`approve.rs:222`). When one
+ enum is bent to carry four unrelated meanings, callers cannot branch on
+ anything.
+3. **A no-op that reads like a safety mechanism.** `mark_approved_but_unbuilt`
+ (`pipeline/mod.rs:272-274`) has a five-line doc comment and an empty body —
+ the real mechanism is the derived query `db::queries::approved_but_unbuilt`.
+ A reader tracing the failure path is invited to believe state is written
+ here. Delete the function, keep the comment on the query.
+4. **Two locks, one promise.** `publish.rs` holds `REPO_LOCK` (line 25) *and*
+ `PUBLISH_LOCK` (line 64), each documented as *the* "one publish per repo"
+ guarantee, both acquired in `publish()` (lines 67, 99); `withdraw_package`
+ takes only `REPO_LOCK` (line 397). Either the second lock is redundant (then
+ delete it) or the guarantee is incomplete (then fix it); today a reader
+ cannot tell which, which is worse than either.
+5. **Dead parameters and `let _ =` debris.** `let _ = db;`
+ (`watch/upstream.rs:262`, `review/risk.rs:113`), `let _ = pb;`
+ (`watch/detect.rs:103`, `review/risk.rs:243`), `let _ = ord;`
+ (`review/diff.rs:254`), `compare_digests(_old, _new, …)`
+ (`risk.rs:178`), `finish(_state, _req, …, _sid, _new)`
+ (`http/mod.rs:263`). Each one is a parameter the design once wanted or no
+ longer wants; leaving them signals a contract that doesn't exist.
+6. **Duplicated logic that can drift.** `hosts()` is byte-identical in
+ `review/diff.rs:226` and `review/risk.rs:220`. The "did the executable part
+ of the PKGBUILD change" heuristic exists twice with *different semantics*:
+ `diff.rs:196-214` keeps only lines that start a function, while
+ `risk.rs:197-215` keeps everything from the first match to EOF. The same
+ change could be flagged by one panel and not the other. The 21-column
+ candidate `SELECT` is copy-pasted four times (`review/candidates.rs:149,
+ 181, 201, 243`) even though `db/queries.rs` establishes the `*_COLS`
+ constant pattern two files over.
+7. **Silent error swallowing in durability-critical spots.** `fsync_file` /
+ `fsync_dir` (`publish.rs:316-329`) ignore every error — in a module whose
+ entire claim is "fsync, then rename". `db::setting_i64`
+ (`queries.rs:29-35`) turns any DB error into a default. `hash::canonical_json`
+ (`hash.rs:76-78`) — which is not actually canonical, despite the name and
+ the comment conceding it isn't — returns `"{}"` on serialization failure,
+ meaning two unserializable identities would hash identically into the
+ approval echo. `auth::random_hex` (`http/auth.rs:22-33`) ignores a failed
+ `/dev/urandom` read and proceeds with a zero buffer.
+
+---
+
+## 5. Per-area notes
+
+### 5.1 `db/` — foundation
+The actor design is sound (§3). The row-mapping discipline (`*_COLS` constants,
+`row_to_*` fns) is good, but `builds_for_pkgbase` (`queries.rs:617`) and
+`all_settings` (`queries.rs:13`) use `filter_map(|r| r.ok())`, silently
+dropping unreadable rows while most queries propagate — pick one policy.
+`builds.rs` is a field-by-field setter buffet (`set_release`, `set_world`,
+`set_candidate`, `set_pkgbase`, `set_profile`, `set_kind`, `set_blocked_on`,
+lines 398-450): anemic rows plus transitions smeared into callers.
+`current_state` returns `""` for a missing build (`builds.rs:455-458`) —
+"no such build" and "build in state (empty)" are different facts.
+`requeue_blocked` (`builds.rs:230-260`) runs one `SELECT count(*)` per waiting
+name per blocked build inside a write transaction (N+1); fine at this scale,
+worth a comment. `approved_but_unbuilt` (`queries.rs:970+`) re-implements
+`pkgver::full_version`'s epoch logic in SQL `CASE` — the version format now
+lives in two languages.
+
+### 5.2 `watch/` — detection
+`detect.rs::analyse` is the longest function in the crate (~150 lines, `detect.rs:107`) and
+carries the most subtle logic in the system (two-stage VCS funnel, identity
+construction, notice-vs-candidate routing). It is readable, but it would
+benefit from extracting the stage-A/stage-B resolution into a named function
+with the `Option<StageA>`/`Option<StageB>` dance inside it rather than four
+parallel `Option`s in scope. `Outcome` (`detect.rs:20-38`) mirrors
+`review::candidates::Upsert` field-for-field with an `outcome_of` converter
+(`detect.rs:292`) — one enum would do. `mirror.rs` is the cleanest module
+in the repo: `Sync` and `Tree` are exactly the right abstractions, and the
+divergence fail-closed (`mirror.rs:91-98`) is well placed.
+`staleness::dependents_of` (`staleness.rs:134-167`) is N+1 (one recipe query
+per index package) and matches on `p.name == name` for the self-exclusion but
+pushes `p.name` — it excludes *the package itself* by name equality on the
+wrong field (`staleness.rs:137-139` compares `p.name == name`, then queries
+`pk.name = ?1` with `p.name`; correct but only by accident of the filter).
+`digests.rs` overloads `skip_declared: true` for all VCS entries
+(`digests.rs:66, 122`) — "declared SKIP" and "digest is a pin, not a checksum"
+are different statements crammed into one boolean.
+
+### 5.3 `review/` — approval
+The heart of the system and mostly its best-written part.
+`upsert_candidate`'s collapse/supersede/reject-memory rules are expressed as
+one transaction with an exhaustive result enum — textbook. `diff.rs`'s
+panel-set design and `render_and_store` (`diff.rs:342`) make the
+displayed-bytes-hash invariant concrete. The problems are the error-type
+abuses in `approve.rs` (§4.2), the hand-rolled audit inserts (§3),
+`withdraw` not checking the release's current state (`approve.rs:245-264` —
+withdrawing an already-withdrawn release silently "succeeds"), and the
+duplications noted in §4.6.
+
+### 5.4 `pipeline/` + `shims/` — build & publish
+The ten-step machine with checkpoint/resume (`pipeline/mod.rs:196-260`) is
+clear and honest; `StepResult::{Done,Skipped,Blocked}` maps cleanly onto the
+step-state column. `steps.rs::collect`'s I9 symlink/containment defense
+(`steps.rs:265-290`) is the kind of paranoid check a reviewer wants to see,
+with the threat model spelled out. Issues: the two-lock confusion (§4.4),
+`extend_lease(..., 90)` hardcoding what `cfg.lease_secs` should own
+(`pipeline/mod.rs:215`), staged artifacts left in the served tree when
+`commit_release` rejects with a conflict (`publish.rs:84-96` — harmless to
+consumers, garbage forever otherwise), `SourceIdentity`'s two-phase
+initialization (`from_candidate` leaves fields empty for `Ctx::new` to fill,
+`pipeline/mod.rs:36-52, 130-140`), and the shims dependency (§3). The
+`shims/` module itself is well-built for its purpose; the problem is only that
+production code can see it at all.
+
+### 5.5 `http/` + CLI + `ops.rs`
+The read/write split (handlers read via thread-local readers, mutations go
+through the writer) is real and consistently applied. The flat route table
+(`http/mod.rs:200-247`) is fine at this size. But `routes.rs` is 1,040 lines
+mixing page rendering, mutations, CSV-ish helpers, and metrics; the auth gate
+is broken (C-1); `Req::form_get` re-parses the whole body per call
+(`http/mod.rs:46-48`); and `metrics` is unauthenticated by design
+(`http/mod.rs:207-212`) — documented and loopback-default, acceptable, but it
+should say so in the response's own docs page (`http/mod.rs:226-230`). The CLI (`main.rs`) genuinely
+drives the same `review::approve` / `pipeline::run` entry points as the UI,
+which is the claim this architecture should make and most such projects fail
+to make. `ops.rs` is cohesive; metrics-on-read (like staleness) is the right
+call and is done twice consistently.
+
+### 5.6 Leaf utilities
+`pkgver/`, `pkginfo.rs`, `recipe.rs`, `git.rs`, `fetch.rs`, `hash.rs`,
+`time.rs` are well-scoped leaf modules with no upward dependencies — except
+that `hash.rs`'s `canonical_json` misnames what it does (§6, M-2) and
+`time.rs`'s pinning is half-honored (§6, m-1).
+
+---
+
+## 6. Findings (severity-ranked)
+
+Severity: **Critical** = exploitable/incorrect behavior in the default
+configuration. **Major** = structural defect that will cause bugs or block
+change. **Minor** = real defect or drift risk with limited blast radius.
+**Nit** = style/clutter.
+
+### Critical
+
+| # | Finding | Evidence |
+|---|---------|----------|
+| C-1 | **Login gate is bypassed by forging a static cookie.** `gate()` treats `Cookie: auth=1` as proof of authentication, and login merely sets that literal value. Any client can read every page (reviews, audit, settings, build logs) by sending `auth=1` without ever supplying the password. The random `sid` session machinery exists (`http/mod.rs:236-239`, `auth.rs:42-59`) but is never bound to the authenticated flag; CSRF then *re-issues* a valid session to the attacker, so even POSTs are reachable once any page is read. | `src/http/routes.rs:20` (`req.cookie("auth").as_deref() == Some("1")`), `src/http/routes.rs:50` (`Set-Cookie: auth=1`), `src/http/mod.rs:236-239` |
+
+*Fix direction:* make the session id the credential — set `sid` at login, mark
+that sid authenticated inside `auth.rs`'s session set, and gate on
+`is_valid_session(sid) && session.is_authenticated`. Delete the `auth` cookie.
+
+### Major
+
+| # | Finding | Evidence |
+|---|---------|----------|
+| M-1 | Writer actor hands raw `&mut Connection` to every module; 12 modules outside `db/` contain hand-rolled SQL (~50 write sites). The schema has no owner. | `src/db/mod.rs:144,159,177`; `src/ops.rs` (22 stmts), `src/review/approve.rs:134,187,256`, `src/pipeline/publish.rs:42-52,369-373`, `src/pipeline/mod.rs:316-323`, `src/watch/detect.rs:86-104` |
+| M-2 | `canonical_json` is not canonical (comment admits it) and returns `"{}"` on serialization failure — every failed identity hashes to the same digest, silently. This is the function behind `Identity::hash`, the value approvals must echo. | `src/hash.rs:76-78`, `src/db/model.rs:64-66` |
+| M-3 | `approve()` converts *all* internal errors (incl. SQLite) into `Stale::NotPending`; `bulk()` reuses the same variant for high-risk refusal and unknown decision, and fabricates `Approval { id: 0 }` for rejects. Callers cannot distinguish "stale review" from "database broken". | `src/review/approve.rs:153, 216, 222-224` |
+| M-4 | Production publish path depends on the test-shim module and its duplicate `.PKGINFO` parser (second parser can drift from `pkginfo.rs`). | `src/pipeline/publish.rs:353`, `src/shims/mod.rs:568-576`, `src/pkginfo.rs:61-71` |
+| M-5 | Two static locks (`REPO_LOCK`, `PUBLISH_LOCK`) each documented as *the* publish serialization guarantee; `withdraw_package` takes only one of the two. | `src/pipeline/publish.rs:25,64,67,99,397` |
+| M-6 | Layer inversion: `db/queries.rs` returns `watch::upstream::StageB`, making persistence depend on a domain module. | `src/db/queries.rs:641,670,699` |
+| M-7 | Module-group cycle: `watch` → `review` (candidates, risk) and `review` → `watch` (digests). | `src/watch/detect.rs:14,113,258-266`; `src/review/risk.rs:74` |
+| M-8 | State machines are `&str` constants with no transition validation; `builds::set_state` writes any string. The build state machine exists only as scattered `WHERE state IN (...)` clauses. | `src/db/model.rs:70-135`, `src/db/builds.rs:195-207` |
+| M-9 | Test hooks are part of the production API surface: fault injection branches in the publish hot path, shim env vars in `Config`, thread-local clock pinning — none gated or marked. | `src/config.rs:62-83`, `src/pipeline/publish.rs:115,146`, `src/time.rs:26-38` |
+
+### Minor
+
+| # | Finding | Evidence |
+|---|---------|----------|
+| m-1 | `secs_ago`/`secs_ahead` ignore the pinned clock that `now()` honors — a pinned-clock test computes real-clock lease expiries. | `src/time.rs:62-70` vs `src/time.rs:14-19` |
+| m-2 | `hosts()` duplicated verbatim; "PKGBUILD body changed" heuristic duplicated with *different* semantics between the diff panel and risk scoring. | `src/review/diff.rs:226` / `src/review/risk.rs:220`; `src/review/diff.rs:196-214` / `src/review/risk.rs:197-215` |
+| m-3 | 21-column candidate `SELECT` copy-pasted 4× despite the `*_COLS` convention used everywhere else in `db/`. | `src/review/candidates.rs:149,181,201,243` |
+| m-4 | Audit rows hand-inserted in three places with three different detail shapes, bypassing `db::audit`. | `src/review/approve.rs:134,187,256` vs `src/db/queries.rs:53` |
+| m-5 | `mark_approved_but_unbuilt` is a documented no-op; the real mechanism is a derived query. Misleading during failure-path tracing. | `src/pipeline/mod.rs:236-241,272-274` |
+| m-6 | `extend_lease` hardcodes 90s instead of `cfg.lease_secs`. | `src/pipeline/mod.rs:215` |
+| m-7 | `fsync_file`/`fsync_dir` swallow all errors in the module whose guarantee is "fsync then rename". | `src/pipeline/publish.rs:316-329` |
+| m-8 | Dead parameters / `let _ =` debris across six modules. | `src/watch/upstream.rs:262`, `src/review/risk.rs:113,178,243`, `src/watch/detect.rs:103`, `src/review/diff.rs:254`, `src/http/mod.rs:263` |
+| m-9 | `setting_i64` maps DB errors to defaults; `filter_map(\|r\| r.ok())` silently drops unreadable rows in some queries but not others. | `src/db/queries.rs:29-35,13-20,617-635` |
+| m-10 | `withdraw` does not check the release's current state; re-withdrawing silently succeeds. | `src/review/approve.rs:245-264` |
+| m-11 | `schedule_next` re-queries with raw SQL a value the caller already had (`sub.poll_interval_secs`). | `src/watch/detect.rs:86-104`, `src/watch/scheduler.rs:47-51` |
+| m-12 | `current_state` returns `""` for a nonexistent build. | `src/db/builds.rs:455-458` |
+| m-13 | `random_hex` proceeds with a zero buffer if `/dev/urandom` read fails. | `src/http/auth.rs:22-33` |
+| m-14 | `is_transient` classifies every `Io` error (incl. ENOSPC/EACCES) as retryable. | `src/error.rs:73-77` |
+| m-15 | `Config::load/save` use `anyhow::Result` while the rest of the crate uses `error::Error`. | `src/config.rs:125,140` |
+| m-16 | Publish leaves staged artifacts in the served tree when `commit_release` rejects (conflict path). | `src/pipeline/publish.rs:84-96` |
+| m-17 | N+1 query patterns: `dependents_of`, `requeue_blocked`. | `src/watch/staleness.rs:134-167`, `src/db/builds.rs:230-260` |
+| m-18 | Version formatting duplicated between Rust (`pkgver::full_version`) and SQL `CASE` in `approved_but_unbuilt`. | `src/db/queries.rs:970+` |
+| m-19 | `digests.rs` overloads `skip_declared: true` for VCS entries (means "digest is a pin", not "declared SKIP"). | `src/watch/digests.rs:66,122` |
+
+### Nit
+
+| # | Finding | Evidence |
+|---|---------|----------|
+| n-1 | `SourceIdentity::from_candidate` returns a half-initialized value completed by `Ctx::new`. | `src/pipeline/mod.rs:36-52,130-140` |
+| n-2 | `watch::detect::Outcome` mirrors `review::candidates::Upsert` with a hand-written converter. | `src/watch/detect.rs:20-38,292` |
+| n-3 | `Req::form_get` re-parses the entire body per call. | `src/http/mod.rs:46-48` |
+| n-4 | `routes.rs` is 1,040 lines mixing pages, mutations, and formatting helpers. | `src/http/routes.rs` |
+| n-5 | `enqueue_manual_rebuild` invents its own identity string format (`aur_commit|recipe_hash|manual`) distinct from candidate identities. | `src/pipeline/mod.rs:295-298` |
+| n-6 | `recipe_at` is `pub` though only used inside `steps.rs`. | `src/pipeline/steps.rs:435` |
+
+---
+
+## 7. Prioritized recommendations
+
+1. **Fix C-1 now.** Bind authentication to the random session id inside
+ `auth.rs` (session set → set of authenticated sids); gate on the sid;
+ delete the `auth=1` cookie. ~30 lines, entirely inside `http/auth.rs` +
+ two call sites. Add a test that a hand-crafted `Cookie: auth=1` gets 302.
+2. **Make `canonical_json` honest** (M-2): rename to `digest_json`, propagate
+ the serialization error instead of `"{}"`, and (cheap) serialize through a
+ `BTreeMap`-normalizing value so the name could eventually be true.
+3. **Give the schema an owner** (M-1): move the ~40 stray SQL statements into
+ `db/queries.rs`/`db/builds.rs` (mechanical), then mark `Writer::call/tx/send`
+ `pub(crate)` so future SQL must land in `db/`. Same trick for the shims
+ dependency (M-4): point `publish.rs::package_name` at `pkginfo::pkginfo_text`,
+ delete `shims::read_pkginfo`/`parse_pkginfo`, and make `shims` a
+ `pub(crate)`-visible test module (or move it under `tests/` support).
+4. **Repair the approve error channel** (M-3): `approve()` should return
+ `Result<Approval, ApproveError>` where `ApproveError = Stale(Stale) |
+ System(Error)`; give `bulk()` its own refusal reasons instead of
+ `Stale::NotPending` overload; return `Option<Approval>` (or nothing) for
+ rejects.
+5. **Pick one publish lock** (M-5) and say so in one comment.
+6. **Break the two dependency cycles** (M-6, M-7): move `StageB` (or a plain
+ `StageBCacheRow`) into `db/model.rs`; move `skip_on_non_vcs` into `recipe.rs`
+ (it is a recipe question, not a watcher question) — both are one-file moves
+ that make the layering a DAG.
+7. **Enum-ify the state machines** (M-8), starting with `build_state`: parse at
+ the row boundary, expose `fn can_transition(from, to) -> bool`, and replace
+ `set_state(&str)` with typed transitions. This is the largest change on the
+ list; do it after 1-6.
+8. **Gate the test hooks** (M-9): a `#[serde(default)] TestHooks` submodule of
+ `Config` documented as test-only (or a cargo feature), and honor the pinned
+ clock in `secs_ago`/`secs_ahead` (m-1).
+9. **De-duplicate**: `hosts()` → `pkgver` or a small `urlutil`; one shared
+ `pkgbuild_bodies()` used by both `diff.rs` and `risk.rs` (m-2); a
+ `CANDIDATE_COLS` constant (m-3); route all audit writes through `db::audit`
+ (m-4).
+10. **Sweep the minors** in whatever order they cross your path: delete the
+ no-op (m-5), use `cfg.lease_secs` (m-6), propagate fsync errors (m-7),
+ remove dead params (m-8), decide the row-error policy (m-9).
+
+---
+
+## 8. Verdict
+
+The domain design is strong — the approval-echo/hash/CAS chain is a coherent
+mechanism for the invariant it serves, and the crash-recovery story (leases +
+reaper-first dispatcher loop + step checkpoints) is better than most systems
+three times this size. What the codebase lacks is *enforcement*: the boundaries
+everyone clearly has in mind (schema lives in `db/`, shims are test-only, states
+have legal transitions, sessions are secrets) are conventions that any future
+commit can violate without a compiler complaint. The fix list is mostly small,
+mechanical, and in the code's own style. Fix C-1 today; the rest will make the
+next hundred commits safer.
diff --git a/Cargo.lock b/Cargo.lock
index f353721..be4a17c 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -127,6 +127,7 @@ version = "0.1.0"
dependencies = [
"anyhow",
"askama",
+ "aur-build",
"chrono",
"clap",
"crossbeam-channel",
diff --git a/Cargo.toml b/Cargo.toml
index b74dbab..79217e8 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -58,12 +58,23 @@ zstd = "0.13"
libc = "0"
flate2 = "1"
+[features]
+# Test-only escape hatches. A fixture sometimes needs a database state no typed
+# API reaches (§6 M-9), and the honest way to allow that is to say where: this
+# feature is enabled only by the crate's own dev-dependency below, so a
+# production build cannot see the raw-SQL door at all.
+test-support = []
+
[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]
+# Self-dependency, the standard way to turn on a feature for the test targets
+# only. The integration tests and `tests/common` are separate crates, so this is
+# how they get the `test-support` escape hatch without the library exposing it.
+aur-build = { path = ".", features = ["test-support"] }
tempfile = "3"
flate2 = "1"
tar = "0.4"
diff --git a/src/db/approvals.rs b/src/db/approvals.rs
new file mode 100644
index 0000000..f04d641
--- /dev/null
+++ b/src/db/approvals.rs
@@ -0,0 +1,70 @@
+//! The approval table: the record of a human decision, and the only thing that
+//! makes a candidate publishable (§7.1a, I1).
+//!
+//! An approval row is what an index entry must trace back to. The rules about
+//! *when* one may be written — same identity, same diff, same base — are domain
+//! logic in `review::approve`; what lives here is the SQL, so the schema has one
+//! owner (§6 M-1).
+
+use rusqlite::{params, OptionalExtension, Transaction};
+
+use crate::db::Db;
+use crate::error::Result;
+
+/// A human decision about one candidate, ready to record.
+pub struct Decision<'a> {
+ pub candidate_id: i64,
+ pub base_release_id: Option<i64>,
+ pub at: &'a str,
+ pub decision: &'a str,
+ pub risk_level: &'a str,
+ pub diff_digest: &'a str,
+ pub identity_hash: &'a str,
+ pub note: Option<&'a str>,
+}
+
+/// Record a decision on a candidate and return the approval row's id.
+pub fn record_in(tx: &mut Transaction<'_>, d: &Decision<'_>) -> Result<i64> {
+ tx.execute(
+ "INSERT INTO approval (candidate_id, base_release_id, decided_at, decision, risk_level,
+ diff_digest, identity_hash, note)
+ VALUES (?1,?2,?3,?4,?5,?6,?7,?8)",
+ params![
+ d.candidate_id,
+ d.base_release_id,
+ d.at,
+ d.decision,
+ d.risk_level,
+ d.diff_digest,
+ d.identity_hash,
+ d.note
+ ],
+ )?;
+ Ok(tx.last_insert_rowid())
+}
+
+/// Record a rejection by copying the candidate's own row into the approval
+/// table. The decision has to describe the bytes that *were* rejected, so it is
+/// read from the row rather than repeated by the caller (§7.1).
+pub fn record_rejection_in(tx: &mut Transaction<'_>, candidate_id: i64, at: &str, identity_hash: &str, note: &str) -> Result<()> {
+ tx.execute(
+ "INSERT INTO approval (candidate_id, base_release_id, decided_at, decision, risk_level,
+ diff_digest, identity_hash, note)
+ SELECT id, base_release_id, ?1, 'rejected', risk_level, diff_digest, ?2, ?3
+ FROM candidate WHERE id=?4",
+ params![at, identity_hash, note, candidate_id],
+ )?;
+ Ok(())
+}
+
+/// The decision recorded against a candidate, if one was.
+pub fn for_candidate(db: &Db, candidate_id: i64) -> Result<Option<(i64, String)>> {
+ db.read(|c| {
+ Ok(c.query_row(
+ "SELECT id, decision FROM approval WHERE candidate_id=?1",
+ params![candidate_id],
+ |r| Ok((r.get(0)?, r.get(1)?)),
+ )
+ .optional()?)
+ })
+}
diff --git a/src/db/builds.rs b/src/db/builds.rs
index 3770746..5c4d1d4 100644
--- a/src/db/builds.rs
+++ b/src/db/builds.rs
@@ -395,12 +395,15 @@ pub fn touch(db: &Db, id: &str) -> Result<()> {
})
}
+/// Record which release a build produced, inside the publish transaction.
+pub fn set_release_in(tx: &rusqlite::Transaction<'_>, id: &str, release_id: i64) -> Result<()> {
+ tx.execute("UPDATE build SET release_id=?1 WHERE id=?2", params![release_id, id])?;
+ Ok(())
+}
+
pub fn set_release(db: &Db, id: &str, release_id: i64) -> Result<()> {
let id = id.to_string();
- db.writer.tx(move |tx| {
- tx.execute("UPDATE build SET release_id=?1 WHERE id=?2", params![release_id, id])?;
- Ok(())
- })
+ db.writer.tx(move |tx| set_release_in(tx, &id, release_id))
}
pub fn set_world(db: &Db, id: &str, world_id: i64) -> Result<()> {
diff --git a/src/db/candidates.rs b/src/db/candidates.rs
new file mode 100644
index 0000000..e41fb94
--- /dev/null
+++ b/src/db/candidates.rs
@@ -0,0 +1,388 @@
+//! The candidate table: its row shape, its column list, and every statement
+//! that touches it (§7.1).
+//!
+//! The *rules* about candidates — collapse into the open review, supersede once
+//! a human has looked, never re-raise a rejection — are domain logic and live
+//! in `review::candidates`. What lives here is SQL, so that the schema has one
+//! owner (§6 M-1). The `_in` functions take a transaction handle so a caller
+//! can compose several of them into one atomic decision; the decision itself
+//! stays with the caller.
+
+use rusqlite::{params, OptionalExtension, Row, Transaction};
+
+use crate::db::{CandidateRow, Db};
+use crate::error::{Error, Result};
+use crate::time;
+
+/// The columns `row_to_candidate` reads, spelled once. Every other table in
+/// this module already works this way; the candidate select was simply copied
+/// four times for long enough to be noticed (§6 m-3).
+const CANDIDATE_COLS: &str = "c.id, c.pkgbase_id, c.base_release_id, c.kind, c.snapshot_id, c.epoch, c.pkgver, \
+ c.pkgrel, c.upstream_pins_json, c.source_digests_json, c.identity_hash, c.diff_digest, \
+ c.revision, c.viewed_at, c.risk_level, c.risk_signals_json, c.missing_deps_json, c.state, \
+ c.detected_at, c.resolved_at, b.name";
+
+fn row_to_candidate(r: &Row<'_>) -> rusqlite::Result<CandidateRow> {
+ Ok(CandidateRow {
+ id: r.get(0)?,
+ pkgbase_id: r.get(1)?,
+ base_release_id: r.get(2)?,
+ kind: r.get(3)?,
+ snapshot_id: r.get(4)?,
+ epoch: r.get(5)?,
+ pkgver: r.get(6)?,
+ pkgrel: r.get(7)?,
+ upstream_pins_json: r.get(8)?,
+ source_digests_json: r.get(9)?,
+ identity_hash: r.get(10)?,
+ diff_digest: r.get(11)?,
+ revision: r.get(12)?,
+ viewed_at: r.get(13)?,
+ risk_level: r.get(14)?,
+ risk_signals_json: r.get(15)?,
+ missing_deps_json: r.get(16)?,
+ state: r.get(17)?,
+ detected_at: r.get(18)?,
+ resolved_at: r.get(19)?,
+ pkgbase: r.get(20)?,
+ })
+}
+
+/// The fields a new candidate row carries, beyond its pkgbase and its base.
+#[derive(Debug, Clone)]
+pub struct NewCandidate {
+ 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,
+}
+
+impl NewCandidate {
+ /// The `epoch:pkgver-pkgrel` this candidate would publish.
+ pub fn version(&self) -> String {
+ crate::pkgver::full_version(&self.epoch, &self.pkgver, &self.pkgrel)
+ }
+}
+
+/// The open review of a pkgbase — as much of it as the collapse rules need.
+#[derive(Debug, Clone)]
+pub struct OpenReview {
+ pub id: i64,
+ pub identity_hash: String,
+ pub viewed_at: Option<String>,
+ pub revision: i64,
+}
+
+impl OpenReview {
+ /// Has a human opened this review yet? That timestamp is what decides
+ /// whether a newer detection collapses or supersedes (§7.1).
+ pub fn viewed(&self) -> bool {
+ self.viewed_at.is_some()
+ }
+}
+
+// ------------------------------------------------------------------ in-tx --
+
+/// Everything the approval gate has to look at to decide, read in one statement
+/// so the check cannot straddle two snapshots of the database.
+#[derive(Debug, Clone)]
+pub struct ReviewSubject {
+ pub id: i64,
+ pub pkgbase_id: i64,
+ pub state: String,
+ pub identity_hash: String,
+ pub diff_digest: String,
+ /// The release this review was opened against (I2).
+ pub base_release_id: Option<i64>,
+ /// What the pkgbase accepts now — the other half of the I2 check.
+ pub current_base_release_id: Option<i64>,
+ pub risk_level: String,
+ pub pkgbase: String,
+}
+
+pub fn review_subject_in(tx: &Transaction<'_>, candidate_id: i64) -> Result<Option<ReviewSubject>> {
+ Ok(tx
+ .query_row(
+ "SELECT c.id, c.pkgbase_id, c.state, c.identity_hash, c.diff_digest, c.base_release_id,
+ p.current_accepted_release_id, c.risk_level, p.name
+ FROM candidate c JOIN pkgbase p ON p.id = c.pkgbase_id
+ WHERE c.id = ?1",
+ params![candidate_id],
+ |r| {
+ Ok(ReviewSubject {
+ id: r.get(0)?,
+ pkgbase_id: r.get(1)?,
+ state: r.get(2)?,
+ identity_hash: r.get(3)?,
+ diff_digest: r.get(4)?,
+ base_release_id: r.get(5)?,
+ current_base_release_id: r.get(6)?,
+ risk_level: r.get(7)?,
+ pkgbase: r.get(8)?,
+ })
+ },
+ )
+ .optional()?)
+}
+
+/// Take a candidate out of the open state: approved, rejected or superseded.
+pub fn resolve_in(tx: &Transaction<'_>, id: i64, state: &str, at: &str) -> Result<()> {
+ tx.execute("UPDATE candidate SET state=?1, resolved_at=?2 WHERE id=?3", params![state, at, id])?;
+ Ok(())
+}
+
+/// A candidate's state, read inside a transaction (the reject path needs it
+/// before it writes).
+pub fn state_in(tx: &Transaction<'_>, id: i64) -> Result<Option<String>> {
+ Ok(tx
+ .query_row("SELECT state FROM candidate WHERE id=?1", params![id], |r| r.get::<_, String>(0))
+ .optional()?)
+}
+
+pub fn identity_in(tx: &Transaction<'_>, id: i64) -> Result<Option<String>> {
+ Ok(tx
+ .query_row("SELECT identity_hash FROM candidate WHERE id=?1", params![id], |r| r.get::<_, String>(0))
+ .optional()?)
+}
+
+/// The risk level recorded at review time, if the candidate exists.
+pub fn risk_level(db: &Db, id: i64) -> Result<Option<String>> {
+ db.read(|c| {
+ Ok(c.query_row("SELECT risk_level FROM candidate WHERE id=?1", params![id], |r| r.get::<_, String>(0))
+ .optional()?)
+ })
+}
+
+/// The pkgbase's open review, if it has one (I7: at most one).
+pub fn open_in(tx: &Transaction<'_>, pkgbase_id: i64) -> Result<Option<OpenReview>> {
+ Ok(tx
+ .query_row(
+ "SELECT id, identity_hash, viewed_at, revision FROM candidate
+ WHERE pkgbase_id=?1 AND state='pending_review'",
+ params![pkgbase_id],
+ |r| {
+ Ok(OpenReview {
+ id: r.get(0)?,
+ identity_hash: r.get(1)?,
+ viewed_at: r.get(2)?,
+ revision: r.get(3)?,
+ })
+ },
+ )
+ .optional()?)
+}
+
+/// Write a newer detection into the open review: same row, same base, one more
+/// revision, and the stale diff rendering dropped so it cannot be approved.
+pub fn collapse_in(tx: &mut Transaction<'_>, open: &OpenReview, nc: &NewCandidate) -> Result<i64> {
+ let revision = open.revision + 1;
+ tx.execute(
+ "UPDATE candidate SET snapshot_id=?1, epoch=?2, pkgver=?3, pkgrel=?4,
+ upstream_pins_json=?5, source_digests_json=?6, identity_hash=?7,
+ revision=?8, detected_at=?9, diff_digest=''
+ WHERE id=?10",
+ params![
+ nc.snapshot_id,
+ nc.epoch,
+ nc.pkgver,
+ nc.pkgrel,
+ nc.upstream_pins_json,
+ nc.source_digests_json,
+ nc.identity_hash,
+ revision,
+ time::now(),
+ open.id
+ ],
+ )?;
+ Ok(revision)
+}
+
+/// Freeze a reviewed candidate as `superseded` so a fresh review can open.
+pub fn supersede_in(tx: &Transaction<'_>, id: i64) -> Result<()> {
+ tx.execute(
+ "UPDATE candidate SET state='superseded', resolved_at=?1 WHERE id=?2",
+ params![time::now(), id],
+ )?;
+ Ok(())
+}
+
+/// Has this exact identity been rejected before? If so the watcher stays quiet
+/// until a human re-opens it (§7.1: "do not nag").
+pub fn rejected_before_in(tx: &Transaction<'_>, pkgbase_id: i64, identity_hash: &str) -> Result<bool> {
+ Ok(tx
+ .query_row(
+ "SELECT id FROM candidate WHERE pkgbase_id=?1 AND identity_hash=?2 AND state='rejected'
+ ORDER BY id DESC LIMIT 1",
+ params![pkgbase_id, identity_hash],
+ |r| r.get::<_, i64>(0),
+ )
+ .optional()?
+ .is_some())
+}
+
+/// Has this identity been recorded at all — approved, superseded, anything?
+/// Then the detection said nothing new.
+pub fn recorded_before_in(tx: &Transaction<'_>, pkgbase_id: i64, identity_hash: &str) -> Result<bool> {
+ Ok(tx
+ .query_row(
+ "SELECT id FROM candidate WHERE pkgbase_id=?1 AND identity_hash=?2
+ ORDER BY id DESC LIMIT 1",
+ params![pkgbase_id, identity_hash],
+ |r| r.get::<_, i64>(0),
+ )
+ .optional()?
+ .is_some())
+}
+
+/// Open a candidate row in `pending_review`.
+pub fn insert_in(
+ tx: &mut Transaction<'_>,
+ pkgbase_id: i64,
+ base: Option<i64>,
+ kind: &str,
+ nc: &NewCandidate,
+) -> Result<i64> {
+ tx.execute(
+ "INSERT INTO candidate (pkgbase_id, base_release_id, kind, snapshot_id, epoch, pkgver, pkgrel,
+ upstream_pins_json, source_digests_json, identity_hash, state, detected_at)
+ VALUES (?1,?2,?3,?4,?5,?6,?7,?8,?9,?10,'pending_review',?11)",
+ params![
+ pkgbase_id,
+ base,
+ kind,
+ nc.snapshot_id,
+ nc.epoch,
+ nc.pkgver,
+ nc.pkgrel,
+ nc.upstream_pins_json,
+ nc.source_digests_json,
+ nc.identity_hash,
+ time::now()
+ ],
+ )?;
+ Ok(tx.last_insert_rowid())
+}
+
+// ------------------------------------------------------------------ reads --
+
+/// Every candidate regardless of state, newest first (`aur-build reviews --all`).
+pub fn all(db: &Db) -> Result<Vec<CandidateRow>> {
+ let sql = format!("SELECT {CANDIDATE_COLS} FROM candidate c JOIN pkgbase b ON b.id = c.pkgbase_id ORDER BY c.detected_at DESC LIMIT 500");
+ db.read(move |c| {
+ let mut stmt = c.prepare(&sql)?;
+ let rows = stmt.query_map([], row_to_candidate)?;
+ let mut out = Vec::new();
+ for r in rows {
+ out.push(r?);
+ }
+ Ok(out)
+ })
+}
+
+/// The reviews waiting for a decision, riskiest first.
+pub fn pending(db: &Db) -> Result<Vec<CandidateRow>> {
+ let sql = format!(
+ "SELECT {CANDIDATE_COLS} FROM candidate c JOIN pkgbase b ON b.id = c.pkgbase_id \
+ WHERE c.state='pending_review' ORDER BY (c.risk_level='high') DESC, c.detected_at"
+ );
+ db.read(move |c| {
+ let mut stmt = c.prepare(&sql)?;
+ let rows = stmt.query_map([], row_to_candidate)?;
+ let mut out = Vec::new();
+ for r in rows {
+ out.push(r?);
+ }
+ Ok(out)
+ })
+}
+
+pub fn by_id(db: &Db, id: i64) -> Result<Option<CandidateRow>> {
+ let sql = format!("SELECT {CANDIDATE_COLS} FROM candidate c JOIN pkgbase b ON b.id = c.pkgbase_id WHERE c.id=?1");
+ db.read(move |c| {
+ Ok(c.query_row(&sql, params![id], row_to_candidate)
+ .optional()?)
+ })
+}
+
+/// Open reviews for a pkgbase (usually zero or one, by I7).
+pub fn open_reviews_for(db: &Db, pkgbase_id: i64) -> Result<Vec<CandidateRow>> {
+ let sql = format!(
+ "SELECT {CANDIDATE_COLS} FROM candidate c JOIN pkgbase b ON b.id = c.pkgbase_id \
+ WHERE c.pkgbase_id=?1 AND c.state='pending_review'"
+ );
+ db.read(move |c| {
+ let mut stmt = c.prepare(&sql)?;
+ let rows = stmt.query_map(params![pkgbase_id], row_to_candidate)?;
+ let mut out = Vec::new();
+ for r in rows {
+ out.push(r?);
+ }
+ Ok(out)
+ })
+}
+
+// ---------------------------------------------------------------- writes --
+
+/// Mark a candidate `viewed` the first time a human opens it. That timestamp is
+/// what decides whether a later detection collapses or supersedes (§7.1).
+pub fn mark_viewed(db: &Db, id: i64) -> Result<()> {
+ let at = time::now();
+ db.writer.tx(move |tx| {
+ tx.execute(
+ "UPDATE candidate SET viewed_at=?1 WHERE id=?2 AND viewed_at IS NULL",
+ params![at, id],
+ )?;
+ Ok(())
+ })
+}
+
+/// §7.1: a rejection can be re-opened. We retire the rejected row so it stops
+/// suppressing the identity, and the next detection opens a fresh review.
+pub fn reopen_rejected(db: &Db, id: i64) -> Result<()> {
+ let at = time::now();
+ db.writer.tx(move |tx| {
+ let n = tx.execute(
+ "UPDATE candidate SET state='superseded', resolved_at=?1 WHERE id=?2 AND state='rejected'",
+ params![at, id],
+ )?;
+ if n == 0 {
+ return Err(Error::conflict("candidate is not rejected"));
+ }
+ Ok(())
+ })
+}
+
+/// Record the risk assessment computed at review time.
+pub fn set_risk(db: &Db, id: i64, level: &str, signals: &[String]) -> Result<()> {
+ let lvl = level.to_string();
+ let sig = serde_json::to_string(signals)?;
+ db.writer.tx(move |tx| {
+ tx.execute(
+ "UPDATE candidate SET risk_level=?1, risk_signals_json=?2 WHERE id=?3",
+ params![lvl, sig, id],
+ )?;
+ Ok(())
+ })
+}
+
+pub fn set_missing_deps(db: &Db, id: i64, missing: &[String]) -> Result<()> {
+ let m = serde_json::to_string(missing)?;
+ db.writer.tx(move |tx| {
+ tx.execute(
+ "UPDATE candidate SET missing_deps_json=?1 WHERE id=?2",
+ params![m, id],
+ )?;
+ Ok(())
+ })
+}
+
+pub fn set_diff_digest(db: &Db, id: i64, digest: &str) -> Result<()> {
+ let d = digest.to_string();
+ db.writer.tx(move |tx| {
+ tx.execute("UPDATE candidate SET diff_digest=?1 WHERE id=?2", params![d, id])?;
+ Ok(())
+ })
+}
diff --git a/src/db/mod.rs b/src/db/mod.rs
index b810453..2cf766b 100644
--- a/src/db/mod.rs
+++ b/src/db/mod.rs
@@ -8,7 +8,9 @@
//! design entirely. Readers are thread-local, read-only connections; WAL lets
//! them proceed concurrently with the writer.
+pub mod approvals;
pub mod builds;
+pub mod candidates;
pub mod migrations;
pub mod model;
pub mod queries;
@@ -139,9 +141,16 @@ impl Writer {
/// 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>
+ /// No transaction may span a build step: `f` should be short.
+ /// Use [`Writer::tx`] for atomic multi-statement mutations.
+ ///
+ /// `pub(crate)`, not `pub`: the schema is the system's most protected asset
+ /// and it has one owner, this module (§6 M-1). Code outside `db/` asks for a
+ /// typed query instead of writing SQL. `pub(crate)` is what keeps the
+ /// *crate's* users (the integration tests, the shim binaries) out; inside
+ /// the crate the convention is enforced by `tests/schema_ownership.rs`,
+ /// which fails the build if a SQL statement appears outside `src/db/`.
+ pub(crate) fn call<T>(&self, f: impl FnOnce(&mut Connection) -> Result<T> + Send + 'static) -> Result<T>
where
T: Send + 'static,
{
@@ -156,7 +165,7 @@ impl Writer {
/// 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>(
+ pub(crate) fn tx<T>(
&self,
f: impl FnOnce(&mut rusqlite::Transaction<'_>) -> Result<T> + Send + 'static,
) -> Result<T>
@@ -174,7 +183,7 @@ impl Writer {
}
/// Fire-and-forget write (audit rows, bookkeeping where the result is unused).
- pub fn send(&self, f: BoxedCall) -> Result<()> {
+ pub(crate) fn send(&self, f: BoxedCall) -> Result<()> {
if !self.is_alive() {
return Err(Error::db("writer actor gone"));
}
@@ -188,6 +197,36 @@ impl Writer {
}
}
+/// The raw-SQL door, open only for the test harness (§6 M-9).
+///
+/// A fixture sometimes has to put the database in a state the typed API only
+/// reaches through several steps — a release published without a build, a
+/// pointer moved out from under a review. That is a reason to have a door, not
+/// a reason to leave it unlocked in the binary an operator runs, so it exists
+/// only under the `test-support` feature, which nothing but this crate's own
+/// dev-dependency enables.
+#[cfg(feature = "test-support")]
+impl Writer {
+ /// Run `f` in a transaction. Test fixtures only.
+ pub fn tx_for_tests<T>(
+ &self,
+ f: impl FnOnce(&mut rusqlite::Transaction<'_>) -> Result<T> + Send + 'static,
+ ) -> Result<T>
+ where
+ T: Send + 'static,
+ {
+ self.tx(f)
+ }
+
+ /// Run `f` on the write connection. Test fixtures only.
+ pub fn call_for_tests<T>(&self, f: impl FnOnce(&mut Connection) -> Result<T> + Send + 'static) -> Result<T>
+ where
+ T: Send + 'static,
+ {
+ self.call(f)
+ }
+}
+
/// Thread-local read-only connection pool.
///
/// One connection per thread per database file, opened read-only. HTTP handlers
@@ -263,6 +302,20 @@ pub fn backup_to(writer: &Writer, dest: &Path) -> Result<()> {
})
}
+/// The schema version a database file reports. A backup that does not open and
+/// answer with a migrated schema is a file, not a backup, and the only way to
+/// find that out is to ask it.
+///
+/// Opened read-write and untouched by the connection pragmas: the point is to
+/// read one number from a file we are not going to modify, and a WAL database
+/// cannot even be opened read-only (it needs its sidecar).
+pub fn schema_version(path: &Path) -> Result<i64> {
+ let conn = rusqlite::Connection::open(path)
+ .map_err(|e| Error::db(format!("{} does not open: {e}", path.display())))?;
+ conn.query_row("PRAGMA user_version", [], |r| r.get(0))
+ .map_err(|e| Error::db(format!("{} has no schema version: {e}", path.display())))
+}
+
/// WAL size + checkpoint lag, surfaced on the Ops page and in metrics.
pub fn wal_stats(db: &Db) -> (u64, u64) {
let db_file = std::fs::metadata(db.writer.path()).map(|m| m.len()).unwrap_or(0);
diff --git a/src/db/queries.rs b/src/db/queries.rs
index ca73e5f..ffb2520 100644
--- a/src/db/queries.rs
+++ b/src/db/queries.rs
@@ -1,7 +1,7 @@
//! 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 rusqlite::{params, params_from_iter, OptionalExtension, Row};
use crate::db::*;
use crate::error::{Error, Result};
@@ -65,17 +65,47 @@ pub fn audit(
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(())
+ audit_in(
+ tx,
+ &AuditEntry {
+ at: &at,
+ actor_kind: &actor_kind,
+ actor: &actor,
+ action: &action,
+ entity: &entity,
+ entity_id: &entity_id,
+ detail,
+ },
+ )
})
}
+/// An audit row to append inside someone else's transaction.
+#[derive(Debug)]
+pub struct AuditEntry<'a> {
+ pub at: &'a str,
+ pub actor_kind: &'a str,
+ pub actor: &'a str,
+ pub action: &'a str,
+ pub entity: &'a str,
+ pub entity_id: &'a str,
+ pub detail: serde_json::Value,
+}
+
+/// Append an audit row inside a caller's transaction (I10). This is the variant
+/// every multi-statement mutation uses: the record of a decision commits with
+/// the decision or not at all, so there is no window where an audit row
+/// describes a change that was rolled back.
+pub fn audit_in(tx: &rusqlite::Transaction<'_>, e: &AuditEntry<'_>) -> Result<()> {
+ tx.execute(
+ "INSERT INTO audit (at, actor_kind, actor, action, entity, entity_id, detail_json)
+ VALUES (?1,?2,?3,?4,?5,?6,?7)",
+ params![e.at, e.actor_kind, e.actor, e.action, e.entity, e.entity_id, e.detail.to_string()],
+ )?;
+ 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)
}
@@ -441,6 +471,15 @@ const RELEASE_COLS_R: &str = "r.id, r.pkgbase_id, r.candidate_id, r.approval_id,
r.recipe_hash, r.upstream_pins_json, r.source_digests_json, r.epoch, r.pkgver, r.pkgrel, \
r.world_snapshot_id, r.state, r.published_at";
+/// Withdraw a published release and remove the packages it served (§9
+/// `repo-remove`, decision 23). Runs in the caller's transaction so the removal
+/// and the audit row that explains it are one fact.
+pub fn withdraw_release_in(tx: &rusqlite::Transaction<'_>, release_id: i64) -> Result<()> {
+ tx.execute("UPDATE release SET state='withdrawn' WHERE id=?1", params![release_id])?;
+ tx.execute("UPDATE package SET state='removed' WHERE release_id=?1", params![release_id])?;
+ Ok(())
+}
+
pub fn release_by_id(db: &Db, id: i64) -> Result<Option<ReleaseRow>> {
db.read(|c| {
c.query_row(
@@ -635,6 +674,286 @@ pub fn builds_for_pkgbase(db: &Db, pkgbase_id: i64, limit: i64) -> Result<Vec<cr
})
}
+// ------------------------------------------------------------ publish writes --
+//
+// Publishing is the one externally visible step, so every statement it needs is
+// here and the *decision* stays in `pipeline::publish`: the caller opens the
+// transaction, calls these in order, and bails if the compare-and-swap says the
+// world moved (I4).
+
+/// The on-disk path of an artifact, by id.
+pub fn artifact_path(db: &Db, id: i64) -> Result<Option<String>> {
+ db.read(|c| {
+ Ok(c.query_row("SELECT path FROM artifact WHERE id=?1", params![id], |r| r.get::<_, String>(0))
+ .optional()?)
+ })
+}
+
+/// The artifact row for a content digest, if one exists. Two releases built from
+/// identical bytes share one artifact row — that is the point of the digest.
+pub fn artifact_id_by_digest_in(tx: &rusqlite::Transaction<'_>, digest: &str) -> Result<Option<i64>> {
+ Ok(tx
+ .query_row("SELECT id FROM artifact WHERE digest=?1", params![digest], |r| r.get::<_, i64>(0))
+ .optional()?)
+}
+
+/// The pkgbase's accepted pointer, read inside a transaction: the CAS baseline.
+pub fn accepted_pointer_in(tx: &rusqlite::Transaction<'_>, pkgbase_id: i64) -> Result<Option<i64>> {
+ tx.query_row(
+ "SELECT current_accepted_release_id FROM pkgbase WHERE id=?1",
+ params![pkgbase_id],
+ |r| r.get::<_, Option<i64>>(0),
+ )
+ .optional()
+ .map(Option::flatten)
+ .map_err(Into::into)
+}
+
+/// Compare-and-swap the accepted pointer inside a transaction. `false` means it
+/// was not where the caller thought it was, and the publish must not land.
+pub fn cas_accepted_release_in(
+ tx: &rusqlite::Transaction<'_>,
+ pkgbase_id: i64,
+ new_release_id: i64,
+ expected: Option<i64>,
+) -> Result<bool> {
+ let moved = tx.execute(
+ "UPDATE pkgbase SET current_accepted_release_id=?1 WHERE id=?2 AND current_accepted_release_id IS ?3",
+ params![new_release_id, pkgbase_id, expected],
+ )?;
+ Ok(moved == 1)
+}
+
+/// Retire whatever the index held for these names. The index holds exactly the
+/// accepted pointers, so this runs before the new rows go in.
+pub fn remove_index_packages_in(tx: &rusqlite::Transaction<'_>, names: &[String]) -> Result<()> {
+ if names.is_empty() {
+ return Ok(());
+ }
+ let ph = names.iter().map(|_| "?").collect::<Vec<_>>().join(",");
+ let sql = format!("UPDATE package SET state='removed' WHERE state='in_index' AND name IN ({ph})");
+ let mut stmt = tx.prepare(&sql)?;
+ stmt.execute(params_from_iter(names.iter().map(|n| n as &dyn rusqlite::ToSql)))?;
+ Ok(())
+}
+
+/// Retire one named package from the index (the §9 withdrawal path).
+pub fn remove_package_by_name_in(tx: &rusqlite::Transaction<'_>, repo_id: i64, name: &str) -> Result<()> {
+ tx.execute(
+ "UPDATE package SET state='removed' WHERE repo_id=?1 AND name=?2",
+ params![repo_id, name],
+ )?;
+ Ok(())
+}
+
+/// Everything a published release records. Borrowed because the caller is in the
+/// middle of a transaction and has the values on the stack.
+pub struct NewRelease<'a> {
+ pub pkgbase_id: i64,
+ pub candidate_id: Option<i64>,
+ pub approval_id: Option<i64>,
+ pub aur_commit: &'a str,
+ pub recipe_hash: &'a str,
+ pub upstream_pins_json: &'a str,
+ pub source_digests_json: &'a str,
+ pub epoch: &'a str,
+ pub pkgver: &'a str,
+ pub pkgrel: &'a str,
+ pub world_snapshot_id: Option<i64>,
+ pub build_id: &'a str,
+}
+
+/// Insert the release row and return its id.
+pub fn insert_release_in(tx: &mut rusqlite::Transaction<'_>, r: &NewRelease<'_>, at: &str) -> Result<i64> {
+ tx.execute(
+ "INSERT INTO release (pkgbase_id, candidate_id, approval_id, aur_commit, recipe_hash,
+ upstream_pins_json, source_digests_json, epoch, pkgver, pkgrel,
+ world_snapshot_id, state, build_id, published_at, created_at)
+ VALUES (?1,?2,?3,?4,?5,?6,?7,?8,?9,?10,?11,'published',?12,?13,?13)",
+ params![
+ 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.build_id,
+ at
+ ],
+ )?;
+ Ok(tx.last_insert_rowid())
+}
+
+/// Put one package into the index, pointing at the artifact with this digest.
+pub fn insert_package_in(
+ tx: &rusqlite::Transaction<'_>,
+ repo_id: i64,
+ release_id: i64,
+ name: &str,
+ arch: &str,
+ version: &str,
+ digest: &str,
+) -> Result<()> {
+ let artifact_id = artifact_id_by_digest_in(tx, digest)?;
+ tx.execute(
+ "INSERT INTO package (repo_id, release_id, name, arch, version, artifact_id, state)
+ VALUES (?1,?2,?3,?4,?5,?6,'in_index')",
+ params![repo_id, release_id, name, arch, version, artifact_id],
+ )?;
+ Ok(())
+}
+
+// ------------------------------------------------------------ staleness reads --
+//
+// Staleness is derived on read (§10.2), and these are the reads it is derived
+// from. They return plain tuples: the *meaning* ("this dependency moved") is
+// `watch::staleness`'s business, the SQL is this module's.
+
+/// `(pkgbase, world members JSON)` for every published release, taken from the
+/// world snapshot its build recorded (§10.1).
+pub fn published_world_members(db: &Db) -> Result<Vec<(String, String)>> {
+ db.read(|c| {
+ let mut st = c.prepare(
+ "SELECT p.name, w.members_json
+ FROM release r
+ JOIN pkgbase p ON p.id = r.pkgbase_id
+ JOIN build b ON b.id = r.build_id
+ JOIN world_snapshot w ON w.id = b.world_snapshot_id
+ WHERE r.state = 'published'",
+ )?;
+ let rows = st.query_map([], |r| Ok((r.get::<_, String>(0)?, r.get::<_, String>(1)?)))?;
+ Ok(rows.filter_map(|r| r.ok()).collect::<Vec<_>>())
+ })
+}
+
+/// `(pkgbase, served pkgver, newest candidate pkgver)` for every accepted
+/// release — the pair the downgrade check compares (§10.2).
+pub fn served_vs_offered_pkgvers(db: &Db) -> Result<Vec<(String, String, String)>> {
+ db.read(|c| {
+ let mut st = c.prepare(
+ "SELECT p.name, r.pkgver, (
+ SELECT c.pkgver FROM candidate c
+ WHERE c.pkgbase_id = r.pkgbase_id
+ ORDER BY c.id DESC LIMIT 1)
+ FROM release r
+ JOIN pkgbase p ON p.current_accepted_release_id = r.id
+ WHERE r.state = 'published'",
+ )?;
+ let rows = st.query_map([], |r| {
+ Ok((
+ r.get::<_, String>(0)?,
+ r.get::<_, String>(1)?,
+ r.get::<_, Option<String>>(2)?.unwrap_or_default(),
+ ))
+ })?;
+ Ok(rows.filter_map(|r| r.ok()).collect::<Vec<_>>())
+ })
+}
+
+/// The `srcinfo_json` of the recipe the index's copy of a package was built
+/// from — what its dependency list actually said.
+pub fn recipe_json_of_index_package(db: &Db, name: &str) -> Result<Option<String>> {
+ db.read(|c| {
+ Ok(c.query_row(
+ "SELECT s.srcinfo_json FROM package pk
+ JOIN release r ON r.id = pk.release_id
+ JOIN candidate cnd ON cnd.id = r.candidate_id
+ JOIN snapshot s ON s.id = cnd.snapshot_id
+ WHERE pk.name = ?1 AND pk.state='in_index'",
+ params![name],
+ |r| r.get::<_, String>(0),
+ )
+ .optional()?)
+ })
+}
+
+/// The note a reviewer left on an approval, empty when there was none.
+pub fn approval_note(db: &Db, approval_id: i64) -> Result<String> {
+ db.read(|c| {
+ c.query_row("SELECT COALESCE(note,'') FROM approval WHERE id=?1", params![approval_id], |r| r.get::<_, String>(0))
+ .optional()
+ .map(|o| o.unwrap_or_default())
+ .map_err(Into::into)
+ })
+}
+
+/// The snapshot a candidate was created from, for rendering its diff.
+pub fn candidate_snapshot_id(db: &Db, candidate_id: i64) -> Result<Option<i64>> {
+ db.read(|c| {
+ Ok(c.query_row("SELECT snapshot_id FROM candidate WHERE id=?1", params![candidate_id], |r| r.get::<_, i64>(0))
+ .optional()?)
+ })
+}
+
+/// The poll interval configured for a subscription, as the scheduler already
+/// knows it (§5.1: one place decides how often a pkgbase is checked).
+pub fn subscription_poll_interval(db: &Db, pkgbase: &str) -> Result<Option<i64>> {
+ db.read(|c| {
+ Ok(c.query_row(
+ "SELECT poll_interval_secs FROM subscription WHERE pkgbase=?1",
+ params![pkgbase],
+ |r| r.get::<_, Option<i64>>(0),
+ )
+ .optional()?
+ .flatten())
+ })
+}
+
+/// Record a fetched source in the content-addressed cache (§5.3).
+pub fn put_source_cache(writer: &Writer, url: &str, digest: &str, size: u64, path: &str) -> Result<()> {
+ let (u, d, p) = (url.to_string(), digest.to_string(), path.to_string());
+ let at = time::now();
+ writer.tx(move |tx| {
+ tx.execute(
+ "INSERT INTO source_cache (url, digest, size, fetched_at, path) VALUES (?1,?2,?3,?4,?5)
+ ON CONFLICT(url, digest) DO UPDATE SET fetched_at=excluded.fetched_at",
+ params![u, d, size as i64, at, p],
+ )?;
+ Ok(())
+ })
+}
+
+/// Where a cached source with this url+digest lives on disk.
+pub fn source_cache_path(db: &Db, url: &str, digest: &str) -> Result<Option<String>> {
+ db.read(|c| {
+ Ok(c.query_row(
+ "SELECT path FROM source_cache WHERE url=?1 AND digest=?2",
+ params![url, digest],
+ |r| r.get::<_, String>(0),
+ )
+ .optional()?)
+ })
+}
+
+/// An artifact produced by a build, ready to record.
+pub struct NewArtifact<'a> {
+ pub digest: &'a str,
+ pub size: i64,
+ pub path: &'a str,
+ pub signature_path: Option<&'a str>,
+ pub build_log_path: Option<&'a str>,
+ pub build_id: &'a str,
+ pub at: &'a str,
+}
+
+/// Record an artifact produced by a build. Identical bytes are one row: the
+/// digest is the identity, and the row is re-stamped with the build that most
+/// recently produced them.
+pub fn insert_artifact_in(tx: &rusqlite::Transaction<'_>, a: &NewArtifact<'_>) -> Result<()> {
+ tx.execute(
+ "INSERT INTO artifact (digest, size, path, signature_path, build_log_path, build_id, created_at)
+ VALUES (?1,?2,?3,?4,?5,?6,?7)
+ ON CONFLICT(digest) DO UPDATE SET build_id=excluded.build_id",
+ params![a.digest, a.size, a.path, a.signature_path, a.build_log_path, a.build_id, a.at],
+ )?;
+ Ok(())
+}
+
// --------------------------------------------------------- stage B cache --
/// Exact cache hit: same recipe, same upstream tips (§5.2).
@@ -898,6 +1217,215 @@ pub fn list_audit(db: &Db, limit: i64) -> Result<Vec<AuditRow>> {
})
}
+// -------------------------------------------------------------- metrics reads --
+//
+// The metrics surface is derived from live state, never stored (§10.3: a
+// counter that is written is a counter that can drift out of truth). These are
+// the reads that derivation is made of, and they live here because the schema
+// they read lives here.
+
+/// The `count(*)` idiom in one place, so a metric cannot accidentally become a
+/// `count(*)` of a join.
+fn count_rows(db: &Db, sql: &str) -> Result<i64> {
+ let sql = sql.to_string();
+ db.read(move |c| {
+ c.query_row(&sql, [], |r| r.get::<_, i64>(0))
+ .map_err(|e| Error::db(e.to_string()))
+ })
+}
+
+/// `(state, count)` for every build state present.
+pub fn build_state_counts(db: &Db) -> Result<Vec<(String, i64)>> {
+ db.read(|c| {
+ let mut st = c.prepare("SELECT state, count(*) FROM build GROUP BY state ORDER BY state")?;
+ let rows = st.query_map([], |r| Ok((r.get::<_, String>(0)?, r.get::<_, i64>(1)?)))?;
+ let mut out = Vec::new();
+ for r in rows {
+ out.push(r?);
+ }
+ Ok(out)
+ })
+}
+
+/// Seconds the oldest queued build has been waiting; 0 when the queue is empty.
+pub fn oldest_queued_age_secs(db: &Db, now: &str) -> Result<i64> {
+ db.read(|c| {
+ c.query_row(
+ "SELECT julianday(?1) - julianday(min(created_at)) FROM build WHERE state='queued'",
+ params![now],
+ |r| r.get::<_, Option<f64>>(0),
+ )
+ .map(|v| (v.unwrap_or(0.0) * 86400.0) as i64)
+ .map(|v| v.max(0))
+ .map_err(|e| Error::db(e.to_string()))
+ })
+}
+
+/// How many candidates are waiting for a decision.
+pub fn count_pending_reviews(db: &Db) -> Result<i64> {
+ count_rows(db, "SELECT count(*) FROM candidate WHERE state='pending_review'")
+}
+
+/// Age in seconds of every pending review; the caller sorts them.
+pub fn pending_review_ages_secs(db: &Db, now: &str) -> Result<Vec<i64>> {
+ db.read(|c| {
+ let mut st = c.prepare("SELECT julianday(?1) - julianday(detected_at) FROM candidate WHERE state='pending_review'")?;
+ let rows = st.query_map(params![now], |r| r.get::<_, Option<f64>>(0))?;
+ let mut out = Vec::new();
+ for r in rows {
+ out.push((r?.unwrap_or(0.0) * 86400.0) as i64);
+ }
+ Ok(out)
+ })
+}
+
+pub fn count_index_packages(db: &Db) -> Result<i64> {
+ count_rows(db, "SELECT count(*) FROM package WHERE state='in_index'")
+}
+
+pub fn count_published_releases(db: &Db) -> Result<i64> {
+ count_rows(db, "SELECT count(*) FROM release WHERE state='published'")
+}
+
+pub fn count_subscriptions(db: &Db) -> Result<i64> {
+ count_rows(db, "SELECT count(*) FROM subscription")
+}
+
+pub fn count_unacknowledged_notices(db: &Db) -> Result<i64> {
+ count_rows(db, "SELECT count(*) FROM notice WHERE acknowledged_at IS NULL")
+}
+
+/// Bytes of artifact still on disk. Purged rows are history, not usage.
+pub fn artifact_bytes_served(db: &Db) -> Result<u64> {
+ db.read(|c| {
+ c.query_row(
+ "SELECT COALESCE(sum(size),0) FROM artifact WHERE purged_at IS NULL",
+ [],
+ |r| r.get::<_, i64>(0),
+ )
+ .map(|v| v.max(0) as u64)
+ .map_err(|e| Error::db(e.to_string()))
+ })
+}
+
+/// Seconds since the last retention run, if there has been one.
+pub fn last_gc_age_secs(db: &Db, now: &str) -> Result<Option<i64>> {
+ let at = db.read(|c| {
+ c.query_row("SELECT max(ran_at) FROM gc_run", [], |r| r.get::<_, Option<String>>(0))
+ .map_err(|e| Error::db(e.to_string()))
+ })?;
+ Ok(at.and_then(|t| time::delta_secs(now, &t)))
+}
+
+/// Seconds since the last successful poll of any source, if there has been one.
+/// This is the metric that catches a watcher that stopped, which no log line
+/// will tell you about.
+pub fn last_poll_age_secs(db: &Db, now: &str) -> Result<Option<i64>> {
+ let at = db.read(|c| {
+ c.query_row("SELECT max(last_checked_at) FROM subscription", [], |r| r.get::<_, Option<String>>(0))
+ .map_err(|e| Error::db(e.to_string()))
+ })?;
+ Ok(at.and_then(|t| time::delta_secs(now, &t)))
+}
+
+// -------------------------------------------------------------- retention reads --
+
+/// `(pkgbase id, current accepted release)` for every pkgbase, in id order.
+pub fn pkgbase_release_pointers(db: &Db) -> Result<Vec<(i64, Option<i64>)>> {
+ db.read(|c| {
+ let mut st = c.prepare("SELECT id, current_accepted_release_id FROM pkgbase ORDER BY id")?;
+ let rows = st.query_map([], |r| Ok((r.get::<_, i64>(0)?, r.get::<_, Option<i64>>(1)?)))?;
+ let mut out = Vec::new();
+ for r in rows {
+ out.push(r?);
+ }
+ Ok(out)
+ })
+}
+
+/// Published release ids of one pkgbase, newest first.
+pub fn published_release_ids(db: &Db, pkgbase_id: i64) -> Result<Vec<i64>> {
+ db.read(|c| {
+ let mut st = c.prepare("SELECT id FROM release WHERE pkgbase_id=?1 AND state='published' ORDER BY id DESC")?;
+ let rows = st.query_map(params![pkgbase_id], |r| r.get::<_, i64>(0))?;
+ let mut out = Vec::new();
+ for r in rows {
+ out.push(r?);
+ }
+ Ok(out)
+ })
+}
+
+/// Releases of one pkgbase that still back an `in_index` package. Retention must
+/// never evict these: the index is pointing at their bytes right now.
+pub fn serving_release_ids(db: &Db, pkgbase_id: i64) -> Result<Vec<i64>> {
+ db.read(|c| {
+ let mut st = c.prepare(
+ "SELECT DISTINCT r.id FROM release r JOIN package p ON p.release_id=r.id
+ WHERE r.pkgbase_id=?1 AND p.state='in_index' ORDER BY r.id DESC",
+ )?;
+ let rows = st.query_map(params![pkgbase_id], |r| r.get::<_, i64>(0))?;
+ let mut out = Vec::new();
+ for r in rows {
+ out.push(r?);
+ }
+ Ok(out)
+ })
+}
+
+/// The three paths one artifact row points at: the package, its signature and
+/// its build log. Any of them can be absent (an unsigned build, a log that was
+/// already purged).
+pub type ArtifactPaths = (Option<String>, Option<String>, Option<String>);
+
+/// The artifact paths one release holds: package, signature, build log.
+pub fn release_artifact_paths(db: &Db, release_id: i64) -> Result<Vec<ArtifactPaths>> {
+ db.read(|c| {
+ let mut st = c.prepare(
+ "SELECT a.path, a.signature_path, a.build_log_path FROM artifact a
+ JOIN package p ON p.artifact_id = a.id WHERE p.release_id = ?1",
+ )?;
+ let rows = st.query_map(params![release_id], |r| {
+ Ok((r.get::<_, Option<String>>(0)?, r.get::<_, Option<String>>(1)?, r.get::<_, Option<String>>(2)?))
+ })?;
+ let mut out = Vec::new();
+ for r in rows {
+ out.push(r?);
+ }
+ Ok(out)
+ })
+}
+
+/// Mark a release and the artifacts behind it as purged, in one transaction.
+/// Half-marking them would leave the next retention pass believing the files are
+/// still retained.
+pub fn mark_release_purged(writer: &Writer, release_id: i64) -> Result<()> {
+ let at = time::now();
+ writer.tx(move |tx| {
+ tx.execute("UPDATE release SET purged_at=?1 WHERE id=?2", params![at, release_id])?;
+ tx.execute(
+ "UPDATE artifact SET purged_at=?1 WHERE purged_at IS NULL AND id IN
+ (SELECT a.id FROM artifact a JOIN package p ON p.artifact_id=a.id WHERE p.release_id=?2)",
+ params![at, release_id],
+ )?;
+ Ok(())
+ })
+}
+
+/// Record a retention run, which is what the ops page and the `last_gc_age`
+/// metric read.
+pub fn record_gc_run(writer: &Writer, at: &str, kept: i64, evicted: i64, files_removed: i64, bytes_freed: i64, staging_swept: i64) -> Result<()> {
+ let at = at.to_string();
+ writer.tx(move |tx| {
+ tx.execute(
+ "INSERT INTO gc_run (ran_at, releases_kept, releases_evicted, files_removed, bytes_freed, staging_swept)
+ VALUES (?1,?2,?3,?4,?5,?6)",
+ params![at, kept, evicted, files_removed, bytes_freed, staging_swept],
+ )?;
+ Ok(())
+ })
+}
+
// ------------------------------------------------------- invariant helpers --
/// I1: every artifact in a served repo index traces to an approval row.
diff --git a/src/http/routes.rs b/src/http/routes.rs
index abd7345..f4ab2ca 100644
--- a/src/http/routes.rs
+++ b/src/http/routes.rs
@@ -693,20 +693,7 @@ fn package_detail(state: &State, req: &Req, name: &str) -> Res {
published_at: r.published_at.unwrap_or_else(|| "—".into()),
approver: r
.approval_id
- .and_then(|aid| {
- db.read(|c| {
- use rusqlite::OptionalExtension;
- c.query_row(
- "SELECT COALESCE(note,'') FROM approval WHERE id=?1",
- rusqlite::params![aid],
- |r| r.get::<_, String>(0),
- )
- .optional()
- .map_err(Into::into)
- })
- .ok()
- .flatten()
- })
+ .and_then(|aid| db::approval_note(db, aid).ok().filter(|s| !s.is_empty()))
.filter(|s| !s.is_empty())
.unwrap_or_else(|| "—".into()),
})
diff --git a/src/ops.rs b/src/ops.rs
index e211a95..fd644c3 100644
--- a/src/ops.rs
+++ b/src/ops.rs
@@ -176,15 +176,7 @@ pub fn metrics(cfg: &Config, db: &Db) -> Result<Metrics> {
let mut m = Metrics::default();
let now = time::now();
- m.builds = db.read(|c| {
- let mut st = c.prepare("SELECT state, count(*) FROM build GROUP BY state ORDER BY state")?;
- let rows = st.query_map([], |r| Ok((r.get::<_, String>(0)?, r.get::<_, i64>(1)?)))?;
- let mut out = Vec::new();
- for r in rows {
- out.push(r?);
- }
- Ok::<_, crate::error::Error>(out)
- })?;
+ m.builds = db::build_state_counts(db)?;
let count = |state: &str| -> i64 {
m.builds.iter().find(|(s, _)| s == state).map(|(_, n)| *n).unwrap_or(0)
};
@@ -193,33 +185,16 @@ pub fn metrics(cfg: &Config, db: &Db) -> Result<Metrics> {
m.failed = count("failed");
m.blocked_missing_dep = count("blocked_missing_dep");
- let oldest = db.read(|c| {
- c.query_row(
- "SELECT julianday(?1) - julianday(min(created_at)) FROM build WHERE state='queued'",
- rusqlite::params![now],
- |r| r.get::<_, Option<f64>>(0),
- )
- .map(|v| (v.unwrap_or(0.0) * 86400.0) as i64)
- .map_err(|e| crate::error::Error::db(e.to_string()))
- })?;
- m.oldest_queued_age_secs = oldest.max(0);
-
- m.pending_review = scalar(db, "SELECT count(*) FROM candidate WHERE state='pending_review'")?;
- m.review_ages = db.read(|c| {
- let mut st = c.prepare("SELECT julianday(?1) - julianday(detected_at) FROM candidate WHERE state='pending_review'")?;
- let rows = st.query_map(rusqlite::params![now], |r| r.get::<_, Option<f64>>(0))?;
- let mut out = Vec::new();
- for r in rows {
- out.push((r?.unwrap_or(0.0) * 86400.0) as i64);
- }
- Ok::<_, crate::error::Error>(out)
- })?;
+ m.oldest_queued_age_secs = db::oldest_queued_age_secs(db, &now)?;
+
+ m.pending_review = db::count_pending_reviews(db)?;
+ m.review_ages = db::pending_review_ages_secs(db, &now)?;
m.review_ages.sort();
- m.index_packages = scalar(db, "SELECT count(*) FROM package WHERE state='in_index'")?;
- m.releases = scalar(db, "SELECT count(*) FROM release WHERE state='published'")?;
- m.subscriptions = scalar(db, "SELECT count(*) FROM subscription")?;
- m.notices_unseen = scalar(db, "SELECT count(*) FROM notice WHERE acknowledged_at IS NULL")?;
+ m.index_packages = db::count_index_packages(db)?;
+ m.releases = db::count_published_releases(db)?;
+ m.subscriptions = db::count_subscriptions(db)?;
+ m.notices_unseen = db::count_unacknowledged_notices(db)?;
let stale = crate::watch::staleness::stale_rows(db)?;
m.stale_outdated = stale.iter().filter(|s| s.kind == crate::watch::staleness::Kind::Outdated).count() as i64;
@@ -228,31 +203,13 @@ pub fn metrics(cfg: &Config, db: &Db) -> Result<Metrics> {
m.db_bytes = file_len(&cfg.db_path());
m.wal_bytes = file_len(&PathBuf::from(format!("{}-wal", cfg.db_path().display())));
- m.artifact_bytes = db.read(|c| {
- c.query_row(
- "SELECT COALESCE(sum(size),0) FROM artifact WHERE purged_at IS NULL",
- [],
- |r| r.get::<_, i64>(0),
- )
- .map(|v| v.max(0) as u64)
- .map_err(|e| crate::error::Error::db(e.to_string()))
- })?;
+ m.artifact_bytes = db::artifact_bytes_served(db)?;
let (dirs, bytes) = staging_usage(&cfg.staging_dir());
m.staging_dirs = dirs;
m.staging_bytes = bytes;
- m.last_gc_age_secs = db
- .read(|c| {
- c.query_row("SELECT max(ran_at) FROM gc_run", [], |r| r.get::<_, Option<String>>(0))
- .map_err(|e| crate::error::Error::db(e.to_string()))
- })?
- .and_then(|t| time::delta_secs(&now, &t));
- m.poll_lag_age_secs = db
- .read(|c| {
- c.query_row("SELECT max(last_checked_at) FROM subscription", [], |r| r.get::<_, Option<String>>(0))
- .map_err(|e| crate::error::Error::db(e.to_string()))
- })?
- .and_then(|t| time::delta_secs(&now, &t));
+ m.last_gc_age_secs = db::last_gc_age_secs(db, &now)?;
+ m.poll_lag_age_secs = db::last_poll_age_secs(db, &now)?;
let _ = cfg;
Ok(m)
}
@@ -263,11 +220,6 @@ fn header(name: &str, help: &str) -> String {
format!("# HELP {name} {help}\n# TYPE {name} gauge\n")
}
-fn scalar(db: &Db, sql: &str) -> Result<i64> {
- let sql = sql.to_string();
- db.read(move |c| c.query_row(&sql, [], |r| r.get::<_, i64>(0)).map_err(|e| crate::error::Error::db(e.to_string())))
-}
-
fn file_len(p: &Path) -> u64 {
std::fs::metadata(p).map(|m| m.len()).unwrap_or(0)
}
@@ -310,44 +262,15 @@ fn dir_bytes(path: &Path) -> u64 {
/// package is not optional.
pub fn plan_retention(db: &Db, keep: usize) -> Result<(Vec<i64>, Vec<EvictPlan>)> {
let keep = keep.max(1);
- let pkgbases: Vec<(i64, Option<i64>)> = db.read(|c| {
- let mut st = c.prepare("SELECT id, current_accepted_release_id FROM pkgbase ORDER BY id")?;
- let rows = st.query_map([], |r| Ok((r.get::<_, i64>(0)?, r.get::<_, Option<i64>>(1)?)))?;
- let mut out = Vec::new();
- for r in rows {
- out.push(r?);
- }
- Ok::<_, crate::error::Error>(out)
- })?;
+ let pkgbases = db::pkgbase_release_pointers(db)?;
let mut kept = Vec::new();
let mut evict = Vec::new();
for (pb_id, accepted) in pkgbases {
- let releases: Vec<i64> = db.read(|c| {
- let mut st = c.prepare(
- "SELECT id FROM release WHERE pkgbase_id=?1 AND state='published' ORDER BY id DESC",
- )?;
- let rows = st.query_map(rusqlite::params![pb_id], |r| r.get::<_, i64>(0))?;
- let mut out = Vec::new();
- for r in rows {
- out.push(r?);
- }
- Ok::<_, crate::error::Error>(out)
- })?;
+ let releases = db::published_release_ids(db, pb_id)?;
// Still in the index? Then it is being served and is not a candidate for
// eviction no matter how old it is.
- let serving: Vec<i64> = db.read(|c| {
- let mut st = c.prepare(
- "SELECT DISTINCT r.id FROM release r JOIN package p ON p.release_id=r.id
- WHERE r.pkgbase_id=?1 AND p.state='in_index' ORDER BY r.id DESC",
- )?;
- let rows = st.query_map(rusqlite::params![pb_id], |r| r.get::<_, i64>(0))?;
- let mut out = Vec::new();
- for r in rows {
- out.push(r?);
- }
- Ok::<_, crate::error::Error>(out)
- })?;
+ let serving = db::serving_release_ids(db, pb_id)?;
let mut keep_set: std::collections::BTreeSet<i64> = serving.iter().cloned().collect();
if let Some(a) = accepted {
@@ -380,7 +303,7 @@ pub struct EvictPlan {
/// one cached archive; deleting it because one release aged out would corrupt a
/// release that is still current.
pub fn retention(cfg: &Config, db: &Db, keep: Option<usize>) -> Result<RetentionReport> {
- let keep = keep.unwrap_or_else(|| setting_usize(db, "retention_versions", DEFAULT_KEEP));
+ let keep = keep.unwrap_or_else(|| db::setting_i64(db, "retention_versions", DEFAULT_KEEP as i64) as usize);
let (kept, evict) = plan_retention(db, keep)?;
// Everything still held by a kept release, so we do not evict a shared file.
@@ -411,7 +334,7 @@ pub fn retention(cfg: &Config, db: &Db, keep: Option<usize>) -> Result<Retention
report.bytes_freed += freed;
if removed > 0 || !files.is_empty() {
report.releases_evicted += 1;
- mark_purged(db, e.release_id)?;
+ db::mark_release_purged(&db.writer, e.release_id)?;
}
}
@@ -452,43 +375,16 @@ pub const STAGING_GRACE_SECS: i64 = 3600;
/// is how a store ends up full of orphans and empty of answers.
pub fn release_files(cfg: &Config, db: &Db, release_id: i64) -> Result<Vec<PathBuf>> {
let mut out = Vec::new();
- let rows: Vec<(Option<String>, Option<String>, Option<String>)> = db.read(|c| {
- let mut st = c.prepare(
- "SELECT a.path, a.signature_path, a.build_log_path FROM artifact a
- JOIN package p ON p.artifact_id = a.id WHERE p.release_id = ?1",
- )?;
- let rows = st.query_map(rusqlite::params![release_id], |r| {
- Ok((r.get::<_, Option<String>>(0)?, r.get::<_, Option<String>>(1)?, r.get::<_, Option<String>>(2)?))
- })?;
- let mut out = Vec::new();
- for r in rows {
- out.push(r?);
- }
- Ok::<_, crate::error::Error>(out)
- })?;
- for (path, sig, log) in rows {
- if let Some(p) = path {
- out.push(PathBuf::from(p));
- }
- if let Some(p) = sig {
- out.push(PathBuf::from(p));
- }
- if let Some(p) = log {
+ for (path, sig, log) in db::release_artifact_paths(db, release_id)? {
+ for p in [path, sig, log].into_iter().flatten() {
out.push(PathBuf::from(p));
}
}
// Cached sources, by content digest (§5.1a: the mirror and the source cache
// are what make an old release rebuildable).
- let digests: String = db
- .read(|c| {
- c.query_row(
- "SELECT source_digests_json FROM release WHERE id=?1",
- rusqlite::params![release_id],
- |r| r.get::<_, String>(0),
- )
- .map_err(|e| crate::error::Error::db(e.to_string()))
- })
- .unwrap_or_else(|_| "[]".into());
+ let digests = db::release_by_id(db, release_id)?
+ .map(|r| r.source_digests_json)
+ .unwrap_or_else(|| "[]".into());
if let Ok(list) = serde_json::from_str::<Vec<db::SourceDigest>>(&digests) {
for d in list {
if !d.digest.is_empty() {
@@ -499,22 +395,6 @@ pub fn release_files(cfg: &Config, db: &Db, release_id: i64) -> Result<Vec<PathB
Ok(out)
}
-fn mark_purged(db: &Db, release_id: i64) -> Result<()> {
- let at = time::now();
- db.writer.tx(move |tx| {
- tx.execute(
- "UPDATE release SET purged_at=?1 WHERE id=?2",
- rusqlite::params![at, release_id],
- )?;
- tx.execute(
- "UPDATE artifact SET purged_at=?1 WHERE purged_at IS NULL AND id IN
- (SELECT a.id FROM artifact a JOIN package p ON p.artifact_id=a.id WHERE p.release_id=?2)",
- rusqlite::params![at, release_id],
- )?;
- Ok(())
- })
-}
-
/// Remove staging directories whose build is finished or unknown (§8.2: staging
/// is disposable, and a GC pass sweeps what was abandoned).
///
@@ -536,14 +416,7 @@ pub fn sweep_staging(cfg: &Config, db: &Db, grace_secs: i64) -> Result<(usize, u
let Some(build_id) = path.file_name().map(|s| s.to_string_lossy().to_string()) else {
continue;
};
- let state: Option<String> = db
- .read(|c| {
- Ok(c.query_row("SELECT state FROM build WHERE id=?1", rusqlite::params![build_id], |r| {
- r.get::<_, String>(0)
- })
- .ok())
- })
- .unwrap_or(None);
+ let state = db::builds::get(db, &build_id)?.map(|b| b.state);
let abandonable = match &state {
// No build row: staging left over from a crash before the row was
// written, or from a build id that no longer exists.
@@ -575,32 +448,15 @@ fn dir_age_secs(path: &Path) -> Option<i64> {
}
fn record_run(db: &Db, r: &RetentionReport) -> Result<()> {
- let at = time::now();
- let (kept, evicted, files, bytes, swept) = (
+ db::record_gc_run(
+ &db.writer,
+ &time::now(),
r.releases_kept as i64,
r.releases_evicted as i64,
r.files_removed as i64,
r.bytes_freed as i64,
r.staging_swept as i64,
- );
- db.writer.tx(move |tx| {
- tx.execute(
- "INSERT INTO gc_run (ran_at, releases_kept, releases_evicted, files_removed, bytes_freed, staging_swept)
- VALUES (?1,?2,?3,?4,?5,?6)",
- rusqlite::params![at, kept, evicted, files, bytes, swept],
- )?;
- Ok(())
- })
-}
-
-fn setting_usize(db: &Db, key: &str, default: usize) -> usize {
- db.read(|c| {
- Ok(c.query_row("SELECT value FROM settings WHERE key=?1", rusqlite::params![key], |r| r.get::<_, String>(0)).ok())
- })
- .ok()
- .flatten()
- .and_then(|v| v.parse().ok())
- .unwrap_or(default)
+ )
}
/// A consistent snapshot of the database, written to `dest`.
@@ -623,19 +479,11 @@ pub fn backup(db: &Db, dest: &Path) -> Result<PathBuf> {
std::fs::create_dir_all(parent)?;
}
}
- let sql = format!("VACUUM INTO '{}'", dest.display().to_string().replace('\'', "''"));
- db.writer.call(move |conn| {
- conn.execute_batch(&sql)
- .map_err(|e| crate::error::Error::db(format!("VACUUM INTO: {e}")))?;
- Ok(())
- })?;
+ db::backup_to(&db.writer, &dest)?;
// The snapshot must be readable on its own: if it does not open and report
// the same schema version, the backup is a file, not a backup.
- let probe = rusqlite::Connection::open(&dest)
+ let version = db::schema_version(&dest)
.map_err(|e| crate::error::Error::db(format!("backup unreadable: {e}")))?;
- let version: i64 = probe
- .query_row("PRAGMA user_version", [], |r| r.get(0))
- .map_err(|e| crate::error::Error::db(format!("backup has no schema: {e}")))?;
if version <= 0 {
return Err(crate::error::Error::db("backup does not contain a migrated database"));
}
diff --git a/src/pipeline/mod.rs b/src/pipeline/mod.rs
index 8f4012e..279ec0f 100644
--- a/src/pipeline/mod.rs
+++ b/src/pipeline/mod.rs
@@ -304,13 +304,7 @@ pub fn enqueue_manual_rebuild(cfg: &Config, db: &Db, pkgbase: &str) -> Result<St
builds::enqueue(db, &id, pb.id, None, "manual_rebuild", Some(world_id), &cfg.build_profile, 1)?;
let id_for_tx = id.clone();
let rid = rel.id;
- db.writer.tx(move |tx| {
- tx.execute(
- "UPDATE build SET release_id=?1 WHERE id=?2",
- rusqlite::params![rid, id_for_tx],
- )?;
- Ok(())
- })?;
+ db.writer.tx(move |tx| builds::set_release_in(tx, &id_for_tx, rid))?;
Ok(id)
}
diff --git a/src/pipeline/publish.rs b/src/pipeline/publish.rs
index d54314e..ab0cb87 100644
--- a/src/pipeline/publish.rs
+++ b/src/pipeline/publish.rs
@@ -11,10 +11,8 @@ use std::path::{Path, PathBuf};
use std::process::Command;
use std::sync::Mutex;
-use rusqlite::OptionalExtension;
-
use crate::config::Config;
-use crate::db::{self, builds, Db, WorldMember};
+use crate::db::{self, builds, candidate_state, candidates, Db, WorldMember};
use crate::error::{Error, Result};
use crate::pipeline::{Collect, Ctx};
use crate::time;
@@ -43,12 +41,7 @@ fn index_artifacts(db: &Db, extra: &[PathBuf]) -> Result<Vec<PathBuf>> {
let mut out: Vec<PathBuf> = Vec::new();
for p in db::index_packages(db)? {
if let Some(aid) = p.artifact_id {
- let path: Option<String> = db.read(|c| {
- use rusqlite::OptionalExtension;
- Ok(c.query_row("SELECT path FROM artifact WHERE id=?1", rusqlite::params![aid], |r| r.get(0))
- .optional()?)
- })?;
- if let Some(p) = path.map(PathBuf::from).filter(|p| p.exists()) {
+ if let Some(p) = db::artifact_path(db, aid)?.map(PathBuf::from).filter(|p| p.exists()) {
out.push(p);
}
}
@@ -205,11 +198,7 @@ fn commit_release(ctx: &Ctx, collect: &Collect) -> Result<i64> {
ctx.db.writer.tx(move |tx| {
// Compare-and-swap on the accepted pointer, inside the write
// transaction: two publishes cannot both land (I4).
- let actual_base: Option<i64> = tx.query_row(
- "SELECT current_accepted_release_id FROM pkgbase WHERE id=?1",
- rusqlite::params![pkgbase_id],
- |r| r.get(0),
- )?;
+ let actual_base = db::accepted_pointer_in(tx, pkgbase_id)?;
if actual_base != expected_base {
return Err(Error::conflict(
"accepted pointer moved while this build was running; refusing to publish",
@@ -217,52 +206,36 @@ fn commit_release(ctx: &Ctx, collect: &Collect) -> Result<i64> {
}
// Retire whatever the index held for these names *before* inserting the
// new rows: the index holds exactly the accepted pointer, nothing else.
- if !names.is_empty() {
- let ph = names.iter().map(|_| "?").collect::<Vec<_>>().join(",");
- let sql = format!(
- "UPDATE package SET state='removed' WHERE state='in_index' AND name IN ({ph})"
- );
- let mut stmt = tx.prepare(&sql)?;
- stmt.execute(rusqlite::params_from_iter(names.iter().map(|n| n as &dyn rusqlite::ToSql)))?;
- }
- tx.execute(
- "INSERT INTO release (pkgbase_id, candidate_id, approval_id, aur_commit, recipe_hash,
- upstream_pins_json, source_digests_json, epoch, pkgver, pkgrel,
- world_snapshot_id, state, build_id, published_at, created_at)
- VALUES (?1,?2,?3,?4,?5,?6,?7,?8,?9,?10,?11,'published',?12,?13,?13)",
- rusqlite::params![
- pkgbase_id, candidate_id, approval_id, src.aur_commit, src.recipe_hash,
- src.upstream_pins_json, src.source_digests_json, src.epoch, src.pkgver, src.pkgrel,
- world_id, build_id, at
- ],
+ db::remove_index_packages_in(tx, &names)?;
+ let release_id = db::insert_release_in(
+ tx,
+ &db::NewRelease {
+ pkgbase_id,
+ candidate_id,
+ approval_id: Some(approval_id),
+ aur_commit: &src.aur_commit,
+ recipe_hash: &src.recipe_hash,
+ upstream_pins_json: &src.upstream_pins_json,
+ source_digests_json: &src.source_digests_json,
+ epoch: &src.epoch,
+ pkgver: &src.pkgver,
+ pkgrel: &src.pkgrel,
+ world_snapshot_id: world_id,
+ build_id: &build_id,
+ },
+ &at,
)?;
- let release_id = tx.last_insert_rowid();
for p in &packages {
- let artifact_id: Option<i64> = tx
- .query_row(
- "SELECT id FROM artifact WHERE digest=?1",
- rusqlite::params![p.digest],
- |r| r.get(0),
- )
- .optional()?;
- tx.execute(
- "INSERT INTO package (repo_id, release_id, name, arch, version, artifact_id, state)
- VALUES (?1,?2,?3,?4,?5,?6,'in_index')",
- rusqlite::params![repo_id, release_id, p.name, p.arch, p.version, artifact_id],
- )?;
+ db::insert_package_in(tx, repo_id, release_id, &p.name, &p.arch, &p.version, &p.digest)?;
}
- let moved = tx.execute(
- "UPDATE pkgbase SET current_accepted_release_id=?1 WHERE id=?2 AND current_accepted_release_id IS ?3",
- rusqlite::params![release_id, pkgbase_id, expected_base],
- )?;
- if moved != 1 {
+ if !db::cas_accepted_release_in(tx, pkgbase_id, release_id, expected_base)? {
return Err(Error::conflict(
"accepted pointer moved while this build was running; refusing to publish",
));
}
- tx.execute("UPDATE build SET release_id=?1 WHERE id=?2", rusqlite::params![release_id, build_id])?;
+ builds::set_release_in(tx, &build_id, release_id)?;
if let Some(cid) = candidate_id {
- tx.execute("UPDATE candidate SET state='approved' WHERE id=?1", rusqlite::params![cid])?;
+ candidates::resolve_in(tx, cid, candidate_state::APPROVED, &at)?;
}
Ok(release_id)
})
@@ -366,12 +339,7 @@ pub fn reconcile(cfg: &Config, db: &Db) -> Result<usize> {
let mut files = Vec::new();
for p in &pkgs {
if let Some(aid) = p.artifact_id {
- let path: Option<String> = db.read(|c| {
- use rusqlite::OptionalExtension;
- Ok(c.query_row("SELECT path FROM artifact WHERE id=?1", rusqlite::params![aid], |r| r.get(0))
- .optional()?)
- })?;
- if let Some(path) = path.map(PathBuf::from).filter(|p| p.exists()) {
+ if let Some(path) = db::artifact_path(db, aid)?.map(PathBuf::from).filter(|p| p.exists()) {
let arch_dir = cfg.repo_arch_dir();
let _ = std::fs::create_dir_all(&arch_dir);
let dest = arch_dir.join(format!("{}-{}-{}.pkg.tar.zst", p.name, p.version, p.arch));
@@ -397,13 +365,7 @@ pub fn withdraw_package(cfg: &Config, db: &Db, name: &str) -> Result<()> {
let _guard = REPO_LOCK.lock().unwrap_or_else(|e| e.into_inner());
let rid = db::repo_id(db)?;
let n = name.to_string();
- db.writer.tx(move |tx| {
- tx.execute(
- "UPDATE package SET state='removed' WHERE repo_id=?1 AND name=?2",
- rusqlite::params![rid, n],
- )?;
- Ok(())
- })?;
+ db.writer.tx(move |tx| db::remove_package_by_name_in(tx, rid, &n))?;
let arch_dir = cfg.repo_arch_dir();
let tmp = arch_dir.join(format!("{}.tar.gz.tmp", cfg.repo_db_name()));
let files = index_artifacts(db, &[])?;
diff --git a/src/pipeline/steps.rs b/src/pipeline/steps.rs
index 6bdf12c..033093b 100644
--- a/src/pipeline/steps.rs
+++ b/src/pipeline/steps.rs
@@ -390,11 +390,17 @@ fn ingest(ctx: &Ctx) -> Result<StepResult> {
let log_path = ctx.log.display().to_string();
ctx.db.writer.tx(move |tx| {
for p in &packages_for_db {
- tx.execute(
- "INSERT INTO artifact (digest, size, path, signature_path, build_log_path, build_id, created_at)
- VALUES (?1,?2,?3,?4,?5,?6,?7)
- ON CONFLICT(digest) DO UPDATE SET build_id=excluded.build_id",
- rusqlite::params![p.digest, p.size as i64, p.path, p.signature_path, log_path, build_id, at],
+ db::insert_artifact_in(
+ tx,
+ &db::NewArtifact {
+ digest: &p.digest,
+ size: p.size as i64,
+ path: &p.path,
+ signature_path: p.signature_path.as_deref(),
+ build_log_path: Some(&log_path),
+ build_id: &build_id,
+ at: &at,
+ },
)?;
}
Ok(())
diff --git a/src/review/approve.rs b/src/review/approve.rs
index 0fdf2b2..704166c 100644
--- a/src/review/approve.rs
+++ b/src/review/approve.rs
@@ -5,9 +5,7 @@
//! rendered; if either has moved under the reviewer, the approval is refused
//! with a conflict (HTTP 409) and a re-render, never silently retargeted.
-use rusqlite::OptionalExtension;
-
-use crate::db::{self, *};
+use crate::db::{self, approvals, candidate_state, candidates, *};
use crate::error::{Error, Result};
use crate::time;
@@ -68,78 +66,54 @@ pub fn approve(
let at = time::now();
db.writer.tx(move |tx| -> Result<std::result::Result<Approval, Stale>> {
- type CandidateState = (i64, String, String, Option<i64>, Option<i64>, String, String);
- let row: Option<CandidateState> = tx
- .query_row(
- "SELECT c.id, c.state, c.identity_hash, c.base_release_id, p.current_accepted_release_id,
- c.risk_level, p.name
- FROM candidate c JOIN pkgbase p ON p.id = c.pkgbase_id
- WHERE c.id = ?1",
- rusqlite::params![candidate_id],
- |r| {
- Ok((
- r.get(0)?,
- r.get(1)?,
- r.get(2)?,
- r.get(3)?,
- r.get(4)?,
- r.get(5)?,
- r.get(6)?,
- ))
- },
- )
- .optional()?;
- let (id, state, actual_identity, base, current_base, risk, _pkgbase) =
- row.ok_or_else(|| Error::not_found(format!("candidate {candidate_id}")))?;
+ let subject = candidates::review_subject_in(tx, candidate_id)?
+ .ok_or_else(|| Error::not_found(format!("candidate {candidate_id}")))?;
+ let id = subject.id;
+ let base = subject.base_release_id;
+ let current_base = subject.current_base_release_id;
// 1. still open
- if state != candidate_state::PENDING {
- return Ok(Err(Stale::NotPending { state }));
+ if subject.state != candidate_state::PENDING {
+ return Ok(Err(Stale::NotPending { state: subject.state }));
}
// 2. same candidate bytes
- if actual_identity != ih {
- return Ok(Err(Stale::Identity { expected: ih.clone(), actual: actual_identity }));
+ if subject.identity_hash != ih {
+ return Ok(Err(Stale::Identity { expected: ih.clone(), actual: subject.identity_hash }));
}
// 3. same rendered diff
- let stored_diff: String = tx.query_row(
- "SELECT diff_digest FROM candidate WHERE id=?1",
- rusqlite::params![id],
- |r| r.get(0),
- )?;
- if stored_diff != dd {
- return Ok(Err(Stale::Diff { expected: dd.clone(), actual: stored_diff }));
+ if subject.diff_digest != dd {
+ return Ok(Err(Stale::Diff { expected: dd.clone(), actual: subject.diff_digest }));
}
// 4. base is still the accepted release (I2, end to end)
if base != current_base {
return Ok(Err(Stale::Base { expected: base, actual: current_base }));
}
- tx.execute(
- "INSERT INTO approval (candidate_id, base_release_id, decided_at, decision, risk_level,
- diff_digest, identity_hash, note)
- VALUES (?1,?2,?3,'approved',?4,?5,?6,?7)",
- rusqlite::params![id, base, at, risk, dd, ih, note],
- )?;
- let approval_id = tx.last_insert_rowid();
- tx.execute(
- "UPDATE candidate SET state='approved', resolved_at=?1 WHERE id=?2",
- rusqlite::params![at, id],
- )?;
- let pkgbase_id: i64 = tx.query_row(
- "SELECT pkgbase_id FROM candidate WHERE id=?1",
- rusqlite::params![id],
- |r| r.get(0),
+ let approval_id = approvals::record_in(
+ tx,
+ &approvals::Decision {
+ candidate_id: id,
+ base_release_id: base,
+ at: &at,
+ decision: "approved",
+ risk_level: &subject.risk_level,
+ diff_digest: &dd,
+ identity_hash: &ih,
+ note: note.as_deref(),
+ },
)?;
- tx.execute(
- "INSERT INTO audit (at, actor_kind, actor, action, entity, entity_id, detail_json)
- VALUES (?1,'human',?2,'approve','candidate',?3,?4)",
- rusqlite::params![
- at,
- actor,
- id.to_string(),
- serde_json::json!({"approval": approval_id, "identity": ih, "pkgbase_id": pkgbase_id})
- .to_string()
- ],
+ candidates::resolve_in(tx, id, candidate_state::APPROVED, &at)?;
+ db::audit_in(
+ tx,
+ &db::AuditEntry {
+ at: &at,
+ actor_kind: "human",
+ actor: &actor,
+ action: "approve",
+ entity: "candidate",
+ entity_id: &id.to_string(),
+ detail: serde_json::json!({"approval": approval_id, "identity": ih, "pkgbase_id": subject.pkgbase_id}),
+ },
)?;
Ok(Ok(Approval {
id: approval_id,
@@ -160,33 +134,26 @@ pub fn reject(db: &Db, actor: &str, candidate_id: i64, note: &str) -> Result<()>
let note = note.to_string();
let at = time::now();
db.writer.tx(move |tx| {
- let state: String = tx
- .query_row("SELECT state FROM candidate WHERE id=?1", rusqlite::params![candidate_id], |r| r.get(0))
- .optional()?
+ let state = candidates::state_in(tx, candidate_id)?
.ok_or_else(|| Error::not_found(format!("candidate {candidate_id}")))?;
if state != candidate_state::PENDING {
return Err(Error::conflict(format!("candidate is {state}, not pending")));
}
- let identity: String = tx.query_row(
- "SELECT identity_hash FROM candidate WHERE id=?1",
- rusqlite::params![candidate_id],
- |r| r.get(0),
- )?;
- tx.execute(
- "INSERT INTO approval (candidate_id, base_release_id, decided_at, decision, risk_level,
- diff_digest, identity_hash, note)
- SELECT id, base_release_id, ?1, 'rejected', risk_level, diff_digest, ?2, ?3
- FROM candidate WHERE id=?4",
- rusqlite::params![at, identity, note, candidate_id],
- )?;
- tx.execute(
- "UPDATE candidate SET state='rejected', resolved_at=?1 WHERE id=?2",
- rusqlite::params![at, candidate_id],
- )?;
- tx.execute(
- "INSERT INTO audit (at, actor_kind, actor, action, entity, entity_id, detail_json)
- VALUES (?1,'human',?2,'reject','candidate',?3,?4)",
- rusqlite::params![at, actor, candidate_id.to_string(), serde_json::json!({"note": note}).to_string()],
+ let identity = candidates::identity_in(tx, candidate_id)?
+ .ok_or_else(|| Error::not_found(format!("candidate {candidate_id}")))?;
+ approvals::record_rejection_in(tx, candidate_id, &at, &identity, &note)?;
+ candidates::resolve_in(tx, candidate_id, candidate_state::REJECTED, &at)?;
+ db::audit_in(
+ tx,
+ &db::AuditEntry {
+ at: &at,
+ actor_kind: "human",
+ actor: &actor,
+ action: "reject",
+ entity: "candidate",
+ entity_id: &candidate_id.to_string(),
+ detail: serde_json::json!({"note": note}),
+ },
)?;
Ok(())
})
@@ -202,15 +169,7 @@ pub fn bulk(
) -> Result<Vec<std::result::Result<Approval, Stale>>> {
let mut out = Vec::new();
for (id, ih, dd) in items {
- let risk: String = db.read(|c| {
- Ok(c.query_row(
- "SELECT risk_level FROM candidate WHERE id=?1",
- rusqlite::params![id],
- |r| r.get(0),
- )
- .optional()?)
- })?
- .unwrap_or_default();
+ let risk = candidates::risk_level(db, *id)?.unwrap_or_default();
if decision == "approve" && risk == "high" && !confirm_high_risk {
out.push(Err(Stale::NotPending {
state: "high-risk: needs individual confirmation".into(),
@@ -230,14 +189,7 @@ pub fn bulk(
/// The approval behind a candidate, if any.
pub fn approval_for(db: &Db, candidate_id: i64) -> Result<Option<(i64, String)>> {
- db.read(|c| {
- Ok(c.query_row(
- "SELECT id, decision FROM approval WHERE candidate_id=?1",
- rusqlite::params![candidate_id],
- |r| Ok((r.get(0)?, r.get(1)?)),
- )
- .optional()?)
- })
+ approvals::for_candidate(db, candidate_id)
}
/// Withdraw a published release (§9 `repo-remove` path, decision 23: warns,
@@ -247,15 +199,18 @@ pub fn withdraw(db: &Db, actor: &str, release_id: i64, reason: &str) -> Result<(
let reason = reason.to_string();
let at = time::now();
db.writer.tx(move |tx| {
- tx.execute("UPDATE release SET state='withdrawn' WHERE id=?1", rusqlite::params![release_id])?;
- tx.execute(
- "UPDATE package SET state='removed' WHERE release_id=?1",
- rusqlite::params![release_id],
- )?;
- tx.execute(
- "INSERT INTO audit (at, actor_kind, actor, action, entity, entity_id, detail_json)
- VALUES (?1,'human',?2,'withdraw','release',?3,?4)",
- rusqlite::params![at, actor, release_id.to_string(), serde_json::json!({"reason": reason}).to_string()],
+ db::withdraw_release_in(tx, release_id)?;
+ db::audit_in(
+ tx,
+ &db::AuditEntry {
+ at: &at,
+ actor_kind: "human",
+ actor: &actor,
+ action: "withdraw",
+ entity: "release",
+ entity_id: &release_id.to_string(),
+ detail: serde_json::json!({"reason": reason}),
+ },
)?;
Ok(())
})
diff --git a/src/review/candidates.rs b/src/review/candidates.rs
index 566434b..7cedf4b 100644
--- a/src/review/candidates.rs
+++ b/src/review/candidates.rs
@@ -5,23 +5,18 @@
//! fixed at creation to the pkgbase's `current_accepted_release` — that is what
//! makes "diff against the last accepted version, never the last seen one" (I2)
//! true no matter how many detections arrive while nobody is looking.
+//!
+//! This module is the *rule*, not the SQL: every statement it needs lives in
+//! `db::candidates` and is called through the transaction handle, so the whole
+//! decision is atomic and the schema still has one owner.
-use rusqlite::OptionalExtension;
-
-use crate::db::{self, *};
+use crate::db::{self, candidates as sql, Db, Pkgbase, ReleaseRow};
use crate::error::Result;
-use crate::time;
-#[derive(Debug, Clone)]
-pub struct NewCandidate {
- 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 use crate::db::candidates::{
+ all as all_candidates, by_id as candidate_by_id, mark_viewed, open_reviews_for, pending as pending_candidates,
+ reopen_rejected, set_diff_digest, set_missing_deps, set_risk, NewCandidate,
+};
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Upsert {
@@ -43,267 +38,41 @@ pub enum Upsert {
/// `accepted` is the pkgbase's current accepted release, or `None` when this is
/// a first introduction (§7.1b).
pub fn upsert_candidate(db: &Db, pb: &Pkgbase, accepted: Option<&ReleaseRow>, nc: &NewCandidate) -> Result<Upsert> {
- let kind = if accepted.is_some() { candidate_kind::NEW_VERSION } else { candidate_kind::FIRST_INTRODUCTION };
+ let kind = if accepted.is_some() { db::candidate_kind::NEW_VERSION } else { db::candidate_kind::FIRST_INTRODUCTION };
let base = accepted.map(|a| a.id);
let pkgbase_id = pb.id;
let nc = nc.clone();
db.writer.tx(move |tx| {
- let existing: Option<(i64, String, Option<String>, i64)> = tx
- .query_row(
- "SELECT id, identity_hash, viewed_at, revision FROM candidate
- WHERE pkgbase_id=?1 AND state='pending_review'",
- rusqlite::params![pkgbase_id],
- |r| Ok((r.get(0)?, r.get(1)?, r.get(2)?, r.get(3)?)),
- )
- .optional()?;
-
- if let Some((id, identity, viewed, revision)) = existing {
- if identity == nc.identity_hash {
+ if let Some(open) = sql::open_in(tx, pkgbase_id)? {
+ if open.identity_hash == nc.identity_hash {
return Ok(Upsert::Unchanged);
}
- if viewed.is_none() {
+ if !open.viewed() {
// Collapse in place: same base, no new row, revision bumped.
- tx.execute(
- "UPDATE candidate SET snapshot_id=?1, epoch=?2, pkgver=?3, pkgrel=?4,
- upstream_pins_json=?5, source_digests_json=?6, identity_hash=?7,
- revision=?8, detected_at=?9, diff_digest=''
- WHERE id=?10",
- rusqlite::params![
- nc.snapshot_id, nc.epoch, nc.pkgver, nc.pkgrel,
- nc.upstream_pins_json, nc.source_digests_json, nc.identity_hash,
- revision + 1, time::now(), id
- ],
- )?;
- return Ok(Upsert::Collapsed { id, revision: revision + 1 });
+ let revision = sql::collapse_in(tx, &open, &nc)?;
+ return Ok(Upsert::Collapsed { id: open.id, revision });
}
// A human saw the old diff: freeze it for the audit trail and open a
// fresh review against the same base.
- tx.execute(
- "UPDATE candidate SET state='superseded', resolved_at=?1 WHERE id=?2",
- rusqlite::params![time::now(), id],
- )?;
- let new_id = insert(tx, pkgbase_id, base, kind, &nc)?;
- return Ok(Upsert::Superseded { old: id, new: new_id });
+ sql::supersede_in(tx, open.id)?;
+ let new_id = sql::insert_in(tx, pkgbase_id, base, kind, &nc)?;
+ return Ok(Upsert::Superseded { old: open.id, new: new_id });
}
// No open review. A previously rejected identity must not be re-raised.
- let rejected: Option<i64> = tx
- .query_row(
- "SELECT id FROM candidate WHERE pkgbase_id=?1 AND identity_hash=?2 AND state='rejected'
- ORDER BY id DESC LIMIT 1",
- rusqlite::params![pkgbase_id, nc.identity_hash],
- |r| r.get(0),
- )
- .optional()?;
- if rejected.is_some() {
+ if sql::rejected_before_in(tx, pkgbase_id, &nc.identity_hash)? {
return Ok(Upsert::PreviouslyRejected);
}
// Same identity already approved/recorded: nothing to do.
- let same: Option<i64> = tx
- .query_row(
- "SELECT id FROM candidate WHERE pkgbase_id=?1 AND identity_hash=?2
- ORDER BY id DESC LIMIT 1",
- rusqlite::params![pkgbase_id, nc.identity_hash],
- |r| r.get(0),
- )
- .optional()?;
- if same.is_some() {
+ if sql::recorded_before_in(tx, pkgbase_id, &nc.identity_hash)? {
return Ok(Upsert::Unchanged);
}
- let id = insert(tx, pkgbase_id, base, kind, &nc)?;
+ let id = sql::insert_in(tx, pkgbase_id, base, kind, &nc)?;
Ok(Upsert::Created { id, kind: kind.to_string() })
})
}
-fn insert(
- tx: &mut rusqlite::Transaction<'_>,
- pkgbase_id: i64,
- base: Option<i64>,
- kind: &str,
- nc: &NewCandidate,
-) -> Result<i64> {
- tx.execute(
- "INSERT INTO candidate (pkgbase_id, base_release_id, kind, snapshot_id, epoch, pkgver, pkgrel,
- upstream_pins_json, source_digests_json, identity_hash, state, detected_at)
- VALUES (?1,?2,?3,?4,?5,?6,?7,?8,?9,?10,'pending_review',?11)",
- rusqlite::params![
- pkgbase_id, base, kind, nc.snapshot_id, nc.epoch, nc.pkgver, nc.pkgrel,
- nc.upstream_pins_json, nc.source_digests_json, nc.identity_hash, time::now()
- ],
- )?;
- Ok(tx.last_insert_rowid())
-}
-
-impl NewCandidate {
- /// The `epoch:pkgver-pkgrel` this candidate would publish.
- pub fn version(&self) -> String {
- crate::pkgver::full_version(&self.epoch, &self.pkgver, &self.pkgrel)
- }
-}
-
-/// Every candidate regardless of state, newest first (`aur-build reviews --all`).
-pub fn all_candidates(db: &Db) -> Result<Vec<CandidateRow>> {
- db.read(|c| {
- let mut stmt = c.prepare(
- "SELECT c.id, c.pkgbase_id, c.base_release_id, c.kind, c.snapshot_id, c.epoch, c.pkgver,
- c.pkgrel, c.upstream_pins_json, c.source_digests_json, c.identity_hash,
- c.diff_digest, c.revision, c.viewed_at, c.risk_level, c.risk_signals_json,
- c.missing_deps_json, c.state, c.detected_at, c.resolved_at, b.name
- FROM candidate c JOIN pkgbase b ON b.id = c.pkgbase_id
- ORDER BY c.detected_at DESC LIMIT 500",
- )?;
- let rows = stmt.query_map([], row_to_candidate)?;
- let mut out = Vec::new();
- for r in rows {
- out.push(r?);
- }
- Ok(out)
- })
-}
-
-/// Mark a candidate `viewed` the first time a human opens it. That timestamp is
-/// what decides whether a later detection collapses or supersedes (§7.1).
-pub fn mark_viewed(db: &Db, id: i64) -> Result<()> {
- let at = time::now();
- db.writer.tx(move |tx| {
- tx.execute(
- "UPDATE candidate SET viewed_at=?1 WHERE id=?2 AND viewed_at IS NULL",
- rusqlite::params![at, id],
- )?;
- Ok(())
- })
-}
-
-pub fn pending_candidates(db: &Db) -> Result<Vec<CandidateRow>> {
- db.read(|c| {
- let mut stmt = c.prepare(
- "SELECT c.id, c.pkgbase_id, c.base_release_id, c.kind, c.snapshot_id, c.epoch, c.pkgver,
- c.pkgrel, c.upstream_pins_json, c.source_digests_json, c.identity_hash,
- c.diff_digest, c.revision, c.viewed_at, c.risk_level, c.risk_signals_json,
- c.missing_deps_json, c.state, c.detected_at, c.resolved_at, b.name
- FROM candidate c JOIN pkgbase b ON b.id = c.pkgbase_id
- WHERE c.state='pending_review'
- ORDER BY (c.risk_level='high') DESC, c.detected_at",
- )?;
- let rows = stmt.query_map([], row_to_candidate)?;
- let mut out = Vec::new();
- for r in rows {
- out.push(r?);
- }
- Ok(out)
- })
-}
-
-pub fn candidate_by_id(db: &Db, id: i64) -> Result<Option<CandidateRow>> {
- db.read(|c| {
- Ok(c.query_row(
- "SELECT c.id, c.pkgbase_id, c.base_release_id, c.kind, c.snapshot_id, c.epoch, c.pkgver,
- c.pkgrel, c.upstream_pins_json, c.source_digests_json, c.identity_hash,
- c.diff_digest, c.revision, c.viewed_at, c.risk_level, c.risk_signals_json,
- c.missing_deps_json, c.state, c.detected_at, c.resolved_at, b.name
- FROM candidate c JOIN pkgbase b ON b.id = c.pkgbase_id WHERE c.id=?1",
- rusqlite::params![id],
- row_to_candidate,
- )
- .optional()?)
- })
-}
-
-fn row_to_candidate(r: &rusqlite::Row<'_>) -> rusqlite::Result<CandidateRow> {
- Ok(CandidateRow {
- id: r.get(0)?,
- pkgbase_id: r.get(1)?,
- base_release_id: r.get(2)?,
- kind: r.get(3)?,
- snapshot_id: r.get(4)?,
- epoch: r.get(5)?,
- pkgver: r.get(6)?,
- pkgrel: r.get(7)?,
- upstream_pins_json: r.get(8)?,
- source_digests_json: r.get(9)?,
- identity_hash: r.get(10)?,
- diff_digest: r.get(11)?,
- revision: r.get(12)?,
- viewed_at: r.get(13)?,
- risk_level: r.get(14)?,
- risk_signals_json: r.get(15)?,
- missing_deps_json: r.get(16)?,
- state: r.get(17)?,
- detected_at: r.get(18)?,
- resolved_at: r.get(19)?,
- pkgbase: r.get(20)?,
- })
-}
-
-/// Open reviews for a pkgbase (usually zero or one, by I7).
-pub fn open_reviews_for(db: &Db, pkgbase_id: i64) -> Result<Vec<CandidateRow>> {
- db.read(|c| {
- let mut stmt = c.prepare(
- "SELECT c.id, c.pkgbase_id, c.base_release_id, c.kind, c.snapshot_id, c.epoch, c.pkgver,
- c.pkgrel, c.upstream_pins_json, c.source_digests_json, c.identity_hash,
- c.diff_digest, c.revision, c.viewed_at, c.risk_level, c.risk_signals_json,
- c.missing_deps_json, c.state, c.detected_at, c.resolved_at, b.name
- FROM candidate c JOIN pkgbase b ON b.id = c.pkgbase_id
- WHERE c.pkgbase_id=?1 AND c.state='pending_review'",
- )?;
- let rows = stmt.query_map(rusqlite::params![pkgbase_id], row_to_candidate)?;
- let mut out = Vec::new();
- for r in rows {
- out.push(r?);
- }
- Ok(out)
- })
-}
-
-/// §7.1: a rejection can be re-opened. We retire the rejected row so it stops
-/// suppressing the identity, and the next detection opens a fresh review.
-pub fn reopen_rejected(db: &Db, id: i64) -> Result<()> {
- let at = time::now();
- db.writer.tx(move |tx| {
- let n = tx.execute(
- "UPDATE candidate SET state='superseded', resolved_at=?1 WHERE id=?2 AND state='rejected'",
- rusqlite::params![at, id],
- )?;
- if n == 0 {
- return Err(crate::error::Error::conflict("candidate is not rejected"));
- }
- Ok(())
- })
-}
-
-/// Record the risk assessment computed at review time.
-pub fn set_risk(db: &Db, id: i64, level: &str, signals: &[String]) -> Result<()> {
- let lvl = level.to_string();
- let sig = serde_json::to_string(signals)?;
- db.writer.tx(move |tx| {
- tx.execute(
- "UPDATE candidate SET risk_level=?1, risk_signals_json=?2 WHERE id=?3",
- rusqlite::params![lvl, sig, id],
- )?;
- Ok(())
- })
-}
-
-pub fn set_missing_deps(db: &Db, id: i64, missing: &[String]) -> Result<()> {
- let m = serde_json::to_string(missing)?;
- db.writer.tx(move |tx| {
- tx.execute(
- "UPDATE candidate SET missing_deps_json=?1 WHERE id=?2",
- rusqlite::params![m, id],
- )?;
- Ok(())
- })
-}
-
-pub fn set_diff_digest(db: &Db, id: i64, digest: &str) -> Result<()> {
- let d = digest.to_string();
- db.writer.tx(move |tx| {
- tx.execute("UPDATE candidate SET diff_digest=?1 WHERE id=?2", rusqlite::params![d, id])?;
- Ok(())
- })
-}
-
/// Convenience used by the watcher: the accepted release of a pkgbase row.
pub fn accepted_for(db: &Db, pb: &Pkgbase) -> Result<Option<ReleaseRow>> {
match pb.current_accepted_release_id {
diff --git a/src/review/diff.rs b/src/review/diff.rs
index 5af6f5a..1196406 100644
--- a/src/review/diff.rs
+++ b/src/review/diff.rs
@@ -72,18 +72,7 @@ fn recipe_of(db: &Db, snapshot_id: Option<i64>) -> Option<Recipe> {
}
fn candidate_snapshot_id(db: &Db, candidate_id: i64) -> Option<i64> {
- db.read(|c| {
- use rusqlite::OptionalExtension;
- c.query_row(
- "SELECT snapshot_id FROM candidate WHERE id=?1",
- rusqlite::params![candidate_id],
- |r| r.get::<_, i64>(0),
- )
- .optional()
- .map_err(Into::into)
- })
- .ok()
- .flatten()
+ db::candidate_snapshot_id(db, candidate_id).ok().flatten()
}
/// `source=()` entries added, removed, or moved to a different host (§6). A new
diff --git a/src/watch/detect.rs b/src/watch/detect.rs
index 71d1b29..deb0749 100644
--- a/src/watch/detect.rs
+++ b/src/watch/detect.rs
@@ -84,19 +84,9 @@ pub fn check_pkgbase(cfg: &Config, db: &Db, name: &str) -> Result<CheckReport> {
}
fn schedule_next(db: &Db, name: &str, pb: &Pkgbase) {
- let interval = db
- .read(|c| {
- use rusqlite::OptionalExtension;
- Ok(c.query_row(
- "SELECT poll_interval_secs FROM subscription WHERE pkgbase=?1",
- rusqlite::params![name],
- |r| r.get::<_, Option<i64>>(0),
- )
- .optional()?)
- })
+ let interval = db::subscription_poll_interval(db, name)
.ok()
.flatten()
- .flatten()
.unwrap_or(crate::db::setting_i64(db, "poll_interval", 86400));
let next = time::secs_ahead(interval);
let _ = db::note_check(&db.writer, name, &next, None);
diff --git a/src/watch/digests.rs b/src/watch/digests.rs
index 07551ca..cb7bdbc 100644
--- a/src/watch/digests.rs
+++ b/src/watch/digests.rs
@@ -11,9 +11,8 @@
//! files are already in the mirror.
use crate::config::Config;
-use crate::db::*;
+use crate::db::{self, *};
use crate::error::Result;
-use crate::time;
use crate::watch::mirror::Tree;
const SKIP: &str = "SKIP";
@@ -144,37 +143,19 @@ pub fn download_and_cache(cfg: &Config, db: &Db, url: &str) -> Result<(String, u
} else {
let _ = std::fs::remove_file(&tmp);
}
- let at = time::now();
let dest_s = dest.display().to_string();
- let u = url.to_string();
- let digest_for_row = digest.clone();
- db.writer.tx(move |tx| {
- tx.execute(
- "INSERT INTO source_cache (url, digest, size, fetched_at, path) VALUES (?1,?2,?3,?4,?5)
- ON CONFLICT(url, digest) DO UPDATE SET fetched_at=excluded.fetched_at",
- rusqlite::params![u, digest_for_row, size as i64, at, dest_s],
- )?;
- Ok(())
- })?;
+ db::put_source_cache(&db.writer, url, &digest, size, &dest_s)?;
Ok((digest, size))
}
/// The cached file holding `digest`, if we still have it. The build uses this
/// so the bytes it consumes are the bytes that were hashed at detection time.
pub fn cached_path(db: &Db, url: &str, digest: &str) -> Option<std::path::PathBuf> {
- let p: Option<String> = db
- .read(|c| {
- use rusqlite::OptionalExtension;
- Ok(c.query_row(
- "SELECT path FROM source_cache WHERE url=?1 AND digest=?2",
- rusqlite::params![url, digest],
- |r| r.get(0),
- )
- .optional()?)
- })
+ db::source_cache_path(db, url, digest)
.ok()
- .flatten();
- p.map(std::path::PathBuf::from).filter(|p| p.exists())
+ .flatten()
+ .map(std::path::PathBuf::from)
+ .filter(|p| p.exists())
}
/// True when a `SKIP` on a non-VCS source means the recipe permanently refuses
diff --git a/src/watch/staleness.rs b/src/watch/staleness.rs
index 210632e..cc7242c 100644
--- a/src/watch/staleness.rs
+++ b/src/watch/staleness.rs
@@ -35,23 +35,10 @@ pub struct Stale {
/// Every stale package, derived from world snapshots against the live index.
pub fn stale_rows(db: &Db) -> Result<Vec<Stale>> {
- let rows: Vec<(String, String, String, String)> = db.read(|c| {
- let mut st = c.prepare(
- "SELECT p.name, w.members_json
- FROM release r
- JOIN pkgbase p ON p.id = r.pkgbase_id
- JOIN build b ON b.id = r.build_id
- JOIN world_snapshot w ON w.id = b.world_snapshot_id
- WHERE r.state = 'published'",
- )?;
- let rows = st.query_map([], |r| {
- Ok((r.get::<_, String>(0)?, r.get::<_, String>(1)?, String::new(), String::new()))
- })?;
- Ok(rows.filter_map(|r| r.ok()).collect::<Vec<_>>())
- })?;
+ let rows = db::published_world_members(db)?;
let mut out = Vec::new();
- for (pkgbase, members_json, _, _) in rows {
+ for (pkgbase, members_json) in rows {
let members: Vec<db::WorldMember> = serde_json::from_str(&members_json).unwrap_or_default();
for m in members {
// A package is not stale relative to itself.
@@ -93,25 +80,7 @@ pub fn stale_for(db: &Db, pkgbase: &str) -> Result<Vec<Stale>> {
/// Derived on read from the newest candidate per pkgbase against the accepted
/// release, so it disappears the moment either side moves.
pub fn downgrades(db: &Db) -> Result<Vec<Stale>> {
- let rows: Vec<(String, String, String)> = db.read(|c| {
- let mut st = c.prepare(
- "SELECT p.name, r.pkgver, (
- SELECT c.pkgver FROM candidate c
- WHERE c.pkgbase_id = r.pkgbase_id
- ORDER BY c.id DESC LIMIT 1)
- FROM release r
- JOIN pkgbase p ON p.current_accepted_release_id = r.id
- WHERE r.state = 'published'",
- )?;
- let rows = st.query_map([], |r| {
- Ok((
- r.get::<_, String>(0)?,
- r.get::<_, String>(1)?,
- r.get::<_, Option<String>>(2)?.unwrap_or_default(),
- ))
- })?;
- Ok(rows.filter_map(|r| r.ok()).collect::<Vec<_>>())
- })?;
+ let rows = db::served_vs_offered_pkgvers(db)?;
let mut out = Vec::new();
for (pkgbase, served, offered) in rows {
if offered.is_empty() || !crate::pkgver::is_downgrade(&served, &offered) {
@@ -137,28 +106,14 @@ pub fn dependents_of(db: &Db, name: &str) -> Result<Vec<String>> {
if p.name == name {
continue;
}
- let depends: bool = db.read(|c| {
- use rusqlite::OptionalExtension;
- let json: Option<String> = c
- .query_row(
- "SELECT s.srcinfo_json FROM package pk
- JOIN release r ON r.id = pk.release_id
- JOIN candidate cnd ON cnd.id = r.candidate_id
- JOIN snapshot s ON s.id = cnd.snapshot_id
- WHERE pk.name = ?1 AND pk.state='in_index'",
- rusqlite::params![p.name],
- |r| r.get::<_, String>(0),
- )
- .optional()?;
- Ok(json
- .and_then(|j| serde_json::from_str::<crate::db::model::Recipe>(&j).ok())
- .map(|r| {
- crate::pkgver::dep_names(&r.depends)
- .into_iter()
- .any(|d| d == name)
- })
- .unwrap_or(false))
- })?;
+ let depends = db::recipe_json_of_index_package(db, &p.name)?
+ .and_then(|j| serde_json::from_str::<crate::db::model::Recipe>(&j).ok())
+ .map(|r| {
+ crate::pkgver::dep_names(&r.depends)
+ .into_iter()
+ .any(|d| d == name)
+ })
+ .unwrap_or(false);
if depends {
out.push(p.name);
}
diff --git a/tests/approve.rs b/tests/approve.rs
index fb894f1..5a515eb 100644
--- a/tests/approve.rs
+++ b/tests/approve.rs
@@ -45,7 +45,7 @@ fn approve_writes_an_immutable_row_carrying_both_hashes() {
let err = env
.db
.writer
- .tx(move |tx| {
+ .tx_for_tests(move |tx| {
tx.execute("UPDATE approval SET note='rewritten' WHERE id=1", [])?;
Ok(())
})
diff --git a/tests/common/mod.rs b/tests/common/mod.rs
index 67c5592..de5f87e 100644
--- a/tests/common/mod.rs
+++ b/tests/common/mod.rs
@@ -64,7 +64,7 @@ impl Env {
let params: Vec<P> = params.to_vec();
self.db
.writer
- .tx(move |tx| {
+ .tx_for_tests(move |tx| {
let refs: Vec<&dyn rusqlite::ToSql> = params
.iter()
.map(|p| match p {
@@ -84,7 +84,7 @@ impl Env {
let at = "2026-01-01T00:00:00Z";
self.db
.writer
- .tx(move |tx| {
+ .tx_for_tests(move |tx| {
tx.execute(
"INSERT INTO approval (candidate_id, base_release_id, decided_at, decision,
risk_level, diff_digest, identity_hash)
diff --git a/tests/db.rs b/tests/db.rs
index e2608a1..75977d1 100644
--- a/tests/db.rs
+++ b/tests/db.rs
@@ -125,7 +125,7 @@ fn accepted_release_pointer_is_compared_and_swapped() {
let rel = env
.db
.writer
- .tx(move |tx| {
+ .tx_for_tests(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')",
@@ -222,7 +222,7 @@ fn i1_query_flags_index_entries_without_approval() {
let rel = env
.db
.writer
- .tx(move |tx| {
+ .tx_for_tests(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')",
diff --git a/tests/invariants.rs b/tests/invariants.rs
index 8234817..a083a89 100644
--- a/tests/invariants.rs
+++ b/tests/invariants.rs
@@ -208,7 +208,7 @@ fn i7_the_schema_refuses_a_second_open_review() {
let err = env
.db
.writer
- .tx(move |tx| {
+ .tx_for_tests(move |tx| {
tx.execute(
"INSERT INTO candidate (pkgbase_id, kind, snapshot_id, epoch, pkgver, pkgrel,
upstream_pins_json, source_digests_json, identity_hash,
@@ -316,7 +316,7 @@ fn i10_audit_is_append_only_and_records_the_decisions() {
let s = sql.to_string();
assert!(
db.writer
- .tx(move |tx| {
+ .tx_for_tests(move |tx| {
tx.execute(&s, [])?;
Ok(())
})
diff --git a/tests/schema_ownership.rs b/tests/schema_ownership.rs
new file mode 100644
index 0000000..e2904f4
--- /dev/null
+++ b/tests/schema_ownership.rs
@@ -0,0 +1,88 @@
+//! The schema has one owner (§6 M-1).
+//!
+//! `db/` is a boundary, not a directory, only if SQL cannot land anywhere else.
+//! Part of that is a compile-time fact: `Writer::call`, `tx` and `send` are
+//! `pub(crate)`, and the raw door the test harness uses exists only under the
+//! `test-support` feature. What the compiler cannot express is the other half —
+//! that no module *inside* this crate writes a statement of its own. This does.
+//!
+//! The rule it enforces: a SQL statement, or a rusqlite statement call, appears
+//! in `src/db/` and nowhere else. A module that needs the database asks `db/`
+//! for a typed query; if the query does not exist, that is the change to make.
+
+use std::path::{Path, PathBuf};
+
+/// String literals that begin a statement. Matched on the quote so a prose
+/// comment that mentions a `SELECT` cannot trip it, and comment lines are
+/// skipped anyway.
+const SQL_LITERALS: &[&str] = &[
+ "\"SELECT", "\"select", "\"INSERT", "\"insert", "\"UPDATE", "\"update", "\"DELETE", "\"delete",
+ "\"PRAGMA", "\"WITH",
+];
+
+/// rusqlite entry points. Outside `db/` there is nothing legitimate to hand
+/// them, since every statement string is supposed to live in `db/`.
+const STATEMENT_CALLS: &[&str] = &[
+ ".query_row(", ".query_map(", ".execute(", ".execute_batch(", ".prepare(", ".pragma_query_value(",
+];
+
+fn rust_files(dir: &Path, out: &mut Vec<PathBuf>) {
+ for entry in std::fs::read_dir(dir).expect("read_dir") {
+ let path = entry.expect("entry").path();
+ if path.is_dir() {
+ rust_files(&path, out);
+ } else if path.extension().is_some_and(|e| e == "rs") {
+ out.push(path);
+ }
+ }
+}
+
+#[test]
+fn no_sql_statements_outside_the_db_module() {
+ let root = Path::new(env!("CARGO_MANIFEST_DIR")).join("src");
+ let mut files = Vec::new();
+ rust_files(&root, &mut files);
+ assert!(files.len() > 20, "found only {} source files — the walk is wrong", files.len());
+
+ let mut offenders: Vec<String> = Vec::new();
+ for file in files {
+ let rel = file.strip_path(&root);
+ // The owner of the schema is allowed to contain SQL.
+ if rel.starts_with("db/") || rel.starts_with("db\\") {
+ continue;
+ }
+ let text = std::fs::read_to_string(&file).expect("read source");
+ for (no, line) in text.lines().enumerate() {
+ let t = line.trim_start();
+ if t.starts_with("//") {
+ continue;
+ }
+ for needle in SQL_LITERALS.iter().chain(STATEMENT_CALLS.iter()) {
+ if line.contains(needle) {
+ offenders.push(format!("{}:{}: {t}", rel, no + 1));
+ break;
+ }
+ }
+ }
+ }
+ assert!(
+ offenders.is_empty(),
+ "SQL belongs to `db/` (§6 M-1). Move these into a typed query:\n{}",
+ offenders.join("\n")
+ );
+}
+
+/// `src/db/queries.rs` → `db/queries.rs`, so the failure message points at the
+/// module rather than an absolute path.
+trait StripPath {
+ fn strip_path(&self, root: &Path) -> String;
+}
+
+impl StripPath for PathBuf {
+ fn strip_path(&self, root: &Path) -> String {
+ self.strip_prefix(root)
+ .unwrap_or(self.as_path())
+ .to_string_lossy()
+ .replace('\\', "/")
+ }
+}