From 8609bad307add05c95a3d5fb0378ff403ef6c791 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Tue, 20 Oct 2026 06:45:06 +0300 Subject: [PATCH] =?UTF-8?q?=E2=9C=A8=20feat:=20live=20runner=20config=20an?= =?UTF-8?q?d=20server=20settings=20in=20admin=20UI?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Runner config: per-runner concurrency and labels editable live from /admin/runners, applied via heartbeat/claim header with no restart; the runner limiter resizes without killing running jobs - Runner detail page at /admin/runners/{id} shows every runner.toml field with source and kind (live / restart needed / read-only), secrets redacted, with live SSE updates - New GET/PUT /api/v1/ci/runners/config endpoints; migrations 0044, 0045 - Server settings at /admin/server: DB-backed overrides over the config file (UI > file > default), five tabs, per-field live / restart / read-only / write-only secret kinds, reset to file value - Shared AppState::live() handle, validation via Config::validate, saves audited by key only; migration 0046 --- crates/forge-ci/src/proto.rs | 62 +- .../migrations/0044_runner_concurrency.sql | 11 + .../migrations/0045_runner_config.sql | 8 + .../migrations/0046_server_settings.sql | 9 + crates/forge-core/src/audit.rs | 10 +- crates/forge-core/src/ci.rs | 218 +++ crates/forge-core/src/config.rs | 44 +- crates/forge-core/src/lib.rs | 1 + crates/forge-core/src/server_settings.rs | 1284 +++++++++++++++++ crates/forge-core/src/store/ci.rs | 433 +++++- crates/forge-core/src/store/migrate.rs | 9 + crates/forge-core/src/store/mod.rs | 1 + .../forge-core/src/store/server_settings.rs | 85 ++ crates/forge-runner/src/cli.rs | 30 +- crates/forge-runner/src/client.rs | 135 +- crates/forge-runner/src/config.rs | 180 +++ crates/forge-runner/src/lib.rs | 1 + crates/forge-runner/src/limiter.rs | 181 +++ crates/forge-runner/src/runner.rs | 30 +- crates/forge-runner/tests/flow.rs | 5 +- crates/forge-web/src/api/releases.rs | 3 +- crates/forge-web/src/boot.rs | 29 +- crates/forge-web/src/ci/api.rs | 151 +- crates/forge-web/src/ci/api_tests.rs | 107 +- crates/forge-web/src/ci/live.rs | 15 + crates/forge-web/src/ci/reaper.rs | 4 +- crates/forge-web/src/ci/release.rs | 4 +- crates/forge-web/src/ci/schedule.rs | 11 +- crates/forge-web/src/client_ip.rs | 3 +- crates/forge-web/src/i18n/admin.rs | 96 ++ crates/forge-web/src/lfs/route_tests.rs | 3 +- crates/forge-web/src/lfs/routes.rs | 4 +- crates/forge-web/src/main.rs | 4 +- crates/forge-web/src/pages/admin_runners.rs | 601 +++++++- crates/forge-web/src/pages/admin_server.rs | 690 +++++++++ crates/forge-web/src/pages/invites.rs | 4 +- crates/forge-web/src/pages/mod.rs | 1 + crates/forge-web/src/pages/org_new.rs | 2 +- crates/forge-web/src/pages/register.rs | 11 +- crates/forge-web/src/pages/releases.rs | 2 +- crates/forge-web/src/pages/releases_tests.rs | 3 +- .../forge-web/src/pages/settings_security.rs | 4 +- crates/forge-web/src/state.rs | 29 + crates/forge-web/src/test_support.rs | 4 +- crates/forge-web/src/views/mod.rs | 9 + crates/forge-web/tests/section_nav_e2e.rs | 1 + docs/architecture.md | 14 + docs/ci.md | 24 +- style/main.scss | 116 ++ 49 files changed, 4603 insertions(+), 83 deletions(-) create mode 100644 crates/forge-core/migrations/0044_runner_concurrency.sql create mode 100644 crates/forge-core/migrations/0045_runner_config.sql create mode 100644 crates/forge-core/migrations/0046_server_settings.sql create mode 100644 crates/forge-core/src/server_settings.rs create mode 100644 crates/forge-core/src/store/server_settings.rs create mode 100644 crates/forge-runner/src/limiter.rs create mode 100644 crates/forge-web/src/pages/admin_server.rs diff --git a/crates/forge-ci/src/proto.rs b/crates/forge-ci/src/proto.rs index 22fc977..440d1e4 100644 --- a/crates/forge-ci/src/proto.rs +++ b/crates/forge-ci/src/proto.rs @@ -46,11 +46,31 @@ impl fmt::Debug for RegisterResponse { /// `POST /api/v1/ci/runners/claim`. Long-polls for up to 30s; 204 means nothing was claimed. /// The labels are informational: the server uses the labels stored for the runner. -#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] pub struct ClaimRequest { pub labels: Vec, + /// The runner's live job concurrency. Absent from an older runner. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub concurrency: Option, + /// The runner's version, for the admin page. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub version: Option, + /// Logical CPUs of the runner's host. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub cpus: Option, + /// Total memory of the runner's host, in bytes. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub memory_bytes: Option, } +/// Response header on a claim: the concurrency an admin set for this runner in the web UI. Absent +/// when there is no override, which means the runner uses the value from its own `runner.toml`. +pub const CONCURRENCY_HEADER: &str = "Forge-Runner-Concurrency"; + +/// The smallest and largest job concurrency a runner accepts. +pub const MIN_CONCURRENCY: u32 = 1; +pub const MAX_CONCURRENCY: u32 = 64; + /// Returned with 200 by the claim endpoint. #[derive(Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct JobAssignment { @@ -108,10 +128,30 @@ impl fmt::Debug for JobAssignment { } } +/// `PUT /api/v1/ci/runners/config`: the runner's effective `runner.toml` as flat JSON by dotted key +/// (`limits.memory`). Secrets are redacted by the runner before they get here. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct RunnerConfigReport { + pub config: BTreeMap, +} + +/// Response to `GET` and `PUT /api/v1/ci/runners/config`: the values an admin set in the web UI, +/// by the same dotted keys. A key that is absent has no override. The runner applies the +/// restart-time ones when it starts; `concurrency` and `labels` are live and travel elsewhere. +#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct RunnerConfigOverrides { + #[serde(default)] + pub overrides: BTreeMap, +} + /// Response to `POST /api/v1/ci/jobs/{id}/heartbeat`. #[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] pub struct HeartbeatResponse { pub cancel: bool, + /// The concurrency an admin set in the web UI. Absent means no override (use `runner.toml`). + /// A runner at its limit does not claim, so it learns about a change from its heartbeats. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub concurrency: Option, } /// `POST /api/v1/ci/jobs/{id}/finish`. @@ -142,6 +182,26 @@ mod tests { assert_eq!(json, "\"cancelled\""); } + #[test] + fn old_and_new_claim_and_heartbeat_bodies_parse() { + let old: ClaimRequest = serde_json::from_str(r#"{"labels":["linux"]}"#).unwrap(); + assert_eq!(old.concurrency, None); + let new = ClaimRequest { + labels: vec![], + concurrency: Some(2), + version: Some("1.0.0".into()), + cpus: Some(8), + memory_bytes: Some(1 << 33), + }; + let back: ClaimRequest = + serde_json::from_str(&serde_json::to_string(&new).unwrap()).unwrap(); + assert_eq!(back, new); + let beat: HeartbeatResponse = serde_json::from_str(r#"{"cancel":false}"#).unwrap(); + assert_eq!(beat.concurrency, None); + let json = serde_json::to_string(&beat).unwrap(); + assert_eq!(json, r#"{"cancel":false}"#); + } + #[test] fn finish_request_round_trips() { let req = FinishRequest { diff --git a/crates/forge-core/migrations/0044_runner_concurrency.sql b/crates/forge-core/migrations/0044_runner_concurrency.sql new file mode 100644 index 0000000..13e3cd3 --- /dev/null +++ b/crates/forge-core/migrations/0044_runner_concurrency.sql @@ -0,0 +1,11 @@ +-- Per-runner job concurrency. `concurrency_override` is set by an admin in the web UI (1 to 64); +-- NULL means the runner uses the value from its own runner.toml. The reported_* columns are what the +-- runner last said about itself on a claim or heartbeat: its live concurrency and host facts. All +-- are NULL until a runner that knows how to report has contacted the forge. The number of jobs a +-- runner is running now is counted from ci_jobs, not stored. Applied by store/migrate.rs. + +ALTER TABLE ci_runners ADD COLUMN concurrency_override INTEGER NULL; +ALTER TABLE ci_runners ADD COLUMN reported_concurrency INTEGER NULL; +ALTER TABLE ci_runners ADD COLUMN reported_version TEXT NULL; +ALTER TABLE ci_runners ADD COLUMN reported_cpus INTEGER NULL; +ALTER TABLE ci_runners ADD COLUMN reported_memory_bytes INTEGER NULL; diff --git a/crates/forge-core/migrations/0045_runner_config.sql b/crates/forge-core/migrations/0045_runner_config.sql new file mode 100644 index 0000000..123ad20 --- /dev/null +++ b/crates/forge-core/migrations/0045_runner_config.sql @@ -0,0 +1,8 @@ +-- Per-runner config shown and edited in the admin UI. `reported_config` is the runner's effective +-- runner.toml as flat JSON (secrets redacted), sent when the runner starts. `config_overrides` is a +-- flat JSON object of admin-set values by field key, so a new field needs no migration. Concurrency +-- keeps its own column (0044) because it is applied live. Both are NULL until used. Applied by +-- store/migrate.rs. + +ALTER TABLE ci_runners ADD COLUMN reported_config TEXT NULL; +ALTER TABLE ci_runners ADD COLUMN config_overrides TEXT NULL; diff --git a/crates/forge-core/migrations/0046_server_settings.sql b/crates/forge-core/migrations/0046_server_settings.sql new file mode 100644 index 0000000..fddd3f9 --- /dev/null +++ b/crates/forge-core/migrations/0046_server_settings.sql @@ -0,0 +1,9 @@ +-- Admin overrides of the server config, layered on the config file: UI override, then file, then +-- default. One row per dotted config key (see server_settings.rs), so a new setting needs no +-- migration. A secret field's value is sealed with the instance key. Applied by store/migrate.rs. + +CREATE TABLE server_settings ( + key TEXT PRIMARY KEY, + value TEXT NOT NULL, + updated_at TEXT NOT NULL +); diff --git a/crates/forge-core/src/audit.rs b/crates/forge-core/src/audit.rs index 7e7f802..38dae44 100644 --- a/crates/forge-core/src/audit.rs +++ b/crates/forge-core/src/audit.rs @@ -60,6 +60,7 @@ pub enum AuditAction { CiSecretDeleted, CiRunnerRegistered, CiRunnerDeleted, + CiRunnerConfigChanged, CiRegistrationTokenCreated, AdvisoryAlertDismissed, AdvisoryAlertReopened, @@ -77,6 +78,7 @@ pub enum AuditAction { DiscussionCommentDeleted, MailSettingsUpdated, MailTestQueued, + ServerSettingsUpdated, SnippetCreated, SnippetUpdated, SnippetDeleted, @@ -157,6 +159,7 @@ impl AuditAction { AuditAction::CiSecretDeleted, AuditAction::CiRunnerRegistered, AuditAction::CiRunnerDeleted, + AuditAction::CiRunnerConfigChanged, AuditAction::CiRegistrationTokenCreated, AuditAction::AdvisoryAlertDismissed, AuditAction::AdvisoryAlertReopened, @@ -174,6 +177,7 @@ impl AuditAction { AuditAction::DiscussionCommentDeleted, AuditAction::MailSettingsUpdated, AuditAction::MailTestQueued, + AuditAction::ServerSettingsUpdated, AuditAction::SnippetCreated, AuditAction::SnippetUpdated, AuditAction::SnippetDeleted, @@ -253,6 +257,7 @@ impl AuditAction { AuditAction::CiSecretDeleted => "ci_secret_deleted", AuditAction::CiRunnerRegistered => "ci_runner_registered", AuditAction::CiRunnerDeleted => "ci_runner_deleted", + AuditAction::CiRunnerConfigChanged => "ci_runner_config_changed", AuditAction::CiRegistrationTokenCreated => "ci_registration_token_created", AuditAction::AdvisoryAlertDismissed => "advisory_alert_dismissed", AuditAction::AdvisoryAlertReopened => "advisory_alert_reopened", @@ -270,6 +275,7 @@ impl AuditAction { AuditAction::DiscussionCommentDeleted => "discussion_comment_deleted", AuditAction::MailSettingsUpdated => "mail_settings_updated", AuditAction::MailTestQueued => "mail_test_queued", + AuditAction::ServerSettingsUpdated => "server_settings_updated", AuditAction::SnippetCreated => "snippet_created", AuditAction::SnippetUpdated => "snippet_updated", AuditAction::SnippetDeleted => "snippet_deleted", @@ -390,13 +396,13 @@ mod tests { #[test] fn names_are_unique_and_round_trip() { let mut names: Vec<&str> = AuditAction::ALL.iter().map(|a| a.as_str()).collect(); - assert_eq!(names.len(), 92); + assert_eq!(names.len(), 94); for action in AuditAction::ALL { assert_eq!(AuditAction::parse(action.as_str()), Some(*action)); } names.sort(); names.dedup(); - assert_eq!(names.len(), 92); + assert_eq!(names.len(), 94); assert_eq!(AuditAction::parse("nope"), None); } diff --git a/crates/forge-core/src/ci.rs b/crates/forge-core/src/ci.rs index fb19407..496ea2b 100644 --- a/crates/forge-core/src/ci.rs +++ b/crates/forge-core/src/ci.rs @@ -4,6 +4,7 @@ //! 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}; @@ -126,8 +127,225 @@ pub struct CiRunner { 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, + /// Admin-set values by field key. A key here beats the runner's own runner.toml. + pub config_overrides: BTreeMap, } +/// 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.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.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 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 { diff --git a/crates/forge-core/src/config.rs b/crates/forge-core/src/config.rs index 9dd9b6b..6f3807a 100644 --- a/crates/forge-core/src/config.rs +++ b/crates/forge-core/src/config.rs @@ -604,6 +604,12 @@ trusted_proxies = [] impl Config { /// Loads the config from `path`. Writes development defaults if the file is missing. pub fn load(path: &Path) -> Result { + Self::load_with_keys(path).map(|(config, _)| config) + } + + /// Like `load`, and also returns the dotted keys the file sets (such as `ci.max_log_mb`), so the + /// settings page can tell a file value from a default. + pub fn load_with_keys(path: &Path) -> Result<(Config, std::collections::BTreeSet)> { let text = match std::fs::read_to_string(path) { Ok(text) => text, Err(e) if e.kind() == std::io::ErrorKind::NotFound => { @@ -617,11 +623,39 @@ impl Config { }; let config: Config = toml::from_str(&text).map_err(|e| Error::Config(format!("{}: {e}", path.display())))?; - config.backup.validate()?; - config.replication.validate()?; - config.self_update.validate()?; - config.storage.validate()?; - Ok(config) + config.validate()?; + let mut keys = std::collections::BTreeSet::new(); + if let Ok(table) = text.parse::() { + flatten_keys("", &table, &mut keys); + } + Ok((config, keys)) + } + + /// The cross-field rules the loader applies after parsing. The settings page runs the same + /// check before it stores an override. + pub fn validate(&self) -> Result<()> { + self.backup.validate()?; + self.replication.validate()?; + self.self_update.validate()?; + self.storage.validate()?; + Ok(()) + } +} + +/// Collects the dotted path of every non-table value in `table`. +fn flatten_keys(prefix: &str, table: &toml::Table, out: &mut std::collections::BTreeSet) { + for (key, value) in table { + let path = if prefix.is_empty() { + key.clone() + } else { + format!("{prefix}.{key}") + }; + match value { + toml::Value::Table(inner) => flatten_keys(&path, inner, out), + _ => { + out.insert(path); + } + } } } diff --git a/crates/forge-core/src/lib.rs b/crates/forge-core/src/lib.rs index dd15391..fb02602 100644 --- a/crates/forge-core/src/lib.rs +++ b/crates/forge-core/src/lib.rs @@ -24,6 +24,7 @@ pub mod reactions; pub mod releases; pub mod reviews; pub mod secret; +pub mod server_settings; pub mod session; pub mod store; pub mod time; diff --git a/crates/forge-core/src/server_settings.rs b/crates/forge-core/src/server_settings.rs new file mode 100644 index 0000000..0927b75 --- /dev/null +++ b/crates/forge-core/src/server_settings.rs @@ -0,0 +1,1284 @@ +//! Admin-editable server settings, layered on the config file. +//! +//! Precedence per field: a UI override (table `server_settings`), then the config file, then the +//! built-in default. The config file is never rewritten. Every field has a [`Kind`]: +//! +//! - `Live`: applied to the running process at once. Consumers read [`Live::current`]. +//! - `Restart`: saved and shown as pending until the process restarts. Boot layers the stored +//! overrides on the file config, so they take effect then. +//! - `ReadOnly`: shown, never editable (listen addresses, database path, data dir). +//! +//! A secret field is write-only: the page shows whether it is set, never the value, and the stored +//! value is sealed with the instance key. +//! +//! Values travel as canonical strings (`true`, `42`, `a, b`) so one table holds every field and a +//! new field needs no migration. [`get`] and [`set`] convert between those strings and [`Config`]. + +use std::collections::{BTreeMap, BTreeSet}; +use std::net::IpAddr; +use std::sync::{Arc, RwLock}; + +use ipnet::IpNet; + +use crate::config::{Config, MailTransport, OrgCreation, Registration, StorageBackend}; +use crate::error::{Error, Result}; + +/// How a field reaches the running process. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Kind { + Live, + Restart, + ReadOnly, +} + +/// The page tab a field belongs to. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Group { + General, + Limits, + Storage, + Backups, + Integrations, +} + +impl Group { + pub const ALL: [Group; 5] = [ + Group::General, + Group::Limits, + Group::Storage, + Group::Backups, + Group::Integrations, + ]; + + pub fn slug(self) -> &'static str { + match self { + Group::General => "general", + Group::Limits => "limits", + Group::Storage => "storage", + Group::Backups => "backups", + Group::Integrations => "integrations", + } + } + + pub fn parse(slug: &str) -> Option { + Group::ALL.into_iter().find(|g| g.slug() == slug) + } +} + +/// The value type of a field, which decides the input and the server-side check. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Ty { + Bool, + /// Whole number in `min..=max`. + Uint(u64, u64), + Text, + /// A filesystem path. Empty is allowed and usually means "off". + Path, + Choice(&'static [&'static str]), + /// Comma separated entries. + List, + /// Write-only text. + Secret, + /// Socket address (read-only fields only). + Addr, +} + +#[derive(Debug, Clone, Copy)] +pub struct Field { + pub key: &'static str, + pub group: Group, + pub kind: Kind, + pub ty: Ty, + pub label: &'static str, + pub help: &'static str, +} + +impl Field { + pub fn is_secret(&self) -> bool { + self.ty == Ty::Secret + } +} + +const fn f( + key: &'static str, + group: Group, + kind: Kind, + ty: Ty, + label: &'static str, + help: &'static str, +) -> Field { + Field { + key, + group, + kind, + ty, + label, + help, + } +} + +use Group::{Backups, General, Integrations, Limits, Storage}; +use Kind::{Live as L, ReadOnly as R, Restart as X}; + +const REGISTRATION: &[&str] = &["closed", "invite", "open"]; +const ORG_CREATION: &[&str] = &["all", "admin"]; +const MAIL_TRANSPORT: &[&str] = &["smtp", "log"]; +const BACKEND: &[&str] = &["fs", "s3", "r2"]; +const JURISDICTION: &[&str] = &["", "eu", "fedramp"]; +const MB: Ty = Ty::Uint(1, 1_048_576); +const PORT: Ty = Ty::Uint(1, 65_535); + +/// Every setting, in display order. +pub static FIELDS: &[Field] = &[ + f( + "registration", + General, + L, + Ty::Choice(REGISTRATION), + "Registration", + "Who may create an account: closed, invite only, or open.", + ), + f( + "orgs.creation", + General, + L, + Ty::Choice(ORG_CREATION), + "Organization creation", + "Who may create an organization: all signed-in people, or admins only.", + ), + f( + "trusted_proxies", + General, + L, + Ty::List, + "Trusted proxies", + "Addresses or CIDR networks whose X-Forwarded-For header is trusted. Comma separated.", + ), + f( + "base_url", + General, + X, + Ty::Text, + "Base URL", + "Public URL used in links and clone URLs.", + ), + f( + "user_content_base_url", + General, + X, + Ty::Text, + "User content URL", + "Separate origin that serves raw user files.", + ), + f( + "ssh_public_host", + General, + X, + Ty::Text, + "SSH host shown", + "Host in SSH clone URLs.", + ), + f( + "ssh_public_port", + General, + X, + PORT, + "SSH port shown", + "Port in SSH clone URLs.", + ), + f( + "listen", + General, + R, + Ty::Addr, + "HTTP listen address", + "Set in the config file.", + ), + f( + "user_content_listen", + General, + R, + Ty::Addr, + "User content listen address", + "Set in the config file.", + ), + f( + "ssh_listen", + General, + R, + Ty::Addr, + "SSH listen address", + "Set in the config file.", + ), + f( + "database", + General, + R, + Ty::Path, + "Database file", + "Set in the config file.", + ), + f( + "data_dir", + General, + R, + Ty::Path, + "Data directory", + "Set in the config file.", + ), + f( + "ci.enabled", + Limits, + L, + Ty::Bool, + "CI enabled", + "When off, pushes and pull requests create no runs.", + ), + f( + "ci.max_log_mb", + Limits, + L, + MB, + "Largest job log (MiB)", + "A longer log is truncated.", + ), + f( + "ci.max_artifact_mb", + Limits, + L, + MB, + "Largest artifact (MiB)", + "", + ), + f( + "ci.max_artifacts_per_job", + Limits, + L, + Ty::Uint(1, 100_000), + "Artifacts per job", + "", + ), + f( + "ci.log_retention_days", + Limits, + L, + Ty::Uint(1, 36_500), + "Log retention (days)", + "", + ), + f( + "ci.artifact_retention_days", + Limits, + L, + Ty::Uint(1, 36_500), + "Artifact retention (days)", + "", + ), + f( + "ci.registration_token_hours", + Limits, + L, + Ty::Uint(1, 8_760), + "Runner token lifetime (hours)", + "How long a runner registration token stays valid.", + ), + f( + "lfs.max_object_mb", + Limits, + L, + MB, + "Largest LFS object (MiB)", + "", + ), + f( + "releases.max_asset_mb", + Limits, + L, + MB, + "Largest release asset (MiB)", + "", + ), + f( + "storage.backend", + Storage, + X, + Ty::Choice(BACKEND), + "Backend", + "Where release assets and CI artifacts live: fs, r2 or s3.", + ), + f( + "storage.r2.account_id", + Storage, + X, + Ty::Text, + "R2 account id", + "32 character hex string from the Cloudflare dashboard.", + ), + f("storage.r2.bucket", Storage, X, Ty::Text, "R2 bucket", ""), + f( + "storage.r2.jurisdiction", + Storage, + X, + Ty::Choice(JURISDICTION), + "R2 jurisdiction", + "eu, fedramp, or empty for the global default.", + ), + f( + "storage.r2.prefix", + Storage, + X, + Ty::Text, + "R2 key prefix", + "", + ), + f( + "storage.r2.access_key_id", + Storage, + X, + Ty::Text, + "R2 access key id", + "", + ), + f( + "storage.r2.secret_access_key_file", + Storage, + X, + Ty::Path, + "R2 secret key file", + "Path of the file that holds the secret access key. The key itself is never read here.", + ), + f("storage.s3.bucket", Storage, X, Ty::Text, "S3 bucket", ""), + f("storage.s3.region", Storage, X, Ty::Text, "S3 region", ""), + f( + "storage.s3.endpoint", + Storage, + X, + Ty::Text, + "S3 endpoint", + "Leave empty for AWS.", + ), + f( + "storage.s3.prefix", + Storage, + X, + Ty::Text, + "S3 key prefix", + "", + ), + f( + "storage.s3.access_key_id", + Storage, + X, + Ty::Text, + "S3 access key id", + "", + ), + f( + "storage.s3.secret_access_key_file", + Storage, + X, + Ty::Path, + "S3 secret key file", + "Path of the file that holds the secret access key.", + ), + f( + "storage.s3.allow_http", + Storage, + X, + Ty::Bool, + "S3 allow http", + "", + ), + f( + "storage.s3.virtual_hosted_style", + Storage, + X, + Ty::Bool, + "S3 virtual hosted style", + "", + ), + f( + "backup.dir", + Backups, + X, + Ty::Path, + "Backup directory", + "Empty turns scheduled backups off.", + ), + f( + "backup.interval_hours", + Backups, + X, + Ty::Uint(1, 8_760), + "Backup interval (hours)", + "", + ), + f( + "backup.keep", + Backups, + X, + Ty::Uint(1, 10_000), + "Backup sets kept", + "", + ), + f( + "backup.fsck_interval_days", + Backups, + X, + Ty::Uint(1, 3_650), + "fsck interval (days)", + "", + ), + f( + "backup.healthcheck_url", + Backups, + X, + Ty::Secret, + "Backup healthcheck URL", + "May hold a token, so it is write-only.", + ), + f( + "replication.target", + Backups, + X, + Ty::Text, + "Replication target", + "Empty turns standby replication off.", + ), + f( + "replication.ssh_port", + Backups, + X, + PORT, + "Replication SSH port", + "", + ), + f( + "replication.identity_file", + Backups, + X, + Ty::Path, + "Replication identity file", + "", + ), + f( + "replication.known_hosts_file", + Backups, + X, + Ty::Path, + "Replication known hosts file", + "", + ), + f( + "replication.db_snapshot_minutes", + Backups, + X, + Ty::Uint(1, 525_600), + "Database snapshot (minutes)", + "", + ), + f( + "replication.reconcile_minutes", + Backups, + X, + Ty::Uint(1, 525_600), + "Reconcile (minutes)", + "", + ), + f( + "replication.healthcheck_url", + Backups, + X, + Ty::Secret, + "Replication healthcheck URL", + "May hold a token, so it is write-only.", + ), + f( + "webhooks.allow_http", + Integrations, + X, + Ty::Bool, + "Allow http webhooks", + "Permit http:// hook URLs besides https://.", + ), + f( + "webhooks.allowed_hosts", + Integrations, + X, + Ty::List, + "Webhook allowed hosts", + "Hostnames or CIDR networks reachable even when they resolve to internal addresses. Comma separated.", + ), + f( + "mail.transport", + Integrations, + X, + Ty::Choice(MAIL_TRANSPORT), + "Mail transport", + "smtp sends mail, log writes it to a directory. The SMTP account is on the Mail page.", + ), + f( + "advisories.enabled", + Integrations, + X, + Ty::Bool, + "Security advisories", + "Download OSV dumps and scan lockfiles.", + ), + f( + "advisories.ecosystems", + Integrations, + X, + Ty::List, + "Advisory ecosystems", + "Any of crates.io, npm, Go. Comma separated.", + ), + f( + "advisories.refresh_hours", + Integrations, + X, + Ty::Uint(1, 8_760), + "Advisory refresh (hours)", + "", + ), + f( + "self_update.enabled", + Integrations, + X, + Ty::Bool, + "Self-update", + "Deploy the artifact of a green run of the forge's own repo.", + ), + f( + "self_update.repo", + Integrations, + X, + Ty::Text, + "Self-update repo", + "As owner/name.", + ), + f( + "self_update.branch", + Integrations, + X, + Ty::Text, + "Self-update branch", + "", + ), + f( + "self_update.job", + Integrations, + X, + Ty::Text, + "Self-update job", + "", + ), + f( + "self_update.artifact", + Integrations, + X, + Ty::Text, + "Self-update artifact", + "", + ), +]; + +/// The field for a dotted key. +pub fn field(key: &str) -> Option<&'static Field> { + FIELDS.iter().find(|f| f.key == key) +} + +fn invalid(field: &Field, why: &str) -> Error { + Error::Invalid(format!("{}: {why}", field.label)) +} + +fn split_list(raw: &str) -> Vec { + raw.split([',', '\n', '\r']) + .map(str::trim) + .filter(|s| !s.is_empty()) + .map(str::to_owned) + .collect() +} + +/// Checks `raw` against the field's type and returns its canonical string. +pub fn normalize(field: &Field, raw: &str) -> Result { + let raw = raw.trim(); + match field.ty { + Ty::Bool => match raw { + "true" | "on" => Ok("true".into()), + "false" | "off" | "" => Ok("false".into()), + _ => Err(invalid(field, "must be on or off")), + }, + Ty::Uint(min, max) => { + let n: u64 = raw + .parse() + .map_err(|_| invalid(field, "must be a whole number"))?; + if n < min || n > max { + return Err(invalid(field, &format!("must be between {min} and {max}"))); + } + Ok(n.to_string()) + } + Ty::Choice(options) => { + if options.contains(&raw) { + Ok(raw.to_owned()) + } else { + let shown: Vec<&str> = options + .iter() + .map(|o| if o.is_empty() { "(empty)" } else { o }) + .collect(); + Err(invalid( + field, + &format!("must be one of {}", shown.join(", ")), + )) + } + } + Ty::Text | Ty::Path | Ty::Secret | Ty::Addr => { + if raw.len() > 1024 || raw.chars().any(char::is_control) { + return Err(invalid( + field, + "must be one line of at most 1024 characters", + )); + } + Ok(raw.to_owned()) + } + Ty::List => { + let items = split_list(raw); + if items + .iter() + .any(|i| i.len() > 253 || i.chars().any(char::is_control)) + { + return Err(invalid(field, "has an entry that is too long")); + } + if field.key == "trusted_proxies" { + for item in &items { + if item.parse::().is_err() && item.parse::().is_err() { + return Err(invalid(field, &format!("invalid trusted proxy `{item}`"))); + } + } + } + if field.key == "advisories.ecosystems" { + for item in &items { + if !matches!(item.as_str(), "crates.io" | "npm" | "Go") { + return Err(invalid(field, &format!("unknown ecosystem `{item}`"))); + } + } + } + Ok(items.join(", ")) + } + } +} + +fn b(v: &str) -> bool { + v == "true" +} + +fn n(v: &str) -> u64 { + v.parse().unwrap_or_default() +} + +fn choice(v: &str, table: &[(&str, T)], fallback: T) -> T { + table + .iter() + .find(|(name, _)| *name == v) + .map_or(fallback, |(_, t)| *t) +} + +fn backend_name(b: StorageBackend) -> &'static str { + match b { + StorageBackend::Fs => "fs", + StorageBackend::S3 => "s3", + StorageBackend::R2 => "r2", + } +} + +/// The canonical string of a field's value in `cfg`. Secrets return their real value, so callers +/// that render must not call this for a secret field. +pub fn get(cfg: &Config, key: &str) -> String { + let path = |p: &std::path::Path| p.to_string_lossy().into_owned(); + let list = |v: &[String]| v.join(", "); + match key { + "registration" => match cfg.registration { + Registration::Closed => "closed", + Registration::Invite => "invite", + Registration::Open => "open", + } + .into(), + "orgs.creation" => match cfg.orgs.creation { + OrgCreation::All => "all", + OrgCreation::Admin => "admin", + } + .into(), + "trusted_proxies" => cfg + .trusted_proxies + .iter() + .map(ToString::to_string) + .collect::>() + .join(", "), + "base_url" => cfg.base_url.clone(), + "user_content_base_url" => cfg.user_content_base_url.clone(), + "ssh_public_host" => cfg.ssh_public_host.clone(), + "ssh_public_port" => cfg.ssh_public_port.to_string(), + "listen" => cfg.listen.to_string(), + "user_content_listen" => cfg.user_content_listen.to_string(), + "ssh_listen" => cfg.ssh_listen.to_string(), + "database" => path(&cfg.database), + "data_dir" => path(&cfg.data_dir), + "ci.enabled" => cfg.ci.enabled.to_string(), + "ci.max_log_mb" => cfg.ci.max_log_mb.to_string(), + "ci.max_artifact_mb" => cfg.ci.max_artifact_mb.to_string(), + "ci.max_artifacts_per_job" => cfg.ci.max_artifacts_per_job.to_string(), + "ci.log_retention_days" => cfg.ci.log_retention_days.to_string(), + "ci.artifact_retention_days" => cfg.ci.artifact_retention_days.to_string(), + "ci.registration_token_hours" => cfg.ci.registration_token_hours.to_string(), + "lfs.max_object_mb" => cfg.lfs.max_object_mb.to_string(), + "releases.max_asset_mb" => cfg.releases.max_asset_mb.to_string(), + "storage.backend" => backend_name(cfg.storage.backend).into(), + "storage.r2.account_id" => cfg.storage.r2.account_id.clone(), + "storage.r2.bucket" => cfg.storage.r2.bucket.clone(), + "storage.r2.jurisdiction" => cfg.storage.r2.jurisdiction.clone(), + "storage.r2.prefix" => cfg.storage.r2.prefix.clone(), + "storage.r2.access_key_id" => cfg.storage.r2.access_key_id.clone(), + "storage.r2.secret_access_key_file" => path(&cfg.storage.r2.secret_access_key_file), + "storage.s3.bucket" => cfg.storage.s3.bucket.clone(), + "storage.s3.region" => cfg.storage.s3.region.clone(), + "storage.s3.endpoint" => cfg.storage.s3.endpoint.clone(), + "storage.s3.prefix" => cfg.storage.s3.prefix.clone(), + "storage.s3.access_key_id" => cfg.storage.s3.access_key_id.clone(), + "storage.s3.secret_access_key_file" => path(&cfg.storage.s3.secret_access_key_file), + "storage.s3.allow_http" => cfg.storage.s3.allow_http.to_string(), + "storage.s3.virtual_hosted_style" => cfg.storage.s3.virtual_hosted_style.to_string(), + "backup.dir" => path(&cfg.backup.dir), + "backup.interval_hours" => cfg.backup.interval_hours.to_string(), + "backup.keep" => cfg.backup.keep.to_string(), + "backup.fsck_interval_days" => cfg.backup.fsck_interval_days.to_string(), + "backup.healthcheck_url" => cfg.backup.healthcheck_url.clone(), + "replication.target" => cfg.replication.target.clone(), + "replication.ssh_port" => cfg.replication.ssh_port.to_string(), + "replication.identity_file" => path(&cfg.replication.identity_file), + "replication.known_hosts_file" => path(&cfg.replication.known_hosts_file), + "replication.db_snapshot_minutes" => cfg.replication.db_snapshot_minutes.to_string(), + "replication.reconcile_minutes" => cfg.replication.reconcile_minutes.to_string(), + "replication.healthcheck_url" => cfg.replication.healthcheck_url.clone(), + "webhooks.allow_http" => cfg.webhooks.allow_http.to_string(), + "webhooks.allowed_hosts" => list(&cfg.webhooks.allowed_hosts), + "mail.transport" => match cfg.mail.transport { + MailTransport::Smtp => "smtp", + MailTransport::Log => "log", + } + .into(), + "advisories.enabled" => cfg.advisories.enabled.to_string(), + "advisories.ecosystems" => list(&cfg.advisories.ecosystems), + "advisories.refresh_hours" => cfg.advisories.refresh_hours.to_string(), + "self_update.enabled" => cfg.self_update.enabled.to_string(), + "self_update.repo" => cfg.self_update.repo.clone(), + "self_update.branch" => cfg.self_update.branch.clone(), + "self_update.job" => cfg.self_update.job.clone(), + "self_update.artifact" => cfg.self_update.artifact.clone(), + _ => String::new(), + } +} + +/// Checks `raw` and stores it into `cfg`. A read-only or unknown key is refused. +pub fn set(cfg: &mut Config, key: &str, raw: &str) -> Result<()> { + let field = field(key).ok_or_else(|| Error::Invalid(format!("unknown setting `{key}`")))?; + if field.kind == Kind::ReadOnly { + return Err(invalid(field, "is read-only")); + } + let v = normalize(field, raw)?; + let v = v.as_str(); + let p = || std::path::PathBuf::from(v); + let s = || v.to_owned(); + match key { + "registration" => { + cfg.registration = choice( + v, + &[ + ("closed", Registration::Closed), + ("invite", Registration::Invite), + ("open", Registration::Open), + ], + Registration::Closed, + ) + } + "orgs.creation" => { + cfg.orgs.creation = choice( + v, + &[("all", OrgCreation::All), ("admin", OrgCreation::Admin)], + OrgCreation::All, + ) + } + "trusted_proxies" => { + cfg.trusted_proxies = split_list(v) + .iter() + .filter_map(|e| { + e.parse::() + .ok() + .or_else(|| e.parse::().ok().map(IpNet::from)) + }) + .collect() + } + "base_url" => cfg.base_url = s(), + "user_content_base_url" => cfg.user_content_base_url = s(), + "ssh_public_host" => cfg.ssh_public_host = s(), + "ssh_public_port" => cfg.ssh_public_port = n(v) as u16, + "ci.enabled" => cfg.ci.enabled = b(v), + "ci.max_log_mb" => cfg.ci.max_log_mb = n(v), + "ci.max_artifact_mb" => cfg.ci.max_artifact_mb = n(v), + "ci.max_artifacts_per_job" => cfg.ci.max_artifacts_per_job = n(v) as u32, + "ci.log_retention_days" => cfg.ci.log_retention_days = n(v), + "ci.artifact_retention_days" => cfg.ci.artifact_retention_days = n(v), + "ci.registration_token_hours" => cfg.ci.registration_token_hours = n(v) as u32, + "lfs.max_object_mb" => cfg.lfs.max_object_mb = n(v), + "releases.max_asset_mb" => cfg.releases.max_asset_mb = n(v), + "storage.backend" => { + cfg.storage.backend = choice( + v, + &[ + ("fs", StorageBackend::Fs), + ("s3", StorageBackend::S3), + ("r2", StorageBackend::R2), + ], + StorageBackend::Fs, + ) + } + "storage.r2.account_id" => cfg.storage.r2.account_id = s(), + "storage.r2.bucket" => cfg.storage.r2.bucket = s(), + "storage.r2.jurisdiction" => cfg.storage.r2.jurisdiction = s(), + "storage.r2.prefix" => cfg.storage.r2.prefix = s(), + "storage.r2.access_key_id" => cfg.storage.r2.access_key_id = s(), + "storage.r2.secret_access_key_file" => cfg.storage.r2.secret_access_key_file = p(), + "storage.s3.bucket" => cfg.storage.s3.bucket = s(), + "storage.s3.region" => cfg.storage.s3.region = s(), + "storage.s3.endpoint" => cfg.storage.s3.endpoint = s(), + "storage.s3.prefix" => cfg.storage.s3.prefix = s(), + "storage.s3.access_key_id" => cfg.storage.s3.access_key_id = s(), + "storage.s3.secret_access_key_file" => cfg.storage.s3.secret_access_key_file = p(), + "storage.s3.allow_http" => cfg.storage.s3.allow_http = b(v), + "storage.s3.virtual_hosted_style" => cfg.storage.s3.virtual_hosted_style = b(v), + "backup.dir" => cfg.backup.dir = p(), + "backup.interval_hours" => cfg.backup.interval_hours = n(v), + "backup.keep" => cfg.backup.keep = n(v) as usize, + "backup.fsck_interval_days" => cfg.backup.fsck_interval_days = n(v), + "backup.healthcheck_url" => cfg.backup.healthcheck_url = s(), + "replication.target" => cfg.replication.target = s(), + "replication.ssh_port" => cfg.replication.ssh_port = n(v) as u16, + "replication.identity_file" => cfg.replication.identity_file = p(), + "replication.known_hosts_file" => cfg.replication.known_hosts_file = p(), + "replication.db_snapshot_minutes" => cfg.replication.db_snapshot_minutes = n(v), + "replication.reconcile_minutes" => cfg.replication.reconcile_minutes = n(v), + "replication.healthcheck_url" => cfg.replication.healthcheck_url = s(), + "webhooks.allow_http" => cfg.webhooks.allow_http = b(v), + "webhooks.allowed_hosts" => cfg.webhooks.allowed_hosts = split_list(v), + "mail.transport" => { + cfg.mail.transport = choice( + v, + &[("smtp", MailTransport::Smtp), ("log", MailTransport::Log)], + MailTransport::Smtp, + ) + } + "advisories.enabled" => cfg.advisories.enabled = b(v), + "advisories.ecosystems" => cfg.advisories.ecosystems = split_list(v), + "advisories.refresh_hours" => cfg.advisories.refresh_hours = n(v), + "self_update.enabled" => cfg.self_update.enabled = b(v), + "self_update.repo" => cfg.self_update.repo = s(), + "self_update.branch" => cfg.self_update.branch = s(), + "self_update.job" => cfg.self_update.job = s(), + "self_update.artifact" => cfg.self_update.artifact = s(), + _ => return Err(Error::Invalid(format!("unknown setting `{key}`"))), + } + Ok(()) +} + +/// `file` with every override applied. Read-only keys in `overrides` are ignored. Does not +/// validate the result; see [`Config::validate`]. +pub fn apply(file: &Config, overrides: &BTreeMap) -> Result { + let mut cfg = file.clone(); + for (key, value) in overrides { + if field(key).is_some_and(|f| f.kind != Kind::ReadOnly) { + set(&mut cfg, key, value)?; + } + } + Ok(cfg) +} + +/// The config boot runs with: the file plus every stored override. If that combination no longer +/// validates (say the file changed under an override), the overrides are dropped and the error is +/// returned beside the file config so the caller can log it. +pub fn boot_config(file: &Config, overrides: &BTreeMap) -> (Config, Option) { + match apply(file, overrides).and_then(|c| c.validate().map(|()| c)) { + Ok(config) => (config, None), + Err(e) => (file.clone(), Some(e)), + } +} + +/// `boot` with the `Live` fields taken from `pending`: what the running process uses. +pub fn live_view(boot: &Config, pending: &Config) -> Config { + let mut cfg = boot.clone(); + for f in FIELDS.iter().filter(|f| f.kind == Kind::Live) { + // Values from `get` always pass `normalize`, so this cannot fail. + let _ = set(&mut cfg, f.key, &get(pending, f.key)); + } + cfg +} + +/// Where a field's effective value comes from. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Source { + Default, + File, + Ui, +} + +/// One field as the page shows it. +#[derive(Debug, Clone)] +pub struct FieldView { + pub field: &'static Field, + /// Effective value. Empty for a secret. + pub value: String, + /// The value the file (or default) gives. Empty for a secret. + pub file_value: String, + pub source: Source, + /// For a secret: whether a value is set. + pub secret_set: bool, + /// Saved but not yet running: a restart field whose value differs from the running one. + pub restart_pending: bool, +} + +/// The process-wide settings handle: the file config, the config boot ran with, and the live view +/// consumers read. +pub struct Live { + file: Arc, + file_keys: BTreeSet, + boot: Arc, + current: RwLock>, +} + +impl Live { + pub fn new(file: Arc, file_keys: BTreeSet, boot: Arc) -> Live { + Live { + current: RwLock::new(boot.clone()), + file, + file_keys, + boot, + } + } + + /// The config the running process uses right now. + pub fn current(&self) -> Arc { + self.current + .read() + .unwrap_or_else(|poisoned| poisoned.into_inner()) + .clone() + } + + pub fn file(&self) -> &Config { + &self.file + } + + pub fn boot(&self) -> &Config { + &self.boot + } + + /// Validates `file + overrides`, then publishes its live fields. Nothing changes on error. + pub fn publish(&self, overrides: &BTreeMap) -> Result<()> { + let pending = apply(&self.file, overrides)?; + pending.validate()?; + let live = live_view(&self.boot, &pending); + *self + .current + .write() + .unwrap_or_else(|poisoned| poisoned.into_inner()) = Arc::new(live); + Ok(()) + } + + /// Every field with its effective value and source. + pub fn views(&self, overrides: &BTreeMap) -> Vec { + let pending = apply(&self.file, overrides).unwrap_or_else(|_| (*self.file).clone()); + FIELDS + .iter() + .map(|field| { + let secret = field.is_secret(); + let shown = |cfg: &Config| { + if secret { + String::new() + } else { + get(cfg, field.key) + } + }; + let editable = field.kind != Kind::ReadOnly; + let source = if editable && overrides.contains_key(field.key) { + Source::Ui + } else if self.file_keys.contains(field.key) { + Source::File + } else { + Source::Default + }; + let effective = if editable { &pending } else { &*self.boot }; + FieldView { + field, + value: shown(effective), + file_value: shown(&self.file), + source, + secret_set: secret && !get(effective, field.key).is_empty(), + restart_pending: field.kind == Kind::Restart + && get(&pending, field.key) != get(&self.boot, field.key), + } + }) + .collect() + } + + /// Plans a save of one tab. `submitted` maps key to the raw form value. Returns the keys to + /// store, the keys to clear (submitted equal to the file value), and the validated result. + /// A blank secret keeps what is stored. Nothing is stored on error. + pub fn plan_save( + &self, + existing: &BTreeMap, + group: Group, + submitted: &BTreeMap, + ) -> Result { + let before = apply(&self.file, existing)?; + let mut sets = Vec::new(); + let mut clears = Vec::new(); + let mut next = existing.clone(); + for field in FIELDS + .iter() + .filter(|f| f.group == group && f.kind != Kind::ReadOnly) + { + let Some(raw) = submitted.get(field.key) else { + continue; + }; + if field.is_secret() && raw.trim().is_empty() { + continue; + } + let value = normalize(field, raw)?; + if field.is_secret() { + sets.push((field.key.to_owned(), value.clone())); + next.insert(field.key.to_owned(), value); + continue; + } + let has_override = existing.contains_key(field.key); + if value == get(&before, field.key) { + continue; + } + if value == get(&self.file, field.key) { + if has_override { + clears.push(field.key.to_owned()); + next.remove(field.key); + } + continue; + } + sets.push((field.key.to_owned(), value.clone())); + next.insert(field.key.to_owned(), value); + } + let pending = apply(&self.file, &next)?; + pending.validate()?; + Ok(SavePlan { + sets, + clears, + overrides: next, + }) + } + + /// The overrides after dropping `key`, validated. + pub fn plan_reset( + &self, + existing: &BTreeMap, + key: &str, + ) -> Result> { + field(key).ok_or_else(|| Error::Invalid(format!("unknown setting `{key}`")))?; + let mut next = existing.clone(); + next.remove(key); + apply(&self.file, &next)?.validate()?; + Ok(next) + } +} + +/// The outcome of [`Live::plan_save`]. +#[derive(Debug)] +pub struct SavePlan { + pub sets: Vec<(String, String)>, + pub clears: Vec, + /// All overrides once the plan is applied. + pub overrides: BTreeMap, +} + +#[cfg(test)] +mod tests { + use super::*; + + fn base() -> Config { + toml::from_str( + r#" +database = "/tmp/f.db" +data_dir = "/tmp" +listen = "127.0.0.1:1" +base_url = "http://x" +user_content_base_url = "http://y" +ssh_listen = "127.0.0.1:2" +ssh_public_host = "h" +ssh_public_port = 22 +registration = "closed" +[ci] +max_log_mb = 20 +"#, + ) + .expect("config") + } + + fn live() -> Live { + let file = Arc::new(base()); + let keys = ["registration", "ci.max_log_mb"] + .into_iter() + .map(String::from) + .collect(); + Live::new(file.clone(), keys, file) + } + + fn form(pairs: &[(&str, &str)]) -> BTreeMap { + pairs + .iter() + .map(|(k, v)| ((*k).to_owned(), (*v).to_owned())) + .collect() + } + + #[test] + fn every_field_round_trips_through_get_and_set() { + let cfg = base(); + for f in FIELDS.iter().filter(|f| f.kind != Kind::ReadOnly) { + let mut copy = cfg.clone(); + set(&mut copy, f.key, &get(&cfg, f.key)).unwrap_or_else(|e| panic!("{}: {e}", f.key)); + assert_eq!(get(©, f.key), get(&cfg, f.key), "{}", f.key); + } + } + + #[test] + fn precedence_ui_over_file_over_default() { + let live = live(); + let views = live.views(&BTreeMap::new()); + let find = |views: &[FieldView], key: &str| { + views.iter().find(|v| v.field.key == key).cloned().unwrap() + }; + assert_eq!(find(&views, "ci.max_log_mb").source, Source::File); + assert_eq!(find(&views, "ci.max_log_mb").value, "20"); + assert_eq!(find(&views, "ci.max_artifact_mb").source, Source::Default); + assert_eq!(find(&views, "ci.max_artifact_mb").value, "512"); + + let over = form(&[("ci.max_log_mb", "99")]); + let views = live.views(&over); + let v = find(&views, "ci.max_log_mb"); + assert_eq!( + (v.source, v.value.as_str(), v.file_value.as_str()), + (Source::Ui, "99", "20") + ); + } + + #[test] + fn live_fields_apply_and_reset_restores_the_file_value() { + let live = live(); + assert_eq!(live.current().ci.max_log_mb, 20); + live.publish(&form(&[("ci.max_log_mb", "99"), ("registration", "open")])) + .unwrap(); + assert_eq!(live.current().ci.max_log_mb, 99); + assert_eq!(live.current().registration, Registration::Open); + let next = live + .plan_reset(&form(&[("ci.max_log_mb", "99")]), "ci.max_log_mb") + .unwrap(); + live.publish(&next).unwrap(); + assert_eq!(live.current().ci.max_log_mb, 20); + } + + #[test] + fn restart_fields_do_not_apply_until_boot() { + let live = live(); + let over = form(&[("base_url", "https://new.example")]); + live.publish(&over).unwrap(); + assert_eq!(live.current().base_url, "http://x"); + let v = live.views(&over); + let v = v.iter().find(|v| v.field.key == "base_url").unwrap(); + assert!(v.restart_pending); + let (boot, err) = boot_config(live.file(), &over); + assert!(err.is_none()); + assert_eq!(boot.base_url, "https://new.example"); + let after = Live::new(Arc::new(base()), Default::default(), Arc::new(boot)); + assert!(!after.views(&over).iter().any(|v| v.restart_pending)); + } + + #[test] + fn validation_rejects_bad_values() { + let live = live(); + for (key, value) in [ + ("registration", "everyone"), + ("ci.max_log_mb", "0"), + ("ci.max_log_mb", "lots"), + ("trusted_proxies", "not-an-ip"), + ("ssh_public_port", "70000"), + ("advisories.ecosystems", "pip"), + ("storage.r2.jurisdiction", "mars"), + ("listen", "0.0.0.0:1"), + ] { + let mut cfg = base(); + assert!(set(&mut cfg, key, value).is_err(), "{key}={value}"); + } + // Cross-field loader rules apply to a whole save. + let group_form = form(&[("storage.backend", "r2")]); + assert!( + live.plan_save(&BTreeMap::new(), Group::Storage, &group_form) + .is_err() + ); + let group_form = form(&[("backup.dir", "/var/backups"), ("backup.keep", "5")]); + assert!( + live.plan_save(&BTreeMap::new(), Group::Backups, &group_form) + .is_ok() + ); + } + + #[test] + fn save_skips_unchanged_values_and_clears_when_back_at_the_file_value() { + let live = live(); + let plan = live + .plan_save( + &BTreeMap::new(), + Group::Limits, + &form(&[ + ("ci.max_log_mb", "20"), + ("ci.max_artifact_mb", "512"), + ("ci.enabled", "false"), + ]), + ) + .unwrap(); + assert_eq!( + plan.sets, + vec![("ci.enabled".to_owned(), "false".to_owned())] + ); + let existing = form(&[("ci.max_log_mb", "99")]); + let plan = live + .plan_save(&existing, Group::Limits, &form(&[("ci.max_log_mb", "20")])) + .unwrap(); + assert_eq!(plan.clears, vec!["ci.max_log_mb".to_owned()]); + assert!(plan.overrides.is_empty()); + } + + #[test] + fn secrets_are_never_in_a_view_and_blank_keeps_the_stored_value() { + let live = live(); + let existing = form(&[("backup.healthcheck_url", "https://hc.example/token-123")]); + let views = live.views(&existing); + let v = views + .iter() + .find(|v| v.field.key == "backup.healthcheck_url") + .unwrap(); + assert!(v.secret_set && v.value.is_empty() && v.file_value.is_empty()); + let plan = live + .plan_save( + &existing, + Group::Backups, + &form(&[("backup.healthcheck_url", "")]), + ) + .unwrap(); + assert!(plan.sets.is_empty()); + assert_eq!(plan.overrides, existing); + for view in &views { + assert!(!view.value.contains("token-123")); + } + } +} diff --git a/crates/forge-core/src/store/ci.rs b/crates/forge-core/src/store/ci.rs index 2563ecb..92fefdc 100644 --- a/crates/forge-core/src/store/ci.rs +++ b/crates/forge-core/src/store/ci.rs @@ -13,7 +13,10 @@ use super::{ Store, col_blob, col_bool, col_int, col_opt_text, col_text, db_err, fetch_all, fetch_opt, finish, insert_err, missing_row, new_id, }; -use crate::ci::{CiArtifact, CiJob, CiRun, CiRunner, JobState, NewJob, RunState}; +use crate::ci::{ + CiArtifact, CiJob, CiRun, CiRunner, FieldKind, JobState, MAX_RUNNER_CONCURRENCY, + MIN_RUNNER_CONCURRENCY, NewJob, RunState, RunnerReport, validate_runner_field, +}; use crate::error::{Error, Result}; use crate::secret; use crate::time::{now_stamp, stamp_after}; @@ -23,7 +26,10 @@ const JOB_COLS: &str = "id, run_id, name, spec, state, runner_id, exit_code, mes started_at, finished_at, heartbeat_at, cancel_requested, log_bytes"; const RUN_COLS: &str = "id, repo_id, number, trigger, git_ref, commit_oid, pull_number, actor_id, \ state, config_error, created_at, finished_at"; -const RUNNER_COLS: &str = "id, name, labels, created_at, last_seen_at, disabled"; +const RUNNER_COLS: &str = "id, name, labels, created_at, last_seen_at, disabled, \ + concurrency_override, reported_concurrency, reported_version, reported_cpus, \ + reported_memory_bytes, reported_config, config_overrides, \ + (SELECT COUNT(*) FROM ci_jobs WHERE ci_jobs.runner_id = ci_runners.id AND ci_jobs.state = 'running')"; const ARTIFACT_COLS: &str = "id, job_id, name, size, sha256, created_at"; /// Longest runner name, in bytes. @@ -64,9 +70,31 @@ fn map_runner(row: &Row) -> Result { created_at: col_text(row, 3)?, last_seen_at: col_opt_text(row, 4)?, disabled: col_bool(row, 5)?, + concurrency_override: opt_u32(row, 6)?, + reported: RunnerReport { + concurrency: opt_u32(row, 7)?, + version: col_opt_text(row, 8)?, + cpus: opt_u32(row, 9)?, + memory_bytes: opt_int(row, 10)?.and_then(|n| u64::try_from(n).ok()), + }, + running_jobs: opt_u32(row, 13)?.unwrap_or(0), + reported_config: json_map(row, 11)?, + config_overrides: json_map(row, 12)?, }) } +/// A NULL-able column holding a flat JSON object. Bad or missing JSON reads as empty. +fn json_map(row: &Row, i: usize) -> Result> { + Ok(col_opt_text(row, i)? + .and_then(|text| serde_json::from_str(&text).ok()) + .unwrap_or_default()) +} + +/// A NULL-able integer column that holds a count. +fn opt_u32(row: &Row, i: usize) -> Result> { + Ok(opt_int(row, i)?.and_then(|n| u32::try_from(n).ok())) +} + fn map_run(row: &Row) -> Result { Ok(CiRun { id: col_text(row, 0)?, @@ -464,6 +492,194 @@ impl Store { Ok(()) } + /// Sets (`Some`) or clears (`None`) the admin's concurrency override for a runner. The value + /// must be 1 to 64, else `Invalid`. `NotFound` if the runner does not exist. + pub async fn set_runner_concurrency(&self, id: &str, value: Option) -> Result<()> { + if let Some(n) = value + && !(MIN_RUNNER_CONCURRENCY..=MAX_RUNNER_CONCURRENCY).contains(&n) + { + return Err(Error::Invalid(format!( + "concurrency must be {MIN_RUNNER_CONCURRENCY} to {MAX_RUNNER_CONCURRENCY}" + ))); + } + let conn = self.inner.conn.lock().await; + let n = conn + .execute( + "UPDATE ci_runners SET concurrency_override = ?2 WHERE id = ?1", + (id.to_string(), opt_int_value(value.map(i64::from))), + ) + .await + .map_err(db_err)?; + if n == 0 { + return Err(Error::NotFound); + } + Ok(()) + } + + /// Sets (`Some(text)`) or clears (`None`) the admin override of one runner config field. The + /// text is checked by [`validate_runner_field`]; read-only fields and bad values are `Invalid`. + /// `concurrency` goes to its own column and `labels` also replaces the labels the runner claims + /// with. Clearing `labels` restores the labels the runner reported. `NotFound` if the runner is + /// gone. + pub async fn set_runner_field(&self, id: &str, key: &str, value: Option<&str>) -> Result<()> { + let field = crate::ci::runner_field(key) + .filter(|f| f.kind != FieldKind::ReadOnly) + .ok_or_else(|| Error::Invalid("this field cannot be changed from the forge".into()))?; + let parsed = match value { + Some(raw) => Some(validate_runner_field(key, raw).map_err(Error::Invalid)?), + None => None, + }; + if field.key == "concurrency" { + let n = parsed.as_ref().and_then(serde_json::Value::as_u64); + return self + .set_runner_concurrency(id, n.and_then(|n| u32::try_from(n).ok())) + .await; + } + let conn = self.inner.conn.lock().await; + let mut runner = fetch_opt( + &conn, + &format!("SELECT {RUNNER_COLS} FROM ci_runners WHERE id = ?1"), + (id.to_string(),), + map_runner, + ) + .await? + .ok_or(Error::NotFound)?; + match parsed { + Some(v) => { + runner.config_overrides.insert(key.to_owned(), v); + } + None => { + runner.config_overrides.remove(key); + } + } + let overrides = if runner.config_overrides.is_empty() { + Value::Null + } else { + text( + &serde_json::to_string(&runner.config_overrides) + .map_err(|e| Error::Database(e.to_string()))?, + ) + }; + // The forge claims with the labels it stores, so a labels override is live at once. + let labels = if key == "labels" { + let chosen = runner + .config_overrides + .get("labels") + .or_else(|| runner.reported_config.get("labels")); + chosen.and_then(|v| serde_json::from_value::>(v.clone()).ok()) + } else { + None + }; + if let Some(labels) = labels { + conn.execute( + "UPDATE ci_runners SET config_overrides = ?2, labels = ?3 WHERE id = ?1", + ( + id.to_string(), + overrides, + text( + &serde_json::to_string(&labels) + .map_err(|e| Error::Database(e.to_string()))?, + ), + ), + ) + .await + .map_err(db_err)?; + } else { + conn.execute( + "UPDATE ci_runners SET config_overrides = ?2 WHERE id = ?1", + (id.to_string(), overrides), + ) + .await + .map_err(db_err)?; + } + Ok(()) + } + + /// Stores the runner's effective config (secrets already redacted by the runner). Returns true + /// when it differs from what was stored. + pub async fn set_runner_reported_config( + &self, + id: &str, + config: &BTreeMap, + ) -> Result { + let conn = self.inner.conn.lock().await; + let current = fetch_opt( + &conn, + &format!("SELECT {RUNNER_COLS} FROM ci_runners WHERE id = ?1"), + (id.to_string(),), + map_runner, + ) + .await?; + let Some(current) = current else { + return Ok(false); + }; + if ¤t.reported_config == config { + return Ok(false); + } + conn.execute( + "UPDATE ci_runners SET reported_config = ?2 WHERE id = ?1", + ( + id.to_string(), + text(&serde_json::to_string(config).map_err(|e| Error::Database(e.to_string()))?), + ), + ) + .await + .map_err(db_err)?; + Ok(true) + } + + /// The runner's concurrency override, read fresh. `None` when unset or the runner is gone. + pub async fn runner_concurrency_override(&self, id: &str) -> Result> { + let conn = self.read_conn().await; + let found = fetch_opt( + &conn, + "SELECT concurrency_override FROM ci_runners WHERE id = ?1", + (id.to_string(),), + |row| opt_u32(row, 0), + ) + .await?; + Ok(found.flatten()) + } + + /// Stores what a runner reported about itself. Fields that are `None` keep their stored + /// value. Returns true when a stored value changed, so the caller can tell live pages. + pub async fn record_runner_report(&self, id: &str, report: &RunnerReport) -> Result { + let conn = self.inner.conn.lock().await; + let current = fetch_opt( + &conn, + &format!("SELECT {RUNNER_COLS} FROM ci_runners WHERE id = ?1"), + (id.to_string(),), + map_runner, + ) + .await?; + let Some(current) = current else { + return Ok(false); + }; + let merged = RunnerReport { + concurrency: report.concurrency.or(current.reported.concurrency), + version: report.version.clone().or(current.reported.version.clone()), + cpus: report.cpus.or(current.reported.cpus), + memory_bytes: report.memory_bytes.or(current.reported.memory_bytes), + }; + if merged == current.reported { + return Ok(false); + } + conn.execute( + "UPDATE ci_runners SET reported_concurrency = ?2, reported_version = ?3, \ + reported_cpus = ?4, reported_memory_bytes = ?5 WHERE id = ?1", + ( + id.to_string(), + opt_int_value(merged.concurrency.map(i64::from)), + opt_text(merged.version.as_deref()), + opt_int_value(merged.cpus.map(i64::from)), + opt_int_value(merged.memory_bytes.and_then(|n| i64::try_from(n).ok())), + ), + ) + .await + .map_err(db_err)?; + Ok(true) + } + /// Removes a runner. `NotFound` if it does not exist. pub async fn delete_runner(&self, id: &str) -> Result<()> { let conn = self.inner.conn.lock().await; @@ -1279,6 +1495,11 @@ mod tests { created_at: now_stamp(), last_seen_at: None, disabled: false, + concurrency_override: None, + reported: RunnerReport::default(), + running_jobs: 0, + reported_config: BTreeMap::new(), + config_overrides: BTreeMap::new(), } } @@ -1336,6 +1557,214 @@ mod tests { )); } + #[tokio::test] + async fn concurrency_override_is_set_validated_and_cleared() { + let fx = fixture().await; + let (runner, secret) = runner_with(&fx.store, &fx.tahinli.id, &["linux"]).await; + assert_eq!(runner.concurrency_override, None); + + fx.store + .set_runner_concurrency(&runner.id, Some(4)) + .await + .unwrap(); + let found = fx.store.runner_by_secret(&secret).await.unwrap().unwrap(); + assert_eq!(found.concurrency_override, Some(4)); + assert_eq!( + fx.store + .runner_concurrency_override(&runner.id) + .await + .unwrap(), + Some(4) + ); + + for bad in [0, 65, 1000] { + assert!(matches!( + fx.store.set_runner_concurrency(&runner.id, Some(bad)).await, + Err(Error::Invalid(_)) + )); + } + assert_eq!( + fx.store.list_runners().await.unwrap()[0].concurrency_override, + Some(4), + "a rejected value changes nothing" + ); + for edge in [1, 64] { + fx.store + .set_runner_concurrency(&runner.id, Some(edge)) + .await + .unwrap(); + } + + fx.store + .set_runner_concurrency(&runner.id, None) + .await + .unwrap(); + assert_eq!( + fx.store + .runner_concurrency_override(&runner.id) + .await + .unwrap(), + None + ); + assert!(matches!( + fx.store.set_runner_concurrency("missing", Some(2)).await, + Err(Error::NotFound) + )); + } + + #[tokio::test] + async fn config_field_overrides_validate_and_labels_are_live() { + let fx = fixture().await; + let (runner, secret) = runner_with(&fx.store, &fx.tahinli.id, &["linux"]).await; + let reported: BTreeMap = [ + ("labels".to_owned(), serde_json::json!(["linux"])), + ("limits.memory".to_owned(), serde_json::json!("4g")), + ] + .into(); + assert!( + fx.store + .set_runner_reported_config(&runner.id, &reported) + .await + .unwrap() + ); + assert!( + !fx.store + .set_runner_reported_config(&runner.id, &reported) + .await + .unwrap() + ); + + fx.store + .set_runner_field(&runner.id, "limits.memory", Some("8g")) + .await + .unwrap(); + for (key, bad) in [ + ("limits.memory", "lots"), + ("limits.pids", "0"), + ("executor", "docker"), + ("work_dir", "relative/path"), + ("url", "https://evil.example"), + ("runner_secret", "x"), + ("nonsense", "1"), + ] { + assert!( + matches!( + fx.store.set_runner_field(&runner.id, key, Some(bad)).await, + Err(Error::Invalid(_)) + ), + "{key}={bad}" + ); + } + let found = fx.store.runner_by_secret(&secret).await.unwrap().unwrap(); + assert_eq!(found.config_overrides["limits.memory"], "8g"); + assert_eq!(found.reported_config["limits.memory"], "4g"); + + // Labels are claimed with at once, and a reset restores what the runner reported. + fx.store + .set_runner_field(&runner.id, "labels", Some("linux, arm")) + .await + .unwrap(); + let after = fx.store.list_runners().await.unwrap().remove(0); + assert_eq!(after.labels, vec!["linux".to_string(), "arm".to_string()]); + fx.store + .set_runner_field(&runner.id, "labels", None) + .await + .unwrap(); + fx.store + .set_runner_field(&runner.id, "limits.memory", None) + .await + .unwrap(); + let after = fx.store.list_runners().await.unwrap().remove(0); + assert_eq!(after.labels, vec!["linux".to_string()]); + assert!(after.config_overrides.is_empty()); + + // Concurrency goes through the same entry point. + fx.store + .set_runner_field(&runner.id, "concurrency", Some("6")) + .await + .unwrap(); + assert_eq!( + fx.store.list_runners().await.unwrap()[0].concurrency_override, + Some(6) + ); + assert!(matches!( + fx.store + .set_runner_field(&runner.id, "concurrency", Some("65")) + .await, + Err(Error::Invalid(_)) + )); + } + + #[tokio::test] + async fn runner_report_round_trip_and_running_count() { + let fx = fixture().await; + let (runner, _secret) = runner_with(&fx.store, &fx.tahinli.id, &["linux"]).await; + assert_eq!(runner.reported, RunnerReport::default()); + + let full = RunnerReport { + concurrency: Some(2), + version: Some("0.9.1".into()), + cpus: Some(8), + memory_bytes: Some(16 << 30), + }; + assert!( + fx.store + .record_runner_report(&runner.id, &full) + .await + .unwrap() + ); + assert!( + !fx.store + .record_runner_report(&runner.id, &full) + .await + .unwrap(), + "an identical report is not a change" + ); + // A heartbeat reports only the concurrency and keeps the host facts. + let beat = RunnerReport { + concurrency: Some(3), + ..RunnerReport::default() + }; + assert!( + fx.store + .record_runner_report(&runner.id, &beat) + .await + .unwrap() + ); + let listed = fx.store.list_runners().await.unwrap().remove(0); + assert_eq!( + listed.reported, + RunnerReport { + concurrency: Some(3), + ..full + } + ); + assert_eq!(listed.running_jobs, 0); + + // The running count comes from the job table, and drops when the job finishes. + create( + &fx.store, + &fx.repo.id, + &fx.tahinli.id, + &[job("one", &[], &[])], + false, + ) + .await; + let (claimed, _, _) = fx.store.claim_job(&runner).await.unwrap().unwrap(); + assert_eq!(fx.store.list_runners().await.unwrap()[0].running_jobs, 1); + fx.store + .finish_job(&claimed.id, JobState::Success, Some(0), None) + .await + .unwrap(); + assert_eq!(fx.store.list_runners().await.unwrap()[0].running_jobs, 0); + assert!( + !fx.store + .record_runner_report("missing", &beat) + .await + .unwrap() + ); + } + #[tokio::test] async fn runner_secret_lookup_and_disable() { let fx = fixture().await; diff --git a/crates/forge-core/src/store/migrate.rs b/crates/forge-core/src/store/migrate.rs index da3adb1..7f1a8ff 100644 --- a/crates/forge-core/src/store/migrate.rs +++ b/crates/forge-core/src/store/migrate.rs @@ -62,6 +62,15 @@ pub const MIGRATIONS: &[(u32, &str)] = &[ (41, include_str!("../../migrations/0041_accent.sql")), (42, include_str!("../../migrations/0042_colours.sql")), (43, include_str!("../../migrations/0043_sidebar_side.sql")), + ( + 44, + include_str!("../../migrations/0044_runner_concurrency.sql"), + ), + (45, include_str!("../../migrations/0045_runner_config.sql")), + ( + 46, + include_str!("../../migrations/0046_server_settings.sql"), + ), ]; /// The highest migration version this binary knows about. diff --git a/crates/forge-core/src/store/mod.rs b/crates/forge-core/src/store/mod.rs index 5dd403f..3e0bd51 100644 --- a/crates/forge-core/src/store/mod.rs +++ b/crates/forge-core/src/store/mod.rs @@ -28,6 +28,7 @@ pub mod releases; pub mod replication; pub mod repo_listing; pub mod reviews; +pub mod server_settings; pub mod signatures; pub mod snapshot; pub mod snippets; diff --git a/crates/forge-core/src/store/server_settings.rs b/crates/forge-core/src/store/server_settings.rs new file mode 100644 index 0000000..72316d3 --- /dev/null +++ b/crates/forge-core/src/store/server_settings.rs @@ -0,0 +1,85 @@ +//! Storage for the admin overrides of the server config (migration 0046). One row per dotted key. +//! The key set and the value rules live in `server_settings`; this layer only moves strings, and +//! seals the value of a secret field with the instance key. + +use std::collections::BTreeMap; + +use super::{Store, col_text, db_err, fetch_all}; +use crate::error::{Error, Result}; +use crate::{secret, server_settings}; + +impl Store { + fn settings_key(&self) -> Result<[u8; 32]> { + self.inner + .secret_key + .get() + .copied() + .ok_or_else(|| Error::Crypto("the instance key is not set".into())) + } + + /// Every stored override, with secret values opened. A key this binary does not know is + /// skipped, so an override written by a newer version does not break an older one. + pub async fn server_overrides(&self) -> Result> { + let rows = { + let conn = self.read_conn().await; + fetch_all(&conn, "SELECT key, value FROM server_settings", (), |row| { + Ok((col_text(row, 0)?, col_text(row, 1)?)) + }) + .await? + }; + let mut out = BTreeMap::new(); + for (key, value) in rows { + let Some(field) = server_settings::field(&key) else { + continue; + }; + let value = if field.is_secret() { + let plain = secret::open(&self.settings_key()?, &value)?; + String::from_utf8(plain) + .map_err(|_| Error::Crypto("a sealed setting is not text".into()))? + } else { + value + }; + out.insert(key, value); + } + Ok(out) + } + + /// Stores overrides, replacing any existing value for the same keys. Unknown keys are refused. + pub async fn set_server_overrides(&self, entries: &[(String, String)]) -> Result<()> { + let now = crate::time::now_stamp(); + let mut prepared = Vec::with_capacity(entries.len()); + for (key, value) in entries { + let field = server_settings::field(key) + .ok_or_else(|| Error::Invalid(format!("unknown setting `{key}`")))?; + let stored = if field.is_secret() { + secret::seal(&self.settings_key()?, value.as_bytes())? + } else { + value.clone() + }; + prepared.push((key.clone(), stored)); + } + let conn = self.inner.conn.lock().await; + for (key, stored) in prepared { + conn.execute( + "INSERT INTO server_settings (key, value, updated_at) VALUES (?1, ?2, ?3) \ + ON CONFLICT(key) DO UPDATE SET value = excluded.value, updated_at = excluded.updated_at", + (key, stored, now.clone()), + ) + .await + .map_err(db_err)?; + } + Ok(()) + } + + /// Removes the override of `key`, so the file value (or the default) applies again. + pub async fn clear_server_override(&self, key: &str) -> Result<()> { + let conn = self.inner.conn.lock().await; + conn.execute( + "DELETE FROM server_settings WHERE key = ?1", + (key.to_owned(),), + ) + .await + .map_err(db_err)?; + Ok(()) + } +} diff --git a/crates/forge-runner/src/cli.rs b/crates/forge-runner/src/cli.rs index 519de2e..86e8382 100644 --- a/crates/forge-runner/src/cli.rs +++ b/crates/forge-runner/src/cli.rs @@ -223,7 +223,8 @@ async fn run(cli: Cli) -> Result> { Some(p) => p, None => config::default_config_path()?, }; - let cfg = config::load(&path)?; + let mut cfg = config::load(&path)?; + sync_config_with_forge(&mut cfg).await; let shutdown = CancellationToken::new(); let cache_root = cfg.work_dir.join(".cache"); let cache_cap = cfg.cache_max_gib; @@ -343,3 +344,30 @@ fn spawn_image_gc( fn gib(gb: u64) -> u64 { gb.saturating_mul(1024 * 1024 * 1024) } + +/// Applies the admin's startup-time overrides from the forge to `cfg` and reports the effective +/// config back for the admin page. Best effort: an older forge, or a forge that cannot be reached, +/// leaves `runner.toml` as it is and the runner starts anyway. +async fn sync_config_with_forge(cfg: &mut RunnerConfig) { + let client = match crate::client::ForgeClient::new(&cfg.url) { + Ok(client) => client, + Err(e) => { + tracing::warn!(error = %e, "cannot sync config with the forge"); + return; + } + }; + match client.get_config(&cfg.runner_secret).await { + Ok(reply) => { + for line in cfg.apply_overrides(&reply.overrides) { + tracing::info!("{line}"); + } + } + Err(e) => tracing::warn!(error = %e, "cannot read config overrides, using runner.toml"), + } + let report = forge_ci::proto::RunnerConfigReport { + config: cfg.report(), + }; + if let Err(e) = client.put_config(&cfg.runner_secret, &report).await { + tracing::warn!(error = %e, "cannot report config to the forge"); + } +} diff --git a/crates/forge-runner/src/client.rs b/crates/forge-runner/src/client.rs index 70af693..f4a5b1f 100644 --- a/crates/forge-runner/src/client.rs +++ b/crates/forge-runner/src/client.rs @@ -7,8 +7,8 @@ use std::path::Path; use std::time::Duration; use forge_ci::proto::{ - ClaimRequest, FinishRequest, HeartbeatResponse, JobAssignment, RegisterRequest, - RegisterResponse, + CONCURRENCY_HEADER, ClaimRequest, FinishRequest, HeartbeatResponse, JobAssignment, + RegisterRequest, RegisterResponse, RunnerConfigOverrides, RunnerConfigReport, }; use reqwest::StatusCode; use reqwest::header::{CONTENT_LENGTH, HeaderMap}; @@ -30,6 +30,7 @@ const HEADER_RUNNER_TARGET: &str = "Forge-Runner-Target"; const HEADER_BINARY_SHA256: &str = "Forge-Binary-Sha256"; /// `GET`: the forge's binary, for a runner that is updating itself. const BINARY_PATH: &str = "/api/v1/ci/runners/binary"; +const CONFIG_PATH: &str = "/api/v1/ci/runners/config"; /// Errors from talking to the forge. #[derive(Debug, thiserror::Error)] @@ -60,6 +61,8 @@ pub struct ClaimReply { pub job: Option, /// The sha256 (lowercase hex) of the forge's binary, when the response advertises one. pub binary_sha256: Option, + /// The concurrency an admin set in the web UI. `None` means no override. + pub concurrency: Option, } /// A client for one forge base URL. @@ -104,8 +107,24 @@ impl ForgeClient { runner_secret: &str, labels: &[String], ) -> Result { + self.claim_with(runner_secret, labels, None).await + } + + /// Like [`ForgeClient::claim`], and also reports the runner's live `concurrency` and its host + /// facts (version, CPUs, memory) for the forge's admin page. + pub async fn claim_with( + &self, + runner_secret: &str, + labels: &[String], + concurrency: Option, + ) -> Result { + let host = host_facts(); let req = ClaimRequest { labels: labels.to_vec(), + concurrency: concurrency.and_then(|n| u32::try_from(n).ok()), + version: Some(env!("CARGO_PKG_VERSION").to_owned()), + cpus: host.cpus, + memory_bytes: host.memory_bytes, }; let target = format!("{}-{}", std::env::consts::ARCH, std::env::consts::OS); let resp = self @@ -118,19 +137,54 @@ impl ForgeClient { .send() .await?; let binary_sha256 = advertised_sha256(resp.headers()); + let concurrency = advertised_concurrency(resp.headers()); match resp.status() { StatusCode::NO_CONTENT => Ok(ClaimReply { job: None, binary_sha256, + concurrency, }), status if status.is_success() => Ok(ClaimReply { job: Some(resp.json().await?), binary_sha256, + concurrency, }), _ => Err(status_error(resp).await), } } + /// `GET /api/v1/ci/runners/config`: the overrides an admin set for this runner. + pub async fn get_config( + &self, + runner_secret: &str, + ) -> Result { + let resp = self + .http + .get(self.url(CONFIG_PATH)) + .bearer_auth(runner_secret) + .timeout(REQUEST_TIMEOUT) + .send() + .await?; + json_or_error(resp).await + } + + /// `PUT /api/v1/ci/runners/config`: reports the runner's effective config (secrets redacted). + pub async fn put_config( + &self, + runner_secret: &str, + report: &RunnerConfigReport, + ) -> Result { + let resp = self + .http + .put(self.url(CONFIG_PATH)) + .bearer_auth(runner_secret) + .json(report) + .timeout(REQUEST_TIMEOUT) + .send() + .await?; + json_or_error(resp).await + } + /// `GET /api/v1/ci/runners/binary`. Streams the forge's binary into `dest` and returns the /// sha256 (lowercase hex) of the bytes written. The caller checks it against the advertised /// value and syncs the file. @@ -200,14 +254,25 @@ impl ForgeClient { job_id: &str, job_token: &str, ) -> Result { - let resp = self + self.heartbeat_with(job_id, job_token, None).await + } + + /// Like [`ForgeClient::heartbeat`], and also tells the forge the runner's live `concurrency`. + pub async fn heartbeat_with( + &self, + job_id: &str, + job_token: &str, + concurrency: Option, + ) -> Result { + let mut req = self .http .post(self.url(&format!("/api/v1/ci/jobs/{job_id}/heartbeat"))) .bearer_auth(job_token) - .timeout(REQUEST_TIMEOUT) - .send() - .await?; - json_or_error(resp).await + .timeout(REQUEST_TIMEOUT); + if let Some(n) = concurrency { + req = req.header(CONCURRENCY_HEADER, n.to_string()); + } + json_or_error(req.send().await?).await } /// `PUT /api/v1/ci/jobs/{id}/artifacts/{name}`, streaming the file from disk. @@ -270,6 +335,40 @@ fn advertised_sha256(headers: &HeaderMap) -> Option { .filter(|v| !v.is_empty()) } +/// The `Forge-Runner-Concurrency` header, when it holds a number. +fn advertised_concurrency(headers: &HeaderMap) -> Option { + headers + .get(CONCURRENCY_HEADER)? + .to_str() + .ok()? + .trim() + .parse() + .ok() +} + +/// Cheap facts about the host that help an admin size the runner's concurrency. +struct HostFacts { + cpus: Option, + memory_bytes: Option, +} + +fn host_facts() -> HostFacts { + let cpus = std::thread::available_parallelism() + .ok() + .and_then(|n| u32::try_from(n.get()).ok()); + let memory_bytes = std::fs::read_to_string("/proc/meminfo") + .ok() + .and_then(|text| parse_mem_total(&text)); + HostFacts { cpus, memory_bytes } +} + +/// `MemTotal` of `/proc/meminfo`, in bytes. The file reports kibibytes. +fn parse_mem_total(meminfo: &str) -> Option { + let line = meminfo.lines().find(|l| l.starts_with("MemTotal:"))?; + let kib: u64 = line.split_whitespace().nth(1)?.parse().ok()?; + kib.checked_mul(1024) +} + async fn json_or_error(resp: reqwest::Response) -> Result { if resp.status().is_success() { Ok(resp.json().await?) @@ -289,3 +388,25 @@ async fn status_error(resp: reqwest::Response) -> ClientError { .collect(); ClientError::Status { status, body } } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn reads_mem_total_in_bytes() { + let text = "MemTotal: 16384 kB\nMemFree: 100 kB\n"; + assert_eq!(parse_mem_total(text), Some(16384 * 1024)); + assert_eq!(parse_mem_total("nothing"), None); + } + + #[test] + fn concurrency_header_must_be_a_number() { + let mut headers = HeaderMap::new(); + assert_eq!(advertised_concurrency(&headers), None); + headers.insert(CONCURRENCY_HEADER, "3".parse().unwrap()); + assert_eq!(advertised_concurrency(&headers), Some(3)); + headers.insert(CONCURRENCY_HEADER, "many".parse().unwrap()); + assert_eq!(advertised_concurrency(&headers), None); + } +} diff --git a/crates/forge-runner/src/config.rs b/crates/forge-runner/src/config.rs index 405f062..365c776 100644 --- a/crates/forge-runner/src/config.rs +++ b/crates/forge-runner/src/config.rs @@ -1,5 +1,6 @@ //! The runner's `runner.toml`: the forge URL, the runner identity and secret, and local limits. +use std::collections::BTreeMap; use std::fmt; use std::fs::OpenOptions; use std::io::Write; @@ -220,6 +221,144 @@ impl RunnerConfig { } } +impl RunnerConfig { + /// The effective config as flat JSON by dotted key, for the forge's admin page. The runner + /// secret and registry passwords are never included: the secret shows as `` and a + /// registry shows only as `host (username)`. + pub fn report(&self) -> BTreeMap { + use serde_json::json; + let mut m = BTreeMap::new(); + m.insert("url".into(), json!(self.url)); + m.insert("runner_id".into(), json!(self.runner_id)); + m.insert("runner_secret".into(), json!("")); + m.insert("name".into(), json!(self.name)); + m.insert("labels".into(), json!(self.labels)); + m.insert( + "work_dir".into(), + json!(self.work_dir.display().to_string()), + ); + m.insert("concurrency".into(), json!(self.concurrency)); + m.insert("limits.memory".into(), json!(self.limits.memory)); + m.insert("limits.cpus".into(), json!(self.limits.cpus)); + m.insert("limits.pids".into(), json!(self.limits.pids)); + m.insert( + "limits.image_max_gb".into(), + json!(self.limits.image_max_gb), + ); + let executor = match self.executor { + ExecutorKind::Builtin => "builtin", + ExecutorKind::Podman => "podman", + }; + m.insert("executor".into(), json!(executor)); + m.insert("images.keep_days".into(), json!(self.images.keep_days)); + let userns = match self.sandbox.userns { + UsernsMode::Auto => "auto", + UsernsMode::Single => "single", + UsernsMode::Subuid => "subuid", + }; + m.insert("sandbox.userns".into(), json!(userns)); + m.insert("auto_update".into(), json!(self.auto_update)); + m.insert("cache_max_gib".into(), json!(self.cache_max_gib)); + let registries: Vec = self + .registries + .iter() + .map(|r| format!("{} ({})", r.host, r.username)) + .collect(); + m.insert("registry".into(), json!(registries)); + m + } + + /// Applies the admin's overrides from the forge to this in-memory config, for the fields that + /// are read at startup. `runner.toml` on disk is not touched. A value that does not fit is + /// skipped. Returns one line per field that changed. `concurrency` and `labels` are live and + /// handled elsewhere, and fields that are not listed here are ignored. + pub fn apply_overrides( + &mut self, + overrides: &BTreeMap, + ) -> Vec { + let mut changed = Vec::new(); + let before = self.clone(); + for (key, value) in overrides { + let ok = match key.as_str() { + "auto_update" => value.as_bool().map(|v| self.auto_update = v).is_some(), + "work_dir" => value + .as_str() + .map(|v| self.work_dir = PathBuf::from(v)) + .is_some(), + "limits.memory" => value + .as_str() + .map(|v| self.limits.memory = v.to_owned()) + .is_some(), + "limits.cpus" => value + .as_str() + .map(|v| self.limits.cpus = v.to_owned()) + .is_some(), + "limits.pids" => value + .as_u64() + .and_then(|v| u32::try_from(v).ok()) + .map(|v| self.limits.pids = v) + .is_some(), + "limits.image_max_gb" => value + .as_u64() + .map(|v| self.limits.image_max_gb = v) + .is_some(), + "images.keep_days" => value + .as_u64() + .and_then(|v| u32::try_from(v).ok()) + .map(|v| self.images.keep_days = v) + .is_some(), + "cache_max_gib" => value.as_u64().map(|v| self.cache_max_gib = v).is_some(), + "executor" => match value.as_str() { + Some("builtin") => { + self.executor = ExecutorKind::Builtin; + true + } + Some("podman") => { + self.executor = ExecutorKind::Podman; + true + } + _ => false, + }, + "sandbox.userns" => match value.as_str() { + Some("auto") => { + self.sandbox.userns = UsernsMode::Auto; + true + } + Some("single") => { + self.sandbox.userns = UsernsMode::Single; + true + } + Some("subuid") => { + self.sandbox.userns = UsernsMode::Subuid; + true + } + _ => false, + }, + _ => continue, + }; + if !ok { + tracing::warn!(field = %key, "ignoring a config override with the wrong type"); + } + } + if self.validate().is_err() { + tracing::warn!("config overrides from the forge do not validate, ignoring them"); + *self = before; + return changed; + } + let (old, new) = (before.report(), self.report()); + for (key, value) in &new { + if old.get(key) != Some(value) { + changed.push(format!( + "runner: {key} {} -> {} (set from server)", + old.get(key).map_or_else(String::new, ToString::to_string), + value + )); + } + } + changed + } +} + /// The default config path: `$HOME/.config/forge-runner/runner.toml`. pub fn default_config_path() -> Result { let home = std::env::var_os("HOME").ok_or(ConfigError::NoHome)?; @@ -271,6 +410,47 @@ pub fn save(path: &Path, config: &RunnerConfig) -> Result<(), ConfigError> { #[cfg(test)] mod tests { + #[test] + fn report_redacts_secrets() { + let dir = tempfile::tempdir().expect("tempdir"); + let mut config = sample(dir.path()); + config.registries.push(RegistryConfig { + host: "ghcr.io".into(), + username: "tahinli".into(), + password: "hunter2-pass".into(), + }); + let text = serde_json::to_string(&config.report()).unwrap(); + assert!(!text.contains(&config.runner_secret)); + assert!(!text.contains("hunter2-pass")); + assert!(text.contains("ghcr.io (tahinli)")); + assert!(text.contains("limits.memory")); + } + + #[test] + fn overrides_apply_and_bad_ones_are_dropped() { + let dir = tempfile::tempdir().expect("tempdir"); + let mut config = sample(dir.path()); + let mut ov = BTreeMap::new(); + ov.insert("limits.memory".to_owned(), serde_json::json!("8g")); + ov.insert("cache_max_gib".to_owned(), serde_json::json!(5)); + ov.insert("concurrency".to_owned(), serde_json::json!(9)); + let lines = config.apply_overrides(&ov); + assert_eq!(config.limits.memory, "8g"); + assert_eq!(config.cache_max_gib, 5); + assert_ne!( + config.concurrency, 9, + "concurrency is live, not a startup override" + ); + assert_eq!(lines.len(), 2, "{lines:?}"); + + // A value that breaks validation drops the whole set and keeps the config. + let before = config.clone(); + let mut bad = BTreeMap::new(); + bad.insert("limits.image_max_gb".to_owned(), serde_json::json!(0)); + assert!(config.apply_overrides(&bad).is_empty()); + assert_eq!(config, before); + } + use super::*; fn sample(dir: &Path) -> RunnerConfig { diff --git a/crates/forge-runner/src/lib.rs b/crates/forge-runner/src/lib.rs index 634e597..9bf74d2 100644 --- a/crates/forge-runner/src/lib.rs +++ b/crates/forge-runner/src/lib.rs @@ -11,6 +11,7 @@ pub mod cli; pub mod client; pub mod config; pub mod executor; +pub mod limiter; pub mod logs; pub mod oci; pub mod runner; diff --git a/crates/forge-runner/src/limiter.rs b/crates/forge-runner/src/limiter.rs new file mode 100644 index 0000000..ae0a030 --- /dev/null +++ b/crates/forge-runner/src/limiter.rs @@ -0,0 +1,181 @@ +//! The runner's live job concurrency. A tokio semaphore holds one permit per job slot. The limit +//! can change while jobs run: growing adds permits, shrinking takes back the idle ones at once and +//! the rest as running jobs finish. A running job is never killed to make room. + +use std::sync::{Arc, Mutex, PoisonError}; + +use forge_ci::proto::{MAX_CONCURRENCY, MIN_CONCURRENCY}; +use tokio::sync::{OwnedSemaphorePermit, Semaphore}; + +/// A resizable job limit. Cheap to share: clone the `Arc`. +pub struct Limiter { + semaphore: Arc, + /// The value from `runner.toml`, used when the forge has no override. + base: usize, + state: Mutex, +} + +struct State { + /// The limit now. + current: usize, + /// Permits still to be taken back after a shrink, because jobs hold them. Each is forgotten + /// instead of released when the job that holds one finishes. + debt: usize, +} + +/// A job slot. Dropping it frees the slot, or retires it when the limit was lowered. +pub struct Slot { + permit: Option, + limiter: Arc, +} + +impl Drop for Slot { + fn drop(&mut self) { + if let Some(permit) = self.permit.take() { + self.limiter.release(permit); + } + } +} + +/// Clamps a requested concurrency to the range the forge accepts. +pub fn clamp(n: usize) -> usize { + n.clamp(MIN_CONCURRENCY as usize, MAX_CONCURRENCY as usize) +} + +impl Limiter { + /// A limiter starting at `base`, which is also the fallback when the forge sends no override. + pub fn new(base: usize) -> Arc { + let base = clamp(base); + Arc::new(Self { + semaphore: Arc::new(Semaphore::new(base)), + base, + state: Mutex::new(State { + current: base, + debt: 0, + }), + }) + } + + /// The limit now. + pub fn current(&self) -> usize { + self.lock().current + } + + fn lock(&self) -> std::sync::MutexGuard<'_, State> { + self.state.lock().unwrap_or_else(PoisonError::into_inner) + } + + /// Waits for a free slot. `Err` when the semaphore is closed, which only happens at teardown. + pub async fn acquire(self: &Arc) -> Result { + let permit = self.semaphore.clone().acquire_owned().await?; + Ok(Slot { + permit: Some(permit), + limiter: self.clone(), + }) + } + + /// Applies what the forge asked for: `Some(n)` is an override, `None` means no override and + /// brings back the `runner.toml` value. Returns `(old, new)` when the limit changed. + pub fn apply(&self, desired: Option) -> Option<(usize, usize)> { + let target = desired.map_or(self.base, |n| clamp(n as usize)); + let mut state = self.lock(); + let old = state.current; + if target == old { + return None; + } + if target > old { + let mut grow = target - old; + // Permits owed from an earlier shrink are simply kept. + let cancel = grow.min(state.debt); + state.debt -= cancel; + grow -= cancel; + self.semaphore.add_permits(grow); + } else { + let shrink = old - target; + let taken = self.semaphore.forget_permits(shrink); + state.debt += shrink - taken; + } + state.current = target; + Some((old, target)) + } + + /// Like [`Limiter::apply`], and logs one line when the limit changes. + pub fn apply_logged(&self, desired: Option) { + if let Some((old, new)) = self.apply(desired) { + let from = if desired.is_some() { + "set from server" + } else { + "back to runner.toml" + }; + tracing::info!("runner: concurrency {old} -> {new} ({from})"); + } + } + + fn release(&self, permit: OwnedSemaphorePermit) { + let mut state = self.lock(); + if state.debt > 0 { + state.debt -= 1; + permit.forget(); + } + // Otherwise the permit drops here and the slot is free again. + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[tokio::test] + async fn grows_and_shrinks_without_touching_running_jobs() { + let limiter = Limiter::new(1); + let a = limiter.acquire().await.unwrap(); + assert_eq!(limiter.apply(Some(3)), Some((1, 3))); + assert_eq!(limiter.apply(Some(3)), None, "no change, no log"); + let b = limiter.acquire().await.unwrap(); + let c = limiter.acquire().await.unwrap(); + assert_eq!(limiter.semaphore.available_permits(), 0); + + // Shrink to 1 while all 3 slots are busy: nothing is killed, the slots retire on finish. + assert_eq!(limiter.apply(Some(1)), Some((3, 1))); + assert_eq!(limiter.current(), 1); + drop(b); + drop(c); + assert_eq!(limiter.semaphore.available_permits(), 0, "both retired"); + drop(a); + assert_eq!(limiter.semaphore.available_permits(), 1, "one slot stays"); + } + + #[tokio::test] + async fn idle_permits_are_taken_back_at_once() { + let limiter = Limiter::new(4); + let held = limiter.acquire().await.unwrap(); + assert_eq!(limiter.apply(Some(2)), Some((4, 2))); + assert_eq!(limiter.semaphore.available_permits(), 1); + drop(held); + assert_eq!(limiter.semaphore.available_permits(), 2); + } + + #[tokio::test] + async fn growing_cancels_owed_retirements() { + let limiter = Limiter::new(3); + let slots = [ + limiter.acquire().await.unwrap(), + limiter.acquire().await.unwrap(), + limiter.acquire().await.unwrap(), + ]; + limiter.apply(Some(1)); + limiter.apply(Some(3)); + drop(slots); + assert_eq!(limiter.semaphore.available_permits(), 3); + assert_eq!(limiter.current(), 3); + } + + #[tokio::test] + async fn no_override_returns_to_the_config_value_and_values_are_clamped() { + let limiter = Limiter::new(2); + assert_eq!(limiter.apply(Some(500)), Some((2, 64))); + assert_eq!(limiter.apply(Some(0)), Some((64, 1))); + assert_eq!(limiter.apply(None), Some((1, 2))); + assert_eq!(limiter.apply(None), None); + } +} diff --git a/crates/forge-runner/src/runner.rs b/crates/forge-runner/src/runner.rs index edb2e9f..6e0b90f 100644 --- a/crates/forge-runner/src/runner.rs +++ b/crates/forge-runner/src/runner.rs @@ -6,7 +6,7 @@ use std::time::Duration; use forge_ci::mask::{MaskStream, Masker}; use forge_ci::proto::{FinishRequest, JobAssignment, Outcome}; -use tokio::sync::{Semaphore, mpsc}; +use tokio::sync::mpsc; use tokio::task::{JoinHandle, JoinSet}; use tokio::time::Instant; use tokio_util::sync::CancellationToken; @@ -16,6 +16,7 @@ use crate::cache::CacheStore; use crate::client::{ClientError, ForgeClient}; use crate::config::RunnerConfig; use crate::executor::{ExecRequest, ExecResult, Executor}; +use crate::limiter::Limiter; use crate::logs::{self, PumpConfig}; use crate::update::{self, Installed, UpdateState}; use crate::workspace; @@ -66,6 +67,8 @@ pub struct Runner { options: RunOptions, /// The build cache, when it is on. See [`CacheStore`]. cache: Option>, + /// The live job limit. Starts at `runner.toml` and follows the forge's override. + limiter: Arc, } impl Runner { @@ -75,12 +78,14 @@ impl Runner { options: RunOptions, ) -> Result { let client = ForgeClient::new(&config.url)?; + let limiter = Limiter::new(config.concurrency); Ok(Self { client, config: Arc::new(config), executor, options, cache: None, + limiter, }) } @@ -101,7 +106,6 @@ impl Runner { /// claimed. Once the running jobs finish, the binary is replaced and the loop returns /// [`RunEnd::Updated`]. pub async fn run(&self, shutdown: CancellationToken) -> RunEnd { - let semaphore = Arc::new(Semaphore::new(self.config.concurrency)); let mut jobs: JoinSet<()> = JoinSet::new(); // Hashed once at startup. Without it, or with auto_update off, updates stay disabled. let exe = if self.config.auto_update { @@ -121,7 +125,7 @@ impl Runner { ); tracing::info!( name = %self.config.name, - concurrency = self.config.concurrency, + concurrency = self.limiter.current(), auto_update = updates.enabled(), "runner started" ); @@ -162,7 +166,7 @@ impl Runner { let permit = tokio::select! { _ = shutdown.cancelled() => break RunEnd::Stopped, - permit = semaphore.clone().acquire_owned() => match permit { + permit = self.limiter.acquire() => match permit { Ok(permit) => permit, Err(_) => break RunEnd::Stopped, }, @@ -172,10 +176,16 @@ impl Runner { drop(permit); break RunEnd::Stopped; } - r = self.client.claim(&self.config.runner_secret, &self.config.labels) => r, + r = self.client.claim_with( + &self.config.runner_secret, + &self.config.labels, + Some(self.limiter.current()), + ) => r, }; match claimed { Ok(reply) => { + // No header means no override: back to the runner.toml value. + self.limiter.apply_logged(reply.concurrency); if updates.observe(reply.binary_sha256.as_deref()) && let Some(sha) = updates.pending() { @@ -353,6 +363,7 @@ impl Runner { fn spawn_heartbeat(&self, job: &JobAssignment, cancel: CancellationToken) -> JoinHandle<()> { let client = self.client.clone(); + let limiter = self.limiter.clone(); let job_id = job.job_id.clone(); let token = job.job_token.clone(); let every = self.options.heartbeat_every; @@ -360,13 +371,18 @@ impl Runner { let mut ticker = tokio::time::interval_at(Instant::now() + every, every); loop { ticker.tick().await; - match client.heartbeat(&job_id, &token).await { + match client + .heartbeat_with(&job_id, &token, Some(limiter.current())) + .await + { Ok(beat) if beat.cancel => { + limiter.apply_logged(beat.concurrency); tracing::info!(job_id = %job_id, "forge requested cancel"); cancel.cancel(); return; } - Ok(_) => {} + // A runner at its limit does not claim, so the heartbeat carries changes too. + Ok(beat) => limiter.apply_logged(beat.concurrency), Err(e) => tracing::warn!(job_id = %job_id, error = %e, "heartbeat failed"), } } diff --git a/crates/forge-runner/tests/flow.rs b/crates/forge-runner/tests/flow.rs index 52ae108..768fe53 100644 --- a/crates/forge-runner/tests/flow.rs +++ b/crates/forge-runner/tests/flow.rs @@ -127,7 +127,10 @@ fn route( ("POST", ["heartbeat"]) => { st.heartbeats += 1; let cancel = st.cancel_from_heartbeat.is_some_and(|n| st.heartbeats >= n); - Reply::json(&forge_ci::proto::HeartbeatResponse { cancel }) + Reply::json(&forge_ci::proto::HeartbeatResponse { + cancel, + concurrency: None, + }) } ("PUT", ["artifacts", name]) => { let valid = !name.is_empty() diff --git a/crates/forge-web/src/api/releases.rs b/crates/forge-web/src/api/releases.rs index 7c9b034..3f1cd81 100644 --- a/crates/forge-web/src/api/releases.rs +++ b/crates/forge-web/src/api/releases.rs @@ -395,7 +395,6 @@ fn no_content() -> Response { #[cfg(test)] mod tests { use std::path::{Path, PathBuf}; - use std::sync::Arc; use forge_core::releases::NewRelease; use forge_core::token::{generate_token, hash_token}; @@ -448,7 +447,7 @@ mod tests { if let Some(mb) = max_mb { let mut config = (*state.config).clone(); config.releases.max_asset_mb = mb; - state.config = Arc::new(config); + state.set_config(config); } let store = state.store.clone(); let owner = store diff --git a/crates/forge-web/src/boot.rs b/crates/forge-web/src/boot.rs index f2a97d7..5101178 100644 --- a/crates/forge-web/src/boot.rs +++ b/crates/forge-web/src/boot.rs @@ -31,7 +31,13 @@ use crate::state::AppState; pub(crate) const MIN_GIT: (u32, u32, u32) = (2, 38, 0); /// Boots every component and serves until shutdown. -pub async fn serve(config: Config) -> forge_core::Result<()> { +pub async fn serve( + file_config: Config, + file_keys: std::collections::BTreeSet, +) -> forge_core::Result<()> { + // The listeners, the database path and the data dir are read-only settings, so the file alone + // decides them. Every other field may be overridden in the database, which opens below. + let config = file_config.clone(); let listen = config.listen; let user_content_listen = config.user_content_listen; let ssh_listen = config.ssh_listen; @@ -45,6 +51,24 @@ pub async fn serve(config: Config) -> forge_core::Result<()> { let store = Store::open(&config.database).await?; store.set_secret_key(*key); + // Layer the stored admin overrides on the file config (UI, then file, then default). If the + // two no longer validate together, boot with the file alone and say so. + let overrides = store.server_overrides().await?; + let (config, rejected) = forge_core::server_settings::boot_config(&config, &overrides); + if let Some(e) = rejected { + tracing::error!(error = %e, "stored server settings do not validate with the config file, ignoring them"); + } + let file_config = Arc::new(file_config); + let config = Arc::new(config); + let settings = Arc::new(forge_core::server_settings::Live::new( + file_config, + file_keys, + config.clone(), + )); + if let Err(e) = settings.publish(&overrides) { + tracing::error!(error = %e, "stored live server settings were not applied"); + } + let git = Arc::new(GitEnv { git_bin: find_git(), data_dir: data_dir.clone(), @@ -91,7 +115,8 @@ pub async fn serve(config: Config) -> forge_core::Result<()> { }; let blobs = crate::blobs::BlobStore::from_config(&config.storage, &data_dir)?; let state = AppState { - config: Arc::new(config), + config, + settings, store, git, key, diff --git a/crates/forge-web/src/ci/api.rs b/crates/forge-web/src/ci/api.rs index 4f2fe46..64cec02 100644 --- a/crates/forge-web/src/ci/api.rs +++ b/crates/forge-web/src/ci/api.rs @@ -9,10 +9,11 @@ use forge_ci::config::JobSpec; use forge_ci::mask::Masker; use forge_ci::proto::{ - FinishRequest, HeartbeatResponse, JobAssignment, Outcome, RegisterRequest, RegisterResponse, + CONCURRENCY_HEADER, ClaimRequest, FinishRequest, HeartbeatResponse, JobAssignment, Outcome, + RegisterRequest, RegisterResponse, RunnerConfigOverrides, RunnerConfigReport, }; use forge_core::Error as CoreError; -use forge_core::ci::{CiJob, CiRun, CiRunner, JobState, RunState}; +use forge_core::ci::{CiJob, CiRun, CiRunner, JobState, RunState, RunnerReport}; use futures_util::StreamExt; use http::header::HeaderValue; use serde_json::json; @@ -170,21 +171,109 @@ async fn register(cx: &Cx, body: Body) -> topcoat::Result { } #[route(POST "/api/v1/ci/runners/claim")] -async fn claim(cx: &Cx) -> topcoat::Result { - let mut res = claim_work(cx).await?; +async fn claim(cx: &Cx, body: Body) -> topcoat::Result { + let state = app_context::(cx); + // The labels in the request are ignored: the labels stored at registration are used. + let runner = match runner_from(state, headers(cx)).await { + Ok(runner) => runner, + Err(res) => return Ok(*res), + }; + // What the runner says about itself. An older runner sends only labels, and a body that does + // not parse is not worth failing a claim over. + let request: ClaimRequest = match api::read_body(body, MAX_JSON_BODY).await { + Ok(bytes) => serde_json::from_slice(&bytes).unwrap_or_default(), + Err(_) => ClaimRequest::default(), + }; + note_report( + state, + &runner.id, + &RunnerReport { + concurrency: request.concurrency, + version: request.version.filter(|v| v.len() <= 64), + cpus: request.cpus, + memory_bytes: request.memory_bytes, + }, + ) + .await; + let mut res = claim_work(state, &runner).await?; + // The override can change during the long poll, so it is read at answer time. + set_concurrency_header(state, &runner.id, &mut res).await; // Advertises the binary sha256 when self-update is on and the runner asked for this target. - self_update::advertise(app_context::(cx), headers(cx), &mut res); + self_update::advertise(state, headers(cx), &mut res); Ok(res) } -async fn claim_work(cx: &Cx) -> topcoat::Result { +/// Stores a runner's self report and wakes the admin pages when it changed something. +async fn note_report(state: &AppState, runner_id: &str, report: &RunnerReport) { + match state.store.record_runner_report(runner_id, report).await { + Ok(true) => state.ci_live.bump_runners(), + Ok(false) => {} + Err(e) => tracing::warn!(error = %e, "ci: runner report not stored"), + } +} + +/// Adds the admin's concurrency override to a claim answer. No header means no override. +async fn set_concurrency_header(state: &AppState, runner_id: &str, res: &mut Response) { + if !matches!(res.status(), StatusCode::OK | StatusCode::NO_CONTENT) { + return; + } + if let Ok(Some(n)) = state.store.runner_concurrency_override(runner_id).await + && let Ok(value) = HeaderValue::from_str(&n.to_string()) + { + res.headers_mut().insert(CONCURRENCY_HEADER, value); + } +} + +/// `GET` and `PUT /api/v1/ci/runners/config`. The runner reads the admin's overrides when it +/// starts, applies them to its in-memory config, then reports its effective config here. +#[route(GET "/api/v1/ci/runners/config")] +async fn runner_config_get(cx: &Cx) -> topcoat::Result { let state = app_context::(cx); - // The labels in the request are ignored: the labels stored at registration are used. let runner = match runner_from(state, headers(cx)).await { Ok(runner) => runner, Err(res) => return Ok(*res), }; + Ok(overrides_response(&runner)) +} +#[route(PUT "/api/v1/ci/runners/config")] +async fn runner_config_put(cx: &Cx, body: Body) -> topcoat::Result { + let state = app_context::(cx); + let runner = match runner_from(state, headers(cx)).await { + Ok(runner) => runner, + Err(res) => return Ok(*res), + }; + let report: RunnerConfigReport = match json_body(body).await { + Ok(report) => report, + Err(res) => return Ok(*res), + }; + // Only known fields are kept, and the secret is never stored whatever the runner sent. + let mut config = report.config; + config.retain(|key, _| forge_core::ci::runner_field(key).is_some()); + config.insert("runner_secret".into(), json!("")); + match state + .store + .set_runner_reported_config(&runner.id, &config) + .await + { + Ok(true) => state.ci_live.bump_runners(), + Ok(false) => {} + Err(e) => return Ok(*api::internal(e)), + } + Ok(overrides_response(&runner)) +} + +fn overrides_response(runner: &CiRunner) -> Response { + let reply = RunnerConfigOverrides { + overrides: runner.config_overrides.clone(), + }; + api::json( + StatusCode::OK, + &serde_json::to_value(reply).unwrap_or_default(), + ) +} + +async fn claim_work(state: &AppState, runner: &CiRunner) -> topcoat::Result { // Arm the wake-up before each attempt, so a job queued during the attempt is not missed. // Producers use notify_waiters, which wakes every claimer, so a runner whose labels // don't match a job re-arms and keeps waiting for the rest of CLAIM_WAIT. @@ -194,7 +283,7 @@ async fn claim_work(cx: &Cx) -> topcoat::Result { let mut woken = std::pin::pin!(waker.notified()); woken.as_mut().enable(); - match try_claim(state, &runner).await { + match try_claim(state, runner).await { Ok(Some(assignment)) => return Ok(assignment_response(&assignment)), Ok(None) => {} Err(res) => return Ok(*res), @@ -252,6 +341,7 @@ async fn try_claim(state: &AppState, runner: &CiRunner) -> Result topcoat::Result { Err(res) => return Ok(*res), }; match state.store.heartbeat(&job.id).await { - Ok(cancel) => Ok(api::json( - StatusCode::OK, - &serde_json::to_value(HeartbeatResponse { cancel }).unwrap_or_default(), - )), + Ok(cancel) => { + // The runner says its live concurrency, and the answer carries the admin's override. + // A runner at its limit does not claim, so this is how it learns about a change. + let mut concurrency = None; + if let Some(runner_id) = job.runner_id.as_deref() { + let said = headers(cx) + .get(CONCURRENCY_HEADER) + .and_then(|v| v.to_str().ok()) + .and_then(|v| v.trim().parse::().ok()); + note_report( + state, + runner_id, + &RunnerReport { + concurrency: said, + ..RunnerReport::default() + }, + ) + .await; + concurrency = state + .store + .runner_concurrency_override(runner_id) + .await + .ok() + .flatten(); + } + Ok(api::json( + StatusCode::OK, + &serde_json::to_value(HeartbeatResponse { + cancel, + concurrency, + }) + .unwrap_or_default(), + )) + } Err(e) => Ok(*api::internal(e)), } } @@ -557,7 +677,7 @@ async fn store_log_bytes( ) -> Result<(), Refusal> { use tokio::io::AsyncWriteExt; - let cap = state.config.ci.max_log_mb.saturating_mul(MIB); + let cap = state.live().ci.max_log_mb.saturating_mul(MIB); let current = match tokio::fs::metadata(path).await { Ok(meta) => meta.len(), Err(e) if e.kind() == std::io::ErrorKind::NotFound => 0, @@ -610,7 +730,7 @@ async fn upload_artifact(cx: &Cx, body: Body) -> topcoat::Result { /// Streams the body to a temporary blob, then records the artifact and moves the blob to its /// final key `ci/`. The id is only known once the row exists. async fn upload(state: &AppState, job: &CiJob, name: &str, body: Body) -> Result { - let max_artifacts = state.config.ci.max_artifacts_per_job; + let max_artifacts = state.live().ci.max_artifacts_per_job; let existing = state .store .list_artifacts(&job.id) @@ -629,7 +749,7 @@ async fn upload(state: &AppState, job: &CiJob, name: &str, body: Body) -> Result ))); } - let max_bytes = state.config.ci.max_artifact_mb.saturating_mul(MIB); + let max_bytes = state.live().ci.max_artifact_mb.saturating_mul(MIB); let temp_key = format!("ci/tmp/{}", ulid::Ulid::generate()); let mut writer = state .blobs @@ -770,6 +890,7 @@ async fn finish_job( crate::ci::sync_status(state, &run, &other).await; } } + state.ci_live.bump_runners(); if any_changed { state.ci_live.bump_run(&run.id); state.ci_live.bump_repo(&run.repo_id); diff --git a/crates/forge-web/src/ci/api_tests.rs b/crates/forge-web/src/ci/api_tests.rs index 0581c3c..f3a48c0 100644 --- a/crates/forge-web/src/ci/api_tests.rs +++ b/crates/forge-web/src/ci/api_tests.rs @@ -2,7 +2,6 @@ //! server builds, so routing, auth and status codes are covered end to end. use std::path::PathBuf; -use std::sync::Arc; use forge_core::ci::{CiJob, CiRun, CiRunner, JobState, NewJob}; use forge_core::{Repo, Store, Visibility}; @@ -79,7 +78,7 @@ async fn bare(tune: impl FnOnce(&mut forge_core::config::CiConfig)) -> Bare { let mut state = test_state(&data_dir).await; let mut config = (*state.config).clone(); tune(&mut config.ci); - state.config = Arc::new(config); + state.set_config(config); let store = state.store.clone(); let router = app_router(state); let owner = store @@ -462,6 +461,108 @@ async fn heartbeat_reports_a_cancel_request() { assert_eq!(sent.status, 401); } +#[tokio::test] +async fn claim_and_heartbeat_carry_the_concurrency_round_trip() { + let env = bare(|_| {}).await; + let (runner, secret) = runner(&env, &[]).await; + make_run(&env, "push", None, COMMIT, &[job("a", spec(&[], &[]))]).await; + make_run(&env, "push", None, COMMIT, &[job("b", spec(&[], &[]))]).await; + + // No override: no header, and the runner's report is stored. + let body = serde_json::json!({ + "labels": [], "concurrency": 2, "version": "9.9.9", "cpus": 8, "memory_bytes": 17179869184u64 + }); + let sent = send( + &env.router, + "POST", + "/api/v1/ci/runners/claim", + &[bearer(&secret)], + json_body(&body), + ) + .await; + assert_eq!(sent.status, 200); + assert!(sent.headers.get("Forge-Runner-Concurrency").is_none()); + let listed = env.store.list_runners().await.unwrap().remove(0); + assert_eq!(listed.reported.concurrency, Some(2)); + assert_eq!(listed.reported.version.as_deref(), Some("9.9.9")); + assert_eq!(listed.reported.cpus, Some(8)); + assert_eq!(listed.running_jobs, 1); + let assignment = sent.json(); + + // An override set in the UI shows up on the next claim answer and on the heartbeat. + env.store + .set_runner_concurrency(&runner.id, Some(4)) + .await + .unwrap(); + let sent = claim(&env.router, &secret).await; + assert_eq!(sent.status, 200); + assert_eq!(sent.headers.get("Forge-Runner-Concurrency").unwrap(), "4"); + let uri = format!( + "/api/v1/ci/jobs/{}/heartbeat", + assignment["job_id"].as_str().unwrap() + ); + let token = assignment["job_token"].as_str().unwrap(); + let beat = send( + &env.router, + "POST", + &uri, + &[bearer(token), ("Forge-Runner-Concurrency", "3".to_owned())], + Vec::new(), + ) + .await; + assert_eq!(beat.json()["concurrency"], 4); + assert_eq!( + env.store.list_runners().await.unwrap()[0] + .reported + .concurrency, + Some(3), + "the heartbeat reports the live value" + ); + + // Cleared: the heartbeat omits the field, so an old runner sees the same body as before. + env.store + .set_runner_concurrency(&runner.id, None) + .await + .unwrap(); + let beat = send(&env.router, "POST", &uri, &[bearer(token)], Vec::new()).await; + assert!(beat.json().get("concurrency").is_none()); +} + +#[tokio::test] +async fn runner_config_report_and_overrides_round_trip() { + let env = bare(|_| {}).await; + let (runner, secret) = runner(&env, &["linux"]).await; + let uri = "/api/v1/ci/runners/config"; + let sent = send(&env.router, "GET", uri, &[bearer(&secret)], Vec::new()).await; + assert_eq!(sent.status, 200); + assert_eq!(sent.json()["overrides"], serde_json::json!({})); + + env.store + .set_runner_field(&runner.id, "limits.memory", Some("8g")) + .await + .unwrap(); + let report = serde_json::json!({ "config": { + "limits.memory": "4g", "runner_secret": "leaked", "bogus.key": 1, "concurrency": 1 + }}); + let sent = send( + &env.router, + "PUT", + uri, + &[bearer(&secret)], + json_body(&report), + ) + .await; + assert_eq!(sent.status, 200); + assert_eq!(sent.json()["overrides"]["limits.memory"], "8g"); + let stored = env.store.list_runners().await.unwrap().remove(0); + assert_eq!(stored.reported_config["limits.memory"], "4g"); + assert_eq!(stored.reported_config["runner_secret"], ""); + assert!(!stored.reported_config.contains_key("bogus.key")); + + let sent = send(&env.router, "GET", uri, &[bearer("wrong")], Vec::new()).await; + assert_eq!(sent.status, 401); +} + // --------------------------------------------------------------------------------------------- // Artifacts // --------------------------------------------------------------------------------------------- @@ -852,7 +953,7 @@ async fn bare_with_self_update() -> Bare { let mut config = (*state.config).clone(); config.self_update.enabled = true; config.self_update.repo = format!("{OWNER}/{REPO}"); - state.config = Arc::new(config); + state.set_config(config); let store = state.store.clone(); let router = app_router(state); let owner = store diff --git a/crates/forge-web/src/ci/live.rs b/crates/forge-web/src/ci/live.rs index 8cae2bc..3cea8c2 100644 --- a/crates/forge-web/src/ci/live.rs +++ b/crates/forge-web/src/ci/live.rs @@ -12,12 +12,16 @@ use std::sync::{Mutex, MutexGuard, PoisonError}; use tokio::sync::watch; +/// The one key of the runners signal: the admin pages follow all runners together. +const RUNNERS_KEY: &str = "runners"; + /// The change counters of CI jobs and runs, each keyed by its id. #[derive(Default)] pub struct CiLive { jobs: Signals, runs: Signals, repos: Signals, + runners: Signals, } impl CiLive { @@ -38,6 +42,17 @@ impl CiLive { self.repos.subscribe(repo_id) } + /// Subscribes to changes of any runner: its jobs, live concurrency, reported config or an + /// admin edit. Same rules as [`CiLive::subscribe_job`]. + pub fn subscribe_runners(&self) -> watch::Receiver { + self.runners.subscribe(RUNNERS_KEY) + } + + /// Wakes the subscribers of the runners pages. + pub fn bump_runners(&self) { + self.runners.bump(RUNNERS_KEY); + } + /// Wakes the subscribers of job `job_id`: its log grew or its state changed. Does nothing when /// nobody is subscribed. pub fn bump_job(&self, job_id: &str) { diff --git a/crates/forge-web/src/ci/reaper.rs b/crates/forge-web/src/ci/reaper.rs index 183eac8..918d415 100644 --- a/crates/forge-web/src/ci/reaper.rs +++ b/crates/forge-web/src/ci/reaper.rs @@ -81,6 +81,7 @@ pub async fn reap_before(state: &AppState, older_than: &str) -> usize { state.ci_waker.notify_waiters(); } if !jobs.is_empty() { + state.ci_live.bump_runners(); tracing::warn!(count = jobs.len(), "ci: reaped lost jobs"); } jobs.len() @@ -89,7 +90,8 @@ pub async fn reap_before(state: &AppState, older_than: &str) -> usize { /// Deletes the logs and artifacts past retention. Rows go first (in the store); files follow. /// Missing files are fine. Returns `(logs deleted, artifacts deleted)` as attempted. pub async fn purge_once(state: &AppState) -> (usize, usize) { - let ci = &state.config.ci; + let live = state.live(); + let ci = &live.ci; let day = |days: u64| Duration::from_secs(days.saturating_mul(24 * 60 * 60)); let logs_before = stamp_ago(day(ci.log_retention_days)); let artifacts_before = stamp_ago(day(ci.artifact_retention_days)); diff --git a/crates/forge-web/src/ci/release.rs b/crates/forge-web/src/ci/release.rs index f9cdd82..41a7bac 100644 --- a/crates/forge-web/src/ci/release.rs +++ b/crates/forge-web/src/ci/release.rs @@ -96,7 +96,7 @@ async fn publish( return format!("Could not publish release {tag}: could not list the jobs"); } }; - let max_bytes = state.config.releases.max_asset_mb.saturating_mul(MIB); + let max_bytes = state.live().releases.max_asset_mb.saturating_mul(MIB); let mut attached = 0usize; let mut failed: Vec = Vec::new(); for job in &jobs { @@ -329,7 +329,7 @@ fn bullets(commits: &[CommitInfo], footer: Option<&str>) -> String { /// the outcome is not lost, it is also in the tracing output. async fn note(state: &AppState, job: &CiJob, text: &str) { let line = format!("[forge] {text}\n"); - let cap = state.config.ci.max_log_mb.saturating_mul(MIB); + let cap = state.live().ci.max_log_mb.saturating_mul(MIB); let path = log_path(&state.config.data_dir, &job.id); let current = match tokio::fs::metadata(&path).await { Ok(meta) => meta.len(), diff --git a/crates/forge-web/src/ci/schedule.rs b/crates/forge-web/src/ci/schedule.rs index 1220b33..c9d5cfc 100644 --- a/crates/forge-web/src/ci/schedule.rs +++ b/crates/forge-web/src/ci/schedule.rs @@ -71,7 +71,7 @@ pub async fn on_ref_update( refname: &str, new_oid: &str, ) { - if !state.config.ci.enabled || is_zero_oid(new_oid) { + if !state.live().ci.enabled || is_zero_oid(new_oid) { return; } let (trigger, event) = if let Some(branch) = refname.strip_prefix("refs/heads/") { @@ -118,7 +118,7 @@ pub async fn on_ref_update( /// the head commit. A fork head, or an author without Write on the base repo, creates the run in /// WaitingApproval: its jobs wait until someone approves it. pub async fn on_pull_event(state: &AppState, repo: &Repo, pull: &PullRequest, actor_id: &str) { - if !state.config.ci.enabled { + if !state.live().ci.enabled { return; } if let Err(e) = pull_run(state, repo, pull, actor_id).await { @@ -171,7 +171,7 @@ pub async fn manual_run( branch: &str, actor_id: &str, ) -> forge_core::Result { - if !state.config.ci.enabled { + if !state.live().ci.enabled { return Err(forge_core::Error::Invalid( "CI is disabled on this instance".into(), )); @@ -293,7 +293,7 @@ async fn note_warnings( for warning in warnings.iter().take(MAX_WARNING_LINES) { text.push_str(&format!("[forge] warning: {warning}\n")); } - let cap = state.config.ci.max_log_mb.saturating_mul(MIB); + let cap = state.live().ci.max_log_mb.saturating_mul(MIB); for job in state.store.jobs_for_run(&run.id).await? { let path = log_path(&state.config.data_dir, &job.id); let current = match tokio::fs::metadata(&path).await { @@ -466,7 +466,6 @@ where #[cfg(test)] pub(super) mod tests { use std::path::{Path, PathBuf}; - use std::sync::Arc; use std::time::Duration; use forge_core::ci::{CiJob, CiRunner, JobState, RunState}; @@ -1020,7 +1019,7 @@ run = "make" let mut cfg = (*fx.state.config).clone(); cfg.ci.log_retention_days = 0; let mut state = fx.state.clone(); - state.config = Arc::new(cfg); + state.set_config(cfg); tokio::time::sleep(Duration::from_millis(1100)).await; let (logs, _artifacts) = purge_once(&state).await; diff --git a/crates/forge-web/src/client_ip.rs b/crates/forge-web/src/client_ip.rs index caa9605..157eb84 100644 --- a/crates/forge-web/src/client_ip.rs +++ b/crates/forge-web/src/client_ip.rs @@ -18,7 +18,8 @@ const FORWARDED_FOR: &str = "x-forwarded-for"; /// The client IP for this request, bucketed for throttling. Unix-socket requests have no peer and /// map to the unspecified address. pub fn client_ip(cx: &Cx) -> IpAddr { - let trusted = &app_context::(cx).config.trusted_proxies; + let live = app_context::(cx).live(); + let trusted = &live.trusted_proxies; let peer = remote_addr(cx).map(|addr| addr.ip()); let forwarded = headers(cx) .get_all(FORWARDED_FOR) diff --git a/crates/forge-web/src/i18n/admin.rs b/crates/forge-web/src/i18n/admin.rs index fb2f9c2..55dd0fa 100644 --- a/crates/forge-web/src/i18n/admin.rs +++ b/crates/forge-web/src/i18n/admin.rs @@ -66,6 +66,29 @@ pub enum K { LastDbSnapshotShipped, LastSeen, LastSuccess, + ServerSettings, + ServerSettingsIntro, + SrvTabGeneral, + SrvTabLimits, + SrvTabStorage, + SrvTabBackups, + SrvTabIntegrations, + SrvSaved, + SrvNothingChanged, + SrvResetDone, + SrvResetToFile, + SrvRestartNeeded, + SrvKindLive, + SrvKindRestart, + SrvKindReadOnly, + SrvSourceDefault, + SrvSourceFile, + SrvSourceUi, + SrvSecretSet, + SrvSecretNotSet, + SrvSecretHint, + SrvFileValue, + SrvEmpty, Mail, MailHost, MailIntro, @@ -305,6 +328,56 @@ pub fn t(lang: Lang, key: K) -> &'static str { (LastSeen, Tr) => "Son görülme", (LastSuccess, En) => "Last success", (LastSuccess, Tr) => "Son başarı", + (ServerSettings, En) => "Server", + (ServerSettings, Tr) => "Sunucu", + (ServerSettingsIntro, En) => { + "The forge's own settings. A saved value overrides the config file; the file is never rewritten. Live settings apply at once, the others wait for a restart." + } + (ServerSettingsIntro, Tr) => { + "Forge'un kendi ayarları. Kaydedilen değer yapılandırma dosyasını geçersiz kılar; dosya hiç yeniden yazılmaz. Canlı ayarlar hemen uygulanır, diğerleri yeniden başlatmayı bekler." + } + (SrvTabGeneral, En) => "General", + (SrvTabGeneral, Tr) => "Genel", + (SrvTabLimits, En) => "CI and limits", + (SrvTabLimits, Tr) => "CI ve sınırlar", + (SrvTabStorage, En) => "Storage", + (SrvTabStorage, Tr) => "Depolama", + (SrvTabBackups, En) => "Backups", + (SrvTabBackups, Tr) => "Yedekler", + (SrvTabIntegrations, En) => "Integrations", + (SrvTabIntegrations, Tr) => "Entegrasyonlar", + (SrvSaved, En) => "Server settings saved.", + (SrvSaved, Tr) => "Sunucu ayarları kaydedildi.", + (SrvNothingChanged, En) => "Nothing changed.", + (SrvNothingChanged, Tr) => "Değişiklik yok.", + (SrvResetDone, En) => "Back to the file value.", + (SrvResetDone, Tr) => "Dosya değerine dönüldü.", + (SrvResetToFile, En) => "Reset to file value", + (SrvResetToFile, Tr) => "Dosya değerine sıfırla", + (SrvRestartNeeded, En) => "restart needed", + (SrvRestartNeeded, Tr) => "yeniden başlatma gerekli", + (SrvKindLive, En) => "live", + (SrvKindLive, Tr) => "canlı", + (SrvKindRestart, En) => "restart", + (SrvKindRestart, Tr) => "yeniden başlatma", + (SrvKindReadOnly, En) => "read-only", + (SrvKindReadOnly, Tr) => "salt okunur", + (SrvSourceDefault, En) => "default", + (SrvSourceDefault, Tr) => "varsayılan", + (SrvSourceFile, En) => "file", + (SrvSourceFile, Tr) => "dosya", + (SrvSourceUi, En) => "UI", + (SrvSourceUi, Tr) => "arayüz", + (SrvSecretSet, En) => "set", + (SrvSecretSet, Tr) => "ayarlı", + (SrvSecretNotSet, En) => "not set", + (SrvSecretNotSet, Tr) => "ayarlı değil", + (SrvSecretHint, En) => "Write-only. Leave blank to keep the current value.", + (SrvSecretHint, Tr) => "Yalnızca yazılır. Mevcut değeri korumak için boş bırakın.", + (SrvFileValue, En) => "File value", + (SrvFileValue, Tr) => "Dosya değeri", + (SrvEmpty, En) => "(empty)", + (SrvEmpty, Tr) => "(boş)", (Mail, En) => "Mail", (Mail, Tr) => "E-posta", (MailTabSettings, En) => "Settings", @@ -782,6 +855,29 @@ mod tests { K::LastDbSnapshotShipped, K::LastSeen, K::LastSuccess, + K::ServerSettings, + K::ServerSettingsIntro, + K::SrvTabGeneral, + K::SrvTabLimits, + K::SrvTabStorage, + K::SrvTabBackups, + K::SrvTabIntegrations, + K::SrvSaved, + K::SrvNothingChanged, + K::SrvResetDone, + K::SrvResetToFile, + K::SrvRestartNeeded, + K::SrvKindLive, + K::SrvKindRestart, + K::SrvKindReadOnly, + K::SrvSourceDefault, + K::SrvSourceFile, + K::SrvSourceUi, + K::SrvSecretSet, + K::SrvSecretNotSet, + K::SrvSecretHint, + K::SrvFileValue, + K::SrvEmpty, K::Mail, K::MailHost, K::MailIntro, diff --git a/crates/forge-web/src/lfs/route_tests.rs b/crates/forge-web/src/lfs/route_tests.rs index 79c5ff2..1570434 100644 --- a/crates/forge-web/src/lfs/route_tests.rs +++ b/crates/forge-web/src/lfs/route_tests.rs @@ -1,7 +1,6 @@ //! Route tests for the LFS API, driven through the public router. use std::path::PathBuf; -use std::sync::Arc; use base64::prelude::{BASE64_STANDARD, Engine}; use forge_core::lfs_token::{self, LfsOp}; @@ -64,7 +63,7 @@ impl Fixture { state.store = self.store.clone(); let mut config = (*state.config).clone(); config.lfs.max_object_mb = max_object_mb; - state.config = Arc::new(config); + state.set_config(config); self.router = app_router(state); } } diff --git a/crates/forge-web/src/lfs/routes.rs b/crates/forge-web/src/lfs/routes.rs index 5427a49..9490be7 100644 --- a/crates/forge-web/src/lfs/routes.rs +++ b/crates/forge-web/src/lfs/routes.rs @@ -84,7 +84,7 @@ async fn batch(cx: &Cx, body: Body) -> topcoat::Result { Ok(plan) => plan, Err(response) => return Ok(*response), }; - let max = state.config.lfs.max_object_bytes(); + let max = state.live().lfs.max_object_bytes(); for object in &request.objects { if !is_valid_oid(&object.oid) { return Ok(message(StatusCode::UNPROCESSABLE_ENTITY, "invalid oid")); @@ -251,7 +251,7 @@ async fn put_object(cx: &Cx, body: Body) -> topcoat::Result { return Ok(*response); } - let max = state.config.lfs.max_object_bytes(); + let max = state.live().lfs.max_object_bytes(); let declared = headers .get(CONTENT_LENGTH) .and_then(|v| v.to_str().ok()) diff --git a/crates/forge-web/src/main.rs b/crates/forge-web/src/main.rs index c17b530..74a45ec 100644 --- a/crates/forge-web/src/main.rs +++ b/crates/forge-web/src/main.rs @@ -71,8 +71,8 @@ async fn healthz() -> Result { } async fn serve(config_path: &std::path::Path) -> Result<(), BoxError> { - let config = Config::load(config_path)?; - boot::serve(config).await?; + let (config, file_keys) = Config::load_with_keys(config_path)?; + boot::serve(config, file_keys).await?; Ok(()) } diff --git a/crates/forge-web/src/pages/admin_runners.rs b/crates/forge-web/src/pages/admin_runners.rs index 28bb704..232f42b 100644 --- a/crates/forge-web/src/pages/admin_runners.rs +++ b/crates/forge-web/src/pages/admin_runners.rs @@ -7,7 +7,7 @@ //! runner are audited; the token itself is never written to the audit log. use forge_core::AuditAction; -use forge_core::ci::CiRunner; +use forge_core::ci::{CiRunner, FieldKind, RUNNER_FIELDS, runner_field}; use serde::Deserialize; use time::OffsetDateTime; use time::format_description::well_known::Rfc3339; @@ -16,6 +16,7 @@ use topcoat::context::{Cx, app_context}; use topcoat::router::content::Form; use topcoat::router::error::{SeeOther, forbidden, see_other}; use topcoat::router::request::uri; +use topcoat::router::response::Response; use topcoat::router::{page, path_param, route}; use topcoat::view::{View, component, view}; @@ -24,12 +25,55 @@ use crate::auth::check_csrf; use crate::i18n::admin::{self as g, K}; use crate::i18n::{self, Key, Lang}; use crate::pages::admin_users::admin_only; +use crate::pages::ci_runs::events_response; use crate::pages::repo_mirrors::stamp_in_tz; use crate::state::AppState; use crate::views::{enc, now_unix, relative_time, shell}; path_param!(runner_id); +/// Picks the English or Turkish text. The runner page strings live here, not in `i18n::admin`. +fn s(lang: Lang, en: &'static str, tr: &'static str) -> &'static str { + match lang { + Lang::En => en, + Lang::Tr => tr, + } +} + +/// Extra notice words: (word, English, Turkish, is an error). +const EXTRA_NOTICES: [(&str, &str, &str, bool); 5] = [ + ( + "saved", + "Saved. The runner picks it up on its next check-in.", + "Kaydedildi. Çalıştırıcı bir sonraki yoklamasında uygular.", + false, + ), + ( + "saved-restart", + "Saved. It applies when the runner next starts.", + "Kaydedildi. Çalıştırıcı yeniden başlayınca uygulanır.", + false, + ), + ( + "reset", + "Override removed. The runner.toml value is used again.", + "Üzerine yazma kaldırıldı. runner.toml değeri yeniden kullanılıyor.", + false, + ), + ( + "invalid", + "That value is not valid for this field. Nothing was changed.", + "Bu değer bu alan için geçerli değil. Hiçbir şey değiştirilmedi.", + true, + ), + ( + "read-only", + "That field cannot be changed from the forge.", + "Bu alan forge üzerinden değiştirilemez.", + true, + ), +]; + /// Notice words (the only text a `?notice=` query can show), their text key, and whether they are errors. const NOTICES: [(&str, K, bool); 5] = [ ("disabled", K::RunnerDisabledNotice, false), @@ -45,6 +89,22 @@ struct CsrfForm { csrf: String, } +#[derive(Deserialize)] +struct ConfigForm { + #[serde(default)] + csrf: String, + #[serde(default)] + key: String, + #[serde(default)] + value: String, + /// Set by the "use runner.toml value" button. + #[serde(default)] + reset: String, + /// `detail` returns to the runner's page, anything else to the list. + #[serde(default)] + back: String, +} + #[derive(Deserialize)] struct DisableForm { #[serde(default)] @@ -64,6 +124,36 @@ struct RunnerRow { disabled: bool, toggle_action: String, delete_action: String, + detail_href: String, + config_action: String, + /// The concurrency shown in the input: the admin's override, else what the runner reports. + concurrency: String, + /// "UI", "runner.toml" or empty when the runner has not reported. + concurrency_source: &'static str, + has_override: bool, + running: u32, +} + +/// The effective concurrency as a number to show, and where it comes from. +fn concurrency_of(runner: &CiRunner) -> (String, &'static str) { + if let Some(n) = runner.concurrency_override { + return (n.to_string(), "UI"); + } + let base = runner + .reported + .concurrency + .or_else(|| { + runner + .reported_config + .get("concurrency") + .and_then(serde_json::Value::as_u64) + .and_then(|n| u32::try_from(n).ok()) + }) + .map(|n| n.to_string()); + match base { + Some(n) => (n, "runner.toml"), + None => (String::new(), ""), + } } fn runner_row(runner: &CiRunner, tz: &str, lang: Lang, now: i64) -> RunnerRow { @@ -78,6 +168,7 @@ fn runner_row(runner: &CiRunner, tz: &str, lang: Lang, now: i64) -> RunnerRow { } None => (i18n::t(lang, Key::Never).to_owned(), String::new()), }; + let (concurrency, concurrency_source) = concurrency_of(runner); RunnerRow { name: runner.name.clone(), labels: runner.labels.clone(), @@ -86,6 +177,12 @@ fn runner_row(runner: &CiRunner, tz: &str, lang: Lang, now: i64) -> RunnerRow { disabled: runner.disabled, toggle_action: format!("/admin/runners/{}/disabled", enc(&runner.id)), delete_action: format!("/admin/runners/{}/delete", enc(&runner.id)), + detail_href: format!("/admin/runners/{}", enc(&runner.id)), + config_action: format!("/admin/runners/{}/config", enc(&runner.id)), + concurrency, + concurrency_source, + has_override: runner.concurrency_override.is_some(), + running: runner.running_jobs, } } @@ -95,6 +192,9 @@ fn notice_from_query(cx: &Cx, lang: Lang) -> Option<(&'static str, bool)> { let word = form_urlencoded::parse(query.as_bytes()) .find(|(key, _)| key == "notice") .map(|(_, value)| value.into_owned())?; + if let Some((_, en, tr, is_error)) = EXTRA_NOTICES.iter().find(|(name, ..)| *name == word) { + return Some((s(lang, en, tr), *is_error)); + } NOTICES .iter() .find(|(name, _, _)| *name == word) @@ -122,6 +222,7 @@ async fn runners_view( note: String, ) -> Result { Ok(view! { +

(g::t(lang, K::CiRunners))

@@ -143,6 +244,8 @@ async fn runners_view( (g::t(lang, K::TableName)) (g::t(lang, K::TableLabels)) + (s(lang, "Concurrency", "Eşzamanlılık")) + (s(lang, "Running", "Çalışan")) (g::t(lang, K::LastSeen)) (g::t(lang, K::TableState)) @@ -151,7 +254,7 @@ async fn runners_view( for row in rows.iter() { - (row.name.as_str()) + (row.name.as_str()) for label in row.labels.iter() { @@ -159,6 +262,10 @@ async fn runners_view( } + + concurrency_form(lang: lang, csrf: csrf.as_str(), action: row.config_action.as_str(), key: "concurrency", value: row.concurrency.as_str(), source: row.concurrency_source, has_override: row.has_override, back: "list") + + (row.running.to_string()) (row.last_seen.as_str()) if row.disabled { @@ -195,6 +302,36 @@ async fn runners_view( +
+ }) +} + +/// The inline number form for concurrency: input, Save, and a reset button while an override is set. +#[component] +async fn concurrency_form( + lang: Lang, + csrf: &str, + action: &str, + key: &str, + value: &str, + source: &'static str, + has_override: bool, + back: &'static str, +) -> Result { + Ok(view! { +
+ + + + + + if has_override { + + } + if !source.is_empty() { + (source) + } +
}) } @@ -242,7 +379,7 @@ async fn runners_page(cx: &Cx) -> Result { let notice = notice_from_query(cx, lang); let note = g::token_ttl_note( lang, - &g::hours_text(lang, state.config.ci.registration_token_hours), + &g::hours_text(lang, state.live().ci.registration_token_hours), ); let title = g::t(lang, K::CiRunners); Ok(view! { @@ -260,7 +397,7 @@ async fn runner_token_create(cx: &Cx, Form(form): Form) -> Result(cx); let lang = i18n::lang(cx, Some(&viewer.0)); - let ttl_hours = state.config.ci.registration_token_hours; + let ttl_hours = state.live().ci.registration_token_hours; let token = match state .store .create_registration_token(&viewer.0.id, ttl_hours) @@ -350,6 +487,312 @@ async fn runner_delete(cx: &Cx, Form(form): Form) -> Result Ok(back_to_list("deleted")) } +/// One row of the runner's config table, already formatted. +struct FieldRow { + key: &'static str, + /// The value in the input, or the text for a read-only field. + value: String, + source: &'static str, + /// "live", "restart" or "read-only". + kind: FieldKind, + /// The override is stored but the runner has not started with it yet. + pending: bool, + has_override: bool, + reported: bool, +} + +/// A JSON config value as the admin reads and types it: lists are comma separated. +fn show_value(value: &serde_json::Value) -> String { + match value { + serde_json::Value::String(text) => text.clone(), + serde_json::Value::Array(items) => { + items.iter().map(show_value).collect::>().join(", ") + } + other => other.to_string(), + } +} + +fn field_rows(runner: &CiRunner) -> Vec { + RUNNER_FIELDS + .iter() + .map(|field| { + let reported = runner.reported_config.get(field.key); + let overridden = if field.key == "concurrency" { + runner.concurrency_override.map(serde_json::Value::from) + } else { + runner.config_overrides.get(field.key).cloned() + }; + let live_concurrency = (field.key == "concurrency") + .then(|| runner.reported.concurrency.map(serde_json::Value::from)) + .flatten(); + let shown = live_concurrency + .clone() + .or_else(|| overridden.clone()) + .or_else(|| reported.cloned()); + // Restart fields wait for a start; a live concurrency waits for the next check-in. + let pending = match (&overridden, field.kind) { + (Some(want), FieldKind::Restart) => reported != Some(want), + (Some(want), FieldKind::Live) if field.key == "concurrency" => { + live_concurrency.as_ref() != Some(want) + } + _ => false, + }; + FieldRow { + key: field.key, + value: shown.as_ref().map(show_value).unwrap_or_default(), + source: if overridden.is_some() { + "UI" + } else { + "runner.toml" + }, + kind: field.kind, + pending, + has_override: overridden.is_some(), + reported: shown.is_some(), + } + }) + .collect() +} + +/// The input for one editable field. +#[component] +async fn field_input(key: &'static str, value: &str, lang: Lang) -> Result { + let aria = key; + Ok(view! { + if key == "auto_update" { + + } else if key == "executor" { + + } else if key == "sandbox.userns" { + + } else if matches!(key, "limits.pids" | "limits.image_max_gb" | "images.keep_days" | "cache_max_gib" | "concurrency") { + + } else { + + } + }) +} + +fn sel(on: bool) -> Option<&'static str> { + on.then_some("selected") +} + +fn bytes_text(bytes: u64) -> String { + let gib = bytes as f64 / (1u64 << 30) as f64; + format!("{gib:.1} GiB") +} + +#[component] +async fn runner_detail_view( + lang: Lang, + csrf: String, + runner: CiRunner, + row: RunnerRow, + fields: Vec, + notice: Option<(&'static str, bool)>, + action: String, +) -> Result { + let host_version = runner.reported.version.clone().unwrap_or_default(); + let host_cpus = runner + .reported + .cpus + .map(|n| n.to_string()) + .unwrap_or_default(); + let host_mem = runner + .reported + .memory_bytes + .map(bytes_text) + .unwrap_or_default(); + Ok(view! { +
+
+

(runner.name.as_str())

+

(g::t(lang, K::BackToRunners))

+
+ if let Some((text, is_error)) = notice { + if is_error { + + } else { +
(text)
+ } + } +
+

(s(lang, "Status", "Durum"))

+
+
(s(lang, "Running jobs", "Çalışan işler"))
(row.running.to_string())
+
(g::t(lang, K::LastSeen))
(row.last_seen.as_str())
+ if !host_version.is_empty() { +
(s(lang, "Runner version", "Çalıştırıcı sürümü"))
(host_version.as_str())
+ } + if !host_cpus.is_empty() { +
(s(lang, "CPUs", "CPU sayısı"))
(host_cpus.as_str())
+ } + if !host_mem.is_empty() { +
(s(lang, "Memory", "Bellek"))
(host_mem.as_str())
+ } +
+
+
+

(s(lang, "Configuration", "Yapılandırma"))

+

(s(lang, "Live fields apply on the runner's next check-in. Restart fields are stored now and apply when the runner next starts. A UI value beats runner.toml; resetting returns to runner.toml.", "Canlı alanlar çalıştırıcının sonraki yoklamasında uygulanır. Yeniden başlatma gerektiren alanlar şimdi saklanır, çalıştırıcı yeniden başlayınca uygulanır. Arayüzdeki değer runner.toml'u geçersiz kılar; sıfırlamak runner.toml'a döndürür."))

+
+ + + + + + + + + + + for f in fields.iter() { + + + if f.kind == FieldKind::ReadOnly { + + + + } else { + + + + } + + } + +
(s(lang, "Field", "Alan"))(s(lang, "Value", "Değer"))(s(lang, "Source", "Kaynak"))(s(lang, "Applies", "Uygulanma"))
(f.key) + if f.reported { (f.value.as_str()) } else { "-" } + (if f.reported { "runner.toml" } else { "" })(s(lang, "read-only", "salt okunur")) +
+ + + + field_input(key: f.key, value: f.value.as_str(), lang: lang) + + if f.has_override { + + } +
+
(if f.reported || f.has_override { f.source } else { "" }) + if f.kind == FieldKind::Live { + (if f.pending { s(lang, "live, pending", "canlı, bekliyor") } else { s(lang, "live", "canlı") }) + } else { + (if f.pending { s(lang, "restart needed", "yeniden başlatma gerekli") } else { s(lang, "applies on restart", "yeniden başlatınca") }) + } +
+
+
+
+ }) +} + +/// One runner with its status and every config field. Instance admins only. +#[page("/admin/runners/{runner_id}")] +async fn runner_detail_page(cx: &Cx) -> Result { + let viewer = admin_only(cx).await?; + let lang = i18n::lang(cx, Some(&viewer.0)); + let state = app_context::(cx); + let id = path_param::(cx); + let Some(runner) = runner_named(state, id).await? else { + return Err(back_to_list("missing").into()); + }; + let row = runner_row(&runner, &viewer.0.timezone, lang, now_unix()); + let fields = field_rows(&runner); + let csrf = viewer.1.csrf_token.clone(); + let notice = notice_from_query(cx, lang); + let action = row.config_action.clone(); + let title = runner.name.clone(); + Ok(view! { + shell(title: title.as_str(), viewer: Some(&viewer), runner_detail_view(lang: lang, csrf: csrf, runner: runner.clone(), row: row, fields: fields, notice: notice, action: action)) + }) +} + +/// The live `changed` stream of the runners pages. Sent on a runner's report, claim, finish or an +/// admin edit; nothing is sent on connect. +#[route(GET "/admin/runners/events")] +async fn runners_events(cx: &Cx) -> Result { + admin_only(cx).await?; + let state = app_context::(cx); + let wake = state.ci_live.subscribe_runners(); + let events = futures_util::stream::unfold(wake, |mut wake| async move { + wake.changed().await.ok()?; + Some(( + crate::pages::ci_runs::changed_event("runners".to_owned()), + wake, + )) + }); + events_response(cx, events) +} + +/// Sets or resets one config field of a runner. Concurrency and labels are live; the rest are +/// stored for the runner's next start. Read-only fields and bad values change nothing. +#[route(POST "/admin/runners/{runner_id}/config")] +async fn runner_set_config(cx: &Cx, Form(form): Form) -> Result { + let viewer = admin_only(cx).await?; + if !check_csrf(&viewer.1, &form.csrf) { + return Err(forbidden().into()); + } + let id = path_param::(cx); + let state = app_context::(cx); + let back = |notice: &str| { + if form.back == "detail" { + see_other(format!("/admin/runners/{}?notice={}", enc(id), enc(notice))) + } else { + back_to_list(notice) + } + }; + if runner_named(state, id).await?.is_none() { + return Ok(back_to_list("missing")); + } + let Some(field) = runner_field(&form.key) else { + return Ok(back("read-only")); + }; + if field.kind == FieldKind::ReadOnly { + return Ok(back("read-only")); + } + let reset = form.reset == "1"; + let value = (!reset).then_some(form.value.as_str()); + match state.store.set_runner_field(id, field.key, value).await { + Ok(()) => {} + Err(forge_core::Error::Invalid(_)) => return Ok(back("invalid")), + Err(forge_core::Error::NotFound) => return Ok(back_to_list("missing")), + Err(e) => return Err(e.into()), + } + state.ci_live.bump_runners(); + tracing::info!(actor_id = %viewer.0.id, runner_id = %id, field = field.key, reset, "ci runner config changed"); + audit::record( + &state.store, + Some(cx), + Actor::User(&viewer.0), + AuditAction::CiRunnerConfigChanged, + Target { + kind: "ci_runner", + id, + name: "", + }, + serde_json::json!({ "field": field.key, "reset": reset }), + ) + .await; + Ok(back(if reset { + "reset" + } else if field.kind == FieldKind::Live { + "saved" + } else { + "saved-restart" + })) +} + #[cfg(test)] mod tests { use super::*; @@ -620,4 +1063,154 @@ mod tests { .await; assert!(page.contains("No runner has that id")); } + + async fn one_runner(store: &Store, router: &Router) -> forge_core::ci::CiRunner { + let (_, created) = send( + router, + "POST", + "/admin/runners/tokens", + Some(ADMIN_TOKEN), + csrf_form(""), + ) + .await; + let token = created + .split("--token ") + .nth(1) + .and_then(|rest| rest.split(' ').next()) + .expect("token") + .to_owned(); + store + .register_runner(&token, "tahinli-box", &["linux".to_owned()]) + .await + .expect("register"); + store.list_runners().await.expect("list").remove(0) + } + + #[tokio::test] + async fn admin_sets_and_resets_concurrency_and_config_fields() { + let dir = tempfile::tempdir().expect("tempdir"); + let (store, router) = fixture(dir.path()).await; + let runner = one_runner(&store, &router).await; + let action = format!("/admin/runners/{}/config", runner.id); + + let (status, _) = send( + &router, + "POST", + &action, + Some(ADMIN_TOKEN), + csrf_form("&key=concurrency&value=3&back=list"), + ) + .await; + assert_eq!(status, 303); + assert_eq!( + store.list_runners().await.unwrap()[0].concurrency_override, + Some(3) + ); + let (_, list) = send(&router, "GET", "/admin/runners", Some(ADMIN_TOKEN), None).await; + assert!(list.contains(r#"value="3""#)); + assert!(list.contains("Use runner.toml value")); + assert!(list.contains(r#"data-live="/admin/runners/events""#)); + + // Out of range, wrong kind of field and a read-only field change nothing. + for form in [ + "&key=concurrency&value=65", + "&key=concurrency&value=0", + "&key=concurrency&value=abc", + "&key=url&value=https://x.example", + "&key=runner_secret&value=x", + ] { + let (status, _) = + send(&router, "POST", &action, Some(ADMIN_TOKEN), csrf_form(form)).await; + assert_eq!(status, 303, "{form}"); + } + assert_eq!( + store.list_runners().await.unwrap()[0].concurrency_override, + Some(3) + ); + + let (status, _) = send( + &router, + "POST", + &action, + Some(ADMIN_TOKEN), + csrf_form("&key=limits.memory&value=8g&back=detail"), + ) + .await; + assert_eq!(status, 303); + let detail_uri = format!("/admin/runners/{}", runner.id); + let (status, detail) = send(&router, "GET", &detail_uri, Some(ADMIN_TOKEN), None).await; + assert_eq!(status, 200); + assert!(detail.contains("limits.memory")); + assert!(detail.contains("restart needed")); + assert!(detail.contains("read-only")); + assert!(detail.contains(r#"data-live="/admin/runners/events""#)); + + let (_, _) = send( + &router, + "POST", + &action, + Some(ADMIN_TOKEN), + csrf_form("&key=concurrency&reset=1"), + ) + .await; + let (_, _) = send( + &router, + "POST", + &action, + Some(ADMIN_TOKEN), + csrf_form("&key=limits.memory&reset=1"), + ) + .await; + let after = store.list_runners().await.unwrap().remove(0); + assert_eq!(after.concurrency_override, None); + assert!(after.config_overrides.is_empty()); + } + + #[tokio::test] + async fn config_posts_need_admin_and_csrf_and_the_events_stream_is_admin_only() { + let dir = tempfile::tempdir().expect("tempdir"); + let (store, router) = fixture(dir.path()).await; + let runner = one_runner(&store, &router).await; + let action = format!("/admin/runners/{}/config", runner.id); + let (status, _) = send( + &router, + "POST", + &action, + Some(USER_TOKEN), + csrf_form("&key=concurrency&value=2"), + ) + .await; + assert_eq!(status, 404); + let (status, _) = send( + &router, + "POST", + &action, + Some(ADMIN_TOKEN), + Some("csrf=wrong&key=concurrency&value=2".into()), + ) + .await; + assert_eq!(status, 403); + assert_eq!( + store.list_runners().await.unwrap()[0].concurrency_override, + None + ); + let (status, _) = send( + &router, + "GET", + "/admin/runners/events", + Some(USER_TOKEN), + None, + ) + .await; + assert_eq!(status, 404); + let (status, _) = send( + &router, + "GET", + &format!("/admin/runners/{}", runner.id), + Some(USER_TOKEN), + None, + ) + .await; + assert_eq!(status, 404); + } } diff --git a/crates/forge-web/src/pages/admin_server.rs b/crates/forge-web/src/pages/admin_server.rs new file mode 100644 index 0000000..d6b05a9 --- /dev/null +++ b/crates/forge-web/src/pages/admin_server.rs @@ -0,0 +1,690 @@ +//! Page: the forge's own settings (`/admin/server`). Instance admins only; anyone else gets 404. +//! +//! One tab per group of settings. Each field shows its effective value, where that value comes +//! from (default, config file, or a UI override) and how a change reaches the process: live +//! (applied at once), restart (saved, applied at the next start) or read-only. Saving a tab stores +//! the changed fields as database overrides on top of the config file, which is never rewritten. +//! A field with an override has "Reset to file value". Secret fields are write-only: the page +//! shows only whether they are set. See `forge_core::server_settings` for the rules. +//! Saving and resetting are audited, with the keys but never the values. + +use std::collections::{BTreeMap, HashMap}; + +use forge_core::server_settings::{self as ss, Field, FieldView, Group, Kind, Source, Ty}; +use forge_core::{AuditAction, Error}; +use serde::Deserialize; +use topcoat::Result; +use topcoat::context::{Cx, app_context}; +use topcoat::router::content::Form; +use topcoat::router::error::{forbidden, see_other}; +use topcoat::router::response::Response; +use topcoat::router::{page, query_params, route}; +use topcoat::view::{View, component, view}; + +use crate::audit::{self, Actor, Target}; +use crate::auth::check_csrf; +use crate::i18n::admin::{self as g, K}; +use crate::i18n::{self, Key, Lang}; +use crate::pages::admin_users::admin_only; +use crate::state::AppState; +use crate::views::{enc, shell}; + +#[query_params(error = bad_request)] +pub(crate) struct ServerQuery { + notice: Option, + tab: Option, +} + +struct OptionRow { + value: String, + label: String, + selected: bool, +} + +/// One field, already formatted for the template. A secret's value is never in here. +struct Row { + key: &'static str, + label: &'static str, + help: &'static str, + kind_label: &'static str, + kind_class: &'static str, + source_label: &'static str, + value: String, + file_value: String, + show_file_value: bool, + has_override: bool, + pending: bool, + checked: bool, + min: String, + max: String, + options: Vec, + secret_state: &'static str, + is_bool: bool, + is_number: bool, + is_select: bool, + is_secret: bool, + fixed: bool, +} + +fn tab_label(lang: Lang, group: Group) -> &'static str { + g::t( + lang, + match group { + Group::General => K::SrvTabGeneral, + Group::Limits => K::SrvTabLimits, + Group::Storage => K::SrvTabStorage, + Group::Backups => K::SrvTabBackups, + Group::Integrations => K::SrvTabIntegrations, + }, + ) +} + +fn tab_class(on: bool) -> &'static str { + if on { + "subnav-link current" + } else { + "subnav-link" + } +} + +fn row(lang: Lang, view: &FieldView) -> Row { + let field: &Field = view.field; + let (kind_label, kind_class) = match field.kind { + Kind::Live => (g::t(lang, K::SrvKindLive), "badge srv-live"), + Kind::Restart => (g::t(lang, K::SrvKindRestart), "badge srv-restart"), + Kind::ReadOnly => (g::t(lang, K::SrvKindReadOnly), "badge srv-ro"), + }; + let source_label = match view.source { + Source::Default => g::t(lang, K::SrvSourceDefault), + Source::File => g::t(lang, K::SrvSourceFile), + Source::Ui => g::t(lang, K::SrvSourceUi), + }; + let (min, max) = match field.ty { + Ty::Uint(min, max) => (min.to_string(), max.to_string()), + _ => (String::new(), String::new()), + }; + let options = match field.ty { + Ty::Choice(all) => all + .iter() + .map(|option| OptionRow { + value: (*option).to_owned(), + label: if option.is_empty() { + g::t(lang, K::SrvEmpty).to_owned() + } else { + (*option).to_owned() + }, + selected: *option == view.value, + }) + .collect(), + _ => Vec::new(), + }; + let editable = field.kind != Kind::ReadOnly; + Row { + key: field.key, + label: field.label, + help: field.help, + kind_label, + kind_class, + source_label, + value: view.value.clone(), + file_value: if view.file_value.is_empty() { + g::t(lang, K::SrvEmpty).to_owned() + } else { + view.file_value.clone() + }, + show_file_value: editable && view.source == Source::Ui && !field.is_secret(), + has_override: editable && view.source == Source::Ui, + pending: view.restart_pending, + checked: view.value == "true", + min, + max, + options, + secret_state: if view.secret_set { + g::t(lang, K::SrvSecretSet) + } else { + g::t(lang, K::SrvSecretNotSet) + }, + is_bool: field.ty == Ty::Bool && editable, + is_number: matches!(field.ty, Ty::Uint(..)) && editable, + is_select: matches!(field.ty, Ty::Choice(_)) && editable, + is_secret: field.is_secret(), + fixed: !editable, + } +} + +async fn rows_for(state: &AppState, lang: Lang, group: Group) -> forge_core::Result> { + let overrides = state.store.server_overrides().await?; + Ok(state + .settings + .views(&overrides) + .iter() + .filter(|view| view.field.group == group) + .map(|view| row(lang, view)) + .collect()) +} + +#[component] +async fn server_view( + lang: Lang, + csrf: String, + group: Group, + rows: Vec, + notice: Option, +) -> Result { + let tab = group.slug(); + let any_editable = rows.iter().any(|r| !r.fixed); + Ok(view! { +
+

(g::t(lang, K::ServerSettings))

+

(g::t(lang, K::ServerSettingsIntro))

+
+ + if let Some(message) = notice { +
+

(message.as_str())

+
+ } +
+
+ + +
+ for r in rows.iter() { +
+
+ (r.label) + (r.kind_label) + (r.source_label) + if r.pending { + (g::t(lang, K::SrvRestartNeeded)) + } +
+ if r.is_bool { + + } else if r.is_select { + + } else if r.is_number { + + } else if r.is_secret { + +

(r.secret_state) ". " (g::t(lang, K::SrvSecretHint))

+ } else if r.fixed { + (r.value.as_str()) + } else { + + } + if !r.help.is_empty() { +

(r.help)

+ } + if r.has_override { +

+ if r.show_file_value { + (g::t(lang, K::SrvFileValue)) ": " (r.file_value.as_str()) + } + +

+ } +
+ } +
+ if any_editable { +
+ +
+ } +
+
+ + +
+
+ }) +} + +#[page("/admin/server")] +async fn server_page(cx: &Cx) -> Result { + let viewer = admin_only(cx).await?; + let query = query_params::(cx)?; + let state = app_context::(cx); + let lang = i18n::lang(cx, Some(&viewer.0)); + let group = query + .tab + .as_deref() + .and_then(Group::parse) + .unwrap_or(Group::General); + let rows = rows_for(state, lang, group).await?; + let csrf = viewer.1.csrf_token.clone(); + let title = g::t(lang, K::ServerSettings); + Ok(view! { + shell(title: title, viewer: Some(&viewer), server_view(lang: lang, csrf: csrf, group: group, rows: rows, notice: query.notice.clone())) + }) +} + +#[route(POST "/admin/server")] +async fn server_save(cx: &Cx, Form(mut form): Form>) -> Result { + let viewer = admin_only(cx).await?; + if !check_csrf(&viewer.1, form.get("csrf").map_or("", String::as_str)) { + return Err(forbidden().into()); + } + let lang = i18n::lang(cx, Some(&viewer.0)); + let state = app_context::(cx); + let group = form + .get("tab") + .and_then(|t| Group::parse(t)) + .unwrap_or(Group::General); + // An unchecked box is absent from the post. + for field in ss::FIELDS + .iter() + .filter(|f| f.group == group && f.ty == Ty::Bool && f.kind != Kind::ReadOnly) + { + form.entry(field.key.to_owned()) + .or_insert_with(|| "false".to_owned()); + } + let submitted: BTreeMap = form.into_iter().collect(); + let notice = match save(cx, state, &viewer.0, group, &submitted, lang).await { + Ok(Some(())) => g::t(lang, K::SrvSaved).to_owned(), + Ok(None) => g::t(lang, K::SrvNothingChanged).to_owned(), + Err(Error::Invalid(message)) => message, + Err(Error::Config(message)) => message, + Err(other) => other.to_string(), + }; + Err(see_other(format!( + "/admin/server?tab={}¬ice={}", + group.slug(), + enc(¬ice) + )) + .into()) +} + +/// Validates the whole tab as one unit, stores it, publishes the live fields and audits the keys. +/// `Ok(None)` means nothing differed from what is already in effect. +async fn save( + cx: &Cx, + state: &AppState, + user: &forge_core::User, + group: Group, + submitted: &BTreeMap, + _lang: Lang, +) -> forge_core::Result> { + let existing = state.store.server_overrides().await?; + let plan = state.settings.plan_save(&existing, group, submitted)?; + if plan.sets.is_empty() && plan.clears.is_empty() { + return Ok(None); + } + state.store.set_server_overrides(&plan.sets).await?; + for key in &plan.clears { + state.store.clear_server_override(key).await?; + } + state.settings.publish(&plan.overrides)?; + let keys: Vec<&str> = plan.sets.iter().map(|(k, _)| k.as_str()).collect(); + audit::record( + &state.store, + Some(cx), + Actor::User(user), + AuditAction::ServerSettingsUpdated, + Target { + kind: "server", + id: "", + name: "", + }, + serde_json::json!({ "set": keys, "cleared": plan.clears }), + ) + .await; + Ok(Some(())) +} + +#[derive(Deserialize, Default)] +struct ResetForm { + #[serde(default)] + csrf: String, + #[serde(default)] + tab: String, + #[serde(default)] + key: String, +} + +#[route(POST "/admin/server/reset")] +async fn server_reset(cx: &Cx, Form(form): Form) -> Result { + let viewer = admin_only(cx).await?; + if !check_csrf(&viewer.1, &form.csrf) { + return Err(forbidden().into()); + } + let lang = i18n::lang(cx, Some(&viewer.0)); + let state = app_context::(cx); + let group = Group::parse(&form.tab).unwrap_or(Group::General); + let notice = match reset(cx, state, &viewer.0, &form.key).await { + Ok(()) => g::t(lang, K::SrvResetDone).to_owned(), + Err(Error::Invalid(message)) => message, + Err(Error::Config(message)) => message, + Err(other) => other.to_string(), + }; + Err(see_other(format!( + "/admin/server?tab={}¬ice={}", + group.slug(), + enc(¬ice) + )) + .into()) +} + +async fn reset( + cx: &Cx, + state: &AppState, + user: &forge_core::User, + key: &str, +) -> forge_core::Result<()> { + let existing = state.store.server_overrides().await?; + let next = state.settings.plan_reset(&existing, key)?; + state.store.clear_server_override(key).await?; + state.settings.publish(&next)?; + audit::record( + &state.store, + Some(cx), + Actor::User(user), + AuditAction::ServerSettingsUpdated, + Target { + kind: "server", + id: "", + name: "", + }, + serde_json::json!({ "set": [], "cleared": [key] }), + ) + .await; + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + use topcoat::router::request::Request; + use topcoat::router::{Body, Router, to_bytes}; + + use crate::auth::SESSION_COOKIE; + use crate::test_support::{app_router, create_session, test_state}; + + const ADMIN_TOKEN: &str = "server-admin-session"; + const USER_TOKEN: &str = "server-user-session"; + const CSRF: &str = "server-csrf"; + + struct Fixture { + _dir: tempfile::TempDir, + router: Router, + state: AppState, + } + + async fn fixture() -> Fixture { + let dir = tempfile::tempdir().expect("tempdir"); + let data_dir = dir.path().join("data"); + std::fs::create_dir_all(&data_dir).expect("data dir"); + let state = test_state(&data_dir).await; + let admin = state + .store + .create_user("tahinli", Some("admin@example.com"), "h", true) + .await + .expect("admin"); + let user = state + .store + .create_user("plain", None, "h", false) + .await + .expect("user"); + create_session(&state.store, &admin.id, ADMIN_TOKEN, CSRF).await; + create_session(&state.store, &user.id, USER_TOKEN, CSRF).await; + let router = app_router(state.clone()); + Fixture { + _dir: dir, + router, + state, + } + } + + async fn send( + router: &Router, + method: &str, + uri: &str, + token: Option<&str>, + form: Option, + ) -> (u16, String, String) { + let mut builder = Request::builder().method(method).uri(uri); + if let Some(token) = token { + builder = builder.header("cookie", format!("__Host-{SESSION_COOKIE}={token}")); + } + let body = match form { + Some(form) => { + builder = builder.header("content-type", "application/x-www-form-urlencoded"); + Body::from(form) + } + None => Body::empty(), + }; + let res = router.handle(builder.body(body).expect("request")).await; + let status = res.status().as_u16(); + let location = res + .headers() + .get("location") + .and_then(|v| v.to_str().ok()) + .unwrap_or_default() + .to_owned(); + let bytes = to_bytes(res.into_body(), usize::MAX).await.expect("body"); + ( + status, + String::from_utf8_lossy(&bytes).into_owned(), + location, + ) + } + + async fn admin_get(fx: &Fixture, uri: &str) -> String { + let (status, body, _) = send(&fx.router, "GET", uri, Some(ADMIN_TOKEN), None).await; + assert_eq!(status, 200, "GET {uri}"); + body + } + + /// Posts a tab and follows the redirect to read the notice it shows. + async fn save(fx: &Fixture, tab: &str, fields: &str) -> String { + let form = format!("csrf={CSRF}&tab={tab}&{fields}"); + let (status, _, location) = send( + &fx.router, + "POST", + "/admin/server", + Some(ADMIN_TOKEN), + Some(form), + ) + .await; + assert_eq!(status, 303); + admin_get(fx, &location).await + } + + #[tokio::test] + async fn the_page_and_its_posts_are_404_for_anonymous_and_non_admins() { + let fx = fixture().await; + for token in [None, Some(USER_TOKEN)] { + let (get, _, _) = send(&fx.router, "GET", "/admin/server", token, None).await; + assert_eq!(get, 404); + let form = format!("csrf={CSRF}&tab=limits&ci.max_log_mb=99"); + let (post, _, _) = send(&fx.router, "POST", "/admin/server", token, Some(form)).await; + assert_eq!(post, 404); + let form = format!("csrf={CSRF}&tab=limits&key=ci.max_log_mb"); + let (post, _, _) = + send(&fx.router, "POST", "/admin/server/reset", token, Some(form)).await; + assert_eq!(post, 404); + } + assert!(fx.state.store.server_overrides().await.unwrap().is_empty()); + } + + #[tokio::test] + async fn a_bad_csrf_token_is_refused() { + let fx = fixture().await; + let form = "csrf=wrong&tab=limits&ci.max_log_mb=99".to_owned(); + let (status, _, _) = send( + &fx.router, + "POST", + "/admin/server", + Some(ADMIN_TOKEN), + Some(form), + ) + .await; + assert_eq!(status, 403); + assert_eq!(fx.state.live().ci.max_log_mb, 16); + } + + #[tokio::test] + async fn a_live_override_applies_at_once_and_reset_goes_back() { + let fx = fixture().await; + assert_eq!(fx.state.live().ci.max_log_mb, 16); + let body = save(&fx, "limits", "ci.max_log_mb=99&ci.enabled=true").await; + assert!(body.contains("Server settings saved."), "{body}"); + assert_eq!(fx.state.live().ci.max_log_mb, 99); + let stored = fx.state.store.server_overrides().await.unwrap(); + assert_eq!(stored.get("ci.max_log_mb").map(String::as_str), Some("99")); + assert!( + !stored.contains_key("ci.enabled"), + "unchanged fields are not stored" + ); + let page = admin_get(&fx, "/admin/server?tab=limits").await; + assert!(page.contains("Reset to file value")); + + let form = format!("csrf={CSRF}&tab=limits&key=ci.max_log_mb"); + let (status, _, _) = send( + &fx.router, + "POST", + "/admin/server/reset", + Some(ADMIN_TOKEN), + Some(form), + ) + .await; + assert_eq!(status, 303); + assert_eq!(fx.state.live().ci.max_log_mb, 16); + assert!(fx.state.store.server_overrides().await.unwrap().is_empty()); + } + + #[tokio::test] + async fn live_registration_is_read_by_the_register_page() { + let fx = fixture().await; + let (closed, _, _) = send(&fx.router, "GET", "/register", None, None).await; + assert_eq!(closed, 404); + save(&fx, "general", "registration=open&orgs.creation=all").await; + let (open, _, _) = send(&fx.router, "GET", "/register", None, None).await; + assert_eq!(open, 200); + } + + #[tokio::test] + async fn bad_values_are_rejected_and_nothing_is_stored() { + let fx = fixture().await; + for (tab, fields) in [ + ("general", "registration=everyone"), + ("general", "trusted_proxies=not-an-ip"), + ("limits", "ci.max_log_mb=0"), + ("limits", "ci.max_log_mb=lots"), + ("storage", "storage.backend=r2"), + ("backups", "backup.keep=0&backup.dir=%2Fvar%2Fbackups"), + ] { + let body = save(&fx, tab, fields).await; + assert!(!body.contains("Server settings saved."), "{fields}: {body}"); + assert!( + fx.state.store.server_overrides().await.unwrap().is_empty(), + "{fields}" + ); + } + assert_eq!(fx.state.live().ci.max_log_mb, 16); + } + + #[tokio::test] + async fn a_restart_field_is_saved_but_waits_for_a_restart() { + let fx = fixture().await; + save(&fx, "general", "base_url=https%3A%2F%2Fnew.example").await; + assert_eq!( + fx.state + .store + .server_overrides() + .await + .unwrap() + .get("base_url") + .map(String::as_str), + Some("https://new.example") + ); + assert_eq!(fx.state.live().base_url, "https://forge.test/"); + let page = admin_get(&fx, "/admin/server?tab=general").await; + assert!(page.contains("restart needed")); + assert!(page.contains("https://new.example")); + } + + #[tokio::test] + async fn read_only_fields_are_shown_and_cannot_be_posted() { + let fx = fixture().await; + let page = admin_get(&fx, "/admin/server?tab=general").await; + assert!(page.contains("127.0.0.1:7660")); + assert!(!page.contains("name=\"listen\"")); + save(&fx, "general", "listen=0.0.0.0%3A1").await; + assert!(fx.state.store.server_overrides().await.unwrap().is_empty()); + } + + #[tokio::test] + async fn secrets_are_never_rendered_and_are_stored_sealed() { + let fx = fixture().await; + let secret = "https://hc.example/ping/TOPSECRET-TOKEN"; + let body = save( + &fx, + "backups", + &format!("backup.healthcheck_url={}", enc(secret)), + ) + .await; + assert!(body.contains("Server settings saved."), "{body}"); + for tab in ["backups", "general", "limits", "storage", "integrations"] { + let page = admin_get(&fx, &format!("/admin/server?tab={tab}")).await; + assert!(!page.contains("TOPSECRET"), "tab {tab}"); + } + let page = admin_get(&fx, "/admin/server?tab=backups").await; + assert!(page.contains("set")); + // Stored sealed, readable only through the store with the instance key. + let conn_value = fx.state.store.server_overrides().await.unwrap(); + assert_eq!( + conn_value.get("backup.healthcheck_url").map(String::as_str), + Some(secret) + ); + // A blank post keeps it. + save(&fx, "backups", "backup.healthcheck_url=").await; + assert!( + fx.state + .store + .server_overrides() + .await + .unwrap() + .contains_key("backup.healthcheck_url") + ); + // Reset removes it. + let form = format!("csrf={CSRF}&tab=backups&key=backup.healthcheck_url"); + send( + &fx.router, + "POST", + "/admin/server/reset", + Some(ADMIN_TOKEN), + Some(form), + ) + .await; + assert!(fx.state.store.server_overrides().await.unwrap().is_empty()); + } + + #[tokio::test] + async fn saving_is_audited_without_values() { + let fx = fixture().await; + save(&fx, "limits", "ci.max_log_mb=77").await; + let entries = fx + .state + .store + .list_audit(&Default::default(), None, 50) + .await + .unwrap(); + let entry = entries + .iter() + .find(|e| e.action == AuditAction::ServerSettingsUpdated) + .expect("audit entry"); + let text = format!("{entry:?}"); + assert!(text.contains("ci.max_log_mb")); + assert!(!text.contains("77")); + } +} diff --git a/crates/forge-web/src/pages/invites.rs b/crates/forge-web/src/pages/invites.rs index f6d8ea0..385f4bc 100644 --- a/crates/forge-web/src/pages/invites.rs +++ b/crates/forge-web/src/pages/invites.rs @@ -81,7 +81,7 @@ async fn invites_submit(cx: &Cx, Form(form): Form) -> Result (topcoat::router::Router, AppState) { let mut state = crate::test_support::test_state(dir).await; - state.config = std::sync::Arc::new(forge_core::Config { + state.set_config(forge_core::Config { registration: Registration::Invite, ..crate::test_support::test_config(dir) }); diff --git a/crates/forge-web/src/pages/mod.rs b/crates/forge-web/src/pages/mod.rs index a682d0a..aad48ad 100644 --- a/crates/forge-web/src/pages/mod.rs +++ b/crates/forge-web/src/pages/mod.rs @@ -4,6 +4,7 @@ pub mod admin_backups; pub mod admin_mail; pub mod admin_replication; pub mod admin_runners; +pub mod admin_server; pub mod admin_users; pub mod archive; pub mod assets; diff --git a/crates/forge-web/src/pages/org_new.rs b/crates/forge-web/src/pages/org_new.rs index 92c6f14..e0ffed4 100644 --- a/crates/forge-web/src/pages/org_new.rs +++ b/crates/forge-web/src/pages/org_new.rs @@ -33,7 +33,7 @@ struct NewOrgForm { /// Whether `user` may create an organization under the instance's policy. fn may_create_org(state: &AppState, user: &User) -> bool { - match state.config.orgs.creation { + match state.live().orgs.creation { OrgCreation::All => true, OrgCreation::Admin => user.is_admin, } diff --git a/crates/forge-web/src/pages/register.rs b/crates/forge-web/src/pages/register.rs index 2938e7b..2028840 100644 --- a/crates/forge-web/src/pages/register.rs +++ b/crates/forge-web/src/pages/register.rs @@ -184,7 +184,7 @@ async fn register_form( #[page("/register")] async fn register_page(cx: &Cx) -> Result { let state = app_context::(cx); - if state.config.registration == Registration::Closed { + if state.live().registration == Registration::Closed { return Err(not_found().into()); } if current_user(cx).await?.is_some() { @@ -198,7 +198,7 @@ async fn register_page(cx: &Cx) -> Result { "" => None, token => state.store.invite_email(token).await?, }; - let gate = gate_for(&state.config.registration, &invite, invited_email.is_some()); + let gate = gate_for(&state.live().registration, &invite, invited_email.is_some()); let invited = invited_email.is_some(); let email = invited_email.unwrap_or_default(); let lang = i18n::lang(cx, None); @@ -265,7 +265,7 @@ async fn create_account( #[page(POST "/register")] async fn register_submit(cx: &Cx, Form(form): Form) -> Result { let state = app_context::(cx); - if state.config.registration == Registration::Closed { + if state.live().registration == Registration::Closed { return Err(not_found().into()); } // Login CSRF: the pre-session token must match the cookie before anything else runs. @@ -287,7 +287,7 @@ async fn register_submit(cx: &Cx, Form(form): Form) -> Result None, token => state.store.invite_email(token).await?, }; - let gate = gate_for(&state.config.registration, &invite, invited_email.is_some()); + let gate = gate_for(&state.live().registration, &invite, invited_email.is_some()); let mut error = None; if limited && gate == Gate::Form { error = Some(t(lang, Key::ErrThrottled).to_owned()); @@ -509,14 +509,13 @@ mod tests { use std::path::Path; use forge_core::{Config, Registration}; - use std::sync::Arc; use super::test_helpers::{field_from, link_in, precsrf_for, send}; use crate::state::AppState; async fn app(dir: &Path, mode: Registration) -> (topcoat::router::Router, AppState) { let mut state = crate::test_support::test_state(dir).await; - state.config = Arc::new(Config { + state.set_config(Config { registration: mode, ..crate::test_support::test_config(dir) }); diff --git a/crates/forge-web/src/pages/releases.rs b/crates/forge-web/src/pages/releases.rs index 21c68dc..749e92b 100644 --- a/crates/forge-web/src/pages/releases.rs +++ b/crates/forge-web/src/pages/releases.rs @@ -954,7 +954,7 @@ async fn edit_parts( links, delete_actions, upload_action: format!("/{title}/releases/{}/assets", enc(&release.id)), - upload_hint: g::upload_hint(lang, state.config.releases.max_asset_mb), + upload_hint: g::upload_hint(lang, state.live().releases.max_asset_mb), delete_href: format!("/{title}/releases/{}/delete", enc(&release.id)), view_tag: tag_href(&title, &release.tag), action: release_edit_href(&title, &release.id), diff --git a/crates/forge-web/src/pages/releases_tests.rs b/crates/forge-web/src/pages/releases_tests.rs index c637fe9..d89041f 100644 --- a/crates/forge-web/src/pages/releases_tests.rs +++ b/crates/forge-web/src/pages/releases_tests.rs @@ -2,7 +2,6 @@ //! download counter, the size cap and deletion. Each test runs against a real bare repo. use std::path::{Path, PathBuf}; -use std::sync::Arc; use forge_core::releases::Release; use forge_core::{Repo, Role, Store, User, Visibility}; @@ -120,7 +119,7 @@ async fn fixture(max_mb: Option) -> Fixture { if let Some(mb) = max_mb { let mut config = (*state.config).clone(); config.releases.max_asset_mb = mb; - state.config = Arc::new(config); + state.set_config(config); } let store = state.store.clone(); let tahinli = store diff --git a/crates/forge-web/src/pages/settings_security.rs b/crates/forge-web/src/pages/settings_security.rs index 197d922..d0e8116 100644 --- a/crates/forge-web/src/pages/settings_security.rs +++ b/crates/forge-web/src/pages/settings_security.rs @@ -1048,8 +1048,10 @@ mod tests { orgs: Default::default(), self_update: Default::default(), }; + let config = Arc::new(config); let state = AppState { - config: Arc::new(config), + settings: crate::state::settings_for(&config), + config, store: store.clone(), git: Arc::new(GitEnv { git_bin: "git".into(), diff --git a/crates/forge-web/src/state.rs b/crates/forge-web/src/state.rs index 1cfcda3..9ec7156 100644 --- a/crates/forge-web/src/state.rs +++ b/crates/forge-web/src/state.rs @@ -11,7 +11,11 @@ use crate::throttle::Throttle; #[derive(Clone)] pub struct AppState { + /// The config the process booted with: the file plus every stored override. Live settings + /// can differ from it, so read those through `live()`. pub config: Arc, + /// The admin-editable settings layer: file config, boot config and the live view. + pub settings: Arc, pub store: Store, pub git: Arc, /// Instance secret key (data_dir/forge.key). Signs private raw-file URLs. @@ -46,3 +50,28 @@ pub struct AppState { /// Change counters of CI jobs and runs. Log followers and run pages wait on them. pub ci_live: Arc, } + +/// A settings handle over `config` with no stored overrides and no file keys. For tests. +#[cfg(test)] +pub fn settings_for(config: &Arc) -> Arc { + Arc::new(forge_core::server_settings::Live::new( + config.clone(), + Default::default(), + config.clone(), + )) +} + +impl AppState { + /// The config the running process uses now: `config` with the live settings applied. Take it + /// once per request or pass; a later save does not change a value already read. + pub fn live(&self) -> Arc { + self.settings.current() + } + + /// Replaces the config and resets the settings layer over it. For tests. + #[cfg(test)] + pub fn set_config(&mut self, config: Config) { + self.config = Arc::new(config); + self.settings = settings_for(&self.config); + } +} diff --git a/crates/forge-web/src/test_support.rs b/crates/forge-web/src/test_support.rs index a008a62..86552b2 100644 --- a/crates/forge-web/src/test_support.rs +++ b/crates/forge-web/src/test_support.rs @@ -60,8 +60,10 @@ pub fn test_config(dir: &Path) -> Config { pub async fn test_state(dir: &Path) -> AppState { let store = Store::open(&dir.join("forge.db")).await.unwrap(); store.set_secret_key(KEY); + let config = Arc::new(test_config(dir)); AppState { - config: Arc::new(test_config(dir)), + settings: crate::state::settings_for(&config), + config, store, git: Arc::new(GitEnv { git_bin: "git".into(), diff --git a/crates/forge-web/src/views/mod.rs b/crates/forge-web/src/views/mod.rs index e000a2d..bce3a03 100644 --- a/crates/forge-web/src/views/mod.rs +++ b/crates/forge-web/src/views/mod.rs @@ -476,6 +476,12 @@ fn admin_items(lang: Lang) -> Vec { "runners", ), item("mail", "/admin/mail", ad::t(lang, AK::Mail), "mail"), + item( + "server", + "/admin/server", + ad::t(lang, AK::ServerSettings), + "server", + ), item( "backups", "/admin/backups", @@ -662,6 +668,9 @@ async fn nav_icon(name: &str) -> Result { if name == "mail" { } + if name == "server" { + + } if name == "backups" { } diff --git a/crates/forge-web/tests/section_nav_e2e.rs b/crates/forge-web/tests/section_nav_e2e.rs index 2cf15b7..286106f 100644 --- a/crates/forge-web/tests/section_nav_e2e.rs +++ b/crates/forge-web/tests/section_nav_e2e.rs @@ -285,6 +285,7 @@ async fn admin_pages_get_the_admin_sidebar() { "/admin/audit", "/admin/runners", "/admin/mail", + "/admin/server", "/admin/backups", "/admin/replication", ]; diff --git a/docs/architecture.md b/docs/architecture.md index aa1594e..837aa50 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -320,6 +320,20 @@ Written at boot by `write_managed_gitconfig()`. Keys: - 2.38 is required for `merge-tree --write-tree`. - In practice, track the latest git release for security fixes. Keep it patched (CVE-2024-32002 and CVE-2025-48384 are submodule hook-execution bugs). +### 7.6 Server settings (`/admin/server`) + +Instance admins can view and edit the forge's own config from the web UI. Overrides live in the `server_settings` table (one row per dotted key such as `ci.max_log_mb`, migration 0046), so a new setting needs no migration. The config file is never rewritten. + +Precedence per field: **UI override, then config file, then built-in default.** The page shows each field's effective value and its source (default, file, UI). "Reset to file value" deletes the override. Saving one tab validates the combined result with the same rules the config loader uses (`Config::validate`) before anything is stored, so a bad combination is refused whole. + +Each field has a kind: + +- **live**: applied at once. Consumers read `AppState::live()`, which `Live::publish` swaps on every save. Registration, organization creation, trusted proxies, and the CI, LFS and release limits are live. +- **restart**: saved, shown with a "restart needed" badge until the process restarts. At boot the stored overrides are layered on the file config. If the two no longer validate together, boot logs an error and uses the file alone. +- **read-only**: listen addresses, database path and data dir. Shown, never editable. + +Secret fields (the backup and replication healthcheck URLs, which may hold tokens) are write-only: the page shows "set" or "not set", a blank input keeps the stored value, and the stored value is sealed with the instance key. Saves and resets are audited with the keys only. + --- ## 8. Data safety and reliability diff --git a/docs/ci.md b/docs/ci.md index 9465fdc..5239a60 100644 --- a/docs/ci.md +++ b/docs/ci.md @@ -411,7 +411,14 @@ jobs are running, the runner stops claiming, replaces its binary, and exits with restarts it. It is skipped when the forge's binary is for a different OS or architecture. Set `auto_update = false` to pin the binary by hand. -`concurrency` is the number of jobs run in parallel. The default is 1. Jobs without `needs` between +`concurrency` is the number of jobs run in parallel. The default is 1. An admin can change it per runner +on the runners page (`/admin/runners`) with no restart: type a number from 1 to 64 and save. The +runner picks it up on its next claim or job heartbeat, grows or shrinks its job slots, and logs +`runner: concurrency 1 -> 2 (set from server)`. Lowering it never kills a running job; the extra +slots retire as those jobs finish. The precedence is the UI value first, then `runner.toml`. "Use +runner.toml value" removes the UI value and the runner goes back to its file. The page also shows +the jobs running now, the last contact, and the runner's version, CPU count and memory, to help +choose a number. Jobs without `needs` between them (for example `test` and `build` in this repo's own `ci.toml`) only run at the same time when the forge has capacity for both: set `concurrency = 2` on the runner or register a second runner. Otherwise they queue and run one after the other. Each concurrent job needs its own RAM, so a @@ -419,6 +426,21 @@ second Rust build alongside the first needs several more GB even with `CARGO_BUI capabilities and `no_new_privileges`. The builtin executor also runs each job under a seccomp profile that denies calls such as `mount`, `ptrace`, `bpf` and `unshare`. +Every `runner.toml` field is visible on the runner's page (`/admin/runners/`), with its value and +whether it comes from `runner.toml` or the UI. The runner reports its effective config when it +starts, with the secret and registry passwords left out. Fields come in three kinds: + +- Live: `concurrency` and `labels`, applied on the runner's next check-in. +- Restart needed: `auto_update`, `executor`, `work_dir`, `sandbox.userns`, the `limits.*` values, + `images.keep_days` and `cache_max_gib`. The forge stores the value now and the runner applies it to + its in-memory config when it next starts, so `runner.toml` on disk is never rewritten. The row says + "restart needed" until the runner has started with it. +- Read-only: `name`, `url`, `runner_id`, `runner_secret` and `registry`, because changing them from the + forge could lock the runner out. + +A UI value beats `runner.toml` and "Use runner.toml value" clears it. Old runners and old forges still +work together: an old runner just never reports, and an old forge never sends overrides. + Image garbage collection runs at startup and then daily. Unpacked images are kept under `work_dir/oci`. diff --git a/style/main.scss b/style/main.scss index 9a31223..6781097 100644 --- a/style/main.scss +++ b/style/main.scss @@ -4005,6 +4005,44 @@ span.reaction { white-space: nowrap; } +// Runner concurrency and config forms: a compact input with its buttons on one line. +.runner-conc-form { + display: flex; + align-items: center; + gap: 8px; + margin: 0; + + input[type="number"] { + width: 5.5rem; + } + + input, + select, + button { + height: var(--control-h); + margin: 0; + } +} + +.runner-source { + white-space: nowrap; +} + +.runner-facts { + display: grid; + grid-template-columns: max-content 1fr; + gap: 4px 16px; + margin: 0; + + dt { + color: var(--muted); + } + + dd { + margin: 0; + } +} + .ci-state.runner-disabled { background: var(--code-bg); color: var(--muted); @@ -5676,3 +5714,81 @@ span.reaction { min-width: 0; } } + +// Server settings page (/admin/server): a grid of field cells that fits a tab in the viewport. +.srv-grid { + display: grid; + grid-template-columns: repeat(auto-fill, minmax(18rem, 1fr)); + gap: 16px 24px; +} + +.srv-field { + display: flex; + flex-direction: column; + gap: 6px; + min-width: 0; + + p { + margin: 0; + } + + input[type="text"], + input[type="number"], + input[type="password"], + select { + width: 100%; + } +} + +.srv-head { + display: flex; + flex-wrap: wrap; + align-items: center; + gap: 4px; + + .badge { + margin-left: 0; + } +} + +.srv-label { + font-weight: 500; + font-size: 0.875rem; + color: var(--text-2); + margin-right: 4px; +} + +.badge { + &.srv-live { + background: var(--public-bg); + color: var(--public-text); + } + + &.srv-restart, + &.srv-ro, + &.srv-source { + background: var(--private-bg); + color: var(--private-text); + border-color: var(--border-strong); + } + + &.srv-pending { + color: var(--warn); + border-color: var(--warn); + } +} + +.srv-fixed { + overflow-wrap: anywhere; +} + +.srv-reset { + display: flex; + flex-wrap: wrap; + align-items: center; + gap: 8px; +} + +.srv-form .actions { + margin-top: 16px; +}