//! CI models: run and job states, runners, runs, jobs and artifacts. The stored shape is in //! migrations/0024_ci.sql; the store functions live in store/ci.rs. //! //! Job specs are kept as JSON text (`CiJob::spec_json`). The store reads only the `needs` and //! `runs_on` arrays out of it, so this crate does not depend on forge-ci. use std::collections::BTreeMap; use std::str::FromStr; use crate::error::{Error, Result}; /// State of a run. Stored as the `as_str` name. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum RunState { WaitingApproval, Queued, Running, Success, Failure, Cancelled, Error, } impl RunState { pub fn as_str(self) -> &'static str { match self { RunState::WaitingApproval => "waiting_approval", RunState::Queued => "queued", RunState::Running => "running", RunState::Success => "success", RunState::Failure => "failure", RunState::Cancelled => "cancelled", RunState::Error => "error", } } /// True for states a run cannot leave. pub fn is_terminal(self) -> bool { matches!( self, RunState::Success | RunState::Failure | RunState::Cancelled | RunState::Error ) } } impl FromStr for RunState { type Err = Error; fn from_str(s: &str) -> Result { Ok(match s { "waiting_approval" => RunState::WaitingApproval, "queued" => RunState::Queued, "running" => RunState::Running, "success" => RunState::Success, "failure" => RunState::Failure, "cancelled" => RunState::Cancelled, "error" => RunState::Error, other => return Err(Error::Database(format!("unknown CI run state {other:?}"))), }) } } /// State of a job. Stored as the `as_str` name. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum JobState { Blocked, Queued, Running, Success, Failure, Cancelled, Error, Skipped, } impl JobState { pub fn as_str(self) -> &'static str { match self { JobState::Blocked => "blocked", JobState::Queued => "queued", JobState::Running => "running", JobState::Success => "success", JobState::Failure => "failure", JobState::Cancelled => "cancelled", JobState::Error => "error", JobState::Skipped => "skipped", } } /// True for states a job cannot leave. pub fn is_terminal(self) -> bool { matches!( self, JobState::Success | JobState::Failure | JobState::Cancelled | JobState::Error | JobState::Skipped ) } } impl FromStr for JobState { type Err = Error; fn from_str(s: &str) -> Result { Ok(match s { "blocked" => JobState::Blocked, "queued" => JobState::Queued, "running" => JobState::Running, "success" => JobState::Success, "failure" => JobState::Failure, "cancelled" => JobState::Cancelled, "error" => JobState::Error, "skipped" => JobState::Skipped, other => return Err(Error::Database(format!("unknown CI job state {other:?}"))), }) } } /// A registered runner. The secret and its hash are never part of this type. #[derive(Debug, Clone, PartialEq, Eq)] pub struct CiRunner { pub id: String, pub name: String, pub labels: Vec, pub created_at: String, pub last_seen_at: Option, pub disabled: bool, /// The concurrency an admin set in the web UI (1 to 64). `None` means the runner uses the /// value from its own `runner.toml`. pub concurrency_override: Option, /// What the runner last reported about itself. All `None` for a runner that never has. pub reported: RunnerReport, /// Jobs this runner is running now, counted from the job table. pub running_jobs: u32, /// The runner's effective config as it last reported it, by field key. Secrets are redacted. pub reported_config: BTreeMap, /// A restart an admin asked for that the runner has not yet carried out. pub restart: Option, /// Admin-set values by field key. A key here beats the runner's own runner.toml. pub config_overrides: BTreeMap, } /// How a runner restarts when an admin asks. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum RestartMode { /// Stop claiming, let the running jobs finish, then restart. Drain, /// Cancel the running jobs and restart at once. Now, } impl RestartMode { pub fn as_str(self) -> &'static str { match self { Self::Drain => "drain", Self::Now => "now", } } } impl std::str::FromStr for RestartMode { type Err = (); fn from_str(s: &str) -> std::result::Result { match s { "drain" => Ok(Self::Drain), "now" => Ok(Self::Now), _ => Err(()), } } } /// A pending runner restart: asked for, not yet seen to happen. #[derive(Debug, Clone, PartialEq, Eq)] pub struct RunnerRestart { pub mode: RestartMode, pub requested_at: String, } /// How a runner config field can be changed from the web UI. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum FieldKind { /// Applied on the runner's next check-in, with no restart. Live, /// Stored now, applied when the runner next starts. Restart, /// Shown only. ReadOnly, } /// One field of `runner.toml` as the admin UI sees it. `key` is the dotted TOML path. #[derive(Debug, Clone, Copy)] pub struct RunnerField { pub key: &'static str, pub kind: FieldKind, } /// Every field the runner reports, in display order. Identity, the secret and the forge URL are /// read-only: changing them from the forge would lock the runner out. Only `concurrency` and /// `labels` can be applied without a restart, because the forge holds the labels itself and the /// runner resizes its job slots live. Everything else is read once at startup. pub const RUNNER_FIELDS: &[RunnerField] = &[ RunnerField { key: "concurrency", kind: FieldKind::Live, }, RunnerField { key: "labels", kind: FieldKind::Live, }, RunnerField { key: "auto_update", kind: FieldKind::Restart, }, RunnerField { key: "executor", kind: FieldKind::Restart, }, RunnerField { key: "work_dir", kind: FieldKind::Restart, }, RunnerField { key: "limits.memory", kind: FieldKind::Restart, }, RunnerField { key: "limits.reserve_memory", kind: FieldKind::Live, }, RunnerField { key: "limits.memory_budget", kind: FieldKind::Live, }, RunnerField { key: "limits.cpus", kind: FieldKind::Restart, }, RunnerField { key: "limits.pids", kind: FieldKind::Restart, }, RunnerField { key: "limits.image_max_gb", kind: FieldKind::Restart, }, RunnerField { key: "images.keep_days", kind: FieldKind::Restart, }, RunnerField { key: "cache_max_gib", kind: FieldKind::Restart, }, RunnerField { key: "sandbox.userns", kind: FieldKind::Restart, }, RunnerField { key: "name", kind: FieldKind::ReadOnly, }, RunnerField { key: "url", kind: FieldKind::ReadOnly, }, RunnerField { key: "runner_id", kind: FieldKind::ReadOnly, }, RunnerField { key: "runner_secret", kind: FieldKind::ReadOnly, }, RunnerField { key: "registry", kind: FieldKind::ReadOnly, }, ]; /// The field with this key. pub fn runner_field(key: &str) -> Option<&'static RunnerField> { RUNNER_FIELDS.iter().find(|f| f.key == key) } fn int_in( raw: &str, lo: i64, hi: i64, what: &str, ) -> std::result::Result { match raw.trim().parse::() { Ok(n) if (lo..=hi).contains(&n) => Ok(serde_json::Value::from(n)), _ => Err(format!("{what} must be a whole number from {lo} to {hi}")), } } /// Checks `raw` (the text the admin typed) for field `key` and returns the JSON value to store. /// `Err` carries a message for the admin. Read-only and unknown fields are refused. pub fn validate_runner_field( key: &str, raw: &str, ) -> std::result::Result { use serde_json::Value; let raw = raw.trim(); match key { "concurrency" => int_in( raw, i64::from(MIN_RUNNER_CONCURRENCY), i64::from(MAX_RUNNER_CONCURRENCY), "concurrency", ), "labels" => { let labels: Vec = raw .split(',') .map(|l| l.trim().to_owned()) .filter(|l| !l.is_empty()) .collect(); if labels .iter() .any(|l| l.len() > 64 || l.contains(char::is_whitespace)) { return Err("each label is 1 to 64 characters with no spaces".into()); } Ok(Value::from(labels)) } "auto_update" => match raw { "true" => Ok(Value::Bool(true)), "false" => Ok(Value::Bool(false)), _ => Err("auto_update must be true or false".into()), }, "executor" => match raw { "builtin" | "podman" => Ok(Value::from(raw)), _ => Err("executor must be builtin or podman".into()), }, "sandbox.userns" => match raw { "auto" | "single" | "subuid" => Ok(Value::from(raw)), _ => Err("userns must be auto, single or subuid".into()), }, "work_dir" => { if raw.starts_with('/') && raw.len() <= 512 && !raw.contains('\0') { Ok(Value::from(raw)) } else { Err("work_dir must be an absolute path".into()) } } "limits.memory" => { let digits = raw.trim_end_matches(|c: char| c.is_ascii_alphabetic()); let unit = &raw[digits.len()..]; let ok = !digits.is_empty() && digits.chars().all(|c| c.is_ascii_digit()) && matches!( unit.to_ascii_lowercase().as_str(), "" | "b" | "k" | "m" | "g" | "t" | "kb" | "mb" | "gb" | "tb" ); if ok { Ok(Value::from(raw)) } else { Err("memory looks like 4g, 512m or a byte count".into()) } } "limits.reserve_memory" => { if size_in_range(raw, 64 << 20, 1 << 40) { Ok(Value::from(raw)) } else { Err("reserve_memory looks like 1g or 512m, from 64m to 1024g".into()) } } "limits.memory_budget" => { if raw == "auto" || size_in_range(raw, 256 << 20, 1 << 50) { Ok(Value::from(raw)) } else { Err("memory_budget is auto, or looks like 6g or 6144m".into()) } } "limits.cpus" => { let ok = raw.parse::().is_ok_and(|n| n > 0.0 && n <= 1024.0) && raw.chars().all(|c| c.is_ascii_digit() || c == '.'); if ok { Ok(Value::from(raw)) } else { Err("cpus is a positive number such as 2 or 1.5".into()) } } "limits.pids" => int_in(raw, 1, 4_194_304, "pids"), "limits.image_max_gb" => int_in(raw, 1, 100_000, "image_max_gb"), "images.keep_days" => int_in(raw, 0, 3650, "keep_days"), "cache_max_gib" => int_in(raw, 0, 1_000_000, "cache_max_gib"), _ => Err("this field cannot be changed from the forge".into()), } } /// Facts a runner reports about itself on a claim or heartbeat. A field the runner did not send is /// `None` and leaves the stored value alone. #[derive(Debug, Clone, Default, PartialEq, Eq)] pub struct RunnerReport { /// The concurrency the runner is applying right now. pub concurrency: Option, pub version: Option, pub cpus: Option, pub memory_bytes: Option, /// The runner's build identity, like `0.1.0 (cf8e648, 2026-10-20)`. pub build: Option, /// Random per process start. A change means the runner restarted. pub boot_id: Option, /// Features the runner says it has. The crate version never changes between builds, so the /// forge gates features on these and not on the version. pub capabilities: Vec, /// The runner's memory budget for jobs, in bytes. pub memory_budget: Option, /// Budget minus what running jobs reserved, as of the runner's last claim. pub memory_free: Option, /// What the runner reserves for a job that declares no `memory`. pub memory_reserve: Option, } impl RunnerReport { /// Memory the running jobs reserved, when the runner reports a budget. pub fn memory_reserved(&self) -> Option { Some(self.memory_budget?.saturating_sub(self.memory_free?)) } } /// How long a queued job that does not fit a runner may wait before smaller jobs stop passing it. /// See [`pick_by_memory`]. pub const STARVE_AFTER_SECS: u64 = 300; /// What a runner can admit right now, from its claim. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct MemoryOffer { /// Budget minus what running jobs reserved, in bytes. pub free: u64, /// The runner's whole budget. A job that reserves more than this is treated as reserving the /// whole budget, so it still runs when the runner is idle instead of waiting forever. pub budget: Option, /// The reservation of a job that declares no `memory`. pub default_reserve: u64, } impl MemoryOffer { /// What a job reserves on this runner: its declared memory or the default, capped at the /// budget. pub fn reservation(&self, declared: Option) -> u64 { let want = declared.unwrap_or(self.default_reserve); self.budget.map_or(want, |budget| want.min(budget)) } /// True when a job with this declared memory fits in the free memory. pub fn fits(&self, declared: Option) -> bool { self.reservation(declared) <= self.free } } /// Picks which of the label-compatible queued jobs, oldest first, a runner with `offer` takes. /// Each candidate is `(declared memory, seconds waited)`. Returns the index of the first job that /// fits. A job that does not fit is skipped so smaller jobs behind it can run, but only while it /// has waited less than `starve_after` seconds. Once an unfit job has waited that long, nothing /// behind it is handed out: the runner drains its running jobs until the old job fits. pub fn pick_by_memory( candidates: &[(Option, u64)], offer: &MemoryOffer, starve_after: u64, ) -> Option { for (i, (declared, waited)) in candidates.iter().enumerate() { if offer.fits(*declared) { return Some(i); } if *waited >= starve_after { return None; } } None } fn size_in_range(raw: &str, lo: u64, hi: u64) -> bool { forge_ci::size::parse_size(raw).is_some_and(|n| (lo..=hi).contains(&n)) } /// The capability of a runner that restarts when the forge asks. pub const CAP_RESTART: &str = "restart"; impl CiRunner { /// True when the runner advertises that it honours a restart request. pub fn supports_restart(&self) -> bool { self.reported.capabilities.iter().any(|c| c == CAP_RESTART) } } /// The smallest and largest concurrency an admin may set. pub const MIN_RUNNER_CONCURRENCY: u32 = 1; pub const MAX_RUNNER_CONCURRENCY: u32 = 64; /// One run of the workflow for a commit. #[derive(Debug, Clone, PartialEq, Eq)] pub struct CiRun { pub id: String, pub repo_id: String, pub number: i64, /// `push`, `tag`, `pull_request` or `manual`. pub trigger: String, pub git_ref: String, pub commit_oid: String, pub pull_number: Option, pub actor_id: String, pub state: RunState, pub config_error: Option, pub created_at: String, pub finished_at: Option, } /// One job of a run. `spec_json` is the JobSpec as JSON text. #[derive(Debug, Clone, PartialEq, Eq)] pub struct CiJob { pub id: String, pub run_id: String, pub name: String, pub spec_json: String, pub state: JobState, pub runner_id: Option, pub exit_code: Option, pub message: Option, pub queued_at: Option, pub started_at: Option, pub finished_at: Option, pub heartbeat_at: Option, pub cancel_requested: bool, pub log_bytes: i64, /// Processes the OOM killer took in the job's cgroup, as its runner reported. `None` when the /// runner did not say (an older runner) or nothing was killed. pub oom_kills: Option, } /// An artifact uploaded by a job. The file itself is stored outside the database. #[derive(Debug, Clone, PartialEq, Eq)] pub struct CiArtifact { pub id: String, pub job_id: String, pub name: String, pub size: i64, pub sha256: String, pub created_at: String, } /// A job to create with a run. `needs` must match the `needs` in `spec_json`. #[derive(Debug, Clone, Copy)] pub struct NewJob<'a> { pub name: &'a str, pub spec_json: &'a str, pub needs: &'a [String], } #[cfg(test)] mod memory_tests { use super::*; const GIB: u64 = 1 << 30; fn offer(free: u64) -> MemoryOffer { MemoryOffer { free: free * GIB, budget: Some(6 * GIB), default_reserve: GIB, } } #[test] fn a_waiting_job_is_passed_only_until_the_threshold() { let young = [(Some(4 * GIB), 299), (Some(GIB), 0)]; assert_eq!(pick_by_memory(&young, &offer(2), 300), Some(1)); let old = [(Some(4 * GIB), 300), (Some(GIB), 0)]; assert_eq!(pick_by_memory(&old, &offer(2), 300), None); assert_eq!(pick_by_memory(&old, &offer(4), 300), Some(0)); } #[test] fn memory_fields_are_validated() { for ok in ["1g", "512m", "2G"] { assert!(validate_runner_field("limits.reserve_memory", ok).is_ok()); } for bad in ["", "0", "lots", "1k", "2t"] { assert!(validate_runner_field("limits.reserve_memory", bad).is_err()); } for ok in ["auto", "6g", "6144m"] { assert!(validate_runner_field("limits.memory_budget", ok).is_ok()); } for bad in ["", "0", "-1", "big"] { assert!(validate_runner_field("limits.memory_budget", bad).is_err()); } assert_eq!( runner_field("limits.memory_budget").map(|f| f.kind), Some(FieldKind::Live) ); } }