summaryrefslogtreecommitdiffstats
path: root/src/watch
diff options
context:
space:
mode:
Diffstat (limited to 'src/watch')
-rw-r--r--src/watch/detect.rs288
-rw-r--r--src/watch/digests.rs193
-rw-r--r--src/watch/mirror.rs119
-rw-r--r--src/watch/mod.rs12
-rw-r--r--src/watch/scheduler.rs71
5 files changed, 683 insertions, 0 deletions
diff --git a/src/watch/detect.rs b/src/watch/detect.rs
new file mode 100644
index 0000000..e00a2f9
--- /dev/null
+++ b/src/watch/detect.rs
@@ -0,0 +1,288 @@
+//! Detection: the recipe watcher pass for one pkgbase (§5.1, §5.2, §5.3).
+//!
+//! The decision that matters is *what counts as a change*. A candidate exists
+//! only if something **publishable** changed — if the version string is
+//! unchanged, `pacman` cannot offer an upgrade, so there is nothing to approve.
+//! Those events become `notice` rows instead, and are never silently dropped
+//! (I11).
+
+use crate::config::Config;
+use crate::db::{self, *};
+use crate::error::Result;
+use crate::pkgver;
+use crate::recipe::recipe_from_tree;
+use crate::review::candidates::{upsert_candidate, NewCandidate, Upsert};
+use crate::time;
+use crate::watch::digests::resolve_sources;
+use crate::watch::mirror::{read_tree, sync_mirror, Sync};
+
+#[derive(Debug, Clone)]
+pub enum Outcome {
+ /// Nothing moved at all.
+ NoChange,
+ /// A new review was opened.
+ Candidate { id: i64, kind: String },
+ /// The open review was updated in place (I7).
+ Collapsed { id: i64, revision: i64 },
+ /// The seen-but-unresolved review was frozen and a new one opened.
+ Superseded { old: i64, new: i64 },
+ /// Identical to something a human already rejected.
+ PreviouslyRejected,
+ /// Something changed but nothing is publishable (I11).
+ Notice { kind: String, detail: serde_json::Value },
+ /// The package vanished from AUR.
+ Gone,
+ /// Detection could not complete; the watcher will back off.
+ Blocked(String),
+}
+
+#[derive(Debug, Clone)]
+pub struct CheckReport {
+ pub pkgbase: String,
+ pub head: String,
+ pub outcome: Outcome,
+}
+
+/// One full detection pass for a subscribed pkgbase.
+pub fn check_pkgbase(cfg: &Config, db: &Db, name: &str) -> Result<CheckReport> {
+ let pb = get_pkgbase(db, name)?
+ .ok_or_else(|| crate::error::Error::not_found(format!("pkgbase {name}")))?;
+ let sync = sync_mirror(cfg, db, name, &pb.aur_url)?;
+ let head = match &sync {
+ Sync::Gone => {
+ db::put_notice_once(
+ &db.writer,
+ pb.id,
+ notice_kind::DELETED,
+ "high",
+ serde_json::json!({"aur_url": pb.aur_url, "note": "repository no longer exists"}),
+ )?;
+ db::set_subscription_state(&db.writer, name, subscription_state::ORPHANED)?;
+ return Ok(CheckReport { pkgbase: name.into(), head: String::new(), outcome: Outcome::Gone });
+ }
+ // The cheap poll saved us a fetch, but we still have to look: a source
+ // can change its bytes without the recipe moving at all, and that is the
+ // digest-drift case §5.3 calls the single most valuable detection.
+ Sync::Unchanged { head } => head.clone(),
+ Sync::Fetched { head, .. } | Sync::Cloned { head } => head.clone(),
+ };
+ let r = analyse(cfg, db, &pb, &head);
+ schedule_next(db, name, &pb);
+ r
+}
+
+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()?)
+ })
+ .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);
+ let _ = pb;
+}
+
+/// Everything after the mirror is up to date.
+fn analyse(cfg: &Config, db: &Db, pb: &Pkgbase, head: &str) -> Result<CheckReport> {
+ let mirror = cfg.mirror_path(&pb.name);
+ let report = |outcome: Outcome| CheckReport { pkgbase: pb.name.clone(), head: head.to_string(), outcome };
+
+ // §16 mirror divergence: if the accepted pin has vanished from our own
+ // mirror, hard-fail this pkgbase rather than silently re-pinning.
+ let accepted = crate::review::candidates::accepted_for(db, pb)?;
+ if let Some(a) = &accepted {
+ if !crate::git::has_commit(&mirror, &a.aur_commit) {
+ db::put_notice_once(
+ &db.writer,
+ pb.id,
+ notice_kind::DELETED,
+ "high",
+ serde_json::json!({"mirror_divergence": a.aur_commit}),
+ )?;
+ return Ok(report(Outcome::Blocked(format!(
+ "accepted pin {} missing from local mirror",
+ a.aur_commit
+ ))));
+ }
+ }
+
+ let tree = read_tree(&mirror, head)?;
+ let recipe = recipe_from_tree(&tree.files)?;
+ let recipe_hash = tree.recipe_hash();
+ let digests = resolve_sources(cfg, db, &mirror, head, &tree, &recipe, &[])?;
+ let pins: Vec<UpstreamPin> = Vec::new(); // P1 fills this in for VCS sources
+
+ let identity = Identity {
+ aur_commit: head.to_string(),
+ epoch: recipe.epoch.clone(),
+ pkgver: recipe.pkgver.clone(),
+ pkgrel: recipe.pkgrel.clone(),
+ upstream_pins: pins.clone(),
+ source_digests: digests.clone(),
+ };
+ let identity_hash = identity.hash();
+ let snap_id = db::put_snapshot(
+ &db.writer,
+ pb.id,
+ head,
+ &recipe_hash,
+ &serde_json::to_string(&recipe)?,
+ &tree.json_list(),
+ )?;
+
+ let nc = NewCandidate {
+ snapshot_id: snap_id,
+ epoch: recipe.epoch.clone(),
+ pkgver: recipe.pkgver.clone(),
+ pkgrel: recipe.pkgrel.clone(),
+ upstream_pins_json: serde_json::to_string(&pins)?,
+ source_digests_json: serde_json::to_string(&digests)?,
+ identity_hash: identity_hash.clone(),
+ };
+
+ let Some(base) = accepted else {
+ // §7.1b: nothing to diff against — this is a first introduction.
+ return match upsert_candidate(db, pb, None, &nc)? {
+ Upsert::Created { id, kind } => Ok(report(Outcome::Candidate { id, kind })),
+ other => Ok(report(outcome_of(other))),
+ };
+ };
+
+ // Same identity as what we already serve: nothing happened.
+ if base.aur_commit == head
+ && base.epoch == nc.epoch
+ && base.pkgver == nc.pkgver
+ && base.pkgrel == nc.pkgrel
+ && base.upstream_pins_json == nc.upstream_pins_json
+ && base.source_digests_json == nc.source_digests_json
+ {
+ return Ok(report(Outcome::NoChange));
+ }
+
+ let new_version = nc.version();
+ let publishable = pkgver::vercmp(&base.version(), &new_version) != std::cmp::Ordering::Equal;
+
+ if !publishable {
+ // §5.2 / §5.3: nothing pacman could offer as an upgrade. Record it
+ // loudly instead of inventing a pkgrel bump.
+ return Ok(report(non_publishable(db, pb, &base, &nc, &recipe)?));
+ }
+
+ if pkgver::is_downgrade(&base.version(), &new_version) {
+ db::put_notice_once(
+ &db.writer,
+ pb.id,
+ notice_kind::DOWNGRADE,
+ "warning",
+ serde_json::json!({"served": base.version(), "aur": new_version}),
+ )?;
+ }
+
+ let up = upsert_candidate(db, pb, Some(&base), &nc)?;
+ Ok(report(outcome_of(up)))
+}
+
+fn outcome_of(up: Upsert) -> Outcome {
+ match up {
+ Upsert::Created { id, kind } => Outcome::Candidate { id, kind },
+ Upsert::Collapsed { id, revision } => Outcome::Collapsed { id, revision },
+ Upsert::Superseded { old, new } => Outcome::Superseded { old, new },
+ Upsert::PreviouslyRejected => Outcome::PreviouslyRejected,
+ Upsert::Unchanged => Outcome::NoChange,
+ }
+}
+
+/// The version string did not move, so there is no review to open — but the
+/// change is recorded, because a silently drifting tarball is exactly the kind
+/// of thing that must not be invisible (§5.3).
+fn non_publishable(
+ db: &Db,
+ pb: &Pkgbase,
+ base: &ReleaseRow,
+ nc: &NewCandidate,
+ recipe: &Recipe,
+) -> Result<Outcome> {
+ let old_digests: Vec<SourceDigest> = base.digests();
+ let new_digests: Vec<SourceDigest> = serde_json::from_str(&nc.source_digests_json).unwrap_or_default();
+ // A local source is part of the recipe: when its bytes move, that *is* the
+ // recipe drift, not an integrity event. The integrity alert is specifically
+ // "the bytes upstream serves no longer match what we built" (§5.3).
+ let changed_remote: Vec<&SourceDigest> = new_digests
+ .iter()
+ .filter(|n| n.kind != "local")
+ .filter(|n| match old_digests.iter().find(|o| o.index == n.index) {
+ Some(o) => o.digest != n.digest,
+ None => true,
+ })
+ .collect();
+ let digest_changed = !changed_remote.is_empty();
+ let old_pins: Vec<UpstreamPin> = base.pins();
+ let new_pins: Vec<UpstreamPin> = serde_json::from_str(&nc.upstream_pins_json).unwrap_or_default();
+ let pins_changed = old_pins != new_pins;
+
+ if digest_changed {
+ // The single most valuable detection in the system: the artifact in the
+ // index was built from bytes upstream no longer serves, and the version
+ // string is unchanged. An approval would be useless (approving it would
+ // not let us publish anything), so this is an alert, not a review.
+ let changed: Vec<serde_json::Value> = changed_remote
+ .iter()
+ .map(|n| {
+ serde_json::json!({"index": n.index, "url": n.url,
+ "old": old_digests.iter().find(|o| o.index == n.index)
+ .map(|o| o.digest.clone()).unwrap_or_default(),
+ "new": n.digest})
+ })
+ .collect();
+ db::put_notice_once(
+ &db.writer,
+ pb.id,
+ notice_kind::INTEGRITY_ALERT,
+ "high",
+ serde_json::json!({
+ "version": nc.version(),
+ "changed": changed,
+ "message": "the artifact in your index was built from bytes upstream no longer serves; the version string is unchanged",
+ }),
+ )?;
+ return Ok(Outcome::Notice { kind: notice_kind::INTEGRITY_ALERT.into(), detail: serde_json::json!({"changed": changed}) });
+ }
+ if pins_changed {
+ db::put_notice_once(
+ &db.writer,
+ pb.id,
+ notice_kind::PIN_DRIFT,
+ "info",
+ serde_json::json!({
+ "version": nc.version(),
+ "message": "upstream moved; pkgver unchanged, nothing publishable",
+ }),
+ )?;
+ return Ok(Outcome::Notice { kind: notice_kind::PIN_DRIFT.into(), detail: serde_json::json!({}) });
+ }
+ // The recipe drifted under a static version: the maintainer probably forgot
+ // to bump pkgrel, and the user should know.
+ let _ = recipe;
+ db::put_notice_once(
+ &db.writer,
+ pb.id,
+ notice_kind::RECIPE_DRIFT,
+ "warning",
+ serde_json::json!({
+ "version": nc.version(),
+ "accepted_aur_commit": base.aur_commit,
+ "aur_commit": "moved",
+ "message": "recipe changed but the version did not; the maintainer may have forgotten to bump pkgrel",
+ }),
+ )?;
+ Ok(Outcome::Notice { kind: notice_kind::RECIPE_DRIFT.into(), detail: serde_json::json!({}) })
+}
diff --git a/src/watch/digests.rs b/src/watch/digests.rs
new file mode 100644
index 0000000..07551ca
--- /dev/null
+++ b/src/watch/digests.rs
@@ -0,0 +1,193 @@
+//! Source digest resolution (§5.3).
+//!
+//! `sha256sums=('SKIP')` is the hole in the integrity story. We resolve and
+//! record the digest of *every* source ourselves, at detection time, regardless
+//! of what the PKGBUILD declares — which turns a silent artifact swap into a
+//! reviewable (or at least alertable) event.
+//!
+//! Cost control: only `SKIP`-declared static sources cost bandwidth. Declared
+//! checksums are trusted-as-declared for identity because makepkg enforces them
+//! at build time; VCS digests come free from the pin we already resolved; local
+//! files are already in the mirror.
+
+use crate::config::Config;
+use crate::db::*;
+use crate::error::Result;
+use crate::time;
+use crate::watch::mirror::Tree;
+
+const SKIP: &str = "SKIP";
+
+fn declared_sums(recipe: &Recipe, index: usize) -> Option<String> {
+ recipe
+ .sha256sums
+ .get(index)
+ .or_else(|| recipe.b2sums.get(index))
+ .map(|s| s.trim().to_string())
+ .filter(|s| !s.is_empty())
+}
+
+fn is_hex_digest(s: &str) -> bool {
+ (s.len() == 64 || s.len() == 128) && s.chars().all(|c| c.is_ascii_hexdigit())
+}
+
+/// Resolve the digest of every `source=()` entry.
+pub fn resolve_sources(
+ cfg: &Config,
+ db: &Db,
+ mirror: &std::path::Path,
+ commit: &str,
+ tree: &Tree,
+ recipe: &Recipe,
+ pins: &[UpstreamPin],
+) -> Result<Vec<SourceDigest>> {
+ let mut out = Vec::new();
+ for entry in &recipe.source_entries {
+ let declared = declared_sums(recipe, entry.index);
+ let skip_declared = match &declared {
+ Some(d) => d == SKIP || !is_hex_digest(d),
+ None => true,
+ };
+
+ if entry.is_vcs() {
+ // The resolved commit *is* the digest; captured during Stage B where
+ // we clone anyway (§5.2), so near-free.
+ let pin = pins.iter().find(|p| p.index == entry.index);
+ let digest = pin
+ .map(|p| p.commit.clone())
+ .or_else(|| entry.commit.clone())
+ .unwrap_or_default();
+ out.push(SourceDigest {
+ index: entry.index,
+ url: entry.url.clone(),
+ kind: entry.vcs.clone().unwrap_or_else(|| "vcs".into()),
+ digest,
+ size: 0,
+ skip_declared: true,
+ });
+ continue;
+ }
+
+ if entry.local {
+ let name = entry.filename.clone().unwrap_or_default();
+ let path = tree
+ .blobs
+ .iter()
+ .find(|(p, _)| p == &name || p.ends_with(&format!("/{name}")))
+ .map(|(p, _)| p.clone());
+ let (digest, size) = match path {
+ Some(p) => {
+ let bytes = crate::watch::mirror::read_file(mirror, commit, &p)?;
+ let d = crate::hash::hex(&bytes);
+ (d, bytes.len() as u64)
+ }
+ // A "local" file that is not in the tree is the recipe's bug;
+ // record the absence rather than inventing a digest.
+ None => (String::new(), 0),
+ };
+ out.push(SourceDigest {
+ index: entry.index,
+ url: entry.url.clone(),
+ kind: "local".into(),
+ digest,
+ size,
+ skip_declared,
+ });
+ continue;
+ }
+
+ // Static source.
+ if !skip_declared {
+ // Trusted-as-declared: makepkg verifies it at build time.
+ out.push(SourceDigest {
+ index: entry.index,
+ url: entry.url.clone(),
+ kind: "static".into(),
+ digest: declared.unwrap_or_default(),
+ size: 0,
+ skip_declared: false,
+ });
+ continue;
+ }
+
+ // The paid path: download and stream-hash into the cache, which the
+ // build then reuses so the bytes are paid for once.
+ let (digest, size) = download_and_cache(cfg, db, &entry.url)?;
+ out.push(SourceDigest {
+ index: entry.index,
+ url: entry.url.clone(),
+ kind: "static".into(),
+ digest,
+ size,
+ skip_declared: true,
+ });
+ }
+ Ok(out)
+}
+
+/// Download `url`, hashing as we go, and record it in `source_cache`.
+///
+/// This always goes to the network. That is deliberate: the whole point of §5.3
+/// is to notice that the bytes behind a `SKIP` source changed while the version
+/// did not, and answering from our own cache would make that impossible. The
+/// cache exists so the *build* can reuse the bytes it was reviewed against
+/// ([`cached_path`]), not so detection can skip looking.
+pub fn download_and_cache(cfg: &Config, db: &Db, url: &str) -> Result<(String, u64)> {
+ let tmp = cfg.source_cache_dir().join(format!("tmp-{}", crate::hash::short(url.as_bytes(), 16)));
+ let (digest, size) = crate::fetch::fetch_to(url, &tmp)?;
+ let dest = cfg.source_cache_path(&digest);
+ if !dest.exists() {
+ if let Some(parent) = dest.parent() {
+ std::fs::create_dir_all(parent)?;
+ }
+ std::fs::rename(&tmp, &dest)?;
+ } 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(())
+ })?;
+ 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()?)
+ })
+ .ok()
+ .flatten();
+ p.map(std::path::PathBuf::from).filter(|p| p.exists())
+}
+
+/// True when a `SKIP` on a non-VCS source means the recipe permanently refuses
+/// to verify its input — itself a risk signal (§5.3).
+pub fn skip_on_non_vcs(recipe: &Recipe) -> Vec<usize> {
+ recipe
+ .source_entries
+ .iter()
+ .filter(|e| !e.is_vcs())
+ .filter(|e| match declared_sums(recipe, e.index) {
+ Some(d) => d == SKIP || !is_hex_digest(&d),
+ None => true,
+ })
+ .map(|e| e.index)
+ .collect()
+}
diff --git a/src/watch/mirror.rs b/src/watch/mirror.rs
new file mode 100644
index 0000000..989b968
--- /dev/null
+++ b/src/watch/mirror.rs
@@ -0,0 +1,119 @@
+//! The local AUR git mirror (§5.1).
+//!
+//! Clone, don't scrape. The mirror is load-bearing rather than a cache: every
+//! build materializes its recipe from it at the pinned commit and never asks
+//! the network for a recipe (§5.1a), so losing it would mean losing the ability
+//! to reproduce any historical release.
+
+use std::collections::BTreeMap;
+use std::path::Path;
+
+use crate::config::Config;
+use crate::db::{self, Db};
+use crate::error::{Error, Result};
+use crate::git;
+
+/// Result of a cheap poll. `Unchanged` means we did **not** fetch — the poll is
+/// `git ls-remote`, one request per pkgbase (§5.1).
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub enum Sync {
+ /// Remote is gone (deleted from AUR).
+ Gone,
+ /// `ls-remote` matched the local tip; no fetch performed.
+ Unchanged { head: String },
+ /// The tip moved; we fetched and now have `head`.
+ Fetched { head: String, previous: Option<String> },
+ /// We had no local mirror yet.
+ Cloned { head: String },
+}
+
+/// Ensure a mirror exists and is polled. Updates `pkgbase.aur_head`.
+pub fn sync_mirror(cfg: &Config, db: &Db, name: &str, url: &str) -> Result<Sync> {
+ let mirror = cfg.mirror_path(name);
+ let known_head = db::get_pkgbase(db, name)?.and_then(|p| p.aur_head.clone());
+
+ if !mirror.exists() {
+ git::clone(url, &mirror)?;
+ let head = git::head(&mirror)?;
+ record(db, name, &head, &mirror)?;
+ return Ok(Sync::Cloned { head });
+ }
+
+ let remote = match git::ls_remote_head(url)? {
+ Some(h) => h,
+ None => return Ok(Sync::Gone),
+ };
+ let local = git::head(&mirror).ok();
+ if let Some(l) = &local {
+ if *l == remote {
+ return Ok(Sync::Unchanged { head: remote });
+ }
+ }
+ let head = git::fetch_head(&mirror)?;
+ record(db, name, &head, &mirror)?;
+ Ok(Sync::Fetched { head, previous: known_head })
+}
+
+fn record(db: &Db, name: &str, head: &str, mirror: &Path) -> Result<()> {
+ let pb = db::get_pkgbase(db, name)?.ok_or_else(|| Error::not_found(format!("pkgbase {name}")))?;
+ db::set_aur_head(&db.writer, pb.id, head, &mirror.display().to_string())
+}
+
+/// A materialized snapshot tree: blob ids for hashing, text bodies for parsing
+/// and diffing.
+#[derive(Debug, Clone)]
+pub struct Tree {
+ /// `(path, git blob id)` for every file in the tree — the input to
+ /// `recipe_hash`. Covers PKGBUILD, .SRCINFO, *.install and shipped patches
+ /// (§3): a patch file is part of the recipe.
+ pub blobs: Vec<(String, String)>,
+ /// Text bodies, keyed by path. Binary files are omitted from this map but
+ /// still counted in `blobs`.
+ pub files: BTreeMap<String, String>,
+}
+
+impl Tree {
+ pub fn recipe_hash(&self) -> String {
+ crate::hash::recipe_hash(&self.blobs)
+ }
+ pub fn get(&self, suffix: &str) -> Option<&String> {
+ self.files
+ .iter()
+ .find(|(k, _)| k.ends_with(suffix))
+ .map(|(_, v)| v)
+ }
+ pub fn json_list(&self) -> String {
+ serde_json::to_string(&self.blobs).unwrap_or_else(|_| "[]".into())
+ }
+}
+
+/// Read a commit's tree out of the mirror without touching the network.
+pub fn read_tree(mirror: &Path, commit: &str) -> Result<Tree> {
+ // §16 mirror divergence: if a pin we are asked to read has vanished, that is
+ // a hard failure, not a silent re-pin.
+ if !git::has_commit(mirror, commit) {
+ return Err(Error::fail_closed(format!(
+ "commit {commit} is missing from the local mirror; history was rewritten"
+ )));
+ }
+ let blobs = git::ls_tree(mirror, commit)?;
+ let mut files = BTreeMap::new();
+ for (path, _) in &blobs {
+ let bytes = git::read_blob(mirror, commit, path)?;
+ if bytes.len() > 4 * 1024 * 1024 || !looks_textual(&bytes) {
+ continue;
+ }
+ files.insert(path.clone(), String::from_utf8_lossy(&bytes).into_owned());
+ }
+ Ok(Tree { blobs, files })
+}
+
+fn looks_textual(b: &[u8]) -> bool {
+ !b[..b.len().min(512)].contains(&0)
+}
+
+/// Raw bytes of one file at a commit — used to hash sources shipped in the AUR
+/// repo (§5.3 "local file shipped in the AUR repo").
+pub fn read_file(mirror: &Path, commit: &str, path: &str) -> Result<Vec<u8>> {
+ git::read_blob(mirror, commit, path)
+}
diff --git a/src/watch/mod.rs b/src/watch/mod.rs
new file mode 100644
index 0000000..3f0d217
--- /dev/null
+++ b/src/watch/mod.rs
@@ -0,0 +1,12 @@
+//! Watchers: AUR recipe mirror (§5.1), upstream VCS probe (§5.2), source digest
+//! resolution (§5.3), and the scheduler tick.
+
+pub mod detect;
+pub mod digests;
+pub mod mirror;
+pub mod scheduler;
+
+pub use detect::{check_pkgbase, CheckReport, Outcome};
+pub use digests::{cached_path, download_and_cache, resolve_sources, skip_on_non_vcs};
+pub use mirror::{read_tree, sync_mirror, Tree};
+pub use scheduler::spawn_scheduler;
diff --git a/src/watch/scheduler.rs b/src/watch/scheduler.rs
new file mode 100644
index 0000000..ca42e32
--- /dev/null
+++ b/src/watch/scheduler.rs
@@ -0,0 +1,71 @@
+//! The scheduler tick (§4: "one tick thread + sweep over `next_check_at`").
+//!
+//! Blocking is the right shape here: the tick sleeps between sweeps and each
+//! sweep is a sequence of blocking git and HTTP calls.
+
+use std::sync::atomic::{AtomicBool, Ordering};
+use std::sync::Arc;
+use std::thread::JoinHandle;
+
+use crate::config::Config;
+use crate::db::{self, Db};
+use crate::watch::detect::check_pkgbase;
+
+/// Spawn the watcher tick thread.
+pub fn spawn_scheduler(cfg: Arc<Config>, db: Db, stop: Arc<AtomicBool>) -> JoinHandle<()> {
+ std::thread::Builder::new()
+ .name("watcher".into())
+ .spawn(move || {
+ while !stop.load(Ordering::SeqCst) {
+ let tick = crate::db::setting_i64(&db, "poll_tick", 30);
+ sweep(&cfg, &db);
+ // Sleep in small slices so shutdown is prompt.
+ let mut slept = 0;
+ while slept < tick && !stop.load(Ordering::SeqCst) {
+ std::thread::sleep(std::time::Duration::from_secs(1));
+ slept += 1;
+ }
+ }
+ })
+ .expect("spawn watcher")
+}
+
+/// One sweep over everything that is due.
+pub fn sweep(cfg: &Config, db: &Db) -> usize {
+ let now = crate::time::now();
+ let due = match db::due_subscriptions(db, &now) {
+ Ok(d) => d,
+ Err(_) => return 0,
+ };
+ let mut n = 0;
+ for sub in due {
+ // Mark it checked first so a slow or hanging source cannot make the
+ // scheduler re-enter it on the next tick.
+ let interval = sub
+ .poll_interval_secs
+ .unwrap_or(crate::db::setting_i64(db, "poll_interval", 86400));
+ let _ = db::note_check(&db.writer, &sub.pkgbase, &crate::time::secs_ahead(interval), None);
+ match check_pkgbase(cfg, db, &sub.pkgbase) {
+ Ok(report) => {
+ if matches!(report.outcome, crate::watch::detect::Outcome::Blocked(_)) {
+ let _ = db::note_check(
+ &db.writer,
+ &sub.pkgbase,
+ &crate::time::secs_ahead(600),
+ Some(&format!("{:?}", report.outcome)),
+ );
+ }
+ }
+ Err(e) => {
+ let _ = db::note_check(
+ &db.writer,
+ &sub.pkgbase,
+ &crate::time::secs_ahead(600),
+ Some(&e.to_string()),
+ );
+ }
+ }
+ n += 1;
+ }
+ n
+}